Example #1
0
void JSKitPebble::openURL(const QUrl &url)
{
    qCDebug(l) << "opening url" << url.toString();
    emit _mgr->appOpenUrl(url);
}
Example #2
0
void Page::parseTags()
{
	// Check redirection
	QUrl redir = m_replyTags->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
	if (!redir.isEmpty())
	{
		m_urlRegex = m_site->fixUrl(redir.toString(), m_urlRegex);
		loadTags();
		return;
	}

	QString source = QString::fromUtf8(m_replyTags->readAll());
	m_tags.clear();

	if (m_site->contains("Regex/Tags"))
	{
		QRegExp rxtags(m_site->value("Regex/Tags"));
		rxtags.setMinimal(true);
		int p = 0;
		QStringList order = m_site->value("Regex/TagsOrder").split('|', QString::SkipEmptyParts);
		while ((p = rxtags.indexIn(source, p)) != -1)
		{
			p += rxtags.matchedLength();
			QString type = "", tag = "";
			int count = 1;
			if (order.empty())
			{
				switch (rxtags.captureCount())
				{
					case 4:	order << "type" << "" << "count" << "tag";	break;
					case 3:	order << "type" << "tag" << "count";		break;
					case 2:	order << "type" << "tag";					break;
					case 1:	order << "tag";								break;
				}
			}
			for (int o = 0; o < order.size(); o++)
			{
				if (order.at(o) == "tag" && tag.isEmpty())
				{ tag = rxtags.cap(o + 1).replace(" ", "_").replace("&amp;", "&").trimmed(); }
				else if (order.at(o) == "type" && type.isEmpty())
				{
					type = rxtags.cap(o + 1).toLower().trimmed();
					if (type.contains(", "))
					{ type = type.split(", ").at(0).trimmed(); }
					if (type == "series")
					{ type = "copyright"; }
					else if (type == "mangaka")
					{ type = "artist"; }
					else if (type == "game")
					{ type = "copyright"; }
					else if (type == "studio")
					{ type = "circle"; }
					else if (type == "source")
					{ type = "general"; }
					else if (type == "character group")
					{ type = "general"; }
					else if (type.length() == 1)
					{
						int tpe = type.toInt();
						if (tpe >= 0 && tpe <= 4)
						{
							QStringList types = QStringList() << "general" << "artist" << "unknown" << "copyright" << "character";
							type = types[tpe];
						}
					}
				}
				else if (order.at(o) == "count" && count != 0)
				{ count = rxtags.cap(o + 1).toLower().endsWith('k') ? rxtags.cap(3).left(rxtags.cap(3).length() - 1).toInt() * 1000 : rxtags.cap(3).toInt(); }
			}
			if (type.isEmpty())
			{ type = "unknown"; }
			m_tags.append(Tag(tag, type, count));
		}
	}

	// Getting last page
	if (m_site->contains("Regex/Count") && m_imagesCount < 1)
	{
		QRegExp rxlast(m_site->value("Regex/Count"));
		rxlast.indexIn(source, 0);
		m_imagesCount = rxlast.cap(1).remove(",").toInt();
	}
	if (m_imagesCount < 1)
	{
		for (Tag tag : m_tags)
		{
			if (tag.text() == m_search.join(" "))
			{
				m_imagesCount = tag.count();
				if (m_pagesCount < 0)
					m_pagesCount = (int)ceil((m_imagesCount * 1.) / m_imagesPerPage);
			}
		}
	}
	if (m_site->contains("Regex/LastPage") && (m_imagesCount < 1 || m_imagesCount % 1000 == 0))
	{
		QRegExp rxlast(m_site->value("Regex/LastPage"));
		rxlast.indexIn(source, 0);
		m_pagesCount = rxlast.cap(1).remove(",").toInt();
		if (m_pagesCount != 0)
			m_imagesCount = m_pagesCount * m_imagesPerPage;
	}

	// Wiki
	m_wiki.clear();
	if (m_site->contains("Regex/Wiki"))
	{
		QRegExp rxwiki(m_site->value("Regex/Wiki"));
		rxwiki.setMinimal(true);
		if (rxwiki.indexIn(source) != -1)
		{
			m_wiki = rxwiki.cap(1);
			m_wiki.remove("/wiki/show?title=").remove(QRegExp("<p><a href=\"([^\"]+)\">Full entry &raquo;</a></p>")).replace("<h6>", "<span class=\"title\">").replace("</h6>", "</span>");
		}
	}

	m_replyTags->deleteLater();
	m_replyTagsExists = false;

	emit finishedLoadingTags(this);
}
Example #3
0
void MainWindow::setAddressUrl(const QUrl& url)
{
    setAddressUrl(url.toString(QUrl::RemoveUserInfo));
}
Example #4
0
QString FileServerHandler::LocalFilePath(const QUrl &url,
                                           const QString &wantgroup)
{
    QString lpath = url.path();

    if (lpath.section('/', -2, -2) == "channels")
    {
        // This must be an icon request. Check channel.icon to be safe.
        QString querytext;

        QString file = lpath.section('/', -1);
        lpath = "";

        MSqlQuery query(MSqlQuery::InitCon());
        query.prepare("SELECT icon FROM channel WHERE icon LIKE :FILENAME ;");
        query.bindValue(":FILENAME", QString("%/") + file);

        if (query.exec() && query.next())
        {
            lpath = query.value(0).toString();
        }
        else
        {
            MythDB::DBError("Icon path", query);
        }
    }
    else
    {
        lpath = lpath.section('/', -1);

        QString fpath = lpath;
        if (fpath.right(4) == ".png")
            fpath = fpath.left(fpath.length() - 4);

        ProgramInfo pginfo(fpath);
        if (pginfo.GetChanID())
        {
            QString pburl = GetPlaybackURL(&pginfo);
            if (pburl.left(1) == "/")
            {
                lpath = pburl.section('/', 0, -2) + "/" + lpath;
                LOG(VB_FILE, LOG_INFO,
                    QString("Local file path: %1").arg(lpath));
            }
            else
            {
                LOG(VB_GENERAL, LOG_ERR,
                        QString("LocalFilePath unable to find local "
                                "path for '%1', found '%2' instead.")
                                .arg(lpath).arg(pburl));
                lpath = "";
            }
        }
        else if (!lpath.isEmpty())
        {
            // For securities sake, make sure filename is really the pathless.
            QString opath = lpath;
            StorageGroup sgroup;

            if (!wantgroup.isEmpty())
            {
                sgroup.Init(wantgroup);
                lpath = url.toString();
            }
            else
            {
                lpath = QFileInfo(lpath).fileName();
            }

            QString tmpFile = sgroup.FindFile(lpath);
            if (!tmpFile.isEmpty())
            {
                lpath = tmpFile;
                LOG(VB_FILE, LOG_INFO,
                        QString("LocalFilePath(%1 '%2'), found through "
                                "exhaustive search at '%3'")
                            .arg(url.toString()).arg(opath).arg(lpath));
            }
            else
            {
                LOG(VB_GENERAL, LOG_ERR, QString("LocalFilePath unable to "
                                                 "find local path for '%1'.")
                                .arg(opath));
                lpath = "";
            }

        }
        else
        {
            lpath = "";
        }
    }

    return lpath;
}
void SdtpCatalogDataProvider::parseNetworkReply( QNetworkReply *reply )
{
    //
    //
    //
    if( !m_netRequests.contains(reply) ) {
        qDebug("Orphan request found with url = '%s'",
               reply->url().toString().toLatin1().constData());
        reply->deleteLater();
        return;
    }

#ifdef QT_DEBUG
    qDebug("Network request '%s' took %d ms",
           reply->url().toString().toLatin1().constData(),
           m_debug_requestStart[reply].elapsed() );
    m_debug_requestStart[reply].restart();

    if ( reply->error() != QNetworkReply::NoError ) {
        qDebug("QNetworkReply error! Code: %d", reply->error());
    }
#endif

    QPair<void*, RequestType> pair = m_netRequests[reply];
    void* param = pair.first;
    RequestType type = pair.second;

    //
    // HANDLE REDIRECTION
    //
    QUrl redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();

    if ( !redirectUrl.isEmpty() && redirectUrl != reply->url()) {
        // all non-local thumbnail redirects are disabled!
        QString redirUrl = redirectUrl.toString();
        if ( Thumbnail != type || !redirUrl.contains(QRegExp("is74.ru/", Qt::CaseInsensitive, QRegExp::Wildcard)) )
        {
            QNetworkReply* newReply = m_network->get(QNetworkRequest(redirectUrl));
#ifdef QT_DEBUG
            debug_addRequestTime(newReply);
#endif
            // replace reply ptr in hash
            m_netRequests[newReply] = m_netRequests[reply];
            m_netRequests.remove(reply);
            return;
        }
    }

    m_netRequests.remove(reply);

    switch ( type ) {
    case FoldersRecursive: {
        XFolder* parent = static_cast<XFolder*>(param);
        XFolderList *list = new XFolderList;
        XFolderDict *dict = new XFolderDict;
        bool ok = parseFoldersRecursiveData(parent, *reply, *dict, *list);
        if ( ok ) {
            emit data(FoldersRecursive, parent, list);
            emit data(FoldersRecursiveDictionary, parent, dict);
        } else {
            delete list;
            delete dict;
            emit error(FoldersRecursive, parent);
        }
        break;
    }

    case Folders: {
        XFolder* parent = static_cast<XFolder*>(param);
        XFolderList *list = new XFolderList;
        bool ok = parseFoldersData(parent, *reply, *list);
        if ( ok )
            emit data(Folders, parent, list);
        else {
            delete list;
            emit error(Folders, parent);
        }
        break;
    }

    case Files: {
        XFolder *parent = static_cast<XFolder*>(param);
        XFileList *list = new XFileList;
        bool ok = parseFilesData(parent, *reply, *list);
        if ( ok )
            emit data(Files, parent, list);
        else {
            delete list;
            emit error(Files, parent);
        }
        break;
    }

    case FileDetails: {
        XFile *file = static_cast<XFile*>(param);
        XFile *dummy = new XFile(0,0,QString());;
        bool ok = parseFileDetailsData(dummy, *reply);
        if ( ok )
            emit data(FileDetails, file, dummy);
        else {
            delete dummy;
            emit error(FileDetails, file);
        }
        break;
    }

    case Thumbnail: {
        XFile *file = static_cast<XFile*>(param);
        QImageReader imgReader(reply);
        QImage *image = new QImage();
        *image = imgReader.read();
        if ( !image->isNull() ) {
            emit data(Thumbnail, file, image);
        } else {
            delete image;
            emit error(Thumbnail, file);
        }

        break;
    }

    case Search: {
        XFileList *list = new XFileList;
        bool ok = parseSearchData(*reply, *list);
        if ( ok )
            emit data(Search, NULL, list);
        else {
            delete list;
            emit error(Search, NULL);
        }

        break;
    }

    case FoldersRecursiveDictionary:
    default:
    {
        qDebug("Unsupported RequetType reply '%d'", type);
    }

    }

#ifdef QT_DEBUG
    qDebug("Parsing took %d ms", m_debug_requestStart[reply].elapsed() );
    m_debug_requestStart.remove(reply);
#endif

    reply->deleteLater();
}
Example #6
0
void MyTextBrowser::slotLinkClicked(const QUrl &link)
{
  char buf[MAX_PRINTF_LENGTH];
  QString url;
  int i;

  url = link.toString();

  // replace "href=\"//awite://" by "href=/"
  while(1)
  {
    i = url.indexOf("awite://");
    if(i < 0) break;
    url = url.replace(i,8,"/");
    if(opt.arg_debug) printf("MyTextBrowser::slotLinkClicked::link clicked = %s\n", (const char *) url.toUtf8());
  }

  if(opt.arg_debug) printf("slotLinkClicked(%s)\n", (const char *) url.toUtf8());
  if(url.startsWith("http://") && (url.endsWith(".pdf") || url.endsWith(".PDF")))
  {
    QString cmd = opt.view_pdf;
    cmd += " ";
    url.replace(" ","%20");
    cmd += url;
//#ifndef PVWIN32
//    cmd +=  " &";
//#endif
    mysystem(cmd.toUtf8());
  }
  else if(
         !url.startsWith("http://audio.") &&
          url.startsWith("http://") && (
          url.endsWith(".mp3",  Qt::CaseInsensitive) || 
          url.endsWith(".ogg",  Qt::CaseInsensitive) || 
          url.endsWith(".m3u",  Qt::CaseInsensitive) || 
          url.endsWith(".asx",  Qt::CaseInsensitive) || 
          url.contains(".pls?", Qt::CaseInsensitive) ||
          url.contains("mp3e",  Qt::CaseInsensitive) ||
          url.startsWith("http://www.youtube.com/watch?") ))
  {
    QString cmd = opt.view_audio;
    cmd += " ";
    url.replace(" ","%20");
    cmd += url;
//#ifndef PVWIN32
//    cmd +=  " &";
//#endif
    mysystem(cmd.toUtf8());
  }
  else if(
         !url.startsWith("http://video.") &&
          url.startsWith("http://") && (
          url.endsWith(".mp4",  Qt::CaseInsensitive) || 
          url.endsWith(".mov",  Qt::CaseInsensitive) || 
          url.endsWith(".ogv",  Qt::CaseInsensitive) || 
          url.endsWith(".avi",  Qt::CaseInsensitive) ))
  {
    QString cmd = opt.view_video;
    cmd += " ";
    url.replace(" ","%20");
    cmd += url;
//#ifndef PVWIN32
//    cmd +=  " &";
//#endif
    mysystem(cmd.toUtf8());
  }
  else
  {
    if(url.length()+40 > MAX_PRINTF_LENGTH) return;
    sprintf(buf,"text(%d,\"%s\")\n", id,decode(url));
    tcp_send(s,buf,strlen(buf));
#ifdef NO_WEBKIT
    if     (url.startsWith("http:"))  setSource(QUrl(url));
    else if(url.startsWith("https:")) setSource(QUrl(url));
    else if(!url.contains("://"))     setSource(QUrl(url));
#else    
    load(link);
#endif    
  }  
}
Example #7
0
bool MixtureCloud::urlSupported(const QUrl &url) const {
    return urlPattern().indexIn(url.toString()) == 0;
}
static bool launchWebBrowser(const QUrl &url)
{
    if (url.scheme() == QLatin1String("mailto")) {
        //Retrieve the commandline for the default mail client
        //the default key used below is the command line for the mailto: shell command
        DWORD  bufferSize = sizeof(wchar_t) * MAX_PATH;
        long  returnValue =  -1;
        QString command;

        HKEY handle;
        LONG res;
        wchar_t keyValue[MAX_PATH] = {0};
        QString keyName(QLatin1String("mailto"));

        //Check if user has set preference, otherwise use default.
        res = RegOpenKeyEx(HKEY_CURRENT_USER,
                           L"Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\mailto\\UserChoice",
                           0, KEY_READ, &handle);
        if (res == ERROR_SUCCESS) {
            returnValue = RegQueryValueEx(handle, L"Progid", 0, 0, reinterpret_cast<unsigned char*>(keyValue), &bufferSize);
            if (!returnValue)
                keyName = QString::fromUtf16((const ushort*)keyValue);
            RegCloseKey(handle);
        }
        keyName += QLatin1String("\\Shell\\Open\\Command");
        res = RegOpenKeyExW(HKEY_CLASSES_ROOT, (const wchar_t*)keyName.utf16(), 0, KEY_READ, &handle);
        if (res != ERROR_SUCCESS)
            return false;

        bufferSize = sizeof(wchar_t) * MAX_PATH;
        returnValue = RegQueryValueEx(handle, L"", 0, 0, reinterpret_cast<unsigned char*>(keyValue), &bufferSize);
        if (!returnValue)
            command = QString::fromRawData((QChar*)keyValue, bufferSize);
        RegCloseKey(handle);

        if (returnValue)
            return false;

        command = expandEnvStrings(command);
        command = command.trimmed();
        //Make sure the path for the process is in quotes
        int index = -1 ;
        if (command[0]!= QLatin1Char('\"')) {
            index = command.indexOf(QLatin1String(".exe "), 0, Qt::CaseInsensitive);
            command.insert(index+4, QLatin1Char('\"'));
            command.insert(0, QLatin1Char('\"'));
        }
        //pass the url as the parameter
        index =  command.lastIndexOf(QLatin1String("%1"));
        if (index != -1){
            command.replace(index, 2, url.toString());
        }
        //start the process
        PROCESS_INFORMATION pi;
        ZeroMemory(&pi, sizeof(pi));
        STARTUPINFO si;
        ZeroMemory(&si, sizeof(si));
        si.cb = sizeof(si);

        returnValue = CreateProcess(NULL, (wchar_t*)command.utf16(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);

        if (!returnValue)
            return false;

        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
        return true;
    }

    if (!url.isValid())
        return false;

    if (url.scheme().isEmpty())
        return openDocument(url);

    quintptr returnValue = (quintptr)ShellExecute(0, 0, (wchar_t *)QString::fromUtf8(url.toEncoded().constData()).utf16(),
                                                  0, 0, SW_SHOWNORMAL);
    return (returnValue > 32);
}
void MainWindow::downloadFinished(QNetworkReply *reply)
{
    QScrollBar *sb = ui->textBrowser->verticalScrollBar();
    QUrl url = reply->url();

    if (reply->error()) {
      if ( !url.toString().contains("hgt.zip") ) {
        ui->textBrowser->append("Download of " + QString(url.toEncoded().constData()) + " failed: " + QString(reply->errorString()));
        sb->setValue(sb->maximum()); // get the info shown
      }

        QString fileUrl = url.toEncoded().constData();
    } else {
        QString path = url.path();
        QString fileName = QFileInfo(path).fileName();
        if (fileName.isEmpty()) fileName = "download";

        QDir dir(dataDirectory);
        dir.mkpath(dataDirectory);
        QFile file(dataDirectory+"/"+fileName);

        if (fileName.contains("dl")) {
            // obtain url
            QFile file(dataDirectory+"/"+fileName);
        } else if (fileName.contains("hgt")) {
            // obtain elevation files
            dir.mkpath(dataDirectory+"/SRTM-3/");
            file.setFileName(dataDirectory+"/SRTM-3/"+fileName);
            GUILog( url.toString() + "\n", "download" );
        }

        if (file.open(QIODevice::WriteOnly)) {
            file.write(reply->readAll());
            file.close();
        }

        // download actual shapefile package
        if (fileName.contains("dl")) {
            QFile dlFile(dataDirectory+"/"+fileName);
            if (!dlFile.open(QIODevice::ReadOnly | QIODevice::Text))
                return;
            QTextStream textStream( &dlFile);
            QString dlUrl = textStream.readAll();
            dlUrl.remove("<p>The document has moved <a href=\"");
            dlUrl.remove("\">here</a></p>\n");
            QNetworkReply *r = _manager->get(QNetworkRequest("http://mapserver.flightgear.org"+dlUrl));
            connect(r, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(downloadShapefilesProgressBar(qint64, qint64)));
        }

        ui->textBrowser->append("Download of "+QString(url.toEncoded().constData())+" succeded saved to: "+QString(fileName));
        sb->setValue(sb->maximum()); // get the info shown

        // unzip shapefile package
        if (fileName.contains("-")) {
            // unpack zip
            QString arguments;
#ifdef Q_OS_WIN
            arguments += "7z.exe x \""+dataDirectory+"/"+fileName+"\" -o\""+dataDirectory+"\" -aoa";
#endif
#ifdef Q_OS_UNIX
            arguments += "unzip -o "+dataDirectory+"/"+fileName+" -d "+dataDirectory;
#endif
            //ui->textBrowser->append(arguments);
            GUILog( arguments + "\n", "download" );
            QProcess proc;
            proc.start(arguments, QIODevice::ReadWrite);
            proc.waitForReadyRead();
            proc.waitForFinished(-1);

            // delete temporary files
            QFile shapeFile(dataDirectory+"/"+fileName);
            shapeFile.remove();
            QFile dlshpFile(dataDirectory+"/dlshp");
            dlshpFile.remove();

            // re-enable download button
            ui->downloadShapefilesButton->setText("Download shapefiles");
            ui->downloadShapefilesButton->setEnabled(1);
        }

        if (fileName.contains(".hgt.zip")){
            // adjust progress bar
            ui->downloadElevationProgressBar->setValue(ui->downloadElevationProgressBar->value()+1);
        }
    }
    // re-enable download button
    if (ui->downloadElevationProgressBar->value() == ui->downloadElevationProgressBar->maximum()) {
        ui->downloadElevationButton->setEnabled(1);
    }
}
Example #10
0
// Send request to the network manager
// Caller must hold m_mutex
bool NetStream::Request(const QUrl& url)
{
    if (!IsSupported(url))
    {
        LOG(VB_GENERAL, LOG_WARNING, LOC +
            QString("(%1) Request unsupported URL: %2")
            .arg(m_id).arg(url.toString()) );
        return false;
    }

    if (m_pending)
    {
        // Cancel the pending request
        m_pending->m_bCancelled = true;
        m_pending = 0;
    }

    if (m_reply)
    {
        // Abort the current reply
        // NB the abort method appears to only work if called from NAMThread
        m_reply->disconnect(this);
        NAMThread::PostEvent(new NetStreamAbort(m_id, m_reply));
        // NAMthread will delete the reply
        m_reply = 0;
    }

    m_request.setUrl(url);

    const QByteArray ua("User-Agent");
    if (!m_request.hasRawHeader(ua))
        m_request.setRawHeader(ua, "UK-MHEG/2 MYT001/001 MHGGNU/001");

    if (m_pos > 0 || m_size >= 0)
        m_request.setRawHeader("Range", QString("bytes=%1-").arg(m_pos).toLatin1());

#ifndef QT_NO_OPENSSL
    if (m_request.url().scheme() == "https")
    {
        QSslConfiguration ssl(QSslConfiguration::defaultConfiguration());

        QList<QSslCertificate> clist;
        if (!m_cert.isEmpty())
        {
            clist = QSslCertificate::fromData(m_cert, QSsl::Der);
            if (clist.isEmpty())
                LOG(VB_GENERAL, LOG_WARNING, LOC + QString("Invalid certificate: %1")
                    .arg(m_cert.toPercentEncoding().constData()) );
        }

        if (clist.isEmpty())
            // The BBC servers use a self certified cert so don't verify it
            ssl.setPeerVerifyMode(QSslSocket::VerifyNone);
        else
            ssl.setCaCertificates(clist);

        // We need to provide a client certificate for the BBC,  See:
        // openssl s_client -state -prexit -connect securegate.iplayer.bbc.co.uk:443
        // for a list of accepted certificates
        QString fname = gCoreContext->GetSetting("MhegClientCert", "");
        if (!fname.isEmpty())
        {
            QFile f(QFile::exists(fname) ? fname : GetShareDir() + fname);
            if (f.open(QIODevice::ReadOnly))
            {
                QSslCertificate cert(&f, QSsl::Pem);
                if (!cert.isNull())
                    ssl.setLocalCertificate(cert);
                else
                    LOG(VB_GENERAL, LOG_WARNING, LOC +
                        QString("'%1' is an invalid certificate").arg(f.fileName()) );
            }
            else
                LOG(VB_GENERAL, LOG_WARNING, LOC +
                    QString("Opening client certificate '%1': %2")
                    .arg(f.fileName()).arg(f.errorString()) );

            // Get the private key
            fname = gCoreContext->GetSetting("MhegClientKey", "");
            if (!fname.isEmpty())
            {
                QFile f(QFile::exists(fname) ? fname : GetShareDir() + fname);
                if (f.open(QIODevice::ReadOnly))
                {
                    QSslKey key(&f, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey,
                        gCoreContext->GetSetting("MhegClientKeyPass", "").toLatin1());
                    if (!key.isNull())
                        ssl.setPrivateKey(key);
                    else
                        LOG(VB_GENERAL, LOG_WARNING, LOC +
                            QString("'%1' is an invalid key").arg(f.fileName()) );
                }
                else
                    LOG(VB_GENERAL, LOG_WARNING, LOC +
                        QString("Opening private key '%1': %2")
                        .arg(f.fileName()).arg(f.errorString()) );
            }
        }

        m_request.setSslConfiguration(ssl);
    }
#endif

    LOG(VB_FILE, LOG_INFO, LOC + QString("(%1) Request %2 bytes=%3- from %4")
        .arg(m_id).arg(m_request.url().toString())
        .arg(m_pos).arg(Source(m_request)) );
    m_pending = new NetStreamRequest(m_id, m_request);
    NAMThread::PostEvent(m_pending);
    return true;
}
Example #11
0
void BrowserApplication::openUrl(const QUrl &url)
{
    mainWindow()->loadPage(url.toString());
}
Example #12
0
void Parser::parseFiles(QNetworkReply *reply, QMap<QNetworkReply*, Structureelement*> *replies, QString downloadDirectoryPath)
{
    // Holen die aktuelle Veranstaltung aus der Map
    Structureelement* aktuellerOrdner = replies->value(reply);

    // Auslesen der Antwort und Speichern in dem XmlReader
    QString replyText = reply->readAll();
    QXmlStreamReader Reader;
    Reader.addData(replyText);


    // Vorbereitung der Daten für die Elemente
    QString currentXmlTag;
    QUrl    url;
    QString name;
    QString time;
    qint32  size = 0;

    // Prüfen auf das Ende
    while(!Reader.atEnd())
    {
        // Lese nächstes Element
        Reader.readNext();

        // 1. Fall: Öffnendes Element <Element>
        if(Reader.isStartElement())
        {
            // Speichern des Namens
            currentXmlTag = Reader.name().toString();
        }

        // 2. Fall: Schließendes Element mit Namen Response </Response>
        else if (Reader.isEndElement() && Reader.name() == "response")
        {
            // Hinzufügen des Slashs bei der Url von Ordnern
            if(!size)
                url.setUrl(url.toString() % "/");

            // Wechsel in den übergeordneten Ordner des aktuellen Elements
            QString bla = url.toString();
            while(!url.toString().contains((aktuellerOrdner->data(urlRole).toUrl().toString()), Qt::CaseSensitive))//(in = RegExp.indexIn(url.toString())) == -1)
            {
                aktuellerOrdner->sortChildren(0, Qt::AscendingOrder);
                aktuellerOrdner = (Structureelement*)aktuellerOrdner->parent();
                if (aktuellerOrdner == 0)
                    qDebug() << replyText;
            }

            // Ignorieren aller Adressen, die "/Forms" enthalten
            if (!url.toString().contains("/Forms", Qt::CaseSensitive))
            {
                // Prüfe auf Elementart
                // 1. Fall: Datei (size > 0)
                if (size)
                {
                    // Erstellen einer neuen Datei
                    Structureelement* newFile = new Structureelement(name, url, time, size);

                    // Hinzufügen des endungsabhängigen Icons
                    // PDF
                    if (name.contains(QRegExp(".pdf$", Qt::CaseInsensitive)))
                        newFile->setData(QIcon(":/Icons/Icons/filetype_pdf.png"), Qt::DecorationRole);

                    // ZIP
                    else if (name.contains(QRegExp(".zip$", Qt::CaseInsensitive)))
                        newFile->setData(QIcon(":/Icons/Icons/filetype_zip.png"), Qt::DecorationRole);

                    // RAR
                    else if (name.contains(QRegExp(".rar$", Qt::CaseInsensitive)))
                        newFile->setData(QIcon(":/Icons/Icons/filetype_rar.png"), Qt::DecorationRole);

                    // Sonstige
                    else
                        newFile->setData(QIcon(":/Icons/Icons/file.png"), Qt::DecorationRole);


                    QString path;
                    path.append(Utils::getStrukturelementPfad(aktuellerOrdner, downloadDirectoryPath) %"/");
                    path.append(name);
                    path.remove(0,8);

                    if(QFile::exists(path))
                    {
                        newFile->setData(SYNCHRONISED, synchronisedRole);
                    }
                    else
                    {
                        newFile->setData(NOT_SYNCHRONISED, synchronisedRole);
                    }

                    QList<QStandardItem*> row;
                    row.append(newFile);
                    row.append(new QStandardItem(QString::number(size/1024.0/1024.0, 'f', 2) % " MB"));
                    row.append(new QStandardItem(QDateTime::fromString(time, Qt::ISODate).toString("yyyy-MM-dd hh:mm")));

                    // Hinzufügen zum aktuellen Ordner
                    aktuellerOrdner->appendRow(row);
                }
                // 2. Fall: Ordner/Veranstaltung
                // Ausschließen der Ordnernamen "documents" und "structured"
                else if (name != "documents" && name != "structured" && !url.toString().contains("exerciseCourse"))
                {
                    // Erstellen eines neuen Ordners
                    Structureelement* newDirectory = new Structureelement(name, url, directoryItem);

                    // Setzen des Zeichens
                    newDirectory->setData(QIcon(":/Icons/Icons/25_folder.png"), Qt::DecorationRole);

                    // Hinzufügen zum aktuellen Ordner
                    aktuellerOrdner->appendRow(newDirectory);

                    // NeuerOrdner wird zum aktuellen Ordner
                    aktuellerOrdner = newDirectory;
                }
            }

            // Löschen aller eingelesener Daten
            url.clear();
            name.clear();
            size = 0;
            time.clear();
        }

        // Einlesen der Elementeigenschaften
        else if (Reader.isCharacters() && !Reader.isWhitespace())
        {
            // URL
            if(currentXmlTag == "href" && url.isEmpty())
                url.setUrl(QString::fromUtf8(Reader.text().toString().toLatin1()));

            // Name
            else if (currentXmlTag == "displayname")
                name = QString::fromUtf8(Reader.text().toString().toLatin1());

            // Größe
            else if (currentXmlTag == "getcontentlength")
                size = Reader.text().toString().toInt();

            // Modifizierungsdatum
            else if (currentXmlTag == "getlastmodified")
                time = QString::fromUtf8(Reader.text().toString().toLatin1());
        }
    }

    // Leere Ordner wieder rausschmeißen.
    Structureelement* rootCourse = replies->value(reply);
    for (int i = 0; i < rootCourse->rowCount(); i++)
    {
        Structureelement *item = (Structureelement *)rootCourse->child(i);
        if (item->type() == directoryItem && item->rowCount() == 0)
        {
            rootCourse->removeRow(i);
        }
    }
    // Sortieren aller Dateien
    replies->value(reply)->sortChildren(0, Qt::AscendingOrder);
}
Example #13
0
bool ThumbnailProtocol::createSubThumbnail(QImage& thumbnail, const QString& filePath,
                                           int segmentWidth, int segmentHeight)
{
    if (m_enabledPlugins.isEmpty()) {
        const KConfigGroup globalConfig(KSharedConfig::openConfig(), "PreviewSettings");
        m_enabledPlugins = globalConfig.readEntry("Plugins", QStringList()
                                                             << "imagethumbnail"
                                                             << "jpegthumbnail"
                                                             << "videopreview");
    }

    const QMimeDatabase db;
    const QUrl fileUrl = QUrl::fromLocalFile(filePath);
    const QString subPlugin = pluginForMimeType(db.mimeTypeForUrl(fileUrl).name());
    if (subPlugin.isEmpty() || !m_enabledPlugins.contains(subPlugin)) {
        return false;
    }

    ThumbCreator* subCreator = getThumbCreator(subPlugin);
    if (!subCreator) {
        // qDebug() << "found no creator for" << dir.filePath();
        return false;
    }

    if ((segmentWidth <= 256) && (segmentHeight <= 256)) {
        // check whether a cached version of the file is available for
        // 128 x 128 or 256 x 256 pixels
        int cacheSize = 0;
        QCryptographicHash md5(QCryptographicHash::Md5);
        md5.addData(QFile::encodeName(fileUrl.toString()));
        const QString thumbName = QFile::encodeName(md5.result().toHex()).append(".png");

        if (m_thumbBasePath.isEmpty()) {
            m_thumbBasePath = QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation) + QLatin1String("/thumbnails/");
            QDir basePath(m_thumbBasePath);
            basePath.mkpath("normal/");
            QFile::setPermissions(basePath.absoluteFilePath("normal"), QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner);
            basePath.mkpath("large/");
            QFile::setPermissions(basePath.absoluteFilePath("large"), QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner);
        }

        QDir thumbPath(m_thumbBasePath);
        if ((segmentWidth <= 128) && (segmentHeight <= 128)) {
            cacheSize = 128;
            thumbPath.cd("normal");
        } else {
            cacheSize = 256;
            thumbPath.cd("large");
        }
        if (!thumbnail.load(thumbPath.absoluteFilePath(thumbName))) {
            // no cached version is available, a new thumbnail must be created

            QSaveFile thumbnailfile(thumbPath.absoluteFilePath(thumbName));
            bool savedCorrectly = false;
            if (subCreator->create(filePath, cacheSize, cacheSize, thumbnail)) {
                scaleDownImage(thumbnail, cacheSize, cacheSize);

                // The thumbnail has been created successfully. Store the thumbnail
                // to the cache for future access.
                if (thumbnailfile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
                    savedCorrectly = thumbnail.save(&thumbnailfile, "PNG");
                }
            } else {
                return false;
            }
            if(savedCorrectly)
            {
                thumbnailfile.commit();
            }
        }
    } else if (!subCreator->create(filePath, segmentWidth, segmentHeight, thumbnail)) {
        return false;
    }
    return true;
}
Example #14
0
void QNetworkAccessFileBackend::open()
{
    QUrl url = this->url();

    if (url.host() == QLatin1String("localhost"))
        url.setHost(QString());
#if !defined(Q_OS_WIN)
    // do not allow UNC paths on Unix
    if (!url.host().isEmpty()) {
        // we handle only local files
        error(QNetworkReply::ProtocolInvalidOperationError,
              QCoreApplication::translate("QNetworkAccessFileBackend", "Request for opening non-local file %1").arg(url.toString()));
        finished();
        return;
    }
#endif // !defined(Q_OS_WIN)
    if (url.path().isEmpty())
        url.setPath(QLatin1String("/"));
    setUrl(url);

    QString fileName = url.toLocalFile();
    if (fileName.isEmpty()) {
        if (url.scheme() == QLatin1String("qrc"))
            fileName = QLatin1Char(':') + url.path();
        else
            fileName = url.toString(QUrl::RemoveAuthority | QUrl::RemoveFragment | QUrl::RemoveQuery);
    }
    file.setFileName(fileName);

    if (operation() == QNetworkAccessManager::GetOperation) {
        if (!loadFileInfo())
            return;
    }

    QIODevice::OpenMode mode;
    switch (operation()) {
    case QNetworkAccessManager::GetOperation:
        mode = QIODevice::ReadOnly;
        break;
    case QNetworkAccessManager::PutOperation:
        mode = QIODevice::WriteOnly | QIODevice::Truncate;
        uploadByteDevice = createUploadByteDevice();
        QObject::connect(uploadByteDevice, SIGNAL(readyRead()), this, SLOT(uploadReadyReadSlot()));
        QMetaObject::invokeMethod(this, "uploadReadyReadSlot", Qt::QueuedConnection);
        break;
    default:
        Q_ASSERT_X(false, "QNetworkAccessFileBackend::open",
                   "Got a request operation I cannot handle!!");
        return;
    }

    mode |= QIODevice::Unbuffered;
    bool opened = file.open(mode);

    // could we open the file?
    if (!opened) {
        QString msg = QCoreApplication::translate("QNetworkAccessFileBackend", "Error opening %1: %2")
                                                .arg(this->url().toString(), file.errorString());

        // why couldn't we open the file?
        // if we're opening for reading, either it doesn't exist, or it's access denied
        // if we're opening for writing, not existing means it's access denied too
        if (file.exists() || operation() == QNetworkAccessManager::PutOperation)
            error(QNetworkReply::ContentAccessDenied, msg);
        else
            error(QNetworkReply::ContentNotFoundError, msg);
        finished();
    }
}
void OwncloudSetupWizard::slotNoOwnCloudFoundAuthTimeout(const QUrl&url)
{
    _ocWizard->displayError(tr("Timeout while trying to connect to %1 at %2.")
                            .arg(Theme::instance()->appNameGUI(),
                                 url.toString()), false);
}
Example #16
0
void Agent::run() {
    ThreadedAssignment::commonInit(AGENT_LOGGING_NAME, NodeType::Agent);
    
    NodeList* nodeList = NodeList::getInstance();
    nodeList->addSetOfNodeTypesToNodeInterestSet(NodeSet()
                                                 << NodeType::AudioMixer
                                                 << NodeType::AvatarMixer
                                                 << NodeType::VoxelServer
                                                 << NodeType::ParticleServer
                                                 << NodeType::ModelServer
                                                );
    
    // figure out the URL for the script for this agent assignment
    QUrl scriptURL;
    if (_payload.isEmpty())  {
        scriptURL = QUrl(QString("http://%1:%2/assignment/%3")
            .arg(NodeList::getInstance()->getDomainHandler().getIP().toString())
            .arg(DOMAIN_SERVER_HTTP_PORT)
            .arg(uuidStringWithoutCurlyBraces(_uuid)));
    } else {
        scriptURL = QUrl(_payload);
    }
   
    NetworkAccessManager& networkAccessManager = NetworkAccessManager::getInstance();
    QNetworkReply *reply = networkAccessManager.get(QNetworkRequest(scriptURL));
    
    QNetworkDiskCache* cache = new QNetworkDiskCache();
    QString cachePath = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
    cache->setCacheDirectory(!cachePath.isEmpty() ? cachePath : "agentCache");
    networkAccessManager.setCache(cache);
    
    qDebug() << "Downloading script at" << scriptURL.toString();
    
    QEventLoop loop;
    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    
    loop.exec();
    
    QString scriptContents(reply->readAll());
    
    qDebug() << "Downloaded script:" << scriptContents;
    
    // setup an Avatar for the script to use
    ScriptableAvatar scriptedAvatar(&_scriptEngine);
    scriptedAvatar.setForceFaceshiftConnected(true);

    // call model URL setters with empty URLs so our avatar, if user, will have the default models
    scriptedAvatar.setFaceModelURL(QUrl());
    scriptedAvatar.setSkeletonModelURL(QUrl());
    
    // give this AvatarData object to the script engine
    _scriptEngine.setAvatarData(&scriptedAvatar, "Avatar");
    _scriptEngine.setAvatarHashMap(&_avatarHashMap, "AvatarList");
    
    // register ourselves to the script engine
    _scriptEngine.registerGlobalObject("Agent", this);

    _scriptEngine.init(); // must be done before we set up the viewers

    _scriptEngine.registerGlobalObject("VoxelViewer", &_voxelViewer);
    // connect the VoxelViewer and the VoxelScriptingInterface to each other
    JurisdictionListener* voxelJL = _scriptEngine.getVoxelsScriptingInterface()->getJurisdictionListener();
    _voxelViewer.setJurisdictionListener(voxelJL);
    _voxelViewer.init();
    _scriptEngine.getVoxelsScriptingInterface()->setVoxelTree(_voxelViewer.getTree());
    
    _scriptEngine.registerGlobalObject("ParticleViewer", &_particleViewer);
    JurisdictionListener* particleJL = _scriptEngine.getParticlesScriptingInterface()->getJurisdictionListener();
    _particleViewer.setJurisdictionListener(particleJL);
    _particleViewer.init();
    _scriptEngine.getParticlesScriptingInterface()->setParticleTree(_particleViewer.getTree());

    _scriptEngine.registerGlobalObject("ModelViewer", &_modelViewer);
    JurisdictionListener* modelJL = _scriptEngine.getModelsScriptingInterface()->getJurisdictionListener();
    _modelViewer.setJurisdictionListener(modelJL);
    _modelViewer.init();
    _scriptEngine.getModelsScriptingInterface()->setModelTree(_modelViewer.getTree());

    _scriptEngine.setScriptContents(scriptContents);
    _scriptEngine.run();
    setFinished(true);
}
    void httpFinished() {
        DEBUG("httpFinished()");
        QVariant redirectionTarget = qreply->attribute(QNetworkRequest::RedirectionTargetAttribute);
        if (!redirectionTarget.isNull())
        {
            QUrl newUrl = url.resolved(redirectionTarget.toUrl());
            DEBUG("Handled redirect to: " << newUrl.toString());
            qreply->deleteLater();
            qreply = nullptr;
            doOperation(newUrl);
            return;
        }
        else if (qreply->error())
        {
            WARN("HTTP ERROR:" << qreply->error() << qreply->errorString());

            httpStatus = HTTPInvocationDefinition::UNDEFINED;
            invocationStatus = Invocation::ERROR;
            result << InvocationErrors::CONNECTION_FAILED
                   << Result::Meta("qnetworkreply_error_string", qreply->errorString())
                   << Result::Meta("qnetworkreply_error_number", qreply->error());

            QNetworkReply::NetworkError err = qreply->error();
            result << NetworkErrorReasons::from(err, qreply->errorString());

            // get possible return data
            replyData = qreply->readAll();
            if (!replyData.isEmpty())
                result << Result::Meta("response_data", replyData);

            emit q->finishedError(q);
        }
        else
        {
            // we have data
            replyData = qreply->readAll();
            QVariant statusCode = qreply->attribute( QNetworkRequest::HttpStatusCodeAttribute );
            if (statusCode.isValid())
            {
                // TODO: handle more codes!
                switch (statusCode.toInt())
                {
                case 200:
                    httpStatus = HTTPInvocationDefinition::OK_200;
                    break;
                default:
                    httpStatus = HTTPInvocationDefinition::UNDEFINED;
                }
            } else {
                result << InvocationErrors::INVOCATION_FAILED
                       << Result::reasonFromDesc("Invalid http status code");
            }

            invocationStatus = Invocation::RESPONSE_RECEIVED;
            TRACE("DATA:" << replyData);
            emit q->finishedOK(q);
        }

        qreply->deleteLater();
        qreply = nullptr;
    }
Example #18
0
void MainWindow::updateLocation(const QUrl& url)
{
    locationEdit->setText(url.toString());
    setWindowTitle(view->title());
}
Example #19
0
Menu::Menu() {
    auto dialogsManager = DependencyManager::get<DialogsManager>();
    auto accountManager = DependencyManager::get<AccountManager>();

    // File/Application menu ----------------------------------
    MenuWrapper* fileMenu = addMenu("File");

    // File > Login menu items
    {
        addActionToQMenuAndActionHash(fileMenu, MenuOption::Login);

        // connect to the appropriate signal of the AccountManager so that we can change the Login/Logout menu item
        connect(accountManager.data(), &AccountManager::profileChanged,
                dialogsManager.data(), &DialogsManager::toggleLoginDialog);
        connect(accountManager.data(), &AccountManager::logoutComplete,
                dialogsManager.data(), &DialogsManager::toggleLoginDialog);
    }

    // File > Quit
    addActionToQMenuAndActionHash(fileMenu, MenuOption::Quit, Qt::CTRL | Qt::Key_Q, qApp, SLOT(quit()), QAction::QuitRole);


    // Edit menu ----------------------------------
    MenuWrapper* editMenu = addMenu("Edit");

    // Edit > Cut
    auto cutAction = addActionToQMenuAndActionHash(editMenu, "Cut", QKeySequence::Cut);
    connect(cutAction, &QAction::triggered, [] {
            QKeyEvent* keyEvent = new QKeyEvent(QEvent::KeyPress, Qt::Key_X, Qt::ControlModifier);
            QCoreApplication::postEvent(QCoreApplication::instance(), keyEvent);
    });

    // Edit > Copy
    auto copyAction = addActionToQMenuAndActionHash(editMenu, "Copy", QKeySequence::Copy);
    connect(copyAction, &QAction::triggered, [] {
            QKeyEvent* keyEvent = new QKeyEvent(QEvent::KeyPress, Qt::Key_C, Qt::ControlModifier);
            QCoreApplication::postEvent(QCoreApplication::instance(), keyEvent);
    });

    // Edit > Paste
    auto pasteAction = addActionToQMenuAndActionHash(editMenu, "Paste", QKeySequence::Paste);
    connect(pasteAction, &QAction::triggered, [] {
            QKeyEvent* keyEvent = new QKeyEvent(QEvent::KeyPress, Qt::Key_V, Qt::ControlModifier);
            QCoreApplication::postEvent(QCoreApplication::instance(), keyEvent);
    });

    // Edit > Delete
    auto deleteAction = addActionToQMenuAndActionHash(editMenu, "Delete", QKeySequence::Delete);
    connect(deleteAction, &QAction::triggered, [] {
            QKeyEvent* keyEvent = new QKeyEvent(QEvent::KeyPress, Qt::Key_Delete, Qt::ControlModifier);
            QCoreApplication::postEvent(QCoreApplication::instance(), keyEvent);
    });

    editMenu->addSeparator();

    // Edit > Running Scripts
    auto action = addActionToQMenuAndActionHash(editMenu, MenuOption::RunningScripts, Qt::CTRL | Qt::Key_J);
    connect(action, &QAction::triggered, [] {
        if (!qApp->getLoginDialogPoppedUp()) {
            static const QUrl widgetUrl("hifi/dialogs/RunningScripts.qml");
            static const QUrl tabletUrl("hifi/dialogs/TabletRunningScripts.qml");
            static const QString name("RunningScripts");
            qApp->showDialog(widgetUrl, tabletUrl, name);
        }
    });

    editMenu->addSeparator();

    // Edit > Asset Browser
    auto assetServerAction = addActionToQMenuAndActionHash(editMenu, MenuOption::AssetServer,
                                                           Qt::CTRL | Qt::SHIFT | Qt::Key_A,
                                                           qApp, SLOT(showAssetServerWidget()));
    {
        auto nodeList = DependencyManager::get<NodeList>();
        QObject::connect(nodeList.data(), &NodeList::canWriteAssetsChanged, assetServerAction, &QAction::setEnabled);
        assetServerAction->setEnabled(nodeList->getThisNodeCanWriteAssets());
    }

    // Edit > Avatar Packager
#ifndef Q_OS_ANDROID
    action = addActionToQMenuAndActionHash(editMenu, MenuOption::AvatarPackager);
    connect(action, &QAction::triggered, [] {
        DependencyManager::get<AvatarPackager>()->open();
    });
#endif

    // Edit > Reload All Content
    addActionToQMenuAndActionHash(editMenu, MenuOption::ReloadContent, 0, qApp, SLOT(reloadResourceCaches()));

    // Display menu ----------------------------------
    // FIXME - this is not yet matching Alan's spec because it doesn't have
    // menus for "2D"/"3D" - we need to add support for detecting the appropriate
    // default 3D display mode
    addMenu(DisplayPlugin::MENU_PATH());
    MenuWrapper* displayModeMenu = addMenu(MenuOption::OutputMenu);
    QActionGroup* displayModeGroup = new QActionGroup(displayModeMenu);
    displayModeGroup->setExclusive(true);


    // View menu ----------------------------------
    MenuWrapper* viewMenu = addMenu("View");
    QActionGroup* cameraModeGroup = new QActionGroup(viewMenu);

    // View > [camera group]
    cameraModeGroup->setExclusive(true);

    // View > First Person
    auto firstPersonAction = cameraModeGroup->addAction(addCheckableActionToQMenuAndActionHash(
                                   viewMenu, MenuOption::FirstPerson, 0,
                                   true, qApp, SLOT(cameraMenuChanged())));

    firstPersonAction->setProperty(EXCLUSION_GROUP_KEY, QVariant::fromValue(cameraModeGroup));

    // View > Third Person
    auto thirdPersonAction = cameraModeGroup->addAction(addCheckableActionToQMenuAndActionHash(
                                   viewMenu, MenuOption::ThirdPerson, 0,
                                   false, qApp, SLOT(cameraMenuChanged())));

    thirdPersonAction->setProperty(EXCLUSION_GROUP_KEY, QVariant::fromValue(cameraModeGroup));

    // View > Mirror
    auto viewMirrorAction = cameraModeGroup->addAction(addCheckableActionToQMenuAndActionHash(
                                   viewMenu, MenuOption::FullscreenMirror, 0,
                                   false, qApp, SLOT(cameraMenuChanged())));

    viewMirrorAction->setProperty(EXCLUSION_GROUP_KEY, QVariant::fromValue(cameraModeGroup));

    // View > Independent
    auto viewIndependentAction = cameraModeGroup->addAction(addCheckableActionToQMenuAndActionHash(viewMenu,
        MenuOption::IndependentMode, 0,
        false, qApp, SLOT(cameraMenuChanged())));

    viewIndependentAction->setProperty(EXCLUSION_GROUP_KEY, QVariant::fromValue(cameraModeGroup));

    // View > Entity Camera
    auto viewEntityCameraAction = cameraModeGroup->addAction(addCheckableActionToQMenuAndActionHash(viewMenu,
        MenuOption::CameraEntityMode, 0,
        false, qApp, SLOT(cameraMenuChanged())));

    viewEntityCameraAction->setProperty(EXCLUSION_GROUP_KEY, QVariant::fromValue(cameraModeGroup));

    viewMenu->addSeparator();

    // View > Center Player In View
    addCheckableActionToQMenuAndActionHash(viewMenu, MenuOption::CenterPlayerInView,
        0, true, qApp, SLOT(rotationModeChanged()));

    // View > Enter First Person Mode in HMD
    addCheckableActionToQMenuAndActionHash(viewMenu, MenuOption::FirstPersonHMD, 0, true);

    //TODO: Remove Navigation menu when these functions are included in GoTo menu
    // Navigate menu ----------------------------------
    MenuWrapper* navigateMenu = addMenu("Navigate");

    // Navigate > LocationBookmarks related menus -- Note: the LocationBookmarks class adds its own submenus here.
    auto locationBookmarks = DependencyManager::get<LocationBookmarks>();
    locationBookmarks->setupMenus(this, navigateMenu);

    // Navigate > Copy Address
    auto addressManager = DependencyManager::get<AddressManager>();
    addActionToQMenuAndActionHash(navigateMenu, MenuOption::CopyAddress, 0,
        addressManager.data(), SLOT(copyAddress()));

    // Navigate > Copy Path
    addActionToQMenuAndActionHash(navigateMenu, MenuOption::CopyPath, 0,
        addressManager.data(), SLOT(copyPath()));

    // Navigate > Start-up Location
    MenuWrapper* startupLocationMenu = navigateMenu->addMenu(MenuOption::StartUpLocation);
    QActionGroup* startupLocatiopnGroup = new QActionGroup(startupLocationMenu);
    startupLocatiopnGroup->setExclusive(true);
    startupLocatiopnGroup->addAction(addCheckableActionToQMenuAndActionHash(startupLocationMenu, MenuOption::HomeLocation, 0, 
        false));
    startupLocatiopnGroup->addAction(addCheckableActionToQMenuAndActionHash(startupLocationMenu, MenuOption::LastLocation, 0, 
        true));

    // Settings menu ----------------------------------
    MenuWrapper* settingsMenu = addMenu("Settings");

    // Settings > General...
    action = addActionToQMenuAndActionHash(settingsMenu, MenuOption::Preferences, Qt::CTRL | Qt::Key_G, nullptr, nullptr);
    connect(action, &QAction::triggered, [] {
        if (!qApp->getLoginDialogPoppedUp()) {
            qApp->showDialog(QString("hifi/dialogs/GeneralPreferencesDialog.qml"),
                QString("hifi/tablet/TabletGeneralPreferences.qml"), "GeneralPreferencesDialog");
        }
    });

    // Settings > Controls...
    action = addActionToQMenuAndActionHash(settingsMenu, "Controls...");
    connect(action, &QAction::triggered, [] {
            auto tablet = DependencyManager::get<TabletScriptingInterface>()->getTablet("com.highfidelity.interface.tablet.system");
            auto hmd = DependencyManager::get<HMDScriptingInterface>();
            tablet->pushOntoStack("hifi/tablet/ControllerSettings.qml");

            if (!hmd->getShouldShowTablet()) {
                hmd->toggleShouldShowTablet();
            }
    });

    // Settings > Audio...
    action = addActionToQMenuAndActionHash(settingsMenu, "Audio...");
    connect(action, &QAction::triggered, [] {
        static const QUrl tabletUrl("hifi/audio/Audio.qml");
        auto tablet = DependencyManager::get<TabletScriptingInterface>()->getTablet("com.highfidelity.interface.tablet.system");
        auto hmd = DependencyManager::get<HMDScriptingInterface>();
        tablet->pushOntoStack(tabletUrl);

        if (!hmd->getShouldShowTablet()) {
            hmd->toggleShouldShowTablet();
        }
    });

    // Settings > Graphics...
    action = addActionToQMenuAndActionHash(settingsMenu, "Graphics...");
    connect(action, &QAction::triggered, [] {
        qApp->showDialog(QString("hifi/dialogs/GraphicsPreferencesDialog.qml"),
            QString("hifi/tablet/TabletGraphicsPreferences.qml"), "GraphicsPreferencesDialog");
    });

    // Settings > Security...
    action = addActionToQMenuAndActionHash(settingsMenu, "Security...");
    connect(action, &QAction::triggered, [] {
		auto tablet = DependencyManager::get<TabletScriptingInterface>()->getTablet("com.highfidelity.interface.tablet.system");
		auto hmd = DependencyManager::get<HMDScriptingInterface>();
		tablet->pushOntoStack("hifi/dialogs/security/Security.qml");

		if (!hmd->getShouldShowTablet()) {
			hmd->toggleShouldShowTablet();
		}
    });

    // Settings > Developer Menu
    addCheckableActionToQMenuAndActionHash(settingsMenu, "Developer Menu", 0, false, this, SLOT(toggleDeveloperMenus()));

    // Settings > Ask to Reset Settings
    addCheckableActionToQMenuAndActionHash(settingsMenu, MenuOption::AskToResetSettings, 0, false);

    // Developer menu ----------------------------------
    MenuWrapper* developerMenu = addMenu("Developer", "Developer");
    
    // Developer > Scripting >>>
    MenuWrapper* scriptingOptionsMenu = developerMenu->addMenu("Scripting");
    
    // Developer > Scripting > Console...
    addActionToQMenuAndActionHash(scriptingOptionsMenu, MenuOption::Console, Qt::CTRL | Qt::ALT | Qt::Key_J,
                                  DependencyManager::get<StandAloneJSConsole>().data(),
                                  SLOT(toggleConsole()),
                                  QAction::NoRole,
                                  UNSPECIFIED_POSITION);

     // Developer > Scripting > API Debugger
    action = addActionToQMenuAndActionHash(scriptingOptionsMenu, "API Debugger");
    connect(action, &QAction::triggered, [] {
        QUrl defaultScriptsLoc = PathUtils::defaultScriptsLocation();
        defaultScriptsLoc.setPath(defaultScriptsLoc.path() + "developer/utilities/tools/currentAPI.js");
        DependencyManager::get<ScriptEngines>()->loadScript(defaultScriptsLoc.toString());
    });
    
    // Developer > Scripting > Entity Script Server Log
    auto essLogAction = addActionToQMenuAndActionHash(scriptingOptionsMenu, MenuOption::EntityScriptServerLog, 0,
                                                      qApp, SLOT(toggleEntityScriptServerLogDialog()));
    {
        auto nodeList = DependencyManager::get<NodeList>();
        QObject::connect(nodeList.data(), &NodeList::canRezChanged, essLogAction, [essLogAction] {
            auto nodeList = DependencyManager::get<NodeList>();
            essLogAction->setEnabled(nodeList->getThisNodeCanRez());
        });
        essLogAction->setEnabled(nodeList->getThisNodeCanRez());
    }

    // Developer > Scripting > Script Log (HMD friendly)...
    addActionToQMenuAndActionHash(scriptingOptionsMenu, "Script Log (HMD friendly)...", Qt::NoButton,
                                           qApp, SLOT(showScriptLogs()));

    // Developer > Scripting > Verbose Logging
    addCheckableActionToQMenuAndActionHash(scriptingOptionsMenu, MenuOption::VerboseLogging, 0, false,
                                           qApp, SLOT(updateVerboseLogging()));
    
    // Developer > Scripting > Enable Speech Control API
#if defined(Q_OS_MAC) || defined(Q_OS_WIN)
    auto speechRecognizer = DependencyManager::get<SpeechRecognizer>();
    QAction* speechRecognizerAction = addCheckableActionToQMenuAndActionHash(scriptingOptionsMenu, MenuOption::ControlWithSpeech,
        Qt::CTRL | Qt::SHIFT | Qt::Key_C,
        speechRecognizer->getEnabled(),
        speechRecognizer.data(),
        SLOT(setEnabled(bool)),
        UNSPECIFIED_POSITION);
    connect(speechRecognizer.data(), SIGNAL(enabledUpdated(bool)), speechRecognizerAction, SLOT(setChecked(bool)));
#endif
    
    // Developer > UI >>>
    MenuWrapper* uiOptionsMenu = developerMenu->addMenu("UI");
    action = addCheckableActionToQMenuAndActionHash(uiOptionsMenu, MenuOption::DesktopTabletToToolbar, 0,
                                                    qApp->getDesktopTabletBecomesToolbarSetting());
    
    // Developer > UI > Show Overlays
    addCheckableActionToQMenuAndActionHash(uiOptionsMenu, MenuOption::Overlays, 0, true);
    
    // Developer > UI > Desktop Tablet Becomes Toolbar
    connect(action, &QAction::triggered, [action] {
        qApp->setDesktopTabletBecomesToolbarSetting(action->isChecked());
    });
    
     // Developer > UI > HMD Tablet Becomes Toolbar
    action = addCheckableActionToQMenuAndActionHash(uiOptionsMenu, MenuOption::HMDTabletToToolbar, 0,
                                                    qApp->getHmdTabletBecomesToolbarSetting());
    connect(action, &QAction::triggered, [action] {
        qApp->setHmdTabletBecomesToolbarSetting(action->isChecked());
    });

    // Developer > Render >>>
    MenuWrapper* renderOptionsMenu = developerMenu->addMenu("Render");

    action = addCheckableActionToQMenuAndActionHash(renderOptionsMenu, MenuOption::AntiAliasing, 0, true);
    connect(action, &QAction::triggered, [action] {
        auto renderConfig = qApp->getRenderEngine()->getConfiguration();
        if (renderConfig) {
            auto mainViewJitterCamConfig = renderConfig->getConfig<JitterSample>("RenderMainView.JitterCam");
            auto mainViewAntialiasingConfig = renderConfig->getConfig<Antialiasing>("RenderMainView.Antialiasing");
            if (mainViewJitterCamConfig && mainViewAntialiasingConfig) {
                if (action->isChecked()) {
                    mainViewJitterCamConfig->play();
                    mainViewAntialiasingConfig->setDebugFXAA(false);
                } else {
                    mainViewJitterCamConfig->none();
                    mainViewAntialiasingConfig->setDebugFXAA(true);
                }
            }
        }
    });

    action = addCheckableActionToQMenuAndActionHash(renderOptionsMenu, MenuOption::Shadows, 0, true);
    connect(action, &QAction::triggered, [action] {
        auto renderConfig = qApp->getRenderEngine()->getConfiguration();
        if (renderConfig) {
            auto lightingModelConfig = renderConfig->getConfig<MakeLightingModel>("RenderMainView.LightingModel");
            if (lightingModelConfig) {
                lightingModelConfig->setShadow(action->isChecked());
            }
        }
    });

    action = addCheckableActionToQMenuAndActionHash(renderOptionsMenu, MenuOption::AmbientOcclusion, 0, false);
    connect(action, &QAction::triggered, [action] {
        auto renderConfig = qApp->getRenderEngine()->getConfiguration();
        if (renderConfig) {
            auto lightingModelConfig = renderConfig->getConfig<MakeLightingModel>("RenderMainView.LightingModel");
            if (lightingModelConfig) {
                lightingModelConfig->setAmbientOcclusion(action->isChecked());
            }
         }
    });

    addCheckableActionToQMenuAndActionHash(renderOptionsMenu, MenuOption::WorldAxes);
    addCheckableActionToQMenuAndActionHash(renderOptionsMenu, MenuOption::DefaultSkybox, 0, true);

    // Developer > Render > Throttle FPS If Not Focus
    addCheckableActionToQMenuAndActionHash(renderOptionsMenu, MenuOption::ThrottleFPSIfNotFocus, 0, true);

    // Developer > Render > OpenVR threaded submit
    addCheckableActionToQMenuAndActionHash(renderOptionsMenu, MenuOption::OpenVrThreadedSubmit, 0, true);

    // Developer > Render > Resolution
    MenuWrapper* resolutionMenu = renderOptionsMenu->addMenu(MenuOption::RenderResolution);
    QActionGroup* resolutionGroup = new QActionGroup(resolutionMenu);
    resolutionGroup->setExclusive(true);
    resolutionGroup->addAction(addCheckableActionToQMenuAndActionHash(resolutionMenu, MenuOption::RenderResolutionOne, 0, true));
    resolutionGroup->addAction(addCheckableActionToQMenuAndActionHash(resolutionMenu, MenuOption::RenderResolutionTwoThird, 0, false));
    resolutionGroup->addAction(addCheckableActionToQMenuAndActionHash(resolutionMenu, MenuOption::RenderResolutionHalf, 0, false));
    resolutionGroup->addAction(addCheckableActionToQMenuAndActionHash(resolutionMenu, MenuOption::RenderResolutionThird, 0, false));
    resolutionGroup->addAction(addCheckableActionToQMenuAndActionHash(resolutionMenu, MenuOption::RenderResolutionQuarter, 0, false));

    //const QString  = "Automatic Texture Memory";
    //const QString  = "64 MB";
    //const QString  = "256 MB";
    //const QString  = "512 MB";
    //const QString  = "1024 MB";
    //const QString  = "2048 MB";

    // Developer > Render > Maximum Texture Memory
    MenuWrapper* textureMenu = renderOptionsMenu->addMenu(MenuOption::RenderMaxTextureMemory);
    QActionGroup* textureGroup = new QActionGroup(textureMenu);
    textureGroup->setExclusive(true);
    textureGroup->addAction(addCheckableActionToQMenuAndActionHash(textureMenu, MenuOption::RenderMaxTextureAutomatic, 0, true));
    textureGroup->addAction(addCheckableActionToQMenuAndActionHash(textureMenu, MenuOption::RenderMaxTexture4MB, 0, false));
    textureGroup->addAction(addCheckableActionToQMenuAndActionHash(textureMenu, MenuOption::RenderMaxTexture64MB, 0, false));
    textureGroup->addAction(addCheckableActionToQMenuAndActionHash(textureMenu, MenuOption::RenderMaxTexture256MB, 0, false));
    textureGroup->addAction(addCheckableActionToQMenuAndActionHash(textureMenu, MenuOption::RenderMaxTexture512MB, 0, false));
    textureGroup->addAction(addCheckableActionToQMenuAndActionHash(textureMenu, MenuOption::RenderMaxTexture1024MB, 0, false));
    textureGroup->addAction(addCheckableActionToQMenuAndActionHash(textureMenu, MenuOption::RenderMaxTexture2048MB, 0, false));
    textureGroup->addAction(addCheckableActionToQMenuAndActionHash(textureMenu, MenuOption::RenderMaxTexture4096MB, 0, false));
    textureGroup->addAction(addCheckableActionToQMenuAndActionHash(textureMenu, MenuOption::RenderMaxTexture6144MB, 0, false));
    textureGroup->addAction(addCheckableActionToQMenuAndActionHash(textureMenu, MenuOption::RenderMaxTexture8192MB, 0, false));
    connect(textureGroup, &QActionGroup::triggered, [textureGroup] {
        auto checked = textureGroup->checkedAction();
        auto text = checked->text();
        gpu::Context::Size newMaxTextureMemory { 0 };
        if (MenuOption::RenderMaxTexture4MB == text) {
            newMaxTextureMemory = MB_TO_BYTES(4);
        } else if (MenuOption::RenderMaxTexture64MB == text) {
            newMaxTextureMemory = MB_TO_BYTES(64);
        } else if (MenuOption::RenderMaxTexture256MB == text) {
            newMaxTextureMemory = MB_TO_BYTES(256);
        } else if (MenuOption::RenderMaxTexture512MB == text) {
            newMaxTextureMemory = MB_TO_BYTES(512);
        } else if (MenuOption::RenderMaxTexture1024MB == text) {
            newMaxTextureMemory = MB_TO_BYTES(1024);
        } else if (MenuOption::RenderMaxTexture2048MB == text) {
            newMaxTextureMemory = MB_TO_BYTES(2048);
        } else if (MenuOption::RenderMaxTexture4096MB == text) {
            newMaxTextureMemory = MB_TO_BYTES(4096);
        } else if (MenuOption::RenderMaxTexture6144MB == text) {
            newMaxTextureMemory = MB_TO_BYTES(6144);
        } else if (MenuOption::RenderMaxTexture8192MB == text) {
            newMaxTextureMemory = MB_TO_BYTES(8192);
        }
        gpu::Texture::setAllowedGPUMemoryUsage(newMaxTextureMemory);
    });

#ifdef Q_OS_WIN
    // Developer > Render > Enable Sparse Textures
    {
        auto action = addCheckableActionToQMenuAndActionHash(renderOptionsMenu, MenuOption::SparseTextureManagement, 0, gpu::Texture::getEnableSparseTextures());
        connect(action, &QAction::triggered, [&](bool checked) {
            qDebug() << "[TEXTURE TRANSFER SUPPORT] --- Enable Dynamic Texture Management menu option:" << checked;
            gpu::Texture::setEnableSparseTextures(checked);
        });
    }

#else
    qDebug() << "[TEXTURE TRANSFER SUPPORT] Incremental Texture Transfer and Dynamic Texture Management not supported on this platform.";
#endif


    {
        auto action = addActionToQMenuAndActionHash(renderOptionsMenu, MenuOption::RenderClearKtxCache);
        connect(action, &QAction::triggered, []{
            Setting::Handle<int>(KTXCache::SETTING_VERSION_NAME, KTXCache::INVALID_VERSION).set(KTXCache::INVALID_VERSION);
        });
    }

    // Developer > Render > LOD Tools
    addActionToQMenuAndActionHash(renderOptionsMenu, MenuOption::LodTools, 0,
                                  qApp, SLOT(loadLODToolsDialog()));

    // HACK enable texture decimation
    {
        auto action = addCheckableActionToQMenuAndActionHash(renderOptionsMenu, "Decimate Textures");
        connect(action, &QAction::triggered, [&](bool checked) {
            DEV_DECIMATE_TEXTURES = checked;
        });
    }

    addCheckableActionToQMenuAndActionHash(renderOptionsMenu, MenuOption::ComputeBlendshapes, 0, true,
        DependencyManager::get<ModelBlender>().data(), SLOT(setComputeBlendshapes(bool)));

    // Developer > Assets >>>
    // Menu item is not currently needed but code should be kept in case it proves useful again at some stage.
//#define WANT_ASSET_MIGRATION
#ifdef WANT_ASSET_MIGRATION
    MenuWrapper* assetDeveloperMenu = developerMenu->addMenu("Assets");
    auto& atpMigrator = ATPAssetMigrator::getInstance();
    atpMigrator.setDialogParent(this);

    addActionToQMenuAndActionHash(assetDeveloperMenu, MenuOption::AssetMigration,
        0, &atpMigrator,
        SLOT(loadEntityServerFile()));
#endif

    // Developer > Avatar >>>
    MenuWrapper* avatarDebugMenu = developerMenu->addMenu("Avatar");

    // Developer > Avatar > Face Tracking
    MenuWrapper* faceTrackingMenu = avatarDebugMenu->addMenu("Face Tracking");
    {
        QActionGroup* faceTrackerGroup = new QActionGroup(avatarDebugMenu);

        bool defaultNoFaceTracking = true;
#ifdef HAVE_DDE
        defaultNoFaceTracking = false;
#endif
        QAction* noFaceTracker = addCheckableActionToQMenuAndActionHash(faceTrackingMenu, MenuOption::NoFaceTracking,
            0, defaultNoFaceTracking,
            qApp, SLOT(setActiveFaceTracker()));
        faceTrackerGroup->addAction(noFaceTracker);

#ifdef HAVE_DDE
        QAction* ddeFaceTracker = addCheckableActionToQMenuAndActionHash(faceTrackingMenu, MenuOption::UseCamera,
            0, true,
            qApp, SLOT(setActiveFaceTracker()));
        faceTrackerGroup->addAction(ddeFaceTracker);
#endif
    }
#ifdef HAVE_DDE
    faceTrackingMenu->addSeparator();
    QAction* binaryEyelidControl = addCheckableActionToQMenuAndActionHash(faceTrackingMenu, MenuOption::BinaryEyelidControl, 0, true);
    binaryEyelidControl->setVisible(true);  // DDE face tracking is on by default
    QAction* coupleEyelids = addCheckableActionToQMenuAndActionHash(faceTrackingMenu, MenuOption::CoupleEyelids, 0, true);
    coupleEyelids->setVisible(true);  // DDE face tracking is on by default
    QAction* useAudioForMouth = addCheckableActionToQMenuAndActionHash(faceTrackingMenu, MenuOption::UseAudioForMouth, 0, true);
    useAudioForMouth->setVisible(true);  // DDE face tracking is on by default
    QAction* ddeFiltering = addCheckableActionToQMenuAndActionHash(faceTrackingMenu, MenuOption::VelocityFilter, 0, true);
    ddeFiltering->setVisible(true);  // DDE face tracking is on by default
    QAction* ddeCalibrate = addActionToQMenuAndActionHash(faceTrackingMenu, MenuOption::CalibrateCamera, 0,
        DependencyManager::get<DdeFaceTracker>().data(), SLOT(calibrate()));
    ddeCalibrate->setVisible(true);  // DDE face tracking is on by default
    faceTrackingMenu->addSeparator();
    addCheckableActionToQMenuAndActionHash(faceTrackingMenu, MenuOption::MuteFaceTracking,
        [](bool mute) { FaceTracker::setIsMuted(mute); },
        Qt::CTRL | Qt::SHIFT | Qt::Key_F, FaceTracker::isMuted());
    addCheckableActionToQMenuAndActionHash(faceTrackingMenu, MenuOption::AutoMuteAudio, 0, false);
#endif

#ifdef HAVE_IVIEWHMD
    // Developer > Avatar > Eye Tracking
    MenuWrapper* eyeTrackingMenu = avatarDebugMenu->addMenu("Eye Tracking");
    addCheckableActionToQMenuAndActionHash(eyeTrackingMenu, MenuOption::SMIEyeTracking, 0, false,
        qApp, SLOT(setActiveEyeTracker()));
    {
        MenuWrapper* calibrateEyeTrackingMenu = eyeTrackingMenu->addMenu("Calibrate");
        addActionToQMenuAndActionHash(calibrateEyeTrackingMenu, MenuOption::OnePointCalibration, 0,
            qApp, SLOT(calibrateEyeTracker1Point()));
        addActionToQMenuAndActionHash(calibrateEyeTrackingMenu, MenuOption::ThreePointCalibration, 0,
            qApp, SLOT(calibrateEyeTracker3Points()));
        addActionToQMenuAndActionHash(calibrateEyeTrackingMenu, MenuOption::FivePointCalibration, 0,
            qApp, SLOT(calibrateEyeTracker5Points()));
    }
    addCheckableActionToQMenuAndActionHash(eyeTrackingMenu, MenuOption::SimulateEyeTracking, 0, false,
        qApp, SLOT(setActiveEyeTracker()));
#endif

    action = addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::AvatarReceiveStats, 0, false);
    connect(action, &QAction::triggered, [this]{ Avatar::setShowReceiveStats(isOptionChecked(MenuOption::AvatarReceiveStats)); });
    action = addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::ShowBoundingCollisionShapes, 0, false);
    connect(action, &QAction::triggered, [this]{ Avatar::setShowCollisionShapes(isOptionChecked(MenuOption::ShowBoundingCollisionShapes)); });
    action = addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::ShowMyLookAtVectors, 0, false);
    connect(action, &QAction::triggered, [this]{ Avatar::setShowMyLookAtVectors(isOptionChecked(MenuOption::ShowMyLookAtVectors)); });
    action = addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::ShowOtherLookAtVectors, 0, false);
    connect(action, &QAction::triggered, [this]{ Avatar::setShowOtherLookAtVectors(isOptionChecked(MenuOption::ShowOtherLookAtVectors)); });

    auto avatarManager = DependencyManager::get<AvatarManager>();
    auto avatar = avatarManager->getMyAvatar();

    action = addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::EnableLookAtSnapping, 0, true);
    connect(action, &QAction::triggered, [this, avatar]{
            avatar->setProperty("lookAtSnappingEnabled", isOptionChecked(MenuOption::EnableLookAtSnapping));
        });

    addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::FixGaze, 0, false);
    addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::ToggleHipsFollowing, 0, false,
        avatar.get(), SLOT(setToggleHips(bool)));
    addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::AnimDebugDrawBaseOfSupport, 0, false,
        avatar.get(), SLOT(setEnableDebugDrawBaseOfSupport(bool)));
    addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::AnimDebugDrawDefaultPose, 0, false,
        avatar.get(), SLOT(setEnableDebugDrawDefaultPose(bool)));
    addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::AnimDebugDrawAnimPose, 0, false,
        avatar.get(), SLOT(setEnableDebugDrawAnimPose(bool)));
    addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::AnimDebugDrawPosition, 0, false,
        avatar.get(), SLOT(setEnableDebugDrawPosition(bool)));
    addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::MeshVisible, 0, true,
        avatar.get(), SLOT(setEnableMeshVisible(bool)));
    addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::DisableEyelidAdjustment, 0, false);
    addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::TurnWithHead, 0, false);
    addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::EnableInverseKinematics, 0, true,
        avatar.get(), SLOT(setEnableInverseKinematics(bool)));
    addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::RenderSensorToWorldMatrix, 0, false,
        avatar.get(), SLOT(setEnableDebugDrawSensorToWorldMatrix(bool)));
    addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::RenderIKTargets, 0, false,
        avatar.get(), SLOT(setEnableDebugDrawIKTargets(bool)));
    addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::RenderIKConstraints, 0, false,
        avatar.get(), SLOT(setEnableDebugDrawIKConstraints(bool)));
    addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::RenderIKChains, 0, false,
        avatar.get(), SLOT(setEnableDebugDrawIKChains(bool)));
    addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::RenderDetailedCollision, 0, false,
        avatar.get(), SLOT(setEnableDebugDrawDetailedCollision(bool)));

    addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::ActionMotorControl, 0, true,
        avatar.get(), SLOT(updateMotionBehaviorFromMenu()),
        UNSPECIFIED_POSITION, "Developer");

    addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::ScriptedMotorControl, 0, true,
        avatar.get(), SLOT(updateMotionBehaviorFromMenu()),
        UNSPECIFIED_POSITION, "Developer");

    addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::ShowTrackedObjects, 0, false, qApp, SLOT(setShowTrackedObjects(bool)));

    addActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::PackageModel, 0, qApp, SLOT(packageModel()));

    // Developer > Hands >>>
    MenuWrapper* handOptionsMenu = developerMenu->addMenu("Hands");
    addCheckableActionToQMenuAndActionHash(handOptionsMenu, MenuOption::DisplayHandTargets, 0, false,
        avatar.get(), SLOT(setEnableDebugDrawHandControllers(bool)));

    // Developer > Entities >>>
    MenuWrapper* entitiesOptionsMenu = developerMenu->addMenu("Entities");

    addActionToQMenuAndActionHash(entitiesOptionsMenu, MenuOption::OctreeStats, 0,
        qApp, SLOT(loadEntityStatisticsDialog()));

    addCheckableActionToQMenuAndActionHash(entitiesOptionsMenu, MenuOption::ShowRealtimeEntityStats);

    // Developer > Network >>>
    MenuWrapper* networkMenu = developerMenu->addMenu("Network");
    action = addActionToQMenuAndActionHash(networkMenu, MenuOption::Networking);
    connect(action, &QAction::triggered, [] {
        qApp->showDialog(QString("hifi/dialogs/NetworkingPreferencesDialog.qml"),
            QString("hifi/tablet/TabletNetworkingPreferences.qml"), "NetworkingPreferencesDialog");
    });
    addActionToQMenuAndActionHash(networkMenu, MenuOption::ReloadContent, 0, qApp, SLOT(reloadResourceCaches()));
    addActionToQMenuAndActionHash(networkMenu, MenuOption::ClearDiskCache, 0,
        DependencyManager::get<AssetClient>().data(), SLOT(clearCache()));
    addCheckableActionToQMenuAndActionHash(networkMenu,
        MenuOption::DisableActivityLogger,
        0,
        false,
        &UserActivityLogger::getInstance(),
        SLOT(disable(bool)));
    addActionToQMenuAndActionHash(networkMenu, MenuOption::ShowDSConnectTable, 0,
        qApp, SLOT(loadDomainConnectionDialog()));

    #if (PR_BUILD || DEV_BUILD)
    addCheckableActionToQMenuAndActionHash(networkMenu, MenuOption::SendWrongProtocolVersion, 0, false,
                qApp, SLOT(sendWrongProtocolVersionsSignature(bool)));

    {
        auto nodeList = DependencyManager::get<NodeList>();
        addCheckableActionToQMenuAndActionHash(networkMenu, MenuOption::SendWrongDSConnectVersion, 0, false,
            nodeList.data(), SLOT(toggleSendNewerDSConnectVersion(bool)));
    }
    #endif


    // Developer >> Tests >>>
    MenuWrapper* testMenu = developerMenu->addMenu("Tests");
    addActionToQMenuAndActionHash(testMenu, MenuOption::RunClientScriptTests, 0, dialogsManager.data(), SLOT(showTestingResults()));

    // Developer > Timing >>>
    MenuWrapper* timingMenu = developerMenu->addMenu("Timing");
    MenuWrapper* perfTimerMenu = timingMenu->addMenu("Performance Timer");
    addCheckableActionToQMenuAndActionHash(perfTimerMenu, MenuOption::DisplayDebugTimingDetails, 0, false,
            qApp, SLOT(enablePerfStats(bool)));
    addCheckableActionToQMenuAndActionHash(perfTimerMenu, MenuOption::OnlyDisplayTopTen, 0, true);
    addCheckableActionToQMenuAndActionHash(perfTimerMenu, MenuOption::ExpandUpdateTiming, 0, false);
    addCheckableActionToQMenuAndActionHash(perfTimerMenu, MenuOption::ExpandSimulationTiming, 0, false);
    addCheckableActionToQMenuAndActionHash(perfTimerMenu, MenuOption::ExpandPhysicsTiming, 0, false);
    addCheckableActionToQMenuAndActionHash(perfTimerMenu, MenuOption::ExpandMyAvatarTiming, 0, false);
    addCheckableActionToQMenuAndActionHash(perfTimerMenu, MenuOption::ExpandMyAvatarSimulateTiming, 0, false);
    addCheckableActionToQMenuAndActionHash(perfTimerMenu, MenuOption::ExpandOtherAvatarTiming, 0, false);
    addCheckableActionToQMenuAndActionHash(perfTimerMenu, MenuOption::ExpandPaintGLTiming, 0, false);

    addCheckableActionToQMenuAndActionHash(timingMenu, MenuOption::FrameTimer);
    addActionToQMenuAndActionHash(timingMenu, MenuOption::RunTimingTests, 0, qApp, SLOT(runTests()));
    addCheckableActionToQMenuAndActionHash(timingMenu, MenuOption::PipelineWarnings);
    addCheckableActionToQMenuAndActionHash(timingMenu, MenuOption::LogExtraTimings);
    addCheckableActionToQMenuAndActionHash(timingMenu, MenuOption::SuppressShortTimings);


    // Developer > Audio >>>
    MenuWrapper* audioDebugMenu = developerMenu->addMenu("Audio");

    action = addActionToQMenuAndActionHash(audioDebugMenu, "Stats...");
    connect(action, &QAction::triggered, [] {
        QUrl defaultScriptsLoc = PathUtils::defaultScriptsLocation();
        defaultScriptsLoc.setPath(defaultScriptsLoc.path() + "developer/utilities/audio/stats.js");
        DependencyManager::get<ScriptEngines>()->loadScript(defaultScriptsLoc.toString());
    });

    action = addActionToQMenuAndActionHash(audioDebugMenu, "Buffers...");
    connect(action, &QAction::triggered, [] {
        qApp->showDialog(QString("hifi/dialogs/AudioBuffers.qml"),
            QString("hifi/tablet/TabletAudioBuffers.qml"), "AudioBuffersDialog");
    });

    addActionToQMenuAndActionHash(audioDebugMenu, MenuOption::MuteEnvironment, 0,
        DependencyManager::get<AudioClient>().data(), SLOT(sendMuteEnvironmentPacket()));

    action = addActionToQMenuAndActionHash(audioDebugMenu, MenuOption::AudioScope);
    connect(action, &QAction::triggered, [] {
        QUrl defaultScriptsLoc = PathUtils::defaultScriptsLocation();
        defaultScriptsLoc.setPath(defaultScriptsLoc.path() + "developer/utilities/audio/audioScope.js");
        DependencyManager::get<ScriptEngines>()->loadScript(defaultScriptsLoc.toString());
    });

    // Developer > Physics >>>
    MenuWrapper* physicsOptionsMenu = developerMenu->addMenu("Physics");
    {
        auto drawStatusConfig = qApp->getRenderEngine()->getConfiguration()->getConfig<render::DrawStatus>("RenderMainView.DrawStatus");
        addCheckableActionToQMenuAndActionHash(physicsOptionsMenu, MenuOption::PhysicsShowOwned,
            0, false, drawStatusConfig, SLOT(setShowNetwork(bool)));
    }

    addCheckableActionToQMenuAndActionHash(physicsOptionsMenu, MenuOption::PhysicsShowBulletWireframe, 0, false, qApp, SLOT(setShowBulletWireframe(bool)));
    addCheckableActionToQMenuAndActionHash(physicsOptionsMenu, MenuOption::PhysicsShowBulletAABBs, 0, false, qApp, SLOT(setShowBulletAABBs(bool)));
    addCheckableActionToQMenuAndActionHash(physicsOptionsMenu, MenuOption::PhysicsShowBulletContactPoints, 0, false, qApp, SLOT(setShowBulletContactPoints(bool)));
    addCheckableActionToQMenuAndActionHash(physicsOptionsMenu, MenuOption::PhysicsShowBulletConstraints, 0, false, qApp, SLOT(setShowBulletConstraints(bool)));
    addCheckableActionToQMenuAndActionHash(physicsOptionsMenu, MenuOption::PhysicsShowBulletConstraintLimits, 0, false, qApp, SLOT(setShowBulletConstraintLimits(bool)));

    // Developer > Picking >>>
    MenuWrapper* pickingOptionsMenu = developerMenu->addMenu("Picking");
    addCheckableActionToQMenuAndActionHash(pickingOptionsMenu, MenuOption::ForceCoarsePicking, 0, false,
        DependencyManager::get<PickManager>().data(), SLOT(setForceCoarsePicking(bool)));

    // Developer > Crash >>>
    MenuWrapper* crashMenu = developerMenu->addMenu("Crash");
    
    // Developer > Crash > Display Crash Options
    addCheckableActionToQMenuAndActionHash(crashMenu, MenuOption::DisplayCrashOptions, 0, true);

    addActionToQMenuAndActionHash(crashMenu, MenuOption::DeadlockInterface, 0, qApp, SLOT(deadlockApplication()));
    addActionToQMenuAndActionHash(crashMenu, MenuOption::UnresponsiveInterface, 0, qApp, SLOT(unresponsiveApplication()));

    action = addActionToQMenuAndActionHash(crashMenu, MenuOption::CrashPureVirtualFunction);
    connect(action, &QAction::triggered, qApp, []() { crash::pureVirtualCall(); });
    action = addActionToQMenuAndActionHash(crashMenu, MenuOption::CrashPureVirtualFunctionThreaded);
    connect(action, &QAction::triggered, qApp, []() { std::thread(crash::pureVirtualCall).join(); });

    action = addActionToQMenuAndActionHash(crashMenu, MenuOption::CrashDoubleFree);
    connect(action, &QAction::triggered, qApp, []() { crash::doubleFree(); });
    action = addActionToQMenuAndActionHash(crashMenu, MenuOption::CrashDoubleFreeThreaded);
    connect(action, &QAction::triggered, qApp, []() { std::thread(crash::doubleFree).join(); });

    action = addActionToQMenuAndActionHash(crashMenu, MenuOption::CrashAbort);
    connect(action, &QAction::triggered, qApp, []() { crash::doAbort(); });
    action = addActionToQMenuAndActionHash(crashMenu, MenuOption::CrashAbortThreaded);
    connect(action, &QAction::triggered, qApp, []() { std::thread(crash::doAbort).join(); });

    action = addActionToQMenuAndActionHash(crashMenu, MenuOption::CrashNullDereference);
    connect(action, &QAction::triggered, qApp, []() { crash::nullDeref(); });
    action = addActionToQMenuAndActionHash(crashMenu, MenuOption::CrashNullDereferenceThreaded);
    connect(action, &QAction::triggered, qApp, []() { std::thread(crash::nullDeref).join(); });

    action = addActionToQMenuAndActionHash(crashMenu, MenuOption::CrashOutOfBoundsVectorAccess);
    connect(action, &QAction::triggered, qApp, []() { crash::outOfBoundsVectorCrash(); });
    action = addActionToQMenuAndActionHash(crashMenu, MenuOption::CrashOutOfBoundsVectorAccessThreaded);
    connect(action, &QAction::triggered, qApp, []() { std::thread(crash::outOfBoundsVectorCrash).join(); });

    action = addActionToQMenuAndActionHash(crashMenu, MenuOption::CrashNewFault);
    connect(action, &QAction::triggered, qApp, []() { crash::newFault(); });
    action = addActionToQMenuAndActionHash(crashMenu, MenuOption::CrashNewFaultThreaded);
    connect(action, &QAction::triggered, qApp, []() { std::thread(crash::newFault).join(); });

    // Developer > Show Statistics
    addCheckableActionToQMenuAndActionHash(developerMenu, MenuOption::Stats, 0, true);

    // Developer > Show Animation Statistics
    addCheckableActionToQMenuAndActionHash(developerMenu, MenuOption::AnimStats);

    // Developer > Log
    addActionToQMenuAndActionHash(developerMenu, MenuOption::Log, Qt::CTRL | Qt::SHIFT | Qt::Key_L,
                                  qApp, SLOT(toggleLogDialog()));

#if 0 ///  -------------- REMOVED FOR NOW --------------
    addDisabledActionAndSeparator(navigateMenu, "History");
    QAction* backAction = addActionToQMenuAndActionHash(navigateMenu, MenuOption::Back, 0, addressManager.data(), SLOT(goBack()));
    QAction* forwardAction = addActionToQMenuAndActionHash(navigateMenu, MenuOption::Forward, 0, addressManager.data(), SLOT(goForward()));

    // connect to the AddressManager signal to enable and disable the back and forward menu items
    connect(addressManager.data(), &AddressManager::goBackPossible, backAction, &QAction::setEnabled);
    connect(addressManager.data(), &AddressManager::goForwardPossible, forwardAction, &QAction::setEnabled);

    // set the two actions to start disabled since the stacks are clear on startup
    backAction->setDisabled(true);
    forwardAction->setDisabled(true);

    MenuWrapper* toolsMenu = addMenu("Tools");
    addActionToQMenuAndActionHash(toolsMenu,
                                  MenuOption::ToolWindow,
                                  Qt::CTRL | Qt::ALT | Qt::Key_T,
                                  dialogsManager.data(),
                                  SLOT(toggleToolWindow()),
                                  QAction::NoRole, UNSPECIFIED_POSITION, "Advanced");


    addCheckableActionToQMenuAndActionHash(avatarMenu, MenuOption::NamesAboveHeads, 0, true,
                NULL, NULL, UNSPECIFIED_POSITION, "Advanced");
#endif

    // Help/Application menu ----------------------------------
    MenuWrapper * helpMenu = addMenu("Help");

    // Help > About High Fidelity
    action = addActionToQMenuAndActionHash(helpMenu, "About High Fidelity");
    connect(action, &QAction::triggered, [] {
        qApp->showDialog(QString("hifi/dialogs/AboutDialog.qml"),
            QString("hifi/dialogs/TabletAboutDialog.qml"), "AboutDialog");
    });
    helpMenu->addSeparator();

    // Help > HiFi Docs
    action = addActionToQMenuAndActionHash(helpMenu, "Online Documentation");
    connect(action, &QAction::triggered, qApp, [] {
        QDesktopServices::openUrl(QUrl("https://docs.highfidelity.com/"));
    });

    // Help > HiFi Forum
    action = addActionToQMenuAndActionHash(helpMenu, "Online Forums");
    connect(action, &QAction::triggered, qApp, [] {
        QDesktopServices::openUrl(QUrl("https://forums.highfidelity.com/"));
    });

    // Help > Scripting Reference
    action = addActionToQMenuAndActionHash(helpMenu, "Online Script Reference");
    connect(action, &QAction::triggered, qApp, [] {
        QDesktopServices::openUrl(QUrl("https://docs.highfidelity.com/api-reference"));
    });

    addActionToQMenuAndActionHash(helpMenu, "Controls Reference", 0, qApp, SLOT(showHelp()));

    helpMenu->addSeparator();

    // Help > Release Notes
    action = addActionToQMenuAndActionHash(helpMenu, "Release Notes");
    connect(action, &QAction::triggered, qApp, [] {
        QDesktopServices::openUrl(QUrl("http://steamcommunity.com/games/390540/announcements/"));
    });

    // Help > Report a Bug!
    action = addActionToQMenuAndActionHash(helpMenu, "Report a Bug!");
    connect(action, &QAction::triggered, qApp, [] {
        QDesktopServices::openUrl(QUrl("mailto:[email protected]"));
    });
}
Example #20
0
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" );
        cmd.replace( "+", "%20" ); // QUrl doesn't parse '+' into " "
        tLog() << "Parsing tomahawk link command" << cmd;

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

        // for backwards compatibility
        if ( cmdType == "load" )
        {
            if ( urlHasQueryItem( u, "xspf" ) )
            {
                QUrl xspf = QUrl::fromUserInput( urlQueryItemValue( u, "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 ( urlHasQueryItem( u, "jspf" ) )
            {
                QUrl jspf = QUrl::fromUserInput( urlQueryItemValue( u, "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 if ( cmdType == "import" )
        {
            return handleImportCommand( u );
        }
        else
        {
            tLog() << "Tomahawk link not supported, command not known!" << cmdType << u.path();
            return false;
        }
    }
    else
    {
        tLog() << "Not a tomahawk:// link!";
        return false;
    }
}
Example #21
0
bool FileServerHandler::HandleAnnounce(MythSocket *socket,
                  QStringList &commands, QStringList &slist)
{
    if (commands[1] == "FileServer")
    {
        if (slist.size() >= 3)
        {
            SocketHandler *handler =
                new SocketHandler(socket, m_parent, commands[2]);

            handler->BlockShutdown(true);
            handler->AllowStandardEvents(true);
            handler->AllowSystemEvents(true);

            QWriteLocker wlock(&m_fsLock);
            m_fsMap.insert(commands[2], handler);
            m_parent->AddSocketHandler(handler);

            slist.clear();
            slist << "OK";
            handler->SendStringList(slist);
            return true;
        }
        return false;
    }

    if (commands[1] != "FileTransfer")
        return false;

    if (slist.size() < 3)
        return false;

    if ((commands.size() < 3) || (commands.size() > 6))
        return false;

    FileTransfer *ft    = NULL;
    QString hostname    = "";
    QString filename    = "";
    bool writemode      = false;
    bool usereadahead   = true;
    int timeout_ms      = 2000;
    switch (commands.size())
    {
      case 6:
        timeout_ms      = commands[5].toInt();
      case 5:
        usereadahead    = commands[4].toInt();
      case 4:
        writemode       = commands[3].toInt();
      default:
        hostname        = commands[2];
    }

    QStringList::const_iterator it = slist.begin();
    QUrl qurl           = *(++it);
    QString wantgroup   = *(++it);

    QStringList checkfiles;
    while (++it != slist.end())
        checkfiles += *(it);

    slist.clear();

    LOG(VB_GENERAL, LOG_DEBUG, "FileServerHandler::HandleAnnounce");
    LOG(VB_GENERAL, LOG_INFO, QString("adding: %1 as remote file transfer")
                            .arg(hostname));

    if (writemode)
    {
        if (wantgroup.isEmpty())
            wantgroup = "Default";

        StorageGroup sgroup(wantgroup, gCoreContext->GetHostName(), false);
        QString dir = sgroup.FindNextDirMostFree();
        if (dir.isEmpty())
        {
            LOG(VB_GENERAL, LOG_ERR, "Unable to determine directory "
                    "to write to in FileTransfer write command");

            slist << "ERROR" << "filetransfer_directory_not_found";
            socket->writeStringList(slist);
            return true;
        }

        QString basename = qurl.path();
        if (basename.isEmpty())
        {
            LOG(VB_GENERAL, LOG_ERR, QString("FileTransfer write "
                    "filename is empty in url '%1'.")
                    .arg(qurl.toString()));

            slist << "ERROR" << "filetransfer_filename_empty";
            socket->writeStringList(slist);
            return true;
        }

        if ((basename.contains("/../")) ||
            (basename.startsWith("../")))
        {
            LOG(VB_GENERAL, LOG_ERR, QString("FileTransfer write "
                    "filename '%1' does not pass sanity checks.")
                    .arg(basename));

            slist << "ERROR" << "filetransfer_filename_dangerous";
            socket->writeStringList(slist);
            return true;
        }

        filename = dir + "/" + basename;
    }
    else
        filename = LocalFilePath(qurl, wantgroup);

    QFileInfo finfo(filename);
    if (finfo.isDir())
    {
        LOG(VB_GENERAL, LOG_ERR, QString("FileTransfer filename "
                "'%1' is actually a directory, cannot transfer.")
                .arg(filename));

        slist << "ERROR" << "filetransfer_filename_is_a_directory";
        socket->writeStringList(slist);
        return true;
    }

    if (writemode)
    {
        QString dirPath = finfo.absolutePath();
        QDir qdir(dirPath);
        if (!qdir.exists())
        {
            if (!qdir.mkpath(dirPath))
            {
                LOG(VB_GENERAL, LOG_ERR, QString("FileTransfer "
                        "filename '%1' is in a subdirectory which does "
                        "not exist, but can not be created.")
                        .arg(filename));

                slist << "ERROR" << "filetransfer_unable_to_create_subdirectory";
                socket->writeStringList(slist);
                return true;
            }
        }

        ft = new FileTransfer(filename, socket, m_parent, writemode);
    }
    else
        ft = new FileTransfer(filename, socket, m_parent, usereadahead, timeout_ms);

    ft->BlockShutdown(true);

    {
        QWriteLocker wlock(&m_ftLock);
        m_ftMap.insert(socket->socket(), ft);
    }

    slist << "OK"
          << QString::number(socket->socket())
          << QString::number(ft->GetFileSize());

    if (checkfiles.size())
    {
        QFileInfo fi(filename);
        QDir dir = fi.absoluteDir();
        for (it = checkfiles.begin(); it != checkfiles.end(); ++it)
        {
            if (dir.exists(*it) &&
                QFileInfo(dir, *it).size() >= kReadTestSize)
                    slist << *it;
        }
    }

    socket->writeStringList(slist);
    m_parent->AddSocketHandler(ft);
    return true;
}
Example #22
0
bool SoundCloud::urlSupported(const QUrl &url) const {
    return this->urlPattern().indexIn(url.toString()) == 0;
}
Example #23
0
void
SocialWidget::onShortLinkReady( const QUrl& longUrl, const QUrl& shortUrl, const QVariant& callbackObj )
{
    Q_UNUSED( longUrl );
    Q_UNUSED( callbackObj );

    if ( m_query->album().isEmpty() )
        ui->textEdit->setText( tr( "Listening to \"%1\" by %2. %3" ).arg( m_query->track() ).arg( m_query->artist() ).arg( shortUrl.toString() ) );
    else
        ui->textEdit->setText( tr( "Listening to \"%1\" by %2 on \"%3\". %4" ).arg( m_query->track() ).arg( m_query->artist() ).arg( m_query->album() ).arg( shortUrl.toString() ) );
}
Example #24
0
LookConfig::LookConfig(Settings &st) : ConfigWidget(st) {
	setupUi(this);

#ifndef Q_OS_MAC
	if (! QSystemTrayIcon::isSystemTrayAvailable())
#endif
		qgbTray->hide();

	qcbLanguage->addItem(tr("System default"));
	QDir d(QLatin1String(":"),QLatin1String("mumble_*.qm"),QDir::Name,QDir::Files);
	foreach(const QString &key, d.entryList()) {
		QString cc = key.mid(7,key.indexOf(QLatin1Char('.'))-7);
		QLocale tmpLocale = QLocale(cc);

		//If there is no native language name, use the locale
		QString displayName = cc;
		if(!tmpLocale.nativeLanguageName().isEmpty()) {
			displayName = QString(QLatin1String("%1 (%2)"))
			        .arg(tmpLocale.nativeLanguageName())
			        .arg(cc);
		} else if (cc == QLatin1String("eo")){
			// Can't initialize QLocale for a countryless language (QTBUG-8452, QTBUG-14592).
			// We only have one so special case it.
			displayName = QLatin1String("Esperanto (eo)");
		}
		
		qcbLanguage->addItem(displayName, QVariant(cc));
	}

	qcbExpand->addItem(tr("None"), Settings::NoChannels);
	qcbExpand->addItem(tr("Only with users"), Settings::ChannelsWithUsers);
	qcbExpand->addItem(tr("All"), Settings::AllChannels);

	qcbChannelDrag->insertItem(Settings::Ask, tr("Ask"), Settings::Ask);
	qcbChannelDrag->insertItem(Settings::DoNothing, tr("Do Nothing"), Settings::DoNothing);
	qcbChannelDrag->insertItem(Settings::Move, tr("Move"), Settings::Move);
	
	qcbUserDrag->insertItem(Settings::Ask, tr("Ask"), Settings::Ask);
	qcbUserDrag->insertItem(Settings::DoNothing, tr("Do Nothing"), Settings::DoNothing);
	qcbUserDrag->insertItem(Settings::Move, tr("Move"), Settings::Move);

	connect(qrbLCustom,SIGNAL(toggled(bool)),qcbLockLayout,SLOT(setEnabled(bool)));
	
	QDir userThemeDirectory = Themes::getUserThemesDirectory();
	if (userThemeDirectory.exists()) {
		m_themeDirectoryWatcher = new QFileSystemWatcher(this);
		
		// Use a timer to cut down floods of directory changes. We only want
		// to trigger a refresh after nothing has happened for 200ms in the
		// watched directory.
		m_themeDirectoryDebouncer = new QTimer(this);
		m_themeDirectoryDebouncer->setSingleShot(true);
		m_themeDirectoryDebouncer->setInterval(200);
		m_themeDirectoryDebouncer->connect(m_themeDirectoryWatcher, SIGNAL(directoryChanged(QString)), SLOT(start()));
		
		connect(m_themeDirectoryDebouncer, SIGNAL(timeout()), SLOT(themeDirectoryChanged()));
		m_themeDirectoryWatcher->addPath(userThemeDirectory.path());
		
		QUrl userThemeDirectoryUrl = QUrl::fromLocalFile(userThemeDirectory.path());
		//: This link is located next to the theme heading in the ui config and opens the user theme directory
		qlThemesDirectory->setText(tr("<a href=\"%1\">Browse</a>").arg(userThemeDirectoryUrl.toString()));
		qlThemesDirectory->setOpenExternalLinks(true);
	}
	
}
Example #25
0
void Page::parse()
{
    m_source = m_reply->readAll();

	// Check redirection
	QUrl redir = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
	if (!redir.isEmpty())
	{
		m_url = m_site->fixUrl(redir.toString(), m_url);
		load();
		return;
	}

	// Reading reply and resetting vars
	qDeleteAll(m_images);
	m_images.clear();
	m_tags.clear();
	/*m_imagesCount = -1;
	m_pagesCount = -1;*/

	if (m_source.isEmpty())
	{
		if (m_reply->error() != QNetworkReply::OperationCanceledError)
		{
			log("Loading error: "+m_reply->errorString());
			fallback();
		}
		return;
	}

	int first = m_smart ? ((m_page - 1) * m_imagesPerPage) % m_blim : 0;

	// XML
	if (m_format == "xml")
	{
		// Initializations
		QDomDocument doc;
		QString errorMsg;
		int errorLine, errorColumn;
		if (!doc.setContent(m_source, false, &errorMsg, &errorLine, &errorColumn))
		{
			log(tr("Erreur lors de l'analyse du fichier XML : %1 (%2 - %3).").arg(errorMsg, QString::number(errorLine), QString::number(errorColumn)));
			fallback();
			return;
		}
		QDomElement docElem = doc.documentElement();

		// Getting last page
		int count = docElem.attributes().namedItem("count").nodeValue().toFloat();
		QString database = docElem.attributes().namedItem("type").nodeValue();
		if (count == 0 && database == "array")
		{ count = docElem.elementsByTagName("total-count").at(0).toElement().text().toInt(); }
		if (count > 0)
		{ m_imagesCount = count; }

		// Reading posts
		QDomNodeList nodeList = docElem.elementsByTagName("post");
		if (nodeList.count() > 0)
		{
			for (int id = 0; id < nodeList.count(); id++)
			{
				QMap<QString,QString> d;
				if (database == "array")
				{
					QStringList infos, assoc;
					infos << "created_at" << "status" << "source" << "has_comments" << "file_url" << "sample_url" << "change" << "sample_width" << "has_children" << "preview_url" << "width" << "md5" << "preview_width" << "sample_height" << "parent_id" << "height" << "has_notes" << "creator_id" << "file_size" << "id" << "preview_height" << "rating" << "tags" << "author" << "score" << "tags_artist" << "tags_character" << "tags_copyright" << "tags_general" << "ext";
					assoc << "created-at" << "status" << "source" << "has_comments" << "file-url" << "large-file-url" << "change" << "sample_width" << "has-children" << "preview-file-url" << "image-width" << "md5" << "preview_width" << "sample_height" << "parent-id" << "image-height" << "has_notes" << "uploader-id" << "file_size" << "id" << "preview_height" << "rating" << "tag-string" << "uploader-name" << "score" << "tag-string-artist" << "tag-string-character" << "tag-string-copyright" << "tag-string-general" << "file-ext";
					for (int i = 0; i < infos.count(); i++)
					{ d[infos.at(i)] = nodeList.at(id + first).namedItem(assoc.at(i)).toElement().text(); }
				}
				else
				{
					QStringList infos;
					infos << "created_at" << "status" << "source" << "has_comments" << "file_url" << "sample_url" << "change" << "sample_width" << "has_children" << "preview_url" << "width" << "md5" << "preview_width" << "sample_height" << "parent_id" << "height" << "has_notes" << "creator_id" << "file_size" << "id" << "preview_height" << "rating" << "tags" << "author" << "score";
					for (int i = 0; i < infos.count(); i++)
					{ d[infos.at(i)] = nodeList.at(id + first).attributes().namedItem(infos.at(i)).nodeValue().trimmed(); }
				}
				this->parseImage(d, id + first);
			}
		}
	}

	// RSS
	else if (m_format == "rss")
	{
		// Initializations
		QDomDocument doc;
		QString errorMsg;
		int errorLine, errorColumn;
		if (!doc.setContent(m_source, false, &errorMsg, &errorLine, &errorColumn))
		{
			log(tr("Erreur lors de l'analyse du fichier RSS : %1 (%2 - %3).").arg(errorMsg, QString::number(errorLine), QString::number(errorColumn)));
			fallback();
			return;
		}
		QDomElement docElem = doc.documentElement();

		// Reading posts
		QDomNodeList nodeList = docElem.elementsByTagName("item");
		if (nodeList.count() > 0)
		{
			for (int id = 0; id < nodeList.count(); id++)
			{
				QDomNodeList children = nodeList.at(id + first).childNodes();
				QMap<QString,QString> d, dat;
				for (int i = 0; i < children.size(); i++)
				{
					QString content = children.at(i).childNodes().at(0).nodeValue();
					if (!content.isEmpty())
					{ dat.insert(children.at(i).nodeName(), content.trimmed()); }
					else
					{ dat.insert(children.at(i).nodeName(), children.at(i).attributes().namedItem("url").nodeValue().trimmed()); }
				}
				// QDateTime::fromString(date, "ddd, dd MMM yyyy hh:mm:ss +0000"); // shimmie date format
				d.insert("page_url", dat["link"]);
				d.insert("tags", dat["media:keywords"]);
				d.insert("preview_url", dat["media:thumbnail"]);
				d.insert("sample_url", dat["media:content"]);
				d.insert("file_url", dat["media:content"]);
				if (!d.contains("id"))
				{
					QRegExp rx("/(\\d+)");
					rx.indexIn(d["page_url"]);
					d.insert("id", rx.cap(1));
				}
				this->parseImage(d, id + first);
			}
		}
	}

	// Regexes
	else if (m_format == "regex")
	{
		// Getting tags
		if (m_site->contains("Regex/Tags"))
		{
			QRegExp rxtags(m_site->value("Regex/Tags"));
			rxtags.setMinimal(true);
			QStringList tags = QStringList();
			int p = 0;
			while (((p = rxtags.indexIn(m_source, p)) != -1))
			{
				if (!tags.contains(rxtags.cap(2)))
				{
					m_tags.append(Tag(rxtags.cap(2), rxtags.cap(1), rxtags.cap(3).toInt()));
					tags.append(rxtags.cap(2));
				}
				p += rxtags.matchedLength();
			}
		}

		// Getting images
		QRegExp rx(m_site->value("Regex/Image"));
		QStringList order = m_site->value("Regex/Order").split('|');
		rx.setMinimal(true);
		int pos = 0, id = 0;
		while ((pos = rx.indexIn(m_source, pos)) != -1)
        {
			pos += rx.matchedLength();
			QMap<QString,QString> d;
			for (int i = 0; i < order.size(); i++)
			{ d[order.at(i)] = rx.cap(i+1); }

			// JSON elements
			if (order.contains("json") && !d["json"].isEmpty())
			{
				QVariant src = Json::parse(d["json"]);
				if (!src.isNull())
				{
					QMap<QString,QVariant> map = src.toMap();
					for (int i = 0; i < map.size(); i++)
					{ d[map.keys().at(i)] = map.values().at(i).toString(); }
				}
			}
			this->parseImage(d, id + first);
			id++;
		}
	}

	// JSON
	else if (m_format == "json")
	{
		QVariant src = Json::parse(m_source);
		if (!src.isNull())
		{
			QMap<QString, QVariant> sc;
			QList<QVariant> sourc = src.toList();
			if (sourc.isEmpty())
			{ sourc = src.toMap().value("images").toList(); }
			for (int id = 0; id < sourc.count(); id++)
			{
				sc = sourc.at(id + first).toMap();
				QMap<QString,QString> d;
				if (sc.contains("tag_string"))
				{
					QStringList infos, assoc;
					infos << "created_at" << "status" << "source" << "has_comments" << "file_url" << "sample_url" << "change" << "sample_width" << "has_children" << "preview_url" << "width" << "md5" << "preview_width" << "sample_height" << "parent_id" << "height" << "has_notes" << "creator_id" << "file_size" << "id" << "preview_height" << "rating" << "tags" << "author" << "score" << "tags_artist" << "tags_character" << "tags_copyright" << "tags_general";
					assoc << "created_at" << "status" << "source" << "has_comments" << "file_url" << "large_file_url" << "change" << "sample_width" << "has_children" << "preview_file_url" << "image_width" << "md5" << "preview_width" << "sample_height" << "parent_id" << "image_height" << "has_notes" << "uploader_id" << "file_size" << "id" << "preview_height" << "rating" << "tag_string" << "uploader_name" << "score" << "tag_string_artist" << "tag_string_character" << "tag_string_copyright" << "tag_string_general";
					for (int i = 0; i < infos.count(); i++)
					{ d[infos.at(i)] = sc.value(assoc.at(i)).toString().trimmed(); }
				}
				else if (sc.contains("tag_ids"))
				{
					QStringList infos, assoc;
					infos << "created_at" << "source" << "file_url" << "preview_url" << "width" << "md5" << "height" << "id" << "tags" << "author" << "score";
					assoc << "created_at" << "source_url" << "image" << "image" << "width" << "id" << "height" << "id_number" << "tags" << "uploader" << "score";
					for (int i = 0; i < infos.count(); i++)
					{ d[infos.at(i)] = sc.value(assoc.at(i)).toString().trimmed(); }
				}
				else
				{
					QStringList infos;
					infos << "created_at" << "status" << "source" << "has_comments" << "file_url" << "sample_url" << "change" << "sample_width" << "has_children" << "preview_url" << "width" << "md5" << "preview_width" << "sample_height" << "parent_id" << "height" << "has_notes" << "creator_id" << "file_size" << "id" << "preview_height" << "rating" << "tags" << "author" << "score";
					for (int i = 0; i < infos.count(); i++)
					{ d[infos.at(i)] = sc.value(infos.at(i)).toString().trimmed(); }
                }
				this->parseImage(d, id + first);
			}
		}
		else
		{
			fallback();
			return;
		}
	}

	// If tags have not been retrieved yet
	if (m_tags.isEmpty())
	{
		QStringList tagsGot;
		for (int i = 0; i < m_images.count(); i++)
		{
			QList<Tag> tags = m_images.at(i)->tags();
			for (int t = 0; t < tags.count(); t++)
			{
				if (tagsGot.contains(tags[t].text()))
				{ m_tags[tagsGot.indexOf(tags[t].text())].setCount(m_tags[tagsGot.indexOf(tags[t].text())].count()+1); }
				else
				{
					m_tags.append(tags[t]);
					tagsGot.append(tags[t].text());
				}
			}
		}
	}

	// Getting last page
	if (m_site->contains("LastPage") && m_pagesCount < 1)
	{ m_pagesCount = m_site->value("LastPage").toInt(); }
	if (m_site->contains("Regex/Count") && m_imagesCount < 1)
	{
		QRegExp rxlast(m_site->value("Regex/Count"));
		rxlast.indexIn(m_source, 0);
		m_imagesCount = rxlast.cap(1).remove(",").toInt();
	}
	if (m_site->contains("Regex/LastPage") && m_pagesCount < 1)
	{
		QRegExp rxlast(m_site->value("Regex/LastPage"));
		rxlast.indexIn(m_source, 0);
		m_pagesCount = rxlast.cap(1).remove(",").toInt();
	}

	// Guess images count
	if (m_site->contains("Urls/"+QString::number(m_currentSource)+"/Limit") && m_pagesCount > 0)
	{ m_imagesCount = m_pagesCount * m_site->value("Urls/"+QString::number(m_currentSource)+"/Limit").toInt(); }

	// Remove first n images (according to site settings)
	int skip = m_site->setting("ignore/always", 0).toInt();
	if (m_page == m_site->value("FirstPage").toInt())
		skip = m_site->setting("ignore/1", 0).toInt();
	if (m_images.size() > m_imagesPerPage && m_images.size() > skip)
		for (int i = 0; i < skip; ++i)
			m_images.removeFirst();

	// Virtual paging
	int firstImage = 0;
	int lastImage = m_smart ? m_imagesPerPage : m_images.size();
	if (!m_originalUrl.contains("{page}"))
	{
		firstImage = m_imagesPerPage * (m_page - 1);
		lastImage = m_imagesPerPage;
	}
    while (firstImage > 0)
	{
		m_images.removeFirst();
		firstImage--;
	}
	while (m_images.size() > lastImage)
	{ m_images.removeLast(); }

	m_reply->deleteLater();
	m_replyExists = false;

	QString t = m_search.join(" ");
	if (m_site->contains("DefaultTag") && t.isEmpty())
	{ t = m_site->value("DefaultTag"); }
	if (!m_search.isEmpty() && !m_site->value("Urls/"+QString::number(m_currentSource)+"/"+(t.isEmpty() && !m_site->contains("Urls/"+QString::number(m_currentSource)+"/Home") ? "Home" : "Tags")).contains("{tags}"))
	{ m_errors.append(tr("La recherche par tags est impossible avec la source choisie (%1).").arg(m_format)); }

	emit finishedLoading(this);
}
Example #26
0
void MiniClient::connectToServer(const Jid &jid, bool legacy_ssl_probe, bool legacy_ssl, bool forcessl, const QString &_host, int _port, QString proxy, QString *_pass)
{
	j = jid;

	QString host;
	int port = -1;
	bool useHost = false;
	force_ssl = forcessl;
	if(!_host.isEmpty()) {
		useHost = true;
		host = _host;
		port = _port;
	}

	AdvancedConnector::Proxy p;
	if(!proxy.isEmpty()) {
		const ProxyItem &pi = ProxyManager::instance()->getItem(proxy);
		if(pi.type == "http") // HTTP Connect
			p.setHttpConnect(pi.settings.host, pi.settings.port);
		else if(pi.type == "socks") // SOCKS
			p.setSocks(pi.settings.host, pi.settings.port);
		else if(pi.type == "poll") { // HTTP Poll
			QUrl u = pi.settings.url;
			if(u.queryItems().isEmpty()) {
				if (useHost)
					u.addQueryItem("server",host + ':' + QString::number(port));
				else
					u.addQueryItem("server",jid.domain());
			}
			p.setHttpPoll(pi.settings.host, pi.settings.port, u.toString());
			p.setPollInterval(2);
		}

		if(pi.settings.useAuth) {
			p.setUserPass(pi.settings.user, pi.settings.pass);
		}
	}

	conn = new AdvancedConnector;
	if (QCA::isSupported("tls")) {
		tls = new QCA::TLS;
		tls->setTrustedCertificates(CertificateHelpers::allCertificates(ApplicationInfo::getCertificateStoreDirs()));
		tlsHandler = new QCATLSHandler(tls);
		tlsHandler->setXMPPCertCheck(true);
		connect(tlsHandler, SIGNAL(tlsHandshaken()), SLOT(tls_handshaken()));
	}

	conn->setProxy(p);
	if (useHost) {
		conn->setOptHostPort(host, port);
		conn->setOptSSL(legacy_ssl);
	}
	else {
		conn->setOptProbe(legacy_ssl_probe);
	}

	stream = new ClientStream(conn, tlsHandler);
	connect(stream, SIGNAL(connected()), SLOT(cs_connected()));
	connect(stream, SIGNAL(securityLayerActivated(int)), SLOT(cs_securityLayerActivated(int)));
	connect(stream, SIGNAL(needAuthParams(bool, bool, bool)), SLOT(cs_needAuthParams(bool, bool, bool)));
	connect(stream, SIGNAL(authenticated()), SLOT(cs_authenticated()));
	connect(stream, SIGNAL(connectionClosed()), SLOT(cs_connectionClosed()));
	connect(stream, SIGNAL(delayedCloseFinished()), SLOT(cs_delayedCloseFinished()));
	connect(stream, SIGNAL(warning(int)), SLOT(cs_warning(int)));
	connect(stream, SIGNAL(error(int)), SLOT(cs_error(int)), Qt::QueuedConnection);

	if(_pass) {
		auth = true;
		pass = *_pass;
		_client->connectToServer(stream, j);
	}
	else {
		auth = false;
		_client->connectToServer(stream, j, false);
	}
}
Example #27
0
void MainWindow::onUrlChanged(const QUrl &url)
{
    urlEdit->setText(url.toString());
}
Example #28
0
QVariant PokeTextEdit::loadResource(int type, const QUrl &name)
{
    if (type != QTextDocument::ImageResource) {
        goto end;
    }

    {
        QString url = name.toString();

        if (url.indexOf(":") <= 0) {
            goto end;
        }

        {
            QString res = url.section(':', 0, 0);

            if (res != "pokemon" && res != "item") {
                goto end;
            }

            {
                QVariant ret;

                if (res == "pokemon") {
                    QStringList params = url.section(':', 1).split('&');

                    int gen = 5;
                    int gender = 0;
                    Pokemon::uniqueId num = Pokemon::NoPoke;
                    bool shiny=false;
                    bool back = false;

                    foreach (QString param, params) {
                        QString par = param.section('=', 0,0);
                        QString val = param.section('=', 1);

                        if (par.length() > 0 && par[0].isDigit() && val.length() == 0) {
                            val = par;
                            par = "num";
                        }

                        if (par == "gen") {
                            gen = val.toInt();
                        } else if (par == "num") {
                            num = Pokemon::uniqueId(val.section('-', 0,0).toInt(), val.section('-', 1).toInt());
                        } else if (par == "shiny") {
                            shiny = val == "true";
                        } else if (par == "gender") {
                            gender = val == "male" ? Pokemon::Male : (val == "female"?Pokemon::Female : Pokemon::Neutral);
                        } else if (par == "back") {
                            back = val == "true";
                        }
                    }

                    ret = PokemonInfo::Picture(num, gen, gender, shiny, back);
                } else if (res == "item") {
                    int item = url.section(':', 1).toInt();
                    ret = ItemInfo::Icon(item);
                }

                return ret;
            }
Example #29
0
void MainWindow::fileUploaded(QUrl url)
{
    QClipboard *clipboard = QApplication::clipboard();
    tray.showMessage("Upload complete", "Upload complete");
    clipboard->setText(url.toString());
}
void DirectShowPlayerService::doSetUrlSource(QMutexLocker *locker)
{
    IBaseFilter *source = 0;

    QMediaResource resource = m_resources.takeFirst();
    QUrl url = resource.url();

    HRESULT hr = E_FAIL;

    if (url.scheme() == QLatin1String("http") || url.scheme() == QLatin1String("https")) {
        static const GUID clsid_WMAsfReader = {
            0x187463a0, 0x5bb7, 0x11d3, {0xac, 0xbe, 0x00, 0x80, 0xc7, 0x5e, 0x24, 0x6e} };

        // {56a868a6-0ad4-11ce-b03a-0020af0ba770}
        static const GUID iid_IFileSourceFilter = {
            0x56a868a6, 0x0ad4, 0x11ce, {0xb0, 0x3a, 0x00, 0x20, 0xaf, 0x0b, 0xa7, 0x70} };

        if (IFileSourceFilter *fileSource = com_new<IFileSourceFilter>(
                clsid_WMAsfReader, iid_IFileSourceFilter)) {
            locker->unlock();
            hr = fileSource->Load(reinterpret_cast<const OLECHAR *>(url.toString().utf16()), 0);
            locker->relock();

            if (SUCCEEDED(hr)) {
                source = com_cast<IBaseFilter>(fileSource, IID_IBaseFilter);

                if (!SUCCEEDED(hr = m_graph->AddFilter(source, L"Source")) && source) {
                    source->Release();
                    source = 0;
                }
            }

            fileSource->Release();
        }
    } else if (url.scheme() == QLatin1String("qrc")) {
        DirectShowRcSource *rcSource = new DirectShowRcSource(m_loop);

        if (rcSource->open(url) && SUCCEEDED(hr = m_graph->AddFilter(rcSource, L"Source")))
            source = rcSource;
        else
            rcSource->Release();
    }

    if (!SUCCEEDED(hr)) {
        locker->unlock();
        hr = m_graph->AddSourceFilter(
                reinterpret_cast<const OLECHAR *>(url.toString().utf16()), L"Source", &source);
        locker->relock();
    }

    if (SUCCEEDED(hr)) {
        m_executedTasks = SetSource;
        m_pendingTasks |= Render;

        if (m_audioOutput)
            m_pendingTasks |= SetAudioOutput;
        if (m_videoOutput)
            m_pendingTasks |= SetVideoOutput;

        if (m_rate != 1.0)
            m_pendingTasks |= SetRate;

        m_source = source;
    } else if (!m_resources.isEmpty()) {
        m_pendingTasks |= SetUrlSource;
    } else {
        m_pendingTasks = 0;
        m_graphStatus = InvalidMedia;

        switch (hr) {
        case VFW_E_UNKNOWN_FILE_TYPE:
            m_error = QMediaPlayer::FormatError;
            m_errorString = QString();
            break;
        case E_OUTOFMEMORY:
        case VFW_E_CANNOT_LOAD_SOURCE_FILTER:
        case VFW_E_NOT_FOUND:
            m_error = QMediaPlayer::ResourceError;
            m_errorString = QString();
        default:
            m_error = QMediaPlayer::ResourceError;
            m_errorString = QString();
            qWarning("DirectShowPlayerService::doSetUrlSource: Unresolved error code %x", uint(hr));
            break;
        }

        QCoreApplication::postEvent(this, new QEvent(QEvent::Type(Error)));
    }
}