Ejemplo n.º 1
0
/*!
  \internal

  The given (namespace qualified) \a type is resolved to either
  \list
  \li a QDeclarativeImportedNamespace stored at \a ns_return,
  \li a QDeclarativeType stored at \a type_return, or
  \li a component located at \a url_return.
  \endlist

  If any return pointer is 0, the corresponding search is not done.

  \sa addImport()
*/
bool QDeclarativeImports::resolveType(const QByteArray& type,
                                      QDeclarativeType** type_return, QUrl* url_return, int *vmaj, int *vmin,
                                      QDeclarativeImportedNamespace** ns_return, QString *errorString) const
{
    QDeclarativeImportedNamespace* ns = d->findNamespace(QString::fromUtf8(type));
    if (ns) {
        if (ns_return)
            *ns_return = ns;
        return true;
    }
    if (type_return || url_return) {
        if (d->find(type,vmaj,vmin,type_return,url_return, errorString)) {
            if (qmlImportTrace()) {
                if (type_return && *type_return && url_return && !url_return->isEmpty())
                    qDebug().nospace() << "QDeclarativeImports(" << qPrintable(baseUrl().toString()) << ")" << "::resolveType: "
                                       << type << " => " << (*type_return)->typeName() << " " << *url_return;
                if (type_return && *type_return)
                    qDebug().nospace() << "QDeclarativeImports(" << qPrintable(baseUrl().toString()) << ")" << "::resolveType: "
                                       << type << " => " << (*type_return)->typeName();
                if (url_return && !url_return->isEmpty())
                    qDebug().nospace() << "QDeclarativeImports(" << qPrintable(baseUrl().toString()) << ")" << "::resolveType: "
                                       << type << " => " << *url_return;
            }
            return true;
        }
    }
    return false;
}
Ejemplo n.º 2
0
QString RDFeed::audioUrl(RDFeed::MediaLinkMode mode,unsigned cast_id)
{
  QUrl url(baseUrl());
  QString ret;
  RDPodcast *cast;

  switch(mode) {
    case RDFeed::LinkNone:
      ret="";
      break;

    case RDFeed::LinkDirect:
      cast=new RDPodcast(cast_id);
      ret=QString().sprintf("%s/%s",
			    (const char *)baseUrl(),
			    (const char *)cast->audioFilename());
      delete cast;
      break;

    case RDFeed::LinkCounted:
      ret=QString().sprintf("http://%s%s/rd-bin/rdfeed.%s?%s&cast_id=%d",
			    (const char *)basePreamble(),
			    (const char *)url.host(),
			    (const char *)uploadExtension(),
			    (const char *)keyName(),
			    cast_id);
      break;
  }
  return ret;
}
Ejemplo n.º 3
0
void FrameLoaderClientQt::callErrorPageExtension(const WebCore::ResourceError& error)
{
    QWebPage* page = m_webFrame->page();
    if (page->supportsExtension(QWebPage::ErrorPageExtension)) {
        QWebPage::ErrorPageExtensionOption option;

        if (error.domain() == "QtNetwork")
            option.domain = QWebPage::QtNetwork;
        else if (error.domain() == "HTTP")
            option.domain = QWebPage::Http;
        else if (error.domain() == "WebKit")
            option.domain = QWebPage::WebKit;
        else
            return;

        option.url = QUrl(error.failingURL());
        option.frame = m_webFrame;
        option.error = error.errorCode();
        option.errorString = error.localizedDescription();

        QWebPage::ErrorPageExtensionReturn output;
        if (!page->extension(QWebPage::ErrorPageExtension, &option, &output))
            return;

        KURL baseUrl(output.baseUrl);
        KURL failingUrl(option.url);

        WebCore::ResourceRequest request(baseUrl);
        WTF::RefPtr<WebCore::SharedBuffer> buffer = WebCore::SharedBuffer::create(output.content.constData(), output.content.length());
        WebCore::SubstituteData substituteData(buffer, output.contentType, output.encoding, failingUrl);
        m_frame->loader()->load(request, substituteData, false);
    }
}
void RWebBrowser::changeLocation()
{
    QUrl baseUrl("http://");
    QUrl url = baseUrl.resolved(QUrl(m_locationEdit->text()));
    m_webView->load(url);
    m_webView->setFocus();
}
Ejemplo n.º 5
0
bool QtQuickControlsPlugin::isLoadedFromResource() const
{
    // If one file is missing, it will load all the files from the resource
    QFile file(baseUrl().toLocalFile() + "/ApplicationWindow.qml");
    if (!file.exists())
        return true;
    return false;
}
Ejemplo n.º 6
0
bool MachinekitApplicationPlugin::isLoadedFromResource() const
{
    // If one file is missing, it will load all the files from the resource
    QFile file(baseUrl().toLocalFile() + "/ApplicationCore.qml");
    if (!file.exists())
        return true;
    return false;
}
Ejemplo n.º 7
0
bool TestHTTPServer::reply(QTcpSocket *socket, const QByteArray &fileNameIn)
{
    const QString fileName = QLatin1String(fileNameIn);
    if (m_redirects.contains(fileName)) {
        const QByteArray response
            = "HTTP/1.1 302 Found\r\nContent-length: 0\r\nContent-type: text/html; charset=UTF-8\r\nLocation: "
              + m_redirects.value(fileName).toUtf8() + "\r\n\r\n";
        socket->write(response);
        return true;
    }

    for (int ii = 0; ii < m_directories.count(); ++ii) {
        const QString &dir = m_directories.at(ii).first;
        const Mode mode = m_directories.at(ii).second;

        QString dirFile = dir + QLatin1Char('/') + fileName;

        if (!QFile::exists(dirFile)) {
            const QHash<QString, QString>::const_iterator it = m_aliases.constFind(fileName);
            if (it != m_aliases.constEnd())
                dirFile = dir + QLatin1Char('/') + it.value();
        }

        QFile file(dirFile);
        if (file.open(QIODevice::ReadOnly)) {

            if (mode == Disconnect)
                return true;

            QByteArray data = file.readAll();
            if (m_contentSubstitutedFileNames.contains(QLatin1Char('/') + fileName))
                data.replace(QByteArrayLiteral("{{ServerBaseUrl}}"), baseUrl().toString().toUtf8());

            QByteArray response
                = "HTTP/1.0 200 OK\r\nContent-type: text/html; charset=UTF-8\r\nContent-length: ";
            response += QByteArray::number(data.count());
            response += "\r\n\r\n";
            response += data;

            if (mode == Delay) {
                m_toSend.append(qMakePair(socket, response));
                QTimer::singleShot(500, this, &TestHTTPServer::sendOne);
                return false;
            } else {
                socket->write(response);
                return true;
            }
        }
    }

    socket->write("HTTP/1.0 404 Not found\r\nContent-type: text/html; charset=UTF-8\r\n\r\n");

    return true;
}
Ejemplo n.º 8
0
QNetworkReply* QPubNub::sendRequest(const QString& path) {
  QNetworkRequest request(baseUrl() + path);

  request.setHeader(QNetworkRequest::UserAgentHeader, "Qt/1.0");
  request.setRawHeader("V", "3.4");

  // Only emit signal if there are connections currently.
  if (m_trace) {
    emit trace(request.url().toString());
  }
  return m_networkAccessManager->get(request);
}
Ejemplo n.º 9
0
bool TestHTTPServer::reply(QTcpSocket *socket, const QByteArray &fileName)
{
    if (redirects.contains(fileName)) {
        QByteArray response = "HTTP/1.1 302 Found\r\nContent-length: 0\r\nContent-type: text/html; charset=UTF-8\r\nLocation: " + redirects[fileName].toUtf8() + "\r\n\r\n";
        socket->write(response);
        return true;
    }

    for (int ii = 0; ii < dirs.count(); ++ii) {
        QString dir = dirs.at(ii).first;
        Mode mode = dirs.at(ii).second;

        QString dirFile = dir + QLatin1String("/") + QLatin1String(fileName);

        if (!QFile::exists(dirFile)) {
            if (aliases.contains(fileName))
                dirFile = dir + QLatin1String("/") + aliases.value(fileName);
        }

        QFile file(dirFile);
        if (file.open(QIODevice::ReadOnly)) {

            if (mode == Disconnect)
                return true;

            QByteArray data = file.readAll();
            if (contentSubstitutedFileNames.contains("/" + fileName)) {
                data.replace(QByteArrayLiteral("{{ServerBaseUrl}}"), baseUrl().toString().toUtf8());
            }

            QByteArray response = "HTTP/1.0 200 OK\r\nContent-type: text/html; charset=UTF-8\r\nContent-length: ";
            response += QByteArray::number(data.count());
            response += "\r\n\r\n";
            response += data;

            if (mode == Delay) {
                toSend.append(qMakePair(socket, response));
                QTimer::singleShot(500, this, SLOT(sendOne()));
                return false;
            } else {
                socket->write(response);
                return true;
            }
        }
    }


    QByteArray response = "HTTP/1.0 404 Not found\r\nContent-type: text/html; charset=UTF-8\r\n\r\n";
    socket->write(response);

    return true;
}
Ejemplo n.º 10
0
int QWebFrame::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        if (_id < 13)
            qt_static_metacall(this, _c, _id, _a);
        _id -= 13;
    }
#ifndef QT_NO_PROPERTIES
      else if (_c == QMetaObject::ReadProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: *reinterpret_cast< qreal*>(_v) = textSizeMultiplier(); break;
        case 1: *reinterpret_cast< qreal*>(_v) = zoomFactor(); break;
        case 2: *reinterpret_cast< QString*>(_v) = title(); break;
        case 3: *reinterpret_cast< QUrl*>(_v) = url(); break;
        case 4: *reinterpret_cast< QUrl*>(_v) = requestedUrl(); break;
        case 5: *reinterpret_cast< QUrl*>(_v) = baseUrl(); break;
        case 6: *reinterpret_cast< QIcon*>(_v) = icon(); break;
        case 7: *reinterpret_cast< QSize*>(_v) = contentsSize(); break;
        case 8: *reinterpret_cast< QPoint*>(_v) = scrollPosition(); break;
        case 9: *reinterpret_cast< bool*>(_v) = hasFocus(); break;
        }
        _id -= 10;
    } else if (_c == QMetaObject::WriteProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: setTextSizeMultiplier(*reinterpret_cast< qreal*>(_v)); break;
        case 1: setZoomFactor(*reinterpret_cast< qreal*>(_v)); break;
        case 3: setUrl(*reinterpret_cast< QUrl*>(_v)); break;
        case 8: setScrollPosition(*reinterpret_cast< QPoint*>(_v)); break;
        }
        _id -= 10;
    } else if (_c == QMetaObject::ResetProperty) {
        _id -= 10;
    } else if (_c == QMetaObject::QueryPropertyDesignable) {
        _id -= 10;
    } else if (_c == QMetaObject::QueryPropertyScriptable) {
        _id -= 10;
    } else if (_c == QMetaObject::QueryPropertyStored) {
        _id -= 10;
    } else if (_c == QMetaObject::QueryPropertyEditable) {
        _id -= 10;
    } else if (_c == QMetaObject::QueryPropertyUser) {
        _id -= 10;
    }
#endif // QT_NO_PROPERTIES
    return _id;
}
void MangoTerminalExtensionPlugin::registerTypes(const char *uri)
{
    // @uri Mango.Terminal
    qmlRegisterType<TerminalScreen>(uri, 0, 1, "TerminalScreen");
    qmlRegisterType<ObjectDestructItem>(uri, 0, 1, "ObjectDestructItem");
    qmlRegisterType<MonoText>(uri, 0, 1, "MonoText");
    qmlRegisterType<Screen>();
    qmlRegisterType<Text>();
    qmlRegisterType<Cursor>();
    qmlRegisterType<Selection>();

    const QString filesLocation = baseUrl().toString();
    for (int i = 0; i < int(sizeof(qmldir)/sizeof(qmldir[0])); i++)
        qmlRegisterType(QUrl(filesLocation + "/" + qmldir[i].type + ".qml"), uri, qmldir[i].major, qmldir[i].minor, qmldir[i].type);
}
Ejemplo n.º 12
0
int Updater::checkManifest()
{
    QUrl baseUrl(MANIFEST_URL);
    QNetworkAccessManager manager;
    QNetworkRequest request = getNetworkRequest(baseUrl);
    QNetworkReply *rep = manager.get(request);

    while(rep->error() == QNetworkReply::NoError && !rep->isFinished())
        QCoreApplication::processEvents();

    while(true)
    {
        while(!rep->isFinished())
            QCoreApplication::processEvents();

        if(rep->error() != QNetworkReply::NoError)
            return RES_CHECK_FAILED;

        QVariant redirect = rep->attribute(QNetworkRequest::RedirectionTargetAttribute);
        if(redirect.type() != QVariant::Url)
            break;

        // redirect
        baseUrl = baseUrl.resolved(redirect.toUrl());
        request = getNetworkRequest(baseUrl);
        rep = manager.get(request);
    }

    if(rep->isFinished() && rep->size() != 0)
    {
        QString s;
        QString ver(VERSION);
        while(!rep->atEnd())
        {
            s = rep->readLine();

            QStringList parts = s.split(' ', QString::SkipEmptyParts);
            if(parts.size() < 3 || !ver.contains(parts[0]))
                continue;

            if(REVISION < parts[1].toInt())
                return RES_UPDATE_AVAILABLE;
            else
                return RES_NO_UPDATE;
        }
    }
    return RES_NO_UPDATE;
}
int QtScriptedStateMachine::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QtStateMachine::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: eventTriggered((*reinterpret_cast< const QString(*)>(_a[1]))); break;
        case 1: postNamedEvent((*reinterpret_cast< const QString(*)>(_a[1]))); break;
        case 2: executeScript((*reinterpret_cast< const QString(*)>(_a[1]))); break;
        case 3: registerSession(); break;
        case 4: unregisterSession(); break;
        default: ;
        }
        _id -= 5;
    }
#ifndef QT_NO_PROPERTIES
      else if (_c == QMetaObject::ReadProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: *reinterpret_cast< QUrl*>(_v) = baseUrl(); break;
        }
        _id -= 1;
    } else if (_c == QMetaObject::WriteProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: setBaseUrl(*reinterpret_cast< QUrl*>(_v)); break;
        }
        _id -= 1;
    } else if (_c == QMetaObject::ResetProperty) {
        _id -= 1;
    } else if (_c == QMetaObject::QueryPropertyDesignable) {
        _id -= 1;
    } else if (_c == QMetaObject::QueryPropertyScriptable) {
        _id -= 1;
    } else if (_c == QMetaObject::QueryPropertyStored) {
        _id -= 1;
    } else if (_c == QMetaObject::QueryPropertyEditable) {
        _id -= 1;
    } else if (_c == QMetaObject::QueryPropertyUser) {
        _id -= 1;
    }
#endif // QT_NO_PROPERTIES
    return _id;
}
Ejemplo n.º 14
0
// -----------------------------------------------------------------------------
// CUpnpDevice::ConcatWithUrlBase
// -----------------------------------------------------------------------------
//
EXPORT_C HBufC8* CUpnpDevice::ConcatWithUrlBaseL(const TDesC8& aUrl)
    {
    TPtrC8 baseUrl( UrlBase() );

    if( baseUrl.Length() == 0 ||
            aUrl.Length() == 0 ||
            aUrl.Find( KHttp ) == 0 ||
            ( aUrl[0] == KSlash8()[0] && !( baseUrl.Find( KHttp ) == 0 ) ) )

        {
        return aUrl.AllocL();
        }

    HBufC8* result( NULL );
    TBool slashInBase( baseUrl[baseUrl.Length() - 1] == KSlash8()[0] );
    TBool slashInUrl( aUrl[0] == KSlash8()[0] );
    TInt length( 0 );

    if( slashInBase && slashInUrl )
        {
        length = baseUrl.Length() + aUrl.Length() - 1;
        result = HBufC8::NewL( length );
        TPtr8 resultPtr( result->Des() );
        resultPtr.Append( baseUrl.Left( baseUrl.Length() - 1 ));
        }
    else if( slashInBase != slashInUrl )
        {
        length = baseUrl.Length() + aUrl.Length();
        result = HBufC8::NewL( length );
        TPtr8 resultPtr( result->Des() );
        resultPtr.Append( baseUrl );
        }
    else
        {
        length = baseUrl.Length() + aUrl.Length() + 1;
        result = HBufC8::NewL( length );
        TPtr8 resultPtr( result->Des() );
        resultPtr.Append( baseUrl );
        resultPtr.Append( '/' );
        }

    result->Des().Append( aUrl );
    return result;
    }
Ejemplo n.º 15
0
QUrl setUpRemoteTestDir(const QString& testFile)
{
    QWidget* authWindow = 0;
    if (qgetenv("GV_REMOTE_TESTS_BASE_URL").isEmpty()) {
        qWarning() << "Environment variable GV_REMOTE_TESTS_BASE_URL not set: remote tests disabled";
        return QUrl();
    }

    QUrl baseUrl(QString::fromLocal8Bit(qgetenv("GV_REMOTE_TESTS_BASE_URL")));
    baseUrl = baseUrl.adjusted(QUrl::StripTrailingSlash);
    baseUrl.setPath(baseUrl.path() + "/gwenview-remote-tests");

    KIO::StatJob *statJob = KIO::stat(baseUrl, KIO::StatJob::DestinationSide, 0);
    KJobWidgets::setWindow(statJob, authWindow);

    if (statJob->exec()) {
        KIO::DeleteJob *deleteJob = KIO::del(baseUrl);
        KJobWidgets::setWindow(deleteJob, authWindow);
        deleteJob->exec();
    }

    KIO::MkdirJob *mkdirJob = KIO::mkdir(baseUrl);
    KJobWidgets::setWindow(mkdirJob, authWindow);
    if (!mkdirJob->exec()) {
        qCritical() << "Could not create dir" << baseUrl << ":" << mkdirJob->errorString();
        return QUrl();
    }

    if (!testFile.isEmpty()) {
        QUrl dstUrl = baseUrl;
        dstUrl = dstUrl.adjusted(QUrl::StripTrailingSlash);
        dstUrl.setPath(dstUrl.path() + '/' + testFile);
        KIO::FileCopyJob *copyJob = KIO::file_copy(urlForTestFile(testFile), dstUrl);
        KJobWidgets::setWindow(copyJob, authWindow);
        if (!copyJob->exec()) {
            qCritical() << "Could not copy" << testFile << "to" << dstUrl << ":" << copyJob->errorString();
            return QUrl();
        }
    }

    return baseUrl;
}
Ejemplo n.º 16
0
KexiFileWidget::~KexiFileWidget()
{
    kDebug() << d->recentDirClass;
    if (!d->recentDirClass.isEmpty()) {
        QString hf = highlightedFile();
        KUrl dir;
        if (hf.isEmpty()) {
            dir = baseUrl();
        }
        else {
            QFileInfo fi(hf);
            QString dirStr = fi.isDir() ? fi.absoluteFilePath() : fi.dir().absolutePath();
            dir = KUrl::fromPath(dirStr);
        }
        kDebug() << dir;
        kDebug() << highlightedFile();
        if (!dir.isEmpty())
            KRecentDirs::add(d->recentDirClass, dir.url());
    }
    delete d;
}
void RWebBrowser::finishLoading(bool)
{
//    m_progress = 100;
    //    adjustTitle();

    QWebFrame* frame = m_webView->page()->mainFrame();
    if (frame!=NULL)
    {
        QWebElementCollection elements = frame->findAllElements("a");
        foreach (QWebElement element, elements)
        {
            QStringList attributesList = element.attributeNames();
            foreach (QString attributeName, attributesList)
            {
                if (attributeName != "href") break;
                QRegExp rx(".*.mp1$|.*.mp2$|.*.mp3$|.*.mp4$|.*.mpg$|.*.mpa$|.*.wav$|.*.ogg$|.*.m3u$|.*.pls$|.*.xspf$");
                rx.setCaseSensitivity(Qt::CaseInsensitive);
                if (element.attribute(attributeName).contains(rx))
                {

                    QUrl baseUrl(m_webView->url());
                    QUrl relativeUrl = QUrl::fromEncoded(element.attribute(attributeName).toUtf8(), QUrl::StrictMode);
                    QString streamName = baseUrl.resolved(relativeUrl).toString();

                    qDebug() << streamName;

                    //test button

                    QPushButton *testButton = new QPushButton(streamName);
                    m_buttonLayout->addWidget(testButton);

                    //


                }
            }
        }
Ejemplo n.º 18
0
KexiFileWidget::~KexiFileWidget()
{
    kDebug() << d->recentDirClass;
    if (!d->recentDirClass.isEmpty()) {
        QString hf = highlightedFile();
        KUrl dir;
        if (hf.isEmpty()) {
            dir = baseUrl();
        }
        else {
            QFileInfo fi(hf);
            QString dirStr = fi.isDir() ? fi.absoluteFilePath() : fi.dir().absolutePath();
            dir = KUrl::fromPath(dirStr);
        }
        kDebug() << dir;
        kDebug() << highlightedFile();
        if (!dir.isEmpty())
            KRecentDirs::add(d->recentDirClass, dir.url());
    }
    delete d;
//Qt4 #ifdef Q_WS_WIN
// saveLastVisitedPath(currentFileName());
//#endif
}
Ejemplo n.º 19
0
int QWebFrame::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: javaScriptWindowObjectCleared(); break;
        case 1: provisionalLoad(); break;
        case 2: titleChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break;
        case 3: urlChanged((*reinterpret_cast< const QUrl(*)>(_a[1]))); break;
        case 4: initialLayoutCompleted(); break;
        case 5: iconChanged(); break;
        case 6: contentsSizeChanged((*reinterpret_cast< const QSize(*)>(_a[1]))); break;
        case 7: loadStarted(); break;
        case 8: loadFinished((*reinterpret_cast< bool(*)>(_a[1]))); break;
        case 9: { QVariant _r = evaluateJavaScript((*reinterpret_cast< const QString(*)>(_a[1])));
            if (_a[0]) *reinterpret_cast< QVariant*>(_a[0]) = _r; }  break;
        case 10: print((*reinterpret_cast< QPrinter*(*)>(_a[1]))); break;
        default: ;
        }
        _id -= 11;
    }
#ifndef QT_NO_PROPERTIES
      else if (_c == QMetaObject::ReadProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: *reinterpret_cast< qreal*>(_v) = textSizeMultiplier(); break;
        case 1: *reinterpret_cast< qreal*>(_v) = zoomFactor(); break;
        case 2: *reinterpret_cast< QString*>(_v) = title(); break;
        case 3: *reinterpret_cast< QUrl*>(_v) = url(); break;
        case 4: *reinterpret_cast< QUrl*>(_v) = requestedUrl(); break;
        case 5: *reinterpret_cast< QUrl*>(_v) = baseUrl(); break;
        case 6: *reinterpret_cast< QIcon*>(_v) = icon(); break;
        case 7: *reinterpret_cast< QSize*>(_v) = contentsSize(); break;
        case 8: *reinterpret_cast< QPoint*>(_v) = scrollPosition(); break;
        case 9: *reinterpret_cast< bool*>(_v) = hasFocus(); break;
        }
        _id -= 10;
    } else if (_c == QMetaObject::WriteProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: setTextSizeMultiplier(*reinterpret_cast< qreal*>(_v)); break;
        case 1: setZoomFactor(*reinterpret_cast< qreal*>(_v)); break;
        case 3: setUrl(*reinterpret_cast< QUrl*>(_v)); break;
        case 8: setScrollPosition(*reinterpret_cast< QPoint*>(_v)); break;
        }
        _id -= 10;
    } else if (_c == QMetaObject::ResetProperty) {
        _id -= 10;
    } else if (_c == QMetaObject::QueryPropertyDesignable) {
        _id -= 10;
    } else if (_c == QMetaObject::QueryPropertyScriptable) {
        _id -= 10;
    } else if (_c == QMetaObject::QueryPropertyStored) {
        _id -= 10;
    } else if (_c == QMetaObject::QueryPropertyEditable) {
        _id -= 10;
    } else if (_c == QMetaObject::QueryPropertyUser) {
        _id -= 10;
    }
#endif // QT_NO_PROPERTIES
    return _id;
}
Ejemplo n.º 20
0
QString MachinekitApplicationPlugin::fileLocation() const
{
    if (isLoadedFromResource())
        return "qrc:/Machinekit/Application";
    return baseUrl().toString();
}
Ejemplo n.º 21
0
QUrl TestHTTPServer::url(const QString &documentPath) const
{
    return baseUrl().resolved(documentPath);
}
Ejemplo n.º 22
0
bool XMLTVParser::parseFile(
    QString filename, ChannelInfoList *chanlist,
    QMap<QString, QList<ProgInfo> > *proglist)
{
    QDomDocument doc;
    QFile f;

    if (!dash_open(f, filename, QIODevice::ReadOnly))
    {
        LOG(VB_GENERAL, LOG_ERR,
            QString("Error unable to open '%1' for reading.") .arg(filename));
        return false;
    }

    QString errorMsg = "unknown";
    int errorLine = 0;
    int errorColumn = 0;

    if (!doc.setContent(&f, &errorMsg, &errorLine, &errorColumn))
    {
        LOG(VB_GENERAL, LOG_ERR, QString("Error in %1:%2: %3")
            .arg(errorLine).arg(errorColumn).arg(errorMsg));

        f.close();
        return true;
    }

    f.close();

    QDomElement docElem = doc.documentElement();

    QUrl baseUrl(docElem.attribute("source-data-url", ""));
    //QUrl sourceUrl(docElem.attribute("source-info-url", ""));

    QString aggregatedTitle;
    QString aggregatedDesc;

    QDomNode n = docElem.firstChild();
    while (!n.isNull())
    {
        QDomElement e = n.toElement();
        if (!e.isNull())
        {
            if (e.tagName() == "channel")
            {
                ChannelInfo *chinfo = parseChannel(e, baseUrl);
                if (!chinfo->xmltvid.isEmpty())
                    chanlist->push_back(*chinfo);
                delete chinfo;
            }
            else if (e.tagName() == "programme")
            {
                ProgInfo *pginfo = parseProgram(e);

                if (pginfo->startts == pginfo->endts)
                {
                    LOG(VB_GENERAL, LOG_WARNING, QString("Invalid programme (%1), "
                                                        "identical start and end "
                                                        "times, skipping")
                                                        .arg(pginfo->title));
                }
                else
                {
                    if (pginfo->clumpidx.isEmpty())
                        (*proglist)[pginfo->channel].push_back(*pginfo);
                    else
                    {
                        /* append all titles/descriptions from one clump */
                        if (pginfo->clumpidx.toInt() == 0)
                        {
                            aggregatedTitle.clear();
                            aggregatedDesc.clear();
                        }

                        if (!pginfo->title.isEmpty())
                        {
                            if (!aggregatedTitle.isEmpty())
                                aggregatedTitle.append(" | ");
                            aggregatedTitle.append(pginfo->title);
                        }

                        if (!pginfo->description.isEmpty())
                        {
                            if (!aggregatedDesc.isEmpty())
                                aggregatedDesc.append(" | ");
                            aggregatedDesc.append(pginfo->description);
                        }
                        if (pginfo->clumpidx.toInt() ==
                            pginfo->clumpmax.toInt() - 1)
                        {
                            pginfo->title = aggregatedTitle;
                            pginfo->description = aggregatedDesc;
                            (*proglist)[pginfo->channel].push_back(*pginfo);
                        }
                    }
                }
                delete pginfo;
            }
        }
        n = n.nextSibling();
    }

    return true;
}
Ejemplo n.º 23
0
void TestPreferences::testPreferences()
{
	auto pref = SettingsObjectWrapper::instance();
	pref->load();

	auto cloud = pref->cloud_storage;
	cloud->setBackgroundSync(true);
	TEST(cloud->backgroundSync(), true);
	cloud->setBackgroundSync(false);
	TEST(cloud->backgroundSync(), false);

	cloud->setBaseUrl("test_one");
	TEST(cloud->baseUrl(), QStringLiteral("test_one"));
	cloud->setBaseUrl("test_two");
	TEST(cloud->baseUrl(), QStringLiteral("test_two"));

	cloud->setEmail("*****@*****.**");
	TEST(cloud->email(), QStringLiteral("*****@*****.**"));
	cloud->setEmail("*****@*****.**");
	TEST(cloud->email(), QStringLiteral("*****@*****.**"));

	cloud->setGitLocalOnly(true);
	TEST(cloud->gitLocalOnly(), true);
	cloud->setGitLocalOnly(false);
	TEST(cloud->gitLocalOnly(), false);

	// Why there's new password and password on the prefs?
	cloud->setNewPassword("ABCD");
	TEST(cloud->newPassword(), QStringLiteral("ABCD"));
	cloud->setNewPassword("ABCDE");
	TEST(cloud->newPassword(), QStringLiteral("ABCDE"));

	cloud->setPassword("ABCDE");
	TEST(cloud->password(), QStringLiteral("ABCDE"));
	cloud->setPassword("ABCABC");
	TEST(cloud->password(), QStringLiteral("ABCABC"));

	cloud->setSavePasswordLocal(true);
	TEST(cloud->savePasswordLocal(), true);
	cloud->setSavePasswordLocal(false);
	TEST(cloud->savePasswordLocal(), false);

	// Why this is short and not bool?
	cloud->setSaveUserIdLocal(1);
	TEST(cloud->saveUserIdLocal(), (short)1);
	cloud->setSaveUserIdLocal(0);
	TEST(cloud->saveUserIdLocal(), (short)0);

	cloud->setUserId("Tomaz");
	TEST(cloud->userId(), QStringLiteral("Tomaz"));
	cloud->setUserId("Zamot");
	TEST(cloud->userId(), QStringLiteral("Zamot"));

	cloud->setVerificationStatus(0);
	TEST(cloud->verificationStatus(), (short)0);
	cloud->setVerificationStatus(1);
	TEST(cloud->verificationStatus(), (short)1);

	auto tecDetails = pref->techDetails;
	tecDetails->setModp02(0.2);
	TEST(tecDetails->modp02(), 0.2);
	tecDetails->setModp02(1.0);
	TEST(tecDetails->modp02(), 1.0);

	tecDetails->setGflow(2);
	TEST(tecDetails->gflow(), 2);
	tecDetails->setGflow(3);
	TEST(tecDetails->gflow(), 3);

	tecDetails->setGfhigh(4);
	TEST(tecDetails->gfhigh(), 4);
	tecDetails->setGfhigh(5);
	TEST(tecDetails->gfhigh(), 5);

	tecDetails->setVpmbConservatism(5);
	TEST(tecDetails->vpmbConservatism(), (short)5);
	tecDetails->setVpmbConservatism(6);
	TEST(tecDetails->vpmbConservatism(), (short)6);

	tecDetails->setEad(true);
	TEST(tecDetails->ead(), true);
	tecDetails->setMod(true);
	TEST(tecDetails->mod(), true);
	tecDetails->setDCceiling(true);
	TEST(tecDetails->dcceiling(), true);
	tecDetails->setRedceiling(true);
	TEST(tecDetails->redceiling(), true);
	tecDetails->setCalcceiling(true);
	TEST(tecDetails->calcceiling(), true);
	tecDetails->setCalcceiling3m(true);
	TEST(tecDetails->calcceiling3m(), true);
	tecDetails->setCalcalltissues(true);
	TEST(tecDetails->calcalltissues(), true);
	tecDetails->setCalcndltts(true);
	TEST(tecDetails->calcndltts(), true);
	tecDetails->setBuehlmann(true);
	TEST(tecDetails->buehlmann(), true);
	tecDetails->setHRgraph(true);
	TEST(tecDetails->hrgraph(), true);
	tecDetails->setTankBar(true);
	TEST(tecDetails->tankBar(), true);
	tecDetails->setPercentageGraph(true);
	TEST(tecDetails->percentageGraph(), true);
	tecDetails->setRulerGraph(true);
	TEST(tecDetails->rulerGraph(), true);
	tecDetails->setShowCCRSetpoint(true);
	TEST(tecDetails->showCCRSetpoint(), true);
	tecDetails->setShowCCRSensors(true);
	TEST(tecDetails->showCCRSensors(), true);
	tecDetails->setZoomedPlot(true);
	TEST(tecDetails->zoomedPlot(), true);
	tecDetails->setShowSac(true);
	TEST(tecDetails->showSac(), true);
	tecDetails->setGfLowAtMaxDepth(true);
	TEST(tecDetails->gfLowAtMaxDepth(), true);
	tecDetails->setDisplayUnusedTanks(true);
	TEST(tecDetails->displayUnusedTanks(), true);
	tecDetails->setShowAverageDepth(true);
	TEST(tecDetails->showAverageDepth(), true);
	tecDetails->setShowPicturesInProfile(true);
	TEST(tecDetails->showPicturesInProfile(), true);

	tecDetails->setEad(false);
	TEST(tecDetails->ead(), false);
	tecDetails->setMod(false);
	TEST(tecDetails->mod(), false);
	tecDetails->setDCceiling(false);
	TEST(tecDetails->dcceiling(), false);
	tecDetails->setRedceiling(false);
	TEST(tecDetails->redceiling(), false);
	tecDetails->setCalcceiling(false);
	TEST(tecDetails->calcceiling(), false);
	tecDetails->setCalcceiling3m(false);
	TEST(tecDetails->calcceiling3m(), false);
	tecDetails->setCalcalltissues(false);
	TEST(tecDetails->calcalltissues(), false);
	tecDetails->setCalcndltts(false);
	TEST(tecDetails->calcndltts(), false);
	tecDetails->setBuehlmann(false);
	TEST(tecDetails->buehlmann(), false);
	tecDetails->setHRgraph(false);
	TEST(tecDetails->hrgraph(), false);
	tecDetails->setTankBar(false);
	TEST(tecDetails->tankBar(), false);
	tecDetails->setPercentageGraph(false);
	TEST(tecDetails->percentageGraph(), false);
	tecDetails->setRulerGraph(false);
	TEST(tecDetails->rulerGraph(), false);
	tecDetails->setShowCCRSetpoint(false);
	TEST(tecDetails->showCCRSetpoint(), false);
	tecDetails->setShowCCRSensors(false);
	TEST(tecDetails->showCCRSensors(), false);
	tecDetails->setZoomedPlot(false);
	TEST(tecDetails->zoomedPlot(), false);
	tecDetails->setShowSac(false);
	TEST(tecDetails->showSac(), false);
	tecDetails->setGfLowAtMaxDepth(false);
	TEST(tecDetails->gfLowAtMaxDepth(), false);
	tecDetails->setDisplayUnusedTanks(false);
	TEST(tecDetails->displayUnusedTanks(), false);
	tecDetails->setShowAverageDepth(false);
	TEST(tecDetails->showAverageDepth(), false);
	tecDetails->setShowPicturesInProfile(false);
	TEST(tecDetails->showPicturesInProfile(), false);

	auto pp = pref->pp_gas;
	pp->setShowPn2(false);
	pp->setShowPhe(false);
	pp->setShowPo2(false);
	pp->setPo2Threshold(1.0);
	pp->setPn2Threshold(2.0);
	pp->setPheThreshold(3.0);

	TEST(pp->showPn2(), (short) false);
	TEST(pp->showPhe(), (short) false);
	TEST(pp->showPo2(), (short) false);
	TEST(pp->pn2Threshold(), 2.0);
	TEST(pp->pheThreshold(), 3.0);
	TEST(pp->po2Threshold(), 1.0);

	pp->setShowPn2(true);
	pp->setShowPhe(true);
	pp->setShowPo2(true);
	pp->setPo2Threshold(4.0);
	pp->setPn2Threshold(5.0);
	pp->setPheThreshold(6.0);

	TEST(pp->showPn2(), (short) true);
	TEST(pp->showPhe(), (short) true);
	TEST(pp->showPo2(), (short) true);
	TEST(pp->pn2Threshold(), 5.0);
	TEST(pp->pheThreshold(), 6.0);
	TEST(pp->po2Threshold(), 4.0);

	auto fb = pref->facebook;
	fb->setAccessToken("rand-access-token");
	fb->setUserId("tomaz-user-id");
	fb->setAlbumId("album-id");

	TEST(fb->accessToken(),QStringLiteral("rand-access-token"));
	TEST(fb->userId(),     QStringLiteral("tomaz-user-id"));
	TEST(fb->albumId(),    QStringLiteral("album-id"));

	fb->setAccessToken("rand-access-token-2");
	fb->setUserId("tomaz-user-id-2");
	fb->setAlbumId("album-id-2");

	TEST(fb->accessToken(),QStringLiteral("rand-access-token-2"));
	TEST(fb->userId(),     QStringLiteral("tomaz-user-id-2"));
	TEST(fb->albumId(),    QStringLiteral("album-id-2"));

	auto geo = pref->geocoding;
	geo->setEnableGeocoding(true);
	geo->setParseDiveWithoutGps(true);
	geo->setTagExistingDives(true);

	TEST(geo->enableGeocoding(),true);
	TEST(geo->parseDiveWithoutGps(),true);
	TEST(geo->tagExistingDives(),true);

	geo->setFirstTaxonomyCategory(TC_NONE);
	geo->setSecondTaxonomyCategory(TC_OCEAN);
	geo->setThirdTaxonomyCategory(TC_COUNTRY);

	TEST(geo->firstTaxonomyCategory(), TC_NONE);
	TEST(geo->secondTaxonomyCategory(), TC_OCEAN);
	TEST(geo->thirdTaxonomyCategory(), TC_COUNTRY);

	geo->setEnableGeocoding(false);
	geo->setParseDiveWithoutGps(false);
	geo->setTagExistingDives(false);

	TEST(geo->enableGeocoding(),false);
	TEST(geo->parseDiveWithoutGps(),false);
	TEST(geo->tagExistingDives(),false);

	geo->setFirstTaxonomyCategory(TC_OCEAN);
	geo->setSecondTaxonomyCategory(TC_COUNTRY);
	geo->setThirdTaxonomyCategory(TC_NONE);

	TEST(geo->firstTaxonomyCategory(), TC_OCEAN);
	TEST(geo->secondTaxonomyCategory(), TC_COUNTRY);
	TEST(geo->thirdTaxonomyCategory(), TC_NONE);

	auto proxy = pref->proxy;
	proxy->setType(2);
	proxy->setPort(80);
	proxy->setAuth(true);
	proxy->setHost("localhost");
	proxy->setUser("unknown");
	proxy->setPass("secret");

	TEST(proxy->type(),2);
	TEST(proxy->port(),80);
	TEST(proxy->auth(),true);
	TEST(proxy->host(),QStringLiteral("localhost"));
	TEST(proxy->user(),QStringLiteral("unknown"));
	TEST(proxy->pass(),QStringLiteral("secret"));

	proxy->setType(3);
	proxy->setPort(8080);
	proxy->setAuth(false);
	proxy->setHost("127.0.0.1");
	proxy->setUser("unknown_1");
	proxy->setPass("secret_1");

	TEST(proxy->type(),3);
	TEST(proxy->port(),8080);
	TEST(proxy->auth(),false);
	TEST(proxy->host(),QStringLiteral("127.0.0.1"));
	TEST(proxy->user(),QStringLiteral("unknown_1"));
	TEST(proxy->pass(),QStringLiteral("secret_1"));

	auto planner = pref->planner_settings;
	planner->setLastStop(true);
	planner->setVerbatimPlan(true);
	planner->setDisplayRuntime(true);
	planner->setDisplayDuration(true);
	planner->setDisplayTransitions(true);
	planner->setDoo2breaks(true);
	planner->setDropStoneMode(true);
	planner->setSafetyStop(true);
	planner->setSwitchAtRequiredStop(true);

	planner->setAscrate75(1);
	planner->setAscrate50(2);
	planner->setAscratestops(3);
	planner->setAscratelast6m(4);
	planner->setDescrate(5);
	planner->setBottompo2(6);
	planner->setDecopo2(7);
	planner->setBestmixend(8);
	planner->setReserveGas(9);
	planner->setMinSwitchDuration(10);
	planner->setBottomSac(11);
	planner->setDecoSac(12);

	planner->setDecoMode(BUEHLMANN);

	TEST(planner->lastStop(),true);
	TEST(planner->verbatimPlan(),true);
	TEST(planner->displayRuntime(),true);
	TEST(planner->displayDuration(),true);
	TEST(planner->displayTransitions(),true);
	TEST(planner->doo2breaks(),true);
	TEST(planner->dropStoneMode(),true);
	TEST(planner->safetyStop(),true);
	TEST(planner->switchAtRequiredStop(),true);

	TEST(planner->ascrate75(),1);
	TEST(planner->ascrate50(),2);
	TEST(planner->ascratestops(),3);
	TEST(planner->ascratelast6m(),4);
	TEST(planner->descrate(),5);
	TEST(planner->bottompo2(),6);
	TEST(planner->decopo2(),7);
	TEST(planner->bestmixend(),8);
	TEST(planner->reserveGas(),9);
	TEST(planner->minSwitchDuration(),10);
	TEST(planner->bottomSac(),11);
	TEST(planner->decoSac(),12);

	TEST(planner->decoMode(),BUEHLMANN);

	planner->setLastStop(false);
	planner->setVerbatimPlan(false);
	planner->setDisplayRuntime(false);
	planner->setDisplayDuration(false);
	planner->setDisplayTransitions(false);
	planner->setDoo2breaks(false);
	planner->setDropStoneMode(false);
	planner->setSafetyStop(false);
	planner->setSwitchAtRequiredStop(false);

	planner->setAscrate75(11);
	planner->setAscrate50(12);
	planner->setAscratestops(13);
	planner->setAscratelast6m(14);
	planner->setDescrate(15);
	planner->setBottompo2(16);
	planner->setDecopo2(17);
	planner->setBestmixend(18);
	planner->setReserveGas(19);
	planner->setMinSwitchDuration(110);
	planner->setBottomSac(111);
	planner->setDecoSac(112);

	planner->setDecoMode(RECREATIONAL);

	TEST(planner->lastStop(),false);
	TEST(planner->verbatimPlan(),false);
	TEST(planner->displayRuntime(),false);
	TEST(planner->displayDuration(),false);
	TEST(planner->displayTransitions(),false);
	TEST(planner->doo2breaks(),false);
	TEST(planner->dropStoneMode(),false);
	TEST(planner->safetyStop(),false);
	TEST(planner->switchAtRequiredStop(),false);

	TEST(planner->ascrate75(),11);
	TEST(planner->ascrate50(),12);
	TEST(planner->ascratestops(),13);
	TEST(planner->ascratelast6m(),14);
	TEST(planner->descrate(),15);
	TEST(planner->bottompo2(),16);
	TEST(planner->decopo2(),17);
	TEST(planner->bestmixend(),18);
	TEST(planner->reserveGas(),19);
	TEST(planner->minSwitchDuration(),110);
	TEST(planner->bottomSac(),111);
	TEST(planner->decoSac(),112);

	TEST(planner->decoMode(),RECREATIONAL);

	auto units = pref->unit_settings;
	units->setLength(0);
	units->setPressure(0);
	units->setVolume(0);
	units->setTemperature(0);
	units->setWeight(0);
	units->setVerticalSpeedTime(0);
	units->setUnitSystem(QStringLiteral("metric"));
	units->setCoordinatesTraditional(false);

	TEST(units->length(),0);
	TEST(units->pressure(),0);
	TEST(units->volume(),0);
	TEST(units->temperature(),0);
	TEST(units->weight(),0);
	TEST(units->verticalSpeedTime(),0);
	TEST(units->unitSystem(),QStringLiteral("metric"));
	TEST(units->coordinatesTraditional(),false);

	units->setLength(1);
	units->setPressure(1);
	units->setVolume(1);
	units->setTemperature(1);
	units->setWeight(1);
	units->setVerticalSpeedTime(1);
	units->setUnitSystem(QStringLiteral("fake-metric-system"));
	units->setCoordinatesTraditional(true);

	TEST(units->length(),1);
	TEST(units->pressure(),1);
	TEST(units->volume(),1);
	TEST(units->temperature(),1);
	TEST(units->weight(),1);
	TEST(units->verticalSpeedTime(),1);
	TEST(units->unitSystem(),QStringLiteral("personalized"));
	TEST(units->coordinatesTraditional(),true);

	auto general = pref->general_settings;
	general->setDefaultFilename       ("filename");
	general->setDefaultCylinder       ("cylinder_2");
	//TODOl: Change this to a enum. 	// This is 'undefined', it will need to figure out later between no_file or use_deault file.
	general->setDefaultFileBehavior   (0);
	general->setDefaultSetPoint       (0);
	general->setO2Consumption         (0);
	general->setPscrRatio             (0);
	general->setUseDefaultFile        (true);

	TEST(general->defaultFilename(), QStringLiteral("filename"));
	TEST(general->defaultCylinder(), QStringLiteral("cylinder_2"));
	TEST(general->defaultFileBehavior(), (short) LOCAL_DEFAULT_FILE); // since we have a default file, here it returns
	TEST(general->defaultSetPoint(), 0);
	TEST(general->o2Consumption(), 0);
	TEST(general->pscrRatio(), 0);
	TEST(general->useDefaultFile(), true);

	general->setDefaultFilename       ("no_file_name");
	general->setDefaultCylinder       ("cylinder_1");
	//TODOl: Change this to a enum.
	general->setDefaultFileBehavior   (CLOUD_DEFAULT_FILE);

	general->setDefaultSetPoint       (1);
	general->setO2Consumption         (1);
	general->setPscrRatio             (1);
	general->setUseDefaultFile        (false);

	TEST(general->defaultFilename(), QStringLiteral("no_file_name"));
	TEST(general->defaultCylinder(), QStringLiteral("cylinder_1"));
	TEST(general->defaultFileBehavior(), (short) CLOUD_DEFAULT_FILE);
	TEST(general->defaultSetPoint(), 1);
	TEST(general->o2Consumption(), 1);
	TEST(general->pscrRatio(), 1);
	TEST(general->useDefaultFile(), false);

	auto display = pref->display_settings;
	display->setDivelistFont("comic");
	display->setFontSize(10.0);
	display->setDisplayInvalidDives(true);

	TEST(display->divelistFont(),QStringLiteral("comic"));
	TEST(display->fontSize(), 10.0);
	TEST(display->displayInvalidDives(),(short) true); //TODO: this is true / false.

	display->setDivelistFont("helvetica");
	display->setFontSize(14.0);
	display->setDisplayInvalidDives(false);

	TEST(display->divelistFont(),QStringLiteral("helvetica"));
	TEST(display->fontSize(), 14.0);
	TEST(display->displayInvalidDives(),(short) false);

	auto language = pref->language_settings;
	language->setLangLocale         ("en_US");
	language->setLanguage           ("en");
	language->setTimeFormat         ("hh:mm");
	language->setDateFormat         ("dd/mm/yy");
	language->setDateFormatShort    ("dd/mm");
	language->setTimeFormatOverride (false);
	language->setDateFormatOverride (false);
	language->setUseSystemLanguage  (false);

	TEST(language->langLocale(), QStringLiteral("en_US"));
	TEST(language->language(), QStringLiteral("en"));
	TEST(language->timeFormat(), QStringLiteral("hh:mm"));
	TEST(language->dateFormat(), QStringLiteral("dd/mm/yy"));
	TEST(language->dateFormatShort(), QStringLiteral("dd/mm"));
	TEST(language->timeFormatOverride(), false);
	TEST(language->dateFormatOverride(), false);
	TEST(language->useSystemLanguage(), false);

	language->setLangLocale         ("en_EN");
	language->setLanguage           ("br");
	language->setTimeFormat         ("mm:hh");
	language->setDateFormat         ("yy/mm/dd");
	language->setDateFormatShort    ("dd/yy");
	language->setTimeFormatOverride (true);
	language->setDateFormatOverride (true);
	language->setUseSystemLanguage  (true);

	TEST(language->langLocale(), QStringLiteral("en_EN"));
	TEST(language->language(), QStringLiteral("br"));
	TEST(language->timeFormat(), QStringLiteral("mm:hh"));
	TEST(language->dateFormat(), QStringLiteral("yy/mm/dd"));
	TEST(language->dateFormatShort(), QStringLiteral("dd/yy"));
	TEST(language->timeFormatOverride(),true);
	TEST(language->dateFormatOverride(),true);
	TEST(language->useSystemLanguage(), true);

	pref->animation_settings->setAnimationSpeed(20);
	TEST(pref->animation_settings->animationSpeed(), 20);
	pref->animation_settings->setAnimationSpeed(30);
	TEST(pref->animation_settings->animationSpeed(), 30);

	auto location = pref->location_settings;
	location->setTimeThreshold(10);
	location->setDistanceThreshold(20);

	TEST(location->timeThreshold(), 10);
	TEST(location->distanceThreshold(), 20);

	location->setTimeThreshold(30);
	location->setDistanceThreshold(40);

	TEST(location->timeThreshold(), 30);
	TEST(location->distanceThreshold(), 40);

	auto update = pref->update_manager_settings;
	QDate date = QDate::currentDate();

	update->setDontCheckForUpdates(true);
	update->setLastVersionUsed("tomaz-1");
	update->setNextCheck(date);

	TEST(update->dontCheckForUpdates(), true);
	TEST(update->lastVersionUsed(), QStringLiteral("tomaz-1"));
	TEST(update->nextCheck(), date);

	date.addDays(3);
	update->setDontCheckForUpdates(false);
	update->setLastVersionUsed("tomaz-2");
	update->setNextCheck(date);

	TEST(update->dontCheckForUpdates(), false);
	TEST(update->lastVersionUsed(), QStringLiteral("tomaz-2"));
	TEST(update->nextCheck(), date);

	auto dc = pref->dive_computer_settings;
	dc->setDevice("TomazComputer");
	TEST(dc->dc_device(), QStringLiteral("TomazComputer"));
	dc->setDevice("Deepwater");
	TEST(dc->dc_device(), QStringLiteral("Deepwater"));

	dc->setDownloadMode(0);
	TEST(dc->downloadMode(), 0);
	dc->setDownloadMode(1);
	TEST(dc->downloadMode(), 1);

	dc->setProduct("Thingy1");
	TEST(dc->dc_product(), QStringLiteral("Thingy1"));
	dc->setProduct("Thingy2");
	TEST(dc->dc_product(), QStringLiteral("Thingy2"));

	dc->setVendor("Sharewater");
	TEST(dc->dc_vendor(), QStringLiteral("Sharewater"));
	dc->setVendor("OSTS");
	TEST(dc->dc_vendor(), QStringLiteral("OSTS"));
}
Ejemplo n.º 24
0
char *dos_qqmlcontext_baseUrl(const ::DosQQmlContext *vptr)
{
    auto context = static_cast<const QQmlContext *>(vptr);
    QUrl url = context->baseUrl();
    return convert_to_cstring(url.toString());
}
Ejemplo n.º 25
0
QString QtQuickControlsPlugin::fileLocation() const
{
    if (isLoadedFromResource())
        return "qrc:/QtQuick/Controls";
    return baseUrl().toString();
}
Ejemplo n.º 26
0
bool KexiFileWidget::checkSelectedFile()
{
    kDebug() << "d->highlightedUrl: " << d->highlightedUrl;

    if (!locationEdit()->lineEdit()->text().isEmpty()) {
        kDebug() << locationEdit()->lineEdit()->text();
        //kDebug() << locationEdit()->urls();
        kDebug() << baseUrl();

        d->highlightedUrl = baseUrl();
        const QString firstUrl(locationEdit()->lineEdit()->text());   // FIXME: find first...
        if (QDir::isAbsolutePath(firstUrl))
            d->highlightedUrl = KUrl::fromPath(firstUrl);
        else
            d->highlightedUrl.addPath(firstUrl);
    }

    kDebug() << "d->highlightedUrl: " << d->highlightedUrl;
    if (d->highlightedUrl.isEmpty()) {
        KMessageBox::error(this, i18n("Enter a filename."));
        return false;
    }

    if (!currentFilter().isEmpty()) {
        if (d->mode & SavingFileBasedDB) {
            const QStringList filters( currentFilter().split(' ') );
            QString path = highlightedFile();
            kDebug()<< "filter:" << filters << "path:" << path;
            QString ext( QFileInfo(path).suffix() );
            bool hasExtension = false;
            foreach (const QString& filter, filters) {
                const QString f( filter.trimmed() );
                hasExtension = !f.mid(2).isEmpty() && ext==f.mid(2);
                if (hasExtension)
                break;
            }
            if (!hasExtension) {
                //no extension: add one
                QString defaultExtension( d->defaultExtension );
                if (defaultExtension.isEmpty()) {
                    defaultExtension = filters.first().trimmed().mid(2); //first one
                }
                path += (QLatin1String(".")+defaultExtension);
                kDebug() << "appended extension" << path;
                setSelection( path );
                d->highlightedUrl = KUrl(path);
            }
        }
    }

    kDebug() << "KexiFileWidget::checkURL() path: " << d->highlightedUrl;
// kDebug() << "KexiFileWidget::checkURL() fname: " << url.fileName();
//! @todo if ( url.isLocalFile() ) {
    QFileInfo fi(d->highlightedUrl.toLocalFile());
    if (mode() & KFile::ExistingOnly) {
        if (!fi.exists()) {
            KMessageBox::error(this, "<qt>" + i18n("The file \"%1\" does not exist.",
                                                   QDir::convertSeparators(d->highlightedUrl.toLocalFile())));
            return false;
        } else if (mode() & KFile::File) {
            if (!fi.isFile()) {
                KMessageBox::error(this, "<qt>" + i18n("Enter a filename."));
                return false;
            } else if (!fi.isReadable()) {
                KMessageBox::error(this, "<qt>" + i18n("The file \"%1\" is not readable.",
                                                       QDir::convertSeparators(d->highlightedUrl.path())));
                return false;
            }
        }
    } else if (d->confirmOverwrites && !askForOverwriting(d->highlightedUrl.path(), this)) {
        return false;
    }
    return true;
}
Ejemplo n.º 27
0
QString MachinekitHalRemoteControlsPlugin::fileLocation() const
{
    if (isLoadedFromResource())
        return "qrc:/Machinekit/HalRemote/Controls";
    return baseUrl().toString();
}
Ejemplo n.º 28
0
bool ControllerHandler::handle(HttpRequest* req, HttpResponse& res, map<string, string> urlpattMap, map<string, string> mappattMap, void* dlib,
		string ext, resFuncMap rstCntMap, map<string, string> mapMap, map<string, string> urlMap, string pthwofile)
{
	Logger logger = Logger::getLogger("ControllerHandler");
	string claz;
	bool isContrl = false;
	if((urlpattMap[req->getCntxt_name()+"*.*"]!="" || urlMap[req->getCntxt_name()+ext]!=""))
	{
		//logger << "Controller requested for " << req->getCntxt_name() << " name " << urlMap[req->getCntxt_name()+ext] << endl;
		if(urlpattMap[req->getCntxt_name()+"*.*"]!="")
			claz = "getReflectionCIFor" + urlpattMap[req->getCntxt_name()+"*.*"];
		else
			claz = "getReflectionCIFor" + urlMap[req->getCntxt_name()+ext];
		string libName = Constants::INTER_LIB_FILE;
		if(dlib == NULL)
		{
			cerr << dlerror() << endl;
			exit(-1);
		}
		void *mkr = dlsym(dlib, claz.c_str());
		if(mkr!=NULL)
		{
			FunPtr f =  (FunPtr)mkr;
			ClassInfo srv = f();
			args argus;
			Constructor ctor = srv.getConstructor(argus);
			Reflector ref;
			void *_temp = ref.newInstanceGVP(ctor);
			Controller *thrd = (Controller *)_temp;
			try{
				 logger << "Controller called" << endl;
				 res = thrd->service(*req);
				 logger << res.getStatusCode() << endl;
				 logger << res.getContent_type() << endl;
				 logger << res.getContent_len() << endl;
				 if(res.getStatusCode()!="")
					 isContrl = true;
				 ext = AuthHandler::getFileExtension(req->getUrl());
				 //delete mkr;
			}catch(...){ logger << "Controller exception" << endl;}
			logger << "Controller called\n" << flush;
		}
	}
	else if((mappattMap[req->getCntxt_name()+"*.*"]!="" || mapMap[req->getCntxt_name()+ext]!=""))
	{
		string file = req->getFile();
		string fili = file.substr(0,file.find_last_of("."));
		if(mappattMap[req->getCntxt_name()+"*.*"]!="")
		{
			req->setFile(fili+mappattMap[req->getCntxt_name()+"*.*"]);
			logger << "URL mapped from * to " << mappattMap[req->getCntxt_name()+"*.*"] << endl;
		}
		else
		{
			req->setFile(fili+mapMap[req->getCntxt_name()+ext]);
			logger << "URL mapped from " << ext << " to " << mapMap[req->getCntxt_name()+ext] << endl;
		}
	}
	else
	{
		resFuncMap::iterator it;
		RestFunction rft;
		bool flag = false;
		int prsiz = 0;
		vector<string> valss;
		//logger << pthwofile << endl;
		for (it=rstCntMap.begin();it!=rstCntMap.end();it++)
		{
			valss.clear();
			//logger << it->first << endl;
			//if(pthwofile.find(it->first)!=string::npos)
			{
				RestFunction ft = it->second;
				prsiz = ft.params.size();
				string pthwofiletemp(pthwofile);
				if(ft.baseUrl=="")
				{
					logger << "checking url : " << pthwofiletemp << ",param size: " << prsiz <<
							", against url: " << it->first << endl;
					for (int var = 0; var < prsiz; var++)
					{
						//logger << "loop - " << pthwofiletemp << endl;
						string valsvv(pthwofiletemp.substr(pthwofiletemp.find_last_of("/")+1));
						pthwofiletemp = pthwofiletemp.substr(0, pthwofiletemp.find_last_of("/"));
						valss.push_back(valsvv);
					}
					reverse(valss.begin(),valss.end());
					//logger << "after - " << pthwofiletemp << endl;
					/*if(pthwofiletemp.at(pthwofiletemp.length()-1)=='/')
					{
						pthwofiletemp = pthwofiletemp.substr(0, pthwofiletemp.length()-1);
					}*/
					//logger << "after - " << pthwofiletemp << endl;
					logger << "checking url : " << pthwofiletemp << ",param size: " << prsiz << ",vals: " << valss.size() <<
							", against url: " << it->first << endl;
					if(it->first==pthwofiletemp)
					{
						string lhs = StringUtil::toUpperCopy(ft.meth);
						string rhs = StringUtil::toUpperCopy(req->getMethod());
						logger << lhs << " <> " << rhs << endl;
						if(prsiz==(int)valss.size() && lhs==rhs)
						{
							logger << "got correct url -- restcontroller " << endl;
							rft = ft;
							flag = true;
						}
						else
						{
							res.setStatusCode("404");
							res.setStatusMsg("Not Found");
							//res.setContent_type("text/plain");
							/*if(prsiz==valss.size())
								res.setContent_str("Invalid number of arguments");
							else
								res.setContent_str("Invalid HTTPMethod used");*/
							logger << "Rest Controller Param/Method Error" << endl;
						}
						break;
					}
				}
				else
				{
					string baseUrl(req->getCntxt_name()+ft.baseUrl);
					logger << "checking url : " << pthwofiletemp << ",param size: " << prsiz <<
							", against url: " << baseUrl << endl;
					for (int var = 1; var <= prsiz; var++)
					{
						strVec vemp;
						stringstream ss;
						ss << "{";
						ss << var;
						ss << "}";
						string param;
						ss >> param;
						StringUtil::split(vemp, baseUrl, (param));
						if(vemp.size()==2 && pthwofiletemp.find(vemp.at(0))!=string::npos)
						{
							string temp = pthwofiletemp;
							StringUtil::replaceFirst(temp, vemp.at(0), "");
							if(temp.find("/")!=string::npos)
							{
								pthwofiletemp = temp.substr(temp.find("/"));
								temp = temp.substr(0, temp.find("/"));
							}
							valss.push_back(temp);
							baseUrl = vemp.at(1);
							logger << "variable at " << param << " mapped to " << temp << " from URL" << endl;
							logger << baseUrl << endl;
							logger << pthwofiletemp << endl;
						}
						else
						{
							flag = false;
							break;
						}
					}
					string lhs = StringUtil::toUpperCopy(ft.meth);
					string rhs = StringUtil::toUpperCopy(req->getMethod());
					logger << lhs << " <> " << rhs << endl;
					if(prsiz==(int)valss.size() && lhs==rhs)
					{

						logger << "got correct url -- restcontroller " << endl;
						rft = ft;
						flag = true;
						break;
					}
					else
					{
						res.setStatusCode("404");
						res.setStatusMsg("Not Found");
						//res.setContent_type("text/plain");
						/*if(prsiz==valss.size())
							res.setContent_str("Invalid number of arguments");
						else
							res.setContent_str("Invalid HTTPMethod used");*/
						logger << "Rest Controller Param/Method Error" << endl;
					}
				}
			}
		}
		if(flag)
		{
			//logger << "inside restcontroller logic ..." << endl;
			string libName = Constants::INTER_LIB_FILE;
			if(dlib == NULL)
			{
				cerr << dlerror() << endl;
				exit(-1);
			}
			string clasnam("getReflectionCIFor"+rft.clas);
			void *mkr = dlsym(dlib, clasnam.c_str());
			logger << mkr << endl;
			if(mkr!=NULL)
			{
				FunPtr f =  (FunPtr)mkr;
				ClassInfo srv = f();
				args argus;
				Constructor ctor = srv.getConstructor(argus);
				Reflector ref;
				void *_temp = ref.newInstanceGVP(ctor);
				RestController* rstcnt = (RestController*)_temp;
				rstcnt->request = req;
				rstcnt->response = &res;

				vals valus;
				bool invValue = false;
				for (int var = 0; var < prsiz; var++)
				{
					try
					{
						argus.push_back(rft.params.at(var).type);
						if(rft.params.at(var).type=="int")
						{
							int* ival = new int(CastUtil::lexical_cast<int>(valss.at(var)));
							valus.push_back(ival);
						}
						else if(rft.params.at(var).type=="long")
						{
							long* ival = new long(CastUtil::lexical_cast<long>(valss.at(var)));
							valus.push_back(ival);
						}
						else if(rft.params.at(var).type=="double")
						{
							double* ival = new double(CastUtil::lexical_cast<double>(valss.at(var)));
							valus.push_back(ival);
						}
						else if(rft.params.at(var).type=="float")
						{
							float* ival = new float(CastUtil::lexical_cast<float>(valss.at(var)));
							valus.push_back(ival);
						}
						else if(rft.params.at(var).type=="bool")
						{
							bool* ival = new bool(CastUtil::lexical_cast<bool>(valss.at(var)));
							valus.push_back(ival);
						}
						else if(rft.params.at(var).type=="string")
						{
							string* sval = new string(valss.at(var));
							valus.push_back(sval);
						}
					} catch (...) {
						invValue= true;
						break;
					}
				}

				Method meth = srv.getMethod(rft.name, argus);
				if(meth.getMethodName()!="" && !invValue)
				{
					ref.invokeMethodUnknownReturn(_temp,meth,valus);
					logger << "successfully called restcontroller" << endl;
					//return;
				}
				else
				{
					res.setStatusCode("404");
					res.setStatusMsg("Not Found");
					//res.setContent_type("text/plain");
					/*if(invValue)
						res.setContent_str("Invalid value passed as URL param");
					else
						res.setContent_str("Rest Controller Method Not Found");*/
					logger << "Rest Controller Method Not Found" << endl;
					//return;
				}
			}
		}
	}
	return isContrl;
}
Ejemplo n.º 29
0
bool XMLTVParser::parseFile(
    QString filename, QList<ChanInfo> *chanlist,
    QMap<QString, QList<ProgInfo> > *proglist)
{
    QDomDocument doc;
    QFile f;

    if (!dash_open(f, filename, QIODevice::ReadOnly))
    {
        VERBOSE(VB_IMPORTANT, QString("Error unable to open '%1' for reading.")
                .arg(filename));
        return false;
    }

    QString errorMsg = "unknown";
    int errorLine = 0;
    int errorColumn = 0;

    if (!doc.setContent(&f, &errorMsg, &errorLine, &errorColumn))
    {
        VERBOSE(VB_IMPORTANT, QString("Error in %1:%2: %3")
            .arg(errorLine).arg(errorColumn).arg(errorMsg));

        f.close();
        return true;
    }

    f.close();

    // now we calculate the localTimezoneOffset, so that we can fix
    // the programdata if needed
    QString config_offset = gCoreContext->GetSetting("TimeOffset", "None");
    // we disable this feature by setting it invalid (> 840min = 14hr)
    int localTimezoneOffset = 841;

    if (config_offset == "Auto")
    {
        // we mark auto with the -ve of the disable magic number
        localTimezoneOffset = -841;
    }
    else if (config_offset != "None")
    {
        localTimezoneOffset = TimezoneToInt(config_offset);
        if (abs(localTimezoneOffset) > 840)
        {
            VERBOSE(VB_XMLTV, QString("Ignoring invalid TimeOffset %1")
                .arg(config_offset));
            localTimezoneOffset = 841;
        }
    }

    QDomElement docElem = doc.documentElement();

    QUrl baseUrl(docElem.attribute("source-data-url", ""));

    QUrl sourceUrl(docElem.attribute("source-info-url", ""));
    if (sourceUrl.toString() == "http://labs.zap2it.com/")
    {
        VERBOSE(VB_IMPORTANT, "Don't use tv_grab_na_dd, use the"
            "internal datadirect grabber.");
        exit(GENERIC_EXIT_SETUP_ERROR);
    }

    QString aggregatedTitle;
    QString aggregatedDesc;
    QString groupingTitle;
    QString groupingDesc;

    QDomNode n = docElem.firstChild();
    while (!n.isNull())
    {
        QDomElement e = n.toElement();
        if (!e.isNull())
        {
            if (e.tagName() == "channel")
            {
                ChanInfo *chinfo = parseChannel(e, baseUrl);
                chanlist->push_back(*chinfo);
                delete chinfo;
            }
            else if (e.tagName() == "programme")
            {
                ProgInfo *pginfo = parseProgram(e, localTimezoneOffset);

                if (pginfo->startts == pginfo->endts)
                {
                    /* Not a real program : just a grouping marker */
                    if (!pginfo->title.isEmpty())
                        groupingTitle = pginfo->title + " : ";

                    if (!pginfo->description.isEmpty())
                        groupingDesc = pginfo->description + " : ";
                }
                else
                {
                    if (pginfo->clumpidx.isEmpty())
                    {
                        if (!groupingTitle.isEmpty())
                        {
                            pginfo->title.prepend(groupingTitle);
                            groupingTitle.clear();
                        }

                        if (!groupingDesc.isEmpty())
                        {
                            pginfo->description.prepend(groupingDesc);
                            groupingDesc.clear();
                        }

                        (*proglist)[pginfo->channel].push_back(*pginfo);
                    }
                    else
                    {
                        /* append all titles/descriptions from one clump */
                        if (pginfo->clumpidx.toInt() == 0)
                        {
                            aggregatedTitle.clear();
                            aggregatedDesc.clear();
                        }

                        if (!pginfo->title.isEmpty())
                        {
                            if (!aggregatedTitle.isEmpty())
                                aggregatedTitle.append(" | ");
                            aggregatedTitle.append(pginfo->title);
                        }

                        if (!pginfo->description.isEmpty())
                        {
                            if (!aggregatedDesc.isEmpty())
                                aggregatedDesc.append(" | ");
                            aggregatedDesc.append(pginfo->description);
                        }
                        if (pginfo->clumpidx.toInt() ==
                            pginfo->clumpmax.toInt() - 1)
                        {
                            pginfo->title = aggregatedTitle;
                            pginfo->description = aggregatedDesc;
                            (*proglist)[pginfo->channel].push_back(*pginfo);
                        }
                    }
                }
                delete pginfo;
            }
        }
        n = n.nextSibling();
    }

    return true;
}
Ejemplo n.º 30
0
bool NewAccountPage::validatePage()
{
    if(hasCreatedAccount)
    {
        return true;
    }
    serverQueryFinished = false;
    serverQueryError = false;
    //Check if passwords match
    if(input_password->text() != input_confirmPassword->text())
    {
        label_message->setText(tr("<font color='red'>Passwords do not match</font>"));
        return false;
    }
    label_message->setText("Creating account...");
    QUrl baseUrl( "https://api.screencloud.net/1.0/users/register.xml" );
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
    QUrlQuery query(baseUrl);
#else
    QUrl query(baseUrl);
#endif
    query.addQueryItem("oauth_version", "1.0");
    query.addQueryItem("oauth_signature_method", "PLAINTEXT");
    query.addQueryItem("oauth_consumer_key", CONSUMER_KEY_SCREENCLOUD);
    query.addQueryItem("oauth_signature", CONSUMER_SECRET_SCREENCLOUD);
    query.addQueryItem("oauth_timestamp", QString::number(QDateTime::currentDateTimeUtc().toTime_t()));
    query.addQueryItem("oauth_nonce", NetworkUtils::generateNonce(15));
    // create a request parameters map
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
    QUrlQuery bodyParams;
#else
    QUrl bodyParams;
#endif
    bodyParams.addQueryItem("data[User][email]", input_email->text());
    bodyParams.addQueryItem("data[User][password]", input_password->text());
    bodyParams.addQueryItem("data[User][password_confirmation]", input_confirmPassword->text());

    // construct the body string
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
    QByteArray body = bodyParams.query(QUrl::FullyEncoded).toUtf8();
#else
    QByteArray body = bodyParams.encodedQuery();
#endif

#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
    QUrl fullUrl(baseUrl);
    fullUrl.setQuery(query);
#else
    QUrl fullUrl(query);
#endif
    QNetworkRequest request;
    request.setUrl(fullUrl);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    manager->post(request, body);
    while (!serverQueryFinished) {
       qApp->processEvents(QEventLoop::WaitForMoreEvents);
    }
    if(serverQueryError)
    {
        return false;
    }
    hasCreatedAccount = true;
    return true;
}