예제 #1
2
// --------------------------------------------------------------------------
void wait(int msec)
{
  QEventLoop eventLoop;
  QTimer::singleShot(msec, &eventLoop, SLOT(quit()));
  eventLoop.exec();
}
예제 #2
1
void Delay()
{
    QEventLoop loop;
    QTimer::singleShot(1, &loop, SLOT(quit()));
    loop.exec();
}
예제 #3
0
void kwp2000::pause()
{
    QEventLoop loop;
    QTimer::singleShot(900, &loop, SLOT(quit()));
    loop.exec();
}
예제 #4
0
/*!
 * \brief Waits for response from the server.
 * On Linux it is used in a seperate thread, so the main
 * thread would not be freezed during the waiting of
 * the server repsonse.
 */
void Translator::linuxTranslate(QNetworkRequest &request)
{
    QEventLoop loop;
    connect(parent->getManager()->get(request), &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();
}
예제 #5
0
void TestAbstractAsyncClient::startEventLoop(const int delay)
{
    QEventLoop el;
    QTimer::singleShot(delay, &el, SLOT(quit()));
    el.exec();
}
Installer::Installer(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Installer)
{
    setAttribute(Qt::WA_DeleteOnClose, true);
    ui->setupUi(this);

    QProgressDialog wait(this);
    wait.setLabelText("Checking for new Required Core Tools ...");
    wait.show();

    if (qnam.networkAccessible() != QNetworkAccessManager::Accessible) {
        wait.hide();
        QMessageBox::critical(this, "Network Inaccessible", "Can't check for updates as you appear to be offline.");
        return;
    }

    QSettings conf;
    QWidget *w = new QWidget;
    QGridLayout *g = new QGridLayout;
    QPushButton *b = 0;

#if defined(Q_OS_WIN)
    #define OS_PATH "win32"
#elif defined(Q_OS_MAC)
    #define OS_PATH "osx"
#elif defined(Q_OS_LINUX)
    #define OS_PATH "osx"
#else
    #error "Not yet specialized for other OSs"
#endif

    int row = 0;
    g->addWidget(new QLabel("Name"), row, 0, 1, 1, Qt::AlignLeft);
    g->addWidget(new QLabel("Size"), row, 1, 1, 1, Qt::AlignHCenter);
    g->addWidget(new QLabel("Action"), row, 2, 1, 1, Qt::AlignRight);

#if defined(Q_OS_WIN) || defined(Q_OS_MAC)
    {
        reply = qnam.head(QNetworkRequest(QUrl("http://apertium.projectjj.com/" OS_PATH "/nightly/apertium-all-dev.7z")));
        QEventLoop loop;
        connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
        loop.exec();

        QString lm = reply->rawHeader("Last-Modified");
        QString cl = reply->rawHeader("Content-Length");
        QString label("Install");
        if (conf.contains("apertium-all-dev")) {
            label = "Reinstall";
            if (conf.value("apertium-all-dev").toString() != lm) {
                label = "Update";
            }
        }

        ++row;
        g->addWidget(new QLabel("Required Core Tools"), row, 0, 1, 1, Qt::AlignLeft);
        g->addWidget(new QLabel(formatBytes(cl.toUInt())), row, 1, 1, 1, Qt::AlignRight);
        g->addWidget(b = new QPushButton(label), row, 2, 1, 1, Qt::AlignRight);
        b->setProperty("name", "apertium-all-dev");
        b->setProperty("url", QString("http://apertium.projectjj.com/" OS_PATH "/nightly/apertium-all-dev.7z"));
        b->setProperty("bsize", cl);
        b->setProperty("lm", lm);
        connect(b, SIGNAL(clicked()), this, SLOT(installpkg()));
    }
#endif

    {
        wait.setLabelText("Checking for new language pairs ...");
        reply = qnam.get(QNetworkRequest(QUrl("http://apertium.projectjj.com/" OS_PATH "/nightly/data.php")));
        QEventLoop loop;
        connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
        loop.exec();

        QString body = reply->readAll();
        QRegularExpression rx("<tr><td>(apertium-\\w+-\\w+)</td><td>[^<]+</td><td>(\\d+)</td><td>([^<]+)</td>.*?</tr>");
        QRegularExpressionMatchIterator it = rx.globalMatch(body);
        while (it.hasNext()) {
            QRegularExpressionMatch m = it.next();

            QString name = m.captured(1);
            QString label("Install");
            if (conf.contains(name)) {
                label = "Reinstall";
                if (conf.value(name).toString() != m.captured(3)) {
                    label = "Update";
                }
            }

            ++row;
            g->addWidget(new QLabel(name), row, 0, 1, 1, Qt::AlignLeft);
            g->addWidget(new QLabel(formatBytes(m.captured(2).toUInt())), row, 1, 1, 1, Qt::AlignRight);
            g->addWidget(b = new QPushButton(label), row, 2, 1, 1, Qt::AlignRight);
            b->setProperty("name", name);
            b->setProperty("url", QString("http://apertium.projectjj.com/" OS_PATH "/nightly/data.php?deb=")+name);
            b->setProperty("bsize", m.captured(2));
            b->setProperty("lm", m.captured(3));
            connect(b, SIGNAL(clicked()), this, SLOT(installpkg()));
        }
    }

    w->setLayout(g);
    ui->scrollArea->setWidgetResizable(true);
    ui->scrollArea->setWidget(w);
}
예제 #7
0
파일: user.cpp 프로젝트: KasaiDot/Shinjiru
int User::loadNext() {
  if (queue.empty()) return 1;

  if (this->cancel) return 1;

  QMap<Anime *, bool> data = queue.front();
  queue.pop();

  Anime *anime = data.keys().first();
  bool download_cover = data.values().first();

  QString ID = anime->getID();
  QUrl ID_URL = API::sharedAPI()->sharedAniListAPI()->API_ANIME(ID);

  QJsonObject result =
      API::sharedAPI()->sharedAniListAPI()->get(ID_URL).object();

  anime->setCoverURL(QUrl(result.value("image_url_lge").toString()));

  if (download_cover) {
    QEventLoop evt;
    connect(anime, SIGNAL(new_image()), &evt, SLOT(quit()));
    anime->downloadCover();
    evt.exec();
  }

  QString description = result.value("description").toString();

  anime->setDuration(result.value("duration").toInt());
  anime->setSynopsis(description);
  anime->setRomajiTitle(result.value("title_romaji").toString());
  anime->setJapaneseTitle(result.value("title_japanese").toString());
  anime->setEnglishTitle(result.value("title_english").toString());
  anime->setType(result.value("type").toString());
  anime->setAiringStatus(result.value("airing_status").toString());
  anime->setEpisodeCount(result.value("total_episodes").toInt());
  anime->setAverageScore(result.value("average_score").toString());
  anime->setTitle(result.value(title_language).toString());

  if (anime->getAiringStatus() == "currently airing") {
    QJsonObject airing = result.value("airing").toObject();

    anime->setNextEpisode(airing.value("next_episode").toInt());
    anime->setCountdown(airing.value("countdown").toInt());

    if (anime->getCountdown() > 0) {
      anime->setAiringSchedule(true);
    } else {
      anime->setAiringSchedule(false);
    }
  }

  QJsonArray synonyms = result.value("synonyms").toArray();

  for (int j = 0; j < synonyms.count(); j++) {
    anime->addSynonym(synonyms.at(j).toString());
  }

  anime->finishReload();

  qDebug() << "Loaded extra data for anime" << anime->getTitle();
  db->saveAnime(anime);

  if (!queue.empty()) {
    async_registry.append(QtConcurrent::run([&, this]() {  // NOLINT
      loadNext();
      return 1;
    }));
  }

  return 1;
}
예제 #8
0
bool QgsWfsRequest::sendGET( const QUrl &url, bool synchronous, bool forceRefresh, bool cache )
{
  abort(); // cancel previous
  mIsAborted = false;
  mTimedout = false;
  mGotNonEmptyResponse = false;

  mErrorMessage.clear();
  mErrorCode = QgsWfsRequest::NoError;
  mForceRefresh = forceRefresh;
  mResponse.clear();

  QUrl modifiedUrl( url );

  // Specific code for testing
  if ( modifiedUrl.toString().contains( QLatin1String( "fake_qgis_http_endpoint" ) ) )
  {
    // Just for testing with local files instead of http:// resources
    QString modifiedUrlString = modifiedUrl.toString();
    // Qt5 does URL encoding from some reason (of the FILTER parameter for example)
    modifiedUrlString = QUrl::fromPercentEncoding( modifiedUrlString.toUtf8() );
    QgsDebugMsg( QString( "Get %1" ).arg( modifiedUrlString ) );
    modifiedUrlString = modifiedUrlString.mid( QStringLiteral( "http://" ).size() );
    QString args = modifiedUrlString.mid( modifiedUrlString.indexOf( '?' ) );
    if ( modifiedUrlString.size() > 256 )
    {
      args = QCryptographicHash::hash( args.toUtf8(), QCryptographicHash::Md5 ).toHex();
    }
    else
    {
      args.replace( QLatin1String( "?" ), QLatin1String( "_" ) );
      args.replace( QLatin1String( "&" ), QLatin1String( "_" ) );
      args.replace( QLatin1String( "<" ), QLatin1String( "_" ) );
      args.replace( QLatin1String( ">" ), QLatin1String( "_" ) );
      args.replace( QLatin1String( "'" ), QLatin1String( "_" ) );
      args.replace( QLatin1String( "\"" ), QLatin1String( "_" ) );
      args.replace( QLatin1String( " " ), QLatin1String( "_" ) );
      args.replace( QLatin1String( ":" ), QLatin1String( "_" ) );
      args.replace( QLatin1String( "/" ), QLatin1String( "_" ) );
      args.replace( QLatin1String( "\n" ), QLatin1String( "_" ) );
    }
#ifdef Q_OS_WIN
    // Passing "urls" like "http://c:/path" to QUrl 'eats' the : after c,
    // so we must restore it
    if ( modifiedUrlString[1] == '/' )
    {
      modifiedUrlString = modifiedUrlString[0] + ":/" + modifiedUrlString.mid( 2 );
    }
#endif
    modifiedUrlString = modifiedUrlString.mid( 0, modifiedUrlString.indexOf( '?' ) ) + args;
    QgsDebugMsg( QStringLiteral( "Get %1 (after laundering)" ).arg( modifiedUrlString ) );
    modifiedUrl = QUrl::fromLocalFile( modifiedUrlString );
  }

  QgsDebugMsgLevel( QStringLiteral( "Calling: %1" ).arg( modifiedUrl.toDisplayString( ) ), 4 );

  QNetworkRequest request( modifiedUrl );
  if ( !mUri.auth().setAuthorization( request ) )
  {
    mErrorCode = QgsWfsRequest::NetworkError;
    mErrorMessage = errorMessageFailedAuth();
    QgsMessageLog::logMessage( mErrorMessage, tr( "WFS" ) );
    return false;
  }

  if ( cache )
  {
    request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, forceRefresh ? QNetworkRequest::AlwaysNetwork : QNetworkRequest::PreferCache );
    request.setAttribute( QNetworkRequest::CacheSaveControlAttribute, true );
  }

  mReply = QgsNetworkAccessManager::instance()->get( request );
  if ( !mUri.auth().setAuthorizationReply( mReply ) )
  {
    mErrorCode = QgsWfsRequest::NetworkError;
    mErrorMessage = errorMessageFailedAuth();
    QgsMessageLog::logMessage( mErrorMessage, tr( "WFS" ) );
    return false;
  }
  connect( mReply, &QNetworkReply::finished, this, &QgsWfsRequest::replyFinished );
  connect( mReply, &QNetworkReply::downloadProgress, this, &QgsWfsRequest::replyProgress );

  if ( !synchronous )
    return true;

  QEventLoop loop;
  connect( this, &QgsWfsRequest::downloadFinished, &loop, &QEventLoop::quit );
  loop.exec( QEventLoop::ExcludeUserInputEvents );

  return mErrorMessage.isEmpty();
}
예제 #9
0
파일: Agent.cpp 프로젝트: JeroMiya/hifi
void Agent::run() {
    ThreadedAssignment::commonInit(AGENT_LOGGING_NAME, NodeType::Agent);
    
    NodeList* nodeList = NodeList::getInstance();
    nodeList->addSetOfNodeTypesToNodeInterestSet(NodeSet()
                                                 << NodeType::AudioMixer
                                                 << NodeType::AvatarMixer
                                                 << NodeType::VoxelServer
                                                 << NodeType::ParticleServer
                                                 << NodeType::ModelServer
                                                );
    
    // figure out the URL for the script for this agent assignment
    QUrl scriptURL;
    if (_payload.isEmpty())  {
        scriptURL = QUrl(QString("http://%1:%2/assignment/%3")
            .arg(NodeList::getInstance()->getDomainHandler().getIP().toString())
            .arg(DOMAIN_SERVER_HTTP_PORT)
            .arg(uuidStringWithoutCurlyBraces(_uuid)));
    } else {
        scriptURL = QUrl(_payload);
    }
   
    NetworkAccessManager& networkAccessManager = NetworkAccessManager::getInstance();
    QNetworkReply *reply = networkAccessManager.get(QNetworkRequest(scriptURL));
    
    QNetworkDiskCache* cache = new QNetworkDiskCache();
    QString cachePath = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
    cache->setCacheDirectory(!cachePath.isEmpty() ? cachePath : "agentCache");
    networkAccessManager.setCache(cache);
    
    qDebug() << "Downloading script at" << scriptURL.toString();
    
    QEventLoop loop;
    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    
    loop.exec();
    
    QString scriptContents(reply->readAll());
    
    qDebug() << "Downloaded script:" << scriptContents;
    
    // setup an Avatar for the script to use
    ScriptableAvatar scriptedAvatar(&_scriptEngine);
    scriptedAvatar.setForceFaceshiftConnected(true);

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

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

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

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

    _scriptEngine.setScriptContents(scriptContents);
    _scriptEngine.run();
    setFinished(true);
}
예제 #10
0
void MainWindow::loadSettings()
{
    mainLog.Log("Loading settings...");
    QSettings settings;
    if(settings.allKeys().size() == 0)
    {
        mainLog.Log("Settings is empty. Default values will be used.");
    }
    else mainLog.Log("Loading settings from %s.", settings.fileName().toLocal8Bit().data());


    QPoint defaultPosition;
    QSize defaultSize(800,600);
    if(!settings.contains("MainWindow/size") || !settings.contains("MainWindow/pos"))
    {
        int frameWidth = 0;
        int frameTop = 0;
        int frameBottom = 0;
        bool screenHack = true; //If we want to get frame geometry (which is apparently a pain in qt).
        if(screenHack)
        {
            //The following from a post on stackoverflow by TonyK

            // BIG PAIN: We want to get the dialog box to caluclate its own size. But there is
            // no simple way to do this. The following seems to work, but only if processEvents
            // is called at least twice. God knows why:
            setAttribute (Qt::WA_DontShowOnScreen, true) ; // Prevent screen flicker
            show() ;

            QEventLoop EventLoop (this) ;
            for (int i = 0 ; i < 10 ; i++)
              if (!EventLoop.processEvents()) break ;

            hide() ;
            setAttribute (Qt::WA_DontShowOnScreen, false) ;
            //End code section from TonyK

            frameWidth = frameGeometry().width()-geometry().width();
            frameTop = abs(geometry().top()-frameGeometry().top());
            frameBottom = abs(frameGeometry().bottom()-geometry().bottom());
        }

        //Ensure sane positioning for first run (i.e. not split across multiple monitors
        QDesktopWidget* desk = QApplication::desktop();
        int usedScreen = 0;
        const QRect available = desk->availableGeometry(usedScreen);
        if((available.x()+available.width())/2 >= defaultSize.width()/2+frameWidth/2)
        {
            defaultPosition.setX((available.x()+available.width())/2-(defaultSize.width()/2+frameWidth/2));
        }
        else
        {
            defaultPosition.setX(available.x());
            defaultSize.setWidth(available.width()-frameWidth);
        }
        if((available.y()+available.height())/2 >= defaultSize.height()/2 + (frameTop+frameBottom)/2)
        {
            defaultPosition.setY((available.y()+available.height())/2-defaultSize.height()/2);
        }
        else
        {
            defaultPosition.setY(available.y());
            defaultSize.setHeight(available.height()-(frameTop+frameBottom));
        }
        mainLog.Log("Positioning window at (%d, %d) with size (%d, %d) on screen %d/%d",defaultPosition.x(),defaultPosition.y(),defaultSize.width(),defaultSize.height(),usedScreen,desk->screenCount());
    }

    mainLog.setLogPriority(settings.value("LoggingLevels/mainLog",DEFAULT_PRIORITY).toInt());
    levelLog.setLogPriority(settings.value("LoggingLevels/levelLog",DEFAULT_PRIORITY).toInt());
    int levelPriorities[NUMBER_OF_BLOCKS];

    levelPriorities[BLOCK_TEXTURES] = settings.value("LoggingLevels/blockTextures",levelLog.getLogPriority()).toInt();
    levelPriorities[BLOCK_MODELS] = settings.value("LoggingLevels/blockModels",levelLog.getLogPriority()).toInt();
    levelPriorities[BLOCK_WORLD] = settings.value("LoggingLevels/blockWorld",levelLog.getLogPriority()).toInt();
    levelPriorities[BLOCK_RANDOM_MODEL_PLACEMENT] = settings.value("LoggingLevels/blockRandomModelPlacement",levelLog.getLogPriority()).toInt();
    levelPriorities[BLOCK_TEXTURE_DEFINITIONS] = settings.value("LoggingLevels/blockTextureDefinitions",levelLog.getLogPriority()).toInt();
    levelPriorities[BLOCK_ROAD_TABLE] = settings.value("LoggingLevels/blockRoadTable",levelLog.getLogPriority()).toInt();
    levelPriorities[BLOCK_ROAD_CONNECTIONS] = settings.value("LoggingLevels/blockRoadConnections",levelLog.getLogPriority()).toInt();
    levelPriorities[BLOCK_INTERSECTIONS] = settings.value("LoggingLevels/blockIntersections",levelLog.getLogPriority()).toInt();
    levelPriorities[BLOCK_HEIGHTMAP_TILES] = settings.value("LoggingLevels/blockHeightmapTiles",levelLog.getLogPriority()).toInt();
    levelPriorities[BLOCK_HEIGHTMAP] = settings.value("LoggingLevels/blockHeightmap",levelLog.getLogPriority()).toInt();
    levelPriorities[BLOCK_MODEL_NAMES] = settings.value("LoggingLevels/blockModelNames",levelLog.getLogPriority()).toInt();
    levelPriorities[BLOCK_EVENT_MODELS] = settings.value("LoggingLevels/blockEventModels",levelLog.getLogPriority()).toInt();
    levelPriorities[BLOCK_VISIBILITY] = settings.value("LoggingLevels/blockVisibility",levelLog.getLogPriority()).toInt();
    levelPriorities[BLOCK_SECTOR_TEXTURE_USAGE] = settings.value("LoggingLevels/blockSectorTextureUsage",levelLog.getLogPriority()).toInt();
    levelPriorities[BLOCK_ROAD_SECTIONS] = settings.value("LoggingLevels/blockRoadSections",levelLog.getLogPriority()).toInt();
    levelPriorities[BLOCK_INTERSECTION_POSITIONS] = settings.value("LoggingLevels/blockIntersectionPositions",levelLog.getLogPriority()).toInt();
    levelPriorities[BLOCK_LAMPS] = settings.value("LoggingLevels/blockLamps",levelLog.getLogPriority()).toInt();
    levelPriorities[BLOCK_CHAIR_PLACEMENT] = settings.value("LoggingLevels/blockChairPlacement",levelLog.getLogPriority()).toInt();
    level.setLogPriorities(levelPriorities);

    resize(settings.value("MainWindow/size",defaultSize).toSize());
    move(settings.value("MainWindow/pos", defaultPosition).toPoint());
    if(settings.value("MainWindow/maximized",false).toBool())
    showMaximized();
    else showNormal();
    show();

    customLevelDialog->setLastDirectory(settings.value("directories/lastOpenFileDir","C:\\Program Files\\GT Interactive\\Driver\\Levels").toString());

    if(settings.value("firstRun",true).toBool())
    {
        int ret = QMessageBox::No;
        QMessageBox msgBox(centralWindow);
        msgBox.setText(tr("<b>It looks like this is the first run.</b>"));
        msgBox.setInformativeText(tr("It is recommended that you set the default Driver directory. Would you like to do this now? The directory can be changed later in the settings menu. ")+rootDir);
        msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
        msgBox.setDefaultButton(QMessageBox::Yes);
        ret = msgBox.exec();
        if(ret == QMessageBox::Yes)
        {
            QString newRootDir = QFileDialog::getExistingDirectory(centralWindow,tr("Choose the root Driver directory."),"C:\\Program Files\\GT Interactive\\Driver");
            if(!newRootDir.isEmpty())
            {
                settings.setValue("directories/rootDir",newRootDir);
            }
        }
    }

    rootDir = QDir::toNativeSeparators(settings.value("directories/rootDir").toString());

    if(!rootDir.isEmpty())
    setConvenienceActionsEnabled(true);

    textureBrowser->loadSettings();
    modelViewPanel->loadSettings();
    mainLog.Log("Finished loading settings.");
};
예제 #11
0
void QgsComposerLabel::paint( QPainter* painter, const QStyleOptionGraphicsItem* itemStyle, QWidget* pWidget )
{
  Q_UNUSED( itemStyle );
  Q_UNUSED( pWidget );
  if ( !painter )
  {
    return;
  }

  drawBackground( painter );
  painter->save();

  double penWidth = pen().widthF();
  QRectF painterRect( penWidth + mMargin, penWidth + mMargin, rect().width() - 2 * penWidth - 2 * mMargin, rect().height() - 2 * penWidth - 2 * mMargin );

  QString textToDraw = displayText();

  if ( mHtmlState )
  {
    painter->scale( 1.0 / mHtmlUnitsToMM / 10.0, 1.0 / mHtmlUnitsToMM / 10.0 );

    QWebPage *webPage = new QWebPage();
    webPage->setNetworkAccessManager( QgsNetworkAccessManager::instance() );

    //Setup event loop and timeout for rendering html
    QEventLoop loop;
    QTimer timeoutTimer;
    timeoutTimer.setSingleShot( true );

    //This makes the background transparent. Found on http://blog.qt.digia.com/blog/2009/06/30/transparent-qwebview-or-qwebpage/
    QPalette palette = webPage->palette();
    palette.setBrush( QPalette::Base, Qt::transparent );
    webPage->setPalette( palette );
    //webPage->setAttribute(Qt::WA_OpaquePaintEvent, false); //this does not compile, why ?

    webPage->setViewportSize( QSize( painterRect.width() * mHtmlUnitsToMM * 10.0, painterRect.height() * mHtmlUnitsToMM * 10.0 ) );
    webPage->mainFrame()->setZoomFactor( 10.0 );
    webPage->mainFrame()->setScrollBarPolicy( Qt::Horizontal, Qt::ScrollBarAlwaysOff );
    webPage->mainFrame()->setScrollBarPolicy( Qt::Vertical, Qt::ScrollBarAlwaysOff );

    // QGIS segfaults when rendering web page while in composer if html
    // contains images. So if we are not printing the composition, then
    // disable image loading
    if ( mComposition->plotStyle() != QgsComposition::Print &&
         mComposition->plotStyle() != QgsComposition::Postscript )
    {
      webPage->settings()->setAttribute( QWebSettings::AutoLoadImages, false );
    }

    //Connect timeout and webpage loadFinished signals to loop
    connect( &timeoutTimer, SIGNAL( timeout() ), &loop, SLOT( quit() ) );
    connect( webPage, SIGNAL( loadFinished( bool ) ), &loop, SLOT( quit() ) );

    //mHtmlLoaded tracks whether the QWebPage has completed loading
    //its html contents, set it initially to false. The loadingHtmlFinished slot will
    //set this to true after html is loaded.
    mHtmlLoaded = false;
    connect( webPage, SIGNAL( loadFinished( bool ) ), SLOT( loadingHtmlFinished( bool ) ) );

    webPage->mainFrame()->setHtml( textToDraw );

    //For very basic html labels with no external assets, the html load will already be
    //complete before we even get a chance to start the QEventLoop. Make sure we check
    //this before starting the loop
    if ( !mHtmlLoaded )
    {
      // Start a 20 second timeout in case html loading will never complete
      timeoutTimer.start( 20000 );
      // Pause until html is loaded
      loop.exec();
    }

    webPage->mainFrame()->render( painter );//DELETE WEBPAGE ?
  }
  else
  {
예제 #12
0
파일: qtools.cpp 프로젝트: jnse/qtar8200
void qtools::sleep(int msec)
{
    QEventLoop loop;
    QTimer::singleShot(1000,&loop,SLOT(quit()));
    loop.exec();
}
예제 #13
0
  void CHttpThread::sendHttp(const CProtocol& protocol)
  {
    //LOG_PROTOCOL(protocol);
    QByteArray postData;
    // konwertuj protokol do postaci binarnej tablicy QByteArray
    if (!convertToBinary(postData, protocol)){
      // nieprawidlowy format protokolu
      LOG_ERROR("Sending protocol error. idPackage:", protocol.getIdPackage());
      DConnectionResult res(new CConnectionResult(protocol, EConnectionStatus::OUTPUT_PROTOCOL_FORMAT_ERROR));
      resultsQueue.push(res);
    }
    else
    {
      //convertToProtocolDebug(postData);

      uint16_t crc = NUtil::CCryptography::crc16(postData.constData(), postData.size());
      postData.replace(postData.size() - sizeof(crc), sizeof(crc), reinterpret_cast<char*>(&crc), sizeof(crc));

      // tworzy tymczasowa petle komunikatow
      QEventLoop eventLoop;

      // dla sygnalu QNetworkAccessManager::finished wywolaj QEventLoop::quit
      QNetworkAccessManager mgr;
      QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));

      // HTTP
      const std::string url = NEngine::CConfigurationFactory::getInstance()->getServerUrl();
      QUrl qUrl(url.c_str());
      QNetworkRequest req(qUrl);
      // typ MIME
      req.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/octet-stream"));
      // wyslij post'a
      std::shared_ptr<QNetworkReply> reply(mgr.post(req, postData));
      eventLoop.exec(); // czekaj QEventLoop::quit (czyli QNetworkAccessManager::finished)

      if (reply->error() == QNetworkReply::NoError) {
        //success
        LOG_DEBUG("Protocol has been sent successfully. idPackage:", protocol.getIdPackage());

        CByteWrapper wrapper(reply->readAll());
        // wyslanie potwierdzenia zmiany konfiguracji - jesli zmiana odbyla sie bez problemow nie zwraca danych
        if (wrapper.getSize() > 0)
        {
          if (!wrapper.isCRCValid())
          {
            LOG_ERROR("Received protocol error - CRC. idPackage:", protocol.getIdPackage());
            DConnectionResult res(new CConnectionResult(protocol, EConnectionStatus::CRC_ERROR));
            resultsQueue.push(res);

          }
          else
          {

            std::shared_ptr<CProtocol> responseProtocol =
                convertToProtocol(wrapper);
            // przekonwertuj do struktury
            if (!responseProtocol)
            {
              // blad struktury protokolu
              LOG_ERROR("Received protocol error. idPackage:", protocol.getIdPackage());
              DConnectionResult res(new CConnectionResult(protocol, EConnectionStatus::INPUT_PROTOCOL_FORMAT_ERROR));
              resultsQueue.push(res);
            }
            else
            {
              LOG_DEBUG("Protocol has been received successfully. idPackage:", responseProtocol->getIdPackage());
              DConnectionResult res(new CConnectionResult(protocol, responseProtocol, EConnectionStatus::NONE));
              resultsQueue.push(res);
            }
          }
        }

      }
      else {

        LOG_ERROR("Protocol sending error. idPackage:",
                  protocol.getIdPackage(), ". Error: ", reply->errorString().toStdString());
        DConnectionResult res(new CConnectionResult(protocol, EConnectionStatus::CONNECTION_ERROR));
        resultsQueue.push(res);
      }
    }
  }
예제 #14
0
void TestQGeoPositionInfoSource::lastKnownPosition()
{
    CHECK_SOURCE_VALID;
    QFETCH(int, positioningMethod);
    QFETCH(bool, lastKnownPositionArgument);
    QFETCH(bool, positionValid);

#if defined(Q_OS_SYMBIAN)
    QSKIP("Real GPS not suitable for autotesting, skipping the test.", SkipAll);
#endif
    QGeoPositionInfoSource::PositioningMethods method
            = static_cast<QGeoPositionInfoSource::PositioningMethods>(positioningMethod);

    if ((m_source->supportedPositioningMethods() & method) == 0)
        QSKIP("Not a supported positioning method for this position source", SkipSingle);

    m_source->setPreferredPositioningMethods(method);

    QSignalSpy spy(m_source, SIGNAL(positionUpdated(const QGeoPositionInfo&)));
    QSignalSpy timeout(m_source, SIGNAL(updateTimeout()));
    int time_out = 7000;
    m_source->setUpdateInterval(time_out);
    m_source->startUpdates();

    // Use QEventLoop instead of qWait() to ensure we stop as soon as a
    // position is emitted (otherwise the lastKnownPosition() may have
    // changed by the time it is checked)
    QEventLoop loop;
    QTimer timer;
    timer.setInterval(9500);
    connect(m_source, SIGNAL(positionUpdated(const QGeoPositionInfo&)),
            &loop, SLOT(quit()));
    connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
    timer.start();
    loop.exec();

    EXPECT_FAIL_WINCE_SEE_MOBILITY_337_ABORT;

    QVERIFY((spy.count() > 0) && (timeout.count() == 0));

    QList<QVariant> list = spy.takeFirst();
    QGeoPositionInfo info;
    info = list.at(0).value<QGeoPositionInfo>();
    QGeoPositionInfo lastPositioninfo;
    lastPositioninfo = m_source->lastKnownPosition(lastKnownPositionArgument);
 
    QCOMPARE(lastPositioninfo.isValid(), positionValid);

    if (positionValid) {
        QCOMPARE(info.coordinate(), lastPositioninfo.coordinate());
        QCOMPARE(info.timestamp(), lastPositioninfo.timestamp());

        QCOMPARE(info.hasAttribute(QGeoPositionInfo::HorizontalAccuracy),
                 lastPositioninfo.hasAttribute(QGeoPositionInfo::HorizontalAccuracy));

        if (info.hasAttribute(QGeoPositionInfo::HorizontalAccuracy)) {
            bool isNaN1 =  qIsNaN(info.attribute(QGeoPositionInfo::HorizontalAccuracy));
            bool isNaN2 =  qIsNaN(lastPositioninfo.attribute(QGeoPositionInfo::HorizontalAccuracy));
            QCOMPARE(isNaN1, isNaN2);
            if (!isNaN1) {
                QCOMPARE(qFuzzyCompare(info.attribute(QGeoPositionInfo::HorizontalAccuracy),
                                       lastPositioninfo.attribute(QGeoPositionInfo::HorizontalAccuracy)), TRUE);
            }
        }

        QCOMPARE(info.hasAttribute(QGeoPositionInfo::VerticalAccuracy),
                 lastPositioninfo.hasAttribute(QGeoPositionInfo::VerticalAccuracy));

        if (info.hasAttribute(QGeoPositionInfo::VerticalAccuracy)) {
            bool isNaN1 =  qIsNaN(info.attribute(QGeoPositionInfo::VerticalAccuracy));
            bool isNaN2 =  qIsNaN(lastPositioninfo.attribute(QGeoPositionInfo::VerticalAccuracy));
            QCOMPARE(isNaN1, isNaN2);
            if (!isNaN1) {
                QCOMPARE(qFuzzyCompare(info.attribute(QGeoPositionInfo::VerticalAccuracy),
                                       lastPositioninfo.attribute(QGeoPositionInfo::VerticalAccuracy)), TRUE);
            }
        }
    }

    m_source->stopUpdates();
}
예제 #15
0
void MapQuestRunner::retrieveRoute( const RouteRequest *route )
{
    if ( route->size() < 2 ) {
        return;
    }

    QHash<QString, QVariant> settings = route->routingProfile().pluginSettings()["mapquest"];

    if ( settings.value( "appKey" ).toString().isEmpty() )
    {
        return;
    }

    QString url = "http://open.mapquestapi.com/directions/v1/route?callback=renderAdvancedNarrative&outFormat=xml&narrativeType=text&shapeFormat=raw&generalize=0";
    GeoDataCoordinates::Unit const degree = GeoDataCoordinates::Degree;
    append( &url, "from", QString::number( route->source().latitude( degree ), 'f', 6 ) + ',' + QString::number( route->source().longitude( degree ), 'f', 6 ) );
    for ( int i=1; i<route->size(); ++i ) {
        append( &url, "to", QString::number( route->at( i ).latitude( degree ), 'f', 6 ) + ',' + QString::number( route->at( i ).longitude( degree ), 'f', 6 ) );
    }

    QString const unit = MarbleGlobal::getInstance()->locale()->measurementSystem() == MarbleLocale::MetricSystem ? "k" : "m";
    append( &url, "units", unit );

    if ( settings["noMotorways"].toInt() ) {
        append( &url, "avoids", "Limited Access" );
    }
    if ( settings["noTollroads"].toInt() ) {
        append( &url, "avoids", "Toll road" );
    }
    if ( settings["noFerries"].toInt() ) {
        append( &url, "avoids", "Ferry" );
    }

    if ( !settings["preference"].toString().isEmpty() ) {
        append( &url, "routeType", settings["preference"].toString() );
    }

    if ( !settings["ascending"].toString().isEmpty() && !settings["descending"].toString().isEmpty() ) {
            if ( settings["ascending"].toString() == "AVOID_UP_HILL"
                       && settings["descending"].toString() == "AVOID_DOWN_HILL" ) {
                append( &url, "roadGradeStrategy", "AVOID_ALL_HILLS" );
            }
            else if ( settings["ascending"].toString() == "FAVOR_UP_HILL"
                         && settings["descending"].toString() == "FAVOR_DOWN_HILL" ) {
                append( &url, "roadGradeStrategy", "FAVOR_ALL_HILLS" );
            }
            else if ( settings["ascending"].toString() == "DEFAULT_STRATEGY"
                         && settings["descending"].toString() == "DEFAULT_STRATEGY" ) {
                append( &url, "roadGradeStrategy", "DEFAULT_STRATEGY" );
            }
            else if ( settings["ascending"].toString() == "DEFAULT_STRATEGY" ) {
                append( &url, "roadGradeStrategy", settings["descending"].toString() );
            }
            else if ( settings["descending"].toString() == "DEFAULT_STRATEGY" ) {
                append( &url, "roadGradeStrategy", settings["ascending"].toString() );
            }
            else if ( settings["descending"].toString() == "AVOID_DOWN_HILL" ) {
                append( &url, "roadGradeStrategy", settings["descending"].toString() );
            }
            else if ( settings["ascending"].toString() == "AVOID_UP_HILL" ) {
                append( &url, "roadGradeStrategy", settings["ascending"].toString() );
            }
        }
    QUrl qurl(url);
// FIXME: verify that this works with special characters.
#if QT_VERSION >= 0x050000
    QUrlQuery urlQuery;
    urlQuery.addQueryItem( "key", settings.value( "appKey" ).toByteArray() );
    qurl.setQuery(urlQuery);
#else
    qurl.addEncodedQueryItem( "key", settings.value( "appKey" ).toByteArray() );
#endif
    m_request.setUrl( qurl );
    m_request.setRawHeader( "User-Agent", HttpDownloadManager::userAgent( "Browser", "MapQuestRunner" ) );

    QEventLoop eventLoop;

    QTimer timer;
    timer.setSingleShot( true );
    timer.setInterval( 15000 );

    connect( &timer, SIGNAL(timeout()),
             &eventLoop, SLOT(quit()));
    connect( this, SIGNAL(routeCalculated(GeoDataDocument*)),
             &eventLoop, SLOT(quit()) );

    // @todo FIXME Must currently be done in the main thread, see bug 257376
    QTimer::singleShot( 0, this, SLOT(get()) );
    timer.start();

    eventLoop.exec();
}
예제 #16
0
void MainWindow::StartJudging(int row, int column)
{
    if (is_locked) return;

    Global::g_is_judge_stoped = false;

    board_table->ClearHighlighted();
    board_table->horizontalHeader()->setSectionsMovable(false);
    board_table->horizontalHeader()->setSortIndicatorShown(false);
    board_table->horizontalHeader()->setSortIndicator(-1, Qt::AscendingOrder);
    board_table->setSelectionMode(QAbstractItemView::NoSelection);

    detail_table->StartLastJudgeTimer();
    detail_table->ClearDetail();

    LockTable();

    ui->action_configure->setEnabled(false);
    ui->action_set_list->setEnabled(false);
    ui->action_export->setEnabled(false);
    ui->action_refresh->setEnabled(false);
    ui->action_judge_selected->setEnabled(false);
    ui->action_judge_unjudged->setEnabled(false);
    ui->action_judge_all->setEnabled(false);
    ui->action_stop->setEnabled(true);

    judge_thread = new JudgeThread(row, column, this);

    connect(judge_thread, &JudgeThread::titleDetailFinished, detail_table, &DetailTable::onAddTitleDetail);
    connect(judge_thread, &JudgeThread::noteDetailFinished,  detail_table, &DetailTable::onAddNoteDetail);
    connect(judge_thread, &JudgeThread::pointDetailFinished, detail_table, &DetailTable::onAddPointDetail);
    connect(judge_thread, &JudgeThread::scoreDetailFinished, detail_table, &DetailTable::onAddScoreDetail);

    connect(judge_thread, &JudgeThread::itemJudgeFinished,   board_table, &BoardTable::onSetItemUnselected);
    connect(judge_thread, &JudgeThread::labelTextChanged,    board_table, &BoardTable::onUpdateLabelText);
    connect(judge_thread, &JudgeThread::sumLabelChanged,     board_table, &BoardTable::onUpdateSumLabel);
    connect(judge_thread, &JudgeThread::problemLabelChanged, board_table, &BoardTable::onUpdateProblemLabel);

    if (row == -1) // Judge selected
    {
        for (int i = 0; i < Global::g_contest.player_num; i++)
            for (auto j : Global::g_contest.problem_order)
                if (board_table->item(i, j + 2)->isSelected())
                    judge_thread->AppendProblem(i, j + 2);
    }
    else if (row == -2) // Judge unjudged
    {
        for (int i = 0; i < Global::g_contest.player_num; i++)
            for (auto j : Global::g_contest.problem_order)
                if (Global::g_contest.players[Global::GetLogicalRow(i)]->ProblemLabelAt(j)->State() == ' ')
                {
                    judge_thread->AppendProblem(i, j + 2);
                    board_table->item(i, j + 2)->setSelected(true);
                }
    }
    else if (column <= 1) // Judge one player's all problems
    {
        for (auto j : Global::g_contest.problem_order)
            board_table->item(row, j + 2)->setSelected(true);
    }
    else if (column > 1) // Judge one
        judge_thread->AppendProblem(row, column);

    QEventLoop* eventLoop = new QEventLoop(this);
    connect(judge_thread, &QThread::finished, eventLoop, &QEventLoop::quit);
    judge_thread->start();
    eventLoop->exec();
    delete eventLoop;
    delete judge_thread;

    UnlockTable();

    board_table->horizontalHeader()->setSectionsMovable(true);
    board_table->setSelectionMode(QAbstractItemView::ExtendedSelection);

    if (Global::g_is_contest_closed) return;

    ui->action_configure->setEnabled(true);
    ui->action_set_list->setEnabled(true);
    ui->action_export->setEnabled(true);
    ui->action_refresh->setEnabled(true);
    ui->action_judge_selected->setEnabled(true);
    ui->action_judge_unjudged->setEnabled(true);
    ui->action_judge_all->setEnabled(true);
    ui->action_stop->setEnabled(false);

    this->activateWindow();

    Global::g_contest.SaveResultCache();
}
예제 #17
0
void Installer::installpkg() {
    QString url = sender()->property("url").toString();
    uint bsize = sender()->property("bsize").toUInt();

    wait = new QProgressDialog(this);
    wait->setModal(true);
    wait->setMaximum(bsize+1);
    wait->setLabelText(QString("Downloading ") + url + " ...");
    wait->show();

    reply = qnam.get(QNetworkRequest(QUrl(url)));
    reply->setReadBufferSize(bsize*2);
    QEventLoop loop;
    connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(dlProgress(qint64,qint64)));
    loop.exec();

    QString appdata_path = DATALOCATION;
    QDir().mkpath(appdata_path);
    QDir appdata(appdata_path);
    appdata.remove("data.tmp");
    appdata.remove("data.tar");
    appdata.remove("data.tar.xz");
    appdata.remove("debian-binary");
    appdata.remove("control.tar.gz");

    QFile file(appdata.filePath("data.tmp"));
    file.open(QIODevice::WriteOnly);
    file.write(reply->readAll());
    file.close();

    QDir exep(QCoreApplication::applicationDirPath());
    wait->setLabelText("Unpacking ...");
    QProcess *up = new QProcess(this);
    up->setWorkingDirectory(appdata_path);
#if defined(Q_OS_WIN) || defined(Q_OS_MAC)
    up->start(exep.absoluteFilePath("7z"), QStringList() << "x" << "-y" << "data.tmp");
#else
    up->start("ar", QStringList() << "x" << "data.tmp");
#endif
    up->waitForStarted();
    up->waitForFinished();
    up->deleteLater();

    if (appdata.exists("data.tar")) {
        QProcess *up = new QProcess(this);
        up->setWorkingDirectory(appdata_path);
        up->start(exep.absoluteFilePath("7z"), QStringList() << "x" << "-y" << "data.tar");
        up->waitForStarted();
        up->waitForFinished();
        up->deleteLater();
    }

    if (appdata.exists("data.tar.xz")) {
        QProcess *up = new QProcess(this);
        up->setWorkingDirectory(appdata_path);
        up->start("tar", QStringList() << "-Jxf" << "data.tar.xz");
        up->waitForStarted();
        up->waitForFinished();
        up->deleteLater();
    }

    wait->close();
    wait->deleteLater();
    appdata.remove("data.tmp");
    appdata.remove("data.tar");
    appdata.remove("data.tar.xz");
    appdata.remove("debian-binary");
    appdata.remove("control.tar.gz");

    QSettings conf;
    conf.setValue(sender()->property("name").toString(), sender()->property("lm").toString());
}
예제 #18
0
void Synchro::GetJSON()
{
	try {
		if (oldparse.getJSON().empty() != true)
		{
			char acsjson[1024];
			strcpy(acsjson, this->folder);
			strcat(acsjson, ".acsilserver");
			QFile txt(acsjson);

			txt.open(QIODevice::ReadWrite | QIODevice::Text);
			txt.write(myparse.getJSON().c_str());
			txt.close();

			oldparse.parse(myparse.getJSON());
		}
		else
		{
			char acsjson[1024];
			strcpy(acsjson, this->folder);
			strcat(acsjson, ".acsilserver");
			QFile txt(acsjson);
			if (txt.exists() == true)
			{

				std::string	line;
				std::ifstream myfile(acsjson);
				std::getline(myfile, line);
				while (line.find("-0001-11-30T00:00:00+0009") != std::string::npos)
					replace(line, "-0001-11-30T00:00:00+0009", "2014-10-18T14:24:39+0200");
				oldparse.parse(line);
			}
		}


		char toto[1024];
		strcpy(toto, this->URL);
		strcat(toto, "app_dev.php/service/1/op/listAll");
		m_network = new QNetworkAccessManager();
		QNetworkRequest request;
		QString header = "";

		request.setRawHeader("Authorization", "Bearer " + QByteArray(this->xtoken));
		request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
		request.setRawHeader("Accept", "application/json");
		request.setRawHeader("Accept-encoding", "identity");

		request.setUrl(QUrl(toto));
		QNetworkReply *reply = m_network->post(request, QByteArray(header.toUtf8()));

		QEventLoop loop;
		connect(m_network, SIGNAL(finished(QNetworkReply *)), &loop,
			SLOT(quit()));
		loop.exec();

		QString aQString = QString::fromUtf8(reply->readAll().data());
		std::string json = aQString.toStdString();
		while (json.find("-0001-11-30T00:00:00+0009") != std::string::npos)
			replace(json, "-0001-11-30T00:00:00+0009", "2014-10-18T14:24:39+0200");
		disconnect(m_network);
		myparse.parse(json);
	}
	catch (const std::exception & e) {
		printf(e.what());
	}
}
예제 #19
0
int main(int argc, char**argv)
{
    QCoreApplication app(argc, argv);

#ifdef Q_OS_SYMBIAN
    QNetworkConfigurationManager configurationManager;
    QNetworkConfiguration configuration = configurationManager.defaultConfiguration();
    if (!configuration.isValid()) {
        qDebug() << "Got an invalid session configuration";
        exit(1);
    }

    qDebug() << "Opening session...";
    QNetworkSession *session = new QNetworkSession(configuration);

    // Does not work:
//    session->open();
//    session->waitForOpened();

    // works:
    QEventLoop loop;
    QObject::connect(session, SIGNAL(opened()), &loop, SLOT(quit()), Qt::QueuedConnection);
    QMetaObject::invokeMethod(session, "open", Qt::QueuedConnection);
    loop.exec();


    if (session->isOpen()) {
        qDebug() << "session opened";
    } else {
        qDebug() << "session could not be opened -" << session->errorString();
        exit(1);
    }
#endif

    // create it
    QAbstractSocketEngine *socketEngine =
            QAbstractSocketEngine::createSocketEngine(QAbstractSocket::TcpSocket, QNetworkProxy(QNetworkProxy::NoProxy), 0);
    if (!socketEngine) {
        qDebug() << "could not create engine";
        exit(1);
    }

    // initialize it
    bool initialized = socketEngine->initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol);
    if (!initialized) {
        qDebug() << "not able to initialize engine";
        exit(1);
    }

    // wait for connected
    int r = socketEngine->connectToHost(QHostAddress("74.125.77.99"), 80); // google
    bool readyToRead = false;
    bool readyToWrite = false;
    socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, true, true, 10*1000);
    if (r <= 0) //timeout or error
        exit(1);
    if (readyToWrite) {
        // write the request
        QByteArray request("GET /robots.txt HTTP/1.0\r\n\r\n");
        int ret = socketEngine->write(request.constData(), request.length());
        if (ret == request.length()) {
            // read the response in a loop
            do {
                bool waitReadResult = socketEngine->waitForRead(10*1000);
                int available = socketEngine->bytesAvailable();
                if (waitReadResult == true && available == 0) {
                    // disconnected
                    exit(0);
                }
                bzero(buf, bufsize);
                ret = socketEngine->read(buf, available);
                if (ret > 0) {
#ifdef Q_OS_SYMBIAN
                    qDebug() << buf; //printf goes only to screen, this goes to remote debug channel
#else
                    printf("%s", buf);
#endif
                } else {
                    // some failure when reading
                    exit(1);
                }
            } while (1);
        } else {
            qDebug() << "failed writing";
        }
    } else {
        qDebug() << "failed connecting";
    }
    delete socketEngine;
}
예제 #20
0
// Documentation is at:
// https://strava.pbworks.com/w/page/39241255/v2%20upload%20create
void
StravaUploader::requestUploadStrava()
{
    parent->progressLabel->setText(tr("Upload ride to Strava..."));
    parent->progressBar->setValue(parent->progressBar->value()+10/parent->shareSiteCount);

    QEventLoop eventLoop;
    QNetworkAccessManager networkMgr;

    int year = ride->fileName.left(4).toInt();
    int month = ride->fileName.mid(5,2).toInt();
    int day = ride->fileName.mid(8,2).toInt();
    int hour = ride->fileName.mid(11,2).toInt();
    int minute = ride->fileName.mid(14,2).toInt();;
    int second = ride->fileName.mid(17,2).toInt();;

    QDate rideDate = QDate(year, month, day);
    QTime rideTime = QTime(hour, minute, second);
    QDateTime rideDateTime = QDateTime(rideDate, rideTime);

    connect(&networkMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestUploadStravaFinished(QNetworkReply*)));
    connect(&networkMgr, SIGNAL(finished(QNetworkReply *)), &eventLoop, SLOT(quit()));

    TcxFileReader reader;

    QUrl url = QUrl( "https://www.strava.com/api/v3/uploads" ); // The V3 API doc said "https://api.strava.com" but it is not working yet
    QNetworkRequest request = QNetworkRequest(url);

    //QString boundary = QString::number(qrand() * (90000000000) / (RAND_MAX + 1) + 10000000000, 16);
    QString boundary = QVariant(qrand()).toString()+QVariant(qrand()).toString()+QVariant(qrand()).toString();

    QByteArray file = reader.toByteArray(context, ride->ride(), parent->altitudeChk->isChecked(), parent->powerChk->isChecked(), parent->heartrateChk->isChecked(), parent->cadenceChk->isChecked());

    // MULTIPART *****************

    QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
    multiPart->setBoundary(boundary.toLatin1());

    QHttpPart accessTokenPart;
    accessTokenPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"access_token\""));
    accessTokenPart.setBody(token.toLatin1());

    QHttpPart activityTypePart;
    activityTypePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"activity_type\""));
    activityTypePart.setBody("ride");

    QHttpPart activityNamePart;
    activityNamePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"activity_name\""));
    activityNamePart.setBody(QString(parent->titleEdit->text()).toLatin1());

    QHttpPart dataTypePart;
    dataTypePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"data_type\""));
    dataTypePart.setBody("tcx");

    QHttpPart externalIdPart;
    externalIdPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"external_id\""));
    externalIdPart.setBody("Ride");

    QHttpPart privatePart;
    privatePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"private\""));
    privatePart.setBody("TRUE");

    QHttpPart filePart;
    filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/xml"));
    filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\"; filename=\"file.tcx\"; type=\"text/xml\""));
    filePart.setBody(file);


    multiPart->append(accessTokenPart);
    multiPart->append(activityTypePart);
    multiPart->append(activityNamePart);
    multiPart->append(dataTypePart);
    multiPart->append(externalIdPart);
    multiPart->append(privatePart);
    multiPart->append(filePart);

    QScopedPointer<QNetworkReply> reply( networkMgr.post(request, multiPart) );
    multiPart->setParent(reply.data());

    parent->progressBar->setValue(parent->progressBar->value()+30/parent->shareSiteCount);
    parent->progressLabel->setText(tr("Upload ride... Sending to Strava"));

    eventLoop.exec();
}
예제 #21
0
/*!
  \internal

  Returns the index of \a essid in the list of known networks. If \a essid is empty
  we connect to the next network in the list of known networks.

  This function returns 0 if there is no network with name \a essid or none
  of the known networks is available/online.

  This function performs an active scan and will block until the scan has completed.
*/
int RoamingMonitor::selectWLAN( const QString& essid )
{
    QNetworkDevice dev( configIface->configFile() );
    const QVariant numNets = configIface->property("WirelessNetworks/size");

    if ( !numNets.isValid() ) {
        qLog(Network) << "Cannot connect on" << dev.interfaceName() << ". WLAN configuration missing.";
        return 0; //we don't have a valid configuration. no point in going on
    }

    //if an essid was passed we directly connect to the network
    //otherwise we go through the list of known networks and connect to the first
    //wlan that is online

    //get list of known networks
    //NOTE: if two nets use the same essid we only select the one that comes first
    QStringList knownEssids;
    QStringList knownMACs;
    for( int i=1; i<= numNets.toInt(); i++ ) {
        QString keyPrefix = "WirelessNetworks/"+QString::number(i);
        QString id = configIface->property( keyPrefix+"/ESSID").toString();
        knownEssids.append( id );
        knownMACs.append( configIface->property(keyPrefix+"/AccessPoint").toString() );
        if ( !essid.isEmpty() && essid == id ) {
            qLog(Network) << "Trying to directly connect to" << essid << "on interface"
                << dev.interfaceName();
            return i;
        }
    }
    if ( !essid.isEmpty() )
        return 0; //didn't find the given essid among known networks;

#if WIRELESS_EXT > 13
    //get list of all networks around us
    if ( !scanner ) {
        //we don't have scanning facilities
        //connect to first entry in list
        return 1; //there has to be at least one network ( numNets.toInt() > 0 )
    }

    //do active scan and wait until we have new scan result
    QEventLoop* loop = new QEventLoop();
    if ( !scanner->isScanning() ) {
        const bool hasStarted = scanner->startScanning();
        if ( !hasStarted ) {
            qLog(Network) << "Can not start scan. Attempting to start first configured network.";
            delete loop;
            return 1;
        }
    } // else { //already scanning}
    connect( scanner, SIGNAL(scanningFinished()), loop, SLOT(quit()) );
    loop->exec();
    delete loop;
    
    const QList<WirelessNetwork> results = scanner->results();
    if ( !results.count() ) {
        qLog(Network) << "Could not find any known WLAN that surrounds us";
        return 0;
    }
    QStringList onlineMacs;
    QStringList onlineEssids;
    foreach( WirelessNetwork net, results ) {
        onlineMacs.append( net.data( WirelessNetwork::AP ).toString() );
        onlineEssids.append( net.data( WirelessNetwork::ESSID ).toString() );
    }
예제 #22
0
void
RideWithGpsUploader::requestUploadRideWithGPS()
{
    parent->progressLabel->setText(tr("Upload ride..."));
    parent->progressBar->setValue(parent->progressBar->value()+10/parent->shareSiteCount);

    QEventLoop eventLoop;
    QNetworkAccessManager networkMgr;

    int prevSecs = 0;
    long diffSecs = 0;

    int year = ride->fileName.left(4).toInt();
    int month = ride->fileName.mid(5,2).toInt();
    int day = ride->fileName.mid(8,2).toInt();
    int hour = ride->fileName.mid(11,2).toInt();
    int minute = ride->fileName.mid(14,2).toInt();;
    int second = ride->fileName.mid(17,2).toInt();;

    QDate rideDate = QDate(year, month, day);
    QTime rideTime = QTime(hour, minute, second);
    QDateTime rideDateTime = QDateTime(rideDate, rideTime);

    connect(&networkMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestUploadRideWithGPSFinished(QNetworkReply*)));
    connect(&networkMgr, SIGNAL(finished(QNetworkReply *)), &eventLoop, SLOT(quit()));
    QString out, data;

    QVector<RideFilePoint*> vectorPoints = ride->ride()->dataPoints();
    int totalSize = vectorPoints.size();

    int size = 0;

    QString username = appsettings->cvalue(context->athlete->cyclist, GC_RWGPSUSER).toString();
    QString password = appsettings->cvalue(context->athlete->cyclist, GC_RWGPSPASS).toString();

    // application/json
    out += "{\"apikey\": \"p24n3a9e\", ";
    out += "\"email\": \""+username+"\", ";
    out += "\"password\": \""+password+"\", ";
    out += "\"track_points\": \"";

    data += "\[";
    foreach (const RideFilePoint *point, ride->ride()->dataPoints())
    {
        size++;

        if (point->secs == 0.0)
            continue;

        diffSecs = point->secs - prevSecs;
        prevSecs = point->secs;
        rideDateTime = rideDateTime.addSecs(diffSecs);

        data += "{\"x\": ";
        data += QString("%1").arg(point->lon,0,'f',GPS_COORD_TO_STRING);
        data += ", \"y\": ";
        data += QString("%1").arg(point->lat,0,'f',GPS_COORD_TO_STRING);
        data += ", \"t\": ";
        data += QString("%1").arg(rideDateTime.toTime_t());

        if (parent->altitudeChk->isChecked()) {
            data += ", \"e\": ";
            data += QString("%1").arg(point->alt);
        }
        if (parent->powerChk->isChecked()) {
            data += ", \"p\": ";
            data += QString("%1").arg(point->watts);
        }
        if (parent->cadenceChk->isChecked()) {
            data += ", \"c\": ";
            data += QString("%1").arg(point->cad);
        }
        if (parent->heartrateChk->isChecked()) {
            data += ", \"h\": ";
            data += QString("%1").arg(point->hr);
        }

        data += "}";

        if(size < totalSize)
           data += ",";
    }
    data += "]";
    out += data.replace("\"","\\\"");
    out += "\"}";

    QUrl url = QUrl("http://ridewithgps.com/trips.json");
    QNetworkRequest request = QNetworkRequest(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    parent->progressBar->setValue(parent->progressBar->value()+30/parent->shareSiteCount);
    parent->progressLabel->setText(tr("Upload ride... Sending to RideWithGPS"));

    networkMgr.post( request, out.toLatin1());
    eventLoop.exec();
}
예제 #23
0
    void UrlFactory::TryCorrectGoogleVersions()
    {
        QMutexLocker locker(&mutex);
        if(CorrectGoogleVersions && !IsCorrectGoogleVersions())
        {
            QNetworkReply *reply;
            QNetworkRequest qheader;
            QNetworkAccessManager network;
            QEventLoop q;
            QTimer tT;
            tT.setSingleShot(true);
            connect(&network, SIGNAL(finished(QNetworkReply*)),
                    &q, SLOT(quit()));
            connect(&tT, SIGNAL(timeout()), &q, SLOT(quit()));
            network.setProxy(Proxy);
#ifdef DEBUG_URLFACTORY
            qDebug()<<"Correct GoogleVersion";
#endif //DEBUG_URLFACTORY
            setIsCorrectGoogleVersions(true);
            QString url = "https://maps.google.com";

            qheader.setUrl(QUrl(url));
            qheader.setRawHeader("User-Agent",UserAgent);
            reply=network.get(qheader);
            tT.start(Timeout);
            q.exec();
            if(!tT.isActive())
                return;
            tT.stop();
            if( (reply->error()!=QNetworkReply::NoError))
            {
#ifdef DEBUG_URLFACTORY
                qDebug()<<"Try corrected version withou abort or error:"<<reply->errorString();
#endif //DEBUG_URLFACTORY
                return;
            }
            QString html=QString(reply->readAll());
            QRegExp reg("\"*https://mt0.google.com/vt/lyrs=m@(\\d*)",Qt::CaseInsensitive);
            if(reg.indexIn(html)!=-1)
            {
                QStringList gc=reg.capturedTexts();
                VersionGoogleMap = QString("m@%1").arg(gc[1]);
                VersionGoogleMapChina = VersionGoogleMap;
#ifdef DEBUG_URLFACTORY
                qDebug()<<"TryCorrectGoogleVersions, VersionGoogleMap: "<<VersionGoogleMap;
#endif //DEBUG_URLFACTORY
            }

            reg=QRegExp("\"*https://mt0.google.com/vt/lyrs=h@(\\d*)",Qt::CaseInsensitive);
            if(reg.indexIn(html)!=-1)
            {
                QStringList gc=reg.capturedTexts();
                VersionGoogleLabels = QString("h@%1").arg(gc[1]);
                VersionGoogleLabelsChina = VersionGoogleLabels;
#ifdef DEBUG_URLFACTORY
                qDebug()<<"TryCorrectGoogleVersions, VersionGoogleLabels: "<<VersionGoogleLabels;
#endif //DEBUG_URLFACTORY
            }
            reg=QRegExp("\"*https://khm\\D?\\d.google.com/kh/v=(\\d*)",Qt::CaseInsensitive);
            if(reg.indexIn(html)!=-1)
            {
                QStringList gc=reg.capturedTexts();
                VersionGoogleSatellite = gc[1];
                VersionGoogleSatelliteKorea = VersionGoogleSatellite;
                VersionGoogleSatelliteChina = "s@" + VersionGoogleSatellite;

                qDebug()<<"TryCorrectGoogleVersions, VersionGoogleSatellite: "<<VersionGoogleSatellite;

            }
            reg=QRegExp("\"*https://mt0.google.com/vt/lyrs=t@(\\d*),r@(\\d*)",Qt::CaseInsensitive);
            if(reg.indexIn(html)!=-1)
            {
                QStringList gc=reg.capturedTexts();
                VersionGoogleTerrain = QString("t@%1,r@%2").arg(gc[1]).arg(gc[2]);
                VersionGoogleTerrainChina = VersionGoogleTerrain;
#ifdef DEBUG_URLFACTORY
                qDebug()<<"TryCorrectGoogleVersions, VersionGoogleTerrain: "<<VersionGoogleTerrain;
#endif //DEBUG_URLFACTORY
            }
            reply->deleteLater();

        }
예제 #24
0
QJsonObject SeleniumServerHub::exec(QString url, QByteArray rawBody, int method)
{
    m_result = "";
    QJsonObject result;

    QUrl urlObject(m_urlHub + url);
    QNetworkRequest request(urlObject);

    QString contentType = "application/json";

    QNetworkAccessManager* manager = new QNetworkAccessManager(this);

    if(method == GET) {

        m_reply = manager->get(request);

    } else if(method == POST) {

        if(rawBody.isEmpty()) {

            request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
            m_reply = manager->post(request, "");

        } else {

            QByteArray postDataSize = QByteArray::number(rawBody.size());
            request.setRawHeader("Content-Type", contentType.toLatin1());
            request.setRawHeader("Content-Length", postDataSize);

            m_reply = manager->post(request, rawBody);
        }

    } else if(method == DELETE) {

        m_reply = manager->deleteResource(request);

    } else {
        throw (new QueleniumException("Unsupported method", 99));
    }

    connect(m_reply, SIGNAL(readyRead()), SLOT(slotReplyResponse()));
    connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(slotReplyError()));
    connect(m_reply, SIGNAL(finished()), SLOT(slotFinishRequest()));

    //this loop for synchronize requests
    QEventLoop loop;
    connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), &loop, SLOT(quit()));
    connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), &loop, SLOT(deleteLater()));
    connect(m_reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();

    if(m_result.trimmed().isEmpty()) {
        WebDriverException::throwException("Empty reply from server");
    }

    result = QJsonDocument::fromJson(m_result.toUtf8()).object();

    if(result["status"].toInt() != ResponseStatusCodes::SUCCESS) {

        QString message = result["state"].toString();
        if(result["value"].isObject() && result["value"].toObject()["message"].isString()) {
            message = result["value"].toObject()["message"].toString();
        }

        WebDriverException::throwException(message, result["status"].toInt());
    }

    return result;
}
예제 #25
0
/*!
 * \brief Handle doc translation
 */
void Translator::fileTranslate(QString filePath)
{

    QDir outputDocDir(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation));
    QString dirName = tr("Apertium Translated Documents");
    outputDocDir.mkdir(dirName);
    if (!outputDocDir.cd(dirName)) {
        emit fileTranslateRejected();
        return;
    }
    QFileInfo fileInfo(filePath);
#ifdef Q_OS_LINUX
    auto multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
    QHttpPart filePart;
    filePart.setHeader(QNetworkRequest::ContentDispositionHeader,
                       QVariant("form-data; filename=\"" + fileInfo.fileName() + "\"; name=\"file\""));
    auto file = new QFile(filePath);
    if (!file->open(QIODevice::ReadOnly)) {
        emit fileTranslateRejected();
        return;
    }
    filePart.setBodyDevice(file);
    file->setParent(multiPart);
    multiPart->append(filePart);

    QUrlQuery query;
    query.addQueryItem("langpair",
                       parent->getCurrentSourceLang() + "|" + parent->getCurrentTargetLang());
    QUrl url("http://localhost:2737/translateDoc?");
    QNetworkRequest request(QUrl(url.url() + query.query()));
    QNetworkAccessManager mngr;
    QEventLoop loop;
    QNetworkReply *reply = mngr.post(request, multiPart);
    connect(reply, &QNetworkReply::finished, [&]() {
        loop.exit();
        if (reply->error() != QNetworkReply::NoError) {
            qDebug() << reply->errorString();
            emit fileTranslateRejected();
            return;
        }
        QFile outDoc(outputDocDir.absoluteFilePath(fileInfo.baseName() + "_" +
                                                   parent->getCurrentSourceLang()
                                                   + "-" + parent->getCurrentTargetLang() + "." + fileInfo.completeSuffix()));
        if (!outDoc.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
            emit fileTranslateRejected();
            reply->deleteLater();
            return;
        }
        outDoc.write(reply->readAll());
        outDoc.close();
        emit fileTranslated(outDoc.fileName());
        reply->deleteLater();
    });
    loop.exec();
#else
    if (fileInfo.suffix() == "txt")
        translateTxt(filePath, outputDocDir);
    else if (fileInfo.suffix() == "docx")
        translateDocx(filePath, outputDocDir);
    else if (fileInfo.suffix() == "pptx")
        translatePptx(filePath, outputDocDir);
    else if (fileInfo.suffix() == "xlsx")
        translateXlsx(filePath, outputDocDir);
    else if (fileInfo.suffix() == "html")
        translateHtml(filePath, outputDocDir);
    else if (fileInfo.suffix() == "rtf")
        translateRtf(filePath, outputDocDir);
#endif
}
예제 #26
0
void generateThumbs(QString originalFileName, int n, QSize size, QSize minimumSize, QString mimeType, QString flavor)
{
    std::cout << "Generating " << n <<" "<< flavor.toAscii().constData() << size.width() << "x" << size.height() << " thumbnails for " << originalFileName.toLocal8Bit().constData() << " MIME " << mimeType.toAscii().constData() << "\n";

    QEventLoop loop;
    QTime time;

    Quill::setTemporaryFilePath(QDir::homePath() + Strings::testsTempDir);
    Quill::setPreviewSize(0, size);
    Quill::setMinimumPreviewSize(0, minimumSize);
    Quill::setThumbnailFlavorName(0, flavor);
    Quill::setThumbnailExtension(Strings::jpeg);
    Quill::setThumbnailCreationEnabled(false);

    int numFiles = n;

    QString fileName[numFiles];
    QuillFile *quillFile[numFiles];

    for (int i=0; i<numFiles; i++) {
        {   // Needed for the life of the QTemporaryFile
            QTemporaryFile file;
            file.setFileTemplate(QDir::homePath() + Strings::testsTempFilePattern);
            file.open();
            fileName[i] = file.fileName();
            file.close();
        }
        QFile::remove(fileName[i]);
        QFile::copy(originalFileName, fileName[i]);
    }

    time.start();

    for (int i=0; i<numFiles; i++) {
        quillFile[i] = new QuillFile(fileName[i], mimeType);
        QObject::connect(quillFile[i], SIGNAL(imageAvailable(const QuillImageList)),
                         &loop, SLOT(quit()));
    }

    int initTime = time.elapsed();

    for (int i=0; i<numFiles; i++)
        quillFile[i]->setDisplayLevel(0);

    int displayLevelTime = time.elapsed();

    do
        loop.exec();
    while (Quill::isCalculationInProgress());

    int finalTime = time.elapsed();

    for (int i=0; i<numFiles; i++)
        if (quillFile[i]->image(0).isNull()) {
            std::cout<<"Error: not all images are loaded!\n";
            return;
        }

    std::cout << "Initialize " << numFiles << " QuillFiles: "
             << initTime << "ms" << "\n";

    std::cout << "Set display levels of " << numFiles << " QuillFiles: "
             << displayLevelTime - initTime << "ms" << "\n";

    std::cout << "Use case generate " << numFiles << " thumbnails: "
             << finalTime << "ms" << "\n";

    for (int i=0; i<numFiles; i++) {
        delete quillFile[i];
        QFile::remove(fileName[i]);
    }
}
예제 #27
0
void ZTPManager::msleep(int msecs)
{
    QEventLoop q;
    QTimer::singleShot(msecs,&q,SLOT(quit()));
    q.exec();
}
예제 #28
0
void AddFilm::parseHtml()
{
    int begin, end = 0;
    QNetworkReply *reply = manager->get(QNetworkRequest(QUrl(urlLine->text())));
    QEventLoop loop;
    connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();
    //QByteArray arr = reply->readAll();
    QString text = reply->readAll();//QString::fromAscii(arr.data());
    //text = tr("%1").arg(text);

    //------------------название фильма-------------------------//

    begin = text.indexOf("<meta itemprop=\"name\" content=\"");
    end = text.indexOf("<meta itemprop=\"alternativeHeadline\"");

    qDebug() << begin;
    qDebug() << end;

    QString title = text.mid(begin, end - begin);
    title.remove("<meta itemprop=\"name\" content=\"");
    title.remove("/>");
    title.remove("\"");
    title.remove(title.length() - 1, 1);
    titleLine->setText(title);

    //------------------название фильма-------------------------//


    //------------------год фильма-------------------------//

    begin = text.indexOf("<meta itemprop=\"dateCreated\" content=\"");
    end = text.indexOf("<meta itemprop=\"url\"");

    QString year = text.mid(begin, end - begin);
    year.remove("/>");
    year.remove("\"");
    year.remove(year.length() - 1, 1);
    year = year.right(4);
    yearLine->setText(year);

    //------------------год фильма-------------------------//


    //------------------режиссер фильма-------------------------//
    end = text.indexOf("</span></a></p><p");
    begin = end - 50;
    QString director = text.mid(begin, end - begin);
    int temp = director.indexOf("name\">");
    director.remove(0, temp + 6);
    directorLine->setText(director);

    //------------------режиссер фильма-------------------------//



    //------------------жанр фильма-------------------------//

    begin = text.indexOf("<br/></td></tr><tr><td colspan='2'><span style='header'>");
    end = text.indexOf("</a></td></tr><tr><td colspan='2'><em class=");
    QString genre = text.mid(begin, end - begin);
    genre.remove(QRegExp("[a-zA-Z</>=':-#]"));
    genre.remove(0, 7);
    genre = genre.simplified();
    genreLine->setText(genre);

    //------------------жанр фильма-------------------------//



    //------------------описание фильма-------------------------//

    begin = text.indexOf("<meta itemprop=\"description\" content=");
    end = text.indexOf("/><meta itemprop=\"name\"");

    qDebug() << begin;
    qDebug() << end;

    QString desc = text.mid(begin, end - begin);
    desc.remove(0, 38);
    desc.remove(desc.length() - 2, 1);
    desc = desc.simplified();
    descriptionText->setText(desc);

    //------------------описание фильма-------------------------//


    //------------------постер фильма-------------------------//

    begin = text.indexOf("<link rel='image_src' href=");
    end = text.indexOf("<meta property=\"og:url\"");
    QString url = text.mid(begin, end - begin);
    url.remove(0, 28);
    url = url.simplified();
    url.remove(url.length() - 3, 3);
    linkLine->setText(url);

    //------------------постер фильма-------------------------//


    //------------------ппродолжительность фильма-------------------------//

    end = text.indexOf("<br/></td></tr><tr><td colspan='2'><p align=");
    begin = end - 5;
    QString time = text.mid(begin, end - begin);
    qDebug() << time;
    int h1 = time.left(1).toInt();
    int h2 = time.left(2).toInt();
    int m1 = time.left(4).toInt();
    int m2 = time.left(5).toInt();
    qDebug() << h1 << h2 << m1 << m2;

    //------------------ппродолжительность фильма-------------------------//
}
예제 #29
0
void QtWebKitWebWidget::triggerAction(WindowAction action, bool checked)
{
	const QWebPage::WebAction webAction = mapAction(action);

	if (webAction != QWebPage::NoWebAction)
	{
		m_webView->triggerPageAction(webAction, checked);

		return;
	}

	switch (action)
	{
		case RewindBackAction:
			m_webView->page()->history()->goToItem(m_webView->page()->history()->itemAt(0));

			break;
		case RewindForwardAction:
			m_webView->page()->history()->goToItem(m_webView->page()->history()->itemAt(m_webView->page()->history()->count() - 1));

			break;
		case CopyAddressAction:
			QApplication::clipboard()->setText(getUrl().toString());

			break;
		case ZoomInAction:
			setZoom(qMin((getZoom() + 10), 10000));

			break;
		case ZoomOutAction:
			setZoom(qMax((getZoom() - 10), 10));

			break;
		case ZoomOriginalAction:
			setZoom(100);

			break;
		case ReloadOrStopAction:
			if (isLoading())
			{
				triggerAction(StopAction);
			}
			else
			{
				triggerAction(ReloadAction);
			}

			break;
		case OpenLinkInNewTabAction:
			if (m_hitResult.linkUrl().isValid())
			{
				emit requestedOpenUrl(m_hitResult.linkUrl(), false, false);
			}

			break;
		case OpenLinkInNewTabBackgroundAction:
			if (m_hitResult.linkUrl().isValid())
			{
				emit requestedOpenUrl(m_hitResult.linkUrl(), true, false);
			}

			break;
		case OpenLinkInNewWindowAction:
			if (m_hitResult.linkUrl().isValid())
			{
				emit requestedOpenUrl(m_hitResult.linkUrl(), false, true);
			}

			break;
		case OpenLinkInNewWindowBackgroundAction:
			if (m_hitResult.linkUrl().isValid())
			{
				emit requestedOpenUrl(m_hitResult.linkUrl(), true, true);
			}

			break;
		case BookmarkLinkAction:
			if (m_hitResult.linkUrl().isValid())
			{
				emit requestedAddBookmark(m_hitResult.linkUrl(), m_hitResult.element().attribute(QLatin1String("title")));
			}

			break;
		case OpenSelectionAsLinkAction:
			emit requestedOpenUrl(m_webView->selectedText(), false, false);

			break;
		case ImagePropertiesAction:
			{
				ImagePropertiesDialog dialog(m_hitResult.imageUrl(), m_hitResult.element().attribute(QLatin1String("alt")), m_hitResult.element().attribute(QLatin1String("longdesc")), m_hitResult.pixmap(), (m_networkAccessManager->cache() ? m_networkAccessManager->cache()->data(m_hitResult.imageUrl()) : NULL), this);
				QEventLoop eventLoop;

				m_parent->showDialog(&dialog);

				connect(&dialog, SIGNAL(finished(int)), &eventLoop, SLOT(quit()));
				connect(this, SIGNAL(destroyed()), &eventLoop, SLOT(quit()));

				eventLoop.exec();

				m_parent->hideDialog(&dialog);
			}

			break;
		case InspectPageAction:
			if (!m_inspector)
			{
				m_inspector = new QWebInspector(this);
				m_inspector->setPage(m_webView->page());
				m_inspector->setContextMenuPolicy(Qt::NoContextMenu);
				m_inspector->setMinimumHeight(200);

				m_splitter->addWidget(m_inspector);
			}

			m_inspector->setVisible(checked);

			getAction(InspectPageAction)->setChecked(checked);

			emit actionsChanged();
			emit progressBarGeometryChanged();

			break;
		case SaveLinkToDownloadsAction:
			TransfersManager::startTransfer(m_hitResult.linkUrl().toString(), QString(), isPrivate(), true);

			break;
		case OpenFrameInThisTabAction:
			if (m_hitResult.frame())
			{
				setUrl(m_hitResult.frame()->url().isValid() ? m_hitResult.frame()->url() : m_hitResult.frame()->requestedUrl());
			}

			break;
		case OpenFrameInNewTabBackgroundAction:
			if (m_hitResult.frame())
			{
				emit requestedOpenUrl((m_hitResult.frame()->url().isValid() ? m_hitResult.frame()->url() : m_hitResult.frame()->requestedUrl()), true, false);
			}

			break;
		case CopyFrameLinkToClipboardAction:
			if (m_hitResult.frame())
			{
				QGuiApplication::clipboard()->setText((m_hitResult.frame()->url().isValid() ? m_hitResult.frame()->url() : m_hitResult.frame()->requestedUrl()).toString());
			}

			break;
		case ReloadFrameAction:
			if (m_hitResult.frame())
			{
				const QUrl url = (m_hitResult.frame()->url().isValid() ? m_hitResult.frame()->url() : m_hitResult.frame()->requestedUrl());

				m_hitResult.frame()->setUrl(QUrl());
				m_hitResult.frame()->setUrl(url);
			}

			break;
		case SearchAction:
			search(getAction(SearchAction));

			break;
		case CreateSearchAction:
			{
				QWebElement parentElement = m_hitResult.element().parent();

				while (!parentElement.isNull() && parentElement.tagName().toLower() != "form")
				{
					parentElement = parentElement.parent();
				}

				const QWebElementCollection inputs = parentElement.findAll(QLatin1String("input:not([disabled])[name], select:not([disabled])[name], textarea:not([disabled])[name]"));

				if (!parentElement.isNull() && parentElement.hasAttribute(QLatin1String("action")) && inputs.count() > 0)
				{
					QUrlQuery parameters;

					for (int i = 0; i < inputs.count(); ++i)
					{
						QString value;

						if (inputs.at(i).tagName().toLower() == QLatin1String("textarea"))
						{
							value = inputs.at(i).toPlainText();
						}
						else if (inputs.at(i).tagName().toLower() == QLatin1String("select"))
						{
							const QWebElementCollection options = inputs.at(i).findAll(QLatin1String("option"));

							for (int j = 0; j < options.count(); ++j)
							{
								if (options.at(j).hasAttribute(QLatin1String("selected")))
								{
									value = options.at(j).attribute(QLatin1String("value"), options.at(j).toPlainText());

									break;
								}
							}
						}
						else
						{
							if ((inputs.at(i).attribute(QLatin1String("type")) == QLatin1String("checkbox") || inputs.at(i).attribute(QLatin1String("type")) == QLatin1String("radio")) && !inputs.at(i).hasAttribute(QLatin1String("checked")))
							{
								continue;
							}

							value = inputs.at(i).attribute(QLatin1String("value"));
						}

						parameters.addQueryItem(inputs.at(i).attribute(QLatin1String("name")), ((inputs.at(i) == m_hitResult.element()) ? QLatin1String("{searchTerms}") : value));
					}

					const QStringList identifiers = SearchesManager::getSearchEngines();
					QStringList shortcuts;
					QList<SearchInformation*> engines;

					for (int i = 0; i < identifiers.count(); ++i)
					{
						SearchInformation *engine = SearchesManager::getSearchEngine(identifiers.at(i));

						if (!engine)
						{
							continue;
						}

						engines.append(engine);

						const QString shortcut = engine->shortcut;

						if (!shortcut.isEmpty())
						{
							shortcuts.append(shortcut);
						}
					}

					QString identifier = getUrl().host().toLower().remove(QRegularExpression(QLatin1String("[^a-z0-9]")));

					while (identifier.isEmpty() || identifiers.contains(identifier))
					{
						identifier = QInputDialog::getText(this, tr("Select Identifier"), tr("Input Unique Search Engine Identifier:"));

						if (identifier.isEmpty())
						{
							return;
						}
					}

					const QIcon icon = m_webView->icon();
					const QUrl url(parentElement.attribute(QLatin1String("action")));
					QVariantHash engineData;
					engineData[QLatin1String("identifier")] = identifier;
					engineData[QLatin1String("isDefault")] = false;
					engineData[QLatin1String("encoding")] = QLatin1String("UTF-8");
					engineData[QLatin1String("selfUrl")] = QString();
					engineData[QLatin1String("resultsUrl")] = (url.isEmpty() ? getUrl() : (url.isRelative() ? getUrl().resolved(url) : url)).toString();
					engineData[QLatin1String("resultsEnctype")] = parentElement.attribute(QLatin1String("enctype"));
					engineData[QLatin1String("resultsMethod")] = ((parentElement.attribute(QLatin1String("method"), QLatin1String("get")).toLower() == QLatin1String("post")) ? QLatin1String("post") : QLatin1String("get"));
					engineData[QLatin1String("resultsParameters")] = parameters.toString(QUrl::FullyDecoded);
					engineData[QLatin1String("suggestionsUrl")] = QString();
					engineData[QLatin1String("suggestionsEnctype")] = QString();
					engineData[QLatin1String("suggestionsMethod")] = QLatin1String("get");
					engineData[QLatin1String("suggestionsParameters")] = QString();
					engineData[QLatin1String("shortcut")] = QString();
					engineData[QLatin1String("title")] = getTitle();
					engineData[QLatin1String("description")] = QString();
					engineData[QLatin1String("icon")] = (icon.isNull() ? Utils::getIcon(QLatin1String("edit-find")) : icon);

					SearchPropertiesDialog dialog(engineData, shortcuts, this);

					if (dialog.exec() == QDialog::Rejected)
					{
						return;
					}

					engineData = dialog.getEngineData();

					if (shortcuts.contains(engineData[QLatin1String("shortcut")].toString()))
					{
						engineData[QLatin1String("shortcut")] = QString();
					}

					SearchInformation *engine = new SearchInformation();
					engine->identifier = engineData[QLatin1String("identifier")].toString();
					engine->title = engineData[QLatin1String("title")].toString();
					engine->description = engineData[QLatin1String("description")].toString();
					engine->shortcut = engineData[QLatin1String("shortcut")].toString();
					engine->encoding = engineData[QLatin1String("encoding")].toString();
					engine->selfUrl = engineData[QLatin1String("selfUrl")].toString();
					engine->resultsUrl.url = engineData[QLatin1String("resultsUrl")].toString();
					engine->resultsUrl.enctype = engineData[QLatin1String("resultsEnctype")].toString();
					engine->resultsUrl.method = engineData[QLatin1String("resultsMethod")].toString();
					engine->resultsUrl.parameters = QUrlQuery(engineData[QLatin1String("resultsParameters")].toString());
					engine->icon = engineData[QLatin1String("icon")].value<QIcon>();

					engines.append(engine);

					if (SearchesManager::setSearchEngines(engines) && engineData[QLatin1String("isDefault")].toBool())
					{
						SettingsManager::setValue(QLatin1String("Browser/DefaultSearchEngine"), engineData[QLatin1String("identifier")].toString());
					}
				}
			}

			break;
		case ClearAllAction:
			triggerAction(SelectAllAction);
			triggerAction(DeleteAction);

			break;
		default:
			break;
	}
}
예제 #30
0
void QgsGeometryCheckerSetupTab::runChecks()
{
  // Get selected layer
  QList<QgsVectorLayer *> layers = getSelectedLayers();
  if ( layers.isEmpty() )
    return;

  if ( ui.radioButtonOutputNew->isChecked() )
  {
    for ( QgsVectorLayer *layer : layers )
    {
      if ( layer->dataProvider()->dataSourceUri().startsWith( ui.lineEditOutputDirectory->text() ) )
      {
        QMessageBox::critical( this, tr( "Invalid Output Directory" ), tr( "The chosen output directory contains one or more input layers." ) );
        return;
      }
    }
  }
  QgsVectorLayer *lineLayerCheckLayer = ui.comboLineLayerIntersection->isEnabled() ? dynamic_cast<QgsVectorLayer *>( QgsProject::instance()->mapLayer( ui.comboLineLayerIntersection->currentData().toString() ) ) : nullptr;
  QgsVectorLayer *followBoundaryCheckLayer = ui.comboBoxFollowBoundaries->isEnabled() ? dynamic_cast<QgsVectorLayer *>( QgsProject::instance()->mapLayer( ui.comboBoxFollowBoundaries->currentData().toString() ) ) : nullptr;
  if ( layers.contains( lineLayerCheckLayer ) || layers.contains( followBoundaryCheckLayer ) )
  {
    QMessageBox::critical( this, tr( "Error" ), tr( "The test layer set contains a layer selected for a topology check." ) );
    return;
  }

  for ( QgsVectorLayer *layer : layers )
  {
    if ( layer->isEditable() )
    {
      QMessageBox::critical( this, tr( "Editable Input Layer" ), tr( "Input layer are not allowed to be in editing mode." ) );
      return;
    }
  }
  bool selectedOnly = ui.checkBoxInputSelectedOnly->isChecked();

  // Set window busy
  setCursor( Qt::WaitCursor );
  mRunButton->setEnabled( false );
  ui.labelStatus->setText( tr( "<b>Preparing output...</b>" ) );
  ui.labelStatus->show();
  QApplication::processEvents( QEventLoop::ExcludeUserInputEvents );

  QList<QgsVectorLayer *> processLayers;
  if ( ui.radioButtonOutputNew->isChecked() )
  {
    // Get output directory and file extension
    QDir outputDir = QDir( ui.lineEditOutputDirectory->text() );
    QString outputDriverName = ui.comboBoxOutputFormat->currentText();
    QgsVectorFileWriter::MetaData metadata;
    if ( !QgsVectorFileWriter::driverMetadata( outputDriverName, metadata ) )
    {
      QMessageBox::critical( this, tr( "Unknown Output Format" ), tr( "The specified output format cannot be recognized." ) );
      mRunButton->setEnabled( true );
      ui.labelStatus->hide();
      unsetCursor();
      return;
    }
    QString outputExtension = metadata.ext;

    // List over input layers, check which existing project layers need to be removed and create output layers
    QString filenamePrefix = ui.lineEditFilenamePrefix->text();
    QSettings().setValue( "/geometry_checker/previous_values/filename_prefix", filenamePrefix );
    QStringList toRemove;
    QStringList createErrors;
    for ( QgsVectorLayer *layer : layers )
    {
      QString outputPath = outputDir.absoluteFilePath( filenamePrefix + layer->name() + "." + outputExtension );

      // Remove existing layer with same uri from project
      for ( QgsVectorLayer *projectLayer : QgsProject::instance()->layers<QgsVectorLayer *>() )
      {
        if ( projectLayer->dataProvider()->dataSourceUri().startsWith( outputPath ) )
        {
          toRemove.append( projectLayer->id() );
        }
      }

      // Create output layer
      QString errMsg;
      QgsVectorFileWriter::WriterError err =  QgsVectorFileWriter::writeAsVectorFormat( layer, outputPath, layer->dataProvider()->encoding(), layer->crs(), outputDriverName, selectedOnly, &errMsg );
      if ( err != QgsVectorFileWriter::NoError )
      {
        createErrors.append( errMsg );
        continue;
      }

      QgsVectorLayer *newlayer = new QgsVectorLayer( outputPath, QFileInfo( outputPath ).completeBaseName(), QStringLiteral( "ogr" ) );
      if ( selectedOnly )
      {
        QgsFeature feature;

        // Get features to select (only selected features were written up to this point)
        QgsFeatureIds selectedFeatures = newlayer->allFeatureIds();

        // Write non-selected feature ids
        QgsFeatureList features;
        QgsFeatureIterator it = layer->getFeatures();
        while ( it.nextFeature( feature ) )
        {
          if ( !layer->selectedFeatureIds().contains( feature.id() ) )
          {
            features.append( feature );
          }
        }
        newlayer->dataProvider()->addFeatures( features );

        // Set selected features
        newlayer->selectByIds( selectedFeatures );
      }
      processLayers.append( newlayer );
    }

    //  Remove layers from project
    if ( !toRemove.isEmpty() )
    {
      QgsProject::instance()->removeMapLayers( toRemove );
    }

    // Error if an output layer could not be created
    if ( !createErrors.isEmpty() )
    {
      QMessageBox::critical( this, tr( "Layer Creation Failed" ), tr( "Failed to create one or moure output layers:\n%1" ).arg( createErrors.join( "\n" ) ) );
      mRunButton->setEnabled( true );
      ui.labelStatus->hide();
      unsetCursor();
      return;
    }
  }
  else
  {
    processLayers = layers;
  }

  // Check if output layers are editable
  QList<QgsVectorLayer *> nonEditableLayers;
  for ( QgsVectorLayer *layer : processLayers )
  {
    if ( ( layer->dataProvider()->capabilities() & QgsVectorDataProvider::ChangeGeometries ) == 0 )
    {
      nonEditableLayers.append( layer );
    }
  }
  if ( !nonEditableLayers.isEmpty() )
  {
    QStringList nonEditableLayerNames;
    for ( QgsVectorLayer *layer : nonEditableLayers )
    {
      nonEditableLayerNames.append( layer->name() );
    }
    if ( QMessageBox::Yes != QMessageBox::question( this, tr( "Non-editable Output Layers" ), tr( "The following output layers are ina format that does not support editing features:\n%1\n\nThe geometry check can be performed, but it will not be possible to fix any errors. Do you want to continue?" ).arg( nonEditableLayerNames.join( "\n" ) ), QMessageBox::Yes, QMessageBox::No ) )
    {
      if ( ui.radioButtonOutputNew->isChecked() )
      {
        for ( QgsVectorLayer *layer : processLayers )
        {
          QString layerPath = layer->dataProvider()->dataSourceUri();
          delete layer;
          if ( ui.comboBoxOutputFormat->currentText() == QLatin1String( "ESRI Shapefile" ) )
          {
            QgsVectorFileWriter::deleteShapeFile( layerPath );
          }
          else
          {
            QFile( layerPath ).remove();
          }
        }
        mRunButton->setEnabled( true );
        ui.labelStatus->hide();
        unsetCursor();
      }
      return;
    }
  }

  // Setup checker
  ui.labelStatus->setText( tr( "<b>Building spatial index...</b>" ) );
  QApplication::processEvents( QEventLoop::ExcludeUserInputEvents );
  QMap<QString, QgsFeaturePool *> featurePools;
  for ( QgsVectorLayer *layer : processLayers )
  {
    double layerToMapUntis = mIface->mapCanvas()->mapSettings().layerToMapUnits( layer );
    QgsCoordinateTransform layerToMapTransform = QgsCoordinateTransformCache::instance()->transform( layer->crs().authid(), mIface->mapCanvas()->mapSettings().destinationCrs().authid() );
    featurePools.insert( layer->id(), new QgsFeaturePool( layer, layerToMapUntis, layerToMapTransform, selectedOnly ) );
  }
  // LineLayerIntersection check is enabled, make sure there is also a feature pool for that layer
  if ( ui.checkLineLayerIntersection->isChecked() && !featurePools.keys().contains( ui.comboLineLayerIntersection->currentData().toString() ) )
  {
    QgsVectorLayer *layer = dynamic_cast<QgsVectorLayer *>( QgsProject::instance()->mapLayer( ui.comboLineLayerIntersection->currentData().toString() ) );
    Q_ASSERT( layer );
    double layerToMapUntis = mIface->mapCanvas()->mapSettings().layerToMapUnits( layer );
    QgsCoordinateTransform layerToMapTransform = QgsCoordinateTransformCache::instance()->transform( layer->crs().authid(), mIface->mapCanvas()->mapSettings().destinationCrs().authid() );
    featurePools.insert( layer->id(), new QgsFeaturePool( layer, layerToMapUntis, layerToMapTransform, selectedOnly ) );
  }

  QgsGeometryCheckerContext *context = new QgsGeometryCheckerContext( ui.spinBoxTolerance->value(), mIface->mapCanvas()->mapSettings().destinationCrs().authid(), featurePools );

  QList<QgsGeometryCheck *> checks;
  for ( const QgsGeometryCheckFactory *factory : QgsGeometryCheckFactoryRegistry::getCheckFactories() )
  {
    QgsGeometryCheck *check = factory->createInstance( context, ui );
    if ( check )
    {
      checks.append( check );
    }
  }
  QgsGeometryChecker *checker = new QgsGeometryChecker( checks, context );

  emit checkerStarted( checker );

  if ( ui.radioButtonOutputNew->isChecked() )
  {
    QList<QgsMapLayer *> addLayers;
    for ( QgsVectorLayer *layer : processLayers )
    {
      addLayers.append( layer );
    }
    QgsProject::instance()->addMapLayers( addLayers );
  }

  // Run
  ui.buttonBox->addButton( mAbortButton, QDialogButtonBox::ActionRole );
  mRunButton->hide();
  ui.progressBar->setRange( 0, 0 );
  ui.labelStatus->hide();
  ui.progressBar->show();
  ui.widgetInputs->setEnabled( false );
  QEventLoop evLoop;
  QFutureWatcher<void> futureWatcher;
  connect( checker, &QgsGeometryChecker::progressValue, ui.progressBar, &QProgressBar::setValue );
  connect( &futureWatcher, &QFutureWatcherBase::finished, &evLoop, &QEventLoop::quit );
  connect( mAbortButton, &QAbstractButton::clicked, &futureWatcher, &QFutureWatcherBase::cancel );
  connect( mAbortButton, &QAbstractButton::clicked, this, &QgsGeometryCheckerSetupTab::showCancelFeedback );

  int maxSteps = 0;
  futureWatcher.setFuture( checker->execute( &maxSteps ) );
  ui.progressBar->setRange( 0, maxSteps );
  evLoop.exec();

  // Restore window
  unsetCursor();
  mAbortButton->setEnabled( true );
  ui.buttonBox->removeButton( mAbortButton );
  mRunButton->setEnabled( true );
  mRunButton->show();
  ui.progressBar->hide();
  ui.labelStatus->hide();
  ui.widgetInputs->setEnabled( true );

  // Show result
  emit checkerFinished( !futureWatcher.isCanceled() );
}