Esempio n. 1
0
void CenterWindow::addMvToPlaylist(QString tvUrl)
{
    myTipWin.show();
    myTipWin.setBusyIndicatorShow(true);
    myTipWin.setText("请求数据中");
    QNetworkAccessManager *manager= new QNetworkAccessManager;
    QNetworkReply *reply = manager->get(QNetworkRequest(QUrl(tvUrl)));
    QEventLoop loop;
    QTimer::singleShot(10000,&loop,SLOT(quit()));
    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();
    QByteArray data = reply->readAll();

    QStringList tvNoHrefList;
    //find tvName(title) and QStringList serials//来源名称及剧集列表
    QRegExp rx_title("<span class=\"title\">.*</span>");
    rx_title.setMinimal(true);
    int pos = 0;
    QString title;
    while ((pos = rx_title.indexIn(data, pos)) != -1) {
        title=rx_title.cap(0);
        pos += rx_title.matchedLength();
    }
    QString tvName = title.replace(QRegExp("<span class=\"title\">|</span>"),"");

    if(data.contains("好看的综艺"))//综艺大分类
    {
        //取出地址中的影视ID,http://www.yunfan.com/show/va/6287162973540335925.html
        QString id = tvUrl.split("/").last().replace(".html","");
        QRegExp rx_vlist("\"tv_ico\".*</div>");
        QRegExp rx_vlist_one("source=\'.*\'");
        QStringList vlist;
        rx_vlist.setMinimal(true);
        rx_vlist_one.setMinimal(true);
        pos = 0;
        QString vlistStr;
        while ((pos = rx_vlist.indexIn(data, pos)) != -1) {
            vlistStr=rx_vlist.cap(0);
            pos += rx_vlist.matchedLength();
        }
        pos=0;
        while ((pos = rx_vlist_one.indexIn(vlistStr, pos)) != -1) {
            QString str=rx_vlist_one.cap(0);
            vlist.append(str.replace(QRegExp("source=\'|\'"),""));
            pos += rx_vlist_one.matchedLength();
        }

        foreach (QString v, vlist) {
            QString tvNoHrefListStr;//tvNoHrefList<<tvNoHrefListStr,tvNoHrefListStr:1#href
            QString jsonUrl = QString("http://www.yunfan.com/show/vapage.php?id=%1&site=%2").arg(id).arg(v);
            QNetworkReply *reply = manager->get(QNetworkRequest(QUrl(jsonUrl)));
            QEventLoop loop;
            QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
            loop.exec();
            QByteArray data = reply->readAll();
            pos=0;
            QRegExp rx_href("href=\'.*\'");
            rx_href.setMinimal(true);
            QString href_temp;
            int i=1;
            while ((pos = rx_href.indexIn(data, pos)) != -1 ) {//(pos = rx_href.indexIn(data, pos)) != -1) &&
                href_temp=rx_href.cap(0);
                href_temp.replace(QRegExp("href=\'|\'"),"");
                href_temp.replace("\\","");
                tvNoHrefListStr.append(QString::number(i)+"#"+href_temp.split("#").value(0,"")+"$");
                pos += rx_href.matchedLength();
                i++;
            }
            tvNoHrefList<<tvNoHrefListStr;

        }
bool Rfc1951Decompressor::canReadLine() const
{
    return _output.contains('\n');
}
Esempio n. 3
0
void Widget::tcpProcessData(QByteArray data, QTcpSocket* socket)
{
    QByteArray* recvBuffer=nullptr;
    for (auto pair : tcpClientsList)
    {
        if (pair.first == socket)
        {
            recvBuffer = pair.second;
            break;
        }
    }
    if (recvBuffer == nullptr)
    {
        logMessage("TCP: Error fetching the socket's associated recv buffer");
        return;
    }

#if DEBUG_LOG
    logMessage("tcpProcessData received : "+data);
#endif

    // Login request (forwarded)
    if (useRemoteLogin && recvBuffer->contains("commfunction=login&") && recvBuffer->contains("&version="))
    {
        logMessage("TCP: Remote login not implemented yet.");
        // We need to add the client with his IP/port/passhash to tcpPlayers if he isn't already there
        Player newPlayer;
        newPlayer.IP = socket->peerAddress().toIPv4Address();
        newPlayer.port = socket->peerPort();
        QString passhash = QString(*recvBuffer);
        passhash = passhash.mid(passhash.indexOf("passhash=")+9);
        passhash.truncate(passhash.indexOf('&'));
        newPlayer.passhash = passhash;
        logMessage("IP:"+newPlayer.IP+", passhash:"+newPlayer.passhash);

        // Then connect to the remote and forward the client's requests
        if (!remoteLoginSock.isOpen())
        {
            remoteLoginSock.connectToHost(remoteLoginIP, remoteLoginPort);
            remoteLoginSock.waitForConnected(remoteLoginTimeout);
            if (!remoteLoginSock.isOpen())
            {
                win.logMessage("TCP: Can't connect to remote login server : timed out.");
                return;
            }
        }
        // We just blindly send everything that we're going to remove from recvBuffer at the end of tcpProcessData
        QByteArray toSend = *recvBuffer;
        toSend.left(toSend.indexOf(data) + data.size());
        remoteLoginSock.write(toSend);
    }
    else if (useRemoteLogin && recvBuffer->contains("Server:")) // Login reply (forwarded)
    {
        logMessage("TCP: Remote login not implemented yet.");
        // First we need to find a player matching the received passhash in tcpPlayers
        // Use the player's IP/port to find a matching socket in tcpClientsList
        // The login headers are all the same, so we can just use loginHeader.bin and send back data
    }
    else if (recvBuffer->contains("commfunction=login&") && recvBuffer->contains("&version=")) // Login request
    {
        QString postData = QString(*recvBuffer);
        *recvBuffer = recvBuffer->right(postData.size()-postData.indexOf("version=")-8-4); // 4 : size of version number (ie:version=1344)
        logMessage("TCP: Login request received :");
        QFile file(QString(NETDATAPATH)+"/loginHeader.bin");
        QFile fileServersList(SERVERSLISTFILEPATH);
        QFile fileBadPassword(QString(NETDATAPATH)+"/loginWrongPassword.bin");
        QFile fileAlready(QString(NETDATAPATH)+"/loginAlreadyConnected.bin");
        QFile fileMaxRegistration(QString(NETDATAPATH)+"/loginMaxRegistered.bin");
        QFile fileMaxConnected(QString(NETDATAPATH)+"/loginMaxConnected.bin");
        if (!file.open(QIODevice::ReadOnly) || !fileBadPassword.open(QIODevice::ReadOnly)
        || !fileAlready.open(QIODevice::ReadOnly) || !fileMaxRegistration.open(QIODevice::ReadOnly)
        || !fileMaxConnected.open(QIODevice::ReadOnly) || !fileServersList.open(QIODevice::ReadOnly))
        {
            logStatusMessage("Error reading login data files");
            stopServer();
        }
        else
        {
            win.logMessage("Version : "+postData.mid(postData.indexOf("version=")+8));
            bool ok=true;
            postData = postData.right(postData.size()-postData.indexOf("username="******"passhash=")-9);
            QString passhash = postData;
            passhash.truncate(postData.indexOf('&'));
            logMessage(QString("IP : ")+socket->peerAddress().toString());
            logMessage(QString("Username : "******"Passhash : ")+passhash);

            // Add player to the players list
            Player* player = Player::findPlayer(tcpPlayers, username);
            if (player->name != username) // Not found, create a new player
            {
                // Check max registered number
                if (tcpPlayers.size() >= maxRegistered)
                {
                    logMessage("TCP: Registration failed, too many players registered");
                    socket->write(fileMaxRegistration.readAll());
                    ok = false;
                }
                else
                {
                    logMessage("TCP: Creating user "+username+" in database");
                    Player* newPlayer = new Player;
                    newPlayer->name = username;
                    newPlayer->passhash = passhash;
                    newPlayer->IP = socket->peerAddress().toString();
                    newPlayer->connected = false; // The connection checks are done by the game servers

                    tcpPlayers << newPlayer;
                    if (!Player::savePlayers(tcpPlayers))
                        ok = false;
                }
            }
            else // Found, compare passhashes, check if already connected
            {
                if (player->passhash != passhash) // Bad password
                {
                    logMessage("TCP: Login failed, wrong password");
                    socket->write(fileBadPassword.readAll());
                    ok=false;
                }
                /*
                else if (newPlayer.connected) // Already connected
                {
                    logMessage("TCP: Login failed, player already connected");
                    socket->write(fileAlready.readAll());
                    ok=false;
                }
                */
                else // Good password
                {
                    /*
                    // Check too many connected
                    int n=0;
                    for (int i=0;i<tcpPlayers.size();i++)
                        if (tcpPlayers[i].connected)
                            n++;
                    if (n>=maxConnected)
                    {
                        logMessage("TCP: Login failed, too much players connected");
                        socket->write(fileMaxConnected.readAll());
                        ok=false;
                    }
                    else
                    */
                    {
                        //player->reset();
                        player->IP = socket->peerAddress().toString();
                        player->lastPingTime = timestampNow();
                        player->connected = true;
                    }
                }
            }

            if (ok) // Send servers list
            {
                QByteArray customData = file.readAll();

                QByteArray data1 = QByteArray::fromHex("0D0A61757468726573706F6E73653A0A747275650A");
                QByteArray sesskey = QCryptographicHash::hash(QString(passhash + saltPassword).toLatin1(), QCryptographicHash::Md5).toHex();
#if DEBUG_LOG
                logMessage("TCP: Hash of '"+QString(passhash + saltPassword).toLatin1()
                           +"' is '"+sesskey+"'");
                logMessage("TCP: Sesskey is '"+sesskey+"', passhash is '"+passhash+"', salt is '"+saltPassword+"'");
#endif
                sesskey += passhash;
                QByteArray data2 = QByteArray::fromHex("0A310A");
                QByteArray serversList;
                QByteArray line;
                do {
                    line = fileServersList.readLine().trimmed();
                    serversList+=line;
                    serversList+=0x0A;
                } while (!line.isEmpty());
                serversList = serversList.trimmed();
                QByteArray data3 = QByteArray::fromHex("0D0A300D0A0D0A");
                int dataSize = data1.size() + sesskey.size() + data2.size() + serversList.size() - 2;
                QString dataSizeStr = QString().setNum(dataSize, 16);

                customData += dataSizeStr;
                customData += data1;
                customData += sesskey;
                customData += data2;
                customData += serversList;
                customData += data3;

                logMessage("TCP: Login successful, sending servers list");
                socket->write(customData);
                socket->close();
            }
        }
    }
    else if (data.contains("commfunction=removesession"))
    {
#if DEBUG_LOG
        logMessage("TCP: Session closed by client");
#endif
    }
    else // Unknown request, erase tcp buffer
    {
        // Display data
        logMessage("TCP: Unknown request received : ");
        logMessage(QString(data.data()));
    }
}
Esempio n. 4
0
void keymapping::process(QByteArray inputReport)
{
    int n;
    QList< QPair<int,int> > retKey;
    char irCode = 0;

    bool leftShiftDown = false;
    bool shiftDown = false;
    bool ctrlDown = false;
    bool altDown = false;
    bool symDown = false;

    printf("Processing report: ");
    for (n=0 ; n<inputReport.count() ; n++)
        printf("%02x ", inputReport.at(n));
    printf("\n");

    QByteArray ir = inputReport.mid(5, 6);

    /* Remove empty usage code bytes */
    int j;
    while ((j = ir.indexOf((char)0x00)) != -1)
        ir.remove(j, 1);

    for (j=0; j<ir.length(); j++) /* Quickly check does input report contain bogus */
        if (ir.at(j) < 0xa0)
        {
            printf("keymap: bogus value on input report detected. Resetting TCA\n");
            emit bogusDetected();
            return;
        }

    /* First check modifiers from modifier byte */
    if (inputReport.at(3) & 0x02) symDown = true;
    if (inputReport.at(3) & 0x08) ctrlDown = true;
    if (inputReport.at(3) & 0x10) leftShiftDown = true;
    /* And other modifiers from the usage codes */
    if (ir.contains(0xEA)) { shiftDown = true; ir.remove(ir.indexOf(0xEA), 1); }
    if (ir.contains(0xCF)) { altDown = true; ir.remove(ir.indexOf(0xCF), 1); }
    if (ir.contains(0xBF)) { ctrlDown = true; ir.remove(ir.indexOf(0xBF), 1); }
    if (ir.contains(0xED)) { symDown = true; ir.remove(ir.indexOf(0xED), 1); }

    /* Check space key here, it is a special case */
    if ((inputReport.at(3) & 0x40) || (inputReport.at(3) & 0x80) || ir.contains(0xE9))
    {
        if (!ir.contains(0xE9))
            ir.append(0xE9);
    }

    if (leftShiftDown && sym->pressed)
    {
        releaseStickyModifiers();
        emit toggleCapsLock();
        return;
    }

    shift->set(leftShiftDown || shiftDown, ir.isEmpty());
    ctrl->set(ctrlDown, ir.isEmpty());
    alt->set(altDown, ir.isEmpty());
    sym->set(symDown, ir.isEmpty());

    /* Shortcut out if no actual key pressed */
    if (ir.length() == 0)
    {
        if (pressedCode)
        {
            pressedCode = 0;
            emit keyReleased();
        }
        _prevInputReport = ir;
        return;
    }

    /* Check for new code in report. */
    for (int i=ir.length()-1 ; i >= 0 ; --i)
    {
        if (!_prevInputReport.contains(ir.at(i)))
        {
            irCode = ir.at(i);
                break;
        }
    }

    if (sym->pressed && irCode) /* With SYM modifier */
    {
        int i = 0;
        while (lut_sym[i])
        {
            if (irCode == lut_sym[i])
            {
                retKey.append(qMakePair(lut_sym[i+1], lut_sym[i+2]));
                break;
            }
            i += 3;
        }
    }
    else if (irCode) /* Without SYM modifier */
    {
        int i = 0;
        while (lut_plain[i])
        {
            if (irCode == lut_plain[i])
            {
                retKey.append(qMakePair(lut_plain[i+1], lut_plain[i+2]));
                break;
            }
            i += 3;
        }
    }


    /* If key is changed on the fly without break... emit released */
    if (pressedCode)
    {
        if ( (!ir.contains(pressedCode)) || ((irCode) && (pressedCode != irCode)) )
        {
            pressedCode = 0;
            emit keyReleased();
        }
        if (_prevInputReport == ir)
            return;
    }

    if (!retKey.empty())
    {
        pressedCode = irCode;
        emit keyPressed(retKey);
    }

    _prevInputReport = ir;
}
Esempio n. 5
0
/**
 *
 * Make sure that we are allowed to do what we do by checking the permissions and the selective sync list
 *
 */
void SyncEngine::checkForPermission()
{
    auto selectiveSyncBlackList = _journal->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList);
    std::sort(selectiveSyncBlackList.begin(), selectiveSyncBlackList.end());

    for (SyncFileItemVector::iterator it = _syncedItems.begin(); it != _syncedItems.end(); ++it) {
        if ((*it)->_direction != SyncFileItem::Up) {
            // Currently we only check server-side permissions
            continue;
        }

        // Do not propagate anything in the server if it is in the selective sync blacklist
        const QString path = (*it)->destination() + QLatin1Char('/');
        if (std::binary_search(selectiveSyncBlackList.constBegin(), selectiveSyncBlackList.constEnd(),
                               path)) {
            (*it)->_instruction = CSYNC_INSTRUCTION_IGNORE;
            (*it)->_status = SyncFileItem::FileIgnored;
            (*it)->_errorString = tr("Ignored because of the \"choose what to sync\" blacklist");

            if ((*it)->_isDirectory) {
                for (SyncFileItemVector::iterator it_next = it + 1; it_next != _syncedItems.end() && (*it_next)->_file.startsWith(path); ++it_next) {
                    it = it_next;
                    (*it)->_instruction = CSYNC_INSTRUCTION_IGNORE;
                    (*it)->_status = SyncFileItem::FileIgnored;
                    (*it)->_errorString = tr("Ignored because of the \"choose what to sync\" blacklist");
                }
            }
            continue;
        }

        switch((*it)->_instruction) {
        case CSYNC_INSTRUCTION_NEW: {
            int slashPos = (*it)->_file.lastIndexOf('/');
            QString parentDir = slashPos <= 0 ? "" : (*it)->_file.mid(0, slashPos);
            const QByteArray perms = getPermissions(parentDir);
            if (perms.isNull()) {
                // No permissions set
                break;
            } else if ((*it)->_isDirectory && !perms.contains("K")) {
                qDebug() << "checkForPermission: ERROR" << (*it)->_file;
                (*it)->_instruction = CSYNC_INSTRUCTION_ERROR;
                (*it)->_status = SyncFileItem::NormalError;
                (*it)->_errorString = tr("Not allowed because you don't have permission to add subfolders to that folder");

                for (SyncFileItemVector::iterator it_next = it + 1; it_next != _syncedItems.end() && (*it_next)->_file.startsWith(path); ++it_next) {
                    it = it_next;
                    (*it)->_instruction = CSYNC_INSTRUCTION_ERROR;
                    (*it)->_status = SyncFileItem::NormalError;
                    (*it)->_errorString = tr("Not allowed because you don't have permission to add parent folder");
                }

            } else if (!(*it)->_isDirectory && !perms.contains("C")) {
                qDebug() << "checkForPermission: ERROR" << (*it)->_file;
                (*it)->_instruction = CSYNC_INSTRUCTION_ERROR;
                (*it)->_status = SyncFileItem::NormalError;
                (*it)->_errorString = tr("Not allowed because you don't have permission to add files in that folder");
            }
            break;
        }
        case CSYNC_INSTRUCTION_SYNC: {
            const QByteArray perms = getPermissions((*it)->_file);
            if (perms.isNull()) {
                // No permissions set
                break;
            }
            if (!(*it)->_isDirectory && !perms.contains("W")) {
                qDebug() << "checkForPermission: RESTORING" << (*it)->_file;
                (*it)->_should_update_metadata = true;
                (*it)->_instruction = CSYNC_INSTRUCTION_CONFLICT;
                (*it)->_direction = SyncFileItem::Down;
                (*it)->_isRestoration = true;
                // take the things to write to the db from the "other" node (i.e: info from server)
                (*it)->_modtime = (*it)->log._other_modtime;
                (*it)->_size = (*it)->log._other_size;
                (*it)->_fileId = (*it)->log._other_fileId;
                (*it)->_etag = (*it)->log._other_etag;
                (*it)->_errorString = tr("Not allowed to upload this file because it is read-only on the server, restoring");
                continue;
            }
            break;
        }
        case CSYNC_INSTRUCTION_REMOVE: {
            const QByteArray perms = getPermissions((*it)->_file);
            if (perms.isNull()) {
                // No permissions set
                break;
            }
            if (!perms.contains("D")) {
                qDebug() << "checkForPermission: RESTORING" << (*it)->_file;
                (*it)->_should_update_metadata = true;
                (*it)->_instruction = CSYNC_INSTRUCTION_NEW;
                (*it)->_direction = SyncFileItem::Down;
                (*it)->_isRestoration = true;
                (*it)->_errorString = tr("Not allowed to remove, restoring");

                if ((*it)->_isDirectory) {
                    // restore all sub items
                    for (SyncFileItemVector::iterator it_next = it + 1;
                            it_next != _syncedItems.end() && (*it_next)->_file.startsWith(path); ++it_next) {
                        it = it_next;

                        if ((*it)->_instruction != CSYNC_INSTRUCTION_REMOVE) {
                            qWarning() << "non-removed job within a removed folder"
                                       << (*it)->_file << (*it)->_instruction;
                            continue;
                        }

                        qDebug() << "checkForPermission: RESTORING" << (*it)->_file;
                        (*it)->_should_update_metadata = true;

                        (*it)->_instruction = CSYNC_INSTRUCTION_NEW;
                        (*it)->_direction = SyncFileItem::Down;
                        (*it)->_isRestoration = true;
                        (*it)->_errorString = tr("Not allowed to remove, restoring");
                    }
                }
            } else if(perms.contains("S") && perms.contains("D")) {
                // this is a top level shared dir which can be removed to unshare it,
                // regardless if it is a read only share or not.
                // To avoid that we try to restore files underneath this dir which have
                // not delete permission we fast forward the iterator and leave the
                // delete jobs intact. It is not physically tried to remove this files
                // underneath, propagator sees that.
                if( (*it)->_isDirectory ) {
                    // put a more descriptive message if really a top level share dir is removed.
                    if( it == _syncedItems.begin() || !(path.startsWith((*(it-1))->_file)) ) {
                        (*it)->_errorString = tr("Local files and share folder removed.");
                    }

                    for (SyncFileItemVector::iterator it_next = it + 1;
                            it_next != _syncedItems.end() && (*it_next)->_file.startsWith(path); ++it_next) {
                        it = it_next;
                    }
                }
            }
            break;
        }

        case CSYNC_INSTRUCTION_RENAME: {

            int slashPos = (*it)->_renameTarget.lastIndexOf('/');
            const QString parentDir = slashPos <= 0 ? "" : (*it)->_renameTarget.mid(0, slashPos);
            const QByteArray destPerms = getPermissions(parentDir);
            const QByteArray filePerms = getPermissions((*it)->_file);

            //true when it is just a rename in the same directory. (not a move)
            bool isRename = (*it)->_file.startsWith(parentDir) && (*it)->_file.lastIndexOf('/') == slashPos;


            // Check if we are allowed to move to the destination.
            bool destinationOK = true;
            if (isRename || destPerms.isNull()) {
                // no need to check for the destination dir permission
                destinationOK = true;
            } else if ((*it)->_isDirectory && !destPerms.contains("K")) {
                destinationOK = false;
            } else if (!(*it)->_isDirectory && !destPerms.contains("C")) {
                destinationOK = false;
            }

            // check if we are allowed to move from the source
            bool sourceOK = true;
            if (!filePerms.isNull()
                    &&  ((isRename && !filePerms.contains("N"))
                         || (!isRename && !filePerms.contains("V")))) {

                // We are not allowed to move or rename this file
                sourceOK = false;

                if (filePerms.contains("D") && destinationOK) {
                    // but we are allowed to delete it
                    // TODO!  simulate delete & upload
                }
            }

#if 0 /* We don't like the idea of renaming behind user's back, as the user may be working with the files */

            if (!sourceOK && !destinationOK) {
                // Both the source and the destination won't allow move.  Move back to the original
                std::swap((*it)->_file, (*it)->_renameTarget);
                (*it)->_direction = SyncFileItem::Down;
                (*it)->_errorString = tr("Move not allowed, item restored");
                (*it)->_isRestoration = true;
                qDebug() << "checkForPermission: MOVING BACK" << (*it)->_file;
            } else
#endif
                if (!sourceOK || !destinationOK) {
                    // One of them is not possible, just throw an error
                    (*it)->_instruction = CSYNC_INSTRUCTION_ERROR;
                    (*it)->_status = SyncFileItem::NormalError;
                    const QString errorString = tr("Move not allowed because %1 is read-only").arg(
                                                    sourceOK ? tr("the destination") : tr("the source"));
                    (*it)->_errorString = errorString;

                    qDebug() << "checkForPermission: ERROR MOVING" << (*it)->_file << errorString;

                    // Avoid a rename on next sync:
                    // TODO:  do the resolution now already so we don't need two sync
                    //  At this point we would need to go back to the propagate phase on both remote to take
                    //  the decision.
                    _journal->avoidRenamesOnNextSync((*it)->_file);
                    _anotherSyncNeeded = true;


                    if ((*it)->_isDirectory) {
                        for (SyncFileItemVector::iterator it_next = it + 1;
                                it_next != _syncedItems.end() && (*it_next)->destination().startsWith(path); ++it_next) {
                            it = it_next;
                            (*it)->_instruction = CSYNC_INSTRUCTION_ERROR;
                            (*it)->_status = SyncFileItem::NormalError;
                            (*it)->_errorString = errorString;
                            qDebug() << "checkForPermission: ERROR MOVING" << (*it)->_file;
                        }
                    }
                }
            break;
        }
        default:
            break;
        }
    }
}
Esempio n. 6
0
bool WplParser::TryMagic(const QByteArray& data) const {
  return data.contains("<?wpl") || data.contains("<smil>");
}
Esempio n. 7
0
void MainWindow::importDoxy()
{   
   while (true) {

      QString fname = QFileDialog::getOpenFileName(this, tr("Open Doxygen project file"), m_settings.pathPrior);

      if (fname.isEmpty()) {
         csError(tr("File Open"), tr("No file name was provided"));
         break;
      }

      QFile file(fname);
      if (! file.open(QIODevice::ReadOnly)) {
         csError(tr("Error Opening: ") + fname, tr("Unable to open: ") + file.error());
         break;
      }

      QFileInfo fi(file);
      QString importPath = fi.absolutePath() + QDir::separator() + fi.baseName() + ".json";

      // read file
      QByteArray data;

      data = file.readAll();
      file.close();

      // strip comments
      int posBeg;
      int posEnd;

      while (true) {
         posBeg = data.indexOf("#");

         if (posBeg == -1) {
            break;
         }

         posEnd = data.indexOf("\n",posBeg);
         data.remove(posBeg, posEnd-posBeg);
      }

      // verify a few fields to ensure this is an old project file
      if (! data.contains("PROJECT_NAME") || ! data.contains("OUTPUT_DIRECTORY"))  {
         csError(tr("Convert Project File"), tr("Doxygen project file is missing required information, Convert aborted"));
         break;
      }

      // ** save as new project file
      fname = QFileDialog::getSaveFileName(this, tr("Save as DoxyPress project file"), importPath,
                                           tr("Json Files (*.json)"));

      if (fname.isEmpty()) {
         csError(tr("Convert Project File"), tr("No DoxyPress file name was provided, Convert aborted"));
         break;

      } else {
         QMessageBox quest;
         quest.setWindowTitle(tr("Convert Doxygen Project"));
         quest.setWindowIcon(QIcon("://resources/doxypress.png"));

         quest.setText( tr("If a layout or css file was specified in your project file, please refer to the DoxyPress documentation "
                           "regarding 'Converting to DoxyPress' for additional information. Continue?"));

         quest.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
         quest.setDefaultButton(QMessageBox::No);

         int retval = quest.exec();

         if (retval == QMessageBox::Yes) {            
            m_curFile = fname;
            m_settings.pathPrior = this->pathName(fname);

            clearAllFields();
            convertDoxy(data);

            saveDoxy_Internal();

            json_Write(PATH_PRIOR);

            if (! m_rf_List.contains(m_curFile)) {
               rf_Update();
            }
         }

      }

      // all done, everything is fine
      break;
   }
}
void QmitkDiffusionImagingAppIntroPart::DelegateMeTo(const QUrl& showMeNext)
{
  QString scheme          = showMeNext.scheme();
  QByteArray urlHostname  = showMeNext.encodedHost();
  QByteArray urlPath      = showMeNext.encodedPath();
  QByteArray dataset      = showMeNext.encodedQueryItemValue("dataset");
  QByteArray clear        = showMeNext.encodedQueryItemValue("clear");

  if (scheme.isEmpty()) MITK_INFO << " empty scheme of the to be delegated link" ;

  // if the scheme is set to mitk, it is to be tested which action should be applied
  if (scheme.contains(QString("mitk")) )
  {
    if(urlPath.isEmpty() ) MITK_INFO << " mitk path is empty " ;

    // searching for the perspective keyword within the host name
    if(urlHostname.contains(QByteArray("perspectives")) )
    {
      // the simplified method removes every whitespace
      // ( whitespace means any character for which the standard C++ isspace() method returns true)
      urlPath = urlPath.simplified();
      QString tmpPerspectiveId(urlPath.data());
      tmpPerspectiveId.replace(QString("/"), QString("") );
      std::string perspectiveId  = tmpPerspectiveId.toStdString();

      // is working fine as long as the perspective id is valid, if not the application crashes
      GetIntroSite()->GetWorkbenchWindow()->GetWorkbench()->ShowPerspective(perspectiveId, GetIntroSite()->GetWorkbenchWindow() );

      // search the Workbench for opened StdMultiWidgets to ensure the focus does not stay on the welcome screen and is switched to
      // an StdMultiWidget if one available
      mitk::IDataStorageService::Pointer service =
          berry::Platform::GetServiceRegistry().GetServiceById<mitk::IDataStorageService>(mitk::IDataStorageService::ID);
      berry::IEditorInput::Pointer editorInput;
      editorInput = new mitk::DataStorageEditorInput( service->GetActiveDataStorage() );

      // the solution is not clean, but the dependency to the StdMultiWidget was removed in order to fix a crash problem
      // as described in Bug #11715
      // This is the correct way : use the static string ID variable
      // berry::IEditorPart::Pointer editor = GetIntroSite()->GetPage()->FindEditors( editorInput, QmitkStdMultiWidgetEditor::EDITOR_ID );
      // QuickFix: we use the same string for an local variable
      const std::string stdEditorID = "org.mitk.editors.stdmultiwidget";

      // search for opened StdMultiWidgetEditors
      std::vector<berry::IEditorReference::Pointer> editorList = GetIntroSite()->GetPage()->FindEditors( editorInput, stdEditorID, 1 );

      // if an StdMultiWidgetEditor open was found, give focus to it
      if(editorList.size())
      {
        GetIntroSite()->GetPage()->Activate( editorList[0]->GetPart(true) );
      }

    }
  }
  // if the scheme is set to http, by default no action is performed, if an external webpage needs to be
  // shown it should be implemented below
  else if (scheme.contains(QString("http")) )
  {
    QDesktopServices::openUrl(showMeNext);
//    m_view->load( ) ;
  }
  else if(scheme.contains("qrc"))
  {
    m_view->load(showMeNext);
  }

}
Esempio n. 9
0
// Determine UNIX processes by reading "/proc". Default to ps if
// it does not exist
ProcDataList processList(const ProcDataList &previous)
{
  const QDir procDir(QLatin1String("/proc/"));
  if (!procDir.exists()) {
    return unixProcessListPS(previous);
  }
  ProcDataList rc;
  const QStringList procIds = procDir.entryList();
  if (procIds.isEmpty()) {
    return rc;
  }
  foreach (const QString &procId, procIds) {
    if (!isUnixProcessId(procId)) {
      continue;
    }
    QString filename = QLatin1String("/proc/");
    filename += procId;
    filename += QLatin1String("/stat");
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly)) {
      continue;           // process may have exited
    }

    const QStringList data = QString::fromLocal8Bit(file.readAll()).split(' ');
    ProcData proc;
    proc.ppid = procId;
    proc.name = data.at(1);
    if (proc.name.startsWith(QLatin1Char('(')) && proc.name.endsWith(QLatin1Char(')'))) {
      proc.name.truncate(proc.name.size() - 1);
      proc.name.remove(0, 1);
    }
    proc.state = data.at(2);
    // PPID is element 3

    proc.user = QFileInfo(file).owner();
    file.close();

    QFile cmdFile(QLatin1String("/proc/") + procId + QLatin1String("/cmdline"));
    if(cmdFile.open(QFile::ReadOnly)) {
      QByteArray cmd = cmdFile.readAll();
      cmd.replace('\0', ' ');
      if (!cmd.isEmpty()) {
        proc.name = QString::fromLocal8Bit(cmd);
      }
    }
    cmdFile.close();

    QFile maps(QLatin1String("/proc/") + procId + QLatin1String("/maps"));
    if (!maps.open(QIODevice::ReadOnly)) {
      continue; // process may have exited
    }

    proc.type = ProcData::NoQtApp;
    forever {
      const QByteArray line = maps.readLine();
      if (line.isEmpty()) {
        break;
      }
      if (line.contains(QByteArray("/libQtCore.so"))) {
        proc.type = ProcData::QtApp;
        break;
      }
    }

    rc.push_back(proc);
  }
  return rc;
}
void QmitkMitkWorkbenchIntroPart::DelegateMeTo(const QUrl& showMeNext)
{
  QString scheme          = showMeNext.scheme();
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
  QByteArray urlHostname  = showMeNext.encodedHost();
  QByteArray urlPath      = showMeNext.encodedPath();
  QByteArray dataset      = showMeNext.encodedQueryItemValue("dataset");
  QByteArray clear        = showMeNext.encodedQueryItemValue("clear");
#else
  QByteArray urlHostname  = QUrl::toAce(showMeNext.host());
  QByteArray urlPath      = showMeNext.path().toLatin1();
  QUrlQuery query(showMeNext);
  QByteArray dataset      = query.queryItemValue("dataset").toLatin1();
  QByteArray clear        = query.queryItemValue("clear").toLatin1();//showMeNext.encodedQueryItemValue("clear");
#endif

  if (scheme.isEmpty()) MITK_INFO << " empty scheme of the to be delegated link" ;

  // if the scheme is set to mitk, it is to be tested which action should be applied
  if (scheme.contains(QString("mitk")) )
  {
    if(urlPath.isEmpty() ) MITK_INFO << " mitk path is empty " ;

    // searching for the perspective keyword within the host name
    if(urlHostname.contains(QByteArray("perspectives")) )
    {
      // the simplified method removes every whitespace
      // ( whitespace means any character for which the standard C++ isspace() method returns true)
      urlPath = urlPath.simplified();
      QString tmpPerspectiveId(urlPath.data());
      tmpPerspectiveId.replace(QString("/"), QString("") );
      QString perspectiveId  = tmpPerspectiveId;

      // is working fine as long as the perspective id is valid, if not the application crashes
      GetIntroSite()->GetWorkbenchWindow()->GetWorkbench()->ShowPerspective(perspectiveId, GetIntroSite()->GetWorkbenchWindow() );

      // search the Workbench for opened StdMultiWidgets to ensure the focus does not stay on the welcome screen and is switched to
      // a render window editor if one available
      ctkPluginContext* context = QmitkExtApplicationPlugin::GetDefault()->GetPluginContext();
      mitk::IDataStorageService* service = nullptr;
      ctkServiceReference serviceRef = context->getServiceReference<mitk::IDataStorageService>();
      if (serviceRef) service = context->getService<mitk::IDataStorageService>(serviceRef);
      if (service)
      {
        berry::IEditorInput::Pointer editorInput(new mitk::DataStorageEditorInput( service->GetActiveDataStorage() ));

        // search for opened StdMultiWidgetEditors
        berry::IEditorPart::Pointer editorPart = GetIntroSite()->GetPage()->FindEditor( editorInput );

        // if an StdMultiWidgetEditor open was found, give focus to it
        if(editorPart)
        {
          GetIntroSite()->GetPage()->Activate( editorPart );
        }
      }
    }
  }
  // if the scheme is set to http, by default no action is performed, if an external webpage needs to be
  // shown it should be implemented below
  else if (scheme.contains(QString("http")) )
  {
    QDesktopServices::openUrl(showMeNext);
//    m_view->load( ) ;
  }
  else if(scheme.contains("qrc"))
  {
    m_view->load(showMeNext);
  }

}
Esempio n. 11
-1
bool QgsHelp::urlExists( const QString &url )
{
  QUrl helpUrl( url );
  QTcpSocket socket;

  QgsSettings settings;
  bool proxyEnabled = settings.value( QStringLiteral( "proxy/proxyEnabled" ), false ).toBool();
  if ( proxyEnabled )
  {
    QNetworkProxy proxy;
    QString proxyHost = settings.value( QStringLiteral( "proxy/proxyHost" ), QString() ).toString();
    int proxyPort = settings.value( QStringLiteral( "proxy/proxyPort" ), QString() ).toString().toInt();
    QString proxyUser = settings.value( QStringLiteral( "proxy/proxyUser" ), QString() ).toString();
    QString proxyPassword = settings.value( QStringLiteral( "proxy/proxyPassword" ), QString() ).toString();

    QString proxyTypeString = settings.value( QStringLiteral( "proxy/proxyType" ), QString() ).toString();

    if ( proxyTypeString == QLatin1String( "DefaultProxy" ) )
    {
      QList<QNetworkProxy> proxies = QNetworkProxyFactory::systemProxyForQuery();
      if ( !proxies.isEmpty() )
      {
        proxy = proxies.first();
      }
    }
    else
    {
      QNetworkProxy::ProxyType proxyType = QNetworkProxy::DefaultProxy;
      if ( proxyTypeString == QLatin1String( "Socks5Proxy" ) )
      {
        proxyType = QNetworkProxy::Socks5Proxy;
      }
      else if ( proxyTypeString == QLatin1String( "HttpProxy" ) )
      {
        proxyType = QNetworkProxy::HttpProxy;
      }
      else if ( proxyTypeString == QLatin1String( "HttpCachingProxy" ) )
      {
        proxyType = QNetworkProxy::HttpCachingProxy;
      }
      else if ( proxyTypeString == QLatin1String( "FtpCachingProxy" ) )
      {
        proxyType = QNetworkProxy::FtpCachingProxy;
      }
      proxy = QNetworkProxy( proxyType, proxyHost, proxyPort, proxyUser, proxyPassword );
    }
    socket.setProxy( proxy );
  }

  socket.connectToHost( helpUrl.host(), 80 );
  if ( socket.waitForConnected() )
  {
    socket.write( "HEAD " + helpUrl.path().toUtf8() + " HTTP/1.1\r\n"
                  "Host: " + helpUrl.host().toUtf8() + "\r\n\r\n" );
    if ( socket.waitForReadyRead() )
    {
      QByteArray bytes = socket.readAll();
      if ( bytes.contains( "200 OK" ) ||  bytes.contains( "302 Found" ) ||  bytes.contains( "301 Moved" ) )
      {
        return true;
      }
    }
  }

  return false;
}