QgsVectorLayer *QgsMimeDataUtils::Uri::vectorLayer( bool &owner, QString &error ) const
{
  owner = false;
  if ( layerType != QLatin1String( "vector" ) )
  {
    error = QObject::tr( "%1: Not a vector layer." ).arg( name );
    return nullptr;
  }
  if ( providerKey == QLatin1String( "memory" ) )
  {
    QUrl url = QUrl::fromEncoded( uri.toUtf8() );
    if ( !url.hasQueryItem( QStringLiteral( "pid" ) ) || !url.hasQueryItem( QStringLiteral( "layerid" ) ) )
    {
      error = QObject::tr( "Memory layer uri does not contain process or layer id." );
      return nullptr;
    }
    qint64 pid = url.queryItemValue( QStringLiteral( "pid" ) ).toLongLong();
    if ( pid != QCoreApplication::applicationPid() )
    {
      error = QObject::tr( "Memory layer from another QGIS instance." );
      return nullptr;
    }
    QString layerId = url.queryItemValue( QStringLiteral( "layerid" ) );
    QgsVectorLayer *vectorLayer = QgsProject::instance()->mapLayer<QgsVectorLayer *>( layerId );
    if ( !vectorLayer )
    {
      error = QObject::tr( "Cannot get memory layer." );
      return nullptr;
    }
    return vectorLayer;
  }
  owner = true;
  return new QgsVectorLayer( uri, name, providerKey );
}
bool
GlobalActionManager::handlePlaylistCommand( const QUrl& url )
{
    QStringList parts = url.path().split( "/" ).mid( 1 ); // get the rest of the command
    if ( parts.isEmpty() )
    {
        tLog() << "No specific playlist command:" << url.toString();
        return false;
    }

    if ( parts[ 0 ] == "import" )
    {
        if ( !url.hasQueryItem( "xspf" ) && !url.hasQueryItem( "jspf") )
        {
            tDebug() << "No xspf or jspf to load...";
            return false;
        }
        if ( url.hasQueryItem( "xspf") )
        {
            QUrl xspf = QUrl::fromUserInput( url.queryItemValue( "xspf" ) );
            QString title =  url.hasQueryItem( "title" ) ? url.queryItemValue( "title" ) : QString();
            XSPFLoader* l= new XSPFLoader( true, this );
            l->setOverrideTitle( title );
            l->load( xspf );
            connect( l, SIGNAL( ok( Tomahawk::playlist_ptr ) ), this, SLOT( playlistCreatedToShow( Tomahawk::playlist_ptr) ) );
        }
        else if ( url.hasQueryItem( "jspf" ) )
        {
            QUrl jspf = QUrl::fromUserInput( url.queryItemValue( "jspf" ) );
            QString title =  url.hasQueryItem( "title" ) ? url.queryItemValue( "title" ) : QString();
            JSPFLoader* l= new JSPFLoader( true, this );
            l->setOverrideTitle( title );
            l->load( jspf );
            connect( l, SIGNAL( ok( Tomahawk::playlist_ptr ) ), this, SLOT( playlistCreatedToShow( Tomahawk::playlist_ptr) ) );
        }
    }
    else if ( parts [ 0 ] == "new" )
    {
        if ( !url.hasQueryItem( "title" ) )
        {
            tLog() << "New playlist command needs a title...";
            return false;
        }
        playlist_ptr pl = Playlist::create( SourceList::instance()->getLocal(), uuid(), url.queryItemValue( "title" ), QString(), QString(), false );
        ViewManager::instance()->show( pl );
    }
    else if ( parts[ 0 ] == "add" )
    {
        if ( !url.hasQueryItem( "playlistid" ) || !url.hasQueryItem( "title" ) || !url.hasQueryItem( "artist" ) )
        {
            tLog() << "Add to playlist command needs playlistid, track, and artist..." << url.toString();
            return false;
        }
        // TODO implement. Let the user select what playlist to add to
        return false;
    }

    return false;
}
Exemple #3
0
QNetworkRequest RequestPrivate::buildRequest(QUrl u, bool authRequired) {
    if (authRequired) {
#if QT_VERSION >= 0x050000
        QUrlQuery query(u);
    
        if ((!query.hasQueryItem("key")) && (!apiKey.isEmpty())) {
            query.addQueryItem("key", apiKey);
        }
    
        if ((!query.hasQueryItem("access_token")) && (!accessToken.isEmpty())) {
            query.addQueryItem("access_token", accessToken);
        }
    
        u.setQuery(query);
#else
        if ((!u.hasQueryItem("key")) && (!apiKey.isEmpty())) {
            u.addQueryItem("key", apiKey);
        }
    
        if ((!u.hasQueryItem("access_token")) && (!accessToken.isEmpty())) {
            u.addQueryItem("access_token", accessToken);
        }
#endif
    }
#ifdef QYOUTUBE_DEBUG
    qDebug() << "QYouTube::RequestPrivate::buildRequest" << u;
#endif
    QNetworkRequest request(u);
    
    switch (operation) {
    case Request::PostOperation:
    case Request::PutOperation:
        switch (data.type()) {
        case QVariant::Map:
        case QVariant::List:
        case QVariant::StringList:
            request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
            break;
        default:
            request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
            break;
        }
        
        break;
    default:
        break;
    }
    
    if (!headers.isEmpty()) {
        addRequestHeaders(&request, headers);
    }
    
    return request;
}
bool
GlobalActionManager::handlePlaylistCommand( const QUrl& url )
{
    QStringList parts = url.path().split( "/" ).mid( 1 ); // get the rest of the command
    if ( parts.isEmpty() )
    {
        tLog() << "No specific playlist command:" << url.toString();
        return false;
    }

    if ( parts[ 0 ] == "import" )
    {
        if ( !url.hasQueryItem( "xspf" ) && !url.hasQueryItem( "jspf") )
        {
            tDebug() << "No xspf or jspf to load...";
            return false;
        }
        if ( url.hasQueryItem( "xspf" ) )
        {
            createPlaylistFromUrl( "xspf", url.queryItemValue( "xspf" ), url.hasQueryItem( "title" ) ? url.queryItemValue( "title" ) : QString() );
            return true;
        }
        else if ( url.hasQueryItem( "jspf" ) )
        {
            createPlaylistFromUrl( "jspf", url.queryItemValue( "jspf" ), url.hasQueryItem( "title" ) ? url.queryItemValue( "title" ) : QString() );
            return true;
        }
    }
    else if ( parts [ 0 ] == "new" )
    {
        if ( !url.hasQueryItem( "title" ) )
        {
            tLog() << "New playlist command needs a title...";
            return false;
        }
        playlist_ptr pl = Playlist::create( SourceList::instance()->getLocal(), uuid(), url.queryItemValue( "title" ), QString(), QString(), false );
        ViewManager::instance()->show( pl );
    }
    else if ( parts[ 0 ] == "add" )
    {
        if ( !url.hasQueryItem( "playlistid" ) || !url.hasQueryItem( "title" ) || !url.hasQueryItem( "artist" ) )
        {
            tLog() << "Add to playlist command needs playlistid, track, and artist..." << url.toString();
            return false;
        }
        // TODO implement. Let the user select what playlist to add to
        return false;
    }

    return false;
}
Exemple #5
0
void SoundCloud::checkUrl(const QUrl &webUrl) {
    QUrl url;

    if (webUrl.hasQueryItem("client_id")) {
        url = webUrl;
        url.setHost("api.soundcloud.com");
    }
    else {
        url.setUrl("http://api.soundcloud.com/resolve.json");
#if QT_VERSION >= 0x050000
        QUrlQuery query(url);
        query.addQueryItem("url", webUrl.toString());
        query.addQueryItem("client_id", CLIENT_ID);
        url.setQuery(query);
#else
        url.addQueryItem("url", webUrl.toString());
        url.addQueryItem("client_id", CLIENT_ID);
#endif
    }

    QNetworkRequest request(url);
    QNetworkReply *reply = this->networkAccessManager()->get(request);
    this->connect(reply, SIGNAL(finished()), this, SLOT(checkUrlIsValid()));
    this->connect(this, SIGNAL(currentOperationCancelled()), reply, SLOT(deleteLater()));
}
Exemple #6
0
bool QUrlProto::hasQueryItem(const QString &key) const
{
  QUrl *item = qscriptvalue_cast<QUrl*>(thisObject());
  if (item)
    return item->hasQueryItem(key);
  return false;
}
Exemple #7
0
int Url::hasQueryItem ( lua_State * L )// ( const QString & key ) const : bool
{
	QUrl* lhs = ValueInstaller2<QUrl>::check( L, 1 );
	//QString* key = ValueInstaller2<QString>::check( L, 2 );
	Util::push( L, lhs->hasQueryItem( Util::toString( L, 2 ) ) );
	return 1;
}
Exemple #8
0
void MegaShares::checkUrl(const QUrl &webUrl) {
    QNetworkRequest request;
#if QT_VERSION >= 0x050000
    QUrlQuery query(webUrl);
    
    if (query.hasQueryItem("d01")) {
        m_fileName = query.queryItemValue("d01");
        request.setUrl(webUrl);
    }
#else
    if (webUrl.hasQueryItem("d01")) {
        m_fileName = webUrl.queryItemValue("d01");
        request.setUrl(webUrl);
    }
#endif
    else {
        QString urlString = webUrl.toString();
        m_fileName = urlString.section('/', -1);
        QString id = urlString.section("/dl/", 1, 1).section('/', 0, 0);
        request.setUrl(QUrl("http://d01.megashares.com/?d01=" + id));
    }

    request.setRawHeader("Accept-Language", "en-GB,en-US;q=0.8,en;q=0.6");
    QNetworkReply *reply = this->networkAccessManager()->get(request);
    this->connect(reply, SIGNAL(finished()), this, SLOT(checkUrlIsValid()));
    this->connect(this, SIGNAL(currentOperationCancelled()), reply, SLOT(deleteLater()));
}
Exemple #9
0
bool UTIL::urlHasQueryItem( const QUrl& url, const QString& key )
{
#if QT_VERSION >= QT_VERSION_CHECK( 5, 0, 0 )
    return QUrlQuery( url ).hasQueryItem( key );
#else
    return url.hasQueryItem( key );
#endif
}
Exemple #10
0
bool QXmppSaslClientFacebook::respond(const QByteArray &challenge, QByteArray &response)
{
    if (m_step == 0) {
        // no initial response
        response = QByteArray();
        m_step++;
        return true;
    } else if (m_step == 1) {
        // parse request
#if QT_VERSION >= 0x050000
        QUrlQuery requestUrl(challenge);
#else
        QUrl requestUrl;
        requestUrl.setEncodedQuery(challenge);
#endif
        if (!requestUrl.hasQueryItem("method") || !requestUrl.hasQueryItem("nonce")) {
            warning("QXmppSaslClientFacebook : Invalid challenge, nonce or method missing");
            return false;
        }

        // build response
#if QT_VERSION >= 0x050000
        QUrlQuery responseUrl;
#else
        QUrl responseUrl;
#endif
        responseUrl.addQueryItem("access_token", password());
        responseUrl.addQueryItem("api_key", username());
        responseUrl.addQueryItem("call_id", 0);
        responseUrl.addQueryItem("method", requestUrl.queryItemValue("method"));
        responseUrl.addQueryItem("nonce", requestUrl.queryItemValue("nonce"));
        responseUrl.addQueryItem("v", "1.0");

#if QT_VERSION >= 0x050000
        response = responseUrl.query().toUtf8();
#else
        response = responseUrl.encodedQuery();
#endif
        m_step++;
        return true;
    } else {
        warning("QXmppSaslClientFacebook : Invalid step");
        return false;
    }
}
Exemple #11
0
int 
QDjViewOutline::pageNumber(const char *link)
{
  if (link && link[0] == '#')
    return djview->pageNumber(QString::fromUtf8(link+1));
  if (link == 0 || link[0] != '?')
    return -1;
  QByteArray burl = QByteArray("http://f/f") + link;
#if QT_VERSION >= 0x50000
  QUrlQuery qurl(QUrl::fromEncoded(burl));
#else
  QUrl qurl = QUrl::fromEncoded(burl);
#endif
  if (qurl.hasQueryItem("page"))
    return djview->pageNumber(qurl.queryItemValue("page"));
  else if (qurl.hasQueryItem("pageno"))
    return djview->pageNumber("$" + qurl.queryItemValue("pageno"));
  return -1;
}
	void startHandleRequest(ZhttpRequest *req, int basePathStart, const QByteArray &asPath, const DomainMap::Entry &route)
	{
		Session *s = new Session(this);
		s->req = req;

		QUrl uri = req->requestUri();

		QByteArray encPath = uri.encodedPath();
		s->path = encPath.mid(basePathStart);

		QList<QByteArray> parts = s->path.split('/');
		if(!parts.isEmpty() && parts.last().startsWith("jsonp"))
		{
			if(uri.hasQueryItem("callback"))
			{
				s->jsonpCallback = uri.queryItemValue("callback").toUtf8();
				uri.removeAllQueryItems("callback");
			}
			else if(uri.hasQueryItem("c"))
			{
				s->jsonpCallback = uri.queryItemValue("c").toUtf8();
				uri.removeAllQueryItems("c");
			}
		}

		s->asUri = uri;
		s->asUri.setScheme((s->asUri.scheme() == "https") ? "wss" : "ws");
		if(!asPath.isEmpty())
			s->asUri.setEncodedPath(asPath);
		else
			s->asUri.setEncodedPath(encPath.mid(0, basePathStart));

		s->route = route;

		connect(req, SIGNAL(readyRead()), SLOT(req_readyRead()));
		connect(req, SIGNAL(bytesWritten(int)), SLOT(req_bytesWritten(int)));
		connect(req, SIGNAL(error()), SLOT(req_error()));

		sessions += s;
		sessionsByRequest.insert(s->req, s);

		processRequestInput(s);
	}
Exemple #13
0
void LiteDoc::openUrlFile(const QUrl &url)
{
    QFileInfo info(url.toLocalFile());
    if (!info.exists()) {
        info.setFile(url.path());
    }
    QString ext = info.suffix().toLower();
    if (ext == "html") {
        QFile file(info.filePath());
        if (file.open(QIODevice::ReadOnly)) {
            QByteArray ba = file.readAll();
            file.close();
            if (info.fileName().compare("docs.html",Qt::CaseInsensitive) == 0) {
                updateHtmlDoc(url,ba,QString(),false);
            } else {
                updateHtmlDoc(url,ba);
            }
        }
    } else if (ext == "md") {
        QFile file(info.filePath());
        if (file.open(QIODevice::ReadOnly)) {
            QByteArray ba = mdtohtml(file.readAll());
            updateHtmlDoc(url,ba);
        }
    } else if (ext == "go") {
        LiteApi::IEditor *editor = m_liteApp->fileManager()->openEditor(info.filePath());
        if (editor) {
            editor->setReadOnly(true);
            QPlainTextEdit *ed = LiteApi::findExtensionObject<QPlainTextEdit*>(editor,"LiteApi.QPlainTextEdit");
            if (ed && url.hasQueryItem("s")) {
                QStringList pos = url.queryItemValue("s").split(":");
                if (pos.length() == 2) {
                    bool ok = false;
                    int begin = pos.at(0).toInt(&ok);
                    if (ok) {
                        QTextCursor cur = ed->textCursor();
                        cur.setPosition(begin);
                        ed->setTextCursor(cur);
                        ed->centerCursor();
                    }
                }
            }
        }
    } else if (ext == "pdf") {
        QDesktopServices::openUrl(info.filePath());
    } else {
        QFile file(info.filePath());
        if (file.open(QIODevice::ReadOnly)) {
            QByteArray ba = file.readAll();
            updateTextDoc(url,ba,info.fileName());
        }
    }
}
Exemple #14
0
QUrl WmsServerLayout::downloadUrl( const QUrl &prototypeUrl, const Marble::TileId &tileId ) const
{
    GeoDataLatLonBox box = tileId.toLatLonBox( m_textureLayer );

#if QT_VERSION < 0x050000
    QUrl url = prototypeUrl;
#else
    QUrlQuery url(prototypeUrl.query());
#endif
    url.addQueryItem( "service", "WMS" );
    url.addQueryItem( "request", "GetMap" );
    url.addQueryItem( "version", "1.1.1" );
    if ( !url.hasQueryItem( "styles" ) )
        url.addQueryItem( "styles", "" );
    if ( !url.hasQueryItem( "format" ) ) {
        if ( m_textureLayer->fileFormat().toLower() == "jpg" )
            url.addQueryItem( "format", "image/jpeg" );
        else
            url.addQueryItem( "format", "image/" + m_textureLayer->fileFormat().toLower() );
    }
    if ( !url.hasQueryItem( "srs" ) ) {
        url.addQueryItem( "srs", epsgCode() );
    }
    if ( !url.hasQueryItem( "layers" ) )
        url.addQueryItem( "layers", m_textureLayer->name() );
    url.addQueryItem( "width", QString::number( m_textureLayer->tileSize().width() ) );
    url.addQueryItem( "height", QString::number( m_textureLayer->tileSize().height() ) );
    url.addQueryItem( "bbox", QString( "%1,%2,%3,%4" ).arg( QString::number( box.west( GeoDataCoordinates::Degree ), 'f', 12 ) )
                                                      .arg( QString::number( box.south( GeoDataCoordinates::Degree ), 'f', 12 ) )
                                                      .arg( QString::number( box.east( GeoDataCoordinates::Degree ), 'f', 12 ) )
                                                      .arg( QString::number( box.north( GeoDataCoordinates::Degree ), 'f', 12 ) ) );
#if QT_VERSION < 0x050000
    return url;
#else
    QUrl finalUrl = prototypeUrl;
    finalUrl.setQuery(url);
    return finalUrl;
#endif
}
bool
GlobalActionManager::handleImportCommand( const QUrl& url )
{
    QStringList parts = url.path().split( "/" ).mid( 1 ); // get the rest of the command
    if ( parts.size() < 1 )
        return false;

    if ( parts[ 0 ] == "playlist" )
    {
        if ( url.hasQueryItem( "xspf" ) )
        {
            createPlaylistFromUrl( "xspf", url.queryItemValue( "xspf" ), url.hasQueryItem( "title" ) ? url.queryItemValue( "title" ) : QString() );
            return true;
        }
        else if ( url.hasQueryItem( "jspf" ) )
        {
            createPlaylistFromUrl( "jspf", url.queryItemValue( "jspf" ), url.hasQueryItem( "title" ) ? url.queryItemValue( "title" ) : QString() );
            return true;
        }
    }

    return false;
}
void WebView::onUrlChanged(const QUrl &u) {
#ifdef QSOUNDCLOUD_DEBUG
    qDebug() << "WebView::onUrlChanged" << u;
#endif
#if QT_VERSION >= 0x050000
    QUrlQuery query(u);
    
    if (query.hasQueryItem("code")) {
        request.exchangeCodeForAccessToken(query.queryItemValue("code"));
    }
#else
    if (u.hasQueryItem("code")) {
        request.exchangeCodeForAccessToken(u.queryItemValue("code"));
    }
#endif
}
Exemple #17
0
void
message_view::link_clicked(const QUrl& url)
{
  if (url.scheme()=="mailto") {
#if QT_VERSION<0x050000 // later
    // TODO: use more headers, particularly "body"
    mail_header header;
    if (!url.path().isEmpty())
      header.m_to=url.path();
    if (url.hasQueryItem("subject")) {
      header.m_subject=url.queryItemValue("subject");
    }
    gl_pApplication->start_new_mail(header);
#endif
  }
  else if (url.scheme().isEmpty()) {
    const QString cmd=url.toString();
    if (cmd=="#manitou-fetch") {
      allow_external_contents();
    }
    else if (cmd=="#manitou-to_text") {
      show_text_part();
    }
    else if (cmd=="#manitou-to_html") {
      show_html_part();
    }
    else if (cmd=="#manitou-show") {
      emit on_demand_show_request();
      display_commands();
    }
    else if (cmd=="#manitou-complete_load") {
      complete_body_load();
      enable_command("complete_load", false);
      display_commands();
    }    
  }
  else {
    browser::open_url(url);
  }
}
Exemple #18
0
// Extract the provider definition from the url
bool QgsDelimitedTextFile::setFromUrl( const QUrl &url )
{
  // Close any existing definition
  resetDefinition();

  // Extract the file name
  setFileName( url.toLocalFile() );

  // Extract the encoding
  if ( url.hasQueryItem( "encoding" ) )
  {
    mEncoding = url.queryItemValue( "encoding" );
  }

  //
  if ( url.hasQueryItem( "useWatcher" ) )
  {
    mUseWatcher = ! url.queryItemValue( "useWatcher" ).toUpper().startsWith( 'N' );
  }

  // The default type is csv, to be consistent with the
  // previous implementation (except that quoting should be handled properly)

  QString type( "csv" );
  QString delimiter( "," );
  QString quote = "\"";
  QString escape = "\"";
  mUseHeader = true;
  mSkipLines = 0;

  // Prefer simple "type" for delimiter type, but include delimiterType
  // as optional name  for backwards compatibility
  if ( url.hasQueryItem( "type" ) || url.hasQueryItem( "delimiterType" ) )
  {
    if ( url.hasQueryItem( "type" ) )
      type = url.queryItemValue( "type" );
    else if ( url.hasQueryItem( "delimiterType" ) )
      type = url.queryItemValue( "delimiterType" );

    // Support for previous version of Qgs - plain chars had
    // quote characters ' or "
    if ( type == "plain" )
    {
      quote = "'\"";
      escape = "";
    }
    else if ( type == "regexp " )
    {
      delimiter = "";
      quote = "";
      escape = "";
    }
  }
  if ( url.hasQueryItem( "delimiter" ) )
  {
    delimiter = url.queryItemValue( "delimiter" );
  }
  if ( url.hasQueryItem( "quote" ) )
  {
    quote = url.queryItemValue( "quote" );
  }
  if ( url.hasQueryItem( "escape" ) )
  {
    escape = url.queryItemValue( "escape" );
  }
  if ( url.hasQueryItem( "skipLines" ) )
  {
    mSkipLines = url.queryItemValue( "skipLines" ).toInt();
  }
  if ( url.hasQueryItem( "useHeader" ) )
  {
    mUseHeader = ! url.queryItemValue( "useHeader" ).toUpper().startsWith( 'N' );
  }
  if ( url.hasQueryItem( "skipEmptyFields" ) )
  {
    mDiscardEmptyFields = ! url.queryItemValue( "skipEmptyFields" ).toUpper().startsWith( 'N' );
  }
  if ( url.hasQueryItem( "trimFields" ) )
  {
    mTrimFields = ! url.queryItemValue( "trimFields" ).toUpper().startsWith( 'N' );
  }
  if ( url.hasQueryItem( "maxFields" ) )
  {
    mMaxFields = url.queryItemValue( "maxFields" ).toInt();
  }

  QgsDebugMsg( "Delimited text file is: " + mFileName );
  QgsDebugMsg( "Encoding is: " + mEncoding );
  QgsDebugMsg( "Delimited file type is: " + type );
  QgsDebugMsg( "Delimiter is: [" + delimiter + "]" );
  QgsDebugMsg( "Quote character is: [" + quote + "]" );
  QgsDebugMsg( "Escape character is: [" + escape + "]" );
  QgsDebugMsg( "Skip lines: " + QString::number( mSkipLines ) );
  QgsDebugMsg( "Maximum number of fields in record: " + QString::number( mMaxFields ) );
  QgsDebugMsg( "Use headers: " + QString( mUseHeader ? "Yes" : "No" ) );
  QgsDebugMsg( "Discard empty fields: " + QString( mDiscardEmptyFields ? "Yes" : "No" ) );
  QgsDebugMsg( "Trim fields: " + QString( mTrimFields ? "Yes" : "No" ) );

  // Support for previous version of plain characters
  if ( type == "csv" || type == "plain" )
  {
    setTypeCSV( delimiter, quote, escape );
  }
  else if ( type == "whitespace" )
  {
    setTypeWhitespace();
  }
  else if ( type == "regexp" )
  {
    setTypeRegexp( delimiter );
  }
  else
  {
    return false;
  }
  return mDefinitionValid;
}
Exemple #19
0
ServerItem *ServerItem::fromMimeData(const QMimeData *mime, bool default_name, QWidget *p) {
	if (mime->hasFormat(QLatin1String("OriginatedInMumble")))
		return NULL;

	QUrl url;
	if (mime->hasUrls() && ! mime->urls().isEmpty())
		url = mime->urls().at(0);
	else if (mime->hasText())
		url = QUrl::fromEncoded(mime->text().toUtf8());

	QString qsFile = url.toLocalFile();
	if (! qsFile.isEmpty()) {
		QFile f(qsFile);
		// Make sure we don't accidently read something big the user
		// happened to have in his clipboard. We only want to look
		// at small link files.
		if (f.open(QIODevice::ReadOnly) && f.size() < 10240) {
			QByteArray qba = f.readAll();
			f.close();

			url = QUrl::fromEncoded(qba, QUrl::StrictMode);
			if (! url.isValid()) {
				QSettings qs(qsFile, QSettings::IniFormat);
				url = QUrl::fromEncoded(qs.value(QLatin1String("InternetShortcut/URL")).toByteArray(), QUrl::StrictMode);
			}
		}
	}

#if QT_VERSION >= 0x050000
	QUrlQuery query(url);
#endif

	if (! url.isValid() || (url.scheme() != QLatin1String("mumble")))
		return NULL;

	if (url.userName().isEmpty()) {
		if (g.s.qsUsername.isEmpty()) {
			bool ok;
			QString defUserName = QInputDialog::getText(p, ConnectDialog::tr("Adding host %1").arg(url.host()), ConnectDialog::tr("Enter username"), QLineEdit::Normal, g.s.qsUsername, &ok).trimmed();
			if (! ok)
				return NULL;
			if (defUserName.isEmpty())
				return NULL;
			g.s.qsUsername = defUserName;
		}
		url.setUserName(g.s.qsUsername);
	}

#if QT_VERSION >= 0x050000
	if (! query.hasQueryItem(QLatin1String("title")) && default_name)
		query.addQueryItem(QLatin1String("title"), url.host());

	ServerItem *si = new ServerItem(query.queryItemValue(QLatin1String("title")), url.host(), static_cast<unsigned short>(url.port(DEFAULT_MUMBLE_PORT)), url.userName(), url.password());

	if (query.hasQueryItem(QLatin1String("url")))
		si->qsUrl = query.queryItemValue(QLatin1String("url"));
#else
	if (! url.hasQueryItem(QLatin1String("title")) && default_name)
		url.addQueryItem(QLatin1String("title"), url.host());

	ServerItem *si = new ServerItem(url.queryItemValue(QLatin1String("title")), url.host(), static_cast<unsigned short>(url.port(DEFAULT_MUMBLE_PORT)), url.userName(), url.password());

	if (url.hasQueryItem(QLatin1String("url")))
		si->qsUrl = url.queryItemValue(QLatin1String("url"));
#endif

	return si;
}
Exemple #20
0
void LiteDoc::openUrlFile(const QUrl &url)
{
    QFileInfo info(url.toLocalFile());
    if (!info.exists()) {
        info.setFile(url.path());
    }
    QString ext = info.suffix().toLower();
    if (ext == "html") {
        QFile file(info.filePath());
        if (file.open(QIODevice::ReadOnly)) {
            QByteArray ba = file.readAll();
            file.close();
            if (info.fileName().compare("docs.html",Qt::CaseInsensitive) == 0) {
                updateHtmlDoc(url,ba,QString(),false);
            } else {
                updateHtmlDoc(url,ba);
            }
        }
    } else if (ext == "md") {
        QFile file(info.filePath());
        if (file.open(QIODevice::ReadOnly)) {
            QByteArray ba = md2html(file.readAll());
            updateHtmlDoc(url,ba);
        }
    } else if (ext == "go") {
        LiteApi::IEditor *editor = m_liteApp->fileManager()->openEditor(info.filePath());
        if (editor) {
            editor->setReadOnly(true);
            QPlainTextEdit *ed = LiteApi::findExtensionObject<QPlainTextEdit*>(editor,"LiteApi.QPlainTextEdit");
#if QT_VERSION >= 0x050000
            if (ed && QUrlQuery(url).hasQueryItem("s")) {
                QStringList pos =  QUrlQuery(url).queryItemValue("s").split(":");
#else
            if (ed && url.hasQueryItem("s")) {
                QStringList pos = url.queryItemValue("s").split(":");
#endif
                if (pos.length() == 2) {
                    bool ok = false;
                    int begin = pos.at(0).toInt(&ok);
                    if (ok) {
                        QTextCursor cur = ed->textCursor();
                        cur.setPosition(begin);
                        ed->setTextCursor(cur);
                        ed->centerCursor();
                    }
                }
            }
        }
    } else if (ext == "pdf") {
        QDesktopServices::openUrl(info.filePath());
    } else {
        QFile file(info.filePath());
        if (file.open(QIODevice::ReadOnly)) {
            QByteArray ba = file.readAll();
            updateTextDoc(url,ba,info.fileName());
        }
    }
}

void LiteDoc::updateTextDoc(const QUrl &url, const QByteArray &ba, const QString &header)
{
    m_lastUrl = url;
    QTextCodec *codec = QTextCodec::codecForUtfText(ba,QTextCodec::codecForName("utf-8"));
#if QT_VERSION >= 0x050000
    QString html = codec->toUnicode(ba).toHtmlEscaped();
#else
    QString html = Qt::escape(codec->toUnicode(ba));
#endif
    QString data = m_templateData;
    data.replace("{header}",header);
    data.replace("{nav}","");
    data.replace("{content}",QString("<pre>%1</pre>").arg(html));
    m_docBrowser->setUrlHtml(url,data);

}
Exemple #21
0
QgsMemoryProvider::QgsMemoryProvider( const QString &uri, const ProviderOptions &options )
  : QgsVectorDataProvider( uri, options )
{
  // Initialize the geometry with the uri to support old style uri's
  // (ie, just 'point', 'line', 'polygon')
  QUrl url = QUrl::fromEncoded( uri.toUtf8() );
  QString geometry;
  if ( url.hasQueryItem( QStringLiteral( "geometry" ) ) )
  {
    geometry = url.queryItemValue( QStringLiteral( "geometry" ) );
  }
  else
  {
    geometry = url.path();
  }

  if ( geometry.toLower() == QLatin1String( "none" ) )
  {
    mWkbType = QgsWkbTypes::NoGeometry;
  }
  else
  {
    mWkbType = QgsWkbTypes::parseType( geometry );
  }

  if ( url.hasQueryItem( QStringLiteral( "crs" ) ) )
  {
    QString crsDef = url.queryItemValue( QStringLiteral( "crs" ) );
    mCrs.createFromString( crsDef );
  }

  mNextFeatureId = 1;

  setNativeTypes( QList< NativeType >()
                  << QgsVectorDataProvider::NativeType( tr( "Whole number (integer)" ), QStringLiteral( "integer" ), QVariant::Int, 0, 10 )
                  // Decimal number from OGR/Shapefile/dbf may come with length up to 32 and
                  // precision up to length-2 = 30 (default, if width is not specified in dbf is length = 24 precision = 15)
                  // We know that double (QVariant::Double) has only 15-16 significant numbers,
                  // but setting that correct limits would disable the use of memory provider with
                  // data from Shapefiles. In any case, the data are handled as doubles.
                  // So the limits set here are not correct but enable use of data from Shapefiles.
                  << QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), QStringLiteral( "double" ), QVariant::Double, 0, 32, 0, 30 )
                  << QgsVectorDataProvider::NativeType( tr( "Text (string)" ), QStringLiteral( "string" ), QVariant::String, 0, 255 )

                  // date type
                  << QgsVectorDataProvider::NativeType( tr( "Date" ), QStringLiteral( "date" ), QVariant::Date, -1, -1, -1, -1 )
                  << QgsVectorDataProvider::NativeType( tr( "Time" ), QStringLiteral( "time" ), QVariant::Time, -1, -1, -1, -1 )
                  << QgsVectorDataProvider::NativeType( tr( "Date & Time" ), QStringLiteral( "datetime" ), QVariant::DateTime, -1, -1, -1, -1 )

                  // integer types
                  << QgsVectorDataProvider::NativeType( tr( "Whole number (smallint - 16bit)" ), QStringLiteral( "int2" ), QVariant::Int, -1, -1, 0, 0 )
                  << QgsVectorDataProvider::NativeType( tr( "Whole number (integer - 32bit)" ), QStringLiteral( "int4" ), QVariant::Int, -1, -1, 0, 0 )
                  << QgsVectorDataProvider::NativeType( tr( "Whole number (integer - 64bit)" ), QStringLiteral( "int8" ), QVariant::LongLong, -1, -1, 0, 0 )
                  << QgsVectorDataProvider::NativeType( tr( "Decimal number (numeric)" ), QStringLiteral( "numeric" ), QVariant::Double, 1, 20, 0, 20 )
                  << QgsVectorDataProvider::NativeType( tr( "Decimal number (decimal)" ), QStringLiteral( "decimal" ), QVariant::Double, 1, 20, 0, 20 )

                  // floating point
                  << QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), QStringLiteral( "real" ), QVariant::Double, -1, -1, -1, -1 )
                  << QgsVectorDataProvider::NativeType( tr( "Decimal number (double)" ), QStringLiteral( "double precision" ), QVariant::Double, -1, -1, -1, -1 )

                  // string types
                  << QgsVectorDataProvider::NativeType( tr( "Text, unlimited length (text)" ), QStringLiteral( "text" ), QVariant::String, -1, -1, -1, -1 )
                );

  if ( url.hasQueryItem( QStringLiteral( "field" ) ) )
  {
    QList<QgsField> attributes;
    QRegExp reFieldDef( "\\:"
                        "(int|integer|long|int8|real|double|string|date|time|datetime)" // type
                        "(?:\\((\\-?\\d+)"                // length
                        "(?:\\,(\\d+))?"                  // precision
                        "\\))?(\\[\\])?"                  // array
                        "$", Qt::CaseInsensitive );
    QStringList fields = url.allQueryItemValues( QStringLiteral( "field" ) );
    for ( int i = 0; i < fields.size(); i++ )
    {
      QString name = QUrl::fromPercentEncoding( fields.at( i ).toUtf8() );
      QVariant::Type type = QVariant::String;
      QVariant::Type subType = QVariant::Invalid;
      QString typeName( QStringLiteral( "string" ) );
      int length = 255;
      int precision = 0;

      int pos = reFieldDef.indexIn( name );
      if ( pos >= 0 )
      {
        name = name.mid( 0, pos );
        typeName = reFieldDef.cap( 1 ).toLower();
        if ( typeName == QLatin1String( "int" ) || typeName == QLatin1String( "integer" ) )
        {
          type = QVariant::Int;
          typeName = QStringLiteral( "integer" );
          length = -1;
        }
        else if ( typeName == QLatin1String( "int8" ) || typeName == QLatin1String( "long" ) )
        {
          type = QVariant::LongLong;
          typeName = QStringLiteral( "int8" );
          length = -1;
        }
        else if ( typeName == QLatin1String( "real" ) || typeName == QLatin1String( "double" ) )
        {
          type = QVariant::Double;
          typeName = QStringLiteral( "double" );
          length = 20;
          precision = 5;
        }
        else if ( typeName == QLatin1String( "date" ) )
        {
          type = QVariant::Date;
          typeName = QStringLiteral( "date" );
          length = -1;
        }
        else if ( typeName == QLatin1String( "time" ) )
        {
          type = QVariant::Time;
          typeName = QStringLiteral( "time" );
          length = -1;
        }
        else if ( typeName == QLatin1String( "datetime" ) )
        {
          type = QVariant::DateTime;
          typeName = QStringLiteral( "datetime" );
          length = -1;
        }

        if ( !reFieldDef.cap( 2 ).isEmpty() )
        {
          length = reFieldDef.cap( 2 ).toInt();
        }
        if ( !reFieldDef.cap( 3 ).isEmpty() )
        {
          precision = reFieldDef.cap( 3 ).toInt();
        }
        if ( !reFieldDef.cap( 4 ).isEmpty() )
        {
          //array
          subType = type;
          type = ( subType == QVariant::String ? QVariant::StringList : QVariant::List );
        }
      }
      if ( !name.isEmpty() )
        attributes.append( QgsField( name, type, typeName, length, precision, QLatin1String( "" ), subType ) );
    }
    addAttributes( attributes );
  }

  if ( url.hasQueryItem( QStringLiteral( "index" ) ) && url.queryItemValue( QStringLiteral( "index" ) ) == QLatin1String( "yes" ) )
  {
    createSpatialIndex();
  }

}
Exemple #22
0
QgsMemoryProvider::QgsMemoryProvider( QString uri )
    : QgsVectorDataProvider( uri )
    , mSpatialIndex( 0 )
{
  // Initialize the geometry with the uri to support old style uri's
  // (ie, just 'point', 'line', 'polygon')
  QUrl url = QUrl::fromEncoded( uri.toUtf8() );
  QString geometry;
  if ( url.hasQueryItem( "geometry" ) )
  {
    geometry = url.queryItemValue( "geometry" );
  }
  else
  {
    geometry = url.path();
  }

  geometry = geometry.toLower();
  if ( geometry == "point" )
    mWkbType = QGis::WKBPoint;
  else if ( geometry == "linestring" )
    mWkbType = QGis::WKBLineString;
  else if ( geometry == "polygon" )
    mWkbType = QGis::WKBPolygon;
  else if ( geometry == "multipoint" )
    mWkbType = QGis::WKBMultiPoint;
  else if ( geometry == "multilinestring" )
    mWkbType = QGis::WKBMultiLineString;
  else if ( geometry == "multipolygon" )
    mWkbType = QGis::WKBMultiPolygon;
  else
    mWkbType = QGis::WKBUnknown;

  if ( url.hasQueryItem( "crs" ) )
  {
    QString crsDef = url.queryItemValue( "crs" );
    mCrs.createFromString( crsDef );
  }

  mNextFeatureId = 1;

  mNativeTypes
  << QgsVectorDataProvider::NativeType( tr( "Whole number (integer)" ), "integer", QVariant::Int, 0, 10 )
  // Decimal number from OGR/Shapefile/dbf may come with length up to 32 and
  // precision up to length-2 = 30 (default, if width is not specified in dbf is length = 24 precision = 15)
  // We know that double (QVariant::Double) has only 15-16 significant numbers,
  // but setting that correct limits would disable the use of memory provider with
  // data from Shapefiles. In any case, the data are handled as doubles.
  // So the limits set here are not correct but enable use of data from Shapefiles.
  << QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), "double", QVariant::Double, 0, 32, 0, 30 )
  << QgsVectorDataProvider::NativeType( tr( "Text (string)" ), "string", QVariant::String, 0, 255 )

  // date type
  << QgsVectorDataProvider::NativeType( tr( "Date" ), "date", QVariant::Date, -1, -1, -1, -1 )

  // integer types
  << QgsVectorDataProvider::NativeType( tr( "Whole number (smallint - 16bit)" ), "int2", QVariant::Int, -1, -1, 0, 0 )
  << QgsVectorDataProvider::NativeType( tr( "Whole number (integer - 32bit)" ), "int4", QVariant::Int, -1, -1, 0, 0 )
  << QgsVectorDataProvider::NativeType( tr( "Whole number (integer - 64bit)" ), "int8", QVariant::LongLong, -1, -1, 0, 0 )
  << QgsVectorDataProvider::NativeType( tr( "Decimal number (numeric)" ), "numeric", QVariant::Double, 1, 20, 0, 20 )
  << QgsVectorDataProvider::NativeType( tr( "Decimal number (decimal)" ), "decimal", QVariant::Double, 1, 20, 0, 20 )

  // floating point
  << QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), "real", QVariant::Double, -1, -1, -1, -1 )
  << QgsVectorDataProvider::NativeType( tr( "Decimal number (double)" ), "double precision", QVariant::Double, -1, -1, -1, -1 )

  // string types
  << QgsVectorDataProvider::NativeType( tr( "Text, unlimited length (text)" ), "text", QVariant::String, -1, -1, -1, -1 )
  ;

  if ( url.hasQueryItem( "field" ) )
  {
    QList<QgsField> attributes;
    QRegExp reFieldDef( "\\:"
                        "(int|integer|real|double|string|date)" // type
                        "(?:\\((\\d+)"                // length
                        "(?:\\,(\\d+))?"                // precision
                        "\\))?"
                        "$", Qt::CaseInsensitive );
    QStringList fields = url.allQueryItemValues( "field" );
    for ( int i = 0; i < fields.size(); i++ )
    {
      QString name = fields.at( i );
      QVariant::Type type = QVariant::String;
      QString typeName( "string" );
      int length = 255;
      int precision = 0;

      int pos = reFieldDef.indexIn( name );
      if ( pos >= 0 )
      {
        name = name.mid( 0, pos );
        typeName = reFieldDef.cap( 1 ).toLower();
        if ( typeName == "int" || typeName == "integer" )
        {
          type = QVariant::Int;
          typeName = "integer";
          length = 10;
        }
        else if ( typeName == "real" || typeName == "double" )
        {
          type = QVariant::Double;
          typeName = "double";
          length = 20;
          precision = 5;
        }
        else if ( typeName == "date" )
        {
          type = QVariant::Date;
          typeName = "date";
          length = 10;
        }

        if ( reFieldDef.cap( 2 ) != "" )
        {
          length = reFieldDef.cap( 2 ).toInt();
        }
        if ( reFieldDef.cap( 3 ) != "" )
        {
          precision = reFieldDef.cap( 3 ).toInt();
        }
      }
      if ( name != "" )
        attributes.append( QgsField( name, type, typeName, length, precision ) );
    }
    addAttributes( attributes );
  }

  if ( url.hasQueryItem( "index" ) && url.queryItemValue( "index" ) == "yes" )
  {
    createSpatialIndex();
  }

}
QgsDelimitedTextProvider::QgsDelimitedTextProvider( QString uri )
    : QgsVectorDataProvider( uri )
    , mDelimiter( "," )
    , mDelimiterType( "plain" )
    , mFieldCount( 0 )
    , mXFieldIndex( -1 )
    , mYFieldIndex( -1 )
    , mWktFieldIndex( -1 )
    , mWktHasZM( false )
    , mWktZMRegexp( "\\s+(?:z|m|zm)(?=\\s*\\()", Qt::CaseInsensitive )
    , mWktCrdRegexp( "(\\-?\\d+(?:\\.\\d*)?\\s+\\-?\\d+(?:\\.\\d*)?)\\s[\\s\\d\\.\\-]+" )
    , mFile( 0 )
    , mStream( 0 )
    , mSkipLines( 0 )
    , mFirstDataLine( 0 )
    , mShowInvalidLines( false )
    , mCrs()
    , mWkbType( QGis::WKBUnknown )
{
  QUrl url = QUrl::fromEncoded( uri.toAscii() );

  // Extract the provider definition from the url
  mFileName = url.toLocalFile();

  QString wktField;
  QString xField;
  QString yField;

  if ( url.hasQueryItem( "delimiter" ) )
    mDelimiter = url.queryItemValue( "delimiter" );
  if ( url.hasQueryItem( "delimiterType" ) )
    mDelimiterType = url.queryItemValue( "delimiterType" );
  if ( url.hasQueryItem( "wktField" ) )
    wktField = url.queryItemValue( "wktField" );
  if ( url.hasQueryItem( "xField" ) )
    xField = url.queryItemValue( "xField" );
  if ( url.hasQueryItem( "yField" ) )
    yField = url.queryItemValue( "yField" );
  if ( url.hasQueryItem( "skipLines" ) )
    mSkipLines = url.queryItemValue( "skipLines" ).toInt();
  if ( url.hasQueryItem( "crs" ) )
    mCrs.createFromString( url.queryItemValue( "crs" ) );
  if ( url.hasQueryItem( "decimalPoint" ) )
    mDecimalPoint = url.queryItemValue( "decimalPoint" );

  QgsDebugMsg( "Data source uri is " + uri );
  QgsDebugMsg( "Delimited text file is: " + mFileName );
  QgsDebugMsg( "Delimiter is: " + mDelimiter );
  QgsDebugMsg( "Delimiter type is: " + mDelimiterType );
  QgsDebugMsg( "wktField is: " + wktField );
  QgsDebugMsg( "xField is: " + xField );
  QgsDebugMsg( "yField is: " + yField );
  QgsDebugMsg( "skipLines is: " + QString::number( mSkipLines ) );

  // if delimiter contains some special characters, convert them
  if ( mDelimiterType != "regexp" )
    mDelimiter.replace( "\\t", "\t" ); // replace "\t" with a real tabulator

  // Set the selection rectangle to null
  mSelectionRectangle = QgsRectangle();
  // assume the layer is invalid until proven otherwise
  mValid = false;
  if ( mFileName.isEmpty() || mDelimiter.isEmpty() )
  {
    // uri is invalid so the layer must be too...
    QgsDebugMsg( "Data source is invalid" );
    return;
  }

  // check to see that the file exists and perform some sanity checks
  if ( !QFile::exists( mFileName ) )
  {
    QgsDebugMsg( "Data source " + dataSourceUri() + " doesn't exist" );
    return;
  }

  // Open the file and get number of rows, etc. We assume that the
  // file has a header row and process accordingly. Caller should make
  // sure that the delimited file is properly formed.
  mFile = new QFile( mFileName );
  if ( !mFile->open( QIODevice::ReadOnly ) )
  {
    QgsDebugMsg( "Data source " + dataSourceUri() + " could not be opened" );
    delete mFile;
    mFile = 0;
    return;
  }

  // now we have the file opened and ready for parsing

  // set the initial extent
  mExtent = QgsRectangle();

  QMap<int, bool> couldBeInt;
  QMap<int, bool> couldBeDouble;

  mStream = new QTextStream( mFile );
  QString line;
  mNumberFeatures = 0;
  int lineNumber = 0;
  bool hasFields = false;
  while ( !mStream->atEnd() )
  {
    lineNumber++;
    line = readLine( mStream ); // line of text excluding '\n', default local 8 bit encoding.

    if ( lineNumber < mSkipLines + 1 )
      continue;

    if ( line.isEmpty() )
      continue;

    if ( !hasFields )
    {
      // Get the fields from the header row and store them in the
      // fields vector
      QStringList fieldList = splitLine( line );

      mFieldCount = fieldList.count();

      // We don't know anything about a text based field other
      // than its name. All fields are assumed to be text
      int fieldPos = 0;
      for ( int column = 0; column < mFieldCount; column++ )
      {
        QString field = fieldList[column];

        if (( field.left( 1 ) == "'" || field.left( 1 ) == "\"" ) &&
            field.left( 1 ) == field.right( 1 ) )
          // eat quotes
          field = field.mid( 1, field.length() - 2 );

        if ( field.length() == 0 )
          // skip empty field names
          continue;

        // check to see if this field matches either the x or y field
        if ( !wktField.isEmpty() && wktField == field )
        {
          QgsDebugMsg( "Found wkt field: " + ( field ) );
          mWktFieldIndex = column;
        }
        else if ( !xField.isEmpty() && xField == field )
        {
          QgsDebugMsg( "Found x field: " + ( field ) );
          mXFieldIndex = column;
        }
        else if ( !yField.isEmpty() && yField == field )
        {
          QgsDebugMsg( "Found y field: " + ( field ) );
          mYFieldIndex = column;
        }

        // WKT geometry field won't be displayed in attribute tables
        if ( column == mWktFieldIndex )
          continue;

        QgsDebugMsg( "Adding field: " + ( field ) );
        // assume that the field could be integer or double
        // for now, let's set field type as text
        attributeColumns.append( column );
        attributeFields[fieldPos] = QgsField( field, QVariant::String, "Text" );
        couldBeInt.insert( fieldPos, true );
        couldBeDouble.insert( fieldPos, true );
        fieldPos++;
      }
      if ( mWktFieldIndex >= 0 )
      {
        mXFieldIndex = -1;
        mYFieldIndex = -1;
      }
      QgsDebugMsg( "wktfield index: " + QString::number( mWktFieldIndex ) );
      QgsDebugMsg( "xfield index: " + QString::number( mXFieldIndex ) );
      QgsDebugMsg( "yfield index: " + QString::number( mYFieldIndex ) );
      QgsDebugMsg( "Field count for the delimited text file is " + QString::number( attributeFields.size() ) );
      hasFields = true;
    }
    else // hasFields == true - field names already read
    {
      if ( mFirstDataLine == 0 )
        mFirstDataLine = lineNumber;

      // split the line on the delimiter
      QStringList parts = splitLine( line );

      // Ensure that the input has at least the required number of fields (mainly to tolerate
      // missed blank strings at end of row)
      while ( parts.size() < mFieldCount )
        parts.append( QString::null );

      if ( mWktFieldIndex >= 0 )
      {
        // Get the wkt - confirm it is valid, get the type, and
        // if compatible with the rest of file, add to the extents

        QString sWkt = parts[mWktFieldIndex];
        QgsGeometry *geom = 0;
        try
        {
          if ( !mWktHasZM && sWkt.indexOf( mWktZMRegexp ) >= 0 )
            mWktHasZM = true;
          if ( mWktHasZM )
          {
            sWkt.remove( mWktZMRegexp ).replace( mWktCrdRegexp, "\\1" );
          }
          geom = QgsGeometry::fromWkt( sWkt );
        }
        catch ( ... )
        {
          mInvalidLines << line;
          geom = 0;
        }

        if ( geom )
        {
          QGis::WkbType type = geom->wkbType();
          if ( type != QGis::WKBNoGeometry )
          {
            if ( mNumberFeatures == 0 )
            {
              mNumberFeatures++;
              mWkbType = type;
              mExtent = geom->boundingBox();
            }
            else if ( type == mWkbType )
            {
              mNumberFeatures++;
              QgsRectangle bbox( geom->boundingBox() );
              mExtent.combineExtentWith( &bbox );
            }
          }
          delete geom;
        }
      }
      else if ( mWktFieldIndex == -1 && mXFieldIndex >= 0 && mYFieldIndex >= 0 )
      {
        // Get the x and y values, first checking to make sure they
        // aren't null.

        QString sX = parts[mXFieldIndex];
        QString sY = parts[mYFieldIndex];


        if ( !mDecimalPoint.isEmpty() )
        {
          sX.replace( mDecimalPoint, "." );
          sY.replace( mDecimalPoint, "." );
        }

        bool xOk = false;
        bool yOk = false;
        double x = sX.toDouble( &xOk );
        double y = sY.toDouble( &yOk );

        if ( xOk && yOk )
        {
          if ( mNumberFeatures > 0 )
          {
            mExtent.combineExtentWith( x, y );
          }
          else
          {
            // Extent for the first point is just the first point
            mExtent.set( x, y, x, y );
            mWkbType = QGis::WKBPoint;
          }
          mNumberFeatures++;
        }
        else
        {
          mInvalidLines << line;
        }
      }
      else
      {
        mWkbType = QGis::WKBNoGeometry;
        mNumberFeatures++;
      }

      for ( int i = 0; i < attributeFields.size(); i++ )
      {
        QString &value = parts[attributeColumns[i]];
        if ( value.isEmpty() )
          continue;
        // try to convert attribute values to integer and double
        if ( couldBeInt[i] )
        {
          value.toInt( &couldBeInt[i] );
        }
        if ( couldBeDouble[i] )
        {
          value.toDouble( &couldBeDouble[i] );
        }
      }
    }
  }

  QgsDebugMsg( "geometry type is: " + QString::number( mWkbType ) );
  QgsDebugMsg( "feature count is: " + QString::number( mNumberFeatures ) );

  // now it's time to decide the types for the fields
  for ( QgsFieldMap::iterator it = attributeFields.begin(); it != attributeFields.end(); ++it )
  {
    if ( couldBeInt[it.key()] )
    {
      it->setType( QVariant::Int );
      it->setTypeName( "integer" );
    }
    else if ( couldBeDouble[it.key()] )
    {
      it->setType( QVariant::Double );
      it->setTypeName( "double" );
    }
  }

  mValid = mWkbType != QGis::WKBUnknown;
}
bool
GlobalActionManager::parseTomahawkLink( const QString& urlIn )
{
    QString url = urlIn;
    if ( urlIn.startsWith( "http://toma.hk" ) )
        url.replace( "http://toma.hk/", "tomahawk://" );

    if ( url.contains( "tomahawk://" ) )
    {
        QString cmd = url.mid( 11 );
        cmd.replace( "%2B", "%20" );
        tLog() << "Parsing tomahawk link command" << cmd;

        QString cmdType = cmd.split( "/" ).first();
        QUrl u = QUrl::fromEncoded( cmd.toUtf8() );

        // for backwards compatibility
        if ( cmdType == "load" )
        {
            if ( u.hasQueryItem( "xspf" ) )
            {
                QUrl xspf = QUrl::fromUserInput( u.queryItemValue( "xspf" ) );
                XSPFLoader* l = new XSPFLoader( true, this );
                tDebug() << "Loading spiff:" << xspf.toString();
                l->load( xspf );
                connect( l, SIGNAL( ok( Tomahawk::playlist_ptr ) ), ViewManager::instance(), SLOT( show( Tomahawk::playlist_ptr ) ) );

                return true;
            }
            else if ( u.hasQueryItem( "jspf" ) )
            {
                QUrl jspf = QUrl::fromUserInput( u.queryItemValue( "jspf" ) );
                JSPFLoader* l = new JSPFLoader( true, this );

                tDebug() << "Loading jspiff:" << jspf.toString();
                l->load( jspf );
                connect( l, SIGNAL( ok( Tomahawk::playlist_ptr ) ), ViewManager::instance(), SLOT( show( Tomahawk::playlist_ptr ) ) );

                return true;
            }
        }

        if ( cmdType == "playlist" )
        {
            return handlePlaylistCommand( u );
        }
        else if ( cmdType == "collection" )
        {
            return handleCollectionCommand( u );
        }
        else if ( cmdType == "queue" )
        {
            return handleQueueCommand( u );
        }
        else if ( cmdType == "station" )
        {
            return handleStationCommand( u );
        }
        else if ( cmdType == "autoplaylist" )
        {
            return handleAutoPlaylistCommand( u );
        }
        else if ( cmdType == "search" )
        {
            return handleSearchCommand( u );
        }
        else if ( cmdType == "play" )
        {
            return handlePlayCommand( u );
        }
        else if ( cmdType == "bookmark" )
        {
            return handlePlayCommand( u );
        }
        else if ( cmdType == "open" )
        {
            return handleOpenCommand( u );
        }
        else if ( cmdType == "view" )
        {
            return handleViewCommand( u );
        }
        else
        {
            tLog() << "Tomahawk link not supported, command not known!" << cmdType << u.path();
            return false;
        }
    }
    else
    {
        tLog() << "Not a tomahawk:// link!";
        return false;
    }
}
Exemple #25
0
bool WulforUtil::openUrl(const QString &url){
    if (url.startsWith("http://") || url.startsWith("www.") || url.startsWith(("ftp://")) || url.startsWith("https://")){
        if (!SETTING(MIME_HANDLER).empty())
            QProcess::startDetached(_q(SETTING(MIME_HANDLER)), QStringList(url));
        else
            QDesktopServices::openUrl(QUrl::fromEncoded(url.toAscii()));
    }
    else if (url.startsWith("adc://") || url.startsWith("adcs://")){
        MainWindow::getInstance()->newHubFrame(url, "UTF-8");
    }
    else if (url.startsWith("dchub://")){
        MainWindow::getInstance()->newHubFrame(url, WSGET(WS_DEFAULT_LOCALE));
    }
    else if (url.startsWith("magnet:") && url.contains("urn:tree:tiger")){
        QString magnet = url;
        Magnet *m = new Magnet(MainWindow::getInstance());

        m->setLink(magnet);
        if (WIGET(WI_DEF_MAGNET_ACTION) == 0) {
            m->exec();
        }

        m->deleteLater();
    }
    else if (url.startsWith("magnet:")){
        QString magnet = url;

        QUrl u;

        if (!magnet.contains("+"))
            u.setEncodedUrl(magnet.toAscii());
        else {
            QString _l = magnet;

            _l.replace("+", "%20");
            u.setEncodedUrl(_l.toAscii());
        }

        if (u.hasQueryItem("kt")){
            QString keywords = u.queryItemValue("kt");
            QString hub = u.hasQueryItem("xs")? u.queryItemValue("xs") : "";

            if (!(hub.startsWith("dchub://", Qt::CaseInsensitive) ||
                  hub.startsWith("adc://", Qt::CaseInsensitive) ||
                  hub.startsWith("adcs://", Qt::CaseInsensitive)) && !hub.isEmpty())
                hub.prepend("dchub://");

            if (keywords.isEmpty())
                return false;

            if (!hub.isEmpty())
                WulforUtil::openUrl(hub);

            SearchFrame *sfr = ArenaWidgetFactory().create<SearchFrame>();
            sfr->fastSearch(keywords, false);
        }
        else {
            if (!SETTING(MIME_HANDLER).empty())
                QProcess::startDetached(_q(SETTING(MIME_HANDLER)), QStringList(url));
            else
                QDesktopServices::openUrl(QUrl::fromEncoded(url.toAscii()));
        }
    }
    else
        return false;

    return true;
}
QgsDelimitedTextProvider::QgsDelimitedTextProvider( QString uri )
    : QgsVectorDataProvider( uri )
    , mLayerValid( false )
    , mValid( false )
    , mFile( 0 )
    , mGeomRep( GeomNone )
    , mFieldCount( 0 )
    , mXFieldIndex( -1 )
    , mYFieldIndex( -1 )
    , mWktFieldIndex( -1 )
    , mWktHasZM( false )
    , mWktHasPrefix( false )
    , mXyDms( false )
    , mSubsetString( "" )
    , mSubsetExpression( 0 )
    , mBuildSubsetIndex( true )
    , mUseSubsetIndex( false )
    , mMaxInvalidLines( 50 )
    , mShowInvalidLines( true )
    , mRescanRequired( false )
    , mCrs()
    , mWkbType( QGis::WKBNoGeometry )
    , mGeometryType( QGis::UnknownGeometry )
    , mBuildSpatialIndex( false )
    , mSpatialIndex( 0 )
{

  // Add supported types to enable creating expression fields in field calculator
  mNativeTypes
  << QgsVectorDataProvider::NativeType( tr( "Whole number (integer)" ), "integer", QVariant::Int, 0, 10 )
  << QgsVectorDataProvider::NativeType( tr( "Whole number (integer - 64 bit)" ), "int8", QVariant::LongLong )
  << QgsVectorDataProvider::NativeType( tr( "Decimal number (double)" ), "double precision", QVariant::Double, -1, -1, -1, -1 )
  << QgsVectorDataProvider::NativeType( tr( "Text, unlimited length (text)" ), "text", QVariant::String, -1, -1, -1, -1 )
  ;

  QgsDebugMsg( "Delimited text file uri is " + uri );

  QUrl url = QUrl::fromEncoded( uri.toAscii() );
  mFile = new QgsDelimitedTextFile();
  mFile->setFromUrl( url );

  QString subset;

  if ( url.hasQueryItem( "geomType" ) )
  {
    QString gtype = url.queryItemValue( "geomType" ).toLower();
    if ( gtype == "point" ) mGeometryType = QGis::Point;
    else if ( gtype == "line" ) mGeometryType = QGis::Line;
    else if ( gtype == "polygon" ) mGeometryType = QGis::Polygon;
    else if ( gtype == "none " ) mGeometryType = QGis::NoGeometry;
  }

  if ( mGeometryType != QGis::NoGeometry )
  {
    if ( url.hasQueryItem( "wktField" ) )
    {
      mWktFieldName = url.queryItemValue( "wktField" );
      mGeomRep = GeomAsWkt;
      QgsDebugMsg( "wktField is: " + mWktFieldName );
    }
    else if ( url.hasQueryItem( "xField" ) && url.hasQueryItem( "yField" ) )
    {
      mGeomRep = GeomAsXy;
      mGeometryType = QGis::Point;
      mXFieldName = url.queryItemValue( "xField" );
      mYFieldName = url.queryItemValue( "yField" );
      QgsDebugMsg( "xField is: " + mXFieldName );
      QgsDebugMsg( "yField is: " + mYFieldName );

      if ( url.hasQueryItem( "xyDms" ) )
      {
        mXyDms = ! url.queryItemValue( "xyDms" ).toLower().startsWith( "n" );
      }
    }
    else
    {
      mGeometryType = QGis::NoGeometry;
    }
  }

  if ( url.hasQueryItem( "decimalPoint" ) )
    mDecimalPoint = url.queryItemValue( "decimalPoint" );

  if ( url.hasQueryItem( "crs" ) )
    mCrs.createFromString( url.queryItemValue( "crs" ) );

  if ( url.hasQueryItem( "subsetIndex" ) )
  {
    mBuildSubsetIndex = ! url.queryItemValue( "subsetIndex" ).toLower().startsWith( "n" );
  }

  if ( url.hasQueryItem( "spatialIndex" ) )
  {
    mBuildSpatialIndex = ! url.queryItemValue( "spatialIndex" ).toLower().startsWith( "n" );
  }

  if ( url.hasQueryItem( "subset" ) )
  {
    subset = url.queryItemValue( "subset" );
    QgsDebugMsg( "subset is: " + subset );
  }

  if ( url.hasQueryItem( "quiet" ) ) mShowInvalidLines = false;

  // Do an initial scan of the file to determine field names, types,
  // geometry type (for Wkt), extents, etc.  Parameter value subset.isEmpty()
  // avoid redundant building indexes if we will be building a subset string,
  // in which case indexes will be rebuilt.

  scanFile( subset.isEmpty() );

  if ( ! subset.isEmpty() )
  {
    setSubsetString( subset );
  }
}
QgsDelimitedTextProvider::QgsDelimitedTextProvider( const QString &uri, const ProviderOptions &options )
  : QgsVectorDataProvider( uri, options )
{

  // Add supported types to enable creating expression fields in field calculator
  setNativeTypes( QList< NativeType >()
                  << QgsVectorDataProvider::NativeType( tr( "Whole number (integer)" ), QStringLiteral( "integer" ), QVariant::Int, 0, 10 )
                  << QgsVectorDataProvider::NativeType( tr( "Whole number (integer - 64 bit)" ), QStringLiteral( "int8" ), QVariant::LongLong )
                  << QgsVectorDataProvider::NativeType( tr( "Decimal number (double)" ), QStringLiteral( "double precision" ), QVariant::Double, -1, -1, -1, -1 )
                  << QgsVectorDataProvider::NativeType( tr( "Text, unlimited length (text)" ), QStringLiteral( "text" ), QVariant::String, -1, -1, -1, -1 )
                );

  QgsDebugMsg( "Delimited text file uri is " + uri );

  QUrl url = QUrl::fromEncoded( uri.toLatin1() );
  mFile = qgis::make_unique< QgsDelimitedTextFile >();
  mFile->setFromUrl( url );

  QString subset;

  if ( url.hasQueryItem( QStringLiteral( "geomType" ) ) )
  {
    QString gtype = url.queryItemValue( QStringLiteral( "geomType" ) ).toLower();
    if ( gtype == QLatin1String( "point" ) ) mGeometryType = QgsWkbTypes::PointGeometry;
    else if ( gtype == QLatin1String( "line" ) ) mGeometryType = QgsWkbTypes::LineGeometry;
    else if ( gtype == QLatin1String( "polygon" ) ) mGeometryType = QgsWkbTypes::PolygonGeometry;
    else if ( gtype == QLatin1String( "none " ) ) mGeometryType = QgsWkbTypes::NullGeometry;
  }

  if ( mGeometryType != QgsWkbTypes::NullGeometry )
  {
    if ( url.hasQueryItem( QStringLiteral( "wktField" ) ) )
    {
      mWktFieldName = url.queryItemValue( QStringLiteral( "wktField" ) );
      mGeomRep = GeomAsWkt;
      QgsDebugMsg( "wktField is: " + mWktFieldName );
    }
    else if ( url.hasQueryItem( QStringLiteral( "xField" ) ) && url.hasQueryItem( QStringLiteral( "yField" ) ) )
    {
      mGeomRep = GeomAsXy;
      mGeometryType = QgsWkbTypes::PointGeometry;
      mXFieldName = url.queryItemValue( QStringLiteral( "xField" ) );
      mYFieldName = url.queryItemValue( QStringLiteral( "yField" ) );
      QgsDebugMsg( "xField is: " + mXFieldName );
      QgsDebugMsg( "yField is: " + mYFieldName );

      if ( url.hasQueryItem( QStringLiteral( "xyDms" ) ) )
      {
        mXyDms = ! url.queryItemValue( QStringLiteral( "xyDms" ) ).toLower().startsWith( 'n' );
      }
    }
    else
    {
      mGeometryType = QgsWkbTypes::NullGeometry;
    }
  }

  mDetectTypes = true;
  if ( url.hasQueryItem( QStringLiteral( "detectTypes" ) ) )
    mDetectTypes = ! url.queryItemValue( QStringLiteral( "detectTypes" ) ).toLower().startsWith( 'n' );

  if ( url.hasQueryItem( QStringLiteral( "decimalPoint" ) ) )
    mDecimalPoint = url.queryItemValue( QStringLiteral( "decimalPoint" ) );

  if ( url.hasQueryItem( QStringLiteral( "crs" ) ) )
    mCrs.createFromString( url.queryItemValue( QStringLiteral( "crs" ) ) );

  if ( url.hasQueryItem( QStringLiteral( "subsetIndex" ) ) )
  {
    mBuildSubsetIndex = ! url.queryItemValue( QStringLiteral( "subsetIndex" ) ).toLower().startsWith( 'n' );
  }

  if ( url.hasQueryItem( QStringLiteral( "spatialIndex" ) ) )
  {
    mBuildSpatialIndex = ! url.queryItemValue( QStringLiteral( "spatialIndex" ) ).toLower().startsWith( 'n' );
  }

  if ( url.hasQueryItem( QStringLiteral( "subset" ) ) )
  {
    // We need to specify FullyDecoded so that %25 is decoded as %
    subset = QUrlQuery( url ).queryItemValue( QStringLiteral( "subset" ), QUrl::FullyDecoded );
    QgsDebugMsg( "subset is: " + subset );
  }

  if ( url.hasQueryItem( QStringLiteral( "quiet" ) ) ) mShowInvalidLines = false;

  // Do an initial scan of the file to determine field names, types,
  // geometry type (for Wkt), extents, etc.  Parameter value subset.isEmpty()
  // avoid redundant building indexes if we will be building a subset string,
  // in which case indexes will be rebuilt.

  scanFile( subset.isEmpty() );

  if ( ! subset.isEmpty() )
  {
    setSubsetString( subset );
  }
}