void Ilwis::Postgresql::PostgresqlDatabaseUtil::validateNotNullOrEmpty(QString parameter, QVariant value) const
{
    if (value.isNull() || !value.isValid()) {
        WARN1("Property '%1' is null or empty.", parameter);
    }
}
Example #2
0
QVariant ContractTableModel::data(const QModelIndex& index, int role) const
{
  int column = index.column();
  if (Qt::DisplayRole == role)
  {        
    if (17 == column || 18 == column || 19 == column)
    {        
      QVariant var = QSqlQueryModel::data(index, role);
      if (var.canConvert<QDateTime>())
      {
        return databaseModel()->convertFromServer(var.value<QDateTime>());
      }
      else 
      {
        return QVariant(QVariant::DateTime);
      }
    }
    else if (3 == column || 4 == column || 5 == column || 6 == column)
    {        
      QVariant var = QSqlQueryModel::data(index, role);
      if (var.canConvert<QDate>())
      {
        return databaseModel()->convertFromServer(var.value<QDate>());
      }
      else 
      {
        return QVariant(QVariant::Date);
      }
    }
    else if (7 == column)
    {
      QVariant amountVar = QSqlQueryModel::data(index, role);          
      if (amountVar.canConvert<qint64>())                    
      {
        return QVariant::fromValue(
            model::CurrencyAmount(amountVar.toLongLong()));
      }
      else 
      {
        return QVariant();
      }
    }        
    else if (10 == column)
    {
      QVariant var = QSqlQueryModel::data(index, role);
      if (var.isNull())
      {
        return var;
      }
      if (var.canConvert<QDate>())
      {
        return databaseModel()->convertFromServer(var.value<QDate>());
      }
      else 
      {
        return QVariant(QVariant::Date);
      }
    } 
    else if (9 == column)
    {
      return QVariant();
    }
  }
  else if (Qt::TextAlignmentRole == role && index.isValid())
  {
    if (1 == column || 2 == column || 7 == column)
    {
      return QVariant(Qt::Alignment(Qt::AlignRight | Qt::AlignVCenter));
    }          
    else if (column)
    {
      return QVariant(Qt::Alignment(Qt::AlignLeft | Qt::AlignVCenter));
    }
  }
  else if (Qt::CheckStateRole == role && 9 == column)
  {
    return QSqlQueryModel::data(index).toInt() != 0 
        ? Qt::Checked : Qt::Unchecked;
  }
  return QSqlQueryModel::data(index, role);      
}    
Example #3
0
bool SqlitePreparedStatement::bindValue(KDbField *field, const QVariant& value, int par)
{
    if (value.isNull()) {
        //no value to bind or the value is null: bind NULL
        int res = sqlite3_bind_null(m_sqlResult->prepared_st, par);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        return true;
    }
    if (field->isTextType()) {
        //! @todo optimize: make a static copy so SQLITE_STATIC can be used
        const QByteArray utf8String(value.toString().toUtf8());
        int res = sqlite3_bind_text(m_sqlResult->prepared_st, par,
                                    utf8String.constData(), utf8String.length(), SQLITE_TRANSIENT /*??*/);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        return true;
    }

    switch (field->type()) {
    case KDbField::Byte:
    case KDbField::ShortInteger:
    case KDbField::Integer: {
        //! @todo what about unsigned > INT_MAX ?
        bool ok;
        const int intValue = value.toInt(&ok);
        if (ok) {
            int res = sqlite3_bind_int(m_sqlResult->prepared_st, par, intValue);
            if (res != SQLITE_OK) {
                m_result.setServerErrorCode(res);
                storeResult(&m_result);
                return false;
            }
        } else {
            int res = sqlite3_bind_null(m_sqlResult->prepared_st, par);
            if (res != SQLITE_OK) {
                m_result.setServerErrorCode(res);
                storeResult(&m_result);
                return false;
            }
        }
        break;
    }
    case KDbField::Float:
    case KDbField::Double: {
        int res = sqlite3_bind_double(m_sqlResult->prepared_st, par, value.toDouble());
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        break;
    }
    case KDbField::BigInteger: {
        //! @todo what about unsigned > LLONG_MAX ?
        bool ok;
        const qint64 int64Value = value.toLongLong(&ok);
        if (ok) {
            int res = sqlite3_bind_int64(m_sqlResult->prepared_st, par, int64Value);
            if (res != SQLITE_OK) {
                m_result.setServerErrorCode(res);
                storeResult(&m_result);
                return false;
            }
        } else {
            int res = sqlite3_bind_null(m_sqlResult->prepared_st, par);
            if (res != SQLITE_OK) {
                m_result.setServerErrorCode(res);
                storeResult(&m_result);
                return false;
            }
        }
        break;
    }
    case KDbField::Boolean: {
        int res = sqlite3_bind_text(m_sqlResult->prepared_st, par, value.toBool() ? "1" : "0",
                                    1, SQLITE_TRANSIENT /*??*/);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        break;
    }
    case KDbField::Time: {
        int res = sqlite3_bind_text(m_sqlResult->prepared_st, par,
                                    qPrintable(value.toTime().toString(Qt::ISODate)),
                                    QLatin1String("HH:MM:SS").size(), SQLITE_TRANSIENT /*??*/);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        break;
    }
    case KDbField::Date: {
        int res = sqlite3_bind_text(m_sqlResult->prepared_st, par,
                                    qPrintable(value.toDate().toString(Qt::ISODate)),
                                    QLatin1String("YYYY-MM-DD").size(), SQLITE_TRANSIENT /*??*/);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        break;
    }
    case KDbField::DateTime: {
        int res = sqlite3_bind_text(m_sqlResult->prepared_st, par,
                                qPrintable(value.toDateTime().toString(Qt::ISODate)),
                                QLatin1String("YYYY-MM-DDTHH:MM:SS").size(), SQLITE_TRANSIENT /*??*/);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        break;
    }
    case KDbField::BLOB: {
        const QByteArray byteArray(value.toByteArray());
        int res = sqlite3_bind_blob(m_sqlResult->prepared_st, par,
                                    byteArray.constData(), byteArray.size(), SQLITE_TRANSIENT /*??*/);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
        break;
    }
    default: {
        sqliteWarning() << "unsupported field type:"
                << field->type() << "- NULL value bound to column #" << par;
        int res = sqlite3_bind_null(m_sqlResult->prepared_st, par);
        if (res != SQLITE_OK) {
            m_result.setServerErrorCode(res);
            storeResult(&m_result);
            return false;
        }
    }
    } //switch
    return true;
}
int QgsVectorLayerEditUtils::splitFeatures( const QList<QgsPoint>& splitLine, bool topologicalEditing )
{
  if ( !L->hasGeometryType() )
    return 4;

  QgsFeatureList newFeatures; //store all the newly created features
  double xMin, yMin, xMax, yMax;
  QgsRectangle bBox; //bounding box of the split line
  int returnCode = 0;
  int splitFunctionReturn; //return code of QgsGeometry::splitGeometry
  int numberOfSplittedFeatures = 0;

  QgsFeatureList featureList;
  const QgsFeatureIds selectedIds = L->selectedFeaturesIds();

  if ( selectedIds.size() > 0 ) //consider only the selected features if there is a selection
  {
    featureList = L->selectedFeatures();
  }
  else //else consider all the feature that intersect the bounding box of the split line
  {
    if ( boundingBoxFromPointList( splitLine, xMin, yMin, xMax, yMax ) == 0 )
    {
      bBox.setXMinimum( xMin ); bBox.setYMinimum( yMin );
      bBox.setXMaximum( xMax ); bBox.setYMaximum( yMax );
    }
    else
    {
      return 1;
    }

    if ( bBox.isEmpty() )
    {
      //if the bbox is a line, try to make a square out of it
      if ( bBox.width() == 0.0 && bBox.height() > 0 )
      {
        bBox.setXMinimum( bBox.xMinimum() - bBox.height() / 2 );
        bBox.setXMaximum( bBox.xMaximum() + bBox.height() / 2 );
      }
      else if ( bBox.height() == 0.0 && bBox.width() > 0 )
      {
        bBox.setYMinimum( bBox.yMinimum() - bBox.width() / 2 );
        bBox.setYMaximum( bBox.yMaximum() + bBox.width() / 2 );
      }
      else
      {
        return 2;
      }
    }

    QgsFeatureIterator fit = L->getFeatures( QgsFeatureRequest().setFilterRect( bBox ).setFlags( QgsFeatureRequest::ExactIntersect ) );

    QgsFeature f;
    while ( fit.nextFeature( f ) )
      featureList << QgsFeature( f );
  }

  QgsFeatureList::iterator select_it = featureList.begin();
  for ( ; select_it != featureList.end(); ++select_it )
  {
    if ( !select_it->geometry() )
    {
      continue;
    }
    QList<QgsGeometry*> newGeometries;
    QList<QgsPoint> topologyTestPoints;
    QgsGeometry* newGeometry = 0;
    splitFunctionReturn = select_it->geometry()->splitGeometry( splitLine, newGeometries, topologicalEditing, topologyTestPoints );
    if ( splitFunctionReturn == 0 )
    {
      //change this geometry
      L->editBuffer()->changeGeometry( select_it->id(), select_it->geometry() );

      //insert new features
      for ( int i = 0; i < newGeometries.size(); ++i )
      {
        newGeometry = newGeometries.at( i );
        QgsFeature newFeature;
        newFeature.setGeometry( newGeometry );

        //use default value where possible (primary key issue), otherwise the value from the original (split) feature
        QgsAttributes newAttributes = select_it->attributes();
        QVariant defaultValue;
        for ( int j = 0; j < newAttributes.count(); ++j )
        {
          defaultValue = L->dataProvider()->defaultValue( j );
          if ( !defaultValue.isNull() )
          {
            newAttributes[ j ] = defaultValue;
          }
        }

        newFeature.setAttributes( newAttributes );

        newFeatures.append( newFeature );
      }

      if ( topologicalEditing )
      {
        QList<QgsPoint>::const_iterator topol_it = topologyTestPoints.constBegin();
        for ( ; topol_it != topologyTestPoints.constEnd(); ++topol_it )
        {
          addTopologicalPoints( *topol_it );
        }
      }
      ++numberOfSplittedFeatures;
    }
    else if ( splitFunctionReturn > 1 ) //1 means no split but also no error
    {
      returnCode = splitFunctionReturn;
    }
  }

  if ( numberOfSplittedFeatures == 0 && selectedIds.size() > 0 )
  {
    //There is a selection but no feature has been split.
    //Maybe user forgot that only the selected features are split
    returnCode = 4;
  }


  //now add the new features to this vectorlayer
  L->editBuffer()->addFeatures( newFeatures );

  return returnCode;
}
Example #5
0
void QNetworkReplyImplPrivate::finished()
{
    Q_Q(QNetworkReplyImpl);

    if (state == Finished || state == Aborted || state == WaitingForSession)
        return;

    pauseNotificationHandling();
    QVariant totalSize = cookedHeaders.value(QNetworkRequest::ContentLengthHeader);
    if (preMigrationDownloaded != Q_INT64_C(-1))
        totalSize = totalSize.toLongLong() + preMigrationDownloaded;

    if (!manager.isNull()) {
#ifndef QT_NO_BEARERMANAGEMENT
        QNetworkSession *session = manager->d_func()->networkSession.data();
        if (session && session->state() == QNetworkSession::Roaming &&
            state == Working && errorCode != QNetworkReply::OperationCanceledError) {
            // only content with a known size will fail with a temporary network failure error
            if (!totalSize.isNull()) {
                if (bytesDownloaded != totalSize) {
                    if (migrateBackend()) {
                        // either we are migrating or the request is finished/aborted
                        if (state == Reconnecting || state == WaitingForSession) {
                            resumeNotificationHandling();
                            return; // exit early if we are migrating.
                        }
                    } else {
                        error(QNetworkReply::TemporaryNetworkFailureError,
                              QNetworkReply::tr("Temporary network failure."));
                    }
                }
            }
        }
#endif
    }
    resumeNotificationHandling();

    state = Finished;
    q->setFinished(true);

    pendingNotifications.clear();

    pauseNotificationHandling();
    if (totalSize.isNull() || totalSize == -1) {
        emit q->downloadProgress(bytesDownloaded, bytesDownloaded);
    }

    if (bytesUploaded == -1 && (outgoingData || outgoingDataBuffer))
        emit q->uploadProgress(0, 0);
    resumeNotificationHandling();

    // if we don't know the total size of or we received everything save the cache
    if (totalSize.isNull() || totalSize == -1 || bytesDownloaded == totalSize)
        completeCacheSave();

    // note: might not be a good idea, since users could decide to delete us
    // which would delete the backend too...
    // maybe we should protect the backend
    pauseNotificationHandling();
    emit q->readChannelFinished();
    emit q->finished();
    resumeNotificationHandling();
}
Example #6
0
bool CylindersModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
	QString vString;
	bool addDiveMode = DivePlannerPointsModel::instance()->currentMode() != DivePlannerPointsModel::NOTHING;
	if (addDiveMode)
		DivePlannerPointsModel::instance()->rememberTanks();

	cylinder_t *cyl = cylinderAt(index);
	switch (index.column()) {
	case TYPE:
		if (!value.isNull()) {
			QByteArray ba = value.toByteArray();
			const char *text = ba.constData();
			if (!cyl->type.description || strcmp(cyl->type.description, text)) {
				cyl->type.description = strdup(text);
				changed = true;
			}
		}
		break;
	case SIZE:
		if (CHANGED()) {
			TankInfoModel *tanks = TankInfoModel::instance();
			QModelIndexList matches = tanks->match(tanks->index(0, 0), Qt::DisplayRole, cyl->type.description);

			cyl->type.size = string_to_volume(vString.toUtf8().data(), cyl->type.workingpressure);
			mark_divelist_changed(true);
			if (!matches.isEmpty())
				tanks->setData(tanks->index(matches.first().row(), TankInfoModel::ML), cyl->type.size.mliter);
			changed = true;
		}
		break;
	case WORKINGPRESS:
		if (CHANGED()) {
			TankInfoModel *tanks = TankInfoModel::instance();
			QModelIndexList matches = tanks->match(tanks->index(0, 0), Qt::DisplayRole, cyl->type.description);
			cyl->type.workingpressure = string_to_pressure(vString.toUtf8().data());
			if (!matches.isEmpty())
				tanks->setData(tanks->index(matches.first().row(), TankInfoModel::BAR), cyl->type.workingpressure.mbar / 1000.0);
			changed = true;
		}
		break;
	case START:
		if (CHANGED()) {
			cyl->start = string_to_pressure(vString.toUtf8().data());
			changed = true;
		}
		break;
	case END:
		if (CHANGED()) {
			//&& (!cyl->start.mbar || string_to_pressure(vString.toUtf8().data()).mbar <= cyl->start.mbar)) {
			cyl->end = string_to_pressure(vString.toUtf8().data());
			changed = true;
		}
		break;
	case O2:
		if (CHANGED()) {
			cyl->gasmix.o2 = string_to_fraction(vString.toUtf8().data());
			pressure_t modpO2;
			modpO2.mbar = prefs.decopo2;
			cyl->depth = gas_mod(&cyl->gasmix, modpO2, M_OR_FT(3,10));
			changed = true;
		}
		break;
	case HE:
		if (CHANGED()) {
			cyl->gasmix.he = string_to_fraction(vString.toUtf8().data());
			changed = true;
		}
		break;
	case DEPTH:
		if (CHANGED()) {
			cyl->depth = string_to_depth(vString.toUtf8().data());
			changed = true;
		}
	}
	if (addDiveMode)
		DivePlannerPointsModel::instance()->tanksUpdated();
	dataChanged(index, index);
	return true;
}
Example #7
0
	void LogDelegate::paintTime (QPainter * painter, QStyleOptionViewItemV4 & option4, QModelIndex const & index) const
	{
		QVariant const value = index.data(Qt::DisplayRole);
		if (value.isValid() && !value.isNull())
		{
			unsigned long long const ref_value = m_log_widget.timeRefValue();
			QVariant value = index.data(Qt::DisplayRole);

			long long const ref_dt = value.toString().toULongLong() - ref_value;

			option4.text.clear();
			/*if (m_log_widget.config().m_dt_enabled)
			{
				if (ref_dt >= 0)
				{
					QAbstractItemModel const * model = m_log_widget.m_tableview->model();
					
					int const col_idx = const_cast<logs::LogWidget &>(m_log_widget).findColumn4Tag(tlv::tag_dt);
					
					if (col_idx >= 0)
					{
						QVariant value;

						// @TODO: nemela by toto proxy delat sama?
						if (FilterProxyModel const * proxy = m_log_widget.logProxy())
						{
							QModelIndex const idx = proxy->index(index.row(), col_idx, QModelIndex());
							QModelIndex const curr = proxy->mapToSource(idx);
							value = model->data(curr);
						}
						else
						{
							QModelIndex const idx = model->index(index.row(), col_idx, QModelIndex());
							value = model->data(idx).toString();
						}

						if (value.isValid())
						{
							option4.text = value.toString();
						}
					}
				}
			}
			else*/
			{
				if (ref_dt >= 0)
					option4.text = tr("%1").arg(ref_dt);
			}

			if (value.isValid())
			{
				QString const & val = option4.text;
				float const t_us = val.toFloat();
				float const t_natural_units = 1000000.0f; // microseconds
				float const t = t_us / t_natural_units / m_log_widget.config().m_time_units;
				option4.text = QString::number(t, 'f', 3);
			}

			QWidget const * widget = option4.widget;
			if (widget)
			{
				QStyle * style = widget->style();
				style->drawControl(QStyle::CE_ItemViewItem, &option4, painter, widget);
			}
		}
	}
Example #8
0
void ToitemTableDelegate::setModelData(QWidget *editor, QAbstractItemModel *pModel, const QModelIndex &index) const
{
  bool hitError = false;
  QVariant oldval = pModel->data(index);
  ToitemTableModel *model = static_cast<ToitemTableModel*>(pModel);

  switch (index.column())
  {
    case ITEM_NUMBER_COL:
    {
      ItemLineEdit *item = static_cast<ItemLineEdit*>(editor);
      if (oldval.isNull() || item->itemNumber() != oldval.toString())
      {
	if (! item->itemNumber().isEmpty() && item->isValid())
	{
	  XSqlQuery itemq;
	  itemq.prepare("SELECT *, stdCost(item_id) AS stdcost, uom_name "
			"FROM item JOIN uom ON (item_inv_uom_id=uom_id) "
			"WHERE (item_id=:item_id);");
	  itemq.bindValue(":item_id", item->id());
	  itemq.exec();
	  if (itemq.first())
	  {
	    if (itemq.value("stdcost").toDouble() == 0.0)
	    {
	      QMessageBox::critical(0, tr("No Standard Cost"),
		      tr("<p>The selected item has no Standard "
			 "Costing information. Please see your "
			 "controller to correct this situation "
			 "before continuing."));
	      hitError = true;
	      break;
	    }
	    model->setData(index, item->itemNumber());
	    model->setData(model->index(index.row(), TOITEM_ITEM_ID_COL), itemq.value("item_id").toInt());
	    model->setData(model->index(index.row(), TOITEM_UOM_COL), itemq.value("uom_name"));
	    model->setData(model->index(index.row(), TOITEM_STDCOST_COL),
			   formatPurchPrice(itemq.value("stdcost").toDouble()));
	  }
	  else if (itemq.lastError().type() != QSqlError::None)
	  {
	    systemError(0, itemq.lastError().databaseText(), __FILE__, __LINE__);
	    hitError = true;
	    break;
	  }
	}
	if (hitError)
	{
	  model->setData(index, new QVariant(QVariant::String));
	  model->setData(model->index(index.row(), TOITEM_ITEM_ID_COL), new QVariant(QVariant::Int));
	  model->setData(model->index(index.row(), TOITEM_STDCOST_COL), new QVariant(QVariant::Double));
	}
      }
      break;
    }

    case TOITEM_FREIGHT_COL:
    {
      QLineEdit *lineedit = static_cast<QLineEdit*>(editor);
      if (lineedit->text().toDouble() != oldval.toDouble())
	model->setData(index, formatPurchPrice(lineedit->text().toDouble()));
      break;
    }

    case TOITEM_QTY_ORDERED_COL:
    {
      QLineEdit *lineedit = static_cast<QLineEdit*>(editor);
      if (lineedit->text().isEmpty())
	model->setData(index, QVariant());
      else
	model->setData(index, lineedit->text().toDouble());
      break;
    }
    
    case TOITEM_DUEDATE_COL:
    {
      DLineEdit *duedate = static_cast<DLineEdit*>(editor);
      if (duedate->date() != oldval.toDate())
      {
	model->setData(index, duedate->date());
      }

      break;
    }

#ifdef QE_PROJECT
    case PRJ_NUMBER_COL:
    {
      ProjectLineEdit *prj = static_cast<ProjectLineEdit*>(editor);
      if (prj->id() != oldval.toInt())
      {
	model->setData(model->index(index.row(), TOITEM_PRJ_ID_COL), prj->id());
	model->setData(index, prj->text());
      }
      break;
    }
#endif

    default:
      break;
  }

  QTableView *view = qobject_cast<QTableView*>(parent());
  if (view)
  {
    if (hitError)
      view->setCurrentIndex(index);
    else if (index.row() >= (model->rowCount() - 1))
    {
      QHeaderView* header = view->horizontalHeader();
      if (header->visualIndex(index.column()) >=
	  (header->count() - header->hiddenSectionCount() - 1))
      {
	model->insertRow(model->rowCount());
      }
    }
  }

  return;
}
Example #9
0
void IxValidator::validateNotNull(const QVariant & v, QxInvalidValueX & lstInvalidValues) const
{
   if (v.isNull()) { lstInvalidValues.insert(this); }
}
Example #10
0
bool qgsVariantLessThan( const QVariant& lhs, const QVariant& rhs )
{
  // invalid < NULL < any value
  if ( !lhs.isValid() )
    return rhs.isValid();
  else if ( lhs.isNull() )
    return rhs.isValid() && !rhs.isNull();
  else if ( !rhs.isValid() || rhs.isNull() )
    return false;

  switch ( lhs.type() )
  {
    case QVariant::Int:
      return lhs.toInt() < rhs.toInt();
    case QVariant::UInt:
      return lhs.toUInt() < rhs.toUInt();
    case QVariant::LongLong:
      return lhs.toLongLong() < rhs.toLongLong();
    case QVariant::ULongLong:
      return lhs.toULongLong() < rhs.toULongLong();
    case QVariant::Double:
      return lhs.toDouble() < rhs.toDouble();
    case QVariant::Char:
      return lhs.toChar() < rhs.toChar();
    case QVariant::Date:
      return lhs.toDate() < rhs.toDate();
    case QVariant::Time:
      return lhs.toTime() < rhs.toTime();
    case QVariant::DateTime:
      return lhs.toDateTime() < rhs.toDateTime();
    case QVariant::Bool:
      return lhs.toBool() < rhs.toBool();

    case QVariant::List:
    {
      const QList<QVariant> &lhsl = lhs.toList();
      const QList<QVariant> &rhsl = rhs.toList();

      int i, n = qMin( lhsl.size(), rhsl.size() );
      for ( i = 0; i < n && lhsl[i].type() == rhsl[i].type() && lhsl[i].isNull() == rhsl[i].isNull() && lhsl[i] == rhsl[i]; i++ )
        ;

      if ( i == n )
        return lhsl.size() < rhsl.size();
      else
        return qgsVariantLessThan( lhsl[i], rhsl[i] );
    }

    case QVariant::StringList:
    {
      const QStringList &lhsl = lhs.toStringList();
      const QStringList &rhsl = rhs.toStringList();

      int i, n = qMin( lhsl.size(), rhsl.size() );
      for ( i = 0; i < n && lhsl[i] == rhsl[i]; i++ )
        ;

      if ( i == n )
        return lhsl.size() < rhsl.size();
      else
        return lhsl[i] < rhsl[i];
    }

    default:
      return QString::localeAwareCompare( lhs.toString(), rhs.toString() ) < 0;
  }
}
/** Slot called when the downloading is finished (with or without error) */
void HttpDownloaderPrivate::httpFinished()
{
    if (reply->error() == QNetworkReply::NoError) {
        qWarning() << "httpFinished No error";
	}
    else qWarning() << "httpFinished" << " QNetworkReply::NetworkError value: " << reply->error() << reply->errorString();

    networkError = reply->error();

    if (httpRequestAborted || networkError != QNetworkReply::NoError) {
        if (file) {
            file->close();
            file->remove();
            delete file;
            file = 0;
        }
        reply->deleteLater();
        if (progressDialog)
            progressDialog->hide();
        Q_EMIT q->downloadFinished();
        return;
    }

    if (progressBar) {
        if (networkError != QNetworkReply::NoError) {
            progressBar->setValue(0);
            lastError = tr("Download finished with an error: %1.").arg(reply->errorString());
            progressBar->setToolTip(lastError);
        } else  {
            progressBar->setValue(100);
            progressBar->setToolTip(tr("Download finished."));
        }
    }

    if (!_useBuffer) {
        file->flush();
        file->close();
    }

    QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
    if (networkError) {
        if (!_useBuffer)
            file->remove();
        Utils::informativeMessageBox(tr("Download failed: %1.")
                                     .arg(reply->errorString()), "", "", tr("HTTP"));
    } else if (!redirectionTarget.isNull()) {
        QUrl newUrl = m_Url.resolved(redirectionTarget.toUrl());
        if (Utils::yesNoMessageBox(tr("Redirect to %1?").arg(newUrl.toString()),
                                   tr("Redirect to %1?").arg(newUrl.toString()),
                                   "", tr("HTTP"))) {
            m_Url = newUrl;
            reply->deleteLater();
            if (!_useBuffer) {
                file->open(QIODevice::WriteOnly);
                file->resize(0);
            }
            startRequest(m_Url);
            return;
        }
    } else {
        //        QString fileName = QFileInfo(QUrl(urlLineEdit->text()).path()).fileName();
        LOG(tr("Downloaded %1 to current directory.").arg("file"));//.arg(fileName));
    }

    reply->deleteLater();
    reply = 0;
    if (file)
        delete file;
    file = 0;

    Q_EMIT q->downloadFinished();
}
Example #12
0
bool QSQLiteResult::exec()
{
    const QVector<QVariant> values = boundValues();

    d->skippedStatus = false;
    d->skipRow = false;
    d->rInf.clear();
    clearValues();
    setLastError(QSqlError());

    int res = sqlite3_reset(d->stmt);
    if (res != SQLITE_OK) {
        setLastError(qMakeError(d->access, QCoreApplication::translate("QSQLiteResult",
                     "Unable to reset statement"), QSqlError::StatementError, res));
        d->finalize();
        return false;
    }
    int paramCount = sqlite3_bind_parameter_count(d->stmt);
    if (paramCount == values.count()) {
        for (int i = 0; i < paramCount; ++i) {
            res = SQLITE_OK;
            const QVariant value = values.at(i);

            if (value.isNull()) {
                res = sqlite3_bind_null(d->stmt, i + 1);
            } else {
                switch (value.type()) {
                case QVariant::ByteArray: {
                    const QByteArray *ba = static_cast<const QByteArray*>(value.constData());
                    res = sqlite3_bind_blob(d->stmt, i + 1, ba->constData(),
                                            ba->size(), SQLITE_STATIC);
                    break; }
                case QVariant::Int:
                    res = sqlite3_bind_int(d->stmt, i + 1, value.toInt());
                    break;
                case QVariant::Double:
                    res = sqlite3_bind_double(d->stmt, i + 1, value.toDouble());
                    break;
                case QVariant::UInt:
                case QVariant::LongLong:
                    res = sqlite3_bind_int64(d->stmt, i + 1, value.toLongLong());
                    break;
                case QVariant::String: {
                    // lifetime of string == lifetime of its qvariant
                    const QString *str = static_cast<const QString*>(value.constData());
                    res = sqlite3_bind_text16(d->stmt, i + 1, str->utf16(),
                                              (str->size()) * sizeof(QChar), SQLITE_STATIC);
                    break; }
                default: {
                    QString str = value.toString();
                    // SQLITE_TRANSIENT makes sure that sqlite buffers the data
                    res = sqlite3_bind_text16(d->stmt, i + 1, str.utf16(),
                                              (str.size()) * sizeof(QChar), SQLITE_TRANSIENT);
                    break; }
                }
            }
            if (res != SQLITE_OK) {
                setLastError(qMakeError(d->access, QCoreApplication::translate("QSQLiteResult",
                             "Unable to bind parameters"), QSqlError::StatementError, res));
                d->finalize();
                return false;
            }
        }
    } else {
        setLastError(QSqlError(QCoreApplication::translate("QSQLiteResult",
                        "Parameter count mismatch"), QString(), QSqlError::StatementError));
        return false;
    }
    d->skippedStatus = d->fetchNext(d->firstRow, 0, true);
    if (lastError().isValid()) {
        setSelect(false);
        setActive(false);
        return false;
    }
    setSelect(!d->rInf.isEmpty());
    setActive(true);
    return true;
}
QObject *QDeclarativeVME::run(QDeclarativeVMEStack<QObject *> &stack,
                              QDeclarativeContextData *ctxt,
                              QDeclarativeCompiledData *comp,
                              int start, int count,
                              const QBitField &bindingSkipList)
{
    Q_ASSERT(comp);
    Q_ASSERT(ctxt);
    const QList<QDeclarativeCompiledData::TypeReference> &types = comp->types;
    const QList<QString> &primitives = comp->primitives;
    const QList<QByteArray> &datas = comp->datas;
    const QList<QDeclarativeCompiledData::CustomTypeData> &customTypeData = comp->customTypeData;
    const QList<int> &intData = comp->intData;
    const QList<float> &floatData = comp->floatData;
    const QList<QDeclarativePropertyCache *> &propertyCaches = comp->propertyCaches;
    const QList<QDeclarativeParser::Object::ScriptBlock> &scripts = comp->scripts;
    const QList<QUrl> &urls = comp->urls;

    QDeclarativeEnginePrivate::SimpleList<QDeclarativeAbstractBinding> bindValues;
    QDeclarativeEnginePrivate::SimpleList<QDeclarativeParserStatus> parserStatus;

    QDeclarativeVMEStack<ListInstance> qliststack;

    vmeErrors.clear();
    QDeclarativeEnginePrivate *ep = QDeclarativeEnginePrivate::get(ctxt->engine);

    int status = -1;    //for dbus
    QDeclarativePropertyPrivate::WriteFlags flags = QDeclarativePropertyPrivate::BypassInterceptor;

    for (int ii = start; !isError() && ii < (start + count); ++ii) {
        const QDeclarativeInstruction &instr = comp->bytecode.at(ii);

        switch(instr.type) {
        case QDeclarativeInstruction::Init:
        {
            if (instr.init.bindingsSize)
                bindValues = QDeclarativeEnginePrivate::SimpleList<QDeclarativeAbstractBinding>(instr.init.bindingsSize);
            if (instr.init.parserStatusSize)
                parserStatus = QDeclarativeEnginePrivate::SimpleList<QDeclarativeParserStatus>(instr.init.parserStatusSize);
            if (instr.init.contextCache != -1)
                ctxt->setIdPropertyData(comp->contextCaches.at(instr.init.contextCache));
            if (instr.init.compiledBinding != -1)
                ctxt->optimizedBindings = new QDeclarativeCompiledBindings(datas.at(instr.init.compiledBinding).constData(), ctxt);
        }
        break;

        case QDeclarativeInstruction::CreateObject:
        {
            QBitField bindings;
            if (instr.create.bindingBits != -1) {
                const QByteArray &bits = datas.at(instr.create.bindingBits);
                bindings = QBitField((const quint32*)bits.constData(),
                                     bits.size() * 8);
            }
            if (stack.isEmpty())
                bindings = bindings.united(bindingSkipList);

            QObject *o =
                types.at(instr.create.type).createInstance(ctxt, bindings);

            if (!o) {
                if(types.at(instr.create.type).component)
                    vmeErrors << types.at(instr.create.type).component->errors();

                VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Unable to create object of type %1").arg(QString::fromLatin1(types.at(instr.create.type).className)));
            }

            QDeclarativeData *ddata = QDeclarativeData::get(o);
            Q_ASSERT(ddata);

            if (stack.isEmpty()) {
                if (ddata->context) {
                    Q_ASSERT(ddata->context != ctxt);
                    Q_ASSERT(ddata->outerContext);
                    Q_ASSERT(ddata->outerContext != ctxt);
                    QDeclarativeContextData *c = ddata->context;
                    while (c->linkedContext) c = c->linkedContext;
                    c->linkedContext = ctxt;
                } else {
                    ctxt->addObject(o);
                }

                ddata->ownContext = true;
            } else if (!ddata->context) {
                ctxt->addObject(o);
            }

            ddata->setImplicitDestructible();
            ddata->outerContext = ctxt;
            ddata->lineNumber = instr.line;
            ddata->columnNumber = instr.create.column;

            if (instr.create.data != -1) {
                QDeclarativeCustomParser *customParser =
                    types.at(instr.create.type).type->customParser();
                customParser->setCustomData(o, datas.at(instr.create.data));
            }
            if (!stack.isEmpty()) {
                QObject *parent = stack.top();
                if (o->isWidgetType()) {
                    QWidget *widget = static_cast<QWidget*>(o);
                    if (parent->isWidgetType()) {
                        QWidget *parentWidget = static_cast<QWidget*>(parent);
                        widget->setParent(parentWidget);
                    } else {
                        // TODO: parent might be a layout
                    }
                } else {
                    QDeclarative_setParent_noEvent(o, parent);
                }
            }
            stack.push(o);
        }
        break;

        case QDeclarativeInstruction::CreateSimpleObject:
        {
            QObject *o = (QObject *)operator new(instr.createSimple.typeSize +
                                                 sizeof(QDeclarativeData));
            ::memset(o, 0, instr.createSimple.typeSize + sizeof(QDeclarativeData));
            instr.createSimple.create(o);

            QDeclarativeData *ddata =
                (QDeclarativeData *)(((const char *)o) + instr.createSimple.typeSize);
            ddata->lineNumber = instr.line;
            ddata->columnNumber = instr.createSimple.column;

            QObjectPrivate::get(o)->declarativeData = ddata;
            ddata->context = ddata->outerContext = ctxt;
            ddata->nextContextObject = ctxt->contextObjects;
            if (ddata->nextContextObject)
                ddata->nextContextObject->prevContextObject = &ddata->nextContextObject;
            ddata->prevContextObject = &ctxt->contextObjects;
            ctxt->contextObjects = ddata;

            QObject *parent = stack.top();
            QDeclarative_setParent_noEvent(o, parent);

            stack.push(o);
        }
        break;

        case QDeclarativeInstruction::SetId:
        {
            QObject *target = stack.top();
            ctxt->setIdProperty(instr.setId.index, target);
        }
        break;


        case QDeclarativeInstruction::SetDefault:
        {
            ctxt->contextObject = stack.top();
        }
        break;

        case QDeclarativeInstruction::CreateComponent:
        {
            QDeclarativeComponent *qcomp =
                new QDeclarativeComponent(ctxt->engine, comp, ii + 1, instr.createComponent.count,
                                          stack.isEmpty() ? 0 : stack.top());

            QDeclarativeData *ddata = QDeclarativeData::get(qcomp, true);
            Q_ASSERT(ddata);

            ctxt->addObject(qcomp);

            if (stack.isEmpty())
                ddata->ownContext = true;

            ddata->setImplicitDestructible();
            ddata->outerContext = ctxt;
            ddata->lineNumber = instr.line;
            ddata->columnNumber = instr.create.column;

            QDeclarativeComponentPrivate::get(qcomp)->creationContext = ctxt;

            stack.push(qcomp);
            ii += instr.createComponent.count;
        }
        break;

        case QDeclarativeInstruction::StoreMetaObject:
        {
            QObject *target = stack.top();

            QMetaObject mo;
            const QByteArray &metadata = datas.at(instr.storeMeta.data);
            QMetaObjectBuilder::fromRelocatableData(&mo, 0, metadata);

            const QDeclarativeVMEMetaData *data =
                (const QDeclarativeVMEMetaData *)datas.at(instr.storeMeta.aliasData).constData();

            (void)new QDeclarativeVMEMetaObject(target, &mo, data, comp);

            QDeclarativeData *ddata = QDeclarativeData::get(target, true);
            if (ddata->propertyCache) ddata->propertyCache->release();
            ddata->propertyCache = propertyCaches.at(instr.storeMeta.propertyCache);
            ddata->propertyCache->addref();
        }
        break;

        case QDeclarativeInstruction::StoreVariant:
        {
            QObject *target = stack.top();
            // XXX - can be more efficient
            QVariant v = QDeclarativeStringConverters::variantFromString(primitives.at(instr.storeString.value));
            void *a[] = { &v, 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeString.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::StoreVariantInteger:
        {
            QObject *target = stack.top();
            QVariant v(instr.storeInteger.value);
            void *a[] = { &v, 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeString.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::StoreVariantDouble:
        {
            QObject *target = stack.top();
            QVariant v(instr.storeDouble.value);
            void *a[] = { &v, 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeString.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::StoreVariantBool:
        {
            QObject *target = stack.top();
            QVariant v(instr.storeBool.value);
            void *a[] = { &v, 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeString.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::StoreString:
        {
            QObject *target = stack.top();
            void *a[] = { (void *)&primitives.at(instr.storeString.value), 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeString.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::StoreUrl:
        {
            QObject *target = stack.top();
            void *a[] = { (void *)&urls.at(instr.storeUrl.value), 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeUrl.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::StoreFloat:
        {
            QObject *target = stack.top();
            float f = instr.storeFloat.value;
            void *a[] = { &f, 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeFloat.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::StoreDouble:
        {
            QObject *target = stack.top();
            double d = instr.storeDouble.value;
            void *a[] = { &d, 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeDouble.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::StoreBool:
        {
            QObject *target = stack.top();
            void *a[] = { (void *)&instr.storeBool.value, 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeBool.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::StoreInteger:
        {
            QObject *target = stack.top();
            void *a[] = { (void *)&instr.storeInteger.value, 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeInteger.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::StoreColor:
        {
            QObject *target = stack.top();
            QColor c = QColor::fromRgba(instr.storeColor.value);
            void *a[] = { &c, 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeColor.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::StoreDate:
        {
            QObject *target = stack.top();
            QDate d = QDate::fromJulianDay(instr.storeDate.value);
            void *a[] = { &d, 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeDate.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::StoreTime:
        {
            QObject *target = stack.top();
            QTime t;
            t.setHMS(intData.at(instr.storeTime.valueIndex),
                     intData.at(instr.storeTime.valueIndex+1),
                     intData.at(instr.storeTime.valueIndex+2),
                     intData.at(instr.storeTime.valueIndex+3));
            void *a[] = { &t, 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeTime.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::StoreDateTime:
        {
            QObject *target = stack.top();
            QTime t;
            t.setHMS(intData.at(instr.storeDateTime.valueIndex+1),
                     intData.at(instr.storeDateTime.valueIndex+2),
                     intData.at(instr.storeDateTime.valueIndex+3),
                     intData.at(instr.storeDateTime.valueIndex+4));
            QDateTime dt(QDate::fromJulianDay(intData.at(instr.storeDateTime.valueIndex)), t);
            void *a[] = { &dt, 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeDateTime.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::StorePoint:
        {
            QObject *target = stack.top();
            QPoint p = QPointF(floatData.at(instr.storeRealPair.valueIndex),
                               floatData.at(instr.storeRealPair.valueIndex+1)).toPoint();
            void *a[] = { &p, 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeRealPair.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::StorePointF:
        {
            QObject *target = stack.top();
            QPointF p(floatData.at(instr.storeRealPair.valueIndex),
                      floatData.at(instr.storeRealPair.valueIndex+1));
            void *a[] = { &p, 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeRealPair.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::StoreSize:
        {
            QObject *target = stack.top();
            QSize p = QSizeF(floatData.at(instr.storeRealPair.valueIndex),
                             floatData.at(instr.storeRealPair.valueIndex+1)).toSize();
            void *a[] = { &p, 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeRealPair.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::StoreSizeF:
        {
            QObject *target = stack.top();
            QSizeF s(floatData.at(instr.storeRealPair.valueIndex),
                     floatData.at(instr.storeRealPair.valueIndex+1));
            void *a[] = { &s, 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeRealPair.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::StoreRect:
        {
            QObject *target = stack.top();
            QRect r = QRectF(floatData.at(instr.storeRect.valueIndex),
                             floatData.at(instr.storeRect.valueIndex+1),
                             floatData.at(instr.storeRect.valueIndex+2),
                             floatData.at(instr.storeRect.valueIndex+3)).toRect();
            void *a[] = { &r, 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeRect.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::StoreRectF:
        {
            QObject *target = stack.top();
            QRectF r(floatData.at(instr.storeRect.valueIndex),
                     floatData.at(instr.storeRect.valueIndex+1),
                     floatData.at(instr.storeRect.valueIndex+2),
                     floatData.at(instr.storeRect.valueIndex+3));
            void *a[] = { &r, 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeRect.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::StoreVector3D:
        {
            QObject *target = stack.top();
            QVector3D p(floatData.at(instr.storeVector3D.valueIndex),
                        floatData.at(instr.storeVector3D.valueIndex+1),
                        floatData.at(instr.storeVector3D.valueIndex+2));
            void *a[] = { &p, 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeVector3D.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::StoreObject:
        {
            QObject *assignObj = stack.pop();
            QObject *target = stack.top();

            void *a[] = { (void *)&assignObj, 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeObject.propertyIndex, a);
        }
        break;


        case QDeclarativeInstruction::AssignCustomType:
        {
            QObject *target = stack.top();
            QDeclarativeCompiledData::CustomTypeData data = customTypeData.at(instr.assignCustomType.valueIndex);
            const QString &primitive = primitives.at(data.index);
            QDeclarativeMetaType::StringConverter converter =
                QDeclarativeMetaType::customStringConverter(data.type);
            QVariant v = (*converter)(primitive);

            QMetaProperty prop =
                target->metaObject()->property(instr.assignCustomType.propertyIndex);
            if (v.isNull() || ((int)prop.type() != data.type && prop.userType() != data.type))
                VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot assign value %1 to property %2").arg(primitive).arg(QString::fromUtf8(prop.name())));

            void *a[] = { (void *)v.data(), 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.assignCustomType.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::AssignSignalObject:
        {
            // XXX optimize

            QObject *assign = stack.pop();
            QObject *target = stack.top();
            int sigIdx = instr.assignSignalObject.signal;
            const QByteArray &pr = datas.at(sigIdx);

            QDeclarativeProperty prop(target, QString::fromUtf8(pr));
            if (prop.type() & QDeclarativeProperty::SignalProperty) {

                QMetaMethod method = QDeclarativeMetaType::defaultMethod(assign);
                if (method.signature() == 0)
                    VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot assign object type %1 with no default method").arg(QString::fromLatin1(assign->metaObject()->className())));

                if (!QMetaObject::checkConnectArgs(prop.method().signature(), method.signature()))
                    VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot connect mismatched signal/slot %1 %vs. %2").arg(QString::fromLatin1(method.signature())).arg(QString::fromLatin1(prop.method().signature())));

                QMetaObject::connect(target, prop.index(), assign, method.methodIndex());

            } else {
                VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot assign an object to signal property %1").arg(QString::fromUtf8(pr)));
            }


        }
        break;

        case QDeclarativeInstruction::StoreSignal:
        {
            QObject *target = stack.top();
            QObject *context = stack.at(stack.count() - 1 - instr.assignBinding.context);

            QMetaMethod signal = target->metaObject()->method(instr.storeSignal.signalIndex);

            QDeclarativeBoundSignal *bs = new QDeclarativeBoundSignal(target, signal, target);
            QDeclarativeExpression *expr =
                new QDeclarativeExpression(ctxt, context, primitives.at(instr.storeSignal.value));
            expr->setSourceLocation(comp->name, instr.line);
            bs->setExpression(expr);
        }
        break;

        case QDeclarativeInstruction::StoreImportedScript:
        {
            ctxt->addImportedScript(scripts.at(instr.storeScript.value));
        }
        break;

        case QDeclarativeInstruction::StoreScriptString:
        {
            QObject *target = stack.top();
            QObject *scope = stack.at(stack.count() - 1 - instr.storeScriptString.scope);
            QDeclarativeScriptString ss;
            ss.setContext(ctxt->asQDeclarativeContext());
            ss.setScopeObject(scope);
            ss.setScript(primitives.at(instr.storeScriptString.value));

            void *a[] = { &ss, 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeScriptString.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::BeginObject:
        {
            QObject *target = stack.top();
            QDeclarativeParserStatus *status = reinterpret_cast<QDeclarativeParserStatus *>(reinterpret_cast<char *>(target) + instr.begin.castValue);
            parserStatus.append(status);
            status->d = &parserStatus.values[parserStatus.count - 1];

            status->classBegin();
        }
        break;

        case QDeclarativeInstruction::StoreBinding:
        {
            QObject *target =
                stack.at(stack.count() - 1 - instr.assignBinding.owner);
            QObject *context =
                stack.at(stack.count() - 1 - instr.assignBinding.context);

            QDeclarativeProperty mp =
                QDeclarativePropertyPrivate::restore(datas.at(instr.assignBinding.property), target, ctxt);

            int coreIndex = mp.index();

            if (stack.count() == 1 && bindingSkipList.testBit(coreIndex))
                break;

            QDeclarativeBinding *bind = new QDeclarativeBinding((void *)datas.at(instr.assignBinding.value).constData(), comp, context, ctxt, comp->name, instr.line, 0);
            bindValues.append(bind);
            bind->m_mePtr = &bindValues.values[bindValues.count - 1];
            bind->setTarget(mp);
            bind->addToObject(target);
        }
        break;

        case QDeclarativeInstruction::StoreCompiledBinding:
        {
            QObject *target =
                stack.at(stack.count() - 1 - instr.assignBinding.owner);
            QObject *scope =
                stack.at(stack.count() - 1 - instr.assignBinding.context);

            int property = instr.assignBinding.property;
            if (stack.count() == 1 && bindingSkipList.testBit(property & 0xFFFF))
                break;

            QDeclarativeAbstractBinding *binding =
                ctxt->optimizedBindings->configBinding(instr.assignBinding.value, target, scope, property);
            bindValues.append(binding);
            binding->m_mePtr = &bindValues.values[bindValues.count - 1];
            binding->addToObject(target);
        }
        break;

        case QDeclarativeInstruction::StoreValueSource:
        {
            QObject *obj = stack.pop();
            QDeclarativePropertyValueSource *vs = reinterpret_cast<QDeclarativePropertyValueSource *>(reinterpret_cast<char *>(obj) + instr.assignValueSource.castValue);
            QObject *target = stack.at(stack.count() - 1 - instr.assignValueSource.owner);

            QDeclarativeProperty prop =
                QDeclarativePropertyPrivate::restore(datas.at(instr.assignValueSource.property), target, ctxt);
            obj->setParent(target);
            vs->setTarget(prop);
        }
        break;

        case QDeclarativeInstruction::StoreValueInterceptor:
        {
            QObject *obj = stack.pop();
            QDeclarativePropertyValueInterceptor *vi = reinterpret_cast<QDeclarativePropertyValueInterceptor *>(reinterpret_cast<char *>(obj) + instr.assignValueInterceptor.castValue);
            QObject *target = stack.at(stack.count() - 1 - instr.assignValueInterceptor.owner);
            QDeclarativeProperty prop =
                QDeclarativePropertyPrivate::restore(datas.at(instr.assignValueInterceptor.property), target, ctxt);
            obj->setParent(target);
            vi->setTarget(prop);
            QDeclarativeVMEMetaObject *mo = static_cast<QDeclarativeVMEMetaObject *>((QMetaObject*)target->metaObject());
            mo->registerInterceptor(prop.index(), QDeclarativePropertyPrivate::valueTypeCoreIndex(prop), vi);
        }
        break;

        case QDeclarativeInstruction::StoreObjectQList:
        {
            QObject *assign = stack.pop();

            const ListInstance &list = qliststack.top();
            list.qListProperty.append((QDeclarativeListProperty<void>*)&list.qListProperty, assign);
        }
        break;

        case QDeclarativeInstruction::AssignObjectList:
        {
            // This is only used for assigning interfaces
            QObject *assign = stack.pop();
            const ListInstance &list = qliststack.top();

            int type = list.type;

            void *ptr = 0;

            const char *iid = QDeclarativeMetaType::interfaceIId(type);
            if (iid)
                ptr = assign->qt_metacast(iid);
            if (!ptr)
                VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot assign object to list"));


            list.qListProperty.append((QDeclarativeListProperty<void>*)&list.qListProperty, ptr);
        }
        break;

        case QDeclarativeInstruction::StoreVariantObject:
        {
            QObject *assign = stack.pop();
            QObject *target = stack.top();

            QVariant v = QVariant::fromValue(assign);
            void *a[] = { &v, 0, &status, &flags };
            QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                  instr.storeObject.propertyIndex, a);
        }
        break;

        case QDeclarativeInstruction::StoreInterface:
        {
            QObject *assign = stack.pop();
            QObject *target = stack.top();

            int coreIdx = instr.storeObject.propertyIndex;
            QMetaProperty prop = target->metaObject()->property(coreIdx);
            int t = prop.userType();
            const char *iid = QDeclarativeMetaType::interfaceIId(t);
            bool ok = false;
            if (iid) {
                void *ptr = assign->qt_metacast(iid);
                if (ptr) {
                    void *a[] = { &ptr, 0, &status, &flags };
                    QMetaObject::metacall(target,
                                          QMetaObject::WriteProperty,
                                          coreIdx, a);
                    ok = true;
                }
            }

            if (!ok)
                VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot assign object to interface property"));
        }
        break;

        case QDeclarativeInstruction::FetchAttached:
        {
            QObject *target = stack.top();

            QObject *qmlObject = qmlAttachedPropertiesObjectById(instr.fetchAttached.id, target);

            if (!qmlObject)
                VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Unable to create attached object"));

            stack.push(qmlObject);
        }
        break;

        case QDeclarativeInstruction::FetchQList:
        {
            QObject *target = stack.top();

            qliststack.push(ListInstance(instr.fetchQmlList.type));

            void *a[1];
            a[0] = (void *)&(qliststack.top().qListProperty);
            QMetaObject::metacall(target, QMetaObject::ReadProperty,
                                  instr.fetchQmlList.property, a);
        }
        break;

        case QDeclarativeInstruction::FetchObject:
        {
            QObject *target = stack.top();

            QObject *obj = 0;
            // NOTE: This assumes a cast to QObject does not alter the
            // object pointer
            void *a[1];
            a[0] = &obj;
            QMetaObject::metacall(target, QMetaObject::ReadProperty,
                                  instr.fetch.property, a);

            if (!obj)
                VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot set properties on %1 as it is null").arg(QString::fromUtf8(target->metaObject()->property(instr.fetch.property).name())));

            stack.push(obj);
        }
        break;

        case QDeclarativeInstruction::PopQList:
        {
            qliststack.pop();
        }
        break;

        case QDeclarativeInstruction::Defer:
        {
            if (instr.defer.deferCount) {
                QObject *target = stack.top();
                QDeclarativeData *data =
                    QDeclarativeData::get(target, true);
                comp->addref();
                data->deferredComponent = comp;
                data->deferredIdx = ii;
                ii += instr.defer.deferCount;
            }
        }
        break;

        case QDeclarativeInstruction::PopFetchedObject:
        {
            stack.pop();
        }
        break;

        case QDeclarativeInstruction::FetchValueType:
        {
            QObject *target = stack.top();
            QDeclarativeValueType *valueHandler =
                ep->valueTypes[instr.fetchValue.type];
            valueHandler->read(target, instr.fetchValue.property);
            stack.push(valueHandler);
        }
        break;

        case QDeclarativeInstruction::PopValueType:
        {
            QDeclarativeValueType *valueHandler =
                static_cast<QDeclarativeValueType *>(stack.pop());
            QObject *target = stack.top();
            valueHandler->write(target, instr.fetchValue.property,
                                QDeclarativePropertyPrivate::BypassInterceptor);
        }
        break;

        default:
            qFatal("QDeclarativeCompiledData: Internal error - unknown instruction %d", instr.type);
            break;
        }
    }

    if (isError()) {
        if (!stack.isEmpty()) {
            delete stack.at(0); // ### What about failures in deferred creation?
        } else {
            ctxt->destroy();
        }

        QDeclarativeEnginePrivate::clear(bindValues);
        QDeclarativeEnginePrivate::clear(parserStatus);
        ep->finalizedParserStatus.clear();
        return 0;
    }

    if (bindValues.count)
        ep->bindValues << bindValues;
    if (parserStatus.count)
        ep->parserStatus << parserStatus;

    Q_ASSERT(stack.count() == 1);
    return stack.top();
}
Example #14
0
SharedTileset VariantToMapConverter::toTileset(const QVariant &variant)
{
    const QVariantMap variantMap = variant.toMap();

    const int firstGid = variantMap[QLatin1String("firstgid")].toInt();

    // Handle external tilesets
    const QVariant sourceVariant = variantMap[QLatin1String("source")];
    if (!sourceVariant.isNull()) {
        QString source = resolvePath(mMapDir, sourceVariant);
        QString error;
        SharedTileset tileset = Tiled::readTileset(source, &error);
        if (!tileset) {
            // Insert a placeholder to allow the map to load
            tileset = Tileset::create(QFileInfo(source).completeBaseName(), 32, 32);
            tileset->setFileName(source);
            tileset->setLoaded(false);
        } else {
            mGidMapper.insert(firstGid, tileset.data());
        }
        return tileset;
    }

    const QString name = variantMap[QLatin1String("name")].toString();
    const int tileWidth = variantMap[QLatin1String("tilewidth")].toInt();
    const int tileHeight = variantMap[QLatin1String("tileheight")].toInt();
    const int spacing = variantMap[QLatin1String("spacing")].toInt();
    const int margin = variantMap[QLatin1String("margin")].toInt();
    const QVariantMap tileOffset = variantMap[QLatin1String("tileoffset")].toMap();
    const int tileOffsetX = tileOffset[QLatin1String("x")].toInt();
    const int tileOffsetY = tileOffset[QLatin1String("y")].toInt();
    const int columns = tileOffset[QLatin1String("columns")].toInt();

    if (tileWidth <= 0 || tileHeight <= 0 ||
            (firstGid == 0 && !mReadingExternalTileset)) {
        mError = tr("Invalid tileset parameters for tileset '%1'").arg(name);
        return SharedTileset();
    }

    SharedTileset tileset(Tileset::create(name,
                                          tileWidth, tileHeight,
                                          spacing, margin));

    tileset->setTileOffset(QPoint(tileOffsetX, tileOffsetY));
    tileset->setColumnCount(columns);

    QVariant imageVariant = variantMap[QLatin1String("image")];

    if (!imageVariant.isNull()) {
        const int imageWidth = variantMap[QLatin1String("imagewidth")].toInt();
        const int imageHeight = variantMap[QLatin1String("imageheight")].toInt();

        ImageReference imageRef;
        imageRef.source = resolvePath(mMapDir, imageVariant);
        imageRef.size = QSize(imageWidth, imageHeight);

        tileset->setImageReference(imageRef);
    }

    const QString trans = variantMap[QLatin1String("transparentcolor")].toString();
    if (!trans.isEmpty() && QColor::isValidColor(trans))
        tileset->setTransparentColor(QColor(trans));

    tileset->setProperties(toProperties(variantMap[QLatin1String("properties")]));

    // Read terrains
    QVariantList terrainsVariantList = variantMap[QLatin1String("terrains")].toList();
    for (int i = 0; i < terrainsVariantList.count(); ++i) {
        QVariantMap terrainMap = terrainsVariantList[i].toMap();
        tileset->addTerrain(terrainMap[QLatin1String("name")].toString(),
                            terrainMap[QLatin1String("tile")].toInt());
    }

    // Read tile terrain and external image information
    const QVariantMap tilesVariantMap = variantMap[QLatin1String("tiles")].toMap();
    QVariantMap::const_iterator it = tilesVariantMap.constBegin();
    for (; it != tilesVariantMap.end(); ++it) {
        bool ok;
        const int tileId = it.key().toInt();
        if (tileId < 0) {
            mError = tr("Invalid (negative) tile id: %1").arg(tileId);
            return SharedTileset();
        }

        Tile *tile = tileset->findOrCreateTile(tileId);

        const QVariantMap tileVar = it.value().toMap();
        QList<QVariant> terrains = tileVar[QLatin1String("terrain")].toList();
        if (terrains.count() == 4) {
            for (int i = 0; i < 4; ++i) {
                int terrainId = terrains.at(i).toInt(&ok);
                if (ok && terrainId >= 0 && terrainId < tileset->terrainCount())
                    tile->setCornerTerrainId(i, terrainId);
            }
        }
        float probability = tileVar[QLatin1String("probability")].toFloat(&ok);
        if (ok)
            tile->setProbability(probability);
        imageVariant = tileVar[QLatin1String("image")];
        if (!imageVariant.isNull()) {
            QString imagePath = resolvePath(mMapDir, imageVariant);
            tileset->setTileImage(tile, QPixmap(imagePath), imagePath);
        }
        QVariantMap objectGroupVariant = tileVar[QLatin1String("objectgroup")].toMap();
        if (!objectGroupVariant.isEmpty())
            tile->setObjectGroup(toObjectGroup(objectGroupVariant));

        QVariantList frameList = tileVar[QLatin1String("animation")].toList();
        if (!frameList.isEmpty()) {
            QVector<Frame> frames(frameList.size());
            for (int i = frameList.size() - 1; i >= 0; --i) {
                const QVariantMap frameVariantMap = frameList[i].toMap();
                Frame &frame = frames[i];
                frame.tileId = frameVariantMap[QLatin1String("tileid")].toInt();
                frame.duration = frameVariantMap[QLatin1String("duration")].toInt();
            }
            tile->setFrames(frames);
        }
    }

    // Read tile properties
    QVariantMap propertiesVariantMap = variantMap[QLatin1String("tileproperties")].toMap();
    for (it = propertiesVariantMap.constBegin(); it != propertiesVariantMap.constEnd(); ++it) {
        const int tileId = it.key().toInt();
        const QVariant propertiesVar = it.value();
        const Properties properties = toProperties(propertiesVar);
        tileset->findOrCreateTile(tileId)->setProperties(properties);
    }

    if (!mReadingExternalTileset)
        mGidMapper.insert(firstGid, tileset.data());

    return tileset;
}
void QgsWcsCapabilities::capabilitiesReplyFinished()
{
  if ( mCapabilitiesReply->error() == QNetworkReply::NoError )
  {
    QVariant redirect = mCapabilitiesReply->attribute( QNetworkRequest::RedirectionTargetAttribute );
    if ( !redirect.isNull() )
    {
      emit statusChanged( tr( "Capabilities request redirected." ) );

      QNetworkRequest request( redirect.toUrl() );
      if ( !setAuthorization( request ) )
      {
        mCapabilitiesResponse.clear();
        mError = tr( "Download of capabilities failed: network request update failed for authentication config" );
        QgsMessageLog::logMessage( mError, tr( "WCS" ) );
        return;
      }
      request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferNetwork );
      request.setAttribute( QNetworkRequest::CacheSaveControlAttribute, true );

      mCapabilitiesReply->deleteLater();
      QgsDebugMsg( QString( "redirected getcapabilities: %1" ).arg( redirect.toString() ) );
      mCapabilitiesReply = QgsNetworkAccessManager::instance()->get( request );

      connect( mCapabilitiesReply, SIGNAL( finished() ), this, SLOT( capabilitiesReplyFinished() ) );
      connect( mCapabilitiesReply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( capabilitiesReplyProgress( qint64, qint64 ) ) );
      return;
    }

    mCapabilitiesResponse = mCapabilitiesReply->readAll();

    if ( mCapabilitiesResponse.isEmpty() )
    {
      mErrorFormat = "text/plain";
      mError = tr( "empty of capabilities: %1" ).arg( mCapabilitiesReply->errorString() );
    }
  }
  else
  {
    // Resend request if AlwaysCache
    QNetworkRequest request = mCapabilitiesReply->request();
    if ( request.attribute( QNetworkRequest::CacheLoadControlAttribute ).toInt() == QNetworkRequest::AlwaysCache )
    {
      QgsDebugMsg( "Resend request with PreferCache" );
      request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache );

      mCapabilitiesReply->deleteLater();

      mCapabilitiesReply = QgsNetworkAccessManager::instance()->get( request );
      connect( mCapabilitiesReply, SIGNAL( finished() ), this, SLOT( capabilitiesReplyFinished() ) );
      connect( mCapabilitiesReply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( capabilitiesReplyProgress( qint64, qint64 ) ) );
      return;
    }

    mErrorFormat = "text/plain";
    mError = tr( "Download of capabilities failed: %1" ).arg( mCapabilitiesReply->errorString() );
    QgsMessageLog::logMessage( mError, tr( "WCS" ) );
    mCapabilitiesResponse.clear();
  }

  mCapabilitiesReply->deleteLater();
  mCapabilitiesReply = nullptr;
}
Example #16
0
    void CacheSettingsWidget::ReadConfig()
    {
        bool default_textures_cache_everything = false;
        int default_textures_max_size = 500*1024*1024;
        int default_assets_max_size = 300*1024*1024;

        // Init config file if file/segments doesent exist
        QSettings cache_config(QSettings::IniFormat, QSettings::UserScope, APPLICATION_NAME, "configuration/CacheSettings");
        QString segment = "AssetCache";
        QFile config_file(cache_config.fileName());
        if (!config_file.exists())
        {
            cache_config.beginGroup("TextureCache");
            cache_config.setValue("CacheEverything", default_textures_cache_everything);
            cache_config.setValue("MaxSize", default_textures_max_size);
            cache_config.endGroup();

            cache_config.beginGroup("AssetCache");
            cache_config.setValue("MaxSize", default_assets_max_size);
            cache_config.endGroup();
            cache_config.sync();
        }
        else if (!cache_config.childGroups().contains("TextureCache"))
        {
            cache_config.beginGroup("TextureCache");
            cache_config.setValue("CacheEverything", default_textures_cache_everything);
            cache_config.setValue("MaxSize", default_textures_max_size);
            cache_config.endGroup();
            cache_config.sync();
        }
        else if (!cache_config.childGroups().contains("AssetCache"))
        {
            cache_config.beginGroup("AssetCache");
            cache_config.setValue("MaxSize", default_assets_max_size);
            cache_config.endGroup();
            cache_config.sync();
        }

        // Read config and update ui with them
        // Note: The key-value pairs might not be there even if the segment exists, lets do one more set of checks
        QVariant val;
        segment = "TextureCache/CacheEverything";
        val = cache_config.value(segment);
        if (val.isNull())
        {
            cache_config.setValue(segment, default_textures_cache_everything);
            current_textures_cache_everything_ = default_textures_cache_everything;
        }
        else
            current_textures_cache_everything_ = val.toBool();

        segment = "TextureCache/MaxSize";
        val = cache_config.value(segment);
        if (val.isNull())
        {
            cache_config.setValue(segment, default_textures_max_size);
            current_textures_max_size_ = default_textures_max_size;
        }
        else
            current_textures_max_size_ = val.toInt();
        
        segment = "AssetCache/MaxSize";
        val = cache_config.value(segment);
        if (val.isNull())
        {
            cache_config.setValue(segment, default_assets_max_size);
            current_assets_max_size_ = default_assets_max_size;
        }
        else
            current_assets_max_size_ = val.toInt();

        cache_config.sync();
    }
Example #17
0
QString JSON::stringify(QVariant v){
    if (v.isNull()){
        return QLatin1String("null");
    }
    switch (v.type()) {
        case QVariant::Bool:
            return v.toBool()?QLatin1String("true"):QLatin1String("false");
            break;
        case QVariant::ULongLong:
        case QVariant::UInt:
            return QString::number(v.toULongLong());
            break;
        case QVariant::LongLong:
        case QVariant::Int:
            return QString::number(v.toLongLong());
            break;
        case QVariant::Double:
            return QString::number(v.toDouble());
            break;
        case QVariant::Map:
            {
                QString r=QLatin1String("{");
                QMap<QString, QVariant> map = v.toMap();
                QMapIterator<QString, QVariant> i(map);
                while (i.hasNext()){
                    i.next();
                    r+=QLatin1String("\"")+i.key()+ QLatin1String("\":") +stringify(i.value())+QLatin1String(",");
                }
                if(r.length()>1)
                    r.chop(1);
                r+=QLatin1String("}");
                return r;
            }
            break;
#if QT_VERSION >= 0x040500
        case QVariant::Hash:
            {
                QString r=QLatin1String("{");
                QHash<QString, QVariant> map = v.toHash();
                QHashIterator<QString, QVariant> i(map);
                while (i.hasNext()){
                    i.next();
                    r+=QLatin1String("\"")+i.key()+QLatin1String("\":")+stringify(i.value())+QLatin1String(",");
                }
                if(r.length()>1)
                    r.chop(1);
                r+=QLatin1String("}");
                return r;
            }
            break;
#endif
        case QVariant::StringList:
            {
                QString r=QLatin1String("[");
                QStringList l = v.toStringList();
                foreach(QString i, l){
                    r+=QLatin1String("\"")+i+QLatin1String("\",");
                }
                if(r.length()>1)
                    r.chop(1);
                r+=QLatin1String("]");
                return r;
            }
        case QVariant::List:
            {
                QString r=QLatin1String("[");
                QVariantList l = v.toList();
                foreach(QVariant i, l){
                    r+=stringify(i)+QLatin1String(",");
                }
                if(r.length()>1)
                    r.chop(1);
                r+=QLatin1String("]");
                return r;
            }
Example #18
0
string GoogleMaps::getLatLngForAddress(const QString &address, pair<double, double> &latLng, bool skipMultipleResults) {
  QString code = "codeAddress(\"%1\")";
  QVariant ret = frame->evaluateJavaScript(code.arg(address));
  code = "geocodingDone()";
  ret = frame->evaluateJavaScript(code);

  // disable user input
  // before allowing some display feedback
  tlp::disableQtUserInput();

  while (!ret.toBool()) {
    QApplication::processEvents();
    ret = frame->evaluateJavaScript(code);
  }

  // reenable user input
  tlp::enableQtUserInput();

  code = "getGeocodingNumberOfResults()";
  ret = frame->evaluateJavaScript(code);

  int nbResults = ret.toUInt();
  int idx = 0;

  if (nbResults > 1 && !skipMultipleResults) {
    bool showProgressWidget = false;

    if (progressWidget->isVisible()) {
      progressWidget->hide();
      showProgressWidget = true;
    }

    addressSelectionDialog->clearList();
    addressSelectionDialog->setBaseAddress(address);

    for (int i = 0 ; i < nbResults ; ++i) {
      code = "getGeocodingResultAddress(%1)";
      ret = frame->evaluateJavaScript(code.arg(i));
      addressSelectionDialog->addResultToList(ret.toString());
    }

    addresseSelectionProxy->setPos(width() / 2 - addresseSelectionProxy->sceneBoundingRect().width() / 2, height() / 2 - addresseSelectionProxy->sceneBoundingRect().height() / 2);
    addresseSelectionProxy->show();

    if (addressSelectionDialog->exec() == QDialog::Accepted) {
      idx = addressSelectionDialog->getPickedResultIdx();
    }

    addressSelectionDialog->hide();

    if (showProgressWidget) {
      progressWidget->show();
    }
  }
  else if (nbResults > 1) {
    return "MULTIPLE_RESULTS";
  }

  code = "getGeocodingResultLatLng(%1)";
  ret = frame->evaluateJavaScript(code.arg(idx));

  if (!ret.isNull()) {
    QString pointStr = ret.toString();
    QString xStr = pointStr.mid(1, pointStr.lastIndexOf(',') - 1);
    QString yStr = pointStr.mid(pointStr.lastIndexOf(',') + 1, pointStr.lastIndexOf(')') - pointStr.lastIndexOf(',') - 1);
    latLng = make_pair(xStr.toDouble(), yStr.toDouble());
  }

  code = "getGeocodingStatus()";
  ret = frame->evaluateJavaScript(code);
  return ret.toString().toStdString();
}
Example #19
0
bool QSymSQLResult::exec()
{
    if (d->prepareCalled == false) {
        setLastError(qMakeError(d->access, QCoreApplication::translate("QSymSQLResult",
                        "Statement is not prepared"), QSqlError::StatementError, KErrGeneral));
        return false;
    }
    
    const QVector<QVariant> values = boundValues();
    
    d->skippedStatus = false;
    d->skipRow = false;
    setAt(QSql::BeforeFirstRow);
    setLastError(QSqlError());
    int res = d->stmt.Reset();
    
    if (res != KErrNone) {
        setLastError(qMakeError(d->access, QCoreApplication::translate("QSymSQLResult",
                     "Unable to reset statement"), QSqlError::StatementError, res));
        d->finalize();
        return false;
    }
    TPtrC tmp;
    TInt paramCount = 0;
    while (d->stmt.ParamName(paramCount, tmp) == KErrNone) 
        paramCount++;

    if (paramCount == values.count()) {
        for (int i = 0; i < paramCount; ++i) {
            res = KErrNone;
            const QVariant value = values.at(i);

            if (value.isNull()) {
                res = d->stmt.BindNull(i); //replaced i + 1 with i
            } else {
                switch (value.type()) {
                case QVariant::ByteArray: {
                    const QByteArray *ba = static_cast<const QByteArray*>(value.constData());
                    TPtrC8 data(reinterpret_cast<const TUint8 *>(ba->constData()), ba->length());
                    res = d->stmt.BindBinary(i, data); //replaced i + 1 with i
                    break; }
                case QVariant::Int:
                    res = d->stmt.BindInt(i, value.toInt()); //replaced i + 1 with i
                    break;
                case QVariant::Double:
                    res = d->stmt.BindReal(i, value.toDouble()); //replaced i + 1 with i

                    break;
                case QVariant::UInt:
                case QVariant::LongLong:
                    res = d->stmt.BindReal(i, value.toLongLong()); //replaced i + 1 with i
                    break;
                
                case QVariant::String: {
                    // lifetime of string == lifetime of its qvariant
                    const QString *str = static_cast<const QString*>(value.constData());
                    res = d->stmt.BindText(i, qt_QString2TPtrC(*str)); // replaced i + 1 with i
                    break; }
                default: {
                    QString str = value.toString();
                    res = d->stmt.BindText(i, qt_QString2TPtrC(str)); //replaced i + 1 with i
                    break; }
                }
            }
            if (res != KErrNone) {
                setLastError(qMakeError(d->access, QCoreApplication::translate("QSymSQLResult",
                             "Unable to bind parameters"), QSqlError::StatementError, res));
                d->finalize();
                return false;
            }
        }
    } else {
        setLastError(QSqlError(QCoreApplication::translate("QSymSQLResult",
                        "Parameter count mismatch"), QString(), QSqlError::StatementError));
        return false;
    }
    
    d->skippedStatus = d->fetchNext(true);
    
    if (lastError().isValid()) {
        setSelect(false);
        setActive(false);
        return false;
    }
    
    if (d->stmt.ColumnCount() > 0) {
        //If there is something, it has to be select
        setSelect(true);
    } else {
        //If there isn't it might be just bad query, let's check manually whether we can find SELECT
       QString query = this->lastQuery();
       query = query.trimmed();
       query = query.toLower();
        
       //Just check whether there is one in the beginning, don't know if this is enough
       //Comments should be at the end of line if those are passed
       //For some reason, case insensitive indexOf didn't work for me
       if (query.indexOf(QLatin1String("select")) == 0) {
           setSelect(true);
       } else {
           setSelect(false);
       }
    }

    setActive(true);
    return true;
}
Example #20
0
Window::Window(ConfigController* config, int playerId, QWidget* parent)
	: QMainWindow(parent)
	, m_logView(new LogView())
	, m_stateWindow(nullptr)
	, m_screenWidget(new WindowBackground())
	, m_logo(":/res/mgba-1024.png")
	, m_config(config)
	, m_inputController(playerId)
#ifdef USE_FFMPEG
	, m_videoView(nullptr)
#endif
#ifdef USE_MAGICK
	, m_gifView(nullptr)
#endif
#ifdef USE_GDB_STUB
	, m_gdbController(nullptr)
#endif
	, m_mruMenu(nullptr)
	, m_shortcutController(new ShortcutController(this))
	, m_playerId(playerId)
{
	setFocusPolicy(Qt::StrongFocus);
	setAcceptDrops(true);
	setAttribute(Qt::WA_DeleteOnClose);
	m_controller = new GameController(this);
	m_controller->setInputController(&m_inputController);
	m_controller->setOverrides(m_config->overrides());
	updateTitle();

	m_display = Display::create(this);

	m_logo.setDevicePixelRatio(m_screenWidget->devicePixelRatio());
	m_logo = m_logo; // Free memory left over in old pixmap

	m_screenWidget->setMinimumSize(m_display->minimumSize());
	m_screenWidget->setSizePolicy(m_display->sizePolicy());
	m_screenWidget->setSizeHint(m_display->minimumSize() * 2);
	m_screenWidget->setPixmap(m_logo);
	m_screenWidget->setLockAspectRatio(m_logo.width(), m_logo.height());
	setCentralWidget(m_screenWidget);

	QVariant windowPos = m_config->getQtOption("windowPos");
	if (!windowPos.isNull()) {
		move(windowPos.toPoint());
	}

	connect(m_controller, SIGNAL(gameStarted(GBAThread*)), this, SLOT(gameStarted(GBAThread*)));
	connect(m_controller, SIGNAL(gameStarted(GBAThread*)), &m_inputController, SLOT(suspendScreensaver()));
	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), m_display, SLOT(stopDrawing()));
	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), this, SLOT(gameStopped()));
	connect(m_controller, SIGNAL(gameStopped(GBAThread*)), &m_inputController, SLOT(resumeScreensaver()));
	connect(m_controller, SIGNAL(stateLoaded(GBAThread*)), m_display, SLOT(forceDraw()));
	connect(m_controller, SIGNAL(rewound(GBAThread*)), m_display, SLOT(forceDraw()));
	connect(m_controller, SIGNAL(gamePaused(GBAThread*)), m_display, SLOT(pauseDrawing()));
#ifndef Q_OS_MAC
	connect(m_controller, SIGNAL(gamePaused(GBAThread*)), menuBar(), SLOT(show()));
	connect(m_controller, &GameController::gameUnpaused, [this]() {
		if(isFullScreen()) {
			menuBar()->hide();
		}
	});
#endif
	connect(m_controller, SIGNAL(gamePaused(GBAThread*)), &m_inputController, SLOT(resumeScreensaver()));
	connect(m_controller, SIGNAL(gameUnpaused(GBAThread*)), m_display, SLOT(unpauseDrawing()));
	connect(m_controller, SIGNAL(gameUnpaused(GBAThread*)), &m_inputController, SLOT(suspendScreensaver()));
	connect(m_controller, SIGNAL(postLog(int, const QString&)), m_logView, SLOT(postLog(int, const QString&)));
	connect(m_controller, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(recordFrame()));
	connect(m_controller, SIGNAL(frameAvailable(const uint32_t*)), m_display, SLOT(framePosted(const uint32_t*)));
	connect(m_controller, SIGNAL(gameCrashed(const QString&)), this, SLOT(gameCrashed(const QString&)));
	connect(m_controller, SIGNAL(gameFailed()), this, SLOT(gameFailed()));
	connect(m_controller, SIGNAL(unimplementedBiosCall(int)), this, SLOT(unimplementedBiosCall(int)));
	connect(m_controller, SIGNAL(statusPosted(const QString&)), m_display, SLOT(showMessage(const QString&)));
	connect(m_logView, SIGNAL(levelsSet(int)), m_controller, SLOT(setLogLevel(int)));
	connect(m_logView, SIGNAL(levelsEnabled(int)), m_controller, SLOT(enableLogLevel(int)));
	connect(m_logView, SIGNAL(levelsDisabled(int)), m_controller, SLOT(disableLogLevel(int)));
	connect(this, SIGNAL(startDrawing(GBAThread*)), m_display, SLOT(startDrawing(GBAThread*)), Qt::QueuedConnection);
	connect(this, SIGNAL(shutdown()), m_display, SLOT(stopDrawing()));
	connect(this, SIGNAL(shutdown()), m_controller, SLOT(closeGame()));
	connect(this, SIGNAL(shutdown()), m_logView, SLOT(hide()));
	connect(this, SIGNAL(audioBufferSamplesChanged(int)), m_controller, SLOT(setAudioBufferSamples(int)));
	connect(this, SIGNAL(fpsTargetChanged(float)), m_controller, SLOT(setFPSTarget(float)));
	connect(&m_fpsTimer, SIGNAL(timeout()), this, SLOT(showFPS()));

	m_logView->setLevels(GBA_LOG_WARN | GBA_LOG_ERROR | GBA_LOG_FATAL | GBA_LOG_STATUS);
	m_fpsTimer.setInterval(FPS_TIMER_INTERVAL);

	m_shortcutController->setConfigController(m_config);
	setupMenu(menuBar());
}
Example #21
0
QByteArray QgsSvgCache::getImageData( const QString &path ) const
{
  // is it a path to local file?
  QFile svgFile( path );
  if ( svgFile.exists() )
  {
    if ( svgFile.open( QIODevice::ReadOnly ) )
    {
      return svgFile.readAll();
    }
    else
    {
      return mMissingSvg;
    }
  }

  // maybe it's a url...
  if ( !path.contains( QLatin1String( "://" ) ) ) // otherwise short, relative SVG paths might be considered URLs
  {
    return mMissingSvg;
  }

  QUrl svgUrl( path );
  if ( !svgUrl.isValid() )
  {
    return mMissingSvg;
  }

  // check whether it's a url pointing to a local file
  if ( svgUrl.scheme().compare( QLatin1String( "file" ), Qt::CaseInsensitive ) == 0 )
  {
    svgFile.setFileName( svgUrl.toLocalFile() );
    if ( svgFile.exists() )
    {
      if ( svgFile.open( QIODevice::ReadOnly ) )
      {
        return svgFile.readAll();
      }
    }

    // not found...
    return mMissingSvg;
  }

  // the url points to a remote resource, download it!
  QNetworkReply *reply = nullptr;

  // The following code blocks until the file is downloaded...
  // TODO: use signals to get reply finished notification, in this moment
  // it's executed while rendering.
  while ( true )
  {
    QgsDebugMsg( QString( "get svg: %1" ).arg( svgUrl.toString() ) );
    QNetworkRequest request( svgUrl );
    request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache );
    request.setAttribute( QNetworkRequest::CacheSaveControlAttribute, true );

    reply = QgsNetworkAccessManager::instance()->get( request );
    connect( reply, &QNetworkReply::downloadProgress, this, &QgsSvgCache::downloadProgress );

    //emit statusChanged( tr( "Downloading svg." ) );

    // wait until the image download finished
    // TODO: connect to the reply->finished() signal
    while ( !reply->isFinished() )
    {
      QCoreApplication::processEvents( QEventLoop::ExcludeUserInputEvents, 500 );
    }

    if ( reply->error() != QNetworkReply::NoError )
    {
      QgsMessageLog::logMessage( tr( "SVG request failed [error: %1 - url: %2]" ).arg( reply->errorString(), reply->url().toString() ), tr( "SVG" ) );

      reply->deleteLater();
      return QByteArray();
    }

    QVariant redirect = reply->attribute( QNetworkRequest::RedirectionTargetAttribute );
    if ( redirect.isNull() )
    {
      // neither network error nor redirection
      // TODO: cache the image
      break;
    }

    // do a new request to the redirect url
    svgUrl = redirect.toUrl();
    reply->deleteLater();
  }

  QVariant status = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute );
  if ( !status.isNull() && status.toInt() >= 400 )
  {
    QVariant phrase = reply->attribute( QNetworkRequest::HttpReasonPhraseAttribute );
    QgsMessageLog::logMessage( tr( "SVG request error [status: %1 - reason phrase: %2]" ).arg( status.toInt() ).arg( phrase.toString() ), tr( "SVG" ) );

    reply->deleteLater();
    return mMissingSvg;
  }

  QString contentType = reply->header( QNetworkRequest::ContentTypeHeader ).toString();
  QgsDebugMsg( "contentType: " + contentType );
  if ( !contentType.startsWith( QLatin1String( "image/svg+xml" ), Qt::CaseInsensitive ) )
  {
    reply->deleteLater();
    return mMissingSvg;
  }

  // read the image data
  QByteArray ba = reply->readAll();
  reply->deleteLater();

  return ba;
}
bool SettingsDelegate::editorEvent(QEvent* event,
                                   QAbstractItemModel* mod,
                                   const QStyleOptionViewItem& option,
                                   const QModelIndex& index)
{
    // Get item type and value.
    int type = index.model()->data(index, SettingsModel::TypeRole).toInt();
    QVariant value = index.model()->data(index, Qt::EditRole);
    int item_type = index.model()->data(index, SettingsModel::ItemTypeRole).toInt();

    // Check for mouse double-click events.
    if (event->type() == QEvent::MouseButtonDblClick && index.column() == 1)
    {
        if (type == SettingsValue::INPUT_DIRECTORY)
        {
            QString name = QFileDialog::getExistingDirectory(view_,
                                                             "Select directory",
                                                             value.toString());
            if (!name.isNull())
            {
                name = QDir::current().relativeFilePath(name);
                mod->setData(index, name, Qt::EditRole);
            }
            event->accept();
            return true;
        }
        else if (type == SettingsValue::INPUT_FILE)
        {
            QString name = QFileDialog::getOpenFileName(view_,
                                                        "Input file name",
                                                        value.toString());
            if (!name.isNull())
            {
                name = QDir::current().relativeFilePath(name);
                mod->setData(index, name, Qt::EditRole);
            }
            event->accept();
            return true;
        }
        else if (type == SettingsValue::INPUT_FILE_LIST)
        {
            QStringList list = value.toStringList();
            QString dir;
            if (!list.isEmpty())
                dir = list[0];
            list = QFileDialog::getOpenFileNames(view_,
                                                 "Input file name(s)",
                                                 dir);
            if (!list.isEmpty())
            {
                for (int i = 0; i < list.size(); ++i) {
                    list[i] = QDir::current().relativeFilePath(list[i]);
                }
                mod->setData(index, list, Qt::EditRole);
            }
            event->accept();
            return true;
        }
        else if (type == SettingsValue::OUTPUT_FILE)
        {
            QString name = QFileDialog::getSaveFileName(view_,
                                                        "Output file name",
                                                        value.toString());
            if (!name.isNull())
            {
                name = QDir::current().relativeFilePath(name);
                mod->setData(index, name, Qt::EditRole);
            }
            event->accept();
            return true;
        }
        return QStyledItemDelegate::editorEvent(event, mod, option, index);
    }

    // Check for mouse right-click events.
    else if (event->type() == QEvent::MouseButtonRelease)
    {
        QMouseEvent* mouseEvent = (QMouseEvent*)event;
        if (mouseEvent->button() == Qt::RightButton &&
                        item_type != SettingsItem::LABEL)
        {
            // Set up the context menu.
            QMenu menu;
            QString strResetValue = "Reset";
            QString strCopyKey = "Copy setting key";

            // Add reset action if value is not null.
            QVariant val = mod->data(index, SettingsModel::ValueRole);
            if (!val.isNull() && index.column() == 1)
                menu.addAction(strResetValue);

            menu.addAction(strCopyKey);

            // Display the context menu.
            QAction* action = menu.exec(mouseEvent->globalPos());

            // Check which action was selected.
            if (action && action->text() == strResetValue) {
                mod->setData(index, mod->data(index,
                        SettingsModel::DefaultRole), Qt::EditRole);
            }
            else if (action && action->text() == strCopyKey) {
                QVariant key = mod->data(index, SettingsModel::KeyRole);
                QApplication::clipboard()->setText(key.toString());
            }
            event->accept();
            return true;
        }
        else if (mouseEvent->button() == Qt::RightButton &&
                        item_type == SettingsItem::LABEL)
        {
            QMenu menu;
            QString strResetGroup = "Reset Group";
            menu.addAction(strResetGroup);
            QAction* action = menu.exec(mouseEvent->globalPos());
            if (action && action->text() == strResetGroup) {
                mod->setData(index, QVariant(), SettingsModel::ResetGroupRole);
            }
            event->accept();
            return true;
        }
    }

    return QStyledItemDelegate::editorEvent(event, mod, option, index);
}
Example #23
0
void SaagharItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem &option,
                                const QModelIndex &index) const
{
//  if (parent()->objectName()=="searchTable")
//  {
//      qDebug() << keywordList;
//  }
    bool flagRightToLeft = true;
    if (parentWidget) {
        flagRightToLeft = parentWidget->layoutDirection() == Qt::RightToLeft;
    }

    int textHMargin = 0;
    if (tableStyle) {
        textHMargin = tableStyle->pixelMetric(QStyle::PM_FocusFrameHMargin, &option) + 1 ;
    }

    QBrush itemBrush = painter->brush();

    itemBrush.setColor(SaagharWidget::matchedTextColor);
    itemBrush.setStyle(Qt::SolidPattern);

    QString text = "";
    QString cleanedText = "";
    int lastX, x;
    QFontMetrics fontMetric(index.data(Qt::FontRole).value<QFont>());

    const QString tatweel = QString(0x0640);

    int iconWidth = 0;

    if (index.data().isValid()) {
        text = index.data().toString();

        if (index.data(Qt::DecorationRole).isValid()) {
            QIcon icon = index.data(Qt::DecorationRole).value<QIcon>();
            iconWidth = icon.pixmap(100, 100).width() + 5;
        }

        cleanedText = QGanjoorDbBrowser::cleanString(text);
//      if (text.contains( QString::fromLocal8Bit(
//                            "پسر چون ز مادر بران گونه زاد"
////                                  "پرپر شد ..."
//                  /*"وَز ســوری و نــعــمـان وزد، هـر دم شـمـیـم عـنـبـریـن"*/)))
//      {
//          qDebug() << "textt="<<text;
//          qDebug() << "clean="<<cleanedText;
//      }
        text = QGanjoorDbBrowser::cleanString(text, QStringList() << " " << QGanjoorDbBrowser::someSymbols);
    }
    //qDebug() << "text="<<index.data().toString()<<"W="<<fontMetric.width(index.data().toString())<<"cleanedText="<<cleanedText<<"W="<<fontMetric.width(cleanedText);
    Qt::Alignment itemAlignment = 0;
    QVariant alignValue = index.data(Qt::TextAlignmentRole);

    if (alignValue.isValid() && !alignValue.isNull()) {
        itemAlignment = Qt::Alignment(alignValue.toInt());
    }

    int keywordsCount = keywordList.size();
    for (int i = 0; i < keywordsCount; ++i) {
        lastX = x = option.rect.x() + textHMargin;
        //QString keyword = keywordList.isEmpty() ? "" : keywordList.at(0);
        QString keyword = keywordList.at(i);

        keyword.replace(QChar(0x200C), "", Qt::CaseInsensitive);//replace ZWNJ by ""
        //qDebug() << "keyword1="<<keyword;
        keyword = keyword.split("", QString::SkipEmptyParts).join(tatweel + "*");
        //qDebug() << "keyword2="<<keyword;
        keyword.replace("@" + tatweel + "*", "\\S*", Qt::CaseInsensitive); //replace wildcard by word chars
        //qDebug() << "keyword3="<<keyword;
        QRegExp maybeTatweel(keyword, Qt::CaseInsensitive);
        maybeTatweel.indexIn(text);
        //qDebug() << text<<"count=" << maybeTatweel.captureCount()<<maybeTatweel.capturedTexts();
        //qDebug() << "Match: "<<maybeTatweel.cap(0);
        keyword = maybeTatweel.cap(0);
        if (!(keyword.isEmpty() || text.indexOf(keyword) == -1)) {
            QString txt = text;
            while (txt.size() > 0) {
                int index = txt.indexOf(keyword);
                QString thisPart;
                if (index == -1) {
                    thisPart = txt;
                    txt = QString();
                }
                else {
                    if (index == 0) {
                        thisPart = txt.mid(0, keyword.size());
                        if (txt == keyword) {
                            txt = QString();
                        }
                        else {
                            txt = txt.mid(keyword.size(), txt.size() - keyword.size());
                        }
                    }
                    else {
                        thisPart = txt.mid(0, index);
                        txt = txt.mid(index);
                    }
                }

                QSize sz = fontMetric.boundingRect(thisPart).size();
                if (index == 0) {
                    if (flagRightToLeft) {
                        switch (itemAlignment ^ Qt::AlignVCenter) {
                        case Qt::AlignRight:
                            lastX = option.rect.left() + textHMargin + fontMetric.boundingRect(text).width() - (lastX - option.rect.x() + sz.width() - textHMargin);
                            break;

                        case Qt::AlignHCenter:
                            lastX = option.rect.left() + textHMargin + fontMetric.boundingRect(text).width() - (lastX - option.rect.x() + sz.width() - textHMargin) + ((option.rect.width() - fontMetric.boundingRect(text).width() - textHMargin) / 2);
                            break;

                        case Qt::AlignLeft:
                        default:
                            lastX = option.rect.right() + textHMargin - 1 - (lastX - option.rect.x() + sz.width());
                            break;
                        }
                    }
                    else {
                        if ((itemAlignment ^ Qt::AlignVCenter) == Qt::AlignHCenter) {
                            lastX = option.rect.left() + textHMargin + fontMetric.boundingRect(text).width() - (lastX - option.rect.x() + sz.width() - textHMargin) + ((option.rect.width() - fontMetric.boundingRect(text).width() - textHMargin) / 2);
                        }
                    }

                    QRect rectf(lastX , option.rect.y() + ((option.rect.height() - qMin(option.rect.height(), fontMetric.height())) / 2), sz.width(), fontMetric.height());
                    if (!flagRightToLeft && ((itemAlignment ^ Qt::AlignVCenter) == Qt::AlignHCenter)) {
                        rectf = QStyle::visualRect(Qt::RightToLeft, option.rect, rectf);
                    }

                    qreal oldOpacity = painter->opacity();
                    painter->setOpacity(opacity);
                    rectf.adjust(-iconWidth, 0, -iconWidth, 0);
                    QPainterPath roundedRect;
                    roundedRect.addRoundRect(rectf, 50, 50);
                    QPen defaultPen(painter->pen());
                    painter->setPen(SaagharWidget::matchedTextColor.darker(150));
                    painter->drawPath(roundedRect);
                    painter->fillPath(roundedRect, itemBrush);
                    painter->setOpacity(oldOpacity);
                    painter->setPen(defaultPen);
                    //painter->fillRect( rectf, itemBrush );
                }
                x += fontMetric.width(thisPart);
                lastX = x;
            }
        }
        else if (!(keyword.isEmpty() || cleanedText.indexOf(keyword) == -1)) {
            qreal oldOpacity = painter->opacity();
            painter->setOpacity(0.35);
            painter->fillRect(option.rect, itemBrush);
            painter->setOpacity(oldOpacity);
            //painter->fillRect( rectf, itemBrush );
        }
    }
    QItemDelegate::paint(painter, option, index);
}
Example #24
0
void
WhatsHotWidget::infoSystemInfo( Tomahawk::InfoSystem::InfoRequestData requestData, QVariant output )
{
    if ( requestData.caller != s_whatsHotIdentifier )
        return;

    if ( output.isNull() )
    {
        tDebug( LOGVERBOSE ) << Q_FUNC_INFO << "Info came back empty";
        return;
    }

    if ( !output.canConvert< QVariantMap >() )
    {
        tDebug( LOGVERBOSE ) << Q_FUNC_INFO << "WhatsHot: Could not parse output into a map";
        return;
    }

    QVariantMap returnedData = output.toMap();
    switch ( requestData.type )
    {
    case InfoSystem::InfoChartCapabilities:
    {
        QStandardItem *rootItem= m_crumbModelLeft->invisibleRootItem();
        QVariantMap defaults;
        if ( returnedData.contains( "defaults" ) )
            defaults = returnedData.take( "defaults" ).toMap();
        QString defaultSource = returnedData.take( "defaultSource" ).toString();

        foreach ( const QString label, returnedData.keys() )
        {
            QStandardItem *childItem = parseNode( rootItem, label, returnedData[label] );
            rootItem->appendRow(childItem);
        }

        // Set the default source
        // Set the default chart for each source
        for ( int i = 0; i < rootItem->rowCount(); i++ )
        {
            QStandardItem* source = rootItem->child( i, 0 );
            if ( defaultSource.toLower() == source->text().toLower() )
            {
                source->setData( true, Breadcrumb::DefaultRole );
            }

            if ( defaults.contains( source->text().toLower() ) )
            {
                QStringList defaultIndices = defaults[ source->text().toLower() ].toStringList();
                QStandardItem* cur = source;

                foreach( const QString& index, defaultIndices )
                {
                    // Go through the children of the current item, marking the default one as default
                    for ( int k = 0; k < cur->rowCount(); k++ )
                    {
                        if ( cur->child( k, 0 )->text() == index )
                        {
                            cur = cur->child( k, 0 ); // this is the default, drill down into the default to pick the next default
                            cur->setData( true, Breadcrumb::DefaultRole );
                            break;
                        }
                    }
                }
            }
        }

        m_sortedProxy->setSourceModel( m_crumbModelLeft );
        m_sortedProxy->sort( 0, Qt::AscendingOrder );
        ui->breadCrumbLeft->setModel( m_sortedProxy );
        break;
    }

    case InfoSystem::InfoChart:
    {
        if( !returnedData.contains("type") )
            break;
        const QString type = returnedData["type"].toString();
        if( !returnedData.contains(type) )
            break;
        const QString side = requestData.customData["whatshot_side"].toString();
        const QString chartId = requestData.input.value< Tomahawk::InfoSystem::InfoStringHash >().value( "chart_id" );

        m_queuedFetches.remove( chartId );

        ChartDataLoader* loader = new ChartDataLoader();
        loader->setProperty( "chartid", chartId );
        loader->moveToThread( m_workerThread );

        if ( type == "artists" )
        {
            loader->setType( ChartDataLoader::Artist );
            loader->setData( returnedData[ "artists" ].value< QStringList >() );

            connect( loader, SIGNAL( artists( Tomahawk::ChartDataLoader*, QList< Tomahawk::artist_ptr > ) ), this, SLOT( chartArtistsLoaded( Tomahawk::ChartDataLoader*, QList< Tomahawk::artist_ptr > ) ) );

            TreeModel* artistsModel = new TreeModel( ui->artistsViewLeft );
            artistsModel->setMode( InfoSystemMode );
            artistsModel->setStyle( PlayableModel::Collection );

            m_artistModels[ chartId ] = artistsModel;

            if ( m_queueItemToShow == chartId )
                setLeftViewArtists( artistsModel );
        }
        else if ( type == "albums" )
Tileset *VariantToMapConverter::toTileset(const QVariant &variant)
{
    const QVariantMap variantMap = variant.toMap();

    const int firstGid = variantMap["firstgid"].toInt();
    const QString name = variantMap["name"].toString();
    const int tileWidth = variantMap["tilewidth"].toInt();
    const int tileHeight = variantMap["tileheight"].toInt();
    const int spacing = variantMap["spacing"].toInt();
    const int margin = variantMap["margin"].toInt();
    const QVariantMap tileOffset = variantMap["tileoffset"].toMap();
    const int tileOffsetX = tileOffset["x"].toInt();
    const int tileOffsetY = tileOffset["y"].toInt();

    if (tileWidth <= 0 || tileHeight <= 0 || firstGid == 0) {
        mError = tr("Invalid tileset parameters for tileset '%1'").arg(name);
        return 0;
    }

    typedef QScopedPointer<Tileset> TilesetPtr;
    TilesetPtr tileset(new Tileset(name,
                                   tileWidth, tileHeight,
                                   spacing, margin));

    tileset->setTileOffset(QPoint(tileOffsetX, tileOffsetY));

    const QString trans = variantMap["transparentcolor"].toString();
    if (!trans.isEmpty() && QColor::isValidColor(trans))
        tileset->setTransparentColor(QColor(trans));

    QVariant imageVariant = variantMap["image"];

    if (!imageVariant.isNull()) {
        QString imagePath = resolvePath(mMapDir, imageVariant);
        if (!tileset->loadFromImage(imagePath)) {
            mError = tr("Error loading tileset image:\n'%1'").arg(imagePath);
            return 0;
        }
    }

    tileset->setProperties(toProperties(variantMap["properties"]));

    // Read terrains
    QVariantList terrainsVariantList = variantMap["terrains"].toList();
    for (int i = 0; i < terrainsVariantList.count(); ++i) {
        QVariantMap terrainMap = terrainsVariantList[i].toMap();
        tileset->addTerrain(terrainMap["name"].toString(),
                            terrainMap["tile"].toInt());
    }

    // Read tile terrain and external image information
    const QVariantMap tilesVariantMap = variantMap["tiles"].toMap();
    QVariantMap::const_iterator it = tilesVariantMap.constBegin();
    for (; it != tilesVariantMap.end(); ++it) {
        bool ok;
        const int tileIndex = it.key().toInt();
        if (tileIndex < 0) {
            mError = tr("Tileset tile index negative:\n'%1'").arg(tileIndex);
        }

        if (tileIndex >= tileset->tileCount()) {
            // Extend the tileset to fit the tile
            if (tileIndex >= tilesVariantMap.count()) {
                // If tiles are  defined this way, there should be an entry
                // for each tile.
                // Limit the index to number of entries to prevent running out
                // of memory on malicious input.
                mError = tr("Tileset tile index too high:\n'%1'").arg(tileIndex);
                return 0;
            }
            for (int i = tileset->tileCount(); i <= tileIndex; i++)
                tileset->addTile(QPixmap());
        }

        Tile *tile = tileset->tileAt(tileIndex);
        if (tile) {
            const QVariantMap tileVar = it.value().toMap();
            QList<QVariant> terrains = tileVar["terrain"].toList();
            if (terrains.count() == 4) {
                for (int i = 0; i < 4; ++i) {
                    int terrainId = terrains.at(i).toInt(&ok);
                    if (ok && terrainId >= 0 && terrainId < tileset->terrainCount())
                        tile->setCornerTerrain(i, terrainId);
                }
            }
            float terrainProbability = tileVar["probability"].toFloat(&ok);
            if (ok)
                tile->setTerrainProbability(terrainProbability);
            imageVariant = tileVar["image"];
            if (!imageVariant.isNull()) {
                QString imagePath = resolvePath(mMapDir, imageVariant);
                tileset->setTileImage(tileIndex, QPixmap(imagePath), imagePath);
            }
            QVariantMap objectGroupVariant = tileVar["objectgroup"].toMap();
            if (!objectGroupVariant.isEmpty())
                tile->setObjectGroup(toObjectGroup(objectGroupVariant));

            QVariantList frameList = tileVar["animation"].toList();
            if (!frameList.isEmpty()) {
                QVector<Frame> frames(frameList.size());
                for (int i = frameList.size() - 1; i >= 0; --i) {
                    const QVariantMap frameVariantMap = frameList[i].toMap();
                    Frame &frame = frames[i];
                    frame.tileId = frameVariantMap["tileid"].toInt();
                    frame.duration = frameVariantMap["duration"].toInt();
                }
                tile->setFrames(frames);
            }
        }
    }

    // Read tile properties
    QVariantMap propertiesVariantMap = variantMap["tileproperties"].toMap();
    for (it = propertiesVariantMap.constBegin(); it != propertiesVariantMap.constEnd(); ++it) {
        const int tileIndex = it.key().toInt();
        const QVariant propertiesVar = it.value();
        if (tileIndex >= 0 && tileIndex < tileset->tileCount()) {
            const Properties properties = toProperties(propertiesVar);
            tileset->tileAt(tileIndex)->setProperties(properties);
        }
    }

    mGidMapper.insert(firstGid, tileset.data());
    return tileset.take();
}
Example #26
0
Codri::JsonResource::JsonResource(QxtAbstractWebSessionManager* iSessionManager, QObject* iParent, const QVariant& iClassName)
    : Resource(iSessionManager, iParent, (iClassName.isNull()?"Codri::JsonResource":iClassName)) {
    // QJson objects
    mParser = new QJson::Parser();
    mSerializer = new QJson::Serializer();
}
Example #27
0
ListPanel* PanelTabBar::getPanel(int tabIdx)
{
    QVariant v = tabData(tabIdx);
    if (v.isNull()) return 0;
    return (ListPanel*)v.toLongLong();
}
Example #28
0
/*!
    Renders the delegate using the given \a painter and style \a option for
    the item specified by \a index.

    When reimplementing this function in a subclass, you should update the area
    held by the option's \l{QStyleOption::rect}{rect} variable, using the
    option's \l{QStyleOption::state}{state} variable to determine the state of
    the item to be displayed, and adjust the way it is painted accordingly.

    For example, a selected item may need to be displayed differently to
    unselected items, as shown in the following code:

    \snippet examples/itemviews/pixelator/pixeldelegate.cpp 2
    \dots

    After painting, you should ensure that the painter is returned to its
    the state it was supplied in when this function was called. For example,
    it may be useful to call QPainter::save() before painting and
    QPainter::restore() afterwards.

    \sa QStyle::State
*/
void QItemDelegate::paint(QPainter *painter,
                          const QStyleOptionViewItem &option,
                          const QModelIndex &index) const
{
    Q_D(const QItemDelegate);
    Q_ASSERT(index.isValid());

    QStyleOptionViewItemV4 opt = setOptions(index, option);

    const QStyleOptionViewItemV2 *v2 = qstyleoption_cast<const QStyleOptionViewItemV2 *>(&option);
    opt.features = v2 ? v2->features
                    : QStyleOptionViewItemV2::ViewItemFeatures(QStyleOptionViewItemV2::None);
    const QStyleOptionViewItemV3 *v3 = qstyleoption_cast<const QStyleOptionViewItemV3 *>(&option);
    opt.locale = v3 ? v3->locale : QLocale();
    opt.widget = v3 ? v3->widget : 0;

    // prepare
    painter->save();
    if (d->clipPainting)
        painter->setClipRect(opt.rect);

    // get the data and the rectangles

    QVariant value;

    QPixmap pixmap;
    QRect decorationRect;
    value = index.data(Qt::DecorationRole);
    if (value.isValid()) {
        // ### we need the pixmap to call the virtual function
        pixmap = decoration(opt, value);
        if (value.type() == QVariant::Icon) {
            d->tmp.icon = qvariant_cast<QIcon>(value);
            d->tmp.mode = d->iconMode(option.state);
            d->tmp.state = d->iconState(option.state);
            const QSize size = d->tmp.icon.actualSize(option.decorationSize,
                                                      d->tmp.mode, d->tmp.state);
            decorationRect = QRect(QPoint(0, 0), size);
        } else {
            d->tmp.icon = QIcon();
            decorationRect = QRect(QPoint(0, 0), pixmap.size());
        }
    } else {
        d->tmp.icon = QIcon();
        decorationRect = QRect();
    }

    QString text;
    QRect displayRect;
    value = index.data(Qt::DisplayRole);
    if (value.isValid() && !value.isNull()) {
        text = QItemDelegatePrivate::valueToText(value, opt);
        displayRect = textRectangle(painter, d->textLayoutBounds(opt), opt.font, text);
    }

    QRect checkRect;
    Qt::CheckState checkState = Qt::Unchecked;
    value = index.data(Qt::CheckStateRole);
    if (value.isValid()) {
        checkState = static_cast<Qt::CheckState>(value.toInt());
        checkRect = check(opt, opt.rect, value);
    }

    // do the layout

    doLayout(opt, &checkRect, &decorationRect, &displayRect, false);

    // draw the item

    drawBackground(painter, opt, index);
    drawCheck(painter, opt, checkRect, checkState);
    drawDecoration(painter, opt, decorationRect, pixmap);
    drawDisplay(painter, opt, displayRect, text);
    drawFocus(painter, opt, displayRect);

    // done
    painter->restore();
}
void QXmppRpcMarshaller::marshall(QXmlStreamWriter *writer, const QVariant &value)
{
    writer->writeStartElement("value");
    switch( value.type() )
    {
        case QVariant::Int:
        case QVariant::UInt:
        case QVariant::LongLong:
        case QVariant::ULongLong:
            writer->writeTextElement("i4", value.toString());
            break;
        case QVariant::Double:
            writer->writeTextElement("double", value.toString());
            break;
        case QVariant::Bool:
            writer->writeTextElement("boolean", value.toBool() ? "1" : "0");
            break;
        case QVariant::Date:
            writer->writeTextElement("dateTime.iso8601", value.toDate().toString( Qt::ISODate ) );
            break;
        case QVariant::DateTime:
            writer->writeTextElement("dateTime.iso8601", value.toDateTime().toString( Qt::ISODate ) );
            break;
        case QVariant::Time:
            writer->writeTextElement("dateTime.iso8601", value.toTime().toString( Qt::ISODate ) );
            break;
        case QVariant::StringList:
        case QVariant::List:
        {
            writer->writeStartElement("array");
            writer->writeStartElement("data");
            foreach(const QVariant &item, value.toList())
                marshall(writer, item);
            writer->writeEndElement();
            writer->writeEndElement();
            break;
        }
        case QVariant::Map:
        {
            writer->writeStartElement("struct");
            QMap<QString, QVariant> map = value.toMap();
            QMap<QString, QVariant>::ConstIterator index = map.begin();
            while( index != map.end() )
            {
                writer->writeStartElement("member");
                writer->writeTextElement("name", index.key());
                marshall( writer, *index );
                writer->writeEndElement();
                ++index;
            }
            writer->writeEndElement();
            break;
        }
        case QVariant::ByteArray:
        {
            writer->writeTextElement("base64", value.toByteArray().toBase64() );
            break;
        }
        default:
        {
            if (value.isNull())
                writer->writeEmptyElement("nil");
            else if( value.canConvert(QVariant::String) )
            {
                writer->writeTextElement("string", value.toString() );
            }
            break;
        }
    }
    writer->writeEndElement();
}
Example #30
0
QByteArray ViewEmail::render(Context *c) const
{
    Q_D(const ViewEmail);

    QVariantHash email = c->stash(d->stashKey).toHash();
    if (email.isEmpty()) {
        c->error(QStringLiteral("Cannot render template, template name or template stash key not defined"));
        return QByteArray();
    }

    MimeMessage message;

    QVariant value;
    value = email.value(QStringLiteral("to"));
    if (value.type() == QVariant::String && !value.toString().isEmpty()) {
        message.addTo(value.toString());
    }

    value = email.value(QStringLiteral("cc"));
    if (value.type() == QVariant::String && !value.toString().isEmpty()) {
        message.addCc(value.toString());
    }

    value = email.value(QStringLiteral("from"));
    if (value.type() == QVariant::String && !value.toString().isEmpty()) {
        message.setSender(value.toString());
    }

    value = email.value(QStringLiteral("subject"));
    if (value.type() == QVariant::String && !value.toString().isEmpty()) {
        message.setSubject(value.toString());
    }

    QVariant body = email.value(QStringLiteral("body"));
    QVariant parts = email.value(QStringLiteral("parts"));
    if (body.isNull() && parts.isNull()) {
        c->error(QStringLiteral("Can't send email without parts or body, check stash"));
        return QByteArray();
    }

    if (!parts.isNull()) {
        const QVariantList partsVariant = parts.toList();
        Q_FOREACH (const QVariant &part, partsVariant) {
            MimePart *mime = part.value<MimePart*>();
            if (mime) {
                message.addPart(mime);
            } else {
                qCCritical(CUTELYST_VIEW_EMAIL) << "Failed to cast MimePart";
            }
        }

        auto contentTypeIt = email.constFind(QStringLiteral("content_type"));
        if (contentTypeIt != email.constEnd()
                && !contentTypeIt.value().isNull()
                && !contentTypeIt.value().toString().isEmpty()) {
            const QByteArray contentType = contentTypeIt.value().toString().toLatin1();
            qCDebug(CUTELYST_VIEW_EMAIL) << "Using specified content_type" << contentType;
            message.getContent().setContentType(contentType);
        } else if (!d->defaultContentType.isEmpty()) {
            qCDebug(CUTELYST_VIEW_EMAIL) << "Using default content_type" << d->defaultContentType;
            message.getContent().setContentType(d->defaultContentType);
        }
    } else {