Example #1
0
const QString Move::saveMove(bool isRoot)
{
	QString str;
	
	if (!isRoot)
		str += ";"; //"\n;";
	
	if (x != -1 && y != -1 && gameMode != modeEdit)
	{
		// Write something like 'B[aa]'
		str += stoneColor == stoneBlack ? "B" : "W";
 		str += "[" + Matrix::coordsToString(x-1, y-1) + "]";
	}
	
	// Save edited moves
	str += matrix->saveEditedMoves(parent != NULL ? parent->getMatrix() : 0);
	
	// Save marks
	str += matrix->saveMarks();
	
	// Add nodename, if we have one
	if (!nodeName.isNull() && !nodeName.isEmpty())
	{
		// simpletext
		str += "N[";
		str += nodeName;
		str += "]";
	}

	// Add next move's color
	if (PLinfo)
	{
		if (PLnextMove == stoneBlack)
			str += "PL[B]";
		else
			str += "PL[W]";
	}

	// Add comment, if we have one
	if (!comment.isNull() && !comment.isEmpty())
	{
		// text
		QString tmp = comment;
		int pos = 0;
		while ((pos = tmp.find("]", pos)) != -1 && static_cast<unsigned int>(pos) < tmp.length())
		{
			tmp.replace(pos, 1, "\\]");
			pos += 2;
		}
		str += "C[";
		str += tmp;
		str += "]";
	}

	// time info
	if (timeinfo && !isRoot && (int) timeLeft)
	{
		if (stoneColor == stoneBlack)
			str += "BL[";
		else
			str += "WL[";
		str += QString::number(timeLeft);
		str += "]";

		// open moves info
		if (openMoves > 0)
		{
			if (stoneColor == stoneBlack)
				str += "OB[";
			else
				str += "OW[";
			str += QString::number(openMoves);
			str += "]";
		}
	}

	// Add unknown properties, if we have some
	if (!unknownProperty.isNull() && !unknownProperty.isEmpty())
	{
		// complete property
		str += unknownProperty;
	}
	
	return str;
}
void FileTransferDlgNotify::createFile(const QString &name, unsigned size, bool bCanResume)
{
    m_name = name;
    m_size = size;
    m_name = m_name.replace('\\', '/');


    FileTransfer *ft = m_dlg->m_msg->m_transfer;
    int n = m_name.lastIndexOf('/');
    if (n >= 0)
    {
        QString path;
        QString p(m_name.left(n));
        m_fn = m_name.right(m_name.length()-n);
        m_fn = m_fn.replace(QRegExp("/"), "");

        while (!p.isEmpty())
        {
            QString pp = getToken(p, '/');
            if (!path.isEmpty())
                path += '/';
            if (pp == "..")
            {
                QString errMsg = i18n("Bad path: %1") .arg(m_name);
                m_dlg->m_msg->setError(errMsg);
                ft->setError();
                return;
            }
            path += pp;
            QDir dd(ft->dir() /* + '/' + path */);
            QDir d(ft->dir());
            if (dd.exists() || d.mkdir(path))
                continue;

            QString errMsg = i18n("Can't create: %1") .arg(path);
            m_dlg->m_msg->setError(errMsg);
            ft->setError();
            return;
        }
    }
    m_dlg->m_msg->addFile(m_name, size);
    if (m_name.isEmpty() || m_name[(int)(m_name.length() - 1)] == '/')
    {
        ft->startReceive(0);
        return;
    }

    QString shortName = m_name;
    //m_name = ft->dir() + m_name; Quickfix, noragen
    if (m_fn.isEmpty())
        m_fn=m_name;

    m_name = ft->dir() + m_fn;

    if (ft->m_file)
        delete ft->m_file;
    m_dlg->process();
    ft->m_file = new QFile(m_name);
    if (!ft->m_file->exists())
    {
        if (ft->m_file->open(QIODevice::WriteOnly))
        {
            ft->startReceive(0);
            return;
        }
    }
    else switch (ft->overwrite())
        {
        case Skip:
            skip();
            return;
        case Replace:
            if (ft->m_file->open(QIODevice::WriteOnly | QIODevice::Truncate))
            {
                ft->startReceive(0);
                return;
            }
            break;
        case Resume:
            if (ft->m_file->open(QIODevice::WriteOnly | QIODevice::Append))
            {
                resume();
                return;
            }
            break;
        default:
            if (ft->m_file->open(QIODevice::WriteOnly | QIODevice::Append))
            {
                QStringList buttons;
                QString forAll;
                if (ft->files())
                    forAll = i18n("For all files");
                buttons.append(i18n("&Replace"));
                buttons.append(i18n("&Skip"));
                if (bCanResume && (ft->m_file->size() < size))
                    buttons.append(i18n("Resu&me"));
                m_dlg->m_ask = new BalloonMsg(NULL, quoteString(i18n("File %1 exists") .arg(shortName)),
                                              buttons, m_dlg->lblState, NULL, false, true, 150, forAll);
                QObject::connect(m_dlg->m_ask, SIGNAL(action(int, void*)), m_dlg, SLOT(action(int, void*)));
                raiseWindow(m_dlg);
                m_dlg->m_ask->show();
                return;
            }
        }
Example #3
0
void QgsLocator::fetchResults( const QString &string, const QgsLocatorContext &context, QgsFeedback *feedback )
{
  // ideally this should not be required, as well behaved callers
  // will NOT fire up a new fetchResults call while an existing one is
  // operating/waiting to be canceled...
  cancelRunningQuery();

  // if no feedback object was passed, create one that is owned by this object
  // to ensure that filters ALWAYS receive a valid feedback
  if ( !feedback )
  {
    mOwnedFeedback.reset( new QgsFeedback() );
    feedback = mOwnedFeedback.get();
  }
  else
  {
    mOwnedFeedback.reset( nullptr );
  }
  mFeedback = feedback;

  QList< QgsLocatorFilter * > activeFilters;
  QString searchString = string;
  if ( searchString.indexOf( ' ' ) > 0 )
  {
    QString prefix = searchString.left( searchString.indexOf( ' ' ) );
    if ( mPrefixedFilters.contains( prefix ) && mPrefixedFilters.value( prefix )->enabled() )
    {
      activeFilters << mPrefixedFilters.value( prefix );
      searchString = searchString.mid( prefix.length() + 1 );
    }
  }
  if ( activeFilters.isEmpty() )
  {
    for ( QgsLocatorFilter *filter : qgis::as_const( mFilters ) )
    {
      if ( filter->useWithoutPrefix() && filter->enabled() )
        activeFilters << filter;
    }
  }

  QList< QgsLocatorFilter *> threadedFilters;
  for ( QgsLocatorFilter *filter : qgis::as_const( activeFilters ) )
  {
    std::unique_ptr< QgsLocatorFilter > clone( filter->clone() );
    connect( clone.get(), &QgsLocatorFilter::resultFetched, clone.get(), [this, filter]( QgsLocatorResult result )
    {
      result.filter = filter;
      emit filterSentResult( result );
    } );
    clone->prepare( searchString, context );

    if ( clone->flags() & QgsLocatorFilter::FlagFast )
    {
      // filter is fast enough to fetch results on the main thread
      clone->fetchResults( searchString, context, feedback );
    }
    else
    {
      // run filter in background
      threadedFilters.append( clone.release() );
    }
  }

  mActiveThreads.clear();
  for ( QgsLocatorFilter *filter : qgis::as_const( threadedFilters ) )
  {
    QThread *thread = new QThread();
    mActiveThreads.append( thread );
    filter->moveToThread( thread );
    connect( thread, &QThread::started, filter, [filter, searchString, context, feedback]
    {
      if ( !feedback->isCanceled() )
        filter->fetchResults( searchString, context, feedback );
      filter->emit finished();
    }, Qt::QueuedConnection );
    connect( filter, &QgsLocatorFilter::finished, thread, &QThread::quit );
    connect( filter, &QgsLocatorFilter::finished, filter, &QgsLocatorFilter::deleteLater );
    connect( thread, &QThread::finished, thread, [this, thread]
    {
      mActiveThreads.removeAll( thread );
      if ( mActiveThreads.empty() )
        emit finished();
    } );
    connect( thread, &QThread::finished, thread, &QThread::deleteLater );
    thread->start();
  }

  if ( mActiveThreads.empty() )
    emit finished();
}
Example #4
0
static void recodeAndAppend(QString &to, const QString &input,
                            QUrl::ComponentFormattingOptions encoding, const ushort *tableModifications)
{
    if (!qt_urlRecode(to, input.constData(), input.constData() + input.length(), encoding, tableModifications))
        to += input;
}
QString QStandardPaths::writableLocation(StandardLocation type)
{
    switch (type) {
    case HomeLocation:
        return QDir::homePath();
    case TempLocation:
        return QDir::tempPath();
    case CacheLocation:
    case GenericCacheLocation:
    {
        // http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html
        QString xdgCacheHome = QFile::decodeName(qgetenv("XDG_CACHE_HOME"));
        if (isTestModeEnabled())
            xdgCacheHome = QDir::homePath() + QLatin1String("/.qttest/cache");
        if (xdgCacheHome.isEmpty())
            xdgCacheHome = QDir::homePath() + QLatin1String("/.cache");
        if (type == QStandardPaths::CacheLocation)
            appendOrganizationAndApp(xdgCacheHome);
        return xdgCacheHome;
    }
    case DataLocation:
    case GenericDataLocation:
    {
        QString xdgDataHome = QFile::decodeName(qgetenv("XDG_DATA_HOME"));
        if (isTestModeEnabled())
            xdgDataHome = QDir::homePath() + QLatin1String("/.qttest/share");
        if (xdgDataHome.isEmpty())
            xdgDataHome = QDir::homePath() + QLatin1String("/.local/share");
        if (type == QStandardPaths::DataLocation)
            appendOrganizationAndApp(xdgDataHome);
        return xdgDataHome;
    }
    case ConfigLocation:
    case GenericConfigLocation:
    {
        // http://standards.freedesktop.org/basedir-spec/latest/
        QString xdgConfigHome = QFile::decodeName(qgetenv("XDG_CONFIG_HOME"));
        if (isTestModeEnabled())
            xdgConfigHome = QDir::homePath() + QLatin1String("/.qttest/config");
        if (xdgConfigHome.isEmpty())
            xdgConfigHome = QDir::homePath() + QLatin1String("/.config");
        return xdgConfigHome;
    }
    case RuntimeLocation:
    {
        const uid_t myUid = geteuid();
        // http://standards.freedesktop.org/basedir-spec/latest/
        QString xdgRuntimeDir = QFile::decodeName(qgetenv("XDG_RUNTIME_DIR"));
        if (xdgRuntimeDir.isEmpty()) {
            const QString userName = QFileSystemEngine::resolveUserName(myUid);
            xdgRuntimeDir = QDir::tempPath() + QLatin1String("/runtime-") + userName;
            QDir dir(xdgRuntimeDir);
            if (!dir.exists()) {
                if (!QDir().mkdir(xdgRuntimeDir)) {
                    qWarning("QStandardPaths: error creating runtime directory %s: %s", qPrintable(xdgRuntimeDir), qPrintable(qt_error_string(errno)));
                    return QString();
                }
            }
            qWarning("QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '%s'", qPrintable(xdgRuntimeDir));
        }
        // "The directory MUST be owned by the user"
        QFileInfo fileInfo(xdgRuntimeDir);
        if (fileInfo.ownerId() != myUid) {
            qWarning("QStandardPaths: wrong ownership on runtime directory %s, %d instead of %d", qPrintable(xdgRuntimeDir),
                     fileInfo.ownerId(), myUid);
            return QString();
        }
        // "and he MUST be the only one having read and write access to it. Its Unix access mode MUST be 0700."
        QFile file(xdgRuntimeDir);
        const QFile::Permissions wantedPerms = QFile::ReadUser | QFile::WriteUser | QFile::ExeUser;
        if (file.permissions() != wantedPerms && !file.setPermissions(wantedPerms)) {
            qWarning("QStandardPaths: wrong permissions on runtime directory %s", qPrintable(xdgRuntimeDir));
            return QString();
        }
        return xdgRuntimeDir;
    }
    default:
        break;
    }

#ifndef QT_BOOTSTRAPPED
    // http://www.freedesktop.org/wiki/Software/xdg-user-dirs
    QString xdgConfigHome = QFile::decodeName(qgetenv("XDG_CONFIG_HOME"));
    if (xdgConfigHome.isEmpty())
        xdgConfigHome = QDir::homePath() + QLatin1String("/.config");
    QFile file(xdgConfigHome + QLatin1String("/user-dirs.dirs"));
    if (!isTestModeEnabled() && file.open(QIODevice::ReadOnly)) {
        QHash<QString, QString> lines;
        QTextStream stream(&file);
        // Only look for lines like: XDG_DESKTOP_DIR="$HOME/Desktop"
        QRegExp exp(QLatin1String("^XDG_(.*)_DIR=(.*)$"));
        while (!stream.atEnd()) {
            const QString &line = stream.readLine();
            if (exp.indexIn(line) != -1) {
                const QStringList lst = exp.capturedTexts();
                const QString key = lst.at(1);
                QString value = lst.at(2);
                if (value.length() > 2
                    && value.startsWith(QLatin1Char('\"'))
                    && value.endsWith(QLatin1Char('\"')))
                    value = value.mid(1, value.length() - 2);
                // Store the key and value: "DESKTOP", "$HOME/Desktop"
                lines[key] = value;
            }
        }

        QString key;
        switch (type) {
        case DesktopLocation:
            key = QLatin1String("DESKTOP");
            break;
        case DocumentsLocation:
            key = QLatin1String("DOCUMENTS");
            break;
        case PicturesLocation:
            key = QLatin1String("PICTURES");
            break;
        case MusicLocation:
            key = QLatin1String("MUSIC");
            break;
        case MoviesLocation:
            key = QLatin1String("VIDEOS");
            break;
        case DownloadLocation:
            key = QLatin1String("DOWNLOAD");
            break;
        default:
            break;
        }
        if (!key.isEmpty()) {
            QString value = lines.value(key);
            if (!value.isEmpty()) {
                // value can start with $HOME
                if (value.startsWith(QLatin1String("$HOME")))
                    value = QDir::homePath() + value.mid(5);
                if (value.length() > 1 && value.endsWith(QLatin1Char('/')))
                    value.chop(1);
                return value;
            }
        }
    }
#endif

    QString path;
    switch (type) {
    case DesktopLocation:
        path = QDir::homePath() + QLatin1String("/Desktop");
        break;
    case DocumentsLocation:
        path = QDir::homePath() + QLatin1String("/Documents");
       break;
    case PicturesLocation:
        path = QDir::homePath() + QLatin1String("/Pictures");
        break;

    case FontsLocation:
        path = QDir::homePath() + QLatin1String("/.fonts");
        break;

    case MusicLocation:
        path = QDir::homePath() + QLatin1String("/Music");
        break;

    case MoviesLocation:
        path = QDir::homePath() + QLatin1String("/Videos");
        break;
    case DownloadLocation:
        path = QDir::homePath() + QLatin1String("/Downloads");
        break;
    case ApplicationsLocation:
        path = writableLocation(GenericDataLocation) + QLatin1String("/applications");
        break;

    default:
        break;
    }

    return path;
}
Example #6
0
void SdfRenderer::draw_text(QDomElement &element)
{
	toGen << "{\n";
	//parsestyle(element);
	toGen << "\tQPen pen;\n";
	toGen << "\tQFont font;\n";
	toGen << "\tpen.setStyle(Qt::SolidLine);\n";
	if (element.hasAttribute("font-fill"))
	{
		QColor color = element.attribute("font-fill");
		int red = color.red();
		int green = color.green();
		int blue = color.blue();
		toGen << "\tpen.setColor(QColor("<< red << ", "<< green << ", " << blue <<"));\n";
	}
	if (element.hasAttribute("font-size"))
	{
		QString fontsize = element.attribute("font-size");
		if (fontsize.endsWith("%"))
		{
			fontsize.chop(1);
			toGen << "\tfont.setPixelSize(y_def(\"" << fontsize.toInt() << "\"));\n";
		}
		else if (fontsize.endsWith("a") && mNeedScale)
		{
			fontsize.chop(1);
			toGen << "\tfont.setPixelSize(" << fontsize.toInt() << ");\n";
		}
		else if (fontsize.endsWith("a") && !mNeedScale)
		{
			fontsize.chop(1);
			toGen << "\tfont.setPixelSize(" << fontsize.toInt() << ");\n";
		}
		else
			toGen << "\tfont.setPixelSize(y_def(\"" << fontsize.toInt() << "\"));\n";
		}

		if (element.hasAttribute("font-name"))
		{
			toGen << "\tfont.setFamily(\"" << element.attribute("font-name") << "\");\n";
		}

		if (element.hasAttribute("b"))
		{
			toGen << "\tfont.setBold(" << element.attribute("b").toInt() << ");\n";
		}

		if (element.hasAttribute("i"))
		{
			toGen << "\tfont.setItalic(" << element.attribute("i").toInt() << ");\n";
		}

		if (element.hasAttribute("u"))
		{
			toGen << "\tfont.setUnderline(" << element.attribute("u").toInt() << ");\n";
		}
	toGen << QString("\n\tfloat x1 = x_def(\"%1\");\n").arg(element.attribute("x1"));
	toGen << QString("\tfloat y1 = y_def(\"%1\");\n\n").arg(element.attribute("y1"));
	QString str = element.text();

	// delete "\n" from the beginning of the string
	if (str[0] == '\n')
		str.remove(0, 1);

	// delete "\n" from the end of the string
	if (str[str.length() - 1] == '\n')
		str.remove(str.length() - 1, 1);

	while (str.contains('\n'))
	{
		int i = str.indexOf('\n');
		QString temp = str.left(i);
		str.remove(0, i + 1);
	}

	toGen << "\tQString str(\"" << str << "\");\n";
	toGen << "\tQPointF point(x1, y1);\n";
	toGen << "\tpainter->setPen(pen);\n";
	toGen << "\tpainter->setFont(font);\n";
	toGen << "\tpainter->drawText(point, str);\n";
	toGen << "};\n\n";
}
Example #7
0
void Renamer::renameMovies(QList<Movie*> movies, const QString &filePattern, const QString &filePatternMulti,
                           const QString &directoryPattern, const bool &renameFiles, const bool &renameDirectories, const bool &dryRun)
{
    if ((renameFiles && filePattern.isEmpty()) || (renameDirectories && directoryPattern.isEmpty()))
        return;

    foreach (Movie *movie, movies) {
        if (movie->files().isEmpty() || (movie->files().count() > 1 && filePatternMulti.isEmpty()) || movie->hasChanged())
            continue;

        qApp->processEvents();
        QFileInfo fi(movie->files().first());
        QString fiCanonicalPath = fi.canonicalPath();
        QDir dir(fi.canonicalPath());
        QString newFolderName = directoryPattern;
        QString newFileName;
        QString nfo = Manager::instance()->mediaCenterInterface()->nfoFilePath(movie);
        QString poster = Manager::instance()->mediaCenterInterface()->imageFileName(movie, ImageType::MoviePoster);
        QString fanart = Manager::instance()->mediaCenterInterface()->imageFileName(movie, ImageType::MovieBackdrop);
        QString banner = Manager::instance()->mediaCenterInterface()->imageFileName(movie, ImageType::MovieBanner);
        QString thumb = Manager::instance()->mediaCenterInterface()->imageFileName(movie, ImageType::MovieThumb);
        QString logo = Manager::instance()->mediaCenterInterface()->imageFileName(movie, ImageType::MovieLogo);
        QString clearArt = Manager::instance()->mediaCenterInterface()->imageFileName(movie, ImageType::MovieClearArt);
        QString cdArt = Manager::instance()->mediaCenterInterface()->imageFileName(movie, ImageType::MovieCdArt);

        QDir chkDir(fi.canonicalPath());
        chkDir.cdUp();

        bool isBluRay = Helper::instance()->isBluRay(chkDir.path());
        bool isDvd = Helper::instance()->isDvd(chkDir.path());

        if (isBluRay || isDvd)
            dir.cdUp();

        if (!isBluRay && !isDvd && renameFiles) {
            int partNo = 0;
            foreach (const QString &file, movie->files()) {
                newFileName = (movie->files().count() == 1) ? filePattern : filePatternMulti;
                QFileInfo fi(file);
                QString baseName = fi.completeBaseName();
                QDir currentDir = fi.dir();
                Renamer::replace(newFileName, "title", movie->name());
                Renamer::replace(newFileName, "originalTitle", movie->originalName());
                Renamer::replace(newFileName, "sortTitle", movie->sortTitle());
                Renamer::replace(newFileName, "year", movie->released().toString("yyyy"));
                Renamer::replace(newFileName, "extension", fi.suffix());
                Renamer::replace(newFileName, "partNo", QString::number(++partNo));
                Renamer::replace(newFileName, "resolution", Helper::instance()->matchResolution(movie->streamDetails()->videoDetails().value("width").toInt(),
                                                                                                movie->streamDetails()->videoDetails().value("height").toInt()));
                Renamer::replaceCondition(newFileName, "imdbId", movie->id());
                Renamer::replaceCondition(newFileName, "movieset", movie->set());
                Renamer::replaceCondition(newFileName, "3D", movie->streamDetails()->videoDetails().value("stereomode") != "");
                Helper::instance()->sanitizeFileName(newFileName);
                if (fi.fileName() != newFileName) {
                    ui->results->append(tr("<b>Rename File</b> \"%1\" to \"%2\"").arg(fi.fileName()).arg(newFileName));
                    if (!dryRun) {
                        if (!rename(file, fi.canonicalPath() + "/" + newFileName))
                            ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                    }

                    foreach (const QString &trailerFile, currentDir.entryList(QStringList() << fi.completeBaseName() + "-trailer.*", QDir::Files | QDir::NoDotAndDotDot)) {
                        QFileInfo trailer(fi.canonicalPath() + "/" + trailerFile);
                        QString newTrailerFileName = newFileName;
                        newTrailerFileName = newTrailerFileName.left(newTrailerFileName.lastIndexOf(".")) + "-trailer." + trailer.suffix();
                        if (trailer.fileName() != newTrailerFileName) {
                            ui->results->append(tr("<b>Rename File</b> \"%1\" to \"%2\"").arg(trailer.fileName()).arg(newTrailerFileName));
                            if (!dryRun) {
                                if (!rename(fi.canonicalPath() + "/" + trailerFile, fi.canonicalPath() + "/" + newTrailerFileName))
                                    ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                            }
                        }
                    }

                    QStringList filters;
                    foreach (const QString &extra, m_extraFiles)
                        filters << baseName + extra;
                    foreach (const QString &subFileName, currentDir.entryList(filters, QDir::Files | QDir::NoDotAndDotDot)) {
                        QString subSuffix = subFileName.mid(baseName.length());
                        QString newBaseName = newFileName.left(newFileName.lastIndexOf("."));
                        QString newSubName = newBaseName + subSuffix;
                        ui->results->append(tr("<b>Rename File</b> \"%1\" to \"%2\"").arg(subFileName).arg(newSubName));
                        if (!dryRun) {
                            if (!rename(currentDir.canonicalPath() + "/" + subFileName, currentDir.canonicalPath() + "/" + newSubName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename nfo
            if (!nfo.isEmpty()) {
                QString nfoFileName = QFileInfo(nfo).fileName();
                QList<DataFile> nfoFiles = Settings::instance()->dataFiles(DataFileType::MovieNfo);
                if (!nfoFiles.isEmpty()) {
                    QString newNfoFileName = nfoFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newNfoFileName);
                    if (newNfoFileName != nfoFileName) {
                        ui->results->append(tr("<b>Rename NFO</b> \"%1\" to \"%2\"").arg(nfoFileName).arg(newNfoFileName));
                        if (!dryRun) {
                            if (!rename(nfo, fiCanonicalPath + "/" + newNfoFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename Poster
            if (!poster.isEmpty()) {
                QString posterFileName = QFileInfo(poster).fileName();
                QList<DataFile> posterFiles = Settings::instance()->dataFiles(DataFileType::MoviePoster);
                if (!posterFiles.isEmpty()) {
                    QString newPosterFileName = posterFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newPosterFileName);
                    if (newPosterFileName != posterFileName) {
                        ui->results->append(tr("<b>Rename Poster</b> \"%1\" to \"%2\"").arg(posterFileName).arg(newPosterFileName));
                        if (!dryRun) {
                            if (!rename(poster, fiCanonicalPath + "/" + newPosterFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename Fanart
            if (!fanart.isEmpty()) {
                QString fanartFileName = QFileInfo(fanart).fileName();
                QList<DataFile> fanartFiles = Settings::instance()->dataFiles(DataFileType::MovieBackdrop);
                if (!fanartFiles.isEmpty()) {
                    QString newFanartFileName = fanartFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newFanartFileName);
                    if (newFanartFileName != fanartFileName) {
                        ui->results->append(tr("<b>Rename Fanart</b> \"%1\" to \"%2\"").arg(fanartFileName).arg(newFanartFileName));
                        if (!dryRun) {
                            if (!rename(fanart, fiCanonicalPath + "/" + newFanartFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename Banner
            if (!banner.isEmpty()) {
                QString bannerFileName = QFileInfo(banner).fileName();
                QList<DataFile> bannerFiles = Settings::instance()->dataFiles(DataFileType::MovieBanner);
                if (!bannerFiles.isEmpty()) {
                    QString newBannerFileName = bannerFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newBannerFileName);
                    if (newBannerFileName != bannerFileName) {
                        ui->results->append(tr("<b>Rename Banner</b> \"%1\" to \"%2\"").arg(bannerFileName).arg(newBannerFileName));
                        if (!dryRun) {
                            if (!rename(banner, fiCanonicalPath + "/" + newBannerFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename Thumb
            if (!thumb.isEmpty()) {
                QString thumbFileName = QFileInfo(thumb).fileName();
                QList<DataFile> thumbFiles = Settings::instance()->dataFiles(DataFileType::MovieThumb);
                if (!thumbFiles.isEmpty()) {
                    QString newThumbFileName = thumbFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newThumbFileName);
                    if (newThumbFileName != thumbFileName) {
                        ui->results->append(tr("<b>Rename Thumb</b> \"%1\" to \"%2\"").arg(thumbFileName).arg(newThumbFileName));
                        if (!dryRun) {
                            if (!rename(thumb, fiCanonicalPath + "/" + newThumbFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename Logo
            if (!logo.isEmpty()) {
                QString logoFileName = QFileInfo(logo).fileName();
                QList<DataFile> logoFiles = Settings::instance()->dataFiles(DataFileType::MovieLogo);
                if (!logoFiles.isEmpty()) {
                    QString newLogoFileName = logoFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newLogoFileName);
                    if (newLogoFileName != logoFileName) {
                        ui->results->append(tr("<b>Rename Logo</b> \"%1\" to \"%2\"").arg(logoFileName).arg(newLogoFileName));
                        if (!dryRun) {
                            if (!rename(logo, fiCanonicalPath + "/" + newLogoFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename ClearArt
            if (!clearArt.isEmpty()) {
                QString clearArtFileName = QFileInfo(clearArt).fileName();
                QList<DataFile> clearArtFiles = Settings::instance()->dataFiles(DataFileType::MovieClearArt);
                if (!clearArtFiles.isEmpty()) {
                    QString newClearArtFileName = clearArtFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newClearArtFileName);
                    if (newClearArtFileName != clearArtFileName) {
                        ui->results->append(tr("<b>Rename Clear Art</b> \"%1\" to \"%2\"").arg(clearArtFileName).arg(newClearArtFileName));
                        if (!dryRun) {
                            if (!rename(clearArt, fiCanonicalPath + "/" + newClearArtFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename CdArt
            if (!cdArt.isEmpty()) {
                QString cdArtFileName = QFileInfo(cdArt).fileName();
                QList<DataFile> cdArtFiles = Settings::instance()->dataFiles(DataFileType::MovieCdArt);
                if (!cdArtFiles.isEmpty()) {
                    QString newCdArtFileName = cdArtFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newCdArtFileName);
                    if (newCdArtFileName != cdArtFileName) {
                        ui->results->append(tr("<b>Rename CD Art</b> \"%1\" to \"%2\"").arg(cdArtFileName).arg(newCdArtFileName));
                        if (!dryRun) {
                            if (!rename(cdArt, fiCanonicalPath + "/" + newCdArtFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }
        }
Example #8
0
bool NewLoginDialog::passwordsMatch(const QString &p1, const QString &p2) {
    return (
                ( p1.length() > PASSWORD_MINIMUM_LENGTH )
                && (p1 == p2)
           );
}
int KstGuiData::vectorsToFile(const KstVectorList& vl, QFile *f, bool interpolate) {
  KstApp *app = KstApp::inst();
  int maxlen = -1;

  if (interpolate) { // code duplication is faster
    maxlen = 0;
    for (KstVectorList::ConstIterator v = vl.begin(); v != vl.end(); ++v) {
      (*v)->readLock();
      maxlen = KMAX(maxlen, (*v)->length());
    }
  } else {
    for (KstVectorList::ConstIterator v = vl.begin(); v != vl.end(); ++v) {
      (*v)->readLock();
      if (maxlen == -1) {
        maxlen = (*v)->length();
      } else {
        maxlen = KMIN(maxlen, (*v)->length());
      }
    }
  }

  QString saving = i18n("Saving vectors...");
  register int modval = kMax(maxlen/100, 100);
  app->slotUpdateProgress(maxlen, 0, QString::null);

  bool first = true;
  QString ltxt = ";";
  for (KstVectorList::ConstIterator v = vl.begin(); v != vl.end(); ++v) {
    ltxt += ' ';
    ltxt += (*v)->tagName();
  }
  ltxt += '\n';

  f->writeBlock(ltxt.ascii(), ltxt.length());
  ltxt.fill('-');
  ltxt[0] = ';';
  ltxt[1] = ' ';
  ltxt[ltxt.length() - 1] = '\n';
  f->writeBlock(ltxt.ascii(), ltxt.length());
#if QT_VERSION >= 0x030200
  ltxt.reserve(vl.count()*17);
#endif
  for (int line = 0; line < maxlen; ++line) {
    ltxt.truncate(0);
    first = true;
    for (KstVectorList::ConstIterator v = vl.begin(); v != vl.end(); ++v) {
      if (!first) {
        ltxt += ' ';
      } else {
        first = false;
      }
      double val;
      if (interpolate) {  // might be faster to put this outside the for loops
        val = (*v)->interpolate(line, maxlen);
      } else {
        val = (*v)->value()[line];
      } 
      ltxt += QString::number(val, 'g', 15);
    }
    ltxt += "\n";
    f->writeBlock(ltxt.ascii(), ltxt.length());
    if (line % modval == 0) {
      app->slotUpdateProgress(maxlen, line, saving);
    }
  }

  for (KstVectorList::ConstIterator v = vl.begin(); v != vl.end(); ++v) {
    (*v)->unlock();
  }

  app->slotUpdateProgress(0, 0, QString::null);

  return 0;
}
void FormulaEditorHighlighter::highlightBlock(const QString& text)
{
    // reset syntax highlighting
    setFormat(0, text.length(), QApplication::palette().text().color());

    // save the old ones to identify range changes
    Tokens oldTokens = d->tokens;

    // interpret the text as formula
    // we accept invalid/incomplete formulas
    Formula f;
    d->tokens = f.scan(text);

    QFont editorFont = document()->defaultFont();
    QFont font;

    uint oldRangeCount = d->rangeCount;

    d->rangeCount = 0;
    QList<QColor> colors = d->selection->colors();
    QList<QString> alreadyFoundRanges;

    Sheet *const originSheet = d->selection->originSheet();
    Map *const map = originSheet->map();

    for (int i = 0; i < d->tokens.count(); ++i) {
        Token token = d->tokens[i];
        Token::Type type = token.type();

        switch (type) {
        case Token::Cell:
        case Token::Range: {
            // don't compare, if we have already found a change
            if (!d->rangeChanged && i < oldTokens.count() && token.text() != oldTokens[i].text()) {
                d->rangeChanged = true;
            }

            const Region newRange(token.text(), map, originSheet);
            if (!newRange.isValid()) {
                continue;
            }

            int index = alreadyFoundRanges.indexOf(newRange.name());
            if (index == -1) { /* not found */
                alreadyFoundRanges.append(newRange.name());
                index = alreadyFoundRanges.count() - 1;
            }
            const QColor color(colors[index % colors.size()]);
            setFormat(token.pos() + 1, token.text().length(), color);
            ++d->rangeCount;
        }
        break;
        case Token::Boolean:     // True, False (also i18n-ized)
            /*        font = QFont(editorFont);
                    font.setBold(true);
                    setFormat(token.pos() + 1, token.text().length(), font);*/
            break;
        case Token::Identifier:   // function name or named area*/
            /*        font = QFont(editorFont);
                    font.setBold(true);
                    setFormat(token.pos() + 1, token.text().length(), font);*/
            break;

        case Token::Unknown:
        case Token::Integer:     // 14, 3, 1977
        case Token::Float:       // 3.141592, 1e10, 5.9e-7
        case Token::String:      // "KOffice", "The quick brown fox..."
        case Token::Error:
            break;
        case Token::Operator: {  // +, *, /, -
            switch (token.asOperator()) {
            case Token::LeftPar:
            case Token::RightPar:
                //Check where this brace is in relation to the cursor and highlight it if necessary.
                handleBrace(i);
                break;
            default:
                break;
            }
        }
        break;
        }
    }

    if (oldRangeCount != d->rangeCount)
        d->rangeChanged = true;
}
Example #11
0
CTTask::CTTask(const QString& tokenString, const QString& _comment, const QString& _userLogin, bool _systemCrontab) :
    systemCrontab(_systemCrontab) {

    QString tokStr = tokenString;
    if (tokStr.mid(0, 2) == "#\\") {
        tokStr = tokStr.mid(2, tokStr.length() - 2);
        enabled = false;
    } else if (tokStr.mid(0, 1) == "#") {
        tokStr = tokStr.mid(1, tokStr.length() - 1);
        enabled = false;
    } else
        enabled = true;

    // Skip over 'silence' if found... old option in vixie cron
    if (tokStr.mid(0, 1) == "-")
        tokStr = tokStr.mid(1, tokStr.length() - 1);

    reboot = false;
    if (tokStr.mid(0, 1) == "@") {
        if (tokStr.mid(1, 6) == "yearly") {
            tokStr = "0 0 1 1 *" + tokStr.mid(7, tokStr.length() - 1);
        } else if (tokStr.mid(1, 8) == "annually") {
            tokStr = "0 0 1 1 *" + tokStr.mid(9, tokStr.length() - 1);
        } else if (tokStr.mid(1, 7) == "monthly") {
            tokStr = "0 0 1 * *" + tokStr.mid(8, tokStr.length() - 1);
        } else if (tokStr.mid(1, 6) == "weekly") {
            tokStr = "0 0 * * 0" + tokStr.mid(7, tokStr.length() - 1);
        } else if (tokStr.mid(1, 5) == "daily") {
            tokStr = "0 0 * * *" + tokStr.mid(6, tokStr.length() - 1);
        } else if (tokStr.mid(1, 6) == "hourly") {
            tokStr = "0 * * * *" + tokStr.mid(7, tokStr.length() - 1);
        } else if (tokStr.mid(1, 6) == "reboot") {
            tokStr = tokStr.mid(7, tokStr.length() - 1);
            reboot = true;
        }
    }

    int spacePos(tokStr.indexOf(QRegExp("[ \t]")));
    // If reboot bypass initialize functions so no keys selected in modify task
    if (reboot == false) {

        //logDebug() << "Line : " << tokStr << endl;
        minute.initialize(tokStr.mid(0, spacePos));

        while (isSpace(tokStr, spacePos + 1))
            spacePos++;
        tokStr = tokStr.mid(spacePos + 1, tokStr.length() - 1);
        spacePos = tokStr.indexOf(QRegExp("[ \t]"));
        hour.initialize(tokStr.mid(0, spacePos));

        while (isSpace(tokStr, spacePos + 1))
            spacePos++;
        tokStr = tokStr.mid(spacePos + 1, tokStr.length() - 1);
        spacePos = tokStr.indexOf(QRegExp("[ \t]"));
        dayOfMonth.initialize(tokStr.mid(0, spacePos));

        while (isSpace(tokStr, spacePos + 1))
            spacePos++;
        tokStr = tokStr.mid(spacePos + 1, tokStr.length() - 1);
        spacePos = tokStr.indexOf(QRegExp("[ \t]"));
        month.initialize(tokStr.mid(0, spacePos));

        while (isSpace(tokStr, spacePos + 1))
            spacePos++;
        tokStr = tokStr.mid(spacePos + 1, tokStr.length() - 1);
        spacePos = tokStr.indexOf(QRegExp("[ \t]"));
        dayOfWeek.initialize(tokStr.mid(0, spacePos));
    }

    if (systemCrontab) {
        while (isSpace(tokStr, spacePos + 1))
            spacePos++;
        tokStr = tokStr.mid(spacePos + 1, tokStr.length() - 1);
        spacePos = tokStr.indexOf(QRegExp("[ \t]"));
        userLogin = tokStr.mid(0, spacePos);
    } else {
        userLogin = _userLogin;
    }

    command = tokStr.mid(spacePos + 1, tokStr.length() - 1);
    // remove leading whitespace
    while (command.indexOf(QRegExp("[ \t]")) == 0)
        command = command.mid(1, command.length() - 1);
    comment = _comment;

    initialUserLogin = userLogin;
    initialCommand = command;
    initialComment = comment;
    initialEnabled = enabled;
    initialReboot = reboot;
}
Example #12
0
void vfo::mousePressEvent(QMouseEvent *event)
{
    bool isVFOa = false;
    int digit, cnt;
    QString myStr = "";
    long long freq;

    if (event->button() == Qt::RightButton) {

//qDebug()<<Q_FUNC_INFO<<": event x/y = "<<event->x()<<"/"<<event->y();

        //Check to see if we have right clicked on the band button group
        if ((event->x() > 414) && (event->x() < 573) &&
            (event->y() > 6) && (event->y() < 111)) {
//            storeVFO(); //make the selected button flash yellow & call store routine
            timer.start(500,this);
            ui->btnGrpBand->checkedButton()->setStyleSheet("background-color: yellow");
            emit rightBandClick();  //connected to Band:quickMemStore via UI:quickMemStore

        }   // Check to see if we have right clicked the RIT slider
        else if ((event->x() > 189) && (event->x() < 403) &&
                 (event->y() > 89) && (event->y() < 111)) {
                ui->hSlider->setValue(0);
        }
        // We have clicked either on the display or somewhere else on the widget

        else {  // Check to see if we have clicked outside the vfo display area
            digit = getDigit(event->x(), event->y());
//qDebug()<<Q_FUNC_INFO<<": The value of digit is ..."<<digit;
            if (digit != 9) {       // getDigit returns 9 if click was outside display area.
                if (digit < 9) {    // getDigit returns 0 ... 8 if we clicked on vfoA
                    freq = readA();
                    isVFOa = true;
                    myStr = ui->lbl_Amhz->text() + ui->lbl_Akhz->text() + ui->lbl_Ahz->text();
                }
                else {                  // getDigit returns 10 ... 18 if we clicked on vfoB
                    digit = digit - 10; // so convert to 1 ... 8.
                    freq = readB();
                    myStr = ui->lbl_Bmhz->text() + ui->lbl_Bkhz->text() + ui->lbl_Bhz->text();
                }
                for (cnt = myStr.length(); cnt < 9; cnt++) {
                    myStr = "0" + myStr;
                }
                for (cnt = digit; cnt < 9; cnt++) {
                    myStr[cnt] = QChar('0');
                    ui->hSlider->setValue(0);
                }
                freq = freq - myStr.toLongLong();
                if (isVFOa) {   //We right clicked on vfoA
                    if(selectedVFO == 'A' || selectedVFO == 'S') {
                        emit frequencyMoved(freq, 1);
//qDebug()<<Q_FUNC_INFO<<": vfoA, emit frequencyChanged(myStr.toLongLong()) = "<<freq;
                    }
                    else {
                        writeA(myStr.toLongLong());
//qDebug()<<Q_FUNC_INFO<<": vfoA, writeA(myStr.toInt()) = "<<freq;
                    }
                }
//                else if(ui->pBtnSubRx->isChecked()) { //We right clicked on vfoB
//qDebug()<<Q_FUNC_INFO<<": vfoB and subRx mode";
//                }
                else if(selectedVFO == 'B') {
                        emit frequencyMoved(freq, 1);
//qDebug()<<Q_FUNC_INFO<<": Line 187 ... vfoB, emit frequencyMoved(freq, 1) = "<<freq;
                }
                else {
                        writeB(myStr.toLongLong());
//qDebug()<<Q_FUNC_INFO<<": vfoB, writeA(myStr.toInt()) = "<<freq;
                }
            }
        }
    }   //If event not right button or getDigit = 9, fall thru to here with no processing.
}
Example #13
0
        virtual void run()
        {
            QString result;

            QString workDir;
            QString initSel;
            QFileInfo fi (mStartWith);

            if (fi.isDir())
                workDir = mStartWith;
            else
            {
                workDir = fi.absolutePath();
                initSel = fi.fileName();
            }

            workDir = QDir::toNativeSeparators (workDir);
            if (!workDir.endsWith ("\\"))
                workDir += "\\";

            QString title = mCaption.isNull() ? tr ("Select a file") : mCaption;

            QWidget *topParent = windowManager().realParentWindow(mParent ? mParent : windowManager().mainWindowShown());
            QString winFilters = winFilter (mFilters);
            AssertCompile (sizeof (TCHAR) == sizeof (QChar));
            TCHAR buf [1024];
            if (initSel.length() > 0 && initSel.length() < sizeof (buf))
                memcpy (buf, initSel.isNull() ? 0 : initSel.utf16(),
                        (initSel.length() + 1) * sizeof (TCHAR));
            else
                buf [0] = 0;

            OPENFILENAME ofn;
            memset (&ofn, 0, sizeof (OPENFILENAME));

            ofn.lStructSize = sizeof (OPENFILENAME);
            ofn.hwndOwner = topParent ? topParent->winId() : 0;
            ofn.lpstrFilter = (TCHAR *)(winFilters.isNull() ? 0 : winFilters.utf16());
            ofn.lpstrFile = buf;
            ofn.nMaxFile = sizeof (buf) - 1;
            ofn.lpstrInitialDir = (TCHAR *)(workDir.isNull() ? 0 : workDir.utf16());
            ofn.lpstrTitle = (TCHAR *)(title.isNull() ? 0 : title.utf16());
            ofn.Flags = (OFN_NOCHANGEDIR | OFN_HIDEREADONLY |
                          OFN_EXPLORER | OFN_ENABLEHOOK |
                          OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST);
            ofn.lpfnHook = OFNHookProc;

            if (GetOpenFileName (&ofn))
            {
                result = QString::fromUtf16 ((ushort *) ofn.lpstrFile);
            }

            // qt_win_eatMouseMove();
            MSG msg = {0, 0, 0, 0, 0, 0, 0};
            while (PeekMessage (&msg, 0, WM_MOUSEMOVE, WM_MOUSEMOVE, PM_REMOVE));
            if (msg.message == WM_MOUSEMOVE)
                PostMessage (msg.hwnd, msg.message, 0, msg.lParam);

            result = result.isEmpty() ? result : QFileInfo (result).absoluteFilePath();

            QApplication::postEvent (mTarget, new GetOpenFileNameEvent (result));
        }
Example #14
0
 static bool isUsAscii( const QString & s ) {
   for ( int i = 0 ; i < s.length() ; ++i )
     if ( s[i].unicode() > 127 ) return false;
   return true;
 }
Example #15
0
void QTextOdfWriter::writeBlock(QXmlStreamWriter &writer, const QTextBlock &block)
{
    if (block.textList()) { // its a list-item
        const int listLevel = block.textList()->format().indent();
        if (m_listStack.isEmpty() || m_listStack.top() != block.textList()) {
            // not the same list we were in.
            while (m_listStack.count() >= listLevel && !m_listStack.isEmpty() && m_listStack.top() != block.textList() ) { // we need to close tags
                m_listStack.pop();
                writer.writeEndElement(); // list
                if (m_listStack.count())
                    writer.writeEndElement(); // list-item
            }
            while (m_listStack.count() < listLevel) {
                if (m_listStack.count())
                    writer.writeStartElement(textNS, QString::fromLatin1("list-item"));
                writer.writeStartElement(textNS, QString::fromLatin1("list"));
                if (m_listStack.count() == listLevel - 1) {
                    m_listStack.push(block.textList());
                    writer.writeAttribute(textNS, QString::fromLatin1("style-name"), QString::fromLatin1("L%1")
                            .arg(block.textList()->formatIndex()));
                }
                else {
                    m_listStack.push(0);
                }
            }
        }
        writer.writeStartElement(textNS, QString::fromLatin1("list-item"));
    }
    else {
        while (! m_listStack.isEmpty()) {
            m_listStack.pop();
            writer.writeEndElement(); // list
            if (m_listStack.count())
                writer.writeEndElement(); // list-item
        }
    }

    if (block.length() == 1) { // only a linefeed
        writer.writeEmptyElement(textNS, QString::fromLatin1("p"));
        writer.writeAttribute(textNS, QString::fromLatin1("style-name"), QString::fromLatin1("p%1")
            .arg(block.blockFormatIndex()));
        if (block.textList())
            writer.writeEndElement(); // numbered-paragraph
        return;
    }
    writer.writeStartElement(textNS, QString::fromLatin1("p"));
    writer.writeAttribute(textNS, QString::fromLatin1("style-name"), QString::fromLatin1("p%1")
        .arg(block.blockFormatIndex()));
    for (QTextBlock::Iterator frag= block.begin(); !frag.atEnd(); frag++) {
        writer.writeCharacters(QString()); // Trick to make sure that the span gets no linefeed in front of it.
        writer.writeStartElement(textNS, QString::fromLatin1("span"));

        QString fragmentText = frag.fragment().text();
        if (fragmentText.length() == 1 && fragmentText[0] == 0xFFFC) { // its an inline character.
            writeInlineCharacter(writer, frag.fragment());
            writer.writeEndElement(); // span
            continue;
        }

        writer.writeAttribute(textNS, QString::fromLatin1("style-name"), QString::fromLatin1("c%1")
            .arg(frag.fragment().charFormatIndex()));
        bool escapeNextSpace = true;
        int precedingSpaces = 0;
        int exportedIndex = 0;
        for (int i=0; i <= fragmentText.count(); ++i) {
            bool isSpace = false;
                QChar character = fragmentText[i];
                isSpace = character.unicode() == ' ';

            // find more than one space. -> <text:s text:c="2" />
            if (!isSpace && escapeNextSpace && precedingSpaces > 1) {
                const bool startParag = exportedIndex == 0 && i == precedingSpaces;
                if (!startParag)
                    writer.writeCharacters(fragmentText.mid(exportedIndex, i - precedingSpaces + 1 - exportedIndex));
                writer.writeEmptyElement(textNS, QString::fromLatin1("s"));
                const int count = precedingSpaces - (startParag?0:1);
                if (count > 1)
                    writer.writeAttribute(textNS, QString::fromLatin1("c"), QString::number(count));
                precedingSpaces = 0;
                exportedIndex = i;
            }

            if (i < fragmentText.count()) {
                if (character.unicode() == 0x2028) { // soft-return
                    //if (exportedIndex < i)
                        writer.writeCharacters(fragmentText.mid(exportedIndex, i - exportedIndex));
                    writer.writeEmptyElement(textNS, QString::fromLatin1("line-break"));
                    exportedIndex = i+1;
                    continue;
                } else if (character.unicode() == '\t') { // Tab
                    //if (exportedIndex < i)
                        writer.writeCharacters(fragmentText.mid(exportedIndex, i - exportedIndex));
                    writer.writeEmptyElement(textNS, QString::fromLatin1("tab"));
                    exportedIndex = i+1;
                    precedingSpaces = 0;
                } else if (isSpace) {
                    ++precedingSpaces;
                    escapeNextSpace = true;
                } else if (!isSpace) {
                    precedingSpaces = 0;
                }
            }
        }

        writer.writeCharacters(fragmentText.mid(exportedIndex));
        writer.writeEndElement(); // span
    }
    writer.writeCharacters(QString()); // Trick to make sure that the span gets no linefeed behind it.
    writer.writeEndElement(); // p
    if (block.textList())
        writer.writeEndElement(); // list-item
}
Example #16
0
void WebcamTask::parseData( QByteArray &data, KStreamSocket *socket )
{
	int headerLength = 0;
	int read = 0;
	YahooWebcamInformation *info = &socketMap[socket];
	if( !info->headerRead )
	{
		headerLength = data[0];	
		kDebug(YAHOO_RAW_DEBUG) << "headerLength " << headerLength;
		if( data.size() < headerLength )
			return;			
		if( headerLength >= 8 )
		{
			kDebug() << data[0] << data[1] << data[2] << data[3] << data[4] << data[5] << data[6] << data[7];
			info->reason = data[1];
			info->dataLength = yahoo_get32(data.data() + 4);
		}
		if( headerLength == 13 )
		{
			kDebug() << data[8] << data[9] << data[10] << data[11] << data[12];
			info->timestamp = yahoo_get32(data.data() + 9);
			kDebug(YAHOO_RAW_DEBUG) << "PacketType: " << data[8] << " reason: " << info->reason << " timestamp: " << info->timestamp;
			QStringList::iterator it;
			switch( data[8] )
			{
				case 0x00:
					if( info->direction == Incoming )
					{
						if( info->timestamp == 0 )
						{
							emit webcamClosed( info->sender, 3 );
							cleanUpConnection( socket );
						}
					}
					else
					{
						info->type = UserRequest;
						info->headerRead = true;
					}
				break;
				case 0x02: 
					info->type = Image;
					info->headerRead = true;
				break;
				case 0x04:
					if( info->timestamp == 1 )
					{
						emit webcamPaused( info->sender );
					}
				break;
				case 0x05:
					kDebug(YAHOO_RAW_DEBUG) << "Ready for Transmission";
					if( info->timestamp == 1 )
					{
						info->status = Sending;
						emit readyForTransmission();
					}
					else if( info->timestamp == 0 )
					{
						info->status = SendingEmpty;
						emit stopTransmission();
						sendEmptyWebcamImage();
					
					}
					// Send  very first Invitation packets
					for(it = pendingInvitations.begin(); it != pendingInvitations.end(); it++)
					{
						kDebug(YAHOO_RAW_DEBUG) << "send primary invitation";
						SendNotifyTask *snt = new SendNotifyTask( parent() );
						snt->setTarget( *it );
						snt->setType( SendNotifyTask::NotifyWebcamInvite );
						snt->go( true );
						it = pendingInvitations.erase( it );
						it--;
						info->status = SendingEmpty;
						emit stopTransmission();
						sendEmptyWebcamImage();
					}
					
					break;
				case 0x07: 
					
					info->type = ConnectionClosed;
					emit webcamClosed( info->sender, info->reason );
					cleanUpConnection( socket );
				case 0x0c:
					info->type = NewWatcher;
					info->headerRead = true;
				break;
				case 0x0d:
					info->type = WatcherLeft;
					info->headerRead = true;
				break;
			}
		}
		if( headerLength > 13 || headerLength <= 0)		//Parse error
			return;
		if( !info->headerRead && data.size() > headerLength )
		{
			// More headers to read
			kDebug(YAHOO_RAW_DEBUG) << "More data to read...";
			QByteArray newData;
			newData.reserve( data.size() - headerLength );
			QDataStream stream( &newData, QIODevice::WriteOnly );
			stream.writeRawData( data.data() + headerLength, data.size() - headerLength );
			parseData( newData, socket );
			return;
		}
		kDebug(YAHOO_RAW_DEBUG) << "Parsed Packet: HeaderLen: " << headerLength << " DataLen: " << info->dataLength;
	}
	
	if( info->dataLength <= 0 )
	{
		kDebug(YAHOO_RAW_DEBUG) << "No data to read. (info->dataLength <= 0)";
		if( info->headerRead )
			info->headerRead = false;
		return;
	}
	if( headerLength >= data.size() )
	{
		kDebug(YAHOO_RAW_DEBUG) << "No data to read. (headerLength >= data.size())";
		return;		//Nothing to read here...
	}
	if( !info->buffer )
	{
		kDebug(YAHOO_RAW_DEBUG) << "Buffer created";
		info->buffer = new QBuffer();
		info->buffer->open( QIODevice::WriteOnly );
	}
	kDebug(YAHOO_RAW_DEBUG) << "data.size() " << data.size() << " headerLength " << headerLength << " buffersize " << info->buffer->size();
	read = headerLength + info->dataLength - info->buffer->size();
	info->buffer->write( data.data() + headerLength, data.size() - headerLength );//info->dataLength - info->buffer->size() );
	kDebug(YAHOO_RAW_DEBUG) << "read " << data.size() - headerLength << " Bytes, Buffer is now " << info->buffer->size();
	if( info->buffer->size() >= static_cast<uint>(info->dataLength) )
	{	
		info->buffer->close();
		QString who;
		switch( info->type )
		{
		case UserRequest:
			{
			who.append( info->buffer->buffer() );
			who = who.mid( 2, who.indexOf('\n') - 3);
			kDebug(YAHOO_RAW_DEBUG) << "User wants to view webcam: " << who << " len: " << who.length() << " Index: " << accessGranted.indexOf( who );
			if( accessGranted.indexOf( who ) >= 0 )
			{
				grantAccess( who );
			}
			else
				emit viewerRequest( who );
			}
		break;
		case NewWatcher:
			who.append( info->buffer->buffer() );
			who = who.left( who.length() - 1 );
			kDebug(YAHOO_RAW_DEBUG) << "New Watcher of webcam: " << who;
			emit viewerJoined( who );
		break;
		case WatcherLeft:
			who.append( info->buffer->buffer() );
			who = who.left( who.length() - 1 );
			kDebug(YAHOO_RAW_DEBUG) << "A Watcher left: " << who << " len: " << who.length();
			accessGranted.removeAll( who );
			emit viewerLeft( who );
		break;
		case Image:
			{
			QPixmap webcamImage;
			//webcamImage.loadFromData( info->buffer->buffer() );
			if (WebcamImgFormat::instance())
			{
				if (WebcamImgFormat::instance()->fromYahoo(webcamImage, info->buffer->buffer().constData(), info->buffer->buffer().size()))
				{
					kDebug(YAHOO_RAW_DEBUG) << "Image Received and converted. Size: " << webcamImage.size();
					emit webcamImageReceived( info->sender, webcamImage );
				} else
					kDebug(YAHOO_RAW_DEBUG) << "Failed to convert incoming Yahoo webcam image";
			} else
				kDebug(YAHOO_RAW_DEBUG) << "Failed to initialize WebcamImgFormat helper";
			}
		break;
		default:
		break;
		}
		
		info->headerRead = false;
		delete info->buffer;
		info->buffer = 0L;
	}
	if( data.size() > read )
	{
		// More headers to read
		kDebug(YAHOO_RAW_DEBUG) << "More data to read..." << data.size() - read;
		QByteArray newData;
		newData.reserve( data.size() - read );
		QDataStream stream( &newData, QIODevice::WriteOnly );
		stream.writeRawData( data.data() + read, data.size() - read );
		parseData( newData, socket );
	}
}
Example #17
0
/*!
  Slot activated when toggle comment selection is seleteted from context menu or ctrl+k is pressed.
  The implementation and logic is inspired from Qt Creator sources.
  */
void ModelicaEditor::toggleCommentSelection()
{
  CommentDefinition definition;
  if (!definition.hasSingleLineStyle() && !definition.hasMultiLineStyle()) {
    return;
  }

  QTextCursor cursor = mpPlainTextEdit->textCursor();
  QTextDocument *doc = cursor.document();
  cursor.beginEditBlock();

  int pos = cursor.position();
  int anchor = cursor.anchor();
  int start = qMin(anchor, pos);
  int end = qMax(anchor, pos);
  bool anchorIsStart = (anchor == start);

  QTextBlock startBlock = doc->findBlock(start);
  QTextBlock endBlock = doc->findBlock(end);

  if (end > start && endBlock.position() == end) {
    --end;
    endBlock = endBlock.previous();
  }

  bool doMultiLineStyleUncomment = false;
  bool doMultiLineStyleComment = false;
  bool doSingleLineStyleUncomment = false;

  bool hasSelection = cursor.hasSelection();

  if (hasSelection && definition.hasMultiLineStyle()) {

    QString startText = startBlock.text();
    int startPos = start - startBlock.position();
    const int multiLineStartLength = definition.multiLineStart().length();
    bool hasLeadingCharacters = !startText.left(startPos).trimmed().isEmpty();

    if (startPos >= multiLineStartLength
        && isComment(startText,
                     startPos - multiLineStartLength,
                     definition,
                     &CommentDefinition::multiLineStart)) {
      startPos -= multiLineStartLength;
      start -= multiLineStartLength;
    }

    bool hasSelStart = (startPos <= startText.length() - multiLineStartLength
                        && isComment(startText,
                                     startPos,
                                     definition,
                                     &CommentDefinition::multiLineStart));

    QString endText = endBlock.text();
    int endPos = end - endBlock.position();
    const int multiLineEndLength = definition.multiLineEnd().length();
    bool hasTrailingCharacters =
        !endText.left(endPos).remove(definition.singleLine()).trimmed().isEmpty()
        && !endText.mid(endPos).trimmed().isEmpty();

    if (endPos <= endText.length() - multiLineEndLength
        && isComment(endText, endPos, definition, &CommentDefinition::multiLineEnd)) {
      endPos += multiLineEndLength;
      end += multiLineEndLength;
    }

    bool hasSelEnd = (endPos >= multiLineEndLength
                      && isComment(endText,
                                   endPos - multiLineEndLength,
                                   definition,
                                   &CommentDefinition::multiLineEnd));

    doMultiLineStyleUncomment = hasSelStart && hasSelEnd;
    doMultiLineStyleComment = !doMultiLineStyleUncomment
        && (hasLeadingCharacters
            || hasTrailingCharacters
            || !definition.hasSingleLineStyle());
  } else if (!hasSelection && !definition.hasSingleLineStyle()) {

    QString text = startBlock.text().trimmed();
    doMultiLineStyleUncomment = text.startsWith(definition.multiLineStart())
        && text.endsWith(definition.multiLineEnd());
    doMultiLineStyleComment = !doMultiLineStyleUncomment && !text.isEmpty();

    start = startBlock.position();
    end = endBlock.position() + endBlock.length() - 1;

    if (doMultiLineStyleUncomment) {
      int offset = 0;
      text = startBlock.text();
      const int length = text.length();
      while (offset < length && text.at(offset).isSpace())
        ++offset;
      start += offset;
    }
  }

  if (doMultiLineStyleUncomment) {
    cursor.setPosition(end);
    cursor.movePosition(QTextCursor::PreviousCharacter,
                        QTextCursor::KeepAnchor,
                        definition.multiLineEnd().length());
    cursor.removeSelectedText();
    cursor.setPosition(start);
    cursor.movePosition(QTextCursor::NextCharacter,
                        QTextCursor::KeepAnchor,
                        definition.multiLineStart().length());
    cursor.removeSelectedText();
  } else if (doMultiLineStyleComment) {
    cursor.setPosition(end);
    cursor.insertText(definition.multiLineEnd());
    cursor.setPosition(start);
    cursor.insertText(definition.multiLineStart());
  } else {
    endBlock = endBlock.next();
    doSingleLineStyleUncomment = true;
    for (QTextBlock block = startBlock; block != endBlock; block = block.next()) {
      QString text = block.text().trimmed();
      if (!text.isEmpty() && !text.startsWith(definition.singleLine())) {
        doSingleLineStyleUncomment = false;
        break;
      }
    }

    const int singleLineLength = definition.singleLine().length();
    for (QTextBlock block = startBlock; block != endBlock; block = block.next()) {
      if (doSingleLineStyleUncomment) {
        QString text = block.text();
        int i = 0;
        while (i <= text.size() - singleLineLength) {
          if (isComment(text, i, definition, &CommentDefinition::singleLine)) {
            cursor.setPosition(block.position() + i);
            cursor.movePosition(QTextCursor::NextCharacter,
                                QTextCursor::KeepAnchor,
                                singleLineLength);
            cursor.removeSelectedText();
            break;
          }
          if (!text.at(i).isSpace())
            break;
          ++i;
        }
      } else {
        QString text = block.text();
        foreach(QChar c, text) {
          if (!c.isSpace()) {
            if (definition.isAfterWhiteSpaces())
              cursor.setPosition(block.position() + text.indexOf(c));
            else
              cursor.setPosition(block.position());
            cursor.insertText(definition.singleLine());
            break;
          }
        }
      }
    }
  }
  // adjust selection when commenting out
  if (hasSelection && !doMultiLineStyleUncomment && !doSingleLineStyleUncomment) {
    cursor = mpPlainTextEdit->textCursor();
    if (!doMultiLineStyleComment)
      start = startBlock.position(); // move the comment into the selection
    int lastSelPos = anchorIsStart ? cursor.position() : cursor.anchor();
    if (anchorIsStart) {
      cursor.setPosition(start);
      cursor.setPosition(lastSelPos, QTextCursor::KeepAnchor);
    } else {
      cursor.setPosition(lastSelPos);
      cursor.setPosition(start, QTextCursor::KeepAnchor);
    }
    mpPlainTextEdit->setTextCursor(cursor);
  }
  cursor.endEditBlock();
}
static bool isPrefixOf(const QString &prefix, const QString &what)
{
    return ((what.length() > prefix.length())
            && what.startsWith(prefix));
}
Example #19
0
bool SdfRenderer::while_condition(QString str, int i)
{
	return (str[i] != 'L') && (str[i] != 'C') && (str[i] != 'M')
		&& (str[i] != 'Z') && (i != str.length());
}
Example #20
0
/* FIXME make this less of a hack. */
QRect TestCalendarWidget::visualRect(QString const &item) const
{
    TestWidgetsLog() << item << "my geometry is" << geometry();

    QRect ret;

    QAbstractItemView *view = q->findChild<QAbstractItemView*>();
    QtUiTest::ListWidget *calendarView
        = qtuitest_cast<QtUiTest::ListWidget*>(view);

    if (!calendarView) {
        return ret;
    }

    ret = calendarView->visualRect(item);
    if (!ret.isNull()) {
        ret.moveTopLeft( q->mapFromGlobal( view->mapToGlobal(ret.topLeft()) ) );
        TestWidgetsLog() << item << "is a visible day at" << ret;
        return ret;
    }

    QToolButton *yearButton = 0;
    QToolButton *monthButton = 0;
    QSpinBox *yearSpin = q->findChild<QSpinBox*>();
    QMenu *monthMenu = 0;

    QList<QToolButton*> blist = q->findChildren<QToolButton*>();
    foreach(QToolButton *b, blist) {
        if (!monthButton && (monthMenu = b->menu())) {
            monthButton = b;
        }
        if (!b->menu()) {
            yearButton = b;
        }
    }
    TestWidgetsLog() << "monthButton" << monthButton << "yearButton" << yearButton;
    TestWidgetsLog() << "item" << item << "monthMenu" << monthMenu;

    if (yearButton && yearButton->isVisible() && yearButton->text() == item) {
        QPoint p = q->mapFromGlobal( yearButton->mapToGlobal(QPoint(yearButton->width()+5, yearButton->height()/2)) );
        ret = QRect(p.x() - 2, p.y() - 2, 5, 5);
        TestWidgetsLog() << "click near yearbutton";
    } else if (yearSpin && yearSpin->isVisible() && yearSpin->value() == item.toInt()) {
        TestWidgetsLog() << "confirm spinbox";
        QPoint p = q->mapFromGlobal( yearSpin->mapToGlobal(QPoint(yearSpin->width()+5, yearSpin->height()/2)) );
        ret = QRect(p.x() - 2, p.y() - 2, 5, 5);
    } else if (monthButton && monthButton->isVisible() && monthButton->text() == item) {
        QPoint p = q->mapFromGlobal( monthButton->mapToGlobal(QPoint(-5, monthButton->height()/2)) );
        ret = QRect(p.x() - 2, p.y() - 2, 5, 5);
        TestWidgetsLog() << "click near monthbutton";
    } else if (monthMenu && monthMenu->isVisible()
            && qtuitest_cast<QtUiTest::ListWidget*>(monthMenu)
            && qtuitest_cast<QtUiTest::ListWidget*>(monthMenu)->list().contains(item)) {
        ret = qtuitest_cast<QtUiTest::ListWidget*>(monthMenu)->visualRect(item);
        ret.moveTopLeft( q->mapFromGlobal( monthMenu->mapToGlobal(ret.topLeft()) ) );
        TestWidgetsLog() << "click on monthmenu";
    } else {
        do {
            QStringList items = list();
            if (items.contains(item)) {
                ret = QRect(-1, -1, 1, 1);
                ret.moveTopLeft( q->mapFromGlobal(QPoint(-1,-1)) );
                break;
            }
            foreach (QString s, items) {
                if (!s.startsWith(GetListRegExp)) continue;
                QRegExp re(s.mid(GetListRegExp.length()));
                if (re.exactMatch(item)) {
                    ret = QRect(-1, -1, 1, 1);
                    ret.moveTopLeft( q->mapFromGlobal(QPoint(-1,-1)) );
                    break;
                }
            }
            if (!ret.isNull()) break;
        } while(0);
    }

    TestWidgetsLog() << "returning rect" << ret;

    return ret;
}
Example #21
0
void Server::processEventGroup(QString message_type, QString message, QTcpSocket *tcpSocket)
{
    int idusersocs=tcpSocket->socketDescriptor();
    QTextStream os(tcpSocket);
    os.setAutoDetectUnicode(true);
    os << "HTTP/1.0 200 Ok\r\n"
          "Content-Type: text/html; charset=\"utf-8\"\r\n"
          "\r\n"
          "<h1>Nothing to see here</h1>\n"
          << QDateTime::currentDateTime().toString() << "\n";

    if (message_type == "smsread" || message_type == "phoneread") {

        QMap<quint16, ClientBlock *>::const_iterator i = clientblocks->constBegin();
        while (i != clientblocks->constEnd()) {
            SendData(i.value()->getblockId(), "TONE=0");
            SendData(i.value()->getblockId(), "SERV_LT=");
            ++i;
        }

    } else if (message_type == "sms" || message_type == "phone" || message_type == "notify") {

        QString username = "";
        int index = message.indexOf("INFO=");
        if (index >= 0) {
            index += 5;
            username = message.mid(index);
            QUrl upath = QUrl(username);
            username = upath.fromPercentEncoding(username.toUtf8());
            username = getTranslit(username);
            emit write_message(username);
        }
        username = username.replace('+', " ");
        if (username.length() > 16) {
            username.resize(16);
        }

        bool need_sound = false;
        int hour = QDateTime::currentDateTime().toString("hh").toInt();
        if (time_evt_to >= time_evt_from) {
            if (hour <= time_evt_from || hour >= time_evt_to) {
                need_sound = true;
            }
        } else {
            if (hour >= time_evt_to && hour <= time_evt_from) {
                need_sound = true;
            }
        }

        QMap<quint16, ClientBlock *>::const_iterator i = clientblocks->constBegin();
        while (i != clientblocks->constEnd()) {
            if (message_type == "sms") {
                if (need_sound) SendData(i.value()->getblockId(), "TONE=300,1500");
                SendData(i.value()->getblockId(), "SERV_LT=SMS  " + QDateTime::currentDateTime().toString("dd.MM hh:mm") + username);
            } else if (message_type == "phone") {
                if (need_sound) SendData(i.value()->getblockId(), "TONE=500,500");
                SendData(i.value()->getblockId(), "SERV_LT=CALL " + QDateTime::currentDateTime().toString("dd.MM hh:mm") + username);
            } else {
                if (need_sound) SendData(i.value()->getblockId(), "TONE=800,2000");
                SendData(i.value()->getblockId(), "SERV_LT=NOT  " + QDateTime::currentDateTime().toString("dd.MM hh:mm") + username);
            }
            ++i;
        }

    }
}
manager_menu::manager_menu(QWidget *parent, QString db_login) :
    menu_base(parent),
    ui(new Ui::manager_menu)
{
    ui->setupUi(this);
    n_human_picker = new new_human_picker();
    a_new_subject = new add_new_subject();
    a_new_job = new add_new_job();
    ch_job = new change_job();
    ad_positions = new administrate_position();
    exp_position = new expire_position();
    ass_human_to_position = new assign_human_to_position();
    exp_human_on_position = new expire_human_on_position();
    learn_man_menu = new learning_manager_menu();

    //connects
    connect(n_human_picker,SIGNAL(restore_main_menu()),this,SLOT(restore_menu()));
    connect(a_new_subject,SIGNAL(restore_main_menu()),this,SLOT(restore_menu()));
    connect(a_new_job,SIGNAL(restore_main_menu()),this,SLOT(restore_menu()));
    connect(ch_job,SIGNAL(restore_main_menu()),this,SLOT(restore_menu()));
    connect(ad_positions,SIGNAL(restore_main_menu()),this,SLOT(restore_menu()));
    connect(exp_position,SIGNAL(restore_main_menu()),this,SLOT(restore_menu()));
    connect(ass_human_to_position,SIGNAL(restore_main_menu()),this,SLOT(restore_menu()));
    connect(exp_human_on_position,SIGNAL(restore_main_menu()),this,SLOT(restore_menu()));
    connect(learn_man_menu,SIGNAL(restore_main_menu()),this,SLOT(restore_menu()));

    connect(this,SIGNAL(show_add_new_job_dialog()),a_new_job,SLOT(show_add_new_job_dialog()));
    connect(this,SIGNAL(show_change_job_dialog()),ch_job,SLOT(show_change_job_dialog()));
    connect(this,SIGNAL(show_administrating_positions_dialog()),ad_positions,SLOT(show_administrating_positions_dialog()));
    connect(this,SIGNAL(show_expire_position_dialog()),exp_position,SLOT(show_expire_position_dialog()));
    connect(this,SIGNAL(show_assign_human_to_position_dialog()),ass_human_to_position,SLOT(show_assign_human_to_position_dialog()));
    connect(this,SIGNAL(show_expire_human_on_position_dialog()),exp_human_on_position,SLOT(show_expire_human_on_position_dialog()));


    //Get the staff id

    if(db_login.length()) {
        QString qtext("SELECT sl.id_human, fio(last_name, first_name, patronymic) AS fio "
                      "FROM staff_logins sl "
                      "LEFT JOIN people_workers p ON sl.id_human=p.id_human "
                      "WHERE sl.db_login =?;");

        QSqlQuery query;
        query.prepare(qtext);
        query.addBindValue(db_login);
        query.exec();
        if (query.lastError().type()!=QSqlError::NoError){
            QMessageBox msg;
            qDebug() << query.lastError().text();
            msg.setText(query.lastError().text());
            msg.exec();
            return;
        }
        if(query.next()) {
            staff_id = query.value(0).toInt();
            QString fio = query.value(1).toString();
            this->setWindowTitle(fio);
        }
        query.finish();
    }
    else {
        staff_id=0;
    }
}
Example #23
0
void VCButton::saveToFile(QFile& file, unsigned int parentID)
{
  QString s;
  QString t;

  // Comment
  s = QString("# Virtual Console Button Entry\n");
  file.writeBlock((const char*) s, s.length());

  // Entry type
  s = QString("Entry = Button") + QString("\n");
  file.writeBlock((const char*) s, s.length());

  // Name
  s = QString("Name = ") + caption() + QString("\n");
  file.writeBlock((const char*) s, s.length());

  // Parent ID
  t.setNum(parentID);
  s = QString("Parent = ") + t + QString("\n");
  file.writeBlock((const char*) s, s.length());

  // X
  t.setNum(x());
  s = QString("X = ") + t + QString("\n");
  file.writeBlock((const char*) s, s.length());

  // Y
  t.setNum(y());
  s = QString("Y = ") + t + QString("\n");
  file.writeBlock((const char*) s, s.length());

  // W
  t.setNum(width());
  s = QString("Width = ") + t + QString("\n");
  file.writeBlock((const char*) s, s.length());

  // H
  t.setNum(height());
  s = QString("Height = ") + t + QString("\n");
  file.writeBlock((const char*) s, s.length());

  // Text color
  if (ownPalette())
    {
      t.setNum(qRgb(paletteForegroundColor().red(),
		    paletteForegroundColor().green(),
		    paletteForegroundColor().blue()));
      s = QString("Textcolor = ") + t + QString("\n");
      file.writeBlock((const char*) s, s.length());

      // Background color
      t.setNum(qRgb(paletteBackgroundColor().red(),
		    paletteBackgroundColor().green(),
		    paletteBackgroundColor().blue()));
      s = QString("Backgroundcolor = ") + t + QString("\n");
      file.writeBlock((const char*) s, s.length());
    }

  // Background pixmap
  if (paletteBackgroundPixmap())
    {
      s = QString("Pixmap = " + iconText() + QString("\n"));
      file.writeBlock((const char*) s, s.length());
    }

  // Font
  s = QString("Font = ") + font().toString() + QString("\n");
  file.writeBlock((const char*) s, s.length());

  // Function
  s.sprintf("Function = %d\n", m_functionID);
  file.writeBlock((const char*) s, s.length());

  // Key binding
  assert(m_keyBind);

  s.sprintf("BindKey = %d\n", m_keyBind->key());
  file.writeBlock((const char*) s, s.length());

  s.sprintf("BindMod = %d\n", m_keyBind->mod());
  file.writeBlock((const char*) s, s.length());

  s.sprintf("BindPress = %d\n", m_keyBind->pressAction());
  file.writeBlock((const char*) s, s.length());
  
  s.sprintf("BindRelease = %d\n", m_keyBind->releaseAction());
  file.writeBlock((const char*) s, s.length());
}
bool AddTestCasesWizard::compareFileName(const QString &a, const QString &b)
{
    return a.length() < b.length() || a.length() == b.length() && QString::localeAwareCompare(a, b) < 0;
}
Example #25
0
/*!
  Load, parse, and process a qdoc configuration file. This
  function is only called by the other load() function, but
  this one is recursive, i.e., it calls itself when it sees
  an \c{include} statement in the qdog configuration file.
 */
void Config::load(Location location, const QString& fileName)
{
    QRegExp keySyntax("\\w+(?:\\.\\w+)*");

#define SKIP_CHAR() \
    do { \
        location.advance(c); \
        ++i; \
        c = text.at(i); \
        cc = c.unicode(); \
    } while (0)

#define SKIP_SPACES() \
    while (c.isSpace() && cc != '\n') \
        SKIP_CHAR()

#define PUT_CHAR() \
    word += c; \
    SKIP_CHAR();

    if (location.depth() > 16)
        location.fatal(tr("Too many nested includes"));

    QFile fin(fileName);
    if (!fin.open(QFile::ReadOnly | QFile::Text)) {
        fin.setFileName(fileName + ".qdoc");
        if (!fin.open(QFile::ReadOnly | QFile::Text))
            location.fatal(tr("Cannot open file '%1': %2").arg(fileName).arg(fin.errorString()));
    }

    QTextStream stream(&fin);
    stream.setCodec("UTF-8");
    QString text = stream.readAll();
    text += QLatin1String("\n\n");
    text += QChar('\0');
    fin.close();

    location.push(fileName);
    location.start();

    int i = 0;
    QChar c = text.at(0);
    uint cc = c.unicode();
    while (i < (int) text.length()) {
        if (cc == 0)
            ++i;
        else if (c.isSpace()) {
            SKIP_CHAR();
        }
        else if (cc == '#') {
            do {
                SKIP_CHAR();
            } while (cc != '\n');
        }
        else if (isMetaKeyChar(c)) {
            Location keyLoc = location;
            bool plus = false;
            QString stringValue;
            QStringList stringListValue;
            QString word;
            bool inQuote = false;
            bool prevWordQuoted = true;
            bool metWord = false;

            MetaStack stack;
            do {
                stack.process(c, location);
                SKIP_CHAR();
            } while (isMetaKeyChar(c));

            QStringList keys = stack.getExpanded(location);
            //qDebug() << "KEYS:" << keys;
            SKIP_SPACES();

            if (keys.count() == 1 && keys.first() == "include") {
                QString includeFile;

                if (cc != '(')
                    location.fatal(tr("Bad include syntax"));
                SKIP_CHAR();
                SKIP_SPACES();
                while (!c.isSpace() && cc != '#' && cc != ')') {
                    includeFile += c;
                    SKIP_CHAR();
                }
                SKIP_SPACES();
                if (cc != ')')
                    location.fatal(tr("Bad include syntax"));
                SKIP_CHAR();
                SKIP_SPACES();
                if (cc != '#' && cc != '\n')
                    location.fatal(tr("Trailing garbage"));

                /*
                  Here is the recursive call.
                 */
                load(location,
                      QFileInfo(QFileInfo(fileName).dir(), includeFile)
                      .filePath());
            }
            else {
                /*
                  It wasn't an include statement, so it;s something else.
                 */
                if (cc == '+') {
                    plus = true;
                    SKIP_CHAR();
                }
                if (cc != '=')
                    location.fatal(tr("Expected '=' or '+=' after key"));
                SKIP_CHAR();
                SKIP_SPACES();

                for (;;) {
                    if (cc == '\\') {
                        int metaCharPos;

                        SKIP_CHAR();
                        if (cc == '\n') {
                            SKIP_CHAR();
                        }
                        else if (cc > '0' && cc < '8') {
                            word += QChar(c.digitValue());
                            SKIP_CHAR();
                        }
                        else if ((metaCharPos = QString::fromLatin1("abfnrtv").indexOf(c)) != -1) {
                            word += "\a\b\f\n\r\t\v"[metaCharPos];
                            SKIP_CHAR();
                        }
                        else {
                            PUT_CHAR();
                        }
                    }
                    else if (c.isSpace() || cc == '#') {
                        if (inQuote) {
                            if (cc == '\n')
                                location.fatal(tr("Unterminated string"));
                            PUT_CHAR();
                        }
                        else {
                            if (!word.isEmpty()) {
                                if (metWord)
                                    stringValue += QLatin1Char(' ');
                                stringValue += word;
                                stringListValue << word;
                                metWord = true;
                                word.clear();
                                prevWordQuoted = false;
                            }
                            if (cc == '\n' || cc == '#')
                                break;
                            SKIP_SPACES();
                        }
                    }
                    else if (cc == '"') {
                        if (inQuote) {
                            if (!prevWordQuoted)
                                stringValue += QLatin1Char(' ');
                            stringValue += word;
                            if (!word.isEmpty())
                                stringListValue << word;
                            metWord = true;
                            word.clear();
                            prevWordQuoted = true;
                        }
                        inQuote = !inQuote;
                        SKIP_CHAR();
                    }
                    else if (cc == '$') {
                        QString var;
                        SKIP_CHAR();
                        while (c.isLetterOrNumber() || cc == '_') {
                            var += c;
                            SKIP_CHAR();
                        }
                        if (!var.isEmpty()) {
                            char *val = getenv(var.toLatin1().data());
                            if (val == 0) {
                                location.fatal(tr("Environment variable '%1' undefined").arg(var));
                            }
                            else {
                                word += QString(val);
                            }
                        }
                    }
                    else {
                        if (!inQuote && cc == '=')
                            location.fatal(tr("Unexpected '='"));
                        PUT_CHAR();
                    }
                }

                QStringList::ConstIterator key = keys.begin();
                while (key != keys.end()) {
                    if (!keySyntax.exactMatch(*key))
                        keyLoc.fatal(tr("Invalid key '%1'").arg(*key));

                    if (plus) {
                        if (locMap[*key].isEmpty()) {
                            locMap[*key] = keyLoc;
                        }
                        else {
                            locMap[*key].setEtc(true);
                        }
                        if (stringValueMap[*key].isEmpty()) {
                            stringValueMap[*key] = stringValue;
                        }
                        else {
                            stringValueMap[*key] +=
                                QLatin1Char(' ') + stringValue;
                        }
                        stringListValueMap[*key] += stringListValue;
                    }
                    else {
                        locMap[*key] = keyLoc;
                        stringValueMap[*key] = stringValue;
                        stringListValueMap[*key] = stringListValue;
                    }
                    ++key;
                }
            }
        }
        else {
            location.fatal(tr("Unexpected character '%1' at beginning of line")
                            .arg(c));
        }
    }
}
Example #26
0
void WLQuery::Process()
{
    if (Configuration::HuggleConfiguration->GlobalConfig_Whitelist.isEmpty())
    {
        // there is no whitelist in config for this wiki
        Syslog::HuggleLogs->ErrorLog("Unable to process WL request, there is no whitelist server defined");
        this->Result = new QueryResult();
        this->Result->SetError("Invalid URL");
        this->Status = Huggle::StatusInError;
        return;
    }
    this->StartTime = QDateTime::currentDateTime();
    this->Status = StatusProcessing;
    this->Result = new QueryResult();
    QUrl url(Configuration::HuggleConfiguration->GlobalConfig_Whitelist
             + "?action=read&wp=" + this->GetSite()->WhiteList);
    switch (this->Type)
    {
        case WLQueryType_ReadWL:
            break;
        case WLQueryType_SuspWL:
            url = QUrl(Configuration::HuggleConfiguration->GlobalConfig_Whitelist +
                       "susp.php?action=insert&" + this->Parameters);
            break;
        case WLQueryType_WriteWL:
            url = QUrl(Configuration::HuggleConfiguration->GlobalConfig_Whitelist + "?action=save&user="******"huggle_" + Configuration::HuggleConfiguration->SystemConfig_Username) +
                      "&wp=" + this->GetSite()->WhiteList);
            break;
    }
    QString params = "";
    QByteArray data;
    if (this->Type == WLQueryType_WriteWL)
    {
        QString whitelist = "";
        int p = 0;
        while (p < this->GetSite()->GetProjectConfig()->NewWhitelist.count())
        {
            if (!this->GetSite()->GetProjectConfig()->NewWhitelist.at(p).isEmpty())
            {
                whitelist += this->GetSite()->GetProjectConfig()->NewWhitelist.at(p) + "|";
            }
            p++;
        }
        if (whitelist.endsWith("|"))
        {
            whitelist = whitelist.mid(0, whitelist.length() - 1);
        }
        whitelist += "||EOW||";
        params = "wl=" + QUrl::toPercentEncoding(whitelist);
        data = params.toUtf8();
        long size = (long)data.size();
        Syslog::HuggleLogs->DebugLog("Sending whitelist data of size: " + QString::number(size) + " byte to " + this->GetSite()->Name);
    }
    QNetworkRequest request(url);
    if (this->Type == WLQueryType_ReadWL)
    {
        this->networkReply = Query::NetworkManager->get(request);
    } else
    {
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
        this->networkReply = Query::NetworkManager->post(request, data);
    }
    QObject::connect(this->networkReply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(WriteProgress(qint64,qint64)));
    QObject::connect(this->networkReply, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(WriteProgress(qint64,qint64)));
    QObject::connect(this->networkReply, SIGNAL(finished()), this, SLOT(Finished()));
    QObject::connect(this->networkReply, SIGNAL(readyRead()), this, SLOT(ReadData()));
}
Example #27
0
void EditFile::showFiles()
{
    QString s = edtFile->text();
#ifdef WIN32
    s.replace(QRegExp("\\\\"), "/");
#endif
    if (bDirMode){
        s = QFileDialog::getExistingDirectory(s, topLevelWidget(), title);
    }else if (bMultiplyMode){
        QStringList lst = QFileDialog::getOpenFileNames(filter, QString::null, topLevelWidget());
        if ((lst.count() > 1) || ((lst.count() > 0) && (lst[0].find(' ') >= 0))){
            for (QStringList::Iterator it = lst.begin(); it != lst.end(); ++it){
                *it = QString("\"") + *it + QString("\"");
            }
        }
        s = lst.join(" ");
    }else{
        if (s.isEmpty()){
            s = startDir;
            if (!s.isEmpty()){
                string d;
                d = QFile::encodeName(s);
                makedir((char*)d.c_str());
            }
        }
        if (createPreview){
            FileDialog *dlg = new FileDialog( s, filter, topLevelWidget(), title.isEmpty() ? i18n("Open") : title);
            if ( topLevelWidget()->icon() && !topLevelWidget()->icon()->isNull()){
                dlg->setIcon( *topLevelWidget()->icon() );
            }else if (qApp->mainWidget() && qApp->mainWidget()->icon() && !qApp->mainWidget()->icon()->isNull()){
                dlg->setIcon( *qApp->mainWidget()->icon() );
            }
            FilePreview *preview = createPreview(dlg);
#ifdef USE_KDE
            dlg->setOperationMode( KFileDialog::Opening);
            if (preview)
                dlg->setPreviewWidget(preview);
#else
            dlg->setMode( QFileDialog::ExistingFile );
            if (preview){
                dlg->setContentsPreview(preview, preview);
                dlg->setContentsPreviewEnabled(true);
                dlg->setPreviewMode(QFileDialog::Contents);
            }
#endif
            dlg->setFilter(filter);
            QString result;
            s = "";
            if (dlg->exec() == QDialog::Accepted){
                s = dlg->selectedFile();
            }
			delete preview;
            delete dlg;
        }else{
#ifdef USE_KDE
            if (title.isEmpty()){
                s = QFileDialog::getOpenFileName(s, filter, topLevelWidget());
            }else{
                s = QFileDialog::getOpenFileName(s, filter, topLevelWidget(), title);
            }
#else
            s = QFileDialog::getOpenFileName(s, filter, topLevelWidget(), "filedialog", title);
#endif
        }
    }
#ifdef WIN32
    s.replace(QRegExp("/"), "\\");
#endif
    if (s.length()) edtFile->setText(s);
}
Example #28
0
void SearchFilter::updateFilter() {
	mFilterRegExp.setPattern(mRegExp->currentText());
	mFilterRegExp.setCaseSensitivity(Qt::CaseInsensitive);
	if(! mFilterRegExp.isValid()) {
		QMessageBox::warning(this, tr("Warning - Museeq"), tr("Invalid regular expression, disabling it"));
		mFilterRegExp.setPattern(QString::null);
	}

	bool ok, neg = false;
	qint64 factor = 1;
	QString s = mSize->currentText();
	mFilterSizeExact = false;
	mFilterSize = 0;
	if(! s.isEmpty()) {
		if(s[0] == '=') {
			mFilterSizeExact = true;
			s = s.mid(1);
		} else if(s[0] == '<') {
			neg = true;
			s = s.mid(1);
		}

		if(! s.isEmpty()) {
			QString l = s.right(1).toLower();
			if(l == tr("k"))
				factor = 1024;
			else if(l == tr("m"))
				factor = 1024*1024;
			else if(l == tr("g"))
				factor = 1024*1024*1024;
			if(factor != 1)
				s = s.left(s.length() - 1);
		}

		mFilterSize = s.toInt(&ok);
		if(! ok) {
			QMessageBox::warning(this, tr("Warning - Museeq"), tr("Invalid size filter, disabling it"));
			mFilterSizeExact = false;
			mFilterSize = 0;
		} else {
			if(neg)
				mFilterSize *= -1;
			mFilterSize *= factor;
		}
	}

	neg = false;
	s = mBitrate->currentText();
	mFilterBitrateExact = false;
	mFilterBitrate = 0;
	if(! s.isEmpty()) {
		if(s[0] == '=') {
			mFilterBitrateExact = true;
			s = s.mid(1);
		} else if(s[0] == '<') {
			neg = true;
			s = s.mid(1);
		}
		mFilterBitrate = s.toInt(&ok);
		if(! ok) {
			QMessageBox::warning(this, tr("Warning - Museeq"), tr("Invalid bitrate filter, disabling it"));
			mFilterBitrateExact = false;
			mFilterBitrate = 0;
		} else if(neg)
			mFilterBitrate *= -1;
	}

	mFilterFreeSlot = mFreeSlot->isChecked();
                mFilterInvertMatch = mInvertMatch->isChecked();

	emit filterChanged();
}
Example #29
0
void EditEventValues::paintEvent(QPaintEvent *)
{
    mPainter = new QPainter(this);
    mPen = new QPen(Qt::black);
    mBrush = new QBrush(Qt::lightGray, Qt::SolidPattern);
    mFont.setPointSize(6);
    mPainter->setPen(*mPen);
    mPainter->setBrush(*mBrush);
    mPainter->setFont(mFont);

    //this is perhaps the background?

    long tick;

    unsigned char d0,d1;

    int event_x;
    int event_height;

    bool selected;

    int start_tick = 0 ;
    int end_tick = (width() * m_zoom);

    mPainter->drawRect(0,
                       0,
                       width() - 1,
                       height() - 1);

    m_seq->reset_draw_marker();
    while ( m_seq->get_next_event( m_status,
                                   m_cc,
                                   &tick, &d0, &d1,
                                   &selected ) == true )
    {

        if ( tick >= start_tick && tick <= end_tick )
        {

            /* turn into screen corrids */

            event_x = tick / m_zoom + c_keyboard_padding_x;

            /* generate the value */
            event_height = d1;

            if ( m_status == EVENT_PROGRAM_CHANGE ||
                 m_status == EVENT_CHANNEL_PRESSURE  ){

                event_height = d0;
            }

            /* draw vert lines */
            mPen->setWidth(2);
            mPainter->setPen(*mPen);
            mPainter->drawLine(event_x + 1,
                               height() - event_height,
                               event_x + 1,
                               height());

            //draw numbers
            QString val = QString::number(d1);

            mPen->setColor(Qt::black);
            mPen->setWidth(1);
            mPainter->setPen(*mPen);
            if (val.length() >= 1)
                mPainter->drawText(event_x + 3,
                                   c_dataarea_y - 25,
                                   val.at(0));
            if (val.length() >= 2)
                mPainter->drawText(event_x + 3,
                                   c_dataarea_y - 25 + 8,\
                                   val.at(1));
            if (val.length() >= 3)
                mPainter->drawText(event_x + 3,
                                   c_dataarea_y - 25 + 16,
                                   val.at(2));
        }
    }

    //draw edit line

    if (mLineAdjust)
    {
        int x,y,w,h;
        mPen->setColor(Qt::black);
        mPen->setStyle(Qt::DashLine);
        mPainter->setPen(*mPen);

        xy_to_rect ( mDropX,
                     mDropY,
                     mCurrentX,
                     mCurrentY,
                     &x, &y,
                     &w, &h );

        mOld->setX(x);
        mOld->setY(y);
        mOld->setWidth(w);
        mOld->setHeight(h);

        mPainter->drawLine(mCurrentX + c_keyboard_padding_x,
                           mCurrentY,
                           mDropX + c_keyboard_padding_x,
                           mDropY );
    }

    delete mPainter;
    delete mBrush;
    delete mPen;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QVariant SGBetaTableModel::data(const QModelIndex& index, qint32 role) const
{

  if (!index.isValid())
  {
    return QVariant();
  }

  if (role == Qt::SizeHintRole)
  {
    QStyleOptionComboBox comboBox;

    switch(index.column())
    {
      case BinNumber:
      {
        comboBox.currentText = QString("101");
        const QString header = headerData(BinNumber, Qt::Horizontal, Qt::DisplayRole).toString();
        if (header.length() > comboBox.currentText.length()) { comboBox.currentText = header; }
        break;
      }
      case Alpha:
      {
        comboBox.currentText = QString("10001");
        const QString header = headerData(BinNumber, Qt::Horizontal, Qt::DisplayRole).toString();
        if (header.length() > comboBox.currentText.length()) { comboBox.currentText = header; }
        break;
      }
      case Beta:
      {
        comboBox.currentText = QString("10001");
        const QString header = headerData(BinNumber, Qt::Horizontal, Qt::DisplayRole).toString();
        if (header.length() > comboBox.currentText.length()) { comboBox.currentText = header; }
        break;
      }
      case LineColor:
      {
        comboBox.currentText = QString("Dark Blue     ");
        const QString header = headerData(BinNumber, Qt::Horizontal, Qt::DisplayRole).toString();
        if (header.length() > comboBox.currentText.length())
        {
          comboBox.currentText = header;
        }
        break;
      }
      default:
        Q_ASSERT(false);
    }
    QFontMetrics fontMetrics(data(index, Qt::FontRole) .value<QFont > ());
    comboBox.fontMetrics = fontMetrics;
    QSize size(fontMetrics.width(comboBox.currentText), fontMetrics.height());
    return dream3dApp->style()->sizeFromContents(QStyle::CT_ComboBox, &comboBox, size);
  }
  else if (role == Qt::TextAlignmentRole)
  {
    return int(Qt::AlignRight | Qt::AlignVCenter);
  }
  else if (role == Qt::DisplayRole || role == Qt::EditRole)
  {
    int col = index.column();
    if (col == BinNumber)
    {
      return QVariant(m_BinNumbers[index.row()]);
    }
    else if (col == Alpha)
    {
      return QVariant(m_Alpha[index.row()]);
    }
    else if (col == Beta)
    {
      return QVariant(m_Beta[index.row()]);
    }
    else if (col == LineColor)
    {
      return QVariant(m_Colors[index.row()]);
    }
  }

  return QVariant();
}