Esempio n. 1
0
QUrl searchForResourceSearchPath(const QUrl& baseUrl,
                                 const QUrl& url,
                                 const QStringList& searchPath)
{
  if (url.isRelative()) {
    if (!baseUrl.isLocalFile()) {
      return baseUrl.resolved(url);
    }

    auto path = url.path();
    if (!path.startsWith("/")) {
      auto resolvedUrl = baseUrl.resolved(url);
      if (QFile::exists(resolvedUrl.toLocalFile())) {
        return resolvedUrl;
      }
    } else if (!path.contains("/../")) {
      auto pathRelPart = path.split(QRegularExpression("^/+"))[1];
      for (const auto& str : searchPath) {
        auto dir = QDir(str);
        auto absPath = QDir::cleanPath(dir.absoluteFilePath(pathRelPart));

        if (QFile::exists(absPath)) {
          return QUrl::fromLocalFile(absPath);
        }
      }

      return QUrl();
    } else {
      return QUrl();
    }
  }

  return url;
}
Esempio n. 2
0
QList<WebPageLinkedResource> WebPage::linkedResources(const QString &relation)
{
    QList<WebPageLinkedResource> resources;

#if QT_VERSION >= 0x040600 || defined(WEBKIT_TRUNK)
    QUrl baseUrl = mainFrame()->baseUrl();

    QList<QWebElement> linkElements = mainFrame()->findAllElements(QLatin1String("html > head > link"));

    foreach (const QWebElement &linkElement, linkElements) {
        QString rel = linkElement.attribute(QLatin1String("rel"));
        QString href = linkElement.attribute(QLatin1String("href"));
        QString type = linkElement.attribute(QLatin1String("type"));
        QString title = linkElement.attribute(QLatin1String("title"));

        if (href.isEmpty() || type.isEmpty())
            continue;
        if (!relation.isEmpty() && rel != relation)
            continue;

        WebPageLinkedResource resource;
        resource.rel = rel;
        resource.type = type;
        resource.href = baseUrl.resolved(QUrl::fromEncoded(href.toUtf8()));
        resource.title = title;

        resources.append(resource);
    }
void WebImageView::setURLToRedirectedUrl(QNetworkReply *reply) {
    QUrl redirectionUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
    QUrl baseUrl = reply->url();
    QUrl resolvedUrl = baseUrl.resolved(redirectionUrl);

    setUrl(resolvedUrl.toString());
}
void WebImageView::imageLoaded() {

	// Get reply
	QNetworkReply * reply = qobject_cast<QNetworkReply*>(sender());

	if (reply->error() == QNetworkReply::NoError){

		QUrl baseUrl = reply->url();
		QUrl redirection = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
		// if redirection exists... Set the new Url
		if(redirection.isEmpty()){
			// Process reply
			QByteArray imageData = reply->readAll();

			// Set image from data
			setImage( Image(imageData) );

		}
		else{
			QUrl resolveUrl = baseUrl.resolved(redirection);
			setUrl(resolveUrl.toString());
			return;
		}

	}

		// Memory management
		reply->deleteLater();

	}
Esempio n. 5
0
QString Phantom::resolveRelativeUrl(QString url, QString base)
{
    QUrl u = QUrl::fromEncoded(url.toLatin1());
    QUrl b = QUrl::fromEncoded(base.toLatin1());

    return b.resolved(u).toEncoded();
}
Esempio n. 6
0
void CWizHtmlCollector::ProcessTagValue(CWizHtmlTag *pTag,
                                        const QString& strAttributeName,
                                        WIZHTMLFILEDATA::HtmlFileType eType)
{
    QString strValue = pTag->getValueFromName(strAttributeName);
    if (strValue.isEmpty())
        return;

    QUrl url(strValue);
    if (url.isRelative()) {
        QUrl urlBase = m_url;
        url = urlBase.resolved(url);
    }

    QString strFileName;
    if (!m_files.Lookup(url.toString(), strFileName)) {
        strFileName = url.toLocalFile();
        if (!strFileName.isEmpty() && !PathFileExists(strFileName)) {
            strFileName.clear();
        }

        if (strFileName.isEmpty())
            return;

        m_files.Add(url.toString(), strFileName, eType, false);
    }

    pTag->setValueToName(strAttributeName, ToResourceFileName(strFileName));
}
Esempio n. 7
0
QUrl QUrlProto::resolved(const QUrl &relative) const
{
  QUrl *item = qscriptvalue_cast<QUrl*>(thisObject());
  if (item)
    return item->resolved(relative);
  return QUrl();
}
QList<webFileUtils::webFile> webFileUtils::getWebFiles(QUrl url)
{
    QList<webFileUtils::webFile> list;
    QWebPage *webPage = new QWebPage(this);
    QEventLoop loop;
    connect(webPage->mainFrame(), SIGNAL(loadFinished(bool)), &loop, SLOT(quit()));
    webPage->mainFrame()->load(url);
    loop.exec();
    QUrl baseUrl = webPage->mainFrame()->baseUrl();

    QWebElementCollection collection = webPage->mainFrame()->findAllElements("a");
    foreach (QWebElement element, collection)
    {
        QString href = element.attribute("href");
        if (!href.isEmpty())
        {
            QUrl relativeUrl(href);
            QUrl absoluteUrl = baseUrl.resolved(relativeUrl);
            if(element.toPlainText().contains("exe") | element.toPlainText().contains("tar.xz") | element.toPlainText().contains("zip")) {
                webFile file;
                file.name = element.toPlainText();
                file.url = absoluteUrl;
                list.append(file);
            }
        }
    }
Esempio n. 9
0
void TestRunner::queueLoad(const QString& url, const QString& target)
{
    //qDebug() << ">>>queueLoad" << url << target;
    QUrl mainResourceUrl = m_drt->webPage()->mainFrame()->url();
    QString absoluteUrl = mainResourceUrl.resolved(QUrl(url)).toEncoded();
    WorkQueue::shared()->queue(new LoadItem(absoluteUrl, target, m_drt->webPage()));
}
Esempio n. 10
0
void TestRunner::queueLoad(JSStringRef url, JSStringRef target)
{
    DumpRenderTree* drt = DumpRenderTree::instance();
    QUrl mainResourceUrl = drt->webPage()->mainFrame()->url();
    QString absoluteUrl = mainResourceUrl.resolved(QUrl(JSStringCopyQString(url))).toEncoded();
    WorkQueue::shared()->queue(new LoadItem(JSStringCreateWithQString(absoluteUrl).get(), target));
}
Esempio n. 11
0
int Url::resolved ( lua_State * L )// ( const QUrl & relative ) const : QUrl
{
	QUrl* lhs = ValueInstaller2<QUrl>::check( L, 1 );
	QUrl* relative = ValueInstaller2<QUrl>::check( L, 2 );
	QUrl* res = ValueInstaller2<QUrl>::create( L );
	*res = lhs->resolved( *relative );
	return 1;
}
Esempio n. 12
0
QUrl XSLTUriResolver::resolve(const QUrl& relative, const QUrl& baseURI) const
{
    QUrl url = baseURI.resolved(relative);

    if (!m_document->frame() || !m_document->securityOrigin()->canRequest(url))
        return QUrl();
    return url;
}
Esempio n. 13
0
void Song::set_url(const QUrl& v) {
  if (Application::kIsPortable) {
    QUrl base = QUrl::fromLocalFile(QCoreApplication::applicationDirPath() + "/");
    d->url_ = base.resolved(v);
  } else {
    d->url_ = v;
  }
}
Esempio n. 14
0
// Simulates a mouse down event for drag without sending an actual mouse down event.
void EventSender::beginDragWithFiles(const QStringList& files)
{
    m_currentDragData.clear();
    QList<QUrl> fileUrls;
    QUrl baseUrl = m_page->mainFrame()->baseUrl();
    foreach (const QString& file, files) {
        QUrl resolvedUrl = baseUrl.resolved(file);
        fileUrls.append(resolvedUrl);
    }
    void onQNetworkReplyFinished() {
        // either error or all data has been read
        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->errorString());
            result << InvocationErrors::INVOCATION_FAILED;

            QVariant statusCode = qreply->attribute( QNetworkRequest::HttpStatusCodeAttribute );
            if (statusCode.isValid()) {
                httpStatus = HTTPInvocationDefinition::resolveHttpStatus(statusCode.toInt());
            } else {
                httpStatus = HTTPInvocationDefinition::UNDEFINED;
                result << Result::reasonFromDesc("Http response code is not valid");
            }

            invocationStatus = Invocation::ERROR;

            // get possible return data (detailed error info)
            // responseErrorData = qreply->readAll();
            result << InvocationErrors::CONNECTION_FAILED
                   << Result::Meta("qnetworkreply_error_string", qreply->errorString());

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

            //result << Result::reasonFromCode("QNETWORKREPLY_ERROR", qreply->errorString());
            emit q->finishedError(q);
        }
        else
        {
            // we have all data
            // (TODO: is it so that readRead() is invoked before?)

            if (outputFile.isOpen())
                outputFile.close();

            invocationStatus = Invocation::FINISHED;
            emit q->finishedOK(q);
        }

        qreply->deleteLater();
        qreply = nullptr;
    }
Esempio n. 16
0
QByteArray WebUtils::postByUrl(const QUrl &url,
                            const QMap<QString, QString> &sysAndAppParams,
                            const QMap<QString, FileItem> &tmpFiles)
{
  QHttpMultiPart multiParts(QHttpMultiPart::FormDataType);

  QMapIterator<QString, QString> appParamIter(sysAndAppParams);
  while (appParamIter.hasNext()) {
    appParamIter.next();
    QHttpPart appParamPart;
    appParamPart.setHeader(QNetworkRequest::ContentTypeHeader,
                           QVariant("text/plain; charset = UTF-8"));
    appParamPart.setHeader(QNetworkRequest::ContentDispositionHeader,
                           QVariant("form-data; name =" + appParamIter.key().toUtf8()));
    appParamPart.setBody(appParamIter.value().toUtf8());
    multiParts.append(appParamPart);
  }


  QMapIterator<QString, FileItem> i(tmpFiles);
  while (i.hasNext()) {
    i.next();
    FileItem fileItem = i.value();
    QHttpPart filePart;
    filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(fileItem.getMimeType()));
    QString disposition = QString("form-data; name = %1; filename = %2")
        .arg(i.key()).arg(fileItem.getFileName());
    filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(disposition));
    filePart.setBody(fileItem.getContent());
    multiParts.append(filePart);
  }

  QNetworkReply *reply = qnam.post(QNetworkRequest(url), &multiParts);
  QEventLoop loop;
  connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
  loop.exec();

  QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

  if (reply->error()) {
    qDebug() << reply->errorString();
    return reply->errorString().toUtf8();
  } else if (!redirectionTarget.isNull()) {
    QUrl newUrl = url.resolved(redirectionTarget.toUrl());
    reply->deleteLater();
    return postByUrl(newUrl, sysAndAppParams, tmpFiles);
  }

  QByteArray returnStr = reply->readAll();
  reply->deleteLater();
  return returnStr;
}
void tst_qdeclarativeengine::baseUrl()
{
    QDeclarativeEngine engine;

    QUrl cwd = QUrl::fromLocalFile(QDir::currentPath() + QDir::separator());

    QCOMPARE(engine.baseUrl(), cwd);
    QCOMPARE(engine.rootContext()->resolvedUrl(QUrl("main.qml")), cwd.resolved(QUrl("main.qml")));

    QDir dir = QDir::current();
    dir.cdUp();
    QVERIFY(dir != QDir::current());
    QDir::setCurrent(dir.path());
    QVERIFY(QDir::current() == dir);

    QUrl cwd2 = QUrl::fromLocalFile(QDir::currentPath() + QDir::separator());
    QCOMPARE(engine.baseUrl(), cwd2);
    QCOMPARE(engine.rootContext()->resolvedUrl(QUrl("main.qml")), cwd2.resolved(QUrl("main.qml")));

    engine.setBaseUrl(cwd);
    QCOMPARE(engine.baseUrl(), cwd);
    QCOMPARE(engine.rootContext()->resolvedUrl(QUrl("main.qml")), cwd.resolved(QUrl("main.qml")));
}
 bool DownloadManager::hasRedirect( QNetworkReply *reply )
 {
     if( reply->error() == QNetworkReply::NoError ){
         QVariant redirect = reply->attribute( QNetworkRequest::RedirectionTargetAttribute );
         if( !redirect.isNull() ){
             QUrl originalUrl = reply->request().url();
             QString newUrl = originalUrl.resolved( redirect.toUrl() ).toString();
             stopDownload( originalUrl.toString() );
             startDownload( newUrl );
             return true;
         } else {
             return false;
         }
     }
     return false;
 }
Esempio n. 19
0
bool VWebUtils::fixImageSrc(const QUrl &p_baseUrl, QString &p_html)
{
    bool changed = false;

#if defined(Q_OS_WIN)
    QUrl::ComponentFormattingOption strOpt = QUrl::EncodeSpaces;
#else
    QUrl::ComponentFormattingOption strOpt = QUrl::FullyEncoded;
#endif

    QRegExp reg("<img src=\"([^\"]+)\"");

    int pos = 0;
    while (pos < p_html.size()) {
        int idx = p_html.indexOf(reg, pos);
        if (idx == -1) {
            break;
        }

        QString urlStr = reg.cap(1);
        QUrl imgUrl(urlStr);

        QString fixedStr;
        if (imgUrl.isRelative()) {
            fixedStr = p_baseUrl.resolved(imgUrl).toString(strOpt);
        } else if (imgUrl.isLocalFile()) {
            fixedStr = imgUrl.toString(strOpt);
        } else if (imgUrl.scheme() != "https" && imgUrl.scheme() != "http") {
            QString tmp = imgUrl.toString();
            if (QFileInfo::exists(tmp)) {
                fixedStr = QUrl::fromLocalFile(tmp).toString(strOpt);
            }
        }

        pos = idx + reg.matchedLength();
        if (!fixedStr.isEmpty() && urlStr != fixedStr) {
            qDebug() << "fix img url" << urlStr << fixedStr;
            pos = pos + fixedStr.size() + 1 - urlStr.size();
            p_html.replace(idx,
                           reg.matchedLength(),
                           QString("<img src=\"%1\"").arg(fixedStr));
            changed = true;
        }
    }

    return changed;
}
Esempio n. 20
0
void TemplateSelectionPagePrivate::previewTemplate(const QString& file)
{
    SourceFileTemplate fileTemplate(file);
    if (!fileTemplate.isValid() || fileTemplate.outputFiles().isEmpty()) {
        return;
    }

    TemplatePreviewRenderer renderer;
    renderer.setEmptyLinesPolicy(TemplateRenderer::TrimEmptyLines);

    QTemporaryDir dir;
    QUrl base = QUrl::fromLocalFile(dir.path() + QLatin1Char('/'));
    QHash<QString, QUrl> fileUrls;
    foreach(const SourceFileTemplate::OutputFile& out, fileTemplate.outputFiles()) {
        QUrl url = base.resolved(QUrl(renderer.render(out.outputName)));
        fileUrls.insert(out.identifier, url);
    }
    DocumentChangeSet changes = renderer.renderFileTemplate(fileTemplate, base, fileUrls);
    changes.setActivationPolicy(DocumentChangeSet::DoNotActivate);
    changes.setUpdateHandling(DocumentChangeSet::NoUpdate);
    DocumentChangeSet::ChangeResult result = changes.applyAllChanges();
    if (!result) {
        return;
    }

    int idx = 0;
    foreach(const SourceFileTemplate::OutputFile& out, fileTemplate.outputFiles()) {
        TemplatePreview* preview = nullptr;
        if (ui->tabWidget->count() > idx) {
            // reuse existing tab
            preview = qobject_cast<TemplatePreview*>(ui->tabWidget->widget(idx));
            ui->tabWidget->setTabText(idx, out.label);
            Q_ASSERT(preview);
        } else {
            // create new tabs on demand
            preview = new TemplatePreview(page);
            ui->tabWidget->addTab(preview, out.label);
        }
        preview->document()->openUrl(fileUrls.value(out.identifier));
        ++idx;
    }
    // remove superfluous tabs from last time
    while (ui->tabWidget->count() > fileUrls.size()) {
        delete ui->tabWidget->widget(fileUrls.size());
    }
    return;
}
Esempio n. 21
0
Item ResolveURIFN::evaluateSingleton(const DynamicContext::Ptr &context) const
{
    const Item relItem(m_operands.first()->evaluateSingleton(context));

    if(relItem)
    {
        const QString base(m_operands.last()->evaluateSingleton(context).stringValue());
        const QString relative(relItem.stringValue());

        const QUrl baseURI(AnyURI::toQUrl<ReportContext::FORG0002, DynamicContext::Ptr>(base, context, this));
        const QUrl relativeURI(AnyURI::toQUrl<ReportContext::FORG0002, DynamicContext::Ptr>(relative, context, this));

        return toItem(AnyURI::fromValue(baseURI.resolved(relativeURI)));
    }
    else
        return Item();
}
Esempio n. 22
0
QUrl QWebFrameAdapter::ensureAbsoluteUrl(const QUrl& url)
{
    // FIXME: it would be nice if we could avoid doing this.
    // Convert to KURL and back to preserve the old behavior (e.g. fixup of single slash in 'http:/')
    QUrl validatedUrl = KURL(url);

    if (!validatedUrl.isValid() || !validatedUrl.isRelative())
        return validatedUrl;

    // This contains the URL with absolute path but without
    // the query and the fragment part.
    QUrl baseUrl = QUrl::fromLocalFile(QFileInfo(validatedUrl.toLocalFile()).absoluteFilePath());

    // The path is removed so the query and the fragment parts are there.
    QString pathRemoved = validatedUrl.toString(QUrl::RemovePath);
    QUrl toResolve(pathRemoved);

    return baseUrl.resolved(toResolve);
}
Esempio n. 23
0
static AnimNode::Pointer loadClipNode(const QJsonObject& jsonObj, const QString& id, const QUrl& jsonUrl) {

    READ_STRING(url, jsonObj, id, jsonUrl, nullptr);
    READ_FLOAT(startFrame, jsonObj, id, jsonUrl, nullptr);
    READ_FLOAT(endFrame, jsonObj, id, jsonUrl, nullptr);
    READ_FLOAT(timeScale, jsonObj, id, jsonUrl, nullptr);
    READ_BOOL(loopFlag, jsonObj, id, jsonUrl, nullptr);
    READ_OPTIONAL_BOOL(mirrorFlag, jsonObj, false);

    READ_OPTIONAL_STRING(startFrameVar, jsonObj);
    READ_OPTIONAL_STRING(endFrameVar, jsonObj);
    READ_OPTIONAL_STRING(timeScaleVar, jsonObj);
    READ_OPTIONAL_STRING(loopFlagVar, jsonObj);
    READ_OPTIONAL_STRING(mirrorFlagVar, jsonObj);

    // animation urls can be relative to the containing url document.
    auto tempUrl = QUrl(url);
    tempUrl = jsonUrl.resolved(tempUrl);

    auto node = std::make_shared<AnimClip>(id, tempUrl.toString(), startFrame, endFrame, timeScale, loopFlag, mirrorFlag);

    if (!startFrameVar.isEmpty()) {
        node->setStartFrameVar(startFrameVar);
    }
    if (!endFrameVar.isEmpty()) {
        node->setEndFrameVar(endFrameVar);
    }
    if (!timeScaleVar.isEmpty()) {
        node->setTimeScaleVar(timeScaleVar);
    }
    if (!loopFlagVar.isEmpty()) {
        node->setLoopFlagVar(loopFlagVar);
    }
    if (!mirrorFlagVar.isEmpty()) {
        node->setMirrorFlagVar(mirrorFlagVar);
    }

    return node;
}
Esempio n. 24
0
/**
 * @brief 通过HTTP GET发送URL,因为QNetWorkAccessManager默认不CACHE,所以不必设置
 **/
QByteArray WebUtils::getByUrl(const QUrl &url)
{
  QNetworkReply *reply = qnam.get(QNetworkRequest(url));
  QEventLoop loop;
  connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
  loop.exec();

  QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

  // WARNING: taobao only have once redirect url
  if (reply->error()) {
    qDebug() << reply->errorString();
    return "";
  } else if (!redirectionTarget.isNull()) {
    QUrl newUrl = url.resolved(redirectionTarget.toUrl());
    reply->deleteLater();
    return getByUrl(newUrl);
  }

  QByteArray returnStr = reply->readAll();
  reply->deleteLater();
  return returnStr;
}
Esempio n. 25
0
QUrl ScriptEngine::resolvePath(const QString& include) const {
    QUrl url(include);
    // first lets check to see if it's already a full URL
    if (!url.scheme().isEmpty()) {
        return url;
    }

    // we apparently weren't a fully qualified url, so, let's assume we're relative
    // to the original URL of our script
    QUrl parentURL;
    if (_parentURL.isEmpty()) {
        parentURL = QUrl(_fileNameString);
    } else {
        parentURL = QUrl(_parentURL);
    }
    // if the parent URL's scheme is empty, then this is probably a local file...
    if (parentURL.scheme().isEmpty()) {
        parentURL = QUrl::fromLocalFile(_fileNameString);
    }

    // at this point we should have a legitimate fully qualified URL for our parent
    url = parentURL.resolved(url);
    return url;
}
Esempio n. 26
0
bool QDeclarativeImportedNamespace::find_helper(QDeclarativeTypeLoader *typeLoader, int i, const QByteArray& type, int *vmajor, int *vminor,
                                 QDeclarativeType** type_return, QUrl* url_return,
                                 QUrl *base, bool *typeRecursionDetected)
{
    int vmaj = majversions.at(i);
    int vmin = minversions.at(i);

    QByteArray qt = uris.at(i).toUtf8();
    qt += '/';
    qt += type;

    QDeclarativeType *t = QDeclarativeMetaType::qmlType(qt,vmaj,vmin);
    if (t) {
        if (vmajor) *vmajor = vmaj;
        if (vminor) *vminor = vmin;
        if (type_return)
            *type_return = t;
        return true;
    }

    QDeclarativeDirComponents qmldircomponents = qmlDirComponents.at(i);

    bool typeWasDeclaredInQmldir = false;
    if (!qmldircomponents.isEmpty()) {
        const QString typeName = QString::fromUtf8(type);
        foreach (const QDeclarativeDirParser::Component &c, qmldircomponents) {
            if (c.typeName == typeName) {
                typeWasDeclaredInQmldir = true;

                // importing version -1 means import ALL versions
                if ((vmaj == -1) || (c.majorVersion < vmaj || (c.majorVersion == vmaj && vmin >= c.minorVersion))) {
                    QUrl url = QUrl(urls.at(i) + QLatin1Char('/') + QString::fromUtf8(type) + QLatin1String(".qml"));
                    QUrl candidate = url.resolved(QUrl(c.fileName));
                    if (c.internal && base) {
                        if (base->resolved(QUrl(c.fileName)) != candidate)
                            continue; // failed attempt to access an internal type
                    }
                    if (base && *base == candidate) {
                        if (typeRecursionDetected)
                            *typeRecursionDetected = true;
                        continue; // no recursion
                    }
                    if (url_return)
                        *url_return = candidate;
                    return true;
                }
            }
        }
    }

    if (!typeWasDeclaredInQmldir  && !isLibrary.at(i)) {
        // XXX search non-files too! (eg. zip files, see QT-524)
        QUrl url = QUrl(urls.at(i) + QLatin1Char('/') + QString::fromUtf8(type) + QLatin1String(".qml"));
        QString file = QDeclarativeEnginePrivate::urlToLocalFileOrQrc(url);
        if (!typeLoader->absoluteFilePath(file).isEmpty()) {
            if (base && *base == url) { // no recursion
                if (typeRecursionDetected)
                    *typeRecursionDetected = true;
            } else {
                if (url_return)
                    *url_return = url;
                return true;
            }
        }
    }
    return false;
}
Esempio n. 27
0
int main(int argc, char *argv[])
{
#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
    QCoreApplication::setAttribute(Qt::AA_X11InitThreads);
#endif
    
    KLocalizedString::setApplicationDomain("kdenlive");

    // Init application
    QApplication app(argc, argv);

    // Create KAboutData
    KAboutData aboutData(QByteArray("kdenlive"), 
                         i18n("Kdenlive"), KDENLIVE_VERSION,
                         i18n("An open source video editor."),
                         KAboutLicense::GPL,
                         i18n("Copyright © 2007–2015 Kdenlive authors"),
                         i18n("Please report bugs to http://bugs.kde.org"),
                         QStringLiteral("https://kdenlive.org"));
    aboutData.addAuthor(i18n("Jean-Baptiste Mardelle"), i18n("MLT and KDE SC 4 / KF5 port, main developer and maintainer"), QStringLiteral("*****@*****.**"));
    aboutData.addAuthor(i18n("Vincent Pinon"), i18n("Interim maintainer, KF5 port, bugs fixing, minor functions, profiles updates, etc."), QStringLiteral("*****@*****.**"));
    aboutData.addAuthor(i18n("Laurent Montel"), i18n("Bugs fixing, clean up code, optimization etc."), QStringLiteral("*****@*****.**"));
    aboutData.addAuthor(i18n("Marco Gittler"), i18n("MLT transitions and effects, timeline, audio thumbs"), QStringLiteral("*****@*****.**"));
    aboutData.addAuthor(i18n("Dan Dennedy"), i18n("Bug fixing, etc."), QStringLiteral("*****@*****.**"));
    aboutData.addAuthor(i18n("Simon A. Eugster"), i18n("Color scopes, bug fixing, etc."), QStringLiteral("*****@*****.**"));
    aboutData.addAuthor(i18n("Till Theato"), i18n("Bug fixing, etc."), QStringLiteral("*****@*****.**"));
    aboutData.addAuthor(i18n("Alberto Villa"), i18n("Bug fixing, logo, etc."), QStringLiteral("*****@*****.**"));
    aboutData.addAuthor(i18n("Jean-Michel Poure"), i18n("Rendering profiles customization"), QStringLiteral("*****@*****.**"));
    aboutData.addAuthor(i18n("Ray Lehtiniemi"), i18n("Bug fixing, etc."), QStringLiteral("*****@*****.**"));
    aboutData.addAuthor(i18n("Steve Guilford"), i18n("Bug fixing, etc."), QStringLiteral("*****@*****.**"));
    aboutData.addAuthor(i18n("Jason Wood"), i18n("Original KDE 3 version author (not active anymore)"), QStringLiteral("*****@*****.**"));
    aboutData.setTranslator(i18n("NAME OF TRANSLATORS"), i18n("EMAIL OF TRANSLATORS"));
    aboutData.setOrganizationDomain(QByteArray("kde.org"));


    // Register about data
    KAboutData::setApplicationData(aboutData);

    // Set app stuff from about data
    app.setApplicationName(aboutData.componentName());
    app.setApplicationDisplayName(aboutData.displayName());
    app.setOrganizationDomain(aboutData.organizationDomain());
    app.setApplicationVersion(aboutData.version());
    
    // Create command line parser with options
    QCommandLineParser parser;
    aboutData.setupCommandLine(&parser);
    parser.setApplicationDescription(aboutData.shortDescription());
    parser.addVersionOption();
    parser.addHelpOption();

    parser.addOption(QCommandLineOption(QStringList() <<  QStringLiteral("mlt-path"), i18n("Set the path for MLT environment"), QStringLiteral("mlt-path")));
    parser.addOption(QCommandLineOption(QStringList() <<  QStringLiteral("i"), i18n("Comma separated list of clips to add"), QStringLiteral("clips")));
    parser.addPositionalArgument(QStringLiteral("file"), i18n("Document to open"));

    // Parse command line
    parser.process(app);
    aboutData.processCommandLine(&parser);

    // Register DBus service
    KDBusService programDBusService;

    // see if we are starting with session management
    if (qApp->isSessionRestored()){
	  int n = 1;
	  while (KMainWindow::canBeRestored(n)){
	      (new MainWindow())->restore(n);
	      n++;
	  }
    } else {
        QString clipsToLoad = parser.value(QStringLiteral("i"));
        QString mltPath = parser.value(QStringLiteral("mlt-path"));
        QUrl url;
        if (parser.positionalArguments().count()) {
            url = QUrl::fromLocalFile(parser.positionalArguments().first());
            // Make sure we get an absolute URL so that we can autosave correctly
            QString currentPath = QDir::currentPath();
            QUrl startup = QUrl::fromLocalFile(currentPath.endsWith(QDir::separator()) ? currentPath : currentPath + QDir::separator());
            url = startup.resolved(url);
        }
        MainWindow* window = new MainWindow(mltPath, url, clipsToLoad);
        window->show();
    }
    int result = app.exec();
    
    if (EXIT_RESTART == result) {
        qDebug() << "restarting app";
        QProcess* restart = new QProcess;
        restart->start(app.applicationFilePath(), QStringList());
        restart->waitForReadyRead();
        restart->waitForFinished(1000);
        result = EXIT_SUCCESS;
    }
    
    return result;
}
Esempio n. 28
0
void GeometryResource::downloadFinished(const QByteArray& data) {
    if (_effectiveBaseURL.fileName().toLower().endsWith(".fst")) {
        PROFILE_ASYNC_BEGIN(resource_parse_geometry, "GeometryResource::downloadFinished", _url.toString(), { { "url", _url.toString() } });

        // store parsed contents of FST file
        _mapping = FSTReader::readMapping(data);

        QString filename = _mapping.value("filename").toString();

        if (filename.isNull()) {
            finishedLoading(false);
        } else {
            const QString baseURL = _mapping.value("baseURL").toString();
            const QUrl base = _effectiveBaseURL.resolved(baseURL);
            QUrl url = base.resolved(filename);

            QString texdir = _mapping.value(TEXDIR_FIELD).toString();
            if (!texdir.isNull()) {
                if (!texdir.endsWith('/')) {
                    texdir += '/';
                }
                _textureBaseURL = resolveTextureBaseUrl(url, base.resolved(texdir));
            } else {
                _textureBaseURL = url.resolved(QUrl("."));
            }

            auto scripts = FSTReader::getScripts(base, _mapping);
            if (scripts.size() > 0) {
                _mapping.remove(SCRIPT_FIELD);
                for (auto &scriptPath : scripts) {
                    _mapping.insertMulti(SCRIPT_FIELD, scriptPath);
                }
            }

            auto animGraphVariant = _mapping.value("animGraphUrl");

            if (animGraphVariant.isValid()) {
                QUrl fstUrl(animGraphVariant.toString());
                if (fstUrl.isValid()) {
                    _animGraphOverrideUrl = base.resolved(fstUrl);
                } else {
                    _animGraphOverrideUrl = QUrl();
                }
            } else {
                _animGraphOverrideUrl = QUrl();
            }

            auto modelCache = DependencyManager::get<ModelCache>();
            GeometryExtra extra { GeometryMappingPair(base, _mapping), _textureBaseURL, false };

            // Get the raw GeometryResource
            _geometryResource = modelCache->getResource(url, QUrl(), &extra, std::hash<GeometryExtra>()(extra)).staticCast<GeometryResource>();
            // Avoid caching nested resources - their references will be held by the parent
            _geometryResource->_isCacheable = false;

            if (_geometryResource->isLoaded()) {
                onGeometryMappingLoaded(!_geometryResource->getURL().isEmpty());
            } else {
                if (_connection) {
                    disconnect(_connection);
                }

                _connection = connect(_geometryResource.data(), &Resource::finished, this, &GeometryResource::onGeometryMappingLoaded);
            }
        }
    } else {
        if (_url != _effectiveBaseURL) {
            _url = _effectiveBaseURL;
            _textureBaseURL = _effectiveBaseURL;
        }
        QThreadPool::globalInstance()->start(new GeometryReader(_modelLoader, _self, _effectiveBaseURL, _mappingPair, data, _combineParts, _request->getWebMediaType()));
    }
}
Esempio n. 29
0
    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;
    }
Esempio n. 30
0
// Note: See MaterialEntityItem.h for default values used in practice.
std::pair<std::string, std::shared_ptr<NetworkMaterial>> NetworkMaterialResource::parseJSONMaterial(const QJsonObject& materialJSON, const QUrl& baseUrl) {
    std::string name = "";
    std::shared_ptr<NetworkMaterial> material = std::make_shared<NetworkMaterial>();
    for (auto& key : materialJSON.keys()) {
        if (key == "name") {
            auto nameJSON = materialJSON.value(key);
            if (nameJSON.isString()) {
                name = nameJSON.toString().toStdString();
            }
        } else if (key == "model") {
            auto modelJSON = materialJSON.value(key);
            if (modelJSON.isString()) {
                material->setModel(modelJSON.toString().toStdString());
            }
        } else if (key == "emissive") {
            glm::vec3 color;
            bool isSRGB;
            bool valid = parseJSONColor(materialJSON.value(key), color, isSRGB);
            if (valid) {
                material->setEmissive(color, isSRGB);
            }
        } else if (key == "opacity") {
            auto value = materialJSON.value(key);
            if (value.isDouble()) {
                material->setOpacity(value.toDouble());
            }
        } else if (key == "unlit") {
            auto value = materialJSON.value(key);
            if (value.isBool()) {
                material->setUnlit(value.toBool());
            }
        } else if (key == "albedo") {
            glm::vec3 color;
            bool isSRGB;
            bool valid = parseJSONColor(materialJSON.value(key), color, isSRGB);
            if (valid) {
                material->setAlbedo(color, isSRGB);
            }
        } else if (key == "roughness") {
            auto value = materialJSON.value(key);
            if (value.isDouble()) {
                material->setRoughness(value.toDouble());
            }
        } else if (key == "metallic") {
            auto value = materialJSON.value(key);
            if (value.isDouble()) {
                material->setMetallic(value.toDouble());
            }
        } else if (key == "scattering") {
            auto value = materialJSON.value(key);
            if (value.isDouble()) {
                material->setScattering(value.toDouble());
            }
        } else if (key == "emissiveMap") {
            auto value = materialJSON.value(key);
            if (value.isString()) {
                material->setEmissiveMap(baseUrl.resolved(value.toString()));
            }
        } else if (key == "albedoMap") {
            auto value = materialJSON.value(key);
            if (value.isString()) {
                QString urlString = value.toString();
                bool useAlphaChannel = false;
                auto opacityMap = materialJSON.find("opacityMap");
                if (opacityMap != materialJSON.end() && opacityMap->isString() && opacityMap->toString() == urlString) {
                    useAlphaChannel = true;
                }
                material->setAlbedoMap(baseUrl.resolved(urlString), useAlphaChannel);
            }
        } else if (key == "roughnessMap") {
            auto value = materialJSON.value(key);
            if (value.isString()) {
                material->setRoughnessMap(baseUrl.resolved(value.toString()), false);
            }
        } else if (key == "glossMap") {
            auto value = materialJSON.value(key);
            if (value.isString()) {
                material->setRoughnessMap(baseUrl.resolved(value.toString()), true);
            }
        } else if (key == "metallicMap") {
            auto value = materialJSON.value(key);
            if (value.isString()) {
                material->setMetallicMap(baseUrl.resolved(value.toString()), false);
            }
        } else if (key == "specularMap") {
            auto value = materialJSON.value(key);
            if (value.isString()) {
                material->setMetallicMap(baseUrl.resolved(value.toString()), true);
            }
        } else if (key == "normalMap") {
            auto value = materialJSON.value(key);
            if (value.isString()) {
                material->setNormalMap(baseUrl.resolved(value.toString()), false);
            }
        } else if (key == "bumpMap") {
            auto value = materialJSON.value(key);
            if (value.isString()) {
                material->setNormalMap(baseUrl.resolved(value.toString()), true);
            }
        } else if (key == "occlusionMap") {
            auto value = materialJSON.value(key);
            if (value.isString()) {
                material->setOcclusionMap(baseUrl.resolved(value.toString()));
            }
        } else if (key == "scatteringMap") {
            auto value = materialJSON.value(key);
            if (value.isString()) {
                material->setScatteringMap(baseUrl.resolved(value.toString()));
            }
        } else if (key == "lightMap") {
            auto value = materialJSON.value(key);
            if (value.isString()) {
                material->setLightmapMap(baseUrl.resolved(value.toString()));
            }
        }
    }
    return std::pair<std::string, std::shared_ptr<NetworkMaterial>>(name, material);
}