Example #1
0
bool FileServerHandler::HandleDeleteFile(SocketHandler *socket,
                                QString filename, QString storagegroup)
{
    StorageGroup sgroup(storagegroup, "", false);
    QStringList res;

    if ((filename.isEmpty()) ||
        (filename.contains("/../")) ||
        (filename.startsWith("../")))
    {
        LOG(VB_GENERAL, LOG_ERR,
            QString("ERROR deleting file, filename '%1' fails sanity checks")
                .arg(filename));
        if (socket)
        {
            res << "0";
            socket->SendStringList(res);
            return true;
        }
        return false;
    }

    QString fullfile = sgroup.FindFile(filename);

    if (fullfile.isEmpty())
    {
        LOG(VB_GENERAL, LOG_ERR,
            QString("Unable to find %1 in HandleDeleteFile()") .arg(filename));
        if (socket)
        {
            res << "0";
            socket->SendStringList(res);
            return true;
        }
        return false;
    }

    QFile checkFile(fullfile);
    if (checkFile.exists())
    {
        if (socket)
        {
            res << "1";
            socket->SendStringList(res);
        }
        RunDeleteThread();
        deletethread->AddFile(fullfile);
    }
    else
    {
        LOG(VB_GENERAL, LOG_ERR, QString("Error deleting file: '%1'")
                        .arg(fullfile));
        if (socket)
        {
            res << "0";
            socket->SendStringList(res);
        }
    }

    return true;
}
Example #2
0
void QgsLabel::renderLabel( QPainter * painter, const QgsRectangle& viewExtent,
                            const QgsCoordinateTransform* coordinateTransform,
                            const QgsMapToPixel *transform,
                            QgsFeature &feature, bool selected, QgsLabelAttributes *classAttributes,
                            double sizeScale, double rasterScaleFactor )
{
  QPen pen;
  QFont font;
  QString value;
  QString text;

  /* Calc scale (not nice) */
  QgsPoint point;
  point = transform->transform( 0, 0 );
  double x1 = point.x();
  point = transform->transform( 1000, 0 );
  double x2 = point.x();
  double scale = ( x2 - x1 ) * 0.001;

  /* Text */
  value = fieldValue( Text, feature );
  if ( value.isEmpty() )
  {
    text = mLabelAttributes->text();
  }
  else
  {
    text = value;
  }

  /* Font */
  value = fieldValue( Family, feature );
  if ( value.isEmpty() )
  {
    font.setFamily( mLabelAttributes->family() );
  }
  else
  {
    font.setFamily( value );
  }

  double size;
  value = fieldValue( Size, feature );
  if ( value.isEmpty() )
  {
    size =  mLabelAttributes->size();
  }
  else
  {
    size =  value.toDouble();
  }
  int sizeType;
  value = fieldValue( SizeType, feature );
  if ( value.isEmpty() )
    sizeType = mLabelAttributes->sizeType();
  else
  {
    value = value.toLower();
    if ( value.compare( "mapunits" ) == 0 )
      sizeType = QgsLabelAttributes::MapUnits;
    else
      sizeType = QgsLabelAttributes::PointUnits;
  }
  if ( sizeType == QgsLabelAttributes::MapUnits )
  {
    size *= scale;
  }
  else //point units
  {
    double sizeMM = size * 0.3527;
    size = sizeMM * sizeScale;
  }

  //Request font larger (multiplied by rasterScaleFactor) as a workaround for the Qt font bug
  //and scale the painter down by rasterScaleFactor when drawing the label
  size *= rasterScaleFactor;

  if (( int )size <= 0 )
    // skip too small labels
    return;

  font.setPixelSize( size );

  value = fieldValue( Color, feature );
  if ( value.isEmpty() )
  {
    pen.setColor( mLabelAttributes->color() );
  }
  else
  {
    pen.setColor( QColor( value ) );
  }

  value = fieldValue( Bold, feature );
  if ( value.isEmpty() )
  {
    font.setBold( mLabelAttributes->bold() );
  }
  else
  {
    font.setBold(( bool ) value.toInt() );
  }

  value = fieldValue( Italic, feature );
  if ( value.isEmpty() )
  {
    font.setItalic( mLabelAttributes->italic() );
  }
  else
  {
    font.setItalic(( bool ) value.toInt() );
  }

  value = fieldValue( Underline, feature );
  if ( value.isEmpty() )
  {
    font.setUnderline( mLabelAttributes->underline() );
  }
  else
  {
    font.setUnderline(( bool ) value.toInt() );
  }

  //
  QgsPoint overridePoint;
  bool useOverridePoint = false;
  value = fieldValue( XCoordinate, feature );
  if ( !value.isEmpty() )
  {
    overridePoint.setX( value.toDouble() );
    useOverridePoint = true;
  }
  value = fieldValue( YCoordinate, feature );
  if ( !value.isEmpty() )
  {
    overridePoint.setY( value.toDouble() );
    useOverridePoint = true;
  }

  /* Alignment */
  int alignment;
  QFontMetrics fm( font );
  int width, height;

  if ( mLabelAttributes->multilineEnabled() )
  {
    QStringList texts = text.split( "\n" );

    width = 0;
    for ( int i = 0; i < texts.size(); i++ )
    {
      int w = fm.width( texts[i] );
      if ( w > width )
        width = w;
    }

    height = fm.height() * texts.size();
  }
  else
  {
    width = fm.width( text );
    height = fm.height();
  }

  int dx = 0;
  int dy = 0;

  value = fieldValue( Alignment, feature );
  if ( value.isEmpty() )
  {
    alignment = mLabelAttributes->alignment();
  }
  else
  {
    value = value.toLower();

    alignment = 0;

    if ( value.contains( "left" ) )
      alignment |= Qt::AlignLeft;
    else if ( value.contains( "right" ) )
      alignment |= Qt::AlignRight;
    else
      alignment |= Qt::AlignHCenter;

    if ( value.contains( "bottom" ) )
      alignment |= Qt::AlignBottom;
    else if ( value.contains( "top" ) )
      alignment |= Qt::AlignTop;
    else
      alignment |= Qt::AlignVCenter;
  }

  if ( alignment & Qt::AlignLeft )
  {
    dx = 0;
  }
  else if ( alignment & Qt::AlignHCenter )
  {
    dx = -width / 2;
  }
  else if ( alignment & Qt::AlignRight )
  {
    dx = -width;
  }

  if ( alignment & Qt::AlignBottom )
  {
    dy = 0;
  }
  else if ( alignment & Qt::AlignVCenter )
  {
    dy = height / 2;
  }
  else if ( alignment & Qt::AlignTop )
  {
    dy = height;
  }

  // Offset
  double xoffset, yoffset;
  value = fieldValue( XOffset, feature );
  if ( value.isEmpty() )
  {
    xoffset = mLabelAttributes->xOffset();
  }
  else
  {
    xoffset = value.toDouble();
  }
  value = fieldValue( YOffset, feature );
  if ( value.isEmpty() )
  {
    yoffset = mLabelAttributes->yOffset();
  }
  else
  {
    yoffset = value.toDouble();
  }

  // recalc offset to pixels
  if ( mLabelAttributes->offsetType() == QgsLabelAttributes::MapUnits )
  {
    xoffset *= scale;
    yoffset *= scale;
  }
  else
  {
    xoffset = xoffset * 0.3527 * sizeScale;
    yoffset = yoffset * 0.3527 * sizeScale;
  }

  // Angle
  double ang;
  value = fieldValue( Angle, feature );
  if ( value.isEmpty() )
  {
    ang = mLabelAttributes->angle();
  }
  else
  {
    ang = value.toDouble();
  }


  // Work out a suitable position to put the label for the
  // feature. For multi-geometries, put the same label on each
  // part.
  if ( useOverridePoint )
  {
    renderLabel( painter, overridePoint, coordinateTransform,
                 transform, text, font, pen, dx, dy,
                 xoffset, yoffset, ang, width, height, alignment, sizeScale, rasterScaleFactor );
  }
  else
  {
    std::vector<labelpoint> points;
    labelPoint( points, feature );
    for ( uint i = 0; i < points.size(); ++i )
    {
      renderLabel( painter, points[i].p, coordinateTransform,
                   transform, text, font, pen, dx, dy,
                   xoffset, yoffset, mLabelAttributes->angleIsAuto() ? points[i].angle : ang, width, height, alignment, sizeScale, rasterScaleFactor );
    }
  }
}
/**
  Returns the best match for the given file url in the project directory.

  The method first checks whether the file inside the project directory exists.
  If not, the leading directory in the path is stripped, and the - now shorter - path is
  checked for existence, and so on. Second, it tries to locate the file in the sysroot
  folder specified. Third, we walk the list of project files, and search for a file name match
  there. If all fails, it returns the original path from the file url.
  */
QString FileInProjectFinder::findFile(const QUrl &fileUrl, bool *success) const
{
    if (debug)
        qDebug() << "FileInProjectFinder: trying to find file" << fileUrl.toString() << "...";

    QString originalPath = fileUrl.toLocalFile();
    if (originalPath.isEmpty()) // e.g. qrc://
        originalPath = fileUrl.path();

    if (originalPath.isEmpty()) {
        if (debug)
            qDebug() << "FileInProjectFinder: malformed url, returning";
        if (success)
            *success = false;
        return originalPath;
    }

    if (!m_projectDir.isEmpty()) {
        if (debug)
            qDebug() << "FileInProjectFinder: checking project directory ...";

        int prefixToIgnore = -1;
        const QChar separator = QLatin1Char('/');
        if (originalPath.startsWith(m_projectDir + separator)) {

#ifdef Q_OS_MAC
            // starting with the project path is not sufficient if the file was
            // copied in an insource build, e.g. into MyApp.app/Contents/Resources
            static const QString appResourcePath = QString::fromLatin1(".app/Contents/Resources");
            if (originalPath.contains(appResourcePath)) {
                // the path is inside the project, but most probably as a resource of an insource build
                // so ignore that path
                prefixToIgnore = originalPath.indexOf(appResourcePath) + appResourcePath.length();
            } else {
#endif
                if (debug)
                    qDebug() << "FileInProjectFinder: found" << originalPath << "in project directory";
                if (success)
                    *success = true;
                return originalPath;
#ifdef Q_OS_MAC
            }
#endif
        }

        if (m_cache.contains(originalPath)) {
            if (debug)
                qDebug() << "FileInProjectFinder: checking cache ...";
            // check if cached path is still there
            QString candidate = m_cache.value(originalPath);
            QFileInfo candidateInfo(candidate);
            if (candidateInfo.exists() && candidateInfo.isFile()) {
                if (success)
                    *success = true;
                if (debug)
                    qDebug() << "FileInProjectFinder: found" << candidate << "in the cache";
                return candidate;
            }
        }

        if (debug)
            qDebug() << "FileInProjectFinder: checking stripped paths in project directory ...";

        // Strip directories one by one from the beginning of the path,
        // and see if the new relative path exists in the build directory.
        if (prefixToIgnore < 0) {
            if (!QFileInfo(originalPath).isAbsolute()
                    && !originalPath.startsWith(separator)) {
                prefixToIgnore = 0;
            } else {
                prefixToIgnore = originalPath.indexOf(separator);
            }
        }
        while (prefixToIgnore != -1) {
            QString candidate = originalPath;
            candidate.remove(0, prefixToIgnore);
            candidate.prepend(m_projectDir);
            QFileInfo candidateInfo(candidate);
            if (candidateInfo.exists() && candidateInfo.isFile()) {
                if (success)
                    *success = true;

                if (debug)
                    qDebug() << "FileInProjectFinder: found" << candidate << "in project directory";

                m_cache.insert(originalPath, candidate);
                return candidate;
            }
            prefixToIgnore = originalPath.indexOf(separator, prefixToIgnore + 1);
        }
    }

    // find (solely by filename) in project files
    if (debug)
        qDebug() << "FileInProjectFinder: checking project files ...";

    const QString fileName = QFileInfo(originalPath).fileName();
    foreach (const QString &f, m_projectFiles) {
        if (QFileInfo(f).fileName() == fileName) {
            m_cache.insert(originalPath, f);
            if (success)
                *success = true;
            if (debug)
                qDebug() << "FileInProjectFinder: found" << f << "in project files";
            return f;
        }
    }

    if (debug)
        qDebug() << "FileInProjectFinder: checking absolute path in sysroot ...";

    // check if absolute path is found in sysroot
    if (!m_sysroot.isEmpty()) {
        const QString sysrootPath = m_sysroot + originalPath;
        if (QFileInfo(sysrootPath).exists() && QFileInfo(sysrootPath).isFile()) {
            if (success)
                *success = true;
            m_cache.insert(originalPath, sysrootPath);
            if (debug)
                qDebug() << "FileInProjectFinder: found" << sysrootPath << "in sysroot";
            return sysrootPath;
        }
    }

    if (success)
        *success = false;

    if (debug)
        qDebug() << "FileInProjectFinder: couldn't find file!";
    return originalPath;
}
Example #4
0
void MainWindow::startPatching()
{
    Q_D(MainWindow);

    d->bytes = 0;
    d->maxBytes = 0;
    d->files = 0;
    d->maxFiles = 0;

    d->progressBar->setMaximum(0);
    d->progressBar->setValue(0);
    d->detailsLbl->clear();

    d->state = MainWindowPrivate::Patching;
    updateWidgetsVisibility();

    QString romId;
    if (d->instLocSel->currentIndex() == d->instLocs.size()) {
        romId = QStringLiteral("data-slot-%1").arg(d->instLocLe->text());
    } else if (d->instLocSel->currentIndex() == d->instLocs.size() + 1) {
        romId = QStringLiteral("extsd-slot-%1").arg(d->instLocLe->text());
    } else {
        romId = d->instLocs[d->instLocSel->currentIndex()].id;
    }


    QStringList suffixes;
    suffixes << QStringLiteral(".tar.md5");
    suffixes << QStringLiteral(".tar.md5.gz");
    suffixes << QStringLiteral(".tar.md5.xz");
    suffixes << QStringLiteral(".zip");

    QFileInfo qFileInfo(d->fileName);
    QString suffix;
    QString outputName;
    bool isOdin = false;

    for (const QString &suffix : suffixes) {
        if (d->fileName.endsWith(suffix)) {
            // Input name: <parent path>/<base name>.<suffix>
            // Output name: <parent path>/<base name>_<rom id>.zip
            outputName = d->fileName.left(d->fileName.size() - suffix.size())
                    % QStringLiteral("_")
                    % romId
                    % QStringLiteral(".zip");
            isOdin = suffix.contains(QStringLiteral(".tar.md5"));
            break;
        }
    }
    if (outputName.isEmpty()) {
        outputName = qFileInfo.completeBaseName()
                % QStringLiteral("_")
                % romId
                % QStringLiteral(".")
                % qFileInfo.suffix();
    }

    QString inputPath(QDir::toNativeSeparators(qFileInfo.filePath()));
    QString outputPath(QDir::toNativeSeparators(
            qFileInfo.dir().filePath(outputName)));

    FileInfoPtr fileInfo = new mbp::FileInfo();
    fileInfo->setInputPath(inputPath.toUtf8().constData());
    fileInfo->setOutputPath(outputPath.toUtf8().constData());
    fileInfo->setDevice(d->device);
    fileInfo->setRomId(romId.toUtf8().constData());

    if (isOdin) {
        d->patcher = d->pc->createPatcher("OdinPatcher");
    } else {
        d->patcher = d->pc->createPatcher("MultiBootPatcher");
    }

    emit runThread(d->patcher, fileInfo);
}
Example #5
0
int main (int argc, char *argv[])
{
  FILE *sdb;
  struct dbSpawnStruct dbSpawn;
  int count=0;

  // CGI Convenience class
  CGI cgiconv;
  
  // search variables
  QString searchName = "";
  QString searchZone = "";
  int searchLevel = 0;
  QString searchRace = "";
  int searchClass = 0;

  // are we performing a serch (default = false)
  bool doSearch = false;

  // process any CGI data
  cgiconv.processCGIData();

  // If there are form parameters use them for searching
  if (cgiconv.getParamCount() != 0)
  {
    searchName = cgiconv.getParamValue("name");
    searchZone = cgiconv.getParamValue("zone");
    searchLevel = cgiconv.getParamValue("level").toInt();
    searchRace = cgiconv.getParamValue("race");
    searchClass = cgiconv.getParamValue("class").toInt();

    if (!searchName.isEmpty() || !searchZone.isEmpty() ||
	!searchRace.isEmpty() ||
	(searchLevel != 0) || (searchClass != 0))
      doSearch = true;
  }
  else if (argc == 2)
  {
    // use the argument for the name search
    searchName = argv[1];
    
    // note that a search is being done.
    doSearch = true;
  } 

  // open the output data stream
  QTextStream out(stdout, IO_WriteOnly);
  out.setEncoding(QTextStream::Latin1);
  out.flags(QTextStream::showbase | QTextStream::dec);

  const char* header =
    "Content-type: text/html; charset=iso-8859-1\n\n"
    "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n"
    "<HTML>\n"
    "  <HEAD>\n"
    "    <TITLE>ShowEQ Spawn List</TITLE>\n"
    "    <style type=\"text/css\">\n"
    "      <!--\n"
    "          table { border: black 2px solid }\n"
    "          td { border: black 1px solid }\n"
    "          th { border: black 1px solid }\n"
    "      -->\n"
    "    </style>\n" 
    "  </HEAD>\n"
    "  <BODY>\n";

  /* Print HTML header */
  out << header;

  const char* footer = 
    "  </BODY>\n"
    "</HTML>\n";
  
  // check for browser type
  QString userAgent = cgiconv.getHTTPUserAgent();
  out << "    <!-- Output for UserAgent: " << userAgent << "-->\n";


  out << "<FORM method=\"POST\" action=\"" << cgiconv.getScriptName() 
      << "\">\n";

  // beware Netscape 4.x style sheet brain death
  if ((userAgent.contains("Mozilla/4.") == 1) && 
      (userAgent.contains("MSIE") == 0))
    out << "<TABLE border=2 cellspacing=0 cellpadding=2>\n";
  else
    out << "<TABLE cellspacing=0 cellpadding=2>\n";

  out << 
    "<TR>"
    "<TH>Name</TH><TH>Zone</TH><TH>Level</TH><TH>Race</TH><TH>Class</TH>\n"
    "<TD><INPUT type=\"reset\" value=\"Reset\"/></TD>\n"
    "</TR>\n";

  out << "<TR>";

  // name field
  out << "<TD><INPUT type=\"text\" name=\"name\" value=\"" 
      << searchName << "\"/></TD>\n";

  // zone field
  out << "<TD><INPUT type=\"text\" name=\"zone\" value=\"" 
      << searchZone << "\"/></TD>\n";

  // level field
  out << 
    "<TD><INPUT type=\"text\" name=\"level\" size=\"2\" maxlength=\"2\""
    " value=\"";
  if (searchLevel)
    out << searchLevel;
  out << "\"/></TD>\n";

  // race field
  out << "<TD><INPUT type=\"text\" name=\"race\" value=\"" 
      << searchRace << "\"/></TD>\n";

  // Class field
  out << "<TD><SELECT name=\"class\" size=\"1\">\n";
  out << "<OPTION value=\"0\"";
  if (searchClass == 0)
    out << " selected";
  out << ">Any</OPTION>\n";

  // create a fake spawn to get class names
  Spawn fakeSpawn;

  // start at class value 1, and go until maximum known class value
  for (int i = 1; i <= 32; ++i)
  {
    // set the fake spawns class
    fakeSpawn.setClassVal(i);

    out << "<OPTION value=\"" << i << "\"";
    if (searchClass == i)
      out << " selected";

    // output the name corresponding to the class value
    out << ">" << fakeSpawn.className() << "</OPTION>\n";
  }
  out << "</SELECT></TD>\n";
  
  // Submission button
  out << "<TD><INPUT type=\"submit\" value=\"Search\"/></TD>\n";

  // close the form
  out << 
    "</TR>\n"
    "</TABLE>\n"
    "</FORM>\n";

   sdb = fopen (SPAWNFILE, "r");
   
   if (sdb == NULL) 
   {
     // display the error
     out << "<H1>Unable to open file '" SPAWNFILE "' (errno = " 
	 << errno << ")</H1>\n";

     // close the document
     out << footer;

     // nothing more can be done
     exit(1);
   }

  QString spawnName;
  QRegExp stripExp("[0-9]");

  while (fread (&dbSpawn, sizeof(dbSpawnStruct), 1, sdb))
  {
    Spawn spawn(&dbSpawn.spawn);

    // stash the name for later use and cooking
    spawnName = spawn.name();
    
    // is a search being performed, then do it already...
    if (doSearch)
    {
      // is it a name search, if so do we have a match
      if ((!searchName.isEmpty()) &&
	  (spawnName.find(searchName, 0, false) == -1))
	continue;  // nope, you are the weakest link, good bye...

      // is it a zone search, if so check
      if ((!searchZone.isEmpty()) &&
	  (QString(dbSpawn.zoneName).find(searchZone, 0, false) == -1))
	continue;
      
      // is it a level search, if so check
      if ((searchLevel != 0) && 
	  (searchLevel != spawn.level()))
	continue;
      
      // is it a race search, if so check
      if ((!searchRace.isEmpty()) &&
	  (spawn.raceName().find(searchRace, 0, false) == -1))
	continue;
      
      // is it a class search, if so check
      if ((searchClass != 0) &&
	  (searchClass != spawn.classVal()))
	continue;
    }
	
    // strip the numbers off the spawn name
    spawnName.replace(stripExp, "");

    // display the data
    out << "<H1>" << spawn.realName() << "</H1>\n";
    out << "<P>ShortName: " << spawn.transformedName() << "<BR>\n";
    out << "Level: " << spawn.level() << "<BR>\n";
    out << "HP: " << spawn.HP() << "/"
	<< spawn.maxHP() << "<BR>\n";
    out << "Race: " << spawn.raceName() << "<BR>\n";
    out << "Class: " << spawn.className() << "<BR>\n";
    out << "Found in Zone: " << dbSpawn.zoneName << "<BR>\n";
    out << "Position: " <<  spawn.yPos() << ", " 
	<< spawn.xPos() << ", "
	<< spawn.zPos() << "<BR>\n";
    out << "Mob ID: " << spawn.id() << "<BR>\n";
    out << "<B>Packet data:</B>\n";
    out <<"<PRE>\n";
    printdata (out, sizeof(spawnStruct), (unsigned char *)&dbSpawn.spawn);
    out <<"</PRE>\n";
    out <<"<HR>\n";

    // increment counter
    count++;
  }

  // clsoe the DB
   fclose (sdb);

   // display the number of records found
   out << "<P>Found " << count << " matches.</P>\n";

   out << footer;
}
Example #6
0
int controlyPlugin::launchItem(QList<InputData>* inputData, CatItem* item)
{
	item = item; // Compiler warning

	if (inputData->count() == 1) {
		// no parameters, just the item itsef

		QString path = item->fullPath;

		if (path.contains(",@")) {
			// dll cpl item indexing containing items, e.g. 'main.cpl,@1'

			runProgram("control.exe", item->fullPath); //runProgram(cmd, args);
			// use toNativeSeparators()?
		} else if ((path.startsWith("csidl:", Qt::CaseInsensitive)) && (path.endsWith(".controly", Qt::CaseSensitive))) {
			// Constant special item ID list (CSIDL)

			// shell instance object (special shell extension folder), e.g. 'csidl:0x0014.controly' ('shellinstance:0x0014')
            QString folderId = path.mid(strlen("csidl:"), strlen(path.toLocal8Bit())-strlen("csidl:")-strlen(".controly")); // e.g. 0x0014 = CSIDL_FONTS;
			bool ok;
			int folderIdx = folderId.toLong(&ok, 16);
			if (ok) {
				LPITEMIDLIST pidl;
				HRESULT hres = SHGetFolderLocation(NULL, folderIdx, NULL, 0, &pidl);
				if (hres == S_OK) {
					SHELLEXECUTEINFO sei;
					memset(&sei, 0, sizeof(sei));
					sei.cbSize = sizeof(SHELLEXECUTEINFO);
					sei.fMask = SEE_MASK_IDLIST;
					sei.hwnd = NULL;
					sei.lpVerb = NULL;
					sei.lpFile = NULL;
					sei.lpParameters = NULL;
					sei.lpDirectory = NULL;
					sei.nShow = SW_SHOW;
					sei.hInstApp = NULL;
					sei.lpIDList = pidl;
					sei.hProcess = NULL;
					//it seems we don't need CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
					ShellExecuteEx(&sei);

					CoTaskMemFree((void*)pidl); // needs objbase.h/ole32.lib
				}
			}
		} else {
			// exe cpl item with command line parameters, e.g. 'rundll32.exe shell32.dll,Options_RunDLL 1'
			// or item defined via application name, e.g. 'control.exe /name Microsoft.WindowsUpdate'

			QStringList spl = path.split(".exe ");
			if (spl.size() == 2) {
				// split size currently is always 2, as assured above
				QString executable = spl[0] + ".exe";
				QString parameters = spl[1];
				runProgram(executable, parameters);
			} else {
				runProgram(path, "");
			}
		}

		return 1;
	}

	if (inputData->count() != 2)
		return 1;

	CatItem last = inputData->last().getTopResult();
	if (last.shortName == "Options")
	{
		updateUsage(last);
		return MSG_CONTROL_OPTIONS;
	}
	else if (last.shortName == "Rebuild Catalog")
	{
		updateUsage(last);
		return MSG_CONTROL_REBUILD;
	}
	else if (last.shortName == "Exit")
	{
		updateUsage(last);
		return MSG_CONTROL_EXIT;
	}
	return 1;

}
Example #7
0
// Determine if a channel name contains wildcard characters.
static bool containsWildcards( const QString& channel )
{
    return channel.contains(QLatin1Char('*'));
}
Example #8
0
bool
DropJob::acceptsMimeData( const QMimeData* data, DropJob::DropTypes acceptedType, DropJob::DropAction acceptedAction )
{
    Q_UNUSED( acceptedAction );

    if ( data->hasFormat( "application/tomahawk.query.list" )
        || data->hasFormat( "application/tomahawk.plentry.list" )
        || data->hasFormat( "application/tomahawk.result.list" )
        || data->hasFormat( "application/tomahawk.result" )
        || data->hasFormat( "application/tomahawk.mixed" )
        || data->hasFormat( "application/tomahawk.metadata.album" )
        || data->hasFormat( "application/tomahawk.metadata.artist" ) )
    {
        return true;
    }

    // check plain text url types
    if ( !data->hasFormat( "text/plain" ) )
        if ( !data->hasFormat( "text/uri-list" ) )
            return false;


    const QString url = data->data( "text/plain" );
    if ( acceptedType.testFlag( Playlist ) )
    {
        if ( url.contains( "xspf" ) )
            return true;

        if ( url.contains( "m3u" ) )
            return true;

        if ( data->data( "text/uri-list" ).contains( "xspf" ) )
            return true;

        if ( data->data( "text/uri-list" ).contains( "m3u" ) )
            return true;

        // Not the most elegant
        if ( url.contains( "spotify" ) && url.contains( "playlist" ) && s_canParseSpotifyPlaylists )
            return true;
        
        if ( url.contains( "grooveshark.com" ) && url.contains( "playlist" ) )
            return true;
    }

    if ( acceptedType.testFlag( Track ) )
    {
        if ( url.contains( "m3u" ) )
            return true;

        if ( data->data( "text/uri-list" ).contains( "m3u" ) )
            return true;

        if ( url.contains( "itunes" ) && url.contains( "album" ) ) // YES itunes is f****d up and song links have album/ in the url.
            return true;

        if ( url.contains( "spotify" ) && url.contains( "track" ) )
            return true;

        if ( url.contains( "rdio.com" ) && ( ( ( url.contains( "track" ) && url.contains( "artist" ) && url.contains( "album" ) )
                                               || url.contains( "playlists" )  ) ) )
            return true;
    }

    if ( acceptedType.testFlag( Album ) )
    {
        if ( url.contains( "itunes" ) && url.contains( "album" ) ) // YES itunes is f****d up and song links have album/ in the url.
            return true;
        if ( url.contains( "spotify" ) && url.contains( "album" ) )
            return true;
        if ( url.contains( "rdio.com" ) && ( url.contains( "artist" ) && url.contains( "album" ) && !url.contains( "track" ) )  )
            return true;
    }

    if ( acceptedType.testFlag( Artist ) )
    {
        if ( url.contains( "itunes" ) && url.contains( "artist" ) ) // YES itunes is f****d up and song links have album/ in the url.
            return true;
        if ( url.contains( "spotify" ) && url.contains( "artist" ) )
            return true;
        if ( url.contains( "rdio.com" ) && ( url.contains( "artist" ) && !url.contains( "album" ) && !url.contains( "track" ) )  )
            return true;
    }

    // We whitelist certain url-shorteners since they do some link checking. Often playable (e.g. spotify) links hide behind them,
    // so we do an extra level of lookup
    if ( ShortenedLinkParser::handlesUrl( url ) )
        return true;

    return false;
}
Example #9
0
QString CppToQsConverter::convertCodeLine( Tree *qsTree,
					   const QStringList& program,
					   const QString& code,
					   const QSet<QString>& classesWithNoQ )
{
    static QString dataTypeFmt =
	"(?!return)(?:const\\b\\s*)?[A-Za-z_]+(?:\\s*[*&])?";
    static QRegExp funcPrototypeRegExp(
	"(" + dataTypeFmt + ")\\s*\\b([A-Z][a-zA-Z_0-9]*::)?"
	"([a-z][a-zA-Z_0-9]*)\\(([^);]*)(\\)?)(?:\\s*const)?" );
    static QRegExp paramRegExp(
	"^\\s*(" + dataTypeFmt + ")\\s*\\b([a-z][a-zA-Z_0-9]*)\\s*(,)?\\s*" );
    static QRegExp uninitVarRegExp(
	"(" + dataTypeFmt + ")\\s*\\b([a-z][a-zA-Z_0-9]*);" );
    static QRegExp eqVarRegExp(
	dataTypeFmt + "\\s*\\b([a-z][a-zA-Z_0-9]*)\\s*=(\\s*)(.*)" );
    static QRegExp ctorVarRegExp(
	"(" + dataTypeFmt + ")\\s*\\b([a-z][a-zA-Z_0-9]*)\\((.*)\\);" );
    static QRegExp qdebugRegExp(
	"q(?:Debug|Warning|Fatal)\\(\\s*(\"(?:\\\\.|[^\"])*\")\\s*"
	"(?:,\\s*(\\S(?:[^,]*\\S)?))?\\s*\\);" );
    static QRegExp coutRegExp( "c(?:out|err)\\b(.*);" );
    static QRegExp lshiftRegExp( "\\s*<<\\s*" );
    static QRegExp endlRegExp( "^endl$" );

    if ( code.isEmpty() || code == "{" || code == "}" )
	return code;

    QString result;

    if ( funcPrototypeRegExp.exactMatch(code) ) {
	QString returnType = funcPrototypeRegExp.cap( 1 );
	QString className = funcPrototypeRegExp.cap( 2 );
	QString funcName = funcPrototypeRegExp.cap( 3 );
	QString params = funcPrototypeRegExp.cap( 4 ).trimmed();
	bool toBeContinued = funcPrototypeRegExp.cap( 5 ).isEmpty();
        // ### unused
        Q_UNUSED(toBeContinued);

	className.replace( "::", "." );

	result = "function " + className + funcName + "(";

	if ( !params.isEmpty() && params != "void" ) {
	    result += " ";
	    int i = funcPrototypeRegExp.pos( 4 );
	    while ( (i = paramRegExp.indexIn(code, i,
					     QRegExp::CaretAtOffset)) != -1 ) {
		QString dataType = paramRegExp.cap( 1 );
		QString paramName = paramRegExp.cap( 2 );
		QString comma = paramRegExp.cap( 3 );

		result += paramName + " : " +
			  convertedDataType( qsTree, dataType );
		if ( comma.isEmpty() )
		    break;
		result += ", ";
		i += paramRegExp.matchedLength();
	    }
	    result += " ";
	}

	result += ")";
	returnType = convertedDataType( qsTree, returnType );
	if ( !returnType.isEmpty() )
	    result += " : " + returnType;
    } else if ( uninitVarRegExp.exactMatch(code) ) {
	QString dataType = uninitVarRegExp.cap( 1 );
	QString varName = uninitVarRegExp.cap( 2 );

	result = "var " + varName;
	dataType = convertedDataType( qsTree, dataType );
	if ( !dataType.isEmpty() )
	    result += " : " + dataType;
	result += ";";
    } else if ( eqVarRegExp.exactMatch(code) ) {
	QString varName = eqVarRegExp.cap( 1 );
	QString value = eqVarRegExp.cap( 3 );

	value = convertExpr( qsTree, value, classesWithNoQ );
	result += "var " + varName + " = " + value;
    } else if ( ctorVarRegExp.exactMatch(code) ) {
	QString dataType = ctorVarRegExp.cap( 1 );
	QString varName = ctorVarRegExp.cap( 2 );
	QString value = ctorVarRegExp.cap( 3 ).trimmed();

	result += "var " + varName + " = ";

	dataType = convertedDataType( qsTree, dataType );
	value = convertExpr( qsTree, value, classesWithNoQ );

	if ( dataType.isEmpty() || dataType == "String" ) {
	    if ( value.contains(",") ) {
		result += "...";
	    } else {
		result += value;
	    }
	} else {
	    result += "new " + dataType;
	    if ( !value.isEmpty() )
		result += "( " + value + " )";
	}
	result += ";";
    } else if ( qdebugRegExp.exactMatch(code) ) {
	QString fmt = qdebugRegExp.cap( 1 );
	QString arg1 = qdebugRegExp.cap( 2 );

	result += "println ";
	int i = 0;
	while ( i < (int) fmt.length() ) {
	    if ( fmt[i] == '%' ) {
		int percent = i;
		i++;
		while ( i < (int) fmt.length() &&
			QString("diouxXeEfFgGaAcsCSpn%\"").indexOf(fmt[i]) == -1 )
		    i++;
		if ( fmt[i] == '%' ) {
		    result += fmt[i++];
		} else if ( fmt[i] != '"' ) {
		    if ( percent == 1 ) {
			result.truncate( result.length() - 1 );
		    } else {
			result += "\" + ";
		    }
		    i++;
		    if ( arg1.endsWith(".latin1()") )
			arg1.truncate( arg1.length() - 9 );
		    result += arg1;
		    if ( i == (int) fmt.length() - 1 ) {
			i++;
		    } else {
			result += " + \"";
		    }
		}
	    } else {
		result += fmt[i++];
	    }
	}
	result += ";";
    } else if ( coutRegExp.exactMatch(code) &&
		program.filter("var cout").isEmpty() ) {
	QStringList args = coutRegExp.cap(1).split(lshiftRegExp);
	args.replaceInStrings( endlRegExp, "\"\\n\"" );
	if ( args.last() == "\"\\n\"" ) {
	    args.erase( args.end() - 1 );
	    if ( args.isEmpty() )
		args << "\"\"";
	    result += "println ";
	} else {
	    result += "print ";
	}
	result += args.join( " + " ) + ";";
    } else {
	result = convertExpr( qsTree, code, classesWithNoQ );
    }
    return result;
}
Example #10
0
void NetSearch::slotItemChanged()
{
    QMutexLocker locker(&m_lock);

    ResultItem *item =
              qVariantValue<ResultItem *>(m_searchResultList->GetDataValue());

    if (item && GetFocusWidget() == m_searchResultList)
    {
        MetadataMap metadataMap;
        item->toMap(metadataMap);
        SetTextFromMap(metadataMap);

        if (!item->GetThumbnail().isEmpty() && m_thumbImage)
        {
            MythUIButtonListItem *btn = m_searchResultList->GetItemCurrent();
            QString filename = btn->GetImage();
            if (filename.contains("%SHAREDIR%"))
                filename.replace("%SHAREDIR%", GetShareDir());
            m_thumbImage->Reset();

            if (!filename.isEmpty())
            {
                m_thumbImage->SetFilename(filename);
                m_thumbImage->Load();
            }
        }

        if (m_downloadable)
        {
            if (item->GetDownloadable())
                m_downloadable->DisplayState("yes");
            else
                m_downloadable->DisplayState("no");
        }
    }
    else if (GetFocusWidget() == m_siteList)
    {
        MythUIButtonListItem *item = m_siteList->GetItemCurrent();

        ResultItem *res = new ResultItem(item->GetText(), QString(), QString(),
              QString(), QString(), QString(), QString(), QDateTime(),
              0, 0, -1, QString(), QStringList(), QString(), QStringList(), 0, 0, QString(),
              0, QStringList(), 0, 0, 0);

        MetadataMap metadataMap;
        res->toMap(metadataMap);
        SetTextFromMap(metadataMap);

        if (m_thumbImage)
        {
            QString filename = item->GetImage();
            m_thumbImage->Reset();
            if (filename.contains("%SHAREDIR%"))
                filename.replace("%SHAREDIR%", GetShareDir());

            if (!filename.isEmpty())
            {
                m_thumbImage->SetFilename(filename);
                m_thumbImage->Load();
            }
        }
    }
}
Example #11
0
void CKSocketClient::playMessage(const QString &message) {
	ostringstream os;
	os << message.toStdString() << endl;
	ColorKeeperModel::logMessage(os.str());
	if (message.compare(QString("GET_SCREEN_INFO")) == 0) {
		try {
			const DisplayDevice
					& currScreen =
							ColorKeeperModel::Instance().getDeviceInfo().getCalibrableDisplayDevice(
									_currentScreen);
			ColorKeeperModel::Instance().addCalibModelForScreen(_currentScreen);
			QString sendMessage("SCREEN_INFO_ [index]");

			sendMessage.append(currScreen.getOSIndex());
			sendMessage.append(";[uid]");
			sendMessage.append(currScreen.getFullSerialNumber().c_str());
			sendMessage.append(";[manufacturer]");
			sendMessage.append(currScreen.getManufacturerName().c_str());
			sendMessage.append(";[model]");
			sendMessage.append(currScreen.getModelName().c_str());
			sendMessage.append(";[type]");
			sendMessage.append(currScreen.getStringType().c_str());
			sendMessage.append(";[profil]");
			sendMessage.append(
					ColorKeeperModel::Instance().getScreenProfilName(
							currScreen.getOSIndex()).c_str());
			sendMessage.append("\n");
			writeSocket(sendMessage);

		} catch (std::string e) { //TODO exception
			QString sendMessage = "Error";
			writeSocket(sendMessage);
		}
	} else if (message.contains(QString("DISPLAY_LUM_PATT")) == true) {
		QString m = message;
		m.remove(QString("DISPLAY_LUM_PATT "));
		QChar sc = m[0];
		m.remove(sc);
		int screen = sc.digitValue();
		float gamma = m.toFloat();

		emit displayLumContPatt(gamma, screen, false);
	} else if (message.contains(QString("SET_LUT_ON")) == true) {
		QChar sc = message[11];
		int screen = sc.digitValue();
		ColorKeeperModel::Instance().setScreenShouldApplyCorrection(screen,
				true);
	} else if (message.contains(QString("SET_LUT_OFF")) == true) {
		QChar sc = message[12];
		int screen = sc.digitValue();
		ColorKeeperModel::Instance().setScreenShouldApplyCorrection(screen,
				false);

	} else if (message.contains(QString("UNSET_MOSAIC")) == true) {
		QChar sc = message[13];
		int screen = sc.digitValue();
		emit displayLumContPatt(-1, screen, false);
	} else if (message.contains(QString("SET_MOSAIC")) == true) {
		QChar sc = message[11];
		int screen = sc.digitValue();
		emit displayLumContPatt(-1, screen, true);
	} else if (message.contains(QString("SET_PATCH_COLOR")) == true) {
		QChar sc = message[16];
		int screen = sc.digitValue();
		QStringList list = message.split(QChar('-'));
		QStringList::Iterator it = list.begin() + 1;
		QString tmp = (*it);
		float r = tmp.toFloat() / 255.f;
		++it;
		tmp = (*it);
		float g = tmp.toFloat() / 255.f;
		++it;
		tmp = (*it);
		float b = tmp.toFloat() / 255.f;
		++it;
		tmp = (*it);
		QChar halo = tmp[0];
		bool drawHalo = false;
		if (halo == QChar('t')) {
			drawHalo = true;
		}

		emit displayPatch(screen, r, g, b, drawHalo);
		QString sendMessage("PATCH_OK\n");
		writeSocket(sendMessage);
	} else if (message.contains(QString("SET_REC_COLOR")) == true) {
		QChar sc = message[14];
		int screen = sc.digitValue();
		QStringList list = message.split(QChar('-'));
		QStringList::Iterator it = list.begin() + 1;
		QString tmp = (*it);
		float r = tmp.toFloat() / 255.f;
		++it;
		tmp = (*it);
		float g = tmp.toFloat() / 255.f;
		++it;
		tmp = (*it);
		float b = tmp.toFloat() / 255.f;
		++it;
		tmp = (*it);
		emit displayFullScreenRec(screen, r, g, b);
		QString sendMessage("REC_OK\n");
		writeSocket(sendMessage);
	} else if (message.contains(QString("SET_LUT_SIZE")) == true) {
		QChar sc = message[13];
		int screen = sc.digitValue();
		QStringList list = message.split(QChar('-'));
		QStringList::Iterator it = list.begin() + 1;
		QString tmp = (*it);
		unsigned int size = tmp.toInt();
		ColorKeeperModel::Instance().setCalibSizeForScreen(screen, size);
		QString sendMessage("SET_LUT_SIZE_OK\n");
		writeSocket(sendMessage);
	} else if (message.contains(QString("VALUE")) == true) {
		QChar sc = message[6];
		int screen = sc.digitValue();
		QStringList list = message.split(QChar('-'));
		QStringList::Iterator it = list.begin() + 1;
		QString tmp = (*it);
		unsigned short red = tmp.toInt();
		++it;
		tmp = (*it);
		unsigned short green = tmp.toInt();
		++it;
		tmp = (*it);
		unsigned short blue = tmp.toInt();
		ostringstream os;
		os << (int) red << (int) green << (int) blue << endl;
		ColorKeeperModel::logMessage(os.str());
		ColorKeeperModel::Instance().addCalibValueForScreen(screen, red, green,
				blue);
	} else if (message.contains(QString("SET_LUT_DONE")) == true) {
		//		QString sendMessage("SET_LUT_OK\n");
		//		writeSocket(sendMessage);
		QChar sc = message[13];
		int screen = sc.digitValue();
		ColorKeeperModel::Instance().setCalibDoneForScreen(screen);

	} else if (message.contains(QString("SHOULD_DISPLAY")) == true) {
		QChar sc = message[15];
		int screen = sc.digitValue();
		QChar va = message[17];
		bool tog = false;
		if (va == QChar('t')) {
			tog = true;
		}
		ColorKeeperModel::Instance().shoudDisplayCalibForScreen(screen, tog);
	} else if (message.contains(QString("UPDATE_CALIB_FILE")) == true) {
		QChar sc = message[18];
		int screen = sc.digitValue();
		QString infos = message;
		infos.remove(0, 19);
		infos.replace(QChar('#'), QChar('\n'));
		ColorKeeperModel::Instance().updateCorrection(screen, infos);
		QString sendMessage("UPDATE_OK\n");
		writeSocket(sendMessage);
	} else if (message.contains(QString("BUH_BYE")) == true) {
		QChar sc = message[8];
		int screen = sc.digitValue();
		ColorKeeperModel::Instance().endCalib(screen);
	}
}
Example #12
0
QString addDot(QString ext) {
  if(ext.contains('.')) //We need this check because of the _impl.h thing
    return ext;
  else
    return "." + ext;
}
Example #13
0
// COMMON:
// Description :
// 		View mode : ALL , OWNER, NO-ROOOT , HIDDEN, NETWORK
bool Procview::accept_proc(Procinfo *p)
{
    QString pid;
    static int my_uid = getuid();
    bool result;

    result = true;

    // BAD
    if (false and viewproc == NETWORK)
    {
        /*
        p->read_fds();
        if(p->sock_inodes.size()==0)
                result=false;
        for(int i=0;i<p->sock_inodes.size();i++)
        {
                SockInode *sn=p->sock_inodes[i];
                Sockinfo *si=Procinfo::socks.value(sn->inode,NULL);
                if(si)
                {
                        si->pid=p->pid;
                        linear_socks.append(si);
                }
        }
        */
    }
    else if (viewproc == ALL)
        result = true;
    else if (viewproc == OWNED)
        result = (p->uid == my_uid);
    else if (viewproc == NROOT)
        result = (p->uid != 0);
    else if (viewproc == RUNNING)
        result = strchr("ORDW", p->state) != 0;

    /*
    if ( viewproc == HIDDEN)
    {
            result=false;
            for(int j=0;j<hidden_process.size();j++)
                    if(hidden_process[j]==p->command)
                            result=true ;
    }
    else
    {
            for(int j=0;j<hidden_process.size();j++)
                    if(hidden_process[j]==p->command)
                            result=false;
    } */

    if (result == false)
        return false; // dont go further !! for better speed

    /// if(search_box==NULL)		return result;
    if (filterstr == "")
        return result;

    if (filterstr == "*")
        return true;

    // Notice:
    //  1. some process name maybe different CMDLINE.  ex) Xorg
    if (p->cmdline.contains(filterstr,
                            Qt::CaseInsensitive)) // search_box->text()
        return true;
    if (p->command.contains(filterstr, Qt::CaseInsensitive))
        return true;
    if (p->username.contains(filterstr, Qt::CaseInsensitive))
        return true;

    pid = pid.setNum(p->pid); //=QString::number(p->pid);
    if (pid.contains(filterstr, Qt::CaseInsensitive))
        return true;

    /// printf("search_Box =%s , %s
    /// \n",search_box->text().toAscii().data(),p->command.toAscii().data());

    return false;
}
Example #14
0
bool AutoReply::incomingStanza(int account, const QDomElement& stanza) {
    if (enabled) {
        if (stanza.tagName() == "message") {
            QString Status = AccInfoHost->getStatus(account);
            bool state = false;
            if(Status == "online" && SOnline) { state = true;
            } else {
                if(Status == "away" && SAway) { state = true;
                } else {
                    if(Status == "chat" && SChat) { state = true;
                    } else {
                        if(Status == "xa" && SXa) { state = true;
                        } else {
                            if(Status == "dnd" && SDnd) { state = true;
                            } else {
                                if(Status == "invisible" && SInvis) { state = true;
                                }
                            }
                        }
                    }
                }
            }
            if(!state)    return false;

            QStringList Disable = DisableForAcc.split(QRegExp("\\s+"), QString::SkipEmptyParts);
            QString AccJid = AccInfoHost->getJid(account);
            while(!Disable.isEmpty()) {
                if(AccJid == Disable.takeFirst()) return false;
            }

            QString type = "";
            type = stanza.attribute("type");
            if(type == "groupchat" || type == "error" || type == "normal")    return false;

            QDomElement Body = stanza.firstChildElement("body");
            if(Body.isNull())  return false;

            if(Body.text() == Message)    return false;

            QDomElement rec =  stanza.firstChildElement("received");
            if(!rec.isNull())  return false;

            QDomElement subj = stanza.firstChildElement("subject");
            if (subj.text() == "AutoReply" || subj.text() == "StopSpam" || subj.text() == "StopSpam Question") return false;

            QString from = stanza.attribute("from");
            QString to = stanza.attribute("to");
            QString valF = from.split("/").takeFirst();
            QString valT = to.split("/").takeFirst();
            if(valF.toLower() == valT.toLower())  return false;

            if(!from.contains("@")) return false;

            Disable = DisableFor.split(QRegExp("\\s+"), QString::SkipEmptyParts);
            if(EnableDisable) {
                while(!Disable.isEmpty()) {
                    QString J =     Disable.takeFirst();
                    if(J.toLower() == valF.toLower() || from.contains(J, Qt::CaseInsensitive)) {
                        return false;
                    }
                }
            }
            else {
                bool b = false;
                while(!Disable.isEmpty()) {
                    QString J =     Disable.takeFirst();
                    if(J.toLower() == valF.toLower() || from.contains(J, Qt::CaseInsensitive)) {
                        b = true;
                    }
                }
                if(!b) { return false;
                }
            }

            if(ActiveTabIsEnable) {
                QString getJid = ActiveTabHost->getJid();
                if(getJid.toLower() == from.toLower()) return false;
            }

            if(NotInRoster) {
                QStringList Roster = AccInfoHost->getRoster(account);
                if(!Roster.contains(valF, Qt::CaseInsensitive)) return false;
            }

            if(Times == 0) return false;
            if(Times != -1) {
                int i = Counter.size();
                if(FindAcc(account, from, i)) {
                    Base &B = Counter[i];
                    if(B.count >= Times) {
                        if(QDateTime::currentDateTime().secsTo(B.LastMes) >= -ResetTime*60) {
                            return false;
                        }
                        else {
                            B.count = 1;
                            B.LastMes = QDateTime::currentDateTime();
                        }
                    }
                    else {
                        B.count++;
                        B.LastMes = QDateTime::currentDateTime();
                    }
                }
                else {
                    Base B = {account, from, 1, QDateTime::currentDateTime() };
                    Counter << B;
                }
            }

            QString mes = "<message to='" + StanzaHost->escape(from) + "'";
            if(type != "") {
                mes += " type='" + StanzaHost->escape(type) + "'";
            }
            else {
                mes += "><subject>AutoReply</subject";
            }
            mes += "><body>" + StanzaHost->escape(Message) + "</body></message>";
            StanzaHost->sendStanza(account, mes);
        }
    }
    return false;
}
void ImageWidget::restore(Graph *g, const QStringList& lst)
{
	int frameStyle = 0;
	QPen pen = QPen(Qt::black, 1, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin);
	double x = 0.0, y = 0.0, right = 0.0, bottom = 0.0;
	QStringList::const_iterator line;
	QString fn;
	bool save_xpm = false;
	ImageWidget *i = NULL;
	AttachPolicy attachTo = FrameWidget::Page;
	bool onTop = true;
	for (line = lst.begin(); line != lst.end(); line++){
        QString s = *line;
        if (s.contains("<Frame>"))
			frameStyle = s.remove("<Frame>").remove("</Frame>").toInt();
		else if (s.contains("<Color>"))
			pen.setColor(QColor(s.remove("<Color>").remove("</Color>")));
		else if (s.contains("<FrameWidth>"))
			pen.setWidth(s.remove("<FrameWidth>").remove("</FrameWidth>").toInt());
		else if (s.contains("<LineStyle>"))
			pen.setStyle(PenStyleBox::penStyle(s.remove("<LineStyle>").remove("</LineStyle>").toInt()));
		else if (s.contains("<x>"))
			x = s.remove("<x>").remove("</x>").toDouble();
		else if (s.contains("<y>"))
			y = s.remove("<y>").remove("</y>").toDouble();
		else if (s.contains("<right>"))
			right = s.remove("<right>").remove("</right>").toDouble();
		else if (s.contains("<bottom>"))
			bottom = s.remove("<bottom>").remove("</bottom>").toDouble();
		else if (s.contains("<attachTo>"))
			attachTo = (FrameWidget::AttachPolicy)s.remove("<attachTo>").remove("</attachTo>").toInt();
		else if (s.contains("<onTop>"))
			onTop = s.remove("<onTop>").remove("</onTop>").toInt();
		else if (s.contains("<path>"))
			i = g->addImage(s.remove("<path>").remove("</path>"));
		else if (s.contains("<xpm>")){
			save_xpm = true;
			if (!i){
				QString xpm;
				while ( s != "</xpm>" ){
					s = *(++line);
					xpm += s + "\n";
				}
				QImage image;
    			if (image.loadFromData(xpm.toAscii()))
					i = g->addImage(image);
			}
		}
	}

	if (i){
		i->setFrameStyle(frameStyle);
		i->setFramePen(pen);
		i->setCoordinates(x, y, right, bottom);
		i->setSaveInternally(save_xpm);
		i->setAttachPolicy(attachTo);
		i->setOnTop(onTop);
	}
}
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 busybox 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
}
Example #17
0
QByteArray Html5App::appViewerCppFileCode(QString *errorMessage) const
{
    static const char* touchNavigavigationFiles[] = {
        "webtouchphysicsinterface.h",
        "webtouchphysics.h",
        "webtouchevent.h",
        "webtouchscroller.h",
        "webtouchnavigation.h",
        "webnavigation.h",
        "navigationcontroller.h",
        "webtouchphysicsinterface.cpp",
        "webtouchphysics.cpp",
        "webtouchevent.cpp",
        "webtouchscroller.cpp",
        "webtouchnavigation.cpp",
        "webnavigation.cpp",
        "navigationcontroller.cpp",
    };
    static const QString touchNavigavigationDir =
            originsRoot() + appViewerOriginsSubDir + QLatin1String("touchnavigation/");
    QByteArray touchNavigavigationCode;
    for (size_t i = 0; i < sizeof(touchNavigavigationFiles) / sizeof(touchNavigavigationFiles[0]); ++i) {
        QFile touchNavigavigationFile(touchNavigavigationDir + QLatin1String(touchNavigavigationFiles[i]));
        if (!touchNavigavigationFile.open(QIODevice::ReadOnly)) {
            if (errorMessage)
                *errorMessage = QCoreApplication::translate("QmakeProjectManager::AbstractMobileApp",
                    "Could not open template file '%1'.").arg(QLatin1String(touchNavigavigationFiles[i]));
            return QByteArray();
        }
        QTextStream touchNavigavigationFileIn(&touchNavigavigationFile);
        QString line;
        while (!(line = touchNavigavigationFileIn.readLine()).isNull()) {
            if (line.startsWith(QLatin1String("#include")) ||
                    ((line.startsWith(QLatin1String("#ifndef"))
                      || line.startsWith(QLatin1String("#define"))
                      || line.startsWith(QLatin1String("#endif")))
                    && line.endsWith(QLatin1String("_H"))))
                continue;
            touchNavigavigationCode.append(line.toLatin1());
            touchNavigavigationCode.append('\n');
        }
    }

    QFile appViewerCppFile(path(AppViewerCppOrigin));
    if (!appViewerCppFile.open(QIODevice::ReadOnly)) {
        if (errorMessage)
            *errorMessage = QCoreApplication::translate("QmakeProjectManager::AbstractMobileApp",
                "Could not open template file '%1'.").arg(path(AppViewerCppOrigin));
        return QByteArray();
    }
    QTextStream in(&appViewerCppFile);
    QByteArray appViewerCppCode;
    bool touchNavigavigationCodeInserted = false;
    QString line;
    while (!(line = in.readLine()).isNull()) {
        if (!touchNavigavigationCodeInserted && line == QLatin1String("#ifdef TOUCH_OPTIMIZED_NAVIGATION")) {
            appViewerCppCode.append(line.toLatin1());
            appViewerCppCode.append('\n');
            while (!(line = in.readLine()).isNull()
                && !line.contains(QLatin1String("#endif // TOUCH_OPTIMIZED_NAVIGATION")))
            {
                if (!line.startsWith(QLatin1String("#include \""))) {
                    appViewerCppCode.append(line.toLatin1());
                    appViewerCppCode.append('\n');
                }
            }
            appViewerCppCode.append(touchNavigavigationCode);
            touchNavigavigationCodeInserted = true;
        }
        appViewerCppCode.append(line.toLatin1());
        appViewerCppCode.append('\n');
    }
    return appViewerCppCode;
}
Example #18
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;
}
Example #19
0
QString MainWindow::convert_PlainText(QByteArray data, QString key)
{  
   QString tempStr;

   int posBeg = data.indexOf(key);

   if (posBeg >= 0) {
      int posEnd    = data.indexOf("\n", posBeg);
      int tempStart = posBeg;

      while (posEnd >= 0) {
         QString x = data.mid(tempStart, posEnd - tempStart);

         if (x.contains("\\")) {
            tempStart = posEnd + 1;
            posEnd    = data.indexOf("\n", tempStart);

         } else {
            break;

         }       
      }

      QString x = data.mid(posBeg, posEnd - posBeg);

      posBeg  = x.indexOf("=");
      tempStr = x.mid(posBeg + 1).trimmed();

      // break into parts
      QRegExp regexp("\\\\[ \\t]*[\\n\\r]+");
      QStringList list = tempStr.split(regexp, QString::SkipEmptyParts);

      // walk each item
      int maxList = list.size();

      for (int k = 0; k < maxList; ++k) {

         QString tempStr = list.at(k);
         tempStr = tempStr.trimmed();

         if (tempStr.startsWith("\"") && tempStr.endsWith("\"")) {
            int len = tempStr.length();
            tempStr = tempStr.mid(1, len - 2);

            list.replace(k, tempStr);

         } else if (tempStr.contains(" ") )   {
            // have multiple entries on one line
            bool isFirst = true;

            QStringList insertList = tempStr.split(" ", QString::SkipEmptyParts);
            int maxInsertList = insertList.size();

            for (int j = 0; j < maxInsertList; ++j) {
               QString newStr = insertList.at(j);
               newStr = newStr.trimmed();

               if (isFirst)  {
                  list.replace(k, newStr);
                  isFirst = false;

               } else {
                  list.insert(k+j, newStr);

                  // watch these two lines of code
                  ++maxList;
               }
            }

            // watch this
            k += maxInsertList - 1;

         } else {
            list.replace(k, tempStr);

         }
      }

      // turn it back into a string
      tempStr = list.join(", ");
   }

   return tempStr;
}
//4 columns: name, type, value, comment
//name:type=value - comment
CMakeCacheModel::CMakeCacheModel(QObject *parent, const KUrl &path)
    : QStandardItemModel(parent), m_filePath(path), m_changed(false)
{
    QStringList labels;
    labels.append(i18n("Name"));
    labels.append(i18n("Type"));
    labels.append(i18n("Value"));
    labels.append(i18n("Comment"));
    labels.append(i18n("Advanced"));
    setHorizontalHeaderLabels(labels);
    
    QFile file(path.toLocalFile());
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        kDebug(9032) << "error. Could not find the file";
        return;
    }

    int currentIdx=0;
    QStringList currentComment;
    QTextStream in(&file);
    while (!in.atEnd())
    {
        QString line = in.readLine().trimmed();
        if(line.startsWith("//"))
            currentComment += line.right(line.count()-2);
        else if(!line.isEmpty() && !line.startsWith('#')) //it is a variable
        {
            CacheLine c;
            c.readLine(line);
            
            if(c.isCorrect())
            {
                QString name=c.name(), flag=c.flag();
                
                QString type=c.type();
                QString value=c.value();

                QList<QStandardItem*> lineItems;
                lineItems.append(new QStandardItem(name));
                lineItems.append(new QStandardItem(type));
                lineItems.append(new QStandardItem(value));
                lineItems.append(new QStandardItem(currentComment.join("\n")));

                if(flag=="INTERNAL")
                {
                    m_internal.insert(name);
                } else if(flag=="ADVANCED")
                {
                    if(m_variablePos.contains(name))
                    {
                        int pos=m_variablePos[name];
                        QStandardItem *p = item(pos, 4);
                        if(!p)
                        {
                            p=new QStandardItem(value);
                            setItem(pos, 4, p);
                        }
                        else
                        {
                            p->setText(value);
                        }
                    }
                    else
                    {
                        kDebug(9032) << "Flag for an unknown variable";
                    }
                }
                
                if(!flag.isEmpty())
                {
                    lineItems[0]->setText(lineItems[0]->text()+'-'+flag);
                }
                insertRow(currentIdx, lineItems);
                m_variablePos[name]=currentIdx;
                currentIdx++;
                currentComment.clear();
            }
        }
        else if(line.startsWith('#') && line.contains("INTERNAL"))
        {
            m_internalBegin=currentIdx;
//                 kDebug(9032) << "Comment: " << line << " -.- " << currentIdx;
        }
        else if(!line.startsWith('#') && !line.isEmpty())
        {
            kDebug(9032) << "unrecognized cache line: " << line;
        }
    }
}
Example #21
0
void Progress::parseDesktopFile(QString filePath, QString dirName){

#ifdef DEBUG
    qDebug()<<"* [ii] Parsing file: "<<filePath<<" at "<<dirName;
#endif

    QString name, path, type, icon, exec, args, prefix_path;

    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    QTextStream in(&file);
    while (!in.atEnd()) {
        QString line = in.readLine();
        if (line.contains(QRegExp("^Name=*"))){
            name=dirName;
            name.append(" - ");
            name.append(line.right(line.length()-5));
        } else if (line.contains(QRegExp("^Type=*"))){
            type=line.right(line.length()-5);
        } else if (line.contains(QRegExp("^Path=*"))){
            path=line.right(line.length()-5);
        } else if (line.contains(QRegExp("^Icon=*"))){
            icon=line.right(line.length()-5);
            if (!icon.contains(QRegExp("(png$|xpm$|gif$|jpg$)"))){
                icon.append(".png");
            }
        } else if (line.contains(QRegExp("^Exec=*"))){
            //Parse exec string
            QRegExp rxlen(".*WINEPREFIX=\"(.+)\" .*wine (\\S*) ?(.*)?");
            if (rxlen.indexIn(line) != -1){
                QStringList cap = rxlen.capturedTexts();
#ifdef DEBUG
                qDebug()<<"[ii] Captured Texts :"<<cap;
#endif
                if (cap.count()>=3){
                    prefix_path = cap.at(1).trimmed();
                    exec = cap.at(2).trimmed().replace("\\\\ ", " ").replace("\\\\\\\\", "\\");
                    if (cap.count()==4){
                        args = cap.at(3).trimmed();
                    }
                }
            }
        }
    }

    file.close();

#ifdef DEBUG
    qDebug()<<"= [ii] =======================================================";
    qDebug()<<"type: "<<type;
    qDebug()<<"name: "<<name;
    qDebug()<<"path: "<<path;
    qDebug()<<"exec: "<<exec;
    qDebug()<<"args: "<<args;
    qDebug()<<"prefix_path: "<<prefix_path;
    qDebug()<<"icon: "<<icon;
    qDebug()<<"= [ii] =======================================================";
#endif

    QString prefix_name = db_prefix.getName(prefix_path);
#ifdef DEBUG
    qDebug()<<" [ii] Get prefix by path: "<<prefix_path<<" name is: "<<prefix_name;
#endif

    if (prefix_name.isEmpty())
        return;

    if (!db_dir.isExistsByName(prefix_name, "import"))
        if (!db_dir.addDir(prefix_name, "import")){
             qDebug()<<"Cannot create dir:"<<"\"import\""<<" for prefix:"<<prefix_name;
             return;
        }

    if (!db_icon.isExistsByName(prefix_name, "import", name)){
#ifdef DEBUG
        qDebug()<<" [ii] adding icon...";
#endif
        QString res = CoreLib->getSetting("advanced", "defaultDesktopSize", false, "").toString();
        if (db_icon.addIcon(args, exec, icon, "", prefix_name, "import", name, "", "", "", "", path, res)){
#ifdef DEBUG
            qDebug()<<" [ii] adding icon OK.";
#endif
            if (CoreLib->getSetting("DesktopImport", "remove", false, 0)==1){
#ifdef DEBUG
                qDebug()<<"[ii] removed: "<<file.remove();
#else
                file.remove();
#endif
            }

        }
    }


    return;
}
Example #22
0
bool Packer::pack(Apk::File *apk, QString temp)
{
    const QString CONTENTS = QDir::fromNativeSeparators(apk->getDirectory());
    QDir(CONTENTS + "/META-INF").removeRecursively();

    // Save icons:

    emit loading(20, tr("Saving PNG icons..."));
    if (!saveIcons(apk->getIcons())) {
        return false;
    }

    // Clear temporary intermediate files:

    QFile::remove(temp + "/packed/temp.zip");
    QFile::remove(temp + "/packed/temp-1.apk");
    QFile::remove(temp + "/packed/temp-2.apk");
    QFile::remove(temp + "/packed/temp-3.apk");

    // Pack APK:

    if (!apk->getApktool()) {

        // Pack APK (ZIP):

        emit loading(40, tr("Packing APK..."));
        if (!zip(CONTENTS, temp, apk->getRatio())) {
            return false;
        }
    }
    else {

        // Save application name, version and strings:

        emit loading(30, tr("Saving string resources..."));

        if (apk->getVarAppTitle().isEmpty()) {
            saveAppTitle(CONTENTS, apk->getAppTitle());
        }
        saveAppVersion(CONTENTS, apk->getVersionCode(), apk->getVersionName());
        saveStrings(apk->getStrings());

        // Handle Apktool 2.0.3 issue #1122:

        QFile f(CONTENTS + "/apktool.yml");
        if (f.open(QFile::ReadWrite | QFile::Text)) {
            QString output;
            QTextStream stream(&f);
            while(!stream.atEnd()) {
                QString line = stream.readLine();
                if (!line.contains("- ''")) {
                    output.append(line + "\n");
                }
            }
            f.resize(0);
            stream << output;
            f.close();
        }

        // Pack APK (Apktool);

        emit loading(40, tr("Packing APK..."));
        if (!zip(CONTENTS, temp, temp + "/framework/")) {
            return false;
        }
    }

    // Sign APK:

    bool isSigned = false;
    if (apk->getSign()) {
        qDebug() << "Signing...";
        emit loading(60, tr("Signing APK..."));

        isSigned = apk->getKeystore()
        ? sign(temp, apk->getFileKeystore(), apk->getAlias(), apk->getPassKeystore(), apk->getPassAlias())
        : sign(temp, apk->getFilePem(), apk->getFilePk8());
    }
    else {
        isSigned = true;
        QFile::rename(temp + "/packed/temp-1.apk", temp + "/packed/temp-2.apk");
    }

    // Zipalign APK:

    bool isOptimized = false;
    if (apk->getZipalign()) {
        qDebug() << "Optimizing...";
        emit loading(80, tr("Optimizing APK..."));
        isOptimized = zipalign(temp);
    }
    else {
        isOptimized = true;
        QFile::rename(temp + "/packed/temp-2.apk", temp + "/packed/temp-3.apk");
    }

    // Move APK to the destination:

    QString output = apk->getFilePath();
    QFileInfo fi(apk->getFilePath());
    QString suffix = fi.suffix();
    if (suffix.toLower() != "apk") {
        output += ".apk";
    }
    QFile::remove(output);
    if (!QFile::rename(temp + "/packed/temp-3.apk", output)) {
        emit error(tr("Could not create output APK file."));
        return false;
    }

    // Done!

    emit loading(100, tr("APK successfully packed!"));
    qDebug() << "Done.\n";

    if (isSigned && isOptimized) {
        emit packed(apk, tr("APK successfully packed!"));
    }
    else {
        QString warning(tr("APK packed with following warnings:"));
        if (!isSigned) {
            warning += "<br>&bull; " + tr("APK is <b>not signed</b>;");
        }
        if (!isOptimized) {
            warning += "<br>&bull; " + tr("APK is <b>not optimized</b>;");
        }
        if (!isJavaInstalled()) {
            warning += "<hr>" + tr("Signing APK requires Java Runtime Environment.") + "<br>" + Apk::GETJAVA;
        }
        emit packed(apk, warning, false);
    }
    return true;
}
Example #23
0
File: main.cpp Project: volaya/QGIS
// On Android, there there is a libqgis.so instead of a qgis executable.
// The main method symbol of this library needs to be exported so it can be called by java
APP_EXPORT
#endif
int main( int argc, char *argv[] )
{
#ifdef Q_OS_MACX
  // Increase file resource limits (i.e., number of allowed open files)
  // (from code provided by Larry Biehl, Purdue University, USA, from 'MultiSpec' project)
  // This is generally 256 for the soft limit on Mac
  // NOTE: setrlimit() must come *before* initialization of stdio strings,
  //       e.g. before any debug messages, or setrlimit() gets ignored
  // see: http://stackoverflow.com/a/17726104/2865523
  struct rlimit rescLimit;
  if ( getrlimit( RLIMIT_NOFILE, &rescLimit ) == 0 )
  {
    rlim_t oldSoft( rescLimit.rlim_cur );
    rlim_t oldHard( rescLimit.rlim_max );
#ifdef OPEN_MAX
    rlim_t newSoft( OPEN_MAX );
    rlim_t newHard( std::min( oldHard, newSoft ) );
#else
    rlim_t newSoft( 4096 );
    rlim_t newHard( std::min(( rlim_t )8192, oldHard ) );
#endif
    if ( rescLimit.rlim_cur < newSoft )
    {
      rescLimit.rlim_cur = newSoft;
      rescLimit.rlim_max = newHard;

      if ( setrlimit( RLIMIT_NOFILE, &rescLimit ) == 0 )
      {
        QgsDebugMsg( QString( "Mac RLIMIT_NOFILE Soft/Hard NEW: %1 / %2" )
                     .arg( rescLimit.rlim_cur ).arg( rescLimit.rlim_max ) );
      }
    }
    Q_UNUSED( oldSoft ); //avoid warnings
    QgsDebugMsg( QString( "Mac RLIMIT_NOFILE Soft/Hard ORIG: %1 / %2" )
                 .arg( oldSoft ).arg( oldHard ) );
  }
#endif

  QgsDebugMsg( QString( "Starting qgis main" ) );
#ifdef WIN32  // Windows
#ifdef _MSC_VER
  _set_fmode( _O_BINARY );
#else //MinGW
  _fmode = _O_BINARY;
#endif  // _MSC_VER
#endif  // WIN32

  // Set up the custom qWarning/qDebug custom handler
#ifndef ANDROID
  qInstallMsgHandler( myMessageOutput );
#endif

#if (defined(linux) && !defined(ANDROID)) || defined(__FreeBSD__)
  signal( SIGQUIT, qgisCrash );
  signal( SIGILL, qgisCrash );
  signal( SIGFPE, qgisCrash );
  signal( SIGSEGV, qgisCrash );
  signal( SIGBUS, qgisCrash );
  signal( SIGSYS, qgisCrash );
  signal( SIGTRAP, qgisCrash );
  signal( SIGXCPU, qgisCrash );
  signal( SIGXFSZ, qgisCrash );
#endif

#ifdef Q_OS_WIN
  SetUnhandledExceptionFilter( QgisApp::qgisCrashDump );
#endif

  // initialize random number seed
  qsrand( time( nullptr ) );

  /////////////////////////////////////////////////////////////////
  // Command line options 'behaviour' flag setup
  ////////////////////////////////////////////////////////////////

  //
  // Parse the command line arguments, looking to see if the user has asked for any
  // special behaviours. Any remaining non command arguments will be kept aside to
  // be passed as a list of layers and / or a project that should be loaded.
  //

  // This behaviour is used to load the app, snapshot the map,
  // save the image to disk and then exit
  QString mySnapshotFileName = "";
  int mySnapshotWidth = 800;
  int mySnapshotHeight = 600;

  bool myHideSplash = false;
  bool mySkipVersionCheck = false;
#if defined(ANDROID)
  QgsDebugMsg( QString( "Android: Splash hidden" ) );
  myHideSplash = true;
#endif

  bool myRestoreDefaultWindowState = false;
  bool myRestorePlugins = true;
  bool myCustomization = true;

  QString dxfOutputFile;
  QgsDxfExport::SymbologyExport dxfSymbologyMode = QgsDxfExport::SymbolLayerSymbology;
  double dxfScaleDenom = 50000.0;
  QString dxfEncoding = "CP1252";
  QString dxfPreset;
  QgsRectangle dxfExtent;

  // This behaviour will set initial extent of map canvas, but only if
  // there are no command line arguments. This gives a usable map
  // extent when qgis starts with no layers loaded. When layers are
  // loaded, we let the layers define the initial extent.
  QString myInitialExtent = "";
  if ( argc == 1 )
    myInitialExtent = "-1,-1,1,1";

  // This behaviour will allow you to force the use of a translation file
  // which is useful for testing
  QString myTranslationCode;

  // The user can specify a path which will override the default path of custom
  // user settings (~/.qgis) and it will be used for QSettings INI file
  QString configpath;
  QString optionpath;
  QString authdbdirectory;

  QString pythonfile;

  QString customizationfile;

#if defined(ANDROID)
  QgsDebugMsg( QString( "Android: All params stripped" ) );// Param %1" ).arg( argv[0] ) );
  //put all QGIS settings in the same place
  configpath = QgsApplication::qgisSettingsDirPath();
  QgsDebugMsg( QString( "Android: configpath set to %1" ).arg( configpath ) );
#endif

  QStringList args;

  if ( !bundleclicked( argc, argv ) )
  {
    // Build a local QCoreApplication from arguments. This way, arguments are correctly parsed from their native locale
    // It will use QString::fromLocal8Bit( argv ) under Unix and GetCommandLine() under Windows.
    QCoreApplication coreApp( argc, argv );
    args = QCoreApplication::arguments();

    for ( int i = 1; i < args.size(); ++i )
    {
      const QString &arg = args[i];

      if ( arg == "--help" || arg == "-?" )
      {
        usage( args[0].toStdString() );
        return 2;
      }
      else if ( arg == "--nologo" || arg == "-n" )
      {
        myHideSplash = true;
      }
      else if ( arg == "--noversioncheck" || arg == "-V" )
      {
        mySkipVersionCheck = true;
      }
      else if ( arg == "--noplugins" || arg == "-P" )
      {
        myRestorePlugins = false;
      }
      else if ( arg == "--nocustomization" || arg == "-C" )
      {
        myCustomization = false;
      }
      else if ( i + 1 < argc && ( arg == "--snapshot" || arg == "-s" ) )
      {
        mySnapshotFileName = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
      }
      else if ( i + 1 < argc && ( arg == "--width" || arg == "-w" ) )
      {
        mySnapshotWidth = QString( args[++i] ).toInt();
      }
      else if ( i + 1 < argc && ( arg == "--height" || arg == "-h" ) )
      {
        mySnapshotHeight = QString( args[++i] ).toInt();
      }
      else if ( i + 1 < argc && ( arg == "--lang" || arg == "-l" ) )
      {
        myTranslationCode = args[++i];
      }
      else if ( i + 1 < argc && ( arg == "--project" || arg == "-p" ) )
      {
        myProjectFileName = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
      }
      else if ( i + 1 < argc && ( arg == "--extent" || arg == "-e" ) )
      {
        myInitialExtent = args[++i];
      }
      else if ( i + 1 < argc && ( arg == "--optionspath" || arg == "-o" ) )
      {
        optionpath = QDir::toNativeSeparators( QDir( args[++i] ).absolutePath() );
      }
      else if ( i + 1 < argc && ( arg == "--configpath" || arg == "-c" ) )
      {
        configpath = QDir::toNativeSeparators( QDir( args[++i] ).absolutePath() );
      }
      else if ( i + 1 < argc && ( arg == "--authdbdirectory" || arg == "-a" ) )
      {
        authdbdirectory = QDir::toNativeSeparators( QDir( args[++i] ).absolutePath() );
      }
      else if ( i + 1 < argc && ( arg == "--code" || arg == "-f" ) )
      {
        pythonfile = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
      }
      else if ( i + 1 < argc && ( arg == "--customizationfile" || arg == "-z" ) )
      {
        customizationfile = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
      }
      else if ( arg == "--defaultui" || arg == "-d" )
      {
        myRestoreDefaultWindowState = true;
      }
      else if ( arg == "--dxf-export" )
      {
        dxfOutputFile = args[++i];
      }
      else if ( arg == "--dxf-extent" )
      {
        QgsLocaleNumC l;
        QString ext( args[++i] );
        QStringList coords( ext.split( ',' ) );

        if ( coords.size() != 4 )
        {
          std::cerr << "invalid dxf extent " << ext.toStdString() << std::endl;
          return 2;
        }

        for ( int i = 0; i < 4; i++ )
        {
          bool ok;
          double d;

          d = coords[i].toDouble( &ok );
          if ( !ok )
          {
            std::cerr << "invalid dxf coordinate " << coords[i].toStdString() << " in extent " << ext.toStdString() << std::endl;
            return 2;
          }

          switch ( i )
          {
            case 0:
              dxfExtent.setXMinimum( d );
              break;
            case 1:
              dxfExtent.setYMinimum( d );
              break;
            case 2:
              dxfExtent.setXMaximum( d );
              break;
            case 3:
              dxfExtent.setYMaximum( d );
              break;
          }
        }
      }
      else if ( arg == "--dxf-symbology-mode" )
      {
        QString mode( args[++i] );
        if ( mode == "none" )
        {
          dxfSymbologyMode = QgsDxfExport::NoSymbology;
        }
        else if ( mode == "symbollayer" )
        {
          dxfSymbologyMode = QgsDxfExport::SymbolLayerSymbology;
        }
        else if ( mode == "feature" )
        {
          dxfSymbologyMode = QgsDxfExport::FeatureSymbology;
        }
        else
        {
          std::cerr << "invalid dxf symbology mode " << mode.toStdString() << std::endl;
          return 2;
        }
      }
      else if ( arg == "--dxf-scale-denom" )
      {
        bool ok;
        QString scale( args[++i] );
        dxfScaleDenom = scale.toDouble( &ok );
        if ( !ok )
        {
          std::cerr << "invalid dxf scale " << scale.toStdString() << std::endl;
          return 2;
        }
      }
      else if ( arg == "--dxf-encoding" )
      {
        dxfEncoding = args[++i];
      }
      else if ( arg == "--dxf-preset" )
      {
        dxfPreset = args[++i];
      }
      else if ( arg == "--" )
      {
        for ( i++; i < args.size(); ++i )
          myFileList.append( QDir::toNativeSeparators( QFileInfo( args[i] ).absoluteFilePath() ) );
      }
      else
      {
        myFileList.append( QDir::toNativeSeparators( QFileInfo( args[i] ).absoluteFilePath() ) );
      }
    }
  }

  /////////////////////////////////////////////////////////////////////
  // If no --project was specified, parse the args to look for a     //
  // .qgs file and set myProjectFileName to it. This allows loading  //
  // of a project file by clicking on it in various desktop managers //
  // where an appropriate mime-type has been set up.                 //
  /////////////////////////////////////////////////////////////////////
  if ( myProjectFileName.isEmpty() )
  {
    // check for a .qgs
    for ( int i = 0; i < args.size(); i++ )
    {
      QString arg = QDir::toNativeSeparators( QFileInfo( args[i] ).absoluteFilePath() );
      if ( arg.contains( ".qgs" ) )
      {
        myProjectFileName = arg;
        break;
      }
    }
  }


  /////////////////////////////////////////////////////////////////////
  // Now we have the handlers for the different behaviours...
  ////////////////////////////////////////////////////////////////////

  /////////////////////////////////////////////////////////////////////
  // Initialise the application and the translation stuff
  /////////////////////////////////////////////////////////////////////

#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) && !defined(ANDROID)
  bool myUseGuiFlag = nullptr != getenv( "DISPLAY" );
#else
  bool myUseGuiFlag = true;
#endif
  if ( !myUseGuiFlag )
  {
    std::cerr << QObject::tr(
                "QGIS starting in non-interactive mode not supported.\n"
                "You are seeing this message most likely because you "
                "have no DISPLAY environment variable set.\n"
              ).toUtf8().constData();
    exit( 1 ); //exit for now until a version of qgis is capabable of running non interactive
  }

  if ( !optionpath.isEmpty() || !configpath.isEmpty() )
  {
    // tell QSettings to use INI format and save the file in custom config path
    QSettings::setDefaultFormat( QSettings::IniFormat );
    QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, optionpath.isEmpty() ? configpath : optionpath );
  }

  // GUI customization is enabled according to settings (loaded when instance is created)
  // we force disabled here if --nocustomization argument is used
  if ( !myCustomization )
  {
    QgsCustomization::instance()->setEnabled( false );
  }

  QgsApplication myApp( argc, argv, myUseGuiFlag, configpath );

  myApp.setWindowIcon( QIcon( QgsApplication::appIconPath() ) );

  //
  // Set up the QSettings environment must be done after qapp is created
  QCoreApplication::setOrganizationName( QgsApplication::QGIS_ORGANIZATION_NAME );
  QCoreApplication::setOrganizationDomain( QgsApplication::QGIS_ORGANIZATION_DOMAIN );
  QCoreApplication::setApplicationName( QgsApplication::QGIS_APPLICATION_NAME );
  QCoreApplication::setAttribute( Qt::AA_DontShowIconsInMenus, false );

  QSettings* customizationsettings;
  if ( !optionpath.isEmpty() || !configpath.isEmpty() )
  {
    // tell QSettings to use INI format and save the file in custom config path
    QSettings::setDefaultFormat( QSettings::IniFormat );
    QString path = optionpath.isEmpty() ? configpath : optionpath;
    QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, path );
    customizationsettings = new QSettings( QSettings::IniFormat, QSettings::UserScope, "QGIS", "QGISCUSTOMIZATION2" );
  }
  else
  {
    customizationsettings = new QSettings( "QGIS", "QGISCUSTOMIZATION2" );
  }

  // Using the customizationfile option always overrides the option and config path options.
  if ( !customizationfile.isEmpty() )
  {
    customizationsettings = new QSettings( customizationfile, QSettings::IniFormat );
    QgsCustomization::instance()->setEnabled( true );
  }

  // Load and set possible default customization, must be done afterQgsApplication init and QSettings ( QCoreApplication ) init
  QgsCustomization::instance()->setSettings( customizationsettings );
  QgsCustomization::instance()->loadDefault();

#ifdef Q_OS_MACX
  // If the GDAL plugins are bundled with the application and GDAL_DRIVER_PATH
  // is not already defined, use the GDAL plugins in the application bundle.
  QString gdalPlugins( QCoreApplication::applicationDirPath().append( "/lib/gdalplugins" ) );
  if ( QFile::exists( gdalPlugins ) && !getenv( "GDAL_DRIVER_PATH" ) )
  {
    setenv( "GDAL_DRIVER_PATH", gdalPlugins.toUtf8(), 1 );
  }

  // Point GDAL_DATA at any GDAL share directory embedded in the app bundle
  if ( !getenv( "GDAL_DATA" ) )
  {
    QStringList gdalShares;
    QString appResources( QDir::cleanPath( QgsApplication::pkgDataPath() ) );
    gdalShares << QCoreApplication::applicationDirPath().append( "/share/gdal" )
    << appResources.append( "/share/gdal" )
    << appResources.append( "/gdal" );
    Q_FOREACH ( const QString& gdalShare, gdalShares )
    {
      if ( QFile::exists( gdalShare ) )
      {
        setenv( "GDAL_DATA", gdalShare.toUtf8().constData(), 1 );
        break;
      }
    }
  }
Example #24
0
void MiningPage::readProcessOutput()
{
    QByteArray output;

    minerProcess->reset();

    output = minerProcess->readAll();

    QString outputString(output);

    if (!outputString.isEmpty())
    {
        QStringList list = outputString.split("\n", QString::SkipEmptyParts);
        int i;
        for (i=0; i<list.size(); i++)
        {
            QString line = list.at(i);

            // Ignore protocol dump
            if (!line.startsWith("[") || line.contains("JSON protocol") || line.contains("HTTP hdr"))
                continue;

            if (ui->debugCheckBox->isChecked())
            {
                ui->list->addItem(line.trimmed());
                ui->list->scrollToBottom();
            }

            if (line.contains("(yay!!!)"))
                reportToList("Share accepted", SHARE_SUCCESS, getTime(line));
            else if (line.contains("(booooo)"))
                reportToList("Share rejected", SHARE_FAIL, getTime(line));
            else if (line.contains("LONGPOLL detected new block"))
                reportToList("LONGPOLL detected a new block", LONGPOLL, getTime(line));
            else if (line.contains("Supported options:"))
                reportToList("Miner didn't start properly. Try checking your settings.", ERROR, NULL);
            else if (line.contains("The requested URL returned error: 403"))
                reportToList("Couldn't connect. Please check your username and password.", ERROR, NULL);
            else if (line.contains("HTTP request failed"))
                reportToList("Couldn't connect. Please check pool server and port.", ERROR, NULL);
            else if (line.contains("JSON-RPC call failed"))
                reportToList("Couldn't communicate with server. Retrying in 30 seconds.", ERROR, NULL);
            else if (line.contains("thread ") && line.contains("khash/s"))
            {
                QString threadIDstr = line.at(line.indexOf("thread ")+7);
                int threadID = threadIDstr.toInt();

                int threadSpeedindx = line.indexOf(",");
                QString threadSpeedstr = line.mid(threadSpeedindx);
                threadSpeedstr.chop(8);
                threadSpeedstr.remove(", ");
                threadSpeedstr.remove(" ");
                threadSpeedstr.remove('\n');
                double speed=0;
                speed = threadSpeedstr.toDouble();

                threadSpeed[threadID] = speed;

                updateSpeed();
            }
        }
    }
}
Example #25
0
/**Provide access to the data through the defined QAbstractItemModel definition.
   The index parameter defines how to access the corresponded data while the role
   define the kind of information desired from RepoModel. This method will be queried
   from QView in order to populate the view.

   From the index.internalPointer the RepoModel will have access to the path,
   which uniquely define its entry on ScriptRepository.

   The RepoModel defines 4 columns:
    - Path
    - Status
    - AutoUpdate
    - Delete

   The path, provides the name of the file. The status, give information on the ScriptRepository
   entries. Currently, an entry may be found on the following states:
     - LOCAL_ONLY: The file only exists locally.
     - REMTOE_ONLY: The file has not been downloaded.
     - REMOTE_CHANGED: A new version of the file is available.
     - LOCAL_CHANGED: The file has been changed from the original one.
     - BOTH_CHANGED: Locally and remotelly changed.
     - UPDATED: The remote and local file are identical.

   The AutoUpdate allow to flag the entries to receive the updates automatically when new files
   are available at the central repository.

   The delete column will return a string "protected" or "deletable" that will be used to know if it
   can be deleted or not. For the current version, folders are protected, and files are deletable.

   The repomodel will react to the following roles:
     - DisplayRole: to provide the main information.
     - DecorationRole: to provide icons to make easier and fancier to identify the files and folders.
     - ToolTipRole: to provide user help to interact with this class.
 */
QVariant RepoModel::data(const QModelIndex &index, int role) const
{
    using namespace Mantid::API;
    if (!index.isValid())
        return QVariant();
    RepoItem *item = static_cast<RepoItem*>(index.internalPointer());
    try {
        QString path = item->path();
        Mantid::API::ScriptInfo inf ;
        Mantid::API::SCRIPTSTATUS status;
        // return the data for the display role
        if (role == Qt::DisplayRole) {
            switch(index.column()) {
            case 0: // return the label (the path of the file/folder)
                return item->label();
                break;
            case 1: // ask for the status
                if (isDownloading(index))
                    return downloadSt();
                if (isUploading(index))
                    return uploadSt();
                status = repo_ptr->fileStatus(path.toStdString());
                return fromStatus(status);
                break;
            case 2:// autoupdate option
                status = repo_ptr->fileStatus(path.toStdString());
                if (status == REMOTE_ONLY || status == LOCAL_ONLY)
                    return QVariant();
                inf = repo_ptr->fileInfo(path.toStdString());
                return inf.auto_update?QString("true"):QString("false");
                break;
            case 3:// delete action
                inf = repo_ptr->fileInfo(path.toStdString());
                if (inf.directory)
                    return PROTECTEDENTRY;
                status = repo_ptr->fileStatus(path.toStdString());
                if (!(status == LOCAL_CHANGED || status == BOTH_UNCHANGED))
                    return PROTECTEDENTRY;
                return DELETABLEENTRY;
                break;
            }
        }

        // return the data for the DecorationRole
        if (role == Qt::DecorationRole) {
            if (index.column() == 0) {
                inf = repo_ptr->fileInfo(path.toStdString());
                if (inf.directory) {
                    status = repo_ptr->fileStatus(path.toStdString());
                    if (status == Mantid::API::REMOTE_ONLY)
                        return QIcon::fromTheme("folder-remote",QIcon(QPixmap(":/win/folder-remote")));
                    else
                        return QIcon::fromTheme("folder", QIcon(QPixmap(":/win/folder")));
                }
                else {
                    int pos = QString(path).lastIndexOf('.');
                    if (pos < 0)
                        return QIcon::fromTheme("unknown", QIcon(QPixmap(":/win/unknown")));
                    if (path.contains("readme",Qt::CaseInsensitive))
                        return QIcon::fromTheme("text-x-readme", QIcon(QPixmap(":/win/txt_file.png")));

                    QString extension = QString(path).remove(0,pos);
                    if (extension == ".cpp" || extension == ".CPP" || extension == ".c" || extension == ".C")
                        return QIcon::fromTheme("text-x-c++", QIcon(QPixmap(":/win/unknown")));
                    else if (extension == ".py" || extension == ".PY")
                        return QIcon::fromTheme("text-x-python", QIcon(QPixmap(":/win/text-x-python")));
                    else if (extension == ".ui")
                        return QIcon::fromTheme("document", QIcon(QPixmap(":/win/document")));
                    else if (extension == ".docx" || extension == ".doc" || extension == ".odf")
                        return QIcon::fromTheme("x-office-document", QIcon(QPixmap(":/win/office-document")));
                    else if (extension == ".pdf")
                        return QIcon::fromTheme("application-pdf", QIcon(QPixmap(":/win/file_pdf")));
                    else
                        return QIcon::fromTheme("unknown", QIcon(QPixmap(":/win/unknown")));
                }
            }
        }// end decorationRole

        // tool tip role
        if (role == Qt::ToolTipRole) {
            if (index.column() == 1) {
                if (isDownloading(index))
                    return "Downloading... Be patient.";
                if (isUploading(index))
                    return "Uploading... Be patient.";
                status = repo_ptr->fileStatus(path.toStdString());
                inf = repo_ptr->fileInfo(path.toStdString());
                switch(status) {

                case REMOTE_ONLY:
                    return (inf.directory)?"Click here to download this folder and all its files"
                           :"Click here to download this file";
                    break;
                case BOTH_UNCHANGED:
                    return (inf.directory)? "This folder is up-to-date" : "This file is up-to-date";
                    break;
                case LOCAL_CHANGED:
                    return "Click here to publish your changes";
                case REMOTE_CHANGED:
                case BOTH_CHANGED:
                    return (inf.directory)?
                           "There is a new version of the files inside this folder. Click here to install them.":
                           "There is a new version of this file available. Click here to install it.";
                    break;
                case LOCAL_ONLY:
                    return "Click here to share this file with the Mantid community!";

                }
            } else if (index.column() == 2) {
                return "Enable or disable this item to be downloaded automatically when new versions will be available";
            } else if (index.column() == 3) {
                if (isUploading(index))
                    return "Connection busy... Be patient.";
                inf = repo_ptr->fileInfo(path.toStdString());
                if (inf.directory)
                    return QVariant();
                status = repo_ptr->fileStatus(path.toStdString());
                if (!(status == LOCAL_CHANGED || status == BOTH_UNCHANGED))
                    return QVariant();
                return "Click here to delete this file from the Central Repository";
            }
        }// end tool tip
    } catch(Mantid::API::ScriptRepoException & ex) {
        handleExceptions(ex,"",false);
    }
    return QVariant();
}
Example #26
0
/**
 * \addtogroup myth_network_protocol
 * \par        QUERY_FILE_EXISTS \e storagegroup \e filename
 */
bool FileServerHandler::HandleQueryFileExists(SocketHandler *socket,
                                              QStringList &slist)
{
    QString storageGroup = "Default";
    QStringList res;

    if (slist.size() == 3)
    {
        if (!slist[2].isEmpty())
            storageGroup = slist[2];
    }
    else if (slist.size() != 2)
        return false;

    QString filename = slist[1];
    if ((filename.isEmpty()) || 
        (filename.contains("/../")) || 
        (filename.startsWith("../")))
    {
        LOG(VB_GENERAL, LOG_ERR, 
            QString("ERROR checking for file, filename '%1' "
                    "fails sanity checks").arg(filename));
        res << "";
        socket->SendStringList(res);
        return true;
    }

    StorageGroup sgroup(storageGroup, gCoreContext->GetHostName());
    QString fullname = sgroup.FindFile(filename);

    if (!fullname.isEmpty())
    {
        res << "1"
            << fullname;

        // TODO: convert me to QFile
        struct stat fileinfo;
        if (stat(fullname.toLocal8Bit().constData(), &fileinfo) >= 0)
        {
            res << QString::number(fileinfo.st_dev)
                << QString::number(fileinfo.st_ino)
                << QString::number(fileinfo.st_mode)
                << QString::number(fileinfo.st_nlink)
                << QString::number(fileinfo.st_uid)
                << QString::number(fileinfo.st_gid)
                << QString::number(fileinfo.st_rdev)
                << QString::number(fileinfo.st_size)
#ifdef USING_MINGW
                << "0"
                << "0"
#else
                << QString::number(fileinfo.st_blksize)
                << QString::number(fileinfo.st_blocks)
#endif
                << QString::number(fileinfo.st_atime)
                << QString::number(fileinfo.st_mtime)
                << QString::number(fileinfo.st_ctime);
        }
    }
    else
        res << "0";

    socket->SendStringList(res);
    return true;
}
Example #27
0
void PageParser::findTextOnPage(QString pageContent, QString text)
{
    textFound = pageContent.contains(text);
}
//---------------------------------------------------------------------
// TODO factor code out of here and into its own class for loading and
//      saving PLY files (additional code in stereo/multiviewstereo.cpp)
//
void MainWindow::on_actionView_PLY_File_triggered() {
	QString initialDir = userSettings.contains("InitialPLYDir")
	                     ? userSettings.value("InitialPLYDir").toString()
	                     : QDir::homePath();

	// TODO sheets would be nice for Mac users :)
	QString fname = QFileDialog::getOpenFileName(this,
	                                             tr("Open File"),
	                                             initialDir,
	                                             "PLY Files (*.ply)");

	if(!fname.isNull()) {
		QFile file(fname);
		if(file.open(QFile::ReadOnly)) {
			userSettings.setValue("InitialPLYDir", QDir(fname).absolutePath());

			QTextStream textStream(&file);

			// For now we'll ignore the header and assume a certain format
			QString line;
			bool hasNormal = false;
			bool hasColor = false;
			bool isBinary = false;

			unsigned int numVertices = 0;
			unsigned int numFaces = 0;

			static QRegExp typeTest("n[xyz]");
			static QRegExp normalTest("n[xyz]");
			static QRegExp colorTest("diffuse_(red|blue|green)");
			static QRegExp elementTest("element (vertex|face) (\\d+)");

			while((line = textStream.readLine().trimmed()) != "end_header") {
				if(line.startsWith("property")) {
					if( line.contains(normalTest) )
						hasNormal = true;

					if( line.contains(colorTest) )
						hasColor = true;
				} else if(elementTest.indexIn(line) != -1) {
					if(elementTest.cap(1) == "face")
						numFaces = elementTest.cap(2).toUInt();
					else if(elementTest.cap(1) == "vertex")
						numVertices = elementTest.cap(2).toUInt();
				} else if(line.startsWith("format")) {
					isBinary = line.contains("binary");
				}
			}

			QDataStream dataStream;
			if(isBinary) {
				qint64 pos = textStream.pos();
				file.close();
				file.open(QFile::ReadOnly);
				dataStream.setDevice(&file);
				dataStream.skipRawData(pos);
			}

			//
			// Read in the verticies
			//
			GLfloat d[9] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
			std::vector<GLfloat> vertices(numVertices * 9);
			std::vector<GLfloat>::iterator vertexIter = vertices.begin();
			if(isBinary) {
				uint len = 12 + (hasNormal ? 12 : 0) + (hasColor ? 3 : 0);

				// TODO more efficient to read in larger chunk of data
				for(unsigned int vertex = 0; vertex < numVertices && !textStream.atEnd(); ++vertex) {
					dataStream.readRawData(reinterpret_cast<char *>(d), len);
					if(!hasNormal)
						d[3] = d[4] = d[5] = 0;

					if(!hasColor)
						d[6] = d[7] = d[8] = 1;

					if(dataStream.status() != QDataStream::ReadPastEnd)
						vertexIter = std::copy(d, d + 9, vertexIter);
				}
			} else {
				for(unsigned int vertex = 0; vertex < numVertices && !textStream.atEnd(); ++vertex) {
					textStream >> d[0] >> d[1] >> d[2];
					if(hasNormal)
						textStream >> d[3] >> d[4] >> d[5];
					else
						d[3] = d[4] = d[5] = 0.0f;

					if(hasColor) {
						textStream >> d[6] >> d[7] >> d[8];
						d[6] /= 255.0;
						d[7] /= 255.0;
						d[8] /= 255.0;
					} else {
						d[6] = d[7] = d[8] = 0.5f;
						//d[6] = qrand() / (1.0*RAND_MAX);
						//d[7] = qrand() / (1.0*RAND_MAX);
						//d[8] = qrand() / (1.0*RAND_MAX);
					}

					if(textStream.status() != QTextStream::ReadPastEnd)
						vertexIter = std::copy(d, d + 9, vertexIter);

					textStream.readLine();
				}
Example #29
0
bool FileServerHandler::HandleAnnounce(MythSocket *socket,
                  QStringList &commands, QStringList &slist)
{
    if (commands[1] == "FileServer")
    {
        if (slist.size() >= 3)
        {
            SocketHandler *handler =
                new SocketHandler(socket, m_parent, commands[2]);

            handler->BlockShutdown(true);
            handler->AllowStandardEvents(true);
            handler->AllowSystemEvents(true);

            QWriteLocker wlock(&m_fsLock);
            m_fsMap.insert(commands[2], handler);
            m_parent->AddSocketHandler(handler);

            slist.clear();
            slist << "OK";
            handler->SendStringList(slist);
            return true;
        }
        return false;
    }

    if (commands[1] != "FileTransfer")
        return false;

    if (slist.size() < 3)
        return false;

    if ((commands.size() < 3) || (commands.size() > 6))
        return false;

    FileTransfer *ft    = NULL;
    QString hostname    = "";
    QString filename    = "";
    bool writemode      = false;
    bool usereadahead   = true;
    int timeout_ms      = 2000;
    switch (commands.size())
    {
      case 6:
        timeout_ms      = commands[5].toInt();
      case 5:
        usereadahead    = commands[4].toInt();
      case 4:
        writemode       = commands[3].toInt();
      default:
        hostname        = commands[2];
    }

    QStringList::const_iterator it = slist.begin();
    QUrl qurl           = *(++it);
    QString wantgroup   = *(++it);

    QStringList checkfiles;
    while (++it != slist.end())
        checkfiles += *(it);

    slist.clear();

    LOG(VB_GENERAL, LOG_DEBUG, "FileServerHandler::HandleAnnounce");
    LOG(VB_GENERAL, LOG_INFO, QString("adding: %1 as remote file transfer")
                            .arg(hostname));

    if (writemode)
    {
        if (wantgroup.isEmpty())
            wantgroup = "Default";

        StorageGroup sgroup(wantgroup, gCoreContext->GetHostName(), false);
        QString dir = sgroup.FindNextDirMostFree();
        if (dir.isEmpty())
        {
            LOG(VB_GENERAL, LOG_ERR, "Unable to determine directory "
                    "to write to in FileTransfer write command");

            slist << "ERROR" << "filetransfer_directory_not_found";
            socket->writeStringList(slist);
            return true;
        }

        QString basename = qurl.path();
        if (basename.isEmpty())
        {
            LOG(VB_GENERAL, LOG_ERR, QString("FileTransfer write "
                    "filename is empty in url '%1'.")
                    .arg(qurl.toString()));

            slist << "ERROR" << "filetransfer_filename_empty";
            socket->writeStringList(slist);
            return true;
        }

        if ((basename.contains("/../")) ||
            (basename.startsWith("../")))
        {
            LOG(VB_GENERAL, LOG_ERR, QString("FileTransfer write "
                    "filename '%1' does not pass sanity checks.")
                    .arg(basename));

            slist << "ERROR" << "filetransfer_filename_dangerous";
            socket->writeStringList(slist);
            return true;
        }

        filename = dir + "/" + basename;
    }
    else
        filename = LocalFilePath(qurl, wantgroup);

    QFileInfo finfo(filename);
    if (finfo.isDir())
    {
        LOG(VB_GENERAL, LOG_ERR, QString("FileTransfer filename "
                "'%1' is actually a directory, cannot transfer.")
                .arg(filename));

        slist << "ERROR" << "filetransfer_filename_is_a_directory";
        socket->writeStringList(slist);
        return true;
    }

    if (writemode)
    {
        QString dirPath = finfo.absolutePath();
        QDir qdir(dirPath);
        if (!qdir.exists())
        {
            if (!qdir.mkpath(dirPath))
            {
                LOG(VB_GENERAL, LOG_ERR, QString("FileTransfer "
                        "filename '%1' is in a subdirectory which does "
                        "not exist, but can not be created.")
                        .arg(filename));

                slist << "ERROR" << "filetransfer_unable_to_create_subdirectory";
                socket->writeStringList(slist);
                return true;
            }
        }

        ft = new FileTransfer(filename, socket, m_parent, writemode);
    }
    else
        ft = new FileTransfer(filename, socket, m_parent, usereadahead, timeout_ms);

    ft->BlockShutdown(true);

    {
        QWriteLocker wlock(&m_ftLock);
        m_ftMap.insert(socket->socket(), ft);
    }

    slist << "OK"
          << QString::number(socket->socket())
          << QString::number(ft->GetFileSize());

    if (checkfiles.size())
    {
        QFileInfo fi(filename);
        QDir dir = fi.absoluteDir();
        for (it = checkfiles.begin(); it != checkfiles.end(); ++it)
        {
            if (dir.exists(*it) &&
                QFileInfo(dir, *it).size() >= kReadTestSize)
                    slist << *it;
        }
    }

    socket->writeStringList(slist);
    m_parent->AddSocketHandler(ft);
    return true;
}
Example #30
-1
bool FileServerHandler::HandleDownloadFile(SocketHandler *socket,
                                           QStringList &slist)
{
    QStringList res;

    if (slist.size() != 4)
    {
        res << "ERROR" << QString("Bad %1 command").arg(slist[0]);
        socket->SendStringList(res);
        return true;
    }

    bool synchronous = (slist[0] == "DOWNLOAD_FILE_NOW");
    QString srcURL = slist[1];
    QString storageGroup = slist[2];
    QString filename = slist[3];
    StorageGroup sgroup(storageGroup, gCoreContext->GetHostName(), false);
    QString outDir = sgroup.FindNextDirMostFree();
    QString outFile;
    QStringList retlist;

    if (filename.isEmpty())
    {
        QFileInfo finfo(srcURL);
        filename = finfo.fileName();
    }

    if (outDir.isEmpty())
    {
        LOG(VB_GENERAL, LOG_ERR, QString("Unable to determine directory "
                "to write to in %1 write command").arg(slist[0]));
        res << "ERROR" << "downloadfile_directory_not_found";
        socket->SendStringList(res);
        return true;
    }

    if ((filename.contains("/../")) ||
        (filename.startsWith("../")))
    {
        LOG(VB_GENERAL, LOG_ERR, QString("ERROR: %1 write "
                "filename '%2' does not pass sanity checks.")
                .arg(slist[0]).arg(filename));
        res << "ERROR" << "downloadfile_filename_dangerous";
        socket->SendStringList(res);
        return true;
    }

    outFile = outDir + "/" + filename;

    if (synchronous)
    {
        if (GetMythDownloadManager()->download(srcURL, outFile))
        {
            res << "OK"
                << gCoreContext->GetMasterHostPrefix(storageGroup)
                       + filename;
        }
        else
            res << "ERROR";
    }
    else
    {
        QMutexLocker locker(&m_downloadURLsLock);
        m_downloadURLs[outFile] =
            gCoreContext->GetMasterHostPrefix(storageGroup) +
            StorageGroup::GetRelativePathname(outFile);

        GetMythDownloadManager()->queueDownload(srcURL, outFile, this);
        res << "OK"
            << gCoreContext->GetMasterHostPrefix(storageGroup) + filename;
    }

    socket->SendStringList(res);
    return true;
}