QT_BEGIN_NAMESPACE /*! \class QBitArray \inmodule QtCore \brief The QBitArray class provides an array of bits. \ingroup tools \ingroup shared \reentrant A QBitArray is an array that gives access to individual bits and provides operators (\l{operator&()}{AND}, \l{operator|()}{OR}, \l{operator^()}{XOR}, and \l{operator~()}{NOT}) that work on entire arrays of bits. It uses \l{implicit sharing} (copy-on-write) to reduce memory usage and to avoid the needless copying of data. The following code constructs a QBitArray containing 200 bits initialized to false (0): \snippet code/src_corelib_tools_qbitarray.cpp 0 To initialize the bits to true, either pass \c true as second argument to the constructor, or call fill() later on. QBitArray uses 0-based indexes, just like C++ arrays. To access the bit at a particular index position, you can use operator[](). On non-const bit arrays, operator[]() returns a reference to a bit that can be used on the left side of an assignment. For example: \snippet code/src_corelib_tools_qbitarray.cpp 1 For technical reasons, it is more efficient to use testBit() and setBit() to access bits in the array than operator[](). For example: \snippet code/src_corelib_tools_qbitarray.cpp 2 QBitArray supports \c{&} (\l{operator&()}{AND}), \c{|} (\l{operator|()}{OR}), \c{^} (\l{operator^()}{XOR}), \c{~} (\l{operator~()}{NOT}), as well as \c{&=}, \c{|=}, and \c{^=}. These operators work in the same way as the built-in C++ bitwise operators of the same name. For example: \snippet code/src_corelib_tools_qbitarray.cpp 3 For historical reasons, QBitArray distinguishes between a null bit array and an empty bit array. A \e null bit array is a bit array that is initialized using QBitArray's default constructor. An \e empty bit array is any bit array with size 0. A null bit array is always empty, but an empty bit array isn't necessarily null: \snippet code/src_corelib_tools_qbitarray.cpp 4 All functions except isNull() treat null bit arrays the same as empty bit arrays; for example, QBitArray() compares equal to QBitArray(0). We recommend that you always use isEmpty() and avoid isNull(). \sa QByteArray, QVector */ /*! \fn QBitArray::QBitArray(QBitArray &&other) Move-constructs a QBitArray instance, making it point at the same object that \a other was pointing to. \since 5.2 */ /*! \fn QBitArray::QBitArray() Constructs an empty bit array. \sa isEmpty() */ /* * QBitArray construction note: * * We overallocate the byte array by 1 byte. The first user bit is at * d.data()[1]. On the extra first byte, we store the difference between the * number of bits in the byte array (including this byte) and the number of * bits in the bit array. Therefore, it's always a number between 8 and 15. * * This allows for fast calculation of the bit array size: * inline int size() const { return (d.size() << 3) - *d.constData(); } * * Note: for an array of zero size, *d.constData() is the QByteArray implicit NUL. */ /*! Constructs a bit array containing \a size bits. The bits are initialized with \a value, which defaults to false (0). */ QBitArray::QBitArray(int size, bool value) : d(size <= 0 ? 0 : 1 + (size + 7)/8, Qt::Uninitialized) { Q_ASSERT_X(size >= 0, "QBitArray::QBitArray", "Size must be greater than or equal to 0."); if (size <= 0) return; uchar* c = reinterpret_cast<uchar*>(d.data()); memset(c + 1, value ? 0xff : 0, d.size() - 1); *c = d.size()*8 - size; if (value && size && size % 8) *(c+1+size/8) &= (1 << (size%8)) - 1; }
IbanValidator::IbanValidator(QObject *parent) : QRegExpValidator(parent) { // initialze templates, copied from http://en.wikipedia.org/wiki/International_Bank_Account_Number // templates could also be read from an external text file or from a database // LibreOffice calc (German locale) formula to create the entries from the copied text of wikipedia: // ="ibanTemplate["&ZEILE()-2&"].country = QLatin1String("""&A21&"""); ibanTemplate["&ZEILE()-2&"].length = "&B21&"; ibanTemplate["&ZEILE()-2&"].format = QLatin1String("""&C21&"""); ibanTemplate["&ZEILE()-2&"].codes = QLatin1String("""&LINKS(D21;2)&""");" QList<IbanTemplate> ibanTemplate; ibanTemplate.reserve(56); for (int i(0); i < 56; ++i) ibanTemplate.append(IbanTemplate()); ibanTemplate[0].country = QLatin1String("Albania"); ibanTemplate[0].length = 28; ibanTemplate[0].format = QLatin1String("8n, 16c"); ibanTemplate[0].codes = QLatin1String("AL"); ibanTemplate[1].country = QLatin1String("Andorra"); ibanTemplate[1].length = 24; ibanTemplate[1].format = QLatin1String("8n,12c"); ibanTemplate[1].codes = QLatin1String("AD"); ibanTemplate[2].country = QLatin1String("Austria"); ibanTemplate[2].length = 20; ibanTemplate[2].format = QLatin1String("16n"); ibanTemplate[2].codes = QLatin1String("AT"); ibanTemplate[3].country = QLatin1String("Belgium"); ibanTemplate[3].length = 16; ibanTemplate[3].format = QLatin1String("12n"); ibanTemplate[3].codes = QLatin1String("BE"); ibanTemplate[4].country = QLatin1String("Bahrain"); ibanTemplate[4].length = 22; ibanTemplate[4].format = QLatin1String("4a,14c"); ibanTemplate[4].codes = QLatin1String("BH"); ibanTemplate[5].country = QLatin1String("Bosnia and Herzegovina"); ibanTemplate[5].length = 20; ibanTemplate[5].format = QLatin1String("16n"); ibanTemplate[5].codes = QLatin1String("BA"); ibanTemplate[6].country = QLatin1String("Bulgaria"); ibanTemplate[6].length = 22; ibanTemplate[6].format = QLatin1String("4a,6n,8c"); ibanTemplate[6].codes = QLatin1String("BG"); ibanTemplate[7].country = QLatin1String("Croatia"); ibanTemplate[7].length = 21; ibanTemplate[7].format = QLatin1String("17n"); ibanTemplate[7].codes = QLatin1String("HR"); ibanTemplate[8].country = QLatin1String("Cyprus"); ibanTemplate[8].length = 28; ibanTemplate[8].format = QLatin1String("8n,16c"); ibanTemplate[8].codes = QLatin1String("CY"); ibanTemplate[9].country = QLatin1String("Czech Republic"); ibanTemplate[9].length = 24; ibanTemplate[9].format = QLatin1String("20n"); ibanTemplate[9].codes = QLatin1String("CZ"); ibanTemplate[10].country = QLatin1String("Denmark"); ibanTemplate[10].length = 18; ibanTemplate[10].format = QLatin1String("14n"); ibanTemplate[10].codes = QLatin1String("DK"); ibanTemplate[11].country = QLatin1String("Dominican Republic"); ibanTemplate[11].length = 28; ibanTemplate[11].format = QLatin1String("4a,20n"); ibanTemplate[11].codes = QLatin1String("DO"); ibanTemplate[12].country = QLatin1String("Estonia"); ibanTemplate[12].length = 20; ibanTemplate[12].format = QLatin1String("16n"); ibanTemplate[12].codes = QLatin1String("EE"); ibanTemplate[13].country = QLatin1String("Faroe Islands"); ibanTemplate[13].length = 18; ibanTemplate[13].format = QLatin1String("14n"); ibanTemplate[13].codes = QLatin1String("FO"); ibanTemplate[14].country = QLatin1String("Finland"); ibanTemplate[14].length = 18; ibanTemplate[14].format = QLatin1String("14n"); ibanTemplate[14].codes = QLatin1String("FI"); ibanTemplate[15].country = QLatin1String("France"); ibanTemplate[15].length = 27; ibanTemplate[15].format = QLatin1String("10n,11c,2n"); ibanTemplate[15].codes = QLatin1String("FR, TF, PF, YT, NC, PM, WF"); ibanTemplate[16].country = QLatin1String("Georgia"); ibanTemplate[16].length = 22; ibanTemplate[16].format = QLatin1String("2c,16n"); ibanTemplate[16].codes = QLatin1String("GE"); ibanTemplate[17].country = QLatin1String("Germany"); ibanTemplate[17].length = 22; ibanTemplate[17].format = QLatin1String("18n"); ibanTemplate[17].codes = QLatin1String("DE"); ibanTemplate[18].country = QLatin1String("Gibraltar"); ibanTemplate[18].length = 23; ibanTemplate[18].format = QLatin1String("4a,15c"); ibanTemplate[18].codes = QLatin1String("GI"); ibanTemplate[19].country = QLatin1String("Greece"); ibanTemplate[19].length = 27; ibanTemplate[19].format = QLatin1String("7n,16c"); ibanTemplate[19].codes = QLatin1String("GR"); ibanTemplate[20].country = QLatin1String("Greenland[Note 1]"); ibanTemplate[20].length = 18; ibanTemplate[20].format = QLatin1String("14n"); ibanTemplate[20].codes = QLatin1String("GL"); ibanTemplate[21].country = QLatin1String("Hungary"); ibanTemplate[21].length = 28; ibanTemplate[21].format = QLatin1String("24n"); ibanTemplate[21].codes = QLatin1String("HU"); ibanTemplate[22].country = QLatin1String("Iceland"); ibanTemplate[22].length = 26; ibanTemplate[22].format = QLatin1String("22n"); ibanTemplate[22].codes = QLatin1String("IS"); ibanTemplate[23].country = QLatin1String("Ireland"); ibanTemplate[23].length = 22; ibanTemplate[23].format = QLatin1String("4c,14n"); ibanTemplate[23].codes = QLatin1String("IE"); ibanTemplate[24].country = QLatin1String("Israel"); ibanTemplate[24].length = 23; ibanTemplate[24].format = QLatin1String("19n"); ibanTemplate[24].codes = QLatin1String("IL"); ibanTemplate[25].country = QLatin1String("Italy"); ibanTemplate[25].length = 27; ibanTemplate[25].format = QLatin1String("1a,10n,12c"); ibanTemplate[25].codes = QLatin1String("IT"); ibanTemplate[26].country = QLatin1String("Kazakhstan"); ibanTemplate[26].length = 20; ibanTemplate[26].format = QLatin1String("3n,3c,10n"); ibanTemplate[26].codes = QLatin1String("KZ"); ibanTemplate[27].country = QLatin1String("Kuwait"); ibanTemplate[27].length = 30; ibanTemplate[27].format = QLatin1String("4a, 22n"); ibanTemplate[27].codes = QLatin1String("KW"); ibanTemplate[28].country = QLatin1String("Latvia"); ibanTemplate[28].length = 21; ibanTemplate[28].format = QLatin1String("4a,13c"); ibanTemplate[28].codes = QLatin1String("LV"); ibanTemplate[29].country = QLatin1String("Lebanon"); ibanTemplate[29].length = 28; ibanTemplate[29].format = QLatin1String("4n,20c"); ibanTemplate[29].codes = QLatin1String("LB"); ibanTemplate[30].country = QLatin1String("Liechtenstein"); ibanTemplate[30].length = 21; ibanTemplate[30].format = QLatin1String("5n,12c"); ibanTemplate[30].codes = QLatin1String("LI"); ibanTemplate[31].country = QLatin1String("Lithuania"); ibanTemplate[31].length = 20; ibanTemplate[31].format = QLatin1String("16n"); ibanTemplate[31].codes = QLatin1String("LT"); ibanTemplate[32].country = QLatin1String("Luxembourg"); ibanTemplate[32].length = 20; ibanTemplate[32].format = QLatin1String("3n,13c"); ibanTemplate[32].codes = QLatin1String("LU"); ibanTemplate[33].country = QLatin1String("Macedonia"); ibanTemplate[33].length = 19; ibanTemplate[33].format = QLatin1String("3n,10c,2n"); ibanTemplate[33].codes = QLatin1String("MK"); ibanTemplate[34].country = QLatin1String("Malta"); ibanTemplate[34].length = 31; ibanTemplate[34].format = QLatin1String("4a,5n,18c"); ibanTemplate[34].codes = QLatin1String("MT"); ibanTemplate[35].country = QLatin1String("Mauritania"); ibanTemplate[35].length = 27; ibanTemplate[35].format = QLatin1String("23n"); ibanTemplate[35].codes = QLatin1String("MR"); ibanTemplate[36].country = QLatin1String("Mauritius"); ibanTemplate[36].length = 30; ibanTemplate[36].format = QLatin1String("4a,19n,3a"); ibanTemplate[36].codes = QLatin1String("MU"); ibanTemplate[37].country = QLatin1String("Monaco"); ibanTemplate[37].length = 27; ibanTemplate[37].format = QLatin1String("10n,11c,2n"); ibanTemplate[37].codes = QLatin1String("MC"); ibanTemplate[38].country = QLatin1String("Montenegro"); ibanTemplate[38].length = 22; ibanTemplate[38].format = QLatin1String("18n"); ibanTemplate[38].codes = QLatin1String("ME"); ibanTemplate[39].country = QLatin1String("Netherlands[Note 3]"); ibanTemplate[39].length = 18; ibanTemplate[39].format = QLatin1String("4a,10n"); ibanTemplate[39].codes = QLatin1String("NL"); ibanTemplate[40].country = QLatin1String("Norway"); ibanTemplate[40].length = 15; ibanTemplate[40].format = QLatin1String("11n"); ibanTemplate[40].codes = QLatin1String("NO"); ibanTemplate[41].country = QLatin1String("Poland"); ibanTemplate[41].length = 28; ibanTemplate[41].format = QLatin1String("24n"); ibanTemplate[41].codes = QLatin1String("PL"); ibanTemplate[42].country = QLatin1String("Portugal"); ibanTemplate[42].length = 25; ibanTemplate[42].format = QLatin1String("21n"); ibanTemplate[42].codes = QLatin1String("PT"); ibanTemplate[43].country = QLatin1String("Romania"); ibanTemplate[43].length = 24; ibanTemplate[43].format = QLatin1String("4a,16c"); ibanTemplate[43].codes = QLatin1String("RO"); ibanTemplate[44].country = QLatin1String("San Marino"); ibanTemplate[44].length = 27; ibanTemplate[44].format = QLatin1String("1a,10n,12c"); ibanTemplate[44].codes = QLatin1String("SM"); ibanTemplate[45].country = QLatin1String("Saudi Arabia"); ibanTemplate[45].length = 24; ibanTemplate[45].format = QLatin1String("2n,18c"); ibanTemplate[45].codes = QLatin1String("SA"); ibanTemplate[46].country = QLatin1String("Serbia"); ibanTemplate[46].length = 22; ibanTemplate[46].format = QLatin1String("18n"); ibanTemplate[46].codes = QLatin1String("RS"); ibanTemplate[47].country = QLatin1String("Slovakia"); ibanTemplate[47].length = 24; ibanTemplate[47].format = QLatin1String("20n"); ibanTemplate[47].codes = QLatin1String("SK"); ibanTemplate[48].country = QLatin1String("Slovenia"); ibanTemplate[48].length = 19; ibanTemplate[48].format = QLatin1String("15n"); ibanTemplate[48].codes = QLatin1String("SI"); ibanTemplate[49].country = QLatin1String("Spain"); ibanTemplate[49].length = 24; ibanTemplate[49].format = QLatin1String("20n"); ibanTemplate[49].codes = QLatin1String("ES"); ibanTemplate[50].country = QLatin1String("Sweden"); ibanTemplate[50].length = 24; ibanTemplate[50].format = QLatin1String("20n"); ibanTemplate[50].codes = QLatin1String("SE"); ibanTemplate[51].country = QLatin1String("Switzerland"); ibanTemplate[51].length = 21; ibanTemplate[51].format = QLatin1String("5n,12c"); ibanTemplate[51].codes = QLatin1String("CH"); ibanTemplate[52].country = QLatin1String("Tunisia"); ibanTemplate[52].length = 24; ibanTemplate[52].format = QLatin1String("20n"); ibanTemplate[52].codes = QLatin1String("TN"); ibanTemplate[53].country = QLatin1String("Turkey"); ibanTemplate[53].length = 26; ibanTemplate[53].format = QLatin1String("5n,17c"); ibanTemplate[53].codes = QLatin1String("TR"); ibanTemplate[54].country = QLatin1String("United Arab Emirates"); ibanTemplate[54].length = 23; ibanTemplate[54].format = QLatin1String("3n,16n"); ibanTemplate[54].codes = QLatin1String("AE"); ibanTemplate[55].country = QLatin1String("United Kingdom[Note 4]"); ibanTemplate[55].length = 22; ibanTemplate[55].format = QLatin1String("4a,14n"); ibanTemplate[55].codes = QLatin1String("GB"); // create reg exp from templates QStringList regexp_all; foreach (IbanTemplate t, ibanTemplate){ QString regexp1; // standardized first block: country codes (France uses more than one) and 2 checksum digits regexp1.append(QLatin1String("(")) .append(QRegExp::escape(t.codes.remove(QLatin1Char(' '))).replace(QLatin1Char(','), QLatin1Char('|'))) .append(QLatin1String(")")) .append(QLatin1String("\\d\\d")); // BBAN fields QStringList bbanFields = t.format.split(QLatin1Char(',')); foreach (QString bbanField, bbanFields){ bbanField.remove(QLatin1Char(' ')); Q_ASSERT_X(bbanField.left(bbanField.length() - 1).toInt() > 0, "BBAN format: count is wrong for IBAN", t.country.toLatin1()); QChar formatSymbol(bbanField.at(bbanField.length() - 1)); if (formatSymbol == QLatin1Char('n')) regexp1.append(QLatin1String("[0-9]")); else if (formatSymbol == QLatin1Char('a')) regexp1.append(QLatin1String("[A-Z]")); else if (formatSymbol == QLatin1Char('c')) regexp1.append(QLatin1String("[A-Z0-9]")); else Q_ASSERT_X(false, "BBAN format: format symbol is wrong for IBAN", t.country.toLatin1()); regexp1.append(QLatin1String("{")).append(bbanField.left(bbanField.length() - 1)).append(QLatin1String("}"));}
void PropertyConfigurator::configureGlobalSettings(const Properties &rProperties, LoggerRepository *pLoggerRepository) const { Q_ASSERT_X(pLoggerRepository, "PropertyConfigurator::configureGlobalSettings()", "pLoggerRepository must not be null."); const QLatin1String key_reset("log4j.reset"); const QLatin1String key_debug("log4j.Debug"); const QLatin1String key_config_debug("log4j.configDebug"); const QLatin1String key_threshold("log4j.threshold"); const QLatin1String key_handle_qt_messages("log4j.handleQtMessages"); // Test each global setting and set it // - Reset: log4j.reset // - Debug: log4j.Debug, log4j.configDebug // - Threshold: log4j.threshold // - Handle Qt Messages: log4j.handleQtMessages // Reset QString value = rProperties.property(key_reset); if (!value.isEmpty() && OptionConverter::toBoolean(value, false)) { // Use LogManager and not pLoggerRepository to reset internal // logging. LogManager::resetConfiguration(); logger()->debug("Reset configuration"); } // Debug value = rProperties.property(key_debug); if (value.isNull()) { value = rProperties.property(key_config_debug); if (!value.isNull()) logger()->warn("[%1] is deprecated. Use [%2] instead.", key_config_debug, key_debug); } if (!value.isNull()) { // Don't use OptionConverter::toLevel(). Invalid level string is a valid setting bool ok; Level level = Level::fromString(value, &ok); if (!ok) level = Level::DEBUG_INT; LogManager::logLogger()->setLevel(level); logger()->debug("Set level for Log4Qt logging to %1", LogManager::logLogger()->level().toString()); } // Threshold value = rProperties.property(key_threshold); if (!value.isNull()) { pLoggerRepository->setThreshold(OptionConverter::toLevel(value, Level::ALL_INT)); logger()->debug("Set threshold for LoggerRepository to %1", pLoggerRepository->threshold().toString()); } // Handle Qt messages value = rProperties.property(key_handle_qt_messages); if (!value.isNull()) { LogManager::setHandleQtMessages(OptionConverter::toBoolean(value, false)); logger()->debug("Set handling of Qt messages LoggerRepository to %1", QVariant(LogManager::handleQtMessages()).toString()); } }
/*! \internal */ void CapsuleMesh::createGeometry(bool bForce) { // Create a new geometry node for this level of detail if necessary. QGLSceneNode *geometry = 0; QMap<int, QGLSceneNode *>::iterator It = d->lodGeometry.find(d->lod); if (It != d->lodGeometry.end()) geometry = *It; if (geometry && bForce) { if (d->currentCapsule) d->topNode->removeNode(d->currentCapsule); d->currentCapsule = 0; d->lodGeometry.erase(It); geometry->setParent(0); delete geometry; geometry = 0; } if (!geometry) { QGLBuilder builder; // For the cylinder int facets = 4 * (1 << d->lod); int layers = (1 << d->lod) - 1; // For the spheres int divisions = d->lod; // Sanity check - the height of the capsule must not be less than its // diameter. A minimal capsule is a sphere - where diameter == height. if (d->length < 2.0f * d->radius) { qWarning() << "Length of capsule must exceed its diameter" << " - correcting length."; d->length = 2.0f * d->radius; } float diameter = d->radius+d->radius; float cylinderHeight = d->length - diameter; float offset = cylinderHeight/2.0f; builder << QGL::Faceted; QGLSceneNode *s = 0; s = builder.newNode(); s->setObjectName(QLatin1String("Cylinder")); builder << QGLCylinder(diameter, diameter, cylinderHeight, facets, layers, false, false); s = builder.newNode(); s->setObjectName(QLatin1String("LeftEndCap")); builder << QGLDome(diameter, divisions, false); QMatrix4x4 translateMatrix; translateMatrix.setToIdentity(); translateMatrix.rotate(180.0f, 0.0f, 1.0f, 0.0f); translateMatrix.translate(0.0f, 0.0f, offset); builder.currentNode()->setLocalTransform(translateMatrix); s = builder.newNode(); s->setObjectName(QLatin1String("RightEndCap")); builder << QGLDome(diameter, divisions, false); translateMatrix.setToIdentity(); translateMatrix.translate(0.0f, 0.0f, offset); builder.currentNode()->setLocalTransform(translateMatrix); geometry = builder.finalizedSceneNode(); geometry->setParent(this); d->lodGeometry.insert(d->lod, geometry); } Q_ASSERT_X(geometry != 0, Q_FUNC_INFO, "Could not create/find geometry!"); if (d->currentCapsule != geometry) { if (d->currentCapsule) d->topNode->removeNode(d->currentCapsule); d->topNode->addNode(geometry); d->currentCapsule = geometry; } if (!d->sceneSet) { setScene(new CapsuleScene(d->topNode)); d->sceneSet = true; } }
MainWindow::MainWindow() : QMainWindow(), actionNextDive(0), actionPreviousDive(0), helpView(0), state(VIEWALL), survey(0) { Q_ASSERT_X(m_Instance == NULL, "MainWindow", "MainWindow recreated!"); m_Instance = this; ui.setupUi(this); read_hashes(); // Define the States of the Application Here, Currently the states are situations where the different // widgets will change on the mainwindow. // for the "default" mode MainTab *mainTab = new MainTab(); DiveListView *diveListView = new DiveListView(); ProfileWidget2 *profileWidget = new ProfileWidget2(); #ifndef NO_MARBLE GlobeGPS *globeGps = new GlobeGPS(); #else QWidget *globeGps = NULL; #endif PlannerSettingsWidget *plannerSettings = new PlannerSettingsWidget(); DivePlannerWidget *plannerWidget = new DivePlannerWidget(); PlannerDetails *plannerDetails = new PlannerDetails(); LocationInformationWidget *locationInformation = new LocationInformationWidget(); // what is a sane order for those icons? we should have the ones the user is // most likely to want towards the top so they are always visible // and the ones that someone likely sets and then never touches again towards the bottom profileToolbarActions << ui.profCalcCeiling << ui.profCalcAllTissues << // start with various ceilings ui.profIncrement3m << ui.profDcCeiling << ui.profPhe << ui.profPn2 << ui.profPO2 << // partial pressure graphs ui.profRuler << ui.profScaled << // measuring and scaling ui.profTogglePicture << ui.profTankbar << ui.profMod << ui.profNdl_tts << // various values that a user is either interested in or not ui.profEad << ui.profSAC << ui.profHR << // very few dive computers support this ui.profTissues; // maybe less frequently used QToolBar *toolBar = new QToolBar(); Q_FOREACH (QAction *a, profileToolbarActions) toolBar->addAction(a); toolBar->setOrientation(Qt::Vertical); toolBar->setIconSize(QSize(24,24)); QWidget *profileContainer = new QWidget(); QHBoxLayout *profLayout = new QHBoxLayout(); profLayout->setSpacing(0); profLayout->setMargin(0); profLayout->setContentsMargins(0,0,0,0); profLayout->addWidget(toolBar); profLayout->addWidget(profileWidget); profileContainer->setLayout(profLayout); registerApplicationState("Default", mainTab, profileContainer, diveListView, globeGps ); registerApplicationState("AddDive", mainTab, profileContainer, diveListView, globeGps ); registerApplicationState("EditDive", mainTab, profileContainer, diveListView, globeGps ); registerApplicationState("PlanDive", plannerWidget, profileContainer, plannerSettings, plannerDetails ); registerApplicationState("EditPlannedDive", plannerWidget, profileContainer, diveListView, globeGps ); registerApplicationState("EditDiveSite",locationInformation, profileContainer, diveListView, globeGps ); setApplicationState("Default"); ui.multiFilter->hide(); setWindowIcon(QIcon(":subsurface-icon")); if (!QIcon::hasThemeIcon("window-close")) { QIcon::setThemeName("subsurface"); } connect(dive_list(), SIGNAL(currentDiveChanged(int)), this, SLOT(current_dive_changed(int))); connect(PreferencesDialog::instance(), SIGNAL(settingsChanged()), this, SLOT(readSettings())); connect(PreferencesDialog::instance(), SIGNAL(settingsChanged()), diveListView, SLOT(update())); connect(PreferencesDialog::instance(), SIGNAL(settingsChanged()), diveListView, SLOT(reloadHeaderActions())); connect(PreferencesDialog::instance(), SIGNAL(settingsChanged()), information(), SLOT(updateDiveInfo())); connect(PreferencesDialog::instance(), SIGNAL(settingsChanged()), divePlannerWidget(), SLOT(settingsChanged())); connect(PreferencesDialog::instance(), SIGNAL(settingsChanged()), divePlannerSettingsWidget(), SLOT(settingsChanged())); connect(PreferencesDialog::instance(), SIGNAL(settingsChanged()), TankInfoModel::instance(), SLOT(update())); connect(ui.actionRecent1, SIGNAL(triggered(bool)), this, SLOT(recentFileTriggered(bool))); connect(ui.actionRecent2, SIGNAL(triggered(bool)), this, SLOT(recentFileTriggered(bool))); connect(ui.actionRecent3, SIGNAL(triggered(bool)), this, SLOT(recentFileTriggered(bool))); connect(ui.actionRecent4, SIGNAL(triggered(bool)), this, SLOT(recentFileTriggered(bool))); connect(information(), SIGNAL(addDiveFinished()), graphics(), SLOT(setProfileState())); connect(DivePlannerPointsModel::instance(), SIGNAL(planCreated()), this, SLOT(planCreated())); connect(DivePlannerPointsModel::instance(), SIGNAL(planCanceled()), this, SLOT(planCanceled())); connect(plannerDetails->printPlan(), SIGNAL(pressed()), divePlannerWidget(), SLOT(printDecoPlan())); connect(mainTab, SIGNAL(requestDiveSiteEdit(uint32_t)), this, SLOT(enableDiveSiteEdit(uint32_t))); connect(locationInformation, SIGNAL(informationManagementEnded()), this, SLOT(setDefaultState())); connect(locationInformation, SIGNAL(informationManagementEnded()), information(), SLOT(showLocation())); connect(locationInformation, SIGNAL(coordinatesChanged()), globe(), SLOT(repopulateLabels())); #ifdef NO_PRINTING plannerDetails->printPlan()->hide(); ui.menuFile->removeAction(ui.actionPrint); #endif ui.mainErrorMessage->hide(); graphics()->setEmptyState(); initialUiSetup(); readSettings(); diveListView->reload(DiveTripModel::TREE); diveListView->reloadHeaderActions(); diveListView->setFocus(); globe()->reload(); diveListView->expand(dive_list()->model()->index(0, 0)); diveListView->scrollTo(dive_list()->model()->index(0, 0), QAbstractItemView::PositionAtCenter); divePlannerWidget()->settingsChanged(); divePlannerSettingsWidget()->settingsChanged(); #ifdef NO_MARBLE ui.menuView->removeAction(ui.actionViewGlobe); #else connect(globe(), SIGNAL(coordinatesChanged()), locationInformation, SLOT(updateGpsCoordinates())); #endif #ifdef NO_USERMANUAL ui.menuHelp->removeAction(ui.actionUserManual); #endif memset(©PasteDive, 0, sizeof(copyPasteDive)); memset(&what, 0, sizeof(what)); updateManager = new UpdateManager(this); undoStack = new QUndoStack(this); QAction *undoAction = undoStack->createUndoAction(this, tr("&Undo")); QAction *redoAction = undoStack->createRedoAction(this, tr("&Redo")); undoAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Z)); redoAction->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_Z)); QList<QAction*>undoRedoActions; undoRedoActions.append(undoAction); undoRedoActions.append(redoAction); ui.menu_Edit->addActions(undoRedoActions); ReverseGeoLookupThread *geoLookup = ReverseGeoLookupThread::instance(); connect(geoLookup, SIGNAL(started()),information(), SLOT(disableGeoLookupEdition())); connect(geoLookup, SIGNAL(finished()), information(), SLOT(enableGeoLookupEdition())); }
QDBusMessage qDBusPropertyGet(const QDBusConnectionPrivate::ObjectTreeNode &node, const QDBusMessage &msg) { Q_ASSERT(msg.arguments().count() == 2); Q_ASSERT_X(!node.obj || QThread::currentThread() == node.obj->thread(), "QDBusConnection: internal threading error", "function called for an object that is in another thread!!"); QString interface_name = msg.arguments().at(0).toString(); QByteArray property_name = msg.arguments().at(1).toString().toUtf8(); QDBusAdaptorConnector *connector; QVariant value; bool interfaceFound = false; if (node.flags & QDBusConnection::ExportAdaptors && (connector = qDBusFindAdaptorConnector(node.obj))) { // find the class that implements interface_name or try until we've found the property // in case of an empty interface if (interface_name.isEmpty()) { for (QDBusAdaptorConnector::AdaptorMap::ConstIterator it = connector->adaptors.constBegin(), end = connector->adaptors.constEnd(); it != end; ++it) { const QMetaObject *mo = it->adaptor->metaObject(); int pidx = mo->indexOfProperty(property_name); if (pidx != -1) { value = mo->property(pidx).read(it->adaptor); break; } } } else { QDBusAdaptorConnector::AdaptorMap::ConstIterator it; it = std::lower_bound(connector->adaptors.constBegin(), connector->adaptors.constEnd(), interface_name); if (it != connector->adaptors.constEnd() && interface_name == QLatin1String(it->interface)) { interfaceFound = true; value = it->adaptor->property(property_name); } } } if (!interfaceFound && !value.isValid() && node.flags & (QDBusConnection::ExportAllProperties | QDBusConnection::ExportNonScriptableProperties)) { // try the object itself if (!interface_name.isEmpty()) interfaceFound = qDBusInterfaceInObject(node.obj, interface_name); if (interfaceFound) { int pidx = node.obj->metaObject()->indexOfProperty(property_name); if (pidx != -1) { QMetaProperty mp = node.obj->metaObject()->property(pidx); if ((mp.isScriptable() && (node.flags & QDBusConnection::ExportScriptableProperties)) || (!mp.isScriptable() && (node.flags & QDBusConnection::ExportNonScriptableProperties))) value = mp.read(node.obj); } } } if (!value.isValid()) { // the property was not found if (!interfaceFound) return interfaceNotFoundError(msg, interface_name); return propertyNotFoundError(msg, interface_name, property_name); } return msg.createReply(QVariant::fromValue(QDBusVariant(value))); }
static void qt_tablet_init_wce() { static bool firstTime = true; if (!firstTime) return; firstTime = false; qt_tablet_widget = new QWidget(0); qt_tablet_widget->createWinId(); qt_tablet_widget->setObjectName(QLatin1String("Qt internal tablet widget")); LOGCONTEXT lcMine; qAddPostRoutine(qt_tablet_cleanup_wce); struct tagAXIS tpOri[3]; if (ptrWTInfo && ptrWTOpen && ptrWTQueueSizeGet && ptrWTQueueSizeSet) { // make sure we have WinTab if (!ptrWTInfo(0, 0, NULL)) { #ifdef TABLET_DEBUG qWarning("QWidget: Wintab services not available"); #endif return; } // some tablets don't support tilt, check if it is possible, qt_tablet_tilt_support = ptrWTInfo(WTI_DEVICES, DVC_ORIENTATION, &tpOri); if (qt_tablet_tilt_support) { // check for azimuth and altitude qt_tablet_tilt_support = tpOri[0].axResolution && tpOri[1].axResolution; } // build our context from the default context ptrWTInfo(WTI_DEFSYSCTX, 0, &lcMine); // Go for the raw coordinates, the tablet event will return good stuff lcMine.lcOptions |= CXO_MESSAGES | CXO_CSRMESSAGES; lcMine.lcPktData = PACKETDATA; lcMine.lcPktMode = PACKETMODE; lcMine.lcMoveMask = PACKETDATA; lcMine.lcOutOrgX = 0; lcMine.lcOutExtX = lcMine.lcInExtX; lcMine.lcOutOrgY = 0; lcMine.lcOutExtY = -lcMine.lcInExtY; qt_tablet_context = ptrWTOpen(qt_tablet_widget->winId(), &lcMine, true); #ifdef TABLET_DEBUG qDebug("Tablet is %p", qt_tablet_context); #endif if (!qt_tablet_context) { #ifdef TABLET_DEBUG qWarning("QWidget: Failed to open the tablet"); #endif return; } // Set the size of the Packet Queue to the correct size... int currSize = ptrWTQueueSizeGet(qt_tablet_context); if (!ptrWTQueueSizeSet(qt_tablet_context, QT_TABLET_NPACKETQSIZE)) { // Ideally one might want to use a smaller // multiple, but for now, since we managed to destroy // the existing Q with the previous call, set it back // to the other size, which should work. If not, // there will be trouble. if (!ptrWTQueueSizeSet(qt_tablet_context, currSize)) { Q_ASSERT_X(0, "Qt::Internal", "There is no packet queue for" " the tablet. The tablet will not work"); } } } }
void ResetPassword::setLogin(QString value) { Q_ASSERT_X(!isNull(), "ResetPassword::setLogin", "Setter call on object which isNull"); this->d->login = value; }
/*virtual*/ void AbstractItemView::setModel(QAbstractItemModel *model, AbstractViewItem *prototype) { if( m_model == model || !model) return; if (m_model) { disconnect(m_model, SIGNAL(destroyed()), this, SLOT(_q_modelDestroyed())); disconnect(m_model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT( dataChanged(QModelIndex,QModelIndex))); disconnect(m_model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(rowsInserted(QModelIndex,int,int))); disconnect(m_model, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(rowsRemoved(QModelIndex,int,int))); disconnect(m_model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)), this, SLOT(rowsAboutToBeRemoved(QModelIndex,int,int))); disconnect(m_model, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)), this, SLOT(rowsAboutToBeInserted(QModelIndex,int,int))); disconnect(m_model, SIGNAL(columnsInserted(QModelIndex,int,int)), this, SLOT(columnsInserted(QModelIndex,int,int))); disconnect(m_model, SIGNAL(columnsAboutToBeInserted(QModelIndex,int,int)), this, SLOT(columnsAboutToBeInserted(QModelIndex,int,int))); disconnect(m_model, SIGNAL(columnsRemoved(QModelIndex,int,int)), this, SLOT(columnsRemoved(QModelIndex,int,int))); disconnect(m_model, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)), this, SLOT(columnsAboutToBeRemoved(QModelIndex,int,int))); disconnect(m_model, SIGNAL(modelReset()), this, SLOT(reset())); disconnect(m_model, SIGNAL(layoutChanged()), this, SLOT(_q_layoutChanged())); m_model = 0; } setSelectionModel(0); m_currentIndex = QModelIndex(); m_rootIndex = QModelIndex(); m_model = model; Q_ASSERT_X(m_model->index(0,0) == m_model->index(0,0), "AbstractItemView::setModel", "A model should return the exact same index " "(including its internal id/pointer) when asked for it twice in a row."); Q_ASSERT_X(m_model->index(0,0).parent() == QModelIndex(), "AbstractItemView::setModel", "The parent of a top level index should be invalid"); connect(m_model, SIGNAL(destroyed()), this, SLOT(modelDestroyed())); connect(m_model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT( dataChanged(QModelIndex,QModelIndex))); connect(m_model, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)), this, SLOT(rowsAboutToBeInserted(QModelIndex,int,int))); connect(m_model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(rowsInserted(QModelIndex,int,int))); connect(m_model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)), this, SLOT(rowsAboutToBeRemoved(QModelIndex,int,int))); connect(m_model, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(rowsRemoved(QModelIndex,int,int))); connect(m_model, SIGNAL(modelReset()), this, SLOT(reset())); connect(m_model, SIGNAL(layoutChanged()), this, SLOT(layoutChanged())); setSelectionModel(new QItemSelectionModel(m_model)); if (prototype && m_container) { m_container->setItemPrototype(prototype); m_container->reset(); } }
/*! The destructor. */ QAbstractTextureImage::~QAbstractTextureImage() { Q_ASSERT_X(Qt3DCore::QNodePrivate::get(this)->m_wasCleanedUp, Q_FUNC_INFO, "QNode::cleanup should have been called by now. A Qt3DRender::QAbstractTextureImage subclass didn't call QNode::cleanup in its destructor"); }
QString ResetPassword::getLogin() const { Q_ASSERT_X(!isNull(), "ResetPassword::getLogin", "Getter call on object which isNull"); return this->d->login; }
Private(QueueInterface *theWeaver) : weaver(theWeaver) { Q_ASSERT_X(sizeof StateNames / sizeof StateNames[0] == NoOfStates, "State::Private ctor", "Make sure to keep StateId and StateNames in sync!"); }
//! Access statistic with specified index to modify it. //! //! Statistics are accessed by integer indices. //! A clean way to do this is to use an enum with name corresponding //! to the name of the statistic. double& operator [] (int index) { Q_ASSERT_X(index >= 0 && index < statisticCount, Q_FUNC_INFO, "Index of a statistic out of range"); return statistics[index]; }
QVariant ToConfiguration::Editor::defaultValue(int option) const { switch (option) { case SyntaxHighlightingInt: return QVariant((int) 0); case EditorTypeInt: return QVariant((int) 0); case UseMaxTextWidthMarkBool: return QVariant((bool) false); case MaxTextWidthMarkInt: return QVariant((int)75); case KeywordUpperBool: return QVariant((bool) false); case ObjectNamesUpperBool: return QVariant((bool) false); case CodeCompleteBool: return QVariant((bool) true); case CompleteSortBool: return QVariant((bool) true); case UseEditorShortcutsBool: return QVariant((bool) false); case EditorShortcutsMap: return QVariant(QMap<QString, QVariant>()); case AutoIndentBool: return QVariant((bool) true); case UseSpacesForIndentBool: return QVariant((bool) false); case TabStopInt: return QVariant((int) 8); case ConfTextFont: return QVariant(QString("")); case ConfCodeFont: { QFont fo; QFont mono; #if defined(Q_OS_WIN) mono = QFont("Courier New", 10); #elif defined(Q_OS_MAC) mono = QFont("Courier", 12); #else // TODO #endif mono.setStyleHint(QFont::Monospace, QFont::NoAntialias); fo = mono.resolve(fo); QString fontName = fo.toString(); return QVariant(fontName); } case ListTextFont: return QVariant(QString("")); case Extensions: return QVariant(QString("SQL (*.sql *.pkg *.pkb), Text (*.txt), All (*)")); case EditStyleMap: { static toStylesMap retval; if (!retval.isEmpty()) return QVariant::fromValue(retval); QMetaEnum StyleNameEnum(ENUM_REF(toSyntaxAnalyzer,WordClassEnum)); QsciLexerSQL *l = new QsciLexerSQL(NULL); for (int idx = 0; idx < StyleNameEnum.keyCount(); idx++) { QColor fg = l->color((int)StyleNameEnum.value(idx)); QColor bg = l->paper((int)StyleNameEnum.value(idx)); QFont fo = Utils::toStringToFont(defaultValue(ConfCodeFont).toString()); QString styleName = StyleNameEnum.key(idx); int styleNameEnum = StyleNameEnum.value(idx); retval.insert(styleNameEnum, toStyle(fg, bg, fo)); } delete l; return QVariant::fromValue(retval); } default: Q_ASSERT_X( false, qPrintable(__QHERE__), qPrintable(QString("Context Editor un-registered enum value: %1").arg(option))); return QVariant(); } }
void DailyRollingFileAppender::computeRollOverTime() { // Q_ASSERT_X(, "DailyRollingFileAppender::computeRollOverTime()", "Lock must be held by caller") Q_ASSERT_X(!mActiveDatePattern.isEmpty(), "DailyRollingFileAppender::computeRollOverTime()", "No active date pattern"); QDateTime now = QDateTime::currentDateTime(); QDate now_date = now.date(); QTime now_time = now.time(); QDateTime start; switch (mFrequency) { case MINUTELY_ROLLOVER: { start = QDateTime(now_date, QTime(now_time.hour(), now_time.minute(), 0, 0)); mRollOverTime = start.addSecs(60); } break; case HOURLY_ROLLOVER: { start = QDateTime(now_date, QTime(now_time.hour(), 0, 0, 0)); mRollOverTime = start.addSecs(60*60); } break; case HALFDAILY_ROLLOVER: { int hour = now_time.hour(); if (hour >= 12) hour = 12; else hour = 0; start = QDateTime(now_date, QTime(hour, 0, 0, 0)); mRollOverTime = start.addSecs(60*60*12); } break; case DAILY_ROLLOVER: { start = QDateTime(now_date, QTime(0, 0, 0, 0)); mRollOverTime = start.addDays(1); } break; case WEEKLY_ROLLOVER: { // QT numbers the week days 1..7. The week starts on Monday. // Change it to being numbered 0..6, starting with Sunday. int day = now_date.dayOfWeek(); if (day == Qt::Sunday) day = 0; start = QDateTime(now_date, QTime(0, 0, 0, 0)).addDays(-1 * day); mRollOverTime = start.addDays(7); } break; case MONTHLY_ROLLOVER: { start = QDateTime(QDate(now_date.year(), now_date.month(), 1), QTime(0, 0, 0, 0)); mRollOverTime = start.addMonths(1); } break; default: Q_ASSERT_X(false, "DailyRollingFileAppender::computeInterval()", "Invalid datePattern constant"); mRollOverTime = QDateTime::fromTime_t(0); } mRollOverSuffix = static_cast<DateTime>(start).toString(mActiveDatePattern); Q_ASSERT_X(static_cast<DateTime>(now).toString(mActiveDatePattern) == mRollOverSuffix, "DailyRollingFileAppender::computeRollOverTime()", "File name changes within interval"); Q_ASSERT_X(mRollOverSuffix != static_cast<DateTime>(mRollOverTime).toString(mActiveDatePattern), "DailyRollingFileAppender::computeRollOverTime()", "File name does not change with rollover"); logger()->trace("Computing roll over time from %1: The interval start time is %2. The roll over time is %3", now, start, mRollOverTime); }
bool BrowserNode::tool_cmd(ToolCom * com, const char * args) { switch ((unsigned char) args[-1]) { case applyCmd: { QLOG_FATAL() << Q_FUNC_INFO << "If this got called then we have a logic flaw going on and BrowserNode needs to have Q_OBJECT in it to properly catch ToolCom::Run execution result"; Q_ASSERT_X(0, "applyCmd happened", "very bad"); int runResult = ToolCom::run(args, this, FALSE, FALSE); com->write_unsigned(runResult); break; } case createCmd: // invalid creation com->write_id(0); break; case parentCmd: if (this != BrowserView::get_project()) ((BrowserNode *) parent())->write_id(com); else com->write_id(0); break; case childrenCmd: { unsigned v = com->api_format(); unsigned n = 0; Q3ListViewItem * child; for (child = firstChild(); child != 0; child = child->nextSibling()) if (!((BrowserNode *) child)->deletedp() && ((BrowserNode *) child)->api_compatible(v)) n += 1; com->write_unsigned(n); for (child = firstChild(); child != 0; child = child->nextSibling()) if (!((BrowserNode *) child)->deletedp() && ((BrowserNode *) child)->api_compatible(v)) ((BrowserNode *) child)->write_id(com); } break; case getDefCmd: case getUmlDefCmd: case getCppDefCmd: case getJavaDefCmd: case getPhpDefCmd: case getPythonDefCmd: case getIdlDefCmd: get_data()->send_uml_def(com, this, comment); break; case isWritableCmd: com->write_bool(!is_read_only); break; case supportFileCmd: // goes up to the package return ((BrowserNode *) parent())->tool_cmd(com, args); case isOpenCmd: com->write_bool(isOpen()); break; case referencedByCmd: { BrowserNodeList targetof; referenced_by(targetof); // remove duplicats targetof.sort_it(); BrowserNode * bn; targetof.first(); while ((bn = targetof.current()) != 0) if (bn == targetof.next()) targetof.remove(); com->write_unsigned(targetof.count()); for (bn = targetof.first(); bn != 0; bn = targetof.next()) bn->write_id(com); } break; case setCoupleValueCmd: if (is_read_only && !root_permission()) com->write_ack(FALSE); else { set_value(args, args + strlen(args) + 1); package_modified(); get_data()->modified(); com->write_ack(TRUE); } break; case setDescriptionCmd: if (is_read_only && !root_permission()) com->write_ack(FALSE); else { set_comment(args); package_modified(); com->write_ack(TRUE); } break; case setNameCmd: if (is_read_only && !root_permission()) com->write_ack(FALSE); else { if (name != args) { if (((BrowserNode *) parent())->wrong_child_name(args, get_type(), allow_spaces(), allow_empty())) { com->write_ack(FALSE); return TRUE; } else { set_name(args); update_stereotype(); package_modified(); get_data()->modified(); } } com->write_ack(TRUE); } break; case setOpenCmd: BrowserView::select(this); setOpen(*args); com->write_ack(TRUE); break; case setMarkedCmd: if (*args) { if (this == BrowserView::get_project()) com->write_ack(FALSE); else { if (!is_marked) toggle_mark(); com->write_ack(TRUE); } } else { if (is_marked) toggle_mark(); com->write_ack(TRUE); } break; case moveAfterCmd: if (is_read_only && !root_permission()) com->write_ack(FALSE); else { BrowserNode * p = (BrowserNode *) parent(); BrowserNode * after = (BrowserNode *) com->get_id(args); if (after == 0) { if (p == 0) com->write_ack(FALSE); else { p->takeItem(this); p->insertItem(this); com->write_ack(TRUE); p->package_modified(); } } else if ((after->parent() != p) || (after == this)) { com->write_ack(FALSE); } else { moveItem(after); com->write_ack(TRUE); p->package_modified(); } } break; case moveInCmd: // plug-out upgrade, limited checks if (is_read_only && !root_permission()) com->write_ack(FALSE); else { BrowserNode * newparent = (BrowserNode *) com->get_id(args); BrowserNode * oldparent = (BrowserNode *) parent(); if ((newparent == oldparent) || (newparent == this)) { com->write_ack(FALSE); } else { oldparent->takeItem(this); newparent->insertItem(this); com->write_ack(TRUE); oldparent->package_modified(); newparent->package_modified(); } } break; case old_deleteCmd: case deleteCmd: if (is_read_only && !root_permission()) com->write_ack(FALSE); else { delete_it(); ((BrowserNode *) parent())->get_data()->modified(); package_modified(); com->write_ack(TRUE); } break; case applyStereotypeCmd: if (is_read_only && !root_permission()) com->write_ack(FALSE); else { ProfiledStereotypes::applyStereotype(this); // call package_modified() if needed com->write_ack(TRUE); } break; default: return FALSE; } return TRUE; }
QString qDBusIntrospectObject(const QDBusConnectionPrivate::ObjectTreeNode &node, const QString &path) { // object may be null QString xml_data(QLatin1String(DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE)); xml_data += QLatin1String("<node>\n"); if (node.obj) { Q_ASSERT_X(QThread::currentThread() == node.obj->thread(), "QDBusConnection: internal threading error", "function called for an object that is in another thread!!"); if (node.flags & (QDBusConnection::ExportScriptableContents | QDBusConnection::ExportNonScriptableContents)) { // create XML for the object itself const QMetaObject *mo = node.obj->metaObject(); for ( ; mo != &QObject::staticMetaObject; mo = mo->superClass()) xml_data += qDBusGenerateMetaObjectXml(QString(), mo, mo->superClass(), node.flags); } // does this object have adaptors? QDBusAdaptorConnector *connector; if (node.flags & QDBusConnection::ExportAdaptors && (connector = qDBusFindAdaptorConnector(node.obj))) { // trasverse every adaptor in this object QDBusAdaptorConnector::AdaptorMap::ConstIterator it = connector->adaptors.constBegin(); QDBusAdaptorConnector::AdaptorMap::ConstIterator end = connector->adaptors.constEnd(); for ( ; it != end; ++it) { // add the interface: QString ifaceXml = QDBusAbstractAdaptorPrivate::retrieveIntrospectionXml(it->adaptor); if (ifaceXml.isEmpty()) { // add the interface's contents: ifaceXml += qDBusGenerateMetaObjectXml(QString::fromLatin1(it->interface), it->adaptor->metaObject(), &QDBusAbstractAdaptor::staticMetaObject, QDBusConnection::ExportScriptableContents | QDBusConnection::ExportNonScriptableContents); QDBusAbstractAdaptorPrivate::saveIntrospectionXml(it->adaptor, ifaceXml); } xml_data += ifaceXml; } } // is it a virtual node that handles introspection itself? if (node.flags & QDBusConnectionPrivate::VirtualObject) { xml_data += node.treeNode->introspect(path); } xml_data += QLatin1String( propertiesInterfaceXml ); } xml_data += QLatin1String( introspectableInterfaceXml ); xml_data += QLatin1String( peerInterfaceXml ); if (node.flags & QDBusConnection::ExportChildObjects) { xml_data += generateSubObjectXml(node.obj); } else { // generate from the object tree QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator it = node.children.constBegin(); QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator end = node.children.constEnd(); for ( ; it != end; ++it) if (it->obj || !it->children.isEmpty()) xml_data += QString::fromLatin1(" <node name=\"%1\"/>\n") .arg(it->name); } xml_data += QLatin1String("</node>\n"); return xml_data; }
void QNetworkAccessFileBackend::open() { QUrl url = this->url(); if (url.host() == QLatin1String("localhost")) url.setHost(QString()); #if !defined(Q_OS_WIN) // do not allow UNC paths on Unix if (!url.host().isEmpty()) { // we handle only local files error(QNetworkReply::ProtocolInvalidOperationError, QCoreApplication::translate("QNetworkAccessFileBackend", "Request for opening non-local file %1").arg(url.toString())); finished(); return; } #endif // !defined(Q_OS_WIN) if (url.path().isEmpty()) url.setPath(QLatin1String("/")); setUrl(url); QString fileName = url.toLocalFile(); if (fileName.isEmpty()) { if (url.scheme() == QLatin1String("qrc")) fileName = QLatin1Char(':') + url.path(); else fileName = url.toString(QUrl::RemoveAuthority | QUrl::RemoveFragment | QUrl::RemoveQuery); } file.setFileName(fileName); if (operation() == QNetworkAccessManager::GetOperation) { if (!loadFileInfo()) return; } QIODevice::OpenMode mode; switch (operation()) { case QNetworkAccessManager::GetOperation: mode = QIODevice::ReadOnly; break; case QNetworkAccessManager::PutOperation: mode = QIODevice::WriteOnly | QIODevice::Truncate; uploadByteDevice = createUploadByteDevice(); QObject::connect(uploadByteDevice, SIGNAL(readyRead()), this, SLOT(uploadReadyReadSlot())); QMetaObject::invokeMethod(this, "uploadReadyReadSlot", Qt::QueuedConnection); break; default: Q_ASSERT_X(false, "QNetworkAccessFileBackend::open", "Got a request operation I cannot handle!!"); return; } mode |= QIODevice::Unbuffered; bool opened = file.open(mode); // could we open the file? if (!opened) { QString msg = QCoreApplication::translate("QNetworkAccessFileBackend", "Error opening %1: %2") .arg(this->url().toString(), file.errorString()); // why couldn't we open the file? // if we're opening for reading, either it doesn't exist, or it's access denied // if we're opening for writing, not existing means it's access denied too if (file.exists() || operation() == QNetworkAccessManager::PutOperation) error(QNetworkReply::ContentAccessDenied, msg); else error(QNetworkReply::ContentNotFoundError, msg); finished(); } }
void QgsMapRendererCustomPainterJob::start() { if ( isActive() ) return; mRenderingStart.start(); mActive = true; mErrors.clear(); QgsDebugMsg( "QPAINTER run!" ); QgsDebugMsg( "Preparing list of layer jobs for rendering" ); QTime prepareTime; prepareTime.start(); // clear the background mPainter->fillRect( 0, 0, mSettings.outputSize().width(), mSettings.outputSize().height(), mSettings.backgroundColor() ); mPainter->setRenderHint( QPainter::Antialiasing, mSettings.testFlag( QgsMapSettings::Antialiasing ) ); QPaintDevice* thePaintDevice = mPainter->device(); QString errMsg = QString( "pre-set DPI not equal to painter's DPI (%1 vs %2)" ).arg( thePaintDevice->logicalDpiX() ).arg( mSettings.outputDpi() ); Q_ASSERT_X( thePaintDevice->logicalDpiX() == mSettings.outputDpi(), "Job::startRender()", errMsg.toAscii().data() ); delete mLabelingEngine; mLabelingEngine = nullptr; delete mLabelingEngineV2; mLabelingEngineV2 = nullptr; if ( mSettings.testFlag( QgsMapSettings::DrawLabeling ) ) { #ifdef LABELING_V2 mLabelingEngineV2 = new QgsLabelingEngineV2(); mLabelingEngineV2->readSettingsFromProject(); mLabelingEngineV2->setMapSettings( mSettings ); #else mLabelingEngine = new QgsPalLabeling; mLabelingEngine->loadEngineSettings(); mLabelingEngine->init( mSettings ); #endif } mLayerJobs = prepareJobs( mPainter, mLabelingEngine, mLabelingEngineV2 ); QgsDebugMsg( "Rendering prepared in (seconds): " + QString( "%1" ).arg( prepareTime.elapsed() / 1000.0 ) ); if ( mRenderSynchronously ) { // do the rendering right now! doRender(); return; } // now we are ready to start rendering! connect( &mFutureWatcher, SIGNAL( finished() ), SLOT( futureFinished() ) ); mFuture = QtConcurrent::run( staticRender, this ); mFutureWatcher.setFuture( mFuture ); }
void ApplicationCore::setState(State state) { if (m_state == state) return; qDebug() << "ApplicationCore::setState: going from" << StateNames[m_state] << "to" << StateNames[state]; State previous = m_state; try { switch (m_state) { case Constructed: break; // ignore, but this state is never re-entered case StartingUp: leaveStartingUpState(); break; case Configuring: leaveConfiguringState(); break; case Connecting: leaveConnectingState(); break; case Connected: leaveConnectedState(); break; case Disconnecting: leaveDisconnectingState(); break; case ShuttingDown: leaveShuttingDownState(); break; default: Q_ASSERT_X(false, "ApplicationCore::setState", "Unknown previous application state"); } m_state = state; Q_FOREACH (auto e, m_uiElements) e->stateChanged(m_state); switch (m_state) { case StartingUp: m_model.charmDataModel()->stateChanged(previous, state); m_controller.stateChanged(previous, state); // FIXME unnecessary? // m_mainWindow.stateChanged(previous); // m_timeTracker.stateChanged( previous ); enterStartingUpState(); break; case Configuring: enterConfiguringState(); break; case Connecting: m_model.charmDataModel()->stateChanged(previous, state); m_controller.stateChanged(previous, state); // FIXME unnecessary? // m_mainWindow.stateChanged(previous); // m_timeTracker.stateChanged( previous ); enterConnectingState(); break; case Connected: m_model.charmDataModel()->stateChanged(previous, state); m_controller.stateChanged(previous, state); // FIXME unnecessary? // m_mainWindow.stateChanged(previous); // m_timeTracker.stateChanged( previous ); enterConnectedState(); break; case Disconnecting: // FIXME unnecessary? // m_timeTracker.stateChanged( previous ); // m_mainWindow.stateChanged(previous); m_model.charmDataModel()->stateChanged(previous, state); m_controller.stateChanged(previous, state); enterDisconnectingState(); break; case ShuttingDown: // FIXME unnecessary? // m_timeTracker.stateChanged( previous ); // m_mainWindow.stateChanged(previous); m_model.charmDataModel()->stateChanged(previous, state); m_controller.stateChanged(previous, state); enterShuttingDownState(); break; default: Q_ASSERT_X(false, "ApplicationCore::setState", "Unknown new application state"); } } catch (const CharmException &e) { showCritical(tr("Critical Charm Problem"), e.what()); QCoreApplication::quit(); } }
MessageValidator::~MessageValidator() { Q_ASSERT_X(m_hasChecked, Q_FUNC_INFO, "You must call success()."); }
ApplicationCore &ApplicationCore::instance() { Q_ASSERT_X(m_instance, "ApplicationCore::instance", "Singleton not constructed yet"); return *m_instance; }
/*! Creates a \c ptImageView instance. \param parent The image view’s parent widget. */ ptImageView::ptImageView(QWidget *AParent): QGraphicsView(AParent), MinZoom(0.05), MaxZoom(4.0), MaxImageSize(std::numeric_limits<int>::max()), // Cache is split 60/40 between thumbnail list and image view FThumbGen(Settings->GetInt("FileMgrThumbCacheSize")*1024*1024 * 0.4, 1) { Q_ASSERT_X(Theme != nullptr, __PRETTY_FUNCTION__, "ptTheme pointer is null."); Q_ASSERT_X(Settings != nullptr, __PRETTY_FUNCTION__, "ptSettings pointer is null."); ZoomFactors << MinZoom << 0.08 << 0.10 << 0.15 << 0.20 << 0.25 << 0.33 << 0.50 << 0.66 << 1.00 << 1.50 << 2.00 << 3.00 << MaxZoom; this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); this->setFocusPolicy(Qt::NoFocus); FThumbGen.connectBroadcast(this, SLOT(receiveImage(uint,TThumbPtr))); // Layout to always fill the complete image pane with ViewWindow FParentLayout = new QGridLayout(AParent); FParentLayout->setContentsMargins(9,9,9,9); FParentLayout->setSpacing(0); FParentLayout->addWidget(this); this->setStyleSheet("QGraphicsView { border: none; }"); // We create a Graphicsscene and connect it. FScene = new QGraphicsScene(0, 0, 0, 0, this); this->setScene(FScene); // Init FPixmapItem = FScene->addPixmap(QPixmap()); FPixmapItem->setPos(0,0); FZoomMode = ptZoomMode_Fit; FZoomFactor = 1.0; FZoom = 100; FDragDelta = new QLine(); FLeftMousePressed = false; FZoomSizeOverlay = new ptReportOverlay(this, "", QColor(75,150,255), QColor(190,220,255), 1000, Qt::AlignRight, 20); FStatusOverlay = new ptReportOverlay(this, "", QColor(), QColor(), 0, Qt::AlignLeft, 20); FStatusOverlay->setColors(QColor(75,150,255), QColor(190,220,255)); // blue FStatusOverlay->setDuration(0); // timer for decoupling the mouse wheel FResizeTimeOut = 50; FResizeTimer = new QTimer(this); FResizeTimer->setSingleShot(1); connect(FResizeTimer,SIGNAL(timeout()), this,SLOT(resizeTimerExpired())); FResizeEventTimer.setSingleShot(true); FResizeEventTimer.setInterval(100); connect(&FResizeEventTimer, SIGNAL(timeout()), this, SLOT(zoomFit())); //------------------------------------- // Create actions for context menu FZoomInAction = new QAction(tr("Zoom &in") + "\t" + tr("1"), this); FZoomInAction->setIcon(QIcon(QString::fromUtf8(":/dark/icons/zoom-in.png"))); connect(FZoomInAction, SIGNAL(triggered()), this, SLOT(zoomIn())); FZoom100Action = new QAction(tr("Zoom &100%") + "\t" + tr("2"), this); FZoom100Action->setIcon(QIcon(QString::fromUtf8(":/dark/icons/zoom-original.png"))); connect(FZoom100Action, SIGNAL(triggered()), this, SLOT(zoom100())); FZoomOutAction = new QAction(tr("Zoom &out") + "\t" + tr("3"), this); FZoomOutAction->setIcon(QIcon(QString::fromUtf8(":/dark/icons/zoom-out.png"))); connect(FZoomOutAction, SIGNAL(triggered()), this, SLOT(zoomOut())); FZoomFitAction = new QAction(tr("Zoom &fit") + "\t" + tr("4"), this); FZoomFitAction->setIcon(QIcon(QString::fromUtf8(":/dark/icons/zoom-fit.png"))); connect(FZoomFitAction, SIGNAL(triggered()), this, SLOT(zoomFit())); }
ApplicationCore::ApplicationCore(TaskId startupTask, bool hideAtStart, QObject *parent) : QObject(parent) , m_actionStopAllTasks(this) , m_actionQuit(this) , m_actionAboutDialog(this) , m_actionPreferences(this) , m_actionExportToXml(this) , m_actionImportFromXml(this) , m_actionSyncTasks(this) , m_actionImportTasks(this) , m_actionExportTasks(this) , m_actionCheckForUpdates(this) , m_actionEnterVacation(this) , m_actionActivityReport(this) , m_actionWeeklyTimesheetReport(this) , m_actionMonthlyTimesheetReport(this) , m_uiElements( { &m_timeTracker, &m_tasksView, &m_eventView }), m_startupTask(startupTask) , m_hideAtStart(hideAtStart) #ifdef Q_OS_WIN , m_windowsJumpList(new QWinJumpList(this)) #endif , m_dateChangeWatcher(new DateChangeWatcher(this)) { // QApplication setup QApplication::setQuitOnLastWindowClosed(false); // application metadata setup // note that this modifies the behaviour of QSettings: QCoreApplication::setOrganizationName(QStringLiteral("KDAB")); QCoreApplication::setOrganizationDomain(QStringLiteral("kdab.com")); QCoreApplication::setApplicationName(QStringLiteral("Charm")); QCoreApplication::setApplicationVersion(CharmVersion()); QLocalSocket uniqueApplicationSocket; QString serverName(QStringLiteral("com.kdab.charm")); QString charmHomeEnv(QString::fromLocal8Bit(qgetenv("CHARM_HOME"))); if (!charmHomeEnv.isEmpty()) { serverName.append(QStringLiteral("_%1").arg( charmHomeEnv.replace(QRegExp(QLatin1String(":?/|:?\\\\")), QStringLiteral("_")))); } #ifndef NDEBUG serverName.append(QStringLiteral("_debug")); #endif uniqueApplicationSocket.connectToServer(serverName, QIODevice::ReadWrite); if (uniqueApplicationSocket.waitForConnected(1000)) { QByteArray command; if (startupTask != -1) { command = StartTaskCommand + QByteArray::number(startupTask); } else { command = RaiseWindowCommand; } command += '\n'; qint64 written = uniqueApplicationSocket.write(command); if (written == -1 || written != command.length()) { qWarning() << "Failed to pass " << command << " to running charm instance, error: " << uniqueApplicationSocket.errorString(); } uniqueApplicationSocket.flush(); uniqueApplicationSocket.waitForBytesWritten(); throw AlreadyRunningException(); } connect(&m_uniqueApplicationServer, &QLocalServer::newConnection, this, &ApplicationCore::slotHandleUniqueApplicationConnection, Qt::QueuedConnection); QFile::remove(QDir::tempPath() + QLatin1Char('/') + serverName); bool listening = m_uniqueApplicationServer.listen(serverName); if (!listening) qDebug() << "Failed to create QLocalServer for unique application support:" << m_uniqueApplicationServer.errorString(); Q_INIT_RESOURCE(CharmResources); Q_ASSERT_X(m_instance == 0, "Application ctor", "Application is a singleton and cannot be created more than once"); m_instance = this; qRegisterMetaType<State>("State"); qRegisterMetaType<Event>("Event"); // exit process (app will only exit once controller says it is ready) connect(&m_controller, &Controller::readyToQuit, this, &ApplicationCore::slotControllerReadyToQuit); connectControllerAndModel(&m_controller, m_model.charmDataModel()); Charm::connectControllerAndView(&m_controller, &m_timeTracker); // save the configuration (configuration is managed by the application) connect(&m_timeTracker, &CharmWindow::saveConfiguration, this, &ApplicationCore::slotSaveConfiguration); connect(&m_timeTracker, &TimeTrackingWindow::showNotification, this, &ApplicationCore::slotShowNotification); connect(&m_timeTracker, &TimeTrackingWindow::taskMenuChanged, this, &ApplicationCore::slotPopulateTrayIconMenu); // save the configuration (configuration is managed by the application) connect(&m_tasksView, &TasksView::saveConfiguration, this, &ApplicationCore::slotSaveConfiguration); // due to multiple inheritence we can't use the new style connects here connect(&m_tasksView, SIGNAL(emitCommand(CharmCommand*)), &m_timeTracker, SLOT(sendCommand(CharmCommand*))); connect(&m_tasksView, SIGNAL(emitCommandRollback(CharmCommand*)), &m_timeTracker, SLOT(sendCommandRollback(CharmCommand*))); connect(&m_eventView, SIGNAL(emitCommand(CharmCommand*)), &m_timeTracker, SLOT(sendCommand(CharmCommand*))); connect(&m_eventView, SIGNAL(emitCommandRollback(CharmCommand*)), &m_timeTracker, SLOT(sendCommandRollback(CharmCommand*))); // my own signals: connect(this, &ApplicationCore::goToState, this, &ApplicationCore::setState, Qt::QueuedConnection); // system tray icon: m_actionStopAllTasks.setText(tr("Stop Current Task")); m_actionStopAllTasks.setShortcut(Qt::Key_Escape); m_actionStopAllTasks.setShortcutContext(Qt::ApplicationShortcut); mainView().addAction(&m_actionStopAllTasks); // for the shortcut to work connect(&m_actionStopAllTasks, &QAction::triggered, this, &ApplicationCore::slotStopAllTasks); m_systrayContextMenu.addAction(&m_actionStopAllTasks); m_systrayContextMenu.addSeparator(); m_systrayContextMenu.addAction(m_timeTracker.openCharmAction()); m_systrayContextMenu.addAction(&m_actionQuit); m_trayIcon.setContextMenu(&m_systrayContextMenu); m_trayIcon.setToolTip(tr("No active events")); m_trayIcon.setIcon(Data::charmTrayIcon()); m_trayIcon.show(); QApplication::setWindowIcon(Data::charmIcon()); // set up actions: m_actionQuit.setShortcut(Qt::CTRL + Qt::Key_Q); m_actionQuit.setText(tr("Quit")); m_actionQuit.setIcon(Data::quitCharmIcon()); connect(&m_actionQuit, &QAction::triggered, this, &ApplicationCore::slotQuitApplication); m_actionAboutDialog.setText(tr("About Charm")); connect(&m_actionAboutDialog, &QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotAboutDialog); m_actionPreferences.setText(tr("Preferences")); m_actionPreferences.setIcon(Data::configureIcon()); connect(&m_actionPreferences, &QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotEditPreferences); m_actionPreferences.setEnabled(true); m_actionImportFromXml.setText(tr("Import Database from Previous Export...")); connect(&m_actionImportFromXml, &QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotImportFromXml); m_actionExportToXml.setText(tr("Export Database...")); connect(&m_actionExportToXml, &QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotExportToXml); m_actionSyncTasks.setText(tr("Update Task Definitions...")); //the signature of QAction::triggered does not match slotSyncTasks connect(&m_actionSyncTasks,&QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotSyncTasksVerbose); m_actionImportTasks.setText(tr("Import and Merge Task Definitions...")); connect(&m_actionImportTasks, &QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotImportTasks); m_actionExportTasks.setText(tr("Export Task Definitions...")); connect(&m_actionExportTasks, &QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotExportTasks); m_actionCheckForUpdates.setText(tr("Check for Updates...")); #if 0 // TODO this role should be set to have the action in the app menu, but that // leads to duplicated entries, as each of the three main windows adds the action to the menu // and Qt doesn't prevent duplicates (#222) m_actionCheckForUpdates.setMenuRole(QAction::ApplicationSpecificRole); #endif connect(&m_actionCheckForUpdates, &QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotCheckForUpdatesManual); m_actionEnterVacation.setText(tr("Enter Vacation...")); connect(&m_actionEnterVacation, &QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotEnterVacation); m_actionActivityReport.setText(tr("Activity Report...")); m_actionActivityReport.setShortcut(Qt::CTRL + Qt::Key_A); connect(&m_actionActivityReport, &QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotActivityReport); m_actionWeeklyTimesheetReport.setText(tr("Weekly Timesheet...")); m_actionWeeklyTimesheetReport.setShortcut(Qt::CTRL + Qt::Key_R); connect(&m_actionWeeklyTimesheetReport, &QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotWeeklyTimesheetReport); m_actionMonthlyTimesheetReport.setText(tr("Monthly Timesheet...")); m_actionMonthlyTimesheetReport.setShortcut(Qt::CTRL + Qt::Key_M); connect(&m_actionMonthlyTimesheetReport, &QAction::triggered, &m_timeTracker, &TimeTrackingWindow::slotMonthlyTimesheetReport); // set up idle detection m_idleDetector = IdleDetector::createIdleDetector(this); Q_ASSERT(m_idleDetector); connect(m_idleDetector, SIGNAL(maybeIdle()), SLOT(slotMaybeIdle())); setHttpActionsVisible(Lotsofcake::Configuration().isConfigured()); // add default plugin path for deployment QCoreApplication::addLibraryPath(QCoreApplication::applicationDirPath() + QStringLiteral("/plugins")); if (QCoreApplication::applicationDirPath().endsWith(QLatin1String("MacOS"))) QCoreApplication::addLibraryPath(QCoreApplication::applicationDirPath() + QStringLiteral("/../plugins")); // set up command interface #ifdef CHARM_CI_SUPPORT m_cmdInterface = new CharmCommandInterface(this); #endif // CHARM_CI_SUPPORT // Ladies and gentlemen, please raise upon your seats - // the show is about to begin: emit goToState(StartingUp); }
static QEvent *cloneEvent(QEvent *e) { switch (e->type()) { case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseButtonDblClick: case QEvent::MouseMove: return new QMouseEvent(*static_cast<QMouseEvent*>(e)); case QEvent::KeyPress: case QEvent::KeyRelease: return new QKeyEvent(*static_cast<QKeyEvent*>(e)); case QEvent::FocusIn: case QEvent::FocusOut: return new QFocusEvent(*static_cast<QFocusEvent*>(e)); case QEvent::Enter: return new QEvent(*e); case QEvent::Leave: return new QEvent(*e); break; case QEvent::Paint: Q_ASSERT_X(false, "cloneEvent()", "not implemented"); break; case QEvent::Move: return new QMoveEvent(*static_cast<QMoveEvent*>(e)); case QEvent::Resize: return new QResizeEvent(*static_cast<QResizeEvent*>(e)); case QEvent::Create: Q_ASSERT_X(false, "cloneEvent()", "not implemented"); break; case QEvent::Destroy: Q_ASSERT_X(false, "cloneEvent()", "not implemented"); break; case QEvent::Show: return new QShowEvent(*static_cast<QShowEvent*>(e)); case QEvent::Hide: return new QHideEvent(*static_cast<QHideEvent*>(e)); case QEvent::Close: return new QCloseEvent(*static_cast<QCloseEvent*>(e)); case QEvent::Quit: return new QEvent(*e); case QEvent::ParentChange: return new QEvent(*e); case QEvent::ParentAboutToChange: return new QEvent(*e); case QEvent::ThreadChange: return new QEvent(*e); case QEvent::WindowActivate: case QEvent::WindowDeactivate: return new QEvent(*e); case QEvent::ShowToParent: return new QEvent(*e); case QEvent::HideToParent: return new QEvent(*e); #ifndef QT_NO_WHEELEVENT case QEvent::Wheel: return new QWheelEvent(*static_cast<QWheelEvent*>(e)); #endif //QT_NO_WHEELEVENT case QEvent::WindowTitleChange: return new QEvent(*e); case QEvent::WindowIconChange: return new QEvent(*e); case QEvent::ApplicationWindowIconChange: return new QEvent(*e); case QEvent::ApplicationFontChange: return new QEvent(*e); case QEvent::ApplicationLayoutDirectionChange: return new QEvent(*e); case QEvent::ApplicationPaletteChange: return new QEvent(*e); case QEvent::PaletteChange: return new QEvent(*e); case QEvent::Clipboard: Q_ASSERT_X(false, "cloneEvent()", "not implemented"); break; case QEvent::Speech: Q_ASSERT_X(false, "cloneEvent()", "not implemented"); break; case QEvent::MetaCall: Q_ASSERT_X(false, "cloneEvent()", "not implemented"); break; case QEvent::SockAct: return new QEvent(*e); case QEvent::WinEventAct: return new QEvent(*e); case QEvent::DeferredDelete: return new QEvent(*e); #ifndef QT_NO_DRAGANDDROP case QEvent::DragEnter: return new QDragEnterEvent(*static_cast<QDragEnterEvent*>(e)); case QEvent::DragMove: return new QDragMoveEvent(*static_cast<QDragMoveEvent*>(e)); case QEvent::DragLeave: return new QDragLeaveEvent(*static_cast<QDragLeaveEvent*>(e)); case QEvent::Drop: return new QDropEvent(*static_cast<QDragMoveEvent*>(e)); case QEvent::DragResponse: return new QDragResponseEvent(*static_cast<QDragResponseEvent*>(e)); #endif case QEvent::ChildAdded: return new QChildEvent(*static_cast<QChildEvent*>(e)); case QEvent::ChildPolished: return new QChildEvent(*static_cast<QChildEvent*>(e)); #ifdef QT3_SUPPORT case QEvent::ChildInsertedRequest: return new QEvent(*e); case QEvent::ChildInserted: return new QChildEvent(*static_cast<QChildEvent*>(e)); case QEvent::LayoutHint: Q_ASSERT_X(false, "cloneEvent()", "not implemented"); break; #endif case QEvent::ChildRemoved: return new QChildEvent(*static_cast<QChildEvent*>(e)); case QEvent::ShowWindowRequest: return new QEvent(*e); case QEvent::PolishRequest: return new QEvent(*e); case QEvent::Polish: return new QEvent(*e); case QEvent::LayoutRequest: return new QEvent(*e); case QEvent::UpdateRequest: return new QEvent(*e); case QEvent::UpdateLater: return new QEvent(*e); case QEvent::EmbeddingControl: return new QEvent(*e); case QEvent::ActivateControl: return new QEvent(*e); case QEvent::DeactivateControl: return new QEvent(*e); #ifndef QT_NO_CONTEXTMENU case QEvent::ContextMenu: return new QContextMenuEvent(*static_cast<QContextMenuEvent*>(e)); #endif case QEvent::InputMethod: return new QInputMethodEvent(*static_cast<QInputMethodEvent*>(e)); case QEvent::AccessibilityPrepare: return new QEvent(*e); #ifndef QT_NO_TABLETEVENT case QEvent::TabletMove: return new QTabletEvent(*static_cast<QTabletEvent*>(e)); #endif //QT_NO_TABLETEVENT case QEvent::LocaleChange: return new QEvent(*e); case QEvent::LanguageChange: return new QEvent(*e); case QEvent::LayoutDirectionChange: return new QEvent(*e); case QEvent::Style: return new QEvent(*e); #ifndef QT_NO_TABLETEVENT case QEvent::TabletPress: return new QTabletEvent(*static_cast<QTabletEvent*>(e)); case QEvent::TabletRelease: return new QTabletEvent(*static_cast<QTabletEvent*>(e)); #endif //QT_NO_TABLETEVENT case QEvent::OkRequest: return new QEvent(*e); case QEvent::HelpRequest: return new QEvent(*e); case QEvent::IconDrag: return new QIconDragEvent(*static_cast<QIconDragEvent*>(e)); case QEvent::FontChange: return new QEvent(*e); case QEvent::EnabledChange: return new QEvent(*e); case QEvent::ActivationChange: return new QEvent(*e); case QEvent::StyleChange: return new QEvent(*e); case QEvent::IconTextChange: return new QEvent(*e); case QEvent::ModifiedChange: return new QEvent(*e); case QEvent::MouseTrackingChange: return new QEvent(*e); case QEvent::WindowBlocked: return new QEvent(*e); case QEvent::WindowUnblocked: return new QEvent(*e); case QEvent::WindowStateChange: return new QWindowStateChangeEvent(*static_cast<QWindowStateChangeEvent*>(e)); case QEvent::ToolTip: return new QHelpEvent(*static_cast<QHelpEvent*>(e)); case QEvent::WhatsThis: return new QHelpEvent(*static_cast<QHelpEvent*>(e)); #ifndef QT_NO_STATUSTIP case QEvent::StatusTip: return new QStatusTipEvent(*static_cast<QStatusTipEvent*>(e)); #endif //QT_NO_STATUSTIP #ifndef QT_NO_ACTION case QEvent::ActionChanged: case QEvent::ActionAdded: case QEvent::ActionRemoved: return new QActionEvent(*static_cast<QActionEvent*>(e)); #endif case QEvent::FileOpen: return new QFileOpenEvent(*static_cast<QFileOpenEvent*>(e)); #ifndef QT_NO_SHORTCUT case QEvent::Shortcut: return new QShortcutEvent(*static_cast<QShortcutEvent*>(e)); #endif //QT_NO_SHORTCUT case QEvent::ShortcutOverride: return new QKeyEvent(*static_cast<QKeyEvent*>(e)); #ifdef QT3_SUPPORT case QEvent::Accel: Q_ASSERT_X(false, "cloneEvent()", "not implemented"); break; case QEvent::AccelAvailable: Q_ASSERT_X(false, "cloneEvent()", "not implemented"); break; #endif #ifndef QT_NO_WHATSTHIS case QEvent::WhatsThisClicked: return new QWhatsThisClickedEvent(*static_cast<QWhatsThisClickedEvent*>(e)); #endif //QT_NO_WHATSTHIS #ifndef QT_NO_TOOLBAR case QEvent::ToolBarChange: return new QToolBarChangeEvent(*static_cast<QToolBarChangeEvent*>(e)); #endif //QT_NO_TOOLBAR case QEvent::ApplicationActivate: return new QEvent(*e); case QEvent::ApplicationDeactivate: return new QEvent(*e); case QEvent::QueryWhatsThis: return new QHelpEvent(*static_cast<QHelpEvent*>(e)); case QEvent::EnterWhatsThisMode: return new QEvent(*e); case QEvent::LeaveWhatsThisMode: return new QEvent(*e); case QEvent::ZOrderChange: return new QEvent(*e); case QEvent::HoverEnter: case QEvent::HoverLeave: case QEvent::HoverMove: return new QHoverEvent(*static_cast<QHoverEvent*>(e)); case QEvent::AccessibilityHelp: Q_ASSERT_X(false, "cloneEvent()", "not implemented"); break; case QEvent::AccessibilityDescription: Q_ASSERT_X(false, "cloneEvent()", "not implemented"); break; #ifdef QT_KEYPAD_NAVIGATION case QEvent::EnterEditFocus: return new QEvent(*e); case QEvent::LeaveEditFocus: return new QEvent(*e); #endif case QEvent::AcceptDropsChange: return new QEvent(*e); #ifdef QT3_SUPPORT case QEvent::MenubarUpdated: return new QMenubarUpdatedEvent(*static_cast<QMenubarUpdatedEvent*>(e)); #endif case QEvent::ZeroTimerEvent: Q_ASSERT_X(false, "cloneEvent()", "not implemented"); break; #ifndef QT_NO_GRAPHICSVIEW case QEvent::GraphicsSceneMouseMove: case QEvent::GraphicsSceneMousePress: case QEvent::GraphicsSceneMouseRelease: case QEvent::GraphicsSceneMouseDoubleClick: { QGraphicsSceneMouseEvent *me = static_cast<QGraphicsSceneMouseEvent*>(e); QGraphicsSceneMouseEvent *me2 = new QGraphicsSceneMouseEvent(me->type()); me2->setWidget(me->widget()); me2->setPos(me->pos()); me2->setScenePos(me->scenePos()); me2->setScreenPos(me->screenPos()); // ### for all buttons me2->setButtonDownPos(Qt::LeftButton, me->buttonDownPos(Qt::LeftButton)); me2->setButtonDownPos(Qt::RightButton, me->buttonDownPos(Qt::RightButton)); me2->setButtonDownScreenPos(Qt::LeftButton, me->buttonDownScreenPos(Qt::LeftButton)); me2->setButtonDownScreenPos(Qt::RightButton, me->buttonDownScreenPos(Qt::RightButton)); me2->setLastPos(me->lastPos()); me2->setLastScenePos(me->lastScenePos()); me2->setLastScreenPos(me->lastScreenPos()); me2->setButtons(me->buttons()); me2->setButton(me->button()); me2->setModifiers(me->modifiers()); return me2; } case QEvent::GraphicsSceneContextMenu: { QGraphicsSceneContextMenuEvent *me = static_cast<QGraphicsSceneContextMenuEvent*>(e); QGraphicsSceneContextMenuEvent *me2 = new QGraphicsSceneContextMenuEvent(me->type()); me2->setWidget(me->widget()); me2->setPos(me->pos()); me2->setScenePos(me->scenePos()); me2->setScreenPos(me->screenPos()); me2->setModifiers(me->modifiers()); me2->setReason(me->reason()); return me2; } case QEvent::GraphicsSceneHoverEnter: case QEvent::GraphicsSceneHoverMove: case QEvent::GraphicsSceneHoverLeave: { QGraphicsSceneHoverEvent *he = static_cast<QGraphicsSceneHoverEvent*>(e); QGraphicsSceneHoverEvent *he2 = new QGraphicsSceneHoverEvent(he->type()); he2->setPos(he->pos()); he2->setScenePos(he->scenePos()); he2->setScreenPos(he->screenPos()); he2->setLastPos(he->lastPos()); he2->setLastScenePos(he->lastScenePos()); he2->setLastScreenPos(he->lastScreenPos()); he2->setModifiers(he->modifiers()); return he2; } case QEvent::GraphicsSceneHelp: return new QHelpEvent(*static_cast<QHelpEvent*>(e)); case QEvent::GraphicsSceneDragEnter: case QEvent::GraphicsSceneDragMove: case QEvent::GraphicsSceneDragLeave: case QEvent::GraphicsSceneDrop: { QGraphicsSceneDragDropEvent *dde = static_cast<QGraphicsSceneDragDropEvent*>(e); QGraphicsSceneDragDropEvent *dde2 = new QGraphicsSceneDragDropEvent(dde->type()); dde2->setPos(dde->pos()); dde2->setScenePos(dde->scenePos()); dde2->setScreenPos(dde->screenPos()); dde2->setButtons(dde->buttons()); dde2->setModifiers(dde->modifiers()); return dde2; } case QEvent::GraphicsSceneWheel: { QGraphicsSceneWheelEvent *we = static_cast<QGraphicsSceneWheelEvent*>(e); QGraphicsSceneWheelEvent *we2 = new QGraphicsSceneWheelEvent(we->type()); we2->setPos(we->pos()); we2->setScenePos(we->scenePos()); we2->setScreenPos(we->screenPos()); we2->setButtons(we->buttons()); we2->setModifiers(we->modifiers()); we2->setOrientation(we->orientation()); we2->setDelta(we->delta()); return we2; } #endif case QEvent::KeyboardLayoutChange: return new QEvent(*e); case QEvent::DynamicPropertyChange: return new QDynamicPropertyChangeEvent(*static_cast<QDynamicPropertyChangeEvent*>(e)); #ifndef QT_NO_TABLETEVENT case QEvent::TabletEnterProximity: case QEvent::TabletLeaveProximity: return new QTabletEvent(*static_cast<QTabletEvent*>(e)); #endif //QT_NO_TABLETEVENT case QEvent::NonClientAreaMouseMove: case QEvent::NonClientAreaMouseButtonPress: case QEvent::NonClientAreaMouseButtonRelease: case QEvent::NonClientAreaMouseButtonDblClick: return new QMouseEvent(*static_cast<QMouseEvent*>(e)); case QEvent::MacSizeChange: return new QEvent(*e); case QEvent::ContentsRectChange: return new QEvent(*e); case QEvent::MacGLWindowChange: return new QEvent(*e); case QEvent::FutureCallOut: Q_ASSERT_X(false, "cloneEvent()", "not implemented"); break; #ifndef QT_NO_GRAPHICSVIEW case QEvent::GraphicsSceneResize: { QGraphicsSceneResizeEvent *re = static_cast<QGraphicsSceneResizeEvent*>(e); QGraphicsSceneResizeEvent *re2 = new QGraphicsSceneResizeEvent(); re2->setOldSize(re->oldSize()); re2->setNewSize(re->newSize()); return re2; } case QEvent::GraphicsSceneMove: { QGraphicsSceneMoveEvent *me = static_cast<QGraphicsSceneMoveEvent*>(e); QGraphicsSceneMoveEvent *me2 = new QGraphicsSceneMoveEvent(); me2->setWidget(me->widget()); me2->setNewPos(me->newPos()); me2->setOldPos(me->oldPos()); return me2; } #endif case QEvent::CursorChange: return new QEvent(*e); case QEvent::ToolTipChange: return new QEvent(*e); case QEvent::NetworkReplyUpdated: Q_ASSERT_X(false, "cloneEvent()", "not implemented"); break; case QEvent::GrabMouse: case QEvent::UngrabMouse: case QEvent::GrabKeyboard: case QEvent::UngrabKeyboard: return new QEvent(*e); case QEvent::TouchBegin: case QEvent::TouchUpdate: case QEvent::TouchEnd: return new QTouchEvent(*static_cast<QTouchEvent*>(e)); #ifndef QT_NO_GESTURES case QEvent::NativeGesture: Q_ASSERT_X(false, "cloneEvent()", "not implemented"); break; #endif case QEvent::RequestSoftwareInputPanel: case QEvent::CloseSoftwareInputPanel: return new QEvent(*e); case QEvent::UpdateSoftKeys: return new QEvent(*e); case QEvent::User: case QEvent::MaxUser: Q_ASSERT_X(false, "cloneEvent()", "not implemented"); break; default: ; } return qcoreStateMachineHandler()->cloneEvent(e); }
void KWidget::setAnchor( const QString& a ) { Q_D(KWidget); //检查布局 KWidget* p = qobject_cast<KWidget*>(parent()); Q_ASSERT_X(p, __FUNCTION__, "parent is null"); Q_ASSERT_X(p->layoutType() == KWidget::Anchor, __FUNCTION__, "layout type should be anchor"); QGraphicsLayout *layout = p->layout(); QGraphicsAnchorLayout *anchorLayout = static_cast<QGraphicsAnchorLayout*>(layout); if(anchorLayout == NULL) { Q_ASSERT_X(false, __FUNCTION__, "layout is not group layout"); return ; } if(d->bAddToAnchor) { p->removeLayoutItem(this); } //参数转换 int index = KWidget::staticMetaObject.indexOfEnumerator("AnchorPoint"); QMetaEnum enu = KWidget::staticMetaObject.enumerator(index); QStringList list = a.split('|'); Q_ASSERT_X(list.count()==4, __FUNCTION__, QString("%1 is not valide anchor info").arg(a).toLatin1().constData()); Qt::AnchorPoint anchorPoint[4]={Qt::AnchorLeft}; int distance[4]={0}; for (int i = 0; i < list.count() && i < 4; ++i) { QStringList innerList = list[i].split(':'); Q_ASSERT_X(innerList.count()==2, __FUNCTION__, QString("%1 is not valide anchor info").arg(a).toLatin1().constData()); if (innerList.count() >= 2) { int value = enu.keyToValue(innerList[0].toLatin1().constData()); Q_ASSERT_X(value != -1, __FUNCTION__, (innerList[0] + "is not a valid enum value").toLatin1().constData()); if (value == -1) { value = 0; } anchorPoint[i] = (Qt::AnchorPoint)value; distance[i] = innerList[1].toInt(); } } //AnchorLeft: int idx = 0; QGraphicsAnchor *anchorLeft = anchorLayout->addAnchor(anchorLayout, anchorPoint[idx], this, Qt::AnchorLeft); if(anchorLeft) { anchorLeft->setSpacing(distance[idx]); } else if(anchorPoint[idx] >= Qt::AnchorTop) { Q_ASSERT_X(false, __FUNCTION__, QString("it's not the same orientation for AnchorLeft: bad string is[%1]").arg(list.at(idx)).toStdString().c_str()); } else { Q_ASSERT_X(false, __FUNCTION__, QString("bad parameter.bad string:%1").arg(list.at(idx)).toStdString().c_str()); } //AnchorTop: idx = 1; QGraphicsAnchor *anchorTop = anchorLayout->addAnchor(anchorLayout, anchorPoint[idx], this, Qt::AnchorTop); if(anchorTop) { anchorTop->setSpacing(distance[idx]); } else if(anchorPoint[idx] < Qt::AnchorTop) { Q_ASSERT_X(false, __FUNCTION__, QString("it's not the same orientation for AnchorTop: bad string is[%1]").arg(list.at(idx)).toStdString().c_str()); } else { Q_ASSERT_X(false, __FUNCTION__, QString("bad parameter.bad string:%1").arg(list.at(idx)).toStdString().c_str()); } //AnchorRight: idx = 2; QGraphicsAnchor *anchorRight = anchorLayout->addAnchor(this, Qt::AnchorRight, anchorLayout, anchorPoint[idx]); if(anchorRight) { anchorRight->setSpacing(distance[idx]); } else if(anchorPoint[idx] >= Qt::AnchorTop) { Q_ASSERT_X(false, __FUNCTION__, QString("it's not the same orientation for AnchorRight: bad string is[%1]").arg(list.at(idx)).toStdString().c_str()); } else { Q_ASSERT_X(false, __FUNCTION__, QString("bad parameter.bad string:%1").arg(list.at(idx)).toStdString().c_str()); } //AnchorBottom idx = 3; QGraphicsAnchor *anchorBottom = anchorLayout->addAnchor(this, Qt::AnchorBottom, anchorLayout, anchorPoint[idx]); if(anchorBottom) { anchorBottom->setSpacing(distance[idx]); } else if(anchorPoint[idx] < Qt::AnchorTop) { Q_ASSERT_X(false, __FUNCTION__, QString("it's not the same orientation for AnchorBottom: bad string is[%1]").arg(list.at(idx)).toStdString().c_str()); } else { Q_ASSERT_X(false, __FUNCTION__, QString("bad parameter.bad string:%1").arg(list.at(idx)).toStdString().c_str()); } d->bAddToAnchor = true; }
void TimeLineCells::drawContent() { if ( m_pCache == NULL ) { m_pCache = new QPixmap( size() ); if ( m_pCache->isNull() ) { // fail to create cache return; } } QPainter painter( m_pCache ); Object* object = mEditor->object(); Q_ASSERT_X( object != nullptr, "", "" ); Layer* layer = object->getLayer( mEditor->layers()->currentLayerIndex() ); if ( layer == NULL ) return; // grey background of the view painter.setPen( Qt::NoPen ); painter.setBrush( Qt::lightGray ); painter.drawRect( QRect( 0, 0, width(), height() ) ); // --- draw layers of the current object for ( int i = 0; i < object->getLayerCount(); i++ ) { if ( i != mEditor->layers()->currentLayerIndex() ) { Layer* layeri = object->getLayer( i ); if ( layeri != NULL ) { switch ( m_eType ) { case TIMELINE_CELL_TYPE::Tracks: layeri->paintTrack( painter, this, m_offsetX, getLayerY( i ), width() - m_offsetX, getLayerHeight(), false, frameSize ); break; case TIMELINE_CELL_TYPE::Layers: layeri->paintLabel( painter, this, 0, getLayerY( i ), width() - 1, getLayerHeight(), false, mEditor->allLayers() ); break; } } } } if ( abs( getMouseMoveY() ) > 5 ) { if ( m_eType == TIMELINE_CELL_TYPE::Tracks ) { layer->paintTrack( painter, this, m_offsetX, getLayerY( mEditor->layers()->currentLayerIndex() ) + getMouseMoveY(), width() - m_offsetX, getLayerHeight(), true, frameSize ); } if ( m_eType == TIMELINE_CELL_TYPE::Layers ) { layer->paintLabel( painter, this, 0, getLayerY( mEditor->layers()->currentLayerIndex() ) + getMouseMoveY(), width() - 1, getLayerHeight(), true, mEditor->allLayers() ); } painter.setPen( Qt::black ); painter.drawRect( 0, getLayerY( getLayerNumber( endY ) ) - 1, width(), 2 ); } else { if ( m_eType == TIMELINE_CELL_TYPE::Tracks ) { layer->paintTrack( painter, this, m_offsetX, getLayerY( mEditor->layers()->currentLayerIndex() ), width() - m_offsetX, getLayerHeight(), true, frameSize ); } if ( m_eType == TIMELINE_CELL_TYPE::Layers ) { layer->paintLabel( painter, this, 0, getLayerY( mEditor->layers()->currentLayerIndex() ), width() - 1, getLayerHeight(), true, mEditor->allLayers() ); } } // --- draw top painter.setPen( Qt::NoPen ); painter.setBrush( QColor( 220, 220, 220 ) ); painter.drawRect( QRect( 0, 0, width() - 1, m_offsetY - 1 ) ); painter.setPen( Qt::gray ); painter.drawLine( 0, 0, width() - 1, 0 ); painter.drawLine( 0, m_offsetY - 2, width() - 1, m_offsetY - 2 ); painter.setPen( Qt::lightGray ); painter.drawLine( 0, m_offsetY - 3, width() - 1, m_offsetY - 3 ); painter.drawLine( 0, 0, 0, m_offsetY - 3 ); if ( m_eType == TIMELINE_CELL_TYPE::Layers ) { // --- draw circle painter.setPen( Qt::black ); if ( mEditor->allLayers() == 0 ) { painter.setBrush( Qt::NoBrush ); } if ( mEditor->allLayers() == 1 ) { painter.setBrush( Qt::darkGray ); } if ( mEditor->allLayers() == 2 ) { painter.setBrush( Qt::black ); } painter.setRenderHint( QPainter::Antialiasing, true ); painter.drawEllipse( 6, 4, 9, 9 ); painter.setRenderHint( QPainter::Antialiasing, false ); } else if ( m_eType == TIMELINE_CELL_TYPE::Tracks ) { // --- draw ticks painter.setPen( QColor( 70, 70, 70, 255 ) ); painter.setBrush( Qt::darkGray ); painter.setFont( QFont( "helvetica", 10 ) ); int incr = 0; int fps = mEditor->playback()->fps(); for ( int i = frameOffset; i < frameOffset + ( width() - m_offsetX ) / frameSize; i++ ) { incr = ( i < 9 ) ? 4 : 0; if ( i%fps == 0 ) { painter.drawLine( getFrameX( i ), 1, getFrameX( i ), 5 ); } else if ( i%fps == fps / 2 ) { painter.drawLine( getFrameX( i ), 1, getFrameX( i ), 5 ); } else { painter.drawLine( getFrameX( i ), 1, getFrameX( i ), 3 ); } if ( i == 0 || i%fps == fps - 1 ) { painter.drawText( QPoint( getFrameX( i ) + incr, 15 ), QString::number( i + 1 ) ); } } // --- draw left border line painter.setPen( Qt::darkGray ); painter.drawLine( 0, 0, 0, height() ); } }
void StatisticsObject::readStatisticsFromFile(int frameIdx, int typeID) { try { QFile inputFile(p_srcFilePath); if(inputFile.open(QIODevice::ReadOnly) == false) return; StatisticsItem anItem; QTextStream in(&inputFile); Q_ASSERT_X(p_pocTypeStartList.contains(frameIdx) && p_pocTypeStartList[frameIdx].contains(typeID), "StatisticsObject::readStatisticsFromFile", "POC/type not found in file. Do not call this function with POC/types that do not exist."); qint64 startPos = p_pocTypeStartList[frameIdx][typeID]; if (bFileSortedByPOC) { // If the statistics file is sorted by POC we have to start at the first entry of this POC and parse the // file until another POC is encountered. If this is not done, some information from a different typeID // could be ignored during parsing. // Get the position of the first line with the given frameIdx startPos = std::numeric_limits<qint64>::max(); QMap<int,qint64>::iterator it; for (it = p_pocTypeStartList[frameIdx].begin(); it != p_pocTypeStartList[frameIdx].end(); it++) if (it.value() < startPos) startPos = it.value(); } // fast forward in.seek(startPos); while (!in.atEnd()) { // read one line QString aLine = in.readLine(); // get components of this line QStringList rowItemList = parseCSVLine(aLine, ';'); if (rowItemList[0].isEmpty()) continue; int poc = rowItemList[0].toInt(); int type = rowItemList[5].toInt(); // if there is a new poc, we are done here! if( poc != frameIdx ) break; // if there is a new type and this is a non interleaved file, we are done here. if ( !bFileSortedByPOC && type != typeID ) break; int value1 = rowItemList[6].toInt(); int value2 = (rowItemList.count()>=8)?rowItemList[7].toInt():0; int posX = rowItemList[1].toInt(); int posY = rowItemList[2].toInt(); unsigned int width = rowItemList[3].toUInt(); unsigned int height = rowItemList[4].toUInt(); // Check if block is within the image range if (posX + width > p_width || posY + height > p_height) { // Block not in image throw("A block is outside of the specified image size in the statistics file."); } StatisticsType *statsType = getStatisticsType(type); Q_ASSERT_X(statsType != NULL, "StatisticsObject::readStatisticsFromFile", "Stat type not found."); anItem.type = ((statsType->visualizationType == colorMapType) || (statsType->visualizationType == colorRangeType)) ? blockType : arrowType; anItem.positionRect = QRect(posX, posY, width, height); anItem.rawValues[0] = value1; anItem.rawValues[1] = value2; anItem.color = QColor(); if (statsType->visualizationType == colorMapType) { ColorMap colorMap = statsType->colorMap; anItem.color = colorMap[value1]; } else if (statsType->visualizationType == colorRangeType) { if (statsType->scaleToBlockSize) anItem.color = statsType->colorRange->getColor((float)value1 / (float)(anItem.positionRect.width() * anItem.positionRect.height())); else anItem.color = statsType->colorRange->getColor((float)value1); } else if (statsType->visualizationType == vectorType) { // find color anItem.color = statsType->vectorColor; // calculate the vector size anItem.vector[0] = (float)value1 / statsType->vectorSampling; anItem.vector[1] = (float)value2 / statsType->vectorSampling; } // set grid color. if unset for this type, use color of type for grid, too if (statsType->gridColor.isValid()) { anItem.gridColor = statsType->gridColor; } else { anItem.gridColor = anItem.color; } p_statsCache[poc][type].append(anItem); } inputFile.close(); } // try catch ( const char * str ) { std::cerr << "Error while parsing: " << str << '\n'; setErrorState(QString("Error while parsing meta data: ") + QString(str)); return; } catch (...) { std::cerr << "Error while parsing."; setErrorState(QString("Error while parsing meta data.")); return; } return; }
// Output functions ---------------------------------------------------------- void XmlOutput::newTag(const QString &tag) { Q_ASSERT_X(tag.count(), "XmlOutput", "Cannot open an empty tag"); newTagOpen(tag); closeOpen(); }
virtual void setIndex_(const int which, const uint index) { if(indexType_ == IndexType_U16) {indices16[which] = index;} else if(indexType_ == IndexType_U32) {indices32[which] = index;} else{Q_ASSERT_X(false, Q_FUNC_INFO, "Unknown index type");} }