text
stringlengths
54
60.6k
<commit_before>/* This file is part of kdepim. Copyright (c) 2004 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "webdavhandler.h" #ifdef HAVE_VALUES_H #include <values.h> #else #ifdef HAVE_SYS_LIMITS_H #include <sys/limits.h> #endif #endif #include <libkcal/incidence.h> #include <libkdepim/kpimprefs.h> #include <kdebug.h> #include <kconfig.h> #include <qfile.h> SloxItem::SloxItem() : status( Invalid ) { } WebdavHandler::WebdavHandler() : mLogCount( 0 ) { KConfig cfg( "sloxrc" ); cfg.setGroup( "General" ); mLogFile = cfg.readEntry( "LogFile" ); kdDebug() << "LOG FILE: " << mLogFile << endl; } void WebdavHandler::setUserId( const QString &id ) { mUserId = id; } QString WebdavHandler::userId() const { return mUserId; } void WebdavHandler::log( const QString &text ) { if ( mLogFile.isEmpty() ) return; QString filename = mLogFile + "-" + QString::number( mLogCount ); QFile file( filename ); if ( !file.open( IO_WriteOnly ) ) { kdWarning() << "Unable to open log file '" << filename << "'" << endl; return; } QCString textUtf8 = text.utf8(); file.writeBlock( textUtf8.data(), textUtf8.size() - 1 ); if ( ++mLogCount > 5 ) mLogCount = 0; } QValueList<SloxItem> WebdavHandler::getSloxItems( const QDomDocument &doc ) { kdDebug() << "getSloxItems" << endl; QValueList<SloxItem> items; QDomElement docElement = doc.documentElement(); QDomNode responseNode; for( responseNode = docElement.firstChild(); !responseNode.isNull(); responseNode = responseNode.nextSibling() ) { QDomElement responseElement = responseNode.toElement(); if ( responseElement.tagName() == "response" ) { QDomNode propstat = responseElement.namedItem( "propstat" ); if ( propstat.isNull() ) { kdError() << "Unable to find propstat tag." << endl; continue; } QDomNode prop = propstat.namedItem( "prop" ); if ( prop.isNull() ) { kdError() << "Unable to find WebDAV property" << endl; continue; } QDomNode sloxIdNode = prop.namedItem( "sloxid" ); if ( sloxIdNode.isNull() ) { kdError() << "Unable to find SLOX id." << endl; continue; } QDomElement sloxIdElement = sloxIdNode.toElement(); QString sloxId = sloxIdElement.text(); QDomNode sloxStatus = prop.namedItem( "sloxstatus" ); if ( sloxStatus.isNull() ) { kdError() << "Unable to find SLOX status." << endl; continue; } SloxItem item; item.sloxId = sloxId; item.domNode = prop; QDomElement sloxStatusElement = sloxStatus.toElement(); if ( sloxStatusElement.text() == "DELETE" ) { item.status = SloxItem::Delete; } else if ( sloxStatusElement.text() == "CREATE" ) { item.status = SloxItem::Create; } items.append( item ); } } return items; } QString WebdavHandler::qDateTimeToSlox( const QDateTime &dt ) { uint ticks = -dt.secsTo( QDateTime( QDate( 1970, 1, 1 ), QTime( 0, 0 ) ) ); return QString::number( ticks ) + "000"; } QString WebdavHandler::qDateTimeToSlox( const QDateTime &dt, const QString &timeZoneId ) { QDateTime utc = KPimPrefs::localTimeToUtc( dt, timeZoneId ); uint ticks = -utc.secsTo( QDateTime( QDate( 1970, 1, 1 ), QTime( 0, 0 ) ) ); return QString::number( ticks ) + "000"; } QDateTime WebdavHandler::sloxToQDateTime( const QString &str ) { QString s = str.mid( 0, str.length() - 3 ); bool preEpoch = s.startsWith("-"); if (preEpoch) s = s.mid(1); unsigned long ticks = s.toULong(); QDateTime dt; if (preEpoch) { dt.setTime_t( 0, Qt::UTC ); if (ticks > INT_MAX) { dt = dt.addSecs(-INT_MAX); ticks -= INT_MAX; } dt = dt.addSecs(-((long) ticks)); } else { dt.setTime_t( ticks, Qt::UTC ); } return dt; } QDateTime WebdavHandler::sloxToQDateTime( const QString &str, const QString &timeZoneId ) { return KPimPrefs::utcToLocalTime( sloxToQDateTime(str), timeZoneId ); } QDomElement WebdavHandler::addElement( QDomDocument &doc, QDomNode &node, const QString &tag ) { QDomElement el = doc.createElement( tag ); node.appendChild( el ); return el; } QDomElement WebdavHandler::addDavElement( QDomDocument &doc, QDomNode &node, const QString &tag ) { QDomElement el = doc.createElementNS( "DAV", tag ); node.appendChild( el ); return el; } QDomElement WebdavHandler::addSloxElement( QDomDocument &doc, QDomNode &node, const QString &tag, const QString &text ) { QDomElement el = doc.createElementNS( "SLOX", tag ); if ( !text.isEmpty() ) { QDomText textnode = doc.createTextNode( text ); el.appendChild( textnode ); } node.appendChild( el ); return el; } void WebdavHandler::parseSloxAttribute( const QDomElement &e ) { // kdDebug() << "parseSloxAttribute" << endl; QString tag = e.tagName(); QString text = QString::fromUtf8( e.text().latin1() ); if ( text.isEmpty() ) return; if ( tag == "owner" ) { if ( text == mUserId ) mWritable = true; } else if ( tag == "writerights" ) { QDomNode n; for( n = e.firstChild(); !n.isNull(); n = n.nextSibling() ) { QDomElement e2 = n.toElement(); if ( e2.tagName() == "member" ) { if ( e2.text() == mUserId ) mWritable = true; } // TODO: Process group write rights } } } void WebdavHandler::clearSloxAttributeStatus() { mWritable = false; } void WebdavHandler::setSloxAttributes( KCal::Incidence *i ) { i->setReadOnly( !mWritable ); } void WebdavHandler::setSloxAttributes( KABC::Addressee & ) { // FIXME: libkabc doesn't allow to set an individual addressee to read-only } <commit_msg>Save things to the server in the correct timezone - remove a double conversion bug.<commit_after>/* This file is part of kdepim. Copyright (c) 2004 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "webdavhandler.h" #ifdef HAVE_VALUES_H #include <values.h> #else #ifdef HAVE_SYS_LIMITS_H #include <sys/limits.h> #endif #endif #include <stdlib.h> #include <libkcal/incidence.h> #include <libkdepim/kpimprefs.h> #include <kdebug.h> #include <kconfig.h> #include <qfile.h> SloxItem::SloxItem() : status( Invalid ) { } WebdavHandler::WebdavHandler() : mLogCount( 0 ) { KConfig cfg( "sloxrc" ); cfg.setGroup( "General" ); mLogFile = cfg.readEntry( "LogFile" ); kdDebug() << "LOG FILE: " << mLogFile << endl; } void WebdavHandler::setUserId( const QString &id ) { mUserId = id; } QString WebdavHandler::userId() const { return mUserId; } void WebdavHandler::log( const QString &text ) { if ( mLogFile.isEmpty() ) return; QString filename = mLogFile + "-" + QString::number( mLogCount ); QFile file( filename ); if ( !file.open( IO_WriteOnly ) ) { kdWarning() << "Unable to open log file '" << filename << "'" << endl; return; } QCString textUtf8 = text.utf8(); file.writeBlock( textUtf8.data(), textUtf8.size() - 1 ); if ( ++mLogCount > 5 ) mLogCount = 0; } QValueList<SloxItem> WebdavHandler::getSloxItems( const QDomDocument &doc ) { kdDebug() << "getSloxItems" << endl; QValueList<SloxItem> items; QDomElement docElement = doc.documentElement(); QDomNode responseNode; for( responseNode = docElement.firstChild(); !responseNode.isNull(); responseNode = responseNode.nextSibling() ) { QDomElement responseElement = responseNode.toElement(); if ( responseElement.tagName() == "response" ) { QDomNode propstat = responseElement.namedItem( "propstat" ); if ( propstat.isNull() ) { kdError() << "Unable to find propstat tag." << endl; continue; } QDomNode prop = propstat.namedItem( "prop" ); if ( prop.isNull() ) { kdError() << "Unable to find WebDAV property" << endl; continue; } QDomNode sloxIdNode = prop.namedItem( "sloxid" ); if ( sloxIdNode.isNull() ) { kdError() << "Unable to find SLOX id." << endl; continue; } QDomElement sloxIdElement = sloxIdNode.toElement(); QString sloxId = sloxIdElement.text(); QDomNode sloxStatus = prop.namedItem( "sloxstatus" ); if ( sloxStatus.isNull() ) { kdError() << "Unable to find SLOX status." << endl; continue; } SloxItem item; item.sloxId = sloxId; item.domNode = prop; QDomElement sloxStatusElement = sloxStatus.toElement(); if ( sloxStatusElement.text() == "DELETE" ) { item.status = SloxItem::Delete; } else if ( sloxStatusElement.text() == "CREATE" ) { item.status = SloxItem::Create; } items.append( item ); } } return items; } QString WebdavHandler::qDateTimeToSlox( const QDateTime &dt ) { uint ticks = -dt.secsTo( QDateTime( QDate( 1970, 1, 1 ), QTime( 0, 0 ) ) ); return QString::number( ticks ) + "000"; } QString WebdavHandler::qDateTimeToSlox( const QDateTime &dt, const QString &timeZoneId ) { QDateTime utc = KPimPrefs::localTimeToUtc( dt, timeZoneId ); // secsTo and toTime_t etc also perform a timezone conversion using the system timezone, // but we want to use the calendar timezone, so we have to convert ourself and spoof the tz to UTC before // converting to ticks to prevent this QCString origTz = getenv("TZ"); setenv( "TZ", "UTC", 1 ); uint ticks = utc.toTime_t(); if ( origTz.isNull() ) unsetenv( "TZ" ); else setenv( "TZ", origTz, 1 ); return QString::number( ticks ) + "000"; } QDateTime WebdavHandler::sloxToQDateTime( const QString &str ) { QString s = str.mid( 0, str.length() - 3 ); bool preEpoch = s.startsWith("-"); if (preEpoch) s = s.mid(1); unsigned long ticks = s.toULong(); QDateTime dt; if (preEpoch) { dt.setTime_t( 0, Qt::UTC ); if (ticks > INT_MAX) { dt = dt.addSecs(-INT_MAX); ticks -= INT_MAX; } dt = dt.addSecs(-((long) ticks)); } else { dt.setTime_t( ticks, Qt::UTC ); } return dt; } QDateTime WebdavHandler::sloxToQDateTime( const QString &str, const QString &timeZoneId ) { return KPimPrefs::utcToLocalTime( sloxToQDateTime(str), timeZoneId ); } QDomElement WebdavHandler::addElement( QDomDocument &doc, QDomNode &node, const QString &tag ) { QDomElement el = doc.createElement( tag ); node.appendChild( el ); return el; } QDomElement WebdavHandler::addDavElement( QDomDocument &doc, QDomNode &node, const QString &tag ) { QDomElement el = doc.createElementNS( "DAV", tag ); node.appendChild( el ); return el; } QDomElement WebdavHandler::addSloxElement( QDomDocument &doc, QDomNode &node, const QString &tag, const QString &text ) { QDomElement el = doc.createElementNS( "SLOX", tag ); if ( !text.isEmpty() ) { QDomText textnode = doc.createTextNode( text ); el.appendChild( textnode ); } node.appendChild( el ); return el; } void WebdavHandler::parseSloxAttribute( const QDomElement &e ) { // kdDebug() << "parseSloxAttribute" << endl; QString tag = e.tagName(); QString text = QString::fromUtf8( e.text().latin1() ); if ( text.isEmpty() ) return; if ( tag == "owner" ) { if ( text == mUserId ) mWritable = true; } else if ( tag == "writerights" ) { QDomNode n; for( n = e.firstChild(); !n.isNull(); n = n.nextSibling() ) { QDomElement e2 = n.toElement(); if ( e2.tagName() == "member" ) { if ( e2.text() == mUserId ) mWritable = true; } // TODO: Process group write rights } } } void WebdavHandler::clearSloxAttributeStatus() { mWritable = false; } void WebdavHandler::setSloxAttributes( KCal::Incidence *i ) { i->setReadOnly( !mWritable ); } void WebdavHandler::setSloxAttributes( KABC::Addressee & ) { // FIXME: libkabc doesn't allow to set an individual addressee to read-only } <|endoftext|>
<commit_before>#include <iostream> int main(int argc, char* argv[]) { std::cout << "Hello World!" << std::endl; return 0; }<commit_msg>feat: make it work<commit_after>#include <iostream> int main(int argc, char* argv[]) { std::cout << "Hello World!" << std::endl; std::system("PAUSE"); return 0; }<|endoftext|>
<commit_before>/************************************************************************************ * Copyright (C) 2017, Copyright Holders of the ALICE Collaboration * * 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 <organization> 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 ALICE COLLABORATION 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 <array> #include <cmath> #include <iomanip> #include <iostream> #include <sstream> #include <string> #include <THistManager.h> #include <TLinearBinning.h> #include <TLorentzVector.h> #include "AliAnalysisManager.h" #include "AliAnalysisTaskEmcalJetConstituentQA.h" #include "AliAODInputHandler.h" #include "AliClusterContainer.h" #include "AliEmcalAnalysisFactory.h" #include "AliEmcalTriggerDecisionContainer.h" #include "AliEmcalJet.h" #include "AliInputEventHandler.h" #include "AliJetContainer.h" #include "AliLog.h" #include "AliTrackContainer.h" #include "AliVCluster.h" #include "AliVEvent.h" #include "AliVTrack.h" /// \cond CLASSIMP ClassImp(EmcalTriggerJets::AliAnalysisTaskEmcalJetConstituentQA); /// \endcond using namespace EmcalTriggerJets; AliAnalysisTaskEmcalJetConstituentQA::AliAnalysisTaskEmcalJetConstituentQA(): AliAnalysisTaskEmcalJet(), fHistos(nullptr), fNameTrackContainer(""), fNameClusterContainer(""), fTriggerSelectionString(""), fUseTriggerSelection(kFALSE), fNameTriggerDecisionContainer("EmcalTriggerDecision") { this->SetUseAliAnaUtils(true); } AliAnalysisTaskEmcalJetConstituentQA::AliAnalysisTaskEmcalJetConstituentQA(const char *name): AliAnalysisTaskEmcalJet(name, true), fHistos(nullptr), fNameTrackContainer(""), fNameClusterContainer(""), fTriggerSelectionString(""), fUseTriggerSelection(kFALSE), fNameTriggerDecisionContainer("EmcalTriggerDecision") { this->SetUseAliAnaUtils(true); } AliAnalysisTaskEmcalJetConstituentQA::~AliAnalysisTaskEmcalJetConstituentQA(){ if(fHistos) delete fHistos; } void AliAnalysisTaskEmcalJetConstituentQA::UserCreateOutputObjects(){ AliAnalysisTaskEmcalJet::UserCreateOutputObjects(); TLinearBinning binningz(50, 0., 1), multbinning(51, -0.5, 50.5), binningnef(50, 0., 1.), binningptconst(200, 0., 200.), binningptjet(20, 0., 200.); const TBinning *jetbinning[4] = {&binningptjet, &binningnef, &multbinning, &multbinning}, *chargedbinning[6] = {&binningptjet, &binningnef, &multbinning, &multbinning, &binningptconst, &binningz}, *neutralbinning[7] = {&binningptjet, &binningnef, &multbinning, &multbinning, &binningptconst, &binningptconst, &binningz}; fHistos = new THistManager(Form("histos_%s", GetName())); for(auto c : fNamesJetContainers){ auto contname = dynamic_cast<TObjString *>(c); if(!contname) continue; fHistos->CreateTHnSparse(Form("hJetCounter%s", contname->String().Data()), Form("jet counter for jets %s", contname->String().Data()), 4, jetbinning); fHistos->CreateTHnSparse(Form("hChargedConstituents%s", contname->String().Data()), Form("charged constituents in jets %s", contname->String().Data()), 6, chargedbinning); fHistos->CreateTHnSparse(Form("hNeutralConstituents%s", contname->String().Data()), Form("neutral constituents in jets %s", contname->String().Data()), 7, neutralbinning); } for(auto h : *(fHistos->GetListOfHistograms())) fOutput->Add(h); PostData(1, fOutput); } bool AliAnalysisTaskEmcalJetConstituentQA::Run(){ AliParticleContainer * tracks = GetTrackContainer(fNameTrackContainer); if(!tracks) tracks = GetParticleContainer(fNameTrackContainer); const auto clusters = GetClusterContainer(fNameClusterContainer); if(fNameTrackContainer.Length() && !tracks){ AliErrorStream() << "Track container " << fNameTrackContainer << " required but missing ..." << std::endl; return kFALSE; } if(fNameClusterContainer.Length() && !clusters){ AliErrorStream() << "Cluster container " << fNameClusterContainer << " required but missing ..." << std::endl; return kFALSE; } // Event selection AliDebugStream(1) << "Trigger selection string: " << fTriggerSelectionString << ", fired trigger classes: " << fInputEvent->GetFiredTriggerClasses() << std::endl; if(fTriggerSelectionString.Contains("INT7")){ // INT7 trigger if(!(fInputHandler->IsEventSelected() & AliVEvent::kINT7)) return false; } else if(fTriggerSelectionString.Contains("EJ")){ auto triggerclass = fTriggerSelectionString(fTriggerSelectionString.Index("EJ"),3); // cleanup trigger string from possible tags AliDebugStream(1) << "Inspecting trigger class " << triggerclass << std::endl; // EMCAL JET trigger if(!fMCEvent){ // Running on Data if(!(fInputHandler->IsEventSelected() & AliVEvent::kEMCEJE)) return false; if(!fInputEvent->GetFiredTriggerClasses().Contains(triggerclass)) return false; } if(fUseTriggerSelection) { auto triggerdecisions = dynamic_cast<PWG::EMCAL::AliEmcalTriggerDecisionContainer *>(fInputEvent->FindListObject(fNameTriggerDecisionContainer.Data())); if(!triggerdecisions) { AliErrorStream() << "No offline trigger selection available" << std::endl; return false; } else if(!triggerdecisions->IsEventSelected(triggerclass.Data())) return false; } } else return false; AliDebugStream(1) << "Event is selected" << std::endl; for(auto jc : fNamesJetContainers){ auto contname = dynamic_cast<TObjString *>(jc); if(!contname) { AliErrorStream() << "Non-string object in the list of jet container names" << std::endl; continue; } const auto jetcont = GetJetContainer(contname->String().Data()); if(!jetcont){ AliErrorStream() << "Jet container with name " << contname->String() << " not found in the list of jet containers" << std::endl; continue; } AliDebugStream(2) << "Reading " << jetcont->GetArray()->GetName() << std::endl; for(auto jet : jetcont->accepted()){ AliDebugStream(3) << "Next accepted jet, found " << jet->GetNumberOfTracks() << " tracks and " << jet->GetNumberOfClusters() << " clusters." << std::endl; Double_t pointjet[4] = {std::abs(jet->Pt()), jet->NEF(), static_cast<double>(jet->GetNumberOfTracks()), static_cast<double>(jet->GetNumberOfClusters())}, pointcharged[6] = {std::abs(jet->Pt()), jet->NEF(), static_cast<double>(jet->GetNumberOfTracks()), static_cast<double>(jet->GetNumberOfClusters()), -1., 1.}, pointneutral[7] = {std::abs(jet->Pt()), jet->NEF(), static_cast<double>(jet->GetNumberOfTracks()), static_cast<double>(jet->GetNumberOfClusters()), -1., 1., -1.}; fHistos->FillTHnSparse(Form("hJetCounter%s", contname->String().Data()), pointjet); if(tracks){ for(decltype(jet->GetNumberOfTracks()) itrk = 0; itrk < jet->GetNumberOfTracks(); itrk++){ const auto trk = jet->TrackAt(itrk, tracks->GetArray()); if(!trk) continue; if(trk->Charge()){ pointcharged[4] = std::abs(trk->Pt()); pointcharged[5] = std::abs(jet->GetZ(trk)); fHistos->FillTHnSparse(Form("hChargedConstituents%s", contname->String().Data()), pointcharged); } else { // particle level jets pointneutral[4] = pointneutral[5] = std::abs(trk->E()); pointneutral[6] = std::abs(jet->GetZ(trk)); fHistos->FillTHnSparse(Form("hNeutralConstituents%s", contname->String().Data()), pointneutral); } } } if(clusters){ for(decltype(jet->GetNumberOfClusters()) icl = 0; icl < jet->GetNumberOfClusters(); icl++){ const auto clust = jet->ClusterAt(icl, clusters->GetArray()); if(!clust) continue; TLorentzVector ptvec; clust->GetMomentum(ptvec, this->fVertex, AliVCluster::kHadCorr); pointneutral[4] = std::abs(clust->GetHadCorrEnergy()); pointneutral[5] = std::abs(clust->GetNonLinCorrEnergy()); pointneutral[6] = jet->GetZ(ptvec.Px(), ptvec.Py(), ptvec.Pz()); fHistos->FillTHnSparse(Form("hNeutralConstituents%s", contname->String().Data()), pointneutral); } } } } return kTRUE; } AliAnalysisTaskEmcalJetConstituentQA *AliAnalysisTaskEmcalJetConstituentQA::AddTaskEmcalJetConstituentQA(const char *trigger, bool partmode){ using AnalysisHelpers = EMCalTriggerPtAnalysis::AliEmcalAnalysisFactory; AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if(!mgr) { std::cerr << "[AliAnalysisTaskJetConstituentQA::AddTaskEmcalJetConstituentQA(EE)] No analysis manager provided ..." << std::endl; return nullptr; } std::stringstream taskname; taskname << "constituentQA_" << trigger; auto task = new AliAnalysisTaskEmcalJetConstituentQA(taskname.str().data()); task->SetTriggerSelection(trigger); mgr->AddTask(task); auto inputhandler = mgr->GetInputEventHandler(); auto isAOD = false; if(inputhandler->IsA() == AliAODInputHandler::Class()) isAOD = true; TString tracksname, clustername; AliParticleContainer *tracks(nullptr); AliClusterContainer *clusters(nullptr); if(!partmode) { tracksname = AnalysisHelpers::TrackContainerNameFactory(isAOD); tracks = task->AddTrackContainer(tracksname); task->SetNameTrackContainer(tracksname); tracks->SetMinPt(0.15); clustername = AnalysisHelpers::ClusterContainerNameFactory(isAOD); clusters = task->AddClusterContainer(clustername); task->SetNameClusterContainer(clustername); clusters->SetDefaultClusterEnergy(AliVCluster::kHadCorr); clusters->SetClusHadCorrEnergyCut(0.3); } else { tracksname = "mcparticles"; tracks = task->AddParticleContainer(tracksname); task->SetNameTrackContainer(tracksname); tracks->SetMinPt(0.); } // create jet containers for R02 and R04 jets std::array<double, 2> jetradii = {{0.2, 0.4}}; for(auto r : jetradii) { std::stringstream contname; contname << "fulljets_R" << std::setw(2) << std::setfill('0') << int(r*10.); auto jcont = task->AddJetContainer(AliJetContainer::kFullJet, AliJetContainer::antikt_algorithm, AliJetContainer::E_scheme, r, AliJetContainer::kEMCALfid, tracks, clusters, "Jet"); jcont->SetName(contname.str().data()); task->AddNameJetContainer(contname.str().data()); jcont->SetMinPt(20.); } std::stringstream contname, outfilename; contname << "JetConstituentQA_" << trigger; outfilename << mgr->GetCommonFileName() << ":JetConstituentQA_" << trigger; if(partmode) { contname << "_part"; outfilename << "_part"; } mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, mgr->CreateContainer(contname.str().data(), AliEmcalList::Class(), AliAnalysisManager::kOutputContainer, outfilename.str().data())); return task; } <commit_msg>[Histo] Monitor cluster constituents with high z<commit_after>/************************************************************************************ * Copyright (C) 2017, Copyright Holders of the ALICE Collaboration * * 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 <organization> 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 ALICE COLLABORATION BE LIABLE FOR ANY * * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ************************************************************************************/ #include <algorithm> #include <array> #include <cmath> #include <iomanip> #include <iostream> #include <sstream> #include <string> #include <THistManager.h> #include <TLinearBinning.h> #include <TLorentzVector.h> #include <TVector3.h> #include "AliAnalysisManager.h" #include "AliAnalysisTaskEmcalJetConstituentQA.h" #include "AliAODInputHandler.h" #include "AliClusterContainer.h" #include "AliEmcalAnalysisFactory.h" #include "AliEmcalTriggerDecisionContainer.h" #include "AliEmcalJet.h" #include "AliInputEventHandler.h" #include "AliJetContainer.h" #include "AliLog.h" #include "AliTrackContainer.h" #include "AliVCluster.h" #include "AliVEvent.h" #include "AliVTrack.h" /// \cond CLASSIMP ClassImp(EmcalTriggerJets::AliAnalysisTaskEmcalJetConstituentQA); /// \endcond using namespace EmcalTriggerJets; AliAnalysisTaskEmcalJetConstituentQA::AliAnalysisTaskEmcalJetConstituentQA(): AliAnalysisTaskEmcalJet(), fHistos(nullptr), fNameTrackContainer(""), fNameClusterContainer(""), fTriggerSelectionString(""), fUseTriggerSelection(kFALSE), fNameTriggerDecisionContainer("EmcalTriggerDecision") { this->SetUseAliAnaUtils(true); } AliAnalysisTaskEmcalJetConstituentQA::AliAnalysisTaskEmcalJetConstituentQA(const char *name): AliAnalysisTaskEmcalJet(name, true), fHistos(nullptr), fNameTrackContainer(""), fNameClusterContainer(""), fTriggerSelectionString(""), fUseTriggerSelection(kFALSE), fNameTriggerDecisionContainer("EmcalTriggerDecision") { this->SetUseAliAnaUtils(true); } AliAnalysisTaskEmcalJetConstituentQA::~AliAnalysisTaskEmcalJetConstituentQA(){ if(fHistos) delete fHistos; } void AliAnalysisTaskEmcalJetConstituentQA::UserCreateOutputObjects(){ AliAnalysisTaskEmcalJet::UserCreateOutputObjects(); TLinearBinning binningz(50, 0., 1), multbinning(51, -0.5, 50.5), binningnef(50, 0., 1.), binningR(50, 0., 0.5), binningptconst(200, 0., 200.), binningptjet(20, 0., 200.), binningNCell(101, -0.5, 100.5), binningFracCellLeading(100, 0., 1.), binningM02(100, 0., 1.); const TBinning *jetbinning[4] = {&binningptjet, &binningnef, &multbinning, &multbinning}, *chargedbinning[7] = {&binningptjet, &binningnef, &multbinning, &multbinning, &binningptconst, &binningz, &binningR}, *neutralbinning[8] = {&binningptjet, &binningnef, &multbinning, &multbinning, &binningptconst, &binningptconst, &binningz, &binningR}, *binningHighZClusters[7] = {&binningptjet, &binningnef, &binningptconst, &binningz, &binningNCell, &binningFracCellLeading, &binningM02}; fHistos = new THistManager(Form("histos_%s", GetName())); for(auto c : fNamesJetContainers){ auto contname = dynamic_cast<TObjString *>(c); if(!contname) continue; fHistos->CreateTHnSparse(Form("hJetCounter%s", contname->String().Data()), Form("jet counter for jets %s", contname->String().Data()), 4, jetbinning); fHistos->CreateTHnSparse(Form("hChargedConstituents%s", contname->String().Data()), Form("charged constituents in jets %s", contname->String().Data()), 7, chargedbinning); fHistos->CreateTHnSparse(Form("hNeutralConstituents%s", contname->String().Data()), Form("neutral constituents in jets %s", contname->String().Data()), 8, neutralbinning); fHistos->CreateTHnSparse(Form("hHighZClusters"), "Properties of high-z clusters", 7, binningHighZClusters); } for(auto h : *(fHistos->GetListOfHistograms())) fOutput->Add(h); PostData(1, fOutput); } bool AliAnalysisTaskEmcalJetConstituentQA::Run(){ AliParticleContainer * tracks = GetTrackContainer(fNameTrackContainer); if(!tracks) tracks = GetParticleContainer(fNameTrackContainer); const auto clusters = GetClusterContainer(fNameClusterContainer); if(fNameTrackContainer.Length() && !tracks){ AliErrorStream() << "Track container " << fNameTrackContainer << " required but missing ..." << std::endl; return kFALSE; } if(fNameClusterContainer.Length() && !clusters){ AliErrorStream() << "Cluster container " << fNameClusterContainer << " required but missing ..." << std::endl; return kFALSE; } // Event selection AliDebugStream(1) << "Trigger selection string: " << fTriggerSelectionString << ", fired trigger classes: " << fInputEvent->GetFiredTriggerClasses() << std::endl; if(fTriggerSelectionString.Contains("INT7")){ // INT7 trigger if(!(fInputHandler->IsEventSelected() & AliVEvent::kINT7)) return false; } else if(fTriggerSelectionString.Contains("EJ")){ auto triggerclass = fTriggerSelectionString(fTriggerSelectionString.Index("EJ"),3); // cleanup trigger string from possible tags AliDebugStream(1) << "Inspecting trigger class " << triggerclass << std::endl; // EMCAL JET trigger if(!fMCEvent){ // Running on Data if(!(fInputHandler->IsEventSelected() & AliVEvent::kEMCEJE)) return false; if(!fInputEvent->GetFiredTriggerClasses().Contains(triggerclass)) return false; } if(fUseTriggerSelection) { auto triggerdecisions = dynamic_cast<PWG::EMCAL::AliEmcalTriggerDecisionContainer *>(fInputEvent->FindListObject(fNameTriggerDecisionContainer.Data())); if(!triggerdecisions) { AliErrorStream() << "No offline trigger selection available" << std::endl; return false; } else if(!triggerdecisions->IsEventSelected(triggerclass.Data())) return false; } } else return false; AliDebugStream(1) << "Event is selected" << std::endl; for(auto jc : fNamesJetContainers){ auto contname = dynamic_cast<TObjString *>(jc); if(!contname) { AliErrorStream() << "Non-string object in the list of jet container names" << std::endl; continue; } const auto jetcont = GetJetContainer(contname->String().Data()); if(!jetcont){ AliErrorStream() << "Jet container with name " << contname->String() << " not found in the list of jet containers" << std::endl; continue; } AliDebugStream(2) << "Reading " << jetcont->GetArray()->GetName() << std::endl; for(auto jet : jetcont->accepted()){ AliDebugStream(3) << "Next accepted jet, found " << jet->GetNumberOfTracks() << " tracks and " << jet->GetNumberOfClusters() << " clusters." << std::endl; Double_t pointjet[4] = {std::abs(jet->Pt()), jet->NEF(), static_cast<double>(jet->GetNumberOfTracks()), static_cast<double>(jet->GetNumberOfClusters())}, pointcharged[7] = {std::abs(jet->Pt()), jet->NEF(), static_cast<double>(jet->GetNumberOfTracks()), static_cast<double>(jet->GetNumberOfClusters()), -1., 1., -1.}, pointneutral[8] = {std::abs(jet->Pt()), jet->NEF(), static_cast<double>(jet->GetNumberOfTracks()), static_cast<double>(jet->GetNumberOfClusters()), -1., 1., -1., -1.}, pointHighZCluster[7] = {std::abs(jet->Pt()), jet->NEF(), -1., -1., -1., -1., -1.}; fHistos->FillTHnSparse(Form("hJetCounter%s", contname->String().Data()), pointjet); TVector3 jetvec{jet->Px(), jet->Py(), jet->Pz()}; if(tracks){ for(decltype(jet->GetNumberOfTracks()) itrk = 0; itrk < jet->GetNumberOfTracks(); itrk++){ const auto trk = jet->TrackAt(itrk, tracks->GetArray()); if(!trk) continue; if(trk->Charge()){ pointcharged[4] = std::abs(trk->Pt()); pointcharged[5] = std::abs(jet->GetZ(trk)); pointcharged[6] = jet->DeltaR(trk); fHistos->FillTHnSparse(Form("hChargedConstituents%s", contname->String().Data()), pointcharged); } else { // particle level jets pointneutral[4] = pointneutral[5] = std::abs(trk->E()); pointneutral[6] = std::abs(jet->GetZ(trk)); pointneutral[7] = jet->DeltaR(trk); fHistos->FillTHnSparse(Form("hNeutralConstituents%s", contname->String().Data()), pointneutral); } } } if(clusters){ for(decltype(jet->GetNumberOfClusters()) icl = 0; icl < jet->GetNumberOfClusters(); icl++){ const auto clust = jet->ClusterAt(icl, clusters->GetArray()); if(!clust) continue; TLorentzVector ptvec; clust->GetMomentum(ptvec, this->fVertex, AliVCluster::kHadCorr); pointneutral[4] = std::abs(clust->GetHadCorrEnergy()); pointneutral[5] = std::abs(clust->GetNonLinCorrEnergy()); pointneutral[6] = jet->GetZ(ptvec.Px(), ptvec.Py(), ptvec.Pz()); pointneutral[7] = jetvec.DeltaR(ptvec.Vect()); fHistos->FillTHnSparse(Form("hNeutralConstituents%s", contname->String().Data()), pointneutral); if(pointneutral[6] > 0.95) { pointHighZCluster[2] = pointneutral[4]; pointHighZCluster[3] = pointneutral[6]; pointHighZCluster[4] = clust->GetNCells(); pointHighZCluster[5] = *std::max_element(clust->GetCellsAmplitudeFraction(), clust->GetCellsAmplitudeFraction()+clust->GetNCells()); pointHighZCluster[6] = clust->GetM02(); fHistos->FillTHnSparse("hHighZClusters", pointHighZCluster); } } } } } return kTRUE; } AliAnalysisTaskEmcalJetConstituentQA *AliAnalysisTaskEmcalJetConstituentQA::AddTaskEmcalJetConstituentQA(const char *trigger, bool partmode){ using AnalysisHelpers = EMCalTriggerPtAnalysis::AliEmcalAnalysisFactory; AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if(!mgr) { std::cerr << "[AliAnalysisTaskJetConstituentQA::AddTaskEmcalJetConstituentQA(EE)] No analysis manager provided ..." << std::endl; return nullptr; } std::stringstream taskname; taskname << "constituentQA_" << trigger; auto task = new AliAnalysisTaskEmcalJetConstituentQA(taskname.str().data()); task->SetTriggerSelection(trigger); mgr->AddTask(task); auto inputhandler = mgr->GetInputEventHandler(); auto isAOD = false; if(inputhandler->IsA() == AliAODInputHandler::Class()) isAOD = true; TString tracksname, clustername; AliParticleContainer *tracks(nullptr); AliClusterContainer *clusters(nullptr); if(!partmode) { tracksname = AnalysisHelpers::TrackContainerNameFactory(isAOD); tracks = task->AddTrackContainer(tracksname); task->SetNameTrackContainer(tracksname); tracks->SetMinPt(0.15); clustername = AnalysisHelpers::ClusterContainerNameFactory(isAOD); clusters = task->AddClusterContainer(clustername); task->SetNameClusterContainer(clustername); clusters->SetDefaultClusterEnergy(AliVCluster::kHadCorr); clusters->SetClusHadCorrEnergyCut(0.3); } else { tracksname = "mcparticles"; tracks = task->AddParticleContainer(tracksname); task->SetNameTrackContainer(tracksname); tracks->SetMinPt(0.); } // create jet containers for R02 and R04 jets std::array<double, 2> jetradii = {{0.2, 0.4}}; for(auto r : jetradii) { std::stringstream contname; contname << "fulljets_R" << std::setw(2) << std::setfill('0') << int(r*10.); auto jcont = task->AddJetContainer(AliJetContainer::kFullJet, AliJetContainer::antikt_algorithm, AliJetContainer::E_scheme, r, AliJetContainer::kEMCALfid, tracks, clusters, "Jet"); jcont->SetName(contname.str().data()); task->AddNameJetContainer(contname.str().data()); jcont->SetMinPt(20.); } std::stringstream contname, outfilename; contname << "JetConstituentQA_" << trigger; outfilename << mgr->GetCommonFileName() << ":JetConstituentQA_" << trigger; if(partmode) { contname << "_part"; outfilename << "_part"; } mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, mgr->CreateContainer(contname.str().data(), AliEmcalList::Class(), AliAnalysisManager::kOutputContainer, outfilename.str().data())); return task; } <|endoftext|>
<commit_before>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <fb/xplat_init.h> #include <fbjni/fbjni.h> #include "Binding.h" #include "EventBeatManager.h" #include "EventEmitterWrapper.h" #include "StateWrapperImpl.h" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *) { return facebook::xplat::initialize(vm, [] { facebook::react::Binding::registerNatives(); facebook::react::EventBeatManager::registerNatives(); facebook::react::EventEmitterWrapper::registerNatives(); facebook::react::StateWrapperImpl::registerNatives(); facebook::react::ComponentFactoryDelegate::registerNatives(); }); } <commit_msg>Remove fb/xplat_init dependency<commit_after>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <fbjni/fbjni.h> #include "Binding.h" #include "EventBeatManager.h" #include "EventEmitterWrapper.h" #include "StateWrapperImpl.h" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *) { return facebook::jni::initialize(vm, [] { facebook::react::Binding::registerNatives(); facebook::react::EventBeatManager::registerNatives(); facebook::react::EventEmitterWrapper::registerNatives(); facebook::react::StateWrapperImpl::registerNatives(); facebook::react::ComponentFactoryDelegate::registerNatives(); }); } <|endoftext|>
<commit_before>#include <iostream> // std::cout #include <stdlib.h> // rand() #include <time.h> // time() #include "gtest/gtest.h" #include "sorting.h" #include "printarray.h" #include "verifyarrays.h" #define quiet // ********************************************************************* TEST(EfficientSorts, MergeSortRecursive) { const int N = 4; double *to_sort_data = new double[N]; double *sorted_data = new double[N]; // Initialize the array with random values between 1 and 100 // NOTE: rand() is a terrible pseudo-random number generator (PRNG). // It is still used here for a simple testing task, but don't use it // for anything serious. srand(time(NULL)); for (int i = 0 ; i < N ; i++) { to_sort_data[i] = rand() % 100 + 1; } to_sort_data[0] = 6.0; to_sort_data[1] = 5.0; to_sort_data[2] = 3.0; to_sort_data[3] = 1.0; memcpy(sorted_data, to_sort_data, N*sizeof(double)); sorting::efficient::MergeSort(sorted_data, N); #ifndef quiet std::cout << "Arrays" << std::endl; std::cout << "Index Original Sorted " << std::endl; for (int i = 0 ; i < N ; i++) { std::cout << i+1 << "/" << N << " " << to_sort_data[i] << " " << sorted_data[i] << std::endl; } #endif // quiet for (int i = 1 ; i < N ; i++) { EXPECT_GE(sorted_data[i], sorted_data[i-1]); } for (int i = 0 ; i < N ; i++) { EXPECT_NE(sorted_data[i], 0); } ASSERT_TRUE(VerifyIfAllNotNaN(sorted_data, N)); ASSERT_TRUE(VerifyIfOrdered(sorted_data, N)); ASSERT_TRUE(VerifySortedUnique(to_sort_data, sorted_data, N)); delete[] to_sort_data; delete[] sorted_data; } <commit_msg>Rename test since merge sort is not recursive<commit_after>#include <iostream> // std::cout #include <stdlib.h> // rand() #include <time.h> // time() #include "gtest/gtest.h" #include "sorting.h" #include "printarray.h" #include "verifyarrays.h" #define quiet // ********************************************************************* TEST(EfficientSorts, MergeSort) { const int N = 4; double *to_sort_data = new double[N]; double *sorted_data = new double[N]; // Initialize the array with random values between 1 and 100 // NOTE: rand() is a terrible pseudo-random number generator (PRNG). // It is still used here for a simple testing task, but don't use it // for anything serious. srand(time(NULL)); for (int i = 0 ; i < N ; i++) { to_sort_data[i] = rand() % 100 + 1; } to_sort_data[0] = 6.0; to_sort_data[1] = 5.0; to_sort_data[2] = 3.0; to_sort_data[3] = 1.0; memcpy(sorted_data, to_sort_data, N*sizeof(double)); sorting::efficient::MergeSort(sorted_data, N); #ifndef quiet std::cout << "Arrays" << std::endl; std::cout << "Index Original Sorted " << std::endl; for (int i = 0 ; i < N ; i++) { std::cout << i+1 << "/" << N << " " << to_sort_data[i] << " " << sorted_data[i] << std::endl; } #endif // quiet for (int i = 1 ; i < N ; i++) { EXPECT_GE(sorted_data[i], sorted_data[i-1]); } for (int i = 0 ; i < N ; i++) { EXPECT_NE(sorted_data[i], 0); } ASSERT_TRUE(VerifyIfAllNotNaN(sorted_data, N)); ASSERT_TRUE(VerifyIfOrdered(sorted_data, N)); ASSERT_TRUE(VerifySortedUnique(to_sort_data, sorted_data, N)); delete[] to_sort_data; delete[] sorted_data; } <|endoftext|>
<commit_before>#include <iostream> // std::cout #include <stdlib.h> // rand() #include <time.h> // time() #include "gtest/gtest.h" #include "sorting.h" #include "printarray.h" #include "verifyarrays.h" #include "verifysortedarrays.h" #define quiet // ********************************************************************* TEST(EfficientSorts, MergeSortMultipleSizes) { const double to_sorts[] = {6.0, 5.0, 3.0, 1.0, 2.4, 4.0, 10.0, 7.0}; for (int N = 1 ; N < 8 ; N++) { double *to_sort_data = new double[N]; double *sorted_data = new double[N]; // Initialize the array with random values between 1 and 100 // NOTE: rand() is a terrible pseudo-random number generator (PRNG). // It is still used here for a simple testing task, but don't use it // for anything serious. srand(time(NULL)); for (int i = 0 ; i < N ; i++) { to_sort_data[i] = rand() % 100 + 1; } for (int i = 0 ; i < N ; i++) { to_sort_data[i] = to_sorts[i]; } memcpy(sorted_data, to_sort_data, N*sizeof(double)); SORT_AND_VERIFY(to_sort_data, sorted_data, N, sorting::efficient::MergeSort, false); delete[] to_sort_data; delete[] sorted_data; } } // ********************************************************************* TEST(EfficientSorts, MergeSortMultipleSizesRandom) { for (int N = 1 ; N < 100 ; N++) { double *to_sort_data = new double[N]; double *sorted_data = new double[N]; // Initialize the array with random values between 1 and 100 // NOTE: rand() is a terrible pseudo-random number generator (PRNG). // It is still used here for a simple testing task, but don't use it // for anything serious. srand(time(NULL)); for (int i = 0 ; i < N ; i++) { to_sort_data[i] = rand() % 100 + 1; } memcpy(sorted_data, to_sort_data, N*sizeof(double)); SORT_AND_VERIFY(to_sort_data, sorted_data, N, sorting::efficient::MergeSort, false); delete[] to_sort_data; delete[] sorted_data; } } <commit_msg>No need to set random values if we set specific values<commit_after>#include <iostream> // std::cout #include <stdlib.h> // rand() #include <time.h> // time() #include "gtest/gtest.h" #include "sorting.h" #include "printarray.h" #include "verifyarrays.h" #include "verifysortedarrays.h" #define quiet // ********************************************************************* TEST(EfficientSorts, MergeSortMultipleSizes) { const double to_sorts[] = {6.0, 5.0, 3.0, 1.0, 2.4, 4.0, 10.0, 7.0}; for (int N = 1 ; N < 8 ; N++) { double *to_sort_data = new double[N]; double *sorted_data = new double[N]; for (int i = 0 ; i < N ; i++) { to_sort_data[i] = to_sorts[i]; } memcpy(sorted_data, to_sort_data, N*sizeof(double)); SORT_AND_VERIFY(to_sort_data, sorted_data, N, sorting::efficient::MergeSort, false); delete[] to_sort_data; delete[] sorted_data; } } // ********************************************************************* TEST(EfficientSorts, MergeSortMultipleSizesRandom) { for (int N = 1 ; N < 100 ; N++) { double *to_sort_data = new double[N]; double *sorted_data = new double[N]; // Initialize the array with random values between 1 and 100 // NOTE: rand() is a terrible pseudo-random number generator (PRNG). // It is still used here for a simple testing task, but don't use it // for anything serious. srand(time(NULL)); for (int i = 0 ; i < N ; i++) { to_sort_data[i] = rand() % 100 + 1; } memcpy(sorted_data, to_sort_data, N*sizeof(double)); SORT_AND_VERIFY(to_sort_data, sorted_data, N, sorting::efficient::MergeSort, false); delete[] to_sort_data; delete[] sorted_data; } } <|endoftext|>
<commit_before>//===-- TargetData.cpp - Data size & alignment routines --------------------==// // // This file defines target properties related to datatype size/offset/alignment // information. It uses lazy annotations to cache information about how // structure types are laid out and used. // // This structure should be created once, filled in if the defaults are not // correct and then passed around by const&. None of the members functions // require modification to the object. // //===----------------------------------------------------------------------===// #include "llvm/Target/TargetData.h" #include "llvm/Module.h" #include "llvm/DerivedTypes.h" #include "llvm/Constants.h" // Handle the Pass registration stuff necessary to use TargetData's. namespace { // Register the default SparcV9 implementation... RegisterPass<TargetData> X("targetdata", "Target Data Layout"); } static inline void getTypeInfo(const Type *Ty, const TargetData *TD, uint64_t &Size, unsigned char &Alignment); //===----------------------------------------------------------------------===// // Support for StructLayout Annotation //===----------------------------------------------------------------------===// StructLayout::StructLayout(const StructType *ST, const TargetData &TD) : Annotation(TD.getStructLayoutAID()) { StructAlignment = 0; StructSize = 0; // Loop over each of the elements, placing them in memory... for (StructType::ElementTypes::const_iterator TI = ST->getElementTypes().begin(), TE = ST->getElementTypes().end(); TI != TE; ++TI) { const Type *Ty = *TI; unsigned char A; unsigned TyAlign; uint64_t TySize; getTypeInfo(Ty, &TD, TySize, A); TyAlign = A; // Add padding if necessary to make the data element aligned properly... if (StructSize % TyAlign != 0) StructSize = (StructSize/TyAlign + 1) * TyAlign; // Add padding... // Keep track of maximum alignment constraint StructAlignment = std::max(TyAlign, StructAlignment); MemberOffsets.push_back(StructSize); StructSize += TySize; // Consume space for this data item } // Empty structures have alignment of 1 byte. if (StructAlignment == 0) StructAlignment = 1; // Add padding to the end of the struct so that it could be put in an array // and all array elements would be aligned correctly. if (StructSize % StructAlignment != 0) StructSize = (StructSize/StructAlignment + 1) * StructAlignment; } Annotation *TargetData::TypeAnFactory(AnnotationID AID, const Annotable *T, void *D) { const TargetData &TD = *(const TargetData*)D; assert(AID == TD.AID && "Target data annotation ID mismatch!"); const Type *Ty = cast<Type>((const Value *)T); assert(isa<StructType>(Ty) && "Can only create StructLayout annotation on structs!"); return new StructLayout(cast<StructType>(Ty), TD); } //===----------------------------------------------------------------------===// // TargetData Class Implementation //===----------------------------------------------------------------------===// TargetData::TargetData(const std::string &TargetName, bool isLittleEndian, unsigned char PtrSize, unsigned char PtrAl, unsigned char DoubleAl, unsigned char FloatAl, unsigned char LongAl, unsigned char IntAl, unsigned char ShortAl, unsigned char ByteAl) : AID(AnnotationManager::getID("TargetData::" + TargetName)) { AnnotationManager::registerAnnotationFactory(AID, TypeAnFactory, this); // If this assert triggers, a pass "required" TargetData information, but the // top level tool did not provide once for it. We do not want to default // construct, or else we might end up using a bad endianness or pointer size! // assert(!TargetName.empty() && "ERROR: Tool did not specify a target data to use!"); LittleEndian = isLittleEndian; PointerSize = PtrSize; PointerAlignment = PtrAl; DoubleAlignment = DoubleAl; assert(DoubleAlignment == PtrAl && "Double alignment and pointer alignment agree for now!"); FloatAlignment = FloatAl; LongAlignment = LongAl; IntAlignment = IntAl; ShortAlignment = ShortAl; ByteAlignment = ByteAl; } TargetData::TargetData(const std::string &ToolName, const Module *M) : AID(AnnotationManager::getID("TargetData::" + ToolName)) { AnnotationManager::registerAnnotationFactory(AID, TypeAnFactory, this); LittleEndian = M->isLittleEndian(); PointerSize = M->has32BitPointers() ? 4 : 8; PointerAlignment = PointerSize; DoubleAlignment = PointerSize; FloatAlignment = 4; LongAlignment = 8; IntAlignment = 4; ShortAlignment = 2; ByteAlignment = 1; } TargetData::~TargetData() { AnnotationManager::registerAnnotationFactory(AID, 0); // Deregister factory } static inline void getTypeInfo(const Type *Ty, const TargetData *TD, uint64_t &Size, unsigned char &Alignment) { assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!"); switch (Ty->getPrimitiveID()) { case Type::VoidTyID: case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID: Size = 1; Alignment = TD->getByteAlignment(); return; case Type::UShortTyID: case Type::ShortTyID: Size = 2; Alignment = TD->getShortAlignment(); return; case Type::UIntTyID: case Type::IntTyID: Size = 4; Alignment = TD->getIntAlignment(); return; case Type::ULongTyID: case Type::LongTyID: Size = 8; Alignment = TD->getLongAlignment(); return; case Type::FloatTyID: Size = 4; Alignment = TD->getFloatAlignment(); return; case Type::DoubleTyID: Size = 8; Alignment = TD->getDoubleAlignment(); return; case Type::LabelTyID: case Type::PointerTyID: Size = TD->getPointerSize(); Alignment = TD->getPointerAlignment(); return; case Type::ArrayTyID: { const ArrayType *ATy = (const ArrayType *)Ty; getTypeInfo(ATy->getElementType(), TD, Size, Alignment); Size *= ATy->getNumElements(); return; } case Type::StructTyID: { // Get the layout annotation... which is lazily created on demand. const StructLayout *Layout = TD->getStructLayout((const StructType*)Ty); Size = Layout->StructSize; Alignment = Layout->StructAlignment; return; } case Type::TypeTyID: default: assert(0 && "Bad type for getTypeInfo!!!"); return; } } uint64_t TargetData::getTypeSize(const Type *Ty) const { uint64_t Size; unsigned char Align; getTypeInfo(Ty, this, Size, Align); return Size; } unsigned char TargetData::getTypeAlignment(const Type *Ty) const { uint64_t Size; unsigned char Align; getTypeInfo(Ty, this, Size, Align); return Align; } uint64_t TargetData::getIndexedOffset(const Type *ptrTy, const std::vector<Value*> &Idx) const { const Type *Ty = ptrTy; assert(isa<PointerType>(Ty) && "Illegal argument for getIndexedOffset()"); uint64_t Result = 0; for (unsigned CurIDX = 0; CurIDX != Idx.size(); ++CurIDX) { if (Idx[CurIDX]->getType() == Type::LongTy) { // Update Ty to refer to current element Ty = cast<SequentialType>(Ty)->getElementType(); // Get the array index and the size of each array element. int64_t arrayIdx = cast<ConstantSInt>(Idx[CurIDX])->getValue(); Result += arrayIdx * (int64_t)getTypeSize(Ty); } else { const StructType *STy = cast<StructType>(Ty); assert(Idx[CurIDX]->getType() == Type::UByteTy && "Illegal struct idx"); unsigned FieldNo = cast<ConstantUInt>(Idx[CurIDX])->getValue(); // Get structure layout information... const StructLayout *Layout = getStructLayout(STy); // Add in the offset, as calculated by the structure layout info... assert(FieldNo < Layout->MemberOffsets.size() &&"FieldNo out of range!"); Result += Layout->MemberOffsets[FieldNo]; // Update Ty to refer to current element Ty = STy->getElementTypes()[FieldNo]; } } return Result; } <commit_msg>Add support for 'any' pointer size and endianness<commit_after>//===-- TargetData.cpp - Data size & alignment routines --------------------==// // // This file defines target properties related to datatype size/offset/alignment // information. It uses lazy annotations to cache information about how // structure types are laid out and used. // // This structure should be created once, filled in if the defaults are not // correct and then passed around by const&. None of the members functions // require modification to the object. // //===----------------------------------------------------------------------===// #include "llvm/Target/TargetData.h" #include "llvm/Module.h" #include "llvm/DerivedTypes.h" #include "llvm/Constants.h" // Handle the Pass registration stuff necessary to use TargetData's. namespace { // Register the default SparcV9 implementation... RegisterPass<TargetData> X("targetdata", "Target Data Layout"); } static inline void getTypeInfo(const Type *Ty, const TargetData *TD, uint64_t &Size, unsigned char &Alignment); //===----------------------------------------------------------------------===// // Support for StructLayout Annotation //===----------------------------------------------------------------------===// StructLayout::StructLayout(const StructType *ST, const TargetData &TD) : Annotation(TD.getStructLayoutAID()) { StructAlignment = 0; StructSize = 0; // Loop over each of the elements, placing them in memory... for (StructType::ElementTypes::const_iterator TI = ST->getElementTypes().begin(), TE = ST->getElementTypes().end(); TI != TE; ++TI) { const Type *Ty = *TI; unsigned char A; unsigned TyAlign; uint64_t TySize; getTypeInfo(Ty, &TD, TySize, A); TyAlign = A; // Add padding if necessary to make the data element aligned properly... if (StructSize % TyAlign != 0) StructSize = (StructSize/TyAlign + 1) * TyAlign; // Add padding... // Keep track of maximum alignment constraint StructAlignment = std::max(TyAlign, StructAlignment); MemberOffsets.push_back(StructSize); StructSize += TySize; // Consume space for this data item } // Empty structures have alignment of 1 byte. if (StructAlignment == 0) StructAlignment = 1; // Add padding to the end of the struct so that it could be put in an array // and all array elements would be aligned correctly. if (StructSize % StructAlignment != 0) StructSize = (StructSize/StructAlignment + 1) * StructAlignment; } Annotation *TargetData::TypeAnFactory(AnnotationID AID, const Annotable *T, void *D) { const TargetData &TD = *(const TargetData*)D; assert(AID == TD.AID && "Target data annotation ID mismatch!"); const Type *Ty = cast<Type>((const Value *)T); assert(isa<StructType>(Ty) && "Can only create StructLayout annotation on structs!"); return new StructLayout(cast<StructType>(Ty), TD); } //===----------------------------------------------------------------------===// // TargetData Class Implementation //===----------------------------------------------------------------------===// TargetData::TargetData(const std::string &TargetName, bool isLittleEndian, unsigned char PtrSize, unsigned char PtrAl, unsigned char DoubleAl, unsigned char FloatAl, unsigned char LongAl, unsigned char IntAl, unsigned char ShortAl, unsigned char ByteAl) : AID(AnnotationManager::getID("TargetData::" + TargetName)) { AnnotationManager::registerAnnotationFactory(AID, TypeAnFactory, this); // If this assert triggers, a pass "required" TargetData information, but the // top level tool did not provide once for it. We do not want to default // construct, or else we might end up using a bad endianness or pointer size! // assert(!TargetName.empty() && "ERROR: Tool did not specify a target data to use!"); LittleEndian = isLittleEndian; PointerSize = PtrSize; PointerAlignment = PtrAl; DoubleAlignment = DoubleAl; assert(DoubleAlignment == PtrAl && "Double alignment and pointer alignment agree for now!"); FloatAlignment = FloatAl; LongAlignment = LongAl; IntAlignment = IntAl; ShortAlignment = ShortAl; ByteAlignment = ByteAl; } TargetData::TargetData(const std::string &ToolName, const Module *M) : AID(AnnotationManager::getID("TargetData::" + ToolName)) { AnnotationManager::registerAnnotationFactory(AID, TypeAnFactory, this); LittleEndian = M->getEndianness() != Module::BigEndian; PointerSize = M->getPointerSize() != Module::Pointer64 ? 4 : 8; PointerAlignment = PointerSize; DoubleAlignment = PointerSize; FloatAlignment = 4; LongAlignment = 8; IntAlignment = 4; ShortAlignment = 2; ByteAlignment = 1; } TargetData::~TargetData() { AnnotationManager::registerAnnotationFactory(AID, 0); // Deregister factory } static inline void getTypeInfo(const Type *Ty, const TargetData *TD, uint64_t &Size, unsigned char &Alignment) { assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!"); switch (Ty->getPrimitiveID()) { case Type::VoidTyID: case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID: Size = 1; Alignment = TD->getByteAlignment(); return; case Type::UShortTyID: case Type::ShortTyID: Size = 2; Alignment = TD->getShortAlignment(); return; case Type::UIntTyID: case Type::IntTyID: Size = 4; Alignment = TD->getIntAlignment(); return; case Type::ULongTyID: case Type::LongTyID: Size = 8; Alignment = TD->getLongAlignment(); return; case Type::FloatTyID: Size = 4; Alignment = TD->getFloatAlignment(); return; case Type::DoubleTyID: Size = 8; Alignment = TD->getDoubleAlignment(); return; case Type::LabelTyID: case Type::PointerTyID: Size = TD->getPointerSize(); Alignment = TD->getPointerAlignment(); return; case Type::ArrayTyID: { const ArrayType *ATy = (const ArrayType *)Ty; getTypeInfo(ATy->getElementType(), TD, Size, Alignment); Size *= ATy->getNumElements(); return; } case Type::StructTyID: { // Get the layout annotation... which is lazily created on demand. const StructLayout *Layout = TD->getStructLayout((const StructType*)Ty); Size = Layout->StructSize; Alignment = Layout->StructAlignment; return; } case Type::TypeTyID: default: assert(0 && "Bad type for getTypeInfo!!!"); return; } } uint64_t TargetData::getTypeSize(const Type *Ty) const { uint64_t Size; unsigned char Align; getTypeInfo(Ty, this, Size, Align); return Size; } unsigned char TargetData::getTypeAlignment(const Type *Ty) const { uint64_t Size; unsigned char Align; getTypeInfo(Ty, this, Size, Align); return Align; } uint64_t TargetData::getIndexedOffset(const Type *ptrTy, const std::vector<Value*> &Idx) const { const Type *Ty = ptrTy; assert(isa<PointerType>(Ty) && "Illegal argument for getIndexedOffset()"); uint64_t Result = 0; for (unsigned CurIDX = 0; CurIDX != Idx.size(); ++CurIDX) { if (Idx[CurIDX]->getType() == Type::LongTy) { // Update Ty to refer to current element Ty = cast<SequentialType>(Ty)->getElementType(); // Get the array index and the size of each array element. int64_t arrayIdx = cast<ConstantSInt>(Idx[CurIDX])->getValue(); Result += arrayIdx * (int64_t)getTypeSize(Ty); } else { const StructType *STy = cast<StructType>(Ty); assert(Idx[CurIDX]->getType() == Type::UByteTy && "Illegal struct idx"); unsigned FieldNo = cast<ConstantUInt>(Idx[CurIDX])->getValue(); // Get structure layout information... const StructLayout *Layout = getStructLayout(STy); // Add in the offset, as calculated by the structure layout info... assert(FieldNo < Layout->MemberOffsets.size() &&"FieldNo out of range!"); Result += Layout->MemberOffsets[FieldNo]; // Update Ty to refer to current element Ty = STy->getElementTypes()[FieldNo]; } } return Result; } <|endoftext|>
<commit_before>//===-- TargetData.cpp - Data size & alignment routines --------------------==// // // 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 target properties related to datatype size/offset/alignment // information. // // This structure should be created once, filled in if the defaults are not // correct and then passed around by const&. None of the members functions // require modification to the object. // //===----------------------------------------------------------------------===// #include "llvm/Target/TargetData.h" #include "llvm/Module.h" #include "llvm/DerivedTypes.h" #include "llvm/Constants.h" #include "llvm/Support/GetElementPtrTypeIterator.h" #include "llvm/Support/MathExtras.h" #include "llvm/ADT/StringExtras.h" #include <algorithm> #include <cstdlib> #include <sstream> using namespace llvm; // Handle the Pass registration stuff necessary to use TargetData's. namespace { // Register the default SparcV9 implementation... RegisterPass<TargetData> X("targetdata", "Target Data Layout"); } static inline void getTypeInfo(const Type *Ty, const TargetData *TD, uint64_t &Size, unsigned char &Alignment); //===----------------------------------------------------------------------===// // Support for StructLayout //===----------------------------------------------------------------------===// StructLayout::StructLayout(const StructType *ST, const TargetData &TD) { StructAlignment = 0; StructSize = 0; // Loop over each of the elements, placing them in memory... for (StructType::element_iterator TI = ST->element_begin(), TE = ST->element_end(); TI != TE; ++TI) { const Type *Ty = *TI; unsigned char A; unsigned TyAlign; uint64_t TySize; getTypeInfo(Ty, &TD, TySize, A); TyAlign = A; // Add padding if necessary to make the data element aligned properly... if (StructSize % TyAlign != 0) StructSize = (StructSize/TyAlign + 1) * TyAlign; // Add padding... // Keep track of maximum alignment constraint StructAlignment = std::max(TyAlign, StructAlignment); MemberOffsets.push_back(StructSize); StructSize += TySize; // Consume space for this data item } // Empty structures have alignment of 1 byte. if (StructAlignment == 0) StructAlignment = 1; // Add padding to the end of the struct so that it could be put in an array // and all array elements would be aligned correctly. if (StructSize % StructAlignment != 0) StructSize = (StructSize/StructAlignment + 1) * StructAlignment; } /// getElementContainingOffset - Given a valid offset into the structure, /// return the structure index that contains it. unsigned StructLayout::getElementContainingOffset(uint64_t Offset) const { std::vector<uint64_t>::const_iterator SI = std::upper_bound(MemberOffsets.begin(), MemberOffsets.end(), Offset); assert(SI != MemberOffsets.begin() && "Offset not in structure type!"); --SI; assert(*SI <= Offset && "upper_bound didn't work"); assert((SI == MemberOffsets.begin() || *(SI-1) < Offset) && (SI+1 == MemberOffsets.end() || *(SI+1) > Offset) && "Upper bound didn't work!"); return SI-MemberOffsets.begin(); } //===----------------------------------------------------------------------===// // TargetData Class Implementation //===----------------------------------------------------------------------===// TargetData::TargetData(const std::string &TargetName, bool isLittleEndian, unsigned char PtrSize, unsigned char PtrAl, unsigned char DoubleAl, unsigned char FloatAl, unsigned char LongAl, unsigned char IntAl, unsigned char ShortAl, unsigned char ByteAl, unsigned char BoolAl) { // If this assert triggers, a pass "required" TargetData information, but the // top level tool did not provide one for it. We do not want to default // construct, or else we might end up using a bad endianness or pointer size! // assert(!TargetName.empty() && "ERROR: Tool did not specify a target data to use!"); LittleEndian = isLittleEndian; PointerSize = PtrSize; PointerAlignment = PtrAl; DoubleAlignment = DoubleAl; FloatAlignment = FloatAl; LongAlignment = LongAl; IntAlignment = IntAl; ShortAlignment = ShortAl; ByteAlignment = ByteAl; BoolAlignment = BoolAl; } TargetData::TargetData(const std::string &TargetName, const std::string &TargetDescription) { std::string temp = TargetDescription; LittleEndian = false; PointerSize = 8; PointerAlignment = 8; DoubleAlignment = 8; FloatAlignment = 4; LongAlignment = 8; IntAlignment = 4; ShortAlignment = 2; ByteAlignment = 1; BoolAlignment = 1; while (temp.length() > 0) { std::string token = getToken(temp, "-"); switch(token[0]) { case 'E': LittleEndian = false; break; case 'e': LittleEndian = true; break; case 'p': PointerSize = atoi(getToken(token,":").c_str()) / 8; PointerAlignment = atoi(getToken(token,":").c_str()) / 8; break; case 'd': token = getToken(token,":"); //Ignore the size DoubleAlignment = atoi(getToken(token,":").c_str()) / 8; break; case 'f': token = getToken(token, ":"); //Ignore the size FloatAlignment = atoi(getToken(token, ":").c_str()) / 8; break; case 'l': token = getToken(token, ":"); //Ignore the size LongAlignment = atoi(getToken(token, ":").c_str()) / 8; break; case 'i': token = getToken(token, ":"); //Ignore the size IntAlignment = atoi(getToken(token, ":").c_str()) / 8; break; case 's': token = getToken(token, ":"); //Ignore the size ShortAlignment = atoi(getToken(token, ":").c_str()) / 8; break; case 'b': token = getToken(token, ":"); //Ignore the size ByteAlignment = atoi(getToken(token, ":").c_str()) / 8; break; case 'B': token = getToken(token, ":"); //Ignore the size BoolAlignment = atoi(getToken(token, ":").c_str()) / 8; break; default: break; } } } TargetData::TargetData(const std::string &ToolName, const Module *M) { LittleEndian = M->getEndianness() != Module::BigEndian; PointerSize = M->getPointerSize() != Module::Pointer64 ? 4 : 8; PointerAlignment = PointerSize; DoubleAlignment = PointerSize; FloatAlignment = 4; LongAlignment = PointerSize; IntAlignment = 4; ShortAlignment = 2; ByteAlignment = 1; BoolAlignment = 1; } /// Layouts - The lazy cache of structure layout information maintained by /// TargetData. /// static std::map<std::pair<const TargetData*,const StructType*>, StructLayout> *Layouts = 0; TargetData::~TargetData() { if (Layouts) { // Remove any layouts for this TD. std::map<std::pair<const TargetData*, const StructType*>, StructLayout>::iterator I = Layouts->lower_bound(std::make_pair(this, (const StructType*)0)); while (I != Layouts->end() && I->first.first == this) Layouts->erase(I++); if (Layouts->empty()) { delete Layouts; Layouts = 0; } } } std::string TargetData::getStringRepresentation() const { std::stringstream repr; if (LittleEndian) repr << "e"; else repr << "E"; repr << "-p:" << (PointerSize * 8) << ":" << (PointerAlignment * 8); repr << "-d:64:" << (DoubleAlignment * 8); repr << "-f:32:" << (FloatAlignment * 8); repr << "-l:64:" << (LongAlignment * 8); repr << "-i:32:" << (IntAlignment * 8); repr << "-s:16:" << (ShortAlignment * 8); repr << "-b:8:" << (ByteAlignment * 8); repr << "-B:8:" << (BoolAlignment * 8); return repr.str(); } const StructLayout *TargetData::getStructLayout(const StructType *Ty) const { if (Layouts == 0) Layouts = new std::map<std::pair<const TargetData*,const StructType*>, StructLayout>(); std::map<std::pair<const TargetData*,const StructType*>, StructLayout>::iterator I = Layouts->lower_bound(std::make_pair(this, Ty)); if (I != Layouts->end() && I->first.first == this && I->first.second == Ty) return &I->second; else { return &Layouts->insert(I, std::make_pair(std::make_pair(this, Ty), StructLayout(Ty, *this)))->second; } } /// InvalidateStructLayoutInfo - TargetData speculatively caches StructLayout /// objects. If a TargetData object is alive when types are being refined and /// removed, this method must be called whenever a StructType is removed to /// avoid a dangling pointer in this cache. void TargetData::InvalidateStructLayoutInfo(const StructType *Ty) const { if (!Layouts) return; // No cache. std::map<std::pair<const TargetData*,const StructType*>, StructLayout>::iterator I = Layouts->find(std::make_pair(this, Ty)); if (I != Layouts->end()) Layouts->erase(I); } static inline void getTypeInfo(const Type *Ty, const TargetData *TD, uint64_t &Size, unsigned char &Alignment) { assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!"); switch (Ty->getTypeID()) { case Type::BoolTyID: Size = 1; Alignment = TD->getBoolAlignment(); return; case Type::VoidTyID: case Type::UByteTyID: case Type::SByteTyID: Size = 1; Alignment = TD->getByteAlignment(); return; case Type::UShortTyID: case Type::ShortTyID: Size = 2; Alignment = TD->getShortAlignment(); return; case Type::UIntTyID: case Type::IntTyID: Size = 4; Alignment = TD->getIntAlignment(); return; case Type::ULongTyID: case Type::LongTyID: Size = 8; Alignment = TD->getLongAlignment(); return; case Type::FloatTyID: Size = 4; Alignment = TD->getFloatAlignment(); return; case Type::DoubleTyID: Size = 8; Alignment = TD->getDoubleAlignment(); return; case Type::LabelTyID: case Type::PointerTyID: Size = TD->getPointerSize(); Alignment = TD->getPointerAlignment(); return; case Type::ArrayTyID: { const ArrayType *ATy = cast<ArrayType>(Ty); getTypeInfo(ATy->getElementType(), TD, Size, Alignment); unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment; Size = AlignedSize*ATy->getNumElements(); return; } case Type::PackedTyID: { const PackedType *PTy = cast<PackedType>(Ty); getTypeInfo(PTy->getElementType(), TD, Size, Alignment); unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment; Size = AlignedSize*PTy->getNumElements(); // FIXME: The alignments of specific packed types are target dependent. // For now, just set it to be equal to Size. Alignment = Size; return; } case Type::StructTyID: { // Get the layout annotation... which is lazily created on demand. const StructLayout *Layout = TD->getStructLayout(cast<StructType>(Ty)); Size = Layout->StructSize; Alignment = Layout->StructAlignment; return; } default: assert(0 && "Bad type for getTypeInfo!!!"); return; } } uint64_t TargetData::getTypeSize(const Type *Ty) const { uint64_t Size; unsigned char Align; getTypeInfo(Ty, this, Size, Align); return Size; } unsigned char TargetData::getTypeAlignment(const Type *Ty) const { uint64_t Size; unsigned char Align; getTypeInfo(Ty, this, Size, Align); return Align; } unsigned char TargetData::getTypeAlignmentShift(const Type *Ty) const { unsigned Align = getTypeAlignment(Ty); assert(!(Align & (Align-1)) && "Alignment is not a power of two!"); return Log2_32(Align); } /// getIntPtrType - Return an unsigned integer type that is the same size or /// greater to the host pointer size. const Type *TargetData::getIntPtrType() const { switch (getPointerSize()) { default: assert(0 && "Unknown pointer size!"); case 2: return Type::UShortTy; case 4: return Type::UIntTy; case 8: return Type::ULongTy; } } uint64_t TargetData::getIndexedOffset(const Type *ptrTy, const std::vector<Value*> &Idx) const { const Type *Ty = ptrTy; assert(isa<PointerType>(Ty) && "Illegal argument for getIndexedOffset()"); uint64_t Result = 0; generic_gep_type_iterator<std::vector<Value*>::const_iterator> TI = gep_type_begin(ptrTy, Idx.begin(), Idx.end()); for (unsigned CurIDX = 0; CurIDX != Idx.size(); ++CurIDX, ++TI) { if (const StructType *STy = dyn_cast<StructType>(*TI)) { assert(Idx[CurIDX]->getType() == Type::UIntTy && "Illegal struct idx"); unsigned FieldNo = cast<ConstantUInt>(Idx[CurIDX])->getValue(); // Get structure layout information... const StructLayout *Layout = getStructLayout(STy); // Add in the offset, as calculated by the structure layout info... assert(FieldNo < Layout->MemberOffsets.size() &&"FieldNo out of range!"); Result += Layout->MemberOffsets[FieldNo]; // Update Ty to refer to current element Ty = STy->getElementType(FieldNo); } else { // Update Ty to refer to current element Ty = cast<SequentialType>(Ty)->getElementType(); // Get the array index and the size of each array element. int64_t arrayIdx = cast<ConstantInt>(Idx[CurIDX])->getRawValue(); Result += arrayIdx * (int64_t)getTypeSize(Ty); } } return Result; } <commit_msg>Fix a stupid bug when parsing TargetData strings.<commit_after>//===-- TargetData.cpp - Data size & alignment routines --------------------==// // // 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 target properties related to datatype size/offset/alignment // information. // // This structure should be created once, filled in if the defaults are not // correct and then passed around by const&. None of the members functions // require modification to the object. // //===----------------------------------------------------------------------===// #include "llvm/Target/TargetData.h" #include "llvm/Module.h" #include "llvm/DerivedTypes.h" #include "llvm/Constants.h" #include "llvm/Support/GetElementPtrTypeIterator.h" #include "llvm/Support/MathExtras.h" #include "llvm/ADT/StringExtras.h" #include <algorithm> #include <cstdlib> #include <sstream> using namespace llvm; // Handle the Pass registration stuff necessary to use TargetData's. namespace { // Register the default SparcV9 implementation... RegisterPass<TargetData> X("targetdata", "Target Data Layout"); } static inline void getTypeInfo(const Type *Ty, const TargetData *TD, uint64_t &Size, unsigned char &Alignment); //===----------------------------------------------------------------------===// // Support for StructLayout //===----------------------------------------------------------------------===// StructLayout::StructLayout(const StructType *ST, const TargetData &TD) { StructAlignment = 0; StructSize = 0; // Loop over each of the elements, placing them in memory... for (StructType::element_iterator TI = ST->element_begin(), TE = ST->element_end(); TI != TE; ++TI) { const Type *Ty = *TI; unsigned char A; unsigned TyAlign; uint64_t TySize; getTypeInfo(Ty, &TD, TySize, A); TyAlign = A; // Add padding if necessary to make the data element aligned properly... if (StructSize % TyAlign != 0) StructSize = (StructSize/TyAlign + 1) * TyAlign; // Add padding... // Keep track of maximum alignment constraint StructAlignment = std::max(TyAlign, StructAlignment); MemberOffsets.push_back(StructSize); StructSize += TySize; // Consume space for this data item } // Empty structures have alignment of 1 byte. if (StructAlignment == 0) StructAlignment = 1; // Add padding to the end of the struct so that it could be put in an array // and all array elements would be aligned correctly. if (StructSize % StructAlignment != 0) StructSize = (StructSize/StructAlignment + 1) * StructAlignment; } /// getElementContainingOffset - Given a valid offset into the structure, /// return the structure index that contains it. unsigned StructLayout::getElementContainingOffset(uint64_t Offset) const { std::vector<uint64_t>::const_iterator SI = std::upper_bound(MemberOffsets.begin(), MemberOffsets.end(), Offset); assert(SI != MemberOffsets.begin() && "Offset not in structure type!"); --SI; assert(*SI <= Offset && "upper_bound didn't work"); assert((SI == MemberOffsets.begin() || *(SI-1) < Offset) && (SI+1 == MemberOffsets.end() || *(SI+1) > Offset) && "Upper bound didn't work!"); return SI-MemberOffsets.begin(); } //===----------------------------------------------------------------------===// // TargetData Class Implementation //===----------------------------------------------------------------------===// TargetData::TargetData(const std::string &TargetName, bool isLittleEndian, unsigned char PtrSize, unsigned char PtrAl, unsigned char DoubleAl, unsigned char FloatAl, unsigned char LongAl, unsigned char IntAl, unsigned char ShortAl, unsigned char ByteAl, unsigned char BoolAl) { // If this assert triggers, a pass "required" TargetData information, but the // top level tool did not provide one for it. We do not want to default // construct, or else we might end up using a bad endianness or pointer size! // assert(!TargetName.empty() && "ERROR: Tool did not specify a target data to use!"); LittleEndian = isLittleEndian; PointerSize = PtrSize; PointerAlignment = PtrAl; DoubleAlignment = DoubleAl; FloatAlignment = FloatAl; LongAlignment = LongAl; IntAlignment = IntAl; ShortAlignment = ShortAl; ByteAlignment = ByteAl; BoolAlignment = BoolAl; } TargetData::TargetData(const std::string &TargetName, const std::string &TargetDescription) { std::string temp = TargetDescription; LittleEndian = false; PointerSize = 8; PointerAlignment = 8; DoubleAlignment = 8; FloatAlignment = 4; LongAlignment = 8; IntAlignment = 4; ShortAlignment = 2; ByteAlignment = 1; BoolAlignment = 1; while (temp.length() > 0) { std::string token = getToken(temp, "-"); char signal = getToken(token, ":")[0]; switch(signal) { case 'E': LittleEndian = false; break; case 'e': LittleEndian = true; break; case 'p': PointerSize = atoi(getToken(token,":").c_str()) / 8; PointerAlignment = atoi(getToken(token,":").c_str()) / 8; break; case 'd': token = getToken(token,":"); //Ignore the size DoubleAlignment = atoi(getToken(token,":").c_str()) / 8; break; case 'f': token = getToken(token, ":"); //Ignore the size FloatAlignment = atoi(getToken(token, ":").c_str()) / 8; break; case 'l': token = getToken(token, ":"); //Ignore the size LongAlignment = atoi(getToken(token, ":").c_str()) / 8; break; case 'i': token = getToken(token, ":"); //Ignore the size IntAlignment = atoi(getToken(token, ":").c_str()) / 8; break; case 's': token = getToken(token, ":"); //Ignore the size ShortAlignment = atoi(getToken(token, ":").c_str()) / 8; break; case 'b': token = getToken(token, ":"); //Ignore the size ByteAlignment = atoi(getToken(token, ":").c_str()) / 8; break; case 'B': token = getToken(token, ":"); //Ignore the size BoolAlignment = atoi(getToken(token, ":").c_str()) / 8; break; default: break; } } } TargetData::TargetData(const std::string &ToolName, const Module *M) { LittleEndian = M->getEndianness() != Module::BigEndian; PointerSize = M->getPointerSize() != Module::Pointer64 ? 4 : 8; PointerAlignment = PointerSize; DoubleAlignment = PointerSize; FloatAlignment = 4; LongAlignment = PointerSize; IntAlignment = 4; ShortAlignment = 2; ByteAlignment = 1; BoolAlignment = 1; } /// Layouts - The lazy cache of structure layout information maintained by /// TargetData. /// static std::map<std::pair<const TargetData*,const StructType*>, StructLayout> *Layouts = 0; TargetData::~TargetData() { if (Layouts) { // Remove any layouts for this TD. std::map<std::pair<const TargetData*, const StructType*>, StructLayout>::iterator I = Layouts->lower_bound(std::make_pair(this, (const StructType*)0)); while (I != Layouts->end() && I->first.first == this) Layouts->erase(I++); if (Layouts->empty()) { delete Layouts; Layouts = 0; } } } std::string TargetData::getStringRepresentation() const { std::stringstream repr; if (LittleEndian) repr << "e"; else repr << "E"; repr << "-p:" << (PointerSize * 8) << ":" << (PointerAlignment * 8); repr << "-d:64:" << (DoubleAlignment * 8); repr << "-f:32:" << (FloatAlignment * 8); repr << "-l:64:" << (LongAlignment * 8); repr << "-i:32:" << (IntAlignment * 8); repr << "-s:16:" << (ShortAlignment * 8); repr << "-b:8:" << (ByteAlignment * 8); repr << "-B:8:" << (BoolAlignment * 8); return repr.str(); } const StructLayout *TargetData::getStructLayout(const StructType *Ty) const { if (Layouts == 0) Layouts = new std::map<std::pair<const TargetData*,const StructType*>, StructLayout>(); std::map<std::pair<const TargetData*,const StructType*>, StructLayout>::iterator I = Layouts->lower_bound(std::make_pair(this, Ty)); if (I != Layouts->end() && I->first.first == this && I->first.second == Ty) return &I->second; else { return &Layouts->insert(I, std::make_pair(std::make_pair(this, Ty), StructLayout(Ty, *this)))->second; } } /// InvalidateStructLayoutInfo - TargetData speculatively caches StructLayout /// objects. If a TargetData object is alive when types are being refined and /// removed, this method must be called whenever a StructType is removed to /// avoid a dangling pointer in this cache. void TargetData::InvalidateStructLayoutInfo(const StructType *Ty) const { if (!Layouts) return; // No cache. std::map<std::pair<const TargetData*,const StructType*>, StructLayout>::iterator I = Layouts->find(std::make_pair(this, Ty)); if (I != Layouts->end()) Layouts->erase(I); } static inline void getTypeInfo(const Type *Ty, const TargetData *TD, uint64_t &Size, unsigned char &Alignment) { assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!"); switch (Ty->getTypeID()) { case Type::BoolTyID: Size = 1; Alignment = TD->getBoolAlignment(); return; case Type::VoidTyID: case Type::UByteTyID: case Type::SByteTyID: Size = 1; Alignment = TD->getByteAlignment(); return; case Type::UShortTyID: case Type::ShortTyID: Size = 2; Alignment = TD->getShortAlignment(); return; case Type::UIntTyID: case Type::IntTyID: Size = 4; Alignment = TD->getIntAlignment(); return; case Type::ULongTyID: case Type::LongTyID: Size = 8; Alignment = TD->getLongAlignment(); return; case Type::FloatTyID: Size = 4; Alignment = TD->getFloatAlignment(); return; case Type::DoubleTyID: Size = 8; Alignment = TD->getDoubleAlignment(); return; case Type::LabelTyID: case Type::PointerTyID: Size = TD->getPointerSize(); Alignment = TD->getPointerAlignment(); return; case Type::ArrayTyID: { const ArrayType *ATy = cast<ArrayType>(Ty); getTypeInfo(ATy->getElementType(), TD, Size, Alignment); unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment; Size = AlignedSize*ATy->getNumElements(); return; } case Type::PackedTyID: { const PackedType *PTy = cast<PackedType>(Ty); getTypeInfo(PTy->getElementType(), TD, Size, Alignment); unsigned AlignedSize = (Size + Alignment - 1)/Alignment*Alignment; Size = AlignedSize*PTy->getNumElements(); // FIXME: The alignments of specific packed types are target dependent. // For now, just set it to be equal to Size. Alignment = Size; return; } case Type::StructTyID: { // Get the layout annotation... which is lazily created on demand. const StructLayout *Layout = TD->getStructLayout(cast<StructType>(Ty)); Size = Layout->StructSize; Alignment = Layout->StructAlignment; return; } default: assert(0 && "Bad type for getTypeInfo!!!"); return; } } uint64_t TargetData::getTypeSize(const Type *Ty) const { uint64_t Size; unsigned char Align; getTypeInfo(Ty, this, Size, Align); return Size; } unsigned char TargetData::getTypeAlignment(const Type *Ty) const { uint64_t Size; unsigned char Align; getTypeInfo(Ty, this, Size, Align); return Align; } unsigned char TargetData::getTypeAlignmentShift(const Type *Ty) const { unsigned Align = getTypeAlignment(Ty); assert(!(Align & (Align-1)) && "Alignment is not a power of two!"); return Log2_32(Align); } /// getIntPtrType - Return an unsigned integer type that is the same size or /// greater to the host pointer size. const Type *TargetData::getIntPtrType() const { switch (getPointerSize()) { default: assert(0 && "Unknown pointer size!"); case 2: return Type::UShortTy; case 4: return Type::UIntTy; case 8: return Type::ULongTy; } } uint64_t TargetData::getIndexedOffset(const Type *ptrTy, const std::vector<Value*> &Idx) const { const Type *Ty = ptrTy; assert(isa<PointerType>(Ty) && "Illegal argument for getIndexedOffset()"); uint64_t Result = 0; generic_gep_type_iterator<std::vector<Value*>::const_iterator> TI = gep_type_begin(ptrTy, Idx.begin(), Idx.end()); for (unsigned CurIDX = 0; CurIDX != Idx.size(); ++CurIDX, ++TI) { if (const StructType *STy = dyn_cast<StructType>(*TI)) { assert(Idx[CurIDX]->getType() == Type::UIntTy && "Illegal struct idx"); unsigned FieldNo = cast<ConstantUInt>(Idx[CurIDX])->getValue(); // Get structure layout information... const StructLayout *Layout = getStructLayout(STy); // Add in the offset, as calculated by the structure layout info... assert(FieldNo < Layout->MemberOffsets.size() &&"FieldNo out of range!"); Result += Layout->MemberOffsets[FieldNo]; // Update Ty to refer to current element Ty = STy->getElementType(FieldNo); } else { // Update Ty to refer to current element Ty = cast<SequentialType>(Ty)->getElementType(); // Get the array index and the size of each array element. int64_t arrayIdx = cast<ConstantInt>(Idx[CurIDX])->getRawValue(); Result += arrayIdx * (int64_t)getTypeSize(Ty); } } return Result; } <|endoftext|>
<commit_before>#include <sstream> #include <iostream> #include <cstring> #include "datafeeder.h" void DataFeeder::init() { m_pLevel2Api->RegisterSpi(this); m_pLevel2Api->RegisterFront(const_cast<char*>(this->front_address.c_str())); // 使客户端开始与后台服务建立连接 m_pLevel2Api->Init(); } void DataFeeder::OnFrontConnected() { CThostFtdcReqUserLoginField reqUserLogin; strcpy(reqUserLogin.BrokerID, this->brokerID.c_str()); strcpy(reqUserLogin.UserID, this->userID.c_str()); strcpy(reqUserLogin.Password, this->passwd.c_str()); m_pLevel2Api->ReqUserLogin(&reqUserLogin, 0); } void DataFeeder::OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { std::cout << "OnRspUserLogin:\t" << "ErrorCode=[" << pRspInfo->ErrorID << "], ErrorMsg=[" << pRspInfo->ErrorMsg << "]" << std::endl; if (pRspInfo->ErrorID != 0) std::cout << "Error: Login Error!" << std::endl; } void DataFeeder::subscrib_L2_market_data(std::string stockid) { CThostFtdcSpecificSecurityField query; memset(&query, 0, sizeof(query)); std::string security_id = stockid.substr(2); std::string exchange_id = this->ExchangeIDDict[ stockid.substr(0,2) ]; strcpy(query.SecurityID, security_id.c_str()); strcpy(query.ExchangeID, exchange_id.c_str()); m_pLevel2Api->SubscribeLevel2MarketData(&query, 1); } void DataFeeder::OnRtnLevel2MarketData(CThostFtdcLevel2MarketDataField *pLevel2MarketData) { std::ostringstream oss; CThostFtdcLevel2MarketDataField *p = pLevel2MarketData; std::string stockid = this->ExchangeIDDict_Reverse[p->ExchangeID] + p->SecurityID; oss << stockid << ',' << p->OpenPx << ',' << p->PreClosePx << ',' << p->LastPx << ',' << p->HighPx << ',' << p->LowPx << ',' << p->TotalVolumeTrade << ',' << p->TotalValueTrade << ',' << p->BidPx1 << ',' << p->BidOrderQty1 << ',' << p->BidPx2 << ',' << p->BidOrderQty2 << ',' << p->BidPx3 << ',' << p->BidOrderQty3 << ',' << p->OfferPx1 << ',' << p->OfferOrderQty1 << ',' << p->OfferPx2 << ',' << p->OfferOrderQty2 << ',' << p->OfferPx3 << ',' << p->OfferOrderQty3 << ',' << p->TradingDay << ',' << p->DataTimeStamp; stock_datas[stockid] = oss.str(); // std::cout << stock_datas[stockid] << std::endl; } std::string DataFeeder::get_L2_market_data(std::string stockid) { return this->stock_datas[stockid]; } <commit_msg>Delete datafeeder.cpp<commit_after><|endoftext|>
<commit_before>#include <iostream> #include <sstream> #include <string> using namespace std; class Rational { int a, b; int gcd(int a, int b); void simplify(); bool check(const Rational& f); public: Rational(int a=0, int b=1) : a(a) , b(b) { if (b == 0) return; simplify(); }; Rational& operator= (const Rational& f); Rational& Add(const Rational& f); Rational& Substract(const Rational& f); Rational& Multiply(const Rational& f); Rational& Divide(const Rational& f); bool EqualTo(const Rational& f) const; int CompareTo(const Rational& f) const; bool IsInteger() const; string ToString() const; }; int Rational::gcd (int a, int b) { int c; while (b) { c = b; b = a % b; a = c; } return a; } void Rational::simplify() { int c; while ((c = gcd(a, b)) != 1) { if (c == 0) break; a /= c; b /= c; } } bool Rational::check(const Rational& f) { if (b == 0 || f.b == 0) { b = 0; return true; } return false; } Rational& Rational::operator= (const Rational& f) { if (this != &f) { a = f.a; b = f.b; } return *this; } Rational& Rational::Add(const Rational& f) { check(f); a = a * f.b + b * f.a; b = b * f.b; simplify(); return *this; } Rational& Rational::Substract(const Rational& f) { check(f); a = a * f.b - b * f.a; b = b * f.b; simplify(); return *this; } Rational& Rational::Multiply(const Rational& f) { check(f); a *= f.a; b *= f.b; simplify(); return *this; } Rational& Rational::Divide(const Rational& f) { check(f); a *= f.b; b *= f.a; simplify(); return *this; } bool Rational::EqualTo(const Rational& f) const { if (f.a == a && f.b == b) return true; else return false; } int Rational::CompareTo(const Rational& f) const { int c = a * f.b; int d = b * f.a; if (c > d) return 1; if (c < d) return -1; return 0; } bool Rational::IsInteger() const { if (b == 1) return true; return false; } string Rational::ToString() const { stringstream ss; if (b == 0) { if (a >= 0) return "+NAN"; if (a < 0) return "-NAN"; } else { ss << a << "/" << b; } return ss.str(); } const Rational a(1,1); int main() { Rational q = Rational(1, 3), w(1, 4); Rational s = 4; // a.CompareTo(s); w = q; s.Add(q); cout << s.ToString() << endl; s.Substract(q); cout << s.ToString() << endl; s.Multiply(q); cout << s.ToString() << endl; s.Divide(q); cout << s.ToString() << endl; s.Add(q).Multiply(w); cout << s.ToString() << endl; s.EqualTo(w); s.CompareTo(w); s.IsInteger(); cout << s.ToString() << endl; // cout << q.ToString() << endl; // cout << w.ToString() << endl; return 0; } <commit_msg>chmod -x<commit_after>#include <iostream> #include <sstream> #include <string> using namespace std; class Rational { int a, b; int gcd(int a, int b); void simplify(); bool check(const Rational& f); public: Rational(int a=0, int b=1) : a(a) , b(b) { if (b == 0) return; simplify(); }; Rational& operator= (const Rational& f); Rational& Add(const Rational& f); Rational& Substract(const Rational& f); Rational& Multiply(const Rational& f); Rational& Divide(const Rational& f); bool EqualTo(const Rational& f) const; int CompareTo(const Rational& f) const; bool IsInteger() const; string ToString() const; }; int Rational::gcd (int a, int b) { int c; while (b) { c = b; b = a % b; a = c; } return a; } void Rational::simplify() { int c; while ((c = gcd(a, b)) != 1) { if (c == 0) break; a /= c; b /= c; } } bool Rational::check(const Rational& f) { if (b == 0 || f.b == 0) { b = 0; return true; } return false; } Rational& Rational::operator= (const Rational& f) { if (this != &f) { a = f.a; b = f.b; } return *this; } Rational& Rational::Add(const Rational& f) { check(f); a = a * f.b + b * f.a; b = b * f.b; simplify(); return *this; } Rational& Rational::Substract(const Rational& f) { check(f); a = a * f.b - b * f.a; b = b * f.b; simplify(); return *this; } Rational& Rational::Multiply(const Rational& f) { check(f); a *= f.a; b *= f.b; simplify(); return *this; } Rational& Rational::Divide(const Rational& f) { check(f); a *= f.b; b *= f.a; simplify(); return *this; } bool Rational::EqualTo(const Rational& f) const { if (f.a == a && f.b == b) return true; else return false; } int Rational::CompareTo(const Rational& f) const { int c = a * f.b; int d = b * f.a; if (c > d) return 1; if (c < d) return -1; return 0; } bool Rational::IsInteger() const { if (b == 1) return true; return false; } string Rational::ToString() const { stringstream ss; if (b == 0) { if (a >= 0) return "+NAN"; if (a < 0) return "-NAN"; } else { ss << a << "/" << b; } return ss.str(); } const Rational a(1,1); int main() { Rational q = Rational(1, 3), w(1, 4); Rational s = 4; // a.CompareTo(s); w = q; s.Add(q); cout << s.ToString() << endl; s.Substract(q); cout << s.ToString() << endl; s.Multiply(q); cout << s.ToString() << endl; s.Divide(q); cout << s.ToString() << endl; s.Add(q).Multiply(w); cout << s.ToString() << endl; s.EqualTo(w); s.CompareTo(w); s.IsInteger(); cout << s.ToString() << endl; // cout << q.ToString() << endl; // cout << w.ToString() << endl; return 0; } <|endoftext|>
<commit_before>/* ircprotocol - IRC Protocol Copyright (c) 2002 by Nick Betcher <nbetcher@kde.org> Kopete (c) 2002 by the Kopete developers <kopete-devel@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. * * * ************************************************************************* */ #include "ircprotocol.h" #include <qapplication.h> #include <qcursor.h> #include <qregexp.h> #include <kaction.h> #include <kconfig.h> #include <kdebug.h> #include <kgenericfactory.h> #include <kglobal.h> #include <kiconloader.h> #include <klocale.h> #include <kmessagebox.h> #include <kpopupmenu.h> #include <ksimpleconfig.h> #include <kstandarddirs.h> #include "ircadd.h" #include "ircidentity.h" #include "ircaddcontactpage.h" #include "ircpreferences.h" #include "kopetemetacontact.h" #include "ircchannelcontact.h" #include "kopeteidentitymanager.h" #include "irceditidentitywidget.h" #include "kirc.h" K_EXPORT_COMPONENT_FACTORY( kopete_irc, KGenericFactory<IRCProtocol> ); IRCProtocol::IRCProtocol( QObject *parent, const char *name, const QStringList & /* args */ ) : KopeteProtocol( parent, name ) { m_actionMenu = 0L; actionConnect = new KAction ( i18n("Online"), "", 0, this, SLOT(connect()), this, "actionIRCConnect" ); actionDisconnect = new KAction ( i18n("Offline"), "", 0, this, SLOT(disconnect()), this, "actionIRCDisconnect" ); kdDebug(14120) << k_funcinfo << endl; // Load all ICQ icons from KDE standard dirs setStatusIcon( "irc_protocol_offline" ); new IRCPreferences("irc_protocol", this); KConfig *cfg = KGlobal::config(); cfg->setGroup("IRC"); identity = new IRCIdentity( cfg->readEntry("Nickname", "KopeteUser") + "@" + cfg->readEntry("Server", "irc.freenode.net") + ":" + cfg->readEntry("Port", "6667"), this); } IRCProtocol::~IRCProtocol() { //delete identity; } KActionMenu* IRCProtocol::protocolActions() { if (!m_actionMenu) { m_actionMenu = new KActionMenu( "IRC", this ); m_actionMenu->popupMenu()->insertTitle(SmallIcon( "irc_protocol_small" ), i18n( "IRC" ) ); m_actionMenu->insert(actionConnect); m_actionMenu->insert(actionDisconnect); } return m_actionMenu; } void IRCProtocol::connect() { identity->connect(); } void IRCProtocol::disconnect() { identity->disconnect(); } const QString IRCProtocol::protocolIcon() { return "irc_protocol_small"; } void IRCProtocol::init() { } AddContactPage *IRCProtocol::createAddContactWidget(QWidget *parent) { return new IRCAddContactPage(this,parent); } EditIdentityWidget *IRCProtocol::createEditIdentityWidget(KopeteIdentity *identity, QWidget *parent) { return new IRCEditIdentityWidget(this, static_cast<IRCIdentity*>(identity),parent); } KopeteIdentity *IRCProtocol::createNewIdentity(const QString &identityId) { if( !mIdentityMap.contains( identityId ) ) { IRCIdentity *id = new IRCIdentity( identityId, this ); mIdentityMap[ identityId ] = id; KopeteIdentityManager::manager()->registerIdentity( id ); } return mIdentityMap[ identityId ]; } void IRCProtocol::deserializeContact( KopeteMetaContact *metaContact, const QMap<QString, QString> &serializedData, const QMap<QString, QString> & /* addressBookData */ ) { QString contactId = serializedData[ "contactId" ]; if( !contacts()[ contactId ] ) { QString displayName = serializedData[ "displayName" ]; if( displayName.isEmpty() ) displayName = contactId; identity->addContact( contactId, displayName, metaContact ); } } #include "ircprotocol.moc" // vim: set noet ts=4 sts=4 sw=4: <commit_msg>We don't need to do this it is taken care of<commit_after>/* ircprotocol - IRC Protocol Copyright (c) 2002 by Nick Betcher <nbetcher@kde.org> Kopete (c) 2002 by the Kopete developers <kopete-devel@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. * * * ************************************************************************* */ #include "ircprotocol.h" #include <qapplication.h> #include <qcursor.h> #include <qregexp.h> #include <kaction.h> #include <kconfig.h> #include <kdebug.h> #include <kgenericfactory.h> #include <kglobal.h> #include <kiconloader.h> #include <klocale.h> #include <kmessagebox.h> #include <kpopupmenu.h> #include <ksimpleconfig.h> #include <kstandarddirs.h> #include "ircadd.h" #include "ircidentity.h" #include "ircaddcontactpage.h" #include "ircpreferences.h" #include "kopetemetacontact.h" #include "ircchannelcontact.h" #include "kopeteidentitymanager.h" #include "irceditidentitywidget.h" #include "kirc.h" K_EXPORT_COMPONENT_FACTORY( kopete_irc, KGenericFactory<IRCProtocol> ); IRCProtocol::IRCProtocol( QObject *parent, const char *name, const QStringList & /* args */ ) : KopeteProtocol( parent, name ) { m_actionMenu = 0L; actionConnect = new KAction ( i18n("Online"), "", 0, this, SLOT(connect()), this, "actionIRCConnect" ); actionDisconnect = new KAction ( i18n("Offline"), "", 0, this, SLOT(disconnect()), this, "actionIRCDisconnect" ); kdDebug(14120) << k_funcinfo << endl; // Load all ICQ icons from KDE standard dirs setStatusIcon( "irc_protocol_offline" ); new IRCPreferences("irc_protocol", this); KConfig *cfg = KGlobal::config(); cfg->setGroup("IRC"); identity = new IRCIdentity( cfg->readEntry("Nickname", "KopeteUser") + "@" + cfg->readEntry("Server", "irc.freenode.net") + ":" + cfg->readEntry("Port", "6667"), this); } IRCProtocol::~IRCProtocol() { //delete identity; } KActionMenu* IRCProtocol::protocolActions() { if (!m_actionMenu) { m_actionMenu = new KActionMenu( "IRC", this ); m_actionMenu->popupMenu()->insertTitle(SmallIcon( "irc_protocol_small" ), i18n( "IRC" ) ); m_actionMenu->insert(actionConnect); m_actionMenu->insert(actionDisconnect); } return m_actionMenu; } void IRCProtocol::connect() { identity->connect(); } void IRCProtocol::disconnect() { identity->disconnect(); } const QString IRCProtocol::protocolIcon() { return "irc_protocol_small"; } void IRCProtocol::init() { } AddContactPage *IRCProtocol::createAddContactWidget(QWidget *parent) { return new IRCAddContactPage(this,parent); } EditIdentityWidget *IRCProtocol::createEditIdentityWidget(KopeteIdentity *identity, QWidget *parent) { return new IRCEditIdentityWidget(this, static_cast<IRCIdentity*>(identity),parent); } KopeteIdentity *IRCProtocol::createNewIdentity(const QString &identityId) { if( !mIdentityMap.contains( identityId ) ) { IRCIdentity *id = new IRCIdentity( identityId, this ); mIdentityMap[ identityId ] = id; } return mIdentityMap[ identityId ]; } void IRCProtocol::deserializeContact( KopeteMetaContact *metaContact, const QMap<QString, QString> &serializedData, const QMap<QString, QString> & /* addressBookData */ ) { QString contactId = serializedData[ "contactId" ]; if( !contacts()[ contactId ] ) { QString displayName = serializedData[ "displayName" ]; if( displayName.isEmpty() ) displayName = contactId; identity->addContact( contactId, displayName, metaContact ); } } #include "ircprotocol.moc" // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>/* * Copyright (c) 2016 Jason White * * 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 <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <vector> #include "pefile.h" #include "pemap.h" #include "pepatch.h" namespace { /** * A range of memory to patch. This is used to keep track of what needs to be * patched in the PE file. * * All the patch locations need to be found before finishing parsing. If we * patched while parsing, then parsing could fail and we could be left with an * incomplete patch. Thus, we keep a list of patches and patch everything all at * once to mitigate failure cases. */ struct Patch { // Location to patch. uint8_t* addr; // Length of the data. size_t length; // Data overwrite the given location with. const uint8_t* data; Patch(uint8_t* addr, size_t length, const uint8_t* data) : addr(addr), length(length), data(data) {} template<typename T> Patch(T* addr, const T* data) : addr((uint8_t*)addr), length(sizeof(T)), data((const uint8_t*)data) { } /** * Applies the patch. Note that no bounds checking is done. It is assumed * that it has already been done. */ void apply() { for (size_t i = 0; i < length; ++i) *addr = data[i]; } }; class Patches { private: // List of patches std::vector<Patch> _patches; public: Patches() {} ~Patches() {} void add(Patch patch); void applyAll(); }; void Patches::add(Patch patch) { _patches.push_back(patch); } void Patches::applyAll() { for (auto&& patch: _patches) patch.apply(); } } void patchImage(const char* imagePath, const char* pdbPath) { MemMap image(imagePath); // Replacement for timestamps const uint32_t timestamp = 0; uint8_t* pStart = (uint8_t*)image.buf(); uint8_t* pEnd = pStart + image.length(); uint8_t* p = pStart; Patches patches; if (image.length() < sizeof(IMAGE_DOS_HEADER)) throw InvalidImage("missing DOS header"); IMAGE_DOS_HEADER* dosHeader = (IMAGE_DOS_HEADER*)p; if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE) throw InvalidImage("invalid DOS signature"); // Skip to the NT headers. Note that we assume this is a PE32 (not a PE32+) // header for now. p += dosHeader->e_lfanew; if (p + sizeof(IMAGE_NT_HEADERS32) >= pEnd) throw InvalidImage("missing IMAGE_NT_HEADERS"); IMAGE_NT_HEADERS32* ntHeaders = (IMAGE_NT_HEADERS32*)p; // Check the signature if (ntHeaders->Signature != *(const uint32_t*)"PE\0\0") throw InvalidImage("invalid PE signature"); // Eliminate non-determinism patches.add(Patch(&ntHeaders->FileHeader.TimeDateStamp, &timestamp)); patches.add(Patch(&ntHeaders->OptionalHeader.CheckSum, &timestamp)); patches.applyAll(); } <commit_msg>Minor fefactoring<commit_after>/* * Copyright (c) 2016 Jason White * * 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 <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <vector> #include "pefile.h" #include "pemap.h" #include "pepatch.h" namespace { /** * A range of memory to patch. This is used to keep track of what needs to be * patched in the PE file. * * All the patch locations need to be found before finishing parsing. If we * patched while parsing, then parsing could fail and we could be left with an * incomplete patch. Thus, we keep a list of patches and patch everything all at * once to mitigate failure cases. */ struct Patch { // Location to patch. uint8_t* addr; // Length of the data. size_t length; // Data overwrite the given location with. const uint8_t* data; Patch(uint8_t* addr, size_t length, const uint8_t* data) : addr(addr), length(length), data(data) {} template<typename T> Patch(T* addr, const T* data) : addr((uint8_t*)addr), length(sizeof(T)), data((const uint8_t*)data) { } /** * Applies the patch. Note that no bounds checking is done. It is assumed * that it has already been done. */ void apply() { for (size_t i = 0; i < length; ++i) *addr = data[i]; } }; class Patches { private: // List of patches std::vector<Patch> _patches; public: Patches() {} ~Patches() {} void add(Patch patch) { _patches.push_back(patch); } void applyAll() { for (auto&& patch: _patches) patch.apply(); } }; } void patchImage(const char* imagePath, const char* pdbPath) { MemMap image(imagePath); // Replacement for timestamps const uint32_t timestamp = 0; uint8_t* pStart = (uint8_t*)image.buf(); uint8_t* pEnd = pStart + image.length(); uint8_t* p = pStart; Patches patches; if (image.length() < sizeof(IMAGE_DOS_HEADER)) throw InvalidImage("missing DOS header"); IMAGE_DOS_HEADER* dosHeader = (IMAGE_DOS_HEADER*)p; if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE) throw InvalidImage("invalid DOS signature"); // Skip to the NT headers. Note that we assume this is a PE32 (not a PE32+) // header for now. p += dosHeader->e_lfanew; if (p + sizeof(IMAGE_NT_HEADERS32) >= pEnd) throw InvalidImage("missing IMAGE_NT_HEADERS"); IMAGE_NT_HEADERS32* ntHeaders = (IMAGE_NT_HEADERS32*)p; // Check the signature if (ntHeaders->Signature != *(const uint32_t*)"PE\0\0") throw InvalidImage("invalid PE signature"); // Eliminate non-determinism patches.add(Patch(&ntHeaders->FileHeader.TimeDateStamp, &timestamp)); patches.add(Patch(&ntHeaders->OptionalHeader.CheckSum, &timestamp)); patches.applyAll(); } <|endoftext|>
<commit_before>#include <mettle.hpp> using namespace mettle; #include "run_counter.hpp" template<typename F, typename Tuple, std::size_t ...I> decltype(auto) apply_impl(F &&f, Tuple &&t, std::index_sequence<I...>) { return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...); } template<typename F, typename Tuple> decltype(auto) apply(F&& f, Tuple &&t) { using Indices = std::make_index_sequence< std::tuple_size<std::decay_t<Tuple>>::value >; return apply_impl(std::forward<F>(f), std::forward<Tuple>(t), Indices()); } template<typename Tuple> struct run_counter_from_tuple_t; template<typename ...T> struct run_counter_from_tuple_t<std::tuple<T...>> { using type = run_counter<T &...>; }; template<typename Tuple> using run_counter_from_tuple = typename run_counter_from_tuple_t<Tuple>::type; using namespace mettle::detail; suite<std::tuple<>, std::tuple<int, int>> test_test_caller("test_caller", [](auto &_) { using Fixture = fixture_type_t<decltype(_)>; _.test("test with no fixture", [](auto &tup) { run_counter_from_tuple<Fixture> setup, teardown, test; test_caller<auto_factory_t, Fixture> t( auto_factory, setup, teardown, test ); apply(t, tup); expect("setup run count", setup.runs(), equal_to(1)); expect("test run count", test.runs(), equal_to(1)); expect("teardown run count", teardown.runs(), equal_to(1)); }); // XXX: Enable this test on MSVC (it triggers an ICE somewhere). #if !defined(_MSC_VER) || defined(__clang__) _.test("test with auto fixture", [](auto &tup) { run_counter_from_tuple<decltype( std::tuple_cat(tup, std::tuple<int>()) )> setup, teardown, test; test_caller<auto_factory_t, Fixture, int> t( auto_factory, setup, teardown, test ); apply(t, tup); expect("setup run count", setup.runs(), equal_to(1)); expect("test run count", test.runs(), equal_to(1)); expect("teardown run count", teardown.runs(), equal_to(1)); }); #endif _.test("test with type-only fixture", [](auto &tup) { run_counter_from_tuple<Fixture> setup, teardown, test; test_caller<type_only_factory_t, Fixture, int> t( type_only, setup, teardown, test ); apply(t, tup); expect("setup run count", setup.runs(), equal_to(1)); expect("test run count", test.runs(), equal_to(1)); expect("teardown run count", teardown.runs(), equal_to(1)); }); }); <commit_msg>Enable test_caller tests on MSVC<commit_after>#include <mettle.hpp> using namespace mettle; #include "run_counter.hpp" template<typename F, typename Tuple, std::size_t ...I> decltype(auto) apply_impl(F &&f, Tuple &&t, std::index_sequence<I...>) { return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...); } template<typename F, typename Tuple> decltype(auto) apply(F&& f, Tuple &&t) { using Indices = std::make_index_sequence< std::tuple_size<std::decay_t<Tuple>>::value >; return apply_impl(std::forward<F>(f), std::forward<Tuple>(t), Indices()); } template<typename Tuple> struct run_counter_from_tuple_t; template<typename ...T> struct run_counter_from_tuple_t<std::tuple<T...>> { using type = run_counter<T &...>; }; template<typename Tuple> using run_counter_from_tuple = typename run_counter_from_tuple_t<Tuple>::type; using namespace mettle::detail; suite<std::tuple<>, std::tuple<int, int>> test_test_caller("test_caller", [](auto &_) { using Fixture = fixture_type_t<decltype(_)>; _.test("test with no fixture", [](auto &tup) { run_counter_from_tuple<Fixture> setup, teardown, test; test_caller<auto_factory_t, Fixture> t( auto_factory, setup, teardown, test ); apply(t, tup); expect("setup run count", setup.runs(), equal_to(1)); expect("test run count", test.runs(), equal_to(1)); expect("teardown run count", teardown.runs(), equal_to(1)); }); _.test("test with auto fixture", [](auto &tup) { run_counter_from_tuple<decltype( std::tuple_cat(tup, std::tuple<int>()) )> setup, teardown, test; test_caller<auto_factory_t, Fixture, int> t( auto_factory, setup, teardown, test ); apply(t, tup); expect("setup run count", setup.runs(), equal_to(1)); expect("test run count", test.runs(), equal_to(1)); expect("teardown run count", teardown.runs(), equal_to(1)); }); _.test("test with type-only fixture", [](auto &tup) { run_counter_from_tuple<Fixture> setup, teardown, test; test_caller<type_only_factory_t, Fixture, int> t( type_only, setup, teardown, test ); apply(t, tup); expect("setup run count", setup.runs(), equal_to(1)); expect("test run count", test.runs(), equal_to(1)); expect("teardown run count", teardown.runs(), equal_to(1)); }); }); <|endoftext|>
<commit_before>#include "bs_mesh_stdafx.h" #include "py_rs_mesh.h" #include "bs_mesh_grdecl.h" #include "export_python_wrapper.h" #include "py_pair_converter.h" #include <boost/python/tuple.hpp> #ifdef BSPY_EXPORTING_PLUGIN using namespace boost::python; namespace blue_sky { namespace python { void init_props1(bs_mesh_grdecl& m, t_long nx, t_long ny, t_long nz, spv_float dx, spv_float dy, spv_float dz) { m.init_props(nx, ny, nz, dx, dy, dz); } void init_props2(bs_mesh_grdecl& m, t_long nx, t_long ny, spv_float coord, spv_float zcorn) { m.init_props(nx, ny, coord, zcorn); } PY_EXPORTER (mesh_grdecl_exporter, rs_mesh_iface_exporter) .def ("get_ext_to_int", &T::get_ext_to_int, args(""), "Return reference to external-to-internal mesh index") .def ("get_int_to_ext", &T::get_int_to_ext, args(""), "Return reference to internal-to-external mesh index") .def ("get_volumes", &T::get_volumes, args(""), "Return reference to volumes vector") .def ("get_dimensions_range", &T::get_dimensions_range, args("dim1_max, dim1_min, dim2_max, dim2_min, dim3_max, dim3_min"), "Get dimensions ranges") .def ("get_element_size", &T::get_element_size, args ("n_elem, dx, dy, dz"), "get elements sizes") .def ("get_element_dz", &T::get_element_dim3_size, args ("n_elem"), "get elements dz by internal index") .def ("get_element_dz_ext", &T::get_element_dim3_size_ext, args ("i, j, k"), "get elements dz by external index") .def ("get_element_ijk_to_int", &T::get_element_ijk_to_int, args ("i, j, k"), "get elements sizes") .def ("get_n_active_elements", &T::get_n_active_elements, args (""), "Get elements sizes") .def ("calc_element_tops", &T::calc_element_tops, args (""), "Calc element tops") .def ("calc_element_center", &T::calc_element_center, args (""), "Calc element center") .def ("calc_cells_vertices", &T::calc_cells_vertices) .def ("init_props", &init_props1) .def ("init_props", &init_props2) .def ("get_element_sizes", &T::get_element_sizes) ; PY_EXPORTER_END; }} // eof blue_sky::python namespace { using namespace blue_sky; using namespace blue_sky::python; // same as grdecl exporter, but also export gen_coord_zcorn template <typename T> struct mesh_grdecl_exporter_plus { typedef t_long int_t; typedef t_double fp_t; typedef spv_float spfp_storarr_t; typedef spv_long spi_arr_t; typedef typename spi_arr_t::pure_pointed_t int_arr_t; typedef std::pair< spv_float, spv_float > coord_zcorn_pair; // gen_coord_zcorn overloads static coord_zcorn_pair gen_coord_zcorn1(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz, fp_t x0, fp_t y0) { return T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz, x0, y0); } static coord_zcorn_pair gen_coord_zcorn2(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz, fp_t x0) { return T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz, x0); } static coord_zcorn_pair gen_coord_zcorn3(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz) { return T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz); } // refine_mesh_deltas with overloads static tuple refine_mesh_deltas(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points, fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD) { spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type()); std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh_deltas(nx, ny, coord, points, hit_idx, m_thresh, b_thresh); return make_tuple(r.first, r.second, nx, ny, hit_idx); } static tuple refine_mesh_deltas1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points) { return refine_mesh_deltas(nx, ny, coord, points); } static tuple refine_mesh_deltas2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points, fp_t m_thresh) { return refine_mesh_deltas(nx, ny, coord, points, m_thresh); } // refine_mesh with overloads static tuple refine_mesh(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points, fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD) { spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type()); std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh(nx, ny, coord, zcorn, points, hit_idx, m_thresh, b_thresh); return make_tuple(r.first, r.second, nx, ny, hit_idx); } static tuple refine_mesh1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points) { return refine_mesh(nx, ny, coord, zcorn, points); } static tuple refine_mesh2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points, fp_t m_thresh) { return refine_mesh(nx, ny, coord, zcorn, points, m_thresh); } // refine_mesh_deltas with overloads // (i,j) points format static tuple refine_mesh_deltas_ij(int_t nx, int_t ny, spfp_storarr_t coord, spi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD) { spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type()); std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh_deltas(nx, ny, coord, points_pos, points_param, hit_idx, m_thresh, b_thresh); return make_tuple(r.first, r.second, nx, ny, hit_idx); } static tuple refine_mesh_deltas_ij1(int_t nx, int_t ny, spfp_storarr_t coord, spi_arr_t points_pos, spfp_storarr_t points_param) { return refine_mesh_deltas_ij(nx, ny, coord, points_pos, points_param); } static tuple refine_mesh_deltas_ij2(int_t nx, int_t ny, spfp_storarr_t coord, spi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh) { return refine_mesh_deltas_ij(nx, ny, coord, points_pos, points_param, m_thresh); } // refine_mesh with overloads // (i, j) points format static tuple refine_mesh_ij(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD) { spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type()); std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh(nx, ny, coord, zcorn, points_pos, points_param, hit_idx, m_thresh, b_thresh); return make_tuple(r.first, r.second, nx, ny, hit_idx); } static tuple refine_mesh_ij1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spi_arr_t points_pos, spfp_storarr_t points_param) { return refine_mesh_ij(nx, ny, coord, zcorn, points_pos, points_param); } static tuple refine_mesh_ij2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh) { return refine_mesh_ij(nx, ny, coord, zcorn, points_pos, points_param, m_thresh); } template <typename class_t> static class_t & export_class (class_t &class__) { using namespace boost::python; mesh_grdecl_exporter<T>::export_class (class__) .def("gen_coord_zcorn", &T::gen_coord_zcorn, "Generate COORD & ZCORN from given dimensions") .def("gen_coord_zcorn", &gen_coord_zcorn1, "Generate COORD & ZCORN from given dimensions") .def("gen_coord_zcorn", &gen_coord_zcorn2, "Generate COORD & ZCORN from given dimensions") .def("gen_coord_zcorn", &gen_coord_zcorn3, "Generate COORD & ZCORN from given dimensions") .staticmethod("gen_coord_zcorn") .def("refine_mesh_deltas", &refine_mesh_deltas, "Calc dx and dy arrays for refined mesh in given points") .def("refine_mesh_deltas", &refine_mesh_deltas1, "Calc dx and dy arrays for refined mesh in given points") .def("refine_mesh_deltas", &refine_mesh_deltas2, "Calc dx and dy arrays for refined mesh in given points") .def("refine_mesh_deltas", &refine_mesh_deltas_ij, "Calc dx and dy arrays for refined mesh in given points") .def("refine_mesh_deltas", &refine_mesh_deltas_ij1, "Calc dx and dy arrays for refined mesh in given points") .def("refine_mesh_deltas", &refine_mesh_deltas_ij2, "Calc dx and dy arrays for refined mesh in given points") .staticmethod("refine_mesh_deltas") .def("refine_mesh", &refine_mesh, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh1, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh2, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh_ij, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh_ij1, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh_ij2, "Refine existing mesh in given points") .staticmethod("refine_mesh") ; return class__; } }; template< class fp_type > void reg_sparray_pair() { // register converter from pair of returned arrayes to python list typedef std::pair< spv_float, spv_float > array_pair; typedef bspy_converter< pair_traits< array_pair > > array_pair_converter; array_pair_converter::register_to_py(); array_pair_converter::register_from_py(); } } // eof hidden namespace namespace blue_sky { namespace python { void py_export_mesh_grdecl () { class_exporter< bs_mesh_grdecl, rs_mesh_iface, mesh_grdecl_exporter_plus >::export_class ("mesh_grdecl"); //reg_sparray_pair< float >(); reg_sparray_pair< double >(); } }} // namespace blue_sky::python #endif <commit_msg>added vertices_xyz py-export<commit_after>#include "bs_mesh_stdafx.h" #include "py_rs_mesh.h" #include "bs_mesh_grdecl.h" #include "export_python_wrapper.h" #include "py_pair_converter.h" #include <boost/python/tuple.hpp> #ifdef BSPY_EXPORTING_PLUGIN using namespace boost::python; namespace blue_sky { namespace python { void init_props1(bs_mesh_grdecl& m, t_long nx, t_long ny, t_long nz, spv_float dx, spv_float dy, spv_float dz) { m.init_props(nx, ny, nz, dx, dy, dz); } void init_props2(bs_mesh_grdecl& m, t_long nx, t_long ny, spv_float coord, spv_float zcorn) { m.init_props(nx, ny, coord, zcorn); } PY_EXPORTER (mesh_grdecl_exporter, rs_mesh_iface_exporter) .def ("get_ext_to_int", &T::get_ext_to_int, args(""), "Return reference to external-to-internal mesh index") .def ("get_int_to_ext", &T::get_int_to_ext, args(""), "Return reference to internal-to-external mesh index") .def ("get_volumes", &T::get_volumes, args(""), "Return reference to volumes vector") .def ("get_dimensions_range", &T::get_dimensions_range, args("dim1_max, dim1_min, dim2_max, dim2_min, dim3_max, dim3_min"), "Get dimensions ranges") .def ("get_element_size", &T::get_element_size, args ("n_elem, dx, dy, dz"), "get elements sizes") .def ("get_element_dz", &T::get_element_dim3_size, args ("n_elem"), "get elements dz by internal index") .def ("get_element_dz_ext", &T::get_element_dim3_size_ext, args ("i, j, k"), "get elements dz by external index") .def ("get_element_ijk_to_int", &T::get_element_ijk_to_int, args ("i, j, k"), "get elements sizes") .def ("get_n_active_elements", &T::get_n_active_elements, args (""), "Get elements sizes") .def ("calc_element_tops", &T::calc_element_tops, args (""), "Calc element tops") .def ("calc_element_center", &T::calc_element_center, args (""), "Calc element center") .def ("calc_cells_vertices", &T::calc_cells_vertices) .def ("calc_cells_vertices_xyz", &T::calc_cells_vertices_xyz) .def ("init_props", &init_props1) .def ("init_props", &init_props2) .def ("get_element_sizes", &T::get_element_sizes) ; PY_EXPORTER_END; }} // eof blue_sky::python namespace { using namespace blue_sky; using namespace blue_sky::python; // same as grdecl exporter, but also export gen_coord_zcorn template <typename T> struct mesh_grdecl_exporter_plus { typedef t_long int_t; typedef t_double fp_t; typedef spv_float spfp_storarr_t; typedef spv_long spi_arr_t; typedef typename spi_arr_t::pure_pointed_t int_arr_t; typedef std::pair< spv_float, spv_float > coord_zcorn_pair; // gen_coord_zcorn overloads static coord_zcorn_pair gen_coord_zcorn1(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz, fp_t x0, fp_t y0) { return T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz, x0, y0); } static coord_zcorn_pair gen_coord_zcorn2(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz, fp_t x0) { return T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz, x0); } static coord_zcorn_pair gen_coord_zcorn3(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz) { return T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz); } // refine_mesh_deltas with overloads static tuple refine_mesh_deltas(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points, fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD) { spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type()); std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh_deltas(nx, ny, coord, points, hit_idx, m_thresh, b_thresh); return make_tuple(r.first, r.second, nx, ny, hit_idx); } static tuple refine_mesh_deltas1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points) { return refine_mesh_deltas(nx, ny, coord, points); } static tuple refine_mesh_deltas2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points, fp_t m_thresh) { return refine_mesh_deltas(nx, ny, coord, points, m_thresh); } // refine_mesh with overloads static tuple refine_mesh(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points, fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD) { spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type()); std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh(nx, ny, coord, zcorn, points, hit_idx, m_thresh, b_thresh); return make_tuple(r.first, r.second, nx, ny, hit_idx); } static tuple refine_mesh1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points) { return refine_mesh(nx, ny, coord, zcorn, points); } static tuple refine_mesh2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points, fp_t m_thresh) { return refine_mesh(nx, ny, coord, zcorn, points, m_thresh); } // refine_mesh_deltas with overloads // (i,j) points format static tuple refine_mesh_deltas_ij(int_t nx, int_t ny, spfp_storarr_t coord, spi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD) { spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type()); std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh_deltas(nx, ny, coord, points_pos, points_param, hit_idx, m_thresh, b_thresh); return make_tuple(r.first, r.second, nx, ny, hit_idx); } static tuple refine_mesh_deltas_ij1(int_t nx, int_t ny, spfp_storarr_t coord, spi_arr_t points_pos, spfp_storarr_t points_param) { return refine_mesh_deltas_ij(nx, ny, coord, points_pos, points_param); } static tuple refine_mesh_deltas_ij2(int_t nx, int_t ny, spfp_storarr_t coord, spi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh) { return refine_mesh_deltas_ij(nx, ny, coord, points_pos, points_param, m_thresh); } // refine_mesh with overloads // (i, j) points format static tuple refine_mesh_ij(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD) { spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type()); std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh(nx, ny, coord, zcorn, points_pos, points_param, hit_idx, m_thresh, b_thresh); return make_tuple(r.first, r.second, nx, ny, hit_idx); } static tuple refine_mesh_ij1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spi_arr_t points_pos, spfp_storarr_t points_param) { return refine_mesh_ij(nx, ny, coord, zcorn, points_pos, points_param); } static tuple refine_mesh_ij2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh) { return refine_mesh_ij(nx, ny, coord, zcorn, points_pos, points_param, m_thresh); } template <typename class_t> static class_t & export_class (class_t &class__) { using namespace boost::python; mesh_grdecl_exporter<T>::export_class (class__) .def("gen_coord_zcorn", &T::gen_coord_zcorn, "Generate COORD & ZCORN from given dimensions") .def("gen_coord_zcorn", &gen_coord_zcorn1, "Generate COORD & ZCORN from given dimensions") .def("gen_coord_zcorn", &gen_coord_zcorn2, "Generate COORD & ZCORN from given dimensions") .def("gen_coord_zcorn", &gen_coord_zcorn3, "Generate COORD & ZCORN from given dimensions") .staticmethod("gen_coord_zcorn") .def("refine_mesh_deltas", &refine_mesh_deltas, "Calc dx and dy arrays for refined mesh in given points") .def("refine_mesh_deltas", &refine_mesh_deltas1, "Calc dx and dy arrays for refined mesh in given points") .def("refine_mesh_deltas", &refine_mesh_deltas2, "Calc dx and dy arrays for refined mesh in given points") .def("refine_mesh_deltas", &refine_mesh_deltas_ij, "Calc dx and dy arrays for refined mesh in given points") .def("refine_mesh_deltas", &refine_mesh_deltas_ij1, "Calc dx and dy arrays for refined mesh in given points") .def("refine_mesh_deltas", &refine_mesh_deltas_ij2, "Calc dx and dy arrays for refined mesh in given points") .staticmethod("refine_mesh_deltas") .def("refine_mesh", &refine_mesh, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh1, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh2, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh_ij, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh_ij1, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh_ij2, "Refine existing mesh in given points") .staticmethod("refine_mesh") ; return class__; } }; template< class fp_type > void reg_sparray_pair() { // register converter from pair of returned arrayes to python list typedef std::pair< spv_float, spv_float > array_pair; typedef bspy_converter< pair_traits< array_pair > > array_pair_converter; array_pair_converter::register_to_py(); array_pair_converter::register_from_py(); } } // eof hidden namespace namespace blue_sky { namespace python { void py_export_mesh_grdecl () { class_exporter< bs_mesh_grdecl, rs_mesh_iface, mesh_grdecl_exporter_plus >::export_class ("mesh_grdecl"); //reg_sparray_pair< float >(); reg_sparray_pair< double >(); } }} // namespace blue_sky::python #endif <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkDummyImageToListAdaptorTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information. =========================================================================*/ #include <time.h> #include "itkFixedArray.h" #include "itkImage.h" #include "itkImageAdaptor.h" #include "itkImageRegionIterator.h" #include "itkPixelTraits.h" #include "itkListSampleBase.h" #include "itkImageToListAdaptor.h" #include "itkScalarToArrayCastImageFilter.h" #include "itkImage.h" #include "itkObject.h" #include "itkMacro.h" #include "itkPixelTraits.h" template<class TPixelType> struct MeasurementVectorTraits { typedef TPixelType VectorType; }; /** Specialization of MeasurementVectorTraitss for scalar images. */ template <> struct MeasurementVectorTraits<bool> { typedef itk::FixedArray< bool, 1 > VectorType; }; template <> struct MeasurementVectorTraits<char> { typedef itk::FixedArray< char, 1 > VectorType; }; template <> struct MeasurementVectorTraits<unsigned char> { typedef itk::FixedArray< unsigned char, 1 > VectorType; }; template <> struct MeasurementVectorTraits<short> { typedef itk::FixedArray< short, 1 > VectorType; }; template <> struct MeasurementVectorTraits<unsigned short> { typedef itk::FixedArray< unsigned short, 1 > VectorType; }; template <> struct MeasurementVectorTraits<int> { typedef itk::FixedArray< int, 1 > VectorType; }; template <> struct MeasurementVectorTraits<unsigned int> { typedef itk::FixedArray< unsigned int, 1 > VectorType; }; template <> struct MeasurementVectorTraits<long> { typedef itk::FixedArray< long, 1 > VectorType; }; template <> struct MeasurementVectorTraits<unsigned long> { typedef itk::FixedArray< unsigned long, 1 > VectorType; }; template <> struct MeasurementVectorTraits<float> { typedef itk::FixedArray< float, 1 > VectorType; }; template <> struct MeasurementVectorTraits<double> { typedef itk::FixedArray< double, 1 > VectorType; }; template < class TImage, class TMeasurementVector = ITK_TYPENAME TImage::PixelType > class ITK_EXPORT DummyImageToListAdaptor : public itk::Statistics::ListSampleBase< TMeasurementVector > { public: typedef DummyImageToListAdaptor Self ; typedef itk::Statistics::ListSampleBase< TMeasurementVector > Superclass ; typedef itk::SmartPointer< Self > Pointer ; typedef itk::SmartPointer< const Self > ConstPointer ; itkTypeMacro( DummyImageToListAdaptor, Object ) ; itkNewMacro( Self ) ; typedef typename TImage::PixelType PixelType ; typedef typename itk::PixelTraits< PixelType >::ValueType MeasurementType ; itkStaticConstMacro( MeasurementVectorSize, unsigned int, itk::PixelTraits< PixelType >::Dimension ) ; typedef TMeasurementVector MeasurementVectorType ; unsigned int Size() const { return 1 ;} float GetTotalFrequency() const { return 1 ;} float GetFrequency(const unsigned long& id) const { return 1.0f ; } virtual MeasurementVectorType GetMeasurementVector(const unsigned long& id) { if( m_UseBuffer ) { return *(reinterpret_cast< MeasurementVectorType* > (&(*m_ImageBuffer)[id])) ; } else { return *(reinterpret_cast< MeasurementVectorType* > (&(m_Image->GetPixel( m_Image->ComputeIndex( id ))) ) ) ; } } void SetImage( TImage* image ) { m_Image = image ; m_ImageBuffer = m_Image->GetPixelContainer() ; if ( strcmp( m_Image->GetNameOfClass(), "Image" ) != 0 ) { m_UseBuffer = false ; } else { m_UseBuffer = true ; } } protected: DummyImageToListAdaptor() { m_Image = 0 ; } virtual ~DummyImageToListAdaptor() {} typename TImage::Pointer m_Image ; typename TImage::PixelContainer* m_ImageBuffer ; MeasurementVectorType m_TempVector ; bool m_UseBuffer ; private: DummyImageToListAdaptor(const Self&) ; void operator=(const Self&) ; } ; template < class TImage > class ITK_EXPORT DummyScalarImageToListAdaptor : public DummyImageToListAdaptor< TImage, itk::FixedArray< typename TImage::PixelType, 1> > { public: typedef DummyScalarImageToListAdaptor Self ; typedef DummyImageToListAdaptor< TImage, itk::FixedArray< typename TImage::PixelType, 1> > Superclass ; typedef itk::SmartPointer< Self > Pointer ; typedef itk::SmartPointer< const Self > ConstPointer ; itkTypeMacro( DummyScalarImageToListAdaptor, DummyImageToListAdaptor ) ; itkNewMacro( Self ) ; typedef typename Superclass::MeasurementVectorType MeasurementVectorType ; MeasurementVectorType GetMeasurementVector(const unsigned long& id) { if( m_UseBuffer ) { m_TempVector[0] = (*m_ImageBuffer)[id] ; } else { m_TempVector[0] = m_Image->GetPixel( m_Image->ComputeIndex( id ) ) ; } return m_TempVector ; } protected: DummyScalarImageToListAdaptor() {} virtual ~DummyScalarImageToListAdaptor() {} } ; // end of class template< class TImage, class TCoordRep > struct ImageJointDomainTraits { typedef itk::PixelTraits< typename TImage::PixelType > PixelTraitsType ; itkStaticConstMacro(Size, unsigned int, TImage::ImageDimension + PixelTraitsType::Dimension ) ; typedef itk::JoinTraits< TCoordRep, PixelTraitsType::ValueType > JoinTraitsType ; typedef JoinTraitsType::ValueType MeasurementType ; typedef itk::FixedArray< MeasurementType, itkGetStaticConstMacro(Size) > MeasurementVectorType ; } ; // end of ImageJointDomainTraits template < class TImage, class TCoordRep > class ITK_EXPORT DummyJointDomainImageToListAdaptor : public DummyImageToListAdaptor< TImage, ImageJointDomainTraits< TImage, TCoordRep >::MeasurementVectorType > { public: typedef DummyJointDomainImageToListAdaptor Self ; typedef DummyImageToListAdaptor< TImage, ImageJointDomainTraits< TImage, TCoordRep >::MeasurementVectorType > Superclass ; typedef itk::SmartPointer< Self > Pointer ; typedef itk::SmartPointer< const Self > ConstPointer ; itkTypeMacro( DummyJointDomainImageToListAdaptor, DummyImageToListAdaptor ) ; itkNewMacro( Self ) ; typedef typename Superclass::MeasurementType MeasurementType ; typedef typename Superclass::MeasurementVectorType MeasurementVectorType ; typedef itk::FixedArray< MeasurementType, itk::PixelTraits< typename TImage::PixelType >::Dimension > RangeDomainMeasurementVectorType ; MeasurementVectorType GetMeasurementVector(const unsigned long& id) { typename itk::Point<MeasurementType, TImage::ImageDimension> point ; typename TImage::IndexType index = m_Image->ComputeIndex( id ) ; m_Image->TransformIndexToPhysicalPoint( index, point ) ; for ( unsigned int i = 0 ; i < TImage::ImageDimension ; ++i ) { m_TempVector[i] = point[i] ; } if( m_UseBuffer ) { m_TempVector2 = *(reinterpret_cast< RangeDomainMeasurementVectorType* > (&(*m_ImageBuffer)[id])) ; } else { m_TempVector2 = *(reinterpret_cast< RangeDomainMeasurementVectorType* > (&(m_Image->GetPixel( m_Image->ComputeIndex( id ) ) ) ) ) ; } for ( unsigned int i = TImage::ImageDimension ; i < MeasurementVectorType::Length ; ++i ) { m_TempVector[i]= m_TempVector2[i - TImage::ImageDimension] ; } return m_TempVector ; } protected: DummyJointDomainImageToListAdaptor() {} virtual ~DummyJointDomainImageToListAdaptor() {} RangeDomainMeasurementVectorType m_TempVector2 ; } ; // end of class int itkDummyImageToListAdaptorTest(int, char* [] ) { typedef int ScalarPixelType ; typedef itk::FixedArray< ScalarPixelType, 1 > ArrayPixelType ; typedef itk::Vector< ScalarPixelType, 2 > VectorPixelType ; typedef itk::Image< ScalarPixelType, 3 > ScalarImageType ; typedef itk::Image< ArrayPixelType, 3 > ArrayImageType ; typedef itk::Image< VectorPixelType, 3 > VectorImageType ; typedef itk::ImageRegionIterator< ScalarImageType > ScalarImageIteratorType ; typedef itk::ImageRegionIterator< ArrayImageType > ArrayImageIteratorType ; typedef itk::ImageRegionIterator< VectorImageType > VectorImageIteratorType ; itk::Size< 3 > size ; size.Fill(10) ; ScalarImageType::Pointer scalarImage = ScalarImageType::New() ; scalarImage->SetRegions(size) ; scalarImage->Allocate() ; int count = 0 ; ScalarImageIteratorType s_iter = ScalarImageIteratorType(scalarImage, scalarImage->GetLargestPossibleRegion() ) ; while ( !s_iter.IsAtEnd() ) { s_iter.Set(count) ; ++count ; ++s_iter ; } VectorImageType::Pointer vectorImage = VectorImageType::New() ; vectorImage->SetRegions(size) ; vectorImage->Allocate() ; count = 0 ; VectorImageType::PixelType vPixel ; VectorImageIteratorType v_iter = VectorImageIteratorType(vectorImage, vectorImage->GetLargestPossibleRegion()) ; while ( !v_iter.IsAtEnd() ) { vPixel[0] = count ; vPixel[1] = count ; v_iter.Set( vPixel ) ; ++count ; ++v_iter ; } typedef DummyScalarImageToListAdaptor< ScalarImageType > ScalarListType ; ScalarListType::Pointer sList = ScalarListType::New() ; sList->SetImage( scalarImage ) ; typedef DummyImageToListAdaptor< VectorImageType > VectorListType ; VectorListType::Pointer vList = VectorListType::New() ; vList->SetImage( vectorImage ) ; typedef itk::ScalarToArrayCastImageFilter< ScalarImageType, ArrayImageType > CasterType ; CasterType::Pointer caster = CasterType::New() ; caster->SetInput( scalarImage ) ; caster->Update() ; typedef itk::Statistics::ImageToListAdaptor< ArrayImageType > ImageListType ; ImageListType::Pointer imageList = ImageListType::New() ; imageList->SetImage( caster->GetOutput() ) ; typedef DummyJointDomainImageToListAdaptor< VectorImageType, float > JointDomainImageListType ; JointDomainImageListType::Pointer jointDomainImageList = JointDomainImageListType::New() ; jointDomainImageList->SetImage( vectorImage ) ; std::cout << "Testing the each measurement values:" << std::endl ; for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i ) { if ( sList->GetMeasurementVector( i )[0] != vList->GetMeasurementVector( i )[0] || sList->GetMeasurementVector( i )[0] != imageList->GetMeasurementVector( i )[0] || sList->GetMeasurementVector( i )[0] != jointDomainImageList->GetMeasurementVector( i )[3] ) { std::cout << "ERROR: measurement mismatch!!!" << std::endl ; return EXIT_FAILURE ; } } std::cout << std::endl ; std::cout << "Scalar image (casted) pixel access performance test:" << std::endl ; time_t begin = clock() ; for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i ) { imageList->GetMeasurementVector( i ) ; } time_t end = clock() ; std::cout << "time: " << (double(end - begin) /CLOCKS_PER_SEC) << " seconds" << std::endl ; std::cout << "Scalar image pixel access performance test:" << std::endl ; begin = clock() ; for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i ) { sList->GetMeasurementVector( i ) ; } end = clock() ; std::cout << "time: " << (double(end - begin) /CLOCKS_PER_SEC) << " seconds" << std::endl ; std::cout << "Vector image pixel access performance test:" << std::endl ; begin = clock() ; for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i ) { vList->GetMeasurementVector( i ) ; } end = clock() ; std::cout << "time: " << (double(end - begin) /CLOCKS_PER_SEC) << " seconds" << std::endl ; std::cout << "Joint Domain Vector image pixel access performance test:" << std::endl ; begin = clock() ; for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i ) { std::cout << jointDomainImageList->GetMeasurementVector( i ) << std::endl ; } end = clock() ; std::cout << "time: " << (double(end - begin) /CLOCKS_PER_SEC) << " seconds" << std::endl ; return EXIT_SUCCESS ; } <commit_msg>BUG: BCC complains about the Size enum. to use itkGetStaticConstMacro, each class should have Self declared.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkDummyImageToListAdaptorTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information. =========================================================================*/ #include <time.h> #include "itkFixedArray.h" #include "itkImage.h" #include "itkImageAdaptor.h" #include "itkImageRegionIterator.h" #include "itkPixelTraits.h" #include "itkListSampleBase.h" #include "itkImageToListAdaptor.h" #include "itkScalarToArrayCastImageFilter.h" #include "itkImage.h" #include "itkObject.h" #include "itkMacro.h" #include "itkPixelTraits.h" template < class TImage, class TMeasurementVector = ITK_TYPENAME TImage::PixelType > class ITK_EXPORT DummyImageToListAdaptor : public itk::Statistics::ListSampleBase< TMeasurementVector > { public: typedef DummyImageToListAdaptor Self ; typedef itk::Statistics::ListSampleBase< TMeasurementVector > Superclass ; typedef itk::SmartPointer< Self > Pointer ; typedef itk::SmartPointer< const Self > ConstPointer ; itkTypeMacro( DummyImageToListAdaptor, Object ) ; itkNewMacro( Self ) ; typedef typename TImage::PixelType PixelType ; typedef typename itk::PixelTraits< PixelType >::ValueType MeasurementType ; itkStaticConstMacro( MeasurementVectorSize, unsigned int, itk::PixelTraits< PixelType >::Dimension ) ; typedef TMeasurementVector MeasurementVectorType ; unsigned int Size() const { return 1 ;} float GetTotalFrequency() const { return 1 ;} float GetFrequency(const unsigned long& id) const { return id ; } virtual MeasurementVectorType GetMeasurementVector(const unsigned long& id) { if( m_UseBuffer ) { return *(reinterpret_cast< MeasurementVectorType* > (&(*m_ImageBuffer)[id])) ; } else { return *(reinterpret_cast< MeasurementVectorType* > (&(m_Image->GetPixel( m_Image->ComputeIndex( id ))) ) ) ; } } void SetImage( TImage* image ) { m_Image = image ; m_ImageBuffer = m_Image->GetPixelContainer() ; if ( strcmp( m_Image->GetNameOfClass(), "Image" ) != 0 ) { m_UseBuffer = false ; } else { m_UseBuffer = true ; } } protected: DummyImageToListAdaptor() { m_Image = 0 ; } virtual ~DummyImageToListAdaptor() {} typename TImage::Pointer m_Image ; typename TImage::PixelContainer* m_ImageBuffer ; MeasurementVectorType m_TempVector ; bool m_UseBuffer ; private: DummyImageToListAdaptor(const Self&) ; void operator=(const Self&) ; } ; template < class TImage > class ITK_EXPORT DummyScalarImageToListAdaptor : public DummyImageToListAdaptor< TImage, itk::FixedArray< typename TImage::PixelType, 1> > { public: typedef DummyScalarImageToListAdaptor Self ; typedef DummyImageToListAdaptor< TImage, itk::FixedArray< typename TImage::PixelType, 1> > Superclass ; typedef itk::SmartPointer< Self > Pointer ; typedef itk::SmartPointer< const Self > ConstPointer ; itkTypeMacro( DummyScalarImageToListAdaptor, DummyImageToListAdaptor ) ; itkNewMacro( Self ) ; typedef typename Superclass::MeasurementVectorType MeasurementVectorType ; MeasurementVectorType GetMeasurementVector(const unsigned long& id) { if( m_UseBuffer ) { m_TempVector[0] = (*m_ImageBuffer)[id] ; } else { m_TempVector[0] = m_Image->GetPixel( m_Image->ComputeIndex( id ) ) ; } return m_TempVector ; } protected: DummyScalarImageToListAdaptor() {} virtual ~DummyScalarImageToListAdaptor() {} } ; // end of class template< class TImage, class TCoordRep > struct ImageJointDomainTraits { typedef ImageJointDomainTraits Self ; typedef itk::PixelTraits< typename TImage::PixelType > PixelTraitsType ; itkStaticConstMacro(Size, unsigned int, TImage::ImageDimension + PixelTraitsType::Dimension ) ; typedef itk::JoinTraits< TCoordRep, PixelTraitsType::ValueType > JoinTraitsType ; typedef JoinTraitsType::ValueType MeasurementType ; typedef itk::FixedArray< MeasurementType, itkGetStaticConstMacro(Size) > MeasurementVectorType ; } ; // end of ImageJointDomainTraits template < class TImage, class TCoordRep > class ITK_EXPORT DummyJointDomainImageToListAdaptor : public DummyImageToListAdaptor< TImage, ImageJointDomainTraits< TImage, TCoordRep >::MeasurementVectorType > { public: typedef DummyJointDomainImageToListAdaptor Self ; typedef DummyImageToListAdaptor< TImage, ImageJointDomainTraits< TImage, TCoordRep >::MeasurementVectorType > Superclass ; typedef itk::SmartPointer< Self > Pointer ; typedef itk::SmartPointer< const Self > ConstPointer ; itkTypeMacro( DummyJointDomainImageToListAdaptor, DummyImageToListAdaptor ) ; itkNewMacro( Self ) ; typedef typename Superclass::MeasurementType MeasurementType ; typedef typename Superclass::MeasurementVectorType MeasurementVectorType ; itkStaticConstMacro(RangeDomainDimension, unsigned int, itk::PixelTraits< typename TImage::PixelType >::Dimension) ; typedef typename itk::FixedArray< MeasurementType, itkGetStaticConstMacro( RangeDomainDimension ) > RangeDomainMeasurementVectorType ; MeasurementVectorType GetMeasurementVector(const unsigned long& id) { typename itk::Point<MeasurementType, TImage::ImageDimension> point ; typename TImage::IndexType index = m_Image->ComputeIndex( id ) ; m_Image->TransformIndexToPhysicalPoint( index, point ) ; for ( unsigned int i = 0 ; i < TImage::ImageDimension ; ++i ) { m_TempVector[i] = point[i] ; } if( m_UseBuffer ) { m_TempVector2 = *(reinterpret_cast< RangeDomainMeasurementVectorType* > (&(*m_ImageBuffer)[id])) ; } else { m_TempVector2 = *(reinterpret_cast< RangeDomainMeasurementVectorType* > (&(m_Image->GetPixel( m_Image->ComputeIndex( id ) ) ) ) ) ; } for ( unsigned int i = TImage::ImageDimension ; i < MeasurementVectorType::Length ; ++i ) { m_TempVector[i]= m_TempVector2[i - TImage::ImageDimension] ; } return m_TempVector ; } protected: DummyJointDomainImageToListAdaptor() {} virtual ~DummyJointDomainImageToListAdaptor() {} RangeDomainMeasurementVectorType m_TempVector2 ; } ; // end of class int itkDummyImageToListAdaptorTest(int, char* [] ) { typedef int ScalarPixelType ; typedef itk::FixedArray< ScalarPixelType, 1 > ArrayPixelType ; typedef itk::Vector< ScalarPixelType, 2 > VectorPixelType ; typedef itk::Image< ScalarPixelType, 3 > ScalarImageType ; typedef itk::Image< ArrayPixelType, 3 > ArrayImageType ; typedef itk::Image< VectorPixelType, 3 > VectorImageType ; typedef itk::ImageRegionIterator< ScalarImageType > ScalarImageIteratorType ; typedef itk::ImageRegionIterator< ArrayImageType > ArrayImageIteratorType ; typedef itk::ImageRegionIterator< VectorImageType > VectorImageIteratorType ; itk::Size< 3 > size ; size.Fill(10) ; ScalarImageType::Pointer scalarImage = ScalarImageType::New() ; scalarImage->SetRegions(size) ; scalarImage->Allocate() ; int count = 0 ; ScalarImageIteratorType s_iter = ScalarImageIteratorType(scalarImage, scalarImage->GetLargestPossibleRegion() ) ; while ( !s_iter.IsAtEnd() ) { s_iter.Set(count) ; ++count ; ++s_iter ; } VectorImageType::Pointer vectorImage = VectorImageType::New() ; vectorImage->SetRegions(size) ; vectorImage->Allocate() ; count = 0 ; VectorImageType::PixelType vPixel ; VectorImageIteratorType v_iter = VectorImageIteratorType(vectorImage, vectorImage->GetLargestPossibleRegion()) ; while ( !v_iter.IsAtEnd() ) { vPixel[0] = count ; vPixel[1] = count ; v_iter.Set( vPixel ) ; ++count ; ++v_iter ; } typedef DummyScalarImageToListAdaptor< ScalarImageType > ScalarListType ; ScalarListType::Pointer sList = ScalarListType::New() ; sList->SetImage( scalarImage ) ; typedef DummyImageToListAdaptor< VectorImageType > VectorListType ; VectorListType::Pointer vList = VectorListType::New() ; vList->SetImage( vectorImage ) ; typedef itk::ScalarToArrayCastImageFilter< ScalarImageType, ArrayImageType > CasterType ; CasterType::Pointer caster = CasterType::New() ; caster->SetInput( scalarImage ) ; caster->Update() ; typedef itk::Statistics::ImageToListAdaptor< ArrayImageType > ImageListType ; ImageListType::Pointer imageList = ImageListType::New() ; imageList->SetImage( caster->GetOutput() ) ; typedef DummyJointDomainImageToListAdaptor< VectorImageType, float > JointDomainImageListType ; JointDomainImageListType::Pointer jointDomainImageList = JointDomainImageListType::New() ; jointDomainImageList->SetImage( vectorImage ) ; std::cout << "Testing the each measurement values:" << std::endl ; for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i ) { if ( sList->GetMeasurementVector( i )[0] != vList->GetMeasurementVector( i )[0] || sList->GetMeasurementVector( i )[0] != imageList->GetMeasurementVector( i )[0] || sList->GetMeasurementVector( i )[0] != jointDomainImageList->GetMeasurementVector( i )[3] ) { std::cout << "ERROR: measurement mismatch!!!" << std::endl ; return EXIT_FAILURE ; } } std::cout << std::endl ; std::cout << "Scalar image (casted) pixel access performance test:" << std::endl ; time_t begin = clock() ; for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i ) { imageList->GetMeasurementVector( i ) ; } time_t end = clock() ; std::cout << "time: " << (double(end - begin) /CLOCKS_PER_SEC) << " seconds" << std::endl ; std::cout << "Scalar image pixel access performance test:" << std::endl ; begin = clock() ; for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i ) { sList->GetMeasurementVector( i ) ; } end = clock() ; std::cout << "time: " << (double(end - begin) /CLOCKS_PER_SEC) << " seconds" << std::endl ; std::cout << "Vector image pixel access performance test:" << std::endl ; begin = clock() ; for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i ) { vList->GetMeasurementVector( i ) ; } end = clock() ; std::cout << "time: " << (double(end - begin) /CLOCKS_PER_SEC) << " seconds" << std::endl ; std::cout << "Joint Domain Vector image pixel access performance test:" << std::endl ; begin = clock() ; for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i ) { std::cout << jointDomainImageList->GetMeasurementVector( i ) << std::endl ; } end = clock() ; std::cout << "time: " << (double(end - begin) /CLOCKS_PER_SEC) << " seconds" << std::endl ; return EXIT_SUCCESS ; } <|endoftext|>
<commit_before>#ifndef _BME280_IMPL_ #define _BME280_IMPL_ #include "SensorInterface.hpp" #include <Wire.h> #include <Adafruit_BME280.h> class BME280_Impl : public SensorInterface { public: BME280_Impl(uint8_t i2caddr); virtual ~BME280_Impl(); virtual float temperature(); virtual float humidity(); virtual float pressure(); virtual SensorInterface::SensorState state(); private: void readSensor(); Adafruit_BME280 bme; SensorInterface::SensorState ss; float h; // humidity in percent float t; // temperature as Celsius float p; // pressure in hPa }; inline BME280_Impl::BME280_Impl(uint8_t i2caddr) : bme() , ss(SensorInterface::state()) , t(SensorInterface::temperature()) , h(SensorInterface::humidity()) , p(SensorInterface::pressure()) { if (!bme.begin(i2caddr)) { Homie.getLogger() << "Couldn't find BME280" << endl; ss = connect_error; } else { // weather monitoring bme.setSampling(Adafruit_BME280::MODE_FORCED, Adafruit_BME280::SAMPLING_X1, // temperature Adafruit_BME280::SAMPLING_X1, // pressure Adafruit_BME280::SAMPLING_X1, // humidity Adafruit_BME280::FILTER_OFF ); } } inline BME280_Impl::~BME280_Impl() { } inline void BME280_Impl::readSensor() { if(ss == connect_error) return; static unsigned long lastRead = 0; if(lastRead == 0 || (millis() - lastRead >= 60000UL)) { // suggested: 1 reading per minute // Only needed in forced mode! In normal mode, you can remove the next line. bme.takeForcedMeasurement(); // has no effect in normal mode float _t = bme.readTemperature(); float _h = bme.readHumidity(); float _p = bme.readPressure() / 100.0F; // Check if any reads failed and keep old values (to try again). if (isnan(_h) || isnan(_t) || isnan(_p)) { ss = SensorInterface::read_error; Homie.getLogger() << "Failed to read BME280 sensor!" << endl; } else { ss = SensorInterface::ok; t = _t; h = _h; p = _p; } } } inline float BME280_Impl::temperature() { readSensor(); return t; } inline float BME280_Impl::humidity() { readSensor(); return h; } inline float BME280_Impl::pressure() { readSensor(); return p; } inline SensorInterface::SensorState BME280_Impl::state() { readSensor(); return ss; } #endif <commit_msg>* fixed max reading interval of BME280<commit_after>#ifndef _BME280_IMPL_ #define _BME280_IMPL_ #include "SensorInterface.hpp" #include <Wire.h> #include <Adafruit_BME280.h> class BME280_Impl : public SensorInterface { public: BME280_Impl(uint8_t i2caddr); virtual ~BME280_Impl(); virtual float temperature(); virtual float humidity(); virtual float pressure(); virtual SensorInterface::SensorState state(); private: void readSensor(); Adafruit_BME280 bme; SensorInterface::SensorState ss; float h; // humidity in percent float t; // temperature as Celsius float p; // pressure in hPa }; inline BME280_Impl::BME280_Impl(uint8_t i2caddr) : bme() , ss(SensorInterface::state()) , t(SensorInterface::temperature()) , h(SensorInterface::humidity()) , p(SensorInterface::pressure()) { if (!bme.begin(i2caddr)) { Homie.getLogger() << "Couldn't find BME280" << endl; ss = connect_error; } else { // weather monitoring bme.setSampling(Adafruit_BME280::MODE_FORCED, Adafruit_BME280::SAMPLING_X1, // temperature Adafruit_BME280::SAMPLING_X1, // pressure Adafruit_BME280::SAMPLING_X1, // humidity Adafruit_BME280::FILTER_OFF ); } } inline BME280_Impl::~BME280_Impl() { } inline void BME280_Impl::readSensor() { if(ss == connect_error) return; if((now - last) > 60000UL || (last == 0)) { // suggested: 1 reading per minute // Only needed in forced mode! In normal mode, you can remove the next line. bme.takeForcedMeasurement(); // has no effect in normal mode float _t = bme.readTemperature(); float _h = bme.readHumidity(); float _p = bme.readPressure() / 100.0F; // Check if any reads failed and keep old values (to try again). if (isnan(_h) || isnan(_t) || isnan(_p)) { ss = SensorInterface::read_error; Homie.getLogger() << "Failed to read BME280 sensor!" << endl; } else { ss = SensorInterface::ok; t = _t; h = _h; p = _p; last = now; } } } inline float BME280_Impl::temperature() { readSensor(); return t; } inline float BME280_Impl::humidity() { readSensor(); return h; } inline float BME280_Impl::pressure() { readSensor(); return p; } inline SensorInterface::SensorState BME280_Impl::state() { readSensor(); return ss; } #endif <|endoftext|>
<commit_before>#include <iostream> #include "convexHull.h" #include "testUtil.h" using namespace Eigen; void testConvexHull() { Matrix<double, 2, Dynamic> pts(2, 4); pts << 1.0, 2.0, 3.0, 2.0, 2.0, 1.0, 2.0, 3.0; valuecheck(inConvexHull(pts, Vector2d(2.0, 2.0)), true); valuecheck(inConvexHull(pts, Vector2d(1.0001, 2.0)), true); valuecheck(inConvexHull(pts, Vector2d(0.9999, 2.0)), false); valuecheck(inConvexHull(pts, Vector2d(2.49, 2.49)), true); valuecheck(inConvexHull(pts, Vector2d(2.51, 2.51)), false); } void testDistanceFromHull() { Matrix<double, 2, Dynamic> pts(2, 5); pts << 0, 1, 1, 0, 0.5, 0, 1, 0, 1, 0.5; double d = signedDistanceInsideConvexHull(pts, Vector2d(0, 0)); valuecheck(d, 0.0, 1e-8); d = signedDistanceInsideConvexHull(pts, Vector2d(0.5, 0.5)); valuecheck(d, 0.5, 1e-8); d = signedDistanceInsideConvexHull(pts, Vector2d(-0.5, 0)); valuecheck(d, -0.5, 1e-8); pts << 0, 2, 2, 0, 0.5, 0, 2, 0, 2, 0.5; d = signedDistanceInsideConvexHull(pts, Vector2d(0, 0)); valuecheck(d, 0.0, 1e-8); d = signedDistanceInsideConvexHull(pts, Vector2d(0.5, 0.5)); valuecheck(d, 0.5, 1e-8); d = signedDistanceInsideConvexHull(pts, Vector2d(-0.5, 0)); valuecheck(d, -0.5, 1e-8); } void testRealData() { Matrix<double, 2, Dynamic> pts(2, 16); pts << 0.237506, 0.330077, 0.297687, 0.390258, 0.177325, 0.269896, 0.357868, 0.450439, 0.00257912, 0.116144, 0.0466612, 0.160226, -0.03475, 0.0788149, 0.0873669, 0.200932, -0.00459488, -0.093748, 0.0579462, -0.0312069, -0.067136, -0.156289, 0.120487, 0.0313342, 0.102483, 0.0421703, 0.185504, 0.125191, 0.0321808, -0.0281323, 0.262166, 0.201853; Vector2d q(0.196956, 0.0487772); double d = signedDistanceInsideConvexHull(pts, q); valuecheck(d, 0.136017, 1e-6); } void testDuplicates() { Matrix<double, 2, Dynamic> pts(2, 8); pts << 0.0, 1.0, 1.0, 0.0, 0.5, 0.0, 0.0, 1.0 - 1e-16, 0.0, 1.0, 0.0, 1.0, 0.5, 0.0, 0.0, 1.0 - 1e-16; double d = signedDistanceInsideConvexHull(pts, Vector2d(0, 0)); valuecheck(d, 0.0, 1e-8); d = signedDistanceInsideConvexHull(pts, Vector2d(0.5, 0.5)); valuecheck(d, 0.5, 1e-8); d = signedDistanceInsideConvexHull(pts, Vector2d(-0.5, 0)); valuecheck(d, -0.5, 1e-8); } void testRandomConvexCombinations() { for (int i=2; i < 10; ++i) { for (int j=0; j < 100; ++j) { MatrixXd pts = MatrixXd::Random(2, i); VectorXd weights = VectorXd::Random(i); if (weights.minCoeff() < 0) { weights = weights.array() - weights.minCoeff(); // make sure they're all nonnegative } weights = weights.array() / weights.sum(); Vector2d q = pts * weights; valuecheck(inConvexHull(pts, q, 1e-8), true); } } } int main() { testConvexHull(); std::cout << "testConvexHull passed" << std::endl; testDistanceFromHull(); std::cout << "testDistanceFromHull passed" << std::endl; testRealData(); std::cout << "testRealData passed" << std::endl; testDuplicates(); std::cout << "testDuplicates passed" << std::endl; testRandomConvexCombinations(); std::cout << "testRandomConvexCombinations passed" << std::endl; } <commit_msg>more tests<commit_after>#include <iostream> #include "convexHull.h" #include "testUtil.h" using namespace Eigen; void testConvexHull() { Matrix<double, 2, Dynamic> pts(2, 4); pts << 1.0, 2.0, 3.0, 2.0, 2.0, 1.0, 2.0, 3.0; valuecheck(inConvexHull(pts, Vector2d(2.0, 2.0)), true); valuecheck(inConvexHull(pts, Vector2d(1.0001, 2.0)), true); valuecheck(inConvexHull(pts, Vector2d(0.9999, 2.0)), false); valuecheck(inConvexHull(pts, Vector2d(2.49, 2.49)), true); valuecheck(inConvexHull(pts, Vector2d(2.51, 2.51)), false); } void testDistanceFromHull() { Matrix<double, 2, Dynamic> pts(2, 5); pts << 0, 1, 1, 0, 0.5, 0, 1, 0, 1, 0.5; double d = signedDistanceInsideConvexHull(pts, Vector2d(0, 0)); valuecheck(d, 0.0, 1e-8); d = signedDistanceInsideConvexHull(pts, Vector2d(0.5, 0.5)); valuecheck(d, 0.5, 1e-8); d = signedDistanceInsideConvexHull(pts, Vector2d(-0.5, 0)); valuecheck(d, -0.5, 1e-8); pts << 0, 2, 2, 0, 0.5, 0, 2, 0, 2, 0.5; d = signedDistanceInsideConvexHull(pts, Vector2d(0, 0)); valuecheck(d, 0.0, 1e-8); d = signedDistanceInsideConvexHull(pts, Vector2d(0.5, 0.5)); valuecheck(d, 0.5, 1e-8); d = signedDistanceInsideConvexHull(pts, Vector2d(-0.5, 0)); valuecheck(d, -0.5, 1e-8); } void testRealData() { Matrix<double, 2, Dynamic> pts(2, 16); pts << 0.237506, 0.330077, 0.297687, 0.390258, 0.177325, 0.269896, 0.357868, 0.450439, 0.00257912, 0.116144, 0.0466612, 0.160226, -0.03475, 0.0788149, 0.0873669, 0.200932, -0.00459488, -0.093748, 0.0579462, -0.0312069, -0.067136, -0.156289, 0.120487, 0.0313342, 0.102483, 0.0421703, 0.185504, 0.125191, 0.0321808, -0.0281323, 0.262166, 0.201853; Vector2d q(0.196956, 0.0487772); double d = signedDistanceInsideConvexHull(pts, q); valuecheck(d, 0.136017, 1e-6); } void testDuplicates() { Matrix<double, 2, Dynamic> pts(2, 8); pts << 0.0, 1.0, 1.0, 0.0, 0.5, 0.0, 0.0, 1.0 - 1e-16, 0.0, 1.0, 0.0, 1.0, 0.5, 0.0, 0.0, 1.0 - 1e-16; double d = signedDistanceInsideConvexHull(pts, Vector2d(0, 0)); valuecheck(d, 0.0, 1e-8); d = signedDistanceInsideConvexHull(pts, Vector2d(0.5, 0.5)); valuecheck(d, 0.5, 1e-8); d = signedDistanceInsideConvexHull(pts, Vector2d(-0.5, 0)); valuecheck(d, -0.5, 1e-8); } void testRandomConvexCombinations() { for (int i=2; i < 50; ++i) { for (int j=0; j < 500; ++j) { MatrixXd pts = MatrixXd::Random(2, i); VectorXd weights = VectorXd::Random(i); if (weights.minCoeff() < 0) { weights = weights.array() - weights.minCoeff(); // make sure they're all nonnegative } weights = weights.array() / weights.sum(); Vector2d q = pts * weights; valuecheck(inConvexHull(pts, q, 1e-8), true); } } } int main() { testConvexHull(); std::cout << "testConvexHull passed" << std::endl; testDistanceFromHull(); std::cout << "testDistanceFromHull passed" << std::endl; testRealData(); std::cout << "testRealData passed" << std::endl; testDuplicates(); std::cout << "testDuplicates passed" << std::endl; testRandomConvexCombinations(); std::cout << "testRandomConvexCombinations passed" << std::endl; } <|endoftext|>
<commit_before>//=========================================== // Lumina-DE source code // Copyright (c) 2016, Ken Moore // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #ifdef __linux__ #include <QDebug> #include "LuminaOS.h" #include <unistd.h> #include <stdio.h> // Needed for BUFSIZ //can't read xbrightness settings - assume invalid until set static int screenbrightness = -1; QString LOS::OSName(){ return "Gentoo Linux"; } //OS-specific prefix(s) // NOTE: PREFIX, L_ETCDIR, L_SHAREDIR are defined in the OS-detect.pri project file and passed in QString LOS::LuminaShare(){ return (L_SHAREDIR+"/lumina-desktop/"); } //Install dir for Lumina share files QString LOS::AppPrefix(){ return "/usr/"; } //Prefix for applications QString LOS::SysPrefix(){ return "/"; } //Prefix for system //OS-specific application shortcuts (*.desktop files) QString LOS::ControlPanelShortcut(){ return ""; } //system control panel QString LOS::AppStoreShortcut(){ return LOS::AppPrefix() + "/share/applications/porthole.desktop"; } //graphical app/pkg manager //OS-specific RSS feeds (Format: QStringList[ <name>::::<url> ]; ) QStringList LOS::RSSFeeds(){ return QStringList(); } // ==== ExternalDevicePaths() ==== QStringList LOS::ExternalDevicePaths(){ /* Returns: QStringList[<type>::::<filesystem>::::<path>] Note: <type> = [USB, HDRIVE, DVD, SDCARD, UNKNOWN] df is much better for this than mount, because it skips all non-physical devices (like bind-mounts from schroot) so they are not listed in lumina-fm */ QStringList devs = LUtils::getCmdOutput("df --output=source,fstype,target"); //Now check the output for(int i=0; i<devs.length(); i++){ if(devs[i].startsWith("/dev/")){ devs[i] = devs[i].simplified(); QString type = devs[i].section(" on ",0,0); type.remove("/dev/"); //Determine the type of hardware device based on the dev node if(type.startsWith("sd") || type.startsWith("nvme")){ type = "HDRIVE"; } else if(type.startsWith("sr")){ type="DVD"; } else if(type.contains("mapper")){ type="LVM"; } else{ type = "UNKNOWN"; } //Now put the device in the proper output format devs[i] = type + "::::" + devs[i].section(" ",1,1) + "::::" + devs[i].section(" ",2,2); }else{ //invalid device - remove it from the list devs.removeAt(i); i--; } } return devs; } //Read screen brightness information int LOS::ScreenBrightness(){ //Returns: Screen Brightness as a percentage (0-100, with -1 for errors) if(screenbrightness==-1){ if(QFile::exists(QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/.currentxbrightness")){ int val = LUtils::readFile(QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/.currentxbrightness").join("").simplified().toInt(); screenbrightness = val; } } return screenbrightness; } //Set screen brightness void LOS::setScreenBrightness(int percent){ //ensure bounds if(percent<0){percent=0;} else if(percent>100){ percent=100; } // float pf = percent/100.0; //convert to a decimel //Run the command QString cmd = "xbacklight -set %1"; // cmd = cmd.arg( QString::number( int(65535*pf) ) ); cmd = cmd.arg( QString::number( percent ) ); int ret = LUtils::runCmd(cmd); //Save the result for later if(ret!=0){ screenbrightness = -1; } else{ screenbrightness = percent; } LUtils::writeFile(QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/.currentxbrightness", QStringList() << QString::number(screenbrightness), true); } //Read the current volume int LOS::audioVolume(){ //Returns: audio volume as a percentage (0-100, with -1 for errors) QString info = LUtils::getCmdOutput("amixer get Master").join("").simplified();; int out = -1; int start_position, end_position; QString current_volume; if(!info.isEmpty()){ start_position = info.indexOf("["); start_position++; end_position = info.indexOf("%"); current_volume = info.mid(start_position, end_position - start_position); out = current_volume.toInt(); } return out; } //Set the current volume void LOS::setAudioVolume(int percent){ if(percent<0){percent=0;} else if(percent>100){percent=100;} // QString info = "amixer -c 0 sset Master,0 " + QString::number(percent) + "%"; QString info = "amixer set Master " + QString::number(percent) + "%"; if(!info.isEmpty()){ //Run Command LUtils::runCmd(info); } } //Change the current volume a set amount (+ or -) void LOS::changeAudioVolume(int percentdiff){ int old_volume = audioVolume(); int new_volume = old_volume + percentdiff; if (new_volume < 0) new_volume = 0; if (new_volume > 100) new_volume = 100; qDebug() << "Setting new volume to: " << new_volume; setAudioVolume(new_volume); } //Check if a graphical audio mixer is installed bool LOS::hasMixerUtility(){ return QFile::exists(LOS::AppPrefix() + "bin/pavucontrol"); } //Launch the graphical audio mixer utility void LOS::startMixerUtility(){ QProcess::startDetached(LOS::AppPrefix() + "bin/pavucontrol"); } //Check for user system permission (shutdown/restart) bool LOS::userHasShutdownAccess(){ return QProcess::startDetached("dbus-send --system --print-reply=literal \ --type=method_call --dest=org.freedesktop.login1 \ /org/freedesktop/login1 org.freedesktop.login1.Manager.CanPowerOff"); } //Check for whether the system is safe to power off (no updates being perfomed) bool LOS::systemPerformingUpdates(){ return false; //Not implemented yet } //Return the details of any updates which are waiting to apply on shutdown QString LOS::systemPendingUpdates(){ return ""; } //System Shutdown void LOS::systemShutdown(bool){ //start poweroff sequence //INPUT: skip updates (true/false) QProcess::startDetached("dbus-send --system --print-reply \ --dest=org.freedesktop.login1 /org/freedesktop/login1 \ org.freedesktop.login1.Manager.PowerOff boolean:true"); } //System Restart void LOS::systemRestart(bool){ //start reboot sequence //INPUT: skip updates (true/false) QProcess::startDetached("dbus-send --system --print-reply \ --dest=org.freedesktop.login1 /org/freedesktop/login1 \ org.freedesktop.login1.Manager.Reboot boolean:true"); } //Check for suspend support bool LOS::systemCanSuspend(){ return QProcess::startDetached("dbus-send --system --print-reply=literal \ --type=method_call --dest=org.freedesktop.login1 \ /org/freedesktop/login1 org.freedesktop.login1.Manager.CanSuspend"); } //Put the system into the suspend state void LOS::systemSuspend(){ QProcess::startDetached("dbus-send --system --print-reply \ --dest=org.freedesktop.login1 /org/freedesktop/login1 \ org.freedesktop.login1.Manager.Suspend boolean:true"); } //Battery Availability bool LOS::hasBattery(){ QString my_status = LUtils::getCmdOutput("acpi -b").join(""); bool no_battery = my_status.contains("No support"); if (no_battery) return false; return true; } //Battery Charge Level int LOS::batteryCharge(){ //Returns: percent charge (0-100), anything outside that range is counted as an error QString my_status = LUtils::getCmdOutput("acpi -b").join(""); int my_start = my_status.indexOf("%"); // get the number right before the % sign int my_end = my_start; my_start--; while ( (my_status[my_start] != ' ') && (my_start > 0) ) my_start--; my_start++; int my_charge = my_status.mid(my_start, my_end - my_start).toInt(); if ( (my_charge < 0) || (my_charge > 100) ) return -1; return my_charge; } //Battery Charging State // Many possible values are returned if the laptop is plugged in // these include "Unknown, Full and No support. // However, it seems just one status is returned when running // on battery and that is "Discharging". So if the value we get // is NOT Discharging then we assume the battery is charging. bool LOS::batteryIsCharging(){ QString my_status = LUtils::getCmdOutput("acpi -b").join(""); bool discharging = my_status.contains("Discharging"); if (discharging) return false; return true; } //Battery Time Remaining int LOS::batterySecondsLeft(){ //Returns: estimated number of seconds remaining return 0; //not implemented yet for Linux } //File Checksums QStringList LOS::Checksums(QStringList filepaths){ //Return: checksum of the input file QStringList info = LUtils::getCmdOutput("md5sum \""+filepaths.join("\" \"")+"\""); for(int i=0; i<info.length(); i++){ // first: md5sum: = error ; second: there's always one empty entry generated by getCmdOutput if( info[i].startsWith("md5sum:") || info[i].isEmpty()){ info.removeAt(i); i--; } else{ //Strip out the extra information info[i] = info[i].section(" ",0,0); } } return info; } //file system capacity QString LOS::FileSystemCapacity(QString dir) { //Return: percentage capacity as give by the df command QStringList mountInfo = LUtils::getCmdOutput("df -h \"" + dir + "\""); QString::SectionFlag skipEmpty = QString::SectionSkipEmpty; //output: 200G of 400G available on /mount/point QString capacity = mountInfo[1].section(" ",3,3, skipEmpty) + " of " + mountInfo[1].section(" ",1,1, skipEmpty) + " available on " + mountInfo[1].section(" ",5,5, skipEmpty); return capacity; } QStringList LOS::CPUTemperatures(){ //Returns: List containing the temperature of any CPU's ("50C" for example) QStringList temp = LUtils::getCmdOutput("acpi -t").filter("degrees"); for(int i=0; i<temp.length(); i++){ if(temp[i].startsWith("Thermal")){ temp[i] = temp[i].section(" ", 4, 6); }else{ temp.removeAt(i); i--; } } if(temp.isEmpty()) { temp << "Not available"; } return temp; } int LOS::CPUUsagePercent(){ //Returns: Overall percentage of the amount of CPU cycles in use (-1 for errors) QStringList info = LUtils::getCmdOutput("top -bn1").filter("Cpu(s)"); if(info.isEmpty()){ return -1; } QString idle = info.first().section(" ", 7, 7, QString::SectionSkipEmpty); if(idle.isEmpty()){ return -1; } else{ return (100 - idle.toDouble()); } } int LOS::MemoryUsagePercent(){ QStringList mem = LUtils::getCmdOutput("top -bn1").filter("Mem :"); if(mem.isEmpty()){ return -1; } double fB = 0; //Free Bytes double uB = 0; //Used Bytes fB = mem.first().section(" ", 5, 5, QString::SectionSkipEmpty).toDouble(); uB = mem.first().section(" ", 7, 7, QString::SectionSkipEmpty).toDouble(); double per = (uB/(fB+uB)) * 100.0; return qRound(per); } QStringList LOS::DiskUsage(){ //Returns: List of current read/write stats for each device QStringList info = LUtils::getCmdOutput("iostat -dx -N"); if(info.length()<3){ return QStringList(); } //nothing from command QStringList labs = info[1].split(" ",QString::SkipEmptyParts); QStringList out; QString fmt = "%1: %2 %3"; for(int i=2; i<info.length(); i++){ //skip the first two lines, just labels info[i].replace("\t"," "); if(info[i].startsWith("Device:")){ labs = info[i].split(" ", QString::SkipEmptyParts); }//the labels for each column else{ QStringList data = info[i].split(" ",QString::SkipEmptyParts); //data[0] is always the device if(data.length()>2 && labs.length()>2){ out << fmt.arg(data[0], data[3]+" "+labs[3], data[4]+" "+labs[4]); } } } return out; } #endif <commit_msg>Fix dbus-send calls for Gentoo.<commit_after>//=========================================== // Lumina-DE source code // Copyright (c) 2016, Ken Moore // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #ifdef __linux__ #include <QDebug> #include "LuminaOS.h" #include <unistd.h> #include <stdio.h> // Needed for BUFSIZ //can't read xbrightness settings - assume invalid until set static int screenbrightness = -1; QString LOS::OSName(){ return "Gentoo Linux"; } //OS-specific prefix(s) // NOTE: PREFIX, L_ETCDIR, L_SHAREDIR are defined in the OS-detect.pri project file and passed in QString LOS::LuminaShare(){ return (L_SHAREDIR+"/lumina-desktop/"); } //Install dir for Lumina share files QString LOS::AppPrefix(){ return "/usr/"; } //Prefix for applications QString LOS::SysPrefix(){ return "/"; } //Prefix for system //OS-specific application shortcuts (*.desktop files) QString LOS::ControlPanelShortcut(){ return ""; } //system control panel QString LOS::AppStoreShortcut(){ return LOS::AppPrefix() + "/share/applications/porthole.desktop"; } //graphical app/pkg manager //OS-specific RSS feeds (Format: QStringList[ <name>::::<url> ]; ) QStringList LOS::RSSFeeds(){ return QStringList(); } // ==== ExternalDevicePaths() ==== QStringList LOS::ExternalDevicePaths(){ /* Returns: QStringList[<type>::::<filesystem>::::<path>] Note: <type> = [USB, HDRIVE, DVD, SDCARD, UNKNOWN] df is much better for this than mount, because it skips all non-physical devices (like bind-mounts from schroot) so they are not listed in lumina-fm */ QStringList devs = LUtils::getCmdOutput("df --output=source,fstype,target"); //Now check the output for(int i=0; i<devs.length(); i++){ if(devs[i].startsWith("/dev/")){ devs[i] = devs[i].simplified(); QString type = devs[i].section(" on ",0,0); type.remove("/dev/"); //Determine the type of hardware device based on the dev node if(type.startsWith("sd") || type.startsWith("nvme")){ type = "HDRIVE"; } else if(type.startsWith("sr")){ type="DVD"; } else if(type.contains("mapper")){ type="LVM"; } else{ type = "UNKNOWN"; } //Now put the device in the proper output format devs[i] = type + "::::" + devs[i].section(" ",1,1) + "::::" + devs[i].section(" ",2,2); }else{ //invalid device - remove it from the list devs.removeAt(i); i--; } } return devs; } //Read screen brightness information int LOS::ScreenBrightness(){ //Returns: Screen Brightness as a percentage (0-100, with -1 for errors) if(screenbrightness==-1){ if(QFile::exists(QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/.currentxbrightness")){ int val = LUtils::readFile(QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/.currentxbrightness").join("").simplified().toInt(); screenbrightness = val; } } return screenbrightness; } //Set screen brightness void LOS::setScreenBrightness(int percent){ //ensure bounds if(percent<0){percent=0;} else if(percent>100){ percent=100; } // float pf = percent/100.0; //convert to a decimel //Run the command QString cmd = "xbacklight -set %1"; // cmd = cmd.arg( QString::number( int(65535*pf) ) ); cmd = cmd.arg( QString::number( percent ) ); int ret = LUtils::runCmd(cmd); //Save the result for later if(ret!=0){ screenbrightness = -1; } else{ screenbrightness = percent; } LUtils::writeFile(QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/.currentxbrightness", QStringList() << QString::number(screenbrightness), true); } //Read the current volume int LOS::audioVolume(){ //Returns: audio volume as a percentage (0-100, with -1 for errors) QString info = LUtils::getCmdOutput("amixer get Master").join("").simplified();; int out = -1; int start_position, end_position; QString current_volume; if(!info.isEmpty()){ start_position = info.indexOf("["); start_position++; end_position = info.indexOf("%"); current_volume = info.mid(start_position, end_position - start_position); out = current_volume.toInt(); } return out; } //Set the current volume void LOS::setAudioVolume(int percent){ if(percent<0){percent=0;} else if(percent>100){percent=100;} // QString info = "amixer -c 0 sset Master,0 " + QString::number(percent) + "%"; QString info = "amixer set Master " + QString::number(percent) + "%"; if(!info.isEmpty()){ //Run Command LUtils::runCmd(info); } } //Change the current volume a set amount (+ or -) void LOS::changeAudioVolume(int percentdiff){ int old_volume = audioVolume(); int new_volume = old_volume + percentdiff; if (new_volume < 0) new_volume = 0; if (new_volume > 100) new_volume = 100; qDebug() << "Setting new volume to: " << new_volume; setAudioVolume(new_volume); } //Check if a graphical audio mixer is installed bool LOS::hasMixerUtility(){ return QFile::exists(LOS::AppPrefix() + "bin/pavucontrol"); } //Launch the graphical audio mixer utility void LOS::startMixerUtility(){ QProcess::startDetached(LOS::AppPrefix() + "bin/pavucontrol"); } //Check for user system permission (shutdown/restart) bool LOS::userHasShutdownAccess(){ return QProcess::startDetached("dbus-send --system --print-reply=literal \ --type=method_call --dest=org.freedesktop.ConsoleKit \ /org/freedesktop/ConsoleKit/Manager org.freedesktop.ConsoleKit.Manager.CanPowerOff"); } //Check for whether the system is safe to power off (no updates being perfomed) bool LOS::systemPerformingUpdates(){ return false; //Not implemented yet } //Return the details of any updates which are waiting to apply on shutdown QString LOS::systemPendingUpdates(){ return ""; } //System Shutdown void LOS::systemShutdown(bool){ //start poweroff sequence //INPUT: skip updates (true/false) QProcess::startDetached("dbus-send --system --print-reply \ --dest=org.freedesktop.ConsoleKit /org/freedesktop/ConsoleKit/Manager \ org.freedesktop.ConsoleKit.Manager.PowerOff boolean:true"); } //System Restart void LOS::systemRestart(bool){ //start reboot sequence //INPUT: skip updates (true/false) QProcess::startDetached("dbus-send --system --print-reply \ --dest=org.freedesktop.ConsoleKit /org/freedesktop/ConsoleKit/Manager \ org.freedesktop.ConsoleKit.Manager.Reboot boolean:true"); } //Check for suspend support bool LOS::systemCanSuspend(){ return QProcess::startDetached("dbus-send --system --print-reply=literal \ --type=method_call --dest=org.freedesktop.ConsoleKit \ /org/freedesktop/ConsoleKit/Manager org.freedesktop.ConsoleKit.Manager.CanSuspend"); } //Put the system into the suspend state void LOS::systemSuspend(){ QProcess::startDetached("dbus-send --system --print-reply \ --dest=org.freedesktop.ConsoleKit /org/freedesktop/ConsoleKit/Manager \ org.freedesktop.ConsoleKit.Manager.Suspend boolean:true"); } //Battery Availability bool LOS::hasBattery(){ QString my_status = LUtils::getCmdOutput("acpi -b").join(""); bool no_battery = my_status.contains("No support"); if (no_battery) return false; return true; } //Battery Charge Level int LOS::batteryCharge(){ //Returns: percent charge (0-100), anything outside that range is counted as an error QString my_status = LUtils::getCmdOutput("acpi -b").join(""); int my_start = my_status.indexOf("%"); // get the number right before the % sign int my_end = my_start; my_start--; while ( (my_status[my_start] != ' ') && (my_start > 0) ) my_start--; my_start++; int my_charge = my_status.mid(my_start, my_end - my_start).toInt(); if ( (my_charge < 0) || (my_charge > 100) ) return -1; return my_charge; } //Battery Charging State // Many possible values are returned if the laptop is plugged in // these include "Unknown, Full and No support. // However, it seems just one status is returned when running // on battery and that is "Discharging". So if the value we get // is NOT Discharging then we assume the battery is charging. bool LOS::batteryIsCharging(){ QString my_status = LUtils::getCmdOutput("acpi -b").join(""); bool discharging = my_status.contains("Discharging"); if (discharging) return false; return true; } //Battery Time Remaining int LOS::batterySecondsLeft(){ //Returns: estimated number of seconds remaining return 0; //not implemented yet for Linux } //File Checksums QStringList LOS::Checksums(QStringList filepaths){ //Return: checksum of the input file QStringList info = LUtils::getCmdOutput("md5sum \""+filepaths.join("\" \"")+"\""); for(int i=0; i<info.length(); i++){ // first: md5sum: = error ; second: there's always one empty entry generated by getCmdOutput if( info[i].startsWith("md5sum:") || info[i].isEmpty()){ info.removeAt(i); i--; } else{ //Strip out the extra information info[i] = info[i].section(" ",0,0); } } return info; } //file system capacity QString LOS::FileSystemCapacity(QString dir) { //Return: percentage capacity as give by the df command QStringList mountInfo = LUtils::getCmdOutput("df -h \"" + dir + "\""); QString::SectionFlag skipEmpty = QString::SectionSkipEmpty; //output: 200G of 400G available on /mount/point QString capacity = mountInfo[1].section(" ",3,3, skipEmpty) + " of " + mountInfo[1].section(" ",1,1, skipEmpty) + " available on " + mountInfo[1].section(" ",5,5, skipEmpty); return capacity; } QStringList LOS::CPUTemperatures(){ //Returns: List containing the temperature of any CPU's ("50C" for example) QStringList temp = LUtils::getCmdOutput("acpi -t").filter("degrees"); for(int i=0; i<temp.length(); i++){ if(temp[i].startsWith("Thermal")){ temp[i] = temp[i].section(" ", 4, 6); }else{ temp.removeAt(i); i--; } } if(temp.isEmpty()) { temp << "Not available"; } return temp; } int LOS::CPUUsagePercent(){ //Returns: Overall percentage of the amount of CPU cycles in use (-1 for errors) QStringList info = LUtils::getCmdOutput("top -bn1").filter("Cpu(s)"); if(info.isEmpty()){ return -1; } QString idle = info.first().section(" ", 7, 7, QString::SectionSkipEmpty); if(idle.isEmpty()){ return -1; } else{ return (100 - idle.toDouble()); } } int LOS::MemoryUsagePercent(){ QStringList mem = LUtils::getCmdOutput("top -bn1").filter("Mem :"); if(mem.isEmpty()){ return -1; } double fB = 0; //Free Bytes double uB = 0; //Used Bytes fB = mem.first().section(" ", 5, 5, QString::SectionSkipEmpty).toDouble(); uB = mem.first().section(" ", 7, 7, QString::SectionSkipEmpty).toDouble(); double per = (uB/(fB+uB)) * 100.0; return qRound(per); } QStringList LOS::DiskUsage(){ //Returns: List of current read/write stats for each device QStringList info = LUtils::getCmdOutput("iostat -dx -N"); if(info.length()<3){ return QStringList(); } //nothing from command QStringList labs = info[1].split(" ",QString::SkipEmptyParts); QStringList out; QString fmt = "%1: %2 %3"; for(int i=2; i<info.length(); i++){ //skip the first two lines, just labels info[i].replace("\t"," "); if(info[i].startsWith("Device:")){ labs = info[i].split(" ", QString::SkipEmptyParts); }//the labels for each column else{ QStringList data = info[i].split(" ",QString::SkipEmptyParts); //data[0] is always the device if(data.length()>2 && labs.length()>2){ out << fmt.arg(data[0], data[3]+" "+labs[3], data[4]+" "+labs[4]); } } } return out; } #endif <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch> //------------------------------------------------------------------------------ #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclarationName.h" #include "clang/Sema/Sema.h" #include "clang/Sema/Lookup.h" using namespace clang; namespace cling { namespace utils { Expr* Synthesize::CStyleCastPtrExpr(Sema* S, QualType Ty, uint64_t Ptr) { ASTContext& Ctx = S->getASTContext(); if (!Ty->isPointerType()) Ty = Ctx.getPointerType(Ty); TypeSourceInfo* TSI = Ctx.CreateTypeSourceInfo(Ty); const llvm::APInt Addr(8 * sizeof(void *), Ptr); Expr* Result = IntegerLiteral::Create(Ctx, Addr, Ctx.UnsignedLongTy, SourceLocation()); Result = S->BuildCStyleCastExpr(SourceLocation(), TSI, SourceLocation(), Result).take(); assert(Result && "Cannot create CStyleCastPtrExpr"); return Result; } static NestedNameSpecifier* GetPartiallyDesugaredNNS(const ASTContext& Ctx, NestedNameSpecifier* scope, const llvm::SmallSet<const Type*, 4>& TypesToSkip){ // Desugar the scope qualifier if needed. const Type* scope_type = scope->getAsType(); if (scope_type) { // this is not a namespace, so we might need to desugar NestedNameSpecifier* outer_scope = scope->getPrefix(); if (outer_scope) { outer_scope = GetPartiallyDesugaredNNS(Ctx, outer_scope, TypesToSkip); } QualType desugared = Transform::GetPartiallyDesugaredType(Ctx, QualType(scope_type,0), TypesToSkip, /*fullyQualify=*/false); // NOTE: Should check whether the type has changed or not. return NestedNameSpecifier::Create(Ctx,outer_scope, false /* template keyword wanted */, desugared.getTypePtr()); } return scope; } static NestedNameSpecifier* CreateNestedNameSpecifier(const ASTContext& Ctx, NamespaceDecl* cl) { NamespaceDecl* outer = llvm::dyn_cast_or_null<NamespaceDecl>(cl->getDeclContext()); if (outer && outer->getName().size()) { NestedNameSpecifier* outerNNS = CreateNestedNameSpecifier(Ctx,outer); return NestedNameSpecifier::Create(Ctx,outerNNS, cl); } else { return NestedNameSpecifier::Create(Ctx, 0, /* no starting '::'*/ cl); } } static NestedNameSpecifier* CreateNestedNameSpecifier(const ASTContext& Ctx, TagDecl *cl) { NamedDecl* outer = llvm::dyn_cast_or_null<NamedDecl>(cl->getDeclContext()); if (outer && outer->getName().size()) { NestedNameSpecifier *outerNNS; if (cl->getDeclContext()->isNamespace()) { outerNNS = CreateNestedNameSpecifier(Ctx, llvm::dyn_cast<NamespaceDecl>(outer)); } else { outerNNS = CreateNestedNameSpecifier(Ctx, llvm::dyn_cast<TagDecl>(outer)); } return NestedNameSpecifier::Create(Ctx,outerNNS, false /* template keyword wanted */, Ctx.getTypeDeclType(cl).getTypePtr()); } else { return NestedNameSpecifier::Create(Ctx, 0, /* no starting '::'*/ false /* template keyword wanted */, Ctx.getTypeDeclType(cl).getTypePtr()); } } QualType Transform::GetPartiallyDesugaredType(const ASTContext& Ctx, QualType QT, const llvm::SmallSet<const Type*, 4>& TypesToSkip, bool fullyQualify /*=true*/){ // If there are no constains - use the standard desugaring. if (!TypesToSkip.size()) return QT.getDesugaredType(Ctx); // In case of Int_t* we need to strip the pointer first, desugar and attach // the pointer once again. if (QT->isPointerType()) { // Get the qualifiers. Qualifiers quals = QT.getQualifiers(); QT = GetPartiallyDesugaredType(Ctx, QT->getPointeeType(), TypesToSkip, fullyQualify); QT = Ctx.getPointerType(QT); // Add back the qualifiers. QT = Ctx.getQualifiedType(QT, quals); } // In case of Int_t& we need to strip the pointer first, desugar and attach // the pointer once again. if (QT->isReferenceType()) { // Get the qualifiers. bool isLValueRefTy = isa<LValueReferenceType>(QT.getTypePtr()); Qualifiers quals = QT.getQualifiers(); QT = GetPartiallyDesugaredType(Ctx, QT->getPointeeType(), TypesToSkip, fullyQualify); // Add the r- or l- value reference type back to the desugared one if (isLValueRefTy) QT = Ctx.getLValueReferenceType(QT); else QT = Ctx.getRValueReferenceType(QT); // Add back the qualifiers. QT = Ctx.getQualifiedType(QT, quals); } while(isa<TypedefType>(QT.getTypePtr())) { if (!TypesToSkip.count(QT.getTypePtr())) QT = QT.getSingleStepDesugaredType(Ctx); else return QT; } NestedNameSpecifier* prefix = 0; const ElaboratedType* etype = llvm::dyn_cast<ElaboratedType>(QT.getTypePtr()); if (etype) { // We have to also desugar the prefix. prefix = GetPartiallyDesugaredNNS(Ctx, etype->getQualifier(), TypesToSkip); QT = QualType(etype->getNamedType().getTypePtr(),QT.getLocalFastQualifiers()); } else if (fullyQualify) { // Let's check whether this type should have been an elaborated type. // in which case we want to add it ... but we can't really preserve // the typedef in this case ... CXXRecordDecl* cl = QT->getAsCXXRecordDecl(); if (cl) { NamedDecl* outer = llvm::dyn_cast_or_null<NamedDecl>(cl->getDeclContext()); if (outer && outer->getName ().size()) { if (cl->getDeclContext()->isNamespace()) { prefix = CreateNestedNameSpecifier(Ctx, llvm::dyn_cast<NamespaceDecl>(outer)); } else { prefix = CreateNestedNameSpecifier(Ctx, llvm::dyn_cast<TagDecl>(outer)); } } } } // In case of template specializations iterate over the arguments and // desugar them as well. if(const TemplateSpecializationType* TST = dyn_cast<const TemplateSpecializationType>(QT.getTypePtr())) { bool mightHaveChanged = false; llvm::SmallVector<TemplateArgument, 4> desArgs; for(TemplateSpecializationType::iterator I = TST->begin(), E = TST->end(); I != E; ++I) { QualType SubTy = I->getAsType(); if (SubTy.isNull()) { desArgs.push_back(*I); continue; } // Check if the type needs more desugaring and recurse. if (isa<TypedefType>(SubTy) || isa<TemplateSpecializationType>(SubTy) || fullyQualify) { mightHaveChanged = true; desArgs.push_back(TemplateArgument(GetPartiallyDesugaredType(Ctx, SubTy, TypesToSkip, fullyQualify))); } else desArgs.push_back(*I); } // If desugaring happened allocate new type in the AST. if (mightHaveChanged) { QT = Ctx.getTemplateSpecializationType(TST->getTemplateName(), desArgs.data(), desArgs.size(), TST->getCanonicalTypeInternal()); } } if (prefix) { QT = Ctx.getElaboratedType(ETK_None,prefix,QT); } return QT; } NamespaceDecl* Lookup::Namespace(Sema* S, const char* Name, DeclContext* Within) { DeclarationName DName = &S->Context.Idents.get(Name); LookupResult R(*S, DName, SourceLocation(), Sema::LookupNestedNameSpecifierName); if (!Within) S->LookupName(R, S->TUScope); else S->LookupQualifiedName(R, Within); if (R.empty()) return 0; R.resolveKind(); return dyn_cast<NamespaceDecl>(R.getFoundDecl()); } NamedDecl* Lookup::Named(Sema* S, const char* Name, DeclContext* Within) { DeclarationName DName = &S->Context.Idents.get(Name); LookupResult R(*S, DName, SourceLocation(), Sema::LookupOrdinaryName, Sema::ForRedeclaration); if (!Within) S->LookupName(R, S->TUScope); else S->LookupQualifiedName(R, Within); if (R.empty()) return 0; R.resolveKind(); return R.getFoundDecl(); } } // end namespace utils } // end namespace cling <commit_msg>Do not use standard desugaring if we need to have the full qualification<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch> //------------------------------------------------------------------------------ #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclarationName.h" #include "clang/Sema/Sema.h" #include "clang/Sema/Lookup.h" using namespace clang; namespace cling { namespace utils { Expr* Synthesize::CStyleCastPtrExpr(Sema* S, QualType Ty, uint64_t Ptr) { ASTContext& Ctx = S->getASTContext(); if (!Ty->isPointerType()) Ty = Ctx.getPointerType(Ty); TypeSourceInfo* TSI = Ctx.CreateTypeSourceInfo(Ty); const llvm::APInt Addr(8 * sizeof(void *), Ptr); Expr* Result = IntegerLiteral::Create(Ctx, Addr, Ctx.UnsignedLongTy, SourceLocation()); Result = S->BuildCStyleCastExpr(SourceLocation(), TSI, SourceLocation(), Result).take(); assert(Result && "Cannot create CStyleCastPtrExpr"); return Result; } static NestedNameSpecifier* GetPartiallyDesugaredNNS(const ASTContext& Ctx, NestedNameSpecifier* scope, const llvm::SmallSet<const Type*, 4>& TypesToSkip){ // Desugar the scope qualifier if needed. const Type* scope_type = scope->getAsType(); if (scope_type) { // this is not a namespace, so we might need to desugar NestedNameSpecifier* outer_scope = scope->getPrefix(); if (outer_scope) { outer_scope = GetPartiallyDesugaredNNS(Ctx, outer_scope, TypesToSkip); } QualType desugared = Transform::GetPartiallyDesugaredType(Ctx, QualType(scope_type,0), TypesToSkip, /*fullyQualify=*/false); // NOTE: Should check whether the type has changed or not. return NestedNameSpecifier::Create(Ctx,outer_scope, false /* template keyword wanted */, desugared.getTypePtr()); } return scope; } static NestedNameSpecifier* CreateNestedNameSpecifier(const ASTContext& Ctx, NamespaceDecl* cl) { NamespaceDecl* outer = llvm::dyn_cast_or_null<NamespaceDecl>(cl->getDeclContext()); if (outer && outer->getName().size()) { NestedNameSpecifier* outerNNS = CreateNestedNameSpecifier(Ctx,outer); return NestedNameSpecifier::Create(Ctx,outerNNS, cl); } else { return NestedNameSpecifier::Create(Ctx, 0, /* no starting '::'*/ cl); } } static NestedNameSpecifier* CreateNestedNameSpecifier(const ASTContext& Ctx, TagDecl *cl) { NamedDecl* outer = llvm::dyn_cast_or_null<NamedDecl>(cl->getDeclContext()); if (outer && outer->getName().size()) { NestedNameSpecifier *outerNNS; if (cl->getDeclContext()->isNamespace()) { outerNNS = CreateNestedNameSpecifier(Ctx, llvm::dyn_cast<NamespaceDecl>(outer)); } else { outerNNS = CreateNestedNameSpecifier(Ctx, llvm::dyn_cast<TagDecl>(outer)); } return NestedNameSpecifier::Create(Ctx,outerNNS, false /* template keyword wanted */, Ctx.getTypeDeclType(cl).getTypePtr()); } else { return NestedNameSpecifier::Create(Ctx, 0, /* no starting '::'*/ false /* template keyword wanted */, Ctx.getTypeDeclType(cl).getTypePtr()); } } QualType Transform::GetPartiallyDesugaredType(const ASTContext& Ctx, QualType QT, const llvm::SmallSet<const Type*, 4>& TypesToSkip, bool fullyQualify /*=true*/){ // If there are no constains - use the standard desugaring. if (!TypesToSkip.size() && !fullyQualify) return QT.getDesugaredType(Ctx); // In case of Int_t* we need to strip the pointer first, desugar and attach // the pointer once again. if (QT->isPointerType()) { // Get the qualifiers. Qualifiers quals = QT.getQualifiers(); QT = GetPartiallyDesugaredType(Ctx, QT->getPointeeType(), TypesToSkip, fullyQualify); QT = Ctx.getPointerType(QT); // Add back the qualifiers. QT = Ctx.getQualifiedType(QT, quals); } // In case of Int_t& we need to strip the pointer first, desugar and attach // the pointer once again. if (QT->isReferenceType()) { // Get the qualifiers. bool isLValueRefTy = isa<LValueReferenceType>(QT.getTypePtr()); Qualifiers quals = QT.getQualifiers(); QT = GetPartiallyDesugaredType(Ctx, QT->getPointeeType(), TypesToSkip, fullyQualify); // Add the r- or l- value reference type back to the desugared one if (isLValueRefTy) QT = Ctx.getLValueReferenceType(QT); else QT = Ctx.getRValueReferenceType(QT); // Add back the qualifiers. QT = Ctx.getQualifiedType(QT, quals); } while(isa<TypedefType>(QT.getTypePtr())) { if (!TypesToSkip.count(QT.getTypePtr())) QT = QT.getSingleStepDesugaredType(Ctx); else return QT; } NestedNameSpecifier* prefix = 0; const ElaboratedType* etype = llvm::dyn_cast<ElaboratedType>(QT.getTypePtr()); if (etype) { // We have to also desugar the prefix. prefix = GetPartiallyDesugaredNNS(Ctx, etype->getQualifier(), TypesToSkip); QT = QualType(etype->getNamedType().getTypePtr(),QT.getLocalFastQualifiers()); } else if (fullyQualify) { // Let's check whether this type should have been an elaborated type. // in which case we want to add it ... but we can't really preserve // the typedef in this case ... CXXRecordDecl* cl = QT->getAsCXXRecordDecl(); if (cl) { NamedDecl* outer = llvm::dyn_cast_or_null<NamedDecl>(cl->getDeclContext()); if (outer && outer->getName ().size()) { if (cl->getDeclContext()->isNamespace()) { prefix = CreateNestedNameSpecifier(Ctx, llvm::dyn_cast<NamespaceDecl>(outer)); } else { prefix = CreateNestedNameSpecifier(Ctx, llvm::dyn_cast<TagDecl>(outer)); } } } } // In case of template specializations iterate over the arguments and // desugar them as well. if(const TemplateSpecializationType* TST = dyn_cast<const TemplateSpecializationType>(QT.getTypePtr())) { bool mightHaveChanged = false; llvm::SmallVector<TemplateArgument, 4> desArgs; for(TemplateSpecializationType::iterator I = TST->begin(), E = TST->end(); I != E; ++I) { QualType SubTy = I->getAsType(); if (SubTy.isNull()) { desArgs.push_back(*I); continue; } // Check if the type needs more desugaring and recurse. if (isa<TypedefType>(SubTy) || isa<TemplateSpecializationType>(SubTy) || fullyQualify) { mightHaveChanged = true; desArgs.push_back(TemplateArgument(GetPartiallyDesugaredType(Ctx, SubTy, TypesToSkip, fullyQualify))); } else desArgs.push_back(*I); } // If desugaring happened allocate new type in the AST. if (mightHaveChanged) { // This lose any qualifiers in the original QT (intentional for now) QT = Ctx.getTemplateSpecializationType(TST->getTemplateName(), desArgs.data(), desArgs.size(), TST->getCanonicalTypeInternal()); } } if (prefix) { QT = Ctx.getElaboratedType(ETK_None,prefix,QT); } return QT; } NamespaceDecl* Lookup::Namespace(Sema* S, const char* Name, DeclContext* Within) { DeclarationName DName = &S->Context.Idents.get(Name); LookupResult R(*S, DName, SourceLocation(), Sema::LookupNestedNameSpecifierName); if (!Within) S->LookupName(R, S->TUScope); else S->LookupQualifiedName(R, Within); if (R.empty()) return 0; R.resolveKind(); return dyn_cast<NamespaceDecl>(R.getFoundDecl()); } NamedDecl* Lookup::Named(Sema* S, const char* Name, DeclContext* Within) { DeclarationName DName = &S->Context.Idents.get(Name); LookupResult R(*S, DName, SourceLocation(), Sema::LookupOrdinaryName, Sema::ForRedeclaration); if (!Within) S->LookupName(R, S->TUScope); else S->LookupQualifiedName(R, Within); if (R.empty()) return 0; R.resolveKind(); return R.getFoundDecl(); } } // end namespace utils } // end namespace cling <|endoftext|>
<commit_before>/* Basic Server code for CMPT 276, Spring 2016. */ #include <exception> #include <iostream> #include <memory> #include <string> #include <unordered_map> #include <utility> #include <vector> #include <cpprest/base_uri.h> #include <cpprest/http_listener.h> #include <cpprest/json.h> #include <pplx/pplxtasks.h> #include <was/common.h> #include <was/storage_account.h> #include <was/table.h> #include "TableCache.h" #include "config.h" #include "make_unique.h" #include "azure_keys.h" using azure::storage::cloud_storage_account; using azure::storage::storage_credentials; using azure::storage::storage_exception; using azure::storage::cloud_table; using azure::storage::cloud_table_client; using azure::storage::edm_type; using azure::storage::entity_property; using azure::storage::table_entity; using azure::storage::table_operation; using azure::storage::table_query; using azure::storage::table_query_iterator; using azure::storage::table_result; using pplx::extensibility::critical_section_t; using pplx::extensibility::scoped_critical_section_t; using std::cin; using std::cout; using std::endl; using std::getline; using std::make_pair; using std::pair; using std::string; using std::unordered_map; using std::vector; using web::http::http_headers; using web::http::http_request; using web::http::methods; using web::http::status_codes; using web::http::uri; using web::json::value; using web::http::experimental::listener::http_listener; using prop_vals_t = vector<pair<string,value>>; constexpr const char* def_url = "http://localhost:34568"; const string create_table {"CreateTable"}; const string delete_table {"DeleteTable"}; const string update_entity {"UpdateEntity"}; const string delete_entity {"DeleteEntity"}; /* Cache of opened tables */ TableCache table_cache {storage_connection_string}; /* Convert properties represented in Azure Storage type to prop_vals_t type. */ prop_vals_t get_properties (const table_entity::properties_type& properties, prop_vals_t values = prop_vals_t {}) { for (const auto v : properties) { if (v.second.property_type() == edm_type::string) { values.push_back(make_pair(v.first, value::string(v.second.string_value()))); } else if (v.second.property_type() == edm_type::datetime) { values.push_back(make_pair(v.first, value::string(v.second.str()))); } else if(v.second.property_type() == edm_type::int32) { values.push_back(make_pair(v.first, value::number(v.second.int32_value()))); } else if(v.second.property_type() == edm_type::int64) { values.push_back(make_pair(v.first, value::number(v.second.int64_value()))); } else if(v.second.property_type() == edm_type::double_floating_point) { values.push_back(make_pair(v.first, value::number(v.second.double_value()))); } else if(v.second.property_type() == edm_type::boolean) { values.push_back(make_pair(v.first, value::boolean(v.second.boolean_value()))); } else { values.push_back(make_pair(v.first, value::string(v.second.str()))); } } return values; } /* Given an HTTP message with a JSON body, return the JSON body as an unordered map of strings to strings. Note that all types of JSON values are returned as strings. Use C++ conversion utilities to convert to numbers or dates as necessary. */ unordered_map<string,string> get_json_body(http_request message) { unordered_map<string,string> results {}; const http_headers& headers {message.headers()}; auto content_type (headers.find("Content-Type")); if (content_type == headers.end() || content_type->second != "application/json") return results; value json{}; message.extract_json(true) .then([&json](value v) -> bool { json = v; return true; }) .wait(); if (json.is_object()) { for (const auto& v : json.as_object()) { if (v.second.is_string()) { results[v.first] = v.second.as_string(); } else { results[v.first] = v.second.serialize(); } } } return results; } /* Top-level routine for processing all HTTP GET requests. GET is the only request that has no command. All operands specify the value(s) to be retrieved. */ void handle_get(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** GET " << path << endl; auto paths = uri::split_path(path); // Need at least a table name if (paths.size() < 1) { message.reply(status_codes::BadRequest); return; } cloud_table table {table_cache.lookup_table(paths[0])}; if ( ! table.exists()) { message.reply(status_codes::NotFound); return; } // GET all entries in table if (paths.size() == 1) { table_query query {}; table_query_iterator end; table_query_iterator it = table.execute_query(query); vector<value> key_vec; while (it != end) { cout << "Key: " << it->partition_key() << " / " << it->row_key() << endl; prop_vals_t keys { make_pair("Partition",value::string(it->partition_key())), make_pair("Row", value::string(it->row_key()))}; keys = get_properties(it->properties(), keys); key_vec.push_back(value::object(keys)); ++it; } message.reply(status_codes::OK, value::array(key_vec)); return; } // GET specific entry: Partition == paths[1], Row == paths[2] table_operation retrieve_operation {table_operation::retrieve_entity(paths[1], paths[2])}; table_result retrieve_result {table.execute(retrieve_operation)}; cout << "HTTP code: " << retrieve_result.http_status_code() << endl; if (retrieve_result.http_status_code() == status_codes::NotFound) { message.reply(status_codes::NotFound); return; } table_entity entity {retrieve_result.entity()}; table_entity::properties_type properties {entity.properties()}; // If the entity has any properties, return them as JSON prop_vals_t values (get_properties(properties)); if (values.size() > 0) message.reply(status_codes::OK, value::object(values)); else message.reply(status_codes::OK); } /* Top-level routine for processing all HTTP POST requests. */ void handle_post(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** POST " << path << endl; auto paths = uri::split_path(path); // Need at least an operation and a table name if (paths.size() < 2) { message.reply(status_codes::BadRequest); return; } string table_name {paths[1]}; cloud_table table {table_cache.lookup_table(table_name)}; // Create table (idempotent if table exists) if (paths[0] == create_table) { cout << "Create " << table_name << endl; bool created {table.create_if_not_exists()}; cout << "Administrative table URI " << table.uri().primary_uri().to_string() << endl; if (created) message.reply(status_codes::Created); else message.reply(status_codes::Accepted); } else { message.reply(status_codes::BadRequest); } } /* Top-level routine for processing all HTTP PUT requests. */ void handle_put(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** PUT " << path << endl; auto paths = uri::split_path(path); // Need at least an operation, table name, partition, and row if (paths.size() < 4) { message.reply(status_codes::BadRequest); return; } cloud_table table {table_cache.lookup_table(paths[1])}; if ( ! table.exists()) { message.reply(status_codes::NotFound); return; } table_entity entity {paths[2], paths[3]}; // Update entity if (paths[0] == update_entity) { cout << "Update " << entity.partition_key() << " / " << entity.row_key() << endl; table_entity::properties_type& properties = entity.properties(); for (const auto v : get_json_body(message)) { properties[v.first] = entity_property {v.second}; } table_operation operation {table_operation::insert_or_merge_entity(entity)}; table_result op_result {table.execute(operation)}; message.reply(status_codes::OK); } else { message.reply(status_codes::BadRequest); } } /* Top-level routine for processing all HTTP DELETE requests. */ void handle_delete(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** DELETE " << path << endl; auto paths = uri::split_path(path); // Need at least an operation and table name if (paths.size() < 2) { message.reply(status_codes::BadRequest); return; } string table_name {paths[1]}; cloud_table table {table_cache.lookup_table(table_name)}; // Delete table if (paths[0] == delete_table) { cout << "Delete " << table_name << endl; if ( ! table.exists()) { message.reply(status_codes::NotFound); } table.delete_table(); table_cache.delete_entry(table_name); message.reply(status_codes::OK); } // Delete entity else if (paths[0] == delete_entity) { // For delete entity, also need partition and row if (paths.size() < 4) { message.reply(status_codes::BadRequest); return; } table_entity entity {paths[2], paths[3]}; cout << "Delete " << entity.partition_key() << " / " << entity.row_key()<< endl; table_operation operation {table_operation::delete_entity(entity)}; table_result op_result {table.execute(operation)}; int code {op_result.http_status_code()}; if (code == status_codes::OK || code == status_codes::NoContent) message.reply(status_codes::OK); else message.reply(code); } else { message.reply(status_codes::BadRequest); } } /* Main server routine Install handlers for the HTTP requests and open the listener, which processes each request asynchronously. Wait for a carriage return, then shut the server down. */ int main (int argc, char const * argv[]) { http_listener listener {def_url}; listener.support(methods::GET, &handle_get); listener.support(methods::POST, &handle_post); listener.support(methods::PUT, &handle_put); listener.support(methods::DEL, &handle_delete); listener.open().wait(); // Wait for listener to complete starting cout << "Enter carriage return to stop server." << endl; string line; getline(std::cin, line); // Shut it down listener.close().wait(); cout << "Closed" << endl; } <commit_msg>get partition through specific enrties<commit_after>/* Basic Server code for CMPT 276, Spring 2016. */ #include <exception> #include <iostream> #include <memory> #include <string> #include <unordered_map> #include <utility> #include <vector> #include <string> #include <cpprest/base_uri.h> #include <cpprest/http_listener.h> #include <cpprest/json.h> #include <pplx/pplxtasks.h> #include <was/common.h> #include <was/storage_account.h> #include <was/table.h> #include "TableCache.h" #include "config.h" #include "make_unique.h" #include "azure_keys.h" using azure::storage::cloud_storage_account; using azure::storage::storage_credentials; using azure::storage::storage_exception; using azure::storage::cloud_table; using azure::storage::cloud_table_client; using azure::storage::edm_type; using azure::storage::entity_property; using azure::storage::table_entity; using azure::storage::table_operation; using azure::storage::table_query; using azure::storage::table_query_iterator; using azure::storage::table_result; using pplx::extensibility::critical_section_t; using pplx::extensibility::scoped_critical_section_t; using std::cin; using std::cout; using std::endl; using std::getline; using std::make_pair; using std::pair; using std::string; using std::unordered_map; using std::vector; using web::http::http_headers; using web::http::http_request; using web::http::methods; using web::http::status_codes; using web::http::uri; using web::json::value; using web::http::experimental::listener::http_listener; using prop_vals_t = vector<pair<string,value>>; constexpr const char* def_url = "http://localhost:34568"; const string create_table {"CreateTable"}; const string delete_table {"DeleteTable"}; const string update_entity {"UpdateEntity"}; const string delete_entity {"DeleteEntity"}; /* Cache of opened tables */ TableCache table_cache {storage_connection_string}; /* Convert properties represented in Azure Storage type to prop_vals_t type. */ prop_vals_t get_properties (const table_entity::properties_type& properties, prop_vals_t values = prop_vals_t {}) { for (const auto v : properties) { if (v.second.property_type() == edm_type::string) { values.push_back(make_pair(v.first, value::string(v.second.string_value()))); } else if (v.second.property_type() == edm_type::datetime) { values.push_back(make_pair(v.first, value::string(v.second.str()))); } else if(v.second.property_type() == edm_type::int32) { values.push_back(make_pair(v.first, value::number(v.second.int32_value()))); } else if(v.second.property_type() == edm_type::int64) { values.push_back(make_pair(v.first, value::number(v.second.int64_value()))); } else if(v.second.property_type() == edm_type::double_floating_point) { values.push_back(make_pair(v.first, value::number(v.second.double_value()))); } else if(v.second.property_type() == edm_type::boolean) { values.push_back(make_pair(v.first, value::boolean(v.second.boolean_value()))); } else { values.push_back(make_pair(v.first, value::string(v.second.str()))); } } return values; } /* Given an HTTP message with a JSON body, return the JSON body as an unordered map of strings to strings. Note that all types of JSON values are returned as strings. Use C++ conversion utilities to convert to numbers or dates as necessary. */ unordered_map<string,string> get_json_body(http_request message) { unordered_map<string,string> results {}; const http_headers& headers {message.headers()}; auto content_type (headers.find("Content-Type")); if (content_type == headers.end() || content_type->second != "application/json") return results; value json{}; message.extract_json(true) .then([&json](value v) -> bool { json = v; return true; }) .wait(); if (json.is_object()) { for (const auto& v : json.as_object()) { if (v.second.is_string()) { results[v.first] = v.second.as_string(); } else { results[v.first] = v.second.serialize(); } } } return results; } /* Top-level routine for processing all HTTP GET requests. GET is the only request that has no command. All operands specify the value(s) to be retrieved. */ void handle_get(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** GET " << path << endl; auto paths = uri::split_path(path); // Need at least a table name if (paths.size() < 1) { message.reply(status_codes::BadRequest); return; } cloud_table table {table_cache.lookup_table(paths[0])}; if ( ! table.exists()) { message.reply(status_codes::NotFound); return; } // GET all entries in table if (paths.size() == 1) { table_query query {}; table_query_iterator end; table_query_iterator it = table.execute_query(query); vector<value> key_vec; while (it != end) { cout << "Key: " << it->partition_key() << " / " << it->row_key() << endl; prop_vals_t keys { make_pair("Partition",value::string(it->partition_key())), make_pair("Row", value::string(it->row_key()))}; keys = get_properties(it->properties(), keys); key_vec.push_back(value::object(keys)); ++it; } message.reply(status_codes::OK, value::array(key_vec)); return; } // GET specific entry: Partition == paths[1], Row == paths[2] table_operation retrieve_operation {table_operation::retrieve_entity(paths[1], paths[2])}; table_result retrieve_result {table.execute(retrieve_operation)}; cout << "HTTP code: " << retrieve_result.http_status_code() << endl; if (retrieve_result.http_status_code() == status_codes::NotFound) { // if the table does not exist message.reply(status_codes::NotFound); return; } table_entity entity {retrieve_result.entity()}; table_entity::properties_type properties {entity.properties()}; unordered_map<string,string> json_body {get_json_body (message)}; if (json_body.size () > 0) { // There was a body std::vector<string> nameList; for (const auto v : json_body) { // for every pair in json_body (unordered map) // v is a pair<string,string> representing a property in the JSON object if(v.second == "*"){ nameList.push_back(v.first); } } // Do other things for the case where the message had a body // creates query table_query query {}; table_query_iterator end; /* access_condition exisiting = azure::storage::access_condition(); for(int i = 0 ; i < nameList.size() ; i++){ // Construct the query operation for all entities that fit the name static const utility::string_t addition = azure::storage::table_query::generate_filter_condition ( "RowKey", azure::storage::query_comparison_operator::equal, , nameList[i]); query.set_filter_string(query.combine_filter_conditions (exisiting, static const utility::string_t azure::storage::query_logical_operator::op_and, addition)); }*/ // Execute Query table_query_iterator it = table.execute_query(query); vector<value> key_vec; while (it != end) { cout << "Key: " << it->partition_key() << endl; prop_vals_t keys { make_pair("Partition",value::string(it->partition_key()))}; keys = get_properties(it->properties(), keys); key_vec.push_back(value::object(keys)); ++it; } } // If the entity has any properties, return them as JSON prop_vals_t values (get_properties(properties)); if (values.size() > 0) message.reply(status_codes::OK, value::object(values)); else message.reply(status_codes::OK); } /* Top-level routine for processing all HTTP POST requests. */ void handle_post(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** POST " << path << endl; auto paths = uri::split_path(path); // Need at least an operation and a table name if (paths.size() < 2) { message.reply(status_codes::BadRequest); return; } string table_name {paths[1]}; cloud_table table {table_cache.lookup_table(table_name)}; // Create table (idempotent if table exists) if (paths[0] == create_table) { cout << "Create " << table_name << endl; bool created {table.create_if_not_exists()}; cout << "Administrative table URI " << table.uri().primary_uri().to_string() << endl; if (created) message.reply(status_codes::Created); else message.reply(status_codes::Accepted); } else { message.reply(status_codes::BadRequest); } } /* Top-level routine for processing all HTTP PUT requests. */ void handle_put(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** PUT " << path << endl; auto paths = uri::split_path(path); // Need at least an operation, table name, partition, and row if (paths.size() < 4) { message.reply(status_codes::BadRequest); return; } cloud_table table {table_cache.lookup_table(paths[1])}; if ( ! table.exists()) { message.reply(status_codes::NotFound); return; } table_entity entity {paths[2], paths[3]}; // partition and row // Update entity if (paths[0] == update_entity) { cout << "Update " << entity.partition_key() << " / " << entity.row_key() << endl; table_entity::properties_type& properties = entity.properties(); for (const auto v : get_json_body(message)) { properties[v.first] = entity_property {v.second}; } table_operation operation {table_operation::insert_or_merge_entity(entity)}; table_result op_result {table.execute(operation)}; message.reply(status_codes::OK); } else { message.reply(status_codes::BadRequest); } } /* Top-level routine for processing all HTTP DELETE requests. */ void handle_delete(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** DELETE " << path << endl; auto paths = uri::split_path(path); // Need at least an operation and table name if (paths.size() < 2) { message.reply(status_codes::BadRequest); return; } string table_name {paths[1]}; cloud_table table {table_cache.lookup_table(table_name)}; // Delete table if (paths[0] == delete_table) { cout << "Delete " << table_name << endl; if ( ! table.exists()) { message.reply(status_codes::NotFound); } table.delete_table(); table_cache.delete_entry(table_name); message.reply(status_codes::OK); } // Delete entity else if (paths[0] == delete_entity) { // For delete entity, also need partition and row if (paths.size() < 4) { message.reply(status_codes::BadRequest); return; } table_entity entity {paths[2], paths[3]}; cout << "Delete " << entity.partition_key() << " / " << entity.row_key()<< endl; table_operation operation {table_operation::delete_entity(entity)}; table_result op_result {table.execute(operation)}; int code {op_result.http_status_code()}; if (code == status_codes::OK || code == status_codes::NoContent) message.reply(status_codes::OK); else message.reply(code); } else { message.reply(status_codes::BadRequest); } } /* Main server routine Install handlers for the HTTP requests and open the listener, which processes each request asynchronously. Wait for a carriage return, then shut the server down. */ int main (int argc, char const * argv[]) { http_listener listener {def_url}; listener.support(methods::GET, &handle_get); listener.support(methods::POST, &handle_post); listener.support(methods::PUT, &handle_put); listener.support(methods::DEL, &handle_delete); listener.open().wait(); // Wait for listener to complete starting cout << "Enter carriage return to stop server." << endl; string line; getline(std::cin, line); // Shut it down listener.close().wait(); cout << "Closed" << endl; } <|endoftext|>
<commit_before>#include <stan/math/prim/scal.hpp> #include <boost/math/special_functions/fpclassify.hpp> #include <gtest/gtest.h> #include <limits> template <typename T_N, typename T_n> void test_binom_coefficient(const T_N& N, const T_n& n) { using stan::math::binomial_coefficient_log; EXPECT_FLOAT_EQ(lgamma(N + 1) - lgamma(n + 1) - lgamma(N - n + 1), binomial_coefficient_log(N, n)); } TEST(MathFunctions, binomial_coefficient_log) { using stan::math::binomial_coefficient_log; EXPECT_FLOAT_EQ(1.0, exp(binomial_coefficient_log(2.0, 2.0))); EXPECT_FLOAT_EQ(2.0, exp(binomial_coefficient_log(2.0, 1.0))); EXPECT_FLOAT_EQ(3.0, exp(binomial_coefficient_log(3.0, 1.0))); EXPECT_NEAR(3.0, exp(binomial_coefficient_log(3.0, 2.0)), 0.0001); EXPECT_FLOAT_EQ(29979.16, binomial_coefficient_log(100000, 91116)); for (int n = 0; n < 1010; ++n) { test_binom_coefficient(1010, n); test_binom_coefficient(1010.0, n); test_binom_coefficient(1010, static_cast<double>(n)); test_binom_coefficient(1010.0, static_cast<double>(n)); } test_binom_coefficient(1e9, 1e5); // this overflows with boost lgamma and results in NaN comparisons // TODO(SW): investigate // test_binom_coefficient(1e50, 1e45); } TEST(MathFunctions, binomial_coefficient_log_nan) { double nan = std::numeric_limits<double>::quiet_NaN(); EXPECT_PRED1(boost::math::isnan<double>, stan::math::binomial_coefficient_log(2.0, nan)); EXPECT_PRED1(boost::math::isnan<double>, stan::math::binomial_coefficient_log(nan, 2.0)); EXPECT_PRED1(boost::math::isnan<double>, stan::math::binomial_coefficient_log(nan, nan)); } <commit_msg>reenable large number test for binomial_coefficient_log_test<commit_after>#include <stan/math/prim/scal.hpp> #include <boost/math/special_functions/fpclassify.hpp> #include <gtest/gtest.h> #include <limits> #include <cmath> template <typename T_N, typename T_n> void test_binom_coefficient(const T_N& N, const T_n& n) { using stan::math::binomial_coefficient_log; EXPECT_FLOAT_EQ(lgamma(N + 1) - lgamma(n + 1) - lgamma(N - n + 1), binomial_coefficient_log(N, n)); } TEST(MathFunctions, binomial_coefficient_log) { using stan::math::binomial_coefficient_log; EXPECT_FLOAT_EQ(1.0, exp(binomial_coefficient_log(2.0, 2.0))); EXPECT_FLOAT_EQ(2.0, exp(binomial_coefficient_log(2.0, 1.0))); EXPECT_FLOAT_EQ(3.0, exp(binomial_coefficient_log(3.0, 1.0))); EXPECT_NEAR(3.0, exp(binomial_coefficient_log(3.0, 2.0)), 0.0001); EXPECT_FLOAT_EQ(29979.16, binomial_coefficient_log(100000, 91116)); for (int n = 0; n < 1010; ++n) { test_binom_coefficient(1010, n); test_binom_coefficient(1010.0, n); test_binom_coefficient(1010, static_cast<double>(n)); test_binom_coefficient(1010.0, static_cast<double>(n)); } test_binom_coefficient(1e9, 1e5); // NOTE(SW): 2019-05-31 replaced large number test as // this overflows with boost lgamma and results in NaN comparisons // which always fail // test_binom_coefficient(1e50, 1e45); // 1E25 seems the largest number for lgamma from boost to handle test_binom_coefficient(1e25, 1e20); } TEST(MathFunctions, binomial_coefficient_log_nan) { double nan = std::numeric_limits<double>::quiet_NaN(); EXPECT_PRED1(boost::math::isnan<double>, stan::math::binomial_coefficient_log(2.0, nan)); EXPECT_PRED1(boost::math::isnan<double>, stan::math::binomial_coefficient_log(nan, 2.0)); EXPECT_PRED1(boost::math::isnan<double>, stan::math::binomial_coefficient_log(nan, nan)); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: transliteration_Numeric.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2006-09-17 09:32:20 $ * * 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_i18npool.hxx" #include <transliteration_Numeric.hxx> #include <nativenumbersupplier.hxx> #include <defaultnumberingprovider.hxx> using namespace com::sun::star::uno; using namespace rtl; namespace com { namespace sun { namespace star { namespace i18n { sal_Int16 SAL_CALL transliteration_Numeric::getType() throw(RuntimeException) { return TransliterationType::NUMERIC; } OUString SAL_CALL transliteration_Numeric::folding( const OUString& /*inStr*/, sal_Int32 /*startPos*/, sal_Int32 /*nCount*/, Sequence< sal_Int32 >& /*offset*/ ) throw(RuntimeException) { throw (new RuntimeException()); } sal_Bool SAL_CALL transliteration_Numeric::equals( const OUString& /*str1*/, sal_Int32 /*pos1*/, sal_Int32 /*nCount1*/, sal_Int32& /*nMatch1*/, const OUString& /*str2*/, sal_Int32 /*pos2*/, sal_Int32 /*nCount2*/, sal_Int32& /*nMatch2*/ ) throw(RuntimeException) { throw (new RuntimeException()); } Sequence< OUString > SAL_CALL transliteration_Numeric::transliterateRange( const OUString& /*str1*/, const OUString& /*str2*/ ) throw(RuntimeException) { throw (new RuntimeException()); } #define isNumber(c) ((c) >= 0x30 && (c) <= 0x39) #define NUMBER_ZERO 0x30 OUString SAL_CALL transliteration_Numeric::transliterateBullet( const OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, Sequence< sal_Int32 >& offset ) throw(RuntimeException) { sal_Int32 number = -1, j = 0, endPos = startPos + nCount; if (endPos > inStr.getLength()) endPos = inStr.getLength(); rtl_uString* pStr = x_rtl_uString_new_WithLength( nCount, 1 ); // our x_rtl_ustring.h sal_Unicode* out = pStr->buffer; if (useOffset) offset.realloc(nCount); for (sal_Int32 i = startPos; i < endPos; i++) { if (i < endPos && isNumber(inStr[i])) { if (number == -1) { startPos = i; number = (inStr[i] - NUMBER_ZERO); } else { number = number * 10 + (inStr[i] - NUMBER_ZERO); } } else { if (number == 0) { if (useOffset) offset[j] = startPos; out[j++] = NUMBER_ZERO; } if (number > tableSize && !recycleSymbol) { for (sal_Int32 k = startPos; k < i; k++) { if (useOffset) offset[j] = k; out[j++] = inStr[k]; } } else if (number > 0) { if (useOffset) offset[j] = startPos; out[j++] = table[--number % tableSize]; } else if (i < endPos) { if (useOffset) offset[j] = i; out[j++] = inStr[i]; } number = -1; } } out[j] = 0; if (useOffset) offset.realloc(j); return OUString( pStr, SAL_NO_ACQUIRE ); } OUString SAL_CALL transliteration_Numeric::transliterate( const OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, Sequence< sal_Int32 >& offset ) throw(RuntimeException) { if (tableSize) return transliterateBullet( inStr, startPos, nCount, offset); else return NativeNumberSupplier(useOffset).getNativeNumberString( inStr.copy(startPos, nCount), aLocale, nNativeNumberMode, offset ); } sal_Unicode SAL_CALL transliteration_Numeric::transliterateChar2Char( sal_Unicode inChar ) throw(RuntimeException, MultipleCharsOutputException) { if (tableSize) { if (isNumber(inChar)) { sal_Int16 number = inChar - NUMBER_ZERO; if (number <= tableSize || recycleSymbol) return table[--number % tableSize]; } return inChar; } else return NativeNumberSupplier().getNativeNumberChar( inChar, aLocale, nNativeNumberMode ); } } } } } <commit_msg>INTEGRATION: CWS changefileheader (1.7.138); FILE MERGED 2008/03/31 16:01:33 rt 1.7.138.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: transliteration_Numeric.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_i18npool.hxx" #include <transliteration_Numeric.hxx> #include <nativenumbersupplier.hxx> #include <defaultnumberingprovider.hxx> using namespace com::sun::star::uno; using namespace rtl; namespace com { namespace sun { namespace star { namespace i18n { sal_Int16 SAL_CALL transliteration_Numeric::getType() throw(RuntimeException) { return TransliterationType::NUMERIC; } OUString SAL_CALL transliteration_Numeric::folding( const OUString& /*inStr*/, sal_Int32 /*startPos*/, sal_Int32 /*nCount*/, Sequence< sal_Int32 >& /*offset*/ ) throw(RuntimeException) { throw (new RuntimeException()); } sal_Bool SAL_CALL transliteration_Numeric::equals( const OUString& /*str1*/, sal_Int32 /*pos1*/, sal_Int32 /*nCount1*/, sal_Int32& /*nMatch1*/, const OUString& /*str2*/, sal_Int32 /*pos2*/, sal_Int32 /*nCount2*/, sal_Int32& /*nMatch2*/ ) throw(RuntimeException) { throw (new RuntimeException()); } Sequence< OUString > SAL_CALL transliteration_Numeric::transliterateRange( const OUString& /*str1*/, const OUString& /*str2*/ ) throw(RuntimeException) { throw (new RuntimeException()); } #define isNumber(c) ((c) >= 0x30 && (c) <= 0x39) #define NUMBER_ZERO 0x30 OUString SAL_CALL transliteration_Numeric::transliterateBullet( const OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, Sequence< sal_Int32 >& offset ) throw(RuntimeException) { sal_Int32 number = -1, j = 0, endPos = startPos + nCount; if (endPos > inStr.getLength()) endPos = inStr.getLength(); rtl_uString* pStr = x_rtl_uString_new_WithLength( nCount, 1 ); // our x_rtl_ustring.h sal_Unicode* out = pStr->buffer; if (useOffset) offset.realloc(nCount); for (sal_Int32 i = startPos; i < endPos; i++) { if (i < endPos && isNumber(inStr[i])) { if (number == -1) { startPos = i; number = (inStr[i] - NUMBER_ZERO); } else { number = number * 10 + (inStr[i] - NUMBER_ZERO); } } else { if (number == 0) { if (useOffset) offset[j] = startPos; out[j++] = NUMBER_ZERO; } if (number > tableSize && !recycleSymbol) { for (sal_Int32 k = startPos; k < i; k++) { if (useOffset) offset[j] = k; out[j++] = inStr[k]; } } else if (number > 0) { if (useOffset) offset[j] = startPos; out[j++] = table[--number % tableSize]; } else if (i < endPos) { if (useOffset) offset[j] = i; out[j++] = inStr[i]; } number = -1; } } out[j] = 0; if (useOffset) offset.realloc(j); return OUString( pStr, SAL_NO_ACQUIRE ); } OUString SAL_CALL transliteration_Numeric::transliterate( const OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, Sequence< sal_Int32 >& offset ) throw(RuntimeException) { if (tableSize) return transliterateBullet( inStr, startPos, nCount, offset); else return NativeNumberSupplier(useOffset).getNativeNumberString( inStr.copy(startPos, nCount), aLocale, nNativeNumberMode, offset ); } sal_Unicode SAL_CALL transliteration_Numeric::transliterateChar2Char( sal_Unicode inChar ) throw(RuntimeException, MultipleCharsOutputException) { if (tableSize) { if (isNumber(inChar)) { sal_Int16 number = inChar - NUMBER_ZERO; if (number <= tableSize || recycleSymbol) return table[--number % tableSize]; } return inChar; } else return NativeNumberSupplier().getNativeNumberChar( inChar, aLocale, nNativeNumberMode ); } } } } } <|endoftext|>
<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "iceoryx_utils/cxx/optional.hpp" #include "iceoryx_utils/cxx/vector.hpp" #include "iceoryx_utils/design_pattern/creation.hpp" #include "iceoryx_utils/internal/units/duration.hpp" #include <atomic> #include <condition_variable> #include <cstdint> #include <limits> #include <signal.h> #include <sys/time.h> #include <time.h> namespace iox { namespace posix { enum class TimerError { NO_ERROR, TIMER_NOT_INITIALIZED, NO_VALID_CALLBACK, KERNEL_ALLOC_FAILED, INVALID_ARGUMENTS, ALLOC_MEM_FAILED, NO_PERMISSION, INVALID_POINTER, NO_TIMER_TO_DELETE, INTERNAL_LOGIC_ERROR }; using namespace iox::units::duration_literals; /// @brief Interface for timers on POSIX operating systems /// @note Can't be copied or moved as operating system has a pointer to this object. It needs to be ensured that this /// object lives longer than timeToWait, otherwise the operating system will unregister the timer /// @concurrent not thread safe /// /// @code /// posix::Timer& TiborTheTimer = posix::Timer::getInstance(100_ms, [&]() { fooBar++; }); /// /// // Start a periodic timer /// TiborTheTimer.start(true); /// // [.. wait ..] /// // Timer fires after 100_ms and calls the lambda which increments fooBar /// /// TiborTheTimer.stop(); /// /// @endcode class Timer { public: enum class RunMode { ONCE, PERIODIC }; private: static constexpr size_t SIZE_OF_COMBINDED_INDEX_AND_DESCRIPTOR = sizeof(uint32_t); static constexpr size_t SIZE_OF_SIGVAL_INT = sizeof(int); static_assert(SIZE_OF_SIGVAL_INT >= SIZE_OF_COMBINDED_INDEX_AND_DESCRIPTOR, "size of sigval_int is to low"); static constexpr uint32_t MAX_NUMBER_OF_CALLBACK_HANDLES = 100; static_assert(MAX_NUMBER_OF_CALLBACK_HANDLES <= std::numeric_limits<uint8_t>::max(), "number of callback handles exceeds max index value"); class OsTimer; struct OsTimerCallbackHandle { static constexpr uint32_t MAX_DESCRIPTOR_VALUE{(2 ^ 24) - 1}; static sigval indexAndDescriptorToSigval(uint8_t index, uint32_t descriptor); static uint8_t sigvalToIndex(sigval intVal); static uint32_t sigvalToDescriptor(sigval intVal); void incrementDescriptor(); std::mutex m_accessMutex; /// @brief the descriptor is unique for a timer_t in OsTimer, if this handle is recycled, the descriptor needs /// to be incremented first std::atomic<uint32_t> m_descriptor{0}; std::atomic<bool> m_inUse{false}; std::atomic<bool> m_isTimerActive{false}; OsTimer* m_timer{nullptr}; }; class OsTimer { #ifdef __QNX__ static constexpr timer_t INVALID_TIMER_ID = 0; #else static constexpr timer_t INVALID_TIMER_ID = nullptr; #endif public: /// @brief Wrapper that can be registered with the operating system static void callbackHelper(sigval data); OsTimer(units::Duration timeToWait, std::function<void()> callback) noexcept; OsTimer(const OsTimer&) = delete; OsTimer(OsTimer&&) = delete; OsTimer& operator=(const OsTimer&) = delete; OsTimer& operator=(OsTimer&&) = delete; /// @brief D'tor virtual ~OsTimer() noexcept; /// @brief Starts the timer /// /// The callback is called by the operating system after the time has expired. /// /// @param[in] periodic - can be a periodic timer if set to true, default false /// @note Shall only be called when callback is given cxx::expected<TimerError> start(const RunMode runMode) noexcept; /// @brief Disarms the timer /// @note Shall only be called when callback is given, guarantee after stop() call is callback is immediately /// called or never at all cxx::expected<TimerError> stop() noexcept; /// @brief Disarms the timer, assigns a new timeToWait value and arms the timer /// @note Shall only be called when callback is given cxx::expected<TimerError> restart(const units::Duration timeToWait, const RunMode runMode) noexcept; // @brief Returns the time until the timer expires the next time /// @note Shall only be called when callback is given cxx::expected<units::Duration, TimerError> timeUntilExpiration() noexcept; /// @brief In case the callback is not immediately called by the operating system, getOverruns() returns the /// additional overruns that happended in the delay interval /// @note Shall only be called when callback is given cxx::expected<uint64_t, TimerError> getOverruns() noexcept; /// @brief Returns true if the construction of the object was successful bool hasError() const noexcept; /// @brief Returns the error that occured on constructing the object cxx::error<TimerError> getError() const noexcept; private: /// @brief Call the user-defined callback /// @note This call is wrapped in a plain C function void executeCallback() noexcept; private: /// @brief Duration after the timer calls the user-defined callback function units::Duration m_timeToWait; /// @brief Stores the user-defined callback std::function<void()> m_callback; /// @brief Identifier for the timer in the operating system timer_t m_timerId{INVALID_TIMER_ID}; uint8_t m_callbackHandleIndex{0}; /// @todo will be obsolete with creation pattern /// @brief Bool that signals whether the object is fully initalized bool m_isInitialized{false}; /// @todo creation pattern /// @brief If an error happened during creation the value is stored in here TimerError m_errorValue{TimerError::NO_ERROR}; static OsTimerCallbackHandle s_callbackHandlePool[MAX_NUMBER_OF_CALLBACK_HANDLES]; }; public: /// @brief Creates a timer without an operating system callback /// /// Creates a light-weight timer object that can be used with /// * hasExpiredComparedToCreationTime() /// * resetCreationTime() /// /// @param[in] timeToWait - How long should be waited? /// @note Does not set up an operating system timer, but uses CLOCK_REALTIME instead /// @todo refactor this cTor and its functionality to a class called StopWatch Timer(units::Duration timeToWait) noexcept; /// @brief Creates a timer with an operating system callback /// /// Initially the timer is stopped. /// /// @param[in] timeToWait - How long should be waited? /// @param[in] callback - Function called after timeToWait (User needs to ensure lifetime of function till stop() /// call) /// @note Operating systems needs a valid reference to this object, hence DesignPattern::Creation can't be used Timer(units::Duration timeToWait, std::function<void()> callback) noexcept; /// @brief creates Duration from the result of clock_gettime(CLOCK_REALTIME, ...) /// @return if the clock_gettime call failed TimerError is returned otherwise Duration /// @todo maybe move this to a clock implementation? static cxx::expected<units::Duration, TimerError> now() noexcept; /// @brief Move or semantics are forbidden as address of object is not allowed to change Timer(const Timer& other) = delete; /// @brief Move or semantics are forbidden as address of object is not allowed to change Timer(Timer&& other) = delete; /// @brief Move or semantics are forbidden as address of object is not allowed to change Timer& operator=(const Timer& other) = delete; /// @brief Move or semantics are forbidden as address of object is not allowed to change Timer& operator=(Timer&& other) = delete; /// @brief D'tor virtual ~Timer() noexcept = default; /// @brief Starts the timer /// /// The callback is called by the operating system after the time has expired. /// /// @param[in] periodic - can be a periodic timer if set to true, default false /// @note Shall only be called when callback is given /// @todo replace bool with enum; SingleShot and Periodic cxx::expected<TimerError> start(const RunMode runMode) noexcept; /// @brief Disarms the timer /// @note Shall only be called when callback is given, guarantee after stop() call is callback is immediately /// called or never at all cxx::expected<TimerError> stop() noexcept; /// @brief Disarms the timer, assigns a new timeToWait value and arms the timer /// @note Shall only be called when callback is given cxx::expected<TimerError> restart(const units::Duration timeToWait, const RunMode runMode) noexcept; /// @brief Resets the internal creation time void resetCreationTime() noexcept; /// @brief Checks if the timer has expired compared to its creation time /// @return Is the elapsed time larger than timeToWait? bool hasExpiredComparedToCreationTime() noexcept; // @brief Returns the time until the timer expires the next time /// @note Shall only be called when callback is given cxx::expected<units::Duration, TimerError> timeUntilExpiration() noexcept; /// @brief In case the callback is not immediately called by the operating system, getOverruns() returns the /// additional overruns that happended in the delay interval /// @note Shall only be called when callback is given cxx::expected<uint64_t, TimerError> getOverruns() noexcept; /// @brief Returns true if the construction of the object was successful bool hasError() const noexcept; /// @brief Returns the error that occured on constructing the object cxx::error<TimerError> getError() const noexcept; private: cxx::optional<OsTimer> m_osTimer; /// @brief Converts errnum to TimerError static cxx::error<TimerError> createErrorFromErrno(const int errnum) noexcept; /// @brief Duration after the timer calls the user-defined callback function units::Duration m_timeToWait; /// @brief Time when the timer object was created units::Duration m_creationTime; /// @brief If an error happened during creation the value is stored in here TimerError m_errorValue{TimerError::NO_ERROR}; }; } // namespace posix } // namespace iox <commit_msg>iox-#17 Update timer usage in example<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "iceoryx_utils/cxx/optional.hpp" #include "iceoryx_utils/cxx/vector.hpp" #include "iceoryx_utils/design_pattern/creation.hpp" #include "iceoryx_utils/internal/units/duration.hpp" #include <atomic> #include <condition_variable> #include <cstdint> #include <limits> #include <signal.h> #include <sys/time.h> #include <time.h> namespace iox { namespace posix { enum class TimerError { NO_ERROR, TIMER_NOT_INITIALIZED, NO_VALID_CALLBACK, KERNEL_ALLOC_FAILED, INVALID_ARGUMENTS, ALLOC_MEM_FAILED, NO_PERMISSION, INVALID_POINTER, NO_TIMER_TO_DELETE, INTERNAL_LOGIC_ERROR }; using namespace iox::units::duration_literals; /// @brief Interface for timers on POSIX operating systems /// @note Can't be copied or moved as operating system has a pointer to this object. It needs to be ensured that this /// object lives longer than timeToWait, otherwise the operating system will unregister the timer /// @concurrent not thread safe /// /// @code /// posix::Timer TiborTheTimer{100_ms, [&]() { fooBar++; }}; /// /// // Start a periodic timer /// TiborTheTimer.start(true); /// // [.. wait ..] /// // Timer fires after 100_ms and calls the lambda which increments fooBar /// /// TiborTheTimer.stop(); /// /// @endcode class Timer { public: enum class RunMode { ONCE, PERIODIC }; private: static constexpr size_t SIZE_OF_COMBINDED_INDEX_AND_DESCRIPTOR = sizeof(uint32_t); static constexpr size_t SIZE_OF_SIGVAL_INT = sizeof(int); static_assert(SIZE_OF_SIGVAL_INT >= SIZE_OF_COMBINDED_INDEX_AND_DESCRIPTOR, "size of sigval_int is to low"); static constexpr uint32_t MAX_NUMBER_OF_CALLBACK_HANDLES = 100; static_assert(MAX_NUMBER_OF_CALLBACK_HANDLES <= std::numeric_limits<uint8_t>::max(), "number of callback handles exceeds max index value"); class OsTimer; struct OsTimerCallbackHandle { static constexpr uint32_t MAX_DESCRIPTOR_VALUE{(2 ^ 24) - 1}; static sigval indexAndDescriptorToSigval(uint8_t index, uint32_t descriptor); static uint8_t sigvalToIndex(sigval intVal); static uint32_t sigvalToDescriptor(sigval intVal); void incrementDescriptor(); std::mutex m_accessMutex; /// @brief the descriptor is unique for a timer_t in OsTimer, if this handle is recycled, the descriptor needs /// to be incremented first std::atomic<uint32_t> m_descriptor{0}; std::atomic<bool> m_inUse{false}; std::atomic<bool> m_isTimerActive{false}; OsTimer* m_timer{nullptr}; }; class OsTimer { #ifdef __QNX__ static constexpr timer_t INVALID_TIMER_ID = 0; #else static constexpr timer_t INVALID_TIMER_ID = nullptr; #endif public: /// @brief Wrapper that can be registered with the operating system static void callbackHelper(sigval data); OsTimer(units::Duration timeToWait, std::function<void()> callback) noexcept; OsTimer(const OsTimer&) = delete; OsTimer(OsTimer&&) = delete; OsTimer& operator=(const OsTimer&) = delete; OsTimer& operator=(OsTimer&&) = delete; /// @brief D'tor virtual ~OsTimer() noexcept; /// @brief Starts the timer /// /// The callback is called by the operating system after the time has expired. /// /// @param[in] periodic - can be a periodic timer if set to true, default false /// @note Shall only be called when callback is given cxx::expected<TimerError> start(const RunMode runMode) noexcept; /// @brief Disarms the timer /// @note Shall only be called when callback is given, guarantee after stop() call is callback is immediately /// called or never at all cxx::expected<TimerError> stop() noexcept; /// @brief Disarms the timer, assigns a new timeToWait value and arms the timer /// @note Shall only be called when callback is given cxx::expected<TimerError> restart(const units::Duration timeToWait, const RunMode runMode) noexcept; // @brief Returns the time until the timer expires the next time /// @note Shall only be called when callback is given cxx::expected<units::Duration, TimerError> timeUntilExpiration() noexcept; /// @brief In case the callback is not immediately called by the operating system, getOverruns() returns the /// additional overruns that happended in the delay interval /// @note Shall only be called when callback is given cxx::expected<uint64_t, TimerError> getOverruns() noexcept; /// @brief Returns true if the construction of the object was successful bool hasError() const noexcept; /// @brief Returns the error that occured on constructing the object cxx::error<TimerError> getError() const noexcept; private: /// @brief Call the user-defined callback /// @note This call is wrapped in a plain C function void executeCallback() noexcept; private: /// @brief Duration after the timer calls the user-defined callback function units::Duration m_timeToWait; /// @brief Stores the user-defined callback std::function<void()> m_callback; /// @brief Identifier for the timer in the operating system timer_t m_timerId{INVALID_TIMER_ID}; uint8_t m_callbackHandleIndex{0}; /// @todo will be obsolete with creation pattern /// @brief Bool that signals whether the object is fully initalized bool m_isInitialized{false}; /// @todo creation pattern /// @brief If an error happened during creation the value is stored in here TimerError m_errorValue{TimerError::NO_ERROR}; static OsTimerCallbackHandle s_callbackHandlePool[MAX_NUMBER_OF_CALLBACK_HANDLES]; }; public: /// @brief Creates a timer without an operating system callback /// /// Creates a light-weight timer object that can be used with /// * hasExpiredComparedToCreationTime() /// * resetCreationTime() /// /// @param[in] timeToWait - How long should be waited? /// @note Does not set up an operating system timer, but uses CLOCK_REALTIME instead /// @todo refactor this cTor and its functionality to a class called StopWatch Timer(units::Duration timeToWait) noexcept; /// @brief Creates a timer with an operating system callback /// /// Initially the timer is stopped. /// /// @param[in] timeToWait - How long should be waited? /// @param[in] callback - Function called after timeToWait (User needs to ensure lifetime of function till stop() /// call) /// @note Operating systems needs a valid reference to this object, hence DesignPattern::Creation can't be used Timer(units::Duration timeToWait, std::function<void()> callback) noexcept; /// @brief creates Duration from the result of clock_gettime(CLOCK_REALTIME, ...) /// @return if the clock_gettime call failed TimerError is returned otherwise Duration /// @todo maybe move this to a clock implementation? static cxx::expected<units::Duration, TimerError> now() noexcept; /// @brief Move or semantics are forbidden as address of object is not allowed to change Timer(const Timer& other) = delete; /// @brief Move or semantics are forbidden as address of object is not allowed to change Timer(Timer&& other) = delete; /// @brief Move or semantics are forbidden as address of object is not allowed to change Timer& operator=(const Timer& other) = delete; /// @brief Move or semantics are forbidden as address of object is not allowed to change Timer& operator=(Timer&& other) = delete; /// @brief D'tor virtual ~Timer() noexcept = default; /// @brief Starts the timer /// /// The callback is called by the operating system after the time has expired. /// /// @param[in] periodic - can be a periodic timer if set to true, default false /// @note Shall only be called when callback is given /// @todo replace bool with enum; SingleShot and Periodic cxx::expected<TimerError> start(const RunMode runMode) noexcept; /// @brief Disarms the timer /// @note Shall only be called when callback is given, guarantee after stop() call is callback is immediately /// called or never at all cxx::expected<TimerError> stop() noexcept; /// @brief Disarms the timer, assigns a new timeToWait value and arms the timer /// @note Shall only be called when callback is given cxx::expected<TimerError> restart(const units::Duration timeToWait, const RunMode runMode) noexcept; /// @brief Resets the internal creation time void resetCreationTime() noexcept; /// @brief Checks if the timer has expired compared to its creation time /// @return Is the elapsed time larger than timeToWait? bool hasExpiredComparedToCreationTime() noexcept; // @brief Returns the time until the timer expires the next time /// @note Shall only be called when callback is given cxx::expected<units::Duration, TimerError> timeUntilExpiration() noexcept; /// @brief In case the callback is not immediately called by the operating system, getOverruns() returns the /// additional overruns that happended in the delay interval /// @note Shall only be called when callback is given cxx::expected<uint64_t, TimerError> getOverruns() noexcept; /// @brief Returns true if the construction of the object was successful bool hasError() const noexcept; /// @brief Returns the error that occured on constructing the object cxx::error<TimerError> getError() const noexcept; private: cxx::optional<OsTimer> m_osTimer; /// @brief Converts errnum to TimerError static cxx::error<TimerError> createErrorFromErrno(const int errnum) noexcept; /// @brief Duration after the timer calls the user-defined callback function units::Duration m_timeToWait; /// @brief Time when the timer object was created units::Duration m_creationTime; /// @brief If an error happened during creation the value is stored in here TimerError m_errorValue{TimerError::NO_ERROR}; }; } // namespace posix } // namespace iox <|endoftext|>
<commit_before>//=========================================== // Lumina-DE source code // Copyright (c) 2014, Ken Moore // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #include "FODialog.h" #include "ui_FODialog.h" #include <QApplication> #include <QFontMetrics> FODialog::FODialog(QWidget *parent) : QDialog(parent), ui(new Ui::FODialog){ ui->setupUi(this); //load the designer file ui->label->setText(tr("Calculating")); ui->progressBar->setVisible(false); ui->push_stop->setIcon( LXDG::findIcon("edit-delete","") ); WorkThread = new QThread(); Worker = new FOWorker(); connect(Worker, SIGNAL(startingItem(int,int,QString,QString)), this, SLOT(UpdateItem(int,int,QString,QString)) ); connect(Worker, SIGNAL(finished(QStringList)), this, SLOT(WorkDone(QStringList)) ); Worker->moveToThread(WorkThread); WorkThread->start(); //Make sure this dialog is centered on the parent if(parent!=0){ QPoint ctr = parent->geometry().center(); this->move( ctr.x()-(this->width()/2), ctr.y()-(this->height()/2) ); } this->show(); } FODialog::~FODialog(){ Worker->stopped = true; //just in case it might still be running when closed WorkThread->quit(); WorkThread->wait(); delete Worker; //delete WorkThread; } void FODialog::setOverwrite(bool ovw){ if(ovw){ Worker->overwrite = 1; } else{ Worker->overwrite = 0; } } //Public "start" functions void FODialog::RemoveFiles(QStringList paths){ Worker->ofiles = paths; Worker->isRM = true; if(CheckOverwrite()){ QTimer::singleShot(10,Worker, SLOT(slotStartOperations())); }else{ this->close(); } } void FODialog::CopyFiles(QStringList oldPaths, QStringList newPaths){ //same permissions as old files if(oldPaths.length() == newPaths.length()){ Worker->ofiles = oldPaths; Worker->nfiles = newPaths; } Worker->isCP=true; if(CheckOverwrite()){ QTimer::singleShot(10,Worker, SLOT(slotStartOperations())); }else{ this->close(); } } void FODialog::RestoreFiles(QStringList oldPaths, QStringList newPaths){ //user/group rw permissions if(oldPaths.length() == newPaths.length()){ Worker->ofiles = oldPaths; Worker->nfiles = newPaths; } Worker->isRESTORE = true; if(CheckOverwrite()){ QTimer::singleShot(10,Worker, SLOT(slotStartOperations())); }else{ this->close(); } } void FODialog::MoveFiles(QStringList oldPaths, QStringList newPaths){ //no change in permissions if(oldPaths.length() == newPaths.length()){ Worker->ofiles = oldPaths; \ Worker->nfiles = newPaths; } Worker->isMV=true; if(CheckOverwrite()){ QTimer::singleShot(10,Worker, SLOT(slotStartOperations())); }else{ this->close(); } } bool FODialog::CheckOverwrite(){ bool ok = true; if(!Worker->isRM && Worker->overwrite==-1){ //Check if the new files already exist, and prompt for action QStringList existing; for(int i=0; i<Worker->nfiles.length(); i++){ if(QFile::exists(Worker->nfiles[i])){ existing << Worker->nfiles[i].section("/",-1); } } if(!existing.isEmpty()){ //Prompt for whether to overwrite, not overwrite, or cancel QMessageBox::StandardButton ans = QMessageBox::question(this, tr("Overwrite Files?"), tr("Do you want to overwrite the existing files?")+"\n"+tr("Note: It will just add a number to the filename otherwise.")+"\n\n"+existing.join(", "), QMessageBox::YesToAll | QMessageBox::NoToAll | QMessageBox::Cancel, QMessageBox::NoToAll); if(ans==QMessageBox::NoToAll){ Worker->overwrite = 0; } //don't overwrite else if(ans==QMessageBox::YesToAll){ Worker->overwrite = 1; } //overwrite else{ ok = false; } //cancel operations } } QApplication::processEvents(); QApplication::processEvents(); return ok; } void FODialog::UpdateItem(int cur, int tot, QString oitem, QString nitem){ ui->progressBar->setRange(0,tot); ui->progressBar->setValue(cur); ui->progressBar->setVisible(true); QString msg; if(Worker->isRM){ msg = tr("Removing: %1"); } else if(Worker->isCP){ msg = tr("Copying: %1 to %2"); } else if(Worker->isRESTORE){ msg = tr("Restoring: %1 as %2"); } else if(Worker->isMV){ msg = tr("Moving: %1 to %2"); } if(msg.contains("%2")){ msg = msg.arg(oitem.section("/",-1), nitem.section("/",-1)); }else{ msg = msg.arg(oitem.section("/",-1)); } msg = ui->label->fontMetrics().elidedText(msg, Qt::ElideRight, ui->label->width()); ui->label->setText( msg ); } void FODialog::WorkDone(QStringList errlist){ if(!errlist.isEmpty()){ QString msg; if(Worker->isRM){ msg = tr("Could not remove these files:"); } else if(Worker->isCP){ msg = tr("Could not copy these files:"); } else if(Worker->isRESTORE){ msg = tr("Could not restore these files:"); } else if(Worker->isMV){ msg = tr("Could not move these files:"); } QMessageBox::warning(this, tr("File Errors"), msg+"\n\n"+errlist.join("\n")); } noerrors = errlist.isEmpty(); this->close(); } void FODialog::on_push_stop_clicked(){ Worker->stopped = true; } // =================== // ==== FOWorker Class ==== // =================== QStringList FOWorker::subfiles(QString dirpath, bool dirsfirst){ //NOTE: dirpath (input) is always the first/last item in the output as well! QStringList out; if(dirsfirst){ out << dirpath; } if( QFileInfo(dirpath).isDir() ){ QDir dir(dirpath); if(dirsfirst){ //Now recursively add any subdirectories and their contents QStringList subdirs = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden, QDir::NoSort); for(int i=0; i<subdirs.length(); i++){ out << subfiles(dir.absoluteFilePath(subdirs[i]), dirsfirst); } } //List the files QStringList files = dir.entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::Hidden, QDir::NoSort); for(int i=0; i<files.length(); i++){ out << dir.absoluteFilePath(files[i]); } if(!dirsfirst){ //Now recursively add any subdirectories and their contents QStringList subdirs = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden, QDir::NoSort); for(int i=0; i<subdirs.length(); i++){ out << subfiles(dir.absoluteFilePath(subdirs[i]), dirsfirst); } } } if(!dirsfirst){ out << dirpath; } return out; } QString FOWorker::newFileName(QString path){ int num=1; QString extension = path.section("/",-1).section(".",-1); if( path.section("/",-1) == "."+extension || extension ==path.section("/",-1) ){ extension.clear(); } //just a hidden file without extension or directory if(!extension.isEmpty() ){ extension.prepend("."); path.chop(extension.length()); } while( QFile::exists(path+"-"+QString::number(num)+extension) ){ num++; } return QString(path+"-"+QString::number(num)+extension); } QStringList FOWorker::removeItem(QString path, bool recursive){ //qDebug() << "Remove Path:" << path; QStringList items; if(recursive){ items = subfiles(path,false); } else{ items << path; } //only the given path //qDebug() << " - Subfiles:" << items; QStringList err; for(int i=0; i<items.length(); i++){ if(QFileInfo(items[i]).isDir()){ if(items[i]==path){ //Current Directory Removal QDir dir; if( !dir.rmdir(items[i]) ){ err << items[i]; } }else{ //Recursive Directory Removal err << removeItem(items[i], recursive); } }else{ //Simple File Removal if( !QFile::remove(items[i]) ){ err << items[i]; } } } return err; } QStringList FOWorker::copyItem(QString oldpath, QString newpath){ QStringList err; if(oldpath == newpath){ return err; } //copy something onto itself - just skip it if(QFileInfo(oldpath).isDir()){ //Create a new directory with the same name (no way to copy dir+contents) QDir dir; if( !dir.mkpath(newpath) ){ err << oldpath; } }else{ //Copy the file and reset permissions as necessary if( !QFile::copy(oldpath, newpath) ){ err << oldpath; } else{ if(isCP){ QFile::setPermissions(newpath, QFile::permissions(oldpath)); //Nothing special for copies at the moment (might be something we run into later) }else if(isRESTORE){ QFile::setPermissions(newpath, QFile::permissions(oldpath)); //Nothing special for restores at the moment (might be something we run into later) } } } return err; } // ==== PRIVATE SLOTS ==== void FOWorker::slotStartOperations(){ //qDebug() << "Start File operations" << isRM << isCP << isMV << ofiles << nfiles; //Now setup the UI /*ui->progressBar->setRange(0,ofiles.length()); ui->progressBar->setValue(0); ui->progressBar->setVisible(true); QApplication::processEvents();*/ /*if(!isRM && overwrite==-1){ //Check if the new files already exist, and prompt for action QStringList existing; for(int i=0; i<nfiles.length(); i++){ if(QFile::exists(nfiles[i])){ existing << nfiles[i].section("/",-1); } } if(!existing.isEmpty()){ //Prompt for whether to overwrite, not overwrite, or cancel QMessageBox::StandardButton ans = QMessageBox::question(this, tr("Overwrite Files?"), tr("Do you want to overwrite the existing files?")+"\n"+tr("Note: It will just add a number to the filename otherwise.")+"\n\n"+existing.join(", "), QMessageBox::YesToAll | QMessageBox::NoToAll | QMessageBox::Cancel, QMessageBox::NoToAll); if(ans==QMessageBox::NoToAll){ overwrite = 0; } //don't overwrite else if(ans==QMessageBox::YesToAll){ overwrite = 1; } //overwrite else{ emit finished(QStringList()); return; } //cancel operations } }*/ //Get the complete number of items to be operated on (better tracking) QStringList olist, nlist; //old/new list to actually be used (not inputs - modified/added as necessary) for(int i=0; i<ofiles.length() && !stopped; i++){ if(isRM){ //only old files olist << subfiles(ofiles[i], false); //dirs need to be last for removals }else if(isCP || isRESTORE){ if(QFile::exists(nfiles[i])){ if(!overwrite){ nfiles[i] = newFileName(nfiles[i]); //prompt for new file name up front before anything starts } } QStringList subs = subfiles(ofiles[i], true); //dirs need to be first for additions for(int s=0; s<subs.length(); s++){ olist << subs[s]; QString newsub = subs[s].section(ofiles[i],0,100, QString::SectionSkipEmpty); newsub.prepend(nfiles[i]); nlist << newsub; } }else{ //Move/rename if( nfiles[i].startsWith(ofiles[i]+"/") ){ //This is trying to move a directory into itself (not possible) // Example: move "~/mydir" -> "~/mydir/mydir2" QStringList err; err << tr("Invalid Move") << QString(tr("It is not possible to move a directory into itself. Please make a copy of the directory instead.\n\nOld Location: %1\nNew Location: %2")).arg(ofiles[i], nfiles[i]); emit finished(err); return; }else{ //Check for existance of the new name if(QFile::exists(nfiles[i])){ if(!overwrite){ nfiles[i] = newFileName(nfiles[i]); //prompt for new file name up front before anything starts } } //no changes necessary olist << ofiles[i]; nlist << nfiles[i]; } } } //Now start iterating over the operations QStringList errlist; for(int i=0; i<olist.length() && !stopped; i++){ if(isRM){ /*ui->label->setText( QString(tr("Removing: %1")).arg(olist[i].section("/",-1)) ); QApplication::processEvents();*/ emit startingItem(i+1,olist.length(), olist[i], ""); errlist << removeItem(olist[i]); }else if(isCP || isRESTORE){ /*ui->label->setText( QString(tr("Copying: %1 to %2")).arg(olist[i].section("/",-1), nlist[i].section("/",-1)) ); QApplication::processEvents();*/ emit startingItem(i+1,olist.length(), olist[i],nlist[i]); if(QFile::exists(nlist[i])){ if(overwrite){ errlist << removeItem(nlist[i], true); //recursively remove the file/dir since we are supposed to overwrite it } } //If a parent directory fails to copy, skip all the children as well (they will also fail) //QApplication::processEvents(); if( !errlist.contains(olist[i].section("/",0,-1)) ){ errlist << copyItem(olist[i], nlist[i]); } }else if(isMV){ /*ui->label->setText( QString(tr("Moving: %1 to %2")).arg(ofiles[i].section("/",-1), nfiles[i].section("/",-1)) ); QApplication::processEvents();*/ emit startingItem(i+1,olist.length(), olist[i], nlist[i]); //Clean up any overwritten files/dirs if(QFile::exists(nlist[i])){ if(overwrite){ errlist << removeItem(nlist[i], true); //recursively remove the file/dir since we are supposed to overwrite it } } //Perform the move if no error yet (including skipping all children) if( !errlist.contains(olist[i].section("/",0,-1)) ){ if( !QFile::rename(ofiles[i], nfiles[i]) ){ errlist << ofiles[i]; } } } //ui->progressBar->setValue(i+1); //QApplication::processEvents(); } //All finished, emit the signal errlist.removeAll(""); //make sure to clear any empty items emit finished(errlist); } <commit_msg>Actually move the file/dir copy onto itself check earlier in the procedure, that way we can't run into the situation where the dir is removed because of the conflicting destination.<commit_after>//=========================================== // Lumina-DE source code // Copyright (c) 2014, Ken Moore // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #include "FODialog.h" #include "ui_FODialog.h" #include <QApplication> #include <QFontMetrics> FODialog::FODialog(QWidget *parent) : QDialog(parent), ui(new Ui::FODialog){ ui->setupUi(this); //load the designer file ui->label->setText(tr("Calculating")); ui->progressBar->setVisible(false); ui->push_stop->setIcon( LXDG::findIcon("edit-delete","") ); WorkThread = new QThread(); Worker = new FOWorker(); connect(Worker, SIGNAL(startingItem(int,int,QString,QString)), this, SLOT(UpdateItem(int,int,QString,QString)) ); connect(Worker, SIGNAL(finished(QStringList)), this, SLOT(WorkDone(QStringList)) ); Worker->moveToThread(WorkThread); WorkThread->start(); //Make sure this dialog is centered on the parent if(parent!=0){ QPoint ctr = parent->geometry().center(); this->move( ctr.x()-(this->width()/2), ctr.y()-(this->height()/2) ); } this->show(); } FODialog::~FODialog(){ Worker->stopped = true; //just in case it might still be running when closed WorkThread->quit(); WorkThread->wait(); delete Worker; //delete WorkThread; } void FODialog::setOverwrite(bool ovw){ if(ovw){ Worker->overwrite = 1; } else{ Worker->overwrite = 0; } } //Public "start" functions void FODialog::RemoveFiles(QStringList paths){ Worker->ofiles = paths; Worker->isRM = true; if(CheckOverwrite()){ QTimer::singleShot(10,Worker, SLOT(slotStartOperations())); }else{ this->close(); } } void FODialog::CopyFiles(QStringList oldPaths, QStringList newPaths){ //same permissions as old files if(oldPaths.length() == newPaths.length()){ Worker->ofiles = oldPaths; Worker->nfiles = newPaths; } Worker->isCP=true; if(CheckOverwrite()){ QTimer::singleShot(10,Worker, SLOT(slotStartOperations())); }else{ this->close(); } } void FODialog::RestoreFiles(QStringList oldPaths, QStringList newPaths){ //user/group rw permissions if(oldPaths.length() == newPaths.length()){ Worker->ofiles = oldPaths; Worker->nfiles = newPaths; } Worker->isRESTORE = true; if(CheckOverwrite()){ QTimer::singleShot(10,Worker, SLOT(slotStartOperations())); }else{ this->close(); } } void FODialog::MoveFiles(QStringList oldPaths, QStringList newPaths){ //no change in permissions if(oldPaths.length() == newPaths.length()){ Worker->ofiles = oldPaths; \ Worker->nfiles = newPaths; } Worker->isMV=true; if(CheckOverwrite()){ QTimer::singleShot(10,Worker, SLOT(slotStartOperations())); }else{ this->close(); } } bool FODialog::CheckOverwrite(){ bool ok = true; if(!Worker->isRM && Worker->overwrite==-1){ //Check if the new files already exist, and prompt for action QStringList existing; for(int i=0; i<Worker->nfiles.length(); i++){ if(QFile::exists(Worker->nfiles[i])){ existing << Worker->nfiles[i].section("/",-1); } } if(!existing.isEmpty()){ //Prompt for whether to overwrite, not overwrite, or cancel QMessageBox::StandardButton ans = QMessageBox::question(this, tr("Overwrite Files?"), tr("Do you want to overwrite the existing files?")+"\n"+tr("Note: It will just add a number to the filename otherwise.")+"\n\n"+existing.join(", "), QMessageBox::YesToAll | QMessageBox::NoToAll | QMessageBox::Cancel, QMessageBox::NoToAll); if(ans==QMessageBox::NoToAll){ Worker->overwrite = 0; } //don't overwrite else if(ans==QMessageBox::YesToAll){ Worker->overwrite = 1; } //overwrite else{ ok = false; } //cancel operations } } QApplication::processEvents(); QApplication::processEvents(); return ok; } void FODialog::UpdateItem(int cur, int tot, QString oitem, QString nitem){ ui->progressBar->setRange(0,tot); ui->progressBar->setValue(cur); ui->progressBar->setVisible(true); QString msg; if(Worker->isRM){ msg = tr("Removing: %1"); } else if(Worker->isCP){ msg = tr("Copying: %1 to %2"); } else if(Worker->isRESTORE){ msg = tr("Restoring: %1 as %2"); } else if(Worker->isMV){ msg = tr("Moving: %1 to %2"); } if(msg.contains("%2")){ msg = msg.arg(oitem.section("/",-1), nitem.section("/",-1)); }else{ msg = msg.arg(oitem.section("/",-1)); } msg = ui->label->fontMetrics().elidedText(msg, Qt::ElideRight, ui->label->width()); ui->label->setText( msg ); } void FODialog::WorkDone(QStringList errlist){ if(!errlist.isEmpty()){ QString msg; if(Worker->isRM){ msg = tr("Could not remove these files:"); } else if(Worker->isCP){ msg = tr("Could not copy these files:"); } else if(Worker->isRESTORE){ msg = tr("Could not restore these files:"); } else if(Worker->isMV){ msg = tr("Could not move these files:"); } QMessageBox::warning(this, tr("File Errors"), msg+"\n\n"+errlist.join("\n")); } noerrors = errlist.isEmpty(); this->close(); } void FODialog::on_push_stop_clicked(){ Worker->stopped = true; } // =================== // ==== FOWorker Class ==== // =================== QStringList FOWorker::subfiles(QString dirpath, bool dirsfirst){ //NOTE: dirpath (input) is always the first/last item in the output as well! QStringList out; if(dirsfirst){ out << dirpath; } if( QFileInfo(dirpath).isDir() ){ QDir dir(dirpath); if(dirsfirst){ //Now recursively add any subdirectories and their contents QStringList subdirs = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden, QDir::NoSort); for(int i=0; i<subdirs.length(); i++){ out << subfiles(dir.absoluteFilePath(subdirs[i]), dirsfirst); } } //List the files QStringList files = dir.entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::Hidden, QDir::NoSort); for(int i=0; i<files.length(); i++){ out << dir.absoluteFilePath(files[i]); } if(!dirsfirst){ //Now recursively add any subdirectories and their contents QStringList subdirs = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden, QDir::NoSort); for(int i=0; i<subdirs.length(); i++){ out << subfiles(dir.absoluteFilePath(subdirs[i]), dirsfirst); } } } if(!dirsfirst){ out << dirpath; } return out; } QString FOWorker::newFileName(QString path){ int num=1; QString extension = path.section("/",-1).section(".",-1); if( path.section("/",-1) == "."+extension || extension ==path.section("/",-1) ){ extension.clear(); } //just a hidden file without extension or directory if(!extension.isEmpty() ){ extension.prepend("."); path.chop(extension.length()); } while( QFile::exists(path+"-"+QString::number(num)+extension) ){ num++; } return QString(path+"-"+QString::number(num)+extension); } QStringList FOWorker::removeItem(QString path, bool recursive){ //qDebug() << "Remove Path:" << path; QStringList items; if(recursive){ items = subfiles(path,false); } else{ items << path; } //only the given path //qDebug() << " - Subfiles:" << items; QStringList err; for(int i=0; i<items.length(); i++){ if(QFileInfo(items[i]).isDir()){ if(items[i]==path){ //Current Directory Removal QDir dir; if( !dir.rmdir(items[i]) ){ err << items[i]; } }else{ //Recursive Directory Removal err << removeItem(items[i], recursive); } }else{ //Simple File Removal if( !QFile::remove(items[i]) ){ err << items[i]; } } } return err; } QStringList FOWorker::copyItem(QString oldpath, QString newpath){ QStringList err; if(oldpath == newpath){ return err; } //copy something onto itself - just skip it if(QFileInfo(oldpath).isDir()){ //Create a new directory with the same name (no way to copy dir+contents) QDir dir; if( !dir.mkpath(newpath) ){ err << oldpath; } }else{ //Copy the file and reset permissions as necessary if( !QFile::copy(oldpath, newpath) ){ err << oldpath; } else{ if(isCP){ QFile::setPermissions(newpath, QFile::permissions(oldpath)); //Nothing special for copies at the moment (might be something we run into later) }else if(isRESTORE){ QFile::setPermissions(newpath, QFile::permissions(oldpath)); //Nothing special for restores at the moment (might be something we run into later) } } } return err; } // ==== PRIVATE SLOTS ==== void FOWorker::slotStartOperations(){ //qDebug() << "Start File operations" << isRM << isCP << isMV << ofiles << nfiles; //Now setup the UI /*ui->progressBar->setRange(0,ofiles.length()); ui->progressBar->setValue(0); ui->progressBar->setVisible(true); QApplication::processEvents();*/ /*if(!isRM && overwrite==-1){ //Check if the new files already exist, and prompt for action QStringList existing; for(int i=0; i<nfiles.length(); i++){ if(QFile::exists(nfiles[i])){ existing << nfiles[i].section("/",-1); } } if(!existing.isEmpty()){ //Prompt for whether to overwrite, not overwrite, or cancel QMessageBox::StandardButton ans = QMessageBox::question(this, tr("Overwrite Files?"), tr("Do you want to overwrite the existing files?")+"\n"+tr("Note: It will just add a number to the filename otherwise.")+"\n\n"+existing.join(", "), QMessageBox::YesToAll | QMessageBox::NoToAll | QMessageBox::Cancel, QMessageBox::NoToAll); if(ans==QMessageBox::NoToAll){ overwrite = 0; } //don't overwrite else if(ans==QMessageBox::YesToAll){ overwrite = 1; } //overwrite else{ emit finished(QStringList()); return; } //cancel operations } }*/ //Get the complete number of items to be operated on (better tracking) QStringList olist, nlist; //old/new list to actually be used (not inputs - modified/added as necessary) for(int i=0; i<ofiles.length() && !stopped; i++){ if(isRM){ //only old files olist << subfiles(ofiles[i], false); //dirs need to be last for removals }else if(isCP || isRESTORE){ if(nfiles[i] == ofiles[i]){ //Trying to copy a file/dir to itself - skip it continue; } if(QFile::exists(nfiles[i])){ if(!overwrite){ nfiles[i] = newFileName(nfiles[i]); //prompt for new file name up front before anything starts } } QStringList subs = subfiles(ofiles[i], true); //dirs need to be first for additions for(int s=0; s<subs.length(); s++){ olist << subs[s]; QString newsub = subs[s].section(ofiles[i],0,100, QString::SectionSkipEmpty); newsub.prepend(nfiles[i]); nlist << newsub; } }else{ //Move/rename if( nfiles[i].startsWith(ofiles[i]+"/") ){ //This is trying to move a directory into itself (not possible) // Example: move "~/mydir" -> "~/mydir/mydir2" QStringList err; err << tr("Invalid Move") << QString(tr("It is not possible to move a directory into itself. Please make a copy of the directory instead.\n\nOld Location: %1\nNew Location: %2")).arg(ofiles[i], nfiles[i]); emit finished(err); return; }else{ //Check for existance of the new name if(QFile::exists(nfiles[i])){ if(!overwrite){ nfiles[i] = newFileName(nfiles[i]); //prompt for new file name up front before anything starts } } //no changes necessary olist << ofiles[i]; nlist << nfiles[i]; } } } //Now start iterating over the operations QStringList errlist; for(int i=0; i<olist.length() && !stopped; i++){ if(isRM){ /*ui->label->setText( QString(tr("Removing: %1")).arg(olist[i].section("/",-1)) ); QApplication::processEvents();*/ emit startingItem(i+1,olist.length(), olist[i], ""); errlist << removeItem(olist[i]); }else if(isCP || isRESTORE){ /*ui->label->setText( QString(tr("Copying: %1 to %2")).arg(olist[i].section("/",-1), nlist[i].section("/",-1)) ); QApplication::processEvents();*/ emit startingItem(i+1,olist.length(), olist[i],nlist[i]); if(QFile::exists(nlist[i])){ if(overwrite){ errlist << removeItem(nlist[i], true); //recursively remove the file/dir since we are supposed to overwrite it } } //If a parent directory fails to copy, skip all the children as well (they will also fail) //QApplication::processEvents(); if( !errlist.contains(olist[i].section("/",0,-1)) ){ errlist << copyItem(olist[i], nlist[i]); } }else if(isMV){ /*ui->label->setText( QString(tr("Moving: %1 to %2")).arg(ofiles[i].section("/",-1), nfiles[i].section("/",-1)) ); QApplication::processEvents();*/ emit startingItem(i+1,olist.length(), olist[i], nlist[i]); //Clean up any overwritten files/dirs if(QFile::exists(nlist[i])){ if(overwrite){ errlist << removeItem(nlist[i], true); //recursively remove the file/dir since we are supposed to overwrite it } } //Perform the move if no error yet (including skipping all children) if( !errlist.contains(olist[i].section("/",0,-1)) ){ if( !QFile::rename(ofiles[i], nfiles[i]) ){ errlist << ofiles[i]; } } } //ui->progressBar->setValue(i+1); //QApplication::processEvents(); } //All finished, emit the signal errlist.removeAll(""); //make sure to clear any empty items emit finished(errlist); } <|endoftext|>
<commit_before>#include <algorithm> #include <iterator> #include <vector> // Algorithm to be tested std::vector<int> product_except_impl(std::vector<int> data) { // [i] = product data[0..i[ std::vector<int> prod_upto = {1}; std::copy(data.begin(), data.end() -1, std::back_inserter(prod_upto)); std::transform(prod_upto.begin(), prod_upto.end() -1 , prod_upto.begin() +1 , prod_upto.begin() +1 , [](auto prod, auto cur) { return prod * cur; }); // [size-i-1] = product data]i..size-1] std::vector<int> prod_from_rev = {1}; std::copy(data.rbegin(), data.rend() -1, std::back_inserter(prod_from_rev)); std::transform(prod_from_rev.begin(), prod_from_rev.end() -1 , prod_from_rev.begin() +1 , prod_from_rev.begin() +1 , [](auto prod, auto cur) { return prod * cur; }); for (std::size_t i {} ; i != data.size() ; ++i) { data[i] = prod_upto[i] * prod_from_rev[prod_from_rev.size()-i-1]; } return data; } std::vector<int> product_except(std::vector<int> const& data) { return product_except_impl(data); } #include "tests.hpp" <commit_msg>[visual studio][product-except-self] Fix test failure<commit_after>#include <algorithm> #include <iterator> #include <vector> // Algorithm to be tested std::vector<int> product_except_impl(std::vector<int> data) { if (data.empty()) { return {}; } // [i] = product data[0..i[ std::vector<int> prod_upto = {1}; std::copy(data.begin(), data.end() -1, std::back_inserter(prod_upto)); std::transform(prod_upto.begin(), prod_upto.end() -1 , prod_upto.begin() +1 , prod_upto.begin() +1 , [](auto prod, auto cur) { return prod * cur; }); // [size-i-1] = product data]i..size-1] std::vector<int> prod_from_rev = {1}; std::copy(data.rbegin(), data.rend() -1, std::back_inserter(prod_from_rev)); std::transform(prod_from_rev.begin(), prod_from_rev.end() -1 , prod_from_rev.begin() +1 , prod_from_rev.begin() +1 , [](auto prod, auto cur) { return prod * cur; }); for (std::size_t i {} ; i != data.size() ; ++i) { data[i] = prod_upto[i] * prod_from_rev[prod_from_rev.size()-i-1]; } return data; } std::vector<int> product_except(std::vector<int> const& data) { return product_except_impl(data); } #include "tests.hpp" <|endoftext|>
<commit_before>/* * Copyright 2014 Blistud:io */ #include "blieng/path.h" #include <algorithm> #include <iostream> #include <string> #include <vector> #include <cmath> #ifndef M_PI #define M_PI 3.14159 #endif using blieng::Path; Path::Path() { } Path::~Path() { } std::string Path::toString() const { std::string res = ""; bool first = true; for (blieng::Point pt : points) { if (!first) res += ";"; first = false; res += pt.toString(); } return res; } void Path::addPoint(Point pt) { points.push_back(pt); } int Path::getPointIndex(Point point) { int index = 0; for (blieng::Point pt : points) { if (point == pt) return index; ++index; } return -1; } blieng::Point Path::getPointAt(unsigned int index) { if (index >=0 && index < size()) { return points[index]; } return Point(); } void Path::updatePointAt(unsigned int index, Point new_point) { if (index >= points.size()) return; points[index] = new_point; } void Path::updatePoint(Point point, Point new_point) { auto pi = points.begin(); while (pi != points.end()) { if ((*pi) == point) { (*pi).update(new_point); } ++pi; } } void Path::append(Path another) { points.insert(points.end(), another.points.begin(), another.points.end()); } Path Path::combine(Path another) const { Path newpath; newpath.append(*this); newpath.append(another); return newpath; } blieng::Point Path::takeFirst() { if (points.empty()) return blieng::Point(false); blieng::Point res = points.front(); points.erase(points.begin()); return res; } blieng::Point Path::takeLast() { if (points.empty()) return blieng::Point(false); blieng::Point res = points.back(); points.erase(points.end()); return res; } blieng::Point Path::getStart() { if (points.empty()) return blieng::Point(false); return points.front(); } bool Path::isValid() { return !points.empty(); } blieng::Point Path::getEnd() { if (points.empty()) return blieng::Point(false); return points.back(); } void Path::reverse() { std::reverse(points.begin(), points.end()); } Path Path::copy() const { Path newpath; for (blieng::Point pt : points) { newpath.addPoint(pt); } return newpath; } Path Path::reversed() const { Path rev_path = this->copy(); rev_path.reverse(); return rev_path; } double Path::length() const { double len = 0.0; blieng::Point f(false); for (blieng::Point pt : points) { if (f.isValid() && pt != f) { len += f.length(pt); } f = pt; } return len; } double Path::lengthGeo() const { double len = 0.0; blieng::Point f(false); for (blieng::Point pt : points) { if (f.isValid() && pt != f) { len += f.lengthGeo(pt); } f = pt; } return len; } double Path::simpleArea() const { double res = 0; blieng::Point f(false); for (blieng::Point pt : points) { if (f.isValid() && pt != f) { res += f.x * pt.y - f.y * pt.x; } f = pt; } return fabs(res) / 2.0; } template<typename T> std::vector<blieng::Complex> cmplxI(std::pair<blieng::Complex,blieng::Complex> s, T a, blieng::Complex b=blieng::Complex(0,1)) { std::vector<blieng::Complex> res; blieng::Complex c = s.first; blieng::Complex d = s.second; d = d - c; c = c - a; double e = (d * b.conjugate()).imag(); double e2 = e * e; if (! (e * (0 <= e2 && e2 <= e*e))) { return res; } double t2 = (d * c.conjugate()).imag(); blieng::Complex t3 = b / e; blieng::Complex t4 = t3 * t2; double v = e * (b * c.conjugate()).imag(); if (e * (0 <= v && v <= e2)) { res.push_back(t4 + a); } return res; } template<typename T> std::vector<std::pair<T,T>> expandTypes(std::vector<T> inp) { std::vector<std::pair<T,T>> res; for (unsigned int i = 0; i < inp.size(); ++i) { T a = inp[i]; T b; if (i == inp.size() - 1) { b = inp[0]; } else { b = inp[i + 1]; } res.push_back(std::pair<T,T>(a, b)); } return res; } double complexArea(std::vector<blieng::Complex> inp) { auto P = expandTypes<blieng::Complex>(inp); std::vector<double> i_real; for (auto ab : P) { blieng::Complex a = ab.first; blieng::Complex b = ab.second; for (auto e : P) { for (auto i : cmplxI<blieng::Complex>(e, a, b-a)) { i_real.push_back(i.real()); } } } std::sort(i_real.begin(), i_real.end()); auto lr = expandTypes<double>(i_real); lr.pop_back(); std::vector<std::pair<double,double>> bt; double ar = 0; for (auto tlr : lr) { std::vector<double> ij_imag; double l = tlr.first; double r = tlr.second; for (auto e : P) { for (auto i : cmplxI<double>(e, l)) { for (auto j : cmplxI<double>(e, r)) { ij_imag.push_back( ((i + j).conjugate()).imag() ); } } } std::sort(ij_imag.begin(), ij_imag.end()); auto ij_pairs = expandTypes<double>(ij_imag); bool tock = true; for (auto i : ij_pairs) { if (tock) { double b = i.first; double t = i.second; ar += (t-b) * (r - l) /2; } tock ^= true; } } return ar; } double Path::area() const { std::vector<blieng::Complex> tmp; for (auto pt : points) { tmp.push_back(pt.toComplex()); } return complexArea(tmp); } double Path::areaGeo() const { Path tmp; for (auto pt : points) { tmp.addPoint(pt.geoToMeters()); } return tmp.area(); } bool Path::operator==(const Path &other) const { size_t psize = points.size(); if (other.points.size() != psize) return false; auto a = points.cbegin(); auto b = other.points.begin(); while (a != points.cend()) { if (*a != *b) return false; ++a; ++b; } return true; } bool Path::operator!=(const Path &other) const { return !(*this == other); } unsigned int Path::size() const { return points.size(); } double Path::getPartAngle(unsigned int index) const { unsigned int prev = 0; if (index > 0) { prev = index - 1; } else { prev = points.size() - 1; } unsigned int next = index + 1; if (next > size()) { return 0.0; } if (next == size()) { next = 0; } if (prev < 0) { return 0.0; } Point p1 = points[index]; Point p2 = points[next]; Point p3 = points[prev]; double a1 = p1.x - p2.x; double a2 = p1.y - p2.y; double b1 = p1.x - p3.x; double b2 = p1.y - p3.y; double c1 = p3.x - p2.x; double c2 = p3.y - p2.y; double p0c = sqrt(a1 * a1 + a2 * a2); double p1c = sqrt(b1 * b1 + b2 * b2); double p0p1 = sqrt(c1 * c1 + c2 * c2); double angle_rad = acos( (p1c * p1c + p0c * p0c - p0p1 * p0p1) / (2 * p1c * p0c) ); return angle_rad * 180 / M_PI; } <commit_msg>Tidy<commit_after>/* * Copyright 2014 Blistud:io */ #include "blieng/path.h" #include <algorithm> #include <iostream> #include <string> #include <vector> #include <cmath> #ifndef M_PI #define M_PI 3.14159 #endif using blieng::Path; Path::Path() { } Path::~Path() { } std::string Path::toString() const { std::string res = ""; bool first = true; for (blieng::Point pt : points) { if (!first) res += ";"; first = false; res += pt.toString(); } return res; } void Path::addPoint(Point pt) { points.push_back(pt); } int Path::getPointIndex(Point point) { int index = 0; for (blieng::Point pt : points) { if (point == pt) return index; ++index; } return -1; } blieng::Point Path::getPointAt(unsigned int index) { if (index >=0 && index < size()) { return points[index]; } return Point(); } void Path::updatePointAt(unsigned int index, Point new_point) { if (index >= points.size()) return; points[index] = new_point; } void Path::updatePoint(Point point, Point new_point) { auto pi = points.begin(); while (pi != points.end()) { if ((*pi) == point) { (*pi).update(new_point); } ++pi; } } void Path::append(Path another) { points.insert(points.end(), another.points.begin(), another.points.end()); } Path Path::combine(Path another) const { Path newpath; newpath.append(*this); newpath.append(another); return newpath; } blieng::Point Path::takeFirst() { if (points.empty()) return blieng::Point(false); blieng::Point res = points.front(); points.erase(points.begin()); return res; } blieng::Point Path::takeLast() { if (points.empty()) return blieng::Point(false); blieng::Point res = points.back(); points.erase(points.end()); return res; } blieng::Point Path::getStart() { if (points.empty()) return blieng::Point(false); return points.front(); } bool Path::isValid() { return !points.empty(); } blieng::Point Path::getEnd() { if (points.empty()) return blieng::Point(false); return points.back(); } void Path::reverse() { std::reverse(points.begin(), points.end()); } Path Path::copy() const { Path newpath; for (blieng::Point pt : points) { newpath.addPoint(pt); } return newpath; } Path Path::reversed() const { Path rev_path = this->copy(); rev_path.reverse(); return rev_path; } double Path::length() const { double len = 0.0; blieng::Point f(false); for (blieng::Point pt : points) { if (f.isValid() && pt != f) { len += f.length(pt); } f = pt; } return len; } double Path::lengthGeo() const { double len = 0.0; blieng::Point f(false); for (blieng::Point pt : points) { if (f.isValid() && pt != f) { len += f.lengthGeo(pt); } f = pt; } return len; } double Path::simpleArea() const { double res = 0; blieng::Point f(false); for (blieng::Point pt : points) { if (f.isValid() && pt != f) { res += f.x * pt.y - f.y * pt.x; } f = pt; } return fabs(res) / 2.0; } template<typename T> std::vector<blieng::Complex> cmplxI(std::pair<blieng::Complex,blieng::Complex> s, T a, blieng::Complex b=blieng::Complex(0,1)) { std::vector<blieng::Complex> res; blieng::Complex c = s.first; blieng::Complex d = s.second; d = d - c; c = c - a; double e = (d * b.conjugate()).imag(); double e2 = e * e; if (! (e * (0 <= e2 && e2 <= e*e))) { return res; } double t2 = (d * c.conjugate()).imag(); blieng::Complex t3 = b / e; blieng::Complex t4 = t3 * t2; double v = e * (b * c.conjugate()).imag(); if (e * (0 <= v && v <= e2)) { res.push_back(t4 + a); } return res; } template<typename T> std::vector<std::pair<T,T>> expandTypes(std::vector<T> inp) { std::vector<std::pair<T,T>> res; for (unsigned int i = 0; i < inp.size(); ++i) { T a = inp[i]; T b; if (i == inp.size() - 1) { b = inp[0]; } else { b = inp[i + 1]; } res.push_back(std::pair<T,T>(a, b)); } return res; } double complexArea(std::vector<blieng::Complex> inp) { auto P = expandTypes<blieng::Complex>(inp); std::vector<double> i_real; for (auto ab : P) { blieng::Complex a = ab.first; blieng::Complex b = ab.second; for (auto e : P) { for (auto i : cmplxI<blieng::Complex>(e, a, b - a)) { i_real.push_back(i.real()); } } } std::sort(i_real.begin(), i_real.end()); auto lr = expandTypes<double>(i_real); lr.pop_back(); std::vector<std::pair<double,double>> bt; double ar = 0; for (auto tlr : lr) { std::vector<double> ij_imag; double l = tlr.first; double r = tlr.second; for (auto e : P) { for (auto i : cmplxI<double>(e, l)) { for (auto j : cmplxI<double>(e, r)) { ij_imag.push_back(((i + j).conjugate()).imag()); } } } std::sort(ij_imag.begin(), ij_imag.end()); auto ij_pairs = expandTypes<double>(ij_imag); bool tock = true; for (auto i : ij_pairs) { if (tock) { double b = i.first; double t = i.second; ar += (t - b) * (r - l) / 2; } tock ^= true; } } return ar; } double Path::area() const { std::vector<blieng::Complex> tmp; for (auto pt : points) { tmp.push_back(pt.toComplex()); } return complexArea(tmp); } double Path::areaGeo() const { Path tmp; for (auto pt : points) { tmp.addPoint(pt.geoToMeters()); } return tmp.area(); } bool Path::operator==(const Path &other) const { size_t psize = points.size(); if (other.points.size() != psize) return false; auto a = points.cbegin(); auto b = other.points.begin(); while (a != points.cend()) { if (*a != *b) return false; ++a; ++b; } return true; } bool Path::operator!=(const Path &other) const { return !(*this == other); } unsigned int Path::size() const { return points.size(); } double Path::getPartAngle(unsigned int index) const { unsigned int prev = 0; if (index > 0) { prev = index - 1; } else { prev = points.size() - 1; } unsigned int next = index + 1; if (next > size()) { return 0.0; } if (next == size()) { next = 0; } if (prev < 0) { return 0.0; } Point p1 = points[index]; Point p2 = points[next]; Point p3 = points[prev]; double a1 = p1.x - p2.x; double a2 = p1.y - p2.y; double b1 = p1.x - p3.x; double b2 = p1.y - p3.y; double c1 = p3.x - p2.x; double c2 = p3.y - p2.y; double p0c = sqrt(a1 * a1 + a2 * a2); double p1c = sqrt(b1 * b1 + b2 * b2); double p0p1 = sqrt(c1 * c1 + c2 * c2); double angle_rad = acos( (p1c * p1c + p0c * p0c - p0p1 * p0p1) / (2 * p1c * p0c) ); return angle_rad * 180 / M_PI; } <|endoftext|>
<commit_before>#include "test_utils.h" // Test configuration constants (to be loaded from an INI file) bool FTP_TEST_ENABLED; bool SFTP_TEST_ENABLED; bool HTTP_PROXY_TEST_ENABLED; std::string CURL_LOG_FOLDER; std::string SSL_CERT_FILE; std::string SSL_KEY_FILE; std::string SSL_KEY_PWD; std::string FTP_SERVER; unsigned FTP_SERVER_PORT; std::string FTP_USERNAME; std::string FTP_PASSWORD; std::string FTP_REMOTE_FILE; std::string FTP_REMOTE_UPLOAD_FOLDER; std::string FTP_REMOTE_DOWNLOAD_FOLDER; std::string SFTP_SERVER; unsigned SFTP_SERVER_PORT; std::string SFTP_USERNAME; std::string SFTP_PASSWORD; std::string SFTP_REMOTE_FILE; std::string SFTP_REMOTE_UPLOAD_FOLDER; std::string SFTP_REMOTE_DOWNLOAD_FOLDER; std::string PROXY_SERVER; std::string PROXY_SERVER_FAKE; std::mutex g_mtxConsoleMutex; bool GlobalTestInit(const std::string& strConfFile) { CSimpleIniA ini; ini.LoadFile(strConfFile.c_str()); std::string strTmp; strTmp = ini.GetValue("tests", "ftp", ""); std::transform(strTmp.begin(), strTmp.end(), strTmp.begin(), ::toupper); FTP_TEST_ENABLED = (strTmp == "YES") ? true : false; strTmp = ini.GetValue("tests", "sftp", ""); std::transform(strTmp.begin(), strTmp.end(), strTmp.begin(), ::toupper); SFTP_TEST_ENABLED = (strTmp == "YES") ? true : false; strTmp = ini.GetValue("tests", "http-proxy", ""); std::transform(strTmp.begin(), strTmp.end(), strTmp.begin(), ::toupper); HTTP_PROXY_TEST_ENABLED = (strTmp == "YES") ? true : false; // required when a build is generated with the macro DEBUG_CURL CURL_LOG_FOLDER = ini.GetValue("local", "curl_logs_folder", ""); SSL_CERT_FILE = ini.GetValue("local", "ssl_cert_file", ""); SSL_KEY_FILE = ini.GetValue("local", "ssl_key_file", ""); SSL_KEY_PWD = ini.GetValue("local", "ssl_key_pwd", ""); PROXY_SERVER = ini.GetValue("http-proxy", "host", ""); PROXY_SERVER_FAKE = ini.GetValue("http-proxy", "host_invalid", ""); FTP_SERVER = ini.GetValue("ftp", "host", ""); FTP_SERVER_PORT = atoi(ini.GetValue("ftp", "port", "0")); FTP_USERNAME = ini.GetValue("ftp", "username", ""); FTP_PASSWORD = ini.GetValue("ftp", "password", ""); FTP_REMOTE_FILE = ini.GetValue("ftp", "remote_file", ""); FTP_REMOTE_UPLOAD_FOLDER = ini.GetValue("ftp", "remote_upload_folder", ""); FTP_REMOTE_DOWNLOAD_FOLDER = ini.GetValue("ftp", "remote_download_folder", ""); SFTP_SERVER = ini.GetValue("sftp", "host", ""); SFTP_SERVER_PORT = atoi(ini.GetValue("sftp", "port", "0")); SFTP_USERNAME = ini.GetValue("sftp", "username", ""); SFTP_PASSWORD = ini.GetValue("sftp", "password", ""); SFTP_REMOTE_FILE = ini.GetValue("sftp", "remote_file", ""); SFTP_REMOTE_UPLOAD_FOLDER = ini.GetValue("sftp", "remote_upload_folder", ""); SFTP_REMOTE_DOWNLOAD_FOLDER = ini.GetValue("sftp", "remote_download_folder", ""); if (!FTP_REMOTE_UPLOAD_FOLDER.empty() && FTP_REMOTE_UPLOAD_FOLDER.at(FTP_REMOTE_UPLOAD_FOLDER.length() - 1) != '/') { FTP_REMOTE_UPLOAD_FOLDER += '/'; } if (!FTP_REMOTE_DOWNLOAD_FOLDER.empty()) { if (FTP_REMOTE_DOWNLOAD_FOLDER.at(FTP_REMOTE_DOWNLOAD_FOLDER.length() - 1) != '/') FTP_REMOTE_DOWNLOAD_FOLDER += "/*"; else FTP_REMOTE_DOWNLOAD_FOLDER += "*"; } if (!SFTP_REMOTE_UPLOAD_FOLDER.empty() && SFTP_REMOTE_UPLOAD_FOLDER.at(SFTP_REMOTE_UPLOAD_FOLDER.length() - 1) != '/') { SFTP_REMOTE_UPLOAD_FOLDER += '/'; } if (!SFTP_REMOTE_DOWNLOAD_FOLDER.empty()) { if (SFTP_REMOTE_DOWNLOAD_FOLDER.at(SFTP_REMOTE_DOWNLOAD_FOLDER.length() - 1) != '/') SFTP_REMOTE_DOWNLOAD_FOLDER += "/*"; else SFTP_REMOTE_DOWNLOAD_FOLDER += "*"; } if (FTP_TEST_ENABLED && (FTP_SERVER.empty() || FTP_SERVER_PORT == 0) || SFTP_TEST_ENABLED && (SFTP_SERVER.empty() || SFTP_SERVER_PORT == 0) || HTTP_PROXY_TEST_ENABLED && (PROXY_SERVER.empty() || PROXY_SERVER_FAKE.empty()) ) { std::clog << "[ERROR] Check your INI file parameters." " Disable tests that don't have a server/port value." << std::endl; return false; } return true; } void GlobalTestCleanUp(void) { return; } void TimeStampTest(std::ostringstream& ssTimestamp) { time_t tRawTime; tm * tmTimeInfo; time(&tRawTime); tmTimeInfo = localtime(&tRawTime); ssTimestamp << (tmTimeInfo->tm_year) + 1900 << "/" << tmTimeInfo->tm_mon + 1 << "/" << tmTimeInfo->tm_mday << " at " << tmTimeInfo->tm_hour << ":" << tmTimeInfo->tm_min << ":" << tmTimeInfo->tm_sec; } // for uplaod prog. callback, just use DL one and inverse download parameters with upload ones... int TestUPProgressCallback(void* ptr, double dTotalToDownload, double dNowDownloaded, double dTotalToUpload, double dNowUploaded) { return TestDLProgressCallback(ptr, dTotalToUpload, dNowUploaded, dTotalToDownload, dNowDownloaded); } int TestDLProgressCallback(void* ptr, double dTotalToDownload, double dNowDownloaded, double dTotalToUpload, double dNowUploaded) { // ensure that the file to be downloaded is not empty // because that would cause a division by zero error later on if (dTotalToDownload <= 0.0) return 0; // how wide you want the progress meter to be const int iTotalDots = 20; double dFractionDownloaded = dNowDownloaded / dTotalToDownload; // part of the progressmeter that's already "full" int iDots = static_cast<int>(round(dFractionDownloaded * iTotalDots)); // create the "meter" int iDot = 0; std::cout << static_cast<unsigned>(dFractionDownloaded * 100) << "% ["; // part that's full already for (; iDot < iDots; iDot++) std::cout << "="; // remaining part (spaces) for (; iDot < iTotalDots; iDot++) std::cout << " "; // and back to line begin - do not forget the fflush to avoid output buffering problems! std::cout << "] \r" << std::flush; // if you don't return 0, the transfer will be aborted - see the documentation return 0; } long GetGMTOffset() { time_t now = time(nullptr); struct tm gm = *gmtime(&now); time_t gmt = mktime(&gm); struct tm loc = *localtime(&now); time_t local = mktime(&loc); return static_cast<long>(difftime(local, gmt)); } bool GetFileTime(const char* const & pszFilePath, time_t& tLastModificationTime) { FILE* pFile = fopen(pszFilePath, "rb"); if (pFile != nullptr) { struct stat file_info; #ifndef LINUX if (fstat(_fileno(pFile), &file_info) == 0) #else if (fstat(fileno(pFile), &file_info) == 0) #endif { tLastModificationTime = file_info.st_mtime; return true; } } return false; } <commit_msg>Make paranthesis clearer<commit_after>#include "test_utils.h" // Test configuration constants (to be loaded from an INI file) bool FTP_TEST_ENABLED; bool SFTP_TEST_ENABLED; bool HTTP_PROXY_TEST_ENABLED; std::string CURL_LOG_FOLDER; std::string SSL_CERT_FILE; std::string SSL_KEY_FILE; std::string SSL_KEY_PWD; std::string FTP_SERVER; unsigned FTP_SERVER_PORT; std::string FTP_USERNAME; std::string FTP_PASSWORD; std::string FTP_REMOTE_FILE; std::string FTP_REMOTE_UPLOAD_FOLDER; std::string FTP_REMOTE_DOWNLOAD_FOLDER; std::string SFTP_SERVER; unsigned SFTP_SERVER_PORT; std::string SFTP_USERNAME; std::string SFTP_PASSWORD; std::string SFTP_REMOTE_FILE; std::string SFTP_REMOTE_UPLOAD_FOLDER; std::string SFTP_REMOTE_DOWNLOAD_FOLDER; std::string PROXY_SERVER; std::string PROXY_SERVER_FAKE; std::mutex g_mtxConsoleMutex; bool GlobalTestInit(const std::string& strConfFile) { CSimpleIniA ini; ini.LoadFile(strConfFile.c_str()); std::string strTmp; strTmp = ini.GetValue("tests", "ftp", ""); std::transform(strTmp.begin(), strTmp.end(), strTmp.begin(), ::toupper); FTP_TEST_ENABLED = (strTmp == "YES") ? true : false; strTmp = ini.GetValue("tests", "sftp", ""); std::transform(strTmp.begin(), strTmp.end(), strTmp.begin(), ::toupper); SFTP_TEST_ENABLED = (strTmp == "YES") ? true : false; strTmp = ini.GetValue("tests", "http-proxy", ""); std::transform(strTmp.begin(), strTmp.end(), strTmp.begin(), ::toupper); HTTP_PROXY_TEST_ENABLED = (strTmp == "YES") ? true : false; // required when a build is generated with the macro DEBUG_CURL CURL_LOG_FOLDER = ini.GetValue("local", "curl_logs_folder", ""); SSL_CERT_FILE = ini.GetValue("local", "ssl_cert_file", ""); SSL_KEY_FILE = ini.GetValue("local", "ssl_key_file", ""); SSL_KEY_PWD = ini.GetValue("local", "ssl_key_pwd", ""); PROXY_SERVER = ini.GetValue("http-proxy", "host", ""); PROXY_SERVER_FAKE = ini.GetValue("http-proxy", "host_invalid", ""); FTP_SERVER = ini.GetValue("ftp", "host", ""); FTP_SERVER_PORT = atoi(ini.GetValue("ftp", "port", "0")); FTP_USERNAME = ini.GetValue("ftp", "username", ""); FTP_PASSWORD = ini.GetValue("ftp", "password", ""); FTP_REMOTE_FILE = ini.GetValue("ftp", "remote_file", ""); FTP_REMOTE_UPLOAD_FOLDER = ini.GetValue("ftp", "remote_upload_folder", ""); FTP_REMOTE_DOWNLOAD_FOLDER = ini.GetValue("ftp", "remote_download_folder", ""); SFTP_SERVER = ini.GetValue("sftp", "host", ""); SFTP_SERVER_PORT = atoi(ini.GetValue("sftp", "port", "0")); SFTP_USERNAME = ini.GetValue("sftp", "username", ""); SFTP_PASSWORD = ini.GetValue("sftp", "password", ""); SFTP_REMOTE_FILE = ini.GetValue("sftp", "remote_file", ""); SFTP_REMOTE_UPLOAD_FOLDER = ini.GetValue("sftp", "remote_upload_folder", ""); SFTP_REMOTE_DOWNLOAD_FOLDER = ini.GetValue("sftp", "remote_download_folder", ""); if (!FTP_REMOTE_UPLOAD_FOLDER.empty() && FTP_REMOTE_UPLOAD_FOLDER.at(FTP_REMOTE_UPLOAD_FOLDER.length() - 1) != '/') { FTP_REMOTE_UPLOAD_FOLDER += '/'; } if (!FTP_REMOTE_DOWNLOAD_FOLDER.empty()) { if (FTP_REMOTE_DOWNLOAD_FOLDER.at(FTP_REMOTE_DOWNLOAD_FOLDER.length() - 1) != '/') FTP_REMOTE_DOWNLOAD_FOLDER += "/*"; else FTP_REMOTE_DOWNLOAD_FOLDER += "*"; } if (!SFTP_REMOTE_UPLOAD_FOLDER.empty() && SFTP_REMOTE_UPLOAD_FOLDER.at(SFTP_REMOTE_UPLOAD_FOLDER.length() - 1) != '/') { SFTP_REMOTE_UPLOAD_FOLDER += '/'; } if (!SFTP_REMOTE_DOWNLOAD_FOLDER.empty()) { if (SFTP_REMOTE_DOWNLOAD_FOLDER.at(SFTP_REMOTE_DOWNLOAD_FOLDER.length() - 1) != '/') SFTP_REMOTE_DOWNLOAD_FOLDER += "/*"; else SFTP_REMOTE_DOWNLOAD_FOLDER += "*"; } if ((FTP_TEST_ENABLED && (FTP_SERVER.empty() || FTP_SERVER_PORT == 0)) || (SFTP_TEST_ENABLED && (SFTP_SERVER.empty() || SFTP_SERVER_PORT == 0)) || (HTTP_PROXY_TEST_ENABLED && (PROXY_SERVER.empty() || PROXY_SERVER_FAKE.empty())) ) { std::clog << "[ERROR] Check your INI file parameters." " Disable tests that don't have a server/port value." << std::endl; return false; } return true; } void GlobalTestCleanUp(void) { return; } void TimeStampTest(std::ostringstream& ssTimestamp) { time_t tRawTime; tm * tmTimeInfo; time(&tRawTime); tmTimeInfo = localtime(&tRawTime); ssTimestamp << (tmTimeInfo->tm_year) + 1900 << "/" << tmTimeInfo->tm_mon + 1 << "/" << tmTimeInfo->tm_mday << " at " << tmTimeInfo->tm_hour << ":" << tmTimeInfo->tm_min << ":" << tmTimeInfo->tm_sec; } // for uplaod prog. callback, just use DL one and inverse download parameters with upload ones... int TestUPProgressCallback(void* ptr, double dTotalToDownload, double dNowDownloaded, double dTotalToUpload, double dNowUploaded) { return TestDLProgressCallback(ptr, dTotalToUpload, dNowUploaded, dTotalToDownload, dNowDownloaded); } int TestDLProgressCallback(void* ptr, double dTotalToDownload, double dNowDownloaded, double dTotalToUpload, double dNowUploaded) { // ensure that the file to be downloaded is not empty // because that would cause a division by zero error later on if (dTotalToDownload <= 0.0) return 0; // how wide you want the progress meter to be const int iTotalDots = 20; double dFractionDownloaded = dNowDownloaded / dTotalToDownload; // part of the progressmeter that's already "full" int iDots = static_cast<int>(round(dFractionDownloaded * iTotalDots)); // create the "meter" int iDot = 0; std::cout << static_cast<unsigned>(dFractionDownloaded * 100) << "% ["; // part that's full already for (; iDot < iDots; iDot++) std::cout << "="; // remaining part (spaces) for (; iDot < iTotalDots; iDot++) std::cout << " "; // and back to line begin - do not forget the fflush to avoid output buffering problems! std::cout << "] \r" << std::flush; // if you don't return 0, the transfer will be aborted - see the documentation return 0; } long GetGMTOffset() { time_t now = time(nullptr); struct tm gm = *gmtime(&now); time_t gmt = mktime(&gm); struct tm loc = *localtime(&now); time_t local = mktime(&loc); return static_cast<long>(difftime(local, gmt)); } bool GetFileTime(const char* const & pszFilePath, time_t& tLastModificationTime) { FILE* pFile = fopen(pszFilePath, "rb"); if (pFile != nullptr) { struct stat file_info; #ifndef LINUX if (fstat(_fileno(pFile), &file_info) == 0) #else if (fstat(fileno(pFile), &file_info) == 0) #endif { tLastModificationTime = file_info.st_mtime; return true; } } return false; } <|endoftext|>
<commit_before>// // DynamicVoiceManager.cpp // C700 // // Created by osoumen on 2014/11/30. // // #include "DynamicVoiceManager.h" //----------------------------------------------------------------------------- DynamicVoiceManager::DynamicVoiceManager() : mVoiceLimit(8) { } //----------------------------------------------------------------------------- DynamicVoiceManager::~DynamicVoiceManager() { } //----------------------------------------------------------------------------- void DynamicVoiceManager::Initialize(int voiceLimit) { mVoiceLimit = voiceLimit; for (int i=0; i<16; i++) { mChNoteOns[i] = 0; mChLimit[i] = 127; } } //----------------------------------------------------------------------------- void DynamicVoiceManager::Reset() { mPlayVo.clear(); mWaitVo.clear(); for(int i=0;i<mVoiceLimit;i++){ pushWaitVo(i); } for (int i=0; i<MAX_VOICE; i++) { mVoCh[i] = 0; mVoPrio[i] = 64; mVoUniqueID[i] = 0; mVoKeyOn[i] = false; } } //----------------------------------------------------------------------------- void DynamicVoiceManager::ChangeVoiceLimit(int voiceLimit) { if ( voiceLimit < mVoiceLimit ) { //空きボイスリストから削除する for ( int i=voiceLimit; i<mVoiceLimit; i++ ) { mWaitVo.remove(i); } } if ( voiceLimit > mVoiceLimit ) { //空きボイスを追加する for ( int i=mVoiceLimit; i<voiceLimit; i++ ) { pushWaitVo(i); } } mVoiceLimit = voiceLimit; } //----------------------------------------------------------------------------- int DynamicVoiceManager::AllocVoice(int prio, int ch, int uniqueID, bool monoMode, int *releasedCh, bool *isLegato) { int v = -1; *releasedCh = -1; *isLegato = false; if (monoMode) { v = ch & 0x07; // 固定のchを確保 if (IsPlayingVoice(v)) { if (mVoCh[v] == ch) { // レガートで鳴らした音 // キーオン前に2回叩かれた場合は最後のノートオンだけが有効になるように if (mVoKeyOn[v]) { *isLegato = true; } } else { // 別のchの発音がすでにある場合 mPlayVo.remove(v); *releasedCh = mVoCh[v]; mChNoteOns[mVoCh[v]]--; } } else { mWaitVo.remove(v); } } else { if (mChNoteOns[ch] >= mChLimit[ch]) { // ch発音数を超えてたら、そのchの音を一つ止めて次の音を鳴らす v = StealVoice(ch); if (v != -1) { mPlayVo.remove(v); *releasedCh = mVoCh[v]; mChNoteOns[mVoCh[v]]--; } } else { // 超えてない場合は、後着優先で優先度の低い音を消す v = FindVoice(); if (v >= MAX_VOICE) { //空きがなくてどこかを止めた v -= MAX_VOICE; mPlayVo.remove(v); *releasedCh = mVoCh[v]; mChNoteOns[mVoCh[v]]--; } else if (v >= 0) { mWaitVo.remove(v); } } } if (v != -1) { mVoCh[v] = ch; mVoPrio[v] = prio; mVoKeyOn[v] = false; mVoUniqueID[v] = uniqueID; if (*isLegato == false) { mPlayVo.push_back(v); mChNoteOns[ch]++; } } return v; } //----------------------------------------------------------------------------- int DynamicVoiceManager::ReleaseVoice(int relPrio, int ch, int uniqueID, int *relVo) { int stops = 0; std::list<int>::iterator it = mPlayVo.begin(); while (it != mPlayVo.end()) { int vo = *it; if ( mVoUniqueID[vo] == uniqueID ) { if (mVoKeyOn[vo]) { mVoUniqueID[vo] = 0; mVoPrio[vo] = relPrio; mVoKeyOn[vo] = false; } if ( vo < mVoiceLimit ) { mWaitVo.push_back(vo); } it = mPlayVo.erase(it); stops++; mChNoteOns[ch]--; *relVo = vo; break; // 2重鳴りはホストに任せる //continue; } it++; } return stops; } //----------------------------------------------------------------------------- void DynamicVoiceManager::SetChLimit(int ch, int value) { mChLimit[ch & 0xf] = value; } //----------------------------------------------------------------------------- int DynamicVoiceManager::GetChLimit(int ch) { return mChLimit[ch & 0xf]; } //----------------------------------------------------------------------------- int DynamicVoiceManager::GetNoteOns(int ch) { return mChNoteOns[ch & 0xf]; } //----------------------------------------------------------------------------- void DynamicVoiceManager::SetKeyOn(int vo) { // TODO: voがAlloc済みかどうかチェック mVoKeyOn[vo] = true; } //----------------------------------------------------------------------------- bool DynamicVoiceManager::IsKeyOn(int vo) { return mVoKeyOn[vo]; } //----------------------------------------------------------------------------- void DynamicVoiceManager::pushWaitVo(int vo) { mWaitVo.push_back(vo); mVoCh[vo] = 0; mVoPrio[vo] = 0; } //----------------------------------------------------------------------------- int DynamicVoiceManager::FindFreeVoice() { int v=-1; //空きボイスを探す if ( mWaitVo.size() > 0 ) { v = mWaitVo.front(); mWaitVo.pop_front(); } return v; } //----------------------------------------------------------------------------- bool DynamicVoiceManager::IsPlayingVoice(int v) { std::list<int>::iterator it = mPlayVo.begin(); while (it != mPlayVo.end()) { int vo = *it; if (vo == v) { return true; } it++; } return false; } //----------------------------------------------------------------------------- int DynamicVoiceManager::StealVoice(int ch) { int v=-1; int prio_min = 0x7fff; std::list<int>::reverse_iterator it = mPlayVo.rbegin(); while (it != mPlayVo.rend()) { int vo = *it; if ( (mVoPrio[vo] <= prio_min) && (mVoCh[vo] == ch) ) { prio_min = mVoPrio[vo]; v = vo; } it++; } return v; } //----------------------------------------------------------------------------- int DynamicVoiceManager::FindVoice(int ch) { int v=-1; int prio_min = 0x7fff; std::list<int>::reverse_iterator it = mPlayVo.rbegin(); while (it != mPlayVo.rend()) { int vo = *it; bool chMatch = (mVoCh[vo] == ch) ? true:false; if (ch == -1) { chMatch = true; } if ( (mVoPrio[vo] <= prio_min) && chMatch ) { prio_min = mVoPrio[vo]; v = vo + MAX_VOICE; } it++; } it = mWaitVo.rbegin(); while (it != mWaitVo.rend()) { int vo = *it; if (mVoPrio[vo] <= prio_min) { prio_min = mVoPrio[vo]; v = vo; } it++; } return v; } <commit_msg>モノモード時に同時に2音以上鳴らした場合にノートが残る場合を修正<commit_after>// // DynamicVoiceManager.cpp // C700 // // Created by osoumen on 2014/11/30. // // #include "DynamicVoiceManager.h" //----------------------------------------------------------------------------- DynamicVoiceManager::DynamicVoiceManager() : mVoiceLimit(8) { } //----------------------------------------------------------------------------- DynamicVoiceManager::~DynamicVoiceManager() { } //----------------------------------------------------------------------------- void DynamicVoiceManager::Initialize(int voiceLimit) { mVoiceLimit = voiceLimit; for (int i=0; i<16; i++) { mChNoteOns[i] = 0; mChLimit[i] = 127; } } //----------------------------------------------------------------------------- void DynamicVoiceManager::Reset() { mPlayVo.clear(); mWaitVo.clear(); for(int i=0;i<mVoiceLimit;i++){ pushWaitVo(i); } for (int i=0; i<MAX_VOICE; i++) { mVoCh[i] = 0; mVoPrio[i] = 64; mVoUniqueID[i] = 0; mVoKeyOn[i] = false; } } //----------------------------------------------------------------------------- void DynamicVoiceManager::ChangeVoiceLimit(int voiceLimit) { if ( voiceLimit < mVoiceLimit ) { //空きボイスリストから削除する for ( int i=voiceLimit; i<mVoiceLimit; i++ ) { mWaitVo.remove(i); } } if ( voiceLimit > mVoiceLimit ) { //空きボイスを追加する for ( int i=mVoiceLimit; i<voiceLimit; i++ ) { pushWaitVo(i); } } mVoiceLimit = voiceLimit; } //----------------------------------------------------------------------------- int DynamicVoiceManager::AllocVoice(int prio, int ch, int uniqueID, bool monoMode, int *releasedCh, bool *isLegato) { int v = -1; *releasedCh = -1; *isLegato = false; if (monoMode) { v = ch & 0x07; // 固定のchを確保 if (IsPlayingVoice(v)) { if (mVoCh[v] == ch) { // レガートで鳴らした音 // キーオン前に2回叩かれた場合は最後のノートオンだけが有効になるように if (mVoKeyOn[v]) { *isLegato = true; } } else { // 別のchの発音がすでにある場合 mPlayVo.remove(v); *releasedCh = mVoCh[v]; mChNoteOns[mVoCh[v]]--; } } else { mWaitVo.remove(v); } } else { if (mChNoteOns[ch] >= mChLimit[ch]) { // ch発音数を超えてたら、そのchの音を一つ止めて次の音を鳴らす v = StealVoice(ch); if (v != -1) { mPlayVo.remove(v); *releasedCh = mVoCh[v]; mChNoteOns[mVoCh[v]]--; } } else { // 超えてない場合は、後着優先で優先度の低い音を消す v = FindVoice(); if (v >= MAX_VOICE) { //空きがなくてどこかを止めた v -= MAX_VOICE; mPlayVo.remove(v); *releasedCh = mVoCh[v]; mChNoteOns[mVoCh[v]]--; } else if (v >= 0) { mWaitVo.remove(v); } } } if (v != -1) { mVoCh[v] = ch; mVoPrio[v] = prio; mVoKeyOn[v] = false; mVoUniqueID[v] = uniqueID; if (*isLegato == false && !IsPlayingVoice(v)) { // モノモードの同時ノートオン対策 mPlayVo.push_back(v); mChNoteOns[ch]++; } } return v; } //----------------------------------------------------------------------------- int DynamicVoiceManager::ReleaseVoice(int relPrio, int ch, int uniqueID, int *relVo) { int stops = 0; std::list<int>::iterator it = mPlayVo.begin(); while (it != mPlayVo.end()) { int vo = *it; if ( mVoUniqueID[vo] == uniqueID ) { if (mVoKeyOn[vo]) { mVoUniqueID[vo] = 0; mVoPrio[vo] = relPrio; mVoKeyOn[vo] = false; } if ( vo < mVoiceLimit ) { mWaitVo.push_back(vo); } it = mPlayVo.erase(it); stops++; mChNoteOns[ch]--; *relVo = vo; break; // 2重鳴りはホストに任せる //continue; } it++; } return stops; } //----------------------------------------------------------------------------- void DynamicVoiceManager::SetChLimit(int ch, int value) { mChLimit[ch & 0xf] = value; } //----------------------------------------------------------------------------- int DynamicVoiceManager::GetChLimit(int ch) { return mChLimit[ch & 0xf]; } //----------------------------------------------------------------------------- int DynamicVoiceManager::GetNoteOns(int ch) { return mChNoteOns[ch & 0xf]; } //----------------------------------------------------------------------------- void DynamicVoiceManager::SetKeyOn(int vo) { // TODO: voがAlloc済みかどうかチェック mVoKeyOn[vo] = true; } //----------------------------------------------------------------------------- bool DynamicVoiceManager::IsKeyOn(int vo) { return mVoKeyOn[vo]; } //----------------------------------------------------------------------------- void DynamicVoiceManager::pushWaitVo(int vo) { mWaitVo.push_back(vo); mVoCh[vo] = 0; mVoPrio[vo] = 0; } //----------------------------------------------------------------------------- int DynamicVoiceManager::FindFreeVoice() { int v=-1; //空きボイスを探す if ( mWaitVo.size() > 0 ) { v = mWaitVo.front(); mWaitVo.pop_front(); } return v; } //----------------------------------------------------------------------------- bool DynamicVoiceManager::IsPlayingVoice(int v) { std::list<int>::iterator it = mPlayVo.begin(); while (it != mPlayVo.end()) { int vo = *it; if (vo == v) { return true; } it++; } return false; } //----------------------------------------------------------------------------- int DynamicVoiceManager::StealVoice(int ch) { int v=-1; int prio_min = 0x7fff; std::list<int>::reverse_iterator it = mPlayVo.rbegin(); while (it != mPlayVo.rend()) { int vo = *it; if ( (mVoPrio[vo] <= prio_min) && (mVoCh[vo] == ch) ) { prio_min = mVoPrio[vo]; v = vo; } it++; } return v; } //----------------------------------------------------------------------------- int DynamicVoiceManager::FindVoice(int ch) { int v=-1; int prio_min = 0x7fff; std::list<int>::reverse_iterator it = mPlayVo.rbegin(); while (it != mPlayVo.rend()) { int vo = *it; bool chMatch = (mVoCh[vo] == ch) ? true:false; if (ch == -1) { chMatch = true; } if ( (mVoPrio[vo] <= prio_min) && chMatch ) { prio_min = mVoPrio[vo]; v = vo + MAX_VOICE; } it++; } it = mWaitVo.rbegin(); while (it != mWaitVo.rend()) { int vo = *it; if (mVoPrio[vo] <= prio_min) { prio_min = mVoPrio[vo]; v = vo; } it++; } return v; } <|endoftext|>
<commit_before>#include <stdlib.h> #include "geocsv.hpp" #include "mvt.hpp" #include "serial.hpp" #include "projection.hpp" #include "main.hpp" #include "text.hpp" #include "csv.hpp" #include "milo/dtoa_milo.h" void parse_geocsv(std::vector<struct serialization_state> &sst, std::string fname, int layer, std::string layername) { FILE *f = fopen(fname.c_str(), "r"); if (f == NULL) { perror(fname.c_str()); exit(EXIT_FAILURE); } std::string s; std::vector<std::string> header; ssize_t latcol = -1, loncol = -1; if ((s = csv_getline(f)).size() > 0) { std::string err = check_utf8(s); if (err != "") { fprintf(stderr, "%s: %s\n", fname.c_str(), err.c_str()); exit(EXIT_FAILURE); } header = csv_split(s.c_str()); for (size_t i = 0; i < header.size(); i++) { header[i] = csv_dequote(header[i]); if (header[i] == "lat" || header[i] == "latitude") { latcol = i; } if (header[i] == "lon" || header[i] == "longitude" || header[i] == "long") { loncol = i; } } } if (latcol < 0 || loncol < 0) { fprintf(stderr, "%s: Can't find \"lat\" and \"lon\" columns\n", fname.c_str()); exit(EXIT_FAILURE); } size_t seq = 0; while ((s = csv_getline(f)).size() > 0) { std::string err = check_utf8(s); if (err != "") { fprintf(stderr, "%s: %s\n", fname.c_str(), err.c_str()); exit(EXIT_FAILURE); } seq++; std::vector<std::string> line = csv_split(s.c_str()); if (line.size() != header.size()) { fprintf(stderr, "%s:%zu: Mismatched column count: %zu in line, %zu in header\n", fname.c_str(), seq, line.size(), header.size()); exit(EXIT_FAILURE); } double lon = atof(line[loncol].c_str()); double lat = atof(line[latcol].c_str()); long long x, y; projection->project(lon, lat, 32, &x, &y); drawvec dv; dv.push_back(draw(VT_MOVETO, x, y)); std::vector<std::string> full_keys; std::vector<serial_val> full_values; for (size_t i = 0; i < line.size(); i++) { if (i != (size_t) latcol && i != (size_t) loncol) { full_keys.push_back(header[i]); serial_val sv; sv.type = mvt_string; sv.s = line[i]; full_values.push_back(sv); } } serial_feature sf; sf.layer = layer; sf.layername = layername; sf.segment = sst[0].segment; sf.has_id = false; sf.id = 0; sf.has_tippecanoe_minzoom = false; sf.has_tippecanoe_maxzoom = false; sf.feature_minzoom = false; sf.seq = *(sst[0].layer_seq); sf.geometry = dv; sf.t = 1; // POINT sf.full_keys = full_keys; sf.full_values = full_values; sf.m = sf.full_values.size(); serialize_feature(&sst[0], sf); } if (fclose(f) != 0) { perror("fclose"); exit(EXIT_FAILURE); } } <commit_msg>Check for strings vs numbers in CSV attributes<commit_after>#include <stdlib.h> #include "geocsv.hpp" #include "mvt.hpp" #include "serial.hpp" #include "projection.hpp" #include "main.hpp" #include "text.hpp" #include "csv.hpp" #include "milo/dtoa_milo.h" void parse_geocsv(std::vector<struct serialization_state> &sst, std::string fname, int layer, std::string layername) { FILE *f = fopen(fname.c_str(), "r"); if (f == NULL) { perror(fname.c_str()); exit(EXIT_FAILURE); } std::string s; std::vector<std::string> header; ssize_t latcol = -1, loncol = -1; if ((s = csv_getline(f)).size() > 0) { std::string err = check_utf8(s); if (err != "") { fprintf(stderr, "%s: %s\n", fname.c_str(), err.c_str()); exit(EXIT_FAILURE); } header = csv_split(s.c_str()); for (size_t i = 0; i < header.size(); i++) { header[i] = csv_dequote(header[i]); if (header[i] == "lat" || header[i] == "latitude") { latcol = i; } if (header[i] == "lon" || header[i] == "longitude" || header[i] == "long") { loncol = i; } } } if (latcol < 0 || loncol < 0) { fprintf(stderr, "%s: Can't find \"lat\" and \"lon\" columns\n", fname.c_str()); exit(EXIT_FAILURE); } size_t seq = 0; while ((s = csv_getline(f)).size() > 0) { std::string err = check_utf8(s); if (err != "") { fprintf(stderr, "%s: %s\n", fname.c_str(), err.c_str()); exit(EXIT_FAILURE); } seq++; std::vector<std::string> line = csv_split(s.c_str()); if (line.size() != header.size()) { fprintf(stderr, "%s:%zu: Mismatched column count: %zu in line, %zu in header\n", fname.c_str(), seq, line.size(), header.size()); exit(EXIT_FAILURE); } double lon = atof(line[loncol].c_str()); double lat = atof(line[latcol].c_str()); long long x, y; projection->project(lon, lat, 32, &x, &y); drawvec dv; dv.push_back(draw(VT_MOVETO, x, y)); std::vector<std::string> full_keys; std::vector<serial_val> full_values; for (size_t i = 0; i < line.size(); i++) { if (i != (size_t) latcol && i != (size_t) loncol) { line[i] = csv_dequote(line[i]); serial_val sv; if (is_number(line[i])) { sv.type = mvt_double; } else { sv.type = mvt_string; } sv.s = line[i]; full_keys.push_back(header[i]); full_values.push_back(sv); } } serial_feature sf; sf.layer = layer; sf.layername = layername; sf.segment = sst[0].segment; sf.has_id = false; sf.id = 0; sf.has_tippecanoe_minzoom = false; sf.has_tippecanoe_maxzoom = false; sf.feature_minzoom = false; sf.seq = *(sst[0].layer_seq); sf.geometry = dv; sf.t = 1; // POINT sf.full_keys = full_keys; sf.full_values = full_values; sf.m = sf.full_values.size(); serialize_feature(&sst[0], sf); } if (fclose(f) != 0) { perror("fclose"); exit(EXIT_FAILURE); } } <|endoftext|>
<commit_before><commit_msg>replace use of data member fStack by direct access to stack pointer via instance call, this should solve the failing tests<commit_after><|endoftext|>
<commit_before>//===- LoopAnalysis.cpp - Misc loop analysis routines //-------------------===// // // Copyright 2019 The MLIR 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. // ============================================================================= // // This file implements miscellaneous loop analysis routines. // //===----------------------------------------------------------------------===// #include "mlir/Analysis/LoopAnalysis.h" #include "mlir/Analysis/AffineAnalysis.h" #include "mlir/Analysis/AffineStructures.h" #include "mlir/Analysis/MLFunctionMatcher.h" #include "mlir/Analysis/VectorAnalysis.h" #include "mlir/IR/Builders.h" #include "mlir/IR/BuiltinOps.h" #include "mlir/IR/Statements.h" #include "mlir/StandardOps/StandardOps.h" #include "mlir/SuperVectorOps/SuperVectorOps.h" #include "mlir/Support/Functional.h" #include "mlir/Support/MathExtras.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/SmallString.h" #include <type_traits> using namespace mlir; /// Returns the trip count of the loop as an affine expression if the latter is /// expressible as an affine expression, and nullptr otherwise. The trip count /// expression is simplified before returning. AffineExpr mlir::getTripCountExpr(const ForStmt &forStmt) { // upper_bound - lower_bound int64_t loopSpan; int64_t step = forStmt.getStep(); auto *context = forStmt.getContext(); if (forStmt.hasConstantBounds()) { int64_t lb = forStmt.getConstantLowerBound(); int64_t ub = forStmt.getConstantUpperBound(); loopSpan = ub - lb; } else { auto lbMap = forStmt.getLowerBoundMap(); auto ubMap = forStmt.getUpperBoundMap(); // TODO(bondhugula): handle max/min of multiple expressions. if (lbMap.getNumResults() != 1 || ubMap.getNumResults() != 1) return nullptr; // TODO(bondhugula): handle bounds with different operands. // Bounds have different operands, unhandled for now. if (!forStmt.matchingBoundOperandList()) return nullptr; // ub_expr - lb_expr AffineExpr lbExpr(lbMap.getResult(0)); AffineExpr ubExpr(ubMap.getResult(0)); auto loopSpanExpr = simplifyAffineExpr( ubExpr - lbExpr, std::max(lbMap.getNumDims(), ubMap.getNumDims()), std::max(lbMap.getNumSymbols(), ubMap.getNumSymbols())); auto cExpr = loopSpanExpr.dyn_cast<AffineConstantExpr>(); if (!cExpr) return loopSpanExpr.ceilDiv(step); loopSpan = cExpr.getValue(); } // 0 iteration loops. if (loopSpan < 0) return 0; return getAffineConstantExpr(static_cast<uint64_t>(ceilDiv(loopSpan, step)), context); } /// Returns the trip count of the loop if it's a constant, None otherwise. This /// method uses affine expression analysis (in turn using getTripCount) and is /// able to determine constant trip count in non-trivial cases. llvm::Optional<uint64_t> mlir::getConstantTripCount(const ForStmt &forStmt) { auto tripCountExpr = getTripCountExpr(forStmt); if (!tripCountExpr) return None; if (auto constExpr = tripCountExpr.dyn_cast<AffineConstantExpr>()) return constExpr.getValue(); return None; } /// Returns the greatest known integral divisor of the trip count. Affine /// expression analysis is used (indirectly through getTripCount), and /// this method is thus able to determine non-trivial divisors. uint64_t mlir::getLargestDivisorOfTripCount(const ForStmt &forStmt) { auto tripCountExpr = getTripCountExpr(forStmt); if (!tripCountExpr) return 1; if (auto constExpr = tripCountExpr.dyn_cast<AffineConstantExpr>()) { uint64_t tripCount = constExpr.getValue(); // 0 iteration loops (greatest divisor is 2^64 - 1). if (tripCount == 0) return ULONG_MAX; // The greatest divisor is the trip count. return tripCount; } // Trip count is not a known constant; return its largest known divisor. return tripCountExpr.getLargestKnownDivisor(); } bool mlir::isAccessInvariant(const MLValue &iv, const MLValue &index) { assert(isa<ForStmt>(iv) && "iv must be a ForStmt"); assert(index.getType().isa<IndexType>() && "index must be of IndexType"); SmallVector<OperationStmt *, 4> affineApplyOps; getReachableAffineApplyOps({const_cast<MLValue *>(&index)}, affineApplyOps); if (affineApplyOps.empty()) { // Pointer equality test because of MLValue pointer semantics. return &index != &iv; } if (affineApplyOps.size() > 1) { affineApplyOps[0]->emitError( "CompositionAffineMapsPass must have been run: there should be at most " "one AffineApplyOp"); return false; } auto composeOp = affineApplyOps[0]->cast<AffineApplyOp>(); // We need yet another level of indirection because the `dim` index of the // access may not correspond to the `dim` index of composeOp. unsigned idx = std::numeric_limits<unsigned>::max(); unsigned numResults = composeOp->getNumResults(); for (unsigned i = 0; i < numResults; ++i) { if (&index == composeOp->getResult(i)) { idx = i; break; } } assert(idx < std::numeric_limits<unsigned>::max()); return !AffineValueMap(*composeOp) .isFunctionOf(idx, &const_cast<MLValue &>(iv)); } llvm::DenseSet<const MLValue *> mlir::getInvariantAccesses(const MLValue &iv, llvm::ArrayRef<const MLValue *> indices) { llvm::DenseSet<const MLValue *> res; for (unsigned idx = 0, n = indices.size(); idx < n; ++idx) { auto *val = indices[idx]; if (isAccessInvariant(iv, *val)) { res.insert(val); } } return res; } /// Given: /// 1. an induction variable `iv` of type ForStmt; /// 2. a `memoryOp` of type const LoadOp& or const StoreOp&; /// 3. the index of the `fastestVaryingDim` along which to check; /// determines whether `memoryOp`[`fastestVaryingDim`] is a contiguous access /// along `iv`. /// Contiguous is defined as either invariant or varying only along /// `fastestVaryingDim`. /// /// Prerequisites: /// 1. `iv` of the proper type; /// 2. the MemRef accessed by `memoryOp` has no layout map or at most an /// identity layout map. /// /// Currently only supports no layoutMap or identity layoutMap in the MemRef. /// Returns false if the MemRef has a non-identity layoutMap or more than /// 1 layoutMap. This is conservative. /// // TODO(ntv): check strides. template <typename LoadOrStoreOp> static bool isContiguousAccess(const MLValue &iv, const LoadOrStoreOp &memoryOp, unsigned fastestVaryingDim) { static_assert(std::is_same<LoadOrStoreOp, LoadOp>::value || std::is_same<LoadOrStoreOp, StoreOp>::value, "Must be called on either const LoadOp & or const StoreOp &"); auto memRefType = memoryOp.getMemRefType(); auto layoutMap = memRefType.getAffineMaps(); // TODO(ntv): remove dependence on Builder once we support non-identity // layout map. Builder b(memoryOp.getOperation()->getContext()); if (layoutMap.size() >= 2 || (layoutMap.size() == 1 && !(layoutMap[0] == b.getMultiDimIdentityMap(layoutMap[0].getNumDims())))) { return memoryOp.emitError("NYI: non-trivial layoutMap"), false; } assert(fastestVaryingDim < memRefType.getRank()); auto indices = memoryOp.getIndices(); // TODO(clattner): should iterator_range have a size method? auto numIndices = indices.end() - indices.begin(); unsigned d = 0; for (auto index : indices) { if (fastestVaryingDim == (numIndices - 1) - d++) { continue; } if (!isAccessInvariant(iv, cast<MLValue>(*index))) { return false; } } return true; } template <typename LoadOrStoreOpPointer> static bool isVectorElement(LoadOrStoreOpPointer memoryOp) { auto memRefType = memoryOp->getMemRefType(); return memRefType.getElementType().template isa<VectorType>(); } static bool isVectorTransferReadOrWrite(const Statement &stmt) { const auto *opStmt = cast<OperationStmt>(&stmt); return opStmt->isa<VectorTransferReadOp>() || opStmt->isa<VectorTransferWriteOp>(); } using VectorizableStmtFun = std::function<bool(const ForStmt &, const OperationStmt &)>; static bool isVectorizableLoopWithCond(const ForStmt &loop, VectorizableStmtFun isVectorizableStmt) { if (!matcher::isParallelLoop(loop) && !matcher::isReductionLoop(loop)) { return false; } // No vectorization across conditionals for now. auto conditionals = matcher::If(); auto *forStmt = const_cast<ForStmt *>(&loop); auto conditionalsMatched = conditionals.match(forStmt); if (!conditionalsMatched.empty()) { return false; } auto vectorTransfers = matcher::Op(isVectorTransferReadOrWrite); auto vectorTransfersMatched = vectorTransfers.match(forStmt); if (!vectorTransfersMatched.empty()) { return false; } auto loadAndStores = matcher::Op(matcher::isLoadOrStore); auto loadAndStoresMatched = loadAndStores.match(forStmt); for (auto ls : loadAndStoresMatched) { auto *op = cast<OperationStmt>(ls.first); auto load = op->dyn_cast<LoadOp>(); auto store = op->dyn_cast<StoreOp>(); // Only scalar types are considered vectorizable, all load/store must be // vectorizable for a loop to qualify as vectorizable. // TODO(ntv): ponder whether we want to be more general here. bool vector = load ? isVectorElement(load) : isVectorElement(store); if (vector) { return false; } if (!isVectorizableStmt(loop, *op)) { return false; } } return true; } bool mlir::isVectorizableLoopAlongFastestVaryingMemRefDim( const ForStmt &loop, unsigned fastestVaryingDim) { VectorizableStmtFun fun( [fastestVaryingDim](const ForStmt &loop, const OperationStmt &op) { auto load = op.dyn_cast<LoadOp>(); auto store = op.dyn_cast<StoreOp>(); return load ? isContiguousAccess(loop, *load, fastestVaryingDim) : isContiguousAccess(loop, *store, fastestVaryingDim); }); return isVectorizableLoopWithCond(loop, fun); } bool mlir::isVectorizableLoop(const ForStmt &loop) { VectorizableStmtFun fun( // TODO: implement me [](const ForStmt &loop, const OperationStmt &op) { return true; }); return isVectorizableLoopWithCond(loop, fun); } /// Checks whether SSA dominance would be violated if a for stmt's body /// statements are shifted by the specified shifts. This method checks if a /// 'def' and all its uses have the same shift factor. // TODO(mlir-team): extend this to check for memory-based dependence // violation when we have the support. bool mlir::isStmtwiseShiftValid(const ForStmt &forStmt, ArrayRef<uint64_t> shifts) { auto *forBody = forStmt.getBody(); assert(shifts.size() == forBody->getStatements().size()); unsigned s = 0; for (const auto &stmt : *forBody) { // A for or if stmt does not produce any def/results (that are used // outside). if (const auto *opStmt = dyn_cast<OperationStmt>(&stmt)) { for (unsigned i = 0, e = opStmt->getNumResults(); i < e; ++i) { const MLValue *result = opStmt->getResult(i); for (const StmtOperand &use : result->getUses()) { // If an ancestor statement doesn't lie in the block of forStmt, there // is no shift to check. // This is a naive way. If performance becomes an issue, a map can // be used to store 'shifts' - to look up the shift for a statement in // constant time. if (auto *ancStmt = forBody->findAncestorStmtInBlock(*use.getOwner())) if (shifts[s] != shifts[forBody->findStmtPosInBlock(*ancStmt)]) return false; } } } s++; } return true; } <commit_msg>LoopAnalysis: isContiguousAccess fail gracefully<commit_after>//===- LoopAnalysis.cpp - Misc loop analysis routines //-------------------===// // // Copyright 2019 The MLIR 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. // ============================================================================= // // This file implements miscellaneous loop analysis routines. // //===----------------------------------------------------------------------===// #include "mlir/Analysis/LoopAnalysis.h" #include "mlir/Analysis/AffineAnalysis.h" #include "mlir/Analysis/AffineStructures.h" #include "mlir/Analysis/MLFunctionMatcher.h" #include "mlir/Analysis/VectorAnalysis.h" #include "mlir/IR/Builders.h" #include "mlir/IR/BuiltinOps.h" #include "mlir/IR/Statements.h" #include "mlir/StandardOps/StandardOps.h" #include "mlir/SuperVectorOps/SuperVectorOps.h" #include "mlir/Support/Functional.h" #include "mlir/Support/MathExtras.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/SmallString.h" #include <type_traits> using namespace mlir; /// Returns the trip count of the loop as an affine expression if the latter is /// expressible as an affine expression, and nullptr otherwise. The trip count /// expression is simplified before returning. AffineExpr mlir::getTripCountExpr(const ForStmt &forStmt) { // upper_bound - lower_bound int64_t loopSpan; int64_t step = forStmt.getStep(); auto *context = forStmt.getContext(); if (forStmt.hasConstantBounds()) { int64_t lb = forStmt.getConstantLowerBound(); int64_t ub = forStmt.getConstantUpperBound(); loopSpan = ub - lb; } else { auto lbMap = forStmt.getLowerBoundMap(); auto ubMap = forStmt.getUpperBoundMap(); // TODO(bondhugula): handle max/min of multiple expressions. if (lbMap.getNumResults() != 1 || ubMap.getNumResults() != 1) return nullptr; // TODO(bondhugula): handle bounds with different operands. // Bounds have different operands, unhandled for now. if (!forStmt.matchingBoundOperandList()) return nullptr; // ub_expr - lb_expr AffineExpr lbExpr(lbMap.getResult(0)); AffineExpr ubExpr(ubMap.getResult(0)); auto loopSpanExpr = simplifyAffineExpr( ubExpr - lbExpr, std::max(lbMap.getNumDims(), ubMap.getNumDims()), std::max(lbMap.getNumSymbols(), ubMap.getNumSymbols())); auto cExpr = loopSpanExpr.dyn_cast<AffineConstantExpr>(); if (!cExpr) return loopSpanExpr.ceilDiv(step); loopSpan = cExpr.getValue(); } // 0 iteration loops. if (loopSpan < 0) return 0; return getAffineConstantExpr(static_cast<uint64_t>(ceilDiv(loopSpan, step)), context); } /// Returns the trip count of the loop if it's a constant, None otherwise. This /// method uses affine expression analysis (in turn using getTripCount) and is /// able to determine constant trip count in non-trivial cases. llvm::Optional<uint64_t> mlir::getConstantTripCount(const ForStmt &forStmt) { auto tripCountExpr = getTripCountExpr(forStmt); if (!tripCountExpr) return None; if (auto constExpr = tripCountExpr.dyn_cast<AffineConstantExpr>()) return constExpr.getValue(); return None; } /// Returns the greatest known integral divisor of the trip count. Affine /// expression analysis is used (indirectly through getTripCount), and /// this method is thus able to determine non-trivial divisors. uint64_t mlir::getLargestDivisorOfTripCount(const ForStmt &forStmt) { auto tripCountExpr = getTripCountExpr(forStmt); if (!tripCountExpr) return 1; if (auto constExpr = tripCountExpr.dyn_cast<AffineConstantExpr>()) { uint64_t tripCount = constExpr.getValue(); // 0 iteration loops (greatest divisor is 2^64 - 1). if (tripCount == 0) return ULONG_MAX; // The greatest divisor is the trip count. return tripCount; } // Trip count is not a known constant; return its largest known divisor. return tripCountExpr.getLargestKnownDivisor(); } bool mlir::isAccessInvariant(const MLValue &iv, const MLValue &index) { assert(isa<ForStmt>(iv) && "iv must be a ForStmt"); assert(index.getType().isa<IndexType>() && "index must be of IndexType"); SmallVector<OperationStmt *, 4> affineApplyOps; getReachableAffineApplyOps({const_cast<MLValue *>(&index)}, affineApplyOps); if (affineApplyOps.empty()) { // Pointer equality test because of MLValue pointer semantics. return &index != &iv; } if (affineApplyOps.size() > 1) { affineApplyOps[0]->emitError( "CompositionAffineMapsPass must have been run: there should be at most " "one AffineApplyOp"); return false; } auto composeOp = affineApplyOps[0]->cast<AffineApplyOp>(); // We need yet another level of indirection because the `dim` index of the // access may not correspond to the `dim` index of composeOp. unsigned idx = std::numeric_limits<unsigned>::max(); unsigned numResults = composeOp->getNumResults(); for (unsigned i = 0; i < numResults; ++i) { if (&index == composeOp->getResult(i)) { idx = i; break; } } assert(idx < std::numeric_limits<unsigned>::max()); return !AffineValueMap(*composeOp) .isFunctionOf(idx, &const_cast<MLValue &>(iv)); } llvm::DenseSet<const MLValue *> mlir::getInvariantAccesses(const MLValue &iv, llvm::ArrayRef<const MLValue *> indices) { llvm::DenseSet<const MLValue *> res; for (unsigned idx = 0, n = indices.size(); idx < n; ++idx) { auto *val = indices[idx]; if (isAccessInvariant(iv, *val)) { res.insert(val); } } return res; } /// Given: /// 1. an induction variable `iv` of type ForStmt; /// 2. a `memoryOp` of type const LoadOp& or const StoreOp&; /// 3. the index of the `fastestVaryingDim` along which to check; /// determines whether `memoryOp`[`fastestVaryingDim`] is a contiguous access /// along `iv`. /// Contiguous is defined as either invariant or varying only along /// `fastestVaryingDim`. /// /// Prerequisites: /// 1. `iv` of the proper type; /// 2. the MemRef accessed by `memoryOp` has no layout map or at most an /// identity layout map. /// /// Currently only supports no layoutMap or identity layoutMap in the MemRef. /// Returns false if the MemRef has a non-identity layoutMap or more than /// 1 layoutMap. This is conservative. /// // TODO(ntv): check strides. template <typename LoadOrStoreOp> static bool isContiguousAccess(const MLValue &iv, const LoadOrStoreOp &memoryOp, unsigned fastestVaryingDim) { static_assert(std::is_same<LoadOrStoreOp, LoadOp>::value || std::is_same<LoadOrStoreOp, StoreOp>::value, "Must be called on either const LoadOp & or const StoreOp &"); auto memRefType = memoryOp.getMemRefType(); if (fastestVaryingDim >= memRefType.getRank()) { memoryOp.emitError("fastest varying dim out of bounds"); return false; } auto layoutMap = memRefType.getAffineMaps(); // TODO(ntv): remove dependence on Builder once we support non-identity // layout map. Builder b(memoryOp.getOperation()->getContext()); if (layoutMap.size() >= 2 || (layoutMap.size() == 1 && !(layoutMap[0] == b.getMultiDimIdentityMap(layoutMap[0].getNumDims())))) { return memoryOp.emitError("NYI: non-trivial layoutMap"), false; } auto indices = memoryOp.getIndices(); auto numIndices = llvm::size(indices); unsigned d = 0; for (auto index : indices) { if (fastestVaryingDim == (numIndices - 1) - d++) { continue; } if (!isAccessInvariant(iv, cast<MLValue>(*index))) { return false; } } return true; } template <typename LoadOrStoreOpPointer> static bool isVectorElement(LoadOrStoreOpPointer memoryOp) { auto memRefType = memoryOp->getMemRefType(); return memRefType.getElementType().template isa<VectorType>(); } static bool isVectorTransferReadOrWrite(const Statement &stmt) { const auto *opStmt = cast<OperationStmt>(&stmt); return opStmt->isa<VectorTransferReadOp>() || opStmt->isa<VectorTransferWriteOp>(); } using VectorizableStmtFun = std::function<bool(const ForStmt &, const OperationStmt &)>; static bool isVectorizableLoopWithCond(const ForStmt &loop, VectorizableStmtFun isVectorizableStmt) { if (!matcher::isParallelLoop(loop) && !matcher::isReductionLoop(loop)) { return false; } // No vectorization across conditionals for now. auto conditionals = matcher::If(); auto *forStmt = const_cast<ForStmt *>(&loop); auto conditionalsMatched = conditionals.match(forStmt); if (!conditionalsMatched.empty()) { return false; } auto vectorTransfers = matcher::Op(isVectorTransferReadOrWrite); auto vectorTransfersMatched = vectorTransfers.match(forStmt); if (!vectorTransfersMatched.empty()) { return false; } auto loadAndStores = matcher::Op(matcher::isLoadOrStore); auto loadAndStoresMatched = loadAndStores.match(forStmt); for (auto ls : loadAndStoresMatched) { auto *op = cast<OperationStmt>(ls.first); auto load = op->dyn_cast<LoadOp>(); auto store = op->dyn_cast<StoreOp>(); // Only scalar types are considered vectorizable, all load/store must be // vectorizable for a loop to qualify as vectorizable. // TODO(ntv): ponder whether we want to be more general here. bool vector = load ? isVectorElement(load) : isVectorElement(store); if (vector) { return false; } if (!isVectorizableStmt(loop, *op)) { return false; } } return true; } bool mlir::isVectorizableLoopAlongFastestVaryingMemRefDim( const ForStmt &loop, unsigned fastestVaryingDim) { VectorizableStmtFun fun( [fastestVaryingDim](const ForStmt &loop, const OperationStmt &op) { auto load = op.dyn_cast<LoadOp>(); auto store = op.dyn_cast<StoreOp>(); return load ? isContiguousAccess(loop, *load, fastestVaryingDim) : isContiguousAccess(loop, *store, fastestVaryingDim); }); return isVectorizableLoopWithCond(loop, fun); } bool mlir::isVectorizableLoop(const ForStmt &loop) { VectorizableStmtFun fun( // TODO: implement me [](const ForStmt &loop, const OperationStmt &op) { return true; }); return isVectorizableLoopWithCond(loop, fun); } /// Checks whether SSA dominance would be violated if a for stmt's body /// statements are shifted by the specified shifts. This method checks if a /// 'def' and all its uses have the same shift factor. // TODO(mlir-team): extend this to check for memory-based dependence // violation when we have the support. bool mlir::isStmtwiseShiftValid(const ForStmt &forStmt, ArrayRef<uint64_t> shifts) { auto *forBody = forStmt.getBody(); assert(shifts.size() == forBody->getStatements().size()); unsigned s = 0; for (const auto &stmt : *forBody) { // A for or if stmt does not produce any def/results (that are used // outside). if (const auto *opStmt = dyn_cast<OperationStmt>(&stmt)) { for (unsigned i = 0, e = opStmt->getNumResults(); i < e; ++i) { const MLValue *result = opStmt->getResult(i); for (const StmtOperand &use : result->getUses()) { // If an ancestor statement doesn't lie in the block of forStmt, there // is no shift to check. // This is a naive way. If performance becomes an issue, a map can // be used to store 'shifts' - to look up the shift for a statement in // constant time. if (auto *ancStmt = forBody->findAncestorStmtInBlock(*use.getOwner())) if (shifts[s] != shifts[forBody->findStmtPosInBlock(*ancStmt)]) return false; } } } s++; } return true; } <|endoftext|>
<commit_before>#include <htool/point.hpp> #include <htool/wrapper_hpddm.hpp> #include <htool/fullACA.hpp> #include <htool/hmatrix.hpp> #include <htool/geometry.hpp> using namespace std; using namespace htool; int main(int argc, char const *argv[]){ // Input file if ( argc < 5 ){ // argc should be 5 or more for correct execution // We print argv[0] assuming it is the program name cout<<"usage: "<< argv[0] <<" <matrixfile> <rhsfile> <meshfile> <solutionfile>\n"; return 1; } // Initialize the MPI environment MPI_Init(NULL, NULL); // Get the number of processes int size; MPI_Comm_size(MPI_COMM_WORLD, &size); // Get the rank of the process int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); // bool test =0; SetNdofPerElt(1); SetEpsilon(1e-6); SetEta(0.1); SetMinClusterSize(1); // HPDDM verbosity HPDDM::Option& opt = *HPDDM::Option::get(); opt.parse(argc, argv, rank == 0); if(rank != 0) opt.remove("verbosity"); // Matrix Matrix<complex<double>> A; A.bytes_to_matrix(argv[1]); int n = A.nb_rows(); // Right-hand side std::vector<complex<double>> f_global(n,1); bytes_to_vector(f_global,argv[2]); // Mesh std::vector<R3> p; LoadGMSHMesh(p,argv[3]); // Hmatrix std::vector<int> tab(n); for (int i=0;i<n;i++){ tab[i]=i; } HMatrix<fullACA,complex<double>> HA(A,p,tab); // Global vectors std::vector<complex<double>> x_global(n,0),x_ref(n); bytes_to_vector(x_ref,argv[4]); // Local vectors int n_local= HA.get_local_size_cluster(); const std::vector<std::vector<int>>& MasterClusters = HA.get_MasterClusters(); std::vector<complex<double>> x_local(n_local,0),f_local(n_local,1); for (int i=0;i<n_local;i++){ f_local[i]=f_global[MasterClusters[rank][i]]; } // Solve HPDDMOperator<fullACA,complex<double>> A_HPDDM(HA,A); complex<double>* const rhs = &(f_local[0]); complex<double>* x = &(x_local[0]); HPDDM::IterativeMethod::solve(A_HPDDM, rhs, x, 1,HA.get_comm()); // Local to Global std::vector<complex<double>> rcv(n); std::vector<int> recvcounts(size); std::vector<int> displs(size); displs[0] = 0; for (int i=0; i<size; i++) { recvcounts[i] = MasterClusters[i].size(); if (i > 0) displs[i] = displs[i-1] + recvcounts[i-1]; } MPI_Allgatherv(&(x_local.front()), recvcounts[rank], MPI_DOUBLE_COMPLEX, &(rcv.front()), &(recvcounts.front()), &(displs.front()), MPI_DOUBLE_COMPLEX, HA.get_comm()); for (int i=0; i<size; i++) for (int j=0; j< MasterClusters[i].size(); j++) x_global[MasterClusters[i][j]] = rcv[displs[i]+j]; // Error on inversion double inv_error2=norm2(f_global-A*x_global)/norm2(f_global); double error2 = norm2(x_ref-x_global)/norm2(x_ref); if (rank==0){ cout <<"error on inversion : "<<inv_error2 << endl; cout <<"error on solution : "<<error2 << endl; } test = test || !(inv_error2<opt.val("tol",1e-6)); test = test || !(error2<1e-5); //Finalize the MPI environment. MPI_Finalize(); return test; } <commit_msg>working on hpddm solve<commit_after>#include <htool/point.hpp> #include <htool/wrapper_hpddm.hpp> #include <htool/fullACA.hpp> #include <htool/hmatrix.hpp> #include <htool/geometry.hpp> using namespace std; using namespace htool; int main(int argc, char const *argv[]){ // Input file if ( argc < 5 ){ // argc should be 5 or more for correct execution // We print argv[0] assuming it is the program name cout<<"usage: "<< argv[0] <<" <matrixfile> <rhsfile> <meshfile> <solutionfile>\n"; return 1; } // Initialize the MPI environment MPI_Init(NULL, NULL); // Get the number of processes int size; MPI_Comm_size(MPI_COMM_WORLD, &size); // Get the rank of the process int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); // bool test =0; SetNdofPerElt(1); SetEpsilon(1e-6); SetEta(0.1); SetMinClusterSize(1); // HPDDM verbosity HPDDM::Option& opt = *HPDDM::Option::get(); opt.parse(argc, argv, rank == 0); if(rank != 0) opt.remove("verbosity"); // Matrix Matrix<complex<double>> A; A.bytes_to_matrix(argv[1]); int n = A.nb_rows(); // Right-hand side std::vector<complex<double>> f_global(n,1); bytes_to_vector(f_global,argv[2]); // Mesh std::vector<R3> p; LoadGMSHMesh(p,argv[3]); // Hmatrix std::vector<int> tab(n); for (int i=0;i<n;i++){ tab[i]=i; } HMatrix<fullACA,complex<double>> HA(A,p,tab); // Global vectors std::vector<complex<double>> x_global(n,0),x_ref(n); bytes_to_vector(x_ref,argv[4]); // Local vectors int n_local= HA.get_local_size_cluster(); const std::vector<std::vector<int>>& MasterClusters = HA.get_MasterClusters(); std::vector<complex<double>> x_local(n_local,0),f_local(n_local,1); for (int i=0;i<n_local;i++){ f_local[i]=f_global[MasterClusters[rank][i]]; } // Solve solve(HA,x_local,f_local); // HPDDMOperator<fullACA,complex<double>> A_HPDDM(HA,A); // complex<double>* const rhs = &(f_local[0]); // complex<double>* x = &(x_local[0]); // HPDDM::IterativeMethod::solve(A_HPDDM, rhs, x, 1,HA.get_comm()); // Local to Global std::vector<complex<double>> rcv(n); std::vector<int> recvcounts(size); std::vector<int> displs(size); displs[0] = 0; for (int i=0; i<size; i++) { recvcounts[i] = MasterClusters[i].size(); if (i > 0) displs[i] = displs[i-1] + recvcounts[i-1]; } MPI_Allgatherv(&(x_local.front()), recvcounts[rank], MPI_DOUBLE_COMPLEX, &(rcv.front()), &(recvcounts.front()), &(displs.front()), MPI_DOUBLE_COMPLEX, HA.get_comm()); for (int i=0; i<size; i++) for (int j=0; j< MasterClusters[i].size(); j++) x_global[MasterClusters[i][j]] = rcv[displs[i]+j]; // Error on inversion double inv_error2=norm2(f_global-A*x_global)/norm2(f_global); double error2 = norm2(x_ref-x_global)/norm2(x_ref); if (rank==0){ cout <<"error on inversion : "<<inv_error2 << endl; cout <<"error on solution : "<<error2 << endl; } test = test || !(inv_error2<opt.val("tol",1e-6)); test = test || !(error2<1e-5); //Finalize the MPI environment. MPI_Finalize(); return test; } <|endoftext|>
<commit_before>#include <rai/node/openclwork.hpp> #include <dlfcn.h> namespace { class opencl_initializer { public: opencl_initializer () { opencl_library = dlopen ("libOpenCL.so", RTLD_NOW); if (opencl_library != nullptr) { clGetPlatformIDs = reinterpret_cast <decltype (clGetPlatformIDs)> (dlsym (opencl_library, "clGetPlatformIDs")); } } ~opencl_initializer () { dlclose (opencl_library); } void * opencl_library; cl_int (* clGetPlatformIDs) (cl_uint, cl_platform_id *, cl_uint *); cl_int (* clGetPlatformInfo) (cl_platform_id, cl_platform_info, size_t, void *, size_t *); cl_int (* clGetDeviceIDs) (cl_platform_id, cl_device_type, cl_uint, cl_device_id *, cl_uint *); cl_int (* clGetDeviceInfo) (cl_device_id, cl_device_info, size_t, void *, size_t *); cl_context (* clCreateContext) (cl_context_properties const *, cl_uint, cl_device_id const *, void (*)(const char *, const void *, size_t, void *), void *, cl_int *); cl_command_queue (* clCreateCommandQueue) (cl_context, cl_device_id, cl_command_queue_properties, cl_int *); cl_mem (* clCreateBuffer) (cl_context, cl_mem_flags, size_t, void *, cl_int *); cl_program (* clCreateProgramWithSource) (cl_context, cl_uint, char const **, size_t const *, cl_int *); cl_int (* clBuildProgram) (cl_program, cl_uint, cl_device_id const *, char const *, void (*)(cl_program, void *), void *); cl_kernel (* clCreateKernel) (cl_program, char const *, cl_int *); cl_int (* clSetKernelArg) (cl_kernel, cl_uint, size_t, void const *); cl_int (* clReleaseKernel) (cl_kernel); cl_int (* clReleaseProgram) (cl_program); cl_int (* clReleaseContext) (cl_context); cl_int (* clEnqueueWriteBuffer) (cl_command_queue, cl_mem, cl_bool, size_t, size_t, void const *, cl_uint, cl_event const *, cl_event *); cl_int (* clEnqueueNDRangeKernel) (cl_command_queue, cl_kernel, cl_uint, size_t const *, size_t const *, size_t const *, cl_uint, cl_event const *, cl_event *); cl_int (* clEnqueueReadBuffer) (cl_command_queue, cl_mem, cl_bool, size_t, size_t, void *, cl_uint, cl_event const *, cl_event *); cl_int (* clFinish) (cl_command_queue); static opencl_initializer initializer; }; } opencl_initializer opencl_initializer::initializer; cl_int clGetPlatformIDs (cl_uint num_entries, cl_platform_id * platforms, cl_uint * num_platforms) { cl_int result; if (opencl_initializer::initializer.opencl_library != nullptr) { result = opencl_initializer::initializer.clGetPlatformIDs (num_entries, platforms, num_platforms); } else { result = CL_SUCCESS; *num_platforms = 0; } return result; } cl_int clGetPlatformInfo (cl_platform_id platform, cl_platform_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret) { return opencl_initializer::initializer::clGetPlatformInfo (platform, param_name, param_value_size, param_value, param_value_size_ret); } cl_int clGetDeviceIDs (cl_platform_id platform, cl_device_type device_type, cl_uint num_entries, cl_device_id * devices, cl_uint * num_devices) { return opencl_initializer::initializer::clGetDeviceIDs (platform, device_type, num_entries, devices, num_devices); } cl_int clGetDeviceInfo (cl_device_id device, cl_device_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret) { return opencl_initializer::initializer::clGetDeviceInfo (device, param_name, param_value_size, param_value, param_value_size_ret); } cl_context clCreateContext (cl_context_properties const * properties, cl_uint num_devices, cl_device_id const * devices, void (* pfn_notify)(const char *, const void *, size_t, void *), void * user_data, cl_int * errcode_ret) { return opencl_initializer::initializer::clCreateContext (properties, num_devices, devices, pfn_notify, user_data, errorcode_ret); } cl_command_queue clCreateCommandQueue (cl_context context, cl_device_id device, cl_command_queue_properties properties, cl_int * errcode_ret) { return opencl_initializer::initializer::clCreateCommandQueue (context, device, properties, errorcode_ret); } cl_mem clCreateBuffer (cl_context context, cl_mem_flags flags, size_t size, void * host_ptr, cl_int * errcode_ret) { return opencl_initializer::initializer::clCreateBuffer (context, flags, size, host_ptr, errorcode_ret); } cl_program clCreateProgramWithSource (cl_context context, cl_uint count, char const ** strings, size_t const * lengths, cl_int * errcode_ret) { return opencl_initializer::initializer::clCreateProgramWithSource (context, count, strings, lengths, errorcode_ret); } cl_int clBuildProgram (cl_program program, cl_uint num_devices, cl_device_id const * device_list, char const * options, void (*pfn_notify) (cl_program , void *), void * user_data) { return opencl_initializer::initializer::clBuildProgram (program, num_devices, device_list, options, pfn_notify, user_data); } cl_kernel clCreateKernel (cl_program program, char const * kernel_name, cl_int * errcode_ret) { return opencl_initializer::initializer::clCreateKernel (program, kernel_name, errorcode_ret); } cl_int clSetKernelArg (cl_kernel kernel, cl_uint arg_index, size_t arg_size, void const * arg_value) { return opencl_initializer::initializer::clSetKernelArg (kernel, arg_index, arg_size, arg_value); } cl_int clReleaseKernel (cl_kernel kernel) { return opencl_initializer::initializer::clReleaseKernel (kernel); } cl_int clReleaseProgram (cl_program program) { return opencl_initializer::initializer::clReleaseProgram (program); } cl_int clReleaseContext (cl_context context) { return opencl_initializer::initializer::clReleaseContext (context); } cl_int clEnqueueWriteBuffer (cl_command_queue command_queue, cl_mem buffer, cl_bool blocking_write, size_t offset, size_t size, void const * ptr, cl_uint num_events_in_wait_list, cl_event const * event_wait_list,cl_event * event) { return opencl_initializer::initializer::clEnqueueWriteBuffer (command_queue, buffer, blocking_write, offset, size, ptr, num_events_in_wait_list, event_wait_list, event); } cl_int clEnqueueNDRangeKernel (cl_command_queue command_queue, cl_kernel kernel, cl_uint work_dim, size_t const * global_work_offset, size_t const * global_work_size, size_t const * local_work_size, cl_uint num_events_in_wait_list, cl_event const * event_wait_list, cl_event * event) { return opencl_initializer::initializer::clEnqueueNDRangeKernel (command_queue, kernel, work_dim, global_work_offset, global_work_size, local_work_size, num_events_in_wait_list, event_wait_list, event); } cl_int clEnqueueReadBuffer (cl_command_queue command_queue, cl_mem buffer, cl_bool blocking_read, size_t offset, size_t size, void * ptr, cl_uint num_events_in_wait_list, cl_event const * event_wait_list, cl_event *event) { return opencl_initializer::initializer::clEnqueueReadBuffer (command_queue, buffer, blocking_read, offset, size, ptr, num_events_in_wait_list, event_wait_list, event); } cl_int clFinish (cl_command_queue command_queue) { return opencl_initializer::initializer::clFinish (command_queue); }<commit_msg>Fixing function calls.<commit_after>#include <rai/node/openclwork.hpp> #include <dlfcn.h> namespace { class opencl_initializer { public: opencl_initializer () { opencl_library = dlopen ("libOpenCL.so", RTLD_NOW); if (opencl_library != nullptr) { clGetPlatformIDs = reinterpret_cast <decltype (clGetPlatformIDs)> (dlsym (opencl_library, "clGetPlatformIDs")); } } ~opencl_initializer () { dlclose (opencl_library); } void * opencl_library; cl_int (* clGetPlatformIDs) (cl_uint, cl_platform_id *, cl_uint *); cl_int (* clGetPlatformInfo) (cl_platform_id, cl_platform_info, size_t, void *, size_t *); cl_int (* clGetDeviceIDs) (cl_platform_id, cl_device_type, cl_uint, cl_device_id *, cl_uint *); cl_int (* clGetDeviceInfo) (cl_device_id, cl_device_info, size_t, void *, size_t *); cl_context (* clCreateContext) (cl_context_properties const *, cl_uint, cl_device_id const *, void (*)(const char *, const void *, size_t, void *), void *, cl_int *); cl_command_queue (* clCreateCommandQueue) (cl_context, cl_device_id, cl_command_queue_properties, cl_int *); cl_mem (* clCreateBuffer) (cl_context, cl_mem_flags, size_t, void *, cl_int *); cl_program (* clCreateProgramWithSource) (cl_context, cl_uint, char const **, size_t const *, cl_int *); cl_int (* clBuildProgram) (cl_program, cl_uint, cl_device_id const *, char const *, void (*)(cl_program, void *), void *); cl_kernel (* clCreateKernel) (cl_program, char const *, cl_int *); cl_int (* clSetKernelArg) (cl_kernel, cl_uint, size_t, void const *); cl_int (* clReleaseKernel) (cl_kernel); cl_int (* clReleaseProgram) (cl_program); cl_int (* clReleaseContext) (cl_context); cl_int (* clEnqueueWriteBuffer) (cl_command_queue, cl_mem, cl_bool, size_t, size_t, void const *, cl_uint, cl_event const *, cl_event *); cl_int (* clEnqueueNDRangeKernel) (cl_command_queue, cl_kernel, cl_uint, size_t const *, size_t const *, size_t const *, cl_uint, cl_event const *, cl_event *); cl_int (* clEnqueueReadBuffer) (cl_command_queue, cl_mem, cl_bool, size_t, size_t, void *, cl_uint, cl_event const *, cl_event *); cl_int (* clFinish) (cl_command_queue); static opencl_initializer initializer; }; } opencl_initializer opencl_initializer::initializer; cl_int clGetPlatformIDs (cl_uint num_entries, cl_platform_id * platforms, cl_uint * num_platforms) { cl_int result; if (opencl_initializer::initializer.opencl_library != nullptr) { result = opencl_initializer::initializer.clGetPlatformIDs (num_entries, platforms, num_platforms); } else { result = CL_SUCCESS; *num_platforms = 0; } return result; } cl_int clGetPlatformInfo (cl_platform_id platform, cl_platform_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret) { return opencl_initializer::initializer.clGetPlatformInfo (platform, param_name, param_value_size, param_value, param_value_size_ret); } cl_int clGetDeviceIDs (cl_platform_id platform, cl_device_type device_type, cl_uint num_entries, cl_device_id * devices, cl_uint * num_devices) { return opencl_initializer::initializer.clGetDeviceIDs (platform, device_type, num_entries, devices, num_devices); } cl_int clGetDeviceInfo (cl_device_id device, cl_device_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret) { return opencl_initializer::initializer.clGetDeviceInfo (device, param_name, param_value_size, param_value, param_value_size_ret); } cl_context clCreateContext (cl_context_properties const * properties, cl_uint num_devices, cl_device_id const * devices, void (* pfn_notify)(const char *, const void *, size_t, void *), void * user_data, cl_int * errcode_ret) { return opencl_initializer::initializer.clCreateContext (properties, num_devices, devices, pfn_notify, user_data, errcode_ret); } cl_command_queue clCreateCommandQueue (cl_context context, cl_device_id device, cl_command_queue_properties properties, cl_int * errcode_ret) { return opencl_initializer::initializer.clCreateCommandQueue (context, device, properties, errcode_ret); } cl_mem clCreateBuffer (cl_context context, cl_mem_flags flags, size_t size, void * host_ptr, cl_int * errcode_ret) { return opencl_initializer::initializer.clCreateBuffer (context, flags, size, host_ptr, errcode_ret); } cl_program clCreateProgramWithSource (cl_context context, cl_uint count, char const ** strings, size_t const * lengths, cl_int * errcode_ret) { return opencl_initializer::initializer.clCreateProgramWithSource (context, count, strings, lengths, errcode_ret); } cl_int clBuildProgram (cl_program program, cl_uint num_devices, cl_device_id const * device_list, char const * options, void (*pfn_notify) (cl_program , void *), void * user_data) { return opencl_initializer::initializer.clBuildProgram (program, num_devices, device_list, options, pfn_notify, user_data); } cl_kernel clCreateKernel (cl_program program, char const * kernel_name, cl_int * errcode_ret) { return opencl_initializer::initializer.clCreateKernel (program, kernel_name, errcode_ret); } cl_int clSetKernelArg (cl_kernel kernel, cl_uint arg_index, size_t arg_size, void const * arg_value) { return opencl_initializer::initializer.clSetKernelArg (kernel, arg_index, arg_size, arg_value); } cl_int clReleaseKernel (cl_kernel kernel) { return opencl_initializer::initializer.clReleaseKernel (kernel); } cl_int clReleaseProgram (cl_program program) { return opencl_initializer::initializer.clReleaseProgram (program); } cl_int clReleaseContext (cl_context context) { return opencl_initializer::initializer.clReleaseContext (context); } cl_int clEnqueueWriteBuffer (cl_command_queue command_queue, cl_mem buffer, cl_bool blocking_write, size_t offset, size_t size, void const * ptr, cl_uint num_events_in_wait_list, cl_event const * event_wait_list,cl_event * event) { return opencl_initializer::initializer.clEnqueueWriteBuffer (command_queue, buffer, blocking_write, offset, size, ptr, num_events_in_wait_list, event_wait_list, event); } cl_int clEnqueueNDRangeKernel (cl_command_queue command_queue, cl_kernel kernel, cl_uint work_dim, size_t const * global_work_offset, size_t const * global_work_size, size_t const * local_work_size, cl_uint num_events_in_wait_list, cl_event const * event_wait_list, cl_event * event) { return opencl_initializer::initializer.clEnqueueNDRangeKernel (command_queue, kernel, work_dim, global_work_offset, global_work_size, local_work_size, num_events_in_wait_list, event_wait_list, event); } cl_int clEnqueueReadBuffer (cl_command_queue command_queue, cl_mem buffer, cl_bool blocking_read, size_t offset, size_t size, void * ptr, cl_uint num_events_in_wait_list, cl_event const * event_wait_list, cl_event *event) { return opencl_initializer::initializer.clEnqueueReadBuffer (command_queue, buffer, blocking_read, offset, size, ptr, num_events_in_wait_list, event_wait_list, event); } cl_int clFinish (cl_command_queue command_queue) { return opencl_initializer::initializer.clFinish (command_queue); } <|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 whisperMessage.cpp * @author Vladislav Gluhovsky <vlad@ethdev.com> * @date June 2015 */ #include <boost/test/unit_test.hpp> #include <libdevcore/SHA3.h> #include <libwhisper/BloomFilter.h> using namespace std; using namespace dev; using namespace dev::shh; void testAddNonExisting(TopicBloomFilter& _f, AbridgedTopic const& _h) { BOOST_REQUIRE(!_f.containsRaw(_h)); _f.addRaw(_h); BOOST_REQUIRE(_f.containsRaw(_h)); } void testRemoveExisting(TopicBloomFilter& _f, AbridgedTopic const& _h) { BOOST_REQUIRE(_f.containsRaw(_h)); _f.removeRaw(_h); BOOST_REQUIRE(!_f.containsRaw(_h)); } void testAddNonExistingBloom(TopicBloomFilter& _f, AbridgedTopic const& _h) { BOOST_REQUIRE(!_f.containsBloom(_h)); _f.addBloom(_h); BOOST_REQUIRE(_f.containsBloom(_h)); } void testRemoveExistingBloom(TopicBloomFilter& _f, AbridgedTopic const& _h) { BOOST_REQUIRE(_f.containsBloom(_h)); _f.removeBloom(_h); BOOST_REQUIRE(!_f.containsBloom(_h)); } BOOST_AUTO_TEST_SUITE(bloomFilter) BOOST_AUTO_TEST_CASE(bloomFilterRandom) { VerbosityHolder setTemporaryLevel(10); cnote << "Testing Bloom Filter matching..."; TopicBloomFilter f; vector<AbridgedTopic> vec; Topic x(0xDEADBEEF); int const c_rounds = 4; for (int i = 0; i < c_rounds; ++i, x = sha3(x)) vec.push_back(abridge(x)); for (int i = 0; i < c_rounds; ++i) testAddNonExisting(f, vec[i]); for (int i = 0; i < c_rounds; ++i) testRemoveExisting(f, vec[i]); for (int i = 0; i < c_rounds; ++i) testAddNonExistingBloom(f, vec[i]); for (int i = 0; i < c_rounds; ++i) testRemoveExistingBloom(f, vec[i]); } BOOST_AUTO_TEST_CASE(bloomFilterRaw) { VerbosityHolder setTemporaryLevel(10); cnote << "Testing Raw Bloom matching..."; TopicBloomFilter f; AbridgedTopic b00000001(0x01); AbridgedTopic b00010000(0x10); AbridgedTopic b00011000(0x18); AbridgedTopic b00110000(0x30); AbridgedTopic b00110010(0x32); AbridgedTopic b00111000(0x38); AbridgedTopic b00000110(0x06); AbridgedTopic b00110110(0x36); AbridgedTopic b00110111(0x37); testAddNonExisting(f, b00000001); testAddNonExisting(f, b00010000); testAddNonExisting(f, b00011000); testAddNonExisting(f, b00110000); BOOST_REQUIRE(f.contains(b00111000)); testAddNonExisting(f, b00110010); testAddNonExisting(f, b00000110); BOOST_REQUIRE(f.contains(b00110110)); BOOST_REQUIRE(f.contains(b00110111)); f.removeRaw(b00000001); f.removeRaw(b00000001); f.removeRaw(b00000001); BOOST_REQUIRE(!f.contains(b00000001)); BOOST_REQUIRE(f.contains(b00010000)); BOOST_REQUIRE(f.contains(b00011000)); BOOST_REQUIRE(f.contains(b00110000)); BOOST_REQUIRE(f.contains(b00110010)); BOOST_REQUIRE(f.contains(b00111000)); BOOST_REQUIRE(f.contains(b00000110)); BOOST_REQUIRE(f.contains(b00110110)); BOOST_REQUIRE(!f.contains(b00110111)); f.removeRaw(b00010000); BOOST_REQUIRE(!f.contains(b00000001)); BOOST_REQUIRE(f.contains(b00010000)); BOOST_REQUIRE(f.contains(b00011000)); BOOST_REQUIRE(f.contains(b00110000)); BOOST_REQUIRE(f.contains(b00110010)); BOOST_REQUIRE(f.contains(b00111000)); BOOST_REQUIRE(f.contains(b00000110)); BOOST_REQUIRE(f.contains(b00110110)); BOOST_REQUIRE(!f.contains(b00110111)); f.removeRaw(b00111000); BOOST_REQUIRE(!f.contains(b00000001)); BOOST_REQUIRE(f.contains(b00010000)); BOOST_REQUIRE(!f.contains(b00011000)); BOOST_REQUIRE(f.contains(b00110000)); BOOST_REQUIRE(f.contains(b00110010)); BOOST_REQUIRE(!f.contains(b00111000)); BOOST_REQUIRE(f.contains(b00000110)); BOOST_REQUIRE(f.contains(b00110110)); BOOST_REQUIRE(!f.contains(b00110111)); f.addRaw(b00000001); BOOST_REQUIRE(f.contains(b00000001)); BOOST_REQUIRE(f.contains(b00010000)); BOOST_REQUIRE(!f.contains(b00011000)); BOOST_REQUIRE(f.contains(b00110000)); BOOST_REQUIRE(f.contains(b00110010)); BOOST_REQUIRE(!f.contains(b00111000)); BOOST_REQUIRE(f.contains(b00000110)); BOOST_REQUIRE(f.contains(b00110110)); BOOST_REQUIRE(f.contains(b00110111)); f.removeRaw(b00110111); BOOST_REQUIRE(!f.contains(b00000001)); BOOST_REQUIRE(f.contains(b00010000)); BOOST_REQUIRE(!f.contains(b00011000)); BOOST_REQUIRE(!f.contains(b00110000)); BOOST_REQUIRE(!f.contains(b00110010)); BOOST_REQUIRE(!f.contains(b00111000)); BOOST_REQUIRE(!f.contains(b00000110)); BOOST_REQUIRE(!f.contains(b00110110)); BOOST_REQUIRE(!f.contains(b00110111)); f.removeRaw(b00110111); BOOST_REQUIRE(!f.contains(b00000001)); BOOST_REQUIRE(!f.contains(b00010000)); BOOST_REQUIRE(!f.contains(b00011000)); BOOST_REQUIRE(!f.contains(b00110000)); BOOST_REQUIRE(!f.contains(b00110010)); BOOST_REQUIRE(!f.contains(b00111000)); BOOST_REQUIRE(!f.contains(b00000110)); BOOST_REQUIRE(!f.contains(b00110110)); BOOST_REQUIRE(!f.contains(b00110111)); } BOOST_AUTO_TEST_SUITE_END()<commit_msg>false positive test introduced<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 whisperMessage.cpp * @author Vladislav Gluhovsky <vlad@ethdev.com> * @date June 2015 */ #include <boost/test/unit_test.hpp> #include <libdevcore/SHA3.h> #include <libwhisper/BloomFilter.h> using namespace std; using namespace dev; using namespace dev::shh; void testAddNonExisting(TopicBloomFilter& _f, AbridgedTopic const& _h) { BOOST_REQUIRE(!_f.containsRaw(_h)); _f.addRaw(_h); BOOST_REQUIRE(_f.containsRaw(_h)); } void testRemoveExisting(TopicBloomFilter& _f, AbridgedTopic const& _h) { BOOST_REQUIRE(_f.containsRaw(_h)); _f.removeRaw(_h); BOOST_REQUIRE(!_f.containsRaw(_h)); } void testAddNonExistingBloom(TopicBloomFilter& _f, AbridgedTopic const& _h) { BOOST_REQUIRE(!_f.containsBloom(_h)); _f.addBloom(_h); BOOST_REQUIRE(_f.containsBloom(_h)); } void testRemoveExistingBloom(TopicBloomFilter& _f, AbridgedTopic const& _h) { BOOST_REQUIRE(_f.containsBloom(_h)); _f.removeBloom(_h); BOOST_REQUIRE(!_f.containsBloom(_h)); } int calculateExpected(TopicBloomFilter const& f, int const n) { int const m = f.size * 8; // number of bits in the bloom int const k = f.BitsPerBloom; // number of hash functions (e.g. bits set to 1 in every bloom) double singleBitSet = 1.0 / m; // probability of any bit being set after inserting a single bit double singleBitNotSet = (1.0 - singleBitSet); double singleNot = 1; // single bit not set after inserting N elements in the bloom filter for (int i = 0; i < k * n; ++i) singleNot *= singleBitNotSet; double single = 1.0 - singleNot; // probability of a single bit being set after inserting N elements in the bloom filter double kBitsSet = 1; // probability of K bits being set after inserting N elements in the bloom filter for (int i = 0; i < k; ++i) kBitsSet *= single; return static_cast<int>(kBitsSet * 100 + 0.5); // in percents, rounded up } void testFalsePositiveRate(TopicBloomFilter const& f, int const inserted, Topic& x) { int const c_sampleSize = 1000; int falsePositive = 0; for (int i = 0; i < c_sampleSize; ++i) { x = sha3(x); AbridgedTopic a(x); if (f.containsBloom(a)) ++falsePositive; } falsePositive /= (c_sampleSize / 100); // in percents int expected = calculateExpected(f, inserted); int allowed = expected + (expected / 5); // allow deviations ~20% //cnote << "Inserted: " << inserted << ", False Positive Rate: " << falsePositive << ", Expected: " << expected; BOOST_REQUIRE(falsePositive <= allowed); } BOOST_AUTO_TEST_SUITE(bloomFilter) BOOST_AUTO_TEST_CASE(falsePositiveRate) { VerbosityHolder setTemporaryLevel(10); cnote << "Testing Bloom Filter False Positive Rate..."; TopicBloomFilter f; Topic x(0xABCDEF); // deterministic pseudorandom value for (int i = 1; i < 21; ++i) { x = sha3(x); f.addBloom(AbridgedTopic(x)); testFalsePositiveRate(f, i, x); } } BOOST_AUTO_TEST_CASE(bloomFilterRandom) { VerbosityHolder setTemporaryLevel(10); cnote << "Testing Bloom Filter matching..."; TopicBloomFilter f; vector<AbridgedTopic> vec; Topic x(0xDEADBEEF); int const c_rounds = 4; for (int i = 0; i < c_rounds; ++i, x = sha3(x)) vec.push_back(abridge(x)); for (int i = 0; i < c_rounds; ++i) testAddNonExisting(f, vec[i]); for (int i = 0; i < c_rounds; ++i) testRemoveExisting(f, vec[i]); for (int i = 0; i < c_rounds; ++i) testAddNonExistingBloom(f, vec[i]); for (int i = 0; i < c_rounds; ++i) testRemoveExistingBloom(f, vec[i]); } BOOST_AUTO_TEST_CASE(bloomFilterRaw) { VerbosityHolder setTemporaryLevel(10); cnote << "Testing Raw Bloom matching..."; TopicBloomFilter f; AbridgedTopic b00000001(0x01); AbridgedTopic b00010000(0x10); AbridgedTopic b00011000(0x18); AbridgedTopic b00110000(0x30); AbridgedTopic b00110010(0x32); AbridgedTopic b00111000(0x38); AbridgedTopic b00000110(0x06); AbridgedTopic b00110110(0x36); AbridgedTopic b00110111(0x37); testAddNonExisting(f, b00000001); testAddNonExisting(f, b00010000); testAddNonExisting(f, b00011000); testAddNonExisting(f, b00110000); BOOST_REQUIRE(f.contains(b00111000)); testAddNonExisting(f, b00110010); testAddNonExisting(f, b00000110); BOOST_REQUIRE(f.contains(b00110110)); BOOST_REQUIRE(f.contains(b00110111)); f.removeRaw(b00000001); f.removeRaw(b00000001); f.removeRaw(b00000001); BOOST_REQUIRE(!f.contains(b00000001)); BOOST_REQUIRE(f.contains(b00010000)); BOOST_REQUIRE(f.contains(b00011000)); BOOST_REQUIRE(f.contains(b00110000)); BOOST_REQUIRE(f.contains(b00110010)); BOOST_REQUIRE(f.contains(b00111000)); BOOST_REQUIRE(f.contains(b00000110)); BOOST_REQUIRE(f.contains(b00110110)); BOOST_REQUIRE(!f.contains(b00110111)); f.removeRaw(b00010000); BOOST_REQUIRE(!f.contains(b00000001)); BOOST_REQUIRE(f.contains(b00010000)); BOOST_REQUIRE(f.contains(b00011000)); BOOST_REQUIRE(f.contains(b00110000)); BOOST_REQUIRE(f.contains(b00110010)); BOOST_REQUIRE(f.contains(b00111000)); BOOST_REQUIRE(f.contains(b00000110)); BOOST_REQUIRE(f.contains(b00110110)); BOOST_REQUIRE(!f.contains(b00110111)); f.removeRaw(b00111000); BOOST_REQUIRE(!f.contains(b00000001)); BOOST_REQUIRE(f.contains(b00010000)); BOOST_REQUIRE(!f.contains(b00011000)); BOOST_REQUIRE(f.contains(b00110000)); BOOST_REQUIRE(f.contains(b00110010)); BOOST_REQUIRE(!f.contains(b00111000)); BOOST_REQUIRE(f.contains(b00000110)); BOOST_REQUIRE(f.contains(b00110110)); BOOST_REQUIRE(!f.contains(b00110111)); f.addRaw(b00000001); BOOST_REQUIRE(f.contains(b00000001)); BOOST_REQUIRE(f.contains(b00010000)); BOOST_REQUIRE(!f.contains(b00011000)); BOOST_REQUIRE(f.contains(b00110000)); BOOST_REQUIRE(f.contains(b00110010)); BOOST_REQUIRE(!f.contains(b00111000)); BOOST_REQUIRE(f.contains(b00000110)); BOOST_REQUIRE(f.contains(b00110110)); BOOST_REQUIRE(f.contains(b00110111)); f.removeRaw(b00110111); BOOST_REQUIRE(!f.contains(b00000001)); BOOST_REQUIRE(f.contains(b00010000)); BOOST_REQUIRE(!f.contains(b00011000)); BOOST_REQUIRE(!f.contains(b00110000)); BOOST_REQUIRE(!f.contains(b00110010)); BOOST_REQUIRE(!f.contains(b00111000)); BOOST_REQUIRE(!f.contains(b00000110)); BOOST_REQUIRE(!f.contains(b00110110)); BOOST_REQUIRE(!f.contains(b00110111)); f.removeRaw(b00110111); BOOST_REQUIRE(!f.contains(b00000001)); BOOST_REQUIRE(!f.contains(b00010000)); BOOST_REQUIRE(!f.contains(b00011000)); BOOST_REQUIRE(!f.contains(b00110000)); BOOST_REQUIRE(!f.contains(b00110010)); BOOST_REQUIRE(!f.contains(b00111000)); BOOST_REQUIRE(!f.contains(b00000110)); BOOST_REQUIRE(!f.contains(b00110110)); BOOST_REQUIRE(!f.contains(b00110111)); } BOOST_AUTO_TEST_SUITE_END()<|endoftext|>
<commit_before>/* * This file is part of ATLAS. It is subject to the license terms in * the LICENSE file found in the top-level directory of this distribution. * (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt) * You may not use this file except in compliance with the License. */ #include <iostream> #include <assimp/postprocess.h> #include <assimp/scene.h> #include "AssimpImporter.hpp" namespace AssimpWorker { AssimpImporter::AssimpImporter() : importer() { return; } AssimpImporter::~AssimpImporter(){ return; } const aiScene* AssimpImporter::importSceneFromFile(std::string fileName, Log& log){ importer.SetPropertyBool(AI_CONFIG_PP_FD_REMOVE, true); //remove degenerate polys importer.SetPropertyBool(AI_CONFIG_IMPORT_NO_SKELETON_MESHES, true); //do not import skeletons importer.SetPropertyBool(AI_CONFIG_IMPORT_COLLADA_IGNORE_UP_DIRECTION, true); importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT); //Drop all primitives that aren't triangles const aiScene* scene = importer.ReadFile(fileName, aiProcessPreset_TargetRealtime_Quality); if (!scene) { log.error("Scene not imported: "+fileName); } log.error(importer.GetErrorString()); return scene; } } <commit_msg>Remove no longer necessary assimp import flag<commit_after>/* * This file is part of ATLAS. It is subject to the license terms in * the LICENSE file found in the top-level directory of this distribution. * (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt) * You may not use this file except in compliance with the License. */ #include <iostream> #include <assimp/postprocess.h> #include <assimp/scene.h> #include "AssimpImporter.hpp" namespace AssimpWorker { AssimpImporter::AssimpImporter() : importer() { return; } AssimpImporter::~AssimpImporter(){ return; } const aiScene* AssimpImporter::importSceneFromFile(std::string fileName, Log& log){ importer.SetPropertyBool(AI_CONFIG_PP_FD_REMOVE, true); //remove degenerate polys importer.SetPropertyBool(AI_CONFIG_IMPORT_NO_SKELETON_MESHES, true); //do not import skeletons importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT); //Drop all primitives that aren't triangles const aiScene* scene = importer.ReadFile(fileName, aiProcessPreset_TargetRealtime_Quality); if (!scene) { log.error("Scene not imported: "+fileName); } log.error(importer.GetErrorString()); return scene; } } <|endoftext|>
<commit_before>/** * @file llimage_libtest.cpp * @author Merov Linden * @brief Integration test for the llimage library * * $LicenseInfo:firstyear=2011&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2011, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "linden_common.h" #include "llpointer.h" #include "llimage_libtest.h" // Linden library includes #include "llimage.h" #include "llimagejpeg.h" #include "llimagepng.h" #include "llimagebmp.h" #include "llimagetga.h" #include "llimagej2c.h" #include "lldir.h" // system libraries #include <iostream> // doc string provided when invoking the program with --help static const char USAGE[] = "\n" "usage:\tllimage_libtest [options]\n" "\n" " --help print this help\n" " --in <file1> <file2>... list of image files to load and convert\n" " --out <file1> <file2>... list of image files to create (assumes same order as --in files)\n" "\n"; // Create an empty formatted image instance of the correct type from the filename LLPointer<LLImageFormatted> create_image(const std::string &filename) { std::string exten = gDirUtilp->getExtension(filename); U32 codec = LLImageBase::getCodecFromExtension(exten); LLPointer<LLImageFormatted> image; switch (codec) { case IMG_CODEC_BMP: image = new LLImageBMP(); break; case IMG_CODEC_TGA: image = new LLImageTGA(); break; case IMG_CODEC_JPEG: image = new LLImageJPEG(); break; case IMG_CODEC_J2C: image = new LLImageJ2C(); break; case IMG_CODEC_PNG: image = new LLImagePNG(); break; default: return NULL; } return image; } // Load an image from file and return a raw (decompressed) instance of its data LLPointer<LLImageRaw> load_image(const std::string &src_filename) { LLPointer<LLImageFormatted> image = create_image(src_filename); if (!image->load(src_filename)) { return NULL; } if( (image->getComponents() != 3) && (image->getComponents() != 4) ) { std::cout << "Image files with less than 3 or more than 4 components are not supported\n"; return NULL; } LLPointer<LLImageRaw> raw_image = new LLImageRaw; if (!image->decode(raw_image, 0.0f)) { return NULL; } return raw_image; } // Save a raw image instance into a file bool save_image(const std::string &dest_filename, LLPointer<LLImageRaw> raw_image) { LLPointer<LLImageFormatted> image = create_image(dest_filename); if (!image->encode(raw_image, 0.0f)) { return false; } return image->save(dest_filename); } int main(int argc, char** argv) { // List of input and output files std::list<std::string> input_filenames; std::list<std::string> output_filenames; // Init whatever is necessary ll_init_apr(); LLImage::initClass(); // Analyze command line arguments for (int arg = 1; arg < argc; ++arg) { if (!strcmp(argv[arg], "--help")) { // Send the usage to standard out std::cout << USAGE << std::endl; return 0; } else if (!strcmp(argv[arg], "--in") && arg < argc-1) { std::string file_name = argv[arg+1]; while (file_name[0] != '-') // if arg starts with '-', we consider it's not a file name but some other argument { input_filenames.push_back(file_name); // Add file name to the list arg += 1; // Skip that arg now we know it's a file name if ((arg + 1) == argc) // Break out of the loop if we reach the end of the arg list break; file_name = argv[arg+1]; // Next argument and loop over } } else if (!strcmp(argv[arg], "--out") && arg < argc-1) { std::string file_name = argv[arg+1]; while (file_name[0] != '-') // if arg starts with '-', we consider it's not a file name but some other argument { output_filenames.push_back(file_name); // Add file name to the list arg += 1; // Skip that arg now we know it's a file name if ((arg + 1) == argc) // Break out of the loop if we reach the end of the arg list break; file_name = argv[arg+1]; // Next argument and loop over } } } // Analyze the list of (input,output) files if (input_filenames.size() == 0) { std::cout << "No input file, nothing to do -> exit" << std::endl; return 0; } // TODO: For the moment, we simply convert each input file to something. This needs to evolve... if (input_filenames.size() != output_filenames.size()) { std::cout << "Number of output and input files different -> exit" << std::endl; return 0; } std::list<std::string>::iterator in_file = input_filenames.begin(); std::list<std::string>::iterator out_file = output_filenames.begin(); std::list<std::string>::iterator end = input_filenames.end(); for (; in_file != end; ++in_file, ++out_file) { // Load file LLPointer<LLImageRaw> raw_image = load_image(*in_file); if (!raw_image) { std::cout << "Error: Image " << *in_file << " could not be loaded" << std::endl; continue; } // Save file if (!save_image(*out_file, raw_image)) { std::cout << "Error: Image " << *out_file << " could not be saved" << std::endl; continue; } std::cout << *in_file << " -> " << *out_file << std::endl; // Output stats on each file } // Cleanup and exit LLImage::cleanupClass(); return 0; } <commit_msg>STORM-987 : Implement in and out list of files and pattern matching<commit_after>/** * @file llimage_libtest.cpp * @author Merov Linden * @brief Integration test for the llimage library * * $LicenseInfo:firstyear=2011&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2011, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "linden_common.h" #include "llpointer.h" #include "llimage_libtest.h" // Linden library includes #include "llimage.h" #include "llimagejpeg.h" #include "llimagepng.h" #include "llimagebmp.h" #include "llimagetga.h" #include "llimagej2c.h" #include "lldir.h" // system libraries #include <iostream> // doc string provided when invoking the program with --help static const char USAGE[] = "\n" "usage:\tllimage_libtest [options]\n" "\n" " --help print this help\n" " --in <file1 .. file2> list of image files to load and convert, patterns can be used\n" " --out <file1 .. file2> OR <type> list of image files to create (assumes same order as --in files)\n" " OR 3 letters file type extension to convert each input file into\n" "\n"; // Create an empty formatted image instance of the correct type from the filename LLPointer<LLImageFormatted> create_image(const std::string &filename) { std::string exten = gDirUtilp->getExtension(filename); U32 codec = LLImageBase::getCodecFromExtension(exten); LLPointer<LLImageFormatted> image; switch (codec) { case IMG_CODEC_BMP: image = new LLImageBMP(); break; case IMG_CODEC_TGA: image = new LLImageTGA(); break; case IMG_CODEC_JPEG: image = new LLImageJPEG(); break; case IMG_CODEC_J2C: image = new LLImageJ2C(); break; case IMG_CODEC_PNG: image = new LLImagePNG(); break; default: return NULL; } return image; } // Load an image from file and return a raw (decompressed) instance of its data LLPointer<LLImageRaw> load_image(const std::string &src_filename) { LLPointer<LLImageFormatted> image = create_image(src_filename); if (!image->load(src_filename)) { return NULL; } if( (image->getComponents() != 3) && (image->getComponents() != 4) ) { std::cout << "Image files with less than 3 or more than 4 components are not supported\n"; return NULL; } LLPointer<LLImageRaw> raw_image = new LLImageRaw; if (!image->decode(raw_image, 0.0f)) { return NULL; } return raw_image; } // Save a raw image instance into a file bool save_image(const std::string &dest_filename, LLPointer<LLImageRaw> raw_image) { LLPointer<LLImageFormatted> image = create_image(dest_filename); if (!image->encode(raw_image, 0.0f)) { return false; } return image->save(dest_filename); } void store_input_file(std::list<std::string> &input_filenames, const std::string &path) { // Break the incoming path in its components std::string dir = gDirUtilp->getDirName(path); std::string name = gDirUtilp->getBaseFileName(path); std::string exten = gDirUtilp->getExtension(path); // std::cout << "store_input_file : " << path << ", dir : " << dir << ", name : " << name << ", exten : " << exten << std::endl; // If extension is not an image type or "*", exit // Note: we don't support complex patterns for the extension like "j??" // Note: on most shells, the pattern expansion is done by the shell so that pattern matching limitation is actually not a problem if ((exten.compare("*") != 0) && (LLImageBase::getCodecFromExtension(exten) == IMG_CODEC_INVALID)) { return; } if ((name.find('*') != -1) || ((name.find('?') != -1))) { // If file name is a pattern, iterate to get each file name and store std::string next_name; while (gDirUtilp->getNextFileInDir(dir,name,next_name)) { std::string file_name = dir + gDirUtilp->getDirDelimiter() + next_name; input_filenames.push_back(file_name); } } else { // Verify that the file does exist before storing if (gDirUtilp->fileExists(path)) { input_filenames.push_back(path); } else { std::cout << "store_input_file : the file " << path << " could not be found" << std::endl; } } } void store_output_file(std::list<std::string> &output_filenames, std::list<std::string> &input_filenames, const std::string &path) { // Break the incoming path in its components std::string dir = gDirUtilp->getDirName(path); std::string name = gDirUtilp->getBaseFileName(path); std::string exten = gDirUtilp->getExtension(path); // std::cout << "store_output_file : " << path << ", dir : " << dir << ", name : " << name << ", exten : " << exten << std::endl; if (dir.empty() && exten.empty()) { // If dir and exten are empty, we interpret the name as a file extension type name and will iterate through input list to populate the output list exten = name; // Make sure the extension is an image type if (LLImageBase::getCodecFromExtension(exten) == IMG_CODEC_INVALID) { return; } std::string delim = gDirUtilp->getDirDelimiter(); std::list<std::string>::iterator in_file = input_filenames.begin(); std::list<std::string>::iterator end = input_filenames.end(); for (; in_file != end; ++in_file) { dir = gDirUtilp->getDirName(*in_file); name = gDirUtilp->getBaseFileName(*in_file,true); std::string file_name = dir + delim + name + "." + exten; output_filenames.push_back(file_name); } } else { // Make sure the extension is an image type if (LLImageBase::getCodecFromExtension(exten) == IMG_CODEC_INVALID) { return; } // Store the path output_filenames.push_back(path); } } int main(int argc, char** argv) { // List of input and output files std::list<std::string> input_filenames; std::list<std::string> output_filenames; // Init whatever is necessary ll_init_apr(); LLImage::initClass(); // Analyze command line arguments for (int arg = 1; arg < argc; ++arg) { if (!strcmp(argv[arg], "--help")) { // Send the usage to standard out std::cout << USAGE << std::endl; return 0; } else if (!strcmp(argv[arg], "--in") && arg < argc-1) { std::string file_name = argv[arg+1]; while (file_name[0] != '-') // if arg starts with '-', we consider it's not a file name but some other argument { // std::cout << "input file name : " << file_name << std::endl; store_input_file(input_filenames, file_name); arg += 1; // Skip that arg now we know it's a file name if ((arg + 1) == argc) // Break out of the loop if we reach the end of the arg list break; file_name = argv[arg+1]; // Next argument and loop over } // DEBUG output std::list<std::string>::iterator in_file = input_filenames.begin(); std::list<std::string>::iterator end = input_filenames.end(); for (; in_file != end; ++in_file) { std::cout << "input file : " << *in_file << std::endl; } } else if (!strcmp(argv[arg], "--out") && arg < argc-1) { std::string file_name = argv[arg+1]; while (file_name[0] != '-') // if arg starts with '-', we consider it's not a file name but some other argument { // std::cout << "output file name : " << file_name << std::endl; store_output_file(output_filenames, input_filenames, file_name); arg += 1; // Skip that arg now we know it's a file name if ((arg + 1) == argc) // Break out of the loop if we reach the end of the arg list break; file_name = argv[arg+1]; // Next argument and loop over } // DEBUG output std::list<std::string>::iterator out_file = output_filenames.begin(); std::list<std::string>::iterator end = output_filenames.end(); for (; out_file != end; ++out_file) { std::cout << "output file : " << *out_file << std::endl; } } } // Analyze the list of (input,output) files if (input_filenames.size() == 0) { std::cout << "No input file, nothing to do -> exit" << std::endl; return 0; } std::list<std::string>::iterator in_file = input_filenames.begin(); std::list<std::string>::iterator out_file = output_filenames.begin(); std::list<std::string>::iterator end = input_filenames.end(); for (; in_file != end; ++in_file, ++out_file) { // Load file LLPointer<LLImageRaw> raw_image = load_image(*in_file); if (!raw_image) { std::cout << "Error: Image " << *in_file << " could not be loaded" << std::endl; continue; } // Save file if (!save_image(*out_file, raw_image)) { std::cout << "Error: Image " << *out_file << " could not be saved" << std::endl; continue; } std::cout << *in_file << " -> " << *out_file << std::endl; // Output stats on each file } // Cleanup and exit LLImage::cleanupClass(); return 0; } <|endoftext|>
<commit_before>//============================================================================================================= /** * @file frequencyspectrumdelegate.cpp * @author Christoph Dinh <chdinh@nmr.mgh.harvard.edu>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date May, 2014 * * @section LICENSE * * Copyright (C) 2014, Christoph Dinh and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief Implementation of the FrequencySpectrumDelegate Class. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "frequencyspectrumdelegate.h" #include "frequencyspectrummodel.h" //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QPainter> #include <QPainterPath> #include <QDebug> #include <QThread> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace XDISPLIB; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= FrequencySpectrumDelegate::FrequencySpectrumDelegate(QObject *parent) : QAbstractItemDelegate(parent) { } //************************************************************************************************************* void FrequencySpectrumDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { float t_fPlotHeight = option.rect.height(); switch(index.column()) { case 0: { //chnames painter->save(); painter->rotate(-90); painter->drawText(QRectF(-option.rect.y()-t_fPlotHeight,0,t_fPlotHeight,20),Qt::AlignCenter,index.model()->data(index,Qt::DisplayRole).toString()); painter->restore(); break; } case 1: { //data plot painter->save(); //draw special background when channel is marked as bad // QVariant v = index.model()->data(index,Qt::BackgroundRole); // if(v.canConvert<QBrush>() && !(option.state & QStyle::State_Selected)) { // QPointF oldBO = painter->brushOrigin(); // painter->setBrushOrigin(option.rect.topLeft()); // painter->fillRect(option.rect, qvariant_cast<QBrush>(v)); // painter->setBrushOrigin(oldBO); // } // //Highlight selected channels // if(option.state & QStyle::State_Selected) { // QPointF oldBO = painter->brushOrigin(); // painter->setBrushOrigin(option.rect.topLeft()); // painter->fillRect(option.rect, option.palette.highlight()); // painter->setBrushOrigin(oldBO); // } //Get data QVariant variant = index.model()->data(index,Qt::DisplayRole); RowVectorXd data = variant.value< RowVectorXd >(); const FrequencySpectrumModel* t_pModel = static_cast<const FrequencySpectrumModel*>(index.model()); if(data.size() > 0) { QPainterPath path(QPointF(option.rect.x(),option.rect.y()));//QPointF(option.rect.x()+t_rtmsaModel->relFiffCursor()-1,option.rect.y())); //Plot grid painter->setRenderHint(QPainter::Antialiasing, false); createGridPath(index, option, path, data); createGridTick(index, option, painter); painter->save(); QPen pen; pen.setStyle(Qt::DotLine); pen.setWidthF(0.5); painter->setPen(pen); painter->drawPath(path); painter->restore(); //Plot data path path = QPainterPath(QPointF(option.rect.x(),option.rect.y()));//QPointF(option.rect.x()+t_rtmsaModel->relFiffCursor(),option.rect.y())); createPlotPath(index, option, path, data); painter->save(); painter->translate(0,t_fPlotHeight/2); painter->setRenderHint(QPainter::Antialiasing, true); if(option.state & QStyle::State_Selected) painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkRed : Qt::red, 1, Qt::SolidLine)); else painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkGray : Qt::darkBlue, 1, Qt::SolidLine)); painter->drawPath(path); painter->restore(); } painter->restore(); break; } } } //************************************************************************************************************* QSize FrequencySpectrumDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { QSize size; switch(index.column()) { case 0: size = QSize(20,option.rect.height()); break; case 1: RowVectorXd data = index.model()->data(index).value< RowVectorXd >(); // qint32 nsamples = (static_cast<const FrequencySpectrumModel*>(index.model()))->lastSample()-(static_cast<const FrequencySpectrumModel*>(index.model()))->firstSample(); // size = QSize(nsamples*m_dDx,m_dPlotHeight); Q_UNUSED(option); break; } return size; } //************************************************************************************************************* void FrequencySpectrumDelegate::createPlotPath(const QModelIndex &index, const QStyleOptionViewItem &option, QPainterPath& path, RowVectorXd& data) const { const FrequencySpectrumModel* t_pModel = static_cast<const FrequencySpectrumModel*>(index.model()); float fMaxValue = data.maxCoeff(); float fValue; float fScaleY = option.rect.height()/(fMaxValue*0.5); float y_base = path.currentPosition().y(); QPointF qSamplePosition; //Move to initial starting point if(data.size() > 0) { float val = 0; fValue = val*fScaleY; float newY = y_base+fValue; qSamplePosition.setY(newY); qSamplePosition.setX((double)option.rect.width()*t_pModel->getFreqScale()[0]); path.moveTo(qSamplePosition); } //create lines from one to the next sample qint32 i; for(i = 1; i < data.size(); ++i) { float val = data[i]-data[0]; //remove first sample data[0] as offset fValue = val*fScaleY; float newY = y_base+fValue; qSamplePosition.setY(newY); qSamplePosition.setX((double)option.rect.width()*t_pModel->getFreqScale()[i]); path.lineTo(qSamplePosition); } } //************************************************************************************************************* void FrequencySpectrumDelegate::createGridPath(const QModelIndex &index, const QStyleOptionViewItem &option, QPainterPath& path, RowVectorXd& data) const { Q_UNUSED(data) const FrequencySpectrumModel* t_pModel = static_cast<const FrequencySpectrumModel*>(index.model()); if(t_pModel->getInfo()) { double fs = t_pModel->getInfo()->sfreq/2; qint32 numLines = (qint32)ceil(log10(fs)); QList<qint32> qListLineSamples; for(qint32 lineIdx = 0; lineIdx < numLines; ++lineIdx) { double val = pow(10,lineIdx); qint32 idx = (qint32)floor((val/fs) * t_pModel->getNumStems()); qListLineSamples.append(idx); } //vertical lines float yStart = option.rect.topLeft().y(); float yEnd = option.rect.bottomRight().y(); for(qint32 i = 0; i < qListLineSamples.size(); ++i) { float x = (t_pModel->getFreqScale()[qListLineSamples[i]])*option.rect.width(); path.moveTo(x,yStart); path.lineTo(x,yEnd); } /* //horizontal lines float xStart = option.rect.topLeft().x(); float xEnd = option.rect.bottomRight().x(); for(qint32 i = 0; i < 6; ++i) { float y = option.rect.height()/5.0 * (float)i; path.moveTo(xStart,y); path.lineTo(xEnd,y); } */ } } //************************************************************************************************************* void FrequencySpectrumDelegate::createGridTick(const QModelIndex &index, const QStyleOptionViewItem &option, QPainter *painter) const { const FrequencySpectrumModel* t_pModel = static_cast<const FrequencySpectrumModel*>(index.model()); if(t_pModel->getInfo()) { double fs = t_pModel->getInfo()->sfreq/2; qint32 numLines = (qint32)ceil(log10(fs)); QList<qint32> qListLineSamples; for(qint32 lineIdx = 0; lineIdx < numLines; ++lineIdx) { double val = pow(10,lineIdx); qint32 idx = (qint32)floor((val/fs) * t_pModel->getNumStems()); qListLineSamples.append(idx); } // XTick float yStart = 1.0*option.rect.topLeft().y(); double val = 0.0; float x = (t_pModel->getFreqScale()[qListLineSamples[0]])*option.rect.width(); painter->drawText(x,yStart,QString("%1Hz").arg(val)); for(qint32 i = 1; i < qListLineSamples.size(); ++i) { double val = pow(10,i-1); float x = (t_pModel->getFreqScale()[qListLineSamples[i]])*option.rect.width(); painter->drawText(x,yStart,QString("%1Hz").arg(val)); } // YTick } } <commit_msg>scale fix<commit_after>//============================================================================================================= /** * @file frequencyspectrumdelegate.cpp * @author Christoph Dinh <chdinh@nmr.mgh.harvard.edu>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date May, 2014 * * @section LICENSE * * Copyright (C) 2014, Christoph Dinh and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief Implementation of the FrequencySpectrumDelegate Class. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "frequencyspectrumdelegate.h" #include "frequencyspectrummodel.h" //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QPainter> #include <QPainterPath> #include <QDebug> #include <QThread> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace XDISPLIB; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= FrequencySpectrumDelegate::FrequencySpectrumDelegate(QObject *parent) : QAbstractItemDelegate(parent) { } //************************************************************************************************************* void FrequencySpectrumDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { float t_fPlotHeight = option.rect.height(); switch(index.column()) { case 0: { //chnames painter->save(); painter->rotate(-90); painter->drawText(QRectF(-option.rect.y()-t_fPlotHeight,0,t_fPlotHeight,20),Qt::AlignCenter,index.model()->data(index,Qt::DisplayRole).toString()); painter->restore(); break; } case 1: { //data plot painter->save(); //draw special background when channel is marked as bad // QVariant v = index.model()->data(index,Qt::BackgroundRole); // if(v.canConvert<QBrush>() && !(option.state & QStyle::State_Selected)) { // QPointF oldBO = painter->brushOrigin(); // painter->setBrushOrigin(option.rect.topLeft()); // painter->fillRect(option.rect, qvariant_cast<QBrush>(v)); // painter->setBrushOrigin(oldBO); // } // //Highlight selected channels // if(option.state & QStyle::State_Selected) { // QPointF oldBO = painter->brushOrigin(); // painter->setBrushOrigin(option.rect.topLeft()); // painter->fillRect(option.rect, option.palette.highlight()); // painter->setBrushOrigin(oldBO); // } //Get data QVariant variant = index.model()->data(index,Qt::DisplayRole); RowVectorXd data = variant.value< RowVectorXd >(); const FrequencySpectrumModel* t_pModel = static_cast<const FrequencySpectrumModel*>(index.model()); if(data.size() > 0) { QPainterPath path(QPointF(option.rect.x(),option.rect.y()));//QPointF(option.rect.x()+t_rtmsaModel->relFiffCursor()-1,option.rect.y())); //Plot grid painter->setRenderHint(QPainter::Antialiasing, false); createGridPath(index, option, path, data); createGridTick(index, option, painter); painter->save(); QPen pen; pen.setStyle(Qt::DotLine); pen.setWidthF(0.5); painter->setPen(pen); painter->drawPath(path); painter->restore(); //Plot data path path = QPainterPath(QPointF(option.rect.x(),option.rect.y()));//QPointF(option.rect.x()+t_rtmsaModel->relFiffCursor(),option.rect.y())); createPlotPath(index, option, path, data); painter->save(); painter->translate(0,t_fPlotHeight/2); painter->setRenderHint(QPainter::Antialiasing, true); if(option.state & QStyle::State_Selected) painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkRed : Qt::red, 1, Qt::SolidLine)); else painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkGray : Qt::darkBlue, 1, Qt::SolidLine)); painter->drawPath(path); painter->restore(); } painter->restore(); break; } } } //************************************************************************************************************* QSize FrequencySpectrumDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { QSize size; switch(index.column()) { case 0: size = QSize(20,option.rect.height()); break; case 1: RowVectorXd data = index.model()->data(index).value< RowVectorXd >(); // qint32 nsamples = (static_cast<const FrequencySpectrumModel*>(index.model()))->lastSample()-(static_cast<const FrequencySpectrumModel*>(index.model()))->firstSample(); // size = QSize(nsamples*m_dDx,m_dPlotHeight); Q_UNUSED(option); break; } return size; } //************************************************************************************************************* void FrequencySpectrumDelegate::createPlotPath(const QModelIndex &index, const QStyleOptionViewItem &option, QPainterPath& path, RowVectorXd& data) const { const FrequencySpectrumModel* t_pModel = static_cast<const FrequencySpectrumModel*>(index.model()); float fMaxValue = data.maxCoeff(); float fValue; float fScaleY = option.rect.height()/(fMaxValue*0.5); float y_base = path.currentPosition().y(); QPointF qSamplePosition; //Move to initial starting point if(data.size() > 0) { float val = 0; fValue = val*fScaleY; float newY = y_base+fValue; qSamplePosition.setY(newY); qSamplePosition.setX((double)option.rect.width()*t_pModel->getFreqScale()[0]); path.moveTo(qSamplePosition); } //create lines from one to the next sample qint32 i; for(i = 1; i < data.size(); ++i) { float val = data[i]-data[0]; //remove first sample data[0] as offset fValue = val*fScaleY; float newY = y_base+fValue; qSamplePosition.setY(newY); qSamplePosition.setX((double)option.rect.width()*t_pModel->getFreqScale()[i]); path.lineTo(qSamplePosition); } } //************************************************************************************************************* void FrequencySpectrumDelegate::createGridPath(const QModelIndex &index, const QStyleOptionViewItem &option, QPainterPath& path, RowVectorXd& data) const { Q_UNUSED(data) const FrequencySpectrumModel* t_pModel = static_cast<const FrequencySpectrumModel*>(index.model()); if(t_pModel->getInfo()) { double fs = t_pModel->getInfo()->sfreq/2; qint32 numLines = (qint32)ceil(log10(fs)); QList<qint32> qListLineSamples; qListLineSamples << 0; for(qint32 lineIdx = 0; lineIdx < numLines; ++lineIdx) { double val = pow(10,lineIdx); qint32 idx = (qint32)floor(val / ((float)fs/(float)t_pModel->getNumStems())); qListLineSamples.append(idx); } //vertical lines float yStart = option.rect.topLeft().y(); float yEnd = option.rect.bottomRight().y(); for(qint32 i = 0; i < qListLineSamples.size(); ++i) { float x = (t_pModel->getFreqScale()[qListLineSamples[i]])*option.rect.width(); path.moveTo(x,yStart); path.lineTo(x,yEnd); } /* //horizontal lines float xStart = option.rect.topLeft().x(); float xEnd = option.rect.bottomRight().x(); for(qint32 i = 0; i < 6; ++i) { float y = option.rect.height()/5.0 * (float)i; path.moveTo(xStart,y); path.lineTo(xEnd,y); } */ } } //************************************************************************************************************* void FrequencySpectrumDelegate::createGridTick(const QModelIndex &index, const QStyleOptionViewItem &option, QPainter *painter) const { const FrequencySpectrumModel* t_pModel = static_cast<const FrequencySpectrumModel*>(index.model()); if(t_pModel->getInfo()) { double fs = t_pModel->getInfo()->sfreq/2; qint32 numLines = (qint32)ceil(log10(fs)); QList<qint32> qListLineSamples; qListLineSamples << 0; for(qint32 lineIdx = 0; lineIdx < numLines; ++lineIdx) { double val = pow(10,lineIdx); qint32 idx = (qint32)floor(val / ((float)fs/(float)t_pModel->getNumStems())); qListLineSamples.append(idx); } // XTick float yStart = 1.0*option.rect.topLeft().y(); double val = 0.0; float x = (t_pModel->getFreqScale()[qListLineSamples[0]])*option.rect.width(); painter->drawText(x,yStart,QString("%1Hz").arg(val)); for(qint32 i = 1; i < qListLineSamples.size(); ++i) { double val = pow(10,i-1); float x = (t_pModel->getFreqScale()[qListLineSamples[i]])*option.rect.width(); painter->drawText(x,yStart,QString("%1Hz").arg(val)); } // YTick } } <|endoftext|>
<commit_before>/** * @file * * Define a class that abstracts Linux threads. */ /****************************************************************************** * Copyright (c) 2009-2013, AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************************/ #include <qcc/platform.h> #include <algorithm> #include <assert.h> #include <errno.h> #include <pthread.h> #include <signal.h> #include <string.h> #include <time.h> #include <unistd.h> #include <map> #include <qcc/Debug.h> #include <qcc/String.h> #include <qcc/Mutex.h> #include <qcc/Thread.h> #include <Status.h> using namespace std; /** @internal */ #define QCC_MODULE "THREAD" namespace qcc { static uint32_t started = 0; static uint32_t running = 0; static uint32_t joined = 0; /** Global thread list */ Mutex* Thread::threadListLock = NULL; map<ThreadHandle, Thread*>* Thread::threadList = NULL; static int threadListCounter = 0; ThreadListInitializer::ThreadListInitializer() { if (0 == threadListCounter++) { Thread::threadListLock = new Mutex(); Thread::threadList = new map<ThreadHandle, Thread*>(); } } ThreadListInitializer::~ThreadListInitializer() { if (0 == --threadListCounter) { delete Thread::threadList; delete Thread::threadListLock; } } QStatus Sleep(uint32_t ms) { usleep(1000 * ms); return ER_OK; } Thread* Thread::GetThread() { Thread* ret = NULL; /* Find thread on Thread::threadList */ threadListLock->Lock(); map<ThreadHandle, Thread*>::const_iterator iter = threadList->find(pthread_self()); if (iter != threadList->end()) { ret = iter->second; } threadListLock->Unlock(); /* If the current thread isn't on the list, then create an external (wrapper) thread */ if (NULL == ret) { ret = new Thread("external", NULL, true); } return ret; } const char* Thread::GetThreadName() { Thread* thread = NULL; /* Find thread on Thread::threadList */ threadListLock->Lock(); map<ThreadHandle, Thread*>::const_iterator iter = threadList->find(pthread_self()); if (iter != threadList->end()) { thread = iter->second; } threadListLock->Unlock(); /* If the current thread isn't on the list, then don't create an external (wrapper) thread */ if (thread == NULL) { return "external"; } return thread->GetName(); } void Thread::CleanExternalThreads() { threadListLock->Lock(); map<ThreadHandle, Thread*>::iterator it = threadList->begin(); while (it != threadList->end()) { if (it->second->isExternal) { delete it->second; threadList->erase(it++); } else { ++it; } } threadListLock->Unlock(); } Thread::Thread(qcc::String name, Thread::ThreadFunction func, bool isExternal) : stopEvent(), state(isExternal ? RUNNING : INITIAL), isStopping(false), function(isExternal ? NULL : func), handle(isExternal ? pthread_self() : 0), exitValue(NULL), listener(NULL), isExternal(isExternal), platformContext(NULL), alertCode(0), auxListeners(), auxListenersLock(), waitCount(0), waitLock(), hasBeenJoined(false) { /* qcc::String is not thread safe. Don't use it here. */ funcName[0] = '\0'; strncpy(funcName, name.c_str(), sizeof(funcName)); funcName[sizeof(funcName) - 1] = '\0'; /* If this is an external thread, add it to the thread list here since Run will not be called */ if (isExternal) { assert(func == NULL); threadListLock->Lock(); (*threadList)[handle] = this; threadListLock->Unlock(); } QCC_DbgHLPrintf(("Thread::Thread() created %s - %x -- started:%d running:%d joined:%d", funcName, handle, started, running, joined)); } Thread::~Thread(void) { QCC_DbgHLPrintf(("Thread::~Thread() destroying %s - %x", funcName, handle)); if (!isExternal) { Stop(); Join(); } /* Keep object alive until waitCount goes to zero */ while (waitCount) { qcc::Sleep(2); } QCC_DbgHLPrintf(("Thread::~Thread() destroyed %s - %x -- started:%d running:%d joined:%d", funcName, handle, started, running, joined)); } ThreadInternalReturn Thread::RunInternal(void* threadArg) { Thread* thread(reinterpret_cast<Thread*>(threadArg)); sigset_t newmask; sigemptyset(&newmask); sigaddset(&newmask, SIGUSR1); assert(thread != NULL); if (thread->state != STARTED) { return NULL; } /* Plug race condition between Start and Run. (pthread_create may not write handle before run is called) */ thread->handle = pthread_self(); ++started; QCC_DbgPrintf(("Thread::RunInternal: %s (pid=%x)", thread->funcName, (unsigned long) thread->handle)); /* Add this Thread to list of running threads */ threadListLock->Lock(); (*threadList)[thread->handle] = thread; thread->state = RUNNING; pthread_sigmask(SIG_UNBLOCK, &newmask, NULL); threadListLock->Unlock(); /* Start the thread if it hasn't been stopped */ if (!thread->isStopping) { QCC_DbgPrintf(("Starting thread: %s", thread->funcName)); ++running; thread->exitValue = thread->Run(thread->arg); --running; QCC_DbgPrintf(("Thread function exited: %s --> %p", thread->funcName, thread->exitValue)); } thread->state = STOPPING; thread->stopEvent.ResetEvent(); /* * Call thread exit callback if specified. Note that ThreadExit may dellocate the thread so the * members of thread may not be accessed after this call */ void* retVal = thread->exitValue; ThreadHandle handle = thread->handle; /* Call aux listeners before main listener since main listner may delete the thread */ thread->auxListenersLock.Lock(); ThreadListeners::iterator it = thread->auxListeners.begin(); while (it != thread->auxListeners.end()) { ThreadListener* listener = *it; listener->ThreadExit(thread); it = thread->auxListeners.upper_bound(listener); } thread->auxListenersLock.Unlock(); if (thread->listener) { thread->listener->ThreadExit(thread); } /* This also means no QCC_DbgPrintf as they try to get context on the current thread */ /* Remove this Thread from list of running threads */ threadListLock->Lock(); threadList->erase(handle); threadListLock->Unlock(); return reinterpret_cast<ThreadInternalReturn>(retVal); } static const uint32_t stacksize = 256 * 1024; QStatus Thread::Start(void* arg, ThreadListener* listener) { QStatus status = ER_OK; /* Check that thread can be started */ if (isExternal) { status = ER_EXTERNAL_THREAD; } else if (isStopping) { status = ER_THREAD_STOPPING; } else if (IsRunning()) { status = ER_THREAD_RUNNING; } if (status != ER_OK) { QCC_LogError(status, ("Thread::Start [%s]", funcName)); } else { int ret; /* Clear/initialize the join context */ hasBeenJoined = false; waitCount = 0; /* Reset the stop event so the thread doesn't start out alerted. */ stopEvent.ResetEvent(); /* Create OS thread */ this->arg = arg; this->listener = listener; state = STARTED; pthread_attr_t attr; ret = pthread_attr_init(&attr); if (ret != 0) { status = ER_OS_ERROR; QCC_LogError(status, ("Initializing thread attr: %s", strerror(ret))); } ret = pthread_attr_setstacksize(&attr, stacksize); if (ret != 0) { status = ER_OS_ERROR; QCC_LogError(status, ("Setting stack size: %s", strerror(ret))); } ret = pthread_create(&handle, &attr, RunInternal, this); QCC_DbgTrace(("Thread::Start() [%s] pid = %x", funcName, handle)); if (ret != 0) { state = DEAD; isStopping = false; status = ER_OS_ERROR; QCC_LogError(status, ("Creating thread %s: %s", funcName, strerror(ret))); } } return status; } QStatus Thread::Stop(void) { /* Cannot stop external threads */ if (isExternal) { QCC_LogError(ER_EXTERNAL_THREAD, ("Cannot stop an external thread")); return ER_EXTERNAL_THREAD; } else if ((state == DEAD) || (state == INITIAL)) { QCC_DbgPrintf(("Thread::Stop() thread is dead [%s]", funcName)); return ER_OK; } else { QCC_DbgTrace(("Thread::Stop() %x [%s]", handle, funcName)); isStopping = true; return stopEvent.SetEvent(); } } QStatus Thread::Alert() { if (state == DEAD) { return ER_DEAD_THREAD; } QCC_DbgTrace(("Thread::Alert() [%s:%srunning]", funcName, IsRunning() ? " " : " not ")); return stopEvent.SetEvent(); } QStatus Thread::Alert(uint32_t alertCode) { this->alertCode = alertCode; if (state == DEAD) { return ER_DEAD_THREAD; } QCC_DbgTrace(("Thread::Alert(%u) [%s:%srunning]", alertCode, funcName, IsRunning() ? " " : " not ")); return stopEvent.SetEvent(); } void Thread::AddAuxListener(ThreadListener* listener) { auxListenersLock.Lock(); auxListeners.insert(listener); auxListenersLock.Unlock(); } void Thread::RemoveAuxListener(ThreadListener* listener) { auxListenersLock.Lock(); ThreadListeners::iterator it = auxListeners.find(listener); if (it != auxListeners.end()) { auxListeners.erase(it); } auxListenersLock.Unlock(); } QStatus Thread::Join(void) { QStatus status = ER_OK; QCC_DbgTrace(("Thread::Join() [%s - %x :%srunning]", funcName, handle, IsRunning() ? " " : " not ")); QCC_DbgPrintf(("[%s - %x] Joining thread [%s - %x]", GetThread()->funcName, GetThread()->handle, funcName, handle)); /* * Nothing to join if the thread is dead */ if (state == DEAD) { QCC_DbgPrintf(("Thread::Join() thread is dead [%s]", funcName)); isStopping = false; return ER_OK; } /* * There is a race condition where the underlying OS thread has not yet started to run. We need * to wait until the thread is actually running before we can free it. */ while (state == STARTED) { usleep(1000 * 5); } /* Threads that join themselves must detach without blocking */ if (handle == pthread_self()) { int32_t waiters = IncrementAndFetch(&waitCount); hbjMutex.Lock(); if ((waiters == 1) && !hasBeenJoined) { hasBeenJoined = true; hbjMutex.Unlock(); int ret = pthread_detach(handle); handle = 0; if (ret == 0) { ++joined; } else { status = ER_OS_ERROR; QCC_LogError(status, ("Detaching thread: %d - %s", ret, strerror(ret))); } } else { hbjMutex.Unlock(); } DecrementAndFetch(&waitCount); isStopping = false; } else { /* * Unfortunately, POSIX pthread_join can only be called once for a given thread. This is quite * inconvenient in a system of multiple threads that need to synchronize with each other. * This ugly looking code allows multiple threads to Join a thread. All but one thread block * in a Mutex. The first thread to obtain the mutex is the one that is allowed to call pthread_join. * All other threads wait for that join to complete. Then they are released. */ int ret = 0; int32_t waiters = IncrementAndFetch(&waitCount); waitLock.Lock(); hbjMutex.Lock(); if ((waiters == 1) && !hasBeenJoined) { hasBeenJoined = true; hbjMutex.Unlock(); ret = pthread_join(handle, NULL); handle = 0; ++joined; } else { hbjMutex.Unlock(); } waitLock.Unlock(); DecrementAndFetch(&waitCount); if (ret != 0) { status = ER_OS_ERROR; QCC_LogError(status, ("Joining thread: %d - %s", ret, strerror(ret))); } isStopping = false; } state = DEAD; QCC_DbgPrintf(("Joined thread %s", funcName)); return status; } ThreadReturn STDCALL Thread::Run(void* arg) { QCC_DbgTrace(("Thread::Run() [%s:%srunning]", funcName, IsRunning() ? " " : " not ")); assert(NULL != function); assert(!isExternal); return (*function)(arg); } } /* namespace */ <commit_msg>ASACORE-502: Allow Join() on Thread never Start()ed<commit_after>/** * @file * * Define a class that abstracts Linux threads. */ /****************************************************************************** * Copyright (c) 2009-2013, AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************************/ #include <qcc/platform.h> #include <algorithm> #include <assert.h> #include <errno.h> #include <pthread.h> #include <signal.h> #include <string.h> #include <time.h> #include <unistd.h> #include <map> #include <qcc/Debug.h> #include <qcc/String.h> #include <qcc/Mutex.h> #include <qcc/Thread.h> #include <Status.h> using namespace std; /** @internal */ #define QCC_MODULE "THREAD" namespace qcc { static uint32_t started = 0; static uint32_t running = 0; static uint32_t joined = 0; /** Global thread list */ Mutex* Thread::threadListLock = NULL; map<ThreadHandle, Thread*>* Thread::threadList = NULL; static int threadListCounter = 0; ThreadListInitializer::ThreadListInitializer() { if (0 == threadListCounter++) { Thread::threadListLock = new Mutex(); Thread::threadList = new map<ThreadHandle, Thread*>(); } } ThreadListInitializer::~ThreadListInitializer() { if (0 == --threadListCounter) { delete Thread::threadList; delete Thread::threadListLock; } } QStatus Sleep(uint32_t ms) { usleep(1000 * ms); return ER_OK; } Thread* Thread::GetThread() { Thread* ret = NULL; /* Find thread on Thread::threadList */ threadListLock->Lock(); map<ThreadHandle, Thread*>::const_iterator iter = threadList->find(pthread_self()); if (iter != threadList->end()) { ret = iter->second; } threadListLock->Unlock(); /* If the current thread isn't on the list, then create an external (wrapper) thread */ if (NULL == ret) { ret = new Thread("external", NULL, true); } return ret; } const char* Thread::GetThreadName() { Thread* thread = NULL; /* Find thread on Thread::threadList */ threadListLock->Lock(); map<ThreadHandle, Thread*>::const_iterator iter = threadList->find(pthread_self()); if (iter != threadList->end()) { thread = iter->second; } threadListLock->Unlock(); /* If the current thread isn't on the list, then don't create an external (wrapper) thread */ if (thread == NULL) { return "external"; } return thread->GetName(); } void Thread::CleanExternalThreads() { threadListLock->Lock(); map<ThreadHandle, Thread*>::iterator it = threadList->begin(); while (it != threadList->end()) { if (it->second->isExternal) { delete it->second; threadList->erase(it++); } else { ++it; } } threadListLock->Unlock(); } Thread::Thread(qcc::String name, Thread::ThreadFunction func, bool isExternal) : stopEvent(), state(isExternal ? RUNNING : INITIAL), isStopping(false), function(isExternal ? NULL : func), handle(isExternal ? pthread_self() : 0), exitValue(NULL), listener(NULL), isExternal(isExternal), platformContext(NULL), alertCode(0), auxListeners(), auxListenersLock(), waitCount(0), waitLock(), hasBeenJoined(false) { /* qcc::String is not thread safe. Don't use it here. */ funcName[0] = '\0'; strncpy(funcName, name.c_str(), sizeof(funcName)); funcName[sizeof(funcName) - 1] = '\0'; /* If this is an external thread, add it to the thread list here since Run will not be called */ if (isExternal) { assert(func == NULL); threadListLock->Lock(); (*threadList)[handle] = this; threadListLock->Unlock(); } QCC_DbgHLPrintf(("Thread::Thread() created %s - %x -- started:%d running:%d joined:%d", funcName, handle, started, running, joined)); } Thread::~Thread(void) { QCC_DbgHLPrintf(("Thread::~Thread() destroying %s - %x", funcName, handle)); if (!isExternal) { Stop(); Join(); } /* Keep object alive until waitCount goes to zero */ while (waitCount) { qcc::Sleep(2); } QCC_DbgHLPrintf(("Thread::~Thread() destroyed %s - %x -- started:%d running:%d joined:%d", funcName, handle, started, running, joined)); } ThreadInternalReturn Thread::RunInternal(void* threadArg) { Thread* thread(reinterpret_cast<Thread*>(threadArg)); sigset_t newmask; sigemptyset(&newmask); sigaddset(&newmask, SIGUSR1); assert(thread != NULL); /* Plug race condition between Start and Run. (pthread_create may not write handle before run is called) */ thread->handle = pthread_self(); if (thread->state != STARTED) { return NULL; } ++started; QCC_DbgPrintf(("Thread::RunInternal: %s (pid=%x)", thread->funcName, (unsigned long) thread->handle)); /* Add this Thread to list of running threads */ threadListLock->Lock(); (*threadList)[thread->handle] = thread; thread->state = RUNNING; pthread_sigmask(SIG_UNBLOCK, &newmask, NULL); threadListLock->Unlock(); /* Start the thread if it hasn't been stopped */ if (!thread->isStopping) { QCC_DbgPrintf(("Starting thread: %s", thread->funcName)); ++running; thread->exitValue = thread->Run(thread->arg); --running; QCC_DbgPrintf(("Thread function exited: %s --> %p", thread->funcName, thread->exitValue)); } thread->state = STOPPING; thread->stopEvent.ResetEvent(); /* * Call thread exit callback if specified. Note that ThreadExit may dellocate the thread so the * members of thread may not be accessed after this call */ void* retVal = thread->exitValue; ThreadHandle handle = thread->handle; /* Call aux listeners before main listener since main listner may delete the thread */ thread->auxListenersLock.Lock(); ThreadListeners::iterator it = thread->auxListeners.begin(); while (it != thread->auxListeners.end()) { ThreadListener* listener = *it; listener->ThreadExit(thread); it = thread->auxListeners.upper_bound(listener); } thread->auxListenersLock.Unlock(); if (thread->listener) { thread->listener->ThreadExit(thread); } /* This also means no QCC_DbgPrintf as they try to get context on the current thread */ /* Remove this Thread from list of running threads */ threadListLock->Lock(); threadList->erase(handle); threadListLock->Unlock(); return reinterpret_cast<ThreadInternalReturn>(retVal); } static const uint32_t stacksize = 256 * 1024; QStatus Thread::Start(void* arg, ThreadListener* listener) { QStatus status = ER_OK; /* Check that thread can be started */ if (isExternal) { status = ER_EXTERNAL_THREAD; } else if (isStopping) { status = ER_THREAD_STOPPING; } else if (IsRunning()) { status = ER_THREAD_RUNNING; } if (status != ER_OK) { QCC_LogError(status, ("Thread::Start [%s]", funcName)); } else { int ret; /* Clear/initialize the join context */ hasBeenJoined = false; waitCount = 0; /* Reset the stop event so the thread doesn't start out alerted. */ stopEvent.ResetEvent(); /* Create OS thread */ this->arg = arg; this->listener = listener; state = STARTED; pthread_attr_t attr; ret = pthread_attr_init(&attr); if (ret != 0) { status = ER_OS_ERROR; QCC_LogError(status, ("Initializing thread attr: %s", strerror(ret))); } ret = pthread_attr_setstacksize(&attr, stacksize); if (ret != 0) { status = ER_OS_ERROR; QCC_LogError(status, ("Setting stack size: %s", strerror(ret))); } ret = pthread_create(&handle, &attr, RunInternal, this); QCC_DbgTrace(("Thread::Start() [%s] pid = %x", funcName, handle)); if (ret != 0) { state = DEAD; isStopping = false; status = ER_OS_ERROR; QCC_LogError(status, ("Creating thread %s: %s", funcName, strerror(ret))); } } return status; } QStatus Thread::Stop(void) { /* Cannot stop external threads */ if (isExternal) { QCC_LogError(ER_EXTERNAL_THREAD, ("Cannot stop an external thread")); return ER_EXTERNAL_THREAD; } else if ((state == DEAD) || (state == INITIAL)) { QCC_DbgPrintf(("Thread::Stop() thread is dead [%s]", funcName)); return ER_OK; } else { QCC_DbgTrace(("Thread::Stop() %x [%s]", handle, funcName)); isStopping = true; return stopEvent.SetEvent(); } } QStatus Thread::Alert() { if (state == DEAD) { return ER_DEAD_THREAD; } QCC_DbgTrace(("Thread::Alert() [%s:%srunning]", funcName, IsRunning() ? " " : " not ")); return stopEvent.SetEvent(); } QStatus Thread::Alert(uint32_t alertCode) { this->alertCode = alertCode; if (state == DEAD) { return ER_DEAD_THREAD; } QCC_DbgTrace(("Thread::Alert(%u) [%s:%srunning]", alertCode, funcName, IsRunning() ? " " : " not ")); return stopEvent.SetEvent(); } void Thread::AddAuxListener(ThreadListener* listener) { auxListenersLock.Lock(); auxListeners.insert(listener); auxListenersLock.Unlock(); } void Thread::RemoveAuxListener(ThreadListener* listener) { auxListenersLock.Lock(); ThreadListeners::iterator it = auxListeners.find(listener); if (it != auxListeners.end()) { auxListeners.erase(it); } auxListenersLock.Unlock(); } QStatus Thread::Join(void) { QStatus status = ER_OK; QCC_DbgTrace(("Thread::Join() [%s - %x :%srunning]", funcName, handle, IsRunning() ? " " : " not ")); QCC_DbgPrintf(("[%s - %x] Joining thread [%s - %x]", GetThread()->funcName, GetThread()->handle, funcName, handle)); /* * Nothing to join if the thread is dead */ if (state == DEAD) { QCC_DbgPrintf(("Thread::Join() thread is dead [%s]", funcName)); isStopping = false; return ER_OK; } /* * There is a race condition where the underlying OS thread has not yet started to run. We need * to wait until the thread is actually running before we can free it. */ while (state == STARTED) { usleep(1000 * 5); } /* Threads that join themselves must detach without blocking */ if (handle == pthread_self()) { int32_t waiters = IncrementAndFetch(&waitCount); hbjMutex.Lock(); if ((waiters == 1) && !hasBeenJoined) { hasBeenJoined = true; hbjMutex.Unlock(); int ret = 0; if (state != INITIAL) { assert(handle); ret = pthread_detach(handle); } if (ret == 0) { ++joined; } else { status = ER_OS_ERROR; QCC_LogError(status, ("Detaching thread: %d - %s", ret, strerror(ret))); } handle = 0; } else { hbjMutex.Unlock(); } DecrementAndFetch(&waitCount); isStopping = false; } else { /* * Unfortunately, POSIX pthread_join can only be called once for a given thread. This is quite * inconvenient in a system of multiple threads that need to synchronize with each other. * This ugly looking code allows multiple threads to Join a thread. All but one thread block * in a Mutex. The first thread to obtain the mutex is the one that is allowed to call pthread_join. * All other threads wait for that join to complete. Then they are released. */ int ret = 0; int32_t waiters = IncrementAndFetch(&waitCount); waitLock.Lock(); hbjMutex.Lock(); if ((waiters == 1) && !hasBeenJoined) { hasBeenJoined = true; hbjMutex.Unlock(); if (state != INITIAL) { assert(handle); ret = pthread_join(handle, NULL); } handle = 0; ++joined; } else { hbjMutex.Unlock(); } waitLock.Unlock(); DecrementAndFetch(&waitCount); if (ret != 0) { status = ER_OS_ERROR; QCC_LogError(status, ("Joining thread: %d - %s", ret, strerror(ret))); } isStopping = false; } state = DEAD; QCC_DbgPrintf(("Joined thread %s", funcName)); return status; } ThreadReturn STDCALL Thread::Run(void* arg) { QCC_DbgTrace(("Thread::Run() [%s:%srunning]", funcName, IsRunning() ? " " : " not ")); assert(NULL != function); assert(!isExternal); return (*function)(arg); } } /* namespace */ <|endoftext|>
<commit_before>//============================================================================== // CellML annotation view metadata details widget //============================================================================== #include "borderedwidget.h" #include "cellmlannotationviewmetadatadetailswidget.h" #include "cellmlannotationviewmetadataviewdetailswidget.h" #include "cellmlannotationviewplugin.h" #include "cellmlannotationviewwidget.h" //============================================================================== #include "ui_cellmlannotationviewmetadatadetailswidget.h" //============================================================================== #include <QLabel> //============================================================================== namespace OpenCOR { namespace CellMLAnnotationView { //============================================================================== CellmlAnnotationViewMetadataDetailsWidget::CellmlAnnotationViewMetadataDetailsWidget(CellmlAnnotationViewWidget *pParent) : Widget(pParent), mParent(pParent), mGui(new Ui::CellmlAnnotationViewMetadataDetailsWidget) { // Set up the GUI mGui->setupUi(this); // Create our unsupported metadata message widget mUnsupportedMetadataMsg = new QLabel(pParent); QFont unsupportedMetadataMsgFont = mUnsupportedMetadataMsg->font(); unsupportedMetadataMsgFont.setPointSize(1.5*unsupportedMetadataMsgFont.pointSize()); mUnsupportedMetadataMsg->setAlignment(Qt::AlignHCenter|Qt::AlignVCenter); mUnsupportedMetadataMsg->setFont(unsupportedMetadataMsgFont); mUnsupportedMetadataMsg->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); mUnsupportedMetadataMsg->setWordWrap(true); mBorderedUnsupportedMetadataMsg = new Core::BorderedWidget(mUnsupportedMetadataMsg, false, true, true, false); mBorderedUnsupportedMetadataMsg->setVisible(false); // Note: we don't initially want to see it, so... // Create our details widget mMetadataViewDetails = new CellmlAnnotationViewMetadataViewDetailsWidget(pParent); mBorderedMetadataViewDetails = new Core::BorderedWidget(mMetadataViewDetails, false, true, false, false); // Add our bordered widgets to our layout mGui->layout->addWidget(mBorderedUnsupportedMetadataMsg); mGui->layout->addWidget(mBorderedMetadataViewDetails); // Some further initialisations which are done as part of retranslating the // GUI (so that they can be updated when changing languages) retranslateUi(); } //============================================================================== CellmlAnnotationViewMetadataDetailsWidget::~CellmlAnnotationViewMetadataDetailsWidget() { // Delete the GUI delete mGui; } //============================================================================== void CellmlAnnotationViewMetadataDetailsWidget::retranslateUi() { // Retranslate our GUI mGui->retranslateUi(this); mMetadataViewDetails->retranslateUi(); // Update our unsupported metadata message mUnsupportedMetadataMsg->setText(tr("Sorry, but the <strong>%1</strong> view does not support this type of metadata...").arg(mParent->pluginParent()->viewName())); } //============================================================================== void CellmlAnnotationViewMetadataDetailsWidget::updateGui(const CellMLSupport::CellmlFileRdfTriples &pRdfTriples) { // Show/hide our unsupported metadata message depending on whether the type // of the RDF triples is known or not CellMLSupport::CellmlFileRdfTriple::Type rdfTriplesType = pRdfTriples.type(); mBorderedUnsupportedMetadataMsg->setVisible(rdfTriplesType == CellMLSupport::CellmlFileRdfTriple::Unknown); mBorderedMetadataViewDetails->setVisible(rdfTriplesType == CellMLSupport::CellmlFileRdfTriple::Unknown); // Update our Metadata view details GUI if (mBorderedMetadataViewDetails->isVisible()) mMetadataViewDetails->updateGui(pRdfTriples); } //============================================================================== } // namespace CellMLAnnotationView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Resuming our work on the creation/editing of metadata (#78).<commit_after>//============================================================================== // CellML annotation view metadata details widget //============================================================================== #include "borderedwidget.h" #include "cellmlannotationviewmetadatadetailswidget.h" #include "cellmlannotationviewmetadataviewdetailswidget.h" #include "cellmlannotationviewplugin.h" #include "cellmlannotationviewwidget.h" //============================================================================== #include "ui_cellmlannotationviewmetadatadetailswidget.h" //============================================================================== #include <QLabel> //============================================================================== namespace OpenCOR { namespace CellMLAnnotationView { //============================================================================== CellmlAnnotationViewMetadataDetailsWidget::CellmlAnnotationViewMetadataDetailsWidget(CellmlAnnotationViewWidget *pParent) : Widget(pParent), mParent(pParent), mGui(new Ui::CellmlAnnotationViewMetadataDetailsWidget) { // Set up the GUI mGui->setupUi(this); // Create our unsupported metadata message widget mUnsupportedMetadataMsg = new QLabel(pParent); QFont unsupportedMetadataMsgFont = mUnsupportedMetadataMsg->font(); unsupportedMetadataMsgFont.setPointSize(1.5*unsupportedMetadataMsgFont.pointSize()); mUnsupportedMetadataMsg->setAlignment(Qt::AlignHCenter|Qt::AlignVCenter); mUnsupportedMetadataMsg->setFont(unsupportedMetadataMsgFont); mUnsupportedMetadataMsg->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); mUnsupportedMetadataMsg->setWordWrap(true); mBorderedUnsupportedMetadataMsg = new Core::BorderedWidget(mUnsupportedMetadataMsg, false, true, true, false); mBorderedUnsupportedMetadataMsg->setVisible(false); // Note: we don't initially want to see it, so... // Create our details widget mMetadataViewDetails = new CellmlAnnotationViewMetadataViewDetailsWidget(pParent); mBorderedMetadataViewDetails = new Core::BorderedWidget(mMetadataViewDetails, false, true, false, false); // Add our bordered widgets to our layout mGui->layout->addWidget(mBorderedUnsupportedMetadataMsg); mGui->layout->addWidget(mBorderedMetadataViewDetails); // Some further initialisations which are done as part of retranslating the // GUI (so that they can be updated when changing languages) retranslateUi(); } //============================================================================== CellmlAnnotationViewMetadataDetailsWidget::~CellmlAnnotationViewMetadataDetailsWidget() { // Delete the GUI delete mGui; } //============================================================================== void CellmlAnnotationViewMetadataDetailsWidget::retranslateUi() { // Retranslate our GUI mGui->retranslateUi(this); mMetadataViewDetails->retranslateUi(); // Update our unsupported metadata message mUnsupportedMetadataMsg->setText(tr("Sorry, but the <strong>%1</strong> view does not support this type of metadata...").arg(mParent->pluginParent()->viewName())); } //============================================================================== void CellmlAnnotationViewMetadataDetailsWidget::updateGui(const CellMLSupport::CellmlFileRdfTriples &pRdfTriples) { // Show/hide our unsupported metadata message depending on whether the type // of the RDF triples is known or not mBorderedUnsupportedMetadataMsg->setVisible(pRdfTriples.type() == CellMLSupport::CellmlFileRdfTriple::Unknown); // Update our Metadata view details GUI mMetadataViewDetails->updateGui(pRdfTriples); } //============================================================================== } // namespace CellMLAnnotationView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch> //------------------------------------------------------------------------------ #include "cling/Interpreter/DynamicLibraryManager.h" #include "cling/Interpreter/InvocationOptions.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include <stdlib.h> #ifdef WIN32 #include <Windows.h> #else #include <limits.h> /* PATH_MAX */ #include <dlfcn.h> #endif namespace cling { DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts) : m_Opts(Opts) { } DynamicLibraryManager::~DynamicLibraryManager() {} static bool isSharedLib(llvm::StringRef LibName, bool& exists) { using namespace llvm::sys::fs; file_magic Magic; llvm::error_code Error = identify_magic(LibName, Magic); exists = (Error == llvm::errc::success); return exists && #ifdef __APPLE__ (Magic == file_magic::macho_fixed_virtual_memory_shared_lib || Magic == file_magic::macho_dynamically_linked_shared_lib || Magic == file_magic::macho_dynamically_linked_shared_lib_stub) #elif defined(LLVM_ON_UNIX) Magic == file_magic::elf_shared_object #elif defined(LLVM_ON_WIN32) # error "Windows DLLs not yet implemented!" //Magic == file_magic::pecoff_executable? #else # error "Unsupported platform." #endif ; } static void findSharedLibrary(llvm::StringRef fileStem, const llvm::SmallVectorImpl<std::string>& Paths, llvm::SmallString<512>& FoundDyLib, bool& exists, bool& isDyLib) { for (llvm::SmallVectorImpl<std::string>::const_iterator IPath = Paths.begin(), EPath = Paths.end(); IPath != EPath; ++IPath) { llvm::SmallString<512> ThisPath(*IPath); llvm::sys::path::append(ThisPath, fileStem); isDyLib = isSharedLib(ThisPath.str(), exists); if (isDyLib) ThisPath.swap(FoundDyLib); if (exists) return; } } #if defined(LLVM_ON_UNIX) static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) { char* env_var = getenv("LD_LIBRARY_PATH"); #if __APPLE__ if (!env_var) env_var = getenv("DYLD_LIBRARY_PATH"); if (!env_var) env_var = getenv("DYLD_FALLBACK_LIBRARY_PATH"); #endif if (env_var != 0) { static const char PathSeparator = ':'; const char* at = env_var; const char* delim = strchr(at, PathSeparator); while (delim != 0) { std::string tmp(at, size_t(delim-at)); if (llvm::sys::fs::is_directory(tmp.c_str())) Paths.push_back(tmp); at = delim + 1; delim = strchr(at, PathSeparator); } if (*at != 0) if (llvm::sys::fs::is_directory(llvm::StringRef(at))) Paths.push_back(at); } Paths.push_back("/usr/local/lib/"); Paths.push_back("/usr/X11R6/lib/"); Paths.push_back("/usr/lib/"); Paths.push_back("/lib/"); } #elif defined(LLVM_ON_WIN32) static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) { char buff[MAX_PATH]; // Generic form of C:\Windows\System32 HRESULT res = SHGetFolderPathA(NULL, CSIDL_FLAG_CREATE | CSIDL_SYSTEM, NULL, SHGFP_TYPE_CURRENT, buff); if (res != S_OK) { assert(0 && "Failed to get system directory"); return; } Paths.push_back(buff); // Reset buff. buff[0] = 0; // Generic form of C:\Windows res = SHGetFolderPathA(NULL, CSIDL_FLAG_CREATE | CSIDL_WINDOWS, NULL, SHGFP_TYPE_CURRENT, buff); if (res != S_OK) { assert(0 && "Failed to get windows directory"); return; } Paths.push_back(buff); } #else # error "Unsupported platform." #endif DynamicLibraryManager::LoadLibResult DynamicLibraryManager::tryLinker(const std::string& filename, bool permanent, bool isAbsolute, bool& exists, bool& isDyLib) { using namespace llvm::sys; exists = false; isDyLib = false; llvm::SmallString<512> FoundDyLib; if (isAbsolute) { isDyLib = isSharedLib(filename, exists); if (isDyLib) FoundDyLib = filename; } else { llvm::SmallVector<std::string, 16> SearchPaths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end()); GetSystemLibraryPaths(SearchPaths); findSharedLibrary(filename, SearchPaths, FoundDyLib, exists, isDyLib); if (!exists) { // Add DyLib extension: llvm::SmallString<512> filenameWithExt(filename); #if defined(LLVM_ON_UNIX) #ifdef __APPLE__ llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1; #endif static const char* DyLibExt = ".so"; #elif defined(LLVM_ON_WIN32) static const char* DyLibExt = ".dll"; #else # error "Unsupported platform." #endif filenameWithExt += DyLibExt; findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists, isDyLib); #ifdef __APPLE__ if (!exists) { filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end()); filenameWithExt += ".dylib"; findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists, isDyLib); } #endif } } if (!isDyLib) return kLoadLibError; assert(!FoundDyLib.empty() && "The shared lib exists but can't find it!"); // get canonical path name and check if already loaded #ifdef WIN32 llvm::SmallString<_MAX_PATH> FullPath(_MAX_PATH); char *res = _fullpath((char *)FullPath.data(), FoundDyLib.c_str(), _MAX_PATH); #else llvm::SmallString<PATH_MAX+1> FullPath(PATH_MAX+1); char *res = realpath(FoundDyLib.c_str(), (char *)FullPath.data()); #endif if (res == 0) { llvm::errs() << "cling::Interpreter::tryLinker(): error getting real (canonical) path\n"; return kLoadLibError; } FullPath.set_size(strlen(res)); if (m_loadedLibraries.find(FullPath) != m_loadedLibraries.end()) return kLoadLibExists; // TODO: !permanent case #ifdef WIN32 # error "Windows DLL opening still needs to be implemented!" void* dyLibHandle = needs to be implemented!; std::string errMsg; #else const void* dyLibHandle = dlopen(FullPath.c_str(), RTLD_LAZY|RTLD_GLOBAL); std::string errMsg; if (const char* DyLibError = dlerror()) { errMsg = DyLibError; } #endif if (!dyLibHandle) { llvm::errs() << "cling::Interpreter::tryLinker(): " << errMsg << '\n'; return kLoadLibError; } std::pair<DyLibs::iterator, bool> insRes = m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle, FullPath.str())); if (!insRes.second) return kLoadLibExists; m_loadedLibraries.insert(FullPath); return kLoadLibSuccess; } DynamicLibraryManager::LoadLibResult DynamicLibraryManager::loadLibrary(const std::string& filename, bool permanent, bool* tryCode) { llvm::SmallString<128> Absolute((llvm::StringRef(filename))); llvm::sys::fs::make_absolute(Absolute); bool isAbsolute = filename == Absolute.c_str(); bool exists = false; bool isDyLib = false; LoadLibResult res = tryLinker(filename, permanent, isAbsolute, exists, isDyLib); if (tryCode) { *tryCode = !isDyLib; if (isAbsolute) *tryCode &= exists; } if (exists) return res; if (!isAbsolute && filename.compare(0, 3, "lib")) { // try with "lib" prefix: res = tryLinker("lib" + filename, permanent, false, exists, isDyLib); if (tryCode) { *tryCode = !isDyLib; if (isAbsolute) *tryCode &= exists; } if (res != kLoadLibError) return res; } return kLoadLibError; } bool DynamicLibraryManager::isDynamicLibraryLoaded(llvm::StringRef fullPath) const { // get canonical path name and check if already loaded #ifdef WIN32 char buf[_MAX_PATH]; char *res = _fullpath(buf, fullPath.str().c_str(), _MAX_PATH); #else char buf[PATH_MAX+1]; char *res = realpath(fullPath.str().c_str(), buf); #endif if (res == 0) { llvm::errs() << "cling::Interpreter::isDynamicLibraryLoaded(): error getting real (canonical) path\n"; return false; } if (m_loadedLibraries.find(buf) != m_loadedLibraries.end()) return true; return false; } void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) { llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle)); } } // end namespace cling <commit_msg>Use set_size so make sure the llvm::SmallString is not empty<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch> //------------------------------------------------------------------------------ #include "cling/Interpreter/DynamicLibraryManager.h" #include "cling/Interpreter/InvocationOptions.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include <stdlib.h> #ifdef WIN32 #include <Windows.h> #else #include <limits.h> /* PATH_MAX */ #include <dlfcn.h> #endif namespace cling { DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts) : m_Opts(Opts) { } DynamicLibraryManager::~DynamicLibraryManager() {} static bool isSharedLib(llvm::StringRef LibName, bool& exists) { using namespace llvm::sys::fs; file_magic Magic; llvm::error_code Error = identify_magic(LibName, Magic); exists = (Error == llvm::errc::success); return exists && #ifdef __APPLE__ (Magic == file_magic::macho_fixed_virtual_memory_shared_lib || Magic == file_magic::macho_dynamically_linked_shared_lib || Magic == file_magic::macho_dynamically_linked_shared_lib_stub) #elif defined(LLVM_ON_UNIX) Magic == file_magic::elf_shared_object #elif defined(LLVM_ON_WIN32) # error "Windows DLLs not yet implemented!" //Magic == file_magic::pecoff_executable? #else # error "Unsupported platform." #endif ; } static void findSharedLibrary(llvm::StringRef fileStem, const llvm::SmallVectorImpl<std::string>& Paths, llvm::SmallString<512>& FoundDyLib, bool& exists, bool& isDyLib) { for (llvm::SmallVectorImpl<std::string>::const_iterator IPath = Paths.begin(), EPath = Paths.end(); IPath != EPath; ++IPath) { llvm::SmallString<512> ThisPath(*IPath); llvm::sys::path::append(ThisPath, fileStem); isDyLib = isSharedLib(ThisPath.str(), exists); if (isDyLib) ThisPath.swap(FoundDyLib); if (exists) return; } } #if defined(LLVM_ON_UNIX) static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) { char* env_var = getenv("LD_LIBRARY_PATH"); #if __APPLE__ if (!env_var) env_var = getenv("DYLD_LIBRARY_PATH"); if (!env_var) env_var = getenv("DYLD_FALLBACK_LIBRARY_PATH"); #endif if (env_var != 0) { static const char PathSeparator = ':'; const char* at = env_var; const char* delim = strchr(at, PathSeparator); while (delim != 0) { std::string tmp(at, size_t(delim-at)); if (llvm::sys::fs::is_directory(tmp.c_str())) Paths.push_back(tmp); at = delim + 1; delim = strchr(at, PathSeparator); } if (*at != 0) if (llvm::sys::fs::is_directory(llvm::StringRef(at))) Paths.push_back(at); } Paths.push_back("/usr/local/lib/"); Paths.push_back("/usr/X11R6/lib/"); Paths.push_back("/usr/lib/"); Paths.push_back("/lib/"); } #elif defined(LLVM_ON_WIN32) static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) { char buff[MAX_PATH]; // Generic form of C:\Windows\System32 HRESULT res = SHGetFolderPathA(NULL, CSIDL_FLAG_CREATE | CSIDL_SYSTEM, NULL, SHGFP_TYPE_CURRENT, buff); if (res != S_OK) { assert(0 && "Failed to get system directory"); return; } Paths.push_back(buff); // Reset buff. buff[0] = 0; // Generic form of C:\Windows res = SHGetFolderPathA(NULL, CSIDL_FLAG_CREATE | CSIDL_WINDOWS, NULL, SHGFP_TYPE_CURRENT, buff); if (res != S_OK) { assert(0 && "Failed to get windows directory"); return; } Paths.push_back(buff); } #else # error "Unsupported platform." #endif DynamicLibraryManager::LoadLibResult DynamicLibraryManager::tryLinker(const std::string& filename, bool permanent, bool isAbsolute, bool& exists, bool& isDyLib) { using namespace llvm::sys; exists = false; isDyLib = false; llvm::SmallString<512> FoundDyLib; if (isAbsolute) { isDyLib = isSharedLib(filename, exists); if (isDyLib) FoundDyLib = filename; } else { llvm::SmallVector<std::string, 16> SearchPaths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end()); GetSystemLibraryPaths(SearchPaths); findSharedLibrary(filename, SearchPaths, FoundDyLib, exists, isDyLib); if (!exists) { // Add DyLib extension: llvm::SmallString<512> filenameWithExt(filename); #if defined(LLVM_ON_UNIX) #ifdef __APPLE__ llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1; #endif static const char* DyLibExt = ".so"; #elif defined(LLVM_ON_WIN32) static const char* DyLibExt = ".dll"; #else # error "Unsupported platform." #endif filenameWithExt += DyLibExt; findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists, isDyLib); #ifdef __APPLE__ if (!exists) { filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end()); filenameWithExt += ".dylib"; findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists, isDyLib); } #endif } } if (!isDyLib) return kLoadLibError; assert(!FoundDyLib.empty() && "The shared lib exists but can't find it!"); // get canonical path name and check if already loaded #ifdef WIN32 llvm::SmallString<_MAX_PATH> FullPath; FullPath.set_size(_MAX_PATH); char *res = _fullpath((char *)FullPath.data(), FoundDyLib.c_str(), _MAX_PATH); #else llvm::SmallString<PATH_MAX+1> FullPath; FullPath.set_size(PATH_MAX+1); char *res = realpath(FoundDyLib.c_str(), (char *)FullPath.data()); #endif if (res == 0) { llvm::errs() << "cling::Interpreter::tryLinker(): error getting real (canonical) path\n"; return kLoadLibError; } FullPath.set_size(strlen(res)); if (m_loadedLibraries.find(FullPath) != m_loadedLibraries.end()) return kLoadLibExists; // TODO: !permanent case #ifdef WIN32 # error "Windows DLL opening still needs to be implemented!" void* dyLibHandle = needs to be implemented!; std::string errMsg; #else const void* dyLibHandle = dlopen(FullPath.c_str(), RTLD_LAZY|RTLD_GLOBAL); std::string errMsg; if (const char* DyLibError = dlerror()) { errMsg = DyLibError; } #endif if (!dyLibHandle) { llvm::errs() << "cling::Interpreter::tryLinker(): " << errMsg << '\n'; return kLoadLibError; } std::pair<DyLibs::iterator, bool> insRes = m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle, FullPath.str())); if (!insRes.second) return kLoadLibExists; m_loadedLibraries.insert(FullPath); return kLoadLibSuccess; } DynamicLibraryManager::LoadLibResult DynamicLibraryManager::loadLibrary(const std::string& filename, bool permanent, bool* tryCode) { llvm::SmallString<128> Absolute((llvm::StringRef(filename))); llvm::sys::fs::make_absolute(Absolute); bool isAbsolute = filename == Absolute.c_str(); bool exists = false; bool isDyLib = false; LoadLibResult res = tryLinker(filename, permanent, isAbsolute, exists, isDyLib); if (tryCode) { *tryCode = !isDyLib; if (isAbsolute) *tryCode &= exists; } if (exists) return res; if (!isAbsolute && filename.compare(0, 3, "lib")) { // try with "lib" prefix: res = tryLinker("lib" + filename, permanent, false, exists, isDyLib); if (tryCode) { *tryCode = !isDyLib; if (isAbsolute) *tryCode &= exists; } if (res != kLoadLibError) return res; } return kLoadLibError; } bool DynamicLibraryManager::isDynamicLibraryLoaded(llvm::StringRef fullPath) const { // get canonical path name and check if already loaded #ifdef WIN32 char buf[_MAX_PATH]; char *res = _fullpath(buf, fullPath.str().c_str(), _MAX_PATH); #else char buf[PATH_MAX+1]; char *res = realpath(fullPath.str().c_str(), buf); #endif if (res == 0) { llvm::errs() << "cling::Interpreter::isDynamicLibraryLoaded(): error getting real (canonical) path\n"; return false; } if (m_loadedLibraries.find(buf) != m_loadedLibraries.end()) return true; return false; } void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) { llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle)); } } // end namespace cling <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/Interpreter/DynamicLibraryManager.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/InvocationOptions.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #ifdef WIN32 #include <Windows.h> #include <shlobj.h> #else #include <limits.h> /* PATH_MAX */ #include <dlfcn.h> #endif namespace { #if defined(LLVM_ON_UNIX) static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) { char* env_var = getenv("LD_LIBRARY_PATH"); #if __APPLE__ if (!env_var) env_var = getenv("DYLD_LIBRARY_PATH"); if (!env_var) env_var = getenv("DYLD_FALLBACK_LIBRARY_PATH"); #endif if (env_var != 0) { static const char PathSeparator = ':'; const char* at = env_var; const char* delim = strchr(at, PathSeparator); while (delim != 0) { std::string tmp(at, size_t(delim-at)); if (llvm::sys::fs::is_directory(tmp.c_str())) Paths.push_back(tmp); at = delim + 1; delim = strchr(at, PathSeparator); } if (*at != 0) if (llvm::sys::fs::is_directory(llvm::StringRef(at))) Paths.push_back(at); } #if defined(__APPLE__) || defined(__CYGWIN__) Paths.push_back("/usr/local/lib/"); Paths.push_back("/usr/X11R6/lib/"); Paths.push_back("/usr/lib/"); Paths.push_back("/lib/"); Paths.push_back("/lib/x86_64-linux-gnu/"); Paths.push_back("/usr/local/lib64/"); Paths.push_back("/usr/lib64/"); Paths.push_back("/lib64/"); #else static bool initialized = false; static std::vector<std::string> SysPaths; if (!initialized) { // trick to get the system search path std::string cmd("LD_DEBUG=libs LD_PRELOAD=DOESNOTEXIST ls 2>&1"); FILE *pf = popen(cmd.c_str (), "r"); std::string result = ""; std::string sys_path = ""; char buffer[128]; while (!feof(pf)) { if (fgets(buffer, 128, pf) != NULL) result += buffer; } pclose(pf); std::size_t from = result.find("search path=", result.find("(LD_LIBRARY_PATH)")); std::size_t to = result.find("(system search path)"); if (from != std::string::npos && to != std::string::npos) { from += 12; sys_path = result.substr(from, to-from); sys_path.erase(std::remove_if(sys_path.begin(), sys_path.end(), isspace), sys_path.end()); sys_path += ':'; } static const char PathSeparator = ':'; const char* at = sys_path.c_str(); const char* delim = strchr(at, PathSeparator); while (delim != 0) { std::string tmp(at, size_t(delim-at)); if (llvm::sys::fs::is_directory(tmp.c_str())) SysPaths.push_back(tmp); at = delim + 1; delim = strchr(at, PathSeparator); } initialized = true; } for (std::vector<std::string>::const_iterator I = SysPaths.begin(), E = SysPaths.end(); I != E; ++I) Paths.push_back((*I).c_str()); #endif } #elif defined(LLVM_ON_WIN32) static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) { char buff[MAX_PATH]; // Generic form of C:\Windows\System32 HRESULT res = SHGetFolderPathA(NULL, CSIDL_FLAG_CREATE | CSIDL_SYSTEM, NULL, SHGFP_TYPE_CURRENT, buff); if (res != S_OK) { assert(0 && "Failed to get system directory"); return; } Paths.push_back(buff); // Reset buff. buff[0] = 0; // Generic form of C:\Windows res = SHGetFolderPathA(NULL, CSIDL_FLAG_CREATE | CSIDL_WINDOWS, NULL, SHGFP_TYPE_CURRENT, buff); if (res != S_OK) { assert(0 && "Failed to get windows directory"); return; } Paths.push_back(buff); } #else # error "Unsupported platform." #endif } namespace cling { DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts) : m_Opts(Opts), m_Callbacks(0) { GetSystemLibraryPaths(m_SystemSearchPaths); m_SystemSearchPaths.push_back("."); } DynamicLibraryManager::~DynamicLibraryManager() {} static bool isSharedLib(llvm::StringRef LibName, bool* exists = 0) { using namespace llvm::sys::fs; file_magic Magic; llvm::error_code Error = identify_magic(LibName, Magic); bool onDisk = (Error == llvm::errc::success); if (exists) *exists = onDisk; return onDisk && #ifdef __APPLE__ (Magic == file_magic::macho_fixed_virtual_memory_shared_lib || Magic == file_magic::macho_dynamically_linked_shared_lib || Magic == file_magic::macho_dynamically_linked_shared_lib_stub) #elif defined(LLVM_ON_UNIX) #ifdef __CYGWIN__ (Magic == file_magic::pecoff_executable) #else (Magic == file_magic::elf_shared_object) #endif #elif defined(LLVM_ON_WIN32) (Magic == file_magic::pecoff_executable) #else # error "Unsupported platform." #endif ; } std::string DynamicLibraryManager::lookupLibInPaths(llvm::StringRef libStem) const { llvm::SmallVector<std::string, 128> Paths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end()); Paths.append(m_SystemSearchPaths.begin(), m_SystemSearchPaths.end()); for (llvm::SmallVectorImpl<std::string>::const_iterator IPath = Paths.begin(), E = Paths.end();IPath != E; ++IPath) { llvm::SmallString<512> ThisPath(*IPath); // FIXME: move alloc outside loop llvm::sys::path::append(ThisPath, libStem); bool exists; if (isSharedLib(ThisPath.str(), &exists)) return ThisPath.str(); if (exists) return ""; } return ""; } std::string DynamicLibraryManager::lookupLibMaybeAddExt(llvm::StringRef libStem) const { using namespace llvm::sys; std::string foundDyLib = lookupLibInPaths(libStem); if (foundDyLib.empty()) { // Add DyLib extension: llvm::SmallString<512> filenameWithExt(libStem); #if defined(LLVM_ON_UNIX) #ifdef __APPLE__ llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1; #endif static const char* DyLibExt = ".so"; #elif defined(LLVM_ON_WIN32) static const char* DyLibExt = ".dll"; #else # error "Unsupported platform." #endif filenameWithExt += DyLibExt; foundDyLib = lookupLibInPaths(filenameWithExt); #ifdef __APPLE__ if (foundDyLib.empty()) { filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end()); filenameWithExt += ".dylib"; foundDyLib = lookupLibInPaths(filenameWithExt); } #endif } if (foundDyLib.empty()) return ""; // get canonical path name and check if already loaded #if defined(LLVM_ON_WIN32) llvm::SmallString<_MAX_PATH> FullPath(""); char *res = _fullpath((char *)FullPath.data(), foundDyLib.c_str(), _MAX_PATH); #else llvm::SmallString<PATH_MAX+1> FullPath(""); char *res = realpath(foundDyLib.c_str(), (char *)FullPath.data()); #endif if (res == 0) { llvm::errs() << "cling::DyLibMan::lookupLibMaybeAddExt(): error getting " "real (canonical) path of library " << foundDyLib << '\n'; return foundDyLib; } FullPath.set_size(strlen(res)); return FullPath.str(); } std::string DynamicLibraryManager::normalizePath(llvm::StringRef path) { // Make the path canonical if the file exists. struct stat buffer; if (stat(path.data(), &buffer) != 0) return ""; #if defined(LLVM_ON_WIN32) char buf[_MAX_PATH]; char *res = _fullpath(buf, path.data(), _MAX_PATH); #else char buf[PATH_MAX+1]; char *res = realpath(path.data(), buf); #endif if (res == 0) { assert(0 && "Cannot normalize!?"); return ""; } return res; } std::string DynamicLibraryManager::lookupLibrary(llvm::StringRef libStem) const { llvm::SmallString<128> Absolute(libStem); llvm::sys::fs::make_absolute(Absolute); bool isAbsolute = libStem == Absolute; // If it is an absolute path, don't try iterate over the paths. if (isAbsolute) { if (isSharedLib(libStem)) return normalizePath(libStem); else return ""; } std::string foundName = lookupLibMaybeAddExt(libStem); if (foundName.empty() && !libStem.startswith("lib")) { // try with "lib" prefix: foundName = lookupLibMaybeAddExt("lib" + libStem.str()); } if (isSharedLib(foundName)) return normalizePath(foundName); return ""; } DynamicLibraryManager::LoadLibResult DynamicLibraryManager::loadLibrary(const std::string& libStem, bool permanent) { std::string canonicalLoadedLib = lookupLibrary(libStem); if (canonicalLoadedLib.empty()) return kLoadLibNotFound; if (m_LoadedLibraries.find(canonicalLoadedLib) != m_LoadedLibraries.end()) return kLoadLibAlreadyLoaded; std::string errMsg; // TODO: !permanent case #if defined(LLVM_ON_WIN32) HMODULE dyLibHandle = LoadLibraryEx(canonicalLoadedLib.c_str(), NULL, DONT_RESOLVE_DLL_REFERENCES); errMsg = "LoadLibraryEx: GetLastError() returned "; errMsg += GetLastError(); #else const void* dyLibHandle = dlopen(canonicalLoadedLib.c_str(), RTLD_LAZY|RTLD_GLOBAL); if (const char* DyLibError = dlerror()) { errMsg = DyLibError; } #endif if (!dyLibHandle) { llvm::errs() << "cling::DyLibMan::loadLibrary(): " << errMsg << '\n'; return kLoadLibLoadError; } else if (InterpreterCallbacks* C = getCallbacks()) C->LibraryLoaded(dyLibHandle, canonicalLoadedLib); std::pair<DyLibs::iterator, bool> insRes = m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle, canonicalLoadedLib)); if (!insRes.second) return kLoadLibAlreadyLoaded; m_LoadedLibraries.insert(canonicalLoadedLib); return kLoadLibSuccess; } void DynamicLibraryManager::unloadLibrary(llvm::StringRef libStem) { std::string canonicalLoadedLib = lookupLibrary(libStem); if (!isLibraryLoaded(canonicalLoadedLib)) return; DyLibHandle dyLibHandle = 0; for (DyLibs::const_iterator I = m_DyLibs.begin(), E = m_DyLibs.end(); I != E; ++I) { if (I->second == canonicalLoadedLib) dyLibHandle = I->first; } std::string errMsg; // TODO: !permanent case #if defined(LLVM_ON_WIN32) FreeLibrary((HMODULE)dyLibHandle); errMsg = "UnoadLibraryEx: GetLastError() returned "; errMsg += GetLastError(); #else dlclose(const_cast<void*>(dyLibHandle)); if (const char* DyLibError = dlerror()) { errMsg = DyLibError; } #endif if (InterpreterCallbacks* C = getCallbacks()) C->LibraryUnloaded(dyLibHandle, canonicalLoadedLib); m_DyLibs.erase(dyLibHandle); m_LoadedLibraries.erase(canonicalLoadedLib); } bool DynamicLibraryManager::isLibraryLoaded(llvm::StringRef fullPath) const { std::string canonPath = normalizePath(fullPath); if (m_LoadedLibraries.find(canonPath) != m_LoadedLibraries.end()) return true; return false; } void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) { llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle)); } } // end namespace cling <commit_msg>Use actual class name to make it easier to find the source of errors.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/Interpreter/DynamicLibraryManager.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/InvocationOptions.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #ifdef WIN32 #include <Windows.h> #include <shlobj.h> #else #include <limits.h> /* PATH_MAX */ #include <dlfcn.h> #endif namespace { #if defined(LLVM_ON_UNIX) static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) { char* env_var = getenv("LD_LIBRARY_PATH"); #if __APPLE__ if (!env_var) env_var = getenv("DYLD_LIBRARY_PATH"); if (!env_var) env_var = getenv("DYLD_FALLBACK_LIBRARY_PATH"); #endif if (env_var != 0) { static const char PathSeparator = ':'; const char* at = env_var; const char* delim = strchr(at, PathSeparator); while (delim != 0) { std::string tmp(at, size_t(delim-at)); if (llvm::sys::fs::is_directory(tmp.c_str())) Paths.push_back(tmp); at = delim + 1; delim = strchr(at, PathSeparator); } if (*at != 0) if (llvm::sys::fs::is_directory(llvm::StringRef(at))) Paths.push_back(at); } #if defined(__APPLE__) || defined(__CYGWIN__) Paths.push_back("/usr/local/lib/"); Paths.push_back("/usr/X11R6/lib/"); Paths.push_back("/usr/lib/"); Paths.push_back("/lib/"); Paths.push_back("/lib/x86_64-linux-gnu/"); Paths.push_back("/usr/local/lib64/"); Paths.push_back("/usr/lib64/"); Paths.push_back("/lib64/"); #else static bool initialized = false; static std::vector<std::string> SysPaths; if (!initialized) { // trick to get the system search path std::string cmd("LD_DEBUG=libs LD_PRELOAD=DOESNOTEXIST ls 2>&1"); FILE *pf = popen(cmd.c_str (), "r"); std::string result = ""; std::string sys_path = ""; char buffer[128]; while (!feof(pf)) { if (fgets(buffer, 128, pf) != NULL) result += buffer; } pclose(pf); std::size_t from = result.find("search path=", result.find("(LD_LIBRARY_PATH)")); std::size_t to = result.find("(system search path)"); if (from != std::string::npos && to != std::string::npos) { from += 12; sys_path = result.substr(from, to-from); sys_path.erase(std::remove_if(sys_path.begin(), sys_path.end(), isspace), sys_path.end()); sys_path += ':'; } static const char PathSeparator = ':'; const char* at = sys_path.c_str(); const char* delim = strchr(at, PathSeparator); while (delim != 0) { std::string tmp(at, size_t(delim-at)); if (llvm::sys::fs::is_directory(tmp.c_str())) SysPaths.push_back(tmp); at = delim + 1; delim = strchr(at, PathSeparator); } initialized = true; } for (std::vector<std::string>::const_iterator I = SysPaths.begin(), E = SysPaths.end(); I != E; ++I) Paths.push_back((*I).c_str()); #endif } #elif defined(LLVM_ON_WIN32) static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) { char buff[MAX_PATH]; // Generic form of C:\Windows\System32 HRESULT res = SHGetFolderPathA(NULL, CSIDL_FLAG_CREATE | CSIDL_SYSTEM, NULL, SHGFP_TYPE_CURRENT, buff); if (res != S_OK) { assert(0 && "Failed to get system directory"); return; } Paths.push_back(buff); // Reset buff. buff[0] = 0; // Generic form of C:\Windows res = SHGetFolderPathA(NULL, CSIDL_FLAG_CREATE | CSIDL_WINDOWS, NULL, SHGFP_TYPE_CURRENT, buff); if (res != S_OK) { assert(0 && "Failed to get windows directory"); return; } Paths.push_back(buff); } #else # error "Unsupported platform." #endif } namespace cling { DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts) : m_Opts(Opts), m_Callbacks(0) { GetSystemLibraryPaths(m_SystemSearchPaths); m_SystemSearchPaths.push_back("."); } DynamicLibraryManager::~DynamicLibraryManager() {} static bool isSharedLib(llvm::StringRef LibName, bool* exists = 0) { using namespace llvm::sys::fs; file_magic Magic; llvm::error_code Error = identify_magic(LibName, Magic); bool onDisk = (Error == llvm::errc::success); if (exists) *exists = onDisk; return onDisk && #ifdef __APPLE__ (Magic == file_magic::macho_fixed_virtual_memory_shared_lib || Magic == file_magic::macho_dynamically_linked_shared_lib || Magic == file_magic::macho_dynamically_linked_shared_lib_stub) #elif defined(LLVM_ON_UNIX) #ifdef __CYGWIN__ (Magic == file_magic::pecoff_executable) #else (Magic == file_magic::elf_shared_object) #endif #elif defined(LLVM_ON_WIN32) (Magic == file_magic::pecoff_executable) #else # error "Unsupported platform." #endif ; } std::string DynamicLibraryManager::lookupLibInPaths(llvm::StringRef libStem) const { llvm::SmallVector<std::string, 128> Paths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end()); Paths.append(m_SystemSearchPaths.begin(), m_SystemSearchPaths.end()); for (llvm::SmallVectorImpl<std::string>::const_iterator IPath = Paths.begin(), E = Paths.end();IPath != E; ++IPath) { llvm::SmallString<512> ThisPath(*IPath); // FIXME: move alloc outside loop llvm::sys::path::append(ThisPath, libStem); bool exists; if (isSharedLib(ThisPath.str(), &exists)) return ThisPath.str(); if (exists) return ""; } return ""; } std::string DynamicLibraryManager::lookupLibMaybeAddExt(llvm::StringRef libStem) const { using namespace llvm::sys; std::string foundDyLib = lookupLibInPaths(libStem); if (foundDyLib.empty()) { // Add DyLib extension: llvm::SmallString<512> filenameWithExt(libStem); #if defined(LLVM_ON_UNIX) #ifdef __APPLE__ llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1; #endif static const char* DyLibExt = ".so"; #elif defined(LLVM_ON_WIN32) static const char* DyLibExt = ".dll"; #else # error "Unsupported platform." #endif filenameWithExt += DyLibExt; foundDyLib = lookupLibInPaths(filenameWithExt); #ifdef __APPLE__ if (foundDyLib.empty()) { filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end()); filenameWithExt += ".dylib"; foundDyLib = lookupLibInPaths(filenameWithExt); } #endif } if (foundDyLib.empty()) return ""; // get canonical path name and check if already loaded #if defined(LLVM_ON_WIN32) llvm::SmallString<_MAX_PATH> FullPath(""); char *res = _fullpath((char *)FullPath.data(), foundDyLib.c_str(), _MAX_PATH); #else llvm::SmallString<PATH_MAX+1> FullPath(""); char *res = realpath(foundDyLib.c_str(), (char *)FullPath.data()); #endif if (res == 0) { llvm::errs() << "cling::DynamicLibraryManager::lookupLibMaybeAddExt(): " "error getting real (canonical) path of library " << foundDyLib << '\n'; return foundDyLib; } FullPath.set_size(strlen(res)); return FullPath.str(); } std::string DynamicLibraryManager::normalizePath(llvm::StringRef path) { // Make the path canonical if the file exists. struct stat buffer; if (stat(path.data(), &buffer) != 0) return ""; #if defined(LLVM_ON_WIN32) char buf[_MAX_PATH]; char *res = _fullpath(buf, path.data(), _MAX_PATH); #else char buf[PATH_MAX+1]; char *res = realpath(path.data(), buf); #endif if (res == 0) { assert(0 && "Cannot normalize!?"); return ""; } return res; } std::string DynamicLibraryManager::lookupLibrary(llvm::StringRef libStem) const { llvm::SmallString<128> Absolute(libStem); llvm::sys::fs::make_absolute(Absolute); bool isAbsolute = libStem == Absolute; // If it is an absolute path, don't try iterate over the paths. if (isAbsolute) { if (isSharedLib(libStem)) return normalizePath(libStem); else return ""; } std::string foundName = lookupLibMaybeAddExt(libStem); if (foundName.empty() && !libStem.startswith("lib")) { // try with "lib" prefix: foundName = lookupLibMaybeAddExt("lib" + libStem.str()); } if (isSharedLib(foundName)) return normalizePath(foundName); return ""; } DynamicLibraryManager::LoadLibResult DynamicLibraryManager::loadLibrary(const std::string& libStem, bool permanent) { std::string canonicalLoadedLib = lookupLibrary(libStem); if (canonicalLoadedLib.empty()) return kLoadLibNotFound; if (m_LoadedLibraries.find(canonicalLoadedLib) != m_LoadedLibraries.end()) return kLoadLibAlreadyLoaded; std::string errMsg; // TODO: !permanent case #if defined(LLVM_ON_WIN32) HMODULE dyLibHandle = LoadLibraryEx(canonicalLoadedLib.c_str(), NULL, DONT_RESOLVE_DLL_REFERENCES); errMsg = "LoadLibraryEx: GetLastError() returned "; errMsg += GetLastError(); #else const void* dyLibHandle = dlopen(canonicalLoadedLib.c_str(), RTLD_LAZY|RTLD_GLOBAL); if (const char* DyLibError = dlerror()) { errMsg = DyLibError; } #endif if (!dyLibHandle) { llvm::errs() << "cling::DynamicLibraryManager::loadLibrary(): " << errMsg << '\n'; return kLoadLibLoadError; } else if (InterpreterCallbacks* C = getCallbacks()) C->LibraryLoaded(dyLibHandle, canonicalLoadedLib); std::pair<DyLibs::iterator, bool> insRes = m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle, canonicalLoadedLib)); if (!insRes.second) return kLoadLibAlreadyLoaded; m_LoadedLibraries.insert(canonicalLoadedLib); return kLoadLibSuccess; } void DynamicLibraryManager::unloadLibrary(llvm::StringRef libStem) { std::string canonicalLoadedLib = lookupLibrary(libStem); if (!isLibraryLoaded(canonicalLoadedLib)) return; DyLibHandle dyLibHandle = 0; for (DyLibs::const_iterator I = m_DyLibs.begin(), E = m_DyLibs.end(); I != E; ++I) { if (I->second == canonicalLoadedLib) dyLibHandle = I->first; } std::string errMsg; // TODO: !permanent case #if defined(LLVM_ON_WIN32) FreeLibrary((HMODULE)dyLibHandle); errMsg = "UnoadLibraryEx: GetLastError() returned "; errMsg += GetLastError(); #else dlclose(const_cast<void*>(dyLibHandle)); if (const char* DyLibError = dlerror()) { errMsg = DyLibError; } #endif if (InterpreterCallbacks* C = getCallbacks()) C->LibraryUnloaded(dyLibHandle, canonicalLoadedLib); m_DyLibs.erase(dyLibHandle); m_LoadedLibraries.erase(canonicalLoadedLib); } bool DynamicLibraryManager::isLibraryLoaded(llvm::StringRef fullPath) const { std::string canonPath = normalizePath(fullPath); if (m_LoadedLibraries.find(canonPath) != m_LoadedLibraries.end()) return true; return false; } void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) { llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle)); } } // end namespace cling <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// #pragma once #include "Graphics/BlendStateDesc.hpp" #include "Graphics/RasterizerStateDesc.hpp" #include "Graphics/DepthStencilStateDesc.hpp" #include "Graphics/InputLayoutDesc.hpp" #include "Graphics/SampleDesc.hpp" #include "Graphics/iResourceBinding.hpp" #include "Graphics/IndexStripCut.hpp" #include "Graphics/TopologyType.hpp" #include "IntrusivePtr.hpp" namespace CPF { namespace Graphics { struct iDevice; struct iShader; struct iPipeline; struct iResourceBinding; struct PipelineStateDesc { static constexpr int kMaxRenderTargets = 8; PipelineStateDesc(); PipelineStateDesc(const PipelineStateDesc& rhs); IntrusivePtr<iResourceBinding> mpResourceBinding; // TODO: Shaders should not be instances, they should be opaque handles or a struct. IntrusivePtr<iShader> mpVertex; IntrusivePtr<iShader> mpPixel; IntrusivePtr<iShader> mpDomain; IntrusivePtr<iShader> mpHull; IntrusivePtr<iShader> mpGeometry; BlendStateDesc mBlendState; uint32_t mSampleMask; RasterizerStateDesc mRasterizerState; DepthStencilStateDesc mDepthStencil; cInputLayoutDesc mInputLayout; IndexStripCut mIndexStripCut; TopologyType mTopology; int32_t mRenderTargetCount; Format mRenderTargetFormats[kMaxRenderTargets]; Format mDepthStencilFormat; SampleDesc mSampleState; // Items not in the pipeline at this time. // StreamOutput // node mask // cache pipeline state // flags }; inline PipelineStateDesc::PipelineStateDesc() : mBlendState(Defaults<BlendStateDesc>()) , mSampleMask(uint32_t(-1)) , mRasterizerState(Defaults<RasterizerStateDesc>()) , mIndexStripCut(IndexStripCut::eNone) , mTopology(TopologyType::eTriangle) , mRenderTargetCount(0) , mDepthStencilFormat(Format::eNone) , mSampleState{ 1, 0 } { for (int i = 0; i < kMaxRenderTargets; ++i) mRenderTargetFormats[i] = Format::eNone; } inline PipelineStateDesc::PipelineStateDesc(const PipelineStateDesc& rhs) : mpResourceBinding(rhs.mpResourceBinding) , mpVertex(rhs.mpVertex) , mpPixel(rhs.mpPixel) , mpDomain(rhs.mpDomain) , mpHull(rhs.mpHull) , mpGeometry(rhs.mpGeometry) , mBlendState(rhs.mBlendState) , mSampleMask(rhs.mSampleMask) , mRasterizerState(rhs.mRasterizerState) , mDepthStencil(rhs.mDepthStencil) , mInputLayout(rhs.mInputLayout) , mIndexStripCut(rhs.mIndexStripCut) , mTopology(rhs.mTopology) , mRenderTargetCount(rhs.mRenderTargetCount) , mDepthStencilFormat(rhs.mDepthStencilFormat) , mSampleState(rhs.mSampleState) { for (int i = 0; i < kMaxRenderTargets; ++i) mRenderTargetFormats[i] = rhs.mRenderTargetFormats[i]; } } } <commit_msg>Quick fixit.<commit_after>////////////////////////////////////////////////////////////////////////// #pragma once #include "Graphics/BlendStateDesc.hpp" #include "Graphics/RasterizerStateDesc.hpp" #include "Graphics/DepthStencilStateDesc.hpp" #include "Graphics/InputLayoutDesc.hpp" #include "Graphics/SampleDesc.hpp" #include "Graphics/iResourceBinding.hpp" #include "Graphics/IndexStripCut.hpp" #include "Graphics/TopologyType.hpp" #include "IntrusivePtr.hpp" namespace CPF { namespace Graphics { struct iDevice; struct iShader; struct iPipeline; struct iResourceBinding; struct PipelineStateDesc { static constexpr int kMaxRenderTargets = 8; PipelineStateDesc(); PipelineStateDesc(const PipelineStateDesc& rhs); IntrusivePtr<iResourceBinding> mpResourceBinding; // TODO: Shaders should not be instances, they should be opaque handles or a struct. IntrusivePtr<iShader> mpVertex; IntrusivePtr<iShader> mpPixel; IntrusivePtr<iShader> mpDomain; IntrusivePtr<iShader> mpHull; IntrusivePtr<iShader> mpGeometry; BlendStateDesc mBlendState; uint32_t mSampleMask; RasterizerStateDesc mRasterizerState; DepthStencilStateDesc mDepthStencil; InputLayoutDesc mInputLayout; IndexStripCut mIndexStripCut; TopologyType mTopology; int32_t mRenderTargetCount; Format mRenderTargetFormats[kMaxRenderTargets]; Format mDepthStencilFormat; SampleDesc mSampleState; // Items not in the pipeline at this time. // StreamOutput // node mask // cache pipeline state // flags }; inline PipelineStateDesc::PipelineStateDesc() : mBlendState(Defaults<BlendStateDesc>()) , mSampleMask(uint32_t(-1)) , mRasterizerState(Defaults<RasterizerStateDesc>()) , mIndexStripCut(IndexStripCut::eNone) , mTopology(TopologyType::eTriangle) , mRenderTargetCount(0) , mDepthStencilFormat(Format::eNone) , mSampleState{ 1, 0 } { for (int i = 0; i < kMaxRenderTargets; ++i) mRenderTargetFormats[i] = Format::eNone; } inline PipelineStateDesc::PipelineStateDesc(const PipelineStateDesc& rhs) : mpResourceBinding(rhs.mpResourceBinding) , mpVertex(rhs.mpVertex) , mpPixel(rhs.mpPixel) , mpDomain(rhs.mpDomain) , mpHull(rhs.mpHull) , mpGeometry(rhs.mpGeometry) , mBlendState(rhs.mBlendState) , mSampleMask(rhs.mSampleMask) , mRasterizerState(rhs.mRasterizerState) , mDepthStencil(rhs.mDepthStencil) , mInputLayout(rhs.mInputLayout) , mIndexStripCut(rhs.mIndexStripCut) , mTopology(rhs.mTopology) , mRenderTargetCount(rhs.mRenderTargetCount) , mDepthStencilFormat(rhs.mDepthStencilFormat) , mSampleState(rhs.mSampleState) { for (int i = 0; i < kMaxRenderTargets; ++i) mRenderTargetFormats[i] = rhs.mRenderTargetFormats[i]; } } } <|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 <svdata.hxx> #include <tools/time.hxx> #include <vcl/scheduler.hxx> #include <vcl/timer.hxx> #include <algorithm> #include <saltimer.hxx> void Scheduler::ImplInvoke(sal_uInt64 nTime) { mnUpdateTime = nTime; if (mpSchedulerData->mbDelete || mbInScheduler ) return; // prepare Scheduler Object for deletion after handling SetDeletionFlags(); // invoke it mbInScheduler = true; Invoke(); mbInScheduler = false; } Scheduler* Scheduler::ImplGetHighestPrioTask( bool bTimer ) { ImplSVData* pSVData = ImplGetSVData(); Scheduler * pMostUrgent = NULL; std::for_each(pSVData->maSchedulers->begin(), pSVData->maSchedulers->end(), [&pSVData, bTimer, &pMostUrgent] (ImplSchedulerData *rScheduler) { if ( rScheduler->mpScheduler && rScheduler->mpScheduler->ImplIsScheduleReady(pSVData->mnUpdateStack) && rScheduler->mpScheduler->ReadyForSchedule( bTimer ) && rScheduler->mpScheduler->IsActive() ) { if (!pMostUrgent) pMostUrgent = rScheduler->mpScheduler; else { // Find the highest priority. // If the priority of the current task is higher (numerical value is lower) than // the priority of the most urgent, the current task gets the new most urgent. if ( rScheduler->mpScheduler->GetPriority() < pMostUrgent->GetPriority() ) pMostUrgent = rScheduler->mpScheduler; } } }); return pMostUrgent; } void Scheduler::SetDeletionFlags() { Stop(); } void Scheduler::ImplDeInitScheduler(bool bAll /*=true*/) { ImplSVData* pSVData = ImplGetSVData(); if (pSVData->mpSalTimer) { pSVData->mpSalTimer->Stop(); } pSVData->maSchedulers->remove_if( [] (ImplSchedulerData *rSchedulerData) { if(rSchedulerData->mpScheduler != NULL) { rSchedulerData->mpScheduler->ImplDispose(); } else delete rSchedulerData; return true; }); if(bAll) { delete pSVData->maSchedulers; pSVData->maSchedulers = NULL; } delete pSVData->mpSalTimer; pSVData->mpSalTimer = NULL; } void Scheduler::CallbackTaskScheduling(bool ignore) { // this function is for the saltimer callback (void)ignore; Scheduler::ProcessTaskScheduling( true ); } void Scheduler::ProcessTaskScheduling( bool bTimer ) { // process all pending Tasks // if bTimer True, only handle timer Scheduler* pScheduler = NULL; ImplSVData* pSVData = ImplGetSVData(); sal_uInt64 nTime = tools::Time::GetSystemTicks(); sal_uInt64 nMinPeriod = MAX_TIMER_PERIOD; pSVData->mnUpdateStack++; // tdf#91727 - NB. bTimer is ultimately not used if ((pScheduler = Scheduler::ImplGetHighestPrioTask(bTimer)) != NULL) pScheduler->ImplInvoke(nTime); pSVData->maSchedulers->remove_if( [&nMinPeriod, nTime, pSVData] (ImplSchedulerData *rSchedulerData) { if (rSchedulerData->mpScheduler) return rSchedulerData->mpScheduler->ImplHandleTaskScheduling(nMinPeriod, nTime); else { delete rSchedulerData; return true; } }); // delete clock if no more timers available if ( pSVData->maSchedulers->empty() ) { if ( pSVData->mpSalTimer ) pSVData->mpSalTimer->Stop(); pSVData->mnTimerPeriod = MAX_TIMER_PERIOD; } else { Timer::ImplStartTimer( pSVData, nMinPeriod ); } pSVData->mnUpdateStack--; } void Scheduler::SetPriority( SchedulerPriority ePriority ) { mePriority = ePriority; } void Scheduler::Start() { ImplSVData* pSVData = ImplGetSVData(); // Mark timer active mbActive = true; if ( !mpSchedulerData ) { mpSchedulerData = new ImplSchedulerData; mpSchedulerData->mpScheduler = this; // insert Scheduler mbInScheduler = false; pSVData->maSchedulers->push_back(mpSchedulerData); } mpSchedulerData->mbDelete = false; mnUpdateTime = tools::Time::GetSystemTicks(); mnUpdateStack = pSVData->mnUpdateStack; } void Scheduler::Stop() { mbActive = false; if ( mpSchedulerData ) mpSchedulerData->mbDelete = true; } Scheduler& Scheduler::operator=( const Scheduler& rScheduler ) { if ( IsActive() ) Stop(); mbActive = false; mePriority = rScheduler.mePriority; if ( rScheduler.IsActive() ) Start(); return *this; } Scheduler::Scheduler(const sal_Char *pDebugName): mpSchedulerData(NULL), mpDebugName(pDebugName), mePriority(SchedulerPriority::HIGH), mbActive(false), mnUpdateTime(0) { } Scheduler::Scheduler( const Scheduler& rScheduler ): mpSchedulerData(NULL), mpDebugName(rScheduler.mpDebugName), mePriority(SchedulerPriority::HIGH), mbActive(false), mnUpdateTime(0) { if ( rScheduler.IsActive() ) Start(); } Scheduler::~Scheduler() { if ( mpSchedulerData ) { mpSchedulerData->mbDelete = true; mpSchedulerData->mpScheduler = NULL; } } bool Scheduler::ImplIsScheduleReady(sal_uInt32 nUpdateStack) { return !mpSchedulerData->mbDelete && (mnUpdateStack <= nUpdateStack); } void Scheduler::ImplDispose() { mpSchedulerData->mpScheduler = NULL; delete mpSchedulerData; mpSchedulerData = NULL; } void Scheduler::ImplInitScheduler() { ImplSVData* pSVData = ImplGetSVData(); if(pSVData->maSchedulers == NULL) pSVData->maSchedulers = new ImplScheduler_t; } bool Scheduler::ImplHandleTaskScheduling(sal_uInt64 &nMinPeriod, sal_uInt64 nTime) { // process all pending Tasks if( !mbInScheduler ) { // Should Task be released from scheduling? if ( !mpSchedulerData->mbDelete ) { mnUpdateStack = 0; nMinPeriod = UpdateMinPeriod( nMinPeriod, nTime ); } else { ImplDispose(); return true; } } return false; } <commit_msg>vcl: loplugin:pointertobool<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 <svdata.hxx> #include <tools/time.hxx> #include <vcl/scheduler.hxx> #include <vcl/timer.hxx> #include <algorithm> #include <saltimer.hxx> void Scheduler::ImplInvoke(sal_uInt64 nTime) { mnUpdateTime = nTime; if (mpSchedulerData->mbDelete || mbInScheduler ) return; // prepare Scheduler Object for deletion after handling SetDeletionFlags(); // invoke it mbInScheduler = true; Invoke(); mbInScheduler = false; } Scheduler* Scheduler::ImplGetHighestPrioTask( bool bTimer ) { ImplSVData* pSVData = ImplGetSVData(); Scheduler * pMostUrgent = NULL; std::for_each(pSVData->maSchedulers->begin(), pSVData->maSchedulers->end(), [&pSVData, bTimer, &pMostUrgent] (ImplSchedulerData *rScheduler) { if ( rScheduler->mpScheduler && rScheduler->mpScheduler->ImplIsScheduleReady(pSVData->mnUpdateStack) && rScheduler->mpScheduler->ReadyForSchedule( bTimer ) && rScheduler->mpScheduler->IsActive() ) { if (!pMostUrgent) pMostUrgent = rScheduler->mpScheduler; else { // Find the highest priority. // If the priority of the current task is higher (numerical value is lower) than // the priority of the most urgent, the current task gets the new most urgent. if ( rScheduler->mpScheduler->GetPriority() < pMostUrgent->GetPriority() ) pMostUrgent = rScheduler->mpScheduler; } } }); return pMostUrgent; } void Scheduler::SetDeletionFlags() { Stop(); } void Scheduler::ImplDeInitScheduler(bool bAll /*=true*/) { ImplSVData* pSVData = ImplGetSVData(); if (pSVData->mpSalTimer) { pSVData->mpSalTimer->Stop(); } pSVData->maSchedulers->remove_if( [] (ImplSchedulerData *rSchedulerData) { if(rSchedulerData->mpScheduler != NULL) { rSchedulerData->mpScheduler->ImplDispose(); } else delete rSchedulerData; return true; }); if(bAll) { delete pSVData->maSchedulers; pSVData->maSchedulers = NULL; } delete pSVData->mpSalTimer; pSVData->mpSalTimer = NULL; } void Scheduler::CallbackTaskScheduling(bool ignore) { // this function is for the saltimer callback (void)ignore; Scheduler::ProcessTaskScheduling( true ); } void Scheduler::ProcessTaskScheduling( bool bTimer ) { // process all pending Tasks // if bTimer True, only handle timer Scheduler* pScheduler = NULL; ImplSVData* pSVData = ImplGetSVData(); sal_uInt64 nTime = tools::Time::GetSystemTicks(); sal_uInt64 nMinPeriod = MAX_TIMER_PERIOD; pSVData->mnUpdateStack++; // tdf#91727 - NB. bTimer is ultimately not used if ((pScheduler = Scheduler::ImplGetHighestPrioTask(bTimer)) != NULL) pScheduler->ImplInvoke(nTime); pSVData->maSchedulers->remove_if( [&nMinPeriod, nTime, pSVData] (ImplSchedulerData *rSchedulerData) { if (rSchedulerData->mpScheduler != 0) return rSchedulerData->mpScheduler->ImplHandleTaskScheduling(nMinPeriod, nTime); else { delete rSchedulerData; return true; } }); // delete clock if no more timers available if ( pSVData->maSchedulers->empty() ) { if ( pSVData->mpSalTimer ) pSVData->mpSalTimer->Stop(); pSVData->mnTimerPeriod = MAX_TIMER_PERIOD; } else { Timer::ImplStartTimer( pSVData, nMinPeriod ); } pSVData->mnUpdateStack--; } void Scheduler::SetPriority( SchedulerPriority ePriority ) { mePriority = ePriority; } void Scheduler::Start() { ImplSVData* pSVData = ImplGetSVData(); // Mark timer active mbActive = true; if ( !mpSchedulerData ) { mpSchedulerData = new ImplSchedulerData; mpSchedulerData->mpScheduler = this; // insert Scheduler mbInScheduler = false; pSVData->maSchedulers->push_back(mpSchedulerData); } mpSchedulerData->mbDelete = false; mnUpdateTime = tools::Time::GetSystemTicks(); mnUpdateStack = pSVData->mnUpdateStack; } void Scheduler::Stop() { mbActive = false; if ( mpSchedulerData ) mpSchedulerData->mbDelete = true; } Scheduler& Scheduler::operator=( const Scheduler& rScheduler ) { if ( IsActive() ) Stop(); mbActive = false; mePriority = rScheduler.mePriority; if ( rScheduler.IsActive() ) Start(); return *this; } Scheduler::Scheduler(const sal_Char *pDebugName): mpSchedulerData(NULL), mpDebugName(pDebugName), mePriority(SchedulerPriority::HIGH), mbActive(false), mnUpdateTime(0) { } Scheduler::Scheduler( const Scheduler& rScheduler ): mpSchedulerData(NULL), mpDebugName(rScheduler.mpDebugName), mePriority(SchedulerPriority::HIGH), mbActive(false), mnUpdateTime(0) { if ( rScheduler.IsActive() ) Start(); } Scheduler::~Scheduler() { if ( mpSchedulerData ) { mpSchedulerData->mbDelete = true; mpSchedulerData->mpScheduler = NULL; } } bool Scheduler::ImplIsScheduleReady(sal_uInt32 nUpdateStack) { return !mpSchedulerData->mbDelete && (mnUpdateStack <= nUpdateStack); } void Scheduler::ImplDispose() { mpSchedulerData->mpScheduler = NULL; delete mpSchedulerData; mpSchedulerData = NULL; } void Scheduler::ImplInitScheduler() { ImplSVData* pSVData = ImplGetSVData(); if(pSVData->maSchedulers == NULL) pSVData->maSchedulers = new ImplScheduler_t; } bool Scheduler::ImplHandleTaskScheduling(sal_uInt64 &nMinPeriod, sal_uInt64 nTime) { // process all pending Tasks if( !mbInScheduler ) { // Should Task be released from scheduling? if ( !mpSchedulerData->mbDelete ) { mnUpdateStack = 0; nMinPeriod = UpdateMinPeriod( nMinPeriod, nTime ); } else { ImplDispose(); return true; } } return false; } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved */ #include "../../StroikaPreComp.h" #include "../../Streams/iostream/BinaryOutputStreamFromOStreamAdapter.h" #include "../../Streams/TextOutputStreamBinaryAdapter.h" #include "Writer.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::DataExchangeFormat; using namespace Stroika::Foundation::Streams; /* * TODO: * No known issues */ /* ******************************************************************************** *************** DataExchangeFormat::JSON::PrettyPrint ************************** ******************************************************************************** */ namespace { void Indent_ (const TextOutputStream& out, int indentLevel) { for (int i = 0; i < indentLevel; ++i) { out.Write (L" "); } } } namespace { void PrettyPrint_ (const Memory::VariantValue& v, const TextOutputStream& out, int indentLevel); void PrettyPrint_Null_ (const TextOutputStream& out) { out.Write (L"null"); } void PrettyPrint_ (bool v, const TextOutputStream& out) { if (v) { out.Write (L"true"); } else { out.Write (L"false"); } } void PrettyPrint_ (long long int v, const TextOutputStream& out) { wchar_t buf[1024]; ::swprintf (buf, NEltsOf (buf), L"%lld", v); out.Write (buf); } void PrettyPrint_ (unsigned long long int v, const TextOutputStream& out) { wchar_t buf[1024]; ::swprintf (buf, NEltsOf (buf), L"%llu", v); out.Write (buf); } void PrettyPrint_ (long double v, const TextOutputStream& out) { wchar_t buf[1024]; ::swprintf (buf, NEltsOf (buf), L"%Lf", v); Assert (::wcslen (buf) >= 1); // trim trailing 0 for (size_t i = ::wcslen (buf) - 1; buf[i] == '0'; --i) { if (i >= 0 and buf[i - 1] != '.') { buf[i] = '\0'; } } out.Write (buf); } void PrettyPrint_ (const wstring& v, const TextOutputStream& out) { out.Write (L"\""); for (auto i = v.begin (); i != v.end (); ++i) { switch (*i) { case '\"': out.Write (L"\\\""); break; case '\\': out.Write (L"\\\\"); break; case '\n': out.Write (L"\\n"); break; case '\r': out.Write (L"\\r"); break; // unclear if we need to quote other chars such as \f\t\b\ but probably not... default: wchar_t c = *i; out.Write (&c, &c + 1); break; } } out.Write (L"\""); } void PrettyPrint_ (const vector<Memory::VariantValue>& v, const TextOutputStream& out, int indentLevel) { out.Write (L"[\n"); for (auto i = v.begin (); i != v.end (); ++i) { Indent_ (out, indentLevel + 1); PrettyPrint_ (*i, out, indentLevel + 1); if (i + 1 != v.end ()) { out.Write (L","); } out.Write (L"\n"); } Indent_ (out, indentLevel); out.Write (L"]"); } void PrettyPrint_ (const map<wstring, Memory::VariantValue>& v, const TextOutputStream& out, int indentLevel) { out.Write (L"{\n"); for (auto i = v.begin (); i != v.end ();) { Indent_ (out, indentLevel + 1); PrettyPrint_ (i->first, out, indentLevel + 1); out.Write (L" : "); PrettyPrint_ (i->second, out, indentLevel + 1); ++i; if (i != v.end ()) { out.Write (L","); } out.Write (L"\n"); } Indent_ (out, indentLevel); out.Write (L"}"); } void PrettyPrint_ (const Memory::VariantValue& v, const TextOutputStream& out, int indentLevel) { switch (v.GetType ()) { case Memory::VariantValue::Type::eNull: PrettyPrint_Null_ (out); break; case Memory::VariantValue::Type::eBoolean: PrettyPrint_ (v.As<bool> (), out); break; case Memory::VariantValue::Type::eDate: PrettyPrint_ (v.As<wstring> (), out); break; case Memory::VariantValue::Type::eDateTime: PrettyPrint_ (v.As<wstring> (), out); break; case Memory::VariantValue::Type::eInteger: PrettyPrint_ (v.As<long long int> (), out); break; case Memory::VariantValue::Type::eUnsignedInteger: PrettyPrint_ (v.As<unsigned long long int> (), out); break; case Memory::VariantValue::Type::eFloat: PrettyPrint_ (v.As<long double> (), out); break; case Memory::VariantValue::Type::eString: PrettyPrint_ (v.As<wstring> (), out); break; case Memory::VariantValue::Type::eMap: PrettyPrint_ (v.As<map<wstring, Memory::VariantValue>> (), out, indentLevel); break; case Memory::VariantValue::Type::eArray: PrettyPrint_ (v.As<vector<Memory::VariantValue>> (), out, indentLevel); break; default: RequireNotReached (); // only certain types allowed } } } /* ******************************************************************************** ******************** DataExchangeFormat::JSON::Writer ************************** ******************************************************************************** */ class DataExchangeFormat::JSON::Writer::Rep_ : public DataExchangeFormat::Writer::_IRep { public: DECLARE_USE_BLOCK_ALLOCATION (Rep_); public: virtual _SharedPtrIRep Clone () const override { return _SharedPtrIRep (new Rep_ ()); // no instance data } virtual void Write (const Memory::VariantValue& v, const Streams::BinaryOutputStream& out) override { PrettyPrint_ (v, TextOutputStreamBinaryAdapter (out, TextOutputStreamBinaryAdapter::Format::eUTF8WithoutBOM), 0); } virtual void Write (const Memory::VariantValue& v, const Streams::TextOutputStream& out) override { PrettyPrint_ (v, out, 0); } }; DataExchangeFormat::JSON::Writer::Writer () : inherited (shared_ptr<_IRep> (new Rep_ ())) { } <commit_msg>in JSON writer, extra NL at end of mapping & array - maybe makes layout look better (experiment)<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved */ #include "../../StroikaPreComp.h" #include "../../Streams/iostream/BinaryOutputStreamFromOStreamAdapter.h" #include "../../Streams/TextOutputStreamBinaryAdapter.h" #include "Writer.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::DataExchangeFormat; using namespace Stroika::Foundation::Streams; /* * TODO: * No known issues */ /* ******************************************************************************** *************** DataExchangeFormat::JSON::PrettyPrint ************************** ******************************************************************************** */ namespace { void Indent_ (const TextOutputStream& out, int indentLevel) { for (int i = 0; i < indentLevel; ++i) { out.Write (L" "); } } } namespace { void PrettyPrint_ (const Memory::VariantValue& v, const TextOutputStream& out, int indentLevel); void PrettyPrint_Null_ (const TextOutputStream& out) { out.Write (L"null"); } void PrettyPrint_ (bool v, const TextOutputStream& out) { if (v) { out.Write (L"true"); } else { out.Write (L"false"); } } void PrettyPrint_ (long long int v, const TextOutputStream& out) { wchar_t buf[1024]; ::swprintf (buf, NEltsOf (buf), L"%lld", v); out.Write (buf); } void PrettyPrint_ (unsigned long long int v, const TextOutputStream& out) { wchar_t buf[1024]; ::swprintf (buf, NEltsOf (buf), L"%llu", v); out.Write (buf); } void PrettyPrint_ (long double v, const TextOutputStream& out) { wchar_t buf[1024]; ::swprintf (buf, NEltsOf (buf), L"%Lf", v); Assert (::wcslen (buf) >= 1); // trim trailing 0 for (size_t i = ::wcslen (buf) - 1; buf[i] == '0'; --i) { if (i >= 0 and buf[i - 1] != '.') { buf[i] = '\0'; } } out.Write (buf); } void PrettyPrint_ (const wstring& v, const TextOutputStream& out) { out.Write (L"\""); for (auto i = v.begin (); i != v.end (); ++i) { switch (*i) { case '\"': out.Write (L"\\\""); break; case '\\': out.Write (L"\\\\"); break; case '\n': out.Write (L"\\n"); break; case '\r': out.Write (L"\\r"); break; // unclear if we need to quote other chars such as \f\t\b\ but probably not... default: wchar_t c = *i; out.Write (&c, &c + 1); break; } } out.Write (L"\""); } void PrettyPrint_ (const vector<Memory::VariantValue>& v, const TextOutputStream& out, int indentLevel) { out.Write (L"[\n"); for (auto i = v.begin (); i != v.end (); ++i) { Indent_ (out, indentLevel + 1); PrettyPrint_ (*i, out, indentLevel + 1); if (i + 1 != v.end ()) { out.Write (L","); } out.Write (L"\n"); } Indent_ (out, indentLevel); out.Write (L"]\n"); } void PrettyPrint_ (const map<wstring, Memory::VariantValue>& v, const TextOutputStream& out, int indentLevel) { out.Write (L"{\n"); for (auto i = v.begin (); i != v.end ();) { Indent_ (out, indentLevel + 1); PrettyPrint_ (i->first, out, indentLevel + 1); out.Write (L" : "); PrettyPrint_ (i->second, out, indentLevel + 1); ++i; if (i != v.end ()) { out.Write (L","); } out.Write (L"\n"); } Indent_ (out, indentLevel); out.Write (L"}\n"); } void PrettyPrint_ (const Memory::VariantValue& v, const TextOutputStream& out, int indentLevel) { switch (v.GetType ()) { case Memory::VariantValue::Type::eNull: PrettyPrint_Null_ (out); break; case Memory::VariantValue::Type::eBoolean: PrettyPrint_ (v.As<bool> (), out); break; case Memory::VariantValue::Type::eDate: PrettyPrint_ (v.As<wstring> (), out); break; case Memory::VariantValue::Type::eDateTime: PrettyPrint_ (v.As<wstring> (), out); break; case Memory::VariantValue::Type::eInteger: PrettyPrint_ (v.As<long long int> (), out); break; case Memory::VariantValue::Type::eUnsignedInteger: PrettyPrint_ (v.As<unsigned long long int> (), out); break; case Memory::VariantValue::Type::eFloat: PrettyPrint_ (v.As<long double> (), out); break; case Memory::VariantValue::Type::eString: PrettyPrint_ (v.As<wstring> (), out); break; case Memory::VariantValue::Type::eMap: PrettyPrint_ (v.As<map<wstring, Memory::VariantValue>> (), out, indentLevel); break; case Memory::VariantValue::Type::eArray: PrettyPrint_ (v.As<vector<Memory::VariantValue>> (), out, indentLevel); break; default: RequireNotReached (); // only certain types allowed } } } /* ******************************************************************************** ******************** DataExchangeFormat::JSON::Writer ************************** ******************************************************************************** */ class DataExchangeFormat::JSON::Writer::Rep_ : public DataExchangeFormat::Writer::_IRep { public: DECLARE_USE_BLOCK_ALLOCATION (Rep_); public: virtual _SharedPtrIRep Clone () const override { return _SharedPtrIRep (new Rep_ ()); // no instance data } virtual void Write (const Memory::VariantValue& v, const Streams::BinaryOutputStream& out) override { PrettyPrint_ (v, TextOutputStreamBinaryAdapter (out, TextOutputStreamBinaryAdapter::Format::eUTF8WithoutBOM), 0); } virtual void Write (const Memory::VariantValue& v, const Streams::TextOutputStream& out) override { PrettyPrint_ (v, out, 0); } }; DataExchangeFormat::JSON::Writer::Writer () : inherited (shared_ptr<_IRep> (new Rep_ ())) { } <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. * * 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 "paddle/operators/maxout_op.h" namespace paddle { namespace operators { using framework::Tensor; class MaxOutOpMaker : public framework::OpProtoAndCheckerMaker { public: MaxOutOpMaker(framework::OpProto* proto, framework::OpAttrChecker* op_checker) : OpProtoAndCheckerMaker(proto, op_checker) { AddInput( "X", "(Tensor) The input tensor of maxout operator. " "The format of input tensor is NCHW. Where N is batch size, C is the " "number of channels, H and W is the height and width of feature."); AddOutput("Out", "(Tensor) The output tensor of maxout operator." "The format of output tensor is also NCHW." "Where N is batch size, C is " "the number of channels, H and W is the height and " "width of feature."); AddAttr<int>( "groups", R"DOC("Specifies how many groups the input tensor will be split" "in the channel dimension. And the number of output channel is " "the number of channels divided by groups.." )DOC"); AddComment(R"DOC( Assumed the input shape is (N, Ci, H, W). The output shape is (N, Co, H, W). Then `Co = Ci / groups`. math: y_{si+j} = \max_k x_{gsi + sk + j} g = groups s = input.size / num_channels 0 \le i < num_channels / groups 0 \le j < s 0 \le k < groups Please refer to Paper: - Maxout Networks: http://www.jmlr.org/proceedings/papers/v28/goodfellow13.pdf - Multi-digit Number Recognition from Street View \ Imagery using Deep Convolutional Neural Networks: \ https://arxiv.org/pdf/1312.6082v4.pdf )DOC"); } }; class MaxOutOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) of MaxoutOp" "should not be null."); PADDLE_ENFORCE(ctx->HasOutput("Out"), "Output(Out) of MaxoutOp should not be null."); auto in_x_dims = ctx->GetInputDim("X"); int groups = ctx->Attrs().Get<int>("groups"); // check groups > 1 PADDLE_ENFORCE_GT(groups, 1, "groups should be larger than 1 in maxoutop"); std::vector<int64_t> output_shape({in_x_dims[0], in_x_dims[1] / groups}); output_shape.push_back(in_x_dims[2]); output_shape.push_back(in_x_dims[3]); ctx->SetOutputDim("Out", framework::make_ddim(output_shape)); } }; class MaxOutOpGrad : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) must not be null."); PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("X")), "Input(X@GRAD) should not be null."); ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X")); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP(maxout, ops::MaxOutOp, ops::MaxOutOpMaker, maxout_grad, ops::MaxOutOpGrad); REGISTER_OP_CPU_KERNEL(maxout, ops::MaxOutKernel<paddle::platform::CPUPlace, float>); REGISTER_OP_CPU_KERNEL( maxout_grad, ops::MaxOutGradKernel<paddle::platform::CPUPlace, float>); <commit_msg>fix maxout op latex equation (#6303)<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. * * 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 "paddle/operators/maxout_op.h" namespace paddle { namespace operators { using framework::Tensor; class MaxOutOpMaker : public framework::OpProtoAndCheckerMaker { public: MaxOutOpMaker(framework::OpProto* proto, framework::OpAttrChecker* op_checker) : OpProtoAndCheckerMaker(proto, op_checker) { AddInput( "X", "(Tensor) The input tensor of maxout operator. " "The format of input tensor is NCHW. Where N is batch size, C is the " "number of channels, H and W is the height and width of feature."); AddOutput("Out", "(Tensor) The output tensor of maxout operator." "The format of output tensor is also NCHW." "Where N is batch size, C is " "the number of channels, H and W is the height and " "width of feature."); AddAttr<int>( "groups", R"DOC("Specifies how many groups the input tensor will be split" "in the channel dimension. And the number of output channel is " "the number of channels divided by groups.." )DOC"); AddComment(R"DOC( MaxOut Operator. Assumed the input shape is (N, Ci, H, W). The output shape is (N, Co, H, W). Then $Co = Ci / groups$ and the operator formula is as follows: $$ y_{si+j} = \max_k x_{gsi + sk + j} \\ g = groups \\ s = \frac{input.size}{num\_channels} \\ 0 \le i < \frac{num\_channels}{groups} \\ 0 \le j < s \\ 0 \le k < groups $$ Please refer to Paper: - Maxout Networks: http://www.jmlr.org/proceedings/papers/v28/goodfellow13.pdf - Multi-digit Number Recognition from Street View \ Imagery using Deep Convolutional Neural Networks: \ https://arxiv.org/pdf/1312.6082v4.pdf )DOC"); } }; class MaxOutOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) of MaxoutOp" "should not be null."); PADDLE_ENFORCE(ctx->HasOutput("Out"), "Output(Out) of MaxoutOp should not be null."); auto in_x_dims = ctx->GetInputDim("X"); int groups = ctx->Attrs().Get<int>("groups"); // check groups > 1 PADDLE_ENFORCE_GT(groups, 1, "groups should be larger than 1 in maxoutop"); std::vector<int64_t> output_shape({in_x_dims[0], in_x_dims[1] / groups}); output_shape.push_back(in_x_dims[2]); output_shape.push_back(in_x_dims[3]); ctx->SetOutputDim("Out", framework::make_ddim(output_shape)); } }; class MaxOutOpGrad : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) must not be null."); PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("X")), "Input(X@GRAD) should not be null."); ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X")); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP(maxout, ops::MaxOutOp, ops::MaxOutOpMaker, maxout_grad, ops::MaxOutOpGrad); REGISTER_OP_CPU_KERNEL(maxout, ops::MaxOutKernel<paddle::platform::CPUPlace, float>); REGISTER_OP_CPU_KERNEL( maxout_grad, ops::MaxOutGradKernel<paddle::platform::CPUPlace, float>); <|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2011 Francois Beaune // // 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. // // Interface header. #include "cameracontroller.h" // appleseed.renderer headers. #include "renderer/api/camera.h" #include "renderer/api/scene.h" #include "renderer/api/utility.h" // appleseed.foundation headers. #include "foundation/math/transform.h" // Qt headers. #include <QEvent> #include <QMouseEvent> #include <QWidget> using namespace foundation; using namespace renderer; namespace appleseed { namespace studio { // // CameraController class implementation. // CameraController::CameraController( QWidget* render_widget, Scene* scene) : m_render_widget(render_widget) , m_camera(scene->get_camera()) { configure_controller(scene); m_render_widget->installEventFilter(this); } CameraController::~CameraController() { m_render_widget->removeEventFilter(this); m_camera->get_parameters().insert("controller_target", m_controller.get_target()); } void CameraController::update_camera_transform() { m_camera->set_transform(Transformd(m_controller.get_transform())); } bool CameraController::eventFilter(QObject* object, QEvent* event) { switch (event->type()) { case QEvent::MouseButtonPress: if (handle_mouse_button_press_event(static_cast<QMouseEvent*>(event))) return true; break; case QEvent::MouseButtonRelease: if (handle_mouse_button_release_event(static_cast<QMouseEvent*>(event))) return true; break; case QEvent::MouseMove: if (handle_mouse_move_event(static_cast<QMouseEvent*>(event))) return true; break; } return QObject::eventFilter(object, event); } void CameraController::configure_controller(const Scene* scene) { // Set the controller orientation and position based on the scene camera. m_controller.set_transform( m_camera->get_transform().get_local_to_parent()); if (m_camera->get_parameters().strings().exist("controller_target")) { // The camera already has a target position, use it. m_controller.set_target( m_camera->get_parameters().get_optional<Vector3d>( "controller_target", Vector3d(0.0))); } else { // Otherwise, if the scene is not empty, use its center as the target position. const GAABB3 scene_bbox = compute_parent_bbox<GAABB3>( scene->assembly_instances().begin(), scene->assembly_instances().end()); if (scene_bbox.is_valid()) m_controller.set_target(Vector3d(scene_bbox.center())); } } Vector2d CameraController::get_mouse_position(const QMouseEvent* event) const { const int width = m_render_widget->width(); const int height = m_render_widget->height(); const double x = static_cast<double>(event->x()) / width; const double y = -static_cast<double>(event->y()) / height; return Vector2d(x, y); } bool CameraController::handle_mouse_button_press_event(const QMouseEvent* event) { if (m_controller.is_dragging()) return false; if (!(event->modifiers() & Qt::ControlModifier)) return false; const Vector2d position = get_mouse_position(event); switch (event->button()) { case Qt::LeftButton: m_controller.begin_drag(ControllerType::Tumble, position); return true; case Qt::MidButton: m_controller.begin_drag(ControllerType::Track, position); return true; case Qt::RightButton: m_controller.begin_drag(ControllerType::Dolly, position); return true; } return false; } bool CameraController::handle_mouse_button_release_event(const QMouseEvent* event) { if (!m_controller.is_dragging()) return false; m_controller.end_drag(); return true; } bool CameraController::handle_mouse_move_event(const QMouseEvent* event) { if (!m_controller.is_dragging()) return false; const Vector2d position = get_mouse_position(event); m_controller.update_drag(position); emit signal_camera_changed(); return true; } } // namespace studio } // namespace appleseed <commit_msg>it is now possible to "track" the camera using the left mouse button + Alt, in addition to the middle mouse button.<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2011 Francois Beaune // // 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. // // Interface header. #include "cameracontroller.h" // appleseed.renderer headers. #include "renderer/api/camera.h" #include "renderer/api/scene.h" #include "renderer/api/utility.h" // appleseed.foundation headers. #include "foundation/math/transform.h" // Qt headers. #include <QEvent> #include <QMouseEvent> #include <QWidget> using namespace foundation; using namespace renderer; namespace appleseed { namespace studio { // // CameraController class implementation. // CameraController::CameraController( QWidget* render_widget, Scene* scene) : m_render_widget(render_widget) , m_camera(scene->get_camera()) { configure_controller(scene); m_render_widget->installEventFilter(this); } CameraController::~CameraController() { m_render_widget->removeEventFilter(this); m_camera->get_parameters().insert("controller_target", m_controller.get_target()); } void CameraController::update_camera_transform() { m_camera->set_transform(Transformd(m_controller.get_transform())); } bool CameraController::eventFilter(QObject* object, QEvent* event) { switch (event->type()) { case QEvent::MouseButtonPress: if (handle_mouse_button_press_event(static_cast<QMouseEvent*>(event))) return true; break; case QEvent::MouseButtonRelease: if (handle_mouse_button_release_event(static_cast<QMouseEvent*>(event))) return true; break; case QEvent::MouseMove: if (handle_mouse_move_event(static_cast<QMouseEvent*>(event))) return true; break; } return QObject::eventFilter(object, event); } void CameraController::configure_controller(const Scene* scene) { // Set the controller orientation and position based on the scene camera. m_controller.set_transform( m_camera->get_transform().get_local_to_parent()); if (m_camera->get_parameters().strings().exist("controller_target")) { // The camera already has a target position, use it. m_controller.set_target( m_camera->get_parameters().get_optional<Vector3d>( "controller_target", Vector3d(0.0))); } else { // Otherwise, if the scene is not empty, use its center as the target position. const GAABB3 scene_bbox = compute_parent_bbox<GAABB3>( scene->assembly_instances().begin(), scene->assembly_instances().end()); if (scene_bbox.is_valid()) m_controller.set_target(Vector3d(scene_bbox.center())); } } Vector2d CameraController::get_mouse_position(const QMouseEvent* event) const { const int width = m_render_widget->width(); const int height = m_render_widget->height(); const double x = static_cast<double>(event->x()) / width; const double y = -static_cast<double>(event->y()) / height; return Vector2d(x, y); } bool CameraController::handle_mouse_button_press_event(const QMouseEvent* event) { if (m_controller.is_dragging()) return false; if (!(event->modifiers() & Qt::ControlModifier)) return false; const Vector2d position = get_mouse_position(event); switch (event->button()) { case Qt::LeftButton: m_controller.begin_drag( (event->modifiers() & Qt::AltModifier) ? ControllerType::Track : ControllerType::Tumble, position); return true; case Qt::MidButton: m_controller.begin_drag(ControllerType::Track, position); return true; case Qt::RightButton: m_controller.begin_drag(ControllerType::Dolly, position); return true; } return false; } bool CameraController::handle_mouse_button_release_event(const QMouseEvent* event) { if (!m_controller.is_dragging()) return false; m_controller.end_drag(); return true; } bool CameraController::handle_mouse_move_event(const QMouseEvent* event) { if (!m_controller.is_dragging()) return false; const Vector2d position = get_mouse_position(event); m_controller.update_drag(position); emit signal_camera_changed(); return true; } } // namespace studio } // namespace appleseed <|endoftext|>
<commit_before>#pragma once #include <functional> #include <vector> #include <string> namespace GUI { /// A window where a hymn can be selected. class SelectHymnWindow { public: /// Constructor. SelectHymnWindow(); /// Scan the save directory for hymns. void Scan(); /// Show the window and let the user select a hymn. void Show(); /// Set function to call when closed. /** * @param callback Function to call when window is closed. */ void SetClosedCallback(std::function<void(const std::string&)> callback); /// Get whether the window is visible. /** * @return Whether the window is visible. */ bool IsVisible() const; /// Set whether the window should be visible. /** * @param visible Whether the window should be visible. */ void SetVisible(bool visible); /// Set window title. /** * @param title Window title. */ void SetTitle(const char* title); /// Set the name of the open button. /** * @param openButtonName The name of the open button. */ void SetOpenButtonName(const char* openButtonName); private: // Interaction bool hasClosedCallback = false; std::function<void(const std::string&)> closedCallback; std::vector<std::string> files; char name[128] = ""; bool visible = false; const char* title; const char* openButtonName; }; } <commit_msg>Proper initialization of character array.<commit_after>#pragma once #include <functional> #include <vector> #include <string> namespace GUI { /// A window where a hymn can be selected. class SelectHymnWindow { public: /// Constructor. SelectHymnWindow(); /// Scan the save directory for hymns. void Scan(); /// Show the window and let the user select a hymn. void Show(); /// Set function to call when closed. /** * @param callback Function to call when window is closed. */ void SetClosedCallback(std::function<void(const std::string&)> callback); /// Get whether the window is visible. /** * @return Whether the window is visible. */ bool IsVisible() const; /// Set whether the window should be visible. /** * @param visible Whether the window should be visible. */ void SetVisible(bool visible); /// Set window title. /** * @param title Window title. */ void SetTitle(const char* title); /// Set the name of the open button. /** * @param openButtonName The name of the open button. */ void SetOpenButtonName(const char* openButtonName); private: // Interaction bool hasClosedCallback = false; std::function<void(const std::string&)> closedCallback; std::vector<std::string> files; char name[128] = {'\0'}; bool visible = false; const char* title; const char* openButtonName; }; } <|endoftext|>
<commit_before>//===--- SemaPseudoObject.cpp - Semantic Analysis for Pseudo-Objects ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements semantic analysis for expressions involving // pseudo-object references. Pseudo-objects are conceptual objects // whose storage is entirely abstract and all accesses to which are // translated through some sort of abstraction barrier. // // For example, Objective-C objects can have "properties", either // declared or undeclared. A property may be accessed by writing // expr.prop // where 'expr' is an r-value of Objective-C pointer type and 'prop' // is the name of the property. If this expression is used in a context // needing an r-value, it is treated as if it were a message-send // of the associated 'getter' selector, typically: // [expr prop] // If it is used as the LHS of a simple assignment, it is treated // as a message-send of the associated 'setter' selector, typically: // [expr setProp: RHS] // If it is used as the LHS of a compound assignment, or the operand // of a unary increment or decrement, both are required; for example, // 'expr.prop *= 100' would be translated to: // [expr setProp: [expr prop] * 100] // //===----------------------------------------------------------------------===// #include "clang/Sema/SemaInternal.h" #include "clang/Sema/Initialization.h" #include "clang/AST/ExprObjC.h" #include "clang/Lex/Preprocessor.h" using namespace clang; using namespace sema; static ObjCMethodDecl *LookupMethodInReceiverType(Sema &S, Selector sel, const ObjCPropertyRefExpr *PRE) { bool instanceProperty; QualType searchType; if (PRE->isObjectReceiver()) { searchType = PRE->getBase()->getType() ->castAs<ObjCObjectPointerType>()->getPointeeType(); instanceProperty = true; } else if (PRE->isSuperReceiver()) { searchType = PRE->getSuperReceiverType(); instanceProperty = false; if (const ObjCObjectPointerType *PT = searchType->getAs<ObjCObjectPointerType>()) { searchType = PT->getPointeeType(); instanceProperty = true; } } else if (PRE->isClassReceiver()) { searchType = S.Context.getObjCInterfaceType(PRE->getClassReceiver()); instanceProperty = false; } return S.LookupMethodInObjectType(sel, searchType, instanceProperty); } ExprResult Sema::checkPseudoObjectRValue(Expr *E) { assert(E->getValueKind() == VK_LValue && E->getObjectKind() == OK_ObjCProperty); const ObjCPropertyRefExpr *PRE = E->getObjCProperty(); QualType ReceiverType; if (PRE->isObjectReceiver()) ReceiverType = PRE->getBase()->getType(); else if (PRE->isSuperReceiver()) ReceiverType = PRE->getSuperReceiverType(); else ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver()); ExprValueKind VK = VK_RValue; QualType T; if (PRE->isImplicitProperty()) { if (ObjCMethodDecl *GetterMethod = PRE->getImplicitPropertyGetter()) { T = getMessageSendResultType(ReceiverType, GetterMethod, PRE->isClassReceiver(), PRE->isSuperReceiver()); VK = Expr::getValueKindForType(GetterMethod->getResultType()); } else { Diag(PRE->getLocation(), diag::err_getter_not_found) << PRE->getBase()->getType(); return ExprError(); } } else { ObjCPropertyDecl *prop = PRE->getExplicitProperty(); ObjCMethodDecl *getter = LookupMethodInReceiverType(*this, prop->getGetterName(), PRE); if (getter && !getter->hasRelatedResultType()) DiagnosePropertyAccessorMismatch(prop, getter, PRE->getLocation()); if (!getter) getter = prop->getGetterMethodDecl(); // Figure out the type of the expression. Mostly this is the // result type of the getter, if possible. if (getter) { T = getMessageSendResultType(ReceiverType, getter, PRE->isClassReceiver(), PRE->isSuperReceiver()); VK = Expr::getValueKindForType(getter->getResultType()); // As a special case, if the method returns 'id', try to get a // better type from the property. if (VK == VK_RValue && T->isObjCIdType() && prop->getType()->isObjCRetainableType()) T = prop->getType(); } else { T = prop->getType(); VK = Expr::getValueKindForType(T); T = T.getNonLValueExprType(Context); } } E->setType(T); E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty, E, 0, VK); ExprResult Result = MaybeBindToTemporary(E); if (!Result.isInvalid()) E = Result.take(); return Owned(E); } namespace { struct PseudoObjectInfo { const ObjCPropertyRefExpr *RefExpr; bool HasSetter; Selector SetterSelector; ParmVarDecl *SetterParam; QualType SetterParamType; void setSetter(ObjCMethodDecl *setter) { HasSetter = true; SetterParam = *setter->param_begin(); SetterParamType = SetterParam->getType().getUnqualifiedType(); } PseudoObjectInfo(Sema &S, Expr *E) : RefExpr(E->getObjCProperty()), HasSetter(false), SetterParam(0) { assert(E->getValueKind() == VK_LValue && E->getObjectKind() == OK_ObjCProperty); // Try to find a setter. // For implicit properties, just trust the lookup we already did. if (RefExpr->isImplicitProperty()) { if (ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter()) { setSetter(setter); SetterSelector = setter->getSelector(); } else { IdentifierInfo *getterName = RefExpr->getImplicitPropertyGetter()->getSelector() .getIdentifierInfoForSlot(0); SetterSelector = SelectorTable::constructSetterName(S.PP.getIdentifierTable(), S.PP.getSelectorTable(), getterName); } return; } // For explicit properties, this is more involved. ObjCPropertyDecl *prop = RefExpr->getExplicitProperty(); SetterSelector = prop->getSetterName(); // Do a normal method lookup first. if (ObjCMethodDecl *setter = LookupMethodInReceiverType(S, SetterSelector, RefExpr)) { setSetter(setter); return; } // If that failed, trust the type on the @property declaration. if (!prop->isReadOnly()) { HasSetter = true; SetterParamType = prop->getType().getUnqualifiedType(); } } }; } /// Check an increment or decrement of a pseudo-object expression. ExprResult Sema::checkPseudoObjectIncDec(Scope *S, SourceLocation opcLoc, UnaryOperatorKind opcode, Expr *op) { assert(UnaryOperator::isIncrementDecrementOp(opcode)); PseudoObjectInfo info(*this, op); // If there's no setter, we have no choice but to try to assign to // the result of the getter. if (!info.HasSetter) { QualType resultType = info.RefExpr->getGetterResultType(); assert(!resultType.isNull() && "property has no setter and no getter!"); // Only do this if the getter returns an l-value reference type. if (const LValueReferenceType *refType = resultType->getAs<LValueReferenceType>()) { op = ImplicitCastExpr::Create(Context, refType->getPointeeType(), CK_GetObjCProperty, op, 0, VK_LValue); return BuildUnaryOp(S, opcLoc, opcode, op); } // Otherwise, it's an error. Diag(opcLoc, diag::err_nosetter_property_incdec) << unsigned(info.RefExpr->isImplicitProperty()) << unsigned(UnaryOperator::isDecrementOp(opcode)) << info.SetterSelector << op->getSourceRange(); return ExprError(); } // ++/-- behave like compound assignments, i.e. they need a getter. QualType getterResultType = info.RefExpr->getGetterResultType(); if (getterResultType.isNull()) { assert(info.RefExpr->isImplicitProperty()); Diag(opcLoc, diag::err_nogetter_property_incdec) << unsigned(UnaryOperator::isDecrementOp(opcode)) << info.RefExpr->getImplicitPropertyGetter()->getSelector() << op->getSourceRange(); return ExprError(); } // HACK: change the type of the operand to prevent further placeholder // transformation. op->setType(getterResultType.getNonLValueExprType(Context)); op->setObjectKind(OK_Ordinary); ExprResult result = CreateBuiltinUnaryOp(opcLoc, opcode, op); if (result.isInvalid()) return ExprError(); // Change the object kind back. op->setObjectKind(OK_ObjCProperty); return result; } ExprResult Sema::checkPseudoObjectAssignment(Scope *S, SourceLocation opcLoc, BinaryOperatorKind opcode, Expr *LHS, Expr *RHS) { assert(BinaryOperator::isAssignmentOp(opcode)); PseudoObjectInfo info(*this, LHS); // If there's no setter, we have no choice but to try to assign to // the result of the getter. if (!info.HasSetter) { QualType resultType = info.RefExpr->getGetterResultType(); assert(!resultType.isNull() && "property has no setter and no getter!"); // Only do this if the getter returns an l-value reference type. if (const LValueReferenceType *refType = resultType->getAs<LValueReferenceType>()) { LHS = ImplicitCastExpr::Create(Context, refType->getPointeeType(), CK_GetObjCProperty, LHS, 0, VK_LValue); return BuildBinOp(S, opcLoc, opcode, LHS, RHS); } // Otherwise, it's an error. Diag(opcLoc, diag::err_nosetter_property_assignment) << unsigned(info.RefExpr->isImplicitProperty()) << info.SetterSelector << LHS->getSourceRange() << RHS->getSourceRange(); return ExprError(); } // If there is a setter, we definitely want to use it. // If this is a simple assignment, just initialize the parameter // with the RHS. if (opcode == BO_Assign) { LHS->setType(info.SetterParamType.getNonLValueExprType(Context)); // Under certain circumstances, we need to type-check the RHS as a // straight-up parameter initialization. This gives somewhat // inferior diagnostics, so we try to avoid it. if (RHS->isTypeDependent()) { // Just build the expression. } else if ((getLangOptions().CPlusPlus && LHS->getType()->isRecordType()) || (getLangOptions().ObjCAutoRefCount && info.SetterParam && info.SetterParam->hasAttr<NSConsumedAttr>())) { InitializedEntity param = (info.SetterParam ? InitializedEntity::InitializeParameter(Context, info.SetterParam) : InitializedEntity::InitializeParameter(Context, info.SetterParamType, /*consumed*/ false)); ExprResult arg = PerformCopyInitialization(param, opcLoc, RHS); if (arg.isInvalid()) return ExprError(); RHS = arg.take(); // Warn about assignments of +1 objects to unsafe pointers in ARC. // CheckAssignmentOperands does this on the other path. if (getLangOptions().ObjCAutoRefCount) checkUnsafeExprAssigns(opcLoc, LHS, RHS); } else { ExprResult RHSResult = Owned(RHS); LHS->setObjectKind(OK_Ordinary); QualType resultType = CheckAssignmentOperands(LHS, RHSResult, opcLoc, /*compound*/ QualType()); LHS->setObjectKind(OK_ObjCProperty); if (!RHSResult.isInvalid()) RHS = RHSResult.take(); if (resultType.isNull()) return ExprError(); } // Warn about property sets in ARC that might cause retain cycles. if (getLangOptions().ObjCAutoRefCount && !info.RefExpr->isSuperReceiver()) checkRetainCycles(const_cast<Expr*>(info.RefExpr->getBase()), RHS); return new (Context) BinaryOperator(LHS, RHS, opcode, RHS->getType(), RHS->getValueKind(), RHS->getObjectKind(), opcLoc); } // If this is a compound assignment, we need to use the getter, too. QualType getterResultType = info.RefExpr->getGetterResultType(); if (getterResultType.isNull()) { Diag(opcLoc, diag::err_nogetter_property_compound_assignment) << LHS->getSourceRange() << RHS->getSourceRange(); return ExprError(); } // HACK: change the type of the LHS to prevent further placeholder // transformation. LHS->setType(getterResultType.getNonLValueExprType(Context)); LHS->setObjectKind(OK_Ordinary); ExprResult result = CreateBuiltinBinOp(opcLoc, opcode, LHS, RHS); if (result.isInvalid()) return ExprError(); // Change the object kind back. LHS->setObjectKind(OK_ObjCProperty); return result; } <commit_msg>Reflow code. No intended functionality change.<commit_after>//===--- SemaPseudoObject.cpp - Semantic Analysis for Pseudo-Objects ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements semantic analysis for expressions involving // pseudo-object references. Pseudo-objects are conceptual objects // whose storage is entirely abstract and all accesses to which are // translated through some sort of abstraction barrier. // // For example, Objective-C objects can have "properties", either // declared or undeclared. A property may be accessed by writing // expr.prop // where 'expr' is an r-value of Objective-C pointer type and 'prop' // is the name of the property. If this expression is used in a context // needing an r-value, it is treated as if it were a message-send // of the associated 'getter' selector, typically: // [expr prop] // If it is used as the LHS of a simple assignment, it is treated // as a message-send of the associated 'setter' selector, typically: // [expr setProp: RHS] // If it is used as the LHS of a compound assignment, or the operand // of a unary increment or decrement, both are required; for example, // 'expr.prop *= 100' would be translated to: // [expr setProp: [expr prop] * 100] // //===----------------------------------------------------------------------===// #include "clang/Sema/SemaInternal.h" #include "clang/Sema/Initialization.h" #include "clang/AST/ExprObjC.h" #include "clang/Lex/Preprocessor.h" using namespace clang; using namespace sema; static ObjCMethodDecl *LookupMethodInReceiverType(Sema &S, Selector sel, const ObjCPropertyRefExpr *PRE) { if (PRE->isObjectReceiver()) { const ObjCObjectPointerType *PT = PRE->getBase()->getType()->castAs<ObjCObjectPointerType>(); return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true); } if (PRE->isSuperReceiver()) { if (const ObjCObjectPointerType *PT = PRE->getSuperReceiverType()->getAs<ObjCObjectPointerType>()) return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true); return S.LookupMethodInObjectType(sel, PRE->getSuperReceiverType(), false); } assert(PRE->isClassReceiver() && "Invalid expression"); QualType IT = S.Context.getObjCInterfaceType(PRE->getClassReceiver()); return S.LookupMethodInObjectType(sel, IT, false); } ExprResult Sema::checkPseudoObjectRValue(Expr *E) { assert(E->getValueKind() == VK_LValue && E->getObjectKind() == OK_ObjCProperty); const ObjCPropertyRefExpr *PRE = E->getObjCProperty(); QualType ReceiverType; if (PRE->isObjectReceiver()) ReceiverType = PRE->getBase()->getType(); else if (PRE->isSuperReceiver()) ReceiverType = PRE->getSuperReceiverType(); else ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver()); ExprValueKind VK = VK_RValue; QualType T; if (PRE->isImplicitProperty()) { if (ObjCMethodDecl *GetterMethod = PRE->getImplicitPropertyGetter()) { T = getMessageSendResultType(ReceiverType, GetterMethod, PRE->isClassReceiver(), PRE->isSuperReceiver()); VK = Expr::getValueKindForType(GetterMethod->getResultType()); } else { Diag(PRE->getLocation(), diag::err_getter_not_found) << PRE->getBase()->getType(); return ExprError(); } } else { ObjCPropertyDecl *prop = PRE->getExplicitProperty(); ObjCMethodDecl *getter = LookupMethodInReceiverType(*this, prop->getGetterName(), PRE); if (getter && !getter->hasRelatedResultType()) DiagnosePropertyAccessorMismatch(prop, getter, PRE->getLocation()); if (!getter) getter = prop->getGetterMethodDecl(); // Figure out the type of the expression. Mostly this is the // result type of the getter, if possible. if (getter) { T = getMessageSendResultType(ReceiverType, getter, PRE->isClassReceiver(), PRE->isSuperReceiver()); VK = Expr::getValueKindForType(getter->getResultType()); // As a special case, if the method returns 'id', try to get a // better type from the property. if (VK == VK_RValue && T->isObjCIdType() && prop->getType()->isObjCRetainableType()) T = prop->getType(); } else { T = prop->getType(); VK = Expr::getValueKindForType(T); T = T.getNonLValueExprType(Context); } } E->setType(T); E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty, E, 0, VK); ExprResult Result = MaybeBindToTemporary(E); if (!Result.isInvalid()) E = Result.take(); return Owned(E); } namespace { struct PseudoObjectInfo { const ObjCPropertyRefExpr *RefExpr; bool HasSetter; Selector SetterSelector; ParmVarDecl *SetterParam; QualType SetterParamType; void setSetter(ObjCMethodDecl *setter) { HasSetter = true; SetterParam = *setter->param_begin(); SetterParamType = SetterParam->getType().getUnqualifiedType(); } PseudoObjectInfo(Sema &S, Expr *E) : RefExpr(E->getObjCProperty()), HasSetter(false), SetterParam(0) { assert(E->getValueKind() == VK_LValue && E->getObjectKind() == OK_ObjCProperty); // Try to find a setter. // For implicit properties, just trust the lookup we already did. if (RefExpr->isImplicitProperty()) { if (ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter()) { setSetter(setter); SetterSelector = setter->getSelector(); } else { IdentifierInfo *getterName = RefExpr->getImplicitPropertyGetter()->getSelector() .getIdentifierInfoForSlot(0); SetterSelector = SelectorTable::constructSetterName(S.PP.getIdentifierTable(), S.PP.getSelectorTable(), getterName); } return; } // For explicit properties, this is more involved. ObjCPropertyDecl *prop = RefExpr->getExplicitProperty(); SetterSelector = prop->getSetterName(); // Do a normal method lookup first. if (ObjCMethodDecl *setter = LookupMethodInReceiverType(S, SetterSelector, RefExpr)) { setSetter(setter); return; } // If that failed, trust the type on the @property declaration. if (!prop->isReadOnly()) { HasSetter = true; SetterParamType = prop->getType().getUnqualifiedType(); } } }; } /// Check an increment or decrement of a pseudo-object expression. ExprResult Sema::checkPseudoObjectIncDec(Scope *S, SourceLocation opcLoc, UnaryOperatorKind opcode, Expr *op) { assert(UnaryOperator::isIncrementDecrementOp(opcode)); PseudoObjectInfo info(*this, op); // If there's no setter, we have no choice but to try to assign to // the result of the getter. if (!info.HasSetter) { QualType resultType = info.RefExpr->getGetterResultType(); assert(!resultType.isNull() && "property has no setter and no getter!"); // Only do this if the getter returns an l-value reference type. if (const LValueReferenceType *refType = resultType->getAs<LValueReferenceType>()) { op = ImplicitCastExpr::Create(Context, refType->getPointeeType(), CK_GetObjCProperty, op, 0, VK_LValue); return BuildUnaryOp(S, opcLoc, opcode, op); } // Otherwise, it's an error. Diag(opcLoc, diag::err_nosetter_property_incdec) << unsigned(info.RefExpr->isImplicitProperty()) << unsigned(UnaryOperator::isDecrementOp(opcode)) << info.SetterSelector << op->getSourceRange(); return ExprError(); } // ++/-- behave like compound assignments, i.e. they need a getter. QualType getterResultType = info.RefExpr->getGetterResultType(); if (getterResultType.isNull()) { assert(info.RefExpr->isImplicitProperty()); Diag(opcLoc, diag::err_nogetter_property_incdec) << unsigned(UnaryOperator::isDecrementOp(opcode)) << info.RefExpr->getImplicitPropertyGetter()->getSelector() << op->getSourceRange(); return ExprError(); } // HACK: change the type of the operand to prevent further placeholder // transformation. op->setType(getterResultType.getNonLValueExprType(Context)); op->setObjectKind(OK_Ordinary); ExprResult result = CreateBuiltinUnaryOp(opcLoc, opcode, op); if (result.isInvalid()) return ExprError(); // Change the object kind back. op->setObjectKind(OK_ObjCProperty); return result; } ExprResult Sema::checkPseudoObjectAssignment(Scope *S, SourceLocation opcLoc, BinaryOperatorKind opcode, Expr *LHS, Expr *RHS) { assert(BinaryOperator::isAssignmentOp(opcode)); PseudoObjectInfo info(*this, LHS); // If there's no setter, we have no choice but to try to assign to // the result of the getter. if (!info.HasSetter) { QualType resultType = info.RefExpr->getGetterResultType(); assert(!resultType.isNull() && "property has no setter and no getter!"); // Only do this if the getter returns an l-value reference type. if (const LValueReferenceType *refType = resultType->getAs<LValueReferenceType>()) { LHS = ImplicitCastExpr::Create(Context, refType->getPointeeType(), CK_GetObjCProperty, LHS, 0, VK_LValue); return BuildBinOp(S, opcLoc, opcode, LHS, RHS); } // Otherwise, it's an error. Diag(opcLoc, diag::err_nosetter_property_assignment) << unsigned(info.RefExpr->isImplicitProperty()) << info.SetterSelector << LHS->getSourceRange() << RHS->getSourceRange(); return ExprError(); } // If there is a setter, we definitely want to use it. // If this is a simple assignment, just initialize the parameter // with the RHS. if (opcode == BO_Assign) { LHS->setType(info.SetterParamType.getNonLValueExprType(Context)); // Under certain circumstances, we need to type-check the RHS as a // straight-up parameter initialization. This gives somewhat // inferior diagnostics, so we try to avoid it. if (RHS->isTypeDependent()) { // Just build the expression. } else if ((getLangOptions().CPlusPlus && LHS->getType()->isRecordType()) || (getLangOptions().ObjCAutoRefCount && info.SetterParam && info.SetterParam->hasAttr<NSConsumedAttr>())) { InitializedEntity param = (info.SetterParam ? InitializedEntity::InitializeParameter(Context, info.SetterParam) : InitializedEntity::InitializeParameter(Context, info.SetterParamType, /*consumed*/ false)); ExprResult arg = PerformCopyInitialization(param, opcLoc, RHS); if (arg.isInvalid()) return ExprError(); RHS = arg.take(); // Warn about assignments of +1 objects to unsafe pointers in ARC. // CheckAssignmentOperands does this on the other path. if (getLangOptions().ObjCAutoRefCount) checkUnsafeExprAssigns(opcLoc, LHS, RHS); } else { ExprResult RHSResult = Owned(RHS); LHS->setObjectKind(OK_Ordinary); QualType resultType = CheckAssignmentOperands(LHS, RHSResult, opcLoc, /*compound*/ QualType()); LHS->setObjectKind(OK_ObjCProperty); if (!RHSResult.isInvalid()) RHS = RHSResult.take(); if (resultType.isNull()) return ExprError(); } // Warn about property sets in ARC that might cause retain cycles. if (getLangOptions().ObjCAutoRefCount && !info.RefExpr->isSuperReceiver()) checkRetainCycles(const_cast<Expr*>(info.RefExpr->getBase()), RHS); return new (Context) BinaryOperator(LHS, RHS, opcode, RHS->getType(), RHS->getValueKind(), RHS->getObjectKind(), opcLoc); } // If this is a compound assignment, we need to use the getter, too. QualType getterResultType = info.RefExpr->getGetterResultType(); if (getterResultType.isNull()) { Diag(opcLoc, diag::err_nogetter_property_compound_assignment) << LHS->getSourceRange() << RHS->getSourceRange(); return ExprError(); } // HACK: change the type of the LHS to prevent further placeholder // transformation. LHS->setType(getterResultType.getNonLValueExprType(Context)); LHS->setObjectKind(OK_Ordinary); ExprResult result = CreateBuiltinBinOp(opcLoc, opcode, LHS, RHS); if (result.isInvalid()) return ExprError(); // Change the object kind back. LHS->setObjectKind(OK_ObjCProperty); return result; } <|endoftext|>
<commit_before>/* HardwareSerial.cpp - Hardware serial library for Wiring Copyright (c) 2006 Nicholas Zambetti. All right 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. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified 23 November 2006 by David A. Mellis Modified 28 September 2010 by Mark Sproul */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <inttypes.h> #include "wiring.h" #include "wiring_private.h" // this next line disables the entire HardwareSerial.cpp, // this is so I can support Attiny series and any other chip without a uart #if defined(UBRRH) || defined(UBRR0H) || defined(UBRR1H) || defined(UBRR2H) || defined(UBRR3H) #include "HardwareSerial.h" // Define constants and variables for buffering incoming serial data. We're // using a ring buffer (I think), in which rx_buffer_head is the index of the // location to which to write the next incoming character and rx_buffer_tail // is the index of the location from which to read. #if (RAMEND < 1000) #define RX_BUFFER_SIZE 32 #else #define RX_BUFFER_SIZE 128 #endif struct ring_buffer { unsigned char buffer[RX_BUFFER_SIZE]; int head; int tail; }; #if defined(UBRRH) || defined(UBRR0H) ring_buffer rx_buffer = { { 0 }, 0, 0 }; #endif #if defined(UBRR1H) ring_buffer rx_buffer1 = { { 0 }, 0, 0 }; #endif #if defined(UBRR2H) ring_buffer rx_buffer2 = { { 0 }, 0, 0 }; #endif #if defined(UBRR3H) ring_buffer rx_buffer3 = { { 0 }, 0, 0 }; #endif inline void store_char(unsigned char c, ring_buffer *rx_buffer) { int i = (unsigned int)(rx_buffer->head + 1) % RX_BUFFER_SIZE; // if we should be storing the received character into the location // just before the tail (meaning that the head would advance to the // current location of the tail), we're about to overflow the buffer // and so we don't write the character or advance the head. if (i != rx_buffer->tail) { rx_buffer->buffer[rx_buffer->head] = c; rx_buffer->head = i; } } #if defined(USART_RX_vect) SIGNAL(USART_RX_vect) { #if defined(UDR0) unsigned char c = UDR0; #elif defined(UDR) unsigned char c = UDR; // atmega8535 #else #error UDR not defined #endif store_char(c, &rx_buffer); } #elif defined(SIG_USART0_RECV) && defined(UDR0) SIGNAL(SIG_USART0_RECV) { unsigned char c = UDR0; store_char(c, &rx_buffer); } #elif defined(SIG_UART0_RECV) && defined(UDR0) SIGNAL(SIG_UART0_RECV) { unsigned char c = UDR0; store_char(c, &rx_buffer); } //#elif defined(SIG_USART_RECV) #elif defined(USART0_RX_vect) // fixed by Mark Sproul this is on the 644/644p //SIGNAL(SIG_USART_RECV) SIGNAL(USART0_RX_vect) { #if defined(UDR0) unsigned char c = UDR0; #elif defined(UDR) unsigned char c = UDR; // atmega8, atmega32 #else #error UDR not defined #endif store_char(c, &rx_buffer); } #elif defined(SIG_UART_RECV) // this is for atmega8 SIGNAL(SIG_UART_RECV) { #if defined(UDR0) unsigned char c = UDR0; // atmega645 #elif defined(UDR) unsigned char c = UDR; // atmega8 #endif store_char(c, &rx_buffer); } #elif defined(USBCON) #warning No interrupt handler for usart 0 #warning Serial(0) is on USB interface #else #error No interrupt handler for usart 0 #endif //#if defined(SIG_USART1_RECV) #if defined(USART1_RX_vect) //SIGNAL(SIG_USART1_RECV) SIGNAL(USART1_RX_vect) { unsigned char c = UDR1; store_char(c, &rx_buffer1); } #elif defined(SIG_USART1_RECV) #error SIG_USART1_RECV #endif #if defined(USART2_RX_vect) && defined(UDR2) SIGNAL(USART2_RX_vect) { unsigned char c = UDR2; store_char(c, &rx_buffer2); } #elif defined(SIG_USART2_RECV) #error SIG_USART2_RECV #endif #if defined(USART3_RX_vect) && defined(UDR3) SIGNAL(USART3_RX_vect) { unsigned char c = UDR3; store_char(c, &rx_buffer3); } #elif defined(SIG_USART3_RECV) #error SIG_USART3_RECV #endif // Constructors //////////////////////////////////////////////////////////////// HardwareSerial::HardwareSerial(ring_buffer *rx_buffer, volatile uint8_t *ubrrh, volatile uint8_t *ubrrl, volatile uint8_t *ucsra, volatile uint8_t *ucsrb, volatile uint8_t *udr, uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udre, uint8_t u2x) { _rx_buffer = rx_buffer; _ubrrh = ubrrh; _ubrrl = ubrrl; _ucsra = ucsra; _ucsrb = ucsrb; _udr = udr; _rxen = rxen; _txen = txen; _rxcie = rxcie; _udre = udre; _u2x = u2x; } // Public Methods ////////////////////////////////////////////////////////////// void HardwareSerial::begin(unsigned long baud) { uint16_t baud_setting; bool use_u2x = true; #if F_CPU == 16000000UL // hardcoded exception for compatibility with the bootloader shipped // with the Duemilanove and previous boards and the firmware on the 8U2 // on the Uno and Mega 2560. if (baud == 57600) { use_u2x = false; } #endif if (use_u2x) { *_ucsra = 1 << _u2x; baud_setting = (F_CPU / 4 / baud - 1) / 2; } else { *_ucsra = 0; baud_setting = (F_CPU / 8 / baud - 1) / 2; } // assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register) *_ubrrh = baud_setting >> 8; *_ubrrl = baud_setting; sbi(*_ucsrb, _rxen); sbi(*_ucsrb, _txen); sbi(*_ucsrb, _rxcie); } void HardwareSerial::end() { cbi(*_ucsrb, _rxen); cbi(*_ucsrb, _txen); cbi(*_ucsrb, _rxcie); } int HardwareSerial::available(void) { return (unsigned int)(RX_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % RX_BUFFER_SIZE; } int HardwareSerial::peek(void) { if (_rx_buffer->head == _rx_buffer->tail) { return -1; } else { return _rx_buffer->buffer[_rx_buffer->tail]; } } int HardwareSerial::read(void) { // if the head isn't ahead of the tail, we don't have any characters if (_rx_buffer->head == _rx_buffer->tail) { return -1; } else { unsigned char c = _rx_buffer->buffer[_rx_buffer->tail]; _rx_buffer->tail = (unsigned int)(_rx_buffer->tail + 1) % RX_BUFFER_SIZE; return c; } } void HardwareSerial::flush() { // don't reverse this or there may be problems if the RX interrupt // occurs after reading the value of rx_buffer_head but before writing // the value to rx_buffer_tail; the previous value of rx_buffer_head // may be written to rx_buffer_tail, making it appear as if the buffer // don't reverse this or there may be problems if the RX interrupt // occurs after reading the value of rx_buffer_head but before writing // the value to rx_buffer_tail; the previous value of rx_buffer_head // may be written to rx_buffer_tail, making it appear as if the buffer // were full, not empty. _rx_buffer->head = _rx_buffer->tail; } void HardwareSerial::write(uint8_t c) { while (!((*_ucsra) & (1 << _udre))) ; *_udr = c; } // Preinstantiate Objects ////////////////////////////////////////////////////// #if defined(UBRRH) && defined(UBRRL) HardwareSerial Serial(&rx_buffer, &UBRRH, &UBRRL, &UCSRA, &UCSRB, &UDR, RXEN, TXEN, RXCIE, UDRE, U2X); #elif defined(UBRR0H) && defined(UBRR0L) HardwareSerial Serial(&rx_buffer, &UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UDR0, RXEN0, TXEN0, RXCIE0, UDRE0, U2X0); #elif defined(USBCON) #warning no serial port defined (port 0) #else #error no serial port defined (port 0) #endif #if defined(UBRR1H) HardwareSerial Serial1(&rx_buffer1, &UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UDR1, RXEN1, TXEN1, RXCIE1, UDRE1, U2X1); #endif #if defined(UBRR2H) HardwareSerial Serial2(&rx_buffer2, &UBRR2H, &UBRR2L, &UCSR2A, &UCSR2B, &UDR2, RXEN2, TXEN2, RXCIE2, UDRE2, U2X2); #endif #if defined(UBRR3H) HardwareSerial Serial3(&rx_buffer3, &UBRR3H, &UBRR3L, &UCSR3A, &UCSR3B, &UDR3, RXEN3, TXEN3, RXCIE3, UDRE3, U2X3); #endif #endif // whole file <commit_msg>Fixing 300 baud communication for serial.<commit_after>/* HardwareSerial.cpp - Hardware serial library for Wiring Copyright (c) 2006 Nicholas Zambetti. All right 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. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified 23 November 2006 by David A. Mellis Modified 28 September 2010 by Mark Sproul */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <inttypes.h> #include "wiring.h" #include "wiring_private.h" // this next line disables the entire HardwareSerial.cpp, // this is so I can support Attiny series and any other chip without a uart #if defined(UBRRH) || defined(UBRR0H) || defined(UBRR1H) || defined(UBRR2H) || defined(UBRR3H) #include "HardwareSerial.h" // Define constants and variables for buffering incoming serial data. We're // using a ring buffer (I think), in which rx_buffer_head is the index of the // location to which to write the next incoming character and rx_buffer_tail // is the index of the location from which to read. #if (RAMEND < 1000) #define RX_BUFFER_SIZE 32 #else #define RX_BUFFER_SIZE 128 #endif struct ring_buffer { unsigned char buffer[RX_BUFFER_SIZE]; int head; int tail; }; #if defined(UBRRH) || defined(UBRR0H) ring_buffer rx_buffer = { { 0 }, 0, 0 }; #endif #if defined(UBRR1H) ring_buffer rx_buffer1 = { { 0 }, 0, 0 }; #endif #if defined(UBRR2H) ring_buffer rx_buffer2 = { { 0 }, 0, 0 }; #endif #if defined(UBRR3H) ring_buffer rx_buffer3 = { { 0 }, 0, 0 }; #endif inline void store_char(unsigned char c, ring_buffer *rx_buffer) { int i = (unsigned int)(rx_buffer->head + 1) % RX_BUFFER_SIZE; // if we should be storing the received character into the location // just before the tail (meaning that the head would advance to the // current location of the tail), we're about to overflow the buffer // and so we don't write the character or advance the head. if (i != rx_buffer->tail) { rx_buffer->buffer[rx_buffer->head] = c; rx_buffer->head = i; } } #if defined(USART_RX_vect) SIGNAL(USART_RX_vect) { #if defined(UDR0) unsigned char c = UDR0; #elif defined(UDR) unsigned char c = UDR; // atmega8535 #else #error UDR not defined #endif store_char(c, &rx_buffer); } #elif defined(SIG_USART0_RECV) && defined(UDR0) SIGNAL(SIG_USART0_RECV) { unsigned char c = UDR0; store_char(c, &rx_buffer); } #elif defined(SIG_UART0_RECV) && defined(UDR0) SIGNAL(SIG_UART0_RECV) { unsigned char c = UDR0; store_char(c, &rx_buffer); } //#elif defined(SIG_USART_RECV) #elif defined(USART0_RX_vect) // fixed by Mark Sproul this is on the 644/644p //SIGNAL(SIG_USART_RECV) SIGNAL(USART0_RX_vect) { #if defined(UDR0) unsigned char c = UDR0; #elif defined(UDR) unsigned char c = UDR; // atmega8, atmega32 #else #error UDR not defined #endif store_char(c, &rx_buffer); } #elif defined(SIG_UART_RECV) // this is for atmega8 SIGNAL(SIG_UART_RECV) { #if defined(UDR0) unsigned char c = UDR0; // atmega645 #elif defined(UDR) unsigned char c = UDR; // atmega8 #endif store_char(c, &rx_buffer); } #elif defined(USBCON) #warning No interrupt handler for usart 0 #warning Serial(0) is on USB interface #else #error No interrupt handler for usart 0 #endif //#if defined(SIG_USART1_RECV) #if defined(USART1_RX_vect) //SIGNAL(SIG_USART1_RECV) SIGNAL(USART1_RX_vect) { unsigned char c = UDR1; store_char(c, &rx_buffer1); } #elif defined(SIG_USART1_RECV) #error SIG_USART1_RECV #endif #if defined(USART2_RX_vect) && defined(UDR2) SIGNAL(USART2_RX_vect) { unsigned char c = UDR2; store_char(c, &rx_buffer2); } #elif defined(SIG_USART2_RECV) #error SIG_USART2_RECV #endif #if defined(USART3_RX_vect) && defined(UDR3) SIGNAL(USART3_RX_vect) { unsigned char c = UDR3; store_char(c, &rx_buffer3); } #elif defined(SIG_USART3_RECV) #error SIG_USART3_RECV #endif // Constructors //////////////////////////////////////////////////////////////// HardwareSerial::HardwareSerial(ring_buffer *rx_buffer, volatile uint8_t *ubrrh, volatile uint8_t *ubrrl, volatile uint8_t *ucsra, volatile uint8_t *ucsrb, volatile uint8_t *udr, uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udre, uint8_t u2x) { _rx_buffer = rx_buffer; _ubrrh = ubrrh; _ubrrl = ubrrl; _ucsra = ucsra; _ucsrb = ucsrb; _udr = udr; _rxen = rxen; _txen = txen; _rxcie = rxcie; _udre = udre; _u2x = u2x; } // Public Methods ////////////////////////////////////////////////////////////// void HardwareSerial::begin(unsigned long baud) { uint16_t baud_setting; bool use_u2x = true; #if F_CPU == 16000000UL // hardcoded exception for compatibility with the bootloader shipped // with the Duemilanove and previous boards and the firmware on the 8U2 // on the Uno and Mega 2560. if (baud == 57600) { use_u2x = false; } #endif try_again: if (use_u2x) { *_ucsra = 1 << _u2x; baud_setting = (F_CPU / 4 / baud - 1) / 2; } else { *_ucsra = 0; baud_setting = (F_CPU / 8 / baud - 1) / 2; } if ((baud_setting > 4095) && use_u2x) { use_u2x = false; goto try_again; } // assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register) *_ubrrh = baud_setting >> 8; *_ubrrl = baud_setting; sbi(*_ucsrb, _rxen); sbi(*_ucsrb, _txen); sbi(*_ucsrb, _rxcie); } void HardwareSerial::end() { cbi(*_ucsrb, _rxen); cbi(*_ucsrb, _txen); cbi(*_ucsrb, _rxcie); } int HardwareSerial::available(void) { return (unsigned int)(RX_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % RX_BUFFER_SIZE; } int HardwareSerial::peek(void) { if (_rx_buffer->head == _rx_buffer->tail) { return -1; } else { return _rx_buffer->buffer[_rx_buffer->tail]; } } int HardwareSerial::read(void) { // if the head isn't ahead of the tail, we don't have any characters if (_rx_buffer->head == _rx_buffer->tail) { return -1; } else { unsigned char c = _rx_buffer->buffer[_rx_buffer->tail]; _rx_buffer->tail = (unsigned int)(_rx_buffer->tail + 1) % RX_BUFFER_SIZE; return c; } } void HardwareSerial::flush() { // don't reverse this or there may be problems if the RX interrupt // occurs after reading the value of rx_buffer_head but before writing // the value to rx_buffer_tail; the previous value of rx_buffer_head // may be written to rx_buffer_tail, making it appear as if the buffer // don't reverse this or there may be problems if the RX interrupt // occurs after reading the value of rx_buffer_head but before writing // the value to rx_buffer_tail; the previous value of rx_buffer_head // may be written to rx_buffer_tail, making it appear as if the buffer // were full, not empty. _rx_buffer->head = _rx_buffer->tail; } void HardwareSerial::write(uint8_t c) { while (!((*_ucsra) & (1 << _udre))) ; *_udr = c; } // Preinstantiate Objects ////////////////////////////////////////////////////// #if defined(UBRRH) && defined(UBRRL) HardwareSerial Serial(&rx_buffer, &UBRRH, &UBRRL, &UCSRA, &UCSRB, &UDR, RXEN, TXEN, RXCIE, UDRE, U2X); #elif defined(UBRR0H) && defined(UBRR0L) HardwareSerial Serial(&rx_buffer, &UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UDR0, RXEN0, TXEN0, RXCIE0, UDRE0, U2X0); #elif defined(USBCON) #warning no serial port defined (port 0) #else #error no serial port defined (port 0) #endif #if defined(UBRR1H) HardwareSerial Serial1(&rx_buffer1, &UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UDR1, RXEN1, TXEN1, RXCIE1, UDRE1, U2X1); #endif #if defined(UBRR2H) HardwareSerial Serial2(&rx_buffer2, &UBRR2H, &UBRR2L, &UCSR2A, &UCSR2B, &UDR2, RXEN2, TXEN2, RXCIE2, UDRE2, U2X2); #endif #if defined(UBRR3H) HardwareSerial Serial3(&rx_buffer3, &UBRR3H, &UBRR3L, &UCSR3A, &UCSR3B, &UDR3, RXEN3, TXEN3, RXCIE3, UDRE3, U2X3); #endif #endif // whole file <|endoftext|>
<commit_before>#include <cassert> #include <iostream> #include <map> #include <random> #include <GLFW/glfw3.h> #include <glbinding/Binding.h> #include <glbinding/callbacks.h> #include <glbinding/gl/gl.h> #include <globjects/globjects.h> #include <glm/gtc/matrix_transform.hpp> #include <openll/GlyphRenderer.h> #include <openll/FontLoader.h> #include <openll/Typesetter.h> #include <openll/stages/GlyphPreparationStage.h> #include <openll/FontFace.h> #include <openll/GlyphSequence.h> #include <openll/Alignment.h> #include <openll/LineAnchor.h> #include <openll/SuperSampling.h> #include <openll/layout/layoutbase.h> #include <openll/layout/algorithm.h> #include <cpplocate/cpplocate.h> #include <cpplocate/ModuleInfo.h> #include "PointDrawable.h" #include "RectangleDrawable.h" #include "benchmark.h" using namespace gl; glm::uvec2 g_viewport{640, 480}; bool g_config_changed = true; size_t g_algorithmID = 0; bool g_frames_visible = true; long int g_seed = 0; int g_numLabels = 64; struct Algorithm { std::string name; std::function<void(std::vector<gloperate_text::Label>&)> function; }; using namespace std::placeholders; std::vector<Algorithm> layoutAlgorithms { {"constant", gloperate_text::layout::constant}, {"random", gloperate_text::layout::random}, {"greedy with area", std::bind(gloperate_text::layout::greedy, _1, gloperate_text::layout::overlapArea)}, {"discreteGradientDescent with area", std::bind(gloperate_text::layout::discreteGradientDescent, _1, gloperate_text::layout::overlapArea)}, {"simulatedAnnealing with area", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::overlapArea, false, glm::vec2(0.f))}, {"simulatedAnnealing", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::standard, false, glm::vec2(0.f))}, {"simulatedAnnealing with padding", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::standard, false, glm::vec2(0.2f))}, {"simulatedAnnealing with selection", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::standard, true, glm::vec2(0.f))}, {"simulatedAnnealing (everything)", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::standard, true, glm::vec2(0.2f))}, }; void onResize(GLFWwindow*, int width, int height) { g_viewport = {width, height}; g_config_changed = true; } void onKeyPress(GLFWwindow * window, int key, int, int action, int mods) { if (key == 'Q' && action == GLFW_PRESS && mods == GLFW_MOD_CONTROL) { glfwSetWindowShouldClose(window, 1); } else if (key == 'F' && action == GLFW_PRESS) { g_frames_visible = !g_frames_visible; } else if (key == 'R' && action == GLFW_PRESS) { g_seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); g_config_changed = true; } else if (key == '-' && action == GLFW_PRESS) { g_numLabels = std::max(g_numLabels - 8, 8); g_config_changed = true; } else if ((key == '+' || key == '=') && action == GLFW_PRESS) { g_numLabels = std::min(g_numLabels + 8, 1024); g_config_changed = true; } else if ('1' <= key && key <= '9' && action == GLFW_PRESS) { g_algorithmID = std::min(static_cast<size_t>(key - '1'), layoutAlgorithms.size() - 1); g_config_changed = true; } } void glInitialize() { glbinding::Binding::initialize(false); glbinding::setCallbackMaskExcept( glbinding::CallbackMask::After | glbinding::CallbackMask::Parameters, {"glGetError"}); glbinding::setAfterCallback([](const glbinding::FunctionCall& call) { const auto error = glGetError(); if (error != GL_NO_ERROR) { std::cout << error << " in " << call.function->name() << " with parameters:" << std::endl; for (const auto& parameter : call.parameters) { std::cout << " " << parameter->asString() << std::endl; } } }); globjects::init(); std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl; } std::string random_name(std::default_random_engine engine) { std::uniform_int_distribution<int> charDistribution(32, 126); std::uniform_int_distribution<int> lengthDistribution(3, 15); const auto length = lengthDistribution(engine); std::vector<char> characters; for (int i = 0; i < length; ++i) { characters.push_back(static_cast<char>(charDistribution(engine))); } return {characters.begin(), characters.end()}; } std::vector<gloperate_text::Label> prepareLabels(gloperate_text::FontFace * font, glm::uvec2 viewport) { std::vector<gloperate_text::Label> labels; std::default_random_engine generator; generator.seed(g_seed); std::uniform_real_distribution<float> distribution(-1.f, 1.f); std::uniform_int_distribution<unsigned int> priorityDistribution(1, 10); for (int i = 0; i < g_numLabels; ++i) { const auto string = random_name(generator); const auto priority = priorityDistribution(generator); gloperate_text::GlyphSequence sequence; std::u32string unicode_string(string.begin(), string.end()); sequence.setString(unicode_string); sequence.setWordWrap(true); sequence.setLineWidth(400.f); sequence.setAlignment(gloperate_text::Alignment::LeftAligned); sequence.setLineAnchor(gloperate_text::LineAnchor::Ascent); sequence.setFontSize(10.f + priority); sequence.setFontFace(font); sequence.setFontColor(glm::vec4(glm::vec3(0.5f - priority * 0.05f), 1.f)); sequence.setSuperSampling(gloperate_text::SuperSampling::Quincunx); const auto origin = glm::vec2{distribution(generator), distribution(generator)}; // compute transform matrix glm::mat4 transform; transform = glm::translate(transform, glm::vec3(origin, 0.f)); transform = glm::scale(transform, glm::vec3(1.f, static_cast<float>(viewport.x) / viewport.y, 1.f)); transform = glm::scale(transform, glm::vec3(1 / 300.f)); const auto placement = gloperate_text::LabelPlacement{ glm::vec2{ 0.f, 0.f } , gloperate_text::Alignment::LeftAligned, gloperate_text::LineAnchor::Baseline, true }; sequence.setAdditionalTransform(transform); labels.push_back({sequence, origin, priority, placement}); } return labels; } gloperate_text::GlyphVertexCloud prepareCloud(const std::vector<gloperate_text::Label> & labels) { std::vector<gloperate_text::GlyphSequence> sequences; for (const auto & label : labels) { if (label.placement.display) { sequences.push_back(gloperate_text::applyPlacement(label)); } } return gloperate_text::prepareGlyphs(sequences, true); } void preparePointDrawable(const std::vector<gloperate_text::Label> & labels, PointDrawable& pointDrawable) { std::vector<Point> points; for (const auto & label : labels) { points.push_back({ label.pointLocation, label.placement.display ? glm::vec3(.7f, .0f, .0f) : glm::vec3(.5f, .5f, .5f), (label.placement.display ? 4.f : 2.f) * g_viewport.x / 640 }); } pointDrawable.initialize(points); } void prepareRectangleDrawable(const std::vector<gloperate_text::Label> & labels, RectangleDrawable& rectangleDrawable) { std::vector<glm::vec2> rectangles; for (const auto & label : labels) { auto sequence = gloperate_text::applyPlacement(label); auto extent = gloperate_text::Typesetter::rectangle(sequence, glm::vec3(label.pointLocation, 0.f)); rectangles.push_back(extent.first); rectangles.push_back(extent.first + extent.second); } rectangleDrawable.initialize(rectangles); } void runAndBenchmark(std::vector<gloperate_text::Label> & labels, Algorithm algorithm) { auto start = std::chrono::steady_clock::now(); algorithm.function(labels); auto end = std::chrono::steady_clock::now(); std::chrono::duration<double> diff = end - start; auto positions = labelPositionDesirability(labels); std::cout << "Evaluation results for " << algorithm.name << ":" << std::endl << "Runtime: " << diff.count() << "s" << std::endl << "Labels hidden: " << labelsHidden(labels) << "/" << labels.size() << std::endl << "Overlaps: " << labelOverlaps(labels) << std::endl << "Overlap area: " << labelOverlapArea(labels) << std::endl << "Padding Violations: " << labelOverlaps(labels, {0.2f, 0.2f}) << std::endl << "Padding Overlap: " << labelOverlapArea(labels, {0.2f, 0.2f}) << std::endl << "Relative label positions:" << std::endl << " Upper Right: " << positions[gloperate_text::RelativeLabelPosition::UpperRight] << std::endl << " Upper Left: " << positions[gloperate_text::RelativeLabelPosition::UpperLeft] << std::endl << " Lower Left: " << positions[gloperate_text::RelativeLabelPosition::LowerLeft] << std::endl << " Lower Right: " << positions[gloperate_text::RelativeLabelPosition::LowerRight] << std::endl; std::cout << std::endl; } int main() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); auto window = glfwCreateWindow(g_viewport.x, g_viewport.y, "Text-Demo", 0, nullptr); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glInitialize(); glfwSetWindowSizeCallback(window, onResize); glfwSetKeyCallback(window, onKeyPress); cpplocate::ModuleInfo moduleInfo = cpplocate::findModule("openll"); std::string dataPath = moduleInfo.value("dataPath"); gloperate_text::FontLoader loader; auto font = loader.load(dataPath + "/fonts/opensansr36/opensansr36.fnt"); gloperate_text::GlyphRenderer renderer; gloperate_text::GlyphVertexCloud cloud; std::vector<gloperate_text::Label> labels; PointDrawable pointDrawable {dataPath}; RectangleDrawable rectangleDrawable {dataPath}; glClearColor(1.f, 1.f, 1.f, 1.f); while (!glfwWindowShouldClose(window)) { if (g_config_changed) { glViewport(0, 0, g_viewport.x, g_viewport.y); labels = prepareLabels(font, g_viewport); runAndBenchmark(labels, layoutAlgorithms[g_algorithmID]); cloud = prepareCloud(labels); preparePointDrawable(labels, pointDrawable); prepareRectangleDrawable(labels, rectangleDrawable); } gl::glClear(gl::GL_COLOR_BUFFER_BIT | gl::GL_DEPTH_BUFFER_BIT); gl::glDepthMask(gl::GL_FALSE); gl::glEnable(gl::GL_CULL_FACE); gl::glEnable(gl::GL_BLEND); gl::glBlendFunc(gl::GL_SRC_ALPHA, gl::GL_ONE_MINUS_SRC_ALPHA); renderer.render(cloud); pointDrawable.render(); if (g_frames_visible) rectangleDrawable.render(); gl::glDepthMask(gl::GL_TRUE); gl::glDisable(gl::GL_CULL_FACE); gl::glDisable(gl::GL_BLEND); g_config_changed = false; glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); } <commit_msg>Improve layout example<commit_after>#include <cassert> #include <iostream> #include <map> #include <random> #include <GLFW/glfw3.h> #include <glbinding/Binding.h> #include <glbinding/callbacks.h> #include <glbinding/gl/gl.h> #include <globjects/globjects.h> #include <glm/gtc/matrix_transform.hpp> #include <openll/GlyphRenderer.h> #include <openll/FontLoader.h> #include <openll/Typesetter.h> #include <openll/stages/GlyphPreparationStage.h> #include <openll/FontFace.h> #include <openll/GlyphSequence.h> #include <openll/Alignment.h> #include <openll/LineAnchor.h> #include <openll/SuperSampling.h> #include <openll/layout/layoutbase.h> #include <openll/layout/algorithm.h> #include <cpplocate/cpplocate.h> #include <cpplocate/ModuleInfo.h> #include "PointDrawable.h" #include "RectangleDrawable.h" #include "benchmark.h" using namespace gl; glm::uvec2 g_viewport{640, 480}; bool g_config_changed = true; size_t g_algorithmID = 0; bool g_frames_visible = true; long int g_seed = 0; int g_numLabels = 64; struct Algorithm { std::string name; std::function<void(std::vector<gloperate_text::Label>&)> function; }; using namespace std::placeholders; std::vector<Algorithm> layoutAlgorithms { {"Constant", gloperate_text::layout::constant}, {"Random", gloperate_text::layout::random}, {"Greedy", std::bind(gloperate_text::layout::greedy, _1, gloperate_text::layout::standard)}, {"Discrete Gradient Descent with area", std::bind(gloperate_text::layout::discreteGradientDescent, _1, gloperate_text::layout::standard)}, {"Simulated Annealing", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::standard, false, glm::vec2(0.f))}, {"Simulated Annealing with padding", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::standard, false, glm::vec2(0.2f))}, {"Simulated Annealing with selection", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::standard, true, glm::vec2(0.f))}, {"Simulated Annealing (padding, selection)", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::standard, true, glm::vec2(0.2f))}, }; void onResize(GLFWwindow*, int width, int height) { g_viewport = {width, height}; g_config_changed = true; } void onKeyPress(GLFWwindow * window, int key, int, int action, int mods) { if (key == 'Q' && action == GLFW_PRESS && mods == GLFW_MOD_CONTROL) { glfwSetWindowShouldClose(window, 1); } else if (key == 'F' && action == GLFW_PRESS) { g_frames_visible = !g_frames_visible; } else if (key == 'R' && action == GLFW_PRESS) { g_seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); g_config_changed = true; } else if (key == '-' && action == GLFW_PRESS) { g_numLabels = std::max(g_numLabels - 8, 8); g_config_changed = true; } else if ((key == '+' || key == '=') && action == GLFW_PRESS) { g_numLabels = std::min(g_numLabels + 8, 1024); g_config_changed = true; } else if ('1' <= key && key <= '9' && action == GLFW_PRESS) { g_algorithmID = std::min(static_cast<size_t>(key - '1'), layoutAlgorithms.size() - 1); g_config_changed = true; } } void glInitialize() { glbinding::Binding::initialize(false); glbinding::setCallbackMaskExcept( glbinding::CallbackMask::After | glbinding::CallbackMask::Parameters, {"glGetError"}); glbinding::setAfterCallback([](const glbinding::FunctionCall& call) { const auto error = glGetError(); if (error != GL_NO_ERROR) { std::cout << error << " in " << call.function->name() << " with parameters:" << std::endl; for (const auto& parameter : call.parameters) { std::cout << " " << parameter->asString() << std::endl; } } }); globjects::init(); std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl; } std::string random_name(std::default_random_engine engine) { std::uniform_int_distribution<int> upperDistribution(65, 90); std::uniform_int_distribution<int> lowerDistribution(97, 122); std::uniform_int_distribution<int> lengthDistribution(3, 14); const auto length = lengthDistribution(engine); std::vector<char> characters; characters.push_back(static_cast<char>(upperDistribution(engine))); for (int i = 0; i < length; ++i) { characters.push_back(static_cast<char>(lowerDistribution(engine))); } return {characters.begin(), characters.end()}; } std::vector<gloperate_text::Label> prepareLabels(gloperate_text::FontFace * font, glm::uvec2 viewport) { std::vector<gloperate_text::Label> labels; std::default_random_engine generator; generator.seed(g_seed); std::uniform_real_distribution<float> y_distribution(-.8f, .6f); std::uniform_real_distribution<float> x_distribution(-.8f, .8f); std::uniform_int_distribution<unsigned int> priorityDistribution(1, 10); for (int i = 0; i < g_numLabels; ++i) { const auto string = random_name(generator); const std::u32string unicode_string {string.begin(), string.end()}; const auto priority = priorityDistribution(generator); const auto origin = glm::vec2{x_distribution(generator), y_distribution(generator)}; gloperate_text::GlyphSequence sequence; sequence.setString(unicode_string); sequence.setWordWrap(true); sequence.setLineWidth(400.f); sequence.setAlignment(gloperate_text::Alignment::LeftAligned); sequence.setLineAnchor(gloperate_text::LineAnchor::Ascent); sequence.setFontSize(10.f + priority); sequence.setFontFace(font); sequence.setFontColor(glm::vec4(glm::vec3(0.5f - priority * 0.05f), 1.f)); sequence.setSuperSampling(gloperate_text::SuperSampling::Quincunx); // compute transform matrix glm::mat4 transform; transform = glm::translate(transform, glm::vec3(origin, 0.f)); transform = glm::scale(transform, glm::vec3(1.f, static_cast<float>(viewport.x) / viewport.y, 1.f)); transform = glm::scale(transform, glm::vec3(1 / 300.f)); const auto placement = gloperate_text::LabelPlacement{ glm::vec2{ 0.f, 0.f } , gloperate_text::Alignment::LeftAligned, gloperate_text::LineAnchor::Baseline, true }; sequence.setAdditionalTransform(transform); labels.push_back({sequence, origin, priority, placement}); } return labels; } gloperate_text::GlyphSequence prepareHeadline(gloperate_text::FontFace * font, glm::uvec2 viewport, const std::string & name) { const std::u32string unicode_string {name.begin(), name.end()}; const auto origin = glm::vec2{-0.9f, 0.75f}; gloperate_text::GlyphSequence sequence; sequence.setString(unicode_string); sequence.setWordWrap(false); sequence.setLineWidth(800.f); sequence.setAlignment(gloperate_text::Alignment::LeftAligned); sequence.setLineAnchor(gloperate_text::LineAnchor::Descent); sequence.setFontSize(30.f); sequence.setFontFace(font); sequence.setFontColor(glm::vec4(0.4f, 0.4f, 1.0f, 1.f)); // compute transform matrix glm::mat4 transform; transform = glm::translate(transform, glm::vec3(origin, 0.f)); transform = glm::scale(transform, glm::vec3(1.f, static_cast<float>(viewport.x) / viewport.y, 1.f)); transform = glm::scale(transform, glm::vec3(1 / 300.f)); sequence.setAdditionalTransform(transform); return sequence; } std::vector<gloperate_text::GlyphSequence> getSequences(const std::vector<gloperate_text::Label> & labels) { std::vector<gloperate_text::GlyphSequence> sequences; for (const auto & label : labels) { if (label.placement.display) { sequences.push_back(gloperate_text::applyPlacement(label)); } } return sequences; } void preparePointDrawable(const std::vector<gloperate_text::Label> & labels, PointDrawable& pointDrawable) { std::vector<Point> points; for (const auto & label : labels) { points.push_back({ label.pointLocation, label.placement.display ? glm::vec3(.7f, .0f, .0f) : glm::vec3(.5f, .5f, .5f), (label.placement.display ? 4.f : 2.f) * g_viewport.x / 640 }); } pointDrawable.initialize(points); } void prepareRectangleDrawable(const std::vector<gloperate_text::Label> & labels, RectangleDrawable& rectangleDrawable) { std::vector<glm::vec2> rectangles; for (const auto & label : labels) { auto sequence = gloperate_text::applyPlacement(label); auto extent = gloperate_text::Typesetter::rectangle(sequence, glm::vec3(label.pointLocation, 0.f)); rectangles.push_back(extent.first); rectangles.push_back(extent.first + extent.second); } rectangleDrawable.initialize(rectangles); } void runAndBenchmark(std::vector<gloperate_text::Label> & labels, Algorithm algorithm) { auto start = std::chrono::steady_clock::now(); algorithm.function(labels); auto end = std::chrono::steady_clock::now(); std::chrono::duration<double> diff = end - start; auto positions = labelPositionDesirability(labels); std::cout << "Evaluation results for " << algorithm.name << ":" << std::endl << "Runtime: " << diff.count() << "s" << std::endl << "Labels hidden: " << labelsHidden(labels) << "/" << labels.size() << std::endl << "Overlaps: " << labelOverlaps(labels) << std::endl << "Overlap area: " << labelOverlapArea(labels) << std::endl << "Padding Violations: " << labelOverlaps(labels, {0.2f, 0.2f}) << std::endl << "Padding Overlap: " << labelOverlapArea(labels, {0.2f, 0.2f}) << std::endl << "Relative label positions:" << std::endl << " Upper Right: " << positions[gloperate_text::RelativeLabelPosition::UpperRight] << std::endl << " Upper Left: " << positions[gloperate_text::RelativeLabelPosition::UpperLeft] << std::endl << " Lower Left: " << positions[gloperate_text::RelativeLabelPosition::LowerLeft] << std::endl << " Lower Right: " << positions[gloperate_text::RelativeLabelPosition::LowerRight] << std::endl; std::cout << std::endl; } int main() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); auto window = glfwCreateWindow(g_viewport.x, g_viewport.y, "Text-Demo", 0, nullptr); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glInitialize(); glfwSetWindowSizeCallback(window, onResize); glfwSetKeyCallback(window, onKeyPress); cpplocate::ModuleInfo moduleInfo = cpplocate::findModule("openll"); std::string dataPath = moduleInfo.value("dataPath"); gloperate_text::FontLoader loader; const auto font = loader.load(dataPath + "/fonts/opensansr36/opensansr36.fnt"); gloperate_text::GlyphRenderer renderer; gloperate_text::GlyphVertexCloud cloud; std::vector<gloperate_text::Label> labels; PointDrawable pointDrawable {dataPath}; RectangleDrawable rectangleDrawable {dataPath}; glClearColor(1.f, 1.f, 1.f, 1.f); while (!glfwWindowShouldClose(window)) { if (g_config_changed) { glViewport(0, 0, g_viewport.x, g_viewport.y); labels = prepareLabels(font, g_viewport); runAndBenchmark(labels, layoutAlgorithms[g_algorithmID]); auto sequences = getSequences(labels); sequences.push_back(prepareHeadline(font, g_viewport, layoutAlgorithms[g_algorithmID].name)); cloud = gloperate_text::prepareGlyphs(sequences, true); preparePointDrawable(labels, pointDrawable); prepareRectangleDrawable(labels, rectangleDrawable); } gl::glClear(gl::GL_COLOR_BUFFER_BIT | gl::GL_DEPTH_BUFFER_BIT); gl::glDepthMask(gl::GL_FALSE); gl::glEnable(gl::GL_CULL_FACE); gl::glEnable(gl::GL_BLEND); gl::glBlendFunc(gl::GL_SRC_ALPHA, gl::GL_ONE_MINUS_SRC_ALPHA); renderer.render(cloud); pointDrawable.render(); if (g_frames_visible) rectangleDrawable.render(); gl::glDepthMask(gl::GL_TRUE); gl::glDisable(gl::GL_CULL_FACE); gl::glDisable(gl::GL_BLEND); g_config_changed = false; glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); } <|endoftext|>
<commit_before>#include "fileoperations/coperationperformer.h" #include "cfolderenumeratorrecursive.h" #include "ctestfoldergenerator.h" #include "container/set_operations.hpp" #include "system/processfilepath.hpp" #include "system/ctimeelapsed.h" #include "filecomparator/cfilecomparator.h" // test_utils #include "foldercomparator.h" #include "qt_helpers.hpp" #include "catch2_utils.hpp" DISABLE_COMPILER_WARNINGS #include <QDateTime> #include <QDir> #include <QStringBuilder> #include <QTemporaryDir> RESTORE_COMPILER_WARNINGS #include <algorithm> #include <iostream> #include <string> #define CATCH_CONFIG_RUNNER #include "../catch2/catch.hpp" static uint32_t g_randomSeed = 0; static constexpr QFileDevice::FileTime supportedFileTimeTypes[] { QFileDevice::FileAccessTime, #ifndef __linux__ QFileDevice::FileBirthTime, #endif #if !defined __linux__ && !defined _WIN32 QFileDevice::FileMetadataChangeTime, #endif QFileDevice::FileModificationTime, }; static bool timesAlmostMatch(const QDateTime& t1, const QDateTime& t2, const QFileDevice::FileTime type) { const auto diff = ::abs(t1.toMSecsSinceEpoch() - t2.toMSecsSinceEpoch()); int allowedTimeDiffMs = 0; switch (type) { // These margins are generally too long, but necessary for CI systems (sloooow cloud virtualized hardware) case QFileDevice::FileAccessTime: allowedTimeDiffMs = 3000; break; case QFileDevice::FileBirthTime: allowedTimeDiffMs = 100; break; case QFileDevice::FileMetadataChangeTime: allowedTimeDiffMs = 2500; break; case QFileDevice::FileModificationTime: allowedTimeDiffMs = 100; break; default: assert_and_return_unconditional_r("Unknown QFileDevice::FileTime", false); } #ifdef __APPLE__ static constexpr int multiplier = 10; #else static constexpr int multiplier = 1; #endif if (diff <= allowedTimeDiffMs * multiplier) return true; else { std::cerr << "Time mismatch for type " << type << ": diff = " << diff << ", allowed = " << allowedTimeDiffMs * multiplier << '\n'; return false; } } struct ProgressObserver final : public CFileOperationObserver { inline void onProgressChanged(float totalPercentage, size_t /*numFilesProcessed*/, size_t /*totalNumFiles*/, float filePercentage, uint64_t /*speed*/ /* B/s*/, uint32_t /*secondsRemaining*/) override { CHECK(totalPercentage <= 100.0f); CHECK(filePercentage <= 100.0f); } inline void onProcessHalted(HaltReason /*reason*/, CFileSystemObject /*source*/, CFileSystemObject /*dest*/, QString /*errorMessage*/) override { // User decision required (file exists, file is read-only etc.) FAIL("onProcessHalted called"); } inline void onProcessFinished(QString /*message*/ = QString()) override {} // Done or canceled inline void onCurrentFileChanged(QString /*file*/) override {} // Starting to process a new file }; TEST_CASE((std::string("Copy test #") + std::to_string((srand(time(nullptr)), rand()))).c_str(), "[operationperformer-copy]") { QTemporaryDir sourceDirectory(QDir::tempPath() + "/" + CURRENT_TEST_NAME.c_str() + "_SOURCE_XXXXXX"); QTemporaryDir targetDirectory(QDir::tempPath() + "/" + CURRENT_TEST_NAME.c_str() + "_TARGET_XXXXXX"); REQUIRE(sourceDirectory.isValid()); REQUIRE(targetDirectory.isValid()); TRACE_LOG << "Source: " << sourceDirectory.path(); TRACE_LOG << "Target: " << targetDirectory.path(); REQUIRE(QFileInfo::exists(sourceDirectory.path())); REQUIRE(CFileSystemObject(sourceDirectory.path()).isEmptyDir()); REQUIRE(QFileInfo::exists(targetDirectory.path())); REQUIRE(CFileSystemObject(targetDirectory.path()).isEmptyDir()); CTestFolderGenerator generator; generator.setSeed(g_randomSeed); TRACE_LOG << "std::random seed: " << g_randomSeed; REQUIRE(generator.generateRandomTree(sourceDirectory.path(), 1000, 200)); COperationPerformer p(operationCopy, CFileSystemObject(sourceDirectory.path()), targetDirectory.path()); CTimeElapsed timer(true); ProgressObserver progressObserver; p.setObserver(&progressObserver); p.start(); while (!p.done()) { progressObserver.processEvents(); #ifndef _DEBUG // Reasonable timeout if (timer.elapsed<std::chrono::seconds>() > 2 * 60) { FAIL("File operation timeout reached."); return; } #endif } std::vector<CFileSystemObject> sourceTree, destTree; CFolderEnumeratorRecursive::enumerateFolder(sourceDirectory.path(), sourceTree); CFolderEnumeratorRecursive::enumerateFolder(targetDirectory.path() % '/' % QFileInfo(sourceDirectory.path()).completeBaseName(), destTree); CFileComparator comparator; REQUIRE(sourceTree.size() == destTree.size()); for (size_t i = 0, n = sourceTree.size(); i < n; ++i) { const auto& sourceItem = sourceTree[i]; const auto& destItem = destTree[i]; if (!sourceItem.isFile()) continue; QFile fileA(sourceItem.fullAbsolutePath()); REQUIRE(fileA.open(QFile::ReadOnly)); QFile fileB(destItem.fullAbsolutePath()); REQUIRE(fileB.open(QFile::ReadOnly)); comparator.compareFiles(fileA, fileB, [](int) {}, [](const CFileComparator::ComparisonResult result) { CHECK(result == CFileComparator::Equal); }); for (const auto fileTimeType: supportedFileTimeTypes) { if (!timesAlmostMatch(fileA.fileTime(fileTimeType), fileB.fileTime(fileTimeType), fileTimeType)) FAIL_CHECK(); } } REQUIRE(compareFolderContents(sourceTree, destTree)); } TEST_CASE((std::string("Move test #") + std::to_string((srand(time(nullptr)), rand()))).c_str(), "[operationperformer-move]") { QTemporaryDir sourceDirectory(QDir::tempPath() + "/" + CURRENT_TEST_NAME.c_str() + "_SOURCE_XXXXXX"); QTemporaryDir targetDirectory(QDir::tempPath() + "/" + CURRENT_TEST_NAME.c_str() + "_TARGET_XXXXXX"); REQUIRE(sourceDirectory.isValid()); REQUIRE(targetDirectory.isValid()); TRACE_LOG << "Source: " << sourceDirectory.path(); TRACE_LOG << "Target: " << targetDirectory.path(); REQUIRE(QFileInfo::exists(sourceDirectory.path())); REQUIRE(CFileSystemObject(sourceDirectory.path()).isEmptyDir()); REQUIRE(QFileInfo::exists(targetDirectory.path())); REQUIRE(CFileSystemObject(targetDirectory.path()).isEmptyDir()); CTestFolderGenerator generator; generator.setSeed(g_randomSeed); TRACE_LOG << "std::random seed: " << g_randomSeed; REQUIRE(generator.generateRandomTree(sourceDirectory.path(), 1000, 200)); std::vector<CFileSystemObject> sourceTree; CFolderEnumeratorRecursive::enumerateFolder(sourceDirectory.path(), sourceTree); COperationPerformer p(operationMove, CFileSystemObject(sourceDirectory.path()), targetDirectory.path()); ProgressObserver progressObserver; p.setObserver(&progressObserver); CTimeElapsed timer(true); p.start(); while (!p.done()) { progressObserver.processEvents(); #ifndef _DEBUG // Reasonable timeout if (timer.elapsed<std::chrono::seconds>() > 2 * 60) { FAIL("File operation timeout reached."); return; } #endif } REQUIRE(!CFileSystemObject(sourceDirectory.path()).exists()); std::vector<CFileSystemObject> destTree; CFolderEnumeratorRecursive::enumerateFolder(targetDirectory.path() % '/' % QFileInfo(sourceDirectory.path()).completeBaseName(), destTree); REQUIRE(compareFolderContents(sourceTree, destTree)); } TEST_CASE((std::string("Delete test #") + std::to_string((srand(time(nullptr)), rand()))).c_str(), "[operationperformer-delete]") { QTemporaryDir sourceDirectory(QDir::tempPath() + "/" + CURRENT_TEST_NAME.c_str() + "_SOURCE_XXXXXX"); REQUIRE(sourceDirectory.isValid()); TRACE_LOG << "Source: " << sourceDirectory.path(); REQUIRE(QFileInfo::exists(sourceDirectory.path())); REQUIRE(CFileSystemObject(sourceDirectory.path()).isEmptyDir()); CTestFolderGenerator generator; generator.setSeed(g_randomSeed); TRACE_LOG << "std::random seed: " << g_randomSeed; REQUIRE(generator.generateRandomTree(sourceDirectory.path(), 1000, 200)); REQUIRE(!QDir(sourceDirectory.path()).entryList(QDir::NoDotAndDotDot | QDir::AllEntries).empty()); COperationPerformer p(operationDelete, CFileSystemObject(sourceDirectory.path())); ProgressObserver progressObserver; p.setObserver(&progressObserver); CTimeElapsed timer(true); p.start(); while (!p.done()) { progressObserver.processEvents(); #ifndef _DEBUG // Reasonable timeout if (timer.elapsed<std::chrono::seconds>() > 2 * 60) { FAIL("File operation timeout reached."); return; } #endif } REQUIRE(!CFileSystemObject(sourceDirectory.path()).exists()); } int main(int argc, char* argv[]) { Catch::Session session; // There must be exactly one instance // Build a new parser on top of Catch's using namespace Catch::clara; auto cli = session.cli() // Get Catch's composite command line parser | Opt(g_randomSeed, "std::random seed") // bind variable to a new option, with a hint string ["--std-seed"] // the option names it will respond to ("std::random seed"); // description string for the help output // Now pass the new composite back to Catch so it uses that session.cli(cli); // Let Catch (using Clara) parse the command line const int returnCode = session.applyCommandLine(argc, argv); if (returnCode != 0) // Indicates a command line error return returnCode; return session.run(); } <commit_msg>Failing tests on Mac in Github workflow fixed<commit_after>#include "fileoperations/coperationperformer.h" #include "cfolderenumeratorrecursive.h" #include "ctestfoldergenerator.h" #include "container/set_operations.hpp" #include "system/processfilepath.hpp" #include "system/ctimeelapsed.h" #include "filecomparator/cfilecomparator.h" // test_utils #include "foldercomparator.h" #include "qt_helpers.hpp" #include "catch2_utils.hpp" DISABLE_COMPILER_WARNINGS #include <QDateTime> #include <QDir> #include <QStringBuilder> #include <QTemporaryDir> RESTORE_COMPILER_WARNINGS #include <algorithm> #include <iostream> #include <string> #define CATCH_CONFIG_RUNNER #include "../catch2/catch.hpp" static uint32_t g_randomSeed = 0; static constexpr QFileDevice::FileTime supportedFileTimeTypes[] { QFileDevice::FileAccessTime, #ifndef __linux__ QFileDevice::FileBirthTime, #endif #if !defined __linux__ && !defined _WIN32 QFileDevice::FileMetadataChangeTime, #endif QFileDevice::FileModificationTime, }; static bool timesAlmostMatch(const QDateTime& t1, const QDateTime& t2, const QFileDevice::FileTime type) { const auto diff = ::abs(t1.toMSecsSinceEpoch() - t2.toMSecsSinceEpoch()); int allowedTimeDiffMs = 0; switch (type) { // These margins are generally too long, but necessary for CI systems (sloooow cloud virtualized hardware) case QFileDevice::FileAccessTime: allowedTimeDiffMs = 3000; break; case QFileDevice::FileBirthTime: allowedTimeDiffMs = 100; break; case QFileDevice::FileMetadataChangeTime: allowedTimeDiffMs = 2500; break; case QFileDevice::FileModificationTime: allowedTimeDiffMs = 100; break; default: assert_and_return_unconditional_r("Unknown QFileDevice::FileTime", false); } #ifdef __APPLE__ static constexpr int multiplier = 20; #else static constexpr int multiplier = 1; #endif if (diff <= allowedTimeDiffMs * multiplier) return true; else { std::cerr << "Time mismatch for type " << type << ": diff = " << diff << ", allowed = " << allowedTimeDiffMs * multiplier << '\n'; return false; } } struct ProgressObserver final : public CFileOperationObserver { inline void onProgressChanged(float totalPercentage, size_t /*numFilesProcessed*/, size_t /*totalNumFiles*/, float filePercentage, uint64_t /*speed*/ /* B/s*/, uint32_t /*secondsRemaining*/) override { CHECK(totalPercentage <= 100.0f); CHECK(filePercentage <= 100.0f); } inline void onProcessHalted(HaltReason /*reason*/, CFileSystemObject /*source*/, CFileSystemObject /*dest*/, QString /*errorMessage*/) override { // User decision required (file exists, file is read-only etc.) FAIL("onProcessHalted called"); } inline void onProcessFinished(QString /*message*/ = QString()) override {} // Done or canceled inline void onCurrentFileChanged(QString /*file*/) override {} // Starting to process a new file }; TEST_CASE((std::string("Copy test #") + std::to_string((srand(time(nullptr)), rand()))).c_str(), "[operationperformer-copy]") { QTemporaryDir sourceDirectory(QDir::tempPath() + "/" + CURRENT_TEST_NAME.c_str() + "_SOURCE_XXXXXX"); QTemporaryDir targetDirectory(QDir::tempPath() + "/" + CURRENT_TEST_NAME.c_str() + "_TARGET_XXXXXX"); REQUIRE(sourceDirectory.isValid()); REQUIRE(targetDirectory.isValid()); TRACE_LOG << "Source: " << sourceDirectory.path(); TRACE_LOG << "Target: " << targetDirectory.path(); REQUIRE(QFileInfo::exists(sourceDirectory.path())); REQUIRE(CFileSystemObject(sourceDirectory.path()).isEmptyDir()); REQUIRE(QFileInfo::exists(targetDirectory.path())); REQUIRE(CFileSystemObject(targetDirectory.path()).isEmptyDir()); CTestFolderGenerator generator; generator.setSeed(g_randomSeed); TRACE_LOG << "std::random seed: " << g_randomSeed; REQUIRE(generator.generateRandomTree(sourceDirectory.path(), 1000, 200)); COperationPerformer p(operationCopy, CFileSystemObject(sourceDirectory.path()), targetDirectory.path()); CTimeElapsed timer(true); ProgressObserver progressObserver; p.setObserver(&progressObserver); p.start(); while (!p.done()) { progressObserver.processEvents(); #ifndef _DEBUG // Reasonable timeout if (timer.elapsed<std::chrono::seconds>() > 2 * 60) { FAIL("File operation timeout reached."); return; } #endif } std::vector<CFileSystemObject> sourceTree, destTree; CFolderEnumeratorRecursive::enumerateFolder(sourceDirectory.path(), sourceTree); CFolderEnumeratorRecursive::enumerateFolder(targetDirectory.path() % '/' % QFileInfo(sourceDirectory.path()).completeBaseName(), destTree); CFileComparator comparator; REQUIRE(sourceTree.size() == destTree.size()); for (size_t i = 0, n = sourceTree.size(); i < n; ++i) { const auto& sourceItem = sourceTree[i]; const auto& destItem = destTree[i]; if (!sourceItem.isFile()) continue; QFile fileA(sourceItem.fullAbsolutePath()); REQUIRE(fileA.open(QFile::ReadOnly)); QFile fileB(destItem.fullAbsolutePath()); REQUIRE(fileB.open(QFile::ReadOnly)); comparator.compareFiles(fileA, fileB, [](int) {}, [](const CFileComparator::ComparisonResult result) { CHECK(result == CFileComparator::Equal); }); for (const auto fileTimeType: supportedFileTimeTypes) { if (!timesAlmostMatch(fileA.fileTime(fileTimeType), fileB.fileTime(fileTimeType), fileTimeType)) FAIL_CHECK(); } } REQUIRE(compareFolderContents(sourceTree, destTree)); } TEST_CASE((std::string("Move test #") + std::to_string((srand(time(nullptr)), rand()))).c_str(), "[operationperformer-move]") { QTemporaryDir sourceDirectory(QDir::tempPath() + "/" + CURRENT_TEST_NAME.c_str() + "_SOURCE_XXXXXX"); QTemporaryDir targetDirectory(QDir::tempPath() + "/" + CURRENT_TEST_NAME.c_str() + "_TARGET_XXXXXX"); REQUIRE(sourceDirectory.isValid()); REQUIRE(targetDirectory.isValid()); TRACE_LOG << "Source: " << sourceDirectory.path(); TRACE_LOG << "Target: " << targetDirectory.path(); REQUIRE(QFileInfo::exists(sourceDirectory.path())); REQUIRE(CFileSystemObject(sourceDirectory.path()).isEmptyDir()); REQUIRE(QFileInfo::exists(targetDirectory.path())); REQUIRE(CFileSystemObject(targetDirectory.path()).isEmptyDir()); CTestFolderGenerator generator; generator.setSeed(g_randomSeed); TRACE_LOG << "std::random seed: " << g_randomSeed; REQUIRE(generator.generateRandomTree(sourceDirectory.path(), 1000, 200)); std::vector<CFileSystemObject> sourceTree; CFolderEnumeratorRecursive::enumerateFolder(sourceDirectory.path(), sourceTree); COperationPerformer p(operationMove, CFileSystemObject(sourceDirectory.path()), targetDirectory.path()); ProgressObserver progressObserver; p.setObserver(&progressObserver); CTimeElapsed timer(true); p.start(); while (!p.done()) { progressObserver.processEvents(); #ifndef _DEBUG // Reasonable timeout if (timer.elapsed<std::chrono::seconds>() > 2 * 60) { FAIL("File operation timeout reached."); return; } #endif } REQUIRE(!CFileSystemObject(sourceDirectory.path()).exists()); std::vector<CFileSystemObject> destTree; CFolderEnumeratorRecursive::enumerateFolder(targetDirectory.path() % '/' % QFileInfo(sourceDirectory.path()).completeBaseName(), destTree); REQUIRE(compareFolderContents(sourceTree, destTree)); } TEST_CASE((std::string("Delete test #") + std::to_string((srand(time(nullptr)), rand()))).c_str(), "[operationperformer-delete]") { QTemporaryDir sourceDirectory(QDir::tempPath() + "/" + CURRENT_TEST_NAME.c_str() + "_SOURCE_XXXXXX"); REQUIRE(sourceDirectory.isValid()); TRACE_LOG << "Source: " << sourceDirectory.path(); REQUIRE(QFileInfo::exists(sourceDirectory.path())); REQUIRE(CFileSystemObject(sourceDirectory.path()).isEmptyDir()); CTestFolderGenerator generator; generator.setSeed(g_randomSeed); TRACE_LOG << "std::random seed: " << g_randomSeed; REQUIRE(generator.generateRandomTree(sourceDirectory.path(), 1000, 200)); REQUIRE(!QDir(sourceDirectory.path()).entryList(QDir::NoDotAndDotDot | QDir::AllEntries).empty()); COperationPerformer p(operationDelete, CFileSystemObject(sourceDirectory.path())); ProgressObserver progressObserver; p.setObserver(&progressObserver); CTimeElapsed timer(true); p.start(); while (!p.done()) { progressObserver.processEvents(); #ifndef _DEBUG // Reasonable timeout if (timer.elapsed<std::chrono::seconds>() > 2 * 60) { FAIL("File operation timeout reached."); return; } #endif } REQUIRE(!CFileSystemObject(sourceDirectory.path()).exists()); } int main(int argc, char* argv[]) { Catch::Session session; // There must be exactly one instance // Build a new parser on top of Catch's using namespace Catch::clara; auto cli = session.cli() // Get Catch's composite command line parser | Opt(g_randomSeed, "std::random seed") // bind variable to a new option, with a hint string ["--std-seed"] // the option names it will respond to ("std::random seed"); // description string for the help output // Now pass the new composite back to Catch so it uses that session.cli(cli); // Let Catch (using Clara) parse the command line const int returnCode = session.applyCommandLine(argc, argv); if (returnCode != 0) // Indicates a command line error return returnCode; return session.run(); } <|endoftext|>
<commit_before>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "spriterenderercomponent.h" #include <texture.h> #include <game.h> #include "graphics/item.h" #include "graphics/engine.h" #include "graphics/material.h" #include "graphics/mesh.h" #include "graphics/materialinstance.h" #include "engine/gameobject.h" #include "engine/asset.h" #include <QtGui/QMatrix4x4> #include <QtGui/QColor> #include <QtCore/QMimeData> #include <QtCore/QVariant> REGISTER_OBJECTTYPE( GluonEngine, SpriteRendererComponent ) using namespace GluonEngine; class SpriteRendererComponent::SpriteRendererComponentPrivate { public: SpriteRendererComponentPrivate() { item = 0; texture = 0; material = 0; size = QSizeF( 1.0f, 1.0f ); color.setRgb( 255, 255, 255 ); } GluonGraphics::Item* item; GluonEngine::Asset* texture; GluonGraphics::MaterialInstance* material; QColor color; QSizeF size; }; SpriteRendererComponent::SpriteRendererComponent( QObject* parent ) : Component( parent ) , d( new SpriteRendererComponentPrivate ) { } SpriteRendererComponent::SpriteRendererComponent( const SpriteRendererComponent& other ) : Component( other ) , d( other.d ) { } SpriteRendererComponent::~SpriteRendererComponent() { delete d; } QString SpriteRendererComponent::category() const { return QString( "Graphics Rendering" ); } void SpriteRendererComponent::initialize() { if( !d->item ) { d->item = GluonGraphics::Engine::instance()->createItem( "default" ); } if( d->material ) { Asset* materialAsset = qobject_cast<Asset*>( d->material->parent() ); if( materialAsset ) materialAsset->load(); Asset* texture = 0; if( d->material->property( "texture0" ).type() == QVariant::String ) texture = gameProject()->findChild<Asset*>( d->material->property( "texture0" ).toString() ); else texture = qobject_cast<Asset*>( GluonCore::GluonObjectFactory::instance()->wrappedObject( d->material->property( "texture0" ) ) ); if( texture ) texture->load(); d->item->setMaterialInstance( d->material ); } } void SpriteRendererComponent::start() { } void SpriteRendererComponent::draw( int timeLapse ) { Q_UNUSED( timeLapse ) if( d->item ) { QMatrix4x4 transform = gameObject()->transform(); transform.scale( d->size.width() / 2, d->size.height() / 2 ); d->item->setTransform( transform ); } } void SpriteRendererComponent::cleanup() { if( d->item ) { GluonGraphics::Engine::instance()->destroyItem( d->item ); d->item = 0; } } void SpriteRendererComponent::setSize( const QSizeF& size ) { d->size = size; } QSizeF SpriteRendererComponent::size() { return d->size; } GluonGraphics::MaterialInstance* SpriteRendererComponent::material() { return d->material; } void SpriteRendererComponent::setMaterial( GluonGraphics::MaterialInstance* material ) { if( !material ) return; d->material = material; if( d->item ) d->item->setMaterialInstance( material ); } void SpriteRendererComponent::setMaterial( const QString& path ) { setMaterial( qobject_cast<GluonGraphics::MaterialInstance*>( Game::instance()->gameProject()->findItemByName( path ) ) ); } Q_EXPORT_PLUGIN2( gluon_component_spriterenderer, GluonEngine::SpriteRendererComponent ); #include "spriterenderercomponent.moc" <commit_msg>Allow the materialInstance property to be set to 0.<commit_after>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "spriterenderercomponent.h" #include <texture.h> #include <game.h> #include "graphics/item.h" #include "graphics/engine.h" #include "graphics/material.h" #include "graphics/mesh.h" #include "graphics/materialinstance.h" #include "engine/gameobject.h" #include "engine/asset.h" #include <QtGui/QMatrix4x4> #include <QtGui/QColor> #include <QtCore/QMimeData> #include <QtCore/QVariant> REGISTER_OBJECTTYPE( GluonEngine, SpriteRendererComponent ) using namespace GluonEngine; class SpriteRendererComponent::SpriteRendererComponentPrivate { public: SpriteRendererComponentPrivate() { item = 0; texture = 0; material = 0; size = QSizeF( 1.0f, 1.0f ); color.setRgb( 255, 255, 255 ); } GluonGraphics::Item* item; GluonEngine::Asset* texture; GluonGraphics::MaterialInstance* material; QColor color; QSizeF size; }; SpriteRendererComponent::SpriteRendererComponent( QObject* parent ) : Component( parent ) , d( new SpriteRendererComponentPrivate ) { } SpriteRendererComponent::SpriteRendererComponent( const SpriteRendererComponent& other ) : Component( other ) , d( other.d ) { } SpriteRendererComponent::~SpriteRendererComponent() { delete d; } QString SpriteRendererComponent::category() const { return QString( "Graphics Rendering" ); } void SpriteRendererComponent::initialize() { if( !d->item ) { d->item = GluonGraphics::Engine::instance()->createItem( "default" ); } if( d->material ) { Asset* materialAsset = qobject_cast<Asset*>( d->material->parent() ); if( materialAsset ) materialAsset->load(); Asset* texture = 0; if( d->material->property( "texture0" ).type() == QVariant::String ) texture = gameProject()->findChild<Asset*>( d->material->property( "texture0" ).toString() ); else texture = qobject_cast<Asset*>( GluonCore::GluonObjectFactory::instance()->wrappedObject( d->material->property( "texture0" ) ) ); if( texture ) texture->load(); d->item->setMaterialInstance( d->material ); } } void SpriteRendererComponent::start() { } void SpriteRendererComponent::draw( int timeLapse ) { Q_UNUSED( timeLapse ) if( d->item ) { QMatrix4x4 transform = gameObject()->transform(); transform.scale( d->size.width() / 2, d->size.height() / 2 ); d->item->setTransform( transform ); } } void SpriteRendererComponent::cleanup() { if( d->item ) { GluonGraphics::Engine::instance()->destroyItem( d->item ); d->item = 0; } } void SpriteRendererComponent::setSize( const QSizeF& size ) { d->size = size; } QSizeF SpriteRendererComponent::size() { return d->size; } GluonGraphics::MaterialInstance* SpriteRendererComponent::material() { return d->material; } void SpriteRendererComponent::setMaterial( GluonGraphics::MaterialInstance* material ) { d->material = material; if( d->item ) { if(material) { d->item->setMaterialInstance( material ); } else { d->item->setMaterialInstance(GluonGraphics::Engine::instance()->material("default")->instance("default")); } } } void SpriteRendererComponent::setMaterial( const QString& path ) { setMaterial( qobject_cast<GluonGraphics::MaterialInstance*>( Game::instance()->gameProject()->findItemByName( path ) ) ); } Q_EXPORT_PLUGIN2( gluon_component_spriterenderer, GluonEngine::SpriteRendererComponent ); #include "spriterenderercomponent.moc" <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/component_updater/swiftshader_component_installer.h" #include "base/base_paths.h" #include "base/bind.h" #include "base/compiler_specific.h" #include "base/cpu.h" #include "base/file_util.h" #include "base/files/file_enumerator.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/path_service.h" #include "base/strings/string_util.h" #include "base/values.h" #include "chrome/browser/component_updater/component_updater_service.h" #include "chrome/common/chrome_paths.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/gpu_data_manager.h" #include "content/public/browser/gpu_data_manager_observer.h" #include "gpu/config/gpu_feature_type.h" using content::BrowserThread; using content::GpuDataManager; namespace component_updater { namespace { // CRX hash. The extension id is: nhfgdggnnopgbfdlpeoalgcjdgfafocg. const uint8 kSha2Hash[] = {0xd7, 0x56, 0x36, 0x6d, 0xde, 0xf6, 0x15, 0x3b, 0xf4, 0xe0, 0xb6, 0x29, 0x36, 0x50, 0x5e, 0x26, 0xbd, 0x77, 0x8b, 0x8e, 0x35, 0xc2, 0x7e, 0x43, 0x52, 0x47, 0x62, 0xed, 0x12, 0xca, 0xcc, 0x6a}; // File name of the internal SwiftShader plugin on different platforms. const base::FilePath::CharType kSwiftShaderEglName[] = FILE_PATH_LITERAL("libegl.dll"); const base::FilePath::CharType kSwiftShaderGlesName[] = FILE_PATH_LITERAL("libglesv2.dll"); const char kSwiftShaderManifestName[] = "SwiftShader"; const base::FilePath::CharType kSwiftShaderBaseDirectory[] = FILE_PATH_LITERAL("SwiftShader"); // If we don't have a SwiftShader component, this is the version we claim. const char kNullVersion[] = "0.0.0.0"; // The base directory on windows looks like: // <profile>\AppData\Local\Google\Chrome\User Data\SwiftShader\. base::FilePath GetSwiftShaderBaseDirectory() { base::FilePath result; PathService::Get(chrome::DIR_USER_DATA, &result); return result.Append(kSwiftShaderBaseDirectory); } // SwiftShader has version encoded in the path itself // so we need to enumerate the directories to find the full path. // On success it returns something like: // <profile>\AppData\Local\Google\Chrome\User Data\SwiftShader\10.3.44.555\. bool GetLatestSwiftShaderDirectory(base::FilePath* result, Version* latest, std::vector<base::FilePath>* older_dirs) { base::FilePath base_dir = GetSwiftShaderBaseDirectory(); bool found = false; base::FileEnumerator file_enumerator(base_dir, false, base::FileEnumerator::DIRECTORIES); for (base::FilePath path = file_enumerator.Next(); !path.value().empty(); path = file_enumerator.Next()) { Version version(path.BaseName().MaybeAsASCII()); if (!version.IsValid()) continue; if (version.CompareTo(*latest) > 0 && base::PathExists(path.Append(kSwiftShaderEglName)) && base::PathExists(path.Append(kSwiftShaderGlesName))) { if (found && older_dirs) older_dirs->push_back(*result); *latest = version; *result = path; found = true; } else { if (older_dirs) older_dirs->push_back(path); } } return found; } void RegisterSwiftShaderWithChrome(const base::FilePath& path) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); GpuDataManager::GetInstance()->RegisterSwiftShaderPath(path); } } // namespace class SwiftShaderComponentInstaller : public ComponentInstaller { public: explicit SwiftShaderComponentInstaller(const Version& version); virtual ~SwiftShaderComponentInstaller() {} virtual void OnUpdateError(int error) OVERRIDE; virtual bool Install(const base::DictionaryValue& manifest, const base::FilePath& unpack_path) OVERRIDE; virtual bool GetInstalledFile(const std::string& file, base::FilePath* installed_file) OVERRIDE; private: Version current_version_; }; SwiftShaderComponentInstaller::SwiftShaderComponentInstaller( const Version& version) : current_version_(version) { DCHECK(version.IsValid()); } void SwiftShaderComponentInstaller::OnUpdateError(int error) { NOTREACHED() << "SwiftShader update error: " << error; } bool SwiftShaderComponentInstaller::Install( const base::DictionaryValue& manifest, const base::FilePath& unpack_path) { std::string name; manifest.GetStringASCII("name", &name); if (name != kSwiftShaderManifestName) return false; std::string proposed_version; manifest.GetStringASCII("version", &proposed_version); Version version(proposed_version.c_str()); if (!version.IsValid()) return false; if (current_version_.CompareTo(version) >= 0) return false; if (!base::PathExists(unpack_path.Append(kSwiftShaderEglName)) || !base::PathExists(unpack_path.Append(kSwiftShaderGlesName))) return false; // Passed the basic tests. Time to install it. base::FilePath path = GetSwiftShaderBaseDirectory().AppendASCII(version.GetString()); if (base::PathExists(path)) return false; if (!base::Move(unpack_path, path)) return false; // Installation is done. Now tell the rest of chrome. current_version_ = version; BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&RegisterSwiftShaderWithChrome, path)); return true; } bool SwiftShaderComponentInstaller::GetInstalledFile( const std::string& file, base::FilePath* installed_file) { return false; } void FinishSwiftShaderUpdateRegistration(ComponentUpdateService* cus, const Version& version) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); CrxComponent swiftshader; swiftshader.name = "Swift Shader"; swiftshader.installer = new SwiftShaderComponentInstaller(version); swiftshader.version = version; swiftshader.pk_hash.assign(kSha2Hash, &kSha2Hash[sizeof(kSha2Hash)]); if (cus->RegisterComponent(swiftshader) != ComponentUpdateService::kOk) { NOTREACHED() << "SwiftShader component registration fail"; } } class UpdateChecker : public content::GpuDataManagerObserver { public: explicit UpdateChecker(ComponentUpdateService* cus); virtual void OnGpuInfoUpdate() OVERRIDE; private: ComponentUpdateService* cus_; }; UpdateChecker::UpdateChecker(ComponentUpdateService* cus) : cus_(cus) { } void UpdateChecker::OnGpuInfoUpdate() { GpuDataManager *gpu_data_manager = GpuDataManager::GetInstance(); if (!gpu_data_manager->GpuAccessAllowed(NULL) || gpu_data_manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_WEBGL) || gpu_data_manager->ShouldUseSwiftShader()) { gpu_data_manager->RemoveObserver(this); DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); base::FilePath path = GetSwiftShaderBaseDirectory(); Version version(kNullVersion); GetLatestSwiftShaderDirectory(&path, &version, NULL); BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&FinishSwiftShaderUpdateRegistration, cus_, version)); } } // Check if there already is a version of swiftshader installed, // and if so register it. void RegisterSwiftShaderPath(ComponentUpdateService* cus) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); base::FilePath path = GetSwiftShaderBaseDirectory(); if (!base::PathExists(path)) { if (!base::CreateDirectory(path)) { NOTREACHED() << "Could not create SwiftShader directory."; return; } } Version version(kNullVersion); std::vector<base::FilePath> older_dirs; if (GetLatestSwiftShaderDirectory(&path, &version, &older_dirs)) BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&RegisterSwiftShaderWithChrome, path)); UpdateChecker *update_checker = new UpdateChecker(cus); GpuDataManager::GetInstance()->AddObserver(update_checker); update_checker->OnGpuInfoUpdate(); // We leak update_checker here, because it has to stick around for the life // of the GpuDataManager. // Remove older versions of SwiftShader. for (std::vector<base::FilePath>::iterator iter = older_dirs.begin(); iter != older_dirs.end(); ++iter) { base::DeleteFile(*iter, true); } } void RegisterSwiftShaderComponent(ComponentUpdateService* cus) { #if defined(ENABLE_SWIFTSHADER) base::CPU cpu; if (!cpu.has_sse2()) return; BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, base::Bind(&RegisterSwiftShaderPath, cus)); #endif } } // namespace component_updater <commit_msg>Fixes an ODR for the UpdateChecker class in the component updater.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/component_updater/swiftshader_component_installer.h" #include "base/base_paths.h" #include "base/bind.h" #include "base/compiler_specific.h" #include "base/cpu.h" #include "base/file_util.h" #include "base/files/file_enumerator.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/path_service.h" #include "base/strings/string_util.h" #include "base/values.h" #include "chrome/browser/component_updater/component_updater_service.h" #include "chrome/common/chrome_paths.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/gpu_data_manager.h" #include "content/public/browser/gpu_data_manager_observer.h" #include "gpu/config/gpu_feature_type.h" using content::BrowserThread; using content::GpuDataManager; namespace component_updater { namespace { // CRX hash. The extension id is: nhfgdggnnopgbfdlpeoalgcjdgfafocg. const uint8 kSha2Hash[] = {0xd7, 0x56, 0x36, 0x6d, 0xde, 0xf6, 0x15, 0x3b, 0xf4, 0xe0, 0xb6, 0x29, 0x36, 0x50, 0x5e, 0x26, 0xbd, 0x77, 0x8b, 0x8e, 0x35, 0xc2, 0x7e, 0x43, 0x52, 0x47, 0x62, 0xed, 0x12, 0xca, 0xcc, 0x6a}; // File name of the internal SwiftShader plugin on different platforms. const base::FilePath::CharType kSwiftShaderEglName[] = FILE_PATH_LITERAL("libegl.dll"); const base::FilePath::CharType kSwiftShaderGlesName[] = FILE_PATH_LITERAL("libglesv2.dll"); const char kSwiftShaderManifestName[] = "SwiftShader"; const base::FilePath::CharType kSwiftShaderBaseDirectory[] = FILE_PATH_LITERAL("SwiftShader"); // If we don't have a SwiftShader component, this is the version we claim. const char kNullVersion[] = "0.0.0.0"; // The base directory on windows looks like: // <profile>\AppData\Local\Google\Chrome\User Data\SwiftShader\. base::FilePath GetSwiftShaderBaseDirectory() { base::FilePath result; PathService::Get(chrome::DIR_USER_DATA, &result); return result.Append(kSwiftShaderBaseDirectory); } // SwiftShader has version encoded in the path itself // so we need to enumerate the directories to find the full path. // On success it returns something like: // <profile>\AppData\Local\Google\Chrome\User Data\SwiftShader\10.3.44.555\. bool GetLatestSwiftShaderDirectory(base::FilePath* result, Version* latest, std::vector<base::FilePath>* older_dirs) { base::FilePath base_dir = GetSwiftShaderBaseDirectory(); bool found = false; base::FileEnumerator file_enumerator(base_dir, false, base::FileEnumerator::DIRECTORIES); for (base::FilePath path = file_enumerator.Next(); !path.value().empty(); path = file_enumerator.Next()) { Version version(path.BaseName().MaybeAsASCII()); if (!version.IsValid()) continue; if (version.CompareTo(*latest) > 0 && base::PathExists(path.Append(kSwiftShaderEglName)) && base::PathExists(path.Append(kSwiftShaderGlesName))) { if (found && older_dirs) older_dirs->push_back(*result); *latest = version; *result = path; found = true; } else { if (older_dirs) older_dirs->push_back(path); } } return found; } void RegisterSwiftShaderWithChrome(const base::FilePath& path) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); GpuDataManager::GetInstance()->RegisterSwiftShaderPath(path); } class SwiftShaderComponentInstaller : public ComponentInstaller { public: explicit SwiftShaderComponentInstaller(const Version& version); virtual ~SwiftShaderComponentInstaller() {} virtual void OnUpdateError(int error) OVERRIDE; virtual bool Install(const base::DictionaryValue& manifest, const base::FilePath& unpack_path) OVERRIDE; virtual bool GetInstalledFile(const std::string& file, base::FilePath* installed_file) OVERRIDE; private: Version current_version_; }; SwiftShaderComponentInstaller::SwiftShaderComponentInstaller( const Version& version) : current_version_(version) { DCHECK(version.IsValid()); } void SwiftShaderComponentInstaller::OnUpdateError(int error) { NOTREACHED() << "SwiftShader update error: " << error; } bool SwiftShaderComponentInstaller::Install( const base::DictionaryValue& manifest, const base::FilePath& unpack_path) { std::string name; manifest.GetStringASCII("name", &name); if (name != kSwiftShaderManifestName) return false; std::string proposed_version; manifest.GetStringASCII("version", &proposed_version); Version version(proposed_version.c_str()); if (!version.IsValid()) return false; if (current_version_.CompareTo(version) >= 0) return false; if (!base::PathExists(unpack_path.Append(kSwiftShaderEglName)) || !base::PathExists(unpack_path.Append(kSwiftShaderGlesName))) return false; // Passed the basic tests. Time to install it. base::FilePath path = GetSwiftShaderBaseDirectory().AppendASCII(version.GetString()); if (base::PathExists(path)) return false; if (!base::Move(unpack_path, path)) return false; // Installation is done. Now tell the rest of chrome. current_version_ = version; BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&RegisterSwiftShaderWithChrome, path)); return true; } bool SwiftShaderComponentInstaller::GetInstalledFile( const std::string& file, base::FilePath* installed_file) { return false; } void FinishSwiftShaderUpdateRegistration(ComponentUpdateService* cus, const Version& version) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); CrxComponent swiftshader; swiftshader.name = "Swift Shader"; swiftshader.installer = new SwiftShaderComponentInstaller(version); swiftshader.version = version; swiftshader.pk_hash.assign(kSha2Hash, &kSha2Hash[sizeof(kSha2Hash)]); if (cus->RegisterComponent(swiftshader) != ComponentUpdateService::kOk) { NOTREACHED() << "SwiftShader component registration fail"; } } class UpdateChecker : public content::GpuDataManagerObserver { public: explicit UpdateChecker(ComponentUpdateService* cus); virtual void OnGpuInfoUpdate() OVERRIDE; private: ComponentUpdateService* cus_; }; UpdateChecker::UpdateChecker(ComponentUpdateService* cus) : cus_(cus) { } void UpdateChecker::OnGpuInfoUpdate() { GpuDataManager *gpu_data_manager = GpuDataManager::GetInstance(); if (!gpu_data_manager->GpuAccessAllowed(NULL) || gpu_data_manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_WEBGL) || gpu_data_manager->ShouldUseSwiftShader()) { gpu_data_manager->RemoveObserver(this); DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); base::FilePath path = GetSwiftShaderBaseDirectory(); Version version(kNullVersion); GetLatestSwiftShaderDirectory(&path, &version, NULL); BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&FinishSwiftShaderUpdateRegistration, cus_, version)); } } #if defined(ENABLE_SWIFTSHADER) // Check if there already is a version of swiftshader installed, // and if so register it. void RegisterSwiftShaderPath(ComponentUpdateService* cus) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); base::FilePath path = GetSwiftShaderBaseDirectory(); if (!base::PathExists(path)) { if (!base::CreateDirectory(path)) { NOTREACHED() << "Could not create SwiftShader directory."; return; } } Version version(kNullVersion); std::vector<base::FilePath> older_dirs; if (GetLatestSwiftShaderDirectory(&path, &version, &older_dirs)) BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&RegisterSwiftShaderWithChrome, path)); UpdateChecker *update_checker = new UpdateChecker(cus); GpuDataManager::GetInstance()->AddObserver(update_checker); update_checker->OnGpuInfoUpdate(); // We leak update_checker here, because it has to stick around for the life // of the GpuDataManager. // Remove older versions of SwiftShader. for (std::vector<base::FilePath>::iterator iter = older_dirs.begin(); iter != older_dirs.end(); ++iter) { base::DeleteFile(*iter, true); } } #endif // ENABLE_SWIFTSHADER } // namespace void RegisterSwiftShaderComponent(ComponentUpdateService* cus) { #if defined(ENABLE_SWIFTSHADER) base::CPU cpu; if (!cpu.has_sse2()) return; BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, base::Bind(&RegisterSwiftShaderPath, cus)); #endif } } // namespace component_updater <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: confeventhelpers.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: ihi $ $Date: 2007-11-23 14:01:04 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CONFIGMGR_API_EVENTHELPERS_HXX_ #define CONFIGMGR_API_EVENTHELPERS_HXX_ #ifndef CONFIGMGR_API_EVENTS_HXX_ #include "confevents.hxx" #endif #ifndef CONFIGMGR_CONFIGPATH_HXX_ #include "configpath.hxx" #endif #ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_ #include <com/sun/star/uno/RuntimeException.hpp> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef INCLUDED_MAP #include <map> #define INCLUDED_MAP #endif #ifndef INCLUDED_FUNCTIONAL #include <functional> #define INCLUDED_FUNCTIONAL #endif #include <hash_set> #ifndef INCLUDED_SET #include <set> #define INCLUDED_SET #endif namespace configmgr { namespace internal { using namespace configuration; //////////////////////////////////////////////////////////////////////// template <class ListenerRef> class BroadcastImplHelper { public: osl::Mutex mutex; public: BroadcastImplHelper() {} ~BroadcastImplHelper() { OSL_ENSURE(m_aInterfaces.empty(), "Configuration Broadcaster was not disposed properly"); } public: typedef std::set<ListenerRef> Interfaces; typedef typename Interfaces::iterator FullIterator; typedef typename Interfaces::const_iterator Iterator; public: FullIterator addListener(ListenerRef aListener) { return m_aInterfaces.insert(aListener).first; } void removeListener(ListenerRef aListener) { m_aInterfaces.erase(aListener); } void disposing(IConfigBroadcaster* pSource); public: Iterator begin() const { return m_aInterfaces.begin(); } Iterator end() const { return m_aInterfaces.end(); } Iterator find(ListenerRef aListener) const { return m_aInterfaces.find(aListener); } FullIterator findFull(ListenerRef aListener) { return m_aInterfaces.find(aListener); } private: Interfaces m_aInterfaces; // no implementation - not copyable BroadcastImplHelper(BroadcastImplHelper&); void operator=(BroadcastImplHelper&); }; //////////////////////////////////////////////////////////////////////// template <class Listener> void BroadcastImplHelper<Listener>::disposing(IConfigBroadcaster* pSource) { osl::ClearableMutexGuard aGuard(this->mutex); // ensure that no notifications are running Interfaces aTargets; aTargets.swap(m_aInterfaces); aGuard.clear(); for(FullIterator it = aTargets.begin(); it != aTargets.end(); ) { FullIterator cur = it++; if (*cur) (*cur)->disposing(pSource); } } ///////////////////////////////////////////////////////////////////////// class NodeListenerInfo { public: typedef std::hash_set<AbsolutePath, Path::Hash, Path::Equiv> Pathes; public: NodeListenerInfo(INodeListenerRef const& pListener) : m_pListener(pListener) { } // path handling Pathes const& pathList() const { return m_aPathes; } void addPath(AbsolutePath const& sPath) const { m_aPathes.insert(sPath); } void removePath(AbsolutePath const& sPath) const { m_aPathes.erase(sPath); } //void removeChildPathes(OUString const& sPath); // behave as pointer for use as a 'reference' class INodeListenerRef get() const { return m_pListener; } INodeListenerRef operator->() const { return get(); } INodeListener& operator*() const { return *m_pListener; } // needed to allow if (info) ... struct HasListener; operator HasListener const*() const { return reinterpret_cast<HasListener*>(m_pListener.get()); } bool operator < (NodeListenerInfo const& aInfo) const { return std::less<INodeListener*>()(m_pListener.get(), aInfo.m_pListener.get()); } bool operator == (NodeListenerInfo const& aInfo) const { return !!( m_pListener == aInfo.m_pListener); } bool operator > (NodeListenerInfo const& aInfo) const { return aInfo.operator < (*this); } bool operator >= (NodeListenerInfo const& aInfo) const { return !operator<(aInfo); } bool operator <= (NodeListenerInfo const& aInfo) const { return !operator>(aInfo); } bool operator != (NodeListenerInfo const& aInfo) const { return !operator==(aInfo); } private: INodeListenerRef m_pListener; mutable Pathes m_aPathes; // hack to be mutable even as set element }; class ConfigChangesBroadcasterImpl { public: ConfigChangesBroadcasterImpl(); ~ConfigChangesBroadcasterImpl(); void add(AbsolutePath const& aPath, INodeListenerRef const& pListener); void remove(INodeListenerRef const& pListener); // void removed(OUString const& aPath, bool bRemovedFromModel, IConfigBroadcaster* pSource); void dispatch(Change const& rBaseChange, AbsolutePath const& sChangeLocation, sal_Bool _bError, IConfigBroadcaster* pSource); void dispatch(TreeChangeList const& rList_, sal_Bool _bError, IConfigBroadcaster* pSource); void disposing(IConfigBroadcaster* pSource); private: typedef BroadcastImplHelper<NodeListenerInfo> Listeners; typedef Listeners::FullIterator InfoRef; typedef std::multimap<AbsolutePath, InfoRef, Path::Before> PathMap; Listeners m_aListeners; PathMap m_aPathMap; private: void dispatchInner(INodeListenerRef const& pTarget, AbsolutePath const& sTargetPath, Change const& rBaseChange, AbsolutePath const& sChangeLocation, sal_Bool _bError, IConfigBroadcaster* pSource); void dispatchOuter(INodeListenerRef const& pTarget, AbsolutePath const& sTargetPath, Change const& rBaseChange, AbsolutePath const& sChangeLocation, sal_Bool _bError, IConfigBroadcaster* pSource); }; ///////////////////////////////////////////////////////////////////////// } // namespace } // namespace #endif // CONFIGMGR_API_EVENTHELPERS_HXX_ <commit_msg>INTEGRATION: CWS changefileheader (1.11.16); FILE MERGED 2008/04/01 15:06:29 thb 1.11.16.3: #i85898# Stripping all external header guards 2008/04/01 12:27:08 thb 1.11.16.2: #i85898# Stripping all external header guards 2008/03/31 12:22:34 rt 1.11.16.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: confeventhelpers.hxx,v $ * $Revision: 1.12 $ * * 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 CONFIGMGR_API_EVENTHELPERS_HXX_ #define CONFIGMGR_API_EVENTHELPERS_HXX_ #include "confevents.hxx" #include "configpath.hxx" #include <com/sun/star/uno/RuntimeException.hpp> #include <osl/diagnose.h> #include <osl/mutex.hxx> #ifndef INCLUDED_MAP #include <map> #define INCLUDED_MAP #endif #ifndef INCLUDED_FUNCTIONAL #include <functional> #define INCLUDED_FUNCTIONAL #endif #include <hash_set> #ifndef INCLUDED_SET #include <set> #define INCLUDED_SET #endif namespace configmgr { namespace internal { using namespace configuration; //////////////////////////////////////////////////////////////////////// template <class ListenerRef> class BroadcastImplHelper { public: osl::Mutex mutex; public: BroadcastImplHelper() {} ~BroadcastImplHelper() { OSL_ENSURE(m_aInterfaces.empty(), "Configuration Broadcaster was not disposed properly"); } public: typedef std::set<ListenerRef> Interfaces; typedef typename Interfaces::iterator FullIterator; typedef typename Interfaces::const_iterator Iterator; public: FullIterator addListener(ListenerRef aListener) { return m_aInterfaces.insert(aListener).first; } void removeListener(ListenerRef aListener) { m_aInterfaces.erase(aListener); } void disposing(IConfigBroadcaster* pSource); public: Iterator begin() const { return m_aInterfaces.begin(); } Iterator end() const { return m_aInterfaces.end(); } Iterator find(ListenerRef aListener) const { return m_aInterfaces.find(aListener); } FullIterator findFull(ListenerRef aListener) { return m_aInterfaces.find(aListener); } private: Interfaces m_aInterfaces; // no implementation - not copyable BroadcastImplHelper(BroadcastImplHelper&); void operator=(BroadcastImplHelper&); }; //////////////////////////////////////////////////////////////////////// template <class Listener> void BroadcastImplHelper<Listener>::disposing(IConfigBroadcaster* pSource) { osl::ClearableMutexGuard aGuard(this->mutex); // ensure that no notifications are running Interfaces aTargets; aTargets.swap(m_aInterfaces); aGuard.clear(); for(FullIterator it = aTargets.begin(); it != aTargets.end(); ) { FullIterator cur = it++; if (*cur) (*cur)->disposing(pSource); } } ///////////////////////////////////////////////////////////////////////// class NodeListenerInfo { public: typedef std::hash_set<AbsolutePath, Path::Hash, Path::Equiv> Pathes; public: NodeListenerInfo(INodeListenerRef const& pListener) : m_pListener(pListener) { } // path handling Pathes const& pathList() const { return m_aPathes; } void addPath(AbsolutePath const& sPath) const { m_aPathes.insert(sPath); } void removePath(AbsolutePath const& sPath) const { m_aPathes.erase(sPath); } //void removeChildPathes(OUString const& sPath); // behave as pointer for use as a 'reference' class INodeListenerRef get() const { return m_pListener; } INodeListenerRef operator->() const { return get(); } INodeListener& operator*() const { return *m_pListener; } // needed to allow if (info) ... struct HasListener; operator HasListener const*() const { return reinterpret_cast<HasListener*>(m_pListener.get()); } bool operator < (NodeListenerInfo const& aInfo) const { return std::less<INodeListener*>()(m_pListener.get(), aInfo.m_pListener.get()); } bool operator == (NodeListenerInfo const& aInfo) const { return !!( m_pListener == aInfo.m_pListener); } bool operator > (NodeListenerInfo const& aInfo) const { return aInfo.operator < (*this); } bool operator >= (NodeListenerInfo const& aInfo) const { return !operator<(aInfo); } bool operator <= (NodeListenerInfo const& aInfo) const { return !operator>(aInfo); } bool operator != (NodeListenerInfo const& aInfo) const { return !operator==(aInfo); } private: INodeListenerRef m_pListener; mutable Pathes m_aPathes; // hack to be mutable even as set element }; class ConfigChangesBroadcasterImpl { public: ConfigChangesBroadcasterImpl(); ~ConfigChangesBroadcasterImpl(); void add(AbsolutePath const& aPath, INodeListenerRef const& pListener); void remove(INodeListenerRef const& pListener); // void removed(OUString const& aPath, bool bRemovedFromModel, IConfigBroadcaster* pSource); void dispatch(Change const& rBaseChange, AbsolutePath const& sChangeLocation, sal_Bool _bError, IConfigBroadcaster* pSource); void dispatch(TreeChangeList const& rList_, sal_Bool _bError, IConfigBroadcaster* pSource); void disposing(IConfigBroadcaster* pSource); private: typedef BroadcastImplHelper<NodeListenerInfo> Listeners; typedef Listeners::FullIterator InfoRef; typedef std::multimap<AbsolutePath, InfoRef, Path::Before> PathMap; Listeners m_aListeners; PathMap m_aPathMap; private: void dispatchInner(INodeListenerRef const& pTarget, AbsolutePath const& sTargetPath, Change const& rBaseChange, AbsolutePath const& sChangeLocation, sal_Bool _bError, IConfigBroadcaster* pSource); void dispatchOuter(INodeListenerRef const& pTarget, AbsolutePath const& sTargetPath, Change const& rBaseChange, AbsolutePath const& sChangeLocation, sal_Bool _bError, IConfigBroadcaster* pSource); }; ///////////////////////////////////////////////////////////////////////// } // namespace } // namespace #endif // CONFIGMGR_API_EVENTHELPERS_HXX_ <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2011, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "IECoreMaya/FromMayaCameraConverter.h" #include "IECoreMaya/Convert.h" #include "IECore/CompoundParameter.h" #include "IECore/Camera.h" #include "IECore/MatrixTransform.h" #include "IECore/AngleConversion.h" #include "maya/MFnCamera.h" #include "maya/MString.h" #include "maya/MRenderUtil.h" #include "maya/MCommonRenderSettingsData.h" #include "maya/MDagPath.h" #include "OpenEXR/ImathMath.h" using namespace IECoreMaya; using namespace IECore; using namespace Imath; IE_CORE_DEFINERUNTIMETYPED( FromMayaCameraConverter ); FromMayaDagNodeConverter::Description<FromMayaCameraConverter> FromMayaCameraConverter::m_description( MFn::kCamera, CameraTypeId, true ); FromMayaCameraConverter::FromMayaCameraConverter( const MDagPath &dagPath ) : FromMayaDagNodeConverter( "Converts maya camera shape nodes into IECore::Camera objects.", dagPath ) { IntParameter::PresetsContainer resolutionModePresets; resolutionModePresets.push_back( IntParameter::Preset( "renderGlobals", RenderGlobals ) ); resolutionModePresets.push_back( IntParameter::Preset( "specified", Specified ) ); m_resolutionMode = new IntParameter( "resolutionMode", "Determines how the resolution of the camera is decided.", RenderGlobals, RenderGlobals, Specified, resolutionModePresets, true ); parameters()->addParameter( m_resolutionMode ); V2iParameter::PresetsContainer resolutionPresets; resolutionPresets.push_back( V2iParameter::Preset( "2K", Imath::V2i( 2048, 1556 ) ) ); resolutionPresets.push_back( V2iParameter::Preset( "1K", Imath::V2i( 1024, 778 ) ) ); m_resolution = new V2iParameter( "resolution", "Specifies the resolution of the camera when mode is set to \"Specified\".", Imath::V2i( 2048, 1556 ), resolutionPresets ); parameters()->addParameter( m_resolution ); } IECore::ObjectPtr FromMayaCameraConverter::doConversion( const MDagPath &dagPath, IECore::ConstCompoundObjectPtr operands ) const { MFnCamera fnCamera( dagPath ); // convert things that are required by the IECore::Renderer specification CameraPtr result = new Camera; result->setName( IECore::convert<std::string>( fnCamera.name() ) ); result->setTransform( new MatrixTransform( IECore::convert<Imath::M44f>( dagPath.inclusiveMatrix() ) ) ); V2i resolution; if( operands->member<IntData>( "resolutionMode" )->readable()==RenderGlobals ) { MCommonRenderSettingsData renderSettings; MRenderUtil::getCommonRenderSettings( renderSettings ); resolution = Imath::V2i( renderSettings.width, renderSettings.height ); } else { resolution = operands->member<V2iData>( "resolution" )->readable(); } result->parameters()["resolution"] = new V2iData( resolution ); Imath::V2f clippingPlanes = Imath::V2f( fnCamera.nearClippingPlane(), fnCamera.farClippingPlane() ); result->parameters()["clippingPlanes"] = new V2fData( clippingPlanes ); Imath::Box2d frustum; fnCamera.getRenderingFrustum( (float)resolution.x / (float)resolution.y, frustum.min.x, frustum.max.x, frustum.min.y, frustum.max.y ); if( fnCamera.isOrtho() ) { // orthographic result->parameters()["projection"] = new StringData( "orthographic" ); result->parameters()["screenWindow"] = new Box2fData( Box2f( frustum.min, frustum.max ) ); } else { // perspective result->parameters()["projection"] = new StringData( "perspective" ); // derive horizontal field of view from the viewing frustum float fov = Math<double>::atan( frustum.max.x / clippingPlanes[0] ) * 2.0f; fov = radiansToDegrees( fov ); result->parameters()["projection:fov"] = new FloatData( fov ); // scale the frustum so that it's -1,1 in x and that gives us the screen window float frustumScale = 2.0f/(frustum.max.x - frustum.min.x); Box2f screenWindow( V2f( -1, frustum.min.y * frustumScale ), V2f( 1, frustum.max.y * frustumScale ) ); result->parameters()["screenWindow"] = new Box2fData( screenWindow ); } // and add on other bits and bobs from maya attributes as blind data CompoundDataPtr maya = new CompoundData; result->blindData()->writable()["maya"] = maya; maya->writable()["aperture"] = new V2fData( Imath::V2f( fnCamera.horizontalFilmAperture(), fnCamera.verticalFilmAperture() ) ); return result; } <commit_msg>Fixed FromMayaCameraConverter to account for non-zero film offsets.<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2015, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "IECoreMaya/FromMayaCameraConverter.h" #include "IECoreMaya/Convert.h" #include "IECore/CompoundParameter.h" #include "IECore/Camera.h" #include "IECore/MatrixTransform.h" #include "IECore/AngleConversion.h" #include "maya/MFnCamera.h" #include "maya/MString.h" #include "maya/MRenderUtil.h" #include "maya/MCommonRenderSettingsData.h" #include "maya/MDagPath.h" #include "OpenEXR/ImathMath.h" using namespace IECoreMaya; using namespace IECore; using namespace Imath; IE_CORE_DEFINERUNTIMETYPED( FromMayaCameraConverter ); FromMayaDagNodeConverter::Description<FromMayaCameraConverter> FromMayaCameraConverter::m_description( MFn::kCamera, CameraTypeId, true ); FromMayaCameraConverter::FromMayaCameraConverter( const MDagPath &dagPath ) : FromMayaDagNodeConverter( "Converts maya camera shape nodes into IECore::Camera objects.", dagPath ) { IntParameter::PresetsContainer resolutionModePresets; resolutionModePresets.push_back( IntParameter::Preset( "renderGlobals", RenderGlobals ) ); resolutionModePresets.push_back( IntParameter::Preset( "specified", Specified ) ); m_resolutionMode = new IntParameter( "resolutionMode", "Determines how the resolution of the camera is decided.", RenderGlobals, RenderGlobals, Specified, resolutionModePresets, true ); parameters()->addParameter( m_resolutionMode ); V2iParameter::PresetsContainer resolutionPresets; resolutionPresets.push_back( V2iParameter::Preset( "2K", Imath::V2i( 2048, 1556 ) ) ); resolutionPresets.push_back( V2iParameter::Preset( "1K", Imath::V2i( 1024, 778 ) ) ); m_resolution = new V2iParameter( "resolution", "Specifies the resolution of the camera when mode is set to \"Specified\".", Imath::V2i( 2048, 1556 ), resolutionPresets ); parameters()->addParameter( m_resolution ); } IECore::ObjectPtr FromMayaCameraConverter::doConversion( const MDagPath &dagPath, IECore::ConstCompoundObjectPtr operands ) const { MFnCamera fnCamera( dagPath ); // convert things that are required by the IECore::Renderer specification CameraPtr result = new Camera; result->setName( IECore::convert<std::string>( fnCamera.name() ) ); result->setTransform( new MatrixTransform( IECore::convert<Imath::M44f>( dagPath.inclusiveMatrix() ) ) ); V2i resolution; if( operands->member<IntData>( "resolutionMode" )->readable()==RenderGlobals ) { MCommonRenderSettingsData renderSettings; MRenderUtil::getCommonRenderSettings( renderSettings ); resolution = Imath::V2i( renderSettings.width, renderSettings.height ); } else { resolution = operands->member<V2iData>( "resolution" )->readable(); } result->parameters()["resolution"] = new V2iData( resolution ); Imath::V2f clippingPlanes = Imath::V2f( fnCamera.nearClippingPlane(), fnCamera.farClippingPlane() ); result->parameters()["clippingPlanes"] = new V2fData( clippingPlanes ); Imath::Box2d frustum; fnCamera.getRenderingFrustum( (float)resolution.x / (float)resolution.y, frustum.min.x, frustum.max.x, frustum.min.y, frustum.max.y ); if( fnCamera.isOrtho() ) { // orthographic result->parameters()["projection"] = new StringData( "orthographic" ); result->parameters()["screenWindow"] = new Box2fData( Box2f( frustum.min, frustum.max ) ); } else { // perspective result->parameters()["projection"] = new StringData( "perspective" ); // derive horizontal field of view from the viewing frustum float horizontalFrustumOffset = frustum.max.x - (frustum.max.x - frustum.min.x) / 2.0f; float fov = Math<double>::atan( (frustum.max.x - horizontalFrustumOffset) / ( clippingPlanes[0] ) ) * 2.0f; fov = radiansToDegrees( fov ); result->parameters()["projection:fov"] = new FloatData( fov ); // scale the frustum so that it's -1,1 in x and that gives us the screen window float frustumScale = 2.0f/(frustum.max.x - frustum.min.x); Box2f screenWindow( V2f( -1 + (horizontalFrustumOffset * frustumScale), frustum.min.y * frustumScale ), V2f( 1 + (horizontalFrustumOffset * frustumScale), frustum.max.y * frustumScale ) ); result->parameters()["screenWindow"] = new Box2fData( screenWindow ); } // and add on other bits and bobs from maya attributes as blind data CompoundDataPtr maya = new CompoundData; result->blindData()->writable()["maya"] = maya; maya->writable()["aperture"] = new V2fData( Imath::V2f( fnCamera.horizontalFilmAperture(), fnCamera.verticalFilmAperture() ) ); return result; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: elementformatter.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: ssmith $ $Date: 2002-10-21 13:17:59 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2002 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "elementformatter.hxx" #ifndef CONFIGMGR_XML_STRINGS_HXX_ #include "xmlstrings.hxx" #endif #ifndef CONFIGMGR_TYPECONVERTER_HXX #include "typeconverter.hxx" #endif #ifndef CONFIGMGR_MISC_ATTRIBUTELIST_HXX #include "attributelist.hxx" #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #include <drafts/com/sun/star/configuration/backend/SchemaAttribute.hpp> #include <drafts/com/sun/star/configuration/backend/NodeAttribute.hpp> // ----------------------------------------------------------------------------- namespace configmgr { // ----------------------------------------------------------------------------- namespace xml { // ----------------------------------------------------------------------------- namespace uno = ::com::sun::star::uno; namespace sax = ::com::sun::star::xml::sax; // ----------------------------------------------------------------------------- ElementFormatter::ElementFormatter() : m_aElementType(ElementType::unknown) , m_xAttributes() { } // ----------------------------------------------------------------------------- ElementFormatter::~ElementFormatter() { } // ----------------------------------------------------------------------------- void ElementFormatter::reset() { m_aElementType = ElementType::unknown; m_xAttributes.clear(); } // ----------------------------------------------------------------------------- void ElementFormatter::addAttribute(OUString const & _anAttributeName, OUString const & _aValue) { OSL_PRECOND(m_xAttributes.is(),"Trying to add an attribute to a non-existing list"); m_xAttributes->addAttribute(_anAttributeName, XML_ATTRTYPE_CDATA, _aValue); } // ----------------------------------------------------------------------------- void ElementFormatter::addAttribute(OUString const & _anAttributeName, bool _bValue) { OSL_PRECOND(m_xAttributes.is(),"Trying to add an attribute to a non-existing list"); m_xAttributes->addAttribute(_anAttributeName, XML_ATTRTYPE_CDATA, _bValue ? ATTR_VALUE_TRUE : ATTR_VALUE_FALSE); } // ----------------------------------------------------------------------------- void ElementFormatter::addNamespaces() { static OUString const sNamespaceDecl( RTL_CONSTASCII_USTRINGPARAM("xmlns:") ); addAttribute( sNamespaceDecl.concat(NS_PREFIX_OOR), static_cast<OUString const &>(NS_URI_OOR)); addAttribute( sNamespaceDecl.concat(NS_PREFIX_XS ), static_cast<OUString const &>(NS_URI_XS )); } // ----------------------------------------------------------------------------- void ElementFormatter::prepareElement(ElementInfo const& _aInfo) { if (!m_xAttributes.is()) { m_xAttributes.set( new AttributeListImpl() ); addNamespaces(); } else m_xAttributes->clear(); m_aElementType = _aInfo.type; addName(_aInfo.name); addNodeFlags(_aInfo.flags); addOperation(_aInfo.op); } // ----------------------------------------------------------------------------- void ElementFormatter::prepareSimpleElement(ElementType::Enum _eType) { if (!m_xAttributes.is()) { m_xAttributes.set( new AttributeListImpl() ); addNamespaces(); } else m_xAttributes->clear(); m_aElementType = _eType; } // ----------------------------------------------------------------------------- void ElementFormatter::addName(OUString const & _aName) { OUString _aContext; OUString _aNodeName; sal_Int32 _aIndex; if ( m_aElementType == ElementType::layer ) { _aIndex = _aName.lastIndexOf ( '.'); if (_aName.getLength()) { _aNodeName = _aName.copy(++_aIndex); addAttribute(ATTR_NAME, _aNodeName); } _aContext = _aName.copy( 0, --_aIndex); addAttribute(ATTR_CONTEXT, _aContext); } else { if (_aName.getLength()) addAttribute(ATTR_NAME, _aName); } } // ----------------------------------------------------------------------------- inline void ElementFormatter::maybeAddFlag(FlagsType _eFlags, FlagsType _eSelect, OUString const & _anAttributeName, bool _bValue) { if (_eFlags & _eSelect) addAttribute(_anAttributeName,_bValue); } // ----------------------------------------------------------------------------- void ElementFormatter::addNodeFlags(FlagsType _eFlags) { using namespace drafts::com::sun::star::configuration::backend;; maybeAddFlag(_eFlags,SchemaAttribute::REQUIRED, ATTR_FLAG_NULLABLE, false); maybeAddFlag(_eFlags,SchemaAttribute::LOCALIZED, ATTR_FLAG_LOCALIZED); maybeAddFlag(_eFlags,SchemaAttribute::EXTENSIBLE, ATTR_FLAG_EXTENSIBLE); maybeAddFlag(_eFlags,NodeAttribute::FINALIZED, ATTR_FLAG_FINALIZED); maybeAddFlag(_eFlags,NodeAttribute::MANDATORY, ATTR_FLAG_MANDATORY); maybeAddFlag(_eFlags,NodeAttribute::READONLY, ATTR_FLAG_READONLY); } // ----------------------------------------------------------------------------- void ElementFormatter::addOperation(Operation::Enum _eOp) { switch (_eOp) { case Operation::none: break; case Operation::modify: break ; //addAttribute(ATTR_OPERATION, static_cast<OUString const &>(OPERATION_MODIFY)); break; case Operation::replace: addAttribute(ATTR_OPERATION, static_cast<OUString const &>(OPERATION_REPLACE)); break; case Operation::remove: addAttribute(ATTR_OPERATION, static_cast<OUString const &>(OPERATION_REMOVE)); break; case Operation::unknown: OSL_ENSURE(false, "ElementFormatter: Trying to add attribute for 'unknown' operation"); break; default: OSL_ENSURE(false, "ElementFormatter: Trying to add attribute for invalid operation"); break; } } // ----------------------------------------------------------------------------- void ElementFormatter::addInstanceType(OUString const & _aElementType, OUString const & _aElementTypeModule) { } // ----------------------------------------------------------------------------- static ::rtl::OUString toXmlTypeName(const uno::TypeClass& _rTypeClass) { ::rtl::OUString aRet; switch(_rTypeClass) { case uno::TypeClass_BOOLEAN: aRet = VALUETYPE_BOOLEAN; break; case uno::TypeClass_SHORT: aRet = VALUETYPE_SHORT; break; case uno::TypeClass_LONG: aRet = VALUETYPE_INT; break; case uno::TypeClass_HYPER: aRet = VALUETYPE_LONG; break; case uno::TypeClass_DOUBLE: aRet = VALUETYPE_DOUBLE; break; case uno::TypeClass_STRING: aRet = VALUETYPE_STRING; break; case uno::TypeClass_SEQUENCE: aRet = VALUETYPE_BINARY; break; case uno::TypeClass_ANY: aRet = VALUETYPE_ANY; break; default: OSL_ENSURE(false,"Cannot get type name: unknown typeclass"); break; } return aRet; } // ----------------------------------------------------------------------------- void ElementFormatter::addPropertyValueType(uno::Type const& _aType) { if (_aType == uno::Type()) return; bool bList = false; uno::Type aSimpleType = getBasicType(_aType, bList); uno::TypeClass aSimpleTypeClass = aSimpleType.getTypeClass(); OUString aSimpleTypeName = toXmlTypeName(aSimpleTypeClass); OUString sNsPrefix = (bList || aSimpleTypeClass == uno::TypeClass_ANY) ? NS_PREFIX_OOR : NS_PREFIX_XS; rtl::OUStringBuffer aTypeNameBuf(sNsPrefix); if (sNsPrefix.getLength()) aTypeNameBuf. append(k_NS_SEPARATOR); aTypeNameBuf. append(aSimpleTypeName); if (bList) aTypeNameBuf. append(VALUETYPE_LIST_SUFFIX); addAttribute( ATTR_VALUETYPE, aTypeNameBuf.makeStringAndClear()); } // ----------------------------------------------------------------------------- void ElementFormatter::addLanguage(OUString const & _sLanguage) { OSL_ENSURE(_sLanguage.getLength(), "ElementFormatter: Trying to add empty language attribute"); addAttribute(EXT_ATTR_LANGUAGE, _sLanguage); } // ----------------------------------------------------------------------------- void ElementFormatter::addIsNull(bool _bIsNull) { addAttribute( EXT_ATTR_NULL, _bIsNull); } // ----------------------------------------------------------------------------- void ElementFormatter::addSeparator(OUString const& _sSeparator) { addAttribute( ATTR_VALUESEPARATOR, _sSeparator); } // ----------------------------------------------------------------------------- OUString ElementFormatter::getElementTag() const { switch (m_aElementType) { case ElementType::schema: return TAG_SCHEMA; case ElementType::layer: return TAG_LAYER; case ElementType::component: return TAG_COMPONENT; case ElementType::templates: return TAG_TEMPLATES; case ElementType::property: return TAG_PROP; case ElementType::node: return TAG_NODE; case ElementType::group: return TAG_GROUP; case ElementType::set: return TAG_SET; case ElementType::import: return TAG_IMPORT; case ElementType::instance: return TAG_INSTANCE; case ElementType::item_type: return TAG_ITEMTYPE; case ElementType::value: return TAG_VALUE; case ElementType::uses: return TAG_USES; case ElementType::unknown: OSL_ENSURE(false, "ElementFormatter: Trying to get Tag for 'unknown' element type"); break; case ElementType::other: OSL_ENSURE(false, "ElementFormatter: Trying to get Tag for 'other' element type"); break; default: OSL_ENSURE(false, "ElementFormatter: Trying to get Tag for invalid element type"); break; } return OUString(); } // ----------------------------------------------------------------------------- uno::Reference< sax::XAttributeList > ElementFormatter::getElementAttributes() const { return m_xAttributes.get(); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- } // namespace } // namespace <commit_msg>#103812# updated root node name format<commit_after>/************************************************************************* * * $RCSfile: elementformatter.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: ssmith $ $Date: 2002-10-21 13:33:56 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2002 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "elementformatter.hxx" #ifndef CONFIGMGR_XML_STRINGS_HXX_ #include "xmlstrings.hxx" #endif #ifndef CONFIGMGR_TYPECONVERTER_HXX #include "typeconverter.hxx" #endif #ifndef CONFIGMGR_MISC_ATTRIBUTELIST_HXX #include "attributelist.hxx" #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #include <drafts/com/sun/star/configuration/backend/SchemaAttribute.hpp> #include <drafts/com/sun/star/configuration/backend/NodeAttribute.hpp> // ----------------------------------------------------------------------------- namespace configmgr { // ----------------------------------------------------------------------------- namespace xml { // ----------------------------------------------------------------------------- namespace uno = ::com::sun::star::uno; namespace sax = ::com::sun::star::xml::sax; // ----------------------------------------------------------------------------- ElementFormatter::ElementFormatter() : m_aElementType(ElementType::unknown) , m_xAttributes() { } // ----------------------------------------------------------------------------- ElementFormatter::~ElementFormatter() { } // ----------------------------------------------------------------------------- void ElementFormatter::reset() { m_aElementType = ElementType::unknown; m_xAttributes.clear(); } // ----------------------------------------------------------------------------- void ElementFormatter::addAttribute(OUString const & _anAttributeName, OUString const & _aValue) { OSL_PRECOND(m_xAttributes.is(),"Trying to add an attribute to a non-existing list"); m_xAttributes->addAttribute(_anAttributeName, XML_ATTRTYPE_CDATA, _aValue); } // ----------------------------------------------------------------------------- void ElementFormatter::addAttribute(OUString const & _anAttributeName, bool _bValue) { OSL_PRECOND(m_xAttributes.is(),"Trying to add an attribute to a non-existing list"); m_xAttributes->addAttribute(_anAttributeName, XML_ATTRTYPE_CDATA, _bValue ? ATTR_VALUE_TRUE : ATTR_VALUE_FALSE); } // ----------------------------------------------------------------------------- void ElementFormatter::addNamespaces() { static OUString const sNamespaceDecl( RTL_CONSTASCII_USTRINGPARAM("xmlns:") ); addAttribute( sNamespaceDecl.concat(NS_PREFIX_OOR), static_cast<OUString const &>(NS_URI_OOR)); addAttribute( sNamespaceDecl.concat(NS_PREFIX_XS ), static_cast<OUString const &>(NS_URI_XS )); } // ----------------------------------------------------------------------------- void ElementFormatter::prepareElement(ElementInfo const& _aInfo) { if (!m_xAttributes.is()) { m_xAttributes.set( new AttributeListImpl() ); addNamespaces(); } else m_xAttributes->clear(); m_aElementType = _aInfo.type; addName(_aInfo.name); addNodeFlags(_aInfo.flags); addOperation(_aInfo.op); } // ----------------------------------------------------------------------------- void ElementFormatter::prepareSimpleElement(ElementType::Enum _eType) { if (!m_xAttributes.is()) { m_xAttributes.set( new AttributeListImpl() ); addNamespaces(); } else m_xAttributes->clear(); m_aElementType = _eType; } // ----------------------------------------------------------------------------- void ElementFormatter::addName(OUString const & _aName) { OUString _aContext; OUString _aNodeName; sal_Int32 _aIndex; if ( m_aElementType == ElementType::layer ) { if (_aName.getLength()) { _aIndex = _aName.lastIndexOf ( '.'); _aNodeName = _aName.copy(++_aIndex); addAttribute(ATTR_NAME, _aNodeName); _aContext = _aName.copy( 0, --_aIndex); addAttribute(ATTR_CONTEXT, _aContext); } } else { if (_aName.getLength()) addAttribute(ATTR_NAME, _aName); } } // ----------------------------------------------------------------------------- inline void ElementFormatter::maybeAddFlag(FlagsType _eFlags, FlagsType _eSelect, OUString const & _anAttributeName, bool _bValue) { if (_eFlags & _eSelect) addAttribute(_anAttributeName,_bValue); } // ----------------------------------------------------------------------------- void ElementFormatter::addNodeFlags(FlagsType _eFlags) { using namespace drafts::com::sun::star::configuration::backend;; maybeAddFlag(_eFlags,SchemaAttribute::REQUIRED, ATTR_FLAG_NULLABLE, false); maybeAddFlag(_eFlags,SchemaAttribute::LOCALIZED, ATTR_FLAG_LOCALIZED); maybeAddFlag(_eFlags,SchemaAttribute::EXTENSIBLE, ATTR_FLAG_EXTENSIBLE); maybeAddFlag(_eFlags,NodeAttribute::FINALIZED, ATTR_FLAG_FINALIZED); maybeAddFlag(_eFlags,NodeAttribute::MANDATORY, ATTR_FLAG_MANDATORY); maybeAddFlag(_eFlags,NodeAttribute::READONLY, ATTR_FLAG_READONLY); } // ----------------------------------------------------------------------------- void ElementFormatter::addOperation(Operation::Enum _eOp) { switch (_eOp) { case Operation::none: break; case Operation::modify: break ; //addAttribute(ATTR_OPERATION, static_cast<OUString const &>(OPERATION_MODIFY)); break; case Operation::replace: addAttribute(ATTR_OPERATION, static_cast<OUString const &>(OPERATION_REPLACE)); break; case Operation::remove: addAttribute(ATTR_OPERATION, static_cast<OUString const &>(OPERATION_REMOVE)); break; case Operation::unknown: OSL_ENSURE(false, "ElementFormatter: Trying to add attribute for 'unknown' operation"); break; default: OSL_ENSURE(false, "ElementFormatter: Trying to add attribute for invalid operation"); break; } } // ----------------------------------------------------------------------------- void ElementFormatter::addInstanceType(OUString const & _aElementType, OUString const & _aElementTypeModule) { } // ----------------------------------------------------------------------------- static ::rtl::OUString toXmlTypeName(const uno::TypeClass& _rTypeClass) { ::rtl::OUString aRet; switch(_rTypeClass) { case uno::TypeClass_BOOLEAN: aRet = VALUETYPE_BOOLEAN; break; case uno::TypeClass_SHORT: aRet = VALUETYPE_SHORT; break; case uno::TypeClass_LONG: aRet = VALUETYPE_INT; break; case uno::TypeClass_HYPER: aRet = VALUETYPE_LONG; break; case uno::TypeClass_DOUBLE: aRet = VALUETYPE_DOUBLE; break; case uno::TypeClass_STRING: aRet = VALUETYPE_STRING; break; case uno::TypeClass_SEQUENCE: aRet = VALUETYPE_BINARY; break; case uno::TypeClass_ANY: aRet = VALUETYPE_ANY; break; default: OSL_ENSURE(false,"Cannot get type name: unknown typeclass"); break; } return aRet; } // ----------------------------------------------------------------------------- void ElementFormatter::addPropertyValueType(uno::Type const& _aType) { if (_aType == uno::Type()) return; bool bList = false; uno::Type aSimpleType = getBasicType(_aType, bList); uno::TypeClass aSimpleTypeClass = aSimpleType.getTypeClass(); OUString aSimpleTypeName = toXmlTypeName(aSimpleTypeClass); OUString sNsPrefix = (bList || aSimpleTypeClass == uno::TypeClass_ANY) ? NS_PREFIX_OOR : NS_PREFIX_XS; rtl::OUStringBuffer aTypeNameBuf(sNsPrefix); if (sNsPrefix.getLength()) aTypeNameBuf. append(k_NS_SEPARATOR); aTypeNameBuf. append(aSimpleTypeName); if (bList) aTypeNameBuf. append(VALUETYPE_LIST_SUFFIX); addAttribute( ATTR_VALUETYPE, aTypeNameBuf.makeStringAndClear()); } // ----------------------------------------------------------------------------- void ElementFormatter::addLanguage(OUString const & _sLanguage) { OSL_ENSURE(_sLanguage.getLength(), "ElementFormatter: Trying to add empty language attribute"); addAttribute(EXT_ATTR_LANGUAGE, _sLanguage); } // ----------------------------------------------------------------------------- void ElementFormatter::addIsNull(bool _bIsNull) { addAttribute( EXT_ATTR_NULL, _bIsNull); } // ----------------------------------------------------------------------------- void ElementFormatter::addSeparator(OUString const& _sSeparator) { addAttribute( ATTR_VALUESEPARATOR, _sSeparator); } // ----------------------------------------------------------------------------- OUString ElementFormatter::getElementTag() const { switch (m_aElementType) { case ElementType::schema: return TAG_SCHEMA; case ElementType::layer: return TAG_LAYER; case ElementType::component: return TAG_COMPONENT; case ElementType::templates: return TAG_TEMPLATES; case ElementType::property: return TAG_PROP; case ElementType::node: return TAG_NODE; case ElementType::group: return TAG_GROUP; case ElementType::set: return TAG_SET; case ElementType::import: return TAG_IMPORT; case ElementType::instance: return TAG_INSTANCE; case ElementType::item_type: return TAG_ITEMTYPE; case ElementType::value: return TAG_VALUE; case ElementType::uses: return TAG_USES; case ElementType::unknown: OSL_ENSURE(false, "ElementFormatter: Trying to get Tag for 'unknown' element type"); break; case ElementType::other: OSL_ENSURE(false, "ElementFormatter: Trying to get Tag for 'other' element type"); break; default: OSL_ENSURE(false, "ElementFormatter: Trying to get Tag for invalid element type"); break; } return OUString(); } // ----------------------------------------------------------------------------- uno::Reference< sax::XAttributeList > ElementFormatter::getElementAttributes() const { return m_xAttributes.get(); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- } // namespace } // namespace <|endoftext|>
<commit_before>/* * CardDeck.cpp * * Created on: 2014年10月25日 * Author: nemo */ #include "CardDeck.h" #include <iostream> CardDeck::CardDeck() { LOG_TRACE("Construct CardDeck.") } CardDeck::~CardDeck() { // TODO Auto-generated destructor stub } /// Insert card into card deck. /** * @brief Insert card into card deck. * * @param card Input card pointer. */ void CardDeck::push_back(Card *card) { _card.push_back(card); } /// Show all card in card deck. void CardDeck::show() { for(auto card :_card) { card->show(); } } <commit_msg>Set auto card in show(0) as const.<commit_after>/* * CardDeck.cpp * * Created on: 2014年10月25日 * Author: nemo */ #include "CardDeck.h" #include <iostream> CardDeck::CardDeck() { LOG_TRACE("Construct CardDeck.") } CardDeck::~CardDeck() { // TODO Auto-generated destructor stub } /// Insert card into card deck. /** * @brief Insert card into card deck. * * @param card Input card pointer. */ void CardDeck::push_back(Card *card) { _card.push_back(card); } /// Show all card in card deck. void CardDeck::show() { for(const auto card :_card) { card->show(); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved. */ #include <assert.h> #include <cstddef> #include <string.h> #include <stdlib.h> extern "C" { #include <ovsdb_wrapper.h> }; #include <oper/agent_sandesh.h> #include <ovsdb_types.h> #include <ovsdb_client_idl.h> #include <ovsdb_client_session.h> #include <ovsdb_route_peer.h> #include <ovsdb_entry.h> #include <physical_switch_ovsdb.h> #include <logical_switch_ovsdb.h> #include <physical_port_ovsdb.h> #include <physical_locator_ovsdb.h> #include <vlan_port_binding_ovsdb.h> #include <unicast_mac_local_ovsdb.h> #include <unicast_mac_remote_ovsdb.h> #include <vm_interface_ksync.h> SandeshTraceBufferPtr OvsdbTraceBuf(SandeshTraceBufferCreate("Ovsdb", 5000)); SandeshTraceBufferPtr OvsdbPktTraceBuf(SandeshTraceBufferCreate("Ovsdb Pkt", 5000)); class PhysicalDeviceTable; class InterfaceTable; class PhysicalDeviceVnTable; using OVSDB::OvsdbClientIdl; using OVSDB::OvsdbClientSession; using OVSDB::OvsdbEntryBase; using OVSDB::VMInterfaceKSyncObject; using OVSDB::PhysicalSwitchTable; using OVSDB::LogicalSwitchTable; using OVSDB::PhysicalPortTable; using OVSDB::PhysicalLocatorTable; using OVSDB::VlanPortBindingTable; using OVSDB::UnicastMacLocalOvsdb; using OVSDB::VrfOvsdbObject; namespace OVSDB { void ovsdb_wrapper_idl_callback(void *idl_base, int op, struct ovsdb_idl_row *row) { OvsdbClientIdl *client_idl = (OvsdbClientIdl *) idl_base; int i = ovsdb_wrapper_row_type(row); if (i >= OvsdbClientIdl::OVSDB_TYPE_COUNT) return; if (client_idl->callback_[i] != NULL) client_idl->callback_[i]((OvsdbClientIdl::Op)op, row); } void ovsdb_wrapper_idl_txn_ack(void *idl_base, struct ovsdb_idl_txn *txn) { OvsdbClientIdl *client_idl = (OvsdbClientIdl *) idl_base; OvsdbEntryBase *entry = client_idl->pending_txn_[txn]; bool success = ovsdb_wrapper_is_txn_success(txn); if (!success) { OVSDB_TRACE(Error, "Transaction failed: " + std::string(ovsdb_wrapper_txn_get_error(txn))); // we don't handle the case where txn fails, when entry is not present // case of unicast_mac_remote entry. assert(entry != NULL); } client_idl->DeleteTxn(txn); if (entry) entry->Ack(success); } }; OvsdbClientIdl::OvsdbClientIdl(OvsdbClientSession *session, Agent *agent, OvsPeerManager *manager) : idl_(ovsdb_wrapper_idl_create()), session_(session), agent_(agent), pending_txn_() { vtep_global_= ovsdb_wrapper_vteprec_global_first(idl_); ovsdb_wrapper_idl_set_callback(idl_, (void *)this, ovsdb_wrapper_idl_callback, ovsdb_wrapper_idl_txn_ack); parser_ = NULL; for (int i = 0; i < OVSDB_TYPE_COUNT; i++) { callback_[i] = NULL; } route_peer_.reset(manager->Allocate(IpAddress())); vm_interface_table_.reset(new VMInterfaceKSyncObject(this, (DBTable *)agent->interface_table())); physical_switch_table_.reset(new PhysicalSwitchTable(this)); logical_switch_table_.reset(new LogicalSwitchTable(this, (DBTable *)agent->physical_device_vn_table())); physical_port_table_.reset(new PhysicalPortTable(this)); physical_locator_table_.reset(new PhysicalLocatorTable(this)); vlan_port_table_.reset(new VlanPortBindingTable(this, (DBTable *)agent->interface_table())); unicast_mac_local_ovsdb_.reset(new UnicastMacLocalOvsdb(this, route_peer())); vrf_ovsdb_.reset(new VrfOvsdbObject(this, (DBTable *)agent->vrf_table())); } OvsdbClientIdl::~OvsdbClientIdl() { ovsdb_wrapper_idl_destroy(idl_); } void OvsdbClientIdl::SendMointorReq() { OVSDB_TRACE(Trace, "Sending Monitor Request"); SendJsonRpc(ovsdb_wrapper_idl_encode_monitor_request(idl_)); } void OvsdbClientIdl::SendJsonRpc(struct jsonrpc_msg *msg) { struct json *json_msg = ovsdb_wrapper_jsonrpc_msg_to_json(msg); char *s = ovsdb_wrapper_json_to_string(json_msg, 0); ovsdb_wrapper_json_destroy(json_msg); session_->SendMsg((u_int8_t *)s, strlen(s)); } void OvsdbClientIdl::MessageProcess(const u_int8_t *buf, std::size_t len) { std::size_t used = 0; // Multiple json message may be clubbed together, need to keep reading // the buffer till whole message is consumed. while (used != len) { if (parser_ == NULL) { parser_ = ovsdb_wrapper_json_parser_create(0); } const u_int8_t *pkt = buf + used; std::size_t pkt_len = len - used; std::size_t read; read = ovsdb_wrapper_json_parser_feed(parser_, (const char *)pkt, pkt_len); OVSDB_PKT_TRACE(Trace, "Processed: " + std::string((const char *)pkt, read)); used +=read; /* If we have complete JSON, attempt to parse it as JSON-RPC. */ if (ovsdb_wrapper_json_parser_is_done(parser_)) { struct json *json = ovsdb_wrapper_json_parser_finish(parser_); parser_ = NULL; struct jsonrpc_msg *msg; char *error = ovsdb_wrapper_jsonrpc_msg_from_json(json, &msg); if (error) { assert(0); free(error); //continue; } if (ovsdb_wrapper_msg_echo_req(msg)) { /* Echo request. Send reply. */ struct jsonrpc_msg *reply; reply = ovsdb_wrapper_jsonrpc_create_reply(msg); SendJsonRpc(reply); //jsonrpc_session_send(s, reply); } else if (ovsdb_wrapper_msg_echo_reply(msg)) { /* It's a reply to our echo request. Suppress it. */ } else { ovsdb_wrapper_idl_msg_process(idl_, msg); continue; } ovsdb_wrapper_jsonrpc_msg_destroy(msg); } } } struct ovsdb_idl_txn *OvsdbClientIdl::CreateTxn(OvsdbEntryBase *entry) { struct ovsdb_idl_txn *txn = ovsdb_wrapper_idl_txn_create(idl_); pending_txn_[txn] = entry; return txn; } void OvsdbClientIdl::DeleteTxn(struct ovsdb_idl_txn *txn) { pending_txn_.erase(txn); ovsdb_wrapper_idl_txn_destroy(txn); } Ip4Address OvsdbClientIdl::tsn_ip() { return session_->tsn_ip(); } KSyncObjectManager *OvsdbClientIdl::ksync_obj_manager() { return session_->ksync_obj_manager(); } OvsPeer *OvsdbClientIdl::route_peer() { return route_peer_.get(); } VMInterfaceKSyncObject *OvsdbClientIdl::vm_interface_table() { return vm_interface_table_.get(); } PhysicalSwitchTable *OvsdbClientIdl::physical_switch_table() { return physical_switch_table_.get(); } LogicalSwitchTable *OvsdbClientIdl::logical_switch_table() { return logical_switch_table_.get(); } PhysicalPortTable *OvsdbClientIdl::physical_port_table() { return physical_port_table_.get(); } PhysicalLocatorTable *OvsdbClientIdl::physical_locator_table() { return physical_locator_table_.get(); } VlanPortBindingTable *OvsdbClientIdl::vlan_port_table() { return vlan_port_table_.get(); } UnicastMacLocalOvsdb *OvsdbClientIdl::unicast_mac_local_ovsdb() { return unicast_mac_local_ovsdb_.get(); } VrfOvsdbObject *OvsdbClientIdl::vrf_ovsdb() { return vrf_ovsdb_.get(); } <commit_msg>fix memory leak, while doing ovs send.<commit_after>/* * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved. */ #include <assert.h> #include <cstddef> #include <string.h> #include <stdlib.h> extern "C" { #include <ovsdb_wrapper.h> }; #include <oper/agent_sandesh.h> #include <ovsdb_types.h> #include <ovsdb_client_idl.h> #include <ovsdb_client_session.h> #include <ovsdb_route_peer.h> #include <ovsdb_entry.h> #include <physical_switch_ovsdb.h> #include <logical_switch_ovsdb.h> #include <physical_port_ovsdb.h> #include <physical_locator_ovsdb.h> #include <vlan_port_binding_ovsdb.h> #include <unicast_mac_local_ovsdb.h> #include <unicast_mac_remote_ovsdb.h> #include <vm_interface_ksync.h> SandeshTraceBufferPtr OvsdbTraceBuf(SandeshTraceBufferCreate("Ovsdb", 5000)); SandeshTraceBufferPtr OvsdbPktTraceBuf(SandeshTraceBufferCreate("Ovsdb Pkt", 5000)); class PhysicalDeviceTable; class InterfaceTable; class PhysicalDeviceVnTable; using OVSDB::OvsdbClientIdl; using OVSDB::OvsdbClientSession; using OVSDB::OvsdbEntryBase; using OVSDB::VMInterfaceKSyncObject; using OVSDB::PhysicalSwitchTable; using OVSDB::LogicalSwitchTable; using OVSDB::PhysicalPortTable; using OVSDB::PhysicalLocatorTable; using OVSDB::VlanPortBindingTable; using OVSDB::UnicastMacLocalOvsdb; using OVSDB::VrfOvsdbObject; namespace OVSDB { void ovsdb_wrapper_idl_callback(void *idl_base, int op, struct ovsdb_idl_row *row) { OvsdbClientIdl *client_idl = (OvsdbClientIdl *) idl_base; int i = ovsdb_wrapper_row_type(row); if (i >= OvsdbClientIdl::OVSDB_TYPE_COUNT) return; if (client_idl->callback_[i] != NULL) client_idl->callback_[i]((OvsdbClientIdl::Op)op, row); } void ovsdb_wrapper_idl_txn_ack(void *idl_base, struct ovsdb_idl_txn *txn) { OvsdbClientIdl *client_idl = (OvsdbClientIdl *) idl_base; OvsdbEntryBase *entry = client_idl->pending_txn_[txn]; bool success = ovsdb_wrapper_is_txn_success(txn); if (!success) { OVSDB_TRACE(Error, "Transaction failed: " + std::string(ovsdb_wrapper_txn_get_error(txn))); // we don't handle the case where txn fails, when entry is not present // case of unicast_mac_remote entry. assert(entry != NULL); } client_idl->DeleteTxn(txn); if (entry) entry->Ack(success); } }; OvsdbClientIdl::OvsdbClientIdl(OvsdbClientSession *session, Agent *agent, OvsPeerManager *manager) : idl_(ovsdb_wrapper_idl_create()), session_(session), agent_(agent), pending_txn_() { vtep_global_= ovsdb_wrapper_vteprec_global_first(idl_); ovsdb_wrapper_idl_set_callback(idl_, (void *)this, ovsdb_wrapper_idl_callback, ovsdb_wrapper_idl_txn_ack); parser_ = NULL; for (int i = 0; i < OVSDB_TYPE_COUNT; i++) { callback_[i] = NULL; } route_peer_.reset(manager->Allocate(IpAddress())); vm_interface_table_.reset(new VMInterfaceKSyncObject(this, (DBTable *)agent->interface_table())); physical_switch_table_.reset(new PhysicalSwitchTable(this)); logical_switch_table_.reset(new LogicalSwitchTable(this, (DBTable *)agent->physical_device_vn_table())); physical_port_table_.reset(new PhysicalPortTable(this)); physical_locator_table_.reset(new PhysicalLocatorTable(this)); vlan_port_table_.reset(new VlanPortBindingTable(this, (DBTable *)agent->interface_table())); unicast_mac_local_ovsdb_.reset(new UnicastMacLocalOvsdb(this, route_peer())); vrf_ovsdb_.reset(new VrfOvsdbObject(this, (DBTable *)agent->vrf_table())); } OvsdbClientIdl::~OvsdbClientIdl() { ovsdb_wrapper_idl_destroy(idl_); } void OvsdbClientIdl::SendMointorReq() { OVSDB_TRACE(Trace, "Sending Monitor Request"); SendJsonRpc(ovsdb_wrapper_idl_encode_monitor_request(idl_)); } void OvsdbClientIdl::SendJsonRpc(struct jsonrpc_msg *msg) { struct json *json_msg = ovsdb_wrapper_jsonrpc_msg_to_json(msg); char *s = ovsdb_wrapper_json_to_string(json_msg, 0); ovsdb_wrapper_json_destroy(json_msg); session_->SendMsg((u_int8_t *)s, strlen(s)); // release the memory allocated by ovsdb_wrapper_json_to_string free(s); } void OvsdbClientIdl::MessageProcess(const u_int8_t *buf, std::size_t len) { std::size_t used = 0; // Multiple json message may be clubbed together, need to keep reading // the buffer till whole message is consumed. while (used != len) { if (parser_ == NULL) { parser_ = ovsdb_wrapper_json_parser_create(0); } const u_int8_t *pkt = buf + used; std::size_t pkt_len = len - used; std::size_t read; read = ovsdb_wrapper_json_parser_feed(parser_, (const char *)pkt, pkt_len); OVSDB_PKT_TRACE(Trace, "Processed: " + std::string((const char *)pkt, read)); used +=read; /* If we have complete JSON, attempt to parse it as JSON-RPC. */ if (ovsdb_wrapper_json_parser_is_done(parser_)) { struct json *json = ovsdb_wrapper_json_parser_finish(parser_); parser_ = NULL; struct jsonrpc_msg *msg; char *error = ovsdb_wrapper_jsonrpc_msg_from_json(json, &msg); if (error) { assert(0); free(error); //continue; } if (ovsdb_wrapper_msg_echo_req(msg)) { /* Echo request. Send reply. */ struct jsonrpc_msg *reply; reply = ovsdb_wrapper_jsonrpc_create_reply(msg); SendJsonRpc(reply); //jsonrpc_session_send(s, reply); } else if (ovsdb_wrapper_msg_echo_reply(msg)) { /* It's a reply to our echo request. Suppress it. */ } else { ovsdb_wrapper_idl_msg_process(idl_, msg); continue; } ovsdb_wrapper_jsonrpc_msg_destroy(msg); } } } struct ovsdb_idl_txn *OvsdbClientIdl::CreateTxn(OvsdbEntryBase *entry) { struct ovsdb_idl_txn *txn = ovsdb_wrapper_idl_txn_create(idl_); pending_txn_[txn] = entry; return txn; } void OvsdbClientIdl::DeleteTxn(struct ovsdb_idl_txn *txn) { pending_txn_.erase(txn); ovsdb_wrapper_idl_txn_destroy(txn); } Ip4Address OvsdbClientIdl::tsn_ip() { return session_->tsn_ip(); } KSyncObjectManager *OvsdbClientIdl::ksync_obj_manager() { return session_->ksync_obj_manager(); } OvsPeer *OvsdbClientIdl::route_peer() { return route_peer_.get(); } VMInterfaceKSyncObject *OvsdbClientIdl::vm_interface_table() { return vm_interface_table_.get(); } PhysicalSwitchTable *OvsdbClientIdl::physical_switch_table() { return physical_switch_table_.get(); } LogicalSwitchTable *OvsdbClientIdl::logical_switch_table() { return logical_switch_table_.get(); } PhysicalPortTable *OvsdbClientIdl::physical_port_table() { return physical_port_table_.get(); } PhysicalLocatorTable *OvsdbClientIdl::physical_locator_table() { return physical_locator_table_.get(); } VlanPortBindingTable *OvsdbClientIdl::vlan_port_table() { return vlan_port_table_.get(); } UnicastMacLocalOvsdb *OvsdbClientIdl::unicast_mac_local_ovsdb() { return unicast_mac_local_ovsdb_.get(); } VrfOvsdbObject *OvsdbClientIdl::vrf_ovsdb() { return vrf_ovsdb_.get(); } <|endoftext|>
<commit_before>#include "Genes/Pawn_Advancement_Gene.h" #include <string> #include <memory> #include "Genes/Gene.h" #include "Game/Board.h" #include "Pieces/Piece.h" double Pawn_Advancement_Gene::score_board(const Board& board) const { double score = 0.0; auto perspective = board.whose_turn(); int home_rank = (perspective == WHITE ? 2 : 7); for(char file = 'a'; file <= 'h'; ++file) { for(int rank = 1; rank <= 8; ++rank) { auto piece = board.piece_on_square(file, rank); if(piece && piece->color() == perspective && piece->is_pawn()) { // 1 point per move towards promotion score += std::abs(home_rank - rank); } } } // Count pawn promotions const auto& move_list = board.get_game_record(); for(size_t i = (perspective == board.first_to_move() ? 0 : 1); i < move_list.size(); i += 2) { if(move_list[i]->promotion_piece()) { score += 6; // pawn made it to last rank } } return score/(8*6); // normalize to 8 pawns 6 ranks from home (promotion rank) } std::unique_ptr<Gene> Pawn_Advancement_Gene::duplicate() const { return std::make_unique<Pawn_Advancement_Gene>(*this); } std::string Pawn_Advancement_Gene::name() const { return "Pawn Advancement Gene"; } <commit_msg>Save work in Pawn Advancement Gene<commit_after>#include "Genes/Pawn_Advancement_Gene.h" #include <string> #include <memory> #include "Genes/Gene.h" #include "Game/Board.h" #include "Pieces/Piece.h" double Pawn_Advancement_Gene::score_board(const Board& board) const { double score = 0.0; auto perspective = board.whose_turn(); int home_rank = (perspective == WHITE ? 2 : 7); for(char file = 'a'; file <= 'h'; ++file) { for(int rank = 2; rank <= 7; ++rank) { auto piece = board.piece_on_square(file, rank); if(piece && piece->color() == perspective && piece->is_pawn()) { // 1 point per move towards promotion score += std::abs(home_rank - rank); } } } // Count pawn promotions const auto& move_list = board.get_game_record(); for(size_t i = (perspective == board.first_to_move() ? 0 : 1); i < move_list.size(); i += 2) { if(move_list[i]->promotion_piece()) { score += 6; // pawn made it to last rank } } return score/(8*6); // normalize to 8 pawns 6 ranks from home (promotion rank) } std::unique_ptr<Gene> Pawn_Advancement_Gene::duplicate() const { return std::make_unique<Pawn_Advancement_Gene>(*this); } std::string Pawn_Advancement_Gene::name() const { return "Pawn Advancement Gene"; } <|endoftext|>
<commit_before> /*! \file \author Igor Mironchik (igor.mironchik at gmail dot com). Copyright (c) 2014 Igor Mironchik 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. */ // Qt include. #include <QObject> #include <QtTest/QtTest> #include <QSharedPointer> // QtMWidgets include. #include <QtMWidgets/PageControl> #include <QtMWidgets/FingerGeometry> class TestPageControl : public QObject { Q_OBJECT private slots: void initTestCase() { m_btnSize = QtMWidgets::FingerGeometry::width() * 0.3 / 2 * 3; } void testBusy() { QtMWidgets::PageControl p; p.resize( m_btnSize * 3, m_btnSize * 4 ); p.show(); QVERIFY( QTest::qWaitForWindowActive( &p ) ); p.setPageIndicatorColor( Qt::red ); p.setCurrentPageIndicatorColor( Qt::red ); QVERIFY( p.pageIndicatorColor() == Qt::red ); QVERIFY( p.currentPageIndicatorColor() == Qt::red ); p.setCount( 10 ); p.setCurrentIndex( 4 ); QVERIFY( p.count() == 10 ); QVERIFY( p.currentIndex() == 4 ); QTest::mouseClick( &p, Qt::LeftButton, {}, QRect( 0, 0, m_btnSize, m_btnSize ).center(), 20 ); QVERIFY( p.currentIndex() == 0 ); p.resize( m_btnSize * 5, m_btnSize * 2 ); QTest::qWait( 50 ); QSignalSpy spy( &p, &QtMWidgets::PageControl::currentChanged ); QTest::mouseClick( &p, Qt::LeftButton, {}, QRect( m_btnSize * 4, 0, m_btnSize, m_btnSize ).center(), 20 ); QVERIFY( p.currentIndex() == 4 ); QVERIFY( spy.count() == 1 ); } private: int m_btnSize; }; QTEST_MAIN( TestPageControl ) #include "main.moc" <commit_msg>Fix test.<commit_after> /*! \file \author Igor Mironchik (igor.mironchik at gmail dot com). Copyright (c) 2014 Igor Mironchik 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. */ // Qt include. #include <QObject> #include <QtTest/QtTest> #include <QSharedPointer> // QtMWidgets include. #include <QtMWidgets/PageControl> #include <QtMWidgets/FingerGeometry> class TestPageControl : public QObject { Q_OBJECT private slots: void initTestCase() { m_btnSize = QtMWidgets::FingerGeometry::width() * 0.3 / 2 * 3; } void testBusy() { QtMWidgets::PageControl p; p.resize( m_btnSize * 3, m_btnSize * 4 ); p.show(); QVERIFY( QTest::qWaitForWindowActive( &p ) ); p.setPageIndicatorColor( Qt::red ); p.setCurrentPageIndicatorColor( Qt::red ); QVERIFY( p.pageIndicatorColor() == Qt::red ); QVERIFY( p.currentPageIndicatorColor() == Qt::red ); p.setCount( 10 ); p.setCurrentIndex( 4 ); QVERIFY( p.count() == 10 ); QVERIFY( p.currentIndex() == 4 ); QTest::mouseClick( &p, Qt::LeftButton, {}, QRect( ( p.width() - m_btnSize * 3 ) / 2, 0, m_btnSize, m_btnSize ).center(), 20 ); QVERIFY( p.currentIndex() == 0 ); p.resize( m_btnSize * 5, m_btnSize * 2 ); QTest::qWait( 50 ); QSignalSpy spy( &p, &QtMWidgets::PageControl::currentChanged ); QTest::mouseClick( &p, Qt::LeftButton, {}, QRect( ( p.width() - m_btnSize * 5 ) / 2 + m_btnSize * 4, 0, m_btnSize, m_btnSize ).center(), 20 ); QVERIFY( p.currentIndex() == 4 ); QVERIFY( spy.count() == 1 ); } private: int m_btnSize; }; QTEST_MAIN( TestPageControl ) #include "main.moc" <|endoftext|>
<commit_before>// Copyright (c) 2014-2017 Michael J. Sullivan // Use of this source code is governed by an MIT-style license that can be // found in the LICENSE file. #ifndef QSPINLOCK_SC_H #define QSPINLOCK_SC_H #include <rmc++.h> #include <utility> #include "tagged_ptr.hpp" #define CLEAR_RMW 1 namespace rmclib { // This is based on "MCS locks" and linux's qspinlocks. The key idea // here, and the reason for the extra complication relative to // ticket-taking spinlocks, is that different threads can spin-wait on // different locations, reducing cache contention. //// BEGIN SNIP class QSpinLock { //// END SNIP // This should be yield() or cpu_relax() or something void delay() { } // Aligned to 256 so the CLEAR_BYTE_WRITE trick can work. //// BEGIN SNIP struct alignas(256) Node { using Ptr = tagged_ptr<Node *>; rmc::atomic<Node *> next{nullptr}; rmc::atomic<bool> ready{false}; }; rmc::atomic<Node::Ptr> tail_; //// END SNIP void clearLowBit(rmc::atomic<Node::Ptr> &loc) { // We want to just xadd(-1) the thing, but C++ doesn't let us // because of the level of obstruction^Wabstraction that // tagged_ptr adds. // // Or maybe what we want to do is to align Node on 256 boundaries // so that we can do a one byte write to clear the locked flag. // That is *especially* not a thing in the C++ memory model. #if CLEAR_RMW // This is probably undefined auto &intloc = reinterpret_cast<rmc::atomic<uintptr_t> &>(loc); intloc.fetch_and(~Node::Ptr::kTagBits); #elif CLEAR_BYTE_WRITE // This is certainly undefined, and only works on little endian. // C++ really does not have any story for mixed-size atomics // and mixed-size atomics are pretty funky in practice. // Linux does do this on some platforms, though. auto &byteloc = reinterpret_cast<rmc::atomic<uint8_t> &>(loc); byteloc = 0; #else Node::Ptr state(nullptr, 1); while (!loc.compare_exchange_weak(state, Node::Ptr(state, 0))) { } #endif } //// BEGIN SNIP void slowpathLock(Node::Ptr oldTail) { // makes sure that init of me.next is prior to tail_link in // other thread VEDGE(node_init, enqueue); // init of me needs to be done before publishing it to // previous thread also VEDGE(node_init, tail_link); // Can't write self into previous node until we have read out // the correct previous node (which we do while enqueueing). XEDGE(enqueue, tail_link); LS(node_init, Node me); Node::Ptr curTail; bool newThreads; // Step one, put ourselves at the back of the queue for (;;) { Node::Ptr newTail = Node::Ptr(&me, oldTail.tag()); // Enqueue ourselves... if (L(enqueue, tail_.compare_exchange_strong(oldTail, newTail))) break; // OK, maybe the whole thing is just unlocked now? if (oldTail == Node::Ptr(nullptr, 0)) { // If so, just try to take the lock and be done. if (tail_.compare_exchange_strong( oldTail, Node::Ptr(nullptr, 1))) goto out; } } // Need to make sure not to compete for the lock before the // right time. This makes sure the ordering doesn't get messed // up. XEDGE(ready_wait, lock); // Step two: OK, there is an actual queue, so link up with the old // tail and wait until we are at the head of the queue if (oldTail.ptr()) { // * Writing into the oldTail is safe because threads can't // leave unless there is no thread after them or they have // marked the next ready L(tail_link, oldTail->next = &me); while (!L(ready_wait, me.ready)) delay(); } // Step three: wait until the lock is freed // We don't need a a constraint from this load; "lock" serves // to handle this just fine: lock can't succeed until we've // read an unlocked tail_. while ((curTail = tail_).tag()) { delay(); } // Our lock acquisition needs to be finished before we give the // next thread a chance to try to acquire the lock or it could // compete with us for it, causing trouble. VEDGE(lock, signal_next); // Step four: take the lock for (;;) { assert_eq(curTail.tag(), 0); assert_ne(curTail.ptr(), nullptr); newThreads = curTail.ptr() != &me; // If there aren't any waiters after us, the queue is // empty. Otherwise, keep the old tail. Node *newTailP = newThreads ? curTail : nullptr; Node::Ptr newTail = Node::Ptr(newTailP, 1); // This can fail if new threads add themselves to the // queue. However, nobody else can actually *take* the // lock, so we'll succeed quickly. if (L(lock, tail_.compare_exchange_strong(curTail, newTail))) break; } // Step five: now that we have the lock, if any threads came // in after us, indicate to the next one that it is at the // head of the queue if (newThreads) { // Next thread might not have written itself in, yet, // so we have to wait. // Waiting for threads *after* you in the queue kind of // offends me, to be honest. Node *next; XEDGE(load_next, signal_next); while (!L(load_next, next = me.next)) delay(); L(signal_next, next->ready = true); } out: return; } public: void lock() { XEDGE(lock, out); // If the lock is unlocked and has no waiters, we can acquire // it with no fanfare. Otherwise we need to fall back to the // slow path. Node::Ptr unlocked(nullptr, 0); if (!L(lock, tail_.compare_exchange_strong(unlocked, Node::Ptr(nullptr, 1)))){ LS(lock, slowpathLock(unlocked)); } LPOST(out); } void unlock() { VEDGE(pre, unlock); LS(unlock, clearLowBit(tail_)); } }; //// END SNIP } #endif <commit_msg>rename a label<commit_after>// Copyright (c) 2014-2017 Michael J. Sullivan // Use of this source code is governed by an MIT-style license that can be // found in the LICENSE file. #ifndef QSPINLOCK_SC_H #define QSPINLOCK_SC_H #include <rmc++.h> #include <utility> #include "tagged_ptr.hpp" #define CLEAR_RMW 1 namespace rmclib { // This is based on "MCS locks" and linux's qspinlocks. The key idea // here, and the reason for the extra complication relative to // ticket-taking spinlocks, is that different threads can spin-wait on // different locations, reducing cache contention. //// BEGIN SNIP class QSpinLock { //// END SNIP // This should be yield() or cpu_relax() or something void delay() { } // Aligned to 256 so the CLEAR_BYTE_WRITE trick can work. //// BEGIN SNIP struct alignas(256) Node { using Ptr = tagged_ptr<Node *>; rmc::atomic<Node *> next{nullptr}; rmc::atomic<bool> ready{false}; }; rmc::atomic<Node::Ptr> tail_; //// END SNIP void clearLowBit(rmc::atomic<Node::Ptr> &loc) { // We want to just xadd(-1) the thing, but C++ doesn't let us // because of the level of obstruction^Wabstraction that // tagged_ptr adds. // // Or maybe what we want to do is to align Node on 256 boundaries // so that we can do a one byte write to clear the locked flag. // That is *especially* not a thing in the C++ memory model. #if CLEAR_RMW // This is probably undefined auto &intloc = reinterpret_cast<rmc::atomic<uintptr_t> &>(loc); intloc.fetch_and(~Node::Ptr::kTagBits); #elif CLEAR_BYTE_WRITE // This is certainly undefined, and only works on little endian. // C++ really does not have any story for mixed-size atomics // and mixed-size atomics are pretty funky in practice. // Linux does do this on some platforms, though. auto &byteloc = reinterpret_cast<rmc::atomic<uint8_t> &>(loc); byteloc = 0; #else Node::Ptr state(nullptr, 1); while (!loc.compare_exchange_weak(state, Node::Ptr(state, 0))) { } #endif } //// BEGIN SNIP void slowpathLock(Node::Ptr oldTail) { // makes sure that init of me.next is prior to tail_link in // other thread VEDGE(node_init, enqueue); // init of me needs to be done before publishing it to // previous thread also VEDGE(node_init, tail_link); // Can't write self into previous node until we have read out // the correct previous node (which we do while enqueueing). XEDGE(enqueue, tail_link); LS(node_init, Node me); Node::Ptr curTail; bool newThreads; // Step one, put ourselves at the back of the queue for (;;) { Node::Ptr newTail = Node::Ptr(&me, oldTail.tag()); // Enqueue ourselves... if (L(enqueue, tail_.compare_exchange_strong(oldTail, newTail))) break; // OK, maybe the whole thing is just unlocked now? if (oldTail == Node::Ptr(nullptr, 0)) { // If so, just try to take the lock and be done. if (tail_.compare_exchange_strong( oldTail, Node::Ptr(nullptr, 1))) goto out; } } // Need to make sure not to compete for the lock before the // right time. This makes sure the ordering doesn't get messed // up. XEDGE(ready_wait, lock); // Step two: OK, there is an actual queue, so link up with the old // tail and wait until we are at the head of the queue if (oldTail.ptr()) { // * Writing into the oldTail is safe because threads can't // leave unless there is no thread after them or they have // marked the next ready L(tail_link, oldTail->next = &me); while (!L(ready_wait, me.ready)) delay(); } // Step three: wait until the lock is freed // We don't need a a constraint from this load; "lock" serves // to handle this just fine: lock can't succeed until we've // read an unlocked tail_. while ((curTail = tail_).tag()) { delay(); } // Our lock acquisition needs to be finished before we give the // next thread a chance to try to acquire the lock or it could // compete with us for it, causing trouble. VEDGE(lock, signal_next); // Step four: take the lock for (;;) { assert_eq(curTail.tag(), 0); assert_ne(curTail.ptr(), nullptr); newThreads = curTail.ptr() != &me; // If there aren't any waiters after us, the queue is // empty. Otherwise, keep the old tail. Node *newTailP = newThreads ? curTail : nullptr; Node::Ptr newTail = Node::Ptr(newTailP, 1); // This can fail if new threads add themselves to the // queue. However, nobody else can actually *take* the // lock, so we'll succeed quickly. if (L(lock, tail_.compare_exchange_strong(curTail, newTail))) break; } // Step five: now that we have the lock, if any threads came // in after us, indicate to the next one that it is at the // head of the queue if (newThreads) { // Next thread might not have written itself in, yet, // so we have to wait. // Waiting for threads *after* you in the queue kind of // offends me, to be honest. Node *next; XEDGE(load_next, signal_next); while (!L(load_next, next = me.next)) delay(); L(signal_next, next->ready = true); } out: return; } public: void lock() { XEDGE(lock, body); // If the lock is unlocked and has no waiters, we can acquire // it with no fanfare. Otherwise we need to fall back to the // slow path. Node::Ptr unlocked(nullptr, 0); if (!L(lock, tail_.compare_exchange_strong(unlocked, Node::Ptr(nullptr, 1)))){ LS(lock, slowpathLock(unlocked)); } LPOST(body); } void unlock() { VEDGE(pre, unlock); LS(unlock, clearLowBit(tail_)); } }; //// END SNIP } #endif <|endoftext|>
<commit_before>// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #include "targetver.hpp" #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: // #include <windows.h> #include <SFML/Window.hpp> #include <SFML/Graphics.hpp> #include <SFML/OpenGL.hpp> #include <vector> #include "BaseBlock.hpp" #include "Block.hpp" #include "Blocks/BlockI.hpp" #include "Blocks/BlockJ.hpp" #include "Blocks/BlockL.hpp" #include "Blocks/BlockO.hpp" #include "Blocks/BlockS.hpp" #include "Blocks/BlockT.hpp" #include "Blocks/BlockZ.hpp" #include "BlockChooser.hpp" #include "Field.hpp" <commit_msg>Izmantot GLM matemātikas bibliotēku<commit_after>// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #include "targetver.hpp" #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: // #include <windows.h> #define GLM_FORCE_RADIANS #include <glm/fwd.hpp> #include <glm/common.hpp> #include <glm/matrix.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <SFML/Window.hpp> #include <SFML/Graphics.hpp> #include <SFML/OpenGL.hpp> #include <vector> #include "BaseBlock.hpp" #include "Block.hpp" #include "Blocks/BlockI.hpp" #include "Blocks/BlockJ.hpp" #include "Blocks/BlockL.hpp" #include "Blocks/BlockO.hpp" #include "Blocks/BlockS.hpp" #include "Blocks/BlockT.hpp" #include "Blocks/BlockZ.hpp" #include "BlockChooser.hpp" #include "Field.hpp" <|endoftext|>
<commit_before>//===-- DynamicLinker.cpp - Implement DynamicLinker interface -------------===// // // 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. // //===----------------------------------------------------------------------===// // // Lightweight interface to dynamic library linking and loading, and dynamic // symbol lookup functionality, in whatever form the operating system // provides it. // // Possible future extensions include support for the HPUX shl_load() // interface, the Mac OS X NSLinkModule() interface, and the Windows // LoadLibrary() interface. // // Note that we assume that if dlopen() is available, then dlsym() is too. // //===----------------------------------------------------------------------===// #include "Support/DynamicLinker.h" #include "Config/dlfcn.h" #include "Config/windows.h" #include <cassert> using namespace llvm; bool llvm::LinkDynamicObject (const char *filename, std::string *ErrorMessage) { #if defined (HAVE_DLOPEN) if (dlopen (filename, RTLD_NOW | RTLD_GLOBAL) == 0) { if (ErrorMessage) *ErrorMessage = dlerror (); return true; } return false; #elif defined(HAVE_WINDOWS_H) if (LoadLibrary(filename)) return false; if (ErrorMessage) { char Buffer[100]; // FIXME: This should use FormatMessage sprintf(Buffer, "Windows error code %d\n", GetLastError()); *ErrorMessage = Buffer; } return true; #else assert (0 && "Dynamic object linking not implemented for this platform"); #endif } void *llvm::GetAddressOfSymbol (const char *symbolName) { #if defined (HAVE_DLOPEN) # ifdef RTLD_DEFAULT return dlsym (RTLD_DEFAULT, symbolName); # else static void* CurHandle = dlopen(0, RTLD_LAZY); return dlsym(CurHandle, symbolName); # endif #elif defined(HAVE_WINDOWS_H) static HMODULE ModHandle = NULL; if (ModHandle == 0) ModHandle = GetModuleHandle(NULL); return (void*)GetProcAddress(ModHandle, symbolName); #else assert (0 && "Dynamic symbol lookup not implemented for this platform"); #endif } // soft, cushiony C++ interface. void *llvm::GetAddressOfSymbol(const std::string &symbolName) { return GetAddressOfSymbol(symbolName.c_str()); } <commit_msg>Thoroughly rehack the dynamic linking mechanisms on Win32. The Win32 dynamic linker does not automatically search libraries when looking up symbols with GetProcAddress. Because of this we have to emulate it. The only detail is that there doesn't seem to be a way to enumerate the libraries loaded, so we have a gross hack (tm).<commit_after>//===-- DynamicLinker.cpp - Implement DynamicLinker interface -------------===// // // 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. // //===----------------------------------------------------------------------===// // // Lightweight interface to dynamic library linking and loading, and dynamic // symbol lookup functionality, in whatever form the operating system // provides it. // // Possible future extensions include support for the HPUX shl_load() // interface, and the Mac OS X NSLinkModule() interface. // // Note that we assume that if dlopen() is available, then dlsym() is too. // //===----------------------------------------------------------------------===// #include "Support/DynamicLinker.h" #include "Config/dlfcn.h" #include "Config/windows.h" #include <cassert> #include <vector> using namespace llvm; #if defined(HAVE_WINDOWS_H) // getLoadedLibs - Keep track of the shared objects that are loaded into the // process address space, as the windows GetProcAddress function does not // automatically search an entire address space, it only searches a specific // object. static std::vector<HMODULE> &getLoadedLibHandles() { static std::vector<HMODULE> *LoadedLibHandles = 0; if (LoadedLibHandles == 0) { LoadedLibHandles = new std::vector<HMODULE>(); if (HMODULE H = GetModuleHandle(NULL)) // JIT symbols LoadedLibHandles->push_back(H); if (HMODULE MH = GetModuleHandle("cygwin1.dll")) // Cygwin symbols OR LoadedLibHandles->push_back(MH); else if (HMODULE MH = GetModuleHandle("msvcr80.dll")) // VC++ symbols LoadedLibHandles->push_back(MH); } return *LoadedLibHandles; } #endif bool llvm::LinkDynamicObject(const char *filename, std::string *ErrorMessage) { #if defined(HAVE_WINDOWS_H) if (HMODULE Handle = LoadLibrary(filename)) { // Allow GetProcAddress in this module getLoadedLibHandles().push_back(Handle); return false; } if (ErrorMessage) { char Buffer[100]; // FIXME: This should use FormatMessage sprintf(Buffer, "Windows error code %d\n", GetLastError()); *ErrorMessage = Buffer; } return true; #elif defined (HAVE_DLOPEN) if (dlopen (filename, RTLD_NOW | RTLD_GLOBAL) == 0) { if (ErrorMessage) *ErrorMessage = dlerror (); return true; } return false; #else assert (0 && "Dynamic object linking not implemented for this platform"); #endif } void *llvm::GetAddressOfSymbol(const char *symbolName) { #if defined(HAVE_WINDOWS_H) std::vector<HMODULE> &LH = getLoadedLibHandles(); for (unsigned i = 0, e = LH.size(); i != e; ++i) if (void *Val = (void*)GetProcAddress(LH[i], symbolName)) return Val; return 0; #elif defined(HAVE_DLOPEN) # ifdef RTLD_DEFAULT return dlsym (RTLD_DEFAULT, symbolName); # else static void* CurHandle = dlopen(0, RTLD_LAZY); return dlsym(CurHandle, symbolName); # endif #else assert (0 && "Dynamic symbol lookup not implemented for this platform"); #endif } // soft, cushiony C++ interface. void *llvm::GetAddressOfSymbol(const std::string &symbolName) { return GetAddressOfSymbol(symbolName.c_str()); } <|endoftext|>
<commit_before>#include <QApplication> #include <QWidget> #include <QLabel> #include <QPushButton> #include <QGridLayout> #include <QPointer> #include <QBackingStore> #include <QList> #include <QBasicTimer> #include <QImage> #include <QPixmap> #include <QTime> #include <QDebug> class WidgetMonitor : public QObject { Q_OBJECT QSet<QWidget *> m_awake; QBasicTimer m_timer; int m_counter; void queue(QWidget * w) { m_awake << w->window(); if (! m_timer.isActive()) m_timer.start(0, this); } bool eventFilter(QObject * obj, QEvent * ev) { switch (ev->type()) { case QEvent::Paint: { if (! obj->isWidgetType()) break; queue(static_cast<QWidget*>(obj)); break; } case QEvent::ChildAdded: { if (obj->isWidgetType()) obj->installEventFilter(this); break; } default: break; } return false; } void timerEvent(QTimerEvent * ev) { if (ev->timerId() != m_timer.timerId()) return; qDebug() << "painting: " << m_counter++ << m_awake; foreach (QWidget * w, m_awake) { QImage * img = dynamic_cast<QImage*>(w->backingStore()->paintDevice()); if (img) emit newContents(img, w); } m_awake.clear(); m_timer.stop(); } Q_SLOT void windowDestroyed(QObject * obj) { if (! obj->isWidgetType()) return; m_awake.remove(static_cast<QWidget*>(obj)); } public: explicit WidgetMonitor(QObject * parent = 0) : QObject(parent), m_counter(0) {} explicit WidgetMonitor(QWidget * w, QObject * parent = 0) : QObject(parent), m_counter(0) { monitor(w); } Q_SLOT void monitor(QWidget * w) { w = w->window(); connect(w, &QObject::destroyed, this, &WidgetMonitor::windowDestroyed); w->installEventFilter(this); foreach (QObject * obj, w->children()) { if (obj->isWidgetType()) obj->installEventFilter(this); } queue(w); } Q_SLOT void unMonitor(QWidget * w) { w = w->window(); disconnect(w, &QObject::destroyed, this, &WidgetMonitor::windowDestroyed); m_awake.remove(w); w->removeEventFilter(this); foreach (QObject * obj, w->children()) { if (obj->isWidgetType()) obj->removeEventFilter(this); } } Q_SIGNAL void newContents(const QImage *, QWidget * w); }; class TestWidget : public QWidget { QLabel * m_time; QBasicTimer m_timer; void timerEvent(QTimerEvent * ev) { if (ev->timerId() != m_timer.timerId()) return; m_time->setText(QTime::currentTime().toString()); } public: explicit TestWidget(QWidget * parent = 0) : QWidget(parent), m_time(new QLabel) { QGridLayout * lay = new QGridLayout(this); lay->addWidget(m_time, 0, 0); lay->addWidget(new QLabel("Static Label"), 1, 0); lay->addWidget(new QPushButton("A Button"), 2, 0); m_timer.start(1000, this); } }; int main(int argc, char *argv[]) { QApplication a(argc, argv); TestWidget src; QWidget dst; QGridLayout * dl = new QGridLayout(&dst); QLabel * dstLabel = new QLabel; dstLabel->setFrameShape(QFrame::Box); dl->addWidget(new QLabel("Destination"), 0, 0); dl->addWidget(dstLabel); src.show(); dst.show(); WidgetMonitor mon(&src); QObject::connect(&mon, &WidgetMonitor::newContents, [=](const QImage * img){ dstLabel->resize(img->size()); dstLabel->setPixmap(QPixmap::fromImage(*img)); }); return a.exec(); } #include "main.moc" <commit_msg>C++11-ize<commit_after>// https://github.com/KubaO/stackoverflown/tree/master/questions/surface-20737882 #include <QtWidgets> class WidgetMonitor : public QObject { Q_OBJECT QSet<QWidget *> m_awake; QBasicTimer m_timer; int m_counter = 0; void queue(QWidget * w) { m_awake << w->window(); if (! m_timer.isActive()) m_timer.start(0, this); } bool eventFilter(QObject * obj, QEvent * ev) { switch (ev->type()) { case QEvent::Paint: { if (! obj->isWidgetType()) break; queue(static_cast<QWidget*>(obj)); break; } case QEvent::ChildAdded: { if (obj->isWidgetType()) obj->installEventFilter(this); break; } default: break; } return false; } void timerEvent(QTimerEvent * ev) { if (ev->timerId() != m_timer.timerId()) return; qDebug() << "painting: " << m_counter++ << m_awake; for (auto w : m_awake) { auto img = dynamic_cast<QImage*>(w->backingStore()->paintDevice()); if (img) emit newContents(img, w); } m_awake.clear(); m_timer.stop(); } Q_SLOT void windowDestroyed(QObject * obj) { if (! obj->isWidgetType()) return; m_awake.remove(static_cast<QWidget*>(obj)); } public: explicit WidgetMonitor(QObject * parent = nullptr) : QObject{parent} {} explicit WidgetMonitor(QWidget * w, QObject * parent = nullptr) : QObject{parent} { monitor(w); } Q_SLOT void monitor(QWidget * w) { w = w->window(); connect(w, &QObject::destroyed, this, &WidgetMonitor::windowDestroyed); w->installEventFilter(this); for (auto obj : w->children()) if (obj->isWidgetType()) obj->installEventFilter(this); queue(w); } Q_SLOT void unMonitor(QWidget * w) { w = w->window(); disconnect(w, &QObject::destroyed, this, &WidgetMonitor::windowDestroyed); m_awake.remove(w); w->removeEventFilter(this); for (auto obj : w->children()) { if (obj->isWidgetType()) obj->removeEventFilter(this); } } Q_SIGNAL void newContents(const QImage *, QWidget * w); }; class TestWidget : public QWidget { QVBoxLayout m_layout{this}; QLabel m_time; QBasicTimer m_timer; void timerEvent(QTimerEvent * ev) override { if (ev->timerId() != m_timer.timerId()) return; m_time.setText(QTime::currentTime().toString()); } public: explicit TestWidget(QWidget * parent = 0) : QWidget{parent} { m_layout.addWidget(&m_time); m_layout.addWidget(new QLabel{"Static Label"}); m_layout.addWidget(new QPushButton{"A Button"}); m_timer.start(1000, this); } }; int main(int argc, char **argv) { QApplication app{argc, argv}; TestWidget src; QWidget dst; QVBoxLayout dl{&dst}; QLabel description{"Destination"}; QLabel contents; contents.setFrameShape(QFrame::Box); dl.addWidget(&description); dl.addWidget(&contents); src.show(); dst.show(); WidgetMonitor mon(&src); QObject::connect(&mon, &WidgetMonitor::newContents, [&](const QImage * img){ contents.resize(img->size()); contents.setPixmap(QPixmap::fromImage(*img)); }); return app.exec(); } #include "main.moc" <|endoftext|>
<commit_before>//===- lib/Support/ErrorHandling.cpp - Callbacks for errors ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines an API used to indicate fatal error conditions. Non-fatal // errors (most of them) should be handled through LLVMContext. // //===----------------------------------------------------------------------===// #include "llvm/Support/ErrorHandling.h" #include "llvm-c/Core.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Twine.h" #include "llvm/Config/config.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Errc.h" #include "llvm/Support/Signals.h" #include "llvm/Support/Mutex.h" #include "llvm/Support/MutexGuard.h" #include "llvm/Support/Threading.h" #include "llvm/Support/WindowsError.h" #include "llvm/Support/raw_ostream.h" #include <cassert> #include <cstdlib> #if defined(HAVE_UNISTD_H) # include <unistd.h> #endif #if defined(_MSC_VER) # include <io.h> # include <fcntl.h> #endif using namespace llvm; static fatal_error_handler_t ErrorHandler = nullptr; static void *ErrorHandlerUserData = nullptr; static sys::Mutex ErrorHandlerMutex; void llvm::install_fatal_error_handler(fatal_error_handler_t handler, void *user_data) { llvm::MutexGuard Lock(ErrorHandlerMutex); assert(!ErrorHandler && "Error handler already registered!\n"); ErrorHandler = handler; ErrorHandlerUserData = user_data; } void llvm::remove_fatal_error_handler() { llvm::MutexGuard Lock(ErrorHandlerMutex); ErrorHandler = nullptr; ErrorHandlerUserData = nullptr; } void llvm::report_fatal_error(const char *Reason, bool GenCrashDiag) { report_fatal_error(Twine(Reason), GenCrashDiag); } void llvm::report_fatal_error(const std::string &Reason, bool GenCrashDiag) { report_fatal_error(Twine(Reason), GenCrashDiag); } void llvm::report_fatal_error(StringRef Reason, bool GenCrashDiag) { report_fatal_error(Twine(Reason), GenCrashDiag); } void llvm::report_fatal_error(const Twine &Reason, bool GenCrashDiag) { llvm::fatal_error_handler_t handler = nullptr; void* handlerData = nullptr; { // Only acquire the mutex while reading the handler, so as not to invoke a // user-supplied callback under a lock. llvm::MutexGuard Lock(ErrorHandlerMutex); handler = ErrorHandler; handlerData = ErrorHandlerUserData; } if (handler) { handler(handlerData, Reason.str(), GenCrashDiag); } else { // Blast the result out to stderr. We don't try hard to make sure this // succeeds (e.g. handling EINTR) and we can't use errs() here because // raw ostreams can call report_fatal_error. SmallVector<char, 64> Buffer; raw_svector_ostream OS(Buffer); OS << "LLVM ERROR: " << Reason << "\n"; StringRef MessageStr = OS.str(); ssize_t written = ::write(2, MessageStr.data(), MessageStr.size()); (void)written; // If something went wrong, we deliberately just give up. } // If we reached here, we are failing ungracefully. Run the interrupt handlers // to make sure any special cleanups get done, in particular that we remove // files registered with RemoveFileOnSignal. sys::RunInterruptHandlers(); exit(1); } void llvm::llvm_unreachable_internal(const char *msg, const char *file, unsigned line) { // This code intentionally doesn't call the ErrorHandler callback, because // llvm_unreachable is intended to be used to indicate "impossible" // situations, and not legitimate runtime errors. if (msg) dbgs() << msg << "\n"; dbgs() << "UNREACHABLE executed"; if (file) dbgs() << " at " << file << ":" << line; dbgs() << "!\n"; abort(); #ifdef LLVM_BUILTIN_UNREACHABLE // Windows systems and possibly others don't declare abort() to be noreturn, // so use the unreachable builtin to avoid a Clang self-host warning. LLVM_BUILTIN_UNREACHABLE; #endif } static void bindingsErrorHandler(void *user_data, const std::string& reason, bool gen_crash_diag) { LLVMFatalErrorHandler handler = LLVM_EXTENSION reinterpret_cast<LLVMFatalErrorHandler>(user_data); handler(reason.c_str()); } void LLVMInstallFatalErrorHandler(LLVMFatalErrorHandler Handler) { install_fatal_error_handler(bindingsErrorHandler, LLVM_EXTENSION reinterpret_cast<void *>(Handler)); } void LLVMResetFatalErrorHandler() { remove_fatal_error_handler(); } #ifdef LLVM_ON_WIN32 #include <winerror.h> // I'd rather not double the line count of the following. #define MAP_ERR_TO_COND(x, y) \ case x: \ return make_error_code(errc::y) std::error_code llvm::mapWindowsError(unsigned EV) { switch (EV) { MAP_ERR_TO_COND(ERROR_ACCESS_DENIED, permission_denied); MAP_ERR_TO_COND(ERROR_ALREADY_EXISTS, file_exists); MAP_ERR_TO_COND(ERROR_BAD_UNIT, no_such_device); MAP_ERR_TO_COND(ERROR_BUFFER_OVERFLOW, filename_too_long); MAP_ERR_TO_COND(ERROR_BUSY, device_or_resource_busy); MAP_ERR_TO_COND(ERROR_BUSY_DRIVE, device_or_resource_busy); MAP_ERR_TO_COND(ERROR_CANNOT_MAKE, permission_denied); MAP_ERR_TO_COND(ERROR_CANTOPEN, io_error); MAP_ERR_TO_COND(ERROR_CANTREAD, io_error); MAP_ERR_TO_COND(ERROR_CANTWRITE, io_error); MAP_ERR_TO_COND(ERROR_CURRENT_DIRECTORY, permission_denied); MAP_ERR_TO_COND(ERROR_DEV_NOT_EXIST, no_such_device); MAP_ERR_TO_COND(ERROR_DEVICE_IN_USE, device_or_resource_busy); MAP_ERR_TO_COND(ERROR_DIR_NOT_EMPTY, directory_not_empty); MAP_ERR_TO_COND(ERROR_DIRECTORY, invalid_argument); MAP_ERR_TO_COND(ERROR_DISK_FULL, no_space_on_device); MAP_ERR_TO_COND(ERROR_FILE_EXISTS, file_exists); MAP_ERR_TO_COND(ERROR_FILE_NOT_FOUND, no_such_file_or_directory); MAP_ERR_TO_COND(ERROR_HANDLE_DISK_FULL, no_space_on_device); MAP_ERR_TO_COND(ERROR_INVALID_ACCESS, permission_denied); MAP_ERR_TO_COND(ERROR_INVALID_DRIVE, no_such_device); MAP_ERR_TO_COND(ERROR_INVALID_FUNCTION, function_not_supported); MAP_ERR_TO_COND(ERROR_INVALID_HANDLE, invalid_argument); MAP_ERR_TO_COND(ERROR_INVALID_NAME, invalid_argument); MAP_ERR_TO_COND(ERROR_LOCK_VIOLATION, no_lock_available); MAP_ERR_TO_COND(ERROR_LOCKED, no_lock_available); MAP_ERR_TO_COND(ERROR_NEGATIVE_SEEK, invalid_argument); MAP_ERR_TO_COND(ERROR_NOACCESS, permission_denied); MAP_ERR_TO_COND(ERROR_NOT_ENOUGH_MEMORY, not_enough_memory); MAP_ERR_TO_COND(ERROR_NOT_READY, resource_unavailable_try_again); MAP_ERR_TO_COND(ERROR_OPEN_FAILED, io_error); MAP_ERR_TO_COND(ERROR_OPEN_FILES, device_or_resource_busy); MAP_ERR_TO_COND(ERROR_OUTOFMEMORY, not_enough_memory); MAP_ERR_TO_COND(ERROR_PATH_NOT_FOUND, no_such_file_or_directory); MAP_ERR_TO_COND(ERROR_BAD_NETPATH, no_such_file_or_directory); MAP_ERR_TO_COND(ERROR_READ_FAULT, io_error); MAP_ERR_TO_COND(ERROR_RETRY, resource_unavailable_try_again); MAP_ERR_TO_COND(ERROR_SEEK, io_error); MAP_ERR_TO_COND(ERROR_SHARING_VIOLATION, permission_denied); MAP_ERR_TO_COND(ERROR_TOO_MANY_OPEN_FILES, too_many_files_open); MAP_ERR_TO_COND(ERROR_WRITE_FAULT, io_error); MAP_ERR_TO_COND(ERROR_WRITE_PROTECT, permission_denied); MAP_ERR_TO_COND(WSAEACCES, permission_denied); MAP_ERR_TO_COND(WSAEBADF, bad_file_descriptor); MAP_ERR_TO_COND(WSAEFAULT, bad_address); MAP_ERR_TO_COND(WSAEINTR, interrupted); MAP_ERR_TO_COND(WSAEINVAL, invalid_argument); MAP_ERR_TO_COND(WSAEMFILE, too_many_files_open); MAP_ERR_TO_COND(WSAENAMETOOLONG, filename_too_long); default: return std::error_code(EV, std::system_category()); } } #endif <commit_msg>Converting the ErrorHandlerMutex to a ManagedStatic to avoid the static constructor and destructor.<commit_after>//===- lib/Support/ErrorHandling.cpp - Callbacks for errors ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines an API used to indicate fatal error conditions. Non-fatal // errors (most of them) should be handled through LLVMContext. // //===----------------------------------------------------------------------===// #include "llvm/Support/ErrorHandling.h" #include "llvm-c/Core.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Twine.h" #include "llvm/Config/config.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Errc.h" #include "llvm/Support/Signals.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/Mutex.h" #include "llvm/Support/MutexGuard.h" #include "llvm/Support/Threading.h" #include "llvm/Support/WindowsError.h" #include "llvm/Support/raw_ostream.h" #include <cassert> #include <cstdlib> #if defined(HAVE_UNISTD_H) # include <unistd.h> #endif #if defined(_MSC_VER) # include <io.h> # include <fcntl.h> #endif using namespace llvm; static fatal_error_handler_t ErrorHandler = nullptr; static void *ErrorHandlerUserData = nullptr; static ManagedStatic<sys::Mutex> ErrorHandlerMutex; void llvm::install_fatal_error_handler(fatal_error_handler_t handler, void *user_data) { llvm::MutexGuard Lock(*ErrorHandlerMutex); assert(!ErrorHandler && "Error handler already registered!\n"); ErrorHandler = handler; ErrorHandlerUserData = user_data; } void llvm::remove_fatal_error_handler() { llvm::MutexGuard Lock(*ErrorHandlerMutex); ErrorHandler = nullptr; ErrorHandlerUserData = nullptr; } void llvm::report_fatal_error(const char *Reason, bool GenCrashDiag) { report_fatal_error(Twine(Reason), GenCrashDiag); } void llvm::report_fatal_error(const std::string &Reason, bool GenCrashDiag) { report_fatal_error(Twine(Reason), GenCrashDiag); } void llvm::report_fatal_error(StringRef Reason, bool GenCrashDiag) { report_fatal_error(Twine(Reason), GenCrashDiag); } void llvm::report_fatal_error(const Twine &Reason, bool GenCrashDiag) { llvm::fatal_error_handler_t handler = nullptr; void* handlerData = nullptr; { // Only acquire the mutex while reading the handler, so as not to invoke a // user-supplied callback under a lock. llvm::MutexGuard Lock(*ErrorHandlerMutex); handler = ErrorHandler; handlerData = ErrorHandlerUserData; } if (handler) { handler(handlerData, Reason.str(), GenCrashDiag); } else { // Blast the result out to stderr. We don't try hard to make sure this // succeeds (e.g. handling EINTR) and we can't use errs() here because // raw ostreams can call report_fatal_error. SmallVector<char, 64> Buffer; raw_svector_ostream OS(Buffer); OS << "LLVM ERROR: " << Reason << "\n"; StringRef MessageStr = OS.str(); ssize_t written = ::write(2, MessageStr.data(), MessageStr.size()); (void)written; // If something went wrong, we deliberately just give up. } // If we reached here, we are failing ungracefully. Run the interrupt handlers // to make sure any special cleanups get done, in particular that we remove // files registered with RemoveFileOnSignal. sys::RunInterruptHandlers(); exit(1); } void llvm::llvm_unreachable_internal(const char *msg, const char *file, unsigned line) { // This code intentionally doesn't call the ErrorHandler callback, because // llvm_unreachable is intended to be used to indicate "impossible" // situations, and not legitimate runtime errors. if (msg) dbgs() << msg << "\n"; dbgs() << "UNREACHABLE executed"; if (file) dbgs() << " at " << file << ":" << line; dbgs() << "!\n"; abort(); #ifdef LLVM_BUILTIN_UNREACHABLE // Windows systems and possibly others don't declare abort() to be noreturn, // so use the unreachable builtin to avoid a Clang self-host warning. LLVM_BUILTIN_UNREACHABLE; #endif } static void bindingsErrorHandler(void *user_data, const std::string& reason, bool gen_crash_diag) { LLVMFatalErrorHandler handler = LLVM_EXTENSION reinterpret_cast<LLVMFatalErrorHandler>(user_data); handler(reason.c_str()); } void LLVMInstallFatalErrorHandler(LLVMFatalErrorHandler Handler) { install_fatal_error_handler(bindingsErrorHandler, LLVM_EXTENSION reinterpret_cast<void *>(Handler)); } void LLVMResetFatalErrorHandler() { remove_fatal_error_handler(); } #ifdef LLVM_ON_WIN32 #include <winerror.h> // I'd rather not double the line count of the following. #define MAP_ERR_TO_COND(x, y) \ case x: \ return make_error_code(errc::y) std::error_code llvm::mapWindowsError(unsigned EV) { switch (EV) { MAP_ERR_TO_COND(ERROR_ACCESS_DENIED, permission_denied); MAP_ERR_TO_COND(ERROR_ALREADY_EXISTS, file_exists); MAP_ERR_TO_COND(ERROR_BAD_UNIT, no_such_device); MAP_ERR_TO_COND(ERROR_BUFFER_OVERFLOW, filename_too_long); MAP_ERR_TO_COND(ERROR_BUSY, device_or_resource_busy); MAP_ERR_TO_COND(ERROR_BUSY_DRIVE, device_or_resource_busy); MAP_ERR_TO_COND(ERROR_CANNOT_MAKE, permission_denied); MAP_ERR_TO_COND(ERROR_CANTOPEN, io_error); MAP_ERR_TO_COND(ERROR_CANTREAD, io_error); MAP_ERR_TO_COND(ERROR_CANTWRITE, io_error); MAP_ERR_TO_COND(ERROR_CURRENT_DIRECTORY, permission_denied); MAP_ERR_TO_COND(ERROR_DEV_NOT_EXIST, no_such_device); MAP_ERR_TO_COND(ERROR_DEVICE_IN_USE, device_or_resource_busy); MAP_ERR_TO_COND(ERROR_DIR_NOT_EMPTY, directory_not_empty); MAP_ERR_TO_COND(ERROR_DIRECTORY, invalid_argument); MAP_ERR_TO_COND(ERROR_DISK_FULL, no_space_on_device); MAP_ERR_TO_COND(ERROR_FILE_EXISTS, file_exists); MAP_ERR_TO_COND(ERROR_FILE_NOT_FOUND, no_such_file_or_directory); MAP_ERR_TO_COND(ERROR_HANDLE_DISK_FULL, no_space_on_device); MAP_ERR_TO_COND(ERROR_INVALID_ACCESS, permission_denied); MAP_ERR_TO_COND(ERROR_INVALID_DRIVE, no_such_device); MAP_ERR_TO_COND(ERROR_INVALID_FUNCTION, function_not_supported); MAP_ERR_TO_COND(ERROR_INVALID_HANDLE, invalid_argument); MAP_ERR_TO_COND(ERROR_INVALID_NAME, invalid_argument); MAP_ERR_TO_COND(ERROR_LOCK_VIOLATION, no_lock_available); MAP_ERR_TO_COND(ERROR_LOCKED, no_lock_available); MAP_ERR_TO_COND(ERROR_NEGATIVE_SEEK, invalid_argument); MAP_ERR_TO_COND(ERROR_NOACCESS, permission_denied); MAP_ERR_TO_COND(ERROR_NOT_ENOUGH_MEMORY, not_enough_memory); MAP_ERR_TO_COND(ERROR_NOT_READY, resource_unavailable_try_again); MAP_ERR_TO_COND(ERROR_OPEN_FAILED, io_error); MAP_ERR_TO_COND(ERROR_OPEN_FILES, device_or_resource_busy); MAP_ERR_TO_COND(ERROR_OUTOFMEMORY, not_enough_memory); MAP_ERR_TO_COND(ERROR_PATH_NOT_FOUND, no_such_file_or_directory); MAP_ERR_TO_COND(ERROR_BAD_NETPATH, no_such_file_or_directory); MAP_ERR_TO_COND(ERROR_READ_FAULT, io_error); MAP_ERR_TO_COND(ERROR_RETRY, resource_unavailable_try_again); MAP_ERR_TO_COND(ERROR_SEEK, io_error); MAP_ERR_TO_COND(ERROR_SHARING_VIOLATION, permission_denied); MAP_ERR_TO_COND(ERROR_TOO_MANY_OPEN_FILES, too_many_files_open); MAP_ERR_TO_COND(ERROR_WRITE_FAULT, io_error); MAP_ERR_TO_COND(ERROR_WRITE_PROTECT, permission_denied); MAP_ERR_TO_COND(WSAEACCES, permission_denied); MAP_ERR_TO_COND(WSAEBADF, bad_file_descriptor); MAP_ERR_TO_COND(WSAEFAULT, bad_address); MAP_ERR_TO_COND(WSAEINTR, interrupted); MAP_ERR_TO_COND(WSAEINVAL, invalid_argument); MAP_ERR_TO_COND(WSAEMFILE, too_many_files_open); MAP_ERR_TO_COND(WSAENAMETOOLONG, filename_too_long); default: return std::error_code(EV, std::system_category()); } } #endif <|endoftext|>
<commit_before>//===- DCE.cpp - Code to perform dead code elimination --------------------===// // // This file implements dead code elimination and basic block merging. // // Specifically, this: // * removes definitions with no uses (including unused constants) // * removes basic blocks with no predecessors // * merges a basic block into its predecessor if there is only one and the // predecessor only has one successor. // * Eliminates PHI nodes for basic blocks with a single predecessor // * Eliminates a basic block that only contains an unconditional branch // // TODO: This should REALLY be worklist driven instead of iterative. Right now, // we scan linearly through values, removing unused ones as we go. The problem // is that this may cause other earlier values to become unused. To make sure // that we get them all, we iterate until things stop changing. Instead, when // removing a value, recheck all of its operands to see if they are now unused. // Piece of cake, and more efficient as well. // // Note, this is not trivial, because we have to worry about invalidating // iterators. :( // //===----------------------------------------------------------------------===// #include "llvm/Optimizations/DCE.h" #include "llvm/Support/STLExtras.h" #include "llvm/Module.h" #include "llvm/Method.h" #include "llvm/BasicBlock.h" #include "llvm/iTerminators.h" #include "llvm/iOther.h" #include "llvm/Assembly/Writer.h" #include "llvm/CFG.h" #include <algorithm> using namespace cfg; struct ConstPoolDCE { enum { EndOffs = 0 }; static bool isDCEable(const ConstPoolVal *CPV) { // TODO: The bytecode writer requires that all used types are in the // constant pool for the current method. This is messy and is really // irritating. FIXME return CPV->getType() != Type::TypeTy; // Don't DCE Type plane constants! } }; struct BasicBlockDCE { enum { EndOffs = 1 }; static bool isDCEable(const Instruction *I) { return !I->hasSideEffects(); } }; template<class Container, class DCEController> static bool RemoveUnusedDefs(Container &Vals, DCEController DCEControl) { bool Changed = false; int Offset = DCEController::EndOffs; for (typename Container::iterator DI = Vals.begin(); DI != Vals.end()-Offset; ) { // Look for un"used" definitions... if ((*DI)->use_empty() && DCEController::isDCEable(*DI)) { // Bye bye //cerr << "Removing: " << *DI; delete Vals.remove(DI); Changed = true; } else { ++DI; } } return Changed; } // RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only // a single predecessor. This means that the PHI node must only have a single // RHS value and can be eliminated. // // This routine is very simple because we know that PHI nodes must be the first // things in a basic block, if they are present. // static bool RemoveSingularPHIs(BasicBlock *BB) { pred_iterator PI(pred_begin(BB)); if (PI == pred_end(BB) || ++PI != pred_end(BB)) return false; // More than one predecessor... Instruction *I = BB->front(); if (!I->isPHINode()) return false; // No PHI nodes //cerr << "Killing PHIs from " << BB; //cerr << "Pred #0 = " << *pred_begin(BB); //cerr << "Method == " << BB->getParent(); do { PHINode *PN = (PHINode*)I; assert(PN->getNumOperands() == 2 && "PHI node should only have one value!"); Value *V = PN->getOperand(0); PN->replaceAllUsesWith(V); // Replace PHI node with its single value. delete BB->getInstList().remove(BB->begin()); I = BB->front(); } while (I->isPHINode()); return true; // Yes, we nuked at least one phi node } bool opt::DoRemoveUnusedConstants(SymTabValue *S) { bool Changed = false; ConstantPool &CP = S->getConstantPool(); for (ConstantPool::plane_iterator PI = CP.begin(); PI != CP.end(); ++PI) Changed |= RemoveUnusedDefs(**PI, ConstPoolDCE()); return Changed; } static void ReplaceUsesWithConstant(Instruction *I) { // Get the method level constant pool ConstantPool &CP = I->getParent()->getParent()->getConstantPool(); ConstPoolVal *CPV = 0; ConstantPool::PlaneType *P; if (!CP.getPlane(I->getType(), P)) { // Does plane exist? // Yes, is it empty? if (!P->empty()) CPV = P->front(); } if (CPV == 0) { // We don't have an existing constant to reuse. Just add one. CPV = ConstPoolVal::getNullConstant(I->getType()); // Create a new constant // Add the new value to the constant pool... CP.insert(CPV); } // Make all users of this instruction reference the constant instead I->replaceAllUsesWith(CPV); } // PropogatePredecessors - This gets "Succ" ready to have the predecessors from // "BB". This is a little tricky because "Succ" has PHI nodes, which need to // have extra slots added to them to hold the merge edges from BB's // predecessors. // // Assumption: BB is the single predecessor of Succ. // static void PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) { assert(Succ->front()->isPHINode() && "Only works on PHId BBs!"); // If there is more than one predecessor, and there are PHI nodes in // the successor, then we need to add incoming edges for the PHI nodes // const vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB)); BasicBlock::iterator I = Succ->begin(); do { // Loop over all of the PHI nodes in the successor BB PHINode *PN = (PHINode*)*I; Value *OldVal = PN->removeIncomingValue(BB); assert(OldVal && "No entry in PHI for Pred BB!"); for (vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(), End = BBPreds.end(); PredI != End; ++PredI) { // Add an incoming value for each of the new incoming values... PN->addIncoming(OldVal, *PredI); } ++I; } while ((*I)->isPHINode()); } // SimplifyCFG - This function is used to do simplification of a CFG. For // example, it adjusts branches to branches to eliminate the extra hop, it // eliminates unreachable basic blocks, and does other "peephole" optimization // of the CFG. It returns true if a modification was made, and returns an // iterator that designates the first element remaining after the block that // was deleted. // // WARNING: The entry node of a method may not be simplified. // bool opt::SimplifyCFG(Method::iterator &BBIt) { assert(*BBIt && (*BBIt)->getParent() && "Block not embedded in method!"); BasicBlock *BB = *BBIt; Method *M = BB->getParent(); assert(BB->getTerminator() && "Degenerate basic block encountered!"); assert(BB->getParent()->front() != BB && "Can't Simplify entry block!"); // Remove basic blocks that have no predecessors... which are unreachable. if (pred_begin(BB) == pred_end(BB) && !BB->hasConstantPoolReferences()) { //cerr << "Removing BB: \n" << BB; // Loop through all of our successors and make sure they know that one // of their predecessors is going away. for_each(succ_begin(BB), succ_end(BB), std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB)); while (!BB->empty()) { Instruction *I = BB->back(); // If this instruction is used, replace uses with an arbitrary // constant value. Because control flow can't get here, we don't care // what we replace the value with. Note that since this block is // unreachable, and all values contained within it must dominate their // uses, that all uses will eventually be removed. if (!I->use_empty()) ReplaceUsesWithConstant(I); // Remove the instruction from the basic block delete BB->getInstList().pop_back(); } delete M->getBasicBlocks().remove(BBIt); return true; } // Check to see if this block has no instructions and only a single // successor. If so, replace block references with successor. succ_iterator SI(succ_begin(BB)); if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ? Instruction *I = BB->front(); if (I->isTerminator()) { // Terminator is the only instruction! BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor //cerr << "Killing Trivial BB: \n" << BB; if (Succ != BB) { // Arg, don't hurt infinite loops! if (Succ->front()->isPHINode()) { // If our successor has PHI nodes, then we need to update them to // include entries for BB's predecessors, not for BB itself. // PropogatePredecessorsForPHIs(BB, Succ); } BB->replaceAllUsesWith(Succ); BB = M->getBasicBlocks().remove(BBIt); if (BB->hasName() && !Succ->hasName()) // Transfer name if we can Succ->setName(BB->getName()); delete BB; // Delete basic block //cerr << "Method after removal: \n" << M; return true; } } } // Merge basic blocks into their predecessor if there is only one pred, // and if there is only one successor of the predecessor. pred_iterator PI(pred_begin(BB)); if (PI != pred_end(BB) && *PI != BB && // Not empty? Not same BB? ++PI == pred_end(BB) && !BB->hasConstantPoolReferences()) { BasicBlock *Pred = *pred_begin(BB); TerminatorInst *Term = Pred->getTerminator(); assert(Term != 0 && "malformed basic block without terminator!"); // Does the predecessor block only have a single successor? succ_iterator SI(succ_begin(Pred)); if (++SI == succ_end(Pred)) { //cerr << "Merging: " << BB << "into: " << Pred; // Delete the unconditianal branch from the predecessor... BasicBlock::iterator DI = Pred->end(); assert(Pred->getTerminator() && "Degenerate basic block encountered!"); // Empty bb??? delete Pred->getInstList().remove(--DI); // Destroy uncond branch // Move all definitions in the succecessor to the predecessor... while (!BB->empty()) { DI = BB->begin(); Instruction *Def = BB->getInstList().remove(DI); // Remove from front Pred->getInstList().push_back(Def); // Add to end... } // Remove basic block from the method... and advance iterator to the // next valid block... BB = M->getBasicBlocks().remove(BBIt); // Make all PHI nodes that refered to BB now refer to Pred as their // source... BB->replaceAllUsesWith(Pred); // Inherit predecessors name if it exists... if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName()); delete BB; // You ARE the weakest link... goodbye return true; } } return false; } static bool DoDCEPass(Method *M) { Method::iterator BBIt, BBEnd = M->end(); if (M->begin() == BBEnd) return false; // Nothing to do bool Changed = false; // Loop through now and remove instructions that have no uses... for (BBIt = M->begin(); BBIt != BBEnd; ++BBIt) { Changed |= RemoveUnusedDefs((*BBIt)->getInstList(), BasicBlockDCE()); Changed |= RemoveSingularPHIs(*BBIt); } // Loop over all of the basic blocks (except the first one) and remove them // if they are unneeded... // for (BBIt = M->begin(), ++BBIt; BBIt != M->end(); ) { if (opt::SimplifyCFG(BBIt)) { Changed = true; } else { ++BBIt; } } // Remove unused constants return Changed | opt::DoRemoveUnusedConstants(M); } // It is possible that we may require multiple passes over the code to fully // eliminate dead code. Iterate until we are done. // bool opt::DoDeadCodeElimination(Method *M) { bool Changed = false; while (DoDCEPass(M)) Changed = true; return Changed; } bool opt::DoDeadCodeElimination(Module *C) { bool Val = C->reduceApply(DoDeadCodeElimination); while (DoRemoveUnusedConstants(C)) Val = true; return Val; } <commit_msg>Enable the elimination of method prototypes that are not referenced<commit_after>//===- DCE.cpp - Code to perform dead code elimination --------------------===// // // This file implements dead code elimination and basic block merging. // // Specifically, this: // * removes definitions with no uses (including unused constants) // * removes basic blocks with no predecessors // * merges a basic block into its predecessor if there is only one and the // predecessor only has one successor. // * Eliminates PHI nodes for basic blocks with a single predecessor // * Eliminates a basic block that only contains an unconditional branch // * Eliminates method prototypes that are not referenced // // TODO: This should REALLY be worklist driven instead of iterative. Right now, // we scan linearly through values, removing unused ones as we go. The problem // is that this may cause other earlier values to become unused. To make sure // that we get them all, we iterate until things stop changing. Instead, when // removing a value, recheck all of its operands to see if they are now unused. // Piece of cake, and more efficient as well. // // Note, this is not trivial, because we have to worry about invalidating // iterators. :( // //===----------------------------------------------------------------------===// #include "llvm/Optimizations/DCE.h" #include "llvm/Support/STLExtras.h" #include "llvm/Module.h" #include "llvm/Method.h" #include "llvm/BasicBlock.h" #include "llvm/iTerminators.h" #include "llvm/iOther.h" #include "llvm/Assembly/Writer.h" #include "llvm/CFG.h" #include <algorithm> using namespace cfg; struct ConstPoolDCE { enum { EndOffs = 0 }; static bool isDCEable(const ConstPoolVal *CPV) { // TODO: The bytecode writer requires that all used types are in the // constant pool for the current method. This is messy and is really // irritating. FIXME return CPV->getType() != Type::TypeTy; // Don't DCE Type plane constants! } }; struct BasicBlockDCE { enum { EndOffs = 1 }; static bool isDCEable(const Instruction *I) { return !I->hasSideEffects(); } }; template<class Container, class DCEController> static bool RemoveUnusedDefs(Container &Vals, DCEController DCEControl) { bool Changed = false; int Offset = DCEController::EndOffs; for (typename Container::iterator DI = Vals.begin(); DI != Vals.end()-Offset; ) { // Look for un"used" definitions... if ((*DI)->use_empty() && DCEController::isDCEable(*DI)) { // Bye bye //cerr << "Removing: " << *DI; delete Vals.remove(DI); Changed = true; } else { ++DI; } } return Changed; } // RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only // a single predecessor. This means that the PHI node must only have a single // RHS value and can be eliminated. // // This routine is very simple because we know that PHI nodes must be the first // things in a basic block, if they are present. // static bool RemoveSingularPHIs(BasicBlock *BB) { pred_iterator PI(pred_begin(BB)); if (PI == pred_end(BB) || ++PI != pred_end(BB)) return false; // More than one predecessor... Instruction *I = BB->front(); if (!I->isPHINode()) return false; // No PHI nodes //cerr << "Killing PHIs from " << BB; //cerr << "Pred #0 = " << *pred_begin(BB); //cerr << "Method == " << BB->getParent(); do { PHINode *PN = (PHINode*)I; assert(PN->getNumOperands() == 2 && "PHI node should only have one value!"); Value *V = PN->getOperand(0); PN->replaceAllUsesWith(V); // Replace PHI node with its single value. delete BB->getInstList().remove(BB->begin()); I = BB->front(); } while (I->isPHINode()); return true; // Yes, we nuked at least one phi node } bool opt::DoRemoveUnusedConstants(SymTabValue *S) { bool Changed = false; ConstantPool &CP = S->getConstantPool(); for (ConstantPool::plane_iterator PI = CP.begin(); PI != CP.end(); ++PI) Changed |= RemoveUnusedDefs(**PI, ConstPoolDCE()); return Changed; } static void ReplaceUsesWithConstant(Instruction *I) { // Get the method level constant pool ConstantPool &CP = I->getParent()->getParent()->getConstantPool(); ConstPoolVal *CPV = 0; ConstantPool::PlaneType *P; if (!CP.getPlane(I->getType(), P)) { // Does plane exist? // Yes, is it empty? if (!P->empty()) CPV = P->front(); } if (CPV == 0) { // We don't have an existing constant to reuse. Just add one. CPV = ConstPoolVal::getNullConstant(I->getType()); // Create a new constant // Add the new value to the constant pool... CP.insert(CPV); } // Make all users of this instruction reference the constant instead I->replaceAllUsesWith(CPV); } // PropogatePredecessors - This gets "Succ" ready to have the predecessors from // "BB". This is a little tricky because "Succ" has PHI nodes, which need to // have extra slots added to them to hold the merge edges from BB's // predecessors. // // Assumption: BB is the single predecessor of Succ. // static void PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) { assert(Succ->front()->isPHINode() && "Only works on PHId BBs!"); // If there is more than one predecessor, and there are PHI nodes in // the successor, then we need to add incoming edges for the PHI nodes // const vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB)); BasicBlock::iterator I = Succ->begin(); do { // Loop over all of the PHI nodes in the successor BB PHINode *PN = (PHINode*)*I; Value *OldVal = PN->removeIncomingValue(BB); assert(OldVal && "No entry in PHI for Pred BB!"); for (vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(), End = BBPreds.end(); PredI != End; ++PredI) { // Add an incoming value for each of the new incoming values... PN->addIncoming(OldVal, *PredI); } ++I; } while ((*I)->isPHINode()); } // SimplifyCFG - This function is used to do simplification of a CFG. For // example, it adjusts branches to branches to eliminate the extra hop, it // eliminates unreachable basic blocks, and does other "peephole" optimization // of the CFG. It returns true if a modification was made, and returns an // iterator that designates the first element remaining after the block that // was deleted. // // WARNING: The entry node of a method may not be simplified. // bool opt::SimplifyCFG(Method::iterator &BBIt) { assert(*BBIt && (*BBIt)->getParent() && "Block not embedded in method!"); BasicBlock *BB = *BBIt; Method *M = BB->getParent(); assert(BB->getTerminator() && "Degenerate basic block encountered!"); assert(BB->getParent()->front() != BB && "Can't Simplify entry block!"); // Remove basic blocks that have no predecessors... which are unreachable. if (pred_begin(BB) == pred_end(BB) && !BB->hasConstantPoolReferences()) { //cerr << "Removing BB: \n" << BB; // Loop through all of our successors and make sure they know that one // of their predecessors is going away. for_each(succ_begin(BB), succ_end(BB), std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB)); while (!BB->empty()) { Instruction *I = BB->back(); // If this instruction is used, replace uses with an arbitrary // constant value. Because control flow can't get here, we don't care // what we replace the value with. Note that since this block is // unreachable, and all values contained within it must dominate their // uses, that all uses will eventually be removed. if (!I->use_empty()) ReplaceUsesWithConstant(I); // Remove the instruction from the basic block delete BB->getInstList().pop_back(); } delete M->getBasicBlocks().remove(BBIt); return true; } // Check to see if this block has no instructions and only a single // successor. If so, replace block references with successor. succ_iterator SI(succ_begin(BB)); if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ? Instruction *I = BB->front(); if (I->isTerminator()) { // Terminator is the only instruction! BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor //cerr << "Killing Trivial BB: \n" << BB; if (Succ != BB) { // Arg, don't hurt infinite loops! if (Succ->front()->isPHINode()) { // If our successor has PHI nodes, then we need to update them to // include entries for BB's predecessors, not for BB itself. // PropogatePredecessorsForPHIs(BB, Succ); } BB->replaceAllUsesWith(Succ); BB = M->getBasicBlocks().remove(BBIt); if (BB->hasName() && !Succ->hasName()) // Transfer name if we can Succ->setName(BB->getName()); delete BB; // Delete basic block //cerr << "Method after removal: \n" << M; return true; } } } // Merge basic blocks into their predecessor if there is only one pred, // and if there is only one successor of the predecessor. pred_iterator PI(pred_begin(BB)); if (PI != pred_end(BB) && *PI != BB && // Not empty? Not same BB? ++PI == pred_end(BB) && !BB->hasConstantPoolReferences()) { BasicBlock *Pred = *pred_begin(BB); TerminatorInst *Term = Pred->getTerminator(); assert(Term != 0 && "malformed basic block without terminator!"); // Does the predecessor block only have a single successor? succ_iterator SI(succ_begin(Pred)); if (++SI == succ_end(Pred)) { //cerr << "Merging: " << BB << "into: " << Pred; // Delete the unconditianal branch from the predecessor... BasicBlock::iterator DI = Pred->end(); assert(Pred->getTerminator() && "Degenerate basic block encountered!"); // Empty bb??? delete Pred->getInstList().remove(--DI); // Destroy uncond branch // Move all definitions in the succecessor to the predecessor... while (!BB->empty()) { DI = BB->begin(); Instruction *Def = BB->getInstList().remove(DI); // Remove from front Pred->getInstList().push_back(Def); // Add to end... } // Remove basic block from the method... and advance iterator to the // next valid block... BB = M->getBasicBlocks().remove(BBIt); // Make all PHI nodes that refered to BB now refer to Pred as their // source... BB->replaceAllUsesWith(Pred); // Inherit predecessors name if it exists... if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName()); delete BB; // You ARE the weakest link... goodbye return true; } } return false; } static bool DoDCEPass(Method *M) { Method::iterator BBIt, BBEnd = M->end(); if (M->begin() == BBEnd) return false; // Nothing to do bool Changed = false; // Loop through now and remove instructions that have no uses... for (BBIt = M->begin(); BBIt != BBEnd; ++BBIt) { Changed |= RemoveUnusedDefs((*BBIt)->getInstList(), BasicBlockDCE()); Changed |= RemoveSingularPHIs(*BBIt); } // Loop over all of the basic blocks (except the first one) and remove them // if they are unneeded... // for (BBIt = M->begin(), ++BBIt; BBIt != M->end(); ) { if (opt::SimplifyCFG(BBIt)) { Changed = true; } else { ++BBIt; } } // Remove unused constants return Changed | opt::DoRemoveUnusedConstants(M); } // It is possible that we may require multiple passes over the code to fully // eliminate dead code. Iterate until we are done. // bool opt::DoDeadCodeElimination(Method *M) { bool Changed = false; while (DoDCEPass(M)) Changed = true; return Changed; } bool opt::DoDeadCodeElimination(Module *Mod) { bool Changed = false; for (Module::iterator MI = Mod->begin(); MI != Mod->end(); ) { Method *Meth = *MI; if (!Meth->isExternal()) { // DCE normal methods Changed |= DoDeadCodeElimination(Meth); ++MI; // Next method please } else if (Meth->use_size() == 0) { // No references to prototype? //cerr << "Removing method proto: " << Meth->getName() << endl; delete Mod->getMethodList().remove(MI); // Remove prototype // Remove moves iterator to point to the next one automatically } else { ++MI; // Skip prototype in use. } } while (DoRemoveUnusedConstants(Mod)) Changed = true; return Changed; } <|endoftext|>
<commit_before>#ifdef HAVE_CONFIG_H #include <config.h> #endif #include <SDL_opengl.h> #include <SDL.h> #include <algorithm> #include <cmath> #include "game.hxx" #include "player.hxx" #include "globals.hxx" #include "music_player.hxx" #define ACCEL -0.015f #define MIN_CONV 0.5f #define MAX_CONV 2.5f using namespace std; Game::Game() : currentConvulsion(0), targetConvulsion(1), playerAmplitude(0), enemyFactory(*this), speed(-2.0f) { player = new Player(&field, &distortion, getNearClippingPlane(), &playerDeath, this); field.add(player); } Game::~Game() {} void Game::update(float et) { float distortionDiff = targetConvulsion - currentConvulsion; distortionDiff *= pow(0.1f, et); currentConvulsion = targetConvulsion - distortionDiff; distortion.setConvulsionMult(currentConvulsion); if (player) player->setAmplitude(playerAmplitude); enemyFactory.update(et, -speed); tunnel.update(et); field.update(et); float oldNear = getNearClippingPlane(); speed += ACCEL*et; float nearDelta = getNearClippingPlane() - oldNear; float shift = speed*et; if (player) { player->shotSpeed = -speed; float oldz = player->getZ(); player->advance(shift, nearDelta); if (player) shift = player->getZ() - oldz + nearDelta; } field.translateZ(shift); tunnel.translateZ(shift); distortion.translateZ(shift, -speed); } void Game::configureGL() { glEnable(GL_FOG); glFogi(GL_FOG_MODE, GL_LINEAR); glFogf(GL_FOG_DENSITY, 0.25f); glFogf(GL_FOG_START, max(1.0f, getNearClippingPlane())); glFogf(GL_FOG_END, max(1.1f, 1.1f*getSpawnDistance())); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-1, 1, -vheight, vheight, getNearClippingPlane(), 128.0f); glScalef(2.0f, 2.0f, 1); glTranslatef(-0.5f, -vheight/2.0f, 0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void Game::draw() { glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); tunnel.draw(distortion); field.draw(); } void Game::motion(float x,float) { if (player) player->move(x); } void Game::button(unsigned button) { if (player) { if (button == SDL_BUTTON_LEFT) player->jump(); } } bool Game::running() const { return !!player; } void Game::playerDeath(void* that) { ((Game*)that)->player = NULL; } float Game::getNearClippingPlane() const { return -1.5f/speed; } float Game::getSpawnDistance() const { return min(8*-speed, Tunnel::gridLength*Tunnel::gsqlen/2); } float Game::getPlayerX() const { return player? player->getX() : 0.5f; } static void amplitudeCallback(void* thisVoid, float amp) { ((Game*)thisVoid)->amplitude(amp); } void Game::amplitude(float amp) { // XXX Minor threading issues here; we could see a partial floating-point // update. Oh well. targetConvulsion = amp*(MAX_CONV - MIN_CONV) + MIN_CONV; playerAmplitude = amp; } void Game::startMusic(const char*const* list, unsigned len) { mixer.play(new MusicPlayer(list, len, amplitudeCallback, this), 0x7FFF); } <commit_msg>Use a perspective which more closely follows the player.<commit_after>#ifdef HAVE_CONFIG_H #include <config.h> #endif #include <SDL_opengl.h> #include <SDL.h> #include <algorithm> #include <cmath> #include "game.hxx" #include "player.hxx" #include "globals.hxx" #include "music_player.hxx" #define ACCEL -0.015f #define MIN_CONV 0.5f #define MAX_CONV 2.5f using namespace std; Game::Game() : currentConvulsion(0), targetConvulsion(1), playerAmplitude(0), enemyFactory(*this), speed(-2.0f) { player = new Player(&field, &distortion, getNearClippingPlane(), &playerDeath, this); field.add(player); } Game::~Game() {} void Game::update(float et) { float distortionDiff = targetConvulsion - currentConvulsion; distortionDiff *= pow(0.1f, et); currentConvulsion = targetConvulsion - distortionDiff; distortion.setConvulsionMult(currentConvulsion); if (player) player->setAmplitude(playerAmplitude); enemyFactory.update(et, -speed); tunnel.update(et); field.update(et); float oldNear = getNearClippingPlane(); speed += ACCEL*et; float nearDelta = getNearClippingPlane() - oldNear; float shift = speed*et; if (player) { player->shotSpeed = -speed; float oldz = player->getZ(); player->advance(shift, nearDelta); if (player) shift = player->getZ() - oldz + nearDelta; } field.translateZ(shift); tunnel.translateZ(shift); distortion.translateZ(shift, -speed); } void Game::configureGL() { glEnable(GL_FOG); glFogi(GL_FOG_MODE, GL_LINEAR); glFogf(GL_FOG_DENSITY, 0.25f); glFogf(GL_FOG_START, max(1.0f, getNearClippingPlane())); glFogf(GL_FOG_END, max(1.1f, 1.1f*getSpawnDistance())); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-1/10.0f, 1/10.0f, -vheight/10.0f, vheight/10.0f, getNearClippingPlane(), 128.0f); glScalef(2.0f, 2.0f, 1); float tx, ty; if (player) { tx = - (player->x - 0.5f)*0.9f - 0.5f; ty = -vheight/3.0f - player->y; } else { tx = -0.5f; ty = -vheight/3.0f; } glTranslatef(tx, ty, -0.5f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void Game::draw() { glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); tunnel.draw(distortion); field.draw(); } void Game::motion(float x,float) { if (player) player->move(x); } void Game::button(unsigned button) { if (player) { if (button == SDL_BUTTON_LEFT) player->jump(); } } bool Game::running() const { return !!player; } void Game::playerDeath(void* that) { ((Game*)that)->player = NULL; } float Game::getNearClippingPlane() const { return -1.5f/speed/10.0f; } float Game::getSpawnDistance() const { return min(8*-speed, Tunnel::gridLength*Tunnel::gsqlen/2); } float Game::getPlayerX() const { return player? player->getX() : 0.5f; } static void amplitudeCallback(void* thisVoid, float amp) { ((Game*)thisVoid)->amplitude(amp); } void Game::amplitude(float amp) { // XXX Minor threading issues here; we could see a partial floating-point // update. Oh well. targetConvulsion = amp*(MAX_CONV - MIN_CONV) + MIN_CONV; playerAmplitude = amp; } void Game::startMusic(const char*const* list, unsigned len) { mixer.play(new MusicPlayer(list, len, amplitudeCallback, this), 0x7FFF); } <|endoftext|>
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "rpcnetwork.h" #include "rpcservicepool.h" #include "rpcsendv2.h" #include "rpctargetpool.h" #include "rpcnetworkparams.h" #include <vespa/fnet/frt/supervisor.h> #include <vespa/fnet/scheduler.h> #include <vespa/fnet/transport.h> #include <vespa/messagebus/emptyreply.h> #include <vespa/messagebus/errorcode.h> #include <vespa/messagebus/iprotocol.h> #include <vespa/messagebus/routing/routingnode.h> #include <vespa/slobrok/sbmirror.h> #include <vespa/slobrok/sbregister.h> #include <vespa/vespalib/component/vtag.h> #include <vespa/vespalib/stllike/asciistream.h> #include <vespa/vespalib/util/size_literals.h> #include <vespa/vespalib/util/stringfmt.h> #include <vespa/fastos/thread.h> #include <thread> #include <vespa/log/log.h> LOG_SETUP(".rpcnetwork"); using vespalib::make_string; using namespace std::chrono_literals; namespace mbus { namespace { /** * Implements a helper class for {@link RPCNetwork#sync()}. It provides a * blocking method {@link #await()} that will wait until the internal state * of this object is set to 'done'. By scheduling this task in the network * thread and then calling this method, we achieve handshaking with the network * thread. */ class SyncTask : public FNET_Task { private: vespalib::Gate _gate; public: SyncTask(FNET_Scheduler &s) : FNET_Task(&s), _gate() { ScheduleNow(); } ~SyncTask() override { Kill(); } void await() { _gate.await(); } void PerformTask() override { _gate.countDown(); } }; struct TargetPoolTask : public FNET_Task { RPCTargetPool &_pool; TargetPoolTask(FNET_Scheduler &scheduler, RPCTargetPool &pool) : FNET_Task(&scheduler), _pool(pool) { ScheduleNow(); } ~TargetPoolTask() override { Kill(); } void PerformTask() override { _pool.flushTargets(false); Schedule(1.0); } }; fnet::TransportConfig toFNETConfig(const RPCNetworkParams & params) { return fnet::TransportConfig(params.getNumNetworkThreads()) .maxInputBufferSize(params.getMaxInputBufferSize()) .maxOutputBufferSize(params.getMaxOutputBufferSize()) .tcpNoDelay(params.getTcpNoDelay()) .events_before_wakeup(params.events_before_wakeup()); } } RPCNetwork::SendContext::SendContext(RPCNetwork &net, const Message &msg, const std::vector<RoutingNode*> &recipients) : _net(net), _msg(msg), _traceLevel(msg.getTrace().getLevel()), _recipients(recipients), _hasError(false), _pending(_recipients.size()), _version(_net.getVersion()) { } void RPCNetwork::SendContext::handleVersion(const vespalib::Version *version) { bool shouldSend = false; { std::lock_guard guard(_lock); if (version == nullptr) { _hasError = true; } else if (*version < _version) { _version = *version; } if (--_pending == 0) { shouldSend = true; } } if (shouldSend) { _net.send(*this); delete this; } } RPCNetwork::RPCNetwork(const RPCNetworkParams &params) : _owner(nullptr), _ident(params.getIdentity()), _threadPool(std::make_unique<FastOS_ThreadPool>(128_Ki, 0)), _transport(std::make_unique<FNET_Transport>(toFNETConfig(params))), _orb(std::make_unique<FRT_Supervisor>(_transport.get())), _scheduler(*_transport->GetScheduler()), _slobrokCfgFactory(std::make_unique<slobrok::ConfiguratorFactory>(params.getSlobrokConfig())), _mirror(std::make_unique<slobrok::api::MirrorAPI>(*_orb, *_slobrokCfgFactory)), _regAPI(std::make_unique<slobrok::api::RegisterAPI>(*_orb, *_slobrokCfgFactory)), _requestedPort(params.getListenPort()), _targetPool(std::make_unique<RPCTargetPool>(params.getConnectionExpireSecs(), params.getNumRpcTargets())), _targetPoolTask(std::make_unique<TargetPoolTask>(_scheduler, *_targetPool)), _servicePool(std::make_unique<RPCServicePool>(*_mirror, 4_Ki)), _sendV2(std::make_unique<RPCSendV2>()), _sendAdapters(), _compressionConfig(params.getCompressionConfig()) { } RPCNetwork::~RPCNetwork() { shutdown(); } FRT_RPCRequest * RPCNetwork::allocRequest() { return _orb->AllocRPCRequest(); } RPCTarget::SP RPCNetwork::getTarget(const RPCServiceAddress &address) { return _targetPool->getTarget(*_orb, address); } void RPCNetwork::replyError(const SendContext &ctx, uint32_t errCode, const string &errMsg) { for (RoutingNode * rnode : ctx._recipients) { Reply::UP reply(new EmptyReply()); reply->setTrace(Trace(ctx._traceLevel)); reply->addError(Error(errCode, errMsg)); _owner->deliverReply(std::move(reply), *rnode); } } int RPCNetwork::getPort() const { return _orb->GetListenPort(); } void RPCNetwork::flushTargetPool() { _targetPool->flushTargets(true); } const vespalib::Version & RPCNetwork::getVersion() const { return vespalib::Vtag::currentVersion; } void RPCNetwork::attach(INetworkOwner &owner) { LOG_ASSERT(_owner == nullptr); _owner = &owner; _sendV2->attach(*this); _sendAdapters[vespalib::Version(6, 149)] = _sendV2.get(); FRT_ReflectionBuilder builder(_orb.get()); builder.DefineMethod("mbus.getVersion", "", "s", FRT_METHOD(RPCNetwork::invoke), this); builder.MethodDesc("Retrieves the message bus version."); builder.ReturnDesc("version", "The message bus version."); } void RPCNetwork::invoke(FRT_RPCRequest *req) { req->GetReturn()->AddString(getVersion().toString().c_str()); } const string RPCNetwork::getConnectionSpec() const { return make_string("tcp/%s:%d", _ident.getHostname().c_str(), _orb->GetListenPort()); } RPCSendAdapter * RPCNetwork::getSendAdapter(const vespalib::Version &version) { if (version < _sendAdapters.begin()->first) { return nullptr; } return (--_sendAdapters.upper_bound(version))->second; } bool RPCNetwork::start() { if (!_transport->Start(_threadPool.get())) { return false; } if (!_orb->Listen(_requestedPort)) { return false; } return true; } bool RPCNetwork::waitUntilReady(duration timeout) const { slobrok::api::SlobrokList brokerList; slobrok::Configurator::UP configurator = _slobrokCfgFactory->create(brokerList); bool hasConfig = false; for (int64_t i = 0; i < vespalib::count_ms(timeout)/10; ++i) { if (configurator->poll()) { hasConfig = true; } if (_mirror->ready()) { return true; } std::this_thread::sleep_for(10ms); } if (! hasConfig) { LOG(error, "failed to get config for slobroks in %2.2f seconds", vespalib::to_s(timeout)); } else if (! _mirror->ready()) { auto brokers = brokerList.logString(); LOG(error, "mirror (of %s) failed to become ready in %2.2f seconds", brokers.c_str(), vespalib::to_s(timeout)); } return false; } void RPCNetwork::registerSession(const string &session) { if (_ident.getServicePrefix().empty()) { LOG(warning, "The session (%s) will not be registered in the Slobrok since this network has no identity.", session.c_str()); return; } string name = _ident.getServicePrefix(); name += "/"; name += session; _regAPI->registerName(name); } void RPCNetwork::unregisterSession(const string &session) { if (_ident.getServicePrefix().empty()) { return; } if (getPort() <= 0) { return; } string name = _ident.getServicePrefix(); name += "/"; name += session; _regAPI->unregisterName(name); } bool RPCNetwork::allocServiceAddress(RoutingNode &recipient) { const Hop &hop = recipient.getRoute().getHop(0); string service = hop.getServiceName(); Error error = resolveServiceAddress(recipient, service); if (error.getCode() == ErrorCode::NONE) { return true; // service address resolved } recipient.setError(error); return false; // service adddress not resolved } Error RPCNetwork::resolveServiceAddress(RoutingNode &recipient, const string &serviceName) { RPCServiceAddress::UP ret = _servicePool->resolve(serviceName); if ( ! ret) { return Error(ErrorCode::NO_ADDRESS_FOR_SERVICE, make_string("The address of service '%s' could not be resolved. It is not currently " "registered with the Vespa name server. " "The service must be having problems, or the routing configuration is wrong. " "Address resolution attempted from host '%s'", serviceName.c_str(), getIdentity().getHostname().c_str())); } RPCTarget::SP target = _targetPool->getTarget(*_orb, *ret); if ( ! target) { return Error(ErrorCode::CONNECTION_ERROR, make_string("Failed to connect to service '%s' from host '%s'.", serviceName.c_str(), getIdentity().getHostname().c_str())); } ret->setTarget(std::move(target)); // free by freeServiceAddress() recipient.setServiceAddress(std::move(ret)); return Error(); } void RPCNetwork::freeServiceAddress(RoutingNode &recipient) { recipient.setServiceAddress(IServiceAddress::UP()); } void RPCNetwork::send(const Message &msg, const std::vector<RoutingNode*> &recipients) { SendContext &ctx = *(new SendContext(*this, msg, recipients)); // deletes self duration timeout = ctx._msg.getTimeRemainingNow(); for (uint32_t i = 0, len = ctx._recipients.size(); i < len; ++i) { RoutingNode *&recipient = ctx._recipients[i]; RPCServiceAddress &address = static_cast<RPCServiceAddress&>(recipient->getServiceAddress()); LOG_ASSERT(address.hasTarget()); address.getTarget().resolveVersion(timeout, ctx); } } namespace { void emit_recipient_endpoint(vespalib::asciistream& stream, const RoutingNode& recipient) { if (recipient.hasServiceAddress()) { // At this point the service addresses _should_ be RPCServiceAddress instances, // but stay on the safe side of the tracks anyway. const auto* rpc_addr = dynamic_cast<const RPCServiceAddress*>(&recipient.getServiceAddress()); if (rpc_addr) { stream << rpc_addr->getServiceName() << " at " << rpc_addr->getConnectionSpec(); } else { stream << "<non-RPC service address>"; } } else { stream << "<unknown service address>"; } } } vespalib::string RPCNetwork::buildRecipientListString(const SendContext& ctx) { vespalib::asciistream s; bool first = true; for (const auto* recipient : ctx._recipients) { if (!first) { s << ", "; } first = false; emit_recipient_endpoint(s, *recipient); } return s.str(); } void RPCNetwork::send(RPCNetwork::SendContext &ctx) { if (ctx._hasError) { replyError(ctx, ErrorCode::HANDSHAKE_FAILED, make_string("An error occurred while resolving version of recipient(s) [%s] from host '%s'.", buildRecipientListString(ctx).c_str(), getIdentity().getHostname().c_str())); } else { duration timeRemaining = ctx._msg.getTimeRemainingNow(); Blob payload = _owner->getProtocol(ctx._msg.getProtocol())->encode(ctx._version, ctx._msg); RPCSendAdapter *adapter = getSendAdapter(ctx._version); if (adapter == nullptr) { replyError(ctx, ErrorCode::INCOMPATIBLE_VERSION, make_string("Can not send to version '%s' recipient.", ctx._version.toString().c_str())); } else if (timeRemaining == 0ms) { replyError(ctx, ErrorCode::TIMEOUT, "Aborting transmission because zero time remains."); } else if (payload.size() == 0) { replyError(ctx, ErrorCode::ENCODE_ERROR, make_string("Protocol '%s' failed to encode message.", ctx._msg.getProtocol().c_str())); } else if (ctx._recipients.size() == 1) { adapter->sendByHandover(*ctx._recipients.front(), ctx._version, std::move(payload), timeRemaining); } else { for (auto & recipient : ctx._recipients) { adapter->send(*recipient, ctx._version, payload, timeRemaining); } } } } void RPCNetwork::sync() { SyncTask task(_scheduler); task.await(); } void RPCNetwork::shutdown() { // Unschedule any pending target pool flush task that may race with shutdown target flushing _scheduler.Kill(_targetPoolTask.get()); _transport->ShutDown(true); _threadPool->Close(); } void RPCNetwork::postShutdownHook() { _scheduler.CheckTasks(); } const slobrok::api::IMirrorAPI & RPCNetwork::getMirror() const { return *_mirror; } } // namespace mbus <commit_msg>Add missing include<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "rpcnetwork.h" #include "rpcservicepool.h" #include "rpcsendv2.h" #include "rpctargetpool.h" #include "rpcnetworkparams.h" #include <vespa/fnet/frt/supervisor.h> #include <vespa/fnet/scheduler.h> #include <vespa/fnet/transport.h> #include <vespa/messagebus/emptyreply.h> #include <vespa/messagebus/errorcode.h> #include <vespa/messagebus/iprotocol.h> #include <vespa/messagebus/routing/routingnode.h> #include <vespa/slobrok/sbmirror.h> #include <vespa/slobrok/sbregister.h> #include <vespa/vespalib/component/vtag.h> #include <vespa/vespalib/stllike/asciistream.h> #include <vespa/vespalib/util/size_literals.h> #include <vespa/vespalib/util/stringfmt.h> #include <vespa/vespalib/util/gate.h> #include <vespa/fastos/thread.h> #include <thread> #include <vespa/log/log.h> LOG_SETUP(".rpcnetwork"); using vespalib::make_string; using namespace std::chrono_literals; namespace mbus { namespace { /** * Implements a helper class for {@link RPCNetwork#sync()}. It provides a * blocking method {@link #await()} that will wait until the internal state * of this object is set to 'done'. By scheduling this task in the network * thread and then calling this method, we achieve handshaking with the network * thread. */ class SyncTask : public FNET_Task { private: vespalib::Gate _gate; public: SyncTask(FNET_Scheduler &s) : FNET_Task(&s), _gate() { ScheduleNow(); } ~SyncTask() override { Kill(); } void await() { _gate.await(); } void PerformTask() override { _gate.countDown(); } }; struct TargetPoolTask : public FNET_Task { RPCTargetPool &_pool; TargetPoolTask(FNET_Scheduler &scheduler, RPCTargetPool &pool) : FNET_Task(&scheduler), _pool(pool) { ScheduleNow(); } ~TargetPoolTask() override { Kill(); } void PerformTask() override { _pool.flushTargets(false); Schedule(1.0); } }; fnet::TransportConfig toFNETConfig(const RPCNetworkParams & params) { return fnet::TransportConfig(params.getNumNetworkThreads()) .maxInputBufferSize(params.getMaxInputBufferSize()) .maxOutputBufferSize(params.getMaxOutputBufferSize()) .tcpNoDelay(params.getTcpNoDelay()) .events_before_wakeup(params.events_before_wakeup()); } } RPCNetwork::SendContext::SendContext(RPCNetwork &net, const Message &msg, const std::vector<RoutingNode*> &recipients) : _net(net), _msg(msg), _traceLevel(msg.getTrace().getLevel()), _recipients(recipients), _hasError(false), _pending(_recipients.size()), _version(_net.getVersion()) { } void RPCNetwork::SendContext::handleVersion(const vespalib::Version *version) { bool shouldSend = false; { std::lock_guard guard(_lock); if (version == nullptr) { _hasError = true; } else if (*version < _version) { _version = *version; } if (--_pending == 0) { shouldSend = true; } } if (shouldSend) { _net.send(*this); delete this; } } RPCNetwork::RPCNetwork(const RPCNetworkParams &params) : _owner(nullptr), _ident(params.getIdentity()), _threadPool(std::make_unique<FastOS_ThreadPool>(128_Ki, 0)), _transport(std::make_unique<FNET_Transport>(toFNETConfig(params))), _orb(std::make_unique<FRT_Supervisor>(_transport.get())), _scheduler(*_transport->GetScheduler()), _slobrokCfgFactory(std::make_unique<slobrok::ConfiguratorFactory>(params.getSlobrokConfig())), _mirror(std::make_unique<slobrok::api::MirrorAPI>(*_orb, *_slobrokCfgFactory)), _regAPI(std::make_unique<slobrok::api::RegisterAPI>(*_orb, *_slobrokCfgFactory)), _requestedPort(params.getListenPort()), _targetPool(std::make_unique<RPCTargetPool>(params.getConnectionExpireSecs(), params.getNumRpcTargets())), _targetPoolTask(std::make_unique<TargetPoolTask>(_scheduler, *_targetPool)), _servicePool(std::make_unique<RPCServicePool>(*_mirror, 4_Ki)), _sendV2(std::make_unique<RPCSendV2>()), _sendAdapters(), _compressionConfig(params.getCompressionConfig()) { } RPCNetwork::~RPCNetwork() { shutdown(); } FRT_RPCRequest * RPCNetwork::allocRequest() { return _orb->AllocRPCRequest(); } RPCTarget::SP RPCNetwork::getTarget(const RPCServiceAddress &address) { return _targetPool->getTarget(*_orb, address); } void RPCNetwork::replyError(const SendContext &ctx, uint32_t errCode, const string &errMsg) { for (RoutingNode * rnode : ctx._recipients) { Reply::UP reply(new EmptyReply()); reply->setTrace(Trace(ctx._traceLevel)); reply->addError(Error(errCode, errMsg)); _owner->deliverReply(std::move(reply), *rnode); } } int RPCNetwork::getPort() const { return _orb->GetListenPort(); } void RPCNetwork::flushTargetPool() { _targetPool->flushTargets(true); } const vespalib::Version & RPCNetwork::getVersion() const { return vespalib::Vtag::currentVersion; } void RPCNetwork::attach(INetworkOwner &owner) { LOG_ASSERT(_owner == nullptr); _owner = &owner; _sendV2->attach(*this); _sendAdapters[vespalib::Version(6, 149)] = _sendV2.get(); FRT_ReflectionBuilder builder(_orb.get()); builder.DefineMethod("mbus.getVersion", "", "s", FRT_METHOD(RPCNetwork::invoke), this); builder.MethodDesc("Retrieves the message bus version."); builder.ReturnDesc("version", "The message bus version."); } void RPCNetwork::invoke(FRT_RPCRequest *req) { req->GetReturn()->AddString(getVersion().toString().c_str()); } const string RPCNetwork::getConnectionSpec() const { return make_string("tcp/%s:%d", _ident.getHostname().c_str(), _orb->GetListenPort()); } RPCSendAdapter * RPCNetwork::getSendAdapter(const vespalib::Version &version) { if (version < _sendAdapters.begin()->first) { return nullptr; } return (--_sendAdapters.upper_bound(version))->second; } bool RPCNetwork::start() { if (!_transport->Start(_threadPool.get())) { return false; } if (!_orb->Listen(_requestedPort)) { return false; } return true; } bool RPCNetwork::waitUntilReady(duration timeout) const { slobrok::api::SlobrokList brokerList; slobrok::Configurator::UP configurator = _slobrokCfgFactory->create(brokerList); bool hasConfig = false; for (int64_t i = 0; i < vespalib::count_ms(timeout)/10; ++i) { if (configurator->poll()) { hasConfig = true; } if (_mirror->ready()) { return true; } std::this_thread::sleep_for(10ms); } if (! hasConfig) { LOG(error, "failed to get config for slobroks in %2.2f seconds", vespalib::to_s(timeout)); } else if (! _mirror->ready()) { auto brokers = brokerList.logString(); LOG(error, "mirror (of %s) failed to become ready in %2.2f seconds", brokers.c_str(), vespalib::to_s(timeout)); } return false; } void RPCNetwork::registerSession(const string &session) { if (_ident.getServicePrefix().empty()) { LOG(warning, "The session (%s) will not be registered in the Slobrok since this network has no identity.", session.c_str()); return; } string name = _ident.getServicePrefix(); name += "/"; name += session; _regAPI->registerName(name); } void RPCNetwork::unregisterSession(const string &session) { if (_ident.getServicePrefix().empty()) { return; } if (getPort() <= 0) { return; } string name = _ident.getServicePrefix(); name += "/"; name += session; _regAPI->unregisterName(name); } bool RPCNetwork::allocServiceAddress(RoutingNode &recipient) { const Hop &hop = recipient.getRoute().getHop(0); string service = hop.getServiceName(); Error error = resolveServiceAddress(recipient, service); if (error.getCode() == ErrorCode::NONE) { return true; // service address resolved } recipient.setError(error); return false; // service adddress not resolved } Error RPCNetwork::resolveServiceAddress(RoutingNode &recipient, const string &serviceName) { RPCServiceAddress::UP ret = _servicePool->resolve(serviceName); if ( ! ret) { return Error(ErrorCode::NO_ADDRESS_FOR_SERVICE, make_string("The address of service '%s' could not be resolved. It is not currently " "registered with the Vespa name server. " "The service must be having problems, or the routing configuration is wrong. " "Address resolution attempted from host '%s'", serviceName.c_str(), getIdentity().getHostname().c_str())); } RPCTarget::SP target = _targetPool->getTarget(*_orb, *ret); if ( ! target) { return Error(ErrorCode::CONNECTION_ERROR, make_string("Failed to connect to service '%s' from host '%s'.", serviceName.c_str(), getIdentity().getHostname().c_str())); } ret->setTarget(std::move(target)); // free by freeServiceAddress() recipient.setServiceAddress(std::move(ret)); return Error(); } void RPCNetwork::freeServiceAddress(RoutingNode &recipient) { recipient.setServiceAddress(IServiceAddress::UP()); } void RPCNetwork::send(const Message &msg, const std::vector<RoutingNode*> &recipients) { SendContext &ctx = *(new SendContext(*this, msg, recipients)); // deletes self duration timeout = ctx._msg.getTimeRemainingNow(); for (uint32_t i = 0, len = ctx._recipients.size(); i < len; ++i) { RoutingNode *&recipient = ctx._recipients[i]; RPCServiceAddress &address = static_cast<RPCServiceAddress&>(recipient->getServiceAddress()); LOG_ASSERT(address.hasTarget()); address.getTarget().resolveVersion(timeout, ctx); } } namespace { void emit_recipient_endpoint(vespalib::asciistream& stream, const RoutingNode& recipient) { if (recipient.hasServiceAddress()) { // At this point the service addresses _should_ be RPCServiceAddress instances, // but stay on the safe side of the tracks anyway. const auto* rpc_addr = dynamic_cast<const RPCServiceAddress*>(&recipient.getServiceAddress()); if (rpc_addr) { stream << rpc_addr->getServiceName() << " at " << rpc_addr->getConnectionSpec(); } else { stream << "<non-RPC service address>"; } } else { stream << "<unknown service address>"; } } } vespalib::string RPCNetwork::buildRecipientListString(const SendContext& ctx) { vespalib::asciistream s; bool first = true; for (const auto* recipient : ctx._recipients) { if (!first) { s << ", "; } first = false; emit_recipient_endpoint(s, *recipient); } return s.str(); } void RPCNetwork::send(RPCNetwork::SendContext &ctx) { if (ctx._hasError) { replyError(ctx, ErrorCode::HANDSHAKE_FAILED, make_string("An error occurred while resolving version of recipient(s) [%s] from host '%s'.", buildRecipientListString(ctx).c_str(), getIdentity().getHostname().c_str())); } else { duration timeRemaining = ctx._msg.getTimeRemainingNow(); Blob payload = _owner->getProtocol(ctx._msg.getProtocol())->encode(ctx._version, ctx._msg); RPCSendAdapter *adapter = getSendAdapter(ctx._version); if (adapter == nullptr) { replyError(ctx, ErrorCode::INCOMPATIBLE_VERSION, make_string("Can not send to version '%s' recipient.", ctx._version.toString().c_str())); } else if (timeRemaining == 0ms) { replyError(ctx, ErrorCode::TIMEOUT, "Aborting transmission because zero time remains."); } else if (payload.size() == 0) { replyError(ctx, ErrorCode::ENCODE_ERROR, make_string("Protocol '%s' failed to encode message.", ctx._msg.getProtocol().c_str())); } else if (ctx._recipients.size() == 1) { adapter->sendByHandover(*ctx._recipients.front(), ctx._version, std::move(payload), timeRemaining); } else { for (auto & recipient : ctx._recipients) { adapter->send(*recipient, ctx._version, payload, timeRemaining); } } } } void RPCNetwork::sync() { SyncTask task(_scheduler); task.await(); } void RPCNetwork::shutdown() { // Unschedule any pending target pool flush task that may race with shutdown target flushing _scheduler.Kill(_targetPoolTask.get()); _transport->ShutDown(true); _threadPool->Close(); } void RPCNetwork::postShutdownHook() { _scheduler.CheckTasks(); } const slobrok::api::IMirrorAPI & RPCNetwork::getMirror() const { return *_mirror; } } // namespace mbus <|endoftext|>
<commit_before>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <vector> #include <glog/logging.h> #include <gtest/gtest.h> #include <react/renderer/components/root/RootComponentDescriptor.h> #include <react/renderer/components/view/ViewComponentDescriptor.h> #include <react/renderer/mounting/Differentiator.h> #include <react/renderer/mounting/ShadowViewMutation.h> #include <react/renderer/mounting/stubs.h> #include "Entropy.h" #include "shadowTreeGeneration.h" namespace facebook { namespace react { static void testShadowNodeTreeLifeCycle( uint_fast32_t seed, int treeSize, int repeats, int stages) { auto entropy = seed == 0 ? Entropy() : Entropy(seed); auto eventDispatcher = EventDispatcher::Shared{}; auto contextContainer = std::make_shared<ContextContainer>(); auto componentDescriptorParameters = ComponentDescriptorParameters{eventDispatcher, contextContainer, nullptr}; auto viewComponentDescriptor = ViewComponentDescriptor(componentDescriptorParameters); auto rootComponentDescriptor = RootComponentDescriptor(componentDescriptorParameters); auto noopEventEmitter = std::make_shared<ViewEventEmitter const>(nullptr, -1, eventDispatcher); auto allNodes = std::vector<ShadowNode::Shared>{}; for (int i = 0; i < repeats; i++) { allNodes.clear(); auto family = rootComponentDescriptor.createFamily( {Tag(1), SurfaceId(1), nullptr}, nullptr); // Creating an initial root shadow node. auto emptyRootNode = std::const_pointer_cast<RootShadowNode>( std::static_pointer_cast<RootShadowNode const>( rootComponentDescriptor.createShadowNode( ShadowNodeFragment{RootShadowNode::defaultSharedProps()}, family))); // Applying size constraints. emptyRootNode = emptyRootNode->clone( LayoutConstraints{ Size{512, 0}, Size{512, std::numeric_limits<Float>::infinity()}}, LayoutContext{}); // Generation of a random tree. auto singleRootChildNode = generateShadowNodeTree(entropy, viewComponentDescriptor, treeSize); // Injecting a tree into the root node. auto currentRootNode = std::static_pointer_cast<RootShadowNode const>( emptyRootNode->ShadowNode::clone(ShadowNodeFragment{ ShadowNodeFragment::propsPlaceholder(), std::make_shared<SharedShadowNodeList>( SharedShadowNodeList{singleRootChildNode})})); // Building an initial view hierarchy. auto viewTree = buildStubViewTreeWithoutUsingDifferentiator(*emptyRootNode); viewTree.mutate( calculateShadowViewMutations(*emptyRootNode, *currentRootNode, true)); for (int j = 0; j < stages; j++) { auto nextRootNode = currentRootNode; // Mutating the tree. alterShadowTree( entropy, nextRootNode, { &messWithChildren, &messWithYogaStyles, &messWithLayoutableOnlyFlag, }); std::vector<LayoutableShadowNode const *> affectedLayoutableNodes{}; affectedLayoutableNodes.reserve(1024); // Laying out the tree. std::const_pointer_cast<RootShadowNode>(nextRootNode) ->layoutIfNeeded(&affectedLayoutableNodes); nextRootNode->sealRecursive(); allNodes.push_back(nextRootNode); // Calculating mutations. auto mutations = calculateShadowViewMutations(*currentRootNode, *nextRootNode, true); // Make sure that in a single frame, a DELETE for a // view is not followed by a CREATE for the same view. { std::vector<int> deletedTags{}; for (auto const &mutation : mutations) { if (mutation.type == ShadowViewMutation::Type::Delete) { deletedTags.push_back(mutation.oldChildShadowView.tag); } } for (auto const &mutation : mutations) { if (mutation.type == ShadowViewMutation::Type::Create) { if (std::find( deletedTags.begin(), deletedTags.end(), mutation.newChildShadowView.tag) != deletedTags.end()) { LOG(ERROR) << "Deleted tag was recreated in mutations list: [" << mutation.newChildShadowView.tag << "]"; react_native_assert(false); } } } } // Mutating the view tree. viewTree.mutate(mutations); // Building a view tree to compare with. auto rebuiltViewTree = buildStubViewTreeWithoutUsingDifferentiator(*nextRootNode); // Comparing the newly built tree with the updated one. if (rebuiltViewTree != viewTree) { // Something went wrong. LOG(ERROR) << "Entropy seed: " << entropy.getSeed() << "\n"; // There are some issues getting `getDebugDescription` to compile // under test on Android for now. #ifdef RN_DEBUG_STRING_CONVERTIBLE LOG(ERROR) << "Shadow Tree before: \n" << currentRootNode->getDebugDescription(); LOG(ERROR) << "Shadow Tree after: \n" << nextRootNode->getDebugDescription(); LOG(ERROR) << "View Tree before: \n" << getDebugDescription(viewTree.getRootStubView(), {}); LOG(ERROR) << "View Tree after: \n" << getDebugDescription( rebuiltViewTree.getRootStubView(), {}); LOG(ERROR) << "Mutations:" << "\n" << getDebugDescription(mutations, {}); #endif react_native_assert(false); } currentRootNode = nextRootNode; } } SUCCEED(); } static void testShadowNodeTreeLifeCycleExtensiveFlatteningUnflattening( uint_fast32_t seed, int treeSize, int repeats, int stages) { auto entropy = seed == 0 ? Entropy() : Entropy(seed); auto eventDispatcher = EventDispatcher::Shared{}; auto contextContainer = std::make_shared<ContextContainer>(); auto componentDescriptorParameters = ComponentDescriptorParameters{eventDispatcher, contextContainer, nullptr}; auto viewComponentDescriptor = ViewComponentDescriptor(componentDescriptorParameters); auto rootComponentDescriptor = RootComponentDescriptor(componentDescriptorParameters); auto noopEventEmitter = std::make_shared<ViewEventEmitter const>(nullptr, -1, eventDispatcher); auto allNodes = std::vector<ShadowNode::Shared>{}; for (int i = 0; i < repeats; i++) { allNodes.clear(); auto family = rootComponentDescriptor.createFamily( {Tag(1), SurfaceId(1), nullptr}, nullptr); // Creating an initial root shadow node. auto emptyRootNode = std::const_pointer_cast<RootShadowNode>( std::static_pointer_cast<RootShadowNode const>( rootComponentDescriptor.createShadowNode( ShadowNodeFragment{RootShadowNode::defaultSharedProps()}, family))); // Applying size constraints. emptyRootNode = emptyRootNode->clone( LayoutConstraints{ Size{512, 0}, Size{512, std::numeric_limits<Float>::infinity()}}, LayoutContext{}); // Generation of a random tree. auto singleRootChildNode = generateShadowNodeTree(entropy, viewComponentDescriptor, treeSize); // Injecting a tree into the root node. auto currentRootNode = std::static_pointer_cast<RootShadowNode const>( emptyRootNode->ShadowNode::clone(ShadowNodeFragment{ ShadowNodeFragment::propsPlaceholder(), std::make_shared<SharedShadowNodeList>( SharedShadowNodeList{singleRootChildNode})})); // Building an initial view hierarchy. auto viewTree = buildStubViewTreeWithoutUsingDifferentiator(*emptyRootNode); viewTree.mutate( calculateShadowViewMutations(*emptyRootNode, *currentRootNode, true)); for (int j = 0; j < stages; j++) { auto nextRootNode = currentRootNode; // Mutating the tree. alterShadowTree( entropy, nextRootNode, { &messWithYogaStyles, &messWithLayoutableOnlyFlag, }); alterShadowTree(entropy, nextRootNode, &messWithNodeFlattenednessFlags); alterShadowTree(entropy, nextRootNode, &messWithChildren); std::vector<LayoutableShadowNode const *> affectedLayoutableNodes{}; affectedLayoutableNodes.reserve(1024); // Laying out the tree. std::const_pointer_cast<RootShadowNode>(nextRootNode) ->layoutIfNeeded(&affectedLayoutableNodes); nextRootNode->sealRecursive(); allNodes.push_back(nextRootNode); // Calculating mutations. auto mutations = calculateShadowViewMutations(*currentRootNode, *nextRootNode, true); // Make sure that in a single frame, a DELETE for a // view is not followed by a CREATE for the same view. { std::vector<int> deletedTags{}; for (auto const &mutation : mutations) { if (mutation.type == ShadowViewMutation::Type::Delete) { deletedTags.push_back(mutation.oldChildShadowView.tag); } } for (auto const &mutation : mutations) { if (mutation.type == ShadowViewMutation::Type::Create) { if (std::find( deletedTags.begin(), deletedTags.end(), mutation.newChildShadowView.tag) != deletedTags.end()) { LOG(ERROR) << "Deleted tag was recreated in mutations list: [" << mutation.newChildShadowView.tag << "]"; react_native_assert(false); } } } } // Mutating the view tree. viewTree.mutate(mutations); // Building a view tree to compare with. auto rebuiltViewTree = buildStubViewTreeWithoutUsingDifferentiator(*nextRootNode); // Comparing the newly built tree with the updated one. if (rebuiltViewTree != viewTree) { // Something went wrong. LOG(ERROR) << "Entropy seed: " << entropy.getSeed() << "\n"; // There are some issues getting `getDebugDescription` to compile // under test on Android for now. #ifdef RN_DEBUG_STRING_CONVERTIBLE LOG(ERROR) << "Shadow Tree before: \n" << currentRootNode->getDebugDescription(); LOG(ERROR) << "Shadow Tree after: \n" << nextRootNode->getDebugDescription(); LOG(ERROR) << "View Tree before: \n" << getDebugDescription(viewTree.getRootStubView(), {}); LOG(ERROR) << "View Tree after: \n" << getDebugDescription( rebuiltViewTree.getRootStubView(), {}); LOG(ERROR) << "Mutations:" << "\n" << getDebugDescription(mutations, {}); #endif react_native_assert(false); } currentRootNode = nextRootNode; } } SUCCEED(); } } // namespace react } // namespace facebook using namespace facebook::react; TEST( ShadowTreeLifecyleTest, stableBiggerTreeFewerIterationsOptimizedMovesFlattener) { testShadowNodeTreeLifeCycle( /* seed */ 0, /* size */ 512, /* repeats */ 32, /* stages */ 32); } TEST( ShadowTreeLifecyleTest, stableBiggerTreeFewerIterationsOptimizedMovesFlattener2) { testShadowNodeTreeLifeCycle( /* seed */ 1, /* size */ 512, /* repeats */ 32, /* stages */ 32); } TEST( ShadowTreeLifecyleTest, stableSmallerTreeMoreIterationsOptimizedMovesFlattener) { testShadowNodeTreeLifeCycle( /* seed */ 0, /* size */ 16, /* repeats */ 512, /* stages */ 32); } TEST( ShadowTreeLifecyleTest, unstableSmallerTreeFewerIterationsExtensiveFlatteningUnflattening) { testShadowNodeTreeLifeCycleExtensiveFlatteningUnflattening( /* seed */ 1337, /* size */ 32, /* repeats */ 32, /* stages */ 32); } TEST( ShadowTreeLifecyleTest, unstableBiggerTreeFewerIterationsExtensiveFlatteningUnflattening) { testShadowNodeTreeLifeCycleExtensiveFlatteningUnflattening( /* seed */ 1337, /* size */ 256, /* repeats */ 32, /* stages */ 32); } TEST( ShadowTreeLifecyleTest, unstableSmallerTreeMoreIterationsExtensiveFlatteningUnflattening) { testShadowNodeTreeLifeCycleExtensiveFlatteningUnflattening( /* seed */ 1337, /* size */ 32, /* repeats */ 512, /* stages */ 32); } <commit_msg>Testing mechanism to find new failing Differ test-cases<commit_after>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <vector> #include <glog/logging.h> #include <gtest/gtest.h> #include <react/renderer/components/root/RootComponentDescriptor.h> #include <react/renderer/components/view/ViewComponentDescriptor.h> #include <react/renderer/mounting/Differentiator.h> #include <react/renderer/mounting/ShadowViewMutation.h> #include <react/renderer/mounting/stubs.h> // Uncomment when random test blocks are uncommented below. // #include <algorithm> // #include <random> #include "Entropy.h" #include "shadowTreeGeneration.h" namespace facebook { namespace react { static void testShadowNodeTreeLifeCycle( uint_fast32_t seed, int treeSize, int repeats, int stages) { auto entropy = seed == 0 ? Entropy() : Entropy(seed); auto eventDispatcher = EventDispatcher::Shared{}; auto contextContainer = std::make_shared<ContextContainer>(); auto componentDescriptorParameters = ComponentDescriptorParameters{eventDispatcher, contextContainer, nullptr}; auto viewComponentDescriptor = ViewComponentDescriptor(componentDescriptorParameters); auto rootComponentDescriptor = RootComponentDescriptor(componentDescriptorParameters); auto noopEventEmitter = std::make_shared<ViewEventEmitter const>(nullptr, -1, eventDispatcher); auto allNodes = std::vector<ShadowNode::Shared>{}; for (int i = 0; i < repeats; i++) { allNodes.clear(); auto family = rootComponentDescriptor.createFamily( {Tag(1), SurfaceId(1), nullptr}, nullptr); // Creating an initial root shadow node. auto emptyRootNode = std::const_pointer_cast<RootShadowNode>( std::static_pointer_cast<RootShadowNode const>( rootComponentDescriptor.createShadowNode( ShadowNodeFragment{RootShadowNode::defaultSharedProps()}, family))); // Applying size constraints. emptyRootNode = emptyRootNode->clone( LayoutConstraints{ Size{512, 0}, Size{512, std::numeric_limits<Float>::infinity()}}, LayoutContext{}); // Generation of a random tree. auto singleRootChildNode = generateShadowNodeTree(entropy, viewComponentDescriptor, treeSize); // Injecting a tree into the root node. auto currentRootNode = std::static_pointer_cast<RootShadowNode const>( emptyRootNode->ShadowNode::clone(ShadowNodeFragment{ ShadowNodeFragment::propsPlaceholder(), std::make_shared<SharedShadowNodeList>( SharedShadowNodeList{singleRootChildNode})})); // Building an initial view hierarchy. auto viewTree = buildStubViewTreeWithoutUsingDifferentiator(*emptyRootNode); viewTree.mutate( calculateShadowViewMutations(*emptyRootNode, *currentRootNode, true)); for (int j = 0; j < stages; j++) { auto nextRootNode = currentRootNode; // Mutating the tree. alterShadowTree( entropy, nextRootNode, { &messWithChildren, &messWithYogaStyles, &messWithLayoutableOnlyFlag, }); std::vector<LayoutableShadowNode const *> affectedLayoutableNodes{}; affectedLayoutableNodes.reserve(1024); // Laying out the tree. std::const_pointer_cast<RootShadowNode>(nextRootNode) ->layoutIfNeeded(&affectedLayoutableNodes); nextRootNode->sealRecursive(); allNodes.push_back(nextRootNode); // Calculating mutations. auto mutations = calculateShadowViewMutations(*currentRootNode, *nextRootNode, true); // Make sure that in a single frame, a DELETE for a // view is not followed by a CREATE for the same view. { std::vector<int> deletedTags{}; for (auto const &mutation : mutations) { if (mutation.type == ShadowViewMutation::Type::Delete) { deletedTags.push_back(mutation.oldChildShadowView.tag); } } for (auto const &mutation : mutations) { if (mutation.type == ShadowViewMutation::Type::Create) { if (std::find( deletedTags.begin(), deletedTags.end(), mutation.newChildShadowView.tag) != deletedTags.end()) { LOG(ERROR) << "Deleted tag was recreated in mutations list: [" << mutation.newChildShadowView.tag << "]"; react_native_assert(false); } } } } // Mutating the view tree. viewTree.mutate(mutations); // Building a view tree to compare with. auto rebuiltViewTree = buildStubViewTreeWithoutUsingDifferentiator(*nextRootNode); // Comparing the newly built tree with the updated one. if (rebuiltViewTree != viewTree) { // Something went wrong. LOG(ERROR) << "Entropy seed: " << entropy.getSeed() << "\n"; // There are some issues getting `getDebugDescription` to compile // under test on Android for now. #ifdef RN_DEBUG_STRING_CONVERTIBLE LOG(ERROR) << "Shadow Tree before: \n" << currentRootNode->getDebugDescription(); LOG(ERROR) << "Shadow Tree after: \n" << nextRootNode->getDebugDescription(); LOG(ERROR) << "View Tree before: \n" << getDebugDescription(viewTree.getRootStubView(), {}); LOG(ERROR) << "View Tree after: \n" << getDebugDescription( rebuiltViewTree.getRootStubView(), {}); LOG(ERROR) << "Mutations:" << "\n" << getDebugDescription(mutations, {}); #endif react_native_assert(false); } currentRootNode = nextRootNode; } } SUCCEED(); } static void testShadowNodeTreeLifeCycleExtensiveFlatteningUnflattening( uint_fast32_t seed, int treeSize, int repeats, int stages) { auto entropy = seed == 0 ? Entropy() : Entropy(seed); auto eventDispatcher = EventDispatcher::Shared{}; auto contextContainer = std::make_shared<ContextContainer>(); auto componentDescriptorParameters = ComponentDescriptorParameters{eventDispatcher, contextContainer, nullptr}; auto viewComponentDescriptor = ViewComponentDescriptor(componentDescriptorParameters); auto rootComponentDescriptor = RootComponentDescriptor(componentDescriptorParameters); auto noopEventEmitter = std::make_shared<ViewEventEmitter const>(nullptr, -1, eventDispatcher); auto allNodes = std::vector<ShadowNode::Shared>{}; for (int i = 0; i < repeats; i++) { allNodes.clear(); auto family = rootComponentDescriptor.createFamily( {Tag(1), SurfaceId(1), nullptr}, nullptr); // Creating an initial root shadow node. auto emptyRootNode = std::const_pointer_cast<RootShadowNode>( std::static_pointer_cast<RootShadowNode const>( rootComponentDescriptor.createShadowNode( ShadowNodeFragment{RootShadowNode::defaultSharedProps()}, family))); // Applying size constraints. emptyRootNode = emptyRootNode->clone( LayoutConstraints{ Size{512, 0}, Size{512, std::numeric_limits<Float>::infinity()}}, LayoutContext{}); // Generation of a random tree. auto singleRootChildNode = generateShadowNodeTree(entropy, viewComponentDescriptor, treeSize); // Injecting a tree into the root node. auto currentRootNode = std::static_pointer_cast<RootShadowNode const>( emptyRootNode->ShadowNode::clone(ShadowNodeFragment{ ShadowNodeFragment::propsPlaceholder(), std::make_shared<SharedShadowNodeList>( SharedShadowNodeList{singleRootChildNode})})); // Building an initial view hierarchy. auto viewTree = buildStubViewTreeWithoutUsingDifferentiator(*emptyRootNode); viewTree.mutate( calculateShadowViewMutations(*emptyRootNode, *currentRootNode, true)); for (int j = 0; j < stages; j++) { auto nextRootNode = currentRootNode; // Mutating the tree. alterShadowTree( entropy, nextRootNode, { &messWithYogaStyles, &messWithLayoutableOnlyFlag, }); alterShadowTree(entropy, nextRootNode, &messWithNodeFlattenednessFlags); alterShadowTree(entropy, nextRootNode, &messWithChildren); std::vector<LayoutableShadowNode const *> affectedLayoutableNodes{}; affectedLayoutableNodes.reserve(1024); // Laying out the tree. std::const_pointer_cast<RootShadowNode>(nextRootNode) ->layoutIfNeeded(&affectedLayoutableNodes); nextRootNode->sealRecursive(); allNodes.push_back(nextRootNode); // Calculating mutations. auto mutations = calculateShadowViewMutations(*currentRootNode, *nextRootNode, true); // Make sure that in a single frame, a DELETE for a // view is not followed by a CREATE for the same view. { std::vector<int> deletedTags{}; for (auto const &mutation : mutations) { if (mutation.type == ShadowViewMutation::Type::Delete) { deletedTags.push_back(mutation.oldChildShadowView.tag); } } for (auto const &mutation : mutations) { if (mutation.type == ShadowViewMutation::Type::Create) { if (std::find( deletedTags.begin(), deletedTags.end(), mutation.newChildShadowView.tag) != deletedTags.end()) { LOG(ERROR) << "Deleted tag was recreated in mutations list: [" << mutation.newChildShadowView.tag << "]"; react_native_assert(false); } } } } // Mutating the view tree. viewTree.mutate(mutations); // Building a view tree to compare with. auto rebuiltViewTree = buildStubViewTreeWithoutUsingDifferentiator(*nextRootNode); // Comparing the newly built tree with the updated one. if (rebuiltViewTree != viewTree) { // Something went wrong. LOG(ERROR) << "Entropy seed: " << entropy.getSeed() << "\n"; // There are some issues getting `getDebugDescription` to compile // under test on Android for now. #ifdef RN_DEBUG_STRING_CONVERTIBLE LOG(ERROR) << "Shadow Tree before: \n" << currentRootNode->getDebugDescription(); LOG(ERROR) << "Shadow Tree after: \n" << nextRootNode->getDebugDescription(); LOG(ERROR) << "View Tree before: \n" << getDebugDescription(viewTree.getRootStubView(), {}); LOG(ERROR) << "View Tree after: \n" << getDebugDescription( rebuiltViewTree.getRootStubView(), {}); LOG(ERROR) << "Mutations:" << "\n" << getDebugDescription(mutations, {}); #endif react_native_assert(false); } currentRootNode = nextRootNode; } } SUCCEED(); } } // namespace react } // namespace facebook using namespace facebook::react; TEST( ShadowTreeLifecyleTest, stableBiggerTreeFewerIterationsOptimizedMovesFlattener) { testShadowNodeTreeLifeCycle( /* seed */ 0, /* size */ 512, /* repeats */ 32, /* stages */ 32); } TEST( ShadowTreeLifecyleTest, stableBiggerTreeFewerIterationsOptimizedMovesFlattener2) { testShadowNodeTreeLifeCycle( /* seed */ 1, /* size */ 512, /* repeats */ 32, /* stages */ 32); } TEST( ShadowTreeLifecyleTest, stableSmallerTreeMoreIterationsOptimizedMovesFlattener) { testShadowNodeTreeLifeCycle( /* seed */ 0, /* size */ 16, /* repeats */ 512, /* stages */ 32); } TEST( ShadowTreeLifecyleTest, unstableSmallerTreeFewerIterationsExtensiveFlatteningUnflattening) { testShadowNodeTreeLifeCycleExtensiveFlatteningUnflattening( /* seed */ 1337, /* size */ 32, /* repeats */ 32, /* stages */ 32); } TEST( ShadowTreeLifecyleTest, unstableBiggerTreeFewerIterationsExtensiveFlatteningUnflattening) { testShadowNodeTreeLifeCycleExtensiveFlatteningUnflattening( /* seed */ 1337, /* size */ 256, /* repeats */ 32, /* stages */ 32); } TEST( ShadowTreeLifecyleTest, unstableSmallerTreeMoreIterationsExtensiveFlatteningUnflattening) { testShadowNodeTreeLifeCycleExtensiveFlatteningUnflattening( /* seed */ 1337, /* size */ 32, /* repeats */ 512, /* stages */ 32); } // You may uncomment this - locally only! - to generate failing seeds. // TEST( // ShadowTreeLifecyleTest, // unstableSmallerTreeMoreIterationsExtensiveFlatteningUnflatteningManyRandom) // { // std::random_device device; // for (int i = 0; i < 10; i++) { // uint_fast32_t seed = device(); // LOG(ERROR) << "Seed: " << seed; // testShadowNodeTreeLifeCycleExtensiveFlatteningUnflattening( // /* seed */ seed, // /* size */ 32, // /* repeats */ 512, // /* stages */ 32); // } // } <|endoftext|>
<commit_before>#include "navstack_module.h" #include <ros/ros.h> #include <nav_msgs/GetPlan.h> #include <geometry_msgs/PoseStamped.h> #include <map> using std::map; #include <utility> using std::pair; using std::make_pair; #include <boost/foreach.hpp> #ifdef __CDT_PARSER__ #define forEach(a, b) for(a : b) #else #define forEach BOOST_FOREACH #endif #include <sys/times.h> #include <tf/tf.h> #include <tf/transform_listener.h> VERIFY_CONDITIONCHECKER_DEF(pathCost); ros::NodeHandle* g_NodeHandle = NULL; ros::ServiceClient g_GetPlan; /// Plan requests are issued using this frame - so the poses from the planner are given in this frame (e.g. map) std::string g_WorldFrame; double g_GoalTolerance = 0.5; // Using a cache of queried path costs to prevent calling the path planning service multiple times // Better: Can we assume symmetric path costs? map< pair<string,string>, double> g_PathCostCache; void navstack_init(int argc, char** argv) { ROS_ASSERT(argc == 4); // get world frame ros::NodeHandle nhPriv("~"); std::string tfPrefix = tf::getPrefixParam(nhPriv); g_WorldFrame = tf::resolve(tfPrefix, argv[1]); ROS_INFO("World frame is: %s", g_WorldFrame.c_str()); // get goal tolerance char* checkPtr; g_GoalTolerance = strtod(argv[2], &checkPtr); if(checkPtr == argv[2]) { // conversion error! ROS_ERROR("%s: Could not convert argument for goal tolerance: %s", __func__, argv[2]); g_GoalTolerance = 0.5; } if(strcmp(argv[3], "0") == 0) { ROS_INFO("Using absolute goal tolerance."); } else { // relative goal tolerance, argv[3] contains the base_local_planner namespace ROS_INFO("Using relative goal tolerance."); // get base_local_planner's xy_goal_tolerance std::string base_local_planner_ns = argv[3]; double move_base_tol; ros::NodeHandle nh; if(!nh.getParam(base_local_planner_ns + "/xy_goal_tolerance", move_base_tol)) { ROS_ERROR_STREAM("requested relative goal tolerance, but " << (base_local_planner_ns + "/xy_goal_tolerance") << " was not set" << " - falling back to absolute mode"); } else { // 2. add move_base's tolerance to our relative tolerance g_GoalTolerance += move_base_tol; } } ROS_INFO("Goal Tolerance is: %f.", g_GoalTolerance); // init service query for make plan string service_name = "move_base/make_plan"; g_NodeHandle = new ros::NodeHandle(); while(!ros::service::waitForService(service_name, ros::Duration(3.0))) { ROS_ERROR("Service %s not available - waiting.", service_name.c_str()); } g_GetPlan = g_NodeHandle->serviceClient<nav_msgs::GetPlan>(service_name, true); if(!g_GetPlan) { ROS_FATAL("Could not initialize get plan service from %s (client name: %s)", service_name.c_str(), g_GetPlan.getService().c_str()); } ROS_INFO("Initialized Navstack Module.\n"); } bool fillPathRequest(const ParameterList & parameterList, numericalFluentCallbackType numericalFluentCallback, nav_msgs::GetPlan::Request & request) { // get robot and target location from planner interface ROS_ASSERT(parameterList.size() == 2); ParameterList startParams; startParams.push_back(parameterList[0]); ParameterList goalParams; goalParams.push_back(parameterList[1]); NumericalFluentList nfRequest; nfRequest.reserve(14); nfRequest.push_back(NumericalFluent("x", startParams)); nfRequest.push_back(NumericalFluent("y", startParams)); nfRequest.push_back(NumericalFluent("z", startParams)); nfRequest.push_back(NumericalFluent("qx", startParams)); nfRequest.push_back(NumericalFluent("qy", startParams)); nfRequest.push_back(NumericalFluent("qz", startParams)); nfRequest.push_back(NumericalFluent("qw", startParams)); nfRequest.push_back(NumericalFluent("x", goalParams)); nfRequest.push_back(NumericalFluent("y", goalParams)); nfRequest.push_back(NumericalFluent("z", goalParams)); nfRequest.push_back(NumericalFluent("qx", goalParams)); nfRequest.push_back(NumericalFluent("qy", goalParams)); nfRequest.push_back(NumericalFluent("qz", goalParams)); nfRequest.push_back(NumericalFluent("qw", goalParams)); NumericalFluentList* nfRequestP = &nfRequest; if(!numericalFluentCallback(nfRequestP)) { ROS_ERROR("numericalFluentCallback failed."); return false; } // create the path planning query for service request.start.header.frame_id = g_WorldFrame; request.goal.header.frame_id = g_WorldFrame; request.start.pose.position.x = nfRequest[0].value; request.start.pose.position.y = nfRequest[1].value; request.start.pose.position.z = nfRequest[2].value; request.start.pose.orientation.x = nfRequest[3].value; request.start.pose.orientation.y = nfRequest[4].value; request.start.pose.orientation.z = nfRequest[5].value; request.start.pose.orientation.w = nfRequest[6].value; request.goal.pose.position.x = nfRequest[7].value; request.goal.pose.position.y = nfRequest[8].value; request.goal.pose.position.z = nfRequest[9].value; request.goal.pose.orientation.x = nfRequest[10].value; request.goal.pose.orientation.y = nfRequest[11].value; request.goal.pose.orientation.z = nfRequest[12].value; request.goal.pose.orientation.w = nfRequest[13].value; request.tolerance = g_GoalTolerance; return true; } double pathCost(const ParameterList & parameterList, predicateCallbackType predicateCallback, numericalFluentCallbackType numericalFluentCallback, int relaxed) { if(g_Debug) { // prevent spamming ROS_DEBUG calls unless we really want debug // debugging raw planner calls static unsigned int calls = 0; calls++; if(calls % 10000 == 0) { ROS_DEBUG("Got %d module calls.\n", calls); } } // first lookup in the cache if we answered the query already map<pair<string, string>, double>::iterator it = g_PathCostCache.find(make_pair(parameterList[0].value, parameterList[1].value)); if(it != g_PathCostCache.end()) { return it->second; } nav_msgs::GetPlan srv; if(!fillPathRequest(parameterList, numericalFluentCallback, srv.request)) { return INFINITE_COST; } double cost = INFINITE_COST; if(!g_GetPlan) { ROS_ERROR("Persistent service connection to %s failed.", g_GetPlan.getService().c_str()); // FIXME reconnect - this shouldn't happen. return INFINITE_COST; } // statistics about using the ros path planner service static double plannerCalls = 0; static ros::Duration totalCallsTime = ros::Duration(0.0); plannerCalls += 1.0; ros::Time callStartTime = ros::Time::now(); // This construct is here, because when the robot is moving move_base will not produce other paths // we retry for a certain amount of time to not fail directly. // FIXME: Cleanup the goto code retryGetPlan: static unsigned int failCounter = 0; // perform the actual path planner call if(g_GetPlan.call(srv)) { failCounter = 0; if(g_Debug) { ros::Time callEndTime = ros::Time::now(); ros::Duration dt = callEndTime - callStartTime; totalCallsTime += dt; ROS_DEBUG("ServiceCall took: %f, avg: %f (num %f).", dt.toSec(), totalCallsTime.toSec()/plannerCalls, plannerCalls); } if(!srv.response.plan.poses.empty()) { // get plan cost double pathLength = 0; geometry_msgs::PoseStamped lastPose = srv.response.plan.poses[0]; forEach(const geometry_msgs::PoseStamped & p, srv.response.plan.poses) { double d = hypot(lastPose.pose.position.x - p.pose.position.x, lastPose.pose.position.y - p.pose.position.y); pathLength += d; lastPose = p; } cost = pathLength; } else { ROS_WARN("Got empty plan: %s -> %s", parameterList[0].value.c_str(), parameterList[1].value.c_str()); } //ROS_INFO("Got plan: %s -> %s cost: %f.", parameterList[0].value.c_str(), parameterList[1].value.c_str(), cost); // also empty plan = OK or fail or none? } else { ROS_ERROR("Failed to call service %s - is the robot moving?", g_GetPlan.getService().c_str()); failCounter++; if(failCounter < 300) { usleep(1000 * 1000); goto retryGetPlan; } // FIXME: what if target is unreachable, do we get false or an empty plan? i.e. is this an error return INFINITE_COST; } // return pathcost and cache g_PathCostCache[make_pair(parameterList[0].value, parameterList[1].value)] = cost; return cost; } <commit_msg>navstack_module tries to auto estimate ns<commit_after>#include "navstack_module.h" #include <ros/ros.h> #include <nav_msgs/GetPlan.h> #include <geometry_msgs/PoseStamped.h> #include <map> using std::map; #include <utility> using std::pair; using std::make_pair; #include <boost/foreach.hpp> #ifdef __CDT_PARSER__ #define forEach(a, b) for(a : b) #else #define forEach BOOST_FOREACH #endif #include <sys/times.h> #include <tf/tf.h> #include <tf/transform_listener.h> VERIFY_CONDITIONCHECKER_DEF(pathCost); ros::NodeHandle* g_NodeHandle = NULL; ros::ServiceClient g_GetPlan; /// Plan requests are issued using this frame - so the poses from the planner are given in this frame (e.g. map) std::string g_WorldFrame; double g_GoalTolerance = 0.5; // Using a cache of queried path costs to prevent calling the path planning service multiple times // Better: Can we assume symmetric path costs? map< pair<string,string>, double> g_PathCostCache; void navstack_init(int argc, char** argv) { ROS_ASSERT(argc == 4); // get world frame ros::NodeHandle nhPriv("~"); std::string tfPrefix = tf::getPrefixParam(nhPriv); g_WorldFrame = tf::resolve(tfPrefix, argv[1]); ROS_INFO("World frame is: %s", g_WorldFrame.c_str()); // get goal tolerance char* checkPtr; g_GoalTolerance = strtod(argv[2], &checkPtr); if(checkPtr == argv[2]) { // conversion error! ROS_ERROR("%s: Could not convert argument for goal tolerance: %s", __func__, argv[2]); g_GoalTolerance = 0.5; } ros::NodeHandle nh; std::string base_local_planner_ns; if(strcmp(argv[3], "0") == 0) { ROS_INFO("Using absolute goal tolerance."); } else if(strcmp(argv[3], "1") == 0) { ROS_INFO("Trying to estimate base_local_planner namespace"); std::string local_planner; if(!nh.getParam("move_base_node/base_local_planner", local_planner) && !nh.getParam("move_base/base_local_planner", local_planner)) { ROS_ERROR("move_base(_node)/base_local_planner not set - falling back to absolute mode."); } else { // dwa_local_planner/DWAPlannerROS -> DWAPlannerROS std::string::size_type x = local_planner.find_last_of("/"); if(x == std::string::npos) base_local_planner_ns = local_planner; else base_local_planner_ns = local_planner.substr(x + 1); ROS_INFO("Estimated base_local_planner_ns to %s.", base_local_planner_ns.c_str()); } } else { base_local_planner_ns = argv[3]; } if(!base_local_planner_ns.empty()) { // relative goal tolerance, argv[3] contains the base_local_planner namespace ROS_INFO("Using relative goal tolerance."); // get base_local_planner's xy_goal_tolerance double move_base_tol; if(!nh.getParam(base_local_planner_ns + "/xy_goal_tolerance", move_base_tol)) { ROS_ERROR_STREAM("requested relative goal tolerance, but " << (base_local_planner_ns + "/xy_goal_tolerance") << " was not set" << " - falling back to absolute mode"); } else { // 2. add move_base's tolerance to our relative tolerance g_GoalTolerance += move_base_tol; } } ROS_INFO("Goal Tolerance is: %f.", g_GoalTolerance); // init service query for make plan string service_name = "move_base/make_plan"; g_NodeHandle = new ros::NodeHandle(); while(!ros::service::waitForService(service_name, ros::Duration(3.0))) { ROS_ERROR("Service %s not available - waiting.", service_name.c_str()); } g_GetPlan = g_NodeHandle->serviceClient<nav_msgs::GetPlan>(service_name, true); if(!g_GetPlan) { ROS_FATAL("Could not initialize get plan service from %s (client name: %s)", service_name.c_str(), g_GetPlan.getService().c_str()); } ROS_INFO("Initialized Navstack Module.\n"); } bool fillPathRequest(const ParameterList & parameterList, numericalFluentCallbackType numericalFluentCallback, nav_msgs::GetPlan::Request & request) { // get robot and target location from planner interface ROS_ASSERT(parameterList.size() == 2); ParameterList startParams; startParams.push_back(parameterList[0]); ParameterList goalParams; goalParams.push_back(parameterList[1]); NumericalFluentList nfRequest; nfRequest.reserve(14); nfRequest.push_back(NumericalFluent("x", startParams)); nfRequest.push_back(NumericalFluent("y", startParams)); nfRequest.push_back(NumericalFluent("z", startParams)); nfRequest.push_back(NumericalFluent("qx", startParams)); nfRequest.push_back(NumericalFluent("qy", startParams)); nfRequest.push_back(NumericalFluent("qz", startParams)); nfRequest.push_back(NumericalFluent("qw", startParams)); nfRequest.push_back(NumericalFluent("x", goalParams)); nfRequest.push_back(NumericalFluent("y", goalParams)); nfRequest.push_back(NumericalFluent("z", goalParams)); nfRequest.push_back(NumericalFluent("qx", goalParams)); nfRequest.push_back(NumericalFluent("qy", goalParams)); nfRequest.push_back(NumericalFluent("qz", goalParams)); nfRequest.push_back(NumericalFluent("qw", goalParams)); NumericalFluentList* nfRequestP = &nfRequest; if(!numericalFluentCallback(nfRequestP)) { ROS_ERROR("numericalFluentCallback failed."); return false; } // create the path planning query for service request.start.header.frame_id = g_WorldFrame; request.goal.header.frame_id = g_WorldFrame; request.start.pose.position.x = nfRequest[0].value; request.start.pose.position.y = nfRequest[1].value; request.start.pose.position.z = nfRequest[2].value; request.start.pose.orientation.x = nfRequest[3].value; request.start.pose.orientation.y = nfRequest[4].value; request.start.pose.orientation.z = nfRequest[5].value; request.start.pose.orientation.w = nfRequest[6].value; request.goal.pose.position.x = nfRequest[7].value; request.goal.pose.position.y = nfRequest[8].value; request.goal.pose.position.z = nfRequest[9].value; request.goal.pose.orientation.x = nfRequest[10].value; request.goal.pose.orientation.y = nfRequest[11].value; request.goal.pose.orientation.z = nfRequest[12].value; request.goal.pose.orientation.w = nfRequest[13].value; request.tolerance = g_GoalTolerance; return true; } double pathCost(const ParameterList & parameterList, predicateCallbackType predicateCallback, numericalFluentCallbackType numericalFluentCallback, int relaxed) { if(g_Debug) { // prevent spamming ROS_DEBUG calls unless we really want debug // debugging raw planner calls static unsigned int calls = 0; calls++; if(calls % 10000 == 0) { ROS_DEBUG("Got %d module calls.\n", calls); } } // first lookup in the cache if we answered the query already map<pair<string, string>, double>::iterator it = g_PathCostCache.find(make_pair(parameterList[0].value, parameterList[1].value)); if(it != g_PathCostCache.end()) { return it->second; } nav_msgs::GetPlan srv; if(!fillPathRequest(parameterList, numericalFluentCallback, srv.request)) { return INFINITE_COST; } double cost = INFINITE_COST; if(!g_GetPlan) { ROS_ERROR("Persistent service connection to %s failed.", g_GetPlan.getService().c_str()); // FIXME reconnect - this shouldn't happen. return INFINITE_COST; } // statistics about using the ros path planner service static double plannerCalls = 0; static ros::Duration totalCallsTime = ros::Duration(0.0); plannerCalls += 1.0; ros::Time callStartTime = ros::Time::now(); // This construct is here, because when the robot is moving move_base will not produce other paths // we retry for a certain amount of time to not fail directly. // FIXME: Cleanup the goto code retryGetPlan: static unsigned int failCounter = 0; // perform the actual path planner call if(g_GetPlan.call(srv)) { failCounter = 0; if(g_Debug) { ros::Time callEndTime = ros::Time::now(); ros::Duration dt = callEndTime - callStartTime; totalCallsTime += dt; ROS_DEBUG("ServiceCall took: %f, avg: %f (num %f).", dt.toSec(), totalCallsTime.toSec()/plannerCalls, plannerCalls); } if(!srv.response.plan.poses.empty()) { // get plan cost double pathLength = 0; geometry_msgs::PoseStamped lastPose = srv.response.plan.poses[0]; forEach(const geometry_msgs::PoseStamped & p, srv.response.plan.poses) { double d = hypot(lastPose.pose.position.x - p.pose.position.x, lastPose.pose.position.y - p.pose.position.y); pathLength += d; lastPose = p; } cost = pathLength; } else { ROS_WARN("Got empty plan: %s -> %s", parameterList[0].value.c_str(), parameterList[1].value.c_str()); } //ROS_INFO("Got plan: %s -> %s cost: %f.", parameterList[0].value.c_str(), parameterList[1].value.c_str(), cost); // also empty plan = OK or fail or none? } else { ROS_ERROR("Failed to call service %s - is the robot moving?", g_GetPlan.getService().c_str()); failCounter++; if(failCounter < 300) { usleep(1000 * 1000); goto retryGetPlan; } // FIXME: what if target is unreachable, do we get false or an empty plan? i.e. is this an error return INFINITE_COST; } // return pathcost and cache g_PathCostCache[make_pair(parameterList[0].value, parameterList[1].value)] = cost; return cost; } <|endoftext|>
<commit_before>#include <iostream> // Include before boost::log headers #include "restc-cpp/logging.h" #include "restc-cpp/restc-cpp.h" #include "restc-cpp/RequestBuilder.h" #include "restc-cpp/test_helper.h" #include "lest/lest.hpp" using namespace std; using namespace restc_cpp; static const string defunct_proxy_address = GetDockerUrl("http://172.17.0.1:0"); static const string http_proxy_address = GetDockerUrl("http://172.17.0.1:3003"); static const string socks5_proxy_address = GetDockerUrl("172.17.0.1:3004"); const lest::test specification[] = { STARTCASE(TestFailToConnect) { Request::Properties properties; properties.proxy.type = Request::Proxy::Type::HTTP; properties.proxy.address = defunct_proxy_address; // Create the client with our configuration auto rest_client = RestClient::Create(properties); EXPECT_THROWS(rest_client->ProcessWithPromise([&](Context& ctx) { auto reply = RequestBuilder(ctx) .Get("http://api.example.com/normal/posts/1") .Execute(); }).get()); } ENDCASE STARTCASE(TestWithHttpProxy) { Request::Properties properties; properties.proxy.type = Request::Proxy::Type::HTTP; properties.proxy.address = http_proxy_address; // Create the client with our configuration auto rest_client = RestClient::Create(properties); rest_client->ProcessWithPromise([&](Context& ctx) { auto reply = RequestBuilder(ctx) .Get("http://api.example.com/normal/posts/1") .Execute(); cout << "Got: " << reply->GetBodyAsString() << endl; }).get(); } ENDCASE STARTCASE(TestWithSocks5Proxy) { Request::Properties properties; properties.proxy.type = Request::Proxy::Type::SOCKS5; properties.proxy.address = socks5_proxy_address; // Create the client with our configuration auto rest_client = RestClient::Create(properties); rest_client->ProcessWithPromise([&](Context& ctx) { auto reply = RequestBuilder(ctx) .Get("http://api.example.com/normal/posts/1") .Execute(); cout << "Got: " << reply->GetBodyAsString() << endl; }).get(); } ENDCASE }; //lest int main( int argc, char * argv[] ) { RESTC_CPP_TEST_LOGGING_SETUP("debug"); return lest::run( specification, argc, argv ); } <commit_msg>Changed (back) the default address to mock backend<commit_after>#include <iostream> // Include before boost::log headers #include "restc-cpp/logging.h" #include "restc-cpp/restc-cpp.h" #include "restc-cpp/RequestBuilder.h" #include "restc-cpp/test_helper.h" #include "lest/lest.hpp" using namespace std; using namespace restc_cpp; static const string defunct_proxy_address = GetDockerUrl("http://localhost:0"); static const string http_proxy_address = GetDockerUrl("http://localhost:3003"); static const string socks5_proxy_address = GetDockerUrl("localhost:3004"); const lest::test specification[] = { STARTCASE(TestFailToConnect) { Request::Properties properties; properties.proxy.type = Request::Proxy::Type::HTTP; properties.proxy.address = defunct_proxy_address; // Create the client with our configuration auto rest_client = RestClient::Create(properties); EXPECT_THROWS(rest_client->ProcessWithPromise([&](Context& ctx) { auto reply = RequestBuilder(ctx) .Get("http://api.example.com/normal/posts/1") .Execute(); }).get()); } ENDCASE STARTCASE(TestWithHttpProxy) { Request::Properties properties; properties.proxy.type = Request::Proxy::Type::HTTP; properties.proxy.address = http_proxy_address; // Create the client with our configuration auto rest_client = RestClient::Create(properties); rest_client->ProcessWithPromise([&](Context& ctx) { auto reply = RequestBuilder(ctx) .Get("http://api.example.com/normal/posts/1") .Execute(); cout << "Got: " << reply->GetBodyAsString() << endl; }).get(); } ENDCASE STARTCASE(TestWithSocks5Proxy) { Request::Properties properties; properties.proxy.type = Request::Proxy::Type::SOCKS5; properties.proxy.address = socks5_proxy_address; // Create the client with our configuration auto rest_client = RestClient::Create(properties); rest_client->ProcessWithPromise([&](Context& ctx) { auto reply = RequestBuilder(ctx) .Get("http://api.example.com/normal/posts/1") .Execute(); cout << "Got: " << reply->GetBodyAsString() << endl; }).get(); } ENDCASE }; //lest int main( int argc, char * argv[] ) { RESTC_CPP_TEST_LOGGING_SETUP("debug"); return lest::run( specification, argc, argv ); } <|endoftext|>
<commit_before>/*------------------------------------------------------------------------- * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2018 Advanced Micro Devices, Inc. * Copyright (c) 2018 The Khronos Group Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief VK_KHR_driver_properties tests *//*--------------------------------------------------------------------*/ #include "vktApiDriverPropertiesTests.hpp" #include "vktTestGroupUtil.hpp" #include "vktTestCaseUtil.hpp" #include "vkQueryUtil.hpp" #include "vkTypeUtil.hpp" #include "vkKnownDriverIds.inl" using namespace vk; namespace vkt { namespace api { namespace { enum TestType { TEST_TYPE_DRIVER_ID_MATCH = 0, TEST_TYPE_NAME_IS_NOT_EMPTY, TEST_TYPE_NAME_ZERO_TERMINATED, TEST_TYPE_INFO_ZERO_TERMINATED, TEST_TYPE_VERSION, }; static const VkConformanceVersion knownConformanceVersions[] = { #ifndef CTS_USES_VULKANSC makeConformanceVersion(1, 3, 3, 0), makeConformanceVersion(1, 3, 2, 0), makeConformanceVersion(1, 3, 1, 1), makeConformanceVersion(1, 3, 1, 0), makeConformanceVersion(1, 3, 0, 0), makeConformanceVersion(1, 2, 8, 0), makeConformanceVersion(1, 2, 7, 2), makeConformanceVersion(1, 2, 7, 1), makeConformanceVersion(1, 2, 7, 0), makeConformanceVersion(1, 2, 6, 2), makeConformanceVersion(1, 2, 6, 1), makeConformanceVersion(1, 2, 6, 0), makeConformanceVersion(1, 2, 5, 2), makeConformanceVersion(1, 2, 5, 1), makeConformanceVersion(1, 2, 5, 0), makeConformanceVersion(1, 2, 4, 1), makeConformanceVersion(1, 2, 4, 0), makeConformanceVersion(1, 2, 3, 3), makeConformanceVersion(1, 2, 3, 2), makeConformanceVersion(1, 2, 3, 1), makeConformanceVersion(1, 2, 3, 0), makeConformanceVersion(1, 2, 2, 2), makeConformanceVersion(1, 2, 2, 1), makeConformanceVersion(1, 2, 2, 0), makeConformanceVersion(1, 2, 1, 2), makeConformanceVersion(1, 2, 1, 1), makeConformanceVersion(1, 2, 1, 0), makeConformanceVersion(1, 2, 0, 2), makeConformanceVersion(1, 2, 0, 1), makeConformanceVersion(1, 2, 0, 0), makeConformanceVersion(1, 1, 6, 3), makeConformanceVersion(1, 1, 6, 2), makeConformanceVersion(1, 1, 6, 1), makeConformanceVersion(1, 1, 6, 0), makeConformanceVersion(1, 1, 5, 2), makeConformanceVersion(1, 1, 5, 1), makeConformanceVersion(1, 1, 5, 0), makeConformanceVersion(1, 1, 4, 3), makeConformanceVersion(1, 1, 4, 2), makeConformanceVersion(1, 1, 4, 1), makeConformanceVersion(1, 1, 4, 0), makeConformanceVersion(1, 1, 3, 3), makeConformanceVersion(1, 1, 3, 2), makeConformanceVersion(1, 1, 3, 1), makeConformanceVersion(1, 1, 3, 0), #else makeConformanceVersion(1, 0, 0, 0), #endif // CTS_USES_VULKANSC }; DE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize) { return deStrnlen(str, maxSize) < maxSize; } DE_INLINE bool operator==(const VkConformanceVersion& a, const VkConformanceVersion& b) { return ((a.major == b.major) && (a.minor == b.minor) && (a.subminor == b.subminor) && (a.patch == b.patch)); } void checkSupport (Context& context, const TestType config) { DE_UNREF(config); context.requireDeviceFunctionality("VK_KHR_driver_properties"); } void testDriverMatch (const VkPhysicalDeviceDriverProperties& deviceDriverProperties) { for (deUint32 driverNdx = 0; driverNdx < DE_LENGTH_OF_ARRAY(driverIds); driverNdx++) { if (deviceDriverProperties.driverID == driverIds[driverNdx].id) return; } TCU_FAIL("Driver ID did not match any known driver"); } void testNameIsNotEmpty (const VkPhysicalDeviceDriverProperties& deviceDriverProperties) { if (deviceDriverProperties.driverName[0] == 0) TCU_FAIL("Driver name is empty"); } void testNameZeroTerminated (const VkPhysicalDeviceDriverProperties& deviceDriverProperties) { if (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE)) TCU_FAIL("Driver name is not a null-terminated string"); } void testInfoZeroTerminated (const VkPhysicalDeviceDriverProperties& deviceDriverProperties) { if (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE)) TCU_FAIL("Driver info is not a null-terminated string"); } void testVersion (const VkPhysicalDeviceDriverProperties& deviceDriverProperties, deUint32 usedApiVersion) { const deUint32 apiMajorVersion = VK_API_VERSION_MAJOR(usedApiVersion); const deUint32 apiMinorVersion = VK_API_VERSION_MINOR(usedApiVersion); if (deviceDriverProperties.conformanceVersion.major < apiMajorVersion || (deviceDriverProperties.conformanceVersion.major == apiMajorVersion && deviceDriverProperties.conformanceVersion.minor < apiMinorVersion)) { TCU_FAIL("Wrong driver conformance version (older than used API version)"); } for (const VkConformanceVersion* pConformanceVersion = knownConformanceVersions; pConformanceVersion != DE_ARRAY_END(knownConformanceVersions); ++pConformanceVersion) { if (deviceDriverProperties.conformanceVersion == *pConformanceVersion) return; } TCU_FAIL("Wrong driver conformance version (not known)"); } tcu::TestStatus testQueryProperties (Context& context, const TestType testType) { // Query the driver properties const VkPhysicalDevice physDevice = context.getPhysicalDevice(); const int memsetPattern = 0xaa; VkPhysicalDeviceProperties2 deviceProperties2; VkPhysicalDeviceDriverProperties deviceDriverProperties; deMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties)); deviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES; deviceDriverProperties.pNext = DE_NULL; deMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2)); deviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2; deviceProperties2.pNext = &deviceDriverProperties; context.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2); // Verify the returned values switch (testType) { case TEST_TYPE_DRIVER_ID_MATCH: testDriverMatch (deviceDriverProperties); break; case TEST_TYPE_NAME_IS_NOT_EMPTY: testNameIsNotEmpty (deviceDriverProperties); break; case TEST_TYPE_NAME_ZERO_TERMINATED: testNameZeroTerminated (deviceDriverProperties); break; case TEST_TYPE_INFO_ZERO_TERMINATED: testInfoZeroTerminated (deviceDriverProperties); break; case TEST_TYPE_VERSION: testVersion (deviceDriverProperties, context.getUsedApiVersion()); break; default: TCU_THROW(InternalError, "Unknown test type specified"); } return tcu::TestStatus::pass("Pass"); } void createTestCases (tcu::TestCaseGroup* group) { addFunctionCase(group, "driver_id_match", "Check driverID is supported", checkSupport, testQueryProperties, TEST_TYPE_DRIVER_ID_MATCH); addFunctionCase(group, "name_is_not_empty", "Check name field is not empty", checkSupport, testQueryProperties, TEST_TYPE_NAME_IS_NOT_EMPTY); addFunctionCase(group, "name_zero_terminated", "Check name field is zero-terminated", checkSupport, testQueryProperties, TEST_TYPE_NAME_ZERO_TERMINATED); addFunctionCase(group, "info_zero_terminated", "Check info field is zero-terminated", checkSupport, testQueryProperties, TEST_TYPE_INFO_ZERO_TERMINATED); addFunctionCase(group, "conformance_version", "Check conformanceVersion reported by driver", checkSupport, testQueryProperties, TEST_TYPE_VERSION); } } // anonymous tcu::TestCaseGroup* createDriverPropertiesTests(tcu::TestContext& testCtx) { return createTestGroup(testCtx, "driver_properties", "VK_KHR_driver_properties tests", createTestCases); } } // api } // vkt <commit_msg>Update known conformance version for 1.3.3.1<commit_after>/*------------------------------------------------------------------------- * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2018 Advanced Micro Devices, Inc. * Copyright (c) 2018 The Khronos Group Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief VK_KHR_driver_properties tests *//*--------------------------------------------------------------------*/ #include "vktApiDriverPropertiesTests.hpp" #include "vktTestGroupUtil.hpp" #include "vktTestCaseUtil.hpp" #include "vkQueryUtil.hpp" #include "vkTypeUtil.hpp" #include "vkKnownDriverIds.inl" using namespace vk; namespace vkt { namespace api { namespace { enum TestType { TEST_TYPE_DRIVER_ID_MATCH = 0, TEST_TYPE_NAME_IS_NOT_EMPTY, TEST_TYPE_NAME_ZERO_TERMINATED, TEST_TYPE_INFO_ZERO_TERMINATED, TEST_TYPE_VERSION, }; static const VkConformanceVersion knownConformanceVersions[] = { #ifndef CTS_USES_VULKANSC makeConformanceVersion(1, 3, 3, 1), makeConformanceVersion(1, 3, 3, 0), makeConformanceVersion(1, 3, 2, 0), makeConformanceVersion(1, 3, 1, 1), makeConformanceVersion(1, 3, 1, 0), makeConformanceVersion(1, 3, 0, 0), makeConformanceVersion(1, 2, 8, 0), makeConformanceVersion(1, 2, 7, 2), makeConformanceVersion(1, 2, 7, 1), makeConformanceVersion(1, 2, 7, 0), makeConformanceVersion(1, 2, 6, 2), makeConformanceVersion(1, 2, 6, 1), makeConformanceVersion(1, 2, 6, 0), makeConformanceVersion(1, 2, 5, 2), makeConformanceVersion(1, 2, 5, 1), makeConformanceVersion(1, 2, 5, 0), makeConformanceVersion(1, 2, 4, 1), makeConformanceVersion(1, 2, 4, 0), makeConformanceVersion(1, 2, 3, 3), makeConformanceVersion(1, 2, 3, 2), makeConformanceVersion(1, 2, 3, 1), makeConformanceVersion(1, 2, 3, 0), makeConformanceVersion(1, 2, 2, 2), makeConformanceVersion(1, 2, 2, 1), makeConformanceVersion(1, 2, 2, 0), makeConformanceVersion(1, 2, 1, 2), makeConformanceVersion(1, 2, 1, 1), makeConformanceVersion(1, 2, 1, 0), makeConformanceVersion(1, 2, 0, 2), makeConformanceVersion(1, 2, 0, 1), makeConformanceVersion(1, 2, 0, 0), makeConformanceVersion(1, 1, 6, 3), makeConformanceVersion(1, 1, 6, 2), makeConformanceVersion(1, 1, 6, 1), makeConformanceVersion(1, 1, 6, 0), makeConformanceVersion(1, 1, 5, 2), makeConformanceVersion(1, 1, 5, 1), makeConformanceVersion(1, 1, 5, 0), makeConformanceVersion(1, 1, 4, 3), makeConformanceVersion(1, 1, 4, 2), makeConformanceVersion(1, 1, 4, 1), makeConformanceVersion(1, 1, 4, 0), makeConformanceVersion(1, 1, 3, 3), makeConformanceVersion(1, 1, 3, 2), makeConformanceVersion(1, 1, 3, 1), makeConformanceVersion(1, 1, 3, 0), #else makeConformanceVersion(1, 0, 0, 0), #endif // CTS_USES_VULKANSC }; DE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize) { return deStrnlen(str, maxSize) < maxSize; } DE_INLINE bool operator==(const VkConformanceVersion& a, const VkConformanceVersion& b) { return ((a.major == b.major) && (a.minor == b.minor) && (a.subminor == b.subminor) && (a.patch == b.patch)); } void checkSupport (Context& context, const TestType config) { DE_UNREF(config); context.requireDeviceFunctionality("VK_KHR_driver_properties"); } void testDriverMatch (const VkPhysicalDeviceDriverProperties& deviceDriverProperties) { for (deUint32 driverNdx = 0; driverNdx < DE_LENGTH_OF_ARRAY(driverIds); driverNdx++) { if (deviceDriverProperties.driverID == driverIds[driverNdx].id) return; } TCU_FAIL("Driver ID did not match any known driver"); } void testNameIsNotEmpty (const VkPhysicalDeviceDriverProperties& deviceDriverProperties) { if (deviceDriverProperties.driverName[0] == 0) TCU_FAIL("Driver name is empty"); } void testNameZeroTerminated (const VkPhysicalDeviceDriverProperties& deviceDriverProperties) { if (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE)) TCU_FAIL("Driver name is not a null-terminated string"); } void testInfoZeroTerminated (const VkPhysicalDeviceDriverProperties& deviceDriverProperties) { if (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE)) TCU_FAIL("Driver info is not a null-terminated string"); } void testVersion (const VkPhysicalDeviceDriverProperties& deviceDriverProperties, deUint32 usedApiVersion) { const deUint32 apiMajorVersion = VK_API_VERSION_MAJOR(usedApiVersion); const deUint32 apiMinorVersion = VK_API_VERSION_MINOR(usedApiVersion); if (deviceDriverProperties.conformanceVersion.major < apiMajorVersion || (deviceDriverProperties.conformanceVersion.major == apiMajorVersion && deviceDriverProperties.conformanceVersion.minor < apiMinorVersion)) { TCU_FAIL("Wrong driver conformance version (older than used API version)"); } for (const VkConformanceVersion* pConformanceVersion = knownConformanceVersions; pConformanceVersion != DE_ARRAY_END(knownConformanceVersions); ++pConformanceVersion) { if (deviceDriverProperties.conformanceVersion == *pConformanceVersion) return; } TCU_FAIL("Wrong driver conformance version (not known)"); } tcu::TestStatus testQueryProperties (Context& context, const TestType testType) { // Query the driver properties const VkPhysicalDevice physDevice = context.getPhysicalDevice(); const int memsetPattern = 0xaa; VkPhysicalDeviceProperties2 deviceProperties2; VkPhysicalDeviceDriverProperties deviceDriverProperties; deMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties)); deviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES; deviceDriverProperties.pNext = DE_NULL; deMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2)); deviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2; deviceProperties2.pNext = &deviceDriverProperties; context.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2); // Verify the returned values switch (testType) { case TEST_TYPE_DRIVER_ID_MATCH: testDriverMatch (deviceDriverProperties); break; case TEST_TYPE_NAME_IS_NOT_EMPTY: testNameIsNotEmpty (deviceDriverProperties); break; case TEST_TYPE_NAME_ZERO_TERMINATED: testNameZeroTerminated (deviceDriverProperties); break; case TEST_TYPE_INFO_ZERO_TERMINATED: testInfoZeroTerminated (deviceDriverProperties); break; case TEST_TYPE_VERSION: testVersion (deviceDriverProperties, context.getUsedApiVersion()); break; default: TCU_THROW(InternalError, "Unknown test type specified"); } return tcu::TestStatus::pass("Pass"); } void createTestCases (tcu::TestCaseGroup* group) { addFunctionCase(group, "driver_id_match", "Check driverID is supported", checkSupport, testQueryProperties, TEST_TYPE_DRIVER_ID_MATCH); addFunctionCase(group, "name_is_not_empty", "Check name field is not empty", checkSupport, testQueryProperties, TEST_TYPE_NAME_IS_NOT_EMPTY); addFunctionCase(group, "name_zero_terminated", "Check name field is zero-terminated", checkSupport, testQueryProperties, TEST_TYPE_NAME_ZERO_TERMINATED); addFunctionCase(group, "info_zero_terminated", "Check info field is zero-terminated", checkSupport, testQueryProperties, TEST_TYPE_INFO_ZERO_TERMINATED); addFunctionCase(group, "conformance_version", "Check conformanceVersion reported by driver", checkSupport, testQueryProperties, TEST_TYPE_VERSION); } } // anonymous tcu::TestCaseGroup* createDriverPropertiesTests(tcu::TestContext& testCtx) { return createTestGroup(testCtx, "driver_properties", "VK_KHR_driver_properties tests", createTestCases); } } // api } // vkt <|endoftext|>
<commit_before>/*------------------------------------------------------------------------- * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2018 Advanced Micro Devices, Inc. * Copyright (c) 2018 The Khronos Group Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief VK_KHR_driver_properties tests *//*--------------------------------------------------------------------*/ #include "vktApiDriverPropertiesTests.hpp" #include "vktTestGroupUtil.hpp" #include "vktTestCaseUtil.hpp" #include "vkQueryUtil.hpp" #include "vkTypeUtil.hpp" using namespace vk; namespace vkt { namespace api { namespace { enum TestType { TEST_TYPE_DRIVER_ID_MATCH = 0, TEST_TYPE_NAME_IS_NOT_EMPTY, TEST_TYPE_NAME_ZERO_TERMINATED, TEST_TYPE_INFO_ZERO_TERMINATED, TEST_TYPE_VERSION, }; static const deUint32 knownDriverIds[] = { // Specified in the Vulkan registry (vk.xml) 1, // author = "Advanced Micro Devices, Inc." comment = "AMD proprietary driver" 2, // author = "Advanced Micro Devices, Inc." comment = "AMD open-source driver" 3, // author = "Mesa open source project" comment = "Mesa RADV driver" 4, // author = "NVIDIA Corporation" comment = "NVIDIA proprietary driver" 5, // author = "Intel Corporation" comment = "Intel proprietary Windows driver" 6, // author = "Intel Corporation" comment = "Intel open-source Mesa driver" 7, // author = "Imagination Technologies" comment = "Imagination proprietary driver" 8, // author = "Qualcomm Technologies, Inc." comment = "Qualcomm proprietary driver" 9, // author = "Arm Limited" comment = "Arm proprietary driver" 10, // <enum value="10" name="VK_DRIVER_ID_GOOGLE_SWIFTSHADER_KHR" comment="Google LLC"/> 11, // <enum value="11" name="VK_DRIVER_ID_GGP_PROPRIETARY_KHR" comment="Google LLC"/> 12, // <enum value="12" name="VK_DRIVER_ID_BROADCOM_PROPRIETARY_KHR" comment="Broadcom Inc."/> }; static const VkConformanceVersionKHR knownConformanceVersions[] = { makeConformanceVersion(1, 2, 2, 0), makeConformanceVersion(1, 2, 1, 1), makeConformanceVersion(1, 2, 1, 0), makeConformanceVersion(1, 2, 0, 2), makeConformanceVersion(1, 2, 0, 1), makeConformanceVersion(1, 2, 0, 0), makeConformanceVersion(1, 1, 6, 3), makeConformanceVersion(1, 1, 6, 2), makeConformanceVersion(1, 1, 6, 1), makeConformanceVersion(1, 1, 6, 0), makeConformanceVersion(1, 1, 5, 2), makeConformanceVersion(1, 1, 5, 1), makeConformanceVersion(1, 1, 5, 0), makeConformanceVersion(1, 1, 4, 3), makeConformanceVersion(1, 1, 4, 2), makeConformanceVersion(1, 1, 4, 1), makeConformanceVersion(1, 1, 4, 0), makeConformanceVersion(1, 1, 3, 3), makeConformanceVersion(1, 1, 3, 2), makeConformanceVersion(1, 1, 3, 1), makeConformanceVersion(1, 1, 3, 0), }; DE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize) { return deStrnlen(str, maxSize) < maxSize; } DE_INLINE bool operator==(const VkConformanceVersion& a, const VkConformanceVersion& b) { return ((a.major == b.major) && (a.minor == b.minor) && (a.subminor == b.subminor) && (a.patch == b.patch)); } void checkSupport (Context& context, const TestType config) { DE_UNREF(config); context.requireDeviceFunctionality("VK_KHR_driver_properties"); } void testDriverMatch (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties) { for (const deUint32* pDriverId = knownDriverIds; pDriverId != DE_ARRAY_END(knownDriverIds); ++pDriverId) { if (deviceDriverProperties.driverID == *pDriverId) return; } TCU_FAIL("Driver ID did not match any known driver"); } void testNameIsNotEmpty (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties) { if (deviceDriverProperties.driverName[0] == 0) TCU_FAIL("Driver name is empty"); } void testNameZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties) { if (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE_KHR)) TCU_FAIL("Driver name is not a null-terminated string"); } void testInfoZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties) { if (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR)) TCU_FAIL("Driver info is not a null-terminated string"); } void testVersion (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties, deUint32 usedApiVersion) { const deUint32 apiMajorVersion = VK_VERSION_MAJOR(usedApiVersion); const deUint32 apiMinorVersion = VK_VERSION_MINOR(usedApiVersion); if (deviceDriverProperties.conformanceVersion.major < apiMajorVersion || (deviceDriverProperties.conformanceVersion.major == apiMajorVersion && deviceDriverProperties.conformanceVersion.minor < apiMinorVersion)) { TCU_FAIL("Wrong driver conformance version (older than used API version)"); } for (const VkConformanceVersionKHR* pConformanceVersion = knownConformanceVersions; pConformanceVersion != DE_ARRAY_END(knownConformanceVersions); ++pConformanceVersion) { if (deviceDriverProperties.conformanceVersion == *pConformanceVersion) return; } TCU_FAIL("Wrong driver conformance version (not known)"); } tcu::TestStatus testQueryProperties (Context& context, const TestType testType) { // Query the driver properties const VkPhysicalDevice physDevice = context.getPhysicalDevice(); const int memsetPattern = 0xaa; VkPhysicalDeviceProperties2 deviceProperties2; VkPhysicalDeviceDriverProperties deviceDriverProperties; deMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties)); deviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR; deviceDriverProperties.pNext = DE_NULL; deMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2)); deviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2; deviceProperties2.pNext = &deviceDriverProperties; context.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2); // Verify the returned values switch (testType) { case TEST_TYPE_DRIVER_ID_MATCH: testDriverMatch (deviceDriverProperties); break; case TEST_TYPE_NAME_IS_NOT_EMPTY: testNameIsNotEmpty (deviceDriverProperties); break; case TEST_TYPE_NAME_ZERO_TERMINATED: testNameZeroTerminated (deviceDriverProperties); break; case TEST_TYPE_INFO_ZERO_TERMINATED: testInfoZeroTerminated (deviceDriverProperties); break; case TEST_TYPE_VERSION: testVersion (deviceDriverProperties, context.getUsedApiVersion()); break; default: TCU_THROW(InternalError, "Unknown test type specified"); } return tcu::TestStatus::pass("Pass"); } void createTestCases (tcu::TestCaseGroup* group) { addFunctionCase(group, "driver_id_match", "Check driverID is supported", checkSupport, testQueryProperties, TEST_TYPE_DRIVER_ID_MATCH); addFunctionCase(group, "name_is_not_empty", "Check name field is not empty", checkSupport, testQueryProperties, TEST_TYPE_NAME_IS_NOT_EMPTY); addFunctionCase(group, "name_zero_terminated", "Check name field is zero-terminated", checkSupport, testQueryProperties, TEST_TYPE_NAME_ZERO_TERMINATED); addFunctionCase(group, "info_zero_terminated", "Check info field is zero-terminated", checkSupport, testQueryProperties, TEST_TYPE_INFO_ZERO_TERMINATED); addFunctionCase(group, "conformance_version", "Check conformanceVersion reported by driver", checkSupport, testQueryProperties, TEST_TYPE_VERSION); } } // anonymous tcu::TestCaseGroup* createDriverPropertiesTests(tcu::TestContext& testCtx) { return createTestGroup(testCtx, "driver_properties", "VK_KHR_driver_properties tests", createTestCases); } } // api } // vkt <commit_msg>Whitelist Vulkan CTS 1.2.2.1<commit_after>/*------------------------------------------------------------------------- * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2018 Advanced Micro Devices, Inc. * Copyright (c) 2018 The Khronos Group Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief VK_KHR_driver_properties tests *//*--------------------------------------------------------------------*/ #include "vktApiDriverPropertiesTests.hpp" #include "vktTestGroupUtil.hpp" #include "vktTestCaseUtil.hpp" #include "vkQueryUtil.hpp" #include "vkTypeUtil.hpp" using namespace vk; namespace vkt { namespace api { namespace { enum TestType { TEST_TYPE_DRIVER_ID_MATCH = 0, TEST_TYPE_NAME_IS_NOT_EMPTY, TEST_TYPE_NAME_ZERO_TERMINATED, TEST_TYPE_INFO_ZERO_TERMINATED, TEST_TYPE_VERSION, }; static const deUint32 knownDriverIds[] = { // Specified in the Vulkan registry (vk.xml) 1, // author = "Advanced Micro Devices, Inc." comment = "AMD proprietary driver" 2, // author = "Advanced Micro Devices, Inc." comment = "AMD open-source driver" 3, // author = "Mesa open source project" comment = "Mesa RADV driver" 4, // author = "NVIDIA Corporation" comment = "NVIDIA proprietary driver" 5, // author = "Intel Corporation" comment = "Intel proprietary Windows driver" 6, // author = "Intel Corporation" comment = "Intel open-source Mesa driver" 7, // author = "Imagination Technologies" comment = "Imagination proprietary driver" 8, // author = "Qualcomm Technologies, Inc." comment = "Qualcomm proprietary driver" 9, // author = "Arm Limited" comment = "Arm proprietary driver" 10, // <enum value="10" name="VK_DRIVER_ID_GOOGLE_SWIFTSHADER_KHR" comment="Google LLC"/> 11, // <enum value="11" name="VK_DRIVER_ID_GGP_PROPRIETARY_KHR" comment="Google LLC"/> 12, // <enum value="12" name="VK_DRIVER_ID_BROADCOM_PROPRIETARY_KHR" comment="Broadcom Inc."/> }; static const VkConformanceVersionKHR knownConformanceVersions[] = { makeConformanceVersion(1, 2, 2, 1), makeConformanceVersion(1, 2, 2, 0), makeConformanceVersion(1, 2, 1, 1), makeConformanceVersion(1, 2, 1, 0), makeConformanceVersion(1, 2, 0, 2), makeConformanceVersion(1, 2, 0, 1), makeConformanceVersion(1, 2, 0, 0), makeConformanceVersion(1, 1, 6, 3), makeConformanceVersion(1, 1, 6, 2), makeConformanceVersion(1, 1, 6, 1), makeConformanceVersion(1, 1, 6, 0), makeConformanceVersion(1, 1, 5, 2), makeConformanceVersion(1, 1, 5, 1), makeConformanceVersion(1, 1, 5, 0), makeConformanceVersion(1, 1, 4, 3), makeConformanceVersion(1, 1, 4, 2), makeConformanceVersion(1, 1, 4, 1), makeConformanceVersion(1, 1, 4, 0), makeConformanceVersion(1, 1, 3, 3), makeConformanceVersion(1, 1, 3, 2), makeConformanceVersion(1, 1, 3, 1), makeConformanceVersion(1, 1, 3, 0), }; DE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize) { return deStrnlen(str, maxSize) < maxSize; } DE_INLINE bool operator==(const VkConformanceVersion& a, const VkConformanceVersion& b) { return ((a.major == b.major) && (a.minor == b.minor) && (a.subminor == b.subminor) && (a.patch == b.patch)); } void checkSupport (Context& context, const TestType config) { DE_UNREF(config); context.requireDeviceFunctionality("VK_KHR_driver_properties"); } void testDriverMatch (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties) { for (const deUint32* pDriverId = knownDriverIds; pDriverId != DE_ARRAY_END(knownDriverIds); ++pDriverId) { if (deviceDriverProperties.driverID == *pDriverId) return; } TCU_FAIL("Driver ID did not match any known driver"); } void testNameIsNotEmpty (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties) { if (deviceDriverProperties.driverName[0] == 0) TCU_FAIL("Driver name is empty"); } void testNameZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties) { if (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE_KHR)) TCU_FAIL("Driver name is not a null-terminated string"); } void testInfoZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties) { if (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR)) TCU_FAIL("Driver info is not a null-terminated string"); } void testVersion (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties, deUint32 usedApiVersion) { const deUint32 apiMajorVersion = VK_VERSION_MAJOR(usedApiVersion); const deUint32 apiMinorVersion = VK_VERSION_MINOR(usedApiVersion); if (deviceDriverProperties.conformanceVersion.major < apiMajorVersion || (deviceDriverProperties.conformanceVersion.major == apiMajorVersion && deviceDriverProperties.conformanceVersion.minor < apiMinorVersion)) { TCU_FAIL("Wrong driver conformance version (older than used API version)"); } for (const VkConformanceVersionKHR* pConformanceVersion = knownConformanceVersions; pConformanceVersion != DE_ARRAY_END(knownConformanceVersions); ++pConformanceVersion) { if (deviceDriverProperties.conformanceVersion == *pConformanceVersion) return; } TCU_FAIL("Wrong driver conformance version (not known)"); } tcu::TestStatus testQueryProperties (Context& context, const TestType testType) { // Query the driver properties const VkPhysicalDevice physDevice = context.getPhysicalDevice(); const int memsetPattern = 0xaa; VkPhysicalDeviceProperties2 deviceProperties2; VkPhysicalDeviceDriverProperties deviceDriverProperties; deMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties)); deviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR; deviceDriverProperties.pNext = DE_NULL; deMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2)); deviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2; deviceProperties2.pNext = &deviceDriverProperties; context.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2); // Verify the returned values switch (testType) { case TEST_TYPE_DRIVER_ID_MATCH: testDriverMatch (deviceDriverProperties); break; case TEST_TYPE_NAME_IS_NOT_EMPTY: testNameIsNotEmpty (deviceDriverProperties); break; case TEST_TYPE_NAME_ZERO_TERMINATED: testNameZeroTerminated (deviceDriverProperties); break; case TEST_TYPE_INFO_ZERO_TERMINATED: testInfoZeroTerminated (deviceDriverProperties); break; case TEST_TYPE_VERSION: testVersion (deviceDriverProperties, context.getUsedApiVersion()); break; default: TCU_THROW(InternalError, "Unknown test type specified"); } return tcu::TestStatus::pass("Pass"); } void createTestCases (tcu::TestCaseGroup* group) { addFunctionCase(group, "driver_id_match", "Check driverID is supported", checkSupport, testQueryProperties, TEST_TYPE_DRIVER_ID_MATCH); addFunctionCase(group, "name_is_not_empty", "Check name field is not empty", checkSupport, testQueryProperties, TEST_TYPE_NAME_IS_NOT_EMPTY); addFunctionCase(group, "name_zero_terminated", "Check name field is zero-terminated", checkSupport, testQueryProperties, TEST_TYPE_NAME_ZERO_TERMINATED); addFunctionCase(group, "info_zero_terminated", "Check info field is zero-terminated", checkSupport, testQueryProperties, TEST_TYPE_INFO_ZERO_TERMINATED); addFunctionCase(group, "conformance_version", "Check conformanceVersion reported by driver", checkSupport, testQueryProperties, TEST_TYPE_VERSION); } } // anonymous tcu::TestCaseGroup* createDriverPropertiesTests(tcu::TestContext& testCtx) { return createTestGroup(testCtx, "driver_properties", "VK_KHR_driver_properties tests", createTestCases); } } // api } // vkt <|endoftext|>
<commit_before>#include <bits/stdc++.h> #define dbug(x) cout << '>' << #x << ':' << x << endl #define pline cout << "_________________________" << endl #define mem(x, v) memset(x, v, sizeof(x)) #define eef else if #define sf scanf #define pf printf #define i64 long long #define ll long long #define ui64 unsigned long long #define pcount(num) __builtin_popcount(num) #define all(x) x.begin(), x.end() #define lla(x) x.rbegin(), x.rend() #define SORT(c) sort(all(c)) #define ssort(v) stable_sort(v.begin(), v.end()) #define sz(v) (int)(v).size() #define _lst(X) (X)[sz((X))-1] #define IT iterator #define pb push_back #define ppb pop_back #define mp make_pair #define fi first #define se second #define CTN(T, x) (T.find(x) != T.end()) #define max3(a,b,c) max(a,max(b,c)) #define min3(a,b,c) min(a,min(b,c)) #define maximum(v) *max_element(all(v) #define minimum(v) *min_element(all(v)) #define Reverse(x) reverse(x.begin(),x.end()) #define loop(i,s,e) for(__typeof(s) i=(s);i<=(e);i++) #define pool(i,e,s) for(__typeof(e) i=(e);i>=(s);i--) #define FORIT(i, m) for (__typeof((m).begin()) i=(m).begin(); i!=(m).end(); ++i) #define siter(n,T1) for(set<T1>::iterator it=n.begin();it!=n.end();it++) #define miter(n,T1,T2) for(map<T1,T2>::iterator it=n.begin();it!=n.end();it++) #define ps(x) cout<<"Case "<<++x<<": " #define pcs(x) pf("Case %d: ", ++x) #define newl '\n' #define Newl "\n" #define nl puts ("") #define sqr(a) ((a)*(a)) #define MAX 1e12 #define FAST ios_base::sync_with_stdio(0) using namespace std; int main(){ int matches, goals, a, b, m, wins, stop, draw; while(sf("%d %d", &matches, &goals)==2){ wins = draw = 0, m = matches; vector<int> need; while(m--){ sf("%d %d", &a, &b); if ( a > b ) wins++; else { need.pb((b+1) - a ); } } sort(all(need)); for(int i = 0; i<sz(need); i++){ if ( goals < 1 ){ loop(j, i, sz(need)-1){ if ( need[j] == 1 ){ draw++; goals--; } } break; } if ( goals >= need[i] ){ goals -= need[i]; wins++; } if ( goals > 0 && goals+1 == need[i] ){ draw++; goals--; } } pf("%d\n", (wins*3) + draw); } return 0; } /* Input: 3 1 2 1 1 2 1 3 3 3 1 1 2 2 3 3 2 1 1 1 2 2 7 0 4 2 1 1 1 5 2 2 3 3 4 4 0 6 4 0 1 1 2 2 1 3 0 4 3 10 0 8 0 2 0 0 5 3 1 1 1 3 1 2 1 2 1 2 5 4 0 1 0 1 0 1 0 1 1 8 2 1 0 1 2 2 2 1 0 1 0 1 Output: 4 9 4 7 2 6 6 6 3 1 */ <commit_msg>Update Football_12673.cpp<commit_after>#include <bits/stdc++.h> #define dbug(x) cout << '>' << #x << ':' << x << endl #define pline cout << "_________________________" << endl #define mem(x, v) memset(x, v, sizeof(x)) #define eef else if #define sf scanf #define pf printf #define i64 long long #define ll long long #define ui64 unsigned long long #define pcount(num) __builtin_popcount(num) #define all(x) x.begin(), x.end() #define lla(x) x.rbegin(), x.rend() #define SORT(c) sort(all(c)) #define ssort(v) stable_sort(v.begin(), v.end()) #define sz(v) (int)(v).size() #define _lst(X) (X)[sz((X))-1] #define IT iterator #define pb push_back #define ppb pop_back #define mp make_pair #define fi first #define se second #define CTN(T, x) (T.find(x) != T.end()) #define max3(a,b,c) max(a,max(b,c)) #define min3(a,b,c) min(a,min(b,c)) #define maximum(v) *max_element(all(v) #define minimum(v) *min_element(all(v)) #define Reverse(x) reverse(x.begin(),x.end()) #define loop(i,s,e) for(__typeof(s) i=(s);i<=(e);i++) #define pool(i,e,s) for(__typeof(e) i=(e);i>=(s);i--) #define FORIT(i, m) for (__typeof((m).begin()) i=(m).begin(); i!=(m).end(); ++i) #define siter(n,T1) for(set<T1>::iterator it=n.begin();it!=n.end();it++) #define miter(n,T1,T2) for(map<T1,T2>::iterator it=n.begin();it!=n.end();it++) #define ps(x) cout<<"Case "<<++x<<": " #define pcs(x) pf("Case %d: ", ++x) #define newl '\n' #define Newl "\n" #define nl puts("") #define sqr(a) ((a)*(a)) #define MAX 1e12 #define FAST ios_base::sync_with_stdio(0) using namespace std; int main(){ int matches, goals, a, b, m, wins, stop, draw; while(sf("%d %d", &matches, &goals)==2){ wins = draw = 0, m = matches; vector<int> need; while(m--){ sf("%d %d", &a, &b); if ( a > b ) wins++; else { need.pb((b+1) - a ); } } sort(all(need)); for(int i = 0; i<sz(need); i++){ if ( goals < 1 ){ loop(j, i, sz(need)-1){ if ( need[j] == 1 ){ draw++; goals--; } } break; } if ( goals >= need[i] ){ goals -= need[i]; wins++; } if ( goals > 0 && goals+1 == need[i] ){ draw++; goals--; } } pf("%d\n", (wins*3) + draw); } return 0; } /* Input: 3 1 2 1 1 2 1 3 3 3 1 1 2 2 3 3 2 1 1 1 2 2 7 0 4 2 1 1 1 5 2 2 3 3 4 4 0 6 4 0 1 1 2 2 1 3 0 4 3 10 0 8 0 2 0 0 5 3 1 1 1 3 1 2 1 2 1 2 5 4 0 1 0 1 0 1 0 1 1 8 2 1 0 1 2 2 2 1 0 1 0 1 Output: 4 9 4 7 2 6 6 6 3 1 */ <|endoftext|>
<commit_before>/* Copyright 2014 Open Source Robotics Foundation, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef RCLCPP_RCLCPP_UTILITIES_HPP_ #define RCLCPP_RCLCPP_UTILITIES_HPP_ // TODO: remove #include <iostream> #include <cerrno> #include <chrono> #include <condition_variable> #include <csignal> #include <cstring> #include <mutex> #include <thread> #include <ros_middleware_interface/functions.h> #include <ros_middleware_interface/handles.h> // Determine if sigaction is available #if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE #define HAS_SIGACTION #endif namespace { volatile sig_atomic_t g_signal_status = 0; ros_middleware_interface::GuardConditionHandle g_sigint_guard_cond_handle = \ ros_middleware_interface::create_guard_condition(); std::condition_variable g_interrupt_condition_variable; std::mutex g_interrupt_mutex; #ifdef HAS_SIGACTION struct sigaction old_action; #else void (*old_signal_handler)(int) = 0; #endif void #ifdef HAS_SIGACTION signal_handler(int signal_value, siginfo_t *siginfo, void *context) #else signal_handler(int signal_value) #endif { // TODO: remove std::cout << "signal_handler(" << signal_value << ")" << std::endl; #ifdef HAS_SIGACTION if (old_action.sa_flags & SA_SIGINFO) { if (old_action.sa_sigaction != NULL) { old_action.sa_sigaction(signal_value, siginfo, context); } } else { if (old_action.sa_handler != NULL && // Is set old_action.sa_handler != SIG_DFL && // Is not default old_action.sa_handler != SIG_IGN) // Is not ignored { old_action.sa_handler(signal_value); } } #else if (old_signal_handler) { old_signal_handler(signal_value); } #endif g_signal_status = signal_value; using ros_middleware_interface::trigger_guard_condition; trigger_guard_condition(g_sigint_guard_cond_handle); g_interrupt_condition_variable.notify_all(); } } namespace rclcpp { __thread size_t thread_id = 0; namespace utilities { void init(int argc, char *argv[]) { ros_middleware_interface::init(); #ifdef HAS_SIGACTION struct sigaction action; memset(&action, 0, sizeof(action)); sigemptyset(&action.sa_mask); action.sa_sigaction = ::signal_handler; action.sa_flags = SA_SIGINFO; ssize_t ret = sigaction(SIGINT, &action, &old_action); if (ret == -1) #else ::old_signal_handler = std::signal(SIGINT, ::signal_handler); if (::old_signal_handler == SIG_ERR) #endif { throw std::runtime_error( std::string("Failed to set SIGINT signal handler: (" + std::to_string(errno) + ")") + std::strerror(errno)); } } bool ok() { return ::g_signal_status == 0; } ros_middleware_interface::GuardConditionHandle get_global_sigint_guard_condition() { return ::g_sigint_guard_cond_handle; } template<class Rep, class Period> bool sleep_for(const std::chrono::duration<Rep, Period>& sleep_duration) { // TODO: determine if posix's nanosleep(2) is more efficient here std::unique_lock<std::mutex> lock(::g_interrupt_mutex); auto cvs = ::g_interrupt_condition_variable.wait_for(lock, sleep_duration); return cvs == std::cv_status::no_timeout; } } /* namespace utilities */ } /* namespace rclcpp */ #ifdef HAS_SIGACTION #undef HAS_SIGACTION #endif #endif /* RCLCPP_RCLCPP_UTILITIES_HPP_ */ <commit_msg>update sigaction detection to support os x<commit_after>/* Copyright 2014 Open Source Robotics Foundation, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef RCLCPP_RCLCPP_UTILITIES_HPP_ #define RCLCPP_RCLCPP_UTILITIES_HPP_ // TODO: remove #include <iostream> #include <cerrno> #include <chrono> #include <condition_variable> #include <csignal> #include <cstring> #include <mutex> #include <thread> #include <ros_middleware_interface/functions.h> #include <ros_middleware_interface/handles.h> // Determine if sigaction is available #if __APPLE__ || _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE #define HAS_SIGACTION #endif namespace { volatile sig_atomic_t g_signal_status = 0; ros_middleware_interface::GuardConditionHandle g_sigint_guard_cond_handle = \ ros_middleware_interface::create_guard_condition(); std::condition_variable g_interrupt_condition_variable; std::mutex g_interrupt_mutex; #ifdef HAS_SIGACTION struct sigaction old_action; #else void (*old_signal_handler)(int) = 0; #endif void #ifdef HAS_SIGACTION signal_handler(int signal_value, siginfo_t *siginfo, void *context) #else signal_handler(int signal_value) #endif { // TODO: remove std::cout << "signal_handler(" << signal_value << ")" << std::endl; #ifdef HAS_SIGACTION if (old_action.sa_flags & SA_SIGINFO) { if (old_action.sa_sigaction != NULL) { old_action.sa_sigaction(signal_value, siginfo, context); } } else { if (old_action.sa_handler != NULL && // Is set old_action.sa_handler != SIG_DFL && // Is not default old_action.sa_handler != SIG_IGN) // Is not ignored { old_action.sa_handler(signal_value); } } #else if (old_signal_handler) { old_signal_handler(signal_value); } #endif g_signal_status = signal_value; using ros_middleware_interface::trigger_guard_condition; trigger_guard_condition(g_sigint_guard_cond_handle); g_interrupt_condition_variable.notify_all(); } } namespace rclcpp { __thread size_t thread_id = 0; namespace utilities { void init(int argc, char *argv[]) { ros_middleware_interface::init(); #ifdef HAS_SIGACTION struct sigaction action; memset(&action, 0, sizeof(action)); sigemptyset(&action.sa_mask); action.sa_sigaction = ::signal_handler; action.sa_flags = SA_SIGINFO; ssize_t ret = sigaction(SIGINT, &action, &old_action); if (ret == -1) #else ::old_signal_handler = std::signal(SIGINT, ::signal_handler); if (::old_signal_handler == SIG_ERR) #endif { throw std::runtime_error( std::string("Failed to set SIGINT signal handler: (" + std::to_string(errno) + ")") + std::strerror(errno)); } } bool ok() { return ::g_signal_status == 0; } ros_middleware_interface::GuardConditionHandle get_global_sigint_guard_condition() { return ::g_sigint_guard_cond_handle; } template<class Rep, class Period> bool sleep_for(const std::chrono::duration<Rep, Period>& sleep_duration) { // TODO: determine if posix's nanosleep(2) is more efficient here std::unique_lock<std::mutex> lock(::g_interrupt_mutex); auto cvs = ::g_interrupt_condition_variable.wait_for(lock, sleep_duration); return cvs == std::cv_status::no_timeout; } } /* namespace utilities */ } /* namespace rclcpp */ #ifdef HAS_SIGACTION #undef HAS_SIGACTION #endif #endif /* RCLCPP_RCLCPP_UTILITIES_HPP_ */ <|endoftext|>
<commit_before>/*---------------------------------------------------------------------------*\ * OpenSG NURBS Library * * * * * * Copyright (C) 2001-2006 by the University of Bonn, Computer Graphics Group* * * * http://cg.cs.uni-bonn.de/ * * * * contact: edhellon@cs.uni-bonn.de, guthe@cs.uni-bonn.de, rk@cs.uni-bonn.de * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * 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, version 2. * * * * 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; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * Changes * * * * * * * * * * * * * \*---------------------------------------------------------------------------*/ OSG_BEGIN_NAMESPACE // default constructor template <typename T0, typename T1> DirectedGraph<T0, T1>::DirectedGraph() { invalid = true; } // add a new node // returns node index template <typename T0, typename T1> int DirectedGraph<T0, T1>::AddNode( T0 &n ) { DirectedNode<T0> nn; nn.nodeinfo = n; nodes.push_back( nn ); return Int32(nodes.size()) - 1; } // add a new (possibly directed) edge // returns edge index or -1 template <typename T0, typename T1> int DirectedGraph<T0, T1>::AddEdge( T1 &t, int from, int to, bool direction) { if ( from < 0 || from >= int(nodes.size()) || to < 0 || to >= int(nodes.size()) ) return -1; DirectedEdge<T1> e; int eidx; e.edgeinfo = t; e.from = from; e.to = to; e.direction = direction; e.valid = true; //DEBUG edges.push_back( e ); eidx = Int32(edges.size()) - 1; nodes[ from ].edges.push_back( eidx ); nodes[ to ].edges.push_back( eidx ); return eidx; } // delete edge specified by index template <typename T0, typename T1> int DirectedGraph<T0, T1>::DeleteEdge( int edgeidx ) { if ( edgeidx < 0 || edgeidx >= int(edges.size()) ) return -1; // note: we don't need to actually erase from here // edges.erase( edgeidx ); edges[ edgeidx ].valid = false; DirectedNode<T0> &fromnode = nodes[ edges [ edgeidx ].from ]; DCTPivector::iterator nee = fromnode.edges.end(); DCTPivector::iterator i; for( i = fromnode.edges.begin(); i != nee; ++i ) if ( *i == edgeidx ) { fromnode.edges.erase( i ); break; } DirectedNode<T0> &tonode = nodes[ edges [ edgeidx ].to ]; nee = tonode.edges.end(); for( i = tonode.edges.begin(); i != nee; ++i ) if ( *i == edgeidx ) { tonode.edges.erase( i ); break; } return 0; } template <typename T0, typename T1> DCTPivector & DirectedGraph<T0, T1>::getEdges( int n ) // get all edges (indexes) from a node { return &nodes.edges; } // get one node template <typename T0, typename T1> DirectedNode<T0>& DirectedGraph<T0, T1>::getNode( int nodeindex, int &error ) { error = 0; if ( nodeindex < 0 || nodeindex >= nodes.size() ) { error = -1; return NULL; } return &nodes[ nodeindex ] ; } // get one edge template <typename T0, typename T1> DirectedEdge<T1>& DirectedGraph<T0, T1>::getEdge( int edgeindex, int &error ) { error = 0; if ( edgeindex < 0 || edgeindex >= edges.size() ) { error = -1; return NULL; } return &edges[ edgeindex ] ; } // get one edge's direction template <typename T0, typename T1> bool DirectedGraph<T0, T1>::getEdgeDirection( int edgeindex, int &error ) { error = 0; if ( edgeindex < 0 || edgeindex >= edges.size() ) { error = -1; return NULL; } return edges[ edgeindex ].orientation; } // set the direction of an edge template <typename T0, typename T1> int DirectedGraph<T0, T1>::setEdgeDirection( int edgeindex, int to ) { if ( edgeindex < 0 || edgeindex >= int(edges.size()) ) return -1; if ( edges[ edgeindex ].from != to && edges[ edgeindex ].to != to ) return -1; if ( edges[ edgeindex ].to != to ) { int tmp = edges[ edgeindex ].to; edges[ edgeindex ].to = to; edges[ edgeindex ].from = tmp; } edges[ edgeindex ].direction = true; return 0; } // change (invert) the direction of an edge template <typename T0, typename T1> int DirectedGraph<T0, T1>::changeEdgeDirection( int edgeindex ) { if ( edgeindex < 0 || edgeindex >= edges.size() ) return -1; if ( !edges[ edgeindex ].orientation ) return -1; int tmp = edges[ edgeindex ].to; edges[ edgeindex ].to = edges[ edgeindex ].from; edges[ edgeindex ].from = tmp; return 0; } template <typename T0, typename T1> bool DirectedGraph<T0, T1>::isInvalid( void ) { return invalid; } template <typename T0, typename T1> int DirectedGraph<T0, T1>::FindNode( T0 &nodeinfo ) { for( unsigned int i = 0; i < nodes.size( ); ++i ) { if( nodes[ i ].nodeinfo == nodeinfo ) return i; } return -1; } template <typename T0, typename T1> int DirectedGraph<T0, T1>::FindEdge( int from, int to ) { for( unsigned int i = 0; i < edges.size( ); ++i ) { // std::cerr << "checking edge from " << edges[ i ].from << " to " << edges[ i ].to << std::endl; if( ( edges[ i ].from == from ) && ( edges[ i ].to == to ) ) return i; if( ( edges[ i ].from == to ) && ( edges[ i ].to == from ) ) return i; } return -1; } OSG_END_NAMESPACE <commit_msg>fix return type<commit_after>/*---------------------------------------------------------------------------*\ * OpenSG NURBS Library * * * * * * Copyright (C) 2001-2006 by the University of Bonn, Computer Graphics Group* * * * http://cg.cs.uni-bonn.de/ * * * * contact: edhellon@cs.uni-bonn.de, guthe@cs.uni-bonn.de, rk@cs.uni-bonn.de * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * 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, version 2. * * * * 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; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * Changes * * * * * * * * * * * * * \*---------------------------------------------------------------------------*/ OSG_BEGIN_NAMESPACE // default constructor template <typename T0, typename T1> DirectedGraph<T0, T1>::DirectedGraph() { invalid = true; } // add a new node // returns node index template <typename T0, typename T1> int DirectedGraph<T0, T1>::AddNode( T0 &n ) { DirectedNode<T0> nn; nn.nodeinfo = n; nodes.push_back( nn ); return Int32(nodes.size()) - 1; } // add a new (possibly directed) edge // returns edge index or -1 template <typename T0, typename T1> int DirectedGraph<T0, T1>::AddEdge( T1 &t, int from, int to, bool direction) { if ( from < 0 || from >= int(nodes.size()) || to < 0 || to >= int(nodes.size()) ) return -1; DirectedEdge<T1> e; int eidx; e.edgeinfo = t; e.from = from; e.to = to; e.direction = direction; e.valid = true; //DEBUG edges.push_back( e ); eidx = Int32(edges.size()) - 1; nodes[ from ].edges.push_back( eidx ); nodes[ to ].edges.push_back( eidx ); return eidx; } // delete edge specified by index template <typename T0, typename T1> int DirectedGraph<T0, T1>::DeleteEdge( int edgeidx ) { if ( edgeidx < 0 || edgeidx >= int(edges.size()) ) return -1; // note: we don't need to actually erase from here // edges.erase( edgeidx ); edges[ edgeidx ].valid = false; DirectedNode<T0> &fromnode = nodes[ edges [ edgeidx ].from ]; DCTPivector::iterator nee = fromnode.edges.end(); DCTPivector::iterator i; for( i = fromnode.edges.begin(); i != nee; ++i ) if ( *i == edgeidx ) { fromnode.edges.erase( i ); break; } DirectedNode<T0> &tonode = nodes[ edges [ edgeidx ].to ]; nee = tonode.edges.end(); for( i = tonode.edges.begin(); i != nee; ++i ) if ( *i == edgeidx ) { tonode.edges.erase( i ); break; } return 0; } template <typename T0, typename T1> DCTPivector & DirectedGraph<T0, T1>::getEdges( int n ) // get all edges (indexes) from a node { return &nodes.edges; } // get one node template <typename T0, typename T1> DirectedNode<T0>& DirectedGraph<T0, T1>::getNode( int nodeindex, int &error ) { error = 0; if ( nodeindex < 0 || nodeindex >= nodes.size() ) { error = -1; return NULL; } return &nodes[ nodeindex ] ; } // get one edge template <typename T0, typename T1> DirectedEdge<T1>& DirectedGraph<T0, T1>::getEdge( int edgeindex, int &error ) { error = 0; if ( edgeindex < 0 || edgeindex >= edges.size() ) { error = -1; return NULL; } return &edges[ edgeindex ] ; } // get one edge's direction template <typename T0, typename T1> bool DirectedGraph<T0, T1>::getEdgeDirection( int edgeindex, int &error ) { error = 0; if ( edgeindex < 0 || edgeindex >= edges.size() ) { error = -1; return false; } return edges[ edgeindex ].orientation; } // set the direction of an edge template <typename T0, typename T1> int DirectedGraph<T0, T1>::setEdgeDirection( int edgeindex, int to ) { if ( edgeindex < 0 || edgeindex >= int(edges.size()) ) return -1; if ( edges[ edgeindex ].from != to && edges[ edgeindex ].to != to ) return -1; if ( edges[ edgeindex ].to != to ) { int tmp = edges[ edgeindex ].to; edges[ edgeindex ].to = to; edges[ edgeindex ].from = tmp; } edges[ edgeindex ].direction = true; return 0; } // change (invert) the direction of an edge template <typename T0, typename T1> int DirectedGraph<T0, T1>::changeEdgeDirection( int edgeindex ) { if ( edgeindex < 0 || edgeindex >= edges.size() ) return -1; if ( !edges[ edgeindex ].orientation ) return -1; int tmp = edges[ edgeindex ].to; edges[ edgeindex ].to = edges[ edgeindex ].from; edges[ edgeindex ].from = tmp; return 0; } template <typename T0, typename T1> bool DirectedGraph<T0, T1>::isInvalid( void ) { return invalid; } template <typename T0, typename T1> int DirectedGraph<T0, T1>::FindNode( T0 &nodeinfo ) { for( unsigned int i = 0; i < nodes.size( ); ++i ) { if( nodes[ i ].nodeinfo == nodeinfo ) return i; } return -1; } template <typename T0, typename T1> int DirectedGraph<T0, T1>::FindEdge( int from, int to ) { for( unsigned int i = 0; i < edges.size( ); ++i ) { // std::cerr << "checking edge from " << edges[ i ].from << " to " << edges[ i ].to << std::endl; if( ( edges[ i ].from == from ) && ( edges[ i ].to == to ) ) return i; if( ( edges[ i ].from == to ) && ( edges[ i ].to == from ) ) return i; } return -1; } OSG_END_NAMESPACE <|endoftext|>
<commit_before>#ifdef JOYSMOOTH_H_INC #define JOYSMOOTH_H_INC #include <bitset> #include <GenericHID.h> #include "612.h" #include "update.h" #include "joysmooth.h" //provide definition of constants: const int joysmooth::HOLDBACK; const int joysmooth::NUMBUTTONS; const int joysmooth::NUMAXES; void register_callback(void*); void update_callback_joysmooth(void*); joysmooth::joysmooth(GenericHID* ghid) : joy(ghid) { register_callback((void*)this); } joysmooth::joysmooth(GenericHID& ghid) : joy(&ghid) { register_callback((void*)this); } joysmooth::~joysmooth() { registry().unregister_func(update_callback, (void*)this); } joysmooth::void update() { for (int d = 0; d < NUMBUTTONS; d++) { for (int i = 1; i < HOLDBACK; i++) { buttons[d][i - 1] = buttons[d][i]; } buttons[d][HOLDBACK - 1] = joy->GetRawButton(d); } for(int d = 0; d < NUMAXES; d++) { axes[d] = joy->GetRawAxis(d); } } float joysmooth::GetX(GenericHID::JoystickHand h) { return axes[X_AXIS]; } float joysmooth::GetY(GenericHID::JoystickHand h) { return axes[Y_AXIS]; } float joysmooth::GetZ(){ return axes[Z_AXIS]; } float joysmooth::GetTwist(){ return axis[TWIST_AXIS]; } float joysmooth::GetThrottle(){ return axes[THROTTLE_AXIS]; } float joysmooth::GetRawAxis(UINT32 axisId){ return axes[axisId]; } bool joysmooth::GetTop(){ return GetRawButton(2); } bool joysmooth::GetBumper(){ return joy->GetBumper(); } bool joysmooth::GetRawButton(UINT32 btnId){ for(int i = 0; i < HOLDBACK; i++) { if(!buttons[btnId][i]) { return false; } } return true; } void register_callback(void* thisPtr) { registry().register_func(update_callback_joysmooth, thisPtr); } void update_callback_joysmooth(void* thisPtr) { ((joysmooth*)thisPtr)->update(); } #endif <commit_msg>Fixed bad syntax. May resolve some undefined symbol errors (hopefully)<commit_after>#ifdef JOYSMOOTH_H_INC #define JOYSMOOTH_H_INC #include <bitset> #include <GenericHID.h> #include "612.h" #include "update.h" #include "joysmooth.h" //provide definition of constants: const int joysmooth::HOLDBACK; const int joysmooth::NUMBUTTONS; const int joysmooth::NUMAXES; void register_callback(void*); void update_callback_joysmooth(void*); joysmooth::joysmooth(GenericHID* ghid) : joy(ghid) { register_callback((void*)this); } joysmooth::joysmooth(GenericHID& ghid) : joy(&ghid) { register_callback((void*)this); } joysmooth::~joysmooth() { registry().unregister_func(update_callback, (void*)this); } void joysmooth::update() { for (int d = 0; d < NUMBUTTONS; d++) { for (int i = 1; i < HOLDBACK; i++) { buttons[d][i - 1] = buttons[d][i]; } buttons[d][HOLDBACK - 1] = joy->GetRawButton(d); } for(int d = 0; d < NUMAXES; d++) { axes[d] = joy->GetRawAxis(d); } } float joysmooth::GetX(GenericHID::JoystickHand h) { return axes[X_AXIS]; } float joysmooth::GetY(GenericHID::JoystickHand h) { return axes[Y_AXIS]; } float joysmooth::GetZ(){ return axes[Z_AXIS]; } float joysmooth::GetTwist(){ return axis[TWIST_AXIS]; } float joysmooth::GetThrottle(){ return axes[THROTTLE_AXIS]; } float joysmooth::GetRawAxis(UINT32 axisId){ return axes[axisId]; } bool joysmooth::GetTop(){ return GetRawButton(2); } bool joysmooth::GetBumper(){ return joy->GetBumper(); } bool joysmooth::GetRawButton(UINT32 btnId){ for(int i = 0; i < HOLDBACK; i++) { if(!buttons[btnId][i]) { return false; } } return true; } void register_callback(void* thisPtr) { registry().register_func(update_callback_joysmooth, thisPtr); } void update_callback_joysmooth(void* thisPtr) { ((joysmooth*)thisPtr)->update(); } #endif <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #ifndef MODEL_SQUIRREL_HPP #define MODEL_SQUIRREL_HPP #include <locale> #include "json.hpp" namespace acorn { /** * */ struct Squirrel : json::Serializable { size_t key; Squirrel() : key(0) {} /** * */ Squirrel(std::string name, size_t age, std::string occupation) : key {0} , name_ {name} , age_ {age} , occupation_ {occupation} {} /** * */ std::string json() const; /** * */ virtual void serialize(rapidjson::Writer<rapidjson::StringBuffer>&) const override; /** * */ virtual bool deserialize(const rapidjson::Document&) override; /** * */ bool is_equal(const Squirrel&) const; /** * */ static bool is_equal(const Squirrel&, const Squirrel&); private: const std::string name_; const size_t age_; const std::string occupation_; }; //< struct Squirrel /**--v----------- Implementation Details -----------v--**/ inline std::ostream& operator << (std::ostream& output_device, const Squirrel& s) { return output_device.json(); } void Squirrel::serialize(rapidjson::Writer<rapidjson::StringBuffer>& writer) const { writer.StartObject(); writer.Key("key"); writer.Uint(key); writer.Key("name"); writer.String(name_); writer.Key("age"); writer.Uint(age_); writer.Key("occupation"); writer.String(occupation_); writer.EndObject(); } bool Squirrel::deserialize(const rapidjson::Document& doc) { name_ = doc["name"].GetString(); age_ = doc["age"].GetUint(); occupation_ = doc["occupation"].GetString(); return true; } std::string Squirrel::json() const { using namespace rapidjson; StringBuffer sb; Writer<StringBuffer> writer(sb); serialize(writer); return sb.GetString(); } bool Squirrel::is_equal(const Squirrel& s) const { if(name_.size() != s.name_.size()) return false; for(size_t i = 0; i < name_.size(); i++) { if(std::tolower(name_[i]) != std::tolower(s.name_[i])) return false; } return true; } bool Squirrel::is_equal(const Squirrel& s1, const Squirrel& s2) { return s1.is_equal(s2); } /**--^----------- Implementation Details -----------^--**/ } //< namespace acorn #endif //< MODEL_SQUIRREL_HPP <commit_msg>Refactored Squirrel::is_equal<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #ifndef MODEL_SQUIRREL_HPP #define MODEL_SQUIRREL_HPP #include <locale> #include <algorithm> #include "json.hpp" namespace acorn { /** * */ struct Squirrel : json::Serializable { size_t key; Squirrel() : key(0) {} /** * */ Squirrel(std::string name, size_t age, std::string occupation) : key {0} , name_ {name} , age_ {age} , occupation_ {occupation} {} /** * */ std::string json() const; /** * */ virtual void serialize(rapidjson::Writer<rapidjson::StringBuffer>&) const override; /** * */ virtual bool deserialize(const rapidjson::Document&) override; /** * */ bool is_equal(const Squirrel&) const; /** * */ static bool is_equal(const Squirrel&, const Squirrel&); private: const std::string name_; const size_t age_; const std::string occupation_; }; //< struct Squirrel /**--v----------- Implementation Details -----------v--**/ inline std::ostream& operator << (std::ostream& output_device, const Squirrel& s) { return output_device.json(); } void Squirrel::serialize(rapidjson::Writer<rapidjson::StringBuffer>& writer) const { writer.StartObject(); writer.Key("key"); writer.Uint(key); writer.Key("name"); writer.String(name_); writer.Key("age"); writer.Uint(age_); writer.Key("occupation"); writer.String(occupation_); writer.EndObject(); } bool Squirrel::deserialize(const rapidjson::Document& doc) { name_ = doc["name"].GetString(); age_ = doc["age"].GetUint(); occupation_ = doc["occupation"].GetString(); return true; } std::string Squirrel::json() const { using namespace rapidjson; StringBuffer sb; Writer<StringBuffer> writer(sb); serialize(writer); return sb.GetString(); } bool Squirrel::is_equal(const Squirrel& s) const { if(name_.size() not_eq s.name_.size()) { return false; } return std::equal(name_.begin(), name_.end(), s.name_.begin(), s.name_.end(), [](const auto a, const auto b) { return ::tolower(a) == ::tolower(b); }); } bool Squirrel::is_equal(const Squirrel& s1, const Squirrel& s2) { return s1.is_equal(s2); } /**--^----------- Implementation Details -----------^--**/ } //< namespace acorn #endif //< MODEL_SQUIRREL_HPP <|endoftext|>
<commit_before>/** * KeybdInput 1.0.3 * * @author Roger Lima (rogerlima@outlook.com) * @date 31/aug/2014 * @update 11/feb/2016 * @desc Reads the keyboard input them according to the format specified (only works on Windows) * @example int day, month, year; KeybdInput< int > userin; userin.solicit( "Type a date (btw 01/01/1900 and 31/12/2009): ", std::regex( "([0-2]?[0-9]|3[0-1])/(0?[1-9]|1[012])/(19[0-9]{2}|200[0-9])" ), { &day, &month, &year }, false, false, false, "/" ); */ #pragma once #include <conio.h> #include <iostream> #include <regex> #include <sstream> #include <vector> #include <Windows.h> template< typename T > class KeybdInput { private: // Stores the values to be used in KeybdInput::reset() bool _instverify, _reset, _ispw; size_t _inmaxsize; std::regex _restriction; std::string _rmsg, _sep; std::vector< T * > _references = {}; // Stores the user input std::string input; // Receives the current X and Y cursor position from get_cursor_position() std::vector< short > cursor_position = { 0, 0 }; // Erase the input of user // @param [{size_t=input.size()}] Erase range void erase_input( size_t = 0 ); // Get the console cursor position and pass to the cursor_position void get_cursor_position(); // Set the console cursor position // @param {short} X position of cursor // @param [{short=cursor_position[ 1 ]}] Y position of cursor void set_cursor_position( short, short = 0 ); // Split a string // @param {std::string} Target string // @param [{std::string=""}] Separator std::vector< std::string > splitstr( std::string str, std::string separator = "" ); // Set the reference with input value // @param {const std::string&} Input value // @param {T*} Target place void set_reference( const std::string&, T * ); // Clear all values of references // @param {T*} Target place void clear_references( std::vector< T * > ); public: // Clipboard (arrow up or down to show the last inputs) std::vector< std::string > clipboard; // Requires the user input again // @param [{std::string=_rmsg}] Request message void reset( std::string = "" ); // Requires the keyboard input // @param {string} Request message // @param {regex} The regex // @param {vector< T * >} The place(s) where it will be stored the input // @param [{bool=false}] Instant verify // @param [{bool=false}] Reset possibility // @param [{bool=false}] Is password // @param [{std::string=" "}] Separator // @param [{size_t=1000}] Input size void solicit( std::string, std::regex, std::vector< T * >, bool = false, bool = false, bool = false, std::string = " ", size_t = 1000 ); }; template< typename T > void KeybdInput< T >::erase_input( size_t erase_range = 0 ) { // Default erase range if ( !erase_range ) erase_range = input.size(); for ( size_t i = 0; i < erase_range; i++ ) std::cout << "\b \b"; input = ""; }; template < typename T > void KeybdInput< T >::set_reference( const std::string& value, T *target ) { std::stringstream convert; convert << value; convert >> *target; }; void KeybdInput< std::string >::set_reference( const std::string& value, std::string *target ) { *target = value; }; template < typename T > void KeybdInput< T >::clear_references( std::vector< T * > target ) { for ( size_t i = 0; i < _references.size(); *target[ i++ ] = 0 ); }; void KeybdInput< std::string >::clear_references( std::vector< std::string * > target ) { for ( size_t i = 0; i < _references.size(); *target[ i++ ] = "" ); }; template< typename T > void KeybdInput< T >::get_cursor_position() { CONSOLE_SCREEN_BUFFER_INFO screen_buffer_info; HANDLE hStd = GetStdHandle( STD_OUTPUT_HANDLE ); if ( !GetConsoleScreenBufferInfo( hStd, &screen_buffer_info ) ) MessageBox( NULL, L"An error occurred getting the console cursor position.", L"KeybdInput ERROR", NULL ); cursor_position[ 0 ] = screen_buffer_info.dwCursorPosition.X; cursor_position[ 1 ] = screen_buffer_info.dwCursorPosition.Y; }; template< typename T > void KeybdInput< T >::set_cursor_position( short x, short y = 0 ) { if ( !SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), { x, y ? y : cursor_position[ 1 ] } ) ) MessageBox( NULL, L"An error occurred setting the console cursor position.", L"KeybdInput ERROR", NULL ); }; template< typename T > std::vector< std::string > KeybdInput< T >::splitstr( std::string str, std::string separator = "" ) { size_t index; std::vector< std::string > elems; while ( ( index = str.find( separator ) ) != std::string::npos && str.size() > 1 ) { elems.push_back( str.substr( 0, index ? index : 1 ) ); str.erase( 0, index + ( !separator.size() ? 1 : separator.size() ) ); } elems.push_back( str ); return elems; }; template< typename T > void KeybdInput< T >::reset( std::string msg = "" ) { // Default request message if ( msg == "" && _rmsg != "" ) msg = _rmsg; if ( !_reset ) { MessageBox( NULL, L"Can't possible execute KeybdInput::reset() without set reset_possibility=true in KeybdInput::solicit().", L"KeybdInput ERROR", NULL ); return; } // Clear previously set values clear_references( _references ); // Sets the cursor in the previous line, erase all and requires input again get_cursor_position(); set_cursor_position( static_cast< short >( msg.size() + input.size() ), cursor_position[ 1 ] - 1 ); erase_input( msg.size() + input.size() ); solicit( msg, std::regex( _restriction ), _references, _instverify, _reset, _ispw, _sep, _inmaxsize ); }; template< typename T > void KeybdInput< T >::solicit( std::string request_msg, std::regex restriction, std::vector< T * > references, bool instant_verify, bool reset_possibility, bool is_password, std::string separator, size_t input_max_size ) { static size_t clipboard_index = 0; size_t i, cursor_pos_x, inputLength = 0; char key = 0; bool is_function_key = false, arrow = false, waiting_input = true; std::string input_subtr; std::vector< std::string > inputParts; if ( references.size() == 0 ) { MessageBox( NULL, L"\"refereces\" param need be set with at least one member.", L"KeybdInput ERROR", NULL ); return; } input = ""; std::cout << request_msg; // Retrieves the values to be used in KeybdInput::reset() if ( reset_possibility ) { _rmsg = request_msg; _restriction = restriction; _references = references; _instverify = instant_verify; _reset = reset_possibility; _ispw = is_password; _sep = separator; _inmaxsize = input_max_size; } // Clears previous data else if ( _reset ) { _rmsg = ""; _restriction = ""; _references = {}; _instverify = false; _reset = false; _ispw = false; _sep = " "; _inmaxsize = 1000; } while ( waiting_input ) { key = _getch(); // Arrow keys prefix if ( key == -32 ) { arrow = true; continue; } // Prevents function keys if ( key == 0 ) { is_function_key = true; continue; } else if ( is_function_key ) { is_function_key = false; continue; } // Arrows if ( arrow ) { get_cursor_position(); // LEFT if ( key == 75 && static_cast< size_t >( cursor_position[ 0 ] ) > request_msg.size() ) set_cursor_position( cursor_position[ 0 ] - 1 ); // RIGHT else if ( key == 77 && static_cast< size_t >( cursor_position[ 0 ] ) < input.size() + request_msg.size() ) set_cursor_position( cursor_position[ 0 ] + 1 ); // UP else if ( key == 72 && !is_password && clipboard.size() > 0 && clipboard_index > 0 ) { erase_input(); std::cout << clipboard[ --clipboard_index ]; input = clipboard[ clipboard_index ]; inputLength = clipboard[ clipboard_index ].size(); } // DOWN else if ( key == 80 && !is_password && clipboard.size() > 0 && clipboard_index < clipboard.size() - 1 ) { erase_input(); std::cout << clipboard[ ++clipboard_index ]; input = clipboard[ clipboard_index ]; inputLength = clipboard[ clipboard_index ].size(); if ( clipboard_index >= clipboard.size() ) clipboard_index = clipboard.size() - 1; } } // Valid character else if ( key != 8 && key != 13 ) { // Inserts the character in current cursor position get_cursor_position(); input.insert( cursor_position[ 0 ] - request_msg.size(), std::string( 1, key ) ); // If the user input satisfy the restrictions, removes the character if ( instant_verify && ( input.size() > input_max_size || !std::regex_match( input, restriction ) ) ) { input.erase( cursor_position[ 0 ] - request_msg.size(), 1 ); } else { // Appends the character if cursor is at the end, otherwise, interleaves if ( cursor_position[ 0 ] == ( request_msg.size() + input.size() - 1 ) ) { std::cout << ( ( is_password ) ? '*' : key ); } else { input_subtr = input.substr( input.size() - ( ( request_msg.size() + input.size() ) - cursor_position[ 0 ] - 1 ), input.size() ); std::cout << ( ( is_password ) ? '*' : key ) << ( ( is_password ) ? std::string( input_subtr.size(), '*' ) : input_subtr ); set_cursor_position( cursor_position[ 0 ] + 1 ); } inputLength++; } } // ENTER else if ( key == 13 && inputLength ) { // If the user input satisfy the restrictions, clear input if ( input.size() > input_max_size || !std::regex_match( input, restriction ) ) { erase_input(); inputLength = 0; } else { // Trim left and right input.erase( 0, input.find_first_not_of( ' ' ) ); input.erase( input.find_last_not_of( ' ' ) + 1 ); if ( references.size() == 1 ) set_reference( input, references[ 0 ] ); else for ( i = 0, inputParts = splitstr( input, separator ); i < references.size(); i++ ) if ( i < inputParts.size() ) set_reference( inputParts[ i ], references[ i ] ); std::cout << std::endl; // Prevents repetition on clipboard and don't save if it's a password if ( !is_password && ( clipboard.size() == 0 || input != clipboard[ clipboard.size() - 1 ] ) ) { clipboard.push_back( input ); clipboard_index = clipboard.size(); } waiting_input = false; } } // BACKSPACE else if ( key == 8 && inputLength ) { get_cursor_position(); cursor_pos_x = cursor_position[ 0 ]; if ( cursor_pos_x == ( request_msg.size() + input.size() - 1 ) && inputLength == 1 ) continue; std::cout << "\b \b"; input.erase( cursor_pos_x - request_msg.size() - 1, 1 ); inputLength--; // If the cursor isn't at the end if ( cursor_pos_x <= ( request_msg.size() + input.size() ) ) { // Put the cursor at the start and rewrites the input set_cursor_position( static_cast< short >( request_msg.size() ) ); std::cout << ( ( is_password ) ? std::string( input.size(), '*' ) : input ); // Put the cursor at the end and erase the last char set_cursor_position( static_cast< short >( request_msg.size() + input.size() + 1 ) ); std::cout << "\b \b"; // Put the cursor at the original position set_cursor_position( static_cast< short >( cursor_pos_x - 1 ) ); } } arrow = false; } }; <commit_msg>Buf fix<commit_after>/** * KeybdInput 1.0.3 * * @author Roger Lima (rogerlima@outlook.com) * @date 31/aug/2014 * @update 19/feb/2016 * @desc Reads the keyboard input them according to the format specified (only works on Windows) * @example int day, month, year; KeybdInput< int > userin; userin.solicit( "Type a date (btw 01/01/1900 and 31/12/2009): ", std::regex( "([0-2]?[0-9]|3[0-1])/(0?[1-9]|1[012])/(19[0-9]{2}|200[0-9])" ), { &day, &month, &year }, false, false, false, "/" ); */ #pragma once #include <conio.h> #include <iostream> #include <regex> #include <sstream> #include <vector> #include <Windows.h> template< typename T > class KeybdInput { private: // Stores the values to be used in KeybdInput::reset() bool _instverify, _reset, _ispw; size_t _inmaxsize; std::regex _restriction; std::string _rmsg, _sep; std::vector< T * > _references = {}; // Stores the user input std::string input; // Receives the current X and Y cursor position from get_cursor_position() std::vector< short > cursor_position = { 0, 0 }; // Erase the input of user // @param [{size_t=input.size()}] Erase range void erase_input( size_t = 0 ); // Get the console cursor position and pass to the cursor_position void get_cursor_position(); // Set the console cursor position // @param {short} X position of cursor // @param [{short=cursor_position[ 1 ]}] Y position of cursor void set_cursor_position( short, short = 0 ); // Split a string // @param {std::string} Target string // @param [{std::string=""}] Separator std::vector< std::string > splitstr( std::string str, std::string separator = "" ); // Set the reference with input value // @param {const std::string&} Input value // @param {T*} Target place void set_reference( const std::string&, T * ); // Clear all values of references // @param {T*} Target place void clear_references( std::vector< T * > ); public: // Clipboard (arrow up or down to show the last inputs) std::vector< std::string > clipboard; // Requires the user input again // @param [{std::string=_rmsg}] Request message void reset( std::string = "" ); // Requires the keyboard input // @param {string} Request message // @param {regex} The regex // @param {vector< T * >} The place(s) where it will be stored the input // @param [{bool=false}] Instant verify // @param [{bool=false}] Reset possibility // @param [{bool=false}] Is password // @param [{std::string=" "}] Separator // @param [{size_t=1000}] Input size void solicit( std::string, std::regex, std::vector< T * >, bool = false, bool = false, bool = false, std::string = " ", size_t = 1000 ); }; template< typename T > void KeybdInput< T >::erase_input( size_t erase_range = 0 ) { // Default erase range if ( !erase_range ) erase_range = input.size(); for ( size_t i = 0; i < erase_range; i++ ) std::cout << "\b \b"; input = ""; }; template < typename T > void KeybdInput< T >::set_reference( const std::string& value, T *target ) { std::stringstream convert; convert << value; convert >> *target; }; void KeybdInput< std::string >::set_reference( const std::string& value, std::string *target ) { *target = value; }; template < typename T > void KeybdInput< T >::clear_references( std::vector< T * > target ) { for ( size_t i = 0; i < _references.size(); *target[ i++ ] = 0 ); }; void KeybdInput< std::string >::clear_references( std::vector< std::string * > target ) { for ( size_t i = 0; i < _references.size(); *target[ i++ ] = "" ); }; template< typename T > void KeybdInput< T >::get_cursor_position() { CONSOLE_SCREEN_BUFFER_INFO screen_buffer_info; HANDLE hStd = GetStdHandle( STD_OUTPUT_HANDLE ); if ( !GetConsoleScreenBufferInfo( hStd, &screen_buffer_info ) ) MessageBox( NULL, L"An error occurred getting the console cursor position.", L"KeybdInput ERROR", NULL ); cursor_position[ 0 ] = screen_buffer_info.dwCursorPosition.X; cursor_position[ 1 ] = screen_buffer_info.dwCursorPosition.Y; }; template< typename T > void KeybdInput< T >::set_cursor_position( short x, short y = 0 ) { if ( !SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), { x, y } ) ) MessageBox( NULL, L"An error occurred setting the console cursor position.", L"KeybdInput ERROR", NULL ); }; template< typename T > std::vector< std::string > KeybdInput< T >::splitstr( std::string str, std::string separator = "" ) { size_t index; std::vector< std::string > elems; while ( ( index = str.find( separator ) ) != std::string::npos && str.size() > 1 ) { elems.push_back( str.substr( 0, index ? index : 1 ) ); str.erase( 0, index + ( !separator.size() ? 1 : separator.size() ) ); } elems.push_back( str ); return elems; }; template< typename T > void KeybdInput< T >::reset( std::string msg = "" ) { // Default request message if ( msg == "" && _rmsg != "" ) msg = _rmsg; if ( !_reset ) { MessageBox( NULL, L"Can't possible execute KeybdInput::reset() without set reset_possibility=true in KeybdInput::solicit().", L"KeybdInput ERROR", NULL ); return; } // Clear previously set values clear_references( _references ); // Sets the cursor in the previous line, erase all and requires input again get_cursor_position(); set_cursor_position( static_cast< short >( msg.size() + input.size() ), cursor_position[ 1 ] - 1 ); erase_input( msg.size() + input.size() ); solicit( msg, std::regex( _restriction ), _references, _instverify, _reset, _ispw, _sep, _inmaxsize ); }; template< typename T > void KeybdInput< T >::solicit( std::string request_msg, std::regex restriction, std::vector< T * > references, bool instant_verify, bool reset_possibility, bool is_password, std::string separator, size_t input_max_size ) { static size_t clipboard_index = 0; size_t i, cursor_pos_x, inputLength = 0; char key = 0; bool is_function_key = false, arrow = false, waiting_input = true; std::string input_subtr; std::vector< std::string > inputParts; if ( references.size() == 0 ) { MessageBox( NULL, L"\"refereces\" param need be set with at least one member.", L"KeybdInput ERROR", NULL ); return; } input = ""; std::cout << request_msg; // Retrieves the values to be used in KeybdInput::reset() if ( reset_possibility ) { _rmsg = request_msg; _restriction = restriction; _references = references; _instverify = instant_verify; _reset = reset_possibility; _ispw = is_password; _sep = separator; _inmaxsize = input_max_size; } // Clears previous data else if ( _reset ) { _rmsg = ""; _restriction = ""; _references = {}; _instverify = false; _reset = false; _ispw = false; _sep = " "; _inmaxsize = 1000; } while ( waiting_input ) { key = _getch(); // Arrow keys prefix if ( key == -32 ) { arrow = true; continue; } // Prevents function keys if ( key == 0 ) { is_function_key = true; continue; } else if ( is_function_key ) { is_function_key = false; continue; } // Arrows if ( arrow ) { get_cursor_position(); // LEFT if ( key == 75 && static_cast< size_t >( cursor_position[ 0 ] ) > request_msg.size() ) set_cursor_position( cursor_position[ 0 ] - 1 ); // RIGHT else if ( key == 77 && static_cast< size_t >( cursor_position[ 0 ] ) < input.size() + request_msg.size() ) set_cursor_position( cursor_position[ 0 ] + 1 ); // UP else if ( key == 72 && !is_password && clipboard.size() > 0 && clipboard_index > 0 ) { erase_input(); std::cout << clipboard[ --clipboard_index ]; input = clipboard[ clipboard_index ]; inputLength = clipboard[ clipboard_index ].size(); } // DOWN else if ( key == 80 && !is_password && clipboard.size() > 0 && clipboard_index < clipboard.size() - 1 ) { erase_input(); std::cout << clipboard[ ++clipboard_index ]; input = clipboard[ clipboard_index ]; inputLength = clipboard[ clipboard_index ].size(); if ( clipboard_index >= clipboard.size() ) clipboard_index = clipboard.size() - 1; } } // Valid character else if ( key != 8 && key != 13 ) { // Inserts the character in current cursor position get_cursor_position(); input.insert( cursor_position[ 0 ] - request_msg.size(), std::string( 1, key ) ); // If the user input satisfy the restrictions, removes the character if ( instant_verify && ( input.size() > input_max_size || !std::regex_match( input, restriction ) ) ) { input.erase( cursor_position[ 0 ] - request_msg.size(), 1 ); } else { // Appends the character if cursor is at the end, otherwise, interleaves if ( cursor_position[ 0 ] == ( request_msg.size() + input.size() - 1 ) ) { std::cout << ( ( is_password ) ? '*' : key ); } else { input_subtr = input.substr( input.size() - ( ( request_msg.size() + input.size() ) - cursor_position[ 0 ] - 1 ), input.size() ); std::cout << ( ( is_password ) ? '*' : key ) << ( ( is_password ) ? std::string( input_subtr.size(), '*' ) : input_subtr ); set_cursor_position( cursor_position[ 0 ] + 1 ); } inputLength++; } } // ENTER else if ( key == 13 && inputLength ) { // If the user input satisfy the restrictions, clear input if ( input.size() > input_max_size || !std::regex_match( input, restriction ) ) { erase_input(); inputLength = 0; } else { // Trim left and right input.erase( 0, input.find_first_not_of( ' ' ) ); input.erase( input.find_last_not_of( ' ' ) + 1 ); if ( references.size() == 1 ) set_reference( input, references[ 0 ] ); else for ( i = 0, inputParts = splitstr( input, separator ); i < references.size(); i++ ) if ( i < inputParts.size() ) set_reference( inputParts[ i ], references[ i ] ); std::cout << std::endl; // Prevents repetition on clipboard and don't save if it's a password if ( !is_password && ( clipboard.size() == 0 || input != clipboard[ clipboard.size() - 1 ] ) ) { clipboard.push_back( input ); clipboard_index = clipboard.size(); } waiting_input = false; } } // BACKSPACE else if ( key == 8 && inputLength ) { get_cursor_position(); cursor_pos_x = cursor_position[ 0 ]; if ( cursor_pos_x == ( request_msg.size() + input.size() - 1 ) && inputLength == 1 ) continue; std::cout << "\b \b"; input.erase( cursor_pos_x - request_msg.size() - 1, 1 ); inputLength--; // If the cursor isn't at the end if ( cursor_pos_x <= ( request_msg.size() + input.size() ) ) { // Put the cursor at the start and rewrites the input set_cursor_position( static_cast< short >( request_msg.size() ) ); std::cout << ( ( is_password ) ? std::string( input.size(), '*' ) : input ); // Put the cursor at the end and erase the last char set_cursor_position( static_cast< short >( request_msg.size() + input.size() + 1 ) ); std::cout << "\b \b"; // Put the cursor at the original position set_cursor_position( static_cast< short >( cursor_pos_x - 1 ) ); } } arrow = false; } }; <|endoftext|>
<commit_before>#include "DoubleIntegrator.h" #include "InterpolatorHelpers.h" #include "ParabolicRamp.h" #include "KinodynamicPath.h" #include "CSetHelpers.h" #include <sstream> using namespace std; void Convert(const ParabolicRamp::ParabolicRamp1D& ramp,Spline::PiecewisePolynomial& res) { res.segments.resize(3); res.timeShift.resize(3); res.times.resize(4); res.times[0] = 0; res.times[1] = ramp.tswitch1; res.times[2] = ramp.tswitch2; res.times[3] = ramp.ttotal; res.segments[0].Resize(3); res.segments[0].coef[0] = ramp.x0; res.segments[0].coef[1] = ramp.dx0; res.segments[0].coef[2] = 0.5*ramp.a1; res.timeShift[0] = 0; res.segments[1].Resize(2); res.segments[1].coef[0] = ramp.Evaluate(ramp.tswitch1); res.segments[1].coef[1] = ramp.Derivative(ramp.tswitch1); res.timeShift[1] = ramp.tswitch1; res.segments[2].Resize(3); res.segments[2].coef[0] = ramp.x1; res.segments[2].coef[1] = ramp.dx1; res.segments[2].coef[2] = 0.5*ramp.a2; res.timeShift[2] = ramp.ttotal; if(ramp.ttotal == ramp.tswitch2) { res.times.erase(--res.times.end()); res.segments.erase(--res.segments.end()); res.timeShift.erase(--res.timeShift.end()); } if(ramp.tswitch1 == ramp.tswitch2) { res.times.erase(++res.times.begin()); res.segments.erase(++res.segments.begin()); res.timeShift.erase(++res.timeShift.begin()); } if(ramp.tswitch1 == 0 && res.segments.size()>1) { res.times.erase(res.times.begin()); res.segments.erase(res.segments.begin()); res.timeShift.erase(res.timeShift.begin()); } } void Convert(const ParabolicRamp::ParabolicRampND& ramp,Spline::PiecewisePolynomialND& res) { res.elements.resize(ramp.ramps.size()); for(size_t i=0;i<ramp.ramps.size();i++) Convert(ramp.ramps[i],res.elements[i]); } //concatenates the ramps void Convert(const std::vector<ParabolicRamp::ParabolicRamp1D>& ramps,Spline::PiecewisePolynomial& res) { assert(!ramps.empty()); Convert(ramps[0],res); for(size_t i=1;i<ramps.size();i++) { Spline::PiecewisePolynomial suffix; Convert(ramps[i],suffix); res.Concat(suffix,true); } } void Convert(const std::vector<std::vector<ParabolicRamp::ParabolicRamp1D> >& ramps,Spline::PiecewisePolynomialND& res) { res.elements.resize(ramps.size()); for(size_t i=0;i<ramps.size();i++) Convert(ramps[i],res.elements[i]); } DoubleIntegratorControlSpace::DoubleIntegratorControlSpace(const SmartPointer<CSet>& uset,Real dtmax) :IntegratedControlSpace(uset,dtmax,dtmax) {} Interpolator* DoubleIntegratorControlSpace::Simulate(const State& x0, const ControlInput& u) { //do we want to have the interpolator in the range [0,1]? Vector q0,v0; CVSpace::GetState(x0,q0,v0); Real udt = u(0); ControlInput ubase; ubase.setRef(u,1,1,u.n-1); vector<Spline::Polynomial<double> > elements(x0.n); assert(q0.n == ubase.n); for(int i=0;i<x0.n;i++) { elements[i].Resize(2); elements[i].SetCoef(0,q0[i]); elements[i].SetCoef(1,v0[i]); elements[i].SetCoef(2,0.5*ubase[i]); } Spline::PiecewisePolynomialND path(elements,0,udt); return new PiecewisePolynomialInterpolator(path); } std::string DoubleIntegratorControlSpace::VariableName(int i) { if(i==0) return "time_step"; stringstream ss; ss<<"ddx"<<i-1; return ss.str(); } void DoubleIntegratorControlSpace::Successor(const State& x0, const ControlInput& u,State& x1) { Real udt = u(0); ControlInput ubase; ubase.setRef(u,1,1,u.n-1); EvalDynamics(x0,ubase,udt,x1); } void DoubleIntegratorControlSpace::Derivative(const State& x, const ControlInput& u,State& dx) { Vector q,v; CVSpace::GetState(x,q,v); CVSpace::SetState(v,u,dx); } void DoubleIntegratorControlSpace::EvalDynamics(const State& x0, const ControlInput& ddx,Real t,State& x1) { Vector q0,v0,q1,v1; CVSpace::GetState(x0,q0,v0); q1 = q0 + t*v0 + (0.5*t*t)*ddx; v1 = v0 + t*ddx; CVSpace::SetState(q1,v1,x1); } DoubleIntegratorKinodynamicSpace::DoubleIntegratorKinodynamicSpace(SmartPointer<CSpace> qspace,SmartPointer<CSpace> vspace,SmartPointer<CSet> uset,Real dtmax) :KinodynamicSpace(new CVSpace(qspace,vspace),new DoubleIntegratorControlSpace(uset,dtmax)),visibilityEpsilon(1e-2) { BoxSet* abset = dynamic_cast<BoxSet*>(&*uset); if(!abset) { printf("DoubleIntegratorKinodynamicSpace: No steering function available; accelerations are not box-bounded\n"); } else { //create steering function PropertyMap props; vspace->Properties(props); vector<Real> vmin,vmax; if(!props.getArray("minimum",vmin) || !props.getArray("maximum",vmax)) { vmin.resize(abset->bmin.size(),-Inf); vmax.resize(abset->bmax.size(),Inf); } controlSpace->mySteeringFunction = new DoubleIntegratorBoxBoundedSteeringFunction(abset->bmax,vmax); } } EdgePlanner* DoubleIntegratorKinodynamicSpace::TrajectoryChecker(const ControlInput& u,const SmartPointer<Interpolator>& path) { return new EpsilonEdgeChecker(GetStateSpace(),path,visibilityEpsilon); } void DoubleIntegratorKinodynamicSpace::SetVisibilityEpsilon(Real tol) { visibilityEpsilon = tol; } DoubleIntegratorBoxBoundedSteeringFunction::DoubleIntegratorBoxBoundedSteeringFunction(const Vector& _amax,const Vector& _vmax) :amax(vector<double>(_amax)),vmax(vector<double>(_vmax)) {} void DoubleIntegratorBoxBoundedSteeringFunction::SetConfigurationBounds(const Config& _qmin,const Config& _qmax) { qmin = _qmin; qmax = _qmax; } bool DoubleIntegratorBoxBoundedSteeringFunction::Connect(const State& x,const State& y,KinodynamicMilestonePath& path) { Vector qx,vx,qy,vy; CVSpace::GetState(x,qx,vx); CVSpace::GetState(y,qy,vy); ParabolicRamp::ParabolicRampND ramp; ramp.x0 = qx; ramp.x1 = qy; ramp.dx0 = vx; ramp.dx1 = vy; if(!ramp.SolveMinTime(vector<double>(amax),vector<double>(vmax))) return false; path.milestones[0] = x; path.milestones[1] = y; //NOTE: THE CONTROL IS INVALID. SHOULD WE SPLIT UP THE PATH INTO PIECEWISE QUADRATIC SEGMENTS? path.controls.resize(1); path.controls[0].resize(0); Spline::PiecewisePolynomialND ppath; Convert(ramp,ppath); path.paths.push_back(new PiecewisePolynomialInterpolator(ppath)); return true; }<commit_msg>Fixed DoubleIntegrator steering function problems<commit_after>#include "DoubleIntegrator.h" #include "InterpolatorHelpers.h" #include "ParabolicRamp.h" #include "KinodynamicPath.h" #include "CSetHelpers.h" #include <iostream> #include <sstream> using namespace std; void Convert(const ParabolicRamp::ParabolicRamp1D& ramp,Spline::PiecewisePolynomial& res) { res.segments.resize(3); res.timeShift.resize(3); res.times.resize(4); res.times[0] = 0; res.times[1] = ramp.tswitch1; res.times[2] = ramp.tswitch2; res.times[3] = ramp.ttotal; res.segments[0].Resize(3); res.segments[0].coef[0] = ramp.x0; res.segments[0].coef[1] = ramp.dx0; res.segments[0].coef[2] = 0.5*ramp.a1; res.timeShift[0] = 0; res.segments[1].Resize(2); res.segments[1].coef[0] = ramp.Evaluate(ramp.tswitch1); res.segments[1].coef[1] = ramp.Derivative(ramp.tswitch1); res.timeShift[1] = ramp.tswitch1; res.segments[2].Resize(3); res.segments[2].coef[0] = ramp.x1; res.segments[2].coef[1] = ramp.dx1; res.segments[2].coef[2] = 0.5*ramp.a2; res.timeShift[2] = ramp.ttotal; if(ramp.ttotal == ramp.tswitch2) { res.times.erase(--res.times.end()); res.segments.erase(--res.segments.end()); res.timeShift.erase(--res.timeShift.end()); } if(ramp.tswitch1 == ramp.tswitch2) { res.times.erase(++res.times.begin()); res.segments.erase(++res.segments.begin()); res.timeShift.erase(++res.timeShift.begin()); } if(ramp.tswitch1 == 0 && res.segments.size()>1) { res.times.erase(res.times.begin()); res.segments.erase(res.segments.begin()); res.timeShift.erase(res.timeShift.begin()); } } void Convert(const ParabolicRamp::ParabolicRampND& ramp,Spline::PiecewisePolynomialND& res) { res.elements.resize(ramp.ramps.size()); for(size_t i=0;i<ramp.ramps.size();i++) Convert(ramp.ramps[i],res.elements[i]); } //concatenates the ramps void Convert(const std::vector<ParabolicRamp::ParabolicRamp1D>& ramps,Spline::PiecewisePolynomial& res) { assert(!ramps.empty()); Convert(ramps[0],res); for(size_t i=1;i<ramps.size();i++) { Spline::PiecewisePolynomial suffix; Convert(ramps[i],suffix); res.Concat(suffix,true); } } void Convert(const std::vector<std::vector<ParabolicRamp::ParabolicRamp1D> >& ramps,Spline::PiecewisePolynomialND& res) { res.elements.resize(ramps.size()); for(size_t i=0;i<ramps.size();i++) Convert(ramps[i],res.elements[i]); } DoubleIntegratorControlSpace::DoubleIntegratorControlSpace(const SmartPointer<CSet>& uset,Real dtmax) :IntegratedControlSpace(uset,dtmax,dtmax) {} Interpolator* DoubleIntegratorControlSpace::Simulate(const State& x0, const ControlInput& u) { //do we want to have the interpolator in the range [0,1]? Vector q0,v0; CVSpace::GetState(x0,q0,v0); Real udt = u(0); ControlInput ubase; ubase.setRef(u,1,1,u.n-1); vector<Spline::Polynomial<double> > elements(x0.n); assert(q0.n == ubase.n); for(int i=0;i<q0.n;i++) { elements[i].Resize(3); elements[i].SetCoef(0,q0[i]); elements[i].SetCoef(1,v0[i]); elements[i].SetCoef(2,0.5*ubase[i]); } for(int i=0;i<q0.n;i++) { elements[i+q0.n].Resize(2); elements[i+q0.n].SetCoef(0,v0[i]); elements[i+q0.n].SetCoef(1,ubase[i]); } Spline::PiecewisePolynomialND path(elements,0,udt); return new PiecewisePolynomialInterpolator(path); } std::string DoubleIntegratorControlSpace::VariableName(int i) { if(i==0) return "time_step"; stringstream ss; ss<<"ddx"<<i-1; return ss.str(); } void DoubleIntegratorControlSpace::Successor(const State& x0, const ControlInput& u,State& x1) { Real udt = u(0); ControlInput ubase; ubase.setRef(u,1,1,u.n-1); EvalDynamics(x0,ubase,udt,x1); } void DoubleIntegratorControlSpace::Derivative(const State& x, const ControlInput& u,State& dx) { Vector q,v; CVSpace::GetState(x,q,v); CVSpace::SetState(v,u,dx); } void DoubleIntegratorControlSpace::EvalDynamics(const State& x0, const ControlInput& ddx,Real t,State& x1) { Vector q0,v0,q1,v1; CVSpace::GetState(x0,q0,v0); q1 = q0 + t*v0 + (0.5*t*t)*ddx; v1 = v0 + t*ddx; CVSpace::SetState(q1,v1,x1); } DoubleIntegratorKinodynamicSpace::DoubleIntegratorKinodynamicSpace(SmartPointer<CSpace> qspace,SmartPointer<CSpace> vspace,SmartPointer<CSet> uset,Real dtmax) :KinodynamicSpace(new CVSpace(qspace,vspace),new DoubleIntegratorControlSpace(uset,dtmax)),visibilityEpsilon(1e-2) { BoxSet* abset = dynamic_cast<BoxSet*>(&*uset); if(!abset) { printf("DoubleIntegratorKinodynamicSpace: No steering function available; accelerations are not box-bounded\n"); } else { //create steering function PropertyMap props; vspace->Properties(props); vector<Real> vmin,vmax; if(!props.getArray("minimum",vmin) || !props.getArray("maximum",vmax)) { vmin.resize(abset->bmin.size(),-Inf); vmax.resize(abset->bmax.size(),Inf); } controlSpace->mySteeringFunction = new DoubleIntegratorBoxBoundedSteeringFunction(abset->bmax,vmax); } } EdgePlanner* DoubleIntegratorKinodynamicSpace::TrajectoryChecker(const ControlInput& u,const SmartPointer<Interpolator>& path) { return new EpsilonEdgeChecker(GetStateSpace(),path,visibilityEpsilon); } void DoubleIntegratorKinodynamicSpace::SetVisibilityEpsilon(Real tol) { visibilityEpsilon = tol; } DoubleIntegratorBoxBoundedSteeringFunction::DoubleIntegratorBoxBoundedSteeringFunction(const Vector& _amax,const Vector& _vmax) :amax(vector<double>(_amax)),vmax(vector<double>(_vmax)) {} void DoubleIntegratorBoxBoundedSteeringFunction::SetConfigurationBounds(const Config& _qmin,const Config& _qmax) { qmin = _qmin; qmax = _qmax; } bool DoubleIntegratorBoxBoundedSteeringFunction::Connect(const State& x,const State& y,KinodynamicMilestonePath& path) { Vector qx,vx,qy,vy; CVSpace::GetState(x,qx,vx); CVSpace::GetState(y,qy,vy); ParabolicRamp::ParabolicRampND ramp; ramp.x0 = qx; ramp.x1 = qy; ramp.dx0 = vx; ramp.dx1 = vy; if(!ramp.SolveMinTime(vector<double>(amax),vector<double>(vmax))) return false; path.milestones.resize(2); path.milestones[0] = x; path.milestones[1] = y; //NOTE: THE CONTROL IS INVALID. SHOULD WE SPLIT UP THE PATH INTO PIECEWISE QUADRATIC SEGMENTS? path.controls.resize(1); path.controls[0].resize(qx.n+1,0.0); path.controls[0][0] = ramp.endTime; Spline::PiecewisePolynomialND ppath; Convert(ramp,ppath); Spline::PiecewisePolynomialND dpath = ppath.Differentiate(); //the polynomial needs derivative information too... ppath.elements.insert(ppath.elements.end(),dpath.elements.begin(),dpath.elements.end()); path.paths.push_back(new PiecewisePolynomialInterpolator(ppath)); return true; }<|endoftext|>
<commit_before>/* Authors: Lutong Wang and Bangqi Xu */ /* * Copyright (c) 2019, The Regents of the University of California * 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 University nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 <fstream> #include <iostream> #include "db/tech/frTechObject.h" #include "dr/FlexDR.h" #include "frDesign.h" #include "gc/FlexGC.h" #include "global.h" #include "gr/FlexGR.h" #include "gui/gui.h" #include "io/io.h" #include "pa/FlexPA.h" #include "rp/FlexRP.h" #include "sta/StaMain.hh" #include "ta/FlexTA.h" #include "triton_route/TritonRoute.h" using namespace std; using namespace fr; using namespace triton_route; namespace sta { // Tcl files encoded into strings. extern const char* TritonRoute_tcl_inits[]; } // namespace sta extern "C" { extern int Tritonroute_Init(Tcl_Interp* interp); } TritonRoute::TritonRoute() : debug_(std::make_unique<frDebugSettings>()), num_drvs_(-1), gui_(gui::Gui::get()) { } TritonRoute::~TritonRoute() { } void TritonRoute::setDebugDR(bool on) { debug_->debugDR = on; } void TritonRoute::setDebugMaze(bool on) { debug_->debugMaze = on; } void TritonRoute::setDebugPA(bool on) { debug_->debugPA = on; } void TritonRoute::setDebugNetName(const char* name) { debug_->netName = name; } void TritonRoute::setDebugPinName(const char* name) { debug_->pinName = name; } void TritonRoute::setDebugGCell(int x, int y) { debug_->gcellX = x; debug_->gcellY = y; } void TritonRoute::setDebugIter(int iter) { debug_->iter = iter; } void TritonRoute::setDebugPaMarkers(bool on) { debug_->paMarkers = on; } int TritonRoute::getNumDRVs() const { if (num_drvs_ < 0) { logger_->error(DRT, 2, "Detailed routing has not been run yet."); } return num_drvs_; } void TritonRoute::init(Tcl_Interp* tcl_interp, odb::dbDatabase* db, Logger* logger) { db_ = db; logger_ = logger; design_ = std::make_unique<frDesign>(logger_); // Define swig TCL commands. Tritonroute_Init(tcl_interp); sta::evalTclInit(tcl_interp, sta::TritonRoute_tcl_inits); } void TritonRoute::init() { if (DBPROCESSNODE == "GF14_13M_3Mx_2Cx_4Kx_2Hx_2Gx_LB") { VIAINPIN_BOTTOMLAYERNUM = 2; VIAINPIN_TOPLAYERNUM = 2; USENONPREFTRACKS = false; BOTTOM_ROUTING_LAYER = 4; TOP_ROUTING_LAYER = 18; ENABLE_VIA_GEN = false; } io::Parser parser(getDesign(), logger_); parser.readDb(db_); auto tech = getDesign()->getTech(); if (!BOTTOM_ROUTING_LAYER_NAME.empty()) { frLayer* layer = tech->getLayer(BOTTOM_ROUTING_LAYER_NAME); if (layer) { BOTTOM_ROUTING_LAYER = layer->getLayerNum(); } else { logger_->warn(utl::DRT, 251, "bottomRoutingLayer {} not found", BOTTOM_ROUTING_LAYER_NAME); } } if (!TOP_ROUTING_LAYER_NAME.empty()) { frLayer* layer = tech->getLayer(TOP_ROUTING_LAYER_NAME); if (layer) { TOP_ROUTING_LAYER = layer->getLayerNum(); } else { logger_->warn(utl::DRT, 252, "bottomRoutingLayer {} not found", TOP_ROUTING_LAYER_NAME); } } if (GUIDE_FILE != string("")) { parser.readGuide(); } else { ENABLE_VIA_GEN = false; } parser.postProcess(); FlexPA pa(getDesign(), logger_); pa.setDebug(debug_.get(), db_); pa.main(); if (GUIDE_FILE != string("")) { parser.postProcessGuide(); } // GR-related parser.initRPin(); cout << "BRANCH NDR_testing\n"; } void TritonRoute::prep() { FlexRP rp(getDesign(), getDesign()->getTech(), logger_); rp.main(); } void TritonRoute::gr() { FlexGR gr(getDesign(), logger_); gr.main(db_); } void TritonRoute::ta() { FlexTA ta(getDesign(), logger_); ta.main(); } void TritonRoute::dr() { num_drvs_ = -1; FlexDR dr(getDesign(), logger_, db_); dr.setDebug(debug_.get()); dr.main(); } void TritonRoute::endFR() { io::Writer writer(getDesign(), logger_); writer.updateDb(db_); } void TritonRoute::reportConstraints() { getDesign()->getTech()->printAllConstraints(logger_); } int TritonRoute::main() { init(); if (GUIDE_FILE == string("")) { gr(); io::Parser parser(getDesign(), logger_); GUIDE_FILE = OUTGUIDE_FILE; ENABLE_VIA_GEN = true; parser.readGuide(); parser.initDefaultVias(); parser.postProcessGuide(); } prep(); ta(); dr(); endFR(); num_drvs_ = design_->getTopBlock()->getNumMarkers(); return 0; } void TritonRoute::readParams(const string& fileName) { int readParamCnt = 0; ifstream fin(fileName.c_str()); string line; if (fin.is_open()) { while (fin.good()) { getline(fin, line); if (line[0] != '#') { char delimiter = ':'; int pos = line.find(delimiter); string field = line.substr(0, pos); string value = line.substr(pos + 1); stringstream ss(value); if (field == "lef") { logger_->warn(utl::DRT, 148, "deprecated lef param in params file"); } else if (field == "def") { logger_->warn(utl::DRT, 227, "deprecated def param in params file"); } else if (field == "guide") { GUIDE_FILE = value; ++readParamCnt; } else if (field == "outputTA") { logger_->warn( utl::DRT, 171, "deprecated outputTA param in params file"); } else if (field == "output") { logger_->warn( utl::DRT, 205, "deprecated output param in params file"); } else if (field == "outputguide") { OUTGUIDE_FILE = value; ++readParamCnt; } else if (field == "outputMaze") { OUT_MAZE_FILE = value; ++readParamCnt; } else if (field == "outputDRC") { DRC_RPT_FILE = value; ++readParamCnt; } else if (field == "outputCMap") { CMAP_FILE = value; ++readParamCnt; } else if (field == "threads") { MAX_THREADS = atoi(value.c_str()); ++readParamCnt; } else if (field == "verbose") VERBOSE = atoi(value.c_str()); else if (field == "dbProcessNode") { DBPROCESSNODE = value; ++readParamCnt; } else if (field == "drouteViaInPinBottomLayerNum") { VIAINPIN_BOTTOMLAYERNUM = atoi(value.c_str()); ++readParamCnt; } else if (field == "drouteViaInPinTopLayerNum") { VIAINPIN_TOPLAYERNUM = atoi(value.c_str()); ++readParamCnt; } else if (field == "drouteEndIterNum") { END_ITERATION = atoi(value.c_str()); ++readParamCnt; } else if (field == "OR_SEED") { OR_SEED = atoi(value.c_str()); ++readParamCnt; } else if (field == "OR_K") { OR_K = atof(value.c_str()); ++readParamCnt; } else if (field == "bottomRoutingLayer") { BOTTOM_ROUTING_LAYER_NAME = value; ++readParamCnt; } else if (field == "topRoutingLayer") { TOP_ROUTING_LAYER_NAME = value; ++readParamCnt; } else if (field == "initRouteShapeCost") { ROUTESHAPECOST = atoi(value.c_str()); ++readParamCnt; } } } fin.close(); } if (readParamCnt < 2) { logger_->error(DRT, 1, "Error reading param file: {}", fileName); } } bool fr::isPad(MacroClassEnum e) { return e == MacroClassEnum::PAD || e == MacroClassEnum::PAD_INPUT || e == MacroClassEnum::PAD_OUTPUT || e == MacroClassEnum::PAD_INOUT || e == MacroClassEnum::PAD_POWER || e == MacroClassEnum::PAD_SPACER || e == MacroClassEnum::PAD_AREAIO; } bool fr::isEndcap(MacroClassEnum e) { return e == MacroClassEnum::ENDCAP || e == MacroClassEnum::ENDCAP_PRE || e == MacroClassEnum::ENDCAP_POST || e == MacroClassEnum::ENDCAP_TOPLEFT || e == MacroClassEnum::ENDCAP_TOPRIGHT || e == MacroClassEnum::ENDCAP_BOTTOMLEFT || e == MacroClassEnum::ENDCAP_BOTTOMRIGHT; } <commit_msg>log "BRANCH NDR_testing" in logger<commit_after>/* Authors: Lutong Wang and Bangqi Xu */ /* * Copyright (c) 2019, The Regents of the University of California * 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 University nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 <fstream> #include <iostream> #include "db/tech/frTechObject.h" #include "dr/FlexDR.h" #include "frDesign.h" #include "gc/FlexGC.h" #include "global.h" #include "gr/FlexGR.h" #include "gui/gui.h" #include "io/io.h" #include "pa/FlexPA.h" #include "rp/FlexRP.h" #include "sta/StaMain.hh" #include "ta/FlexTA.h" #include "triton_route/TritonRoute.h" using namespace std; using namespace fr; using namespace triton_route; namespace sta { // Tcl files encoded into strings. extern const char* TritonRoute_tcl_inits[]; } // namespace sta extern "C" { extern int Tritonroute_Init(Tcl_Interp* interp); } TritonRoute::TritonRoute() : debug_(std::make_unique<frDebugSettings>()), num_drvs_(-1), gui_(gui::Gui::get()) { } TritonRoute::~TritonRoute() { } void TritonRoute::setDebugDR(bool on) { debug_->debugDR = on; } void TritonRoute::setDebugMaze(bool on) { debug_->debugMaze = on; } void TritonRoute::setDebugPA(bool on) { debug_->debugPA = on; } void TritonRoute::setDebugNetName(const char* name) { debug_->netName = name; } void TritonRoute::setDebugPinName(const char* name) { debug_->pinName = name; } void TritonRoute::setDebugGCell(int x, int y) { debug_->gcellX = x; debug_->gcellY = y; } void TritonRoute::setDebugIter(int iter) { debug_->iter = iter; } void TritonRoute::setDebugPaMarkers(bool on) { debug_->paMarkers = on; } int TritonRoute::getNumDRVs() const { if (num_drvs_ < 0) { logger_->error(DRT, 2, "Detailed routing has not been run yet."); } return num_drvs_; } void TritonRoute::init(Tcl_Interp* tcl_interp, odb::dbDatabase* db, Logger* logger) { db_ = db; logger_ = logger; design_ = std::make_unique<frDesign>(logger_); // Define swig TCL commands. Tritonroute_Init(tcl_interp); sta::evalTclInit(tcl_interp, sta::TritonRoute_tcl_inits); } void TritonRoute::init() { if (DBPROCESSNODE == "GF14_13M_3Mx_2Cx_4Kx_2Hx_2Gx_LB") { VIAINPIN_BOTTOMLAYERNUM = 2; VIAINPIN_TOPLAYERNUM = 2; USENONPREFTRACKS = false; BOTTOM_ROUTING_LAYER = 4; TOP_ROUTING_LAYER = 18; ENABLE_VIA_GEN = false; } io::Parser parser(getDesign(), logger_); parser.readDb(db_); auto tech = getDesign()->getTech(); if (!BOTTOM_ROUTING_LAYER_NAME.empty()) { frLayer* layer = tech->getLayer(BOTTOM_ROUTING_LAYER_NAME); if (layer) { BOTTOM_ROUTING_LAYER = layer->getLayerNum(); } else { logger_->warn(utl::DRT, 251, "bottomRoutingLayer {} not found", BOTTOM_ROUTING_LAYER_NAME); } } if (!TOP_ROUTING_LAYER_NAME.empty()) { frLayer* layer = tech->getLayer(TOP_ROUTING_LAYER_NAME); if (layer) { TOP_ROUTING_LAYER = layer->getLayerNum(); } else { logger_->warn(utl::DRT, 252, "bottomRoutingLayer {} not found", TOP_ROUTING_LAYER_NAME); } } if (GUIDE_FILE != string("")) { parser.readGuide(); } else { ENABLE_VIA_GEN = false; } parser.postProcess(); FlexPA pa(getDesign(), logger_); pa.setDebug(debug_.get(), db_); pa.main(); if (GUIDE_FILE != string("")) { parser.postProcessGuide(); } // GR-related parser.initRPin(); logger_->info(utl::DRT, -1, "BRANCH NDR_testing\n"); } void TritonRoute::prep() { FlexRP rp(getDesign(), getDesign()->getTech(), logger_); rp.main(); } void TritonRoute::gr() { FlexGR gr(getDesign(), logger_); gr.main(db_); } void TritonRoute::ta() { FlexTA ta(getDesign(), logger_); ta.main(); } void TritonRoute::dr() { num_drvs_ = -1; FlexDR dr(getDesign(), logger_, db_); dr.setDebug(debug_.get()); dr.main(); } void TritonRoute::endFR() { io::Writer writer(getDesign(), logger_); writer.updateDb(db_); } void TritonRoute::reportConstraints() { getDesign()->getTech()->printAllConstraints(logger_); } int TritonRoute::main() { init(); if (GUIDE_FILE == string("")) { gr(); io::Parser parser(getDesign(), logger_); GUIDE_FILE = OUTGUIDE_FILE; ENABLE_VIA_GEN = true; parser.readGuide(); parser.initDefaultVias(); parser.postProcessGuide(); } prep(); ta(); dr(); endFR(); num_drvs_ = design_->getTopBlock()->getNumMarkers(); return 0; } void TritonRoute::readParams(const string& fileName) { int readParamCnt = 0; ifstream fin(fileName.c_str()); string line; if (fin.is_open()) { while (fin.good()) { getline(fin, line); if (line[0] != '#') { char delimiter = ':'; int pos = line.find(delimiter); string field = line.substr(0, pos); string value = line.substr(pos + 1); stringstream ss(value); if (field == "lef") { logger_->warn(utl::DRT, 148, "deprecated lef param in params file"); } else if (field == "def") { logger_->warn(utl::DRT, 227, "deprecated def param in params file"); } else if (field == "guide") { GUIDE_FILE = value; ++readParamCnt; } else if (field == "outputTA") { logger_->warn( utl::DRT, 171, "deprecated outputTA param in params file"); } else if (field == "output") { logger_->warn( utl::DRT, 205, "deprecated output param in params file"); } else if (field == "outputguide") { OUTGUIDE_FILE = value; ++readParamCnt; } else if (field == "outputMaze") { OUT_MAZE_FILE = value; ++readParamCnt; } else if (field == "outputDRC") { DRC_RPT_FILE = value; ++readParamCnt; } else if (field == "outputCMap") { CMAP_FILE = value; ++readParamCnt; } else if (field == "threads") { MAX_THREADS = atoi(value.c_str()); ++readParamCnt; } else if (field == "verbose") VERBOSE = atoi(value.c_str()); else if (field == "dbProcessNode") { DBPROCESSNODE = value; ++readParamCnt; } else if (field == "drouteViaInPinBottomLayerNum") { VIAINPIN_BOTTOMLAYERNUM = atoi(value.c_str()); ++readParamCnt; } else if (field == "drouteViaInPinTopLayerNum") { VIAINPIN_TOPLAYERNUM = atoi(value.c_str()); ++readParamCnt; } else if (field == "drouteEndIterNum") { END_ITERATION = atoi(value.c_str()); ++readParamCnt; } else if (field == "OR_SEED") { OR_SEED = atoi(value.c_str()); ++readParamCnt; } else if (field == "OR_K") { OR_K = atof(value.c_str()); ++readParamCnt; } else if (field == "bottomRoutingLayer") { BOTTOM_ROUTING_LAYER_NAME = value; ++readParamCnt; } else if (field == "topRoutingLayer") { TOP_ROUTING_LAYER_NAME = value; ++readParamCnt; } else if (field == "initRouteShapeCost") { ROUTESHAPECOST = atoi(value.c_str()); ++readParamCnt; } } } fin.close(); } if (readParamCnt < 2) { logger_->error(DRT, 1, "Error reading param file: {}", fileName); } } bool fr::isPad(MacroClassEnum e) { return e == MacroClassEnum::PAD || e == MacroClassEnum::PAD_INPUT || e == MacroClassEnum::PAD_OUTPUT || e == MacroClassEnum::PAD_INOUT || e == MacroClassEnum::PAD_POWER || e == MacroClassEnum::PAD_SPACER || e == MacroClassEnum::PAD_AREAIO; } bool fr::isEndcap(MacroClassEnum e) { return e == MacroClassEnum::ENDCAP || e == MacroClassEnum::ENDCAP_PRE || e == MacroClassEnum::ENDCAP_POST || e == MacroClassEnum::ENDCAP_TOPLEFT || e == MacroClassEnum::ENDCAP_TOPRIGHT || e == MacroClassEnum::ENDCAP_BOTTOMLEFT || e == MacroClassEnum::ENDCAP_BOTTOMRIGHT; } <|endoftext|>
<commit_before>#include <sch/S_Polyhedron/Polyhedron_algorithms.h> #include <sch/File_Parsing/SimplestParsing.h> #include <fstream> #include <stdexcept> #include <string> #include <algorithm> #include <set> //#define CD_POLYHEDRON_ALGORITHM_VERBOSE_MODE //VERBOSE mode (slows down the algorithm) default is commented using namespace sch; Polyhedron_algorithms::Polyhedron_algorithms(void) : fastVertexes_(0x0), lastVertexes_(0x0), numberOfVertices_(0) { } Polyhedron_algorithms::Polyhedron_algorithms(const Polyhedron_algorithms &p) :triangles_(p.triangles_) ,fastVertexes_(0x0) ,lastVertexes_(0x0) { for (unsigned i=0; i<p.vertexes_.size(); ++i) { vertexes_.push_back(p.vertexes_[i]->clone()); } updateVertexNeighbors(); updateFastArrays(); } Polyhedron_algorithms::~Polyhedron_algorithms(void) { if (fastVertexes_!=NULL) { delete[] fastVertexes_; } for (unsigned int i=0; i<vertexes_.size(); ++i) { delete vertexes_[i]; } } const Polyhedron_algorithms& Polyhedron_algorithms::operator =(const Polyhedron_algorithms &p) { if (this==&p) { return *this; } else { clear(); triangles_=p.triangles_; for (unsigned i=0; i<p.vertexes_.size(); ++i) { vertexes_.push_back(p.vertexes_[i]->clone()); } updateVertexNeighbors(); updateFastArrays(); return *this; } } size_t Polyhedron_algorithms::getEdgeKey(PolyhedronEdge e) { return ((e.a<e.b)?(e.a*vertexes_.size()+e.b):(e.b*vertexes_.size()+e.a)); } void Polyhedron_algorithms::fillEdges() { edges_.clear(); PolyhedronEdge edge; std::vector<PolyhedronEdge> triangleEdges; std::set<size_t, std::greater<int>> edgesSet; for(size_t i = 0; i < triangles_.size(); i++) { edge.a = triangles_[i].a; edge.b = triangles_[i].b; edge.computeEdge(vertexes_); triangleEdges.push_back(edge); edge.a = triangles_[i].b; edge.b = triangles_[i].c; edge.computeEdge(vertexes_); triangleEdges.push_back(edge); edge.a = triangles_[i].c; edge.b = triangles_[i].a; edge.computeEdge(vertexes_); triangleEdges.push_back(edge); for(auto j = triangleEdges.begin(); j != triangleEdges.end(); j++) { if(!edgesSet.count(getEdgeKey(*j))) { edges_.push_back(*j); edgesSet.insert(getEdgeKey(*j)); } } triangleEdges.clear(); } } void Polyhedron_algorithms::openFromFile(const std::string &filename) { clear(); std::ifstream is(filename.c_str()); if(!is.is_open()) { std::stringstream errmsg; errmsg << "EXCEPTION: Unable to open File " << filename << std::endl; throw std::invalid_argument(errmsg.str()); } std::string line; // Discard first line std::getline(is, line); size_t nr_vertexes; size_t nr_faces; is>>nr_vertexes; //get the number of points vertexes_.reserve(nr_vertexes); is>>nr_faces; triangles_.reserve(nr_faces); // Discard the last number std::getline(is, line); for (size_t g=0; g<nr_vertexes; g++) { Scalar y[3]; is >> y[0] >> y[1] >> y[2];//get the coords S_PolyhedronVertex *v; v=new S_PolyhedronVertex(); v->setCoordinates(y[0],y[1],y[2]); v->setNumber(unsigned (vertexes_.size())); vertexes_.push_back(v); } //get the normals const size_t normalSearchLen = 13; const char normalSearch[normalSearchLen + 1] = " - normal:"; const size_t verticesSearchLen = 15; const char verticesSearch[verticesSearchLen + 1] = " - vertices:"; PolyhedronEdge edge; Vector3 p1, p2; while(std::getline(is, line).good()) { if(line.substr(0, normalSearchLen) == normalSearch) { std::stringstream ss; ss << line.substr(normalSearchLen); Scalar y[3]; PolyhedronTriangle t; ss>>y[0]; ss>>y[1]; ss>>y[2]; t.normal.Set(y[0],y[1],y[2]); t.normal.normalize(); while(std::getline(is, line).good()) { if(line.substr(0, verticesSearchLen) == verticesSearch) { std::stringstream ss; ss << line.substr(verticesSearchLen); char c = '\0'; while(c!='p' && ss.good()) { ss.get(c); } ss >> t.a; c = '\0'; while(c!='p' && ss.good()) { ss.get(c); } ss >> t.b; c = '\0'; while(c!='p' && ss.good()) { ss.get(c); } ss >> t.c; //updatingNeighbors vertexes_[t.a]->addNeighbor(vertexes_[t.b]); vertexes_[t.a]->addNeighbor(vertexes_[t.c]); vertexes_[t.b]->addNeighbor(vertexes_[t.a]); vertexes_[t.b]->addNeighbor(vertexes_[t.c]); vertexes_[t.c]->addNeighbor(vertexes_[t.a]); vertexes_[t.c]->addNeighbor(vertexes_[t.b]); triangles_.push_back(t); break; } } } } for (unsigned int i=0; i<vertexes_.size(); i++) { vertexes_[i]->updateFastArrays(); } deleteVertexesWithoutNeighbors(); fillEdges(); } void Polyhedron_algorithms::updateVertexNeighbors() { for (unsigned i=0; i<triangles_.size(); ++i) { //updatingNeighbors vertexes_[triangles_[i].a]->addNeighbor(vertexes_[triangles_[i].b]); vertexes_[triangles_[i].a]->addNeighbor(vertexes_[triangles_[i].c]); vertexes_[triangles_[i].b]->addNeighbor(vertexes_[triangles_[i].a]); vertexes_[triangles_[i].b]->addNeighbor(vertexes_[triangles_[i].c]); vertexes_[triangles_[i].c]->addNeighbor(vertexes_[triangles_[i].a]); vertexes_[triangles_[i].c]->addNeighbor(vertexes_[triangles_[i].b]); } for (unsigned i=0; i<vertexes_.size(); ++i) { vertexes_[i]->updateFastArrays(); } } void Polyhedron_algorithms::clear() { for (unsigned int i=0; i<vertexes_.size(); ++i) { delete vertexes_[i]; } vertexes_.clear(); triangles_.clear(); edges_.clear(); updateFastArrays(); } void Polyhedron_algorithms::clearNeighbors() { for (unsigned i=0; i<vertexes_.size(); ++i) { vertexes_[i]->clearNeighbors(); vertexes_[i]->updateFastArrays(); } } void Polyhedron_algorithms::updateFastArrays() { if (fastVertexes_!=NULL) { delete[] fastVertexes_; } numberOfVertices_ = unsigned(vertexes_.size()); if (numberOfVertices_ > 0) { fastVertexes_ = new S_PolyhedronVertex *[numberOfVertices_]; for (unsigned int i = 0; i < numberOfVertices_; ++i) { fastVertexes_[i]=vertexes_[i]; } lastVertexes_ = &(fastVertexes_[numberOfVertices_]); } else { fastVertexes_=lastVertexes_=NULL; } } Point3 Polyhedron_algorithms::naiveSupport(const Vector3&v)const { S_PolyhedronVertex** current; current=fastVertexes_; Scalar supportH=(*current)->supportH(v); Vector3 best=(*current)->getCoordinates(); current++; for (unsigned i = 1; i < numberOfVertices_; i++, current++) { if ((*current)->supportH(v) > supportH) { supportH = (*current)->supportH(v); best = (*current)->getCoordinates(); } } return best; } Point3 Polyhedron_algorithms::support(const Vector3&v,int &lastFeature)const { S_PolyhedronVertex* current; Scalar supportH; if (numberOfVertices_==0) { std::stringstream errmsg; errmsg << "The polyhedron is empty, impossible to compute support function " << std::endl; throw std::length_error(errmsg.str()); } if (lastFeature==-1) { current=*fastVertexes_; } else { current=fastVertexes_[lastFeature]; } bool b=current->isHere(v); unsigned iterations = 0; while (!b) { supportH= current->getNextVertexH(); current = current->getNextVertex(); b=current->isHere(v,supportH); ++iterations; /// if the number of iterations is bigger than the number of vertices it means that we entered an infinite loop ///the best is te return the support computed using the naive version if (iterations>numberOfVertices_) { #ifdef CD_POLYHEDRON_ALGORITHM_VERBOSE_MODE std::cout << "Problem Support Polyhedron, Naive method triggered" << std::endl; #endif return naiveSupport(v); } } lastFeature=current->getNumber(); return current->getCoordinates(); } void Polyhedron_algorithms::deleteVertexesWithoutNeighbors() { int *cache=new int[vertexes_.size()]; std::vector<S_PolyhedronVertex*> v; int index=0; for (unsigned i=0; i<vertexes_.size(); ++i) { if (vertexes_[i]->getNumNeighbors()>0) { v.push_back(vertexes_[i]); vertexes_[i]->setNumber(index); cache[i]=index++; } else { delete vertexes_[i]; cache[i]=-1; } } for (unsigned i=0; i<triangles_.size(); ++i) { triangles_[i].a=cache[triangles_[i].a]; triangles_[i].b=cache[triangles_[i].b]; triangles_[i].c=cache[triangles_[i].c]; } vertexes_=v; updateFastArrays(); delete[] cache; } <commit_msg>Remove unused variables<commit_after>#include <sch/S_Polyhedron/Polyhedron_algorithms.h> #include <sch/File_Parsing/SimplestParsing.h> #include <fstream> #include <stdexcept> #include <string> #include <algorithm> #include <set> //#define CD_POLYHEDRON_ALGORITHM_VERBOSE_MODE //VERBOSE mode (slows down the algorithm) default is commented using namespace sch; Polyhedron_algorithms::Polyhedron_algorithms(void) : fastVertexes_(0x0), lastVertexes_(0x0), numberOfVertices_(0) { } Polyhedron_algorithms::Polyhedron_algorithms(const Polyhedron_algorithms &p) :triangles_(p.triangles_) ,fastVertexes_(0x0) ,lastVertexes_(0x0) { for (unsigned i=0; i<p.vertexes_.size(); ++i) { vertexes_.push_back(p.vertexes_[i]->clone()); } updateVertexNeighbors(); updateFastArrays(); } Polyhedron_algorithms::~Polyhedron_algorithms(void) { if (fastVertexes_!=NULL) { delete[] fastVertexes_; } for (unsigned int i=0; i<vertexes_.size(); ++i) { delete vertexes_[i]; } } const Polyhedron_algorithms& Polyhedron_algorithms::operator =(const Polyhedron_algorithms &p) { if (this==&p) { return *this; } else { clear(); triangles_=p.triangles_; for (unsigned i=0; i<p.vertexes_.size(); ++i) { vertexes_.push_back(p.vertexes_[i]->clone()); } updateVertexNeighbors(); updateFastArrays(); return *this; } } size_t Polyhedron_algorithms::getEdgeKey(PolyhedronEdge e) { return ((e.a<e.b)?(e.a*vertexes_.size()+e.b):(e.b*vertexes_.size()+e.a)); } void Polyhedron_algorithms::fillEdges() { edges_.clear(); PolyhedronEdge edge; std::vector<PolyhedronEdge> triangleEdges; std::set<size_t, std::greater<int>> edgesSet; for(size_t i = 0; i < triangles_.size(); i++) { edge.a = triangles_[i].a; edge.b = triangles_[i].b; edge.computeEdge(vertexes_); triangleEdges.push_back(edge); edge.a = triangles_[i].b; edge.b = triangles_[i].c; edge.computeEdge(vertexes_); triangleEdges.push_back(edge); edge.a = triangles_[i].c; edge.b = triangles_[i].a; edge.computeEdge(vertexes_); triangleEdges.push_back(edge); for(auto j = triangleEdges.begin(); j != triangleEdges.end(); j++) { if(!edgesSet.count(getEdgeKey(*j))) { edges_.push_back(*j); edgesSet.insert(getEdgeKey(*j)); } } triangleEdges.clear(); } } void Polyhedron_algorithms::openFromFile(const std::string &filename) { clear(); std::ifstream is(filename.c_str()); if(!is.is_open()) { std::stringstream errmsg; errmsg << "EXCEPTION: Unable to open File " << filename << std::endl; throw std::invalid_argument(errmsg.str()); } std::string line; // Discard first line std::getline(is, line); size_t nr_vertexes; size_t nr_faces; is>>nr_vertexes; //get the number of points vertexes_.reserve(nr_vertexes); is>>nr_faces; triangles_.reserve(nr_faces); // Discard the last number std::getline(is, line); for (size_t g=0; g<nr_vertexes; g++) { Scalar y[3]; is >> y[0] >> y[1] >> y[2];//get the coords S_PolyhedronVertex *v; v=new S_PolyhedronVertex(); v->setCoordinates(y[0],y[1],y[2]); v->setNumber(unsigned (vertexes_.size())); vertexes_.push_back(v); } //get the normals const size_t normalSearchLen = 13; const char normalSearch[normalSearchLen + 1] = " - normal:"; const size_t verticesSearchLen = 15; const char verticesSearch[verticesSearchLen + 1] = " - vertices:"; PolyhedronEdge edge; while(std::getline(is, line).good()) { if(line.substr(0, normalSearchLen) == normalSearch) { std::stringstream ss; ss << line.substr(normalSearchLen); Scalar y[3]; PolyhedronTriangle t; ss>>y[0]; ss>>y[1]; ss>>y[2]; t.normal.Set(y[0],y[1],y[2]); t.normal.normalize(); while(std::getline(is, line).good()) { if(line.substr(0, verticesSearchLen) == verticesSearch) { std::stringstream ss; ss << line.substr(verticesSearchLen); char c = '\0'; while(c!='p' && ss.good()) { ss.get(c); } ss >> t.a; c = '\0'; while(c!='p' && ss.good()) { ss.get(c); } ss >> t.b; c = '\0'; while(c!='p' && ss.good()) { ss.get(c); } ss >> t.c; //updatingNeighbors vertexes_[t.a]->addNeighbor(vertexes_[t.b]); vertexes_[t.a]->addNeighbor(vertexes_[t.c]); vertexes_[t.b]->addNeighbor(vertexes_[t.a]); vertexes_[t.b]->addNeighbor(vertexes_[t.c]); vertexes_[t.c]->addNeighbor(vertexes_[t.a]); vertexes_[t.c]->addNeighbor(vertexes_[t.b]); triangles_.push_back(t); break; } } } } for (unsigned int i=0; i<vertexes_.size(); i++) { vertexes_[i]->updateFastArrays(); } deleteVertexesWithoutNeighbors(); fillEdges(); } void Polyhedron_algorithms::updateVertexNeighbors() { for (unsigned i=0; i<triangles_.size(); ++i) { //updatingNeighbors vertexes_[triangles_[i].a]->addNeighbor(vertexes_[triangles_[i].b]); vertexes_[triangles_[i].a]->addNeighbor(vertexes_[triangles_[i].c]); vertexes_[triangles_[i].b]->addNeighbor(vertexes_[triangles_[i].a]); vertexes_[triangles_[i].b]->addNeighbor(vertexes_[triangles_[i].c]); vertexes_[triangles_[i].c]->addNeighbor(vertexes_[triangles_[i].a]); vertexes_[triangles_[i].c]->addNeighbor(vertexes_[triangles_[i].b]); } for (unsigned i=0; i<vertexes_.size(); ++i) { vertexes_[i]->updateFastArrays(); } } void Polyhedron_algorithms::clear() { for (unsigned int i=0; i<vertexes_.size(); ++i) { delete vertexes_[i]; } vertexes_.clear(); triangles_.clear(); edges_.clear(); updateFastArrays(); } void Polyhedron_algorithms::clearNeighbors() { for (unsigned i=0; i<vertexes_.size(); ++i) { vertexes_[i]->clearNeighbors(); vertexes_[i]->updateFastArrays(); } } void Polyhedron_algorithms::updateFastArrays() { if (fastVertexes_!=NULL) { delete[] fastVertexes_; } numberOfVertices_ = unsigned(vertexes_.size()); if (numberOfVertices_ > 0) { fastVertexes_ = new S_PolyhedronVertex *[numberOfVertices_]; for (unsigned int i = 0; i < numberOfVertices_; ++i) { fastVertexes_[i]=vertexes_[i]; } lastVertexes_ = &(fastVertexes_[numberOfVertices_]); } else { fastVertexes_=lastVertexes_=NULL; } } Point3 Polyhedron_algorithms::naiveSupport(const Vector3&v)const { S_PolyhedronVertex** current; current=fastVertexes_; Scalar supportH=(*current)->supportH(v); Vector3 best=(*current)->getCoordinates(); current++; for (unsigned i = 1; i < numberOfVertices_; i++, current++) { if ((*current)->supportH(v) > supportH) { supportH = (*current)->supportH(v); best = (*current)->getCoordinates(); } } return best; } Point3 Polyhedron_algorithms::support(const Vector3&v,int &lastFeature)const { S_PolyhedronVertex* current; Scalar supportH; if (numberOfVertices_==0) { std::stringstream errmsg; errmsg << "The polyhedron is empty, impossible to compute support function " << std::endl; throw std::length_error(errmsg.str()); } if (lastFeature==-1) { current=*fastVertexes_; } else { current=fastVertexes_[lastFeature]; } bool b=current->isHere(v); unsigned iterations = 0; while (!b) { supportH= current->getNextVertexH(); current = current->getNextVertex(); b=current->isHere(v,supportH); ++iterations; /// if the number of iterations is bigger than the number of vertices it means that we entered an infinite loop ///the best is te return the support computed using the naive version if (iterations>numberOfVertices_) { #ifdef CD_POLYHEDRON_ALGORITHM_VERBOSE_MODE std::cout << "Problem Support Polyhedron, Naive method triggered" << std::endl; #endif return naiveSupport(v); } } lastFeature=current->getNumber(); return current->getCoordinates(); } void Polyhedron_algorithms::deleteVertexesWithoutNeighbors() { int *cache=new int[vertexes_.size()]; std::vector<S_PolyhedronVertex*> v; int index=0; for (unsigned i=0; i<vertexes_.size(); ++i) { if (vertexes_[i]->getNumNeighbors()>0) { v.push_back(vertexes_[i]); vertexes_[i]->setNumber(index); cache[i]=index++; } else { delete vertexes_[i]; cache[i]=-1; } } for (unsigned i=0; i<triangles_.size(); ++i) { triangles_[i].a=cache[triangles_[i].a]; triangles_[i].b=cache[triangles_[i].b]; triangles_[i].c=cache[triangles_[i].c]; } vertexes_=v; updateFastArrays(); delete[] cache; } <|endoftext|>
<commit_before>// bsls_assert.cpp -*-C++-*- #include <bsls_assert.h> #include <bsls_ident.h> BSLS_IDENT("$Id$ $CSID$") #include <bsls_asserttestexception.h> #include <bsls_pointercastutil.h> #include <bsls_types.h> #include <bsls_log.h> #include <bsls_logseverity.h> #include <exception> #include <cstdio> #include <cstdlib> #include <cstring> #ifdef BSLS_PLATFORM_OS_AIX #include <signal.h> #endif #ifdef BSLS_PLATFORM_OS_UNIX #include <unistd.h> // 'sleep' #endif #ifdef BSLS_PLATFORM_OS_WINDOWS #include <windows.h> // IsDebbugerPresent #include <crtdbg.h> // '_CrtSetReportMode', to suppress pop-ups typedef unsigned long DWORD; extern "C" { __declspec(dllimport) void __stdcall Sleep(DWORD dwMilliseconds); }; #endif #ifdef BSLS_ASSERT_NORETURN #error BSLS_ASSERT_NORETURN must be a macro scoped locally to this file #endif // Note that a portable syntax for 'noreturn' will be available once we have // access to conforming C++0x compilers. //# define BSLS_ASSERT_NORETURN [[noreturn]] #ifdef BSLS_PLATFORM_CMP_MSVC # define BSLS_ASSERT_NORETURN __declspec(noreturn) #else # define BSLS_ASSERT_NORETURN #endif static BloombergLP::bsls::AtomicOperations_Imp::AtomicTypes::Int g_failureReturnCount; namespace BloombergLP { #ifndef BDE_OMIT_INTERNAL_DEPRECATED // We want to print the error message to 'stderr', not 'stdout'. The old // documentation for 'printError' is: //.. // Print a formatted error message to standard output. (Most Bloomberg // processes will send standard output to a log file.) //.. // TBD: find out whether 'stderr' goes to 'act.log'. #endif // BDE_OMIT_INTERNAL_DEPRECATED static void printError(const char *text, const char *file, int line) // Print a formatted error message to 'stderr' using the specified // expression 'text', 'file' name, and 'line' number. If either // 'text' or 'file' is empty ("") or null (0), replace it with some // informative, "human-readable" text, before formatting. { if (!text) { text = "(* Unspecified Expression Text *)"; } else if (!*text) { text = "(* Empty Expression Text *)"; } if (!file) { file = "(* Unspecified File Name *)"; } else if (!*file) { file = "(* Empty File Name *)"; } bsls::Log::logFormattedMessage( bsls::LogSeverity::e_ERROR, file, line, "Assertion failed: %s", text); } namespace bsls { // ------------ // class Assert // ------------ // CLASS DATA bsls::AtomicOperations::AtomicTypes::Pointer Assert::s_handler = {(void *) &Assert::failAbort}; bsls::AtomicOperations::AtomicTypes::Int Assert::s_lockedFlag = {0}; // CLASS METHODS void Assert::setFailureHandlerRaw(Assert::Handler function) { bsls::AtomicOperations::setPtrRelease( &s_handler, PointerCastUtil::cast<void *>(function)); } void Assert::setFailureHandler(Assert::Handler function) { if (!bsls::AtomicOperations::getIntRelaxed(&s_lockedFlag)) { setFailureHandlerRaw(function); } } void Assert::lockAssertAdministration() { bsls::AtomicOperations::setIntRelaxed(&s_lockedFlag, 1); } Assert::Handler Assert::failureHandler() { return (Handler) bsls::AtomicOperations::getPtrAcquire(&s_handler); } // Macro Dispatcher Method BSLS_ASSERT_NORETURN_INVOKE_HANDLER void Assert::invokeHandler(const char *text, const char *file, int line) { Assert::Handler currentHandlerAddress = failureHandler(); currentHandlerAddress(text, file, line); // The failure handler should not return. If a returning failure handler // has been installed, alert the user that the program is continuing to // run. unsigned count = static_cast<unsigned>( AtomicOperations::incrementIntNvAcqRel(&g_failureReturnCount)); if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(0 == (count & (count - 1)))) { BSLS_PERFORMANCEHINT_UNLIKELY_HINT; // Log when 'count' is a power of 2. if (count == (1 << 30)) { // Avoid undefined behavior by resetting the counter. AtomicOperations::setInt(&g_failureReturnCount, 1 << 29); } Log::logFormattedMessage(LogSeverity::e_FATAL, file, line, "BSLS_ASSERT failure: '%s'", text); BSLS_LOG_FATAL("Bad 'bsls_assert' configuration: " "violation handler at %p failed to prevent program " "from continuing.", currentHandlerAddress); } #ifdef BSLS_ASSERT_ENABLE_NORETURN_FOR_INVOKE_HANDLER std::abort(); #endif } // Standard Assertion-Failure Handlers BSLS_ASSERT_NORETURN void Assert::failAbort(const char *text, const char *file, int line) { printError(text, file, line); #ifndef BDE_OMIT_INTERNAL_DEPRECATED // See DRQS 8923441: The following is a work-around for a Fortran compiler bug. #endif // BDE_OMIT_INTERNAL_DEPRECATED #ifdef BSLS_PLATFORM_OS_AIX sigset_t newset; sigemptyset(&newset); sigaddset(&newset, SIGABRT); #if defined(BDE_BUILD_TARGET_MT) pthread_sigmask(SIG_UNBLOCK, &newset, 0); #else sigprocmask(SIG_UNBLOCK, &newset, 0); #endif #endif #ifndef BDE_OMIT_INTERNAL_DEPRECATED // See DRQS 13882128: Note that (according to Oleg) the first line alone may be // sufficient. #endif // BDE_OMIT_INTERNAL_DEPRECATED #ifdef BSLS_PLATFORM_OS_WINDOWS // The following configures the runtime library on how to report asserts, // errors, and warnings in order to avoid pop-up windows when 'abort' is // called. if (!IsDebuggerPresent()) { _CrtSetReportMode(_CRT_ASSERT, 0); _CrtSetReportMode(_CRT_ERROR, 0); _CrtSetReportMode(_CRT_WARN, 0); } #endif std::abort(); } BSLS_ASSERT_NORETURN void Assert::failSleep(const char *text, const char *file, int line) { printError(text, file, line); volatile int sleepDuration = 1; while (1 == sleepDuration) { #if defined(BSLS_PLATFORM_OS_UNIX) sleep(sleepDuration); #elif defined(BSLS_PLATFORM_OS_WINDOWS) Sleep(sleepDuration * 1000); // milliseconds #else #error "Do not know how to sleep on this platform." #endif } // We will never reach this line, but it is needed to let the compiler know // that this function does not return. std::abort(); } BSLS_ASSERT_NORETURN void Assert::failThrow(const char *text, const char *file, int line) { #ifdef BDE_BUILD_TARGET_EXC if (!std::uncaught_exception()) { throw AssertTestException(text, file, line); } else { bsls::Log::logMessage(bsls::LogSeverity::e_ERROR, file, line, "BSLS_ASSERT: An uncaught exception is pending;" " cannot throw 'AssertTestException'."); } #endif failAbort(text, file, line); } } // close package namespace #undef BSLS_ASSERT_NORETURN namespace bsls { // ------------------------------- // class AssertFailureHandlerGuard // ------------------------------- AssertFailureHandlerGuard::AssertFailureHandlerGuard(Assert::Handler temporary) : d_original(Assert::failureHandler()) { Assert::setFailureHandlerRaw(temporary); } AssertFailureHandlerGuard::~AssertFailureHandlerGuard() { Assert::setFailureHandlerRaw(d_original); } } // close package namespace } // close enterprise namespace // ---------------------------------------------------------------------------- // Copyright 2013 Bloomberg Finance L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ----------------------------- END-OF-FILE ---------------------------------- <commit_msg>Move handler return counter into 'invokeHandler'.<commit_after>// bsls_assert.cpp -*-C++-*- #include <bsls_assert.h> #include <bsls_ident.h> BSLS_IDENT("$Id$ $CSID$") #include <bsls_asserttestexception.h> #include <bsls_pointercastutil.h> #include <bsls_types.h> #include <bsls_log.h> #include <bsls_logseverity.h> #include <exception> #include <cstdio> #include <cstdlib> #include <cstring> #ifdef BSLS_PLATFORM_OS_AIX #include <signal.h> #endif #ifdef BSLS_PLATFORM_OS_UNIX #include <unistd.h> // 'sleep' #endif #ifdef BSLS_PLATFORM_OS_WINDOWS #include <windows.h> // IsDebbugerPresent #include <crtdbg.h> // '_CrtSetReportMode', to suppress pop-ups typedef unsigned long DWORD; extern "C" { __declspec(dllimport) void __stdcall Sleep(DWORD dwMilliseconds); }; #endif #ifdef BSLS_ASSERT_NORETURN #error BSLS_ASSERT_NORETURN must be a macro scoped locally to this file #endif // Note that a portable syntax for 'noreturn' will be available once we have // access to conforming C++0x compilers. //# define BSLS_ASSERT_NORETURN [[noreturn]] #ifdef BSLS_PLATFORM_CMP_MSVC # define BSLS_ASSERT_NORETURN __declspec(noreturn) #else # define BSLS_ASSERT_NORETURN #endif namespace BloombergLP { #ifndef BDE_OMIT_INTERNAL_DEPRECATED // We want to print the error message to 'stderr', not 'stdout'. The old // documentation for 'printError' is: //.. // Print a formatted error message to standard output. (Most Bloomberg // processes will send standard output to a log file.) //.. // TBD: find out whether 'stderr' goes to 'act.log'. #endif // BDE_OMIT_INTERNAL_DEPRECATED static void printError(const char *text, const char *file, int line) // Print a formatted error message to 'stderr' using the specified // expression 'text', 'file' name, and 'line' number. If either // 'text' or 'file' is empty ("") or null (0), replace it with some // informative, "human-readable" text, before formatting. { if (!text) { text = "(* Unspecified Expression Text *)"; } else if (!*text) { text = "(* Empty Expression Text *)"; } if (!file) { file = "(* Unspecified File Name *)"; } else if (!*file) { file = "(* Empty File Name *)"; } bsls::Log::logFormattedMessage( bsls::LogSeverity::e_ERROR, file, line, "Assertion failed: %s", text); } namespace bsls { // ------------ // class Assert // ------------ // CLASS DATA bsls::AtomicOperations::AtomicTypes::Pointer Assert::s_handler = {(void *) &Assert::failAbort}; bsls::AtomicOperations::AtomicTypes::Int Assert::s_lockedFlag = {0}; // CLASS METHODS void Assert::setFailureHandlerRaw(Assert::Handler function) { bsls::AtomicOperations::setPtrRelease( &s_handler, PointerCastUtil::cast<void *>(function)); } void Assert::setFailureHandler(Assert::Handler function) { if (!bsls::AtomicOperations::getIntRelaxed(&s_lockedFlag)) { setFailureHandlerRaw(function); } } void Assert::lockAssertAdministration() { bsls::AtomicOperations::setIntRelaxed(&s_lockedFlag, 1); } Assert::Handler Assert::failureHandler() { return (Handler) bsls::AtomicOperations::getPtrAcquire(&s_handler); } // Macro Dispatcher Method BSLS_ASSERT_NORETURN_INVOKE_HANDLER void Assert::invokeHandler(const char *text, const char *file, int line) { static AtomicOperations::AtomicTypes::Int failureReturnCount = {0}; Assert::Handler currentHandlerAddress = failureHandler(); currentHandlerAddress(text, file, line); // The failure handler should not return. If a returning failure handler // has been installed, alert the user that the program is continuing to // run. unsigned count = static_cast<unsigned>( AtomicOperations::incrementIntNvAcqRel(&failureReturnCount)); if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(0 == (count & (count - 1)))) { BSLS_PERFORMANCEHINT_UNLIKELY_HINT; // Log when 'count' is a power of 2. if (count == (1 << 30)) { // Avoid undefined behavior by resetting the counter. AtomicOperations::setInt(&failureReturnCount, 1 << 29); } Log::logFormattedMessage(LogSeverity::e_FATAL, file, line, "BSLS_ASSERT failure: '%s'", text); BSLS_LOG_FATAL("Bad 'bsls_assert' configuration: " "violation handler at %p failed to prevent program " "from continuing.", currentHandlerAddress); } #ifdef BSLS_ASSERT_ENABLE_NORETURN_FOR_INVOKE_HANDLER std::abort(); #endif } // Standard Assertion-Failure Handlers BSLS_ASSERT_NORETURN void Assert::failAbort(const char *text, const char *file, int line) { printError(text, file, line); #ifndef BDE_OMIT_INTERNAL_DEPRECATED // See DRQS 8923441: The following is a work-around for a Fortran compiler bug. #endif // BDE_OMIT_INTERNAL_DEPRECATED #ifdef BSLS_PLATFORM_OS_AIX sigset_t newset; sigemptyset(&newset); sigaddset(&newset, SIGABRT); #if defined(BDE_BUILD_TARGET_MT) pthread_sigmask(SIG_UNBLOCK, &newset, 0); #else sigprocmask(SIG_UNBLOCK, &newset, 0); #endif #endif #ifndef BDE_OMIT_INTERNAL_DEPRECATED // See DRQS 13882128: Note that (according to Oleg) the first line alone may be // sufficient. #endif // BDE_OMIT_INTERNAL_DEPRECATED #ifdef BSLS_PLATFORM_OS_WINDOWS // The following configures the runtime library on how to report asserts, // errors, and warnings in order to avoid pop-up windows when 'abort' is // called. if (!IsDebuggerPresent()) { _CrtSetReportMode(_CRT_ASSERT, 0); _CrtSetReportMode(_CRT_ERROR, 0); _CrtSetReportMode(_CRT_WARN, 0); } #endif std::abort(); } BSLS_ASSERT_NORETURN void Assert::failSleep(const char *text, const char *file, int line) { printError(text, file, line); volatile int sleepDuration = 1; while (1 == sleepDuration) { #if defined(BSLS_PLATFORM_OS_UNIX) sleep(sleepDuration); #elif defined(BSLS_PLATFORM_OS_WINDOWS) Sleep(sleepDuration * 1000); // milliseconds #else #error "Do not know how to sleep on this platform." #endif } // We will never reach this line, but it is needed to let the compiler know // that this function does not return. std::abort(); } BSLS_ASSERT_NORETURN void Assert::failThrow(const char *text, const char *file, int line) { #ifdef BDE_BUILD_TARGET_EXC if (!std::uncaught_exception()) { throw AssertTestException(text, file, line); } else { bsls::Log::logMessage(bsls::LogSeverity::e_ERROR, file, line, "BSLS_ASSERT: An uncaught exception is pending;" " cannot throw 'AssertTestException'."); } #endif failAbort(text, file, line); } } // close package namespace #undef BSLS_ASSERT_NORETURN namespace bsls { // ------------------------------- // class AssertFailureHandlerGuard // ------------------------------- AssertFailureHandlerGuard::AssertFailureHandlerGuard(Assert::Handler temporary) : d_original(Assert::failureHandler()) { Assert::setFailureHandlerRaw(temporary); } AssertFailureHandlerGuard::~AssertFailureHandlerGuard() { Assert::setFailureHandlerRaw(d_original); } } // close package namespace } // close enterprise namespace // ---------------------------------------------------------------------------- // Copyright 2013 Bloomberg Finance L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ----------------------------- END-OF-FILE ---------------------------------- <|endoftext|>
<commit_before>/* +---------------------------------------------------------------------------+ | The Mobile Robot Programming Toolkit (MRPT) C++ library | | | | http://www.mrpt.org/ | | | | Copyright (C) 2005-2012 University of Malaga | | | | This software was written by the Machine Perception and Intelligent | | Robotics Lab, University of Malaga (Spain). | | Contact: Jose-Luis Blanco <jlblanco@ctima.uma.es> | | | | This file is part of the MRPT project. | | | | MRPT 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. | | | | MRPT 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 MRPT. If not, see <http://www.gnu.org/licenses/>. | | | +---------------------------------------------------------------------------+ */ #include <mrpt/vision.h> #include <gtest/gtest.h> #include "chessboard_stereo_camera_calib_internal.h" using namespace mrpt; using namespace mrpt::poses; using namespace mrpt::utils; using namespace mrpt::math; using namespace mrpt::vision; using namespace std; class StereoCalibTests : public ::testing::Test { protected: virtual void SetUp() { } virtual void TearDown() { } void testStereoCalibJacobians( double x,double y, double z, double yaw, double pitch, double roll ) { const CPose3D camPose = CPose3D(x2,y2,z2,yaw2,pitch2,roll2); // Prepare a test state: // -------------------------------------- TCalibrationStereoImageList images; vector<size_t> valid_image_pair_indices; vector<TPoint3D> obj_points; obj_points.push_back(TPoint3D(-0.4,0.3,0)); valid_image_pair_indices.push_back(0); lm_stat_t lm_stat(images, valid_image_pair_indices, obj_points); lm_stat.left_cam_poses.push_back( CPose3D(0,0,1) ); // [fx fy cx cy k1 k2 k3 t1 t2] const double cam_l_params[9] = {600, 400, 320,240, 0,0,0,0,0 }; const double cam_r_params[9] = {500, 300, 250,200, 0,0,0,0,0 }; lm_stat.left_cam_params = CArrayDouble<9>(cam_l_params); lm_stat.right_cam_params = CArrayDouble<9>(cam_r_params); // Evaluate theoretical Jacobians: TResidualJacobianList jacobs; // Theoretical output Jacobians mrpt::vision::recompute_errors_and_Jacobians( lm_stat, jacobs ); // Compare: //EXPECT_NEAR( } }; TEST_F(StereoCalibTests,Jacobians) { testStereoCalibJacobians(0,0,0,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0)); } <commit_msg>removed unimplemented unit test<commit_after><|endoftext|>
<commit_before>#define INSANITY_BUILDING_LIBRARY #include "CWindowsWin32Window.hpp" #if defined(PLATFORM_MSWINDOWS) #include <IThread.hpp> #include <IGarbageCollector.hpp> #include <IApplication.hpp> #include <IString.hpp> #include <TRectangle.hpp> #include <IConfigObject.hpp> #include <windowsx.h> #include <CommCtrl.h> #include <iostream> namespace Insanity { IWindow * IWindow::Create(IWindow * ext, IConfigObject const * cfg) { return new CWindowsWin32Window(ext, cfg); } bool CWindowsWin32Window::s_windowClassRegistered = false; CWindowsWin32EventPumpTask * CWindowsWin32Window::s_pumpTask = nullptr; u64 CWindowsWin32Window::s_winCount = 0; u64 CWindowsWin32Window::GetWindowCount() { return s_winCount; } CWindowsWin32Window::CWindowsWin32Window(IWindow * ext, IConfigObject const * cfg) : _ext(ext), _rect(nullptr) { HMODULE hInst = GetModuleHandle(nullptr); _InitWindowClass(hInst); _InitEventPump(); _InitWindow(hInst, cfg->GetProperty("title", "")); s_winCount++; } CWindowsWin32Window::~CWindowsWin32Window() { if(--s_winCount == 0) { s_pumpTask->Release(); //The windows don't need it anymore. //the pump task will not be deleted until it's dequeued from the thread task list. } //A comment on SetWindowSubclass says to remove the subclass before destroying the window. RemoveWindowSubclass(_win,WindowProc,0); DestroyWindow(_win); _rect->Release(); } void CWindowsWin32Window::_InitWindowClass(HINSTANCE hInst) { if (!s_windowClassRegistered) { WNDCLASSEXW wcex; ZeroMemory(&wcex, sizeof(wcex)); wcex.cbClsExtra = 0; //Won't be able to access wcex.cbSize = sizeof(wcex); //Constant wcex.cbWndExtra = 0; //Won't be able to access wcex.hbrBackground = (HBRUSH) (COLOR_WINDOW);//More or less constant. wcex.hCursor = (HCURSOR) LoadImage(hInst, IDC_ARROW, IMAGE_CURSOR, 0, 0, LR_SHARED); //Can be assigned later wcex.hIcon = (HICON) LoadImage(hInst, IDI_APPLICATION, IMAGE_ICON, 0, 0, LR_SHARED); //Can be assigned later wcex.hIconSm = (HICON) LoadImage(hInst, IDI_APPLICATION, IMAGE_ICON, 0, 0, LR_SHARED); //Can be assigned later wcex.hInstance = hInst; //Constant wcex.lpfnWndProc = InitialWindowProc; //Will assign WindowProc after window creation wcex.lpszClassName = L"InsanityWindowClass";//Constant wcex.lpszMenuName = nullptr; //Can be assigned if/when a Menu is added. wcex.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS; //First two needed, third needed for uniformity with other platforms. RegisterClassExW(&wcex); s_windowClassRegistered = true; } } void CWindowsWin32Window::_InitWindow(HINSTANCE hInst, IConfigObject const * cfg) { //_rect stores the dimensions of the client area of the window. _rect = new TRectangle<s16, u16>(static_cast<s16>(cfg->GetProperty("dims.x", (s64)0)), static_cast<s16>(cfg->GetProperty("dims.y", (s64)0)), static_cast<u16>(cfg->GetProperty("dims.width", (s64)640)), static_cast<u16>(cfg->GetProperty("dims.height", (s64)480))); _rect->Retain(); //Need to adjust for non-client area of window for CreateWindow. RECT adj; adj.left = _rect->GetLeft(); adj.top = _rect->GetTop(); adj.right = _rect->GetRight(); adj.bottom = _rect->GetBottom(); AdjustWindowRectEx(&adj, WS_OVERLAPPEDWINDOW, FALSE, WS_EX_OVERLAPPEDWINDOW); //convert the title to a wchar_t string. Let the garbage collector take care of it. IString<wchar_t> * wtitle = IString<wchar_t>::Create(cfg->GetProperty("title", "")); _win = CreateWindowExW(WS_EX_OVERLAPPEDWINDOW, //will either want this or options for fullscreen L"InsanityWindowClass", //Constant wtitle->Array(), //Good candidate for Config file WS_OVERLAPPEDWINDOW, //as dwExStyle adj.left, adj.top, adj.right - adj.left, adj.bottom - adj.top, //Dimensions are another good candidate HWND_DESKTOP, //If in Config file, would need a way to specify another window NULL, //Menu can be assigned later hInst, //Constant nullptr); //Constant (unused) SetWindowSubclass(_win, WindowProc, 0, reinterpret_cast<DWORD_PTR>(this)); ShowWindow(_win, SW_SHOWDEFAULT); } void CWindowsWin32Window::_InitEventPump() { if (s_pumpTask == nullptr) { //creates a pump task, assigns it to the static pointer, and passes it to RegisterTask. IApplication::GetInstance()->RegisterTask(s_pumpTask = new CWindowsWin32EventPumpTask()); } //Other platforms have to register an event procedure with the event pump task. // Since that's basically an emulation of Windows' event setup, we use the native setup here. } LRESULT CALLBACK CWindowsWin32Window::InitialWindowProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) { //this will receive at least WM_NCCREATE, WM_NCCALCSIZE, and WM_CREATE before assigning WindowProc subclass. return DefWindowProcW(wnd,msg,wParam,lParam); } LRESULT CALLBACK CWindowsWin32Window::WindowProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam, UINT_PTR uSubclassId, DWORD_PTR dwRefData) { //this is the main method for processing window messages. CWindowsWin32Window * self = reinterpret_cast<CWindowsWin32Window*>(dwRefData); self->Retain(); IWindow * call = (self->_ext ? self->_ext : self); POINTS pt = MAKEPOINTS(lParam); WORD highWParam = HIWORD(wParam); switch(msg) { case WM_LBUTTONDOWN: call->MouseHandler(EMouseButton::Left, EMouseButtonState::Down, pt.x, pt.y); break; case WM_LBUTTONUP: call->MouseHandler(EMouseButton::Left, EMouseButtonState::Up, pt.x, pt.y); break; case WM_LBUTTONDBLCLK: call->MouseHandler(EMouseButton::Left, EMouseButtonState::DoubleClick, pt.x, pt.y); break; case WM_RBUTTONDOWN: call->MouseHandler(EMouseButton::Right, EMouseButtonState::Down, pt.x, pt.y); break; case WM_RBUTTONUP: call->MouseHandler(EMouseButton::Right, EMouseButtonState::Up, pt.x, pt.y); break; case WM_RBUTTONDBLCLK: call->MouseHandler(EMouseButton::Right, EMouseButtonState::DoubleClick, pt.x, pt.y); break; case WM_MBUTTONDOWN: call->MouseHandler(EMouseButton::Middle, EMouseButtonState::Down, pt.x, pt.y); break; case WM_MBUTTONUP: call->MouseHandler(EMouseButton::Middle, EMouseButtonState::Up, pt.x, pt.y); break; case WM_MBUTTONDBLCLK: call->MouseHandler(EMouseButton::Middle, EMouseButtonState::DoubleClick, pt.x, pt.y); break; case WM_XBUTTONDOWN: call->MouseHandler((highWParam == 1 ? EMouseButton::X1 : EMouseButton::X2), EMouseButtonState::Down, pt.x, pt.y); break; case WM_XBUTTONUP: call->MouseHandler((highWParam == 1 ? EMouseButton::X1 : EMouseButton::X2), EMouseButtonState::Up, pt.x, pt.y); break; case WM_XBUTTONDBLCLK: call->MouseHandler((highWParam == 1 ? EMouseButton::X1 : EMouseButton::X2), EMouseButtonState::DoubleClick, pt.x, pt.y); break; case WM_KEYUP: call->KeyHandler((EKey) wParam, EKeyState::Up); break; case WM_KEYDOWN: call->KeyHandler((EKey) wParam, EKeyState::Down); break; case WM_CLOSE: std::cout << "Close message received." << std::endl; call->CloseHandler(); break; case WM_SHOWWINDOW: call->ShowHandler(wParam == TRUE); break; case WM_DESTROY: //should only be sent when the window object is destroyed. //should do any code on window destruction in the dtor, not here or a handler. break; case WM_MOVE: //coordinates reported are the upper-left corner of the client area in screen coordinates. call->MoveHandler(pt.x, pt.y); break; case WM_SIZE: call->ResizeHandler(pt.x, pt.y); break; case WM_MOUSEMOVE: call->MouseHandler(EMouseButton::Null, EMouseButtonState::Null, pt.x, pt.y); break; case WM_MOUSEWHEEL: { //need the sign from highWParam SHORT delta = (SHORT)highWParam; //the second parameter to ScrollHandler is a simple magnitude (unsigned), so take the absolute value. call->ScrollHandler((delta > 0 ? EMouseScrollDirection::Up : EMouseScrollDirection::Down), abs(delta / WHEEL_DELTA)); } break; } self->Release(); return DefSubclassProc(wnd,msg,wParam,lParam); } HWND CWindowsWin32Window::GetWindow() const { return _win; } //===================================================== //Interface: IWindow //===================================================== TRectangle<s16,u16> const * CWindowsWin32Window::GetRect() const { return _rect; } void CWindowsWin32Window::MouseHandler(EMouseButton button, EMouseButtonState state, u16 x, u16 y) { } void CWindowsWin32Window::KeyHandler(EKey key, EKeyState state) { } void CWindowsWin32Window::ScrollHandler(EMouseScrollDirection dir, u16 delta) { } void CWindowsWin32Window::ShowHandler(bool show) { } void CWindowsWin32Window::MoveHandler(s16 x, s16 y) { _rect->SetX(x); _rect->SetY(y); } void CWindowsWin32Window::ResizeHandler(u16 width, u16 height) { _rect->SetWidth(width); _rect->SetHeight(height); } void CWindowsWin32Window::CloseHandler() { } void CWindowsWin32Window::Mouse(EMouseButton button, EMouseButtonState state, u16 x, u16 y) { UINT msg = 0; WORD xButton = 0; switch (button) { case EMouseButton::Left: msg = WM_LBUTTONDOWN; break; case EMouseButton::Middle: msg = WM_MBUTTONDOWN; break; case EMouseButton::Right: msg = WM_RBUTTONDOWN; break; case EMouseButton::X1: xButton = 1; msg = WM_XBUTTONDOWN; break; case EMouseButton::X2: xButton = 2; msg = WM_XBUTTONDOWN; break; case EMouseButton::Null: msg = WM_MOUSEMOVE; break; } if (button != EMouseButton::Null) //ignore the state; should be Null, but don't count on it. { switch (state) { case EMouseButtonState::Down: //no-op, Down is already set. break; case EMouseButtonState::Up: msg += 1; break; case EMouseButtonState::DoubleClick: msg += 2; break; } } DWORD tmpX = x; DWORD tmpY = y; LPARAM lParam = (tmpY << 16) | tmpX; PostMessage(_win, msg, xButton << 16, lParam); } void CWindowsWin32Window::Key(EKey key, EKeyState state) { //LPARAM is a bunch of state flags we have no way of tracking, so ignore it. PostMessage(_win, (state == EKeyState::Down ? WM_KEYDOWN : WM_KEYUP), (WPARAM)key, 0); } void CWindowsWin32Window::Scroll(EMouseScrollDirection dir, u16 delta) { //mask off the sign bit (shouldn't cause problems) SHORT postDelta = delta & 0x7fff; postDelta *= (dir == EMouseScrollDirection::Up ? 1 : -1); //Last parameter should be the current mouse position, but that's not provided nor tracked internally. PostMessage(_win, WM_MOUSEWHEEL, (static_cast<DWORD>(postDelta)) << 16, 0); } void CWindowsWin32Window::Show(bool show) { ShowWindow(_win, (show ? SW_SHOWNORMAL : SW_HIDE)); } void CWindowsWin32Window::Move(s16 x, s16 y) { MoveWindow(_win,x,y,0,0,TRUE); } void CWindowsWin32Window::Resize(u16 width, u16 height) { MoveWindow(_win,0,0,width,height,TRUE); } void CWindowsWin32Window::Close() { PostMessage(_win, WM_CLOSE, 0, 0); } } #endif <commit_msg>Pass the correct object to _InitWindow.<commit_after>#define INSANITY_BUILDING_LIBRARY #include "CWindowsWin32Window.hpp" #if defined(PLATFORM_MSWINDOWS) #include <IThread.hpp> #include <IGarbageCollector.hpp> #include <IApplication.hpp> #include <IString.hpp> #include <TRectangle.hpp> #include <IConfigObject.hpp> #include <windowsx.h> #include <CommCtrl.h> #include <iostream> namespace Insanity { IWindow * IWindow::Create(IWindow * ext, IConfigObject const * cfg) { return new CWindowsWin32Window(ext, cfg); } bool CWindowsWin32Window::s_windowClassRegistered = false; CWindowsWin32EventPumpTask * CWindowsWin32Window::s_pumpTask = nullptr; u64 CWindowsWin32Window::s_winCount = 0; u64 CWindowsWin32Window::GetWindowCount() { return s_winCount; } CWindowsWin32Window::CWindowsWin32Window(IWindow * ext, IConfigObject const * cfg) : _ext(ext), _rect(nullptr) { HMODULE hInst = GetModuleHandle(nullptr); _InitWindowClass(hInst); _InitEventPump(); _InitWindow(hInst, cfg); s_winCount++; } CWindowsWin32Window::~CWindowsWin32Window() { if(--s_winCount == 0) { s_pumpTask->Release(); //The windows don't need it anymore. //the pump task will not be deleted until it's dequeued from the thread task list. } //A comment on SetWindowSubclass says to remove the subclass before destroying the window. RemoveWindowSubclass(_win,WindowProc,0); DestroyWindow(_win); _rect->Release(); } void CWindowsWin32Window::_InitWindowClass(HINSTANCE hInst) { if (!s_windowClassRegistered) { WNDCLASSEXW wcex; ZeroMemory(&wcex, sizeof(wcex)); wcex.cbClsExtra = 0; //Won't be able to access wcex.cbSize = sizeof(wcex); //Constant wcex.cbWndExtra = 0; //Won't be able to access wcex.hbrBackground = (HBRUSH) (COLOR_WINDOW);//More or less constant. wcex.hCursor = (HCURSOR) LoadImage(hInst, IDC_ARROW, IMAGE_CURSOR, 0, 0, LR_SHARED); //Can be assigned later wcex.hIcon = (HICON) LoadImage(hInst, IDI_APPLICATION, IMAGE_ICON, 0, 0, LR_SHARED); //Can be assigned later wcex.hIconSm = (HICON) LoadImage(hInst, IDI_APPLICATION, IMAGE_ICON, 0, 0, LR_SHARED); //Can be assigned later wcex.hInstance = hInst; //Constant wcex.lpfnWndProc = InitialWindowProc; //Will assign WindowProc after window creation wcex.lpszClassName = L"InsanityWindowClass";//Constant wcex.lpszMenuName = nullptr; //Can be assigned if/when a Menu is added. wcex.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS; //First two needed, third needed for uniformity with other platforms. RegisterClassExW(&wcex); s_windowClassRegistered = true; } } void CWindowsWin32Window::_InitWindow(HINSTANCE hInst, IConfigObject const * cfg) { //_rect stores the dimensions of the client area of the window. _rect = new TRectangle<s16, u16>(static_cast<s16>(cfg->GetProperty("dims.x", (s64)0)), static_cast<s16>(cfg->GetProperty("dims.y", (s64)0)), static_cast<u16>(cfg->GetProperty("dims.width", (s64)640)), static_cast<u16>(cfg->GetProperty("dims.height", (s64)480))); _rect->Retain(); //Need to adjust for non-client area of window for CreateWindow. RECT adj; adj.left = _rect->GetLeft(); adj.top = _rect->GetTop(); adj.right = _rect->GetRight(); adj.bottom = _rect->GetBottom(); AdjustWindowRectEx(&adj, WS_OVERLAPPEDWINDOW, FALSE, WS_EX_OVERLAPPEDWINDOW); //convert the title to a wchar_t string. Let the garbage collector take care of it. IString<wchar_t> * wtitle = IString<wchar_t>::Create(cfg->GetProperty("title", "")); _win = CreateWindowExW(WS_EX_OVERLAPPEDWINDOW, //will either want this or options for fullscreen L"InsanityWindowClass", //Constant wtitle->Array(), //Good candidate for Config file WS_OVERLAPPEDWINDOW, //as dwExStyle adj.left, adj.top, adj.right - adj.left, adj.bottom - adj.top, //Dimensions are another good candidate HWND_DESKTOP, //If in Config file, would need a way to specify another window NULL, //Menu can be assigned later hInst, //Constant nullptr); //Constant (unused) SetWindowSubclass(_win, WindowProc, 0, reinterpret_cast<DWORD_PTR>(this)); ShowWindow(_win, SW_SHOWDEFAULT); } void CWindowsWin32Window::_InitEventPump() { if (s_pumpTask == nullptr) { //creates a pump task, assigns it to the static pointer, and passes it to RegisterTask. IApplication::GetInstance()->RegisterTask(s_pumpTask = new CWindowsWin32EventPumpTask()); } //Other platforms have to register an event procedure with the event pump task. // Since that's basically an emulation of Windows' event setup, we use the native setup here. } LRESULT CALLBACK CWindowsWin32Window::InitialWindowProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) { //this will receive at least WM_NCCREATE, WM_NCCALCSIZE, and WM_CREATE before assigning WindowProc subclass. return DefWindowProcW(wnd,msg,wParam,lParam); } LRESULT CALLBACK CWindowsWin32Window::WindowProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam, UINT_PTR uSubclassId, DWORD_PTR dwRefData) { //this is the main method for processing window messages. CWindowsWin32Window * self = reinterpret_cast<CWindowsWin32Window*>(dwRefData); self->Retain(); IWindow * call = (self->_ext ? self->_ext : self); POINTS pt = MAKEPOINTS(lParam); WORD highWParam = HIWORD(wParam); switch(msg) { case WM_LBUTTONDOWN: call->MouseHandler(EMouseButton::Left, EMouseButtonState::Down, pt.x, pt.y); break; case WM_LBUTTONUP: call->MouseHandler(EMouseButton::Left, EMouseButtonState::Up, pt.x, pt.y); break; case WM_LBUTTONDBLCLK: call->MouseHandler(EMouseButton::Left, EMouseButtonState::DoubleClick, pt.x, pt.y); break; case WM_RBUTTONDOWN: call->MouseHandler(EMouseButton::Right, EMouseButtonState::Down, pt.x, pt.y); break; case WM_RBUTTONUP: call->MouseHandler(EMouseButton::Right, EMouseButtonState::Up, pt.x, pt.y); break; case WM_RBUTTONDBLCLK: call->MouseHandler(EMouseButton::Right, EMouseButtonState::DoubleClick, pt.x, pt.y); break; case WM_MBUTTONDOWN: call->MouseHandler(EMouseButton::Middle, EMouseButtonState::Down, pt.x, pt.y); break; case WM_MBUTTONUP: call->MouseHandler(EMouseButton::Middle, EMouseButtonState::Up, pt.x, pt.y); break; case WM_MBUTTONDBLCLK: call->MouseHandler(EMouseButton::Middle, EMouseButtonState::DoubleClick, pt.x, pt.y); break; case WM_XBUTTONDOWN: call->MouseHandler((highWParam == 1 ? EMouseButton::X1 : EMouseButton::X2), EMouseButtonState::Down, pt.x, pt.y); break; case WM_XBUTTONUP: call->MouseHandler((highWParam == 1 ? EMouseButton::X1 : EMouseButton::X2), EMouseButtonState::Up, pt.x, pt.y); break; case WM_XBUTTONDBLCLK: call->MouseHandler((highWParam == 1 ? EMouseButton::X1 : EMouseButton::X2), EMouseButtonState::DoubleClick, pt.x, pt.y); break; case WM_KEYUP: call->KeyHandler((EKey) wParam, EKeyState::Up); break; case WM_KEYDOWN: call->KeyHandler((EKey) wParam, EKeyState::Down); break; case WM_CLOSE: std::cout << "Close message received." << std::endl; call->CloseHandler(); break; case WM_SHOWWINDOW: call->ShowHandler(wParam == TRUE); break; case WM_DESTROY: //should only be sent when the window object is destroyed. //should do any code on window destruction in the dtor, not here or a handler. break; case WM_MOVE: //coordinates reported are the upper-left corner of the client area in screen coordinates. call->MoveHandler(pt.x, pt.y); break; case WM_SIZE: call->ResizeHandler(pt.x, pt.y); break; case WM_MOUSEMOVE: call->MouseHandler(EMouseButton::Null, EMouseButtonState::Null, pt.x, pt.y); break; case WM_MOUSEWHEEL: { //need the sign from highWParam SHORT delta = (SHORT)highWParam; //the second parameter to ScrollHandler is a simple magnitude (unsigned), so take the absolute value. call->ScrollHandler((delta > 0 ? EMouseScrollDirection::Up : EMouseScrollDirection::Down), abs(delta / WHEEL_DELTA)); } break; } self->Release(); return DefSubclassProc(wnd,msg,wParam,lParam); } HWND CWindowsWin32Window::GetWindow() const { return _win; } //===================================================== //Interface: IWindow //===================================================== TRectangle<s16,u16> const * CWindowsWin32Window::GetRect() const { return _rect; } void CWindowsWin32Window::MouseHandler(EMouseButton button, EMouseButtonState state, u16 x, u16 y) { } void CWindowsWin32Window::KeyHandler(EKey key, EKeyState state) { } void CWindowsWin32Window::ScrollHandler(EMouseScrollDirection dir, u16 delta) { } void CWindowsWin32Window::ShowHandler(bool show) { } void CWindowsWin32Window::MoveHandler(s16 x, s16 y) { _rect->SetX(x); _rect->SetY(y); } void CWindowsWin32Window::ResizeHandler(u16 width, u16 height) { _rect->SetWidth(width); _rect->SetHeight(height); } void CWindowsWin32Window::CloseHandler() { } void CWindowsWin32Window::Mouse(EMouseButton button, EMouseButtonState state, u16 x, u16 y) { UINT msg = 0; WORD xButton = 0; switch (button) { case EMouseButton::Left: msg = WM_LBUTTONDOWN; break; case EMouseButton::Middle: msg = WM_MBUTTONDOWN; break; case EMouseButton::Right: msg = WM_RBUTTONDOWN; break; case EMouseButton::X1: xButton = 1; msg = WM_XBUTTONDOWN; break; case EMouseButton::X2: xButton = 2; msg = WM_XBUTTONDOWN; break; case EMouseButton::Null: msg = WM_MOUSEMOVE; break; } if (button != EMouseButton::Null) //ignore the state; should be Null, but don't count on it. { switch (state) { case EMouseButtonState::Down: //no-op, Down is already set. break; case EMouseButtonState::Up: msg += 1; break; case EMouseButtonState::DoubleClick: msg += 2; break; } } DWORD tmpX = x; DWORD tmpY = y; LPARAM lParam = (tmpY << 16) | tmpX; PostMessage(_win, msg, xButton << 16, lParam); } void CWindowsWin32Window::Key(EKey key, EKeyState state) { //LPARAM is a bunch of state flags we have no way of tracking, so ignore it. PostMessage(_win, (state == EKeyState::Down ? WM_KEYDOWN : WM_KEYUP), (WPARAM)key, 0); } void CWindowsWin32Window::Scroll(EMouseScrollDirection dir, u16 delta) { //mask off the sign bit (shouldn't cause problems) SHORT postDelta = delta & 0x7fff; postDelta *= (dir == EMouseScrollDirection::Up ? 1 : -1); //Last parameter should be the current mouse position, but that's not provided nor tracked internally. PostMessage(_win, WM_MOUSEWHEEL, (static_cast<DWORD>(postDelta)) << 16, 0); } void CWindowsWin32Window::Show(bool show) { ShowWindow(_win, (show ? SW_SHOWNORMAL : SW_HIDE)); } void CWindowsWin32Window::Move(s16 x, s16 y) { MoveWindow(_win,x,y,0,0,TRUE); } void CWindowsWin32Window::Resize(u16 width, u16 height) { MoveWindow(_win,0,0,width,height,TRUE); } void CWindowsWin32Window::Close() { PostMessage(_win, WM_CLOSE, 0, 0); } } #endif <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: chips/p9/procedures/hwp/memory/p9_mss_draminit_mc.C $ */ /* */ /* IBM CONFIDENTIAL */ /* */ /* EKB Project */ /* */ /* COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* The source code for this program is not published or otherwise */ /* divested of its trade secrets, irrespective of what has been */ /* deposited with the U.S. Copyright Office. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_draminit_mc.C /// @brief Initialize the memory controller to take over the DRAM /// // *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com> // *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <mss.H> #include "p9_mss_draminit_mc.H" using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_MCA; using fapi2::TARGET_TYPE_MCS; extern "C" { /// /// @brief Initialize the MC now that DRAM is up /// @param[in] i_target, the McBIST of the ports /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_draminit_mc( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { auto l_mca = i_target.getChildren<TARGET_TYPE_MCA>(); FAPI_INF("Start draminit MC"); // If we don't have any ports, lets go. if (l_mca.size() == 0) { FAPI_INF("No ports? %s", mss::c_str(i_target)); return fapi2::FAPI2_RC_SUCCESS; } // While we're doing the scominit in here, lets do it for all ports before we dump the MCS regs. for (auto p : i_target.getChildren<TARGET_TYPE_MCA>()) { mss::mc<TARGET_TYPE_MCS> l_mc; // Don't do this yet - leverage the sim inits for the moment #if 0 // All the scominit for this MCA l_mc.scominit(p); #endif // Setup the MC port/dimm address translation registers FAPI_TRY( l_mc.setup_xlate_map(p) ); } for (auto p : l_mca) { // Set the IML Complete bit MBSSQ(3) (SCOM Addr: 0x02011417) to indicate that IML has completed // Can't find MBSSQ or the iml_complete bit - asked Steve. Gary VH created this bit as a scratch // 'you are hre bit' and it was removed for Nimbus. Gary VH asked for it to be put back in. Not // sure if that happened yet. BRS (2/16). // Reset addr_mux_sel to “0” to allow the MCA to take control of the DDR interface over from CCS. // (Note: this step must remain in this procedure to ensure that data path is placed into mainline // mode prior to running memory diagnostics. When Advanced DRAM Training executes, this step // becomes superfluous but not harmful. However, it's not guaranteed that Advanced DRAM Training // will be executed on every system configuration.) // Note: addr_mux_sel is set low in p9_mss_draminit(), however that might be a work-around so we // set it low here kind of like belt-and-suspenders. BRS FAPI_TRY( mss::change_addr_mux_sel(p, mss::LOW) ); // Step Two.1: Check RCD protect time on RDIMM and LRDIMM // Step Two.2: Enable address inversion on each MBA for ALL CARDS // Start the refresh engines by setting MBAREF0Q(0) = “1”. Note that the remaining bits in // MBAREF0Q should retain their initialization values. FAPI_TRY( mss::change_refresh_enable(p, mss::HIGH) ); // Power management is handled in the init file. (or should be BRS) // Enabling periodic calibration FAPI_TRY( mss::enable_periodic_cal(p) ); // Step Six: Setup Control Bit ECC FAPI_TRY( mss::enable_read_ecc(p) ); // At this point the DDR interface must be monitored for memory errors. Memory related FIRs should be unmasked. // Cram a fast write, followed by a read in here for giggles { mss::mcbist::program<TARGET_TYPE_MCBIST> l_program; uint64_t l_start = 0; uint64_t l_end = 0; uint64_t l_pattern = 0; // Write { // Uses address register set 0 mss::mcbist::subtest_t<TARGET_TYPE_MCBIST> l_fw_subtest = mss::mcbist::write_subtest<TARGET_TYPE_MCBIST>(); l_fw_subtest.enable_port(mss::index(p)); // HACK: We only need to worry about the DIMM in slot 0 right now l_fw_subtest.enable_dimm(0); l_program.iv_subtests.push_back(l_fw_subtest); } // Read { // Uses address register set 0 mss::mcbist::subtest_t<TARGET_TYPE_MCBIST> l_fr_subtest = mss::mcbist::read_subtest<TARGET_TYPE_MCBIST>(); l_fr_subtest.enable_port(mss::index(p)); // HACK: We only need to worry about the DIMM in slot 0 right now l_fr_subtest.enable_dimm(0); l_program.iv_subtests.push_back(l_fr_subtest); } FAPI_TRY( mss::mcbist_start_addr(p, l_start) ); FAPI_TRY( mss::mcbist_end_addr(p, l_end) ); // TK: calculate proper polling based on address range // Setup a nice pattern for writing FAPI_TRY( mss::mcbist_write_data(i_target, l_pattern) ); FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD0Q, l_pattern) ); FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD1Q, l_pattern) ); FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD2Q, l_pattern) ); FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD3Q, l_pattern) ); FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD4Q, l_pattern) ); FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD5Q, l_pattern) ); FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD6Q, l_pattern) ); FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD7Q, l_pattern) ); // Sanity check - can't do much if end is before start. // This is either a programming error or a mistake in attribute settings. So we'll just assert. if (l_end < l_start) { FAPI_ERR("mcbist end address is less than mcbist starting address. s: 0x%x e: 0x%x", l_start, l_end); fapi2::Assert(false); } // By default we're in maint address mode so we do a start + len and the 'BIST increments for us. // By default, the write subtest uses the 0'th address start/end registers. mss::mcbist::config_address_range0(i_target, l_start, l_end - l_start); // Just one port for now. Per Shelton we need to set this in maint adress mode // even tho we specify the port/dimm in the subtest. fapi2::buffer<uint8_t> l_port; l_port.setBit(mss::pos(p)); l_program.select_ports(l_port >> 4); // Kick it off, wait for a result FAPI_TRY( mss::mcbist::execute(i_target, l_program) ); // Just because the program executed and no MCBIST failure was reported, it is poosible that // there were address errors. An address error in the only address in a range causes the // 'BIST to skip that command. Since it's the only address, the subtest (or program) can // complete succedssfully even though nothing actually happend. // For now, just dump the registers and vgrep for errors. BRS FAPI_TRY( mss::dump_regs<TARGET_TYPE_MCBIST>(i_target) ); } } fapi_try_exit: FAPI_INF("End draminit MC"); return fapi2::current_err; } } <commit_msg>Add read pointer delay config<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: chips/p9/procedures/hwp/memory/p9_mss_draminit_mc.C $ */ /* */ /* IBM CONFIDENTIAL */ /* */ /* EKB Project */ /* */ /* COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* The source code for this program is not published or otherwise */ /* divested of its trade secrets, irrespective of what has been */ /* deposited with the U.S. Copyright Office. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_draminit_mc.C /// @brief Initialize the memory controller to take over the DRAM /// // *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com> // *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <mss.H> #include "p9_mss_draminit_mc.H" using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_MCA; using fapi2::TARGET_TYPE_MCS; extern "C" { /// /// @brief Initialize the MC now that DRAM is up /// @param[in] i_target, the McBIST of the ports /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_draminit_mc( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { auto l_mca = i_target.getChildren<TARGET_TYPE_MCA>(); FAPI_INF("Start draminit MC"); // If we don't have any ports, lets go. if (l_mca.size() == 0) { FAPI_INF("No ports? %s", mss::c_str(i_target)); return fapi2::FAPI2_RC_SUCCESS; } // While we're doing the scominit in here, lets do it for all ports before we dump the MCS regs. for (auto p : i_target.getChildren<TARGET_TYPE_MCA>()) { mss::mc<TARGET_TYPE_MCS> l_mc; // Don't do this yet - leverage the sim inits for the moment #if 0 // All the scominit for this MCA l_mc.scominit(p); #endif // Setup the MC port/dimm address translation registers FAPI_TRY( l_mc.setup_xlate_map(p) ); } // Setup the read_pointer_delay // TK: Do we need to do this in general or is this a place holder until the // init file gets here? { fapi2::buffer<uint64_t> l_data; FAPI_TRY( mss::getScom(i_target, MCBIST_MBSEC0Q, l_data) ); l_data.insertFromRight<MCA_RECR_MBSECCQ_READ_POINTER_DELAY, MCA_RECR_MBSECCQ_READ_POINTER_DELAY_LEN>(0x1); FAPI_DBG("writing read pointer delay 0x%016lx", l_data); FAPI_TRY( mss::putScom(i_target, MCBIST_MBSEC0Q, l_data) ); } for (auto p : l_mca) { // Set the IML Complete bit MBSSQ(3) (SCOM Addr: 0x02011417) to indicate that IML has completed // Can't find MBSSQ or the iml_complete bit - asked Steve. Gary VH created this bit as a scratch // 'you are hre bit' and it was removed for Nimbus. Gary VH asked for it to be put back in. Not // sure if that happened yet. BRS (2/16). // Reset addr_mux_sel to “0” to allow the MCA to take control of the DDR interface over from CCS. // (Note: this step must remain in this procedure to ensure that data path is placed into mainline // mode prior to running memory diagnostics. When Advanced DRAM Training executes, this step // becomes superfluous but not harmful. However, it's not guaranteed that Advanced DRAM Training // will be executed on every system configuration.) // Note: addr_mux_sel is set low in p9_mss_draminit(), however that might be a work-around so we // set it low here kind of like belt-and-suspenders. BRS FAPI_TRY( mss::change_addr_mux_sel(p, mss::LOW) ); // Step Two.1: Check RCD protect time on RDIMM and LRDIMM // Step Two.2: Enable address inversion on each MBA for ALL CARDS // Start the refresh engines by setting MBAREF0Q(0) = “1”. Note that the remaining bits in // MBAREF0Q should retain their initialization values. FAPI_TRY( mss::change_refresh_enable(p, mss::HIGH) ); // Power management is handled in the init file. (or should be BRS) // Enabling periodic calibration FAPI_TRY( mss::enable_periodic_cal(p) ); // Step Six: Setup Control Bit ECC FAPI_TRY( mss::enable_read_ecc(p) ); // At this point the DDR interface must be monitored for memory errors. Memory related FIRs should be unmasked. // Cram a fast write, followed by a read in here for giggles { mss::mcbist::program<TARGET_TYPE_MCBIST> l_program; uint64_t l_start = 0; uint64_t l_end = 0; uint64_t l_pattern = 0; // Write { // Uses address register set 0 mss::mcbist::subtest_t<TARGET_TYPE_MCBIST> l_fw_subtest = mss::mcbist::write_subtest<TARGET_TYPE_MCBIST>(); l_fw_subtest.enable_port(mss::index(p)); // HACK: We only need to worry about the DIMM in slot 0 right now l_fw_subtest.enable_dimm(0); l_program.iv_subtests.push_back(l_fw_subtest); } // Read { // Uses address register set 0 mss::mcbist::subtest_t<TARGET_TYPE_MCBIST> l_fr_subtest = mss::mcbist::read_subtest<TARGET_TYPE_MCBIST>(); l_fr_subtest.enable_port(mss::index(p)); // HACK: We only need to worry about the DIMM in slot 0 right now l_fr_subtest.enable_dimm(0); l_program.iv_subtests.push_back(l_fr_subtest); } FAPI_TRY( mss::mcbist_start_addr(p, l_start) ); FAPI_TRY( mss::mcbist_end_addr(p, l_end) ); // TK: calculate proper polling based on address range // Setup a nice pattern for writing FAPI_TRY( mss::mcbist_write_data(i_target, l_pattern) ); FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD0Q, l_pattern) ); FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD1Q, l_pattern) ); FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD2Q, l_pattern) ); FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD3Q, l_pattern) ); FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD4Q, l_pattern) ); FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD5Q, l_pattern) ); FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD6Q, l_pattern) ); FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD7Q, l_pattern) ); // Sanity check - can't do much if end is before start. // This is either a programming error or a mistake in attribute settings. So we'll just assert. if (l_end < l_start) { FAPI_ERR("mcbist end address is less than mcbist starting address. s: 0x%x e: 0x%x", l_start, l_end); fapi2::Assert(false); } // By default we're in maint address mode so we do a start + len and the 'BIST increments for us. // By default, the write subtest uses the 0'th address start/end registers. mss::mcbist::config_address_range0(i_target, l_start, l_end - l_start); // Just one port for now. Per Shelton we need to set this in maint adress mode // even tho we specify the port/dimm in the subtest. fapi2::buffer<uint8_t> l_port; l_port.setBit(mss::pos(p)); l_program.select_ports(l_port >> 4); // Kick it off, wait for a result FAPI_TRY( mss::mcbist::execute(i_target, l_program) ); // Just because the program executed and no MCBIST failure was reported, it is poosible that // there were address errors. An address error in the only address in a range causes the // 'BIST to skip that command. Since it's the only address, the subtest (or program) can // complete succedssfully even though nothing actually happend. // For now, just dump the registers and vgrep for errors. BRS FAPI_TRY( mss::dump_regs<TARGET_TYPE_MCBIST>(i_target) ); } } fapi_try_exit: FAPI_INF("End draminit MC"); return fapi2::current_err; } } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * * @author David N. Bertoni (david_n_bertoni@lotus.com) * */ // Base class header file. #include "ProblemListenerDefault.hpp" #include <XalanDOM/XalanNode.hpp> #include <PlatformSupport/DOMStringHelper.hpp> #include <PlatformSupport/PrintWriter.hpp> #include <XSLT/ElemTemplateElement.hpp> static const char* const errorHeader = "error: "; static const char* const warningHeader = "warning: "; static const char* const xslHeader = "XSLT "; static const char* const xmlHeader = "XML "; static const char* const xpathHeader = "XPath "; static const char* const styleTreeNodeHeader = ", style tree node: "; static const char* const sourceTreeNodeHeader = ", source tree node: "; static const char* const locationOpen = " ("; static const char* const uriHeader = ""; static const char* const lineNoHeader = ", line "; static const char* const charOffsetHeader = ", column "; static const char* const locationClose = ")"; ProblemListenerDefault::ProblemListenerDefault(PrintWriter* pw) : ProblemListener(), m_pw(pw) { } ProblemListenerDefault::~ProblemListenerDefault() { } void ProblemListenerDefault::setPrintWriter(PrintWriter* pw) { m_pw = pw; } void ProblemListenerDefault::problem( eProblemSource where, eClassification classification, const XalanNode* sourceNode, const XalanNode* styleNode, const XalanDOMString& msg, const XalanDOMChar* uri, int lineNo, int charOffset) { if (m_pw != 0) { problem(*m_pw, where, classification, sourceNode, styleNode, msg, uri, lineNo, charOffset); } } void ProblemListenerDefault::problem( PrintWriter& pw, eProblemSource where, eClassification classification, const XalanNode* sourceNode, const XalanNode* styleNode, const XalanDOMString& msg, const XalanDOMChar* uri, int lineNo, int charOffset) { if (eXMLPARSER == where) { pw.print(xmlHeader); } else if (eXPATH == where) { pw.print(xpathHeader); } else { pw.print(xslHeader); } if (eERROR == classification) { pw.print(errorHeader); } else { pw.print(warningHeader); } pw.print(msg); if (0 != styleNode) { pw.print(styleTreeNodeHeader); pw.print(styleNode->getNodeName()); } if (0 != sourceNode) { pw.print(sourceTreeNodeHeader); pw.print(sourceNode->getNodeName()); } pw.print(locationOpen); if (0 != uri) { pw.print(uriHeader); pw.print(uri); } pw.print(lineNoHeader); pw.print(lineNo); pw.print(charOffsetHeader); pw.print(charOffset); pw.print(locationClose); pw.println(); } <commit_msg>Added new header for message classification.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * * @author David N. Bertoni (david_n_bertoni@lotus.com) * */ // Base class header file. #include "ProblemListenerDefault.hpp" #include <XalanDOM/XalanNode.hpp> #include <PlatformSupport/DOMStringHelper.hpp> #include <PlatformSupport/PrintWriter.hpp> #include <XSLT/ElemTemplateElement.hpp> static const char* const errorHeader = "error: "; static const char* const warningHeader = "warning: "; static const char* const messageHeader = "message: "; static const char* const xslHeader = "XSLT "; static const char* const xmlHeader = "XML "; static const char* const xpathHeader = "XPath "; static const char* const styleTreeNodeHeader = ", style tree node: "; static const char* const sourceTreeNodeHeader = ", source tree node: "; static const char* const locationOpen = " ("; static const char* const uriHeader = ""; static const char* const lineNoHeader = ", line "; static const char* const charOffsetHeader = ", column "; static const char* const locationClose = ")"; ProblemListenerDefault::ProblemListenerDefault(PrintWriter* pw) : ProblemListener(), m_pw(pw) { } ProblemListenerDefault::~ProblemListenerDefault() { } void ProblemListenerDefault::setPrintWriter(PrintWriter* pw) { m_pw = pw; } void ProblemListenerDefault::problem( eProblemSource where, eClassification classification, const XalanNode* sourceNode, const XalanNode* styleNode, const XalanDOMString& msg, const XalanDOMChar* uri, int lineNo, int charOffset) { if (m_pw != 0) { problem(*m_pw, where, classification, sourceNode, styleNode, msg, uri, lineNo, charOffset); } } void ProblemListenerDefault::problem( PrintWriter& pw, eProblemSource where, eClassification classification, const XalanNode* sourceNode, const XalanNode* styleNode, const XalanDOMString& msg, const XalanDOMChar* uri, int lineNo, int charOffset) { if (eXMLPARSER == where) { pw.print(xmlHeader); } else if (eXPATH == where) { pw.print(xpathHeader); } else { pw.print(xslHeader); } if (eERROR == classification) { pw.print(errorHeader); } else if (eWARNING == classification) { pw.print(warningHeader); } else { pw.print(messageHeader); } pw.print(msg); if (0 != styleNode) { pw.print(styleTreeNodeHeader); pw.print(styleNode->getNodeName()); } if (0 != sourceNode) { pw.print(sourceTreeNodeHeader); pw.print(sourceNode->getNodeName()); } pw.print(locationOpen); if (0 != uri) { pw.print(uriHeader); pw.print(uri); } pw.print(lineNoHeader); pw.print(lineNo); pw.print(charOffsetHeader); pw.print(charOffset); pw.print(locationClose); pw.println(); } <|endoftext|>
<commit_before>/* * XMLLoadHandler.cpp * * Created on: 29.05.2017 * Author: Alexander */ #include "persistence/xml/XMLLoadHandler.hpp" #include <sstream> // used for getLevel() #include <boost/algorithm/string.hpp> // used for string splitting #include "boost/exception/to_string.hpp" #include "ecore/EObject.hpp" #include "ecore/EStructuralFeature.hpp" #include "xerces/XStr.hpp" #include "xerces/WStr.hpp" #include "xercesc/dom/DOMNamedNodeMap.hpp" namespace persistence { namespace xml { XMLLoadHandler::XMLLoadHandler () { m_doc = nullptr; m_currentElement = nullptr; } XMLLoadHandler::~XMLLoadHandler () { if ( m_doc ) { m_doc->release(); } } /**/ DOMDocument *XMLLoadHandler::getDOMDocument () { return m_doc; } void XMLLoadHandler::setDOMDocument ( DOMDocument * doc ) { assert( doc ); if ( doc == nullptr ) { MSG_ERROR( MSG_FLF << " Current DOMDocument 'doc' is empty." ); return; } m_doc = doc; m_rootObject = nullptr; m_currentElement = m_doc->getDocumentElement(); // get root element if ( !m_currentElement ) { MSG_ERROR( MSG_FLF << " Current DOMElement (root) does not exist." ); assert( m_currentElement ); } std::string rootTagName = W(m_currentElement->getTagName()); std::cout << "rootTagName: " << rootTagName << std::endl; unsigned int index = rootTagName.find(':'); if (index != std::string::npos) { m_rootPrefix = rootTagName.substr(0, index); m_rootName = rootTagName.substr(index+1, rootTagName.size()-index); std::string id = W(m_currentElement->getAttribute(X("xmi:id"))); std::cout << "root has xmi:id " << id << std::endl; m_isXSIMode = id.empty(); } else { MSG_ERROR(MSG_FLF << " root prefix could not be selected from root tag name '" << rootTagName << "'"); } if ( m_currentElement->getNodeType() == DOMNode::ELEMENT_NODE ) { m_currentElements.push_back( m_currentElement ); } else { MSG_ERROR( MSG_FLF << " Current DOMElement (root) is not a DOMNode::ELEMENT_NODE." ); } } unsigned int XMLLoadHandler::getNumOfChildNodes () { DOMNode *child; unsigned int count = 0; for ( child = m_currentElement->getLastChild(); child != 0; child = child->getPreviousSibling() ) { if ( child->getNodeType() == DOMNode::ELEMENT_NODE ) { ++count; } } if ( count != m_currentElement->getChildElementCount() ) { MSG_ERROR( MSG_FLF << "Different Number of Children" ); } return count; } std::string XMLLoadHandler::getNextNodeName () { std::string nodeName; DOMNode *child; if ( m_currentElements.size() == 0 ) { nodeName = ""; } else { m_currentElement = (DOMElement*) m_currentElements.back(); nodeName = W( m_currentElement->getNodeName() ); m_currentElements.pop_back(); for ( child = m_currentElement->getLastChild(); child != 0; child = child->getPreviousSibling() ) { if ( child->getNodeType() == DOMNode::ELEMENT_NODE ) { m_currentElements.push_back( child ); } } #if 0 std::cout << "| DEBUG | " << "Node-List: " << std::endl << "| | "; for ( auto current_elem : m_currentElements ) { std::cout << "<" << W( current_elem->getNodeName() ) << "> "; } std::cout << std::endl; #endif } //MSG_DEBUG("NodeName: " << nodeName); return nodeName; } std::map<std::string, std::string> XMLLoadHandler::getAttributeList () { std::map<std::string, std::string> attributeList; DOMAttr *pAttributeNode; std::string aName; std::string aValue; DOMNamedNodeMap *pAttributes = m_currentElement->getAttributes(); const XMLSize_t nSize = pAttributes->getLength(); //MSG_DEBUG("\t" << "Attributes:"); //MSG_DEBUG("\t" << "-----------"); for ( XMLSize_t i = 0; i < nSize; ++i ) { pAttributeNode = (DOMAttr*) pAttributes->item( i ); // get attribute name aName = W( pAttributeNode->getName() ); // get attribute type aValue = W( pAttributeNode->getValue() ); // Print Attribute Name and Value //MSG_DEBUG"\t" << aName << "=" << aValue); attributeList.insert( std::pair<std::string, std::string>( aName, aValue ) ); } return attributeList; } std::string XMLLoadHandler::getCurrentXSITypeName () { DOMAttr *pAttributeNode; std::string aName; DOMNamedNodeMap *pAttributes = m_currentElement->getAttributes(); const XMLSize_t nSize = pAttributes->getLength(); for ( XMLSize_t i = 0; i < nSize; ++i ) { pAttributeNode = (DOMAttr*) pAttributes->item( i ); // get attribute name aName = W( pAttributeNode->getName() ); if (aName == "xsi:type" or aName == "xmi:type") { std::string _type = W(pAttributeNode->getValue()); size_t const double_dot = _type.find(L':', 0); std::string _type_ns = _type.substr(0, double_dot); // TODO '_type_ns' is not used in this case std::string _type_name = _type.substr(double_dot + 1); return _type_name; } } return ""; } std::string XMLLoadHandler::getCurrentXMIID() { DOMAttr *pAttributeNode; std::string aName; DOMNamedNodeMap *pAttributes = m_currentElement->getAttributes(); const XMLSize_t nSize = pAttributes->getLength(); for ( XMLSize_t i = 0; i < nSize; ++i ) { pAttributeNode = (DOMAttr*) pAttributes->item( i ); // get attribute name aName = W( pAttributeNode->getName() ); if (aName == "xmi:id") { std::string id = W(pAttributeNode->getValue()); return id; } } return ""; } std::shared_ptr<ecore::EObject> XMLLoadHandler::checkNodeType(std::shared_ptr<ecore::EObject> object) { DOMNodeList* dom = m_currentElement->getChildNodes(); const XMLSize_t size = dom->getLength(); for (XMLSize_t i=0; i<size; i++) { DOMNode* node = dom->item(i); std::string nodeName = W(node->getNodeName()); if (nodeName == "type") { std::string type = ""; std::string href = ""; DOMNamedNodeMap* attrListNode = node->getAttributes(); const XMLSize_t sizeAttrList = attrListNode->getLength(); for (XMLSize_t i = 0; i < sizeAttrList; ++i) { DOMAttr* attributeNode = (DOMAttr*) attrListNode->item( i ); // get attribute name std::string aName = W( attributeNode->getName() ); if (aName == "xmi:type") { type = W(attributeNode->getValue()); } if (aName == "href") { href = W(attributeNode->getValue()); } } type = type + " " + href; auto iter = m_refToObject_map.find(type); if (iter != m_refToObject_map.end()) { return iter->second; } else { loadTypes(type); auto iter = m_refToObject_map.find(type); if (iter != m_refToObject_map.end()) { return iter->second; } } } } return nullptr; } std::shared_ptr<std::string> XMLLoadHandler::getChildText() { std::string value = W(m_currentElement->getTextContent()); std::shared_ptr<std::string> valuePtr(new std::string(value)); return valuePtr; } } /* namespace xml */ } /* namespace persistence */ <commit_msg>[persistence] modify namespace declaration<commit_after>/* * XMLLoadHandler.cpp * * Created on: 29.05.2017 * Author: Alexander */ #include "persistence/xml/XMLLoadHandler.hpp" #include <sstream> // used for getLevel() #include <boost/algorithm/string.hpp> // used for string splitting #include "boost/exception/to_string.hpp" #include "ecore/EObject.hpp" #include "ecore/EStructuralFeature.hpp" #include "xerces/XStr.hpp" #include "xerces/WStr.hpp" #include "xercesc/dom/DOMNamedNodeMap.hpp" using namespace persistence::xml; XMLLoadHandler::XMLLoadHandler () { m_doc = nullptr; m_currentElement = nullptr; } XMLLoadHandler::~XMLLoadHandler () { if ( m_doc ) { m_doc->release(); } } /**/ DOMDocument *XMLLoadHandler::getDOMDocument () { return m_doc; } void XMLLoadHandler::setDOMDocument ( DOMDocument * doc ) { assert( doc ); if ( doc == nullptr ) { MSG_ERROR( MSG_FLF << " Current DOMDocument 'doc' is empty." ); return; } m_doc = doc; m_rootObject = nullptr; m_currentElement = m_doc->getDocumentElement(); // get root element if ( !m_currentElement ) { MSG_ERROR( MSG_FLF << " Current DOMElement (root) does not exist." ); assert( m_currentElement ); } std::string rootTagName = W(m_currentElement->getTagName()); std::cout << "rootTagName: " << rootTagName << std::endl; unsigned int index = rootTagName.find(':'); if (index != std::string::npos) { m_rootPrefix = rootTagName.substr(0, index); m_rootName = rootTagName.substr(index+1, rootTagName.size()-index); std::string id = W(m_currentElement->getAttribute(X("xmi:id"))); std::cout << "root has xmi:id " << id << std::endl; m_isXSIMode = id.empty(); } else { MSG_ERROR(MSG_FLF << " root prefix could not be selected from root tag name '" << rootTagName << "'"); } if ( m_currentElement->getNodeType() == DOMNode::ELEMENT_NODE ) { m_currentElements.push_back( m_currentElement ); } else { MSG_ERROR( MSG_FLF << " Current DOMElement (root) is not a DOMNode::ELEMENT_NODE." ); } } unsigned int XMLLoadHandler::getNumOfChildNodes () { DOMNode *child; unsigned int count = 0; for ( child = m_currentElement->getLastChild(); child != 0; child = child->getPreviousSibling() ) { if ( child->getNodeType() == DOMNode::ELEMENT_NODE ) { ++count; } } if ( count != m_currentElement->getChildElementCount() ) { MSG_ERROR( MSG_FLF << "Different Number of Children" ); } return count; } std::string XMLLoadHandler::getNextNodeName () { std::string nodeName; DOMNode *child; if ( m_currentElements.size() == 0 ) { nodeName = ""; } else { m_currentElement = (DOMElement*) m_currentElements.back(); nodeName = W( m_currentElement->getNodeName() ); m_currentElements.pop_back(); for ( child = m_currentElement->getLastChild(); child != 0; child = child->getPreviousSibling() ) { if ( child->getNodeType() == DOMNode::ELEMENT_NODE ) { m_currentElements.push_back( child ); } } #if 0 std::cout << "| DEBUG | " << "Node-List: " << std::endl << "| | "; for ( auto current_elem : m_currentElements ) { std::cout << "<" << W( current_elem->getNodeName() ) << "> "; } std::cout << std::endl; #endif } //MSG_DEBUG("NodeName: " << nodeName); return nodeName; } std::map<std::string, std::string> XMLLoadHandler::getAttributeList () { std::map<std::string, std::string> attributeList; DOMAttr *pAttributeNode; std::string aName; std::string aValue; DOMNamedNodeMap *pAttributes = m_currentElement->getAttributes(); const XMLSize_t nSize = pAttributes->getLength(); //MSG_DEBUG("\t" << "Attributes:"); //MSG_DEBUG("\t" << "-----------"); for ( XMLSize_t i = 0; i < nSize; ++i ) { pAttributeNode = (DOMAttr*) pAttributes->item( i ); // get attribute name aName = W( pAttributeNode->getName() ); // get attribute type aValue = W( pAttributeNode->getValue() ); // Print Attribute Name and Value //MSG_DEBUG"\t" << aName << "=" << aValue); attributeList.insert( std::pair<std::string, std::string>( aName, aValue ) ); } return attributeList; } std::string XMLLoadHandler::getCurrentXSITypeName () { DOMAttr *pAttributeNode; std::string aName; DOMNamedNodeMap *pAttributes = m_currentElement->getAttributes(); const XMLSize_t nSize = pAttributes->getLength(); for ( XMLSize_t i = 0; i < nSize; ++i ) { pAttributeNode = (DOMAttr*) pAttributes->item( i ); // get attribute name aName = W( pAttributeNode->getName() ); if (aName == "xsi:type" or aName == "xmi:type") { std::string _type = W(pAttributeNode->getValue()); size_t const double_dot = _type.find(L':', 0); std::string _type_ns = _type.substr(0, double_dot); // TODO '_type_ns' is not used in this case std::string _type_name = _type.substr(double_dot + 1); return _type_name; } } return ""; } std::string XMLLoadHandler::getCurrentXMIID() { DOMAttr *pAttributeNode; std::string aName; DOMNamedNodeMap *pAttributes = m_currentElement->getAttributes(); const XMLSize_t nSize = pAttributes->getLength(); for ( XMLSize_t i = 0; i < nSize; ++i ) { pAttributeNode = (DOMAttr*) pAttributes->item( i ); // get attribute name aName = W( pAttributeNode->getName() ); if (aName == "xmi:id") { std::string id = W(pAttributeNode->getValue()); return id; } } return ""; } std::shared_ptr<ecore::EObject> XMLLoadHandler::checkNodeType(std::shared_ptr<ecore::EObject> object) { DOMNodeList* dom = m_currentElement->getChildNodes(); const XMLSize_t size = dom->getLength(); for (XMLSize_t i=0; i<size; i++) { DOMNode* node = dom->item(i); std::string nodeName = W(node->getNodeName()); if (nodeName == "type") { std::string type = ""; std::string href = ""; DOMNamedNodeMap* attrListNode = node->getAttributes(); const XMLSize_t sizeAttrList = attrListNode->getLength(); for (XMLSize_t i = 0; i < sizeAttrList; ++i) { DOMAttr* attributeNode = (DOMAttr*) attrListNode->item( i ); // get attribute name std::string aName = W( attributeNode->getName() ); if (aName == "xmi:type") { type = W(attributeNode->getValue()); } if (aName == "href") { href = W(attributeNode->getValue()); } } type = type + " " + href; auto iter = m_refToObject_map.find(type); if (iter != m_refToObject_map.end()) { return iter->second; } else { loadTypes(type); auto iter = m_refToObject_map.find(type); if (iter != m_refToObject_map.end()) { return iter->second; } } } } return nullptr; } std::shared_ptr<std::string> XMLLoadHandler::getChildText() { std::string value = W(m_currentElement->getTextContent()); std::shared_ptr<std::string> valuePtr(new std::string(value)); return valuePtr; } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information. =========================================================================*/ #include "@FUNCTIONALITY_NAME@.h" #include "@FUNCTIONALITY_NAME@Controls.h" #include <qaction.h> #include "icon.xpm" #include "QmitkTreeNodeSelector.h" #include "QmitkStdMultiWidget.h" @FUNCTIONALITY_NAME@::@FUNCTIONALITY_NAME@(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIteratorBase* it) : QmitkFunctionality(parent, name, it), m_MultiWidget(mitkStdMultiWidget), m_Controls(NULL) { SetAvailability(true); } @FUNCTIONALITY_NAME@::~@FUNCTIONALITY_NAME@() {} QWidget * @FUNCTIONALITY_NAME@::CreateMainWidget(QWidget *parent) { if ( m_MultiWidget == NULL ) { m_MultiWidget = new QmitkStdMultiWidget( parent ); } return m_MultiWidget; } QWidget * @FUNCTIONALITY_NAME@::CreateControlWidget(QWidget *parent) { if (m_Controls == NULL) { m_Controls = new @FUNCTIONALITY_NAME@Controls(parent); } return m_Controls; } void @FUNCTIONALITY_NAME@::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_TreeNodeSelector), SIGNAL(Activated(mitk::DataTreeIteratorClone)),(QObject*) this, SLOT(ImageSelected(mitk::DataTreeIteratorClone)) ); } } QAction * @FUNCTIONALITY_NAME@::CreateAction(QActionGroup *parent) { QAction* action; action = new QAction( tr( "ToolTip" ), QPixmap((const char**)icon_xpm), tr( "MenueEintrag" ), 0, parent, "@FUNCTIONALITY_NAME@" ); return action; } void @FUNCTIONALITY_NAME@::TreeChanged() { m_Controls->m_TreeNodeSelector->SetDataTreeNodeIterator(this->GetDataTreeIterator()); } void @FUNCTIONALITY_NAME@::Activated() { QmitkFunctionality::Activated(); } void @FUNCTIONALITY_NAME@::ImageSelected(mitk::DataTreeIteratorClone imageIt) { std::string name; if (imageIt->Get()->GetName(name)) { std::cout << "Tree node selected with name '" << name << "'" << std::endl; } } <commit_msg>play a bit more safe/explicit in the image-selected-procedure<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 notices for more information. =========================================================================*/ #include "@FUNCTIONALITY_NAME@.h" #include "@FUNCTIONALITY_NAME@Controls.h" #include <qaction.h> #include "icon.xpm" #include "QmitkTreeNodeSelector.h" #include "QmitkStdMultiWidget.h" @FUNCTIONALITY_NAME@::@FUNCTIONALITY_NAME@(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIteratorBase* it) : QmitkFunctionality(parent, name, it), m_MultiWidget(mitkStdMultiWidget), m_Controls(NULL) { SetAvailability(true); } @FUNCTIONALITY_NAME@::~@FUNCTIONALITY_NAME@() {} QWidget * @FUNCTIONALITY_NAME@::CreateMainWidget(QWidget *parent) { if ( m_MultiWidget == NULL ) { m_MultiWidget = new QmitkStdMultiWidget( parent ); } return m_MultiWidget; } QWidget * @FUNCTIONALITY_NAME@::CreateControlWidget(QWidget *parent) { if (m_Controls == NULL) { m_Controls = new @FUNCTIONALITY_NAME@Controls(parent); } return m_Controls; } void @FUNCTIONALITY_NAME@::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_TreeNodeSelector), SIGNAL(Activated(mitk::DataTreeIteratorClone)),(QObject*) this, SLOT(ImageSelected(mitk::DataTreeIteratorClone)) ); } } QAction * @FUNCTIONALITY_NAME@::CreateAction(QActionGroup *parent) { QAction* action; action = new QAction( tr( "ToolTip" ), QPixmap((const char**)icon_xpm), tr( "MenueEintrag" ), 0, parent, "@FUNCTIONALITY_NAME@" ); return action; } void @FUNCTIONALITY_NAME@::TreeChanged() { m_Controls->m_TreeNodeSelector->SetDataTreeNodeIterator(this->GetDataTreeIterator()); } void @FUNCTIONALITY_NAME@::Activated() { QmitkFunctionality::Activated(); } void @FUNCTIONALITY_NAME@::ImageSelected(mitk::DataTreeIteratorClone imageIt) { assert( imageIt.IsNotNull() ); // should never fail, the selection widget cares for that mitk::DataTreeNode* node = imageIt->Get(); if ( node ) { // here we have a valid mitk::DataTreeNode std::string name; if (node->GetName(name)) { // a property called "name" was found for this DataTreeNode std::cout << "Tree node selected with name '" << name << "'" << std::endl; } // a node itself is not very useful, we need its data item mitk::BaseData* data = node->GetData(); if (data) { // test if this data item is an image or not (could also be a surface or something totally different) mitk::Image* image = dynamic_cast<mitk::Image*>( data ); if (image) { std::cout << "Surprise: this node contains a real image dataset." << std::endl; } } } } <|endoftext|>
<commit_before>#pragma once #include <cstdint> #include <limits> #include "type.hpp" namespace spn { //! 表現に何ビット使うか計算 /*! +1すればMSBの取得にもつかえる */ template <unsigned int N> struct NBits { enum { result=1+NBits<((N)>>1)>::result }; }; template <> struct NBits<0> { enum { result=1 }; }; template <> struct NBits<1> { enum { result=1 }; }; //! NをLで何回割れるか(と、その余り) template <int N, int L, int N2=N> struct NDivide { typedef NDivide<N/L,L,N> Lower; enum { result=Lower::result + ((N>=L) ? 1 : 0), sum=N + Lower::sum, odd=Lower::odd }; }; template <int L, int N2> struct NDivide<0, L, N2> { enum { result=0, sum=0, odd=N2 }; }; //! コンパイル時累乗 template <int N, int P> struct NPow { enum { result=NPow<N,P-1>::result * N }; }; template <int N> struct NPow<N,0> { enum { result=1 }; }; //! 引数のペアを全てXORしたものをORする inline int X_OrArgs() { return 0; } template <class T, class... Args> inline T X_OrArgs(const T& t0, const T& t1, Args... args) { return (t0^t1) | X_OrArgs(args...); } //! 定数Nの使用ビット template <int N> struct BitLength { enum { length = BitLength<(N>>1)>::length + 1 }; }; template <> struct BitLength<0> { enum { length = 0 }; }; //! ビットフィールド定義用 template <int OFS, int LEN> struct BitF { enum { offset=OFS, length=LEN }; }; //! 特定のビットを対象として値を取得 & 代入 /*! \param T 値を保持する型 (unsigned) * \param OFS ビットオフセット * \param LEN ビット長 */ template <class T, int OFS, int LEN> class BitOp { enum { offset=OFS, length=LEN }; T& _value; constexpr static T MASKLOW = ((1 << LEN) - 1), MASK = MASKLOW << OFS; // Tが非数値型だったりsignedな型ならコンパイルエラーを起こす using Limits = std::numeric_limits<T>; constexpr static int Dummy[Limits::is_specialized && Limits::is_integer && !Limits::is_signed ? 0 : -1] = {}; public: template <class P> BitOp(P* ptr): _value(*(T*)ptr) {} BitOp(T* ptr): _value(*ptr) {} BitOp(T& ref): _value(ref) {} template <class V> BitOp& operator = (const V v) { // ビットクリア _value &= ~MASK; _value |= (T(v)<<OFS & MASK); return *this; } operator T () const { return (_value >> OFS) & MASKLOW; } }; //! ワードに対するビット操作 /*! \param WORD 値を保持する型 * \param OFS 下位ビット位置 * \param LEN 処理対象ビット幅 */ template <class WORD, int OFS, int LEN> class BitSub { const static WORD MASKLOW = ((1 << LEN) - 1), MASK = MASKLOW << OFS; using Word = WORD; Word& _word; public: BitSub(Word& w): _word(w) {} template <class V> BitSub& operator = (const V v) { // ビットクリア _word &= ~MASK; _word |= (Word(v)<<OFS & MASK); return *this; } operator Word() const { return get(_word); } static Word get(const Word& w) { return (w >> OFS) & MASKLOW; } //! 違う基本型やビット位置でも交換可能だが、サイズ違いは駄目 template <class T_WORD, int T_OFS> void swap(BitSub<T_WORD, T_OFS, LEN>& bs) noexcept { Word val0(*this); (*this) = Word(bs); bs = val0; } }; //! テンプレートにてビットフィールドを定義 /*! \param T 値を保持する型 \*param Args ビットフィールドを定義するBitOpクラス */ template <class T, class... Ts> struct BitDef : CType<Ts...> { // Tが非数値型だったりsignedな型ならコンパイルエラーを起こす using Limits = std::numeric_limits<T>; constexpr static int UnsignedCheck[Limits::is_specialized && Limits::is_integer && !Limits::is_signed ? 0 : -1] = {}; using Word = T; }; //! ビットフィールドテンプレートクラス /*! \example struct MyDef : BitDef<uint32_t, BitF<0,14>, BitF<14,6>, BitF<20,12>> { <br> enum { VAL0, VAL1, VAL2 }; }; <br> using Value = BitField<MyDef>; <br> Value value; <br> value.at<Value::VAL0>() = 128; <br> int toGet = value.at<Value::VAL0>(); \param BF BitDefクラス */ template <class BF> struct BitField : BF { // BF(CTypes)から総サイズとオフセット計算 constexpr static int maxbit = BF::template Size<>::maxbit, buffsize = ((maxbit-1)/8)+1; using Word = typename BF::Word; constexpr static int WordCheck[buffsize > sizeof(Word) ? -1 : 0] = {}; Word _word; BitField() = default; BitField(const BitField& bf): _word(bf.value()) {} BitField(const Word& w): _word(w) {} Word& value() { return _word; } const Word& value() const { return _word; } template <int N> using BFAt = typename BF::template At<N>::type; template <int N> using BitSubT = BitSub<Word, BFAt<N>::offset, BFAt<N>::length>; //! ビット領域参照 template <int N> BitSubT<N> at() { return BitSubT<N>(_word); } //! ビットフィールド値取得 template <int N> Word at() const { return BitSubT<N>::get(_word); } //! ビット幅マスク取得 template <int N> static Word length_mask() { return (Word(1) << BFAt<N>::length) - 1; } //! ビットマスク取得 template <int N> static Word mask() { auto ret = length_mask<N>(); return ret << BFAt<N>::offset; } //! ビットフィールドで使う場所以外をゼロクリアした値を取得 Word cleanedValue() const { constexpr Word msk = (1 << maxbit)-1; return value() & msk; } bool operator == (const BitField& bf) const { return cleanedValue() == bf.cleanedValue(); } bool operator != (const BitField& bf) const { return !(this->operator == (bf)); } bool operator < (const BitField& bf) const { return cleanedValue() < bf.cleanedValue(); } }; struct Bit { static bool Check(uint32_t val, uint32_t flag) { return val & flag; } static void Clear(uint32_t& val, uint32_t flag) { val &= ~flag; } static void Set(uint32_t& val, uint32_t flag) { val |= flag; } //! ビットチェックした結果を返し、ビットは消去する static bool ChClear(uint32_t& val, uint32_t flag) { bool bRet = Check(val, flag); Clear(val, flag); return bRet; } //! 入力値の一番左のビットだけを残す static uint32_t LowClear(uint32_t x) { x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >>16); return x & ~(x>>1); } //! ビットが幾つ立っているか数える static int Count(uint32_t v) { uint32_t tmp = v & 0xaaaaaaaa; v &= 0x55555555; v = v + (tmp >> 1); tmp = v & 0xcccccccc; v &= 0x33333333; v = v + (tmp >> 2); tmp = v & 0xf0f0f0f0; v &= 0x0f0f0f0f; v = v + (tmp >> 4); tmp = v & 0xff00ff00; v &= 0x00ff00ff; v = v + (tmp >> 8); tmp = v & 0xffff0000; v &= 0x0000ffff; v = v + (tmp >> 16); return v; } //! 入力値が0なら0, それ以外は~0を返す static int32_t ZeroOrFull(int32_t v) { return (v | -v) >> 31; } // ビットの位置を計算 #ifdef USEASM_BITSEARCH static uint32_t MSB_N(uint32_t x) { uint32_t ret; asm("movl %1, %%eax;" "orl $0x01, %%eax;" "bsrl %%eax, %0;" :"=r" (ret) :"r" (x) :"%eax" ); return ret; } static uint32_t LSB_N(uint32_t x) { uint32_t ret; asm("movl %1, %%eax;" "orl $0x80000000, %%eax;" "bsfl %%eax, %0;" :"=r" (ret) :"r" (x) :"%eax" ); return ret; } #else const static char NLRZ_TABLE[33]; //! most significant bit を取得 /*! もし入力値が0の場合は0を返す */ static uint32_t MSB_N(uint32_t x) { return NLRZ_TABLE[0x0aec7cd2U * LowClear(x) >> 27]; } //! least significant bit を取得 /*! もし入力値が0の場合は31を返す */ static uint32_t LSB_N(uint32_t x) { return NLRZ_TABLE[0x0aec7cd2U * (x & -x) >> 27]; } #endif //! 32bit値のエンディアン変換 [little -> bit] static uint32_t LtoB32(uint32_t v) { uint32_t a = v<<24, b = (v&0xff00)<<8, c = (v>>8)&0xff00, d = v>>24; return a|b|c|d; } //! 16bit値のエンディアン変換 [little -> bit] static uint32_t LtoB16(uint32_t v) { uint32_t a = (v>>8)&0xff, b = (v&0xff)<<8; return a|b; } }; } namespace std { template <class W0, int OFS0, class W1, int OFS1, int LEN> inline void swap(spn::BitSub<W0,OFS0,LEN>&& b0, spn::BitSub<W1,OFS1,LEN>&& b1) { b0.swap(b1); } template <class W0, int OFS0, class W1, int OFS1, int LEN> inline void swap(spn::BitSub<W0,OFS0,LEN>&& b0, spn::BitSub<W1,OFS1,LEN>& b1) { b0.swap(b1); } template <class W0, int OFS0, class W1, int OFS1, int LEN> inline void swap(spn::BitSub<W0,OFS0,LEN>& b0, spn::BitSub<W1,OFS1,LEN>&& b1) { b0.swap(b1); } } <commit_msg>Bit::LowClear() をテンプレート対応にした<commit_after>#pragma once #include <cstdint> #include <limits> #include "type.hpp" namespace spn { //! 表現に何ビット使うか計算 /*! +1すればMSBの取得にもつかえる */ template <unsigned int N> struct NBits { enum { result=1+NBits<((N)>>1)>::result }; }; template <> struct NBits<0> { enum { result=1 }; }; template <> struct NBits<1> { enum { result=1 }; }; //! NをLで何回割れるか(と、その余り) template <int N, int L, int N2=N> struct NDivide { typedef NDivide<N/L,L,N> Lower; enum { result=Lower::result + ((N>=L) ? 1 : 0), sum=N + Lower::sum, odd=Lower::odd }; }; template <int L, int N2> struct NDivide<0, L, N2> { enum { result=0, sum=0, odd=N2 }; }; //! コンパイル時累乗 template <int N, int P> struct NPow { enum { result=NPow<N,P-1>::result * N }; }; template <int N> struct NPow<N,0> { enum { result=1 }; }; //! 引数のペアを全てXORしたものをORする inline int X_OrArgs() { return 0; } template <class T, class... Args> inline T X_OrArgs(const T& t0, const T& t1, Args... args) { return (t0^t1) | X_OrArgs(args...); } //! 定数Nの使用ビット template <int N> struct BitLength { enum { length = BitLength<(N>>1)>::length + 1 }; }; template <> struct BitLength<0> { enum { length = 0 }; }; //! ビットフィールド定義用 template <int OFS, int LEN> struct BitF { enum { offset=OFS, length=LEN }; }; //! 特定のビットを対象として値を取得 & 代入 /*! \param T 値を保持する型 (unsigned) * \param OFS ビットオフセット * \param LEN ビット長 */ template <class T, int OFS, int LEN> class BitOp { enum { offset=OFS, length=LEN }; T& _value; constexpr static T MASKLOW = ((1 << LEN) - 1), MASK = MASKLOW << OFS; // Tが非数値型だったりsignedな型ならコンパイルエラーを起こす using Limits = std::numeric_limits<T>; constexpr static int Dummy[Limits::is_specialized && Limits::is_integer && !Limits::is_signed ? 0 : -1] = {}; public: template <class P> BitOp(P* ptr): _value(*(T*)ptr) {} BitOp(T* ptr): _value(*ptr) {} BitOp(T& ref): _value(ref) {} template <class V> BitOp& operator = (const V v) { // ビットクリア _value &= ~MASK; _value |= (T(v)<<OFS & MASK); return *this; } operator T () const { return (_value >> OFS) & MASKLOW; } }; //! ワードに対するビット操作 /*! \param WORD 値を保持する型 * \param OFS 下位ビット位置 * \param LEN 処理対象ビット幅 */ template <class WORD, int OFS, int LEN> class BitSub { const static WORD MASKLOW = ((1 << LEN) - 1), MASK = MASKLOW << OFS; using Word = WORD; Word& _word; public: BitSub(Word& w): _word(w) {} template <class V> BitSub& operator = (const V v) { // ビットクリア _word &= ~MASK; _word |= (Word(v)<<OFS & MASK); return *this; } operator Word() const { return get(_word); } static Word get(const Word& w) { return (w >> OFS) & MASKLOW; } //! 違う基本型やビット位置でも交換可能だが、サイズ違いは駄目 template <class T_WORD, int T_OFS> void swap(BitSub<T_WORD, T_OFS, LEN>& bs) noexcept { Word val0(*this); (*this) = Word(bs); bs = val0; } }; //! テンプレートにてビットフィールドを定義 /*! \param T 値を保持する型 \*param Args ビットフィールドを定義するBitOpクラス */ template <class T, class... Ts> struct BitDef : CType<Ts...> { // Tが非数値型だったりsignedな型ならコンパイルエラーを起こす using Limits = std::numeric_limits<T>; constexpr static int UnsignedCheck[Limits::is_specialized && Limits::is_integer && !Limits::is_signed ? 0 : -1] = {}; using Word = T; }; //! ビットフィールドテンプレートクラス /*! \example struct MyDef : BitDef<uint32_t, BitF<0,14>, BitF<14,6>, BitF<20,12>> { <br> enum { VAL0, VAL1, VAL2 }; }; <br> using Value = BitField<MyDef>; <br> Value value; <br> value.at<Value::VAL0>() = 128; <br> int toGet = value.at<Value::VAL0>(); \param BF BitDefクラス */ template <class BF> struct BitField : BF { // BF(CTypes)から総サイズとオフセット計算 constexpr static int maxbit = BF::template Size<>::maxbit, buffsize = ((maxbit-1)/8)+1; using Word = typename BF::Word; constexpr static int WordCheck[buffsize > sizeof(Word) ? -1 : 0] = {}; Word _word; BitField() = default; BitField(const BitField& bf): _word(bf.value()) {} BitField(const Word& w): _word(w) {} Word& value() { return _word; } const Word& value() const { return _word; } template <int N> using BFAt = typename BF::template At<N>::type; template <int N> using BitSubT = BitSub<Word, BFAt<N>::offset, BFAt<N>::length>; //! ビット領域参照 template <int N> BitSubT<N> at() { return BitSubT<N>(_word); } //! ビットフィールド値取得 template <int N> Word at() const { return BitSubT<N>::get(_word); } //! ビット幅マスク取得 template <int N> static Word length_mask() { return (Word(1) << BFAt<N>::length) - 1; } //! ビットマスク取得 template <int N> static Word mask() { auto ret = length_mask<N>(); return ret << BFAt<N>::offset; } //! ビットフィールドで使う場所以外をゼロクリアした値を取得 Word cleanedValue() const { constexpr Word msk = (1 << maxbit)-1; return value() & msk; } bool operator == (const BitField& bf) const { return cleanedValue() == bf.cleanedValue(); } bool operator != (const BitField& bf) const { return !(this->operator == (bf)); } bool operator < (const BitField& bf) const { return cleanedValue() < bf.cleanedValue(); } }; struct Bit { static bool Check(uint32_t val, uint32_t flag) { return val & flag; } static void Clear(uint32_t& val, uint32_t flag) { val &= ~flag; } static void Set(uint32_t& val, uint32_t flag) { val |= flag; } //! ビットチェックした結果を返し、ビットは消去する static bool ChClear(uint32_t& val, uint32_t flag) { bool bRet = Check(val, flag); Clear(val, flag); return bRet; } //! 入力値の一番左のビットだけを残す template <class T, class=typename std::enable_if<std::is_unsigned<T>::value>::type*> static T LowClear(T x) { x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >>16); return x & ~(x>>1); } //! ビットが幾つ立っているか数える static int Count(uint32_t v) { uint32_t tmp = v & 0xaaaaaaaa; v &= 0x55555555; v = v + (tmp >> 1); tmp = v & 0xcccccccc; v &= 0x33333333; v = v + (tmp >> 2); tmp = v & 0xf0f0f0f0; v &= 0x0f0f0f0f; v = v + (tmp >> 4); tmp = v & 0xff00ff00; v &= 0x00ff00ff; v = v + (tmp >> 8); tmp = v & 0xffff0000; v &= 0x0000ffff; v = v + (tmp >> 16); return v; } //! 入力値が0なら0, それ以外は~0を返す static int32_t ZeroOrFull(int32_t v) { return (v | -v) >> 31; } // ビットの位置を計算 #ifdef USEASM_BITSEARCH static uint32_t MSB_N(uint32_t x) { uint32_t ret; asm("movl %1, %%eax;" "orl $0x01, %%eax;" "bsrl %%eax, %0;" :"=r" (ret) :"r" (x) :"%eax" ); return ret; } static uint32_t LSB_N(uint32_t x) { uint32_t ret; asm("movl %1, %%eax;" "orl $0x80000000, %%eax;" "bsfl %%eax, %0;" :"=r" (ret) :"r" (x) :"%eax" ); return ret; } #else const static char NLRZ_TABLE[33]; //! most significant bit を取得 /*! もし入力値が0の場合は0を返す */ static uint32_t MSB_N(uint32_t x) { return NLRZ_TABLE[0x0aec7cd2U * LowClear(x) >> 27]; } //! least significant bit を取得 /*! もし入力値が0の場合は31を返す */ static uint32_t LSB_N(uint32_t x) { return NLRZ_TABLE[0x0aec7cd2U * (x & -x) >> 27]; } #endif //! 32bit値のエンディアン変換 [little -> bit] static uint32_t LtoB32(uint32_t v) { uint32_t a = v<<24, b = (v&0xff00)<<8, c = (v>>8)&0xff00, d = v>>24; return a|b|c|d; } //! 16bit値のエンディアン変換 [little -> bit] static uint32_t LtoB16(uint32_t v) { uint32_t a = (v>>8)&0xff, b = (v&0xff)<<8; return a|b; } }; } namespace std { template <class W0, int OFS0, class W1, int OFS1, int LEN> inline void swap(spn::BitSub<W0,OFS0,LEN>&& b0, spn::BitSub<W1,OFS1,LEN>&& b1) { b0.swap(b1); } template <class W0, int OFS0, class W1, int OFS1, int LEN> inline void swap(spn::BitSub<W0,OFS0,LEN>&& b0, spn::BitSub<W1,OFS1,LEN>& b1) { b0.swap(b1); } template <class W0, int OFS0, class W1, int OFS1, int LEN> inline void swap(spn::BitSub<W0,OFS0,LEN>& b0, spn::BitSub<W1,OFS1,LEN>&& b1) { b0.swap(b1); } } <|endoftext|>
<commit_before>/* * storeBCDvalueOfVxInsrtruction.cpp * * Created on: Jul 23, 2016 * Author: Tomas Stibrany */ #include "storeBCDvalueOfVxInstruction.hpp" #include "../cpu.hpp" using namespace chip8::core::cpu::instructions; using namespace chip8::core::cpu; StoreBCDvalueOfVxInstruction::StoreBCDvalueOfVxInstruction(u8 registerXindex, CPU *cpu) : IInstruction() { SetRegisterXindex(registerXindex); this->cpu = cpu; } StoreBCDvalueOfVxInstruction::~StoreBCDvalueOfVxInstruction() { } void StoreBCDvalueOfVxInstruction::Execute() { u8 registerXvalue = this->cpu->ReadFromGeneralPurposeRegister(this->registerXindex); // Calculate BCD u8 bcdHundreds = registerXvalue / 100; u8 bcdTens = (registerXvalue - bcdHundreds) / 10; u8 bcdOnes = (registerXvalue - bcdHundreds - bcdTens); // Store BCD u16 address = this->cpu->ReadFromIndexRegister(); this->cpu->WriteToMemory(bcdHundreds); this->cpu->WriteToIndexRegister(address + 1); this->cpu->WriteToMemory(bcdTens); this->cpu->WriteToIndexRegister(address + 2); this->cpu->WriteToMemory(bcdOnes); } void StoreBCDvalueOfVxInstruction::SetRegisterXindex(u8 registerIndex) { this->registerXindex = registerIndex; } <commit_msg>[CHG] StoreBCD instructions restores Index register value<commit_after>/* * storeBCDvalueOfVxInsrtruction.cpp * * Created on: Jul 23, 2016 * Author: Tomas Stibrany */ #include "storeBCDvalueOfVxInstruction.hpp" #include "../cpu.hpp" using namespace chip8::core::cpu::instructions; using namespace chip8::core::cpu; StoreBCDvalueOfVxInstruction::StoreBCDvalueOfVxInstruction(u8 registerXindex, CPU *cpu) : IInstruction() { SetRegisterXindex(registerXindex); this->cpu = cpu; } StoreBCDvalueOfVxInstruction::~StoreBCDvalueOfVxInstruction() { } void StoreBCDvalueOfVxInstruction::Execute() { u8 registerXvalue = this->cpu->ReadFromGeneralPurposeRegister(this->registerXindex); // Calculate BCD u8 bcdHundreds = registerXvalue / 100; u8 bcdTens = (registerXvalue - bcdHundreds) / 10; u8 bcdOnes = (registerXvalue - bcdHundreds - bcdTens); // Store BCD u16 address = this->cpu->ReadFromIndexRegister(); this->cpu->WriteToMemory(bcdHundreds); this->cpu->WriteToIndexRegister(address + 1); this->cpu->WriteToMemory(bcdTens); this->cpu->WriteToIndexRegister(address + 2); this->cpu->WriteToMemory(bcdOnes); // Restore Index register this->cpu->WriteToIndexRegister(address); } void StoreBCDvalueOfVxInstruction::SetRegisterXindex(u8 registerIndex) { this->registerXindex = registerIndex; } <|endoftext|>
<commit_before>#include "Timer.h" namespace fse { Timer::Timer(Scene* scene) : FSEObject(scene) { } Timer::~Timer() { } void Timer::update(float deltaTime) { if (active_) { elapsed_time_ += deltaTime; while (elapsed_time_ * 1000 >= interval_) { elapsed_time_ -= interval_*0.001f; timeout_(); if (single_shot_) { active_ = false; getScene()->destroyFSEObject(this); break; } } } } void Timer::draw(sf::RenderTarget & target) { } void Timer::spawned() { } void Timer::stop() { active_ = false; } void Timer::setInterval(int msecs) { interval_ = msecs; } bool Timer::isActive() const { return active_; } void Timer::setSingleShot(bool singleShot) { single_shot_ = singleShot; } } #include <rttr/registration> RTTR_REGISTRATION { using namespace rttr; registration::class_<fse::Timer>("fse::Timer") .constructor<>([](fse::Scene* scene) { scene->createFSEObject<fse::Timer>(); return nullptr; }) ( parameter_names("scene"), metadata("CHAI_CTOR", true) ) .constructor<>([](fse::Scene* scene, std::function<void(fse::FSEObject*)> func) { scene->createFSEObject<fse::Timer>(func); return nullptr; }) ( parameter_names("scene", "spawnedSlot"), metadata("CHAI_CTOR", true) ) .property_readonly("active_", &fse::Timer::active_) .property("single_shot_", &fse::Timer::single_shot_) .property("interval_", &fse::Timer::interval_) //.method("start", [](fse::Timer* timer, auto slot) { timer->start(slot); }) .method("stop", &fse::Timer::stop) ; } <commit_msg>Timer: catch chaiscript exceptions<commit_after>#include "Timer.h" #include "../Application.h" #include <regex> namespace fse { Timer::Timer(Scene* scene) : FSEObject(scene) { } Timer::~Timer() { } void Timer::update(float deltaTime) { if (active_) { elapsed_time_ += deltaTime; while (elapsed_time_ * 1000 >= interval_) { elapsed_time_ -= interval_*0.001f; //since chaiscript functions can be run, we have to catch chai exceptions try { timeout_(); } catch(chaiscript::exception::eval_error& e) { const std::string evalString = "puts(\"" + std::regex_replace(e.pretty_print(), std::regex("(\")"), "\\\"") + "\");"; scene_->getApplication()->getChai()->eval(evalString); } catch (std::exception& e) { const std::string evalString = "puts(\"" + std::regex_replace(e.what(), std::regex("(\")"), "\\\"") + "\");"; } catch (...) { } if (single_shot_) { active_ = false; getScene()->destroyFSEObject(this); break; } } } } void Timer::draw(sf::RenderTarget & target) { } void Timer::spawned() { } void Timer::stop() { active_ = false; } void Timer::setInterval(int msecs) { interval_ = msecs; } bool Timer::isActive() const { return active_; } void Timer::setSingleShot(bool singleShot) { single_shot_ = singleShot; } } #include <rttr/registration> RTTR_REGISTRATION { using namespace rttr; registration::class_<fse::Timer>("fse::Timer") .constructor<>([](fse::Scene* scene) { scene->createFSEObject<fse::Timer>(); return nullptr; }) ( parameter_names("scene"), metadata("CHAI_CTOR", true) ) .constructor<>([](fse::Scene* scene, std::function<void(fse::FSEObject*)> func) { scene->createFSEObject<fse::Timer>(func); return nullptr; }) ( parameter_names("scene", "spawnedSlot"), metadata("CHAI_CTOR", true) ) .property_readonly("active_", &fse::Timer::active_) .property("single_shot_", &fse::Timer::single_shot_) .property("interval_", &fse::Timer::interval_) //.method("start", [](fse::Timer* timer, auto slot) { timer->start(slot); }) .method("stop", &fse::Timer::stop) ; } <|endoftext|>
<commit_before>#include "physics.h" #include "GLDebugDrawer.h" #include "../state/state.h" #include <iostream> using namespace Physics; Simulation::Simulation() { m_broadphase = new btDbvtBroadphase(); m_collisionConfiguration = new btDefaultCollisionConfiguration(); m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration); m_solver = new btSequentialImpulseConstraintSolver; m_world = new btDiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_solver, m_collisionConfiguration); m_world->setGravity(btVector3(0,-10,0)); mb.request(Events::EventType::Input); } Simulation::~Simulation() { /* delete m_world; delete m_solver; delete m_broadphase; delete m_dispatcher; delete m_collisionConfiguration; */ } // Tuning // Credit to: // http://bullet.googlecode.com/svn-history/r2704/trunk/Demos/ForkLiftDemo/ForkLiftDemo.cpp float gEngineForce = 0.f; float defaultBreakingForce = 10.f; float gBreakingForce = 100.f; float maxEngineForce = 1000.f;//this should be engine/velocity dependent float maxBreakingForce = 100.f; float gVehicleSteering = 0.f; float wheelFriction = 1000;//BT_LARGE_FLOAT; float suspensionStiffness = 2.f; float suspensionDamping = 1.3f; float suspensionCompression = 1.1f; float rollInfluence = 1.01f;//1.0f; btScalar suspensionRestLength(0.2); btRigidBody *Simulation::addRigidBody(double mass, const btTransform& startTransform, btCollisionShape* shape) { btVector3 localInertia(0, 0, 0); if (mass != 0.0) { shape->calculateLocalInertia(mass, localInertia); } btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform); btRigidBody::btRigidBodyConstructionInfo cInfo(mass,myMotionState,shape,localInertia); btRigidBody* body = new btRigidBody(cInfo); body->setContactProcessingThreshold(1); m_world->addRigidBody(body); return body; } int Simulation::loadWorld() { // Create car #define CAR_WIDTH (0.15) #define CAR_LENGTH (0.25) #define CAR_MASS (400.0) btCollisionShape* chassisShape = new btBoxShape(btVector3(CAR_WIDTH, CAR_WIDTH, CAR_LENGTH)); btCompoundShape* compound = new btCompoundShape(); m_collisionShapes.push_back(chassisShape); m_collisionShapes.push_back(compound); btTransform localTrans; // shift gravity to center of car localTrans.setIdentity(); localTrans.setOrigin(btVector3(0,CAR_WIDTH*1, 0)); compound->addChildShape(localTrans, chassisShape); btTransform tr; tr.setIdentity(); tr.setOrigin(btVector3(0,5,0)); m_carChassis = addRigidBody(CAR_MASS, tr, compound); m_vehicleRayCaster = new btDefaultVehicleRaycaster(m_world); m_tuning.m_maxSuspensionTravelCm = 204.8f; m_tuning.m_suspensionCompression = 4.4f; m_tuning.m_suspensionDamping = 2.3f; m_tuning.m_frictionSlip = 10000.0f; m_tuning.m_suspensionStiffness = 5.0f; m_tuning.m_maxSuspensionForce = 1000.0; m_vehicle = new btRaycastVehicle(m_tuning,m_carChassis, m_vehicleRayCaster); m_carChassis->setActivationState(DISABLE_DEACTIVATION); m_world->addVehicle(m_vehicle); float connectionHeight = 0.1; btVector3 wheelDirectionCS0(0,-1,0); btVector3 wheelAxleCS(-1,0,0); #define CON1 (CAR_WIDTH) #define CON2 (CAR_LENGTH) float wheelRadius = 0.075f; float wheelWidth = 0.03f; bool isFrontWheel=true; btVector3 connectionPointCS0(CON1,connectionHeight,CON2); m_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel); connectionPointCS0 = btVector3(-CON1,connectionHeight,CON2); m_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel); isFrontWheel = false; connectionPointCS0 = btVector3(-CON1,connectionHeight,-CON2); m_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel); connectionPointCS0 = btVector3(CON1,connectionHeight,-CON2); m_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel); for (int i=0;i<m_vehicle->getNumWheels();i++) { btWheelInfo& wheel = m_vehicle->getWheelInfo(i); wheel.m_suspensionStiffness = suspensionStiffness; wheel.m_wheelsDampingRelaxation = suspensionDamping; wheel.m_wheelsDampingCompression = suspensionCompression; wheel.m_frictionSlip = wheelFriction; wheel.m_rollInfluence = rollInfluence; } // Add map StateData *state = GetMutState(); btBvhTriangleMeshShape *arenaShape = new btBvhTriangleMeshShape(state->bttmArena, true, true); m_arena = addRigidBody(0.0, btTransform(btQuaternion(0,0,0,1),btVector3(0,0,0)), arenaShape); m_vehicle->resetSuspension(); for (int i=0;i<m_vehicle->getNumWheels();i++) { //synchronize the wheels with the (interpolated) chassis worldtransform m_vehicle->updateWheelTransform(i,true); } return 0; } void Simulation::step(double seconds) { // DEBUGOUT("RUNING PHYSICS %lf\n", seconds); #define STEER_MAX_ANGLE (40.0) #define ENGINE_MAX_FORCE (5000) #define BRAKE_MAX_FORCE (3000) for ( Events::Event *event : (mb.checkMail()) ) { // Hack: Sorry switch ( event->type ) { case Events::EventType::Input: { Events::InputEvent *input = (Events::InputEvent *)event; //double steer = STEER_MAX_ANGLE * input->leftThumbStickRL; //if (steer) { // gVehicleSteering = steer; //} ////DEBUGOUT("STEER %lf, ", gVehicleSteering); //double force = ENGINE_MAX_FORCE * input->rightTrigger; //if(force) { // gEngineForce = force; //} ////DEBUGOUT("FORCE %lf\n", gEngineForce); //double breakingForce = BRAKE_MAX_FORCE * input->leftTrigger; //if(breakingForce) //{ // //gBreakingForce = breakingForce; // gBreakingForce = 0.0; // gEngineForce -= breakingForce; //} gBreakingForce = 0.0; // Not using this yet, maybe for E-brake or something. gVehicleSteering = -STEER_MAX_ANGLE * input->leftThumbStickRL; gEngineForce = ENGINE_MAX_FORCE * input->rightTrigger - BRAKE_MAX_FORCE * input->leftTrigger; DEBUGOUT("Bforce: %lf, Eforce: %lf, Steer: %f\n", gBreakingForce, gEngineForce, gVehicleSteering); } break; default: break; } } mb.emptyMail(); // Apply steering to front wheels m_vehicle->setSteeringValue(gVehicleSteering, 0); m_vehicle->setSteeringValue(gVehicleSteering, 1); // Apply braking and engine force to rear wheels m_vehicle->applyEngineForce(gEngineForce, 2); m_vehicle->applyEngineForce(gEngineForce, 3); m_vehicle->setBrake(gBreakingForce, 2); m_vehicle->setBrake(gBreakingForce, 3); m_world->stepSimulation((btScalar)seconds, 10); // Update the placement of the car in the world state StateData *state = GetMutState(); btTransform car1 = m_vehicle->getChassisWorldTransform(); btVector3 pos = car1.getOrigin(); state->Karts[0].vPos.x = pos.getX(); state->Karts[0].vPos.y = pos.getY(); state->Karts[0].vPos.z = pos.getZ(); btQuaternion rot = car1.getRotation(); btVector3 axis = rot.getAxis(); Vector3 v; v.x = axis.getX(); v.y = axis.getY(); v.z = axis.getZ(); Real angle = -rot.getAngle(); state->Karts[0].qOrient.RotateAxisAngle(v, angle); } void Simulation::enableDebugView() { } <commit_msg>Fixed steering, ITS IN RADIANS!!!!111!!!111<commit_after>#include "physics.h" #include "GLDebugDrawer.h" #include "../state/state.h" #include <iostream> using namespace Physics; Simulation::Simulation() { m_broadphase = new btDbvtBroadphase(); m_collisionConfiguration = new btDefaultCollisionConfiguration(); m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration); m_solver = new btSequentialImpulseConstraintSolver; m_world = new btDiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_solver, m_collisionConfiguration); m_world->setGravity(btVector3(0,-10,0)); mb.request(Events::EventType::Input); } Simulation::~Simulation() { /* delete m_world; delete m_solver; delete m_broadphase; delete m_dispatcher; delete m_collisionConfiguration; */ } // Tuning // Credit to: // http://bullet.googlecode.com/svn-history/r2704/trunk/Demos/ForkLiftDemo/ForkLiftDemo.cpp float gEngineForce = 0.f; float defaultBreakingForce = 10.f; float gBreakingForce = 100.f; float maxEngineForce = 1000.f;//this should be engine/velocity dependent float maxBreakingForce = 100.f; float gVehicleSteering = 0.f; float wheelFriction = 1000;//BT_LARGE_FLOAT; float suspensionStiffness = 2.f; float suspensionDamping = 1.3f; float suspensionCompression = 1.1f; float rollInfluence = 1.01f;//1.0f; btScalar suspensionRestLength(0.2); btRigidBody *Simulation::addRigidBody(double mass, const btTransform& startTransform, btCollisionShape* shape) { btVector3 localInertia(0, 0, 0); if (mass != 0.0) { shape->calculateLocalInertia(mass, localInertia); } btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform); btRigidBody::btRigidBodyConstructionInfo cInfo(mass,myMotionState,shape,localInertia); btRigidBody* body = new btRigidBody(cInfo); body->setContactProcessingThreshold(1); m_world->addRigidBody(body); return body; } int Simulation::loadWorld() { // Create car #define CAR_WIDTH (0.15) #define CAR_LENGTH (0.25) #define CAR_MASS (400.0) btCollisionShape* chassisShape = new btBoxShape(btVector3(CAR_WIDTH, CAR_WIDTH, CAR_LENGTH)); btCompoundShape* compound = new btCompoundShape(); m_collisionShapes.push_back(chassisShape); m_collisionShapes.push_back(compound); btTransform localTrans; // shift gravity to center of car localTrans.setIdentity(); localTrans.setOrigin(btVector3(0,CAR_WIDTH*1, 0)); compound->addChildShape(localTrans, chassisShape); btTransform tr; tr.setIdentity(); tr.setOrigin(btVector3(0,5,0)); m_carChassis = addRigidBody(CAR_MASS, tr, compound); m_vehicleRayCaster = new btDefaultVehicleRaycaster(m_world); m_tuning.m_maxSuspensionTravelCm = 204.8f; m_tuning.m_suspensionCompression = 4.4f; m_tuning.m_suspensionDamping = 2.3f; m_tuning.m_frictionSlip = 10000.0f; m_tuning.m_suspensionStiffness = 5.0f; m_tuning.m_maxSuspensionForce = 1000.0; m_vehicle = new btRaycastVehicle(m_tuning,m_carChassis, m_vehicleRayCaster); m_carChassis->setActivationState(DISABLE_DEACTIVATION); m_world->addVehicle(m_vehicle); float connectionHeight = 0.1; btVector3 wheelDirectionCS0(0,-1,0); btVector3 wheelAxleCS(-1,0,0); #define CON1 (CAR_WIDTH) #define CON2 (CAR_LENGTH) float wheelRadius = 0.075f; float wheelWidth = 0.03f; bool isFrontWheel=true; btVector3 connectionPointCS0(CON1,connectionHeight,CON2); m_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel); connectionPointCS0 = btVector3(-CON1,connectionHeight,CON2); m_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel); isFrontWheel = false; connectionPointCS0 = btVector3(-CON1,connectionHeight,-CON2); m_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel); connectionPointCS0 = btVector3(CON1,connectionHeight,-CON2); m_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel); for (int i=0;i<m_vehicle->getNumWheels();i++) { btWheelInfo& wheel = m_vehicle->getWheelInfo(i); wheel.m_suspensionStiffness = suspensionStiffness; wheel.m_wheelsDampingRelaxation = suspensionDamping; wheel.m_wheelsDampingCompression = suspensionCompression; wheel.m_frictionSlip = wheelFriction; wheel.m_rollInfluence = rollInfluence; } // Add map StateData *state = GetMutState(); btBvhTriangleMeshShape *arenaShape = new btBvhTriangleMeshShape(state->bttmArena, true, true); m_arena = addRigidBody(0.0, btTransform(btQuaternion(0,0,0,1),btVector3(0,0,0)), arenaShape); m_vehicle->resetSuspension(); for (int i=0;i<m_vehicle->getNumWheels();i++) { //synchronize the wheels with the (interpolated) chassis worldtransform m_vehicle->updateWheelTransform(i,true); } return 0; } void Simulation::step(double seconds) { // DEBUGOUT("RUNING PHYSICS %lf\n", seconds); #define STEER_MAX_ANGLE (40) #define ENGINE_MAX_FORCE (3000) #define BRAKE_MAX_FORCE (3000) for ( Events::Event *event : (mb.checkMail()) ) { // Hack: Sorry switch ( event->type ) { case Events::EventType::Input: { Events::InputEvent *input = (Events::InputEvent *)event; //double steer = STEER_MAX_ANGLE * input->leftThumbStickRL; //if (steer) { // gVehicleSteering = steer; //} ////DEBUGOUT("STEER %lf, ", gVehicleSteering); //double force = ENGINE_MAX_FORCE * input->rightTrigger; //if(force) { // gEngineForce = force; //} ////DEBUGOUT("FORCE %lf\n", gEngineForce); //double breakingForce = BRAKE_MAX_FORCE * input->leftTrigger; //if(breakingForce) //{ // //gBreakingForce = breakingForce; // gBreakingForce = 0.0; // gEngineForce -= breakingForce; //} gBreakingForce = 0.0; // Not using this yet, maybe for E-brake or something. gVehicleSteering = DEGTORAD(STEER_MAX_ANGLE) * input->leftThumbStickRL; gEngineForce = ENGINE_MAX_FORCE * input->rightTrigger - BRAKE_MAX_FORCE * input->leftTrigger; DEBUGOUT("Bforce: %lf, Eforce: %lf, Steer: %f\n", gBreakingForce, gEngineForce, gVehicleSteering); if( GetState().key_map['r'] ) { btTransform trans; trans.setOrigin( btVector3( 0, 5, 0 ) ); m_vehicle->getRigidBody()->setWorldTransform( trans ); } } break; default: break; } } mb.emptyMail(); // Apply steering to front wheels m_vehicle->setSteeringValue(gVehicleSteering, 0); m_vehicle->setSteeringValue(gVehicleSteering, 1); // Apply braking and engine force to rear wheels m_vehicle->applyEngineForce(gEngineForce, 2); m_vehicle->applyEngineForce(gEngineForce, 3); m_vehicle->setBrake(gBreakingForce, 2); m_vehicle->setBrake(gBreakingForce, 3); m_world->stepSimulation((btScalar)seconds, 10); // Update the placement of the car in the world state StateData *state = GetMutState(); btTransform car1 = m_vehicle->getChassisWorldTransform(); btVector3 pos = car1.getOrigin(); state->Karts[0].vPos.x = (Real)pos.getX(); state->Karts[0].vPos.y = (Real)pos.getY(); state->Karts[0].vPos.z = (Real)pos.getZ(); btQuaternion rot = car1.getRotation(); state->Karts[0].qOrient.x = (Real)rot.getX(); state->Karts[0].qOrient.y = (Real)-rot.getY(); state->Karts[0].qOrient.z = (Real)rot.getZ(); state->Karts[0].qOrient.w = (Real)rot.getW(); } void Simulation::enableDebugView() { } <|endoftext|>
<commit_before>//===- FileCheck.cpp - Check that File's Contents match what is expected --===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // FileCheck does a line-by line check of a file that validates whether it // contains the expected content. This is useful for regression tests etc. // // This program exits with an error status of 2 on error, exit status of 0 if // the file matched the expected contents, and exit status of 1 if it did not // contain the expected contents. // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Signals.h" using namespace llvm; static cl::opt<std::string> CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required); static cl::opt<std::string> InputFilename("input-file", cl::desc("File to check (defaults to stdin)"), cl::init("-"), cl::value_desc("filename")); static cl::opt<std::string> CheckPrefix("check-prefix", cl::init("CHECK"), cl::desc("Prefix to use from check file (defaults to 'CHECK')")); static cl::opt<bool> NoCanonicalizeWhiteSpace("strict-whitespace", cl::desc("Do not treat all horizontal whitespace as equivalent")); /// CheckString - This is a check that we found in the input file. struct CheckString { /// Str - The string to match. std::string Str; /// Loc - The location in the match file that the check string was specified. SMLoc Loc; /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed /// to a CHECK: directive. bool IsCheckNext; CheckString(const std::string &S, SMLoc L, bool isCheckNext) : Str(S), Loc(L), IsCheckNext(isCheckNext) {} }; /// FindFixedStringInBuffer - This works like strstr, except for two things: /// 1) it handles 'nul' characters in memory buffers. 2) it returns the end of /// the memory buffer on match failure instead of null. static const char *FindFixedStringInBuffer(StringRef Str, const char *CurPtr, const MemoryBuffer &MB) { assert(!Str.empty() && "Can't find an empty string"); const char *BufEnd = MB.getBufferEnd(); while (1) { // Scan for the first character in the match string. CurPtr = (char*)memchr(CurPtr, Str[0], BufEnd-CurPtr); // If we didn't find the first character of the string, then we failed to // match. if (CurPtr == 0) return BufEnd; // If the match string is one character, then we win. if (Str.size() == 1) return CurPtr; // Otherwise, verify that the rest of the string matches. if (Str.size() <= unsigned(BufEnd-CurPtr) && memcmp(CurPtr+1, Str.data()+1, Str.size()-1) == 0) return CurPtr; // If not, advance past this character and try again. ++CurPtr; } } /// ReadCheckFile - Read the check file, which specifies the sequence of /// expected strings. The strings are added to the CheckStrings vector. static bool ReadCheckFile(SourceMgr &SM, std::vector<CheckString> &CheckStrings) { // Open the check file, and tell SourceMgr about it. std::string ErrorStr; MemoryBuffer *F = MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr); if (F == 0) { errs() << "Could not open check file '" << CheckFilename << "': " << ErrorStr << '\n'; return true; } SM.AddNewSourceBuffer(F, SMLoc()); // Find all instances of CheckPrefix followed by : in the file. const char *CurPtr = F->getBufferStart(), *BufferEnd = F->getBufferEnd(); while (1) { // See if Prefix occurs in the memory buffer. const char *Ptr = FindFixedStringInBuffer(CheckPrefix, CurPtr, *F); // If we didn't find a match, we're done. if (Ptr == BufferEnd) break; const char *CheckPrefixStart = Ptr; // When we find a check prefix, keep track of whether we find CHECK: or // CHECK-NEXT: bool IsCheckNext; // Verify that the : is present after the prefix. if (Ptr[CheckPrefix.size()] == ':') { Ptr += CheckPrefix.size()+1; IsCheckNext = false; } else if (BufferEnd-Ptr > 6 && memcmp(Ptr+CheckPrefix.size(), "-NEXT:", 6) == 0) { Ptr += CheckPrefix.size()+7; IsCheckNext = true; } else { CurPtr = Ptr+1; continue; } // Okay, we found the prefix, yay. Remember the rest of the line, but // ignore leading and trailing whitespace. while (*Ptr == ' ' || *Ptr == '\t') ++Ptr; // Scan ahead to the end of line. CurPtr = Ptr; while (CurPtr != BufferEnd && *CurPtr != '\n' && *CurPtr != '\r') ++CurPtr; // Ignore trailing whitespace. while (CurPtr[-1] == ' ' || CurPtr[-1] == '\t') --CurPtr; // Check that there is something on the line. if (Ptr >= CurPtr) { SM.PrintMessage(SMLoc::getFromPointer(CurPtr), "found empty check string with prefix '"+CheckPrefix+":'", "error"); return true; } // Verify that CHECK-NEXT lines have at least one CHECK line before them. if (IsCheckNext && CheckStrings.empty()) { SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart), "found '"+CheckPrefix+"-NEXT:' without previous '"+ CheckPrefix+ ": line", "error"); return true; } // Okay, add the string we captured to the output vector and move on. CheckStrings.push_back(CheckString(std::string(Ptr, CurPtr), SMLoc::getFromPointer(Ptr), IsCheckNext)); } if (CheckStrings.empty()) { errs() << "error: no check strings found with prefix '" << CheckPrefix << ":'\n"; return true; } return false; } // CanonicalizeCheckStrings - Replace all sequences of horizontal whitespace in // the check strings with a single space. static void CanonicalizeCheckStrings(std::vector<CheckString> &CheckStrings) { for (unsigned i = 0, e = CheckStrings.size(); i != e; ++i) { std::string &Str = CheckStrings[i].Str; for (unsigned C = 0; C != Str.size(); ++C) { // If C is not a horizontal whitespace, skip it. if (Str[C] != ' ' && Str[C] != '\t') continue; // Replace the character with space, then remove any other space // characters after it. Str[C] = ' '; while (C+1 != Str.size() && (Str[C+1] == ' ' || Str[C+1] == '\t')) Str.erase(Str.begin()+C+1); } } } /// CanonicalizeInputFile - Remove duplicate horizontal space from the specified /// memory buffer, free it, and return a new one. static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) { SmallVector<char, 16> NewFile; NewFile.reserve(MB->getBufferSize()); for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd(); Ptr != End; ++Ptr) { // If C is not a horizontal whitespace, skip it. if (*Ptr != ' ' && *Ptr != '\t') { NewFile.push_back(*Ptr); continue; } // Otherwise, add one space and advance over neighboring space. NewFile.push_back(' '); while (Ptr+1 != End && (Ptr[1] == ' ' || Ptr[1] == '\t')) ++Ptr; } // Free the old buffer and return a new one. MemoryBuffer *MB2 = MemoryBuffer::getMemBufferCopy(NewFile.data(), NewFile.data() + NewFile.size(), MB->getBufferIdentifier()); delete MB; return MB2; } static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr, const char *CurPtr, const char *BufferEnd) { // Otherwise, we have an error, emit an error message. SM.PrintMessage(CheckStr.Loc, "expected string not found in input", "error"); // Print the "scanning from here" line. If the current position is at the // end of a line, advance to the start of the next line. const char *Scan = CurPtr; while (Scan != BufferEnd && (*Scan == ' ' || *Scan == '\t')) ++Scan; if (*Scan == '\n' || *Scan == '\r') CurPtr = Scan+1; SM.PrintMessage(SMLoc::getFromPointer(CurPtr), "scanning from here", "note"); } static unsigned CountNumNewlinesBetween(const char *Start, const char *End) { unsigned NumNewLines = 0; for (; Start != End; ++Start) { // Scan for newline. if (Start[0] != '\n' && Start[0] != '\r') continue; ++NumNewLines; // Handle \n\r and \r\n as a single newline. if (Start+1 != End && (Start[0] == '\n' || Start[0] == '\r') && (Start[0] != Start[1])) ++Start; } return NumNewLines; } int main(int argc, char **argv) { sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); cl::ParseCommandLineOptions(argc, argv); SourceMgr SM; // Read the expected strings from the check file. std::vector<CheckString> CheckStrings; if (ReadCheckFile(SM, CheckStrings)) return 2; // Remove duplicate spaces in the check strings if requested. if (!NoCanonicalizeWhiteSpace) CanonicalizeCheckStrings(CheckStrings); // Open the file to check and add it to SourceMgr. std::string ErrorStr; MemoryBuffer *F = MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr); if (F == 0) { errs() << "Could not open input file '" << InputFilename << "': " << ErrorStr << '\n'; return true; } // Remove duplicate spaces in the input file if requested. if (!NoCanonicalizeWhiteSpace) F = CanonicalizeInputFile(F); SM.AddNewSourceBuffer(F, SMLoc()); // Check that we have all of the expected strings, in order, in the input // file. const char *CurPtr = F->getBufferStart(), *BufferEnd = F->getBufferEnd(); const char *LastMatch = 0; for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) { const CheckString &CheckStr = CheckStrings[StrNo]; // Find StrNo in the file. const char *Ptr = FindFixedStringInBuffer(CheckStr.Str, CurPtr, *F); // If we didn't find a match, reject the input. if (Ptr == BufferEnd) { PrintCheckFailed(SM, CheckStr, CurPtr, BufferEnd); return 1; } // If this check is a "CHECK-NEXT", verify that the previous match was on // the previous line (i.e. that there is one newline between them). if (CheckStr.IsCheckNext) { // Count the number of newlines between the previous match and this one. assert(LastMatch && "CHECK-NEXT can't be the first check in a file"); unsigned NumNewLines = CountNumNewlinesBetween(LastMatch, Ptr); if (NumNewLines == 0) { SM.PrintMessage(CheckStr.Loc, CheckPrefix+"-NEXT: is on the same line as previous match", "error"); SM.PrintMessage(SMLoc::getFromPointer(Ptr), "'next' match was here", "note"); SM.PrintMessage(SMLoc::getFromPointer(LastMatch), "previous match was here", "note"); return 1; } if (NumNewLines != 1) { SM.PrintMessage(CheckStr.Loc, CheckPrefix+ "-NEXT: is not on the line after the previous match", "error"); SM.PrintMessage(SMLoc::getFromPointer(Ptr), "'next' match was here", "note"); SM.PrintMessage(SMLoc::getFromPointer(LastMatch), "previous match was here", "note"); return 1; } } // Otherwise, everything is good. Remember this as the last match and move // on to the next one. LastMatch = Ptr; CurPtr = Ptr + CheckStr.Str.size(); } return 0; } <commit_msg>rewrite FileCheck in terms of StringRef instead of manual pointer pairs.<commit_after>//===- FileCheck.cpp - Check that File's Contents match what is expected --===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // FileCheck does a line-by line check of a file that validates whether it // contains the expected content. This is useful for regression tests etc. // // This program exits with an error status of 2 on error, exit status of 0 if // the file matched the expected contents, and exit status of 1 if it did not // contain the expected contents. // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Signals.h" using namespace llvm; static cl::opt<std::string> CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required); static cl::opt<std::string> InputFilename("input-file", cl::desc("File to check (defaults to stdin)"), cl::init("-"), cl::value_desc("filename")); static cl::opt<std::string> CheckPrefix("check-prefix", cl::init("CHECK"), cl::desc("Prefix to use from check file (defaults to 'CHECK')")); static cl::opt<bool> NoCanonicalizeWhiteSpace("strict-whitespace", cl::desc("Do not treat all horizontal whitespace as equivalent")); /// CheckString - This is a check that we found in the input file. struct CheckString { /// Str - The string to match. std::string Str; /// Loc - The location in the match file that the check string was specified. SMLoc Loc; /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed /// to a CHECK: directive. bool IsCheckNext; CheckString(const std::string &S, SMLoc L, bool isCheckNext) : Str(S), Loc(L), IsCheckNext(isCheckNext) {} }; /// ReadCheckFile - Read the check file, which specifies the sequence of /// expected strings. The strings are added to the CheckStrings vector. static bool ReadCheckFile(SourceMgr &SM, std::vector<CheckString> &CheckStrings) { // Open the check file, and tell SourceMgr about it. std::string ErrorStr; MemoryBuffer *F = MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr); if (F == 0) { errs() << "Could not open check file '" << CheckFilename << "': " << ErrorStr << '\n'; return true; } SM.AddNewSourceBuffer(F, SMLoc()); // Find all instances of CheckPrefix followed by : in the file. StringRef Buffer = F->getBuffer(); while (1) { // See if Prefix occurs in the memory buffer. Buffer = Buffer.substr(Buffer.find(CheckPrefix)); // If we didn't find a match, we're done. if (Buffer.empty()) break; const char *CheckPrefixStart = Buffer.data(); // When we find a check prefix, keep track of whether we find CHECK: or // CHECK-NEXT: bool IsCheckNext; // Verify that the : is present after the prefix. if (Buffer[CheckPrefix.size()] == ':') { Buffer = Buffer.substr(CheckPrefix.size()+1); IsCheckNext = false; } else if (Buffer.size() > CheckPrefix.size()+6 && memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) { Buffer = Buffer.substr(CheckPrefix.size()+7); IsCheckNext = true; } else { Buffer = Buffer.substr(1); continue; } // Okay, we found the prefix, yay. Remember the rest of the line, but // ignore leading and trailing whitespace. while (!Buffer.empty() && (Buffer[0] == ' ' || Buffer[0] == '\t')) Buffer = Buffer.substr(1); // Scan ahead to the end of line. size_t EOL = Buffer.find_first_of("\n\r"); if (EOL == StringRef::npos) EOL = Buffer.size(); // Ignore trailing whitespace. while (EOL && (Buffer[EOL-1] == ' ' || Buffer[EOL-1] == '\t')) --EOL; // Check that there is something on the line. if (EOL == 0) { SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), "found empty check string with prefix '"+CheckPrefix+":'", "error"); return true; } // Verify that CHECK-NEXT lines have at least one CHECK line before them. if (IsCheckNext && CheckStrings.empty()) { SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart), "found '"+CheckPrefix+"-NEXT:' without previous '"+ CheckPrefix+ ": line", "error"); return true; } // Okay, add the string we captured to the output vector and move on. CheckStrings.push_back(CheckString(std::string(Buffer.data(), Buffer.data()+EOL), SMLoc::getFromPointer(Buffer.data()), IsCheckNext)); Buffer = Buffer.substr(EOL); } if (CheckStrings.empty()) { errs() << "error: no check strings found with prefix '" << CheckPrefix << ":'\n"; return true; } return false; } // CanonicalizeCheckStrings - Replace all sequences of horizontal whitespace in // the check strings with a single space. static void CanonicalizeCheckStrings(std::vector<CheckString> &CheckStrings) { for (unsigned i = 0, e = CheckStrings.size(); i != e; ++i) { std::string &Str = CheckStrings[i].Str; for (unsigned C = 0; C != Str.size(); ++C) { // If C is not a horizontal whitespace, skip it. if (Str[C] != ' ' && Str[C] != '\t') continue; // Replace the character with space, then remove any other space // characters after it. Str[C] = ' '; while (C+1 != Str.size() && (Str[C+1] == ' ' || Str[C+1] == '\t')) Str.erase(Str.begin()+C+1); } } } /// CanonicalizeInputFile - Remove duplicate horizontal space from the specified /// memory buffer, free it, and return a new one. static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) { SmallVector<char, 16> NewFile; NewFile.reserve(MB->getBufferSize()); for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd(); Ptr != End; ++Ptr) { // If C is not a horizontal whitespace, skip it. if (*Ptr != ' ' && *Ptr != '\t') { NewFile.push_back(*Ptr); continue; } // Otherwise, add one space and advance over neighboring space. NewFile.push_back(' '); while (Ptr+1 != End && (Ptr[1] == ' ' || Ptr[1] == '\t')) ++Ptr; } // Free the old buffer and return a new one. MemoryBuffer *MB2 = MemoryBuffer::getMemBufferCopy(NewFile.data(), NewFile.data() + NewFile.size(), MB->getBufferIdentifier()); delete MB; return MB2; } static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr, StringRef Buffer) { // Otherwise, we have an error, emit an error message. SM.PrintMessage(CheckStr.Loc, "expected string not found in input", "error"); // Print the "scanning from here" line. If the current position is at the // end of a line, advance to the start of the next line. Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r")); SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), "scanning from here", "note"); } static unsigned CountNumNewlinesBetween(const char *Start, const char *End) { unsigned NumNewLines = 0; for (; Start != End; ++Start) { // Scan for newline. if (Start[0] != '\n' && Start[0] != '\r') continue; ++NumNewLines; // Handle \n\r and \r\n as a single newline. if (Start+1 != End && (Start[0] == '\n' || Start[0] == '\r') && (Start[0] != Start[1])) ++Start; } return NumNewLines; } int main(int argc, char **argv) { sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); cl::ParseCommandLineOptions(argc, argv); SourceMgr SM; // Read the expected strings from the check file. std::vector<CheckString> CheckStrings; if (ReadCheckFile(SM, CheckStrings)) return 2; // Remove duplicate spaces in the check strings if requested. if (!NoCanonicalizeWhiteSpace) CanonicalizeCheckStrings(CheckStrings); // Open the file to check and add it to SourceMgr. std::string ErrorStr; MemoryBuffer *F = MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr); if (F == 0) { errs() << "Could not open input file '" << InputFilename << "': " << ErrorStr << '\n'; return true; } // Remove duplicate spaces in the input file if requested. if (!NoCanonicalizeWhiteSpace) F = CanonicalizeInputFile(F); SM.AddNewSourceBuffer(F, SMLoc()); // Check that we have all of the expected strings, in order, in the input // file. StringRef Buffer = F->getBuffer(); const char *LastMatch = 0; for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) { const CheckString &CheckStr = CheckStrings[StrNo]; StringRef SearchFrom = Buffer; // Find StrNo in the file. Buffer = Buffer.substr(Buffer.find(CheckStr.Str)); // If we didn't find a match, reject the input. if (Buffer.empty()) { PrintCheckFailed(SM, CheckStr, SearchFrom); return 1; } // If this check is a "CHECK-NEXT", verify that the previous match was on // the previous line (i.e. that there is one newline between them). if (CheckStr.IsCheckNext) { // Count the number of newlines between the previous match and this one. assert(LastMatch && "CHECK-NEXT can't be the first check in a file"); unsigned NumNewLines = CountNumNewlinesBetween(LastMatch, Buffer.data()); if (NumNewLines == 0) { SM.PrintMessage(CheckStr.Loc, CheckPrefix+"-NEXT: is on the same line as previous match", "error"); SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), "'next' match was here", "note"); SM.PrintMessage(SMLoc::getFromPointer(LastMatch), "previous match was here", "note"); return 1; } if (NumNewLines != 1) { SM.PrintMessage(CheckStr.Loc, CheckPrefix+ "-NEXT: is not on the line after the previous match", "error"); SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), "'next' match was here", "note"); SM.PrintMessage(SMLoc::getFromPointer(LastMatch), "previous match was here", "note"); return 1; } } // Otherwise, everything is good. Remember this as the last match and move // on to the next one. LastMatch = Buffer.data(); Buffer = Buffer.substr(CheckStr.Str.size()); } return 0; } <|endoftext|>
<commit_before>/*========================================================================= Library : Image Registration Toolkit (IRTK) Module : $Id$ Copyright : Imperial College, Department of Computing Visual Information Processing (VIP), 2009 onwards Date : $Date$ Version : $Revision$ Changes : $Author$ =========================================================================*/ #include <irtkImage.h> #include <irtkImageFunction.h> #ifdef HAS_VTK #include <vtkPointData.h> #include <vtkPolyData.h> #include <vtkPolyDataReader.h> #include <vtkPolyDataWriter.h> #include <vtkDoubleArray.h> char *input_name = NULL, *output_name = NULL, *image_name = NULL; int main(int argc, char **argv) { int i, j, n; double *profile; double x, y, z, ds, point[3], normal[3]; if (argc != 4) { cerr << "Usage: msample [input] [image] [output] -n [number of steps (default 10)] -ds [step size (default 1)]" << endl; exit(1); } // Parse filenames input_name = argv[1]; argv++; argc--; image_name = argv[1]; argv++; argc--; output_name = argv[1]; argv++; argc--; n = 10; ds = 1; // Allocate memory for intensity profile profile = new double[2*n+1]; // Read model vtkPolyDataReader *reader = vtkPolyDataReader::New(); reader->SetFileName(input_name); reader->Modified(); reader->Update(); vtkPolyData *model = vtkPolyData::New(); model = reader->GetOutput(); model->Update(); // Extract normals if (model->GetPointData()->GetNormals() == NULL) { cerr << "Model has no normals" << endl; exit(1); } // Read image irtkGreyImage image; image.Read(image_name); irtkLinearInterpolateImageFunction interpolator; interpolator.SetInput(&image); interpolator.Initialize(); // Allocate memory vtkDoubleArray *array = vtkDoubleArray::New(); array->SetNumberOfTuples(model->GetNumberOfPoints()); array->SetNumberOfComponents(2*n+1); array->SetName("IntensityProfile"); for (i = 0; i < model->GetNumberOfPoints(); i++) { model->GetPoints()->GetPoint (i, point); model->GetPointData()->GetNormals()->GetTuple(i, normal); image.WorldToImage(point[0], point[1], point[2]); for (j = 0; j < 2*n+1; j++) { x = point[0] + (j - n) * ds * normal[0]; y = point[1] + (j - n) * ds * normal[1]; z = point[2] + (j - n) * ds * normal[2]; profile[j] = interpolator.Evaluate(x, y, z); } array->InsertTupleValue(i, profile); } model->GetPointData()->SetScalars(array); vtkPolyDataWriter *writer = vtkPolyDataWriter::New(); writer->SetInput(model); writer->SetFileName(output_name); writer->Write(); } #else #include <irtkImage.h> int main( int argc, char *argv[] ) { cerr << argv[0] << " this program needs to be compiled with vtk enabled." << endl; return 0; } #endif <commit_msg>fixed a bug. world to image wrong place...all mess up previously<commit_after>/*========================================================================= Library : Image Registration Toolkit (IRTK) Module : $Id$ Copyright : Imperial College, Department of Computing Visual Information Processing (VIP), 2009 onwards Date : $Date$ Version : $Revision$ Changes : $Author$ =========================================================================*/ #include <irtkImage.h> #include <irtkImageFunction.h> #include <irtkUtil.h> #ifdef HAS_VTK #include <vtkPointData.h> #include <vtkPolyData.h> #include <vtkPolyDataReader.h> #include <vtkPolyDataWriter.h> #include <vtkDoubleArray.h> #include <vtkPointLocator.h> #include <vtkIdList.h> char *input_name = NULL, *output_name = NULL, *image_name = NULL, *count_name = NULL; void usage(){ cerr << "Usage: msample [input] [image] [output] " << endl; cerr << "-n [number of steps (default 10)]" << endl; cerr << "-ds [step size (default 1)]" << endl; cerr << "-scalar use one scalar instead of array on the norm"<<endl; cerr << "-abs take the abs value of the scalar"<<endl; cerr << "-count [another mesh] sample along between two mesh, evaluate percentage > 0"<<endl; cerr << "-blur blur the result or not"<<endl; exit(1); } int main(int argc, char **argv) { int i, j, n, son, abson, blur, ok; double *profile, count; double x, y, z, ds, point[3], normal[3]; if (argc < 4) { usage(); } // Parse filenames input_name = argv[1]; argv++; argc--; image_name = argv[1]; argv++; argc--; output_name = argv[1]; argv++; argc--; n = 10; ds = 1; son = 0; abson = 0; count = 0; blur = 0; while (argc > 1) { ok = false; if ((ok == false) && (strcmp(argv[1], "-n") == 0)) { argc--; argv++; n = atoi(argv[1]); argc--; argv++; ok = true; } if ((ok == false) && (strcmp(argv[1], "-count") == 0)) { argc--; argv++; count_name = argv[1]; argc--; argv++; ok = true; } if ((ok == false) && (strcmp(argv[1], "-ds") == 0)) { argc--; argv++; ds = atof(argv[1]); argc--; argv++; ok = true; } if ((ok == false) && (strcmp(argv[1], "-scalar") == 0)) { argc--; argv++; son = 1; ok = true; } if ((ok == false) && (strcmp(argv[1], "-abs") == 0)) { argc--; argv++; abson = 1; ok = true; } if ((ok == false) && (strcmp(argv[1], "-blur") == 0)) { argc--; argv++; blur = 1; ok = true; } if (ok == false) { cerr << "Can't parse argument " << argv[1] << endl; usage(); } } // Allocate memory for intensity profile if(son) profile = new double[1]; else profile = new double[2*n+1]; // Read model vtkPolyDataReader *reader = vtkPolyDataReader::New(); reader->SetFileName(input_name); reader->Modified(); reader->Update(); vtkPolyData *model = vtkPolyData::New(); model = reader->GetOutput(); model->Update(); // Extract normals if (model->GetPointData()->GetNormals() == NULL) { cerr << "Model has no normals" << endl; exit(1); } // Read image irtkGreyImage image; image.Read(image_name); irtkLinearInterpolateImageFunction interpolator; interpolator.SetInput(&image); interpolator.Initialize(); // Allocate memory if(!son){ if(count_name){ vtkPolyDataReader *reader_count = vtkPolyDataReader::New(); reader_count->SetFileName(count_name); reader_count->Modified(); reader_count->Update(); vtkPolyData *model_count = vtkPolyData::New(); model_count = reader_count->GetOutput(); model_count->Update(); vtkDoubleArray *array = vtkDoubleArray::New(); array->SetNumberOfTuples(model->GetNumberOfPoints()); array->SetNumberOfComponents(1); array->SetName("IntensityCountProfile"); vtkDoubleArray *narray = vtkDoubleArray::New(); narray->SetNumberOfTuples(model->GetNumberOfPoints()); narray->SetNumberOfComponents(1); narray->SetName("IntensityCountProfile"); int count2; // Build a locator vtkPointLocator *pointLocator = vtkPointLocator::New(); pointLocator->SetDataSet(reader_count->GetOutput()); pointLocator->BuildLocator(); for (i = 0; i < model->GetNumberOfPoints(); i++) { double distance,point2[3]; model->GetPoints()->GetPoint (i, point); vtkIdType ptId; ptId = pointLocator->FindClosestPoint(point); model_count->GetPoints()->GetPoint(ptId,point2); normal[0] = point2[0] - point[0]; normal[1] = point2[1] - point[1]; normal[2] = point2[2] - point[2]; distance = sqrt(pow(normal[0],2)+pow(normal[1],2)+pow(normal[2],2)); if(distance > 0){ for(j = 0; j < 3; j++){ normal[j] = normal[j] / distance; } ds = distance / n; count = 0; count2 = 0; for (j = 0; j < n; j++) { x = point[0] + (j + 1) * ds * normal[0]; y = point[1] + (j + 1) * ds * normal[1]; z = point[2] + (j + 1) * ds * normal[2]; image.WorldToImage(x,y,z); if(interpolator.Evaluate(x, y, z) >= 0){ count += interpolator.Evaluate(x, y, z); count2 ++; } } } if(count2 > 0){ count = count / count2; } array->InsertTupleValue(i, &count); } // blur if(blur == 1){ for (i = 0; i < model->GetNumberOfPoints(); i++) { vtkIdList *list = vtkIdList::New(); //Find neighbor GetConnectedVertices(model,i,list); //Get number of neighbor n = list->GetNumberOfIds(); double value = 0, *tmp; for (j = 0; j < n; j++){ tmp = array->GetTuple(list->GetId(j)); value += *tmp; } //stretch measure relative change of the vertices spacing count = value / n; narray->InsertTupleValue(i, &count); list->Delete(); } } model->GetPointData()->SetScalars(array); array->Delete(); narray->Delete(); reader_count->Delete(); }else{ vtkDoubleArray *array = vtkDoubleArray::New(); array->SetNumberOfTuples(model->GetNumberOfPoints()); array->SetNumberOfComponents(2*n+1); array->SetName("IntensityProfile"); for (i = 0; i < model->GetNumberOfPoints(); i++) { model->GetPoints()->GetPoint (i, point); model->GetPointData()->GetNormals()->GetTuple(i, normal); for (j = 0; j < 2*n+1; j++) { x = point[0] + (j - n) * ds * normal[0]; y = point[1] + (j - n) * ds * normal[1]; z = point[2] + (j - n) * ds * normal[2]; image.WorldToImage(x,y,z); if(abson) profile[j] = abs(interpolator.Evaluate(x, y, z)); else profile[j] = interpolator.Evaluate(x, y, z); } array->InsertTupleValue(i, profile); } model->GetPointData()->SetScalars(array); array->Delete(); } }else{ vtkDoubleArray *array = vtkDoubleArray::New(); array->SetNumberOfTuples(model->GetNumberOfPoints()); array->SetNumberOfComponents(1); array->SetName("IntensityValue"); for (i = 0; i < model->GetNumberOfPoints(); i++) { model->GetPoints()->GetPoint (i, point); image.WorldToImage(point[0], point[1], point[2]); if(abson) *profile = abs(interpolator.Evaluate(point[0], point[1], point[2])); else *profile = interpolator.Evaluate(point[0], point[1], point[2]); array->InsertTupleValue(i, profile); } model->GetPointData()->SetScalars(array); array->Delete(); } vtkPolyDataWriter *writer = vtkPolyDataWriter::New(); writer->SetInput(model); writer->SetFileName(output_name); writer->Write(); reader->Delete(); delete []profile; } #else #include <irtkImage.h> int main( int argc, char *argv[] ) { cerr << argv[0] << " this program needs to be compiled with vtk enabled." << endl; return 0; } #endif <|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 "arrow/gpu/cuda_memory.h" #include <algorithm> #include <cstdint> #include <cstdlib> #include <memory> #include <mutex> #include <cuda.h> #include "arrow/buffer.h" #include "arrow/io/memory.h" #include "arrow/status.h" #include "arrow/util/logging.h" #include "arrow/gpu/cuda_common.h" #include "arrow/gpu/cuda_context.h" namespace arrow { namespace cuda { // ---------------------------------------------------------------------- // CUDA IPC memory handle struct CudaIpcMemHandle::CudaIpcMemHandleImpl { explicit CudaIpcMemHandleImpl(const uint8_t* handle) { memcpy(&memory_size, handle, sizeof(memory_size)); if (memory_size != 0) memcpy(&ipc_handle, handle + sizeof(memory_size), sizeof(CUipcMemHandle)); } explicit CudaIpcMemHandleImpl(int64_t memory_size, const void* cu_handle) : memory_size(memory_size) { if (memory_size != 0) memcpy(&ipc_handle, cu_handle, sizeof(CUipcMemHandle)); } CUipcMemHandle ipc_handle; /// initialized only when memory_size != 0 int64_t memory_size; /// size of the memory that ipc_handle refers to }; CudaIpcMemHandle::CudaIpcMemHandle(const void* handle) { impl_.reset(new CudaIpcMemHandleImpl(reinterpret_cast<const uint8_t*>(handle))); } CudaIpcMemHandle::CudaIpcMemHandle(int64_t memory_size, const void* cu_handle) { impl_.reset(new CudaIpcMemHandleImpl(memory_size, cu_handle)); } CudaIpcMemHandle::~CudaIpcMemHandle() {} Status CudaIpcMemHandle::FromBuffer(const void* opaque_handle, std::shared_ptr<CudaIpcMemHandle>* handle) { *handle = std::shared_ptr<CudaIpcMemHandle>(new CudaIpcMemHandle(opaque_handle)); return Status::OK(); } Status CudaIpcMemHandle::Serialize(MemoryPool* pool, std::shared_ptr<Buffer>* out) const { std::shared_ptr<Buffer> buffer; int64_t size = impl_->memory_size; size_t kHandleSize = (size > 0 ? sizeof(int64_t) + sizeof(CUipcMemHandle) : sizeof(int64_t)); RETURN_NOT_OK(AllocateBuffer(pool, static_cast<int64_t>(kHandleSize), &buffer)); memcpy(buffer->mutable_data(), &impl_->memory_size, sizeof(impl_->memory_size)); if (size > 0) memcpy(buffer->mutable_data() + sizeof(impl_->memory_size), &impl_->ipc_handle, sizeof(impl_->ipc_handle)); *out = buffer; return Status::OK(); } const void* CudaIpcMemHandle::handle() const { return &impl_->ipc_handle; } int64_t CudaIpcMemHandle::memory_size() const { return impl_->memory_size; } // ---------------------------------------------------------------------- CudaBuffer::CudaBuffer(uint8_t* data, int64_t size, const std::shared_ptr<CudaContext>& context, bool own_data, bool is_ipc) : Buffer(data, size), context_(context), own_data_(own_data), is_ipc_(is_ipc) { is_mutable_ = true; mutable_data_ = data; } CudaBuffer::~CudaBuffer() { DCHECK(Close().ok()); } Status CudaBuffer::Close() { if (own_data_) { if (is_ipc_) { return context_->CloseIpcBuffer(this); } else { return context_->Free(mutable_data_, size_); } } return Status::OK(); } CudaBuffer::CudaBuffer(const std::shared_ptr<CudaBuffer>& parent, const int64_t offset, const int64_t size) : Buffer(parent, offset, size), context_(parent->context()), own_data_(false), is_ipc_(false) { if (parent->is_mutable()) { is_mutable_ = true; mutable_data_ = const_cast<uint8_t*>(data_); } } Status CudaBuffer::FromBuffer(std::shared_ptr<Buffer> buffer, std::shared_ptr<CudaBuffer>* out) { int64_t offset = 0, size = buffer->size(); bool is_mutable = buffer->is_mutable(); // The original CudaBuffer may have been wrapped in another Buffer // (for example through slicing). while (!(*out = std::dynamic_pointer_cast<CudaBuffer>(buffer))) { const std::shared_ptr<Buffer> parent = buffer->parent(); if (!parent) { return Status::TypeError("buffer is not backed by a CudaBuffer"); } offset += buffer->data() - parent->data(); buffer = parent; } // Re-slice to represent the same memory area if (offset != 0 || (*out)->size() != size || !is_mutable) { *out = std::make_shared<CudaBuffer>(*out, offset, size); (*out)->is_mutable_ = is_mutable; } return Status::OK(); } Status CudaBuffer::CopyToHost(const int64_t position, const int64_t nbytes, void* out) const { return context_->CopyDeviceToHost(out, data_ + position, nbytes); } Status CudaBuffer::CopyFromHost(const int64_t position, const void* data, int64_t nbytes) { DCHECK_LE(nbytes, size_ - position) << "Copy would overflow buffer"; return context_->CopyHostToDevice(mutable_data_ + position, data, nbytes); } Status CudaBuffer::CopyFromDevice(const int64_t position, const void* data, int64_t nbytes) { DCHECK_LE(nbytes, size_ - position) << "Copy would overflow buffer"; return context_->CopyDeviceToDevice(mutable_data_ + position, data, nbytes); } Status CudaBuffer::ExportForIpc(std::shared_ptr<CudaIpcMemHandle>* handle) { if (is_ipc_) { return Status::Invalid("Buffer has already been exported for IPC"); } RETURN_NOT_OK(context_->ExportIpcBuffer(mutable_data_, size_, handle)); own_data_ = false; return Status::OK(); } CudaHostBuffer::~CudaHostBuffer() { CudaDeviceManager* manager = nullptr; DCHECK(CudaDeviceManager::GetInstance(&manager).ok()); DCHECK(manager->FreeHost(mutable_data_, size_).ok()); } // ---------------------------------------------------------------------- // CudaBufferReader CudaBufferReader::CudaBufferReader(const std::shared_ptr<Buffer>& buffer) : io::BufferReader(buffer) { if (!CudaBuffer::FromBuffer(buffer, &cuda_buffer_).ok()) { throw std::bad_cast(); } context_ = cuda_buffer_->context(); } CudaBufferReader::~CudaBufferReader() {} Status CudaBufferReader::Read(int64_t nbytes, int64_t* bytes_read, void* buffer) { nbytes = std::min(nbytes, size_ - position_); *bytes_read = nbytes; RETURN_NOT_OK(context_->CopyDeviceToHost(buffer, data_ + position_, nbytes)); position_ += nbytes; return Status::OK(); } Status CudaBufferReader::Read(int64_t nbytes, std::shared_ptr<Buffer>* out) { int64_t size = std::min(nbytes, size_ - position_); *out = std::make_shared<CudaBuffer>(cuda_buffer_, position_, size); position_ += size; return Status::OK(); } // ---------------------------------------------------------------------- // CudaBufferWriter class CudaBufferWriter::CudaBufferWriterImpl { public: explicit CudaBufferWriterImpl(const std::shared_ptr<CudaBuffer>& buffer) : context_(buffer->context()), buffer_(buffer), buffer_size_(0), buffer_position_(0) { buffer_ = buffer; DCHECK(buffer->is_mutable()) << "Must pass mutable buffer"; mutable_data_ = buffer->mutable_data(); size_ = buffer->size(); position_ = 0; } Status Seek(int64_t position) { if (position < 0 || position >= size_) { return Status::IOError("position out of bounds"); } position_ = position; return Status::OK(); } Status Close() { if (!closed_) { closed_ = true; RETURN_NOT_OK(Flush()); } return Status::OK(); } Status Flush() { if (buffer_size_ > 0 && buffer_position_ > 0) { // Only need to flush when the write has been buffered RETURN_NOT_OK( context_->CopyHostToDevice(mutable_data_ + position_ - buffer_position_, host_buffer_data_, buffer_position_)); buffer_position_ = 0; } return Status::OK(); } bool closed() const { return closed_; } Status Tell(int64_t* position) const { *position = position_; return Status::OK(); } Status Write(const void* data, int64_t nbytes) { if (nbytes == 0) { return Status::OK(); } if (buffer_size_ > 0) { if (nbytes + buffer_position_ >= buffer_size_) { // Reach end of buffer, write everything RETURN_NOT_OK(Flush()); RETURN_NOT_OK( context_->CopyHostToDevice(mutable_data_ + position_, data, nbytes)); } else { // Write bytes to buffer std::memcpy(host_buffer_data_ + buffer_position_, data, nbytes); buffer_position_ += nbytes; } } else { // Unbuffered write RETURN_NOT_OK(context_->CopyHostToDevice(mutable_data_ + position_, data, nbytes)); } position_ += nbytes; return Status::OK(); } Status WriteAt(int64_t position, const void* data, int64_t nbytes) { std::lock_guard<std::mutex> guard(lock_); RETURN_NOT_OK(Seek(position)); return Write(data, nbytes); } Status SetBufferSize(const int64_t buffer_size) { if (buffer_position_ > 0) { // Flush any buffered data RETURN_NOT_OK(Flush()); } RETURN_NOT_OK(AllocateCudaHostBuffer(context_.get()->device_number(), buffer_size, &host_buffer_)); host_buffer_data_ = host_buffer_->mutable_data(); buffer_size_ = buffer_size; return Status::OK(); } int64_t buffer_size() const { return buffer_size_; } int64_t buffer_position() const { return buffer_position_; } private: std::shared_ptr<CudaContext> context_; std::shared_ptr<CudaBuffer> buffer_; std::mutex lock_; uint8_t* mutable_data_; int64_t size_; int64_t position_; bool closed_; // Pinned host buffer for buffering writes on CPU before calling cudaMalloc int64_t buffer_size_; int64_t buffer_position_; std::shared_ptr<CudaHostBuffer> host_buffer_; uint8_t* host_buffer_data_; }; CudaBufferWriter::CudaBufferWriter(const std::shared_ptr<CudaBuffer>& buffer) { impl_.reset(new CudaBufferWriterImpl(buffer)); } CudaBufferWriter::~CudaBufferWriter() {} Status CudaBufferWriter::Close() { return impl_->Close(); } bool CudaBufferWriter::closed() const { return impl_->closed(); } Status CudaBufferWriter::Flush() { return impl_->Flush(); } Status CudaBufferWriter::Seek(int64_t position) { if (impl_->buffer_position() > 0) { RETURN_NOT_OK(Flush()); } return impl_->Seek(position); } Status CudaBufferWriter::Tell(int64_t* position) const { return impl_->Tell(position); } Status CudaBufferWriter::Write(const void* data, int64_t nbytes) { return impl_->Write(data, nbytes); } Status CudaBufferWriter::WriteAt(int64_t position, const void* data, int64_t nbytes) { return impl_->WriteAt(position, data, nbytes); } Status CudaBufferWriter::SetBufferSize(const int64_t buffer_size) { return impl_->SetBufferSize(buffer_size); } int64_t CudaBufferWriter::buffer_size() const { return impl_->buffer_size(); } int64_t CudaBufferWriter::num_bytes_buffered() const { return impl_->buffer_position(); } // ---------------------------------------------------------------------- Status AllocateCudaHostBuffer(int device_number, const int64_t size, std::shared_ptr<CudaHostBuffer>* out) { CudaDeviceManager* manager = nullptr; RETURN_NOT_OK(CudaDeviceManager::GetInstance(&manager)); return manager->AllocateHost(device_number, size, out); } } // namespace cuda } // namespace arrow <commit_msg>ARROW-3879: [C++] Fix uninitialized member in CudaBufferWriter<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 "arrow/gpu/cuda_memory.h" #include <algorithm> #include <cstdint> #include <cstdlib> #include <memory> #include <mutex> #include <cuda.h> #include "arrow/buffer.h" #include "arrow/io/memory.h" #include "arrow/status.h" #include "arrow/util/logging.h" #include "arrow/gpu/cuda_common.h" #include "arrow/gpu/cuda_context.h" namespace arrow { namespace cuda { // ---------------------------------------------------------------------- // CUDA IPC memory handle struct CudaIpcMemHandle::CudaIpcMemHandleImpl { explicit CudaIpcMemHandleImpl(const uint8_t* handle) { memcpy(&memory_size, handle, sizeof(memory_size)); if (memory_size != 0) memcpy(&ipc_handle, handle + sizeof(memory_size), sizeof(CUipcMemHandle)); } explicit CudaIpcMemHandleImpl(int64_t memory_size, const void* cu_handle) : memory_size(memory_size) { if (memory_size != 0) memcpy(&ipc_handle, cu_handle, sizeof(CUipcMemHandle)); } CUipcMemHandle ipc_handle; /// initialized only when memory_size != 0 int64_t memory_size; /// size of the memory that ipc_handle refers to }; CudaIpcMemHandle::CudaIpcMemHandle(const void* handle) { impl_.reset(new CudaIpcMemHandleImpl(reinterpret_cast<const uint8_t*>(handle))); } CudaIpcMemHandle::CudaIpcMemHandle(int64_t memory_size, const void* cu_handle) { impl_.reset(new CudaIpcMemHandleImpl(memory_size, cu_handle)); } CudaIpcMemHandle::~CudaIpcMemHandle() {} Status CudaIpcMemHandle::FromBuffer(const void* opaque_handle, std::shared_ptr<CudaIpcMemHandle>* handle) { *handle = std::shared_ptr<CudaIpcMemHandle>(new CudaIpcMemHandle(opaque_handle)); return Status::OK(); } Status CudaIpcMemHandle::Serialize(MemoryPool* pool, std::shared_ptr<Buffer>* out) const { std::shared_ptr<Buffer> buffer; int64_t size = impl_->memory_size; size_t kHandleSize = (size > 0 ? sizeof(int64_t) + sizeof(CUipcMemHandle) : sizeof(int64_t)); RETURN_NOT_OK(AllocateBuffer(pool, static_cast<int64_t>(kHandleSize), &buffer)); memcpy(buffer->mutable_data(), &impl_->memory_size, sizeof(impl_->memory_size)); if (size > 0) memcpy(buffer->mutable_data() + sizeof(impl_->memory_size), &impl_->ipc_handle, sizeof(impl_->ipc_handle)); *out = buffer; return Status::OK(); } const void* CudaIpcMemHandle::handle() const { return &impl_->ipc_handle; } int64_t CudaIpcMemHandle::memory_size() const { return impl_->memory_size; } // ---------------------------------------------------------------------- CudaBuffer::CudaBuffer(uint8_t* data, int64_t size, const std::shared_ptr<CudaContext>& context, bool own_data, bool is_ipc) : Buffer(data, size), context_(context), own_data_(own_data), is_ipc_(is_ipc) { is_mutable_ = true; mutable_data_ = data; } CudaBuffer::~CudaBuffer() { DCHECK(Close().ok()); } Status CudaBuffer::Close() { if (own_data_) { if (is_ipc_) { return context_->CloseIpcBuffer(this); } else { return context_->Free(mutable_data_, size_); } } return Status::OK(); } CudaBuffer::CudaBuffer(const std::shared_ptr<CudaBuffer>& parent, const int64_t offset, const int64_t size) : Buffer(parent, offset, size), context_(parent->context()), own_data_(false), is_ipc_(false) { if (parent->is_mutable()) { is_mutable_ = true; mutable_data_ = const_cast<uint8_t*>(data_); } } Status CudaBuffer::FromBuffer(std::shared_ptr<Buffer> buffer, std::shared_ptr<CudaBuffer>* out) { int64_t offset = 0, size = buffer->size(); bool is_mutable = buffer->is_mutable(); // The original CudaBuffer may have been wrapped in another Buffer // (for example through slicing). while (!(*out = std::dynamic_pointer_cast<CudaBuffer>(buffer))) { const std::shared_ptr<Buffer> parent = buffer->parent(); if (!parent) { return Status::TypeError("buffer is not backed by a CudaBuffer"); } offset += buffer->data() - parent->data(); buffer = parent; } // Re-slice to represent the same memory area if (offset != 0 || (*out)->size() != size || !is_mutable) { *out = std::make_shared<CudaBuffer>(*out, offset, size); (*out)->is_mutable_ = is_mutable; } return Status::OK(); } Status CudaBuffer::CopyToHost(const int64_t position, const int64_t nbytes, void* out) const { return context_->CopyDeviceToHost(out, data_ + position, nbytes); } Status CudaBuffer::CopyFromHost(const int64_t position, const void* data, int64_t nbytes) { DCHECK_LE(nbytes, size_ - position) << "Copy would overflow buffer"; return context_->CopyHostToDevice(mutable_data_ + position, data, nbytes); } Status CudaBuffer::CopyFromDevice(const int64_t position, const void* data, int64_t nbytes) { DCHECK_LE(nbytes, size_ - position) << "Copy would overflow buffer"; return context_->CopyDeviceToDevice(mutable_data_ + position, data, nbytes); } Status CudaBuffer::ExportForIpc(std::shared_ptr<CudaIpcMemHandle>* handle) { if (is_ipc_) { return Status::Invalid("Buffer has already been exported for IPC"); } RETURN_NOT_OK(context_->ExportIpcBuffer(mutable_data_, size_, handle)); own_data_ = false; return Status::OK(); } CudaHostBuffer::~CudaHostBuffer() { CudaDeviceManager* manager = nullptr; DCHECK(CudaDeviceManager::GetInstance(&manager).ok()); DCHECK(manager->FreeHost(mutable_data_, size_).ok()); } // ---------------------------------------------------------------------- // CudaBufferReader CudaBufferReader::CudaBufferReader(const std::shared_ptr<Buffer>& buffer) : io::BufferReader(buffer) { if (!CudaBuffer::FromBuffer(buffer, &cuda_buffer_).ok()) { throw std::bad_cast(); } context_ = cuda_buffer_->context(); } CudaBufferReader::~CudaBufferReader() {} Status CudaBufferReader::Read(int64_t nbytes, int64_t* bytes_read, void* buffer) { nbytes = std::min(nbytes, size_ - position_); *bytes_read = nbytes; RETURN_NOT_OK(context_->CopyDeviceToHost(buffer, data_ + position_, nbytes)); position_ += nbytes; return Status::OK(); } Status CudaBufferReader::Read(int64_t nbytes, std::shared_ptr<Buffer>* out) { int64_t size = std::min(nbytes, size_ - position_); *out = std::make_shared<CudaBuffer>(cuda_buffer_, position_, size); position_ += size; return Status::OK(); } // ---------------------------------------------------------------------- // CudaBufferWriter class CudaBufferWriter::CudaBufferWriterImpl { public: explicit CudaBufferWriterImpl(const std::shared_ptr<CudaBuffer>& buffer) : context_(buffer->context()), buffer_(buffer), buffer_size_(0), buffer_position_(0) { buffer_ = buffer; DCHECK(buffer->is_mutable()) << "Must pass mutable buffer"; mutable_data_ = buffer->mutable_data(); size_ = buffer->size(); position_ = 0; closed_ = false; } #define CHECK_CLOSED() \ if (closed_) { \ return Status::Invalid("Operation on closed CudaBufferWriter"); \ } Status Seek(int64_t position) { CHECK_CLOSED(); if (position < 0 || position >= size_) { return Status::IOError("position out of bounds"); } position_ = position; return Status::OK(); } Status Close() { if (!closed_) { closed_ = true; RETURN_NOT_OK(FlushInternal()); } return Status::OK(); } Status Flush() { CHECK_CLOSED(); return FlushInternal(); } Status FlushInternal() { if (buffer_size_ > 0 && buffer_position_ > 0) { // Only need to flush when the write has been buffered RETURN_NOT_OK( context_->CopyHostToDevice(mutable_data_ + position_ - buffer_position_, host_buffer_data_, buffer_position_)); buffer_position_ = 0; } return Status::OK(); } bool closed() const { return closed_; } Status Tell(int64_t* position) const { CHECK_CLOSED(); *position = position_; return Status::OK(); } Status Write(const void* data, int64_t nbytes) { CHECK_CLOSED(); if (nbytes == 0) { return Status::OK(); } if (buffer_size_ > 0) { if (nbytes + buffer_position_ >= buffer_size_) { // Reach end of buffer, write everything RETURN_NOT_OK(Flush()); RETURN_NOT_OK( context_->CopyHostToDevice(mutable_data_ + position_, data, nbytes)); } else { // Write bytes to buffer std::memcpy(host_buffer_data_ + buffer_position_, data, nbytes); buffer_position_ += nbytes; } } else { // Unbuffered write RETURN_NOT_OK(context_->CopyHostToDevice(mutable_data_ + position_, data, nbytes)); } position_ += nbytes; return Status::OK(); } Status WriteAt(int64_t position, const void* data, int64_t nbytes) { std::lock_guard<std::mutex> guard(lock_); CHECK_CLOSED(); RETURN_NOT_OK(Seek(position)); return Write(data, nbytes); } Status SetBufferSize(const int64_t buffer_size) { CHECK_CLOSED(); if (buffer_position_ > 0) { // Flush any buffered data RETURN_NOT_OK(Flush()); } RETURN_NOT_OK(AllocateCudaHostBuffer(context_.get()->device_number(), buffer_size, &host_buffer_)); host_buffer_data_ = host_buffer_->mutable_data(); buffer_size_ = buffer_size; return Status::OK(); } int64_t buffer_size() const { return buffer_size_; } int64_t buffer_position() const { return buffer_position_; } #undef CHECK_CLOSED private: std::shared_ptr<CudaContext> context_; std::shared_ptr<CudaBuffer> buffer_; std::mutex lock_; uint8_t* mutable_data_; int64_t size_; int64_t position_; bool closed_; // Pinned host buffer for buffering writes on CPU before calling cudaMalloc int64_t buffer_size_; int64_t buffer_position_; std::shared_ptr<CudaHostBuffer> host_buffer_; uint8_t* host_buffer_data_; }; CudaBufferWriter::CudaBufferWriter(const std::shared_ptr<CudaBuffer>& buffer) { impl_.reset(new CudaBufferWriterImpl(buffer)); } CudaBufferWriter::~CudaBufferWriter() {} Status CudaBufferWriter::Close() { return impl_->Close(); } bool CudaBufferWriter::closed() const { return impl_->closed(); } Status CudaBufferWriter::Flush() { return impl_->Flush(); } Status CudaBufferWriter::Seek(int64_t position) { if (impl_->buffer_position() > 0) { RETURN_NOT_OK(Flush()); } return impl_->Seek(position); } Status CudaBufferWriter::Tell(int64_t* position) const { return impl_->Tell(position); } Status CudaBufferWriter::Write(const void* data, int64_t nbytes) { return impl_->Write(data, nbytes); } Status CudaBufferWriter::WriteAt(int64_t position, const void* data, int64_t nbytes) { return impl_->WriteAt(position, data, nbytes); } Status CudaBufferWriter::SetBufferSize(const int64_t buffer_size) { return impl_->SetBufferSize(buffer_size); } int64_t CudaBufferWriter::buffer_size() const { return impl_->buffer_size(); } int64_t CudaBufferWriter::num_bytes_buffered() const { return impl_->buffer_position(); } // ---------------------------------------------------------------------- Status AllocateCudaHostBuffer(int device_number, const int64_t size, std::shared_ptr<CudaHostBuffer>* out) { CudaDeviceManager* manager = nullptr; RETURN_NOT_OK(CudaDeviceManager::GetInstance(&manager)); return manager->AllocateHost(device_number, size, out); } } // namespace cuda } // namespace arrow <|endoftext|>
<commit_before>/* Copyright 2016-present Facebook, Inc. * Licensed under the Apache License, Version 2.0 */ #include "WatchmanConnection.h" #include <folly/ExceptionWrapper.h> #include <folly/SocketAddress.h> #include <folly/Subprocess.h> #include <folly/experimental/bser/Bser.h> #include <folly/futures/InlineExecutor.h> namespace watchman { using namespace folly::bser; using namespace folly; // Ordered with the most likely kind first static const std::vector<dynamic> kUnilateralLabels{"subscription", "log"}; static const dynamic kError("error"); static const dynamic kCapabilities("capabilities"); // We'll just dispatch bser decodes and callbacks inline unless they // give us an alternative environment static InlineExecutor inlineExecutor; WatchmanConnection::WatchmanConnection( EventBase* eventBase, Optional<std::string>&& sockPath, Optional<WatchmanConnection::Callback>&& callback, Executor* cpuExecutor) : eventBase_(eventBase), sockPath_(std::move(sockPath)), callback_(std::move(callback)), cpuExecutor_(cpuExecutor ? cpuExecutor : &inlineExecutor), versionCmd_(nullptr), bufQ_(IOBufQueue::cacheChainLength()) { CHECK_NOTNULL(eventBase); } WatchmanConnection::~WatchmanConnection() { close(); } folly::Future<std::string> WatchmanConnection::getSockPath() { // Take explicit configuration first if (sockPath_.hasValue()) { return makeFuture(sockPath_.value()); } // Else use the environmental variable used by watchman to report // the active socket path auto var = getenv("WATCHMAN_SOCK"); if (var && *var) { return makeFuture(std::string(var)); } return via(cpuExecutor_, [] { // Else discover it from the CLI folly::Subprocess proc( {"watchman", "--output-encoding=bser", "get-sockname"}, folly::Subprocess::Options().pipeStdout().pipeStderr().usePath()); SCOPE_FAIL { // Always clean up to avoid Subprocess asserting on destruction proc.kill(); proc.wait(); }; auto out_pair = proc.communicate(); auto result = parseBser(out_pair.first); proc.waitChecked(); return result["sockname"].asString(); }); } Future<dynamic> WatchmanConnection::connect(folly::dynamic versionArgs) { if (!versionArgs.isObject()) { throw WatchmanError("versionArgs must be object"); } versionCmd_ = folly::dynamic::array("version", versionArgs); auto res = getSockPath().then( [shared_this=shared_from_this()] (std::string&& path) { shared_this->eventBase_->runInEventBaseThread([=] { folly::SocketAddress addr; addr.setFromPath(path); shared_this->sock_ = folly::AsyncSocket::newSocket(shared_this->eventBase_); shared_this->sock_->connect(shared_this.get(), addr); } ); return shared_this->connectPromise_.getFuture(); }); return res; } void WatchmanConnection::close() { if (closing_) { return; } closing_ = true; if (sock_) { eventBase_->runImmediatelyOrRunInEventBaseThreadAndWait([this] { sock_->close(); sock_.reset(); }); } failQueuedCommands( make_exception_wrapper<WatchmanError>( "WatchmanConnection::close() was called")); } // The convention for Watchman responses is that they represent // an error if they contain the "error" key. We want to report // those as exceptions, but it is easier to do that via a Try Try<dynamic> WatchmanConnection::watchmanResponseToTry(dynamic&& value) { auto error = value.get_ptr(kError); if (error) { return Try<dynamic>(make_exception_wrapper<WatchmanResponseError>(value)); } return Try<dynamic>(std::move(value)); } void WatchmanConnection::connectSuccess() noexcept { try { sock_->setReadCB(this); sock_->setCloseOnExec(); run(versionCmd_).then( [shared_this=shared_from_this()] (dynamic&& result) { // If there is no "capabilities" key then the version of // watchman is too old; treat this as an error if (!result.get_ptr(kCapabilities)) { result["error"] = "This watchman server has no support for capabilities, " "please upgrade to the current stable version of watchman"; shared_this->connectPromise_.setTry( shared_this->watchmanResponseToTry(std::move(result))); return; } shared_this->connectPromise_.setValue(std::move(result)); } ).onError( [shared_this=shared_from_this()] (const folly::exception_wrapper& e) { shared_this->connectPromise_.setException(e); } ); } catch(const std::exception& e) { connectPromise_.setException( folly::exception_wrapper(std::current_exception(), e)); } catch(...) { connectPromise_.setException( folly::exception_wrapper(std::current_exception())); } } void WatchmanConnection::connectErr( const folly::AsyncSocketException& ex) noexcept { connectPromise_.setException(ex); } WatchmanConnection::QueuedCommand::QueuedCommand(const dynamic& command) : cmd(command) {} Future<dynamic> WatchmanConnection::run(const dynamic& command) noexcept { auto cmd = std::make_shared<QueuedCommand>(command); if (broken_) { cmd->promise.setException(WatchmanError("The connection was broken")); return cmd->promise.getFuture(); } if (!sock_) { cmd->promise.setException(WatchmanError( "No socket (did you call connect() and check result for exceptions?)")); return cmd->promise.getFuture(); } bool shouldWrite; { std::lock_guard<std::mutex> g(mutex_); // We only need to call sendCommand if we don't have a command in // progress; the completion handler will trigger it once we receive // the response shouldWrite = commandQ_.empty(); commandQ_.push_back(cmd); } if (shouldWrite) { eventBase_->runInEventBaseThread( [shared_this=shared_from_this()] { shared_this->sendCommand(); } ); } return cmd->promise.getFuture(); } // Generate a failure for all queued commands void WatchmanConnection::failQueuedCommands( const folly::exception_wrapper& ex) { std::lock_guard<std::mutex> g(mutex_); auto q = commandQ_; commandQ_.clear(); broken_ = true; for (auto& cmd : q) { if (!cmd->promise.isFulfilled()) { cmd->promise.setException(ex); } } // If the user has explicitly closed the connection no need for callback if (callback_ && !closing_) { cpuExecutor_->add([shared_this=shared_from_this(), ex] { (*(shared_this->callback_))(folly::Try<folly::dynamic>(ex)); }); } } // Sends the next eligible command to the Watchman service void WatchmanConnection::sendCommand(bool pop) { std::shared_ptr<QueuedCommand> cmd; { std::lock_guard<std::mutex> g(mutex_); if (pop) { // We finished processing this one, discard it and focus // on the next item, if any. commandQ_.pop_front(); } if (commandQ_.empty()) { return; } cmd = commandQ_.front(); } sock_->writeChain(this, toBserIOBuf(cmd->cmd, serialization_opts())); } void WatchmanConnection::popAndSendCommand() { sendCommand(/* pop = */ true); } // Called when AsyncSocket::writeChain completes void WatchmanConnection::writeSuccess() noexcept { // Don't care particularly } // Called when AsyncSocket::writeChain fails void WatchmanConnection::writeErr( size_t, const folly::AsyncSocketException& ex) noexcept { failQueuedCommands(ex); } // Called when AsyncSocket wants to give us data void WatchmanConnection::getReadBuffer(void** bufReturn, size_t* lenReturn) { std::lock_guard<std::mutex> g(mutex_); const auto ret = bufQ_.preallocate(2048, 2048); *bufReturn = ret.first; *lenReturn = ret.second; } // Called when AsyncSocket gave us data void WatchmanConnection::readDataAvailable(size_t len) noexcept { { std::lock_guard<std::mutex> g(mutex_); bufQ_.postallocate(len); } cpuExecutor_->add([shared_this=shared_from_this()] { shared_this->decodeNextResponse(); }); } std::unique_ptr<folly::IOBuf> WatchmanConnection::splitNextPdu() { std::lock_guard<std::mutex> g(mutex_); if (!bufQ_.front()) { return nullptr; } // Do we have enough data to decode the next item? size_t pdu_len = 0; try { pdu_len = decodePduLength(bufQ_.front()); } catch (const std::out_of_range&) { // Don't have enough data yet return nullptr; } if (pdu_len > bufQ_.chainLength()) { // Don't have enough data yet return nullptr; } // Remove the PDU blob from the front of the chain return bufQ_.split(pdu_len); } // Try to peel off one or more PDU's from our buffer queue. // Decode each complete PDU from BSER -> dynamic and dispatch // either the associated QueuedCommand or to the callback_ for // unilateral responses. // This is executed via the cpuExecutor. We only allow one // thread to carry out the decoding at a time so that the callbacks // are triggered in the order that they are received. It is possible // for us to receive a large PDU followed by a small one and for the // small one to finish decoding before the large one, so we must // serialize the dispatching. void WatchmanConnection::decodeNextResponse() { { std::lock_guard<std::mutex> g(mutex_); if (decoding_) { return; } decoding_ = true; } SCOPE_EXIT { std::lock_guard<std::mutex> g(mutex_); decoding_ = false; }; while (true) { auto pdu = splitNextPdu(); if (!pdu) { return; } try { auto decoded = parseBser(pdu.get()); bool is_unilateral = false; // Check for a unilateral response for (const auto& k : kUnilateralLabels) { if (decoded.get_ptr(k)) { // This is a unilateral response if (callback_.hasValue()) { callback_.value()(watchmanResponseToTry(std::move(decoded))); is_unilateral = true; break; } // No callback; usage error :-/ failQueuedCommands( std::runtime_error("No unilateral callback has been installed")); return; } } if (is_unilateral) { continue; } // It's actually a command response; get the cmd so that we // can fulfil its promise std::shared_ptr<QueuedCommand> cmd; { std::lock_guard<std::mutex> g(mutex_); if (commandQ_.empty()) { failQueuedCommands( std::runtime_error("No commands have been queued")); return; } cmd = commandQ_.front(); } // Dispatch outside of the lock in case it tries to send another // command cmd->promise.setTry(watchmanResponseToTry(std::move(decoded))); // Now we're in a position to send the next queued command. // We remove it after dispatching the try above in case that // queued up more commands; we want to be the one thing that // is responsible for sending the next queued command here popAndSendCommand(); } catch (const std::exception& ex) { failQueuedCommands(ex); return; } } } // Called when AsyncSocket hits EOF void WatchmanConnection::readEOF() noexcept { failQueuedCommands( std::system_error(ENOTCONN, std::system_category(), "connection closed")); } // Called when AsyncSocket has a read error void WatchmanConnection::readErr( const folly::AsyncSocketException& ex) noexcept { failQueuedCommands(ex); } } // namespace watchman <commit_msg>move InlineExecutor, ManualExecutor, and GlobalThreadPoolList to<commit_after>/* Copyright 2016-present Facebook, Inc. * Licensed under the Apache License, Version 2.0 */ #include "WatchmanConnection.h" #include <folly/ExceptionWrapper.h> #include <folly/SocketAddress.h> #include <folly/Subprocess.h> #include <folly/executors/InlineExecutor.h> #include <folly/experimental/bser/Bser.h> namespace watchman { using namespace folly::bser; using namespace folly; // Ordered with the most likely kind first static const std::vector<dynamic> kUnilateralLabels{"subscription", "log"}; static const dynamic kError("error"); static const dynamic kCapabilities("capabilities"); // We'll just dispatch bser decodes and callbacks inline unless they // give us an alternative environment static InlineExecutor inlineExecutor; WatchmanConnection::WatchmanConnection( EventBase* eventBase, Optional<std::string>&& sockPath, Optional<WatchmanConnection::Callback>&& callback, Executor* cpuExecutor) : eventBase_(eventBase), sockPath_(std::move(sockPath)), callback_(std::move(callback)), cpuExecutor_(cpuExecutor ? cpuExecutor : &inlineExecutor), versionCmd_(nullptr), bufQ_(IOBufQueue::cacheChainLength()) { CHECK_NOTNULL(eventBase); } WatchmanConnection::~WatchmanConnection() { close(); } folly::Future<std::string> WatchmanConnection::getSockPath() { // Take explicit configuration first if (sockPath_.hasValue()) { return makeFuture(sockPath_.value()); } // Else use the environmental variable used by watchman to report // the active socket path auto var = getenv("WATCHMAN_SOCK"); if (var && *var) { return makeFuture(std::string(var)); } return via(cpuExecutor_, [] { // Else discover it from the CLI folly::Subprocess proc( {"watchman", "--output-encoding=bser", "get-sockname"}, folly::Subprocess::Options().pipeStdout().pipeStderr().usePath()); SCOPE_FAIL { // Always clean up to avoid Subprocess asserting on destruction proc.kill(); proc.wait(); }; auto out_pair = proc.communicate(); auto result = parseBser(out_pair.first); proc.waitChecked(); return result["sockname"].asString(); }); } Future<dynamic> WatchmanConnection::connect(folly::dynamic versionArgs) { if (!versionArgs.isObject()) { throw WatchmanError("versionArgs must be object"); } versionCmd_ = folly::dynamic::array("version", versionArgs); auto res = getSockPath().then( [shared_this=shared_from_this()] (std::string&& path) { shared_this->eventBase_->runInEventBaseThread([=] { folly::SocketAddress addr; addr.setFromPath(path); shared_this->sock_ = folly::AsyncSocket::newSocket(shared_this->eventBase_); shared_this->sock_->connect(shared_this.get(), addr); } ); return shared_this->connectPromise_.getFuture(); }); return res; } void WatchmanConnection::close() { if (closing_) { return; } closing_ = true; if (sock_) { eventBase_->runImmediatelyOrRunInEventBaseThreadAndWait([this] { sock_->close(); sock_.reset(); }); } failQueuedCommands( make_exception_wrapper<WatchmanError>( "WatchmanConnection::close() was called")); } // The convention for Watchman responses is that they represent // an error if they contain the "error" key. We want to report // those as exceptions, but it is easier to do that via a Try Try<dynamic> WatchmanConnection::watchmanResponseToTry(dynamic&& value) { auto error = value.get_ptr(kError); if (error) { return Try<dynamic>(make_exception_wrapper<WatchmanResponseError>(value)); } return Try<dynamic>(std::move(value)); } void WatchmanConnection::connectSuccess() noexcept { try { sock_->setReadCB(this); sock_->setCloseOnExec(); run(versionCmd_).then( [shared_this=shared_from_this()] (dynamic&& result) { // If there is no "capabilities" key then the version of // watchman is too old; treat this as an error if (!result.get_ptr(kCapabilities)) { result["error"] = "This watchman server has no support for capabilities, " "please upgrade to the current stable version of watchman"; shared_this->connectPromise_.setTry( shared_this->watchmanResponseToTry(std::move(result))); return; } shared_this->connectPromise_.setValue(std::move(result)); } ).onError( [shared_this=shared_from_this()] (const folly::exception_wrapper& e) { shared_this->connectPromise_.setException(e); } ); } catch(const std::exception& e) { connectPromise_.setException( folly::exception_wrapper(std::current_exception(), e)); } catch(...) { connectPromise_.setException( folly::exception_wrapper(std::current_exception())); } } void WatchmanConnection::connectErr( const folly::AsyncSocketException& ex) noexcept { connectPromise_.setException(ex); } WatchmanConnection::QueuedCommand::QueuedCommand(const dynamic& command) : cmd(command) {} Future<dynamic> WatchmanConnection::run(const dynamic& command) noexcept { auto cmd = std::make_shared<QueuedCommand>(command); if (broken_) { cmd->promise.setException(WatchmanError("The connection was broken")); return cmd->promise.getFuture(); } if (!sock_) { cmd->promise.setException(WatchmanError( "No socket (did you call connect() and check result for exceptions?)")); return cmd->promise.getFuture(); } bool shouldWrite; { std::lock_guard<std::mutex> g(mutex_); // We only need to call sendCommand if we don't have a command in // progress; the completion handler will trigger it once we receive // the response shouldWrite = commandQ_.empty(); commandQ_.push_back(cmd); } if (shouldWrite) { eventBase_->runInEventBaseThread( [shared_this=shared_from_this()] { shared_this->sendCommand(); } ); } return cmd->promise.getFuture(); } // Generate a failure for all queued commands void WatchmanConnection::failQueuedCommands( const folly::exception_wrapper& ex) { std::lock_guard<std::mutex> g(mutex_); auto q = commandQ_; commandQ_.clear(); broken_ = true; for (auto& cmd : q) { if (!cmd->promise.isFulfilled()) { cmd->promise.setException(ex); } } // If the user has explicitly closed the connection no need for callback if (callback_ && !closing_) { cpuExecutor_->add([shared_this=shared_from_this(), ex] { (*(shared_this->callback_))(folly::Try<folly::dynamic>(ex)); }); } } // Sends the next eligible command to the Watchman service void WatchmanConnection::sendCommand(bool pop) { std::shared_ptr<QueuedCommand> cmd; { std::lock_guard<std::mutex> g(mutex_); if (pop) { // We finished processing this one, discard it and focus // on the next item, if any. commandQ_.pop_front(); } if (commandQ_.empty()) { return; } cmd = commandQ_.front(); } sock_->writeChain(this, toBserIOBuf(cmd->cmd, serialization_opts())); } void WatchmanConnection::popAndSendCommand() { sendCommand(/* pop = */ true); } // Called when AsyncSocket::writeChain completes void WatchmanConnection::writeSuccess() noexcept { // Don't care particularly } // Called when AsyncSocket::writeChain fails void WatchmanConnection::writeErr( size_t, const folly::AsyncSocketException& ex) noexcept { failQueuedCommands(ex); } // Called when AsyncSocket wants to give us data void WatchmanConnection::getReadBuffer(void** bufReturn, size_t* lenReturn) { std::lock_guard<std::mutex> g(mutex_); const auto ret = bufQ_.preallocate(2048, 2048); *bufReturn = ret.first; *lenReturn = ret.second; } // Called when AsyncSocket gave us data void WatchmanConnection::readDataAvailable(size_t len) noexcept { { std::lock_guard<std::mutex> g(mutex_); bufQ_.postallocate(len); } cpuExecutor_->add([shared_this=shared_from_this()] { shared_this->decodeNextResponse(); }); } std::unique_ptr<folly::IOBuf> WatchmanConnection::splitNextPdu() { std::lock_guard<std::mutex> g(mutex_); if (!bufQ_.front()) { return nullptr; } // Do we have enough data to decode the next item? size_t pdu_len = 0; try { pdu_len = decodePduLength(bufQ_.front()); } catch (const std::out_of_range&) { // Don't have enough data yet return nullptr; } if (pdu_len > bufQ_.chainLength()) { // Don't have enough data yet return nullptr; } // Remove the PDU blob from the front of the chain return bufQ_.split(pdu_len); } // Try to peel off one or more PDU's from our buffer queue. // Decode each complete PDU from BSER -> dynamic and dispatch // either the associated QueuedCommand or to the callback_ for // unilateral responses. // This is executed via the cpuExecutor. We only allow one // thread to carry out the decoding at a time so that the callbacks // are triggered in the order that they are received. It is possible // for us to receive a large PDU followed by a small one and for the // small one to finish decoding before the large one, so we must // serialize the dispatching. void WatchmanConnection::decodeNextResponse() { { std::lock_guard<std::mutex> g(mutex_); if (decoding_) { return; } decoding_ = true; } SCOPE_EXIT { std::lock_guard<std::mutex> g(mutex_); decoding_ = false; }; while (true) { auto pdu = splitNextPdu(); if (!pdu) { return; } try { auto decoded = parseBser(pdu.get()); bool is_unilateral = false; // Check for a unilateral response for (const auto& k : kUnilateralLabels) { if (decoded.get_ptr(k)) { // This is a unilateral response if (callback_.hasValue()) { callback_.value()(watchmanResponseToTry(std::move(decoded))); is_unilateral = true; break; } // No callback; usage error :-/ failQueuedCommands( std::runtime_error("No unilateral callback has been installed")); return; } } if (is_unilateral) { continue; } // It's actually a command response; get the cmd so that we // can fulfil its promise std::shared_ptr<QueuedCommand> cmd; { std::lock_guard<std::mutex> g(mutex_); if (commandQ_.empty()) { failQueuedCommands( std::runtime_error("No commands have been queued")); return; } cmd = commandQ_.front(); } // Dispatch outside of the lock in case it tries to send another // command cmd->promise.setTry(watchmanResponseToTry(std::move(decoded))); // Now we're in a position to send the next queued command. // We remove it after dispatching the try above in case that // queued up more commands; we want to be the one thing that // is responsible for sending the next queued command here popAndSendCommand(); } catch (const std::exception& ex) { failQueuedCommands(ex); return; } } } // Called when AsyncSocket hits EOF void WatchmanConnection::readEOF() noexcept { failQueuedCommands( std::system_error(ENOTCONN, std::system_category(), "connection closed")); } // Called when AsyncSocket has a read error void WatchmanConnection::readErr( const folly::AsyncSocketException& ex) noexcept { failQueuedCommands(ex); } } // namespace watchman <|endoftext|>
<commit_before>/** * Multiplicative hashing * ====================== * * Based on the golden ratio, so A.K.A. Fibonacci hashing. Simple, fast, but * frequent to collide. */ #include <iostream> uint32_t mulhash32(uint32_t h, int shift) { return (h * 2654435769u) >> shift; } uint64_t mulhash64(uint64_t h, int shift) { return (h * 11400714819323198485llu) >> shift; } int main() { int shift = 64 - 3; // Naively check the distribution. std::cout << mulhash32(0, shift) << std::endl; std::cout << mulhash32(1, shift) << std::endl; std::cout << mulhash32(2, shift) << std::endl; std::cout << mulhash32(3, shift) << std::endl; std::cout << mulhash32(4, shift) << std::endl; std::cout << mulhash32(5, shift) << std::endl; std::cout << mulhash32(6, shift) << std::endl; std::cout << mulhash32(7, shift) << std::endl; std::cout << "---" << std::endl; std::cout << mulhash64(0, shift) << std::endl; std::cout << mulhash64(1, shift) << std::endl; std::cout << mulhash64(2, shift) << std::endl; std::cout << mulhash64(3, shift) << std::endl; std::cout << mulhash64(4, shift) << std::endl; std::cout << mulhash64(5, shift) << std::endl; std::cout << mulhash64(6, shift) << std::endl; std::cout << mulhash64(7, shift) << std::endl; return 0; } <commit_msg>updated mulhash: test cases<commit_after>/** * Multiplicative hashing * ====================== * * Based on the golden ratio, hence A.K.A. Fibonacci hashing. Simple, fast, * but not well evenly-distributed. */ #include <iostream> #include <array> uint32_t mulhash32(uint32_t h, int shift) { return (h * 2654435769u) >> shift; } uint64_t mulhash64(uint64_t h, int shift) { return (h * 11400714819323198485llu) >> shift; } #define LEN 8 #define N 64 template <typename T> void debug(std::array<T, LEN> arr) { if constexpr (std::is_same_v<T, uint32_t>) { std::cout << "mulhash32="; } else { std::cout << "mulhash64="; } std::cout << "["; for (const auto& a : arr) { std::cout << a << ","; } std::cout << "\b]" << std::endl; } int main() { int shift = 64 - 3; std::array<uint32_t, LEN> arr32{}; std::array<uint64_t, LEN> arr64{}; // Naively check the distribution. for (int i = 0; i < N; ++i) ++arr32[mulhash32(i, shift)]; debug(arr32); for (int i = 0; i < N; ++i) ++arr64[mulhash64(i, shift)]; debug(arr64); return 0; } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <string> // basic_string(const basic_string& str, const Allocator& alloc); #include <string> #include <cassert> #include "test_macros.h" #include "test_allocator.h" #include "min_allocator.h" template <class T> struct alloc_imp { bool active; alloc_imp() : active(true) {} T* allocate(std::size_t n) { if (active) return static_cast<T*>(std::malloc(n * sizeof(T))); else throw std::bad_alloc(); } void deallocate(T* p, std::size_t) { std::free(p); } void activate () { active = true; } void deactivate() { active = false; } }; template <class T> struct poca_alloc { typedef T value_type; typedef std::true_type propagate_on_container_copy_assignment; alloc_imp<T> *imp; poca_alloc(alloc_imp<T> *ximp) : imp (ximp) {} template <class U> poca_alloc(const poca_alloc<U>& other) : imp(other.imp) {} T* allocate (std::size_t n) { return imp->allocate(n);} void deallocate(T* p, std::size_t n) { imp->deallocate(p, n); } }; template <typename T, typename U> bool operator==(const poca_alloc<T>& lhs, const poca_alloc<U>& rhs) { return lhs.imp == rhs.imp; } template <typename T, typename U> bool operator!=(const poca_alloc<T>& lhs, const poca_alloc<U>& rhs) { return lhs.imp != rhs.imp; } template <class S> void test(S s1, const typename S::allocator_type& a) { S s2(s1, a); LIBCPP_ASSERT(s2.__invariants()); assert(s2 == s1); assert(s2.capacity() >= s2.size()); assert(s2.get_allocator() == a); } #ifndef TEST_HAS_NO_EXCEPTIONS template <class S> void test_assign(S &s1, const S& s2) { try { s1 = s2; } catch ( std::bad_alloc &) { return; } assert(false); } #endif int main() { { typedef test_allocator<char> A; typedef std::basic_string<char, std::char_traits<char>, A> S; test(S(), A(3)); test(S("1"), A(5)); test(S("1234567890123456789012345678901234567890123456789012345678901234567890"), A(7)); } #if TEST_STD_VER >= 11 { typedef min_allocator<char> A; typedef std::basic_string<char, std::char_traits<char>, A> S; test(S(), A()); test(S("1"), A()); test(S("1234567890123456789012345678901234567890123456789012345678901234567890"), A()); } #ifndef TEST_HAS_NO_EXCEPTIONS { typedef poca_alloc<char> A; typedef std::basic_string<char, std::char_traits<char>, A> S; const char * p1 = "This is my first string"; const char * p2 = "This is my second string"; alloc_imp<char> imp1; alloc_imp<char> imp2; S s1(p1, A(&imp1)); S s2(p2, A(&imp2)); assert(s1 == p1); assert(s2 == p2); imp2.deactivate(); test_assign(s1, s2); assert(s1 == p1); assert(s2 == p2); } #endif #endif } <commit_msg>Fix up some no-exception compile failures<commit_after>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <string> // basic_string(const basic_string& str, const Allocator& alloc); #include <string> #include <cassert> #include "test_macros.h" #include "test_allocator.h" #include "min_allocator.h" #ifndef TEST_HAS_NO_EXCEPTIONS template <class T> struct alloc_imp { bool active; alloc_imp() : active(true) {} T* allocate(std::size_t n) { if (active) return static_cast<T*>(std::malloc(n * sizeof(T))); else throw std::bad_alloc(); } void deallocate(T* p, std::size_t) { std::free(p); } void activate () { active = true; } void deactivate() { active = false; } }; template <class T> struct poca_alloc { typedef T value_type; typedef std::true_type propagate_on_container_copy_assignment; alloc_imp<T> *imp; poca_alloc(alloc_imp<T> *imp_) : imp (imp_) {} template <class U> poca_alloc(const poca_alloc<U>& other) : imp(other.imp) {} T* allocate (std::size_t n) { return imp->allocate(n);} void deallocate(T* p, std::size_t n) { imp->deallocate(p, n); } }; template <typename T, typename U> bool operator==(const poca_alloc<T>& lhs, const poca_alloc<U>& rhs) { return lhs.imp == rhs.imp; } template <typename T, typename U> bool operator!=(const poca_alloc<T>& lhs, const poca_alloc<U>& rhs) { return lhs.imp != rhs.imp; } template <class S> void test_assign(S &s1, const S& s2) { try { s1 = s2; } catch ( std::bad_alloc &) { return; } assert(false); } #endif template <class S> void test(S s1, const typename S::allocator_type& a) { S s2(s1, a); LIBCPP_ASSERT(s2.__invariants()); assert(s2 == s1); assert(s2.capacity() >= s2.size()); assert(s2.get_allocator() == a); } int main() { { typedef test_allocator<char> A; typedef std::basic_string<char, std::char_traits<char>, A> S; test(S(), A(3)); test(S("1"), A(5)); test(S("1234567890123456789012345678901234567890123456789012345678901234567890"), A(7)); } #if TEST_STD_VER >= 11 { typedef min_allocator<char> A; typedef std::basic_string<char, std::char_traits<char>, A> S; test(S(), A()); test(S("1"), A()); test(S("1234567890123456789012345678901234567890123456789012345678901234567890"), A()); } #ifndef TEST_HAS_NO_EXCEPTIONS { typedef poca_alloc<char> A; typedef std::basic_string<char, std::char_traits<char>, A> S; const char * p1 = "This is my first string"; const char * p2 = "This is my second string"; alloc_imp<char> imp1; alloc_imp<char> imp2; S s1(p1, A(&imp1)); S s2(p2, A(&imp2)); assert(s1 == p1); assert(s2 == p2); imp2.deactivate(); test_assign(s1, s2); assert(s1 == p1); assert(s2 == p2); } #endif #endif } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sddll.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: rt $ $Date: 2006-05-02 15:03:04 $ * * 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 _EEITEM_HXX //autogen #include <svx/eeitem.hxx> #endif #include <svx/editeng.hxx> #ifndef _SVDOBJ_HXX //autogen #include <svx/svdobj.hxx> #endif #ifndef INCLUDED_SVTOOLS_MODULEOPTIONS_HXX #include <svtools/moduleoptions.hxx> #endif #ifndef _FM_FMOBJFAC_HXX #include <svx/fmobjfac.hxx> #endif #ifndef _SVX_SIIMPORT_HXX #include <svx/siimport.hxx> #endif #ifndef _SVDFIELD_HXX #include <svx/svdfield.hxx> #endif #ifndef _OBJFAC3D_HXX #include <svx/objfac3d.hxx> #endif #pragma hdrstop #include "sddll.hxx" #ifndef SD_DRAW_DOC_SHELL_HXX #include "DrawDocShell.hxx" #endif #ifndef SD_GRAPHIC_DOC_SHELL_HXX #include "GraphicDocShell.hxx" #endif #include "sdresid.hxx" #include "sdobjfac.hxx" #include "cfgids.hxx" #include "strmname.h" #include "SdShapeTypes.hxx" #include <svx/SvxShapeTypes.hxx> #include <sfx2/docfilt.hxx> #include <sfx2/docfile.hxx> #include <sfx2/fcontnr.hxx> #include <tools/urlobj.hxx> #include <svx/impgrf.hxx> #include <svtools/FilterConfigItem.hxx> #ifndef _COM_SUN_STAR_UTIL_XARCHIVER_HPP_ #include <com/sun/star/util/XArchiver.hpp> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif using namespace ::rtl; using namespace ::com::sun::star; /************************************************************************* |* |* Init |* \************************************************************************/ void SdDLL::Init() { if ( SD_MOD() ) return; SfxObjectFactory* pDrawFact = NULL; SfxObjectFactory* pImpressFact = NULL; if (SvtModuleOptions().IsImpress()) pImpressFact = &::sd::DrawDocShell::Factory(); if (SvtModuleOptions().IsDraw()) pDrawFact = &::sd::GraphicDocShell::Factory(); // the SdModule must be created SdModule** ppShlPtr = (SdModule**) GetAppData(SHL_DRAW); // #i46427# // The SfxModule::SfxModule stops when the first given factory // is 0, so we must not give a 0 as first factory if( pImpressFact ) { (*ppShlPtr) = new SdModule( pImpressFact, pDrawFact ); } else { (*ppShlPtr) = new SdModule( pDrawFact, pImpressFact ); } if (SvtModuleOptions().IsImpress()) { // Register the Impress shape types in order to make the shapes accessible. ::accessibility::RegisterImpressShapeTypes (); ::sd::DrawDocShell::Factory().SetDocumentServiceName( String( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.presentation.PresentationDocument" ) ) ); } if (SvtModuleOptions().IsDraw()) { ::sd::GraphicDocShell::Factory().SetDocumentServiceName( String( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.drawing.DrawingDocument" ) ) ); } // register your view-factories here RegisterFactorys(); // register your shell-interfaces here RegisterInterfaces(); // register your controllers here RegisterControllers(); // SvDraw-Felder registrieren SdrRegisterFieldClasses(); // 3D-Objekt-Factory eintragen E3dObjFactory(); // ::com::sun::star::form::component::Form-Objekt-Factory eintragen FmFormObjFactory(); // factory for dummy import of old si-controls in 3.1 documents //BFS02 SiImportFactory(); // Objekt-Factory eintragen SdrObjFactory::InsertMakeUserDataHdl(LINK(&aSdObjectFactory, SdObjectFactory, MakeUserData)); } /************************************************************************* |* |* Exit |* \************************************************************************/ void SdDLL::Exit() { // called directly befor unloading the DLL // do whatever you want, Sd-DLL is accessible // Objekt-Factory austragen SdrObjFactory::RemoveMakeUserDataHdl(LINK(&aSdObjectFactory, SdObjectFactory, MakeUserData)); // the SdModule must be destroyed SdModule** ppShlPtr = (SdModule**) GetAppData(SHL_DRAW); delete (*ppShlPtr); (*ppShlPtr) = NULL; } /* ULONG SdDLL::DetectFilter(SfxMedium& rMedium, const SfxFilter** ppFilter, SfxFilterFlags nMust, SfxFilterFlags nDont) { ULONG nReturn = ERRCODE_ABORT; // Erkennung fehlgeschlagen, Filter ungueltig BOOL bStorage = FALSE; if( *ppFilter && (*ppFilter)->GetFilterFlags() & SFX_FILTER_PACKED ) { uno::Reference< lang::XMultiServiceFactory > xSMgr( ::comphelper::getProcessServiceFactory() ); uno::Reference< util::XArchiver > xPacker( xSMgr->createInstance( OUString::createFromAscii( "com.sun.star.util.Archiver" ) ), uno::UNO_QUERY ); if( xPacker.is() ) { // extract extra data OUString aPath( rMedium.GetOrigURL() ); OUString aExtraData( xPacker->getExtraData( aPath ) ); const OUString aSig1= OUString::createFromAscii( "private:" ); String aTmp; aTmp += sal_Unicode( '?' ); aTmp += String::CreateFromAscii("simpress"); const OUString aSig2( aTmp ); INT32 nIndex1 = aExtraData.indexOf( aSig1 ); INT32 nIndex2 = aExtraData.indexOf( aSig2 ); if( nIndex1 == 0 && nIndex2 != -1 ) return ERRCODE_NONE; } } else if (rMedium.GetError() == SVSTREAM_OK) { if ( rMedium.IsStorage() ) { bStorage = TRUE; SotStorageRef xStorage = rMedium.GetStorage(); if ( !xStorage.Is() ) return ULONG_MAX; if( SvtModuleOptions().IsImpress() ) { // Erkennung ueber contained streams (PowerPoint 97-Filter) String aStreamName = UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "PowerPoint Document" ) ); if ( xStorage->IsContained( aStreamName ) && xStorage->IsStream( aStreamName ) ) { String aFileName(rMedium.GetName()); aFileName.ToUpperAscii(); if( aFileName.SearchAscii( ".POT" ) == STRING_NOTFOUND ) *ppFilter = SfxFilter::GetFilterByName( pFilterPowerPoint97); else *ppFilter = SfxFilter::GetFilterByName( pFilterPowerPoint97Template ); return ERRCODE_NONE; } } const SfxFilter* pFilter = *ppFilter; if ( *ppFilter ) { if ( (*ppFilter)->GetFormat() == xStorage->GetFormat() ) pFilter = *ppFilter; } if( !pFilter && SvtModuleOptions().IsImpress() ) { SfxFilterMatcher aMatcher( String::CreateFromAscii("simpress") ); pFilter = aMatcher.GetFilter4ClipBoardId( xStorage->GetFormat() ); if ( pFilter ) *ppFilter = pFilter; } if( !pFilter && SvtModuleOptions().IsDraw() ) { SfxFilterMatcher aMatcher( String::CreateFromAscii("sdraw") ); pFilter = aMatcher.GetFilter4ClipBoardId( xStorage->GetFormat() ); if ( pFilter ) *ppFilter = pFilter; } if ( pFilter && ( pFilter->GetFilterFlags() & nMust ) == nMust && ( pFilter->GetFilterFlags() & nDont ) == 0 ) { *ppFilter = pFilter; nReturn = ERRCODE_NONE; } else { *ppFilter = NULL; nReturn = ERRCODE_NONE; } } String aFileName( rMedium.GetName() ); aFileName.ToUpperAscii(); if ( nReturn == ERRCODE_ABORT ) { if( bStorage ) // aber keine Clipboard-Id #55337# { *ppFilter = NULL; } else { // Vektorgraphik? SvStream* pStm = rMedium.GetInStream(); if( !pStm ) nReturn = ERRCODE_IO_GENERAL; else { pStm->Seek( STREAM_SEEK_TO_BEGIN ); const String aFileName( rMedium.GetURLObject().GetMainURL( INetURLObject::NO_DECODE ) ); GraphicDescriptor aDesc( *pStm, &aFileName ); GraphicFilter* pGrfFilter = GetGrfFilter(); if( !aDesc.Detect( FALSE ) ) { if( SvtModuleOptions().IsImpress() ) { *ppFilter = NULL; nReturn = ERRCODE_ABORT; INetURLObject aURL( aFileName ); if( aURL.getExtension().equalsIgnoreAsciiCaseAscii( "cgm" ) ) { sal_uInt8 n8; pStm->Seek( STREAM_SEEK_TO_BEGIN ); *pStm >> n8; if ( ( n8 & 0xf0 ) == 0 ) // we are supporting binary cgm format only, so { // this is a small test to exclude cgm text const String aName = UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "CGM - Computer Graphics Metafile" ) ); SfxFilterMatcher aMatch( String::CreateFromAscii("simpress") ); *ppFilter = aMatch.GetFilter4FilterName( aName ); nReturn = ERRCODE_NONE; } } } } else { if( SvtModuleOptions().IsDraw() ) { String aShortName( aDesc.GetImportFormatShortName( aDesc.GetFileFormat() ) ); const String aName( pGrfFilter->GetImportFormatTypeName( pGrfFilter->GetImportFormatNumberForShortName( aShortName ) ) ); if ( *ppFilter && aShortName.EqualsIgnoreCaseAscii( "PCD" ) ) // there is a multiple pcd selection possible { sal_Int32 nBase = 2; // default Base0 String aFilterTypeName( (*ppFilter)->GetRealTypeName() ); if ( aFilterTypeName.CompareToAscii( "pcd_Photo_CD_Base4" ) == COMPARE_EQUAL ) nBase = 1; else if ( aFilterTypeName.CompareToAscii( "pcd_Photo_CD_Base16" ) == COMPARE_EQUAL ) nBase = 0; String aFilterConfigPath( RTL_CONSTASCII_USTRINGPARAM( "Office.Common/Filter/Graphic/Import/PCD" ) ); FilterConfigItem aFilterConfigItem( aFilterConfigPath ); aFilterConfigItem.WriteInt32( String( RTL_CONSTASCII_USTRINGPARAM( "Resolution" ) ), nBase ); } SfxFilterMatcher aMatch( String::CreateFromAscii("draw") ); *ppFilter = aMatch.GetFilter4FilterName( aName ); nReturn = ERRCODE_NONE; } else { nReturn = ERRCODE_ABORT; *ppFilter = NULL; } } } } } } else { nReturn = rMedium.GetError(); } return nReturn; } */ <commit_msg>INTEGRATION: CWS rt16 (1.13.80); FILE MERGED 2006/08/08 12:17:07 rt 1.13.80.1: #i68214# Obsolete svx headers removed<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sddll.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: ihi $ $Date: 2006-08-29 14:19:08 $ * * 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 _EEITEM_HXX //autogen #include <svx/eeitem.hxx> #endif #include <svx/editeng.hxx> #ifndef _SVDOBJ_HXX //autogen #include <svx/svdobj.hxx> #endif #ifndef INCLUDED_SVTOOLS_MODULEOPTIONS_HXX #include <svtools/moduleoptions.hxx> #endif #ifndef _FM_FMOBJFAC_HXX #include <svx/fmobjfac.hxx> #endif #ifndef _SVDFIELD_HXX #include <svx/svdfield.hxx> #endif #ifndef _OBJFAC3D_HXX #include <svx/objfac3d.hxx> #endif #pragma hdrstop #include "sddll.hxx" #ifndef SD_DRAW_DOC_SHELL_HXX #include "DrawDocShell.hxx" #endif #ifndef SD_GRAPHIC_DOC_SHELL_HXX #include "GraphicDocShell.hxx" #endif #include "sdresid.hxx" #include "sdobjfac.hxx" #include "cfgids.hxx" #include "strmname.h" #include "SdShapeTypes.hxx" #include <svx/SvxShapeTypes.hxx> #include <sfx2/docfilt.hxx> #include <sfx2/docfile.hxx> #include <sfx2/fcontnr.hxx> #include <tools/urlobj.hxx> #include <svx/impgrf.hxx> #include <svtools/FilterConfigItem.hxx> #ifndef _COM_SUN_STAR_UTIL_XARCHIVER_HPP_ #include <com/sun/star/util/XArchiver.hpp> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif using namespace ::rtl; using namespace ::com::sun::star; /************************************************************************* |* |* Init |* \************************************************************************/ void SdDLL::Init() { if ( SD_MOD() ) return; SfxObjectFactory* pDrawFact = NULL; SfxObjectFactory* pImpressFact = NULL; if (SvtModuleOptions().IsImpress()) pImpressFact = &::sd::DrawDocShell::Factory(); if (SvtModuleOptions().IsDraw()) pDrawFact = &::sd::GraphicDocShell::Factory(); // the SdModule must be created SdModule** ppShlPtr = (SdModule**) GetAppData(SHL_DRAW); // #i46427# // The SfxModule::SfxModule stops when the first given factory // is 0, so we must not give a 0 as first factory if( pImpressFact ) { (*ppShlPtr) = new SdModule( pImpressFact, pDrawFact ); } else { (*ppShlPtr) = new SdModule( pDrawFact, pImpressFact ); } if (SvtModuleOptions().IsImpress()) { // Register the Impress shape types in order to make the shapes accessible. ::accessibility::RegisterImpressShapeTypes (); ::sd::DrawDocShell::Factory().SetDocumentServiceName( String( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.presentation.PresentationDocument" ) ) ); } if (SvtModuleOptions().IsDraw()) { ::sd::GraphicDocShell::Factory().SetDocumentServiceName( String( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.drawing.DrawingDocument" ) ) ); } // register your view-factories here RegisterFactorys(); // register your shell-interfaces here RegisterInterfaces(); // register your controllers here RegisterControllers(); // SvDraw-Felder registrieren SdrRegisterFieldClasses(); // 3D-Objekt-Factory eintragen E3dObjFactory(); // ::com::sun::star::form::component::Form-Objekt-Factory eintragen FmFormObjFactory(); // factory for dummy import of old si-controls in 3.1 documents //BFS02 SiImportFactory(); // Objekt-Factory eintragen SdrObjFactory::InsertMakeUserDataHdl(LINK(&aSdObjectFactory, SdObjectFactory, MakeUserData)); } /************************************************************************* |* |* Exit |* \************************************************************************/ void SdDLL::Exit() { // called directly befor unloading the DLL // do whatever you want, Sd-DLL is accessible // Objekt-Factory austragen SdrObjFactory::RemoveMakeUserDataHdl(LINK(&aSdObjectFactory, SdObjectFactory, MakeUserData)); // the SdModule must be destroyed SdModule** ppShlPtr = (SdModule**) GetAppData(SHL_DRAW); delete (*ppShlPtr); (*ppShlPtr) = NULL; } /* ULONG SdDLL::DetectFilter(SfxMedium& rMedium, const SfxFilter** ppFilter, SfxFilterFlags nMust, SfxFilterFlags nDont) { ULONG nReturn = ERRCODE_ABORT; // Erkennung fehlgeschlagen, Filter ungueltig BOOL bStorage = FALSE; if( *ppFilter && (*ppFilter)->GetFilterFlags() & SFX_FILTER_PACKED ) { uno::Reference< lang::XMultiServiceFactory > xSMgr( ::comphelper::getProcessServiceFactory() ); uno::Reference< util::XArchiver > xPacker( xSMgr->createInstance( OUString::createFromAscii( "com.sun.star.util.Archiver" ) ), uno::UNO_QUERY ); if( xPacker.is() ) { // extract extra data OUString aPath( rMedium.GetOrigURL() ); OUString aExtraData( xPacker->getExtraData( aPath ) ); const OUString aSig1= OUString::createFromAscii( "private:" ); String aTmp; aTmp += sal_Unicode( '?' ); aTmp += String::CreateFromAscii("simpress"); const OUString aSig2( aTmp ); INT32 nIndex1 = aExtraData.indexOf( aSig1 ); INT32 nIndex2 = aExtraData.indexOf( aSig2 ); if( nIndex1 == 0 && nIndex2 != -1 ) return ERRCODE_NONE; } } else if (rMedium.GetError() == SVSTREAM_OK) { if ( rMedium.IsStorage() ) { bStorage = TRUE; SotStorageRef xStorage = rMedium.GetStorage(); if ( !xStorage.Is() ) return ULONG_MAX; if( SvtModuleOptions().IsImpress() ) { // Erkennung ueber contained streams (PowerPoint 97-Filter) String aStreamName = UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "PowerPoint Document" ) ); if ( xStorage->IsContained( aStreamName ) && xStorage->IsStream( aStreamName ) ) { String aFileName(rMedium.GetName()); aFileName.ToUpperAscii(); if( aFileName.SearchAscii( ".POT" ) == STRING_NOTFOUND ) *ppFilter = SfxFilter::GetFilterByName( pFilterPowerPoint97); else *ppFilter = SfxFilter::GetFilterByName( pFilterPowerPoint97Template ); return ERRCODE_NONE; } } const SfxFilter* pFilter = *ppFilter; if ( *ppFilter ) { if ( (*ppFilter)->GetFormat() == xStorage->GetFormat() ) pFilter = *ppFilter; } if( !pFilter && SvtModuleOptions().IsImpress() ) { SfxFilterMatcher aMatcher( String::CreateFromAscii("simpress") ); pFilter = aMatcher.GetFilter4ClipBoardId( xStorage->GetFormat() ); if ( pFilter ) *ppFilter = pFilter; } if( !pFilter && SvtModuleOptions().IsDraw() ) { SfxFilterMatcher aMatcher( String::CreateFromAscii("sdraw") ); pFilter = aMatcher.GetFilter4ClipBoardId( xStorage->GetFormat() ); if ( pFilter ) *ppFilter = pFilter; } if ( pFilter && ( pFilter->GetFilterFlags() & nMust ) == nMust && ( pFilter->GetFilterFlags() & nDont ) == 0 ) { *ppFilter = pFilter; nReturn = ERRCODE_NONE; } else { *ppFilter = NULL; nReturn = ERRCODE_NONE; } } String aFileName( rMedium.GetName() ); aFileName.ToUpperAscii(); if ( nReturn == ERRCODE_ABORT ) { if( bStorage ) // aber keine Clipboard-Id #55337# { *ppFilter = NULL; } else { // Vektorgraphik? SvStream* pStm = rMedium.GetInStream(); if( !pStm ) nReturn = ERRCODE_IO_GENERAL; else { pStm->Seek( STREAM_SEEK_TO_BEGIN ); const String aFileName( rMedium.GetURLObject().GetMainURL( INetURLObject::NO_DECODE ) ); GraphicDescriptor aDesc( *pStm, &aFileName ); GraphicFilter* pGrfFilter = GetGrfFilter(); if( !aDesc.Detect( FALSE ) ) { if( SvtModuleOptions().IsImpress() ) { *ppFilter = NULL; nReturn = ERRCODE_ABORT; INetURLObject aURL( aFileName ); if( aURL.getExtension().equalsIgnoreAsciiCaseAscii( "cgm" ) ) { sal_uInt8 n8; pStm->Seek( STREAM_SEEK_TO_BEGIN ); *pStm >> n8; if ( ( n8 & 0xf0 ) == 0 ) // we are supporting binary cgm format only, so { // this is a small test to exclude cgm text const String aName = UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "CGM - Computer Graphics Metafile" ) ); SfxFilterMatcher aMatch( String::CreateFromAscii("simpress") ); *ppFilter = aMatch.GetFilter4FilterName( aName ); nReturn = ERRCODE_NONE; } } } } else { if( SvtModuleOptions().IsDraw() ) { String aShortName( aDesc.GetImportFormatShortName( aDesc.GetFileFormat() ) ); const String aName( pGrfFilter->GetImportFormatTypeName( pGrfFilter->GetImportFormatNumberForShortName( aShortName ) ) ); if ( *ppFilter && aShortName.EqualsIgnoreCaseAscii( "PCD" ) ) // there is a multiple pcd selection possible { sal_Int32 nBase = 2; // default Base0 String aFilterTypeName( (*ppFilter)->GetRealTypeName() ); if ( aFilterTypeName.CompareToAscii( "pcd_Photo_CD_Base4" ) == COMPARE_EQUAL ) nBase = 1; else if ( aFilterTypeName.CompareToAscii( "pcd_Photo_CD_Base16" ) == COMPARE_EQUAL ) nBase = 0; String aFilterConfigPath( RTL_CONSTASCII_USTRINGPARAM( "Office.Common/Filter/Graphic/Import/PCD" ) ); FilterConfigItem aFilterConfigItem( aFilterConfigPath ); aFilterConfigItem.WriteInt32( String( RTL_CONSTASCII_USTRINGPARAM( "Resolution" ) ), nBase ); } SfxFilterMatcher aMatch( String::CreateFromAscii("draw") ); *ppFilter = aMatch.GetFilter4FilterName( aName ); nReturn = ERRCODE_NONE; } else { nReturn = ERRCODE_ABORT; *ppFilter = NULL; } } } } } } else { nReturn = rMedium.GetError(); } return nReturn; } */ <|endoftext|>