/**
 * Executes an operation (or workflow) and generates output
 * @param parameters the input and output parameters that the user filled in
 */
QString OperationCatalogModel::executeoperation(quint64 operationid, const QString& parameters) {
    if ( operationid == 0 || parameters == "")
        return sUNDEF;

    Resource operationresource = mastercatalog()->id2Resource(operationid);
    if ( !operationresource.isValid())
        return sUNDEF;

    em->clearList();

    QString expression;
    QStringList parms = parameters.split("|");
    bool hasInvalidParameters = false;

    for(int i = 0; i < parms.size(); ++ i){
        if (operationresource.ilwisType() & itWORKFLOW){
            int parm = i + 1;
            if (operationresource[QString("pout_%1_optional").arg(parm)] == "false" && i < operationresource["outparameters"].toInt()) {
                QString value = parms[i + operationresource["inparameters"].toInt()];

                QString output = value.split("@@")[0];
                if (output.size() == 0) {
                    em->addError(1, "Output parameter " + QString::number(i) + " is undefined with name " +  operationresource[QString("pout_%1_name").arg(parm)].toString());
                    hasInvalidParameters = true;
                } else {
                    for (const char& c : output.toStdString()) {
                        if (!isalnum(c) && c != ':' && c != '/' && c != '\\' && c != '.') {
                            em->addError(1, "Output parameter " + QString::number(i) + " is not a valid name");
                            hasInvalidParameters = true;
                            break;
                        }
                    }
                }
            }
            if (operationresource[QString("pin_%1_optional").arg(parm)] == "false" && i < operationresource["inparameters"].toInt() && parms[i].size() == 0) {
                em->addError(1, "Input parameter " + QString::number(i) + " is undefined with name " +  operationresource[QString("pin_%1_name").arg(parm)].toString());
                hasInvalidParameters = true;
            }
        }
        if(i < operationresource["inparameters"].toInt()){
            if ( expression.size() != 0)
                expression += ",";
            expression += parms[i];
        }
    }

    if (hasInvalidParameters) return sUNDEF;

    QString allOutputsString;

    bool duplicateFileNames = false;

    QStringList parts = operationresource["outparameters"].toString().split("|");
    int maxparms = parts.last().toInt();
    int count = 1;
    for(int i=(parms.size() - maxparms); i<parms.size(); ++i){
        QString output = parms[i];


        QString pout = QString("pout_%1_type").arg(count++);

        IlwisTypes outputtype = operationresource[pout].toULongLong();
        if ( output.indexOf("@@") != -1 ){
            QString format;
            QStringList parts = output.split("@@");
            output = parts[0];
            if ( output == "")
                continue;

            //Check if user didnt put the same output name in another output field
            int occurences = 0;
            for(int j=(parms.size() - maxparms); j<parms.size(); ++j){
                QString compareString = parms[j].split("@@")[0];
                if(output == compareString){
                    occurences++;
                }
            }

            //Add the duplicate name to the list of duplicate names
            if(occurences>1){
                duplicateFileNames = true;
                em->addError(1, "Workflow did not execute, multiple occurences of an output name");
            }

            QString formatName = parts[1];

            if ( operationresource.ilwisType() & itWORKFLOW) {
                QStringList existingFileNames;

                DIR *directory;

                //If not memory
                QString fileName;

                if(formatName == "Memory" ){
                    //Get all files in the internal catalog
                    QString dataLocation = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/internalcatalog";
                    directory = opendir(dataLocation.toStdString().c_str());
                }else {
                    //Get all files in the directory
                    QString dataLocation = output;
                    dataLocation.remove("file:///");

                    QStringList splitUrl = dataLocation.split("/");

                    fileName = splitUrl.last();

                    QString query = "name='" + formatName + "'";
                    std::multimap<QString, Ilwis::DataFormat>  formats = Ilwis::DataFormat::getSelectedBy(Ilwis::DataFormat::fpNAME, query);
                    if ( formats.size() == 1){
                        QString connector = (*formats.begin()).second.property(DataFormat::fpCONNECTOR).toString();
                        QString code = (*formats.begin()).second.property(DataFormat::fpCODE).toString();

                        QVariantList extensions = Ilwis::DataFormat::getFormatProperties(DataFormat::fpEXTENSION,outputtype, connector, code);

                        fileName += ".";
                        fileName += extensions[0].toString();
                    }

                    splitUrl.removeLast();

                    dataLocation = splitUrl.join("/");

                    directory = opendir(dataLocation.toStdString().c_str());
                }

                struct dirent *file;

                //Put the existing file names in a list for later use
                while ((file = readdir (directory)) != NULL) {
                    existingFileNames.push_back(file->d_name);
                }

                closedir(directory);

                //Check if a file with the same name already exist
                for(int j=0;j<existingFileNames.size();++j){
                    if(formatName == "Memory"){
                        if(existingFileNames[j] == output) {
                            duplicateFileNames = true;
                            em->addError(1, "Workflow did not execute duplicate name: " + output + ". Please change this name.");
                        }
                    }else{
                        if(existingFileNames[j] == fileName){
                            duplicateFileNames = true;
                            em->addError(1, "Workflow did not execute duplicate name: " + fileName + ". Please change this name.");
                        }
                    }
                }
            }

            if ( hasType(outputtype, itCOLUMN)){
                if ( formatName == "Memory"){
                    output = modifyTableOutputUrl(output, parms);
                }else
                    output = parms[0] + "[" + output + "]";
            }
            if ( formatName == "Keep original"){
                IIlwisObject obj;
                obj.prepare(parms[0], operationresource["pin_1_type"].toULongLong());
                if ( obj.isValid()){
                    IlwisTypes type = operationresource[pout].toULongLong();
                    QVariantList values = DataFormat::getFormatProperties(DataFormat::fpCODE,type,obj->provider());
                    if ( values.size() != 0){
                        format = "{format(" + obj->provider() + ",\"" + values[0].toString() + "\")}";
                    }else{
                        kernel()->issues()->log(QString("No valid conversion found for provider %1 and format %2").arg(obj->provider()).arg(IlwisObject::type2Name(type)));
                        return sUNDEF;
                    }
                }
            }
            //overrule the user if he wants to store things in the internalcatalog, then the format is by defintion stream
            if ( context()->workingCatalog()->source().url() == INTERNAL_OBJECT)
                formatName == "Memory";
            if ( formatName != "Memory"){ // special case
                if ( format == "") {
                    QString query = "name='" + formatName + "'";
                    std::multimap<QString, Ilwis::DataFormat>  formats = Ilwis::DataFormat::getSelectedBy(Ilwis::DataFormat::fpNAME, query);
                    if ( formats.size() == 1){
                        format = "{format(" + (*formats.begin()).second.property(DataFormat::fpCONNECTOR).toString() + ",\"" +
                                (*formats.begin()).second.property(DataFormat::fpCODE).toString() + "\")}";
                    }
                }
                // if there is no path we extend it with a path unless the output is a new column, output is than the "old" table so no new output object
                if ( output.indexOf("://") == -1 )
                    output = context()->workingCatalog()->source().url().toString() + "/" + output + format;
                else
                    output = output + format;
            }else{
                if ( hasType(outputtype,itRASTER)){
                    format = "{format(stream,\"rastercoverage\")}";
                }else if (hasType(outputtype, itFEATURE)){
                    format = "{format(stream,\"featurecoverage\")}";
                }else if (hasType(outputtype, itTABLE | itCOLUMN)){
                    format = "{format(stream,\"table\")}";
                }else if (hasType(outputtype, itCATALOG)){
                    format = "{format(stream,\"catalog\")}";
                }else if (hasType(outputtype, itDOMAIN)){
                    format = "{format(stream,\"domain\")}";
                }else if (hasType(outputtype, itCOORDSYSTEM)){
                    format = "{format(stream,\"coordinatesystem\")}";
                }else if (hasType(outputtype, itGEOREF)){
                    format = "{format(stream,\"georeference\")}";
                }

                output = output + format;
            }
        }

        if(!allOutputsString.isEmpty()){
            allOutputsString.append(",");
        }
        allOutputsString += output;
    }

    if(!duplicateFileNames){
        if ( allOutputsString == "")
            expression = QString("script %1(%2)").arg(operationresource.name()).arg(expression);
        else
            expression = QString("script %1=%2(%3)").arg(allOutputsString).arg(operationresource.name()).arg(expression);

        OperationExpression opExpr(expression);

        try {
            QThread* thread = new QThread;
            OperationWorker* worker = new OperationWorker(opExpr);
            worker->moveToThread(thread);
            thread->connect(thread, &QThread::started, worker, &OperationWorker::process);
            thread->connect(worker, &OperationWorker::finished, thread, &QThread::quit);
            thread->connect(worker, &OperationWorker::finished, worker, &OperationWorker::deleteLater);
            thread->connect(thread, &QThread::finished, thread, &QThread::deleteLater);
            thread->start();

            return "TODO";
        } catch (const ErrorObject& err){
            emit error(err.message());
        }
    }
    return sUNDEF;
}
Ejemplo n.º 2
0
// return the absolute path from a filename read from project file
QString QgsProject::readPath( QString src ) const
{
  if ( readBoolEntry( "Paths", "/Absolute", false ) )
  {
    return src;
  }

  // relative path should always start with ./ or ../
  if ( !src.startsWith( "./" ) && !src.startsWith( "../" ) )
  {
#if defined(Q_OS_WIN)
    if ( src.startsWith( "\\\\" ) ||
         src.startsWith( "//" ) ||
         ( src[0].isLetter() && src[1] == ':' ) )
    {
      // UNC or absolute path
      return src;
    }
#else
    if ( src[0] == '/' )
    {
      // absolute path
      return src;
    }
#endif

    // so this one isn't absolute, but also doesn't start // with ./ or ../.
    // That means that it was saved with an earlier version of "relative path support",
    // where the source file had to exist and only the project directory was stripped
    // from the filename.
    QFileInfo pfi( fileName() );
    if ( !pfi.exists() )
      return src;

    QFileInfo fi( pfi.canonicalPath() + "/" + src );

    if ( !fi.exists() )
    {
      return src;
    }
    else
    {
      return fi.canonicalFilePath();
    }
  }

  QString srcPath = src;
  QString projPath = fileName();

  if ( projPath.isEmpty() )
  {
    return src;
  }

#if defined(Q_OS_WIN)
  srcPath.replace( "\\", "/" );
  projPath.replace( "\\", "/" );

  bool uncPath = projPath.startsWith( "//" );
#endif

  QStringList srcElems = srcPath.split( "/", QString::SkipEmptyParts );
  QStringList projElems = projPath.split( "/", QString::SkipEmptyParts );

#if defined(Q_OS_WIN)
  if ( uncPath )
  {
    projElems.insert( 0, "" );
    projElems.insert( 0, "" );
  }
#endif

  // remove project file element
  projElems.removeLast();

  // append source path elements
  projElems << srcElems;
  projElems.removeAll( "." );

  // resolve ..
  int pos;
  while (( pos = projElems.indexOf( ".." ) ) > 0 )
  {
    // remove preceding element and ..
    projElems.removeAt( pos - 1 );
    projElems.removeAt( pos - 1 );
  }

#if !defined(Q_OS_WIN)
  // make path absolute
  projElems.prepend( "" );
#endif

  return projElems.join( "/" );
}
Ejemplo n.º 3
0
void WriteDeclaration::acceptUI(DomUI *node)
{
    QString qualifiedClassName = node->elementClass() + m_option.postfix;
    QString className = qualifiedClassName;

    QString varName = m_driver->findOrInsertWidget(node->elementWidget());
    QString widgetClassName = node->elementWidget()->attributeClass();

    QString exportMacro = node->elementExportMacro();
    if (!exportMacro.isEmpty())
        exportMacro.append(QLatin1Char(' '));

    QStringList namespaceList = qualifiedClassName.split(QLatin1String("::"));
    if (namespaceList.count()) {
        className = namespaceList.last();
        namespaceList.removeLast();
    }

    // This is a bit of the hack but covers the cases Qt in/without namespaces
    // and User defined classes in/without namespaces. The "strange" case
    // is a User using Qt-in-namespace having his own classes not in a namespace.
    // In this case the generated Ui helper classes will also end up in
    // the Qt namespace (which is harmless, but not "pretty")
    const bool needsMacro = namespaceList.count() == 0
        || namespaceList[0] == QLatin1String("qdesigner_internal");

    if (needsMacro)
        m_output << "QT_BEGIN_NAMESPACE\n\n";

    openNameSpaces(namespaceList, m_output);

    if (namespaceList.count())
        m_output << "\n";

    m_output << "class " << exportMacro << m_option.prefix << className << "\n"
           << "{\n"
           << "public:\n";

    const QStringList connections = m_uic->databaseInfo()->connections();
    for (int i=0; i<connections.size(); ++i) {
        const QString connection = connections.at(i);

        if (connection == QLatin1String("(default)"))
            continue;

        m_output << m_option.indent << "QSqlDatabase " << connection << "Connection;\n";
    }

    TreeWalker::acceptWidget(node->elementWidget());
    if (const DomButtonGroups *domButtonGroups = node->elementButtonGroups())
        acceptButtonGroups(domButtonGroups);

    m_output << "\n";

    WriteInitialization(m_uic, m_activateScripts).acceptUI(node);

    if (node->elementImages()) {
        if (m_option.extractImages) {
            ExtractImages(m_uic->option()).acceptUI(node);
        } else {
            m_output << "\n"
                << "protected:\n"
                << m_option.indent << "enum IconID\n"
                << m_option.indent << "{\n";
            WriteIconDeclaration(m_uic).acceptUI(node);

            m_output << m_option.indent << m_option.indent << "unknown_ID\n"
                << m_option.indent << "};\n";

            WriteIconInitialization(m_uic).acceptUI(node);
        }
    }

    if (m_activateScripts) {
        m_output << "\nprivate:\n\n";
        writeScriptContextClass(m_option.indent, m_output);
    }

    m_output << "};\n\n";

    closeNameSpaces(namespaceList, m_output);

    if (namespaceList.count())
        m_output << "\n";

    if (m_option.generateNamespace && !m_option.prefix.isEmpty()) {
        namespaceList.append(QLatin1String("Ui"));

        openNameSpaces(namespaceList, m_output);

        m_output << m_option.indent << "class " << exportMacro << className << ": public " << m_option.prefix << className << " {};\n";

        closeNameSpaces(namespaceList, m_output);

        if (namespaceList.count())
            m_output << "\n";
    }

    if (needsMacro)
        m_output << "QT_END_NAMESPACE\n\n";
}
Ejemplo n.º 4
0
void BootloaderInstallFile::installStage2(void)
{
    emit logItem(tr("Installing Rockbox bootloader"), LOGINFO);
    QCoreApplication::processEvents();

    // if an old bootloader is present (Gigabeat) move it out of the way.
    QString fwfile(Utils::resolvePathCase(m_blfile));
    if(!fwfile.isEmpty()) {
        QString moved = Utils::resolvePathCase(m_blfile) + ".ORIG";
        LOG_INFO() << "renaming" << fwfile << "to" << moved;
        QFile::rename(fwfile, moved);
    }

    // if no old file found resolve path without basename
    QFileInfo fi(m_blfile);
    QString absPath = Utils::resolvePathCase(fi.absolutePath());

    // if it's not possible to locate the base path try to create it
    if(absPath.isEmpty()) {
        QStringList pathElements = m_blfile.split("/");
        // remove filename from list and save last path element
        pathElements.removeLast();
        QString lastElement = pathElements.last();
        // remove last path element for base
        pathElements.removeLast();
        QString basePath = pathElements.join("/");

        // check for base and bail out if not found. Otherwise create folder.
        absPath = Utils::resolvePathCase(basePath);
        QDir d(absPath);
        d.mkpath(lastElement);
        absPath = Utils::resolvePathCase(fi.absolutePath());

        if(absPath.isEmpty()) {
            emit logItem(tr("Error accessing output folder"), LOGERROR);
            emit done(true);
            return;
        }
    }
    fwfile = absPath + "/" + fi.fileName();

    // place (new) bootloader
    m_tempfile.open();
    LOG_INFO() << "renaming" << m_tempfile.fileName()
               << "to" << fwfile;
    m_tempfile.close();

    if(!Utils::resolvePathCase(fwfile).isEmpty()) {
        emit logItem(tr("A firmware file is already present on player"), LOGERROR);
        emit done(true);
        return;
    }
    if(m_tempfile.copy(fwfile)) {
        emit logItem(tr("Bootloader successful installed"), LOGOK);
    }
    else {
        emit logItem(tr("Copying modified firmware file failed"), LOGERROR);
        emit done(true);
        return;
    }

    logInstall(LogAdd);

    emit done(false);
}
Ejemplo n.º 5
0
void CodeView::mousePressEvent( QMouseEvent * event )
{
    Q_UNUSED(event);
    int j;
    
    if(event->button() == Qt::RightButton)
    {
        QPoint pos = event->globalPos();
            
        // Clicked on a text row?
        int rowHeight = getRowHeight();
        int rowIdx = event->pos().y() / rowHeight;
        int lineNo = rowIdx+1;
        if(rowIdx >= 0 && rowIdx < (int)m_highlighter.getRowCount())
        {
            // Get the words in the line
            QVector<TextField*> cols = m_highlighter.getRow(rowIdx);
            
            // Find the word under the cursor
            int x = BORDER_WIDTH+10;
            int foundPos = -1;
            for(j = 0;j < cols.size() && foundPos == -1;j++)
            {
                TextField *field = cols[j];            
                int w = m_fontInfo->width(field->m_text);
                if(x <= event->pos().x() && event->pos().x() <= x+w)
                {
                    foundPos = j;
                }
                x += w;
            }

            // Go to the left until a word is found
            if(foundPos != -1)
            {
                
                while(foundPos >= 0)
                {
                    if(cols[foundPos]->isSpaces() ||
                        m_highlighter.isKeyword(cols[foundPos]->m_text)
                        || m_highlighter.isSpecialChar(cols[foundPos]))
                    {
                        foundPos--;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            // Found anything under the cursor?
            QString incFile;
            QStringList list;
            if(foundPos != -1)
            {
                // Found a include file?
                if(cols[foundPos]->m_type == TextField::INC_STRING)
                {
                    incFile = cols[foundPos]->m_text.trimmed();
                    if(incFile.length() > 2)
                        incFile = incFile.mid(1, incFile.length()-2);
                    else
                        incFile = "";
                }
                 // or a variable?
                else if(cols[foundPos]->m_type == TextField::WORD)
                {
                    QStringList partList = cols[foundPos]->m_text.split('.');

                    // Remove the last word if it is a function
                    if(foundPos+1 < cols.size())
                    {
                        if(cols[foundPos+1]->m_text == "(" && partList.size() > 1)
                            partList.removeLast();
                    }
                    
                    
                    for(int partIdx = 1;partIdx <= partList.size();partIdx++)
                    {
                        QStringList subList = partList.mid(0, partIdx);
                        list += subList.join(".");
                    }

                    // A '[...]' section to the right of the variable?
                    if(foundPos+1 < cols.size())
                    {
                        if(cols[foundPos+1]->m_text == "[")
                        {
                            // Add the entire '[...]' section to the variable name
                            QString extraString = "[";
                            for(int j = foundPos+2;foundPos < cols.size() && cols[j]->m_text != "]";j++)
                            {
                                extraString += cols[j]->m_text;
                            }
                            extraString += ']';
                            list += partList.join(".") + extraString;

                        }
                    }

                }
            }
            
            // Inform the listener
            if(m_inf)
            {
                if(incFile.isEmpty())
                    m_inf->ICodeView_onContextMenu(pos, lineNo, list);
                else
                    m_inf->ICodeView_onContextMenuIncFile(pos,lineNo, incFile);
            
            }
        }
    }
}
Ejemplo n.º 6
0
void WriteDeclaration::acceptUI(DomUI *node)
{
    QString qualifiedClassName = node->elementClass() + option.postfix;
    QString className = qualifiedClassName;

    QString varName = driver->findOrInsertWidget(node->elementWidget());
    QString widgetClassName = node->elementWidget()->attributeClass();

    QString exportMacro = node->elementExportMacro();
    if (!exportMacro.isEmpty())
        exportMacro.append(QLatin1Char(' '));

    QStringList nsList = qualifiedClassName.split(QLatin1String("::"));
    if (nsList.count()) {
        className = nsList.last();
        nsList.removeLast();
    }

    QListIterator<QString> it(nsList);
    while (it.hasNext()) {
        QString ns = it.next();
        if (ns.isEmpty())
            continue;

        output << "namespace " << ns << " {\n";
    }

    if (nsList.count())
        output << "\n";

    output << "class " << exportMacro << option.prefix << className << "\n"
           << "{\n"
           << "public:\n";

    QStringList connections = uic->databaseInfo()->connections();
    for (int i=0; i<connections.size(); ++i) {
        QString connection = connections.at(i);

        if (connection == QLatin1String("(default)"))
            continue;

        output << option.indent << "QSqlDatabase " << connection << "Connection;\n";
    }

    TreeWalker::acceptWidget(node->elementWidget());

    output << "\n";

    WriteInitialization(uic).acceptUI(node);

    if (node->elementImages()) {
        output << "\n"
            << "protected:\n"
            << option.indent << "enum IconID\n"
            << option.indent << "{\n";
        WriteIconDeclaration(uic).acceptUI(node);

        output << option.indent << option.indent << "unknown_ID\n"
            << option.indent << "};\n";

        WriteIconInitialization(uic).acceptUI(node);
    }

    output << "};\n\n";

    it.toBack();
    while (it.hasPrevious()) {
        QString ns = it.previous();
        if (ns.isEmpty())
            continue;

        output << "} // namespace " << ns << "\n";
    }

    if (nsList.count())
        output << "\n";

    if (option.generateNamespace && !option.prefix.isEmpty()) {
        nsList.append(QLatin1String("Ui"));

        QListIterator<QString> it(nsList);
        while (it.hasNext()) {
            QString ns = it.next();
            if (ns.isEmpty())
                continue;

            output << "namespace " << ns << " {\n";
        }

        output << option.indent << "class " << exportMacro << className << ": public " << option.prefix << className << " {};\n";

        it.toBack();
        while (it.hasPrevious()) {
            QString ns = it.previous();
            if (ns.isEmpty())
                continue;

            output << "} // namespace " << ns << "\n";
        }

        if (nsList.count())
            output << "\n";
    }
}
Ejemplo n.º 7
0
Archivo: csv.cpp Proyecto: ambah/KTAB
void CSV::readCSVFile(QString path)
{
    QRegExp space("^\\s*$");
    //getting the csv file path
    QStringList scenarioName;
    if(!path.isEmpty())
    {
        // model->clear();

        QFile file(path);
        if (file.open(QIODevice::ReadOnly) && file.size() > 0)
        {
            int rowindex = 0;                     // file row counter
            QTextStream in(&file);                 // read to text stream

            while (!in.atEnd())
            {
                // read one line from textstream(separated by "\n")
                QString fileLine = in.readLine();

                // parse the read line into separate pieces(tokens) with "," as the delimiter
                QStringList lineToken = fileLine.split(",", QString::SkipEmptyParts);
                QString lastField = lineToken.at(lineToken.length()-1);
                if(lastField.contains(space))
                    lineToken.removeLast();

                if(lineToken.length()>2)//CHECK FOR COLORS CSV
                {
                    if(rowindex >= 2 )
                    {
                        // load parsed data to model accordingly
                        for (int j = 0; j < lineToken.size(); j++)
                        {
                            if(j > 1)
                            {
                                QString value = lineToken.at(j);
                                value = QString::number(value.toFloat(),'f',2);
                                QStandardItem *item = new QStandardItem(value.trimmed());
                                model->setItem(rowindex-2, j, item);
                            }
                            else
                            {
                                QString value = lineToken.at(j);
                                QStandardItem *item = new QStandardItem(value.trimmed());
                                model->setItem(rowindex-2, j, item);
                            }
                        }
                    }
                    else if(rowindex == 1)
                    {
                        for(int i=3; i< lineToken.length(); ++i)
                        {
                            QString header = lineToken.at(i);
                            QStringList headerList = header.split(" ");
                            if(headerList.length()>1)
                            {
                                header = headerList.at(0);
                                header.append(" \n").append(headerList.at(1));
                                lineToken[i]=header;
                            }
                        }

                        model->setHorizontalHeaderLabels(lineToken);
                    }
                    else if(rowindex == 0)
                    {
                        scenarioName.append(lineToken.at(0));
                        scenarioName.append(lineToken.at(1));
                        lineToken.clear();
                    }
                    rowindex++;
                }
                else
                {
                    emit sendMessage("CSV","Unknown Data !");
                    return;
                }
            }
            file.close();
            emit csvModel(model,scenarioName);
        }
        else
        {
            emit sendMessage("CSV","Empty File !");
            return;
        }
    }
}
Ejemplo n.º 8
0
bool ImportIconsWizard::search(const QString& strParam)
{

    QString strParam1 = QUrl::toPercentEncoding(strParam);
    bool retVal = false;
    enableControls(STATE_SEARCHING);
    QUrl url(m_url+"/search");

    CSVEntry entry2 = (*m_missingIter);
    QString channelcsv = QString("%1,%2,%3,%4,%5,%6,%7,%8\n")
                                .arg(escape_csv(entry2.strName))
                                .arg(escape_csv(entry2.strXmlTvId))
                                .arg(escape_csv(entry2.strCallsign))
                                .arg(escape_csv(entry2.strTransportId))
                                .arg(escape_csv(entry2.strAtscMajorChan))
                                .arg(escape_csv(entry2.strAtscMinorChan))
                                .arg(escape_csv(entry2.strNetworkId))
                                .arg(escape_csv(entry2.strServiceId));

    QString message = QObject::tr("Searching for icons for channel %1")
                                                    .arg(entry2.strName);

    OpenBusyPopup(message);

    QString str = wget(url,"s="+strParam1+"&csv="+channelcsv);
    m_listSearch.clear();
    m_iconsList->Reset();

    if (str.isEmpty() || str.startsWith("#") ||
        str.startsWith("Error", Qt::CaseInsensitive))
    {
        LOG(VB_GENERAL, LOG_ERR, QString("Error from search : %1").arg(str));
        retVal = false;
    }
    else
    {
        LOG(VB_CHANNEL, LOG_INFO,
            QString("Icon Import: Working search : %1").arg(str));
        QStringList strSplit = str.split("\n");

        // HACK HACK HACK -- begin
        // This is needed since the user can't escape out of the progress dialog
        // and the result set may contain thousands of channels.
        if (strSplit.size() > 36*3)
        {
            LOG(VB_GENERAL, LOG_WARNING,
                QString("Warning: Result set contains %1 items, "
                        "truncating to the first %2 results")
                    .arg(strSplit.size()).arg(18*3));
            while (strSplit.size() > 18*3) strSplit.removeLast();
        }
        // HACK HACK HACK -- end

        QString prevIconName;
        int namei = 1;

        for (int x = 0; x < strSplit.size(); ++x)
        {
            QString row = strSplit[x];
            if (row != "#" )
            {
                QStringList ret = extract_csv(row);
                LOG(VB_CHANNEL, LOG_INFO,
                    QString("Icon Import: search : %1 %2 %3")
                        .arg(ret[0]).arg(ret[1]).arg(ret[2]));
                SearchEntry entry;
                entry.strID = ret[0];
                entry.strName = ret[1];
                entry.strLogo = ret[2];
                m_listSearch.append(entry);

                MythUIButtonListItem *item;
                if (prevIconName == entry.strName)
                {
                    QString newname = QString("%1 (%2)").arg(entry.strName)
                                                        .arg(namei);
                    item = new MythUIButtonListItem(m_iconsList, newname,
                                             qVariantFromValue(entry));
                    namei++;
                }
                else
                {
                    item = new MythUIButtonListItem(m_iconsList, entry.strName,
                                             qVariantFromValue(entry));
                    namei=1;
                }

                QString iconname = entry.strName;

                item->SetImage(entry.strLogo, "icon", false);
                item->SetText(iconname, "iconname");

                prevIconName = entry.strName;
            }
        }

        retVal = true;
    }
    enableControls(STATE_NORMAL, retVal);
    CloseBusyPopup();
    return retVal;
}
Ejemplo n.º 9
0
QList<File> *Phone::getFileList(QString filter)
{
    QList<File> *fileList = new QList<File>;
    File tmpFile;

    if ((this->getConnectionState() != RECOVERY) && (this->getConnectionState() != DEVICE))
    {
        return NULL;
    }

    QProcess *phone=new QProcess(this);
    phone->setProcessChannelMode(QProcess::MergedChannels);
    QString command;

    qDebug()<<QDateTime::currentDateTime().toString("hh:mm:ss");
    qDebug()<<"Phone::getFileList() - "<<this->getPath();
    if (this->hiddenFiles)
        command="\""+this->sdk+"\""+"adb shell \"busybox ls -l -a \'"+this->codec->toUnicode(this->getPath().toUtf8())+"\' | grep \'" + filter + "\'\"";
    else
        command="\""+this->sdk+"\""+"adb shell \"busybox ls -l \'"+this->codec->toUnicode(this->getPath().toUtf8())+"\' | grep \'" + filter + "\'\"";

    qDebug()<<"Phone::getFileList() - "<<command;
    phone->start(command);
    QString outputLine="1";
    QStringList outputLines;

    while (!outputLine.isEmpty())
    {
        qApp->processEvents();
        phone->waitForReadyRead(-1);
        outputLine = phone->readLine();
        qDebug()<<"Phone::getFileList() - "<<outputLine;
        outputLines.append(outputLine);
    }
    if (outputLines.first().contains("No such file or directory")||outputLines.first().contains("cannot")||outputLines.first().contains("Not a directory"))
    {
        phone->terminate();
        delete phone;
        return NULL;
    }

    outputLines.removeLast();   // pusty

    QStringList lineParts;
    QString name;
    QFile plik;
//    QFileIconProvider *provider = new QFileIconProvider;
    QString tmp;

    while (outputLines.length()>0)
    {
        qApp->processEvents();
        lineParts.clear();
        name.clear();
        tmp.clear();
        tmp = outputLines.takeFirst();
        tmp.remove(QRegExp("\\s+$"));
        lineParts=tmp.split(QRegExp("\\s+"));
//        outputLines.removeFirst();
        if (lineParts.length()>8)
        {
            if (lineParts[4].contains(","))
            {
                tmpFile.fileSize = lineParts.at(4)+lineParts.at(5);
                lineParts.removeAt(5);
            }
            else
                tmpFile.fileSize = lineParts.at(4);
            tmpFile.fileDate = lineParts[5]+" "+lineParts[6]+" "+lineParts[7];

            for (int i=8;i<lineParts.length();i++)
                name.append(lineParts.at(i)+" ");
            name.chop(1);
            name.remove(QString("%1[0m").arg( QChar( 0x1b )));
            name.remove(QChar( 0x1b ), Qt::CaseInsensitive);
            if (name.contains("0;30"))//black
            {
                tmpFile.fileColor = QColor(Qt::black);
            }
            else if (name.contains("0;34"))//blue
            {
                tmpFile.fileColor = QColor(Qt::blue);
            }
            else if (name.contains("0;32"))//green
            {
                tmpFile.fileColor = QColor(Qt::green);
            }
            else if (name.contains("0;36"))//cyan
            {
                tmpFile.fileColor = QColor(Qt::cyan);
            }
            else if (name.contains("0;31"))//red
            {
                tmpFile.fileColor = QColor(Qt::red);
            }
            else if (name.contains("0;35"))//purple
            {
                tmpFile.fileColor = QColor(0, 0, 0);
            }
            else if (name.contains("0;33"))//brown
            {
                tmpFile.fileColor = QColor(0, 0, 0);
            }
            else if (name.contains("0;37"))//light gray
            {
                tmpFile.fileColor = QColor(Qt::lightGray);
            }
            else if (name.contains("1;30"))//dark gray
            {
                tmpFile.fileColor = QColor(Qt::darkGray);
            }
            else if (name.contains("1;34"))//dark gray
            {
                tmpFile.fileColor = QColor(Qt::blue);
            }
            else if (name.contains("1;32"))//light green
            {
                tmpFile.fileColor = QColor(Qt::green);
            }
            else if (name.contains("1;36"))//light cyan
            {
                tmpFile.fileColor = QColor(Qt::cyan);
            }
            else if (name.contains("1;31"))//light red
            {
                tmpFile.fileColor = QColor(Qt::red);
            }
            else if (name.contains("1;35"))//light purple
            {
                tmpFile.fileColor = QColor(0, 0, 0);
            }
            else if (name.contains("1;33"))//yellow
            {
                tmpFile.fileColor = QColor(Qt::yellow);
            }
            else if (name.contains("1;37"))//white
            {
                tmpFile.fileColor = QColor(Qt::white);
            }
            else
                tmpFile.fileColor = QColor(Qt::black);
            name.remove(QRegExp("\\[\\d;\\d+m"));

            tmpFile.fileName = QString::fromUtf8(name.toAscii());
            tmpFile.filePath = this->getPath() + tmpFile.fileName;

            qDebug()<<"Phone::getFileList() - plik: "<<name<< " - " <<lineParts.first();

            if (lineParts.first()[0]=='d')
                tmpFile.fileType = "dir";
            else if (lineParts.first()[0]=='-'||lineParts.first()[0]=='s')
                tmpFile.fileType = "file";
            else if (lineParts.first()[0]=='l')
                tmpFile.fileType = "link";
            else if (lineParts.first()[0]=='c'||lineParts.first()[0]=='b'||lineParts.first()[0]=='p')
                tmpFile.fileType = "device";

            name = tmpFile.fileName;
            name.remove(QString("%1[0m").arg( QChar( 0x1b )));
            name.remove(QChar( 0x1b ), Qt::CaseInsensitive);
            name.remove(QRegExp("\\[\\d;\\d+m"));
//            if (tmpFile.fileType == "file" || tmpFile.fileType == "device")
//            {
//                plik.setFileName(QDir::currentPath()+"/tmp/"+name);
//                plik.open(QFile::WriteOnly);
//                tmpFile.fileIcon = provider->icon(QFileInfo(plik));
//                plik.remove();
//            }
//            else if (tmpFile.fileType == "link")
//            {
//                tmpFile.fileIcon = QApplication::style()->standardIcon(QStyle::SP_FileLinkIcon);
//            }
//            else
//                tmpFile.fileIcon = QApplication::style()->standardIcon(QStyle::SP_DirIcon);

            if (tmpFile.fileName == "." || tmpFile.fileName == "..")
                continue;
            else
                fileList->append(tmpFile);
        }
    }
    phone->close();
    qDebug()<<"Phone::getFileList() - skonczylem analizowac pliki";

    phone->terminate();
//    delete provider;
    delete phone;
    return fileList;
}
Ejemplo n.º 10
0
void TMSI::showStartRecording()
{
    m_iSplitCount = 0;

    //Setup writing to file
    if(m_bWriteToFile)
    {
        m_pOutfid->finish_writing_raw();
        m_bWriteToFile = false;
        m_pTimerRecordingChange->stop();
        m_pActionStartRecording->setIcon(QIcon(":/images/record.png"));
    }
    else
    {
        if(!m_bIsRunning)
        {
            QMessageBox msgBox;
            msgBox.setText("Start data acquisition first!");
            msgBox.exec();
            return;
        }

        if(!m_pFiffInfo)
        {
            QMessageBox msgBox;
            msgBox.setText("FiffInfo missing!");
            msgBox.exec();
            return;
        }

        //Initiate the stream for writing to the fif file
        m_fileOut.setFileName(m_sOutputFilePath);
        if(m_fileOut.exists())
        {
            QMessageBox msgBox;
            msgBox.setText("The file you want to write already exists.");
            msgBox.setInformativeText("Do you want to overwrite this file?");
            msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
            int ret = msgBox.exec();
            if(ret == QMessageBox::No)
                return;
        }

        // Check if path exists -> otherwise create it
        QStringList list = m_sOutputFilePath.split("/");
        list.removeLast(); // remove file name
        QString fileDir = list.join("/");

        if(!dirExists(fileDir.toStdString()))
        {
            QDir dir;
            dir.mkpath(fileDir);
        }

        m_pOutfid = Fiff::start_writing_raw(m_fileOut, *m_pFiffInfo, m_cals);
        fiff_int_t first = 0;
        m_pOutfid->write_int(FIFF_FIRST_SAMPLE, &first);

        m_bWriteToFile = true;

        m_pTimerRecordingChange = QSharedPointer<QTimer>(new QTimer);
        connect(m_pTimerRecordingChange.data(), &QTimer::timeout, this, &TMSI::changeRecordingButton);
        m_pTimerRecordingChange->start(500);
    }
}
void MangaListWidget::updateMangaInfo(QModelIndex index) {
  _editMangaInfoButton->setChecked(false);

  QStandardItem* currentItem = _model->itemFromIndex(index);

  if (!currentItem->parent()) {
    QDir mangaDirectory(_scansDirectory.path()+"/"+currentItem->text());

    if (mangaDirectory.exists("cover.png")) {
      QPixmap pixmap(mangaDirectory.path()+"/cover.png");
      pixmap = pixmap.scaled(_mangaPreviewLabel->width(), _mangaPreviewLabel->height(), Qt::KeepAspectRatio);
      _mangaPreviewLabel->setPixmap(pixmap);
      _coverHasToBeSet = false;
    } else {
      QPixmap pixmap(Utils::getIconsPath()+"/setCover.png");
      pixmap = pixmap.scaled(_mangaPreviewLabel->width(), _mangaPreviewLabel->height(), Qt::KeepAspectRatio);
      _mangaPreviewLabel->setPixmap(pixmap);
      _coverHasToBeSet = true;
    }

    QFile file(mangaDirectory.filePath("mangaInfo.txt"));
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
      QMessageBox::critical(this, "Manga info error", "Can't open "+file.fileName()+" in 'read only' whithin MangaListWidget::updateMangaInfo.");
      _genreLabel->setText("");
      _authorLabel->setText("");
      _artistLabel->setText("");
      _publisherLabel->setText("");
      _magazineLabel->setText("");
      _startDateLabel->setText("");
      return;
    }

    QTextStream inFile(&file);
    inFile.setCodec("UTF-8");

    QStringList infosList = inFile.readAll().split("\n", QString::SkipEmptyParts);
    for (const QString& info: infosList) {
      if (info.isEmpty())
        break;

      QStringList newInfoList = info.split(":");
      if (newInfoList.size() < 2) {
        qDebug() << "Check" << mangaDirectory.filePath("mangaInfo.txt") << "file may be corrupted.";
        break;
      }

      QString newInfo = newInfoList.at(1);

      QStringList resultList;
      if (info.startsWith("Genre")) {
        resultList = newInfo.split(" ");

        while (resultList.size() > 6)
          resultList.removeLast();
        if (resultList.size() > 3) {
          resultList.insert(3, "\n");
          _genreLabel->setText(resultList.join(" "));
        } else {
          _genreLabel->setText(newInfo);
        }
      } else if (info.startsWith("Author"))
        _authorLabel->setText(newInfo);
      else if (info.startsWith("Artist"))
        _artistLabel->setText(newInfo);
      else if (info.startsWith("Publisher"))
        _publisherLabel->setText(newInfo);
      else if (info.startsWith("Magazine")) {
        resultList = newInfo.split(" ");

        if (resultList.size() > 3) {
          resultList.insert(3, "\n");
          _magazineLabel->setText(resultList.join(" "));
        } else {
          _magazineLabel->setText(newInfo);
        }
      } else if (info.startsWith("Start Date"))
        _startDateLabel->setText(newInfo);
    }
  }
}
Ejemplo n.º 12
0
void NetworkAccessManager::HandleDownload(QObject *object){
#ifdef WEBENGINEVIEW
    static QSet<QObject*> set;
    if(set.contains(object)) return;
    set << object;
    connect(object, &QObject::destroyed, [object](){ set.remove(object);});

    Application::AskDownloadPolicyIfNeed();

    DownloadItem *item = new DownloadItem(object);
    QWebEngineDownloadItem *orig_item = qobject_cast<QWebEngineDownloadItem*>(object);

    QString dir = Application::GetDownloadDirectory();
    QString filename;
    QString mime;
    QUrl url;
    if(orig_item){
        if(WebEngineView *w = qobject_cast<WebEngineView*>(Application::CurrentWidget())){
            if(TreeBank *tb = w->GetTreeBank()) tb->GoBackOrCloseForDownload(w);
        }
        filename = orig_item->path();
        mime = orig_item->mimeType();
        url = orig_item->url();
    } else {
        if(QuickWebEngineView *w = qobject_cast<QuickWebEngineView*>(Application::CurrentWidget())){
            if(TreeBank *tb = w->GetTreeBank()) tb->GoBackOrCloseForDownload(w);
        }
        filename = object->property("path").toString();
        mime = object->property("mimeType").toString();
        url = object->property("url").toUrl();
    }

    filename = filename.isEmpty() ? dir
        : dir + filename.split(QStringLiteral("/")).last();

    if(filename.isEmpty() ||
       Application::GetDownloadPolicy() == Application::Undefined_ ||
       Application::GetDownloadPolicy() == Application::AskForEachDownload){

        QString filter;

        QMimeDatabase db;
        QMimeType mimeType = db.mimeTypeForName(mime);
        if(!mimeType.isValid() || mimeType.isDefault()) mimeType = db.mimeTypeForFile(filename);
        if(!mimeType.isValid() || mimeType.isDefault()) mimeType = db.mimeTypeForUrl(url);

        if(mimeType.isValid() && !mimeType.isDefault()) filter = mimeType.filterString();

        filename = ModalDialog::GetSaveFileName_(QString(), filename, filter);
    }

    if(filename.isEmpty()){
        QMetaObject::invokeMethod(object, "cancel");
        item->deleteLater();
        return;
    }

    item->SetPath(filename);
    if(orig_item){
        orig_item->setPath(filename);
    } else {
        object->setProperty("path", filename);
    }
    QMetaObject::invokeMethod(object, "accept");
    MainWindow *win = Application::GetCurrentWindow();
    if(win && win->GetTreeBank()->GetNotifier())
        win->GetTreeBank()->GetNotifier()->RegisterDownload(item);

    QStringList path = filename.split(QStringLiteral("/"));
    path.removeLast();
    Application::SetDownloadDirectory(path.join(QStringLiteral("/")) + QStringLiteral("/"));
#else
    Q_UNUSED(object);
#endif
}
Ejemplo n.º 13
0
int main(int argc, char *argv[])
{
    // Use UTF-8, ignoring any LANG settings in the environment
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));

    {   // Set the default OpenGL version to be 2.1 with sample buffers
        QSurfaceFormat format;
        format.setVersion(2, 1);
        QSurfaceFormat::setDefaultFormat(format);
    }

    // Create the Application object
    App app(argc, argv);

    // Initialize various Python modules and the interpreter itself
    fab::preInit();
    Graph::preInit();
    AppHooks::preInit();
    Py_Initialize();

    // Set locale to C to make atof correctly parse floats
    setlocale(LC_NUMERIC, "C");

    {   // Modify Python's default search path to include the application's
        // directory (as this doesn't happen on Linux by default)
#if defined Q_OS_MAC
        QStringList path = QCoreApplication::applicationDirPath().split("/");
        path.removeLast();
        path << "Resources";
        fab::postInit({path.join("/").toStdString()});
#elif defined Q_OS_LINUX
        auto dir = QCoreApplication::applicationDirPath();
        std::vector<std::string> fab_paths =
            {(dir + "/sb").toStdString(),
             (dir + "/../share/antimony/").toStdString()};
        for (auto p : QStandardPaths::standardLocations(
                QStandardPaths::AppDataLocation))
        {
            fab_paths.push_back(p.toStdString());
        }
        fab::postInit(fab_paths);
#else
#error "Unknown OS!"
#endif
    }

    {   // Install operator.or_ as a reducer for shapes
        auto op = PyImport_ImportModule("operator");
        Datum::installReducer(fab::ShapeType, PyObject_GetAttrString(op, "or_"));
        Py_DECREF(op);
    }

    {   // Check to make sure that the fab module exists
        PyObject* fab = PyImport_ImportModule("fab");
        if (!fab)
        {
            PyErr_Print();
            QMessageBox::critical(NULL, "Import error",
                    "Import Error:<br><br>"
                    "Could not find <tt>fab</tt> Python module.<br>"
                    "Antimony will now exit.");
            exit(1);
        }
        Py_DECREF(fab);
    }

    {   // Parse command-line arguments
        QCommandLineParser parser;
        parser.setApplicationDescription("CAD from a parallel universe");
        parser.addHelpOption();
        QCommandLineOption forceHeightmap("heightmap",
                "Open 3D windows in heightmap mode");
        parser.addOption(forceHeightmap);
        parser.addPositionalArgument("file", "File to open", "[file]");

        parser.process(app);

        auto args = parser.positionalArguments();
        if (args.length() > 1)
        {
            qCritical("Too many command-line arguments");
            exit(1);
        }
        else if (args.length() == 1)
        {
            app.loadFile(args[0]);
        }
    }

    app.makeDefaultWindows();
    return app.exec();
}
Ejemplo n.º 14
0
bool LayoutLoader::readAsaElcFile(QString path, QStringList &channelNames, QVector<QVector<double> > &location3D, QVector<QVector<double> > &location2D, QString &unit)
{
    //Open .elc file
    if(!path.contains(".elc"))
        return false;

    QFile file(path);
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug()<<"Error opening elc file";
        return false;
    }

    //Start reading from file
    double numberElectrodes;
    QTextStream in(&file);
    bool read2D = false;

    while(!in.atEnd())
    {
        QString line = in.readLine();

        QStringList fields = line.split(QRegExp("\\s+"));

        //Delete last element if it is a blank character
        if(fields.at(fields.size()-1) == "")
            fields.removeLast();

        if(!line.contains("#")) //Skip commented areas in file
        {
            //Read number of electrodes
            if(line.contains("NumberPositions"))
                numberElectrodes = fields.at(1).toDouble();

            //Read the unit of the position values
            if(line.contains("UnitPosition"))
                unit = fields.at(1);

            //Read actual electrode positions
            if(line.contains("Positions2D"))
                read2D = true;

            if(line.contains(":") && !read2D) //Read 3D positions
            {
                channelNames.push_back(fields.at(0));
                QVector<double> posTemp;

                posTemp.push_back(fields.at(fields.size()-3).toDouble());    //x
                posTemp.push_back(fields.at(fields.size()-2).toDouble());    //y
                posTemp.push_back(fields.at(fields.size()-1).toDouble());    //z

                location3D.push_back(posTemp);
            }

            if(line.contains(":") && read2D) //Read 2D positions
            {
                QVector<double> posTemp;
                posTemp.push_back(fields.at(fields.size()-2).toDouble());    //x
                posTemp.push_back(fields.at(fields.size()-1).toDouble());    //y
                location2D.push_back(posTemp);
            }

            //Read channel names
            if(line.contains("Labels"))
            {
                line = in.readLine();
                fields = line.split(QRegExp("\\s+"));

                //Delete last element if it is a blank character
                if(fields.at(fields.size()-1) == "")
                    fields.removeLast();

                channelNames = fields;
            }
        }
    }

    Q_UNUSED(numberElectrodes);

    file.close();

    return true;
}
Ejemplo n.º 15
0
void WriteDeclaration::acceptUI(DomUI *node)
{
    QString qualifiedClassName = node->elementClass() + m_option.postfix;
    QString className = qualifiedClassName;

    QString varName = m_driver->findOrInsertWidget(node->elementWidget());
    QString widgetClassName = node->elementWidget()->attributeClass();

    QString exportMacro = node->elementExportMacro();
    if (!exportMacro.isEmpty())
        exportMacro.append(QLatin1Char(' '));

    QStringList namespaceList = qualifiedClassName.split(QLatin1String("::"));
    if (namespaceList.count()) {
        className = namespaceList.last();
        namespaceList.removeLast();
    }

    openNameSpaces(namespaceList, m_output);

    if (namespaceList.count())
        m_output << "\n";

    m_output << "class " << exportMacro << m_option.prefix << className << "\n"
           << "{\n"
           << "public:\n";

    const QStringList connections = m_uic->databaseInfo()->connections();
    for (int i=0; i<connections.size(); ++i) {
        const QString connection = connections.at(i);

        if (connection == QLatin1String("(default)"))
            continue;

        m_output << m_option.indent << "QSqlDatabase " << connection << "Connection;\n";
    }

    TreeWalker::acceptWidget(node->elementWidget());

    m_output << "\n";

    WriteInitialization(m_uic, m_activateScripts).acceptUI(node);

    if (node->elementImages()) {
        if (m_option.extractImages) {
            ExtractImages(m_uic->option()).acceptUI(node);
        } else {
            m_output << "\n"
                << "protected:\n"
                << m_option.indent << "enum IconID\n"
                << m_option.indent << "{\n";
            WriteIconDeclaration(m_uic).acceptUI(node);

            m_output << m_option.indent << m_option.indent << "unknown_ID\n"
                << m_option.indent << "};\n";

            WriteIconInitialization(m_uic).acceptUI(node);
        }
    }

    if (m_activateScripts) {
        m_output << "\nprivate:\n\n";
        writeScriptContextClass(m_option.indent, m_output);
    }

    m_output << "};\n\n";

    closeNameSpaces(namespaceList, m_output);

    if (namespaceList.count())
        m_output << "\n";

    if (m_option.generateNamespace && !m_option.prefix.isEmpty()) {
        namespaceList.append(QLatin1String("Ui"));

        openNameSpaces(namespaceList, m_output);

        m_output << m_option.indent << "class " << exportMacro << className << ": public " << m_option.prefix << className << " {};\n";

        closeNameSpaces(namespaceList, m_output);

        if (namespaceList.count())
            m_output << "\n";
    }
}
Ejemplo n.º 16
0
FileList *Phone::getStaticFileList(QString path, QString sdk, bool hiddenFiles)
{
    QTextCodec *codec = QTextCodec::codecForLocale();
    FileList *fileList = new FileList;

    QProcess *phone=new QProcess;
    phone->setProcessChannelMode(QProcess::MergedChannels);
    QString command;

    qDebug()<<QDateTime::currentDateTime().toString("hh:mm:ss");
    qDebug()<<"Phone::getFileList() - "<<path;
    if (hiddenFiles)
        command="\""+sdk+"\""+"adb shell \"busybox ls -l -a \'"+codec->toUnicode(path.toAscii())+"\'\"";
    else
        command="\""+sdk+"\""+"adb shell \"busybox ls -l \'"+codec->toUnicode(path.toAscii())+"\'\"";

    qDebug()<<"Phone::getFileList() - "<<command;
    phone->start(command);
    QString outputLine="1";
    QStringList outputLines;

    while (!outputLine.isEmpty())
    {
        phone->waitForReadyRead(-1);
        outputLine = phone->readLine();
        qDebug()<<"Phone::getFileList() - "<<outputLine;
        outputLines.append(outputLine);
    }
    if (outputLines.first().contains("No such file or directory")||outputLines.first().contains("cannot")||outputLines.first().contains("Not a directory"))
    {
        fileList->name.append("error");
        phone->terminate();
        delete phone;
        return fileList;
    }

    outputLines.removeLast();   // pusty

    QStringList lineParts;
    QString name;

    while (outputLines.length()>0)
    {
        lineParts.clear();
        name.clear();
        lineParts=outputLines.first().split(QRegExp("\\s+"));
        outputLines.removeFirst();
        if (lineParts.length()>8)
        {
            if (lineParts[4].contains(","))
            {
                fileList->size.append(lineParts.at(4)+lineParts.at(5));
                lineParts.removeAt(5);
            }
            else
                fileList->size.append(lineParts.at(4));
            fileList->date.append(lineParts[5]+" "+lineParts[6]+" "+lineParts[7]);

            for (int i=8;i<lineParts.length()-1;i++)
                name.append(lineParts.at(i)+" ");
            name.chop(1);
            fileList->name.append(name);
            qDebug()<<"Phone::getFileList() - plik: "<<name<< " - " <<lineParts.first();


            if (lineParts.first()[0]=='d')
                fileList->type.append("dir");
            else if (lineParts.first()[0]=='-'||lineParts.first()[0]=='s')
                fileList->type.append("file");
            else if (lineParts.first()[0]=='l')
                fileList->type.append("link");
            else if (lineParts.first()[0]=='c'||lineParts.first()[0]=='b'||lineParts.first()[0]=='p')
                fileList->type.append("device");
        }
    }
    phone->close();
    qDebug()<<"Phone::getFileList() - skonczylem analizowac pliki";
    if (fileList->name.count()>0)
    {
        //        if (fileList->name.first()==".")
        //        {
        int x=fileList->name.indexOf(".");
        if (x!=-1)
        {
            qDebug("deleting .");
            fileList->date.removeAt(x);
            fileList->name.removeAt(x);
            fileList->size.removeAt(x);
            fileList->type.removeAt(x);
        }

        x=fileList->name.indexOf("..");
        if (x!=-1)
        {
            qDebug("deleting ..");
            fileList->date.removeAt(x);
            fileList->name.removeAt(x);
            fileList->size.removeAt(x);
            fileList->type.removeAt(x);
        }
    }
    qDebug()<<"Phone::getFileList() - . i .. usuniete, koncze funkcje";
    phone->terminate();
    delete phone;
    return fileList;
}
Ejemplo n.º 17
0
//! for BED reading (12 or 14 columns)
inline bool annotationReader::readBedLine() {
    bool rval = false;
    // check if there are some "fake lines" available - in this case read this one and leave the file as it is
    if (fakeBedLines.count() > 0) {
        QString line = fakeBedLines.takeFirst();
        QStringList fields = line.split('\t');
        chrom = fields.at(0);
        strand = fields.at(1);
        start = fields.at(2).toUInt();
        end = fields.at(3).toUInt();
        feature = fields.at(4);
        score = fields.at(5).toFloat();
        name = fields.at(6);
        parent = fields.at(7);
        source = "BED";
        phase = ".";
        rval = true;
    } else {
        if(!in.atEnd()) {
            QString line = in.readLine();
            QStringList fields = line.split('\t');
            if (fields.size() >= 6) {
                chrom = fields.at(0);
                start = fields.at(1).toUInt();
                end = fields.at(2).toUInt()-1; //! this is a bit awkward, the start is 0-based, but the end not
                QString modelname = fields.at(3);
                if (fields.size() >= 13) {
                    name = fields.at(12);
                } else {
                    if (modelname.count('.') > 0) {
                        QStringList tempSplit = modelname.split('.');
                        tempSplit.removeLast();
                        name = tempSplit.join(".");
                    } else {
                        name = modelname;
                    }
                }
                QString tempscore = fields.at(4);
                if (tempscore == ".") { score = 0; }
                else { score = tempscore.toFloat(); }
                strand = fields.at(5);
                uint thickStart = fields.at(6).toUInt();
                uint thickEnd = fields.at(7).toUInt();
                QString modelFeature = "";
                if (thickStart == thickEnd) {
                    feature = "non-coding-gene";
                    modelFeature = "non-coding-RNA";
                } else {
                    feature = "gene";
                    modelFeature = "mRNA";
                }
                source = "BED";
                phase = ".";
                parent = "none";
                rval = true;
                // create the fake lines - so first the model
                QStringList toStore;
                toStore << chrom << strand << QString::number(start) << QString::number(end) << modelFeature << QString::number(score) << modelname << name;
                fakeBedLines << toStore.join("\t");
                // and now all the exons
                uint blockCount = fields.at(9).toUInt();
                QStringList blockSizes = fields.at(10).split(',');
                QStringList blockStarts = fields.at(11).split(',');
                uint exonStart = 0;
                uint exonEnd = 0;
                for (uint i = 0; i < blockCount; ++i) {
                    toStore.clear();
                    exonStart = start + blockStarts.at(i).toUInt();
                    exonEnd = exonStart + blockSizes.at(i).toUInt() - 1; //! this is a bit awkward, the start is 0-based, but the end not
                    toStore << chrom << strand << QString::number(exonStart) << QString::number(exonEnd) << "exon" << QString::number(score) << "none" << modelname;
                    fakeBedLines << toStore.join("\t");
                }
            } else {
                if (line.length() == 0) {
                    std::cerr << "skipping empty line" << std::endl << std::flush;
                    rval = this->readBedLine();
                }
                else { if (line.at(0) == '#') {
                        std::cerr << "skipping comment line:" << std::endl << line.toStdString() << std::endl << std::flush;
                        rval = this->readBedLine(); }
                }
            }
        }
    }
    return(rval);
}
Ejemplo n.º 18
0
void Song::removeLastChorus(QStringList ct, QStringList &list)
{
    for(int i(0);i<ct.count();++i)
        list.removeLast();
}
Ejemplo n.º 19
0
template <typename M> void MatchT<M>::split()
{
    if(!ShapeT<M>::isMeshOpen() || parts_.size()==0 || points_.size()==0)
    {
        qCritical() << "Cannot split mesh! Either mesh is not open or parts or points do not exist!" ;
        return;
    }
    
    // Try to find a seg file to use for splitting the mesh
    bool useSegFile = false;
    
    QStringList pathParts = meshFilename_.split("/");
    
    QString segName = pathParts.last().split(".").first().append(".seg");
    
    pathParts.removeLast();
    
    pathParts.push_back(segName);
    
    QString segPath = pathParts.join("/");
    
    QFile file(segPath);
    
    std::vector<int> segLabels;
    
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qCritical() << "Could not open file " << segPath ;
    }
    else
    {
        QTextStream in(&file);
        
        while (!in.atEnd())
        {
            QString line = in.readLine();
            segLabels.push_back(line.toInt());
        }
        
        if (segLabels.size()!= ShapeT<M>::mesh_.n_faces())
        {
            qDebug() << "Mesh has a seg file, but it only contained " << segLabels.size() << " labels for " << ShapeT<M>::mesh_.n_faces() << " faces, so cannot use it!";
        }
        else
        {
            useSegFile = true;
        }
    }
    
    std::map<int, int> partID2partIndex;
    
    std::map<int, std::map<typename M::VertexHandle,typename M::VertexHandle> > partID2vhMap;
    
    typename std::vector<Part>::const_iterator partscIt (parts_.begin()), partscEnd(parts_.end());

    int index =0;
    
    for (; partscIt != partscEnd; ++partscIt)
    {
        partID2partIndex[partscIt->partID_] = index;
        index++;
    }

    
    typename M::ConstFaceIter cfIt(ShapeT<M>::mesh_.faces_begin()), facesEnd(ShapeT<M>::mesh_.faces_end());
    
    int f = 0;
    
    // For every face go over all points of the match and find the nearest point to this face
    for (; cfIt!=facesEnd; ++cfIt)
    {
        int facePartID = -1;
        
        // Get the three vertices of this face (should be 3) so we can get the normal to the face
        typename M::ConstFaceVertexIter cfvIt;
        
        if (useSegFile)
        {
            facePartID = segLabels[ShapeT<M>::indexMap_[f]] + 1; //only works assuming part ids start from 2 and seg ids start from 1
        }
        else
        {
            cfvIt= ShapeT<M>::mesh_.cfv_iter(cfIt);
            
            typename std::vector<MeshPoint>::const_iterator pointsIt(points_.begin()), pointsEnd(points_.end());
            
            double minDistance = std::numeric_limits<double>::max();
          
            typename M::Point p0 = ShapeT<M>::mesh_.point(cfvIt);
            ++cfvIt;
            typename M::Point p1 = ShapeT<M>::mesh_.point(cfvIt);
            ++cfvIt;
            typename M::Point p2 = ShapeT<M>::mesh_.point(cfvIt);
            
            // Go over all points in the match (these have part id labels)
            for( ; pointsIt!=pointsEnd ; ++pointsIt)
            {
                double p2pDistance = sqrDistPoint2Triangle(p0,p1,p2,OpenMesh::vector_cast<typename M::Point>(pointsIt->pos_));
                
                if (p2pDistance < minDistance)
                {
                    minDistance = p2pDistance;
                    facePartID = pointsIt->partID_;
                }
            }
        }
        
        Part& cPart = parts_[partID2partIndex[facePartID]];
        typename ShapeT<M>::Mesh& cMesh = cPart.partShape_.mesh();
        
        std::map< typename M::VertexHandle, typename M::VertexHandle>& cvhMap = partID2vhMap[facePartID];
        
        // reset the face vertex iterator
        cfvIt = ShapeT<M>::mesh_.cfv_iter(cfIt);
        
        std::vector<typename M::VertexHandle> face_vhandles;
        
        int i=0;
        // Go over all vertices of this face (should only be 3 of them), add them to the new mesh if they haven't been added yet, and add their handle to the list of handles for the new face to be added to the new mesh
        for(; cfvIt; ++cfvIt, ++i)
        {
            // check if the vertex has been added to this part
            if(cvhMap.count(cfvIt)<=0)
            {
                typename M::VertexHandle vhandle = cMesh.add_vertex(ShapeT<M>::mesh_.point(cfvIt));
                face_vhandles.push_back(vhandle);
                // add this vertex new handle to the map
                cvhMap[cfvIt] = vhandle;
            }
            else
            {
                face_vhandles.push_back(cvhMap[cfvIt]);
            }
        }
        if( i>3)
        {
            qWarning() << "Warning, found " << i << " vertices for this face instead of 3!!";
        }
        
        cMesh.add_face(face_vhandles);
        
        f++;
    }
    
    // Update normals for all part meshes
    typename std::vector<Part>::iterator partsIt (parts_.begin()), partsEnd(parts_.end());

    for (; partsIt != partsEnd; ++partsIt)
    {
        typename ShapeT<M>::Mesh& cMesh = partsIt->partShape_.mesh();
        
        cMesh.request_face_normals();
        cMesh.request_vertex_normals();
        cMesh.update_face_normals();
        cMesh.update_vertex_normals();
    }
    
    segmented_ = true;
}
Ejemplo n.º 20
0
void UpdatingWindow::fileDownloaded(QNetworkReply* pReply)
{

    //emit a signal
    pReply->deleteLater();
    writeToFile->close();
    this->ui->label->setText("Unpacking");

    QDir dir;
    QStringList path = pathToDownload.split("/");
    path.removeLast();
    QString oldPath = path.join("/")+"_old/";
    QString exeName = fileToDownload.replace(".zip", "");
    qDebug() << exeName << AppData::Instance()->executablePath(pathToDownload+exeName) << AppData::Instance()->executablePath(pathToDownload+exeName).replace(exeName, "").replace(".app", exeName+".app");

    QString resourcesPath = pathToDownload;
    if(osName() == "win")
    {
        resourcesPath = AppData::Instance()->executablePath(pathToDownload).replace(".exe", "")+ "/";
    }


    QString program;
    QStringList arguments;
    if(osName() == "osx" || osName()=="linux")
    {
        program = "unzip";
        arguments << "-o" << pathToDownload + fileToDownload << "-d " << pathToDownload;
        QProcess::execute("unzip -o " + pathToDownload + fileToDownload + " -d " + pathToDownload);
    }
    else if(osName()== "win")
    {
        program = "7za.exe";
        QString test = QString("-o")+pathToDownload;
        arguments << "x" << pathToDownload + fileToDownload << "-aoa" <<test;
    }




    QProcess *myProcess = new QProcess();
    qDebug() << program;
    myProcess->setProcessChannelMode(QProcess::MergedChannels);
    myProcess->start(program, arguments);
    //sleep(10);
    myProcess->waitForFinished(-1);
    //qDebug() << myProcess->program() << myProcess->arguments().at(3);
    qDebug() << myProcess->readAll();
    if (QFile::exists(resourcesPath+"settings.json"))
    {
        if(QFile::remove(resourcesPath+"settings.json")){
            qDebug() << "removed settings.json";
        }

    }
    if (QFile::exists(resourcesPath+"list.json"))
    {
        QFile::remove(resourcesPath+"list.json");
    }

    qDebug() << resourcesPath;
    qDebug() << oldPath;
    QFile file(oldPath+"settings.json");
    if(!file.rename(resourcesPath+"settings.json")){
        qWarning() << "Settings.json move failed!!!";
    }
    QFile file2(oldPath+"list.json");
    file2.rename(resourcesPath+"list.json");
    QDir old(oldPath);
    old.removeRecursively();

    if(writeToFile->remove()){
        qDebug() << "Removed Zip File";
        QDir macJunkDir(pathToDownload + "__MACOSX");
        macJunkDir.removeRecursively();
        writeToFile->close();
    } else {
        qDebug() << "Failed to remove zip file";
    }

    this->ui->label->setText("Done!");
    this->ui->progressBar->setValue(120);
    QString execPath;
    if(osName()=="osx")
    {
        QProcess::execute(QString("chmod +x %1").arg(pathToDownload + fileToDownload.replace(".zip", "")+ + ".app/Contents/MacOS/" + fileToDownload.replace(".zip", "")));
        QProcess::execute(QString("chmod +x %1").arg(pathToDownload + fileToDownload.replace(".zip", "")+ ".app"));
        execPath = QString("open %1").arg(pathToDownload + fileToDownload.replace(".zip", "")+ ".app");
        system(execPath.toLatin1());
    }else if(osName()=="win"){
        execPath = AppData::Instance()->executablePath("start " +pathToDownload+fileToDownload.replace(".zip", ".exe"));
        system(execPath.toLatin1());
    }
    QProcess::startDetached(execPath);
    qDebug() << execPath;
    //qDebug() << process->errorString();
    this->close();

}
Ejemplo n.º 21
0
/*****************************************************************
 *函数名称:reDrawHisDataDisplay
 *函数功能:当历史数据收集器的长度发生变化的时候,点击确定按钮后重绘场景中的
 *                    历史数据显示器控件
 *edit by zqh
 *2011-9-27
 ****************************************************************/
void QHisdDataLoggerDialog::reDrawHisDataDisplay()
{
    int totalSceneNum = pwnd->pSceneSheet.size();
    QList<QGraphicsItem *> Items;
    QGraphicsItem *pItem = NULL;
    QGraphicsItem *pNewItem = NULL;
    int nID = 0;
    int  i = 0;
    int j = 0;
    int k = 0;
    int nsheet = pwnd->nActiveSheetIndex;
    int nOldNum = 0; //原历史数据收集器取样长度
    int nNewNum = pwnd->m_pSamSysParame->m_historyLogData.nSampleLen;//历史数据收集器取样长度
    QStringList *sList = new QStringList();
    QStringList slist;
    Items.clear();

    for(i = 0; i < totalSceneNum;i++)   //扫描所有页面
    {
        pwnd->nActiveSheetIndex = i;
        pwnd->pView->setScene(pwnd->pSceneSheet[i]);
        QPainterPath path;
        path.addRect(0,0,pwnd->pSceneSheet[i]->width(),pwnd->pSceneSheet[i]->height());
        pwnd->pSceneSheet[i]->setSelectionArea(path);
        Items = pwnd->pSceneSheet[i]->selectedItems();
        foreach(QGraphicsItem *item,Items)
            item->setSelected(false);

        for(j = 0; j < Items.size(); j++)   //扫描当前页面的所有控件
        {
            pItem = Items.at(j);//->topLevelItem();
            nID = pItem->data(GROUP_TYPE_KEY).toInt(); //取控件的Key号
            sList->clear();
            slist.clear();
            switch(nID)
            {
                case GROUP_TYPE_HISDATAALARM: //历史数据显示器
                    {
                        slist = pItem->data(GROUP_DATALIST_KEY).toStringList(); //取出每个item的所有数据
                        for(k = 0; k < slist.size();k++)
                            sList->append(slist.at(k));

                        nOldNum = sList->at(99).toInt(); //37
                      //  if(nNewNum != nOldNum)//长度没有改变的时候也要刷新 因为名称会改变
                        //Change by Dylan 2012-3-13
                        {
                            sList->replace(99,QString("%1").arg(nNewNum)); //37
                            int val = nNewNum - nOldNum;
                            if(val < 0) //配方数减少
                            {
                                for(k = 0; k < -val;k++)
                                    sList->removeLast();
                            }
                            else if(val > 0) //配方数增加
                            {
                                for(k = 0; k < val;k++)
                                    sList->append("1");
                            }
                            QDrawGraphics *pDraw = new QDrawGraphics;
                            pNewItem = pDraw->drawHistroyDataDisplayItem(sList);  //重绘配方显示器
                            pNewItem->setData(GROUP_TYPE_KEY,QVariant(GROUP_TYPE_HISDATAALARM));
                            pNewItem->setData(GROUP_DATALIST_KEY,*sList);
                            if(pDraw)
                            {
                                delete pDraw;
                                pDraw = NULL;
                            }
                            pwnd->OnDoubleClik(pItem,pNewItem);
                        } //end if
                    } //end case
                    break;
            } //end switch
        } //end second for
    } //end first for
     pwnd->nActiveSheetIndex = nsheet ; //reset active sheet page
     pwnd->pView->setScene(pwnd->pSceneSheet[nsheet]);
}
Ejemplo n.º 22
0
bool
MainWindow::parseCcliveHostsOutput() {
    hosts.clear();

    QString path = prefs->ccliveEdit->text();

    if (path.isEmpty()) {

        QMessageBox::information(
            this,
            QCoreApplication::applicationName(),
            tr("abby requires `clive' or `cclive'. "
                "Please define path to either executable.")
        );

        onPreferences();

        return false;
    }

    QProcess proc;
    proc.setEnvironment(QStringList() << "CCLIVE_NO_CONFIG=1");
    proc.setProcessChannelMode(QProcess::MergedChannels);
    proc.start(path, QStringList() << "--hosts");

    format->resetHosts();

    if (!proc.waitForFinished()) {
        critCcliveProcessFailed(this, proc.errorString() );
        return false;
    }
    else {
        const QString output =
            QString::fromLocal8Bit( proc.readAll() );

        const int exitCode =
            proc.exitCode();

        if (exitCode == 0) {

            QStringList lst =
                output.split("\n", QString::SkipEmptyParts);

            lst.removeLast(); // The note line.

            const register _uint size = lst.size();
            for (register _uint i=0; i<size; ++i) {

                QString ln      = lst[i].remove("\r");
                QStringList tmp = ln.split("\t");

                if (!tmp[0].isEmpty() && !tmp[1].isEmpty())
                    hosts[tmp[0]] = tmp[1];
            }

            format->parseHosts(hosts);
        }
        else {
            critCcliveExitedWithError(this, exitCode, output);
            return false;
        }
    }

    return true;
}
Ejemplo n.º 23
0
int main(int argc, char *argv[]){

     // here the QT_program is created
     QApplication app(argc, argv);

     //Qt translations
     QTranslator qtTranslator;
     qtTranslator.load("qt_" + QLocale::system().name(),
       QLibraryInfo::location(QLibraryInfo::TranslationsPath));
     app.installTranslator(&qtTranslator);

     //My translations
     QTranslator translator;
     QString trDir = "/usr/share/qshutdown/translations/";
     translator.load(trDir + "qshutdown-" + QLocale::system().name());
     app.installTranslator(&translator);

     QTextStream myOutput(stdout);

     if(!QProcessEnvironment().isEmpty())
       shell = QProcess::systemEnvironment().filter("SHELL").first().remove("SHELL=");
     if(shell.isEmpty() && QFile("/bin/bash").exists())
       shell = "/bin/bash";
     else
       myOutput << "E: No shell found! Custom commands won't work!";

     QString infoStr = QString(QObject::tr("qshutdown will show itself 3 times as a warning "
       "if there are less than 70 seconds left.<br/><br/>This program uses qdbus to send a "
       "shutdown/reboot/suspend/hibernate request to either the gnome- or "
       "kde-session-manager, to HAL/ConsoleKit/DeviceKit/UPower and if none of these works, the "
       "command 'sudo shutdown' will be used (note that when sending the shutdown request to HAL or "
       "ConsoleKit, or the shutdown command is used, the Session will never be saved. If the "
       "shutdown command is used, the program will only be able to shutdown and reboot). So "
       "if nothing happens when the shutdown- or reboot-time is reached, it means that one "
       "lacks the rights for the shutdown command. In this case one can do the following:"
       "<br/><br/>Paste the following in a terminal:<pre>EDITOR=nano sudo -E visudo</pre>and "
       "add this line:<pre>* ALL = NOPASSWD:/sbin/shutdown</pre>whereas * replaces the "
       "user name or %group name.<br/><br/>The maximum Number of countdown_minutes is "
       "1440 (24 hours).<br/>The configuration file (and logfile) is located at "
       "<i>~/.qshutdown/</i> (under Linux/Unix).<br/><br/><b>For admins:</b><br/>If you want "
       "qshutdown to run with \"parental lock\" for every user, you can do "
       "\"sudo cp /usr/share/qshutdown/autostart/99qshutdown /etc/X11/Xsession.d/\" "
       "and set the option Lock_all in /root/.qshutdown/qshutdown.conf to true. Note that "
       "qshutdown has to start once to generate the qshutdown.conf. Furthermore there is a "
       "need to add the following line to the sudoers (as above):"
       "<pre>* ALL = NOPASSWD:/usr/bin/qshutdown</pre><br/>If you should ever forget "
       "your set password, just remove the whole line starting with \"Password\" manually from "
       "the qshutdown.conf.<br/><br/><b>Hints on usage:</b><br/>If you want qshutdown to stop "
       "\"bugging\" you, just remove the hook from "
       "\"warnings on?\".<br/><br/><b>Hotkeys:</b><table border=\"1\"><tr><td>Ctrl+I</td><td>(this)"
       " information window</td></tr><tr><td>Ctrl+Q</td><td>Quit</td></tr><tr><td>Ctrl+P</td>"
       "<td>Preferences</td></tr><tr><td>Ctrl+L</td><td>write the run time once into the logfile (works "
       "only if qshutdown quits. To make it permanent set it in the preferences.)</td></tr><tr>"
       "<td>Ctrl+S</td><td>set to shutdown</td></tr><tr><td>Ctrl+R</td><td>set to restart</td></tr>"
       "<tr><td>Ctrl+U</td><td>set to suspend to RAM</td></tr><tr><td>Ctrl+H</td><td>set to hibernate"
       "</td></tr><tr><td>Ctrl+E</td><td>stop countdown (only if the countdown has started and the admin "
       "didn't restrict the access)</td></tr><tr><td>Shift+E</td><td>to edit the configuration file (for "
       "this a password is necessary. If you are a user, you can set an \"empty password\" (leave the "
       "password field empty)).</td></tr></table>"));
     QTextDocumentFragment infoDoc;
     infoDoc = QTextDocumentFragment::fromHtml(infoStr);
     QString info = infoDoc.toPlainText();

     //Get the arguments passed from the terminal
     QStringList args = QApplication::arguments();
     args.removeFirst(); //this is just the program
     for(int i=1; i<args.size();args.removeLast());
     if(!args.empty()){
       QString arg = args[0];
       if(arg[0] == '-'){
         if(arg[1] == 'h' || arg == "--help")
           myOutput << "\nqshutdown [ options ... ]\n\nOptions are:\n\t-h "
                    << "or --help\tPrints this message.\n\t-i\t\tPrints "
                    << "information.\n\t-v\t\tPrints all errors and warnings.\n"
                    << "\t-s or --start\tStarts the countdown for the set time."
                    << endl;
         if(arg[1] == 'i')
           myOutput << info << endl;
       }
       if(arg != "-h" && arg != "--help" && arg != "-i"
        && !((arg[0] == '-' && (arg.contains("s") || arg.contains("v")))
          || args.contains("--start")))
         myOutput << "Wrong options! Try qshutdown -h" << endl;
       if(arg.contains("-") && arg.contains("-v"))
         verbose = true;
     }

     if(!args.empty() && !((args[0][0] == '-' && (args[0].contains("v")
       || args[0].contains("s"))) || args.contains("--start")))
       exit(0);

     Gui window; //Create the main widget

     #ifndef Q_OS_WIN32
       QDBusConnection::sessionBus().registerObject(OBJECT_NAME, &window,
         QDBusConnection::ExportScriptableSlots);
       if(QDBusConnection::sessionBus().registerService(SERVICE_NAME)){
         //if possible register qshutdown as a service in the session bus
     #endif //Q_OS_WIN32
         window.information = infoStr;
         window.loadSettings();
         window.center();
         window.show();
         app.setQuitOnLastWindowClosed(false);
         if(!args.empty() && ((args[0][0] == '-' && args[0].contains("s"))
           || args.contains("--start")))
           window.set();

         return app.exec();

     #ifndef Q_OS_WIN32
       }
       else{ //if registering qshutdown fails (also because it is already
             // registered, show window
         myOutput << "\nqshutdown is already running!\n" << endl;
         QDBusInterface iface(SERVICE_NAME, OBJECT_NAME, "",
           QDBusConnection::sessionBus(), &window);
         QDBusMessage response = iface.call("showRunningProgram");
         if(response.type() == QDBusMessage::ErrorMessage){
           if(verbose)
             myOutput << "QDBusInterface " << iface.interface() << " seems to be valid... -> "
                      << (iface.isValid()? "true":"false") << "\nW: " << response.errorName()
                      << ": " << response.errorMessage() << "\nYou can ignore this.\n\n" << endl;
           QDBusInterface iface2(SERVICE_NAME, OBJECT_NAME, "local.Gui",
             QDBusConnection::sessionBus(), &window);
           QDBusMessage response2 = iface2.call("showRunningProgram");
           if(response2.type() == QDBusMessage::ErrorMessage)
             myOutput << "QDBusInterface " << iface2.interface() << " seems to be valid... -> "
                      << (iface2.isValid()? "true":"false") << "\nW: " << response2.errorName()
                      << ": " << response2.errorMessage() << "\nPlease report this." << endl;
           else if(!args.empty() && ((args[0][0] == '-' && args[0].contains("s"))
             || args.contains("--start")))
             iface2.call("set");
         }
         else if(!args.empty() && ((args[0][0] == '-' && args[0].contains("s"))
           || args.contains("--start")))
           iface.call("set");
       }
       if(!args.empty() && ((args[0][0] == '-' && args[0].contains("s"))
           || args.contains("--start")))
           myOutput << "Starting countdown!\n";
     #endif //Q_OS_WIN32
}
Ejemplo n.º 24
0
// Return the call tip for a function.
QStringList QsciAPIs::callTips(const QStringList &context, int commas,
        QsciScintilla::CallTipsStyle style, QList<int> &shifts)
{
    QString path;
    QStringList new_context = positionOrigin(context, path);
    QStringList wseps = lexer()->autoCompletionWordSeparators();
    QStringList cts;

    if (origin_len > 0)
    {
        // The path should have a trailing word separator.
        const QString &wsep = wseps.first();
        path.chop(wsep.length());

        QStringList::const_iterator it = origin;
        QString prev;

        // Work out the length of the context.
        QStringList strip = path.split(wsep);
        strip.removeLast();
        int ctstart = strip.join(wsep).length();

        if (ctstart)
            ctstart += wsep.length();

        int shift;

        if (style == QsciScintilla::CallTipsContext)
        {
            shift = ctstart;
            ctstart = 0;
        }
        else
            shift = 0;

        // Make sure we only look at the functions we are interested in.
        path.append('(');

        while (it != prep->raw_apis.end() && (*it).startsWith(path))
        {
            QString w = (*it).mid(ctstart);

            if (w != prev && enoughCommas(w, commas))
            {
                shifts << shift;
                cts << w;
                prev = w;
            }

            ++it;
        }
    }
    else
    {
        const QString &fname = new_context[new_context.count() - 2];

        // Find everywhere the function name appears in the APIs.
        const WordIndexList *wil = wordIndexOf(fname);

        if (wil)
            for (int i = 0; i < wil->count(); ++i)
            {
                const WordIndex &wi = (*wil)[i];
                QStringList awords = prep->apiWords(wi.first, wseps, true);

                // Check the word is the function name and not part of any
                // context.
                if (wi.second != awords.count() - 1)
                    continue;

                const QString &api = prep->raw_apis[wi.first];

                int tail = api.indexOf('(');

                if (tail < 0)
                    continue;

                if (!enoughCommas(api, commas))
                    continue;

                if (style == QsciScintilla::CallTipsNoContext)
                {
                    shifts << 0;
                    cts << (fname + api.mid(tail));
                }
                else
                {
                    shifts << tail - fname.length();

                    // Remove any image type.
                    int im_type = api.indexOf('?');

                    if (im_type <= 0)
                        cts << api;
                    else
                        cts << (api.left(im_type - 1) + api.mid(tail));
                }
            }
    }

    return cts;
}
Ejemplo n.º 25
0
void TestNetwork(const QString &filename, bool printNetwork, bool pvlInput) {
  cerr << "Reading: " << filename << "...\n\n";
  FileName networkFileName(filename);

  LatestControlNetFile * test = NULL;
  LatestControlNetFile * test2 = NULL;
  
  try {

    // If we're reading in a Pvl file, this will call the Pvl update cycle, then
    //   convert to binary, then convert back to Pvl.
    // If we're reading in a binary file, this will call the binary read, then
    //   convert to Pvl, then update, then convert to binary, and back to pvl.
    //   The reason for the intermediate Pvl is described in
    //   ControlNetVersioner.h.
    cerr << "Read network..." << endl;
    test = ControlNetVersioner::Read(networkFileName);

    if(printNetwork) {
      cerr << "Converted directly to Pvl:" << endl;
      Pvl pvlVersion(test->toPvl());
      cerr << pvlVersion << endl;
      pvlVersion.write("./tmp.pvl");
    }

    // Test the latest binary read/write and Pvl conversion
    cerr << "Write the network and re-read it..." << endl;
    ControlNetVersioner::Write(FileName("./tmp"), *test);
          
    try {
      test2 = ControlNetVersioner::Read(FileName("./tmp"));
    }
    catch(IException &e) {
      remove("./tmp");
      throw;
    }

    cerr << "After reading and writing to a binary form does Pvl match?"
         << endl;
    if(printNetwork) {
      Pvl pvlVersion2(test2->toPvl());
      pvlVersion2.write("./tmp2.pvl");
      if(system("cmp ./tmp.pvl ./tmp2.pvl")) {
        cerr << "Reading/Writing results in Pvl differences!" << endl;
      }
      else {
        cerr << "Conversion to Pvl stays consistent" << endl;
      }
    }

    ControlNetVersioner::Write(FileName("./tmp2"), *test2);
    if(system("cmp ./tmp ./tmp2")) {
      cerr << "Reading/Writing control network results in binary differences!"
           << endl;
    }
    else {
      cerr << "Reading/Writing control network is consistent" << endl;
    }

    if (pvlInput) {

      LatestControlNetFile * cNet2 = NULL;
      
      cerr << "Check conversions between the binary format and the pvl format." << endl;
      /*
       * When the input is a pvl, ./tmp is the binary form of the initial input. (pvl1->bin1)
       * Furthermore, ./tmp.pvl is the first binary conversion reverted back to pvl.
       * (pvl1->bin1->pvl2)
       * cNet1 is the binary version of the second pvl. (pvl1->bin1->pvl2->bin2)
       *
       *                                  a       b       c
       *                            (pvl1 -> bin1 -> pvl2 -> bin2)
       * 
       * if (pvl1 != pvl2)
       *        a or b is broken but we don't know which yet
       *        if(bin1 != bin2)
       *                bin->pvl is broken (b) because the error happened after bin1 was created.
       *        else
       *                pvl-bin is broken (a/c) because the error happened before bin1 was created
       *                        and was propagated to bin2 via c.
       * else
       *        The conversions are up to date and correct because neither a nor b broke.
       *
       * 
       */
      cNet2 = ControlNetVersioner::Read(FileName("./tmp.pvl"));

      ControlNetVersioner::Write(FileName("./tmpCNet2"), *cNet2);

      //if there are differences between the pvls.
      QString cmd = "diff -EbB --suppress-common-lines " + filename + " ./tmp.pvl";
      if(system(cmd.toStdString().c_str())) {
        
        //if the binary files are different.
        if(system("diff -EbB --suppress-common-lines ./tmp ./tmpCNet2")){
          cerr << "The conversion from binary to pvl is incorrect." << endl;
        }
        else {
          cerr << "The conversion from pvl to binary is incorrect." << endl;
        }
      }
      else {
        cerr << "The conversion methods for pvl->bin and bin->pvl are correct." << endl;
      }

      remove("./tmpCNet2");
      delete cNet2;
      cNet2 = NULL;
    }

    remove("./tmp");
    remove("./tmp2");

    if(printNetwork) {
      remove("./tmp.pvl");
      remove("./tmp2.pvl");
    }
  }
  catch(IException &e) {
    QStringList errors = e.toString().split("\n");
    errors.removeLast();
    cerr << errors.join("\n") << endl;
  }

  if(test) {
    delete test;
    test = NULL;
  }

  if(test2) {
    delete test2;
    test2 = NULL;
  }

  cerr << endl;
}
Ejemplo n.º 26
0
/*!
    Creates a new main window and initializes the application.
*/
MvdMainWindow::MvdMainWindow(QWidget *parent) :
    QMainWindow(parent),
    d(new Private(this))
{
    Q_ASSERT_X(!Movida::MainWindow, "MvdMainWindow",
        "Internal Error. Only a single instance of MvdMainWindow can be created.");
    Movida::MainWindow = this;

    MVD_WINDOW_ICON

    // Set some GUI related constants
    QHash<QString, QVariant> parameters;
    parameters.insert("movida/maximum-recent-files", 10);
    parameters.insert("movida/default-recent-files", 5);
    parameters.insert("movida/max-menu-items", 10);
    parameters.insert("movida/message-timeout-ms", 5 * 1000);
    parameters.insert("movida/poster-default-width", 70);
    parameters.insert("movida/poster-aspect-ratio", qreal(0.7));
    parameters.insert("movida/imdb-movie-url", "http://akas.imdb.com/title/tt%1");
    parameters.insert("movida/mime/movie", "application/movida-movie");
    parameters.insert("movida/mime/movie-attributes", "application/movida-movie-attributes");
    parameters.insert("movida/mime/movie-filter", "application/movida-movie-filter");
    parameters.insert("movida/d&d/max-pixmaps", 5);
    parameters.insert("movida/d&d/max-values", 8);
    Movida::core().registerParameters(parameters);

    Movida::core().loadStatus();
    MvdSettings &p = Movida::settings();

    // Set default settings
    QByteArray defaultFilterAttributes(6, '\0');
    defaultFilterAttributes[0] = (const char) Movida::TitleAttribute;
    defaultFilterAttributes[1] = (const char) Movida::OriginalTitleAttribute;
    defaultFilterAttributes[2] = (const char) Movida::DirectorsAttribute;
    defaultFilterAttributes[3] = (const char) Movida::CastAttribute;
    defaultFilterAttributes[4] = (const char) Movida::YearAttribute;
    defaultFilterAttributes[5] = (const char) Movida::TagsAttribute;

    p.setDefaultValue("movida/maximum-recent-files", 5);
    p.setDefaultValue("movida/confirm-delete-movie", true);
    p.setDefaultValue("movida/directories/remember", true);
    p.setDefaultValue("movida/movie-list/initials", false);    //! \todo: rename to movie-view
    p.setDefaultValue("movida/use-history", true);
    p.setDefaultValue("movida/max-history-items", 20);
    p.setDefaultValue("movida/quick-filter/case-sensitive", false);
    p.setDefaultValue("movida/quick-filter/attributes", defaultFilterAttributes);
    p.setDefaultValue("movida/quick-filter/sort-attribute", (int) Movida::TitleAttribute);
    p.setDefaultValue("movida/quick-filter/sort-order", (int) Qt::AscendingOrder);
    p.setDefaultValue("movida/effects/bars", true);
    p.setDefaultValue("movida/view-mode", "smart");
    p.setDefaultValue("movida/smart-view/item-size", "medium");
    p.setDefaultValue("movida/movie-view/wheel-up-magnifies", true);

    // Setup UI and collection
    d->mMovieModel = new MvdCollectionModel(this);
    d->mSharedDataModel = new MvdSharedDataModel(Movida::PersonRole, this);

    d->setupUi();
    d->setupConnections();

    // Initialize core library && load user settings
    QStringList recentFiles = p.value("movida/recent-files").toStringList();
    int max = p.value("movida/maximum-recent-files").toInt();
    int recentFilesCount = recentFiles.size();
    while (recentFiles.size() > max)
        recentFiles.removeLast();
    if (recentFilesCount != recentFiles.size())
        p.setValue("movida/recent-files", recentFiles);

    d->mA_FileOpenLast->setDisabled(recentFiles.isEmpty());

    QString viewMode = p.value("movida/view-mode").toString();
    if (viewMode == "smart")
        d->mA_ViewModeSmart->activate(QAction::Trigger);
    else
        d->mA_ViewModeTree->activate(QAction::Trigger);

    viewMode = p.value("movida/smart-view/item-size").toString();
    if (viewMode == "small")
        zoomOut();
    else if (viewMode == "large")
        zoomIn();

    QByteArray ba = p.value("movida/appearance/main-window-state").toByteArray();
    if (!ba.isEmpty())
        restoreState(ba);

    resize(p.value("movida/appearance/main-window-size", QSize(640, 480)).toSize());
    move(p.value("movida/appearance/main-window-pos", QPoint(200, 100)).toPoint());

    bool bl;

    bl = p.value("movida/appearance/start-maximized").toBool();
    if (bl)
        setWindowState(Qt::WindowMaximized);

    d->mFilterWidget->setCaseSensitivity(p.value("movida/quick-filter/case-sensitive").toBool()
        ? Qt::CaseSensitive : Qt::CaseInsensitive);
    d->mFilterModel->setQuickFilterAttributes(p.value("movida/quick-filter/attributes").toByteArray());

    d->mFilterWidget->setBooleanOperator(p.value("movida/quick-filter/use-or-operator").toBool()
        ? Movida::OrOperator : Movida::AndOperator);

    // a new empty collection is always open at startup
    d->mA_FileNew->setDisabled(true);
    d->mA_FileSave->setDisabled(true);
    d->mA_FileSaveAs->setDisabled(true);

    d->movieViewSelectionChanged();
    d->mTreeView->sortByColumn((int)Movida::TitleAttribute, Qt::AscendingOrder);
    d->mSharedDataModel->sort(0, Qt::AscendingOrder);
    d->currentViewChanged();

    setAcceptDrops(true);

    d->registerMessageHandler();

    // Load plugins
    d->loadPlugins();
    d->updateCaption();

    // Connect the collection to the views and main window
    d->collectionCreated(core().currentCollection());

    statusBar()->showMessage(tr("Movida is ready!"));
    iLog() << "Movida is ready!";
}
Ejemplo n.º 27
0
// return the absolute or relative path to write it to the project file
QString QgsProject::writePath( QString src ) const
{
  if ( readBoolEntry( "Paths", "/Absolute", false ) || src.isEmpty() )
  {
    return src;
  }

  QString srcPath = src;
  QString projPath = fileName();

  if ( projPath.isEmpty() )
  {
    return src;
  }

#if defined( Q_OS_WIN )
  const Qt::CaseSensitivity cs = Qt::CaseInsensitive;

  srcPath.replace( "\\", "/" );

  if ( srcPath.startsWith( "//" ) )
  {
    // keep UNC prefix
    srcPath = "\\\\" + srcPath.mid( 2 );
  }

  projPath.replace( "\\", "/" );
  if ( projPath.startsWith( "//" ) )
  {
    // keep UNC prefix
    projPath = "\\\\" + projPath.mid( 2 );
  }
#else
  const Qt::CaseSensitivity cs = Qt::CaseSensitive;
#endif

  QStringList projElems = projPath.split( "/", QString::SkipEmptyParts );
  QStringList srcElems = srcPath.split( "/", QString::SkipEmptyParts );

  // remove project file element
  projElems.removeLast();

  projElems.removeAll( "." );
  srcElems.removeAll( "." );

  // remove common part
  int n = 0;
  while ( srcElems.size() > 0 &&
          projElems.size() > 0 &&
          srcElems[0].compare( projElems[0], cs ) == 0 )
  {
    srcElems.removeFirst();
    projElems.removeFirst();
    n++;
  }

  if ( n == 0 )
  {
    // no common parts; might not even by a file
    return src;
  }

  if ( projElems.size() > 0 )
  {
    // go up to the common directory
    for ( int i = 0; i < projElems.size(); i++ )
    {
      srcElems.insert( 0, ".." );
    }
  }
  else
  {
    // let it start with . nevertheless,
    // so relative path always start with either ./ or ../
    srcElems.insert( 0, "." );
  }

  return srcElems.join( "/" );
}
Ejemplo n.º 28
0
void CashControlModel::setDates(QString dataInicial, QString dataFinal)
{
    // convert dates from dd/MM/yyyy to yyyyMMdd

    dataInicial = QDate::fromString(dataInicial, "dd/MM/yyyy").toString("yyyyMMdd");
    dataFinal = QDate::fromString(dataFinal, "dd/MM/yyyy").toString("yyyyMMdd");

    QSqlDatabase db = QSqlDatabase::database(DB_CONNECTION_NAME);

    QSqlQuery query(db);

    query.prepare("SELECT Data,Grams,Preu FROM cannabis WHERE Data >= :mydatainicial AND Data <= :mydatafinal ORDER BY Data");
    query.bindValue(":mydatainicial", dataInicial);
    query.bindValue(":mydatafinal", dataFinal);

    if (!query.exec())
    {
        qDebug() << "Can't execute query!";
        qDebug() << query.lastError().text();
        return;
    }

    QMap <QString, QStringList> myDataTmp;

    while (query.next())
    {
        QStringList slist;

        QString data(query.value(0).toString());

        QString grams(query.value(1).toString());
        QString preu(query.value(2).toString());

        // comprovem que no hi hagi ja alguna entrada aquesta data
        QStringList oldslist(myDataTmp.value(data, QStringList()));

        if (!oldslist.isEmpty())
        {
            // recollim els valors que ja hi havien i els afegim als nous
            // per anar acumulant el què s'ha consumit a la mateixa data
            grams = QString::number(grams.toDouble() + oldslist.at(1).toDouble());
            preu = QString::number(preu.toDouble() + oldslist.at(2).toDouble());
        }

        slist << QDate::fromString(data, "yyyyMMdd").toString("dd/MM/yyyy");
        slist << grams;
        slist << preu;

        slist << "0";  // Diners

        // el total serà el mateix (de moment)
        slist << preu;

        // si ja existeix el sobreescriu, o sigui que no ens n'hem de preocupar
        myDataTmp.insert(data, slist);
    }

    query.clear();
    query.prepare("SELECT Data,Diners FROM altres WHERE Data >= :mydatainicial AND Data <= :mydatafinal ORDER BY Data");
    query.bindValue(":mydatainicial", dataInicial);
    query.bindValue(":mydatafinal", dataFinal);

    if (!query.exec())
    {
        qDebug() << "Can't execute query!";
        qDebug() << query.lastError().text();
        return;
    }

    while (query.next())
    {
        QStringList slist;

        QString data(query.value(0).toString());

        slist = myDataTmp.value(data, QStringList());

        if (slist.isEmpty())
        {
            slist << QDate::fromString(data, "yyyyMMdd").toString("dd/MM/yyyy");
            slist << "0";
            slist << "0";
            slist << query.value(1).toString();
            slist << query.value(1).toString(); // el total serà el mateix :p
        }
        else
        {
            // Tenim els tres camps, hem de calcular la suma

            slist.removeLast(); // treiem el total, ara no és correcte

            // agafem el valor de diners antic (si no hi havia cap agafarà el zero que hem posat abans).
            QString oldDiners(slist.last());

            // treiem el zero que havíem afegit abans per omplir (o el valor antic si ja teníem info d'aquesta data).
            slist.removeLast();

            slist << QString::number(oldDiners.toDouble() + query.value(1).toDouble());

            // calculem el total

            slist << QString::number(slist.at(2).toDouble() + slist.at(3).toDouble());
        }

        myDataTmp.insert(data, slist);
    }

    layoutAboutToBeChanged();

    myData.clear();

    int row = 0;

    foreach (QStringList slist, myDataTmp)
    {
        myData.insert(row++, slist);
    }
Ejemplo n.º 29
0
void PhoneInfoWidget::showPhoneInfo()
{
        QString data,tmp="1";
        QStringList list;
        QProcess *proces=new QProcess;
        proces->start("\""+sdk+"\""+"adb shell getprop");
        while (!tmp.isEmpty())
        {
            proces->waitForReadyRead(-1);
            tmp=proces->readLine();
            list.append(tmp);
        }

        for (int i=0;i<list.length();i++)
        {
            qDebug()<<"Getprop - "<<list.at(i);
            if (list.at(i).contains("[ro.product.model]"))
            {
                tmp=list.at(i);
                tmp.remove("[ro.product.model]: ");
                tmp.remove("[");
                tmp.remove("]");
                ui->lineEditModel->setText(tmp);
            }
            else if (list.at(i).contains("[ro.baseband]"))
            {
                tmp=list.at(i);
                tmp.remove("[ro.baseband]: ");
                tmp.remove("[");
                tmp.remove("]");
                ui->lineEditRadio->setText(tmp);
            }
            else if (list.at(i).contains("[ro.bootloader]"))
            {
                tmp=list.at(i);
                tmp.remove("[ro.bootloader]: ");
                tmp.remove("[");
                tmp.remove("]");
                ui->lineEditBootloader->setText(tmp);
            }
            else if (list.at(i).contains("[ro.build.display.id]"))
            {
                tmp=list.at(i);
                tmp.remove("[ro.build.display.id]: ");
                tmp.remove("[");
                tmp.remove("]");
                ui->lineEditRom->setText(tmp);
            }
            else if (list.at(i).contains("[gsm.operator.alpha]"))
            {
                tmp=list.at(i);
                tmp.remove("[gsm.operator.alpha]: ");
                tmp.remove("[");
                tmp.remove("]");
                ui->lineEditOperator->setText(tmp);
            }
        }
//        ui->lineEditSerialNumber->setText(this->phone->serialNumber);



        proces->start("\""+sdk+"\""+"adb shell busybox cat /sys/class/power_supply/battery/capacity");
        proces->waitForReadyRead(-1);
        tmp=proces->readLine();
        ui->progressBarBatteryLevel->setValue(tmp.toInt());
        proces->close();
        //get sd-ext folder
        QString sdFolder;
//        QStringList lines, split;
//        sdFolder.clear();
//        proces->start("\"" + this->sdk + "\"adb shell mount");
//        proces->waitForFinished(-1);
//        tmp = proces->readAll();
//        qDebug()<<"Get phone info mount - "<<tmp;
//        if (tmp.contains("ext"))
//        {
//            lines = tmp.split("\n", QString::SkipEmptyParts);
//            while (lines.size() > 0)
//            {
//                tmp = lines.takeFirst();
//                if (tmp.contains("ext"))
//                {
//                    split = tmp.split(QRegExp("\\s+"),QString::SkipEmptyParts);
//                    if (split.size() > 2)
//                    {
//                        sdFolder = split.at(2);
//                        if (sdFolder.endsWith("/",Qt::CaseInsensitive))
//                            sdFolder.remove(sdFolder.length() - 1, 1);
//                    }
//                }
//            }
//        }
        QSettings settings;
        sdFolder = settings.value("sdFolder").toString();
        if (!sdFolder.isEmpty() && !sdFolder.contains(QRegExp("<.*>")))
        {
            if (sdFolder.endsWith("/",Qt::CaseInsensitive))
                sdFolder.chop(1);
        }
        proces->start("\""+sdk+"\""+"adb shell busybox df");
        tmp.clear();

        while (true)
        {
            proces->waitForReadyRead(-1);
            data=proces->readLine();
            if (data.isEmpty())
                break;
            tmp.append(data);
        }
        if (!tmp.contains(sdFolder) || sdFolder.isEmpty())
        {
            ui->progressBarExt->setDisabled(true);
            ui->labelExtAvailable->setDisabled(true);
            ui->labelExt->setDisabled(true);
            ui->labelExtSize->setDisabled(true);
            ui->labelExtUsed->setDisabled(true);
            ui->lineEditExtAvailable->setDisabled(true);
            ui->lineEditExtSize->setDisabled(true);
            ui->lineEditExtUsed->setDisabled(true);
        }
        list=tmp.split("\n");
        QStringList parts;
        QString used,available;
        while (list.count()>0)
        {
            tmp=list.takeFirst();
            qDebug()<<"df - "<<tmp;
            parts=tmp.split(QRegExp("\\s+"));
            if (parts.size()>2)
            {
                parts.removeLast();
                tmp=parts.takeLast();
                parts.removeLast();
                available=parts.takeLast();
                used=parts.takeLast();
            }

            if (tmp=="/data")
            {
                ui->lineEditDataAvailable->setText(PhoneInfoWidget::humanReadableSize(available+"000"));
                ui->lineEditDataUsed->setText(PhoneInfoWidget::humanReadableSize(used+"000"));
                ui->lineEditDataSize->setText(PhoneInfoWidget::humanReadableSize(QString::number(used.toUInt()+available.toUInt())+"000"));
                ui->progressBarData->setMaximum(used.toUInt()+available.toUInt());
                ui->progressBarData->setValue(used.toUInt());
            }
            else if (tmp=="/system")
            {
                ui->lineEditSystemAvailable->setText(PhoneInfoWidget::humanReadableSize(available+"000"));
                ui->lineEditSystemUsed->setText(PhoneInfoWidget::humanReadableSize(used+"000"));
                ui->lineEditSystemSize->setText(PhoneInfoWidget::humanReadableSize(QString::number(used.toUInt()+available.toUInt())+"000"));
                ui->progressBarSystem->setMaximum(used.toUInt()+available.toUInt());
                ui->progressBarSystem->setValue(used.toUInt());
            }
            else if (tmp.contains(sdFolder) && !sdFolder.isEmpty())
            {
                ui->lineEditExtAvailable->setText(PhoneInfoWidget::humanReadableSize(available+"000"));
                ui->lineEditExtUsed->setText(PhoneInfoWidget::humanReadableSize(used+"000"));
                ui->lineEditExtSize->setText(PhoneInfoWidget::humanReadableSize(QString::number(used.toUInt()+available.toUInt())+"000"));
                ui->progressBarExt->setMaximum(used.toUInt()+available.toUInt());
                ui->progressBarExt->setValue(used.toUInt());
            }
            else if (tmp.contains("/sdcard"))
            {
                ui->lineEditSdcardAvailable->setText(PhoneInfoWidget::humanReadableSize(available+"000"));
                ui->lineEditSdcardUsed->setText(PhoneInfoWidget::humanReadableSize(used+"000"));
                ui->lineEditSdcardSize->setText(PhoneInfoWidget::humanReadableSize(QString::number(used.toUInt()+available.toUInt())+"000"));
                ui->progressBarSdcard->setMaximum(used.toUInt()+available.toUInt());
                ui->progressBarSdcard->setValue(used.toUInt());
            }
        }
//        int i=0;
        //df
}
Ejemplo n.º 30
0
bool FilterIO::readFilter(QString path, FilterData &filter)
{
    //Open .txt file
    if(!path.contains(".txt"))
        return false;

    QFile file(path);
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug()<<"Error opening filter txt file for reading";
        return false;
    }

    //Start reading from file
    QTextStream in(&file);
    QVector<double> coefficientsTemp;

    while(!in.atEnd())
    {
        QString line = in.readLine();

        QStringList fields = line.split(QRegExp("\\s+"));

        //Delete last element if it is a blank character
        if(fields.at(fields.size()-1) == "")
            fields.removeLast();

        if(line.contains("#")) //Filter meta information commented areas in file
        {
            //Read filter sFreq
            if(line.contains("sFreq") && fields.size()==2)
                filter.m_sFreq = fields.at(1).toDouble();

            //Read filter name
            if(line.contains("name")) {
                filter.m_sName.clear();
                for(int i=1; i<fields.size(); i++)
                    filter.m_sName.append(fields.at(i));
            }

            //Read the filter order
            if(line.contains("order") && fields.size()==2)
                filter.m_iFilterOrder = fields.at(1).toInt();

            //Read the filter type
            if(line.contains("type") && fields.size()==2)
                filter.m_Type = FilterData::getFilterTypeForString(fields.at(1));

            //Read the filter LPFreq
            if(line.contains("LPFreq") && fields.size()==2)
                filter.m_dLowpassFreq = fields.at(1).toDouble();

            //Read the filter HPFreq
            if(line.contains("HPFreq") && fields.size()==2)
                filter.m_dHighpassFreq = fields.at(1).toDouble();

            //Read the filter CenterFreq
            if(line.contains("CenterFreq") && fields.size()==2)
                filter.m_dCenterFreq = fields.at(1).toDouble();

            //Read the filter DesignMethod
            if(line.contains("DesignMethod") && fields.size()==2)
                filter.m_designMethod = FilterData::getDesignMethodForString(fields.at(1));

        } else // Read filter coefficients
            coefficientsTemp.push_back(fields.join("").toDouble());
    }
    // Check if reading was successful and correct
    if(filter.m_iFilterOrder != coefficientsTemp.size())
        filter.m_iFilterOrder = coefficientsTemp.size();

//    if(filter.m_sFreq)

//    if(filter.m_sName)

//    if(filter.m_Type)

//    if(filter.m_dLowpassFreq)

//    if(filter.m_dHighFreq)

//    if(filter.m_designMethod)

    filter.m_dCoeffA = RowVectorXd::Zero(coefficientsTemp.size());
    for(int i=0; i<filter.m_dCoeffA.cols(); i++)
        filter.m_dCoeffA(i) = coefficientsTemp.at(i);

    //Compute fft of filtercoeeficients
    filter.fftTransformCoeffs();

    file.close();

    return true;
}