Example #1
0
QString
findPartitionPathForMountPoint( const FstabEntryList& fstab,
                                const QString& mountPoint )
{
    if ( fstab.isEmpty() )
        return QString();

    for ( const FstabEntry& entry : fstab )
    {
        if ( entry.mountPoint == mountPoint )
        {
            QProcess readlink;
            QString partPath;

            if ( entry.partitionNode.startsWith( "/dev" ) ) // plain dev node
            {
                partPath = entry.partitionNode;
            }
            else if ( entry.partitionNode.startsWith( "LABEL=" ) )
            {
                partPath = entry.partitionNode.mid( 6 );
                partPath.remove( "\"" );
                partPath.replace( "\\040", "\\ " );
                partPath.prepend( "/dev/disk/by-label/" );
            }
            else if ( entry.partitionNode.startsWith( "UUID=" ) )
            {
                partPath = entry.partitionNode.mid( 5 );
                partPath.remove( "\"" );
                partPath = partPath.toLower();
                partPath.prepend( "/dev/disk/by-uuid/" );
            }
            else if ( entry.partitionNode.startsWith( "PARTLABEL=" ) )
            {
                partPath = entry.partitionNode.mid( 10 );
                partPath.remove( "\"" );
                partPath.replace( "\\040", "\\ " );
                partPath.prepend( "/dev/disk/by-partlabel/" );
            }
            else if ( entry.partitionNode.startsWith( "PARTUUID=" ) )
            {
                partPath = entry.partitionNode.mid( 9 );
                partPath.remove( "\"" );
                partPath = partPath.toLower();
                partPath.prepend( "/dev/disk/by-partuuid/" );
            }

            // At this point we either have /dev/sda1, or /dev/disk/by-something/...

            if ( partPath.startsWith( "/dev/disk/by-" ) ) // we got a fancy node
            {
                readlink.start( "readlink", { "-en", partPath });
                if ( !readlink.waitForStarted( 1000 ) )
                    return QString();
                if ( !readlink.waitForFinished( 1000 ) )
                    return QString();
                if ( readlink.exitCode() != 0 || readlink.exitStatus() != QProcess::NormalExit )
                    return QString();
                partPath = QString::fromLocal8Bit(
                               readlink.readAllStandardOutput() ).trimmed();
            }

            return partPath;
        }
    }

    return QString();
}
Example #2
0
/**
 * Write the source code body file for this classifier.
 */
void CppWriter::writeSourceFile(UMLClassifier *c, QFile &file)
{
    // open stream for writing
    QTextStream cpp (&file);

    // set the starting indentation at zero
    m_indentLevel = 0;

    //try to find a heading file (license, coments, etc)
    QString str;
    str = getHeadingFile(".cpp");
    if (!str.isEmpty()) {
        str.replace(QRegExp("%filename%"), fileName_ + ".cpp");
        str.replace(QRegExp("%filepath%"), file.fileName());
        cpp << str << m_endl;
    }

    // IMPORT statements
    // Q: Why all utils? Isnt just List and Vector the only classes we are using?
    // Our import *should* also look at operations, and check that objects being
    // used arent in another package (and thus need to be explicitly imported here).
    cpp << "#include \"" << className_ << ".h\"" << m_endl;
    writeBlankLine(cpp);

    if (c->visibility() == Uml::Visibility::Implementation) {
        writeClassDecl(c, cpp);
    }

    // Start body of class

    // Constructors: anything we more we need to do here ?
    //
    if (!c->isInterface())
        writeConstructorMethods(c, cpp);

    // METHODS
    //

    // write comment for section IF needed
    QString indnt = indent();
    if (forceDoc() || c->hasAccessorMethods() || c->hasOperationMethods()) {
        writeComment(" ", indnt, cpp);
        writeComment("Methods", indnt, cpp);
        writeComment(" ", indnt, cpp);
        writeBlankLine(cpp);
        writeBlankLine(cpp);
    }

    // write comment for sub-section IF needed
    if (forceDoc() || c->hasAccessorMethods() ) {
        writeComment("Accessor methods", indnt, cpp);
        writeComment(" ", indnt, cpp);
        writeBlankLine(cpp);
    }

    // Accessor methods for attributes
    const bool bInlineAccessors = policyExt()->getAccessorsAreInline();
    if (!bInlineAccessors && c->hasAttributes()) {
        writeAttributeMethods(c->getAttributeListStatic(Uml::Visibility::Public), Uml::Visibility::Public, false, true, !bInlineAccessors, cpp);
        writeAttributeMethods(c->getAttributeList(Uml::Visibility::Public), Uml::Visibility::Public, false, false, !bInlineAccessors, cpp);
        writeAttributeMethods(c->getAttributeListStatic(Uml::Visibility::Protected), Uml::Visibility::Protected, false, true, !bInlineAccessors, cpp);
        writeAttributeMethods(c->getAttributeList(Uml::Visibility::Protected), Uml::Visibility::Protected, false, false, !bInlineAccessors, cpp);
        writeAttributeMethods(c->getAttributeListStatic(Uml::Visibility::Private), Uml::Visibility::Private, false, true, !bInlineAccessors, cpp);
        writeAttributeMethods(c->getAttributeList(Uml::Visibility::Private), Uml::Visibility::Private, false, false, !bInlineAccessors, cpp);
    }

    // accessor methods for associations

    // public
    writeAssociationMethods(c->getSpecificAssocs(Uml::AssociationType::Association), Uml::Visibility::Public, false,
                            !INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);
    writeAssociationMethods(c->getUniAssociationToBeImplemented(), Uml::Visibility::Public, false,
                            !INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);
    writeAssociationMethods(c->getAggregations(), Uml::Visibility::Public, false,
                            !INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);
    writeAssociationMethods(c->getCompositions(), Uml::Visibility::Public, false,
                            !INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);

    // protected
    writeAssociationMethods(c->getSpecificAssocs(Uml::AssociationType::Association), Uml::Visibility::Protected, false,
                            !INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);
    writeAssociationMethods(c->getUniAssociationToBeImplemented(), Uml::Visibility::Protected, false,
                            !INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);
    writeAssociationMethods(c->getAggregations(), Uml::Visibility::Protected, false,
                            !INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);
    writeAssociationMethods(c->getCompositions(), Uml::Visibility::Protected, false,
                            !INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);

    // private
    writeAssociationMethods(c->getSpecificAssocs(Uml::AssociationType::Association), Uml::Visibility::Private, false,
                            !INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);
    writeAssociationMethods(c->getUniAssociationToBeImplemented(), Uml::Visibility::Private, false,
                            !INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);
    writeAssociationMethods(c->getAggregations(), Uml::Visibility::Private, false,
                            !INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);
    writeAssociationMethods(c->getCompositions(), Uml::Visibility::Private, false,
                            !INLINE_ASSOCIATION_METHODS, true, c->id(), cpp);
    writeBlankLine(cpp);

    // Other operation methods -- all other operations are now written
    //

    // write comment for sub-section IF needed
    if (forceDoc() || c->hasOperationMethods()) {
        writeComment("Other methods", indnt, cpp);
        writeComment(" ", indnt, cpp);
        writeBlankLine(cpp);
    }

    if (!policyExt()->getOperationsAreInline()) {
        writeOperations(c,false,Uml::Visibility::Public,cpp);
        writeOperations(c,false,Uml::Visibility::Protected,cpp);
        writeOperations(c,false,Uml::Visibility::Private,cpp);
    }

    // Yep, bringing up the back of the bus, our initialization method for attributes
    writeInitAttributeMethod(c, cpp);

    writeBlankLine(cpp);
}
Example #3
0
QString CustomEdit::evaluate(QString clause)
{
    int e0=0;
    while (true) {
        int s0 = clause.indexOf (QRegExp("\\{[A-Z]+\\}"), e0);

        if (s0 < 0)
            break;

        e0 = clause.indexOf ("}", s0);

        QString mid = clause.mid(s0 + 1, e0 - s0 - 1);
        QString repl = "";

        if (!mid.compare("TITLE")) {
            repl = m_pginfo->GetTitle();
            repl.replace("\'","\'\'");
        } else if (!mid.compare("SUBTITLE")) {
            repl = m_pginfo->GetSubtitle();
            repl.replace("\'","\'\'");
        } else if (!mid.compare("DESCR")) {
            repl = m_pginfo->GetDescription();
            repl.replace("\'","\'\'");
        } else if (!mid.compare("SERIESID")) {
            repl = QString("%1").arg(m_pginfo->GetSeriesID());
        } else if (!mid.compare("PROGID")) {
            repl = m_pginfo->GetProgramID();
        } else if (!mid.compare("SEASON")) {
            repl = QString::number(m_pginfo->GetSeason());
        } else if (!mid.compare("EPISODE")) {
            repl = QString::number(m_pginfo->GetEpisode());
        } else if (!mid.compare("CATEGORY")) {
            repl = m_pginfo->GetCategory();
        } else if (!mid.compare("CHANID")) {
            repl = QString("%1").arg(m_pginfo->GetChanID());
        } else if (!mid.compare("CHANNUM")) {
            repl = m_pginfo->GetChanNum();
        } else if (!mid.compare("SCHEDID")) {
            repl = m_pginfo->GetChannelSchedulingID();
        } else if (!mid.compare("CHANNAME")) {
            repl = m_pginfo->GetChannelName();
        } else if (!mid.compare("DAYNAME")) {
            repl = m_pginfo->GetScheduledStartTime().toString("dddd");
        } else if (!mid.compare("STARTDATE")) {
            repl = m_pginfo->GetScheduledStartTime().toString("yyyy-mm-dd hh:mm:ss");
        } else if (!mid.compare("ENDDATE")) {
            repl = m_pginfo->GetScheduledEndTime().toString("yyyy-mm-dd hh:mm:ss");
        } else if (!mid.compare("STARTTIME")) {
            repl = m_pginfo->GetScheduledStartTime().toString("hh:mm");
        } else if (!mid.compare("ENDTIME")) {
            repl = m_pginfo->GetScheduledEndTime().toString("hh:mm");
        } else if (!mid.compare("STARTSEC")) {
            QDateTime date = m_pginfo->GetScheduledStartTime();
            QDateTime midnight = QDateTime(date.date());
            repl = QString("%1").arg(midnight.secsTo(date));
        } else if (!mid.compare("ENDSEC")) {
            QDateTime date = m_pginfo->GetScheduledEndTime();
            QDateTime midnight = QDateTime(date.date());
            repl = QString("%1").arg(midnight.secsTo(date));
        }
        // unknown tags are simply removed
        clause.replace(s0, e0 - s0 + 1, repl);
    }
    return clause;
}
Example #4
0
static void writeValue(QTextStream &f, const QString &value)
{
    QString escaped = value;
    escaped.replace('"', "\"\"");
    f << "\"" << escaped << "\"";
}
Example #5
0
QString UPnpDevice::toString(uint padding) const
{
    QString ret =
        QString("UPnP Device\n"
                "===========\n"
                "deviceType:       %1\n"
                "friendlyName:     %2\n"
                "manufacturer:     %3\n"
                "manufacturerURL:  %4\n"
                "modelDescription: %5\n"
                "modelName:        %6\n"
                "modelNumber:      %7\n"
                "modelURL:         %8\n")
        .arg(m_sDeviceType      )
        .arg(m_sFriendlyName    )
        .arg(m_sManufacturer    )
        .arg(m_sManufacturerURL )
        .arg(m_sModelDescription)
        .arg(m_sModelName       )
        .arg(m_sModelNumber     )
        .arg(m_sModelURL        ) +
        QString("serialNumber:     %1\n"
                "UPC:              %2\n"
                "presentationURL:  %3\n"
                "UDN:              %4\n")
        .arg(m_sSerialNumber    )
        .arg(m_sUPC             )
        .arg(m_sPresentationURL )
        .arg(m_sUDN             );

    if (!m_lstExtra.empty())
    {
        NameValues::const_iterator it = m_lstExtra.begin();
        ret += "Extra key value pairs\n";
        for (; it != m_lstExtra.end(); ++it)
        {
            ret += (*it).sName;
            ret += ":";
            int int_padding = 18 - ((*it).sName.length() + 1);
            for (int i = 0; i < int_padding; i++)
                ret += " ";
            ret += QString("%1\n").arg((*it).sValue);
        }
    }

    if (!m_listIcons.empty())
    {
        ret += "Icon List:\n";
        UPnpIconList::const_iterator it = m_listIcons.begin();
        for (; it != m_listIcons.end(); ++it)
            ret += (*it)->toString(padding+2) + "\n";
    }

    if (!m_listServices.empty())
    {
        ret += "Service List:\n";
        UPnpServiceList::const_iterator it = m_listServices.begin();
        for (; it != m_listServices.end(); ++it)
            ret += (*it)->toString(padding+2) + "\n";
    }

    if (!m_listDevices.empty())
    {
        ret += "Device List:\n";
        UPnpDeviceList::const_iterator it = m_listDevices.begin();
        for (; it != m_listDevices.end(); ++it)
            ret += (*it)->toString(padding+2) + "\n";
        ret += "\n";
    }

    // remove trailing newline
    if (ret.endsWith("\n"))
        ret = ret.left(ret.length()-1);

    // add any padding as necessary
    if (padding)
    {
        QString pad;
        for (uint i = 0; i < padding; i++)
            pad += " ";
        ret = pad + ret.replace("\n", QString("\n%1").arg(pad));
    }

    return ret;
}
Example #6
0
bool KXSConfigDialog::create()
{
    QVBoxLayout *topLayout = new QVBoxLayout(plainPage(), spacingHint());
    QHBoxLayout *layout = new QHBoxLayout(topLayout, spacingHint());
    QVBox *controlLayout = new QVBox(plainPage());
    controlLayout->setSpacing(spacingHint());
    layout->addWidget(controlLayout);
    ((QBoxLayout*)controlLayout->layout())->addStrut(120);

    KConfig config(mConfigFile);

    QString xmlFile = "/doesntexist";
#ifdef XSCREENSAVER_CONFIG_DIR
    xmlFile = XSCREENSAVER_CONFIG_DIR;
#endif

    xmlFile += "/" + mExeName + ".xml";
    if ( QFile::exists( xmlFile ) ) {
	// We can use the xscreensaver xml config files.
	KXSXml xmlParser(controlLayout);
	xmlParser.parse( xmlFile );
	mConfigItemList = *xmlParser.items();
	QWidget *spacer = new QWidget(controlLayout);
	controlLayout->setStretchFactor(spacer, 1 );
	QString descr = xmlParser.description();
	if ( !descr.isEmpty() ) {
	    descr.replace('\n',' ');
	    descr = descr.simplifyWhiteSpace();
	    QLabel *l = new QLabel( i18n( descr.utf8() ), plainPage() );
	    l->setAlignment ( WordBreak );
 	    topLayout->addWidget( l );
 	}
    } else {
        // fall back to KDE's old config files.
	int idx = 0;
	while (true) {
	    QString group = QString("Arg%1").arg(idx);
	    if (config.hasGroup(group)) {
		config.setGroup(group);
		QString type = config.readEntry("Type");
		if (type == "Range") {
		    KXSRangeControl *rc = new KXSRangeControl(controlLayout, group, config);
		    mConfigItemList.append(rc);
		} else if (type == "DoubleRange") {
		    KXSDoubleRangeControl *rc =
			new KXSDoubleRangeControl(controlLayout, group, config);
		    mConfigItemList.append(rc);
		} else if (type == "Check") {
		    KXSCheckBoxControl *cc = new KXSCheckBoxControl(controlLayout, group,
			    config);
		    mConfigItemList.append(cc);
		} else if (type == "DropList") {
		    KXSDropListControl *dl = new KXSDropListControl(controlLayout, group,
			    config);
		    mConfigItemList.append(dl);
		}
	    } else {
		break;
	    }
	    idx++;
	}
	if ( idx == 0 )
	    return false;
    }

    QPtrListIterator<KXSConfigItem> it( mConfigItemList );
    KXSConfigItem *item;
    while ( (item = it.current()) != 0 ) {
	++it;
	item->read( config );
        QWidget *i = dynamic_cast<QWidget*>(item);
        if (i) {
            connect( i, SIGNAL(changed()), SLOT(slotChanged()) );
        }
    }

    mPreviewProc = new KProcess;
    connect(mPreviewProc, SIGNAL(processExited(KProcess *)),
	    SLOT(slotPreviewExited(KProcess *)));

    mPreviewTimer = new QTimer(this);
    connect(mPreviewTimer, SIGNAL(timeout()), SLOT(slotNewPreview()));

    mPreview = new QWidget(plainPage());
    mPreview->setFixedSize(250, 200);
    //  mPreview->setBackgroundMode(QWidget::NoBackground);
    mPreview->setBackgroundColor(Qt::black);

    layout->add(mPreview);
    show();

    // So that hacks can XSelectInput ButtonPressMask
    XSelectInput(qt_xdisplay(), mPreview->winId(), widgetEventMask );

    slotPreviewExited(0);
    return true;
}
Example #7
0
static QString _2space(QString s)
{
    int index = s.indexOf("_");

    return (index == -1) ? s : s.replace(index, 1, " ");
}
Example #8
0
KExiv2::MetaDataMap KExiv2::getIptcTagsDataList(const QStringList& iptcKeysFilter, bool invertSelection) const
{
    if (d->iptcMetadata().empty())
       return MetaDataMap();

    try
    {
        Exiv2::IptcData iptcData = d->iptcMetadata();
        iptcData.sortByKey();

        QString     ifDItemName;
        MetaDataMap metaDataMap;

        for (Exiv2::IptcData::iterator md = iptcData.begin(); md != iptcData.end(); ++md)
        {
            QString key = QString::fromLocal8Bit(md->key().c_str());

            // Decode the tag value with a user friendly output.
            std::ostringstream os;
            os << *md;
            QString value = QString(os.str().c_str());
            // To make a string just on one line.
            value.replace('\n', ' ');

            // Some Iptc key are redondancy. check if already one exist...
            MetaDataMap::iterator it = metaDataMap.find(key);

            // We apply a filter to get only the Iptc tags that we need.

            if (!invertSelection)
            {
                if (iptcKeysFilter.contains(key.section('.', 1, 1)))
                {
                    if (it == metaDataMap.end())
                        metaDataMap.insert(key, value);
                    else
                    {
                        QString v = *it;
                        v.append(", ");
                        v.append(value);
                        metaDataMap.insert(key, v);
                    }
                }
            }
            else
            {
                if (!iptcKeysFilter.contains(key.section('.', 1, 1)))
                {
                    if (it == metaDataMap.end())
                        metaDataMap.insert(key, value);
                    else
                    {
                        QString v = *it;
                        v.append(", ");
                        v.append(value);
                        metaDataMap.insert(key, v);
                    }
                }
            }
        }

        return metaDataMap;
    }
    catch (Exiv2::Error& e)
    {
        d->printExiv2ExceptionError("Cannot parse Iptc metadata using Exiv2 ", e);
    }

    return MetaDataMap();
}
Example #9
0
void GrepViewWidget::searchActivated()
{
	if ( grepdlg->keepOutputFlag() )
		slotKeepOutput();

	m_tabWidget->showPage( m_curOutput );

	m_curOutput->setLastFileName("");
	m_curOutput->setMatchCount( 0 );

	QString command, files;

	// waba: code below breaks on filenames containing a ',' !!!
	QStringList filelist = QStringList::split(",", grepdlg->filesString());

	if (grepdlg->useProjectFilesFlag())
	{
		KDevProject *openProject = m_part->project();
		if (openProject)
		{
			QString tmpFilePath;
			QStringList projectFiles = openProject->allFiles();
			if (!projectFiles.isEmpty())
			{
				tmpFilePath = openProject->projectDirectory() + QChar(QDir::separator()) + ".grep.tmp";
				QString dir = grepdlg->directoryString(), file;
				QValueList<QRegExp> regExpList;

				if (dir.endsWith(QChar(QDir::separator())))
					dir.truncate(dir.length() - 1);

				if (!filelist.isEmpty())
				{
					for (QStringList::Iterator it = filelist.begin(); it != filelist.end(); ++it)
						regExpList.append(QRegExp(*it, true, true));
				}

				m_tempFile.setName(tmpFilePath);
				if (m_tempFile.open(IO_WriteOnly))
				{
					QTextStream out(&m_tempFile);
					for (QStringList::Iterator it = projectFiles.begin(); it != projectFiles.end(); ++it)
					{
						file = QDir::cleanDirPath(openProject->projectDirectory() + QChar(QDir::separator()) + *it);

						QFileInfo info(file);
						if (grepdlg->recursiveFlag() && !info.dirPath(true).startsWith(dir)) continue;
						if (!grepdlg->recursiveFlag() && info.dirPath(true) != dir) continue;

						bool matchOne = regExpList.count() == 0;
						for (QValueList<QRegExp>::Iterator it2 = regExpList.begin(); it2 != regExpList.end() && !matchOne; ++it2)
							matchOne = (*it2).exactMatch(file);

						if (matchOne)
							out << KShellProcess::quote(file) + "\n";
					}

					m_tempFile.close();
				}
				else
				{
					KMessageBox::error(this, i18n("Unable to create a temporary file for search."));
					return;
				}
			}

			command = "cat ";
			command += tmpFilePath.replace(' ', "\\ ");
		}
	}
	else
	{
		if (!filelist.isEmpty())
		{
			QStringList::Iterator it(filelist.begin());
			files = KShellProcess::quote(*it);
			++it;
			for (; it != filelist.end(); ++it)
				files += " -o -name " + KShellProcess::quote(*it);
		}

		QString filepattern = "find ";
		filepattern += KShellProcess::quote(grepdlg->directoryString());
		if (!grepdlg->recursiveFlag())
			filepattern += " -maxdepth 1";
		filepattern += " \\( -name ";
		filepattern += files;
		filepattern += " \\) -print -follow";
		if (grepdlg->noFindErrorsFlag())
			filepattern += " 2>/dev/null";

		command = filepattern + " " ;
	}

	QStringList excludelist = QStringList::split(",", grepdlg->excludeString());
	if (!excludelist.isEmpty())
	{
		QStringList::Iterator it(excludelist.begin());
		command += "| grep -v ";
		for (; it != excludelist.end(); ++it)
			command += "-e " + KShellProcess::quote(*it) + " ";
	}

	if (!grepdlg->useProjectFilesFlag())
	{
		// quote spaces in filenames going to xargs
		command += "| sed \"s/ /\\\\\\ /g\" ";
	}

	command += "| xargs " ;

#ifndef USE_SOLARIS
	command += "egrep -H -n -s ";
#else
	// -H reported as not being available on Solaris,
	// but we're buggy without it on Linux.
	command += "egrep -n ";
#endif

	if (!grepdlg->caseSensitiveFlag())
	{
		command += "-i ";
	}
	command += "-e ";

	m_lastPattern = grepdlg->patternString();
	QString pattern = grepdlg->templateString();
	if (grepdlg->regexpFlag())
		pattern.replace(QRegExp("%s"), grepdlg->patternString());
	else
		pattern.replace(QRegExp("%s"), escape( grepdlg->patternString() ) );
	command += KShellProcess::quote(pattern);
	m_curOutput->startJob("", command);

	m_part->mainWindow()->raiseView(this);
	m_part->core()->running(m_part, true);
}
Example #10
0
LogFile::LogFile(const QString & szName)
{
	m_szFilename = szName;

	QFileInfo fi(m_szFilename);
	QString szTmpName = fi.fileName();

	m_bCompressed = (fi.suffix() == "gz");
	if(m_bCompressed)
	{
		//removes trailing dot and extension
		szTmpName.chop(3);
	}
	QString szTypeToken = szTmpName.section('_',0,0);
	// Ignore non-logs files, this includes '.' and '..'
	if(KviQString::equalCI(szTypeToken,"channel") || KviQString::equalCI(szTypeToken,"deadchannel"))
	{
		m_szType = "channel";
		m_eType = Channel;
	} else if(KviQString::equalCI(szTypeToken,"console"))
	{
		m_szType = "console";
		m_eType = Console;
	} else if(KviQString::equalCI(szTypeToken,"query"))
	{
		m_szType = "query";
		m_eType = Query;
	} else if(KviQString::equalCI(szTypeToken,"dccchat"))
	{
		m_szType = "dccchat";
		m_eType = DccChat;
	} else {
		m_szType = "";
		m_eType = Other;
	}

	KviCString szUndecoded = szTmpName.section('.',0,0);
	szUndecoded.cutToFirst('_');
	m_szName = szUndecoded.hexDecode(szUndecoded.ptr()).ptr();

	szUndecoded = szTmpName.section('.',1).section('_',0,-2);
	m_szNetwork = szUndecoded.hexDecode(szUndecoded.ptr()).ptr();

	QString szDate = szTmpName.section('_',-1).section('.',0,-2);

	switch(KVI_OPTION_UINT(KviOption_uintOutputDatetimeFormat))
	{
		case 1:
			m_date = QDate::fromString(szDate, Qt::ISODate);
			break;
		case 2:
			m_date = QDate::fromString(szDate, Qt::SystemLocaleShortDate);
			if(!m_date.isValid())
			{
				// some locale date formats use '/' as a separator; we change them to '-'
				// when creating log files. Try to reverse that change here
				QString szUnescapedDate = szDate;
				szUnescapedDate.replace('-', KVI_PATH_SEPARATOR_CHAR);
				m_date = QDate::fromString(szUnescapedDate, Qt::SystemLocaleShortDate);
				if(m_date.isValid())
				{
					//qt4 defaults to 1900 for years. So "11" means "1911" instead of "2011".. what a pity
					if(m_date.year() < 1990)
						m_date = m_date.addYears(100);
				}
			}
			break;
		case 0:
		default:
			m_date = QDate::fromString(szDate, "yyyy.MM.dd");
			break;
	}
	if(!m_date.isValid())
	{
		// probably the log has been created when the OutputDatetimeFormat option
		// was set to a different value. Try to guess its format
		m_date = QDate::fromString(szDate, "yyyy.MM.dd");
		if(!m_date.isValid())
		{
			m_date = QDate::fromString(szDate, Qt::ISODate);
			if(!m_date.isValid())
			{
				m_date = QDate::fromString(szDate, Qt::SystemLocaleShortDate);
				if(!m_date.isValid())
				{
					// some locale date formats use '/' as a separator; we change them to '-'
					// when creating log files. Try to reverse that change here
					QString szUnescapedDate = szDate;
					szUnescapedDate.replace('-', KVI_PATH_SEPARATOR_CHAR);
					m_date = QDate::fromString(szUnescapedDate, Qt::SystemLocaleShortDate);
					if(m_date.isValid())
					{
						//qt4 defaults to 1900 for years. So "11" means "1911" instead of "2011".. what a pity
						if(m_date.year() < 1990)
							m_date = m_date.addYears(100);
					}
				}
				// if the date is still not valid, we give up
			}
		}
	}
}
Example #11
0
void DialogPlainText::updateText() {
    QString temp = this->plainTextEdit->toPlainText();
    this->savedText = temp.replace("\n", " ").replace("{", " ").replace("} ", " ").replace("\r", " ");
}
Example #12
0
void CQSpeciesDetail::setFramework(int framework)
{
  CopasiWidget::setFramework(framework);

  const CModel * pModel = NULL;

  if (mpMetab)
    pModel = mpMetab->getModel();

  QString ValueUnits;

  if (pModel)
    ValueUnits = FROM_UTF8(pModel->getConcentrationUnitsDisplayString());

  if (!ValueUnits.isEmpty())
    ValueUnits = " (" + ValueUnits + ")";

  QString RateUnits;

  if (pModel)
    RateUnits = FROM_UTF8(pModel->getConcentrationRateUnitsDisplayString());

  if (!RateUnits.isEmpty())
    RateUnits = " (" + RateUnits + ")";

  QString FrequencyUnits;

  if (pModel)
    FrequencyUnits = FROM_UTF8(pModel->getFrequencyUnit());

  if (FrequencyUnits != "none")
    FrequencyUnits = " (" + FrequencyUnits + ")";

  switch (mFramework)
    {
      case 0:
        mpLblValue->setText("Concentration" + ValueUnits);

        if (mpMetab != NULL &&
            (CModelEntity::Status) mItemToType[mpComboBoxType->currentIndex()] == CModelEntity::ASSIGNMENT)
          mpLblExpression->setText("Expression" + ValueUnits);
        else
          mpLblExpression->setText("Expression" + RateUnits);

        mpLblRate->setText("Rate" + RateUnits);

        ValueUnits.replace(0, 1, '\n'); // Line break instead of space
        mpLblInitialValue->setText("Initial Concentration" + ValueUnits);
        mpLblInitialExpression->setText("Initial Expression" + ValueUnits);

        mpEditInitialValue->setText(QString::number(mInitialConcentration, 'g', 10));

        if (mpMetab != NULL)
          {
            mpEditInitialValue->setReadOnly(!mpMetab->isInitialConcentrationChangeAllowed());
            mpEditCurrentValue->setText(QString::number(mpMetab->getConcentration(), 'g', 10));
            mpEditRate->setText(QString::number(mpMetab->getConcentrationRate(), 'g', 10));
          }
        else
          {
            mpEditInitialValue->setReadOnly(false);
            mpEditCurrentValue->setText("");
            mpEditRate->setText("");
          }

        break;

      case 1:
        mpLblInitialValue->setText("Initial Particle Number");

        ValueUnits.replace(0, 1, '\n'); // Line break instead of space
        mpLblInitialExpression->setText("Initial Expression" + ValueUnits);

        if (mpMetab != NULL &&
            mpMetab->getStatus() == CModelEntity::ASSIGNMENT)
          mpLblExpression->setText("Expression" + ValueUnits);
        else
          mpLblExpression->setText("Expression" + RateUnits);

        mpLblValue->setText("Particle Number");
        mpLblRate->setText("Rate" + FrequencyUnits);

        mpEditInitialValue->setText(QString::number(mInitialNumber, 'g', 10));
        mpEditInitialValue->setReadOnly(false);

        if (mpMetab != NULL)
          {
            mpEditCurrentValue->setText(QString::number(mpMetab->getValue(), 'g', 10));
            mpEditRate->setText(QString::number(mpMetab->getRate(), 'g', 10));
          }
        else
          {
            mpEditCurrentValue->setText("");
            mpEditRate->setText("");
          }

        break;
    }
}
Example #13
0
void CKSocketClient::playMessage(const QString &message) {
	ostringstream os;
	os << message.toStdString() << endl;
	ColorKeeperModel::logMessage(os.str());
	if (message.compare(QString("GET_SCREEN_INFO")) == 0) {
		try {
			const DisplayDevice
					& currScreen =
							ColorKeeperModel::Instance().getDeviceInfo().getCalibrableDisplayDevice(
									_currentScreen);
			ColorKeeperModel::Instance().addCalibModelForScreen(_currentScreen);
			QString sendMessage("SCREEN_INFO_ [index]");

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

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

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

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

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

	} else if (message.contains(QString("SHOULD_DISPLAY")) == true) {
		QChar sc = message[15];
		int screen = sc.digitValue();
		QChar va = message[17];
		bool tog = false;
		if (va == QChar('t')) {
			tog = true;
		}
		ColorKeeperModel::Instance().shoudDisplayCalibForScreen(screen, tog);
	} else if (message.contains(QString("UPDATE_CALIB_FILE")) == true) {
		QChar sc = message[18];
		int screen = sc.digitValue();
		QString infos = message;
		infos.remove(0, 19);
		infos.replace(QChar('#'), QChar('\n'));
		ColorKeeperModel::Instance().updateCorrection(screen, infos);
		QString sendMessage("UPDATE_OK\n");
		writeSocket(sendMessage);
	} else if (message.contains(QString("BUH_BYE")) == true) {
		QChar sc = message[8];
		int screen = sc.digitValue();
		ColorKeeperModel::Instance().endCalib(screen);
	}
}
Example #14
0
int main (int argc, char *argv[])
{
  FILE *sdb;
  struct dbSpawnStruct dbSpawn;
  int count=0;

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

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

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

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

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

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

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

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

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


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

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

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

  out << "<TR>";

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

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

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

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

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

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

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

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

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

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

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

     // close the document
     out << footer;

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

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

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

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

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

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

    // increment counter
    count++;
  }

  // clsoe the DB
   fclose (sdb);

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

   out << footer;
}
Example #15
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    app.setQuitOnLastWindowClosed(false);
    app.setApplicationName(APP_NAME);
    app.setApplicationVersion("2.0");
    app.setOrganizationName(ORGANIZATION_NAME);

    bool bCallRequest = false;

    g_LanguagesPath         = QApplication::applicationDirPath() + "/lang";
    g_AppSettingsFolderPath = QDir::homePath() + "/OutCALL";
    g_AppDirPath            = QApplication::applicationDirPath();

    if (argc==2 && QString(argv[1]) == "installer")
    {
        // Setup log file paths
        QDir().mkpath(g_AppSettingsFolderPath);
        QFile(g_AppSettingsFolderPath + "/outcall.log").remove();

        if (global::IsOutlookInstalled())
        {
            if (global::EnableOutlookIntegration(true))
                global::log("Outlook plugin installed successfully.", LOG_INFORMATION);
            else
                global::log("Could not install Outlook plugin.", LOG_ERROR);
        }
        else
        {
            global::log("Outlook was not detected.", LOG_INFORMATION);
        }
        return 0;
    }

    if (argc == 2)
    {
        bCallRequest = QString(argv[1]).contains("Dial#####");
    }

    if (bCallRequest)
    {
        QStringList arguments = QString(argv[1]).split("#####");
        QString contactName = arguments[1];
        QString numbers = QString(arguments[2]).replace("outcall://", "");

        contactName.replace("&&&", " ");
        numbers.replace("&&&", " ");

        QLocalSocket s;
        s.connectToServer(LOCAL_SERVER_NAME);

        global::log("MAIN LOCAL", LOG_INFORMATION);

        QString msg = QObject::tr("It appears that %1 is not running.\n" \
                                  "Note for Windows 7/Vista users: please make sure that %2 and Outlook are running under same level of privileges. " \
                                  "Either both elevated (Run as Administrator option) or non-elevated.").arg(APP_NAME).arg(APP_NAME);

        if (!s.waitForConnected(2000))
        {
            MsgBoxInformation(msg);
        }
        else
        {
            if (!s.waitForReadyRead(2000)) // wait for "OK" from the local server
            {
                MsgBoxInformation(QObject::tr("Timeout on local socket. Maybe %1 is not running?").arg(APP_NAME));
            }
            else
            {
                QByteArray socket_data = QString("outlook_call %1 %2\n").arg(QString(contactName.toLatin1().toBase64())).
                                         arg(QString(numbers.toLatin1().toBase64())).toLatin1();
                s.write(socket_data);

                if (!s.waitForBytesWritten(2000))
                    MsgBoxError(QObject::tr("Failed local socket write()."));
            }
        }
        s.disconnectFromServer();
        s.close();

        return 0;
    }

    Notifier notifier;
    QString lang = global::getSettingsValue("language", "general").toString();
    QTranslator translator;
    if (!lang.isEmpty())
    {
        if (translator.load(QString("%1/%2.lang").arg(g_LanguagesPath).arg(lang)))
        {
            qApp->installTranslator(&translator);
        }
        else
        {
            global::setSettingsValue("language", "", "general");
            MsgBoxError(QObject::tr("Failed to load language file."));
        }
    }

    QString username  = global::getSettingsValue("username", "settings").toString();
    QByteArray secret = global::getSettingsValue("password", "settings").toByteArray();
    AsteriskManager manager(username, QString(QByteArray::fromBase64(secret)));

    OutCall outcall;
    outcall.show();

    LocalServer localServer;
    return app.exec();
}
Example #16
0
/*
  This will go through and modify some of the ENML tags and turn
  them into HTML tags.  Things like en-media & en-crypt have no
  HTML values, so we turn them into HTML.
  */
void NoteFormatter::modifyTags(QDomDocument &doc) {
    QLOG_TRACE() << "Entering NeverNote.modifyTags";
    tempFiles.clear();
    QDomElement docElem = doc.documentElement();

    // Modify en-media tags
    QDomNodeList anchors = docElem.elementsByTagName("en-media");
    qint32 enMediaCount = anchors.length();
    for (qint32 i=enMediaCount-1; i>=0; --i) {
            QDomElement enmedia = anchors.at(i).toElement();
            if (enmedia.hasAttribute("type")) {
                    QDomAttr attr = enmedia.attributeNode("type");
                    QDomAttr hash = enmedia.attributeNode("hash");
                    QStringList type = attr.nodeValue().split("/");
                    if (type.size() >= 2) {
                        QString appl = type[1];
                        if (type[0] == "image")
                            modifyImageTags(doc, docElem, enmedia, hash);
                        else
                            modifyApplicationTags(doc, docElem, enmedia, hash, appl);
                    }
            }
    }

    // Modify todo tags
    anchors = docElem.elementsByTagName("en-todo");
    qint32 enTodoCount = anchors.length();
    for (qint32 i=enTodoCount-1; i>=0; i--) {
            QDomElement enmedia = anchors.at(i).toElement();
            modifyTodoTags(enmedia);
    }

    anchors = docElem.elementsByTagName("en-crypt");
    qint32 enCryptLen = anchors.length();
    for (qint32 i=enCryptLen-1; i>=0; i--) {
            QDomElement enmedia(anchors.at(i).toElement());
            enmedia.setAttribute("contentEditable","false");
            enmedia.setAttribute("src", QString("file://")+global.fileManager.getImageDirPath("encrypt.png"));
            enmedia.setAttribute("en-tag","en-crypt");
            enmedia.setAttribute("alt", enmedia.text());
            global.cryptCounter++;
            enmedia.setAttribute("id", "crypt"+QString().number(global.cryptCounter));
            QString encryptedText = enmedia.text();

            // If the encryption string contains crlf at the end, remove them because they mess up the javascript.
            if (encryptedText.endsWith("\n"))
                    encryptedText.truncate(encryptedText.length()-1);
            if (encryptedText.endsWith("\r"))
                    encryptedText.truncate(encryptedText.length()-1);

            // Add the commands
            QString hint = enmedia.attribute("hint");
            hint = hint.replace("'","&apos;");
            enmedia.setAttribute("onClick", "window.jsbridge.decryptText('crypt"+QString().number(global.cryptCounter)+"', '"+encryptedText+"', '"+hint+"');");
            enmedia.setAttribute("onMouseOver", "style.cursor='hand'");
            enmedia.setTagName("img");
            enmedia.removeChild(enmedia.firstChild());   // Remove the actual encrypted text
    }


    // Modify link tags
    anchors = docElem.elementsByTagName("a");
    enCryptLen = anchors.length();
    for (unsigned int i=0; i<anchors.length(); i++) {
            QDomElement element = anchors.at(i).toElement();
            if (!element.attribute("href").toLower().startsWith("latex://"))
                    element.setAttribute("title", element.attribute("href"));
            else {
                    element.setAttribute("title", element.attribute("title").toLower().replace("http://latex.codecogs.com/gif.latex?",""));
            }
    }

    QLOG_TRACE() << "Leaving NeverNote.modifyTags";
}
Example #17
0
void luksaddkey::pbAdd( void )
{
	DialogMsg msg( this ) ;
	QString ExistingKey = m_ui->textEditExistingPassphrase->text() ;

	QString NewKey = m_ui->textEditPassphraseToAdd->text() ;
	QString NewKey_1 = m_ui->lineEditReEnterPassphrase->text() ;

	m_volumePath = m_ui->textEditPathToVolume->text() ;

	if( m_volumePath.isEmpty() ){
		return msg.ShowUIOK( tr( "ERROR!" ),tr( "atleast one required field is empty" ) ) ;
	}

	m_volumePath = utility::resolvePath( m_volumePath ) ;

	if( m_ui->radioButtonPassphraseInVolumeFromFile->isChecked() ){
		if( ExistingKey.isEmpty() ){
			return msg.ShowUIOK( tr( "ERROR!" ),tr( "atleast one required field is empty" ) ) ;
		}
	}

	if( m_ui->radioButtonNewPassphraseFromFile->isChecked() ){
		if( NewKey.isEmpty() ){
			return msg.ShowUIOK( tr( "ERROR!" ),tr( "atleast one required field is empty" ) ) ;
		}
	}else{
		if( NewKey != NewKey_1 ){
			msg.ShowUIOK( tr( "ERROR!" ),tr( "keys do not match" ) ) ;
			m_ui->textEditPassphraseToAdd->clear() ;
			m_ui->lineEditReEnterPassphrase->clear() ;
			m_ui->textEditPassphraseToAdd->setFocus() ;
			return ;
		}
	}

	QString existingPassType ;

	if( m_ui->radioButtonPassphraseInVolumeFromFile->isChecked() ){
		ExistingKey = utility::resolvePath( ExistingKey ).replace( "\"","\"\"\"" ) ;
		existingPassType = QString( "-u" ) ;
	}else{
		existingPassType = QString( "-u" ) ;
		ExistingKey = utility::keyPath() + QString( "-existingKey" ) ;

		QString k = m_ui->textEditExistingPassphrase->text() ;

		utility::keySend( ExistingKey,k ) ;
	}

	QString newPassType ;
	if( m_ui->radioButtonNewPassphraseFromFile->isChecked() ){
		NewKey = utility::resolvePath( NewKey ).replace( "\"","\"\"\"" ) ;
		newPassType = QString( "-n" ) ;
	}else{
		newPassType = QString( "-n" ) ;

		NewKey = utility::keyPath() + QString( "-newKey" ) ;

		QString k = m_ui->textEditPassphraseToAdd->text() ;

		utility::keySend( NewKey,k ) ;
	}

	const QString& a = QString( ZULUCRYPTzuluCrypt ) ;
	QString b = m_volumePath ;
	b.replace( "\"","\"\"\"" ) ;
	const QString& c = existingPassType ;
	const QString& d = ExistingKey ;
	const QString& e = newPassType ;
	const QString& f = NewKey ;

	QString exe = QString( "%1 -a -d \"%2\" %3 \"%4\" %5 \"%6\"" ).arg( a,b,c,d,e,f ) ;

	m_isWindowClosable = false ;

	this->disableAll() ;

	this->taskFinished( Task::await<int>( utility::exec( exe ) ) ) ;
}
Example #18
0
// Modify the en-media tag into an attachment
void NoteFormatter::modifyApplicationTags(QDomDocument &doc, QDomElement &docElem, QDomElement &enmedia, QDomAttr &hash, QString appl) {
    QLOG_TRACE() <<  "Entering NeverNote.modifyApplicationTags";
    if (appl.toLower() == "vnd.evernote.ink") {
            inkNote = true;
            readOnly = true;
            buildInkNote(enmedia, hash);
            QLOG_DEBUG() << doc.toString();
            return;
    }
    ResourceTable resTable;
    QString contextFileName;
    qint32 resLid = resTable.getLidByHashHex(QString::fromStdString(note.guid), hash.value());
    Resource r;
    resTable.get(r, resLid);
    if (!r.__isset.data)
        resourceError = true;
    else {
        if (r.mime == "application/pdf" && pdfPreview) {
            modifyPdfTags(resLid, enmedia);
            return;
        }
        QString fileDetails = "";
        MimeReference ref;
        if (r.__isset.attributes && r.attributes.__isset.fileName)
            fileDetails = QString::fromStdString(r.attributes.fileName);
        fileDetails = ref.getExtensionFromMime(QString::fromStdString(r.mime), fileDetails);


        if (fileDetails != "") {
            if (!noteHistory) {
                enmedia.setAttribute("href", QString("nnres:") +QString::number(resLid)
                                     +global.attachmentNameDelimeter +fileDetails);
                contextFileName = global.fileManager.getTmpDirPath(QString::number(resLid) +global.attachmentNameDelimeter + fileDetails);
            } else {
                enmedia.setAttribute("href", QString("nnres:") +QString::number(resLid) +QString("-")+ QString::number(note.updateSequenceNum)
                                     +global.attachmentNameDelimeter +fileDetails);
                contextFileName = global.fileManager.getTmpDirPath(QString::number(resLid) +QString("-")+ QString(note.updateSequenceNum)
                                                                   +global.attachmentNameDelimeter + fileDetails);
            }
        } else {
            if (!noteHistory) {
                enmedia.setAttribute("href", "nnres:" +QString::number(resLid) +QString("-") +QString(note.updateSequenceNum)
                                     +global.attachmentNameDelimeter +appl);
                contextFileName = global.fileManager.getTmpDirPath(QString::number(resLid) +QString("-")
                                                                   +QString(note.updateSequenceNum)
                                                                   +global.attachmentNameDelimeter + appl);
            } else {
                enmedia.setAttribute("href", "nnres:" +QString::number(resLid)
                                     +global.attachmentNameDelimeter +appl);
                contextFileName = global.fileManager.getTmpDirPath(QString::number(resLid)
                                                                   +global.attachmentNameDelimeter + appl);
            }
        }

        // Setup the context menu.  This is useful if we want to do a "save as" or such
        contextFileName = contextFileName.replace("\\", "/");
        enmedia.setAttribute("onContextMenu", "window.browserWindow.resourceContextMenu('" +contextFileName +"');");
        enmedia.setAttribute("en-tag", "en-media");
        enmedia.setAttribute("lid", QString::number(resLid));
        enmedia.setTagName("a");

        QDomElement newText = doc.createElement("img");
        QFile tfile(contextFileName);
        tfile.open(QIODevice::WriteOnly);
        tfile.close();

        // Build an icon of the image
        QString fileExt;
        if (r.__isset.attributes && r.attributes.__isset.fileName)
            fileExt = QString::fromStdString(r.attributes.fileName);
        else
            fileExt = appl;
        fileExt = ref.getExtensionFromMime(r.mime, r.attributes.fileName);
        QString icon = findIcon(resLid, r, fileExt);
        newText.setAttribute("src", "file:///"+icon);
        if (r.__isset.attributes && r.attributes.__isset.fileName)
            newText.setAttribute("title",QString::fromStdString(r.attributes.fileName));
        newText.setAttribute("en-tag", "temporary");
        enmedia.removeChild(enmedia.firstChild());
        enmedia.appendChild(newText);
        QLOG_TRACE() << "Leaving NeverNote.modifyApplicationTags";
    }
}
    Base::Quantity validateAndInterpret(QString& input, int& pos, QValidator::State& state) const
    {
        Base::Quantity res;
        const double max = this->maximum;
        const double min = this->minimum;

        QString copy = input;

        int len = copy.size();

        const bool plus = max >= 0;
        const bool minus = min <= 0;

        switch (len) {
        case 0:
            state = max != min ? QValidator::Intermediate : QValidator::Invalid;
            goto end;
        case 1:
            if (copy.at(0) == locale.decimalPoint()) {
                state = QValidator::Intermediate;
                copy.prepend(QLatin1Char('0'));
                pos++;
                len++;
                goto end;
            }
            else if (copy.at(0) == QLatin1Char('+')) {
                // the quantity parser doesn't allow numbers of the form '+1.0'
                state = QValidator::Invalid;
                goto end;
            }
            else if (copy.at(0) == QLatin1Char('-')) {
                if (minus)
                    state = QValidator::Intermediate;
                else
                    state = QValidator::Invalid;
                goto end;
            }
            break;
        case 2:
            if (copy.at(1) == locale.decimalPoint()
                && (plus && copy.at(0) == QLatin1Char('+'))) {
                state = QValidator::Intermediate;
                goto end;
            }
            if (copy.at(1) == locale.decimalPoint()
                && (minus && copy.at(0) == QLatin1Char('-'))) {
                state = QValidator::Intermediate;
                copy.insert(1, QLatin1Char('0'));
                pos++;
                len++;
                goto end;
            }
            break;
        default: break;
        }

        {
            if (copy.at(0) == locale.groupSeparator()) {
                state = QValidator::Invalid;
                goto end;
            }
            else if (len > 1) {
                bool decOccurred = false;
                for (int i = 0; i<copy.size(); i++) {
                    if (copy.at(i) == locale.decimalPoint()) {
                        // Disallow multiple decimal points within the same numeric substring
                        if (decOccurred) {
                            state = QValidator::Invalid;
                            goto end;
                        }
                        decOccurred = true;
                    }
                    // Reset decOcurred if non-numeric character found
                    else if (!(copy.at(i) == locale.groupSeparator() || copy.at(i).isDigit())) {
                        decOccurred = false;
                    }
                }
            }

            bool ok = false;
            double value = min;

            if (locale.negativeSign() != QLatin1Char('-'))
                copy.replace(locale.negativeSign(), QLatin1Char('-'));
            if (locale.positiveSign() != QLatin1Char('+'))
                copy.replace(locale.positiveSign(), QLatin1Char('+'));

            try {
                QString copy2 = copy;
                copy2.remove(locale.groupSeparator());

                res = Base::Quantity::parse(copy2);
                value = res.getValue();
                ok = true;
            }
            catch (Base::Exception&) {
            }

            if (!ok) {
                // input may not be finished
                state = QValidator::Intermediate;
            }
            else if (value >= min && value <= max) {
                if (copy.endsWith(locale.decimalPoint())) {
                    // input shouldn't end with a decimal point
                    state = QValidator::Intermediate;
                }
                else if (res.getUnit().isEmpty() && !this->unit.isEmpty()) {
                    // if not dimensionless the input should have a dimension
                    state = QValidator::Intermediate;
                }
                else if (res.getUnit() != this->unit) {
                    state = QValidator::Invalid;
                }
                else {
                    state = QValidator::Acceptable;
                }
            }
            else if (max == min) { // when max and min is the same the only non-Invalid input is max (or min)
                state = QValidator::Invalid;
            }
            else {
                if ((value >= 0 && value > max) || (value < 0 && value < min)) {
                    state = QValidator::Invalid;
                }
                else {
                    state = QValidator::Intermediate;
                }
            }
        }
end:
        if (state != QValidator::Acceptable) {
            res.setValue(max > 0 ? min : max);
        }

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

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

    QString result;

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

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

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

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

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

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

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

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

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

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

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

	result += "println ";
	int i = 0;
	while ( i < (int) fmt.length() ) {
	    if ( fmt[i] == '%' ) {
		int percent = i;
		i++;
		while ( i < (int) fmt.length() &&
			QString("diouxXeEfFgGaAcsCSpn%\"").indexOf(fmt[i]) == -1 )
		    i++;
		if ( fmt[i] == '%' ) {
		    result += fmt[i++];
		} else if ( fmt[i] != '"' ) {
		    if ( percent == 1 ) {
			result.truncate( result.length() - 1 );
		    } else {
			result += "\" + ";
		    }
		    i++;
		    if ( arg1.endsWith(".latin1()") )
			arg1.truncate( arg1.length() - 9 );
		    result += arg1;
		    if ( i == (int) fmt.length() - 1 ) {
			i++;
		    } else {
			result += " + \"";
		    }
		}
	    } else {
		result += fmt[i++];
	    }
	}
	result += ";";
    } else if ( coutRegExp.exactMatch(code) &&
		program.filter("var cout").isEmpty() ) {
	QStringList args = coutRegExp.cap(1).split(lshiftRegExp);
	args.replaceInStrings( endlRegExp, "\"\\n\"" );
	if ( args.last() == "\"\\n\"" ) {
	    args.erase( args.end() - 1 );
	    if ( args.isEmpty() )
		args << "\"\"";
	    result += "println ";
	} else {
	    result += "print ";
	}
	result += args.join( " + " ) + ";";
    } else {
	result = convertExpr( qsTree, code, classesWithNoQ );
    }
    return result;
}
Example #21
0
void Login::RetrievePrivateConfig()
{
    if (this->LoginQuery != NULL)
    {
        if (this->LoginQuery->Processed())
        {
            if (this->LoginQuery->Result->Failed)
            {
                /// \todo LOCALIZE ME
                this->ui->label_6->setText("Login failed unable to retrieve user config: " + this->LoginQuery->Result->ErrorMessage);
                this->Progress(0);
                this->_Status = LoginFailed;
                this->LoginQuery->SafeDelete();
                this->LoginQuery = NULL;
                return;
            }
            QDomDocument d;
            d.setContent(this->LoginQuery->Result->Data);
            QDomNodeList l = d.elementsByTagName("rev");
            if (l.count() == 0)
            {
                Syslog::HuggleLogs->DebugLog(this->LoginQuery->Result->Data);
                /// \todo LOCALIZE ME
                this->ui->label_6->setText("Login failed unable to retrieve user config, the api query returned no data");
                this->Progress(0);
                this->_Status = LoginFailed;
                this->LoginQuery->SafeDelete();
                this->LoginQuery = NULL;
                return;
            }
            QDomElement data = l.at(0).toElement();
            if (Configuration::ParseUserConfig(data.text()))
            {
                if (!Configuration::HuggleConfiguration->LocalConfig_EnableAll)
                {
                    /// \todo LOCALIZE ME
                    this->ui->label_6->setText("Login failed because you don't have enable:true in your personal config");
                    this->Progress(0);
                    this->_Status = LoginFailed;
                    this->LoginQuery->SafeDelete();
                    this->LoginQuery = NULL;
                    return;
                }
                this->LoginQuery->SafeDelete();
                this->LoginQuery = NULL;
                this->_Status = RetrievingUser;
                return;
            }
            /// \todo LOCALIZE ME
            this->ui->label_6->setText("Login failed unable to parse the user config, see debug log for more details");
            Syslog::HuggleLogs->DebugLog(data.text());
            this->Progress(0);
            this->_Status = LoginFailed;
            this->LoginQuery->SafeDelete();
            this->LoginQuery = NULL;
            return;
        }
        return;
    }
    this->Progress(82);
    this->ui->label_6->setText("Retrieving user config");
    this->LoginQuery = new ApiQuery();
    QString page = Configuration::HuggleConfiguration->GlobalConfig_UserConf;
    page = page.replace("$1", Configuration::HuggleConfiguration->UserName);
    this->LoginQuery->SetAction(ActionQuery);
    this->LoginQuery->Parameters = "prop=revisions&rvprop=content&rvlimit=1&titles=" +
            QUrl::toPercentEncoding(page);
    this->LoginQuery->Process();
}
Example #22
0
void HttpConnection::respond() {
  if ((m_socket->peerAddress() != QHostAddress::LocalHost
      && m_socket->peerAddress() != QHostAddress::LocalHostIPv6)
     || m_httpserver->isLocalAuthEnabled()) {
    // Authentication
    const QString peer_ip = m_socket->peerAddress().toString();
    const int nb_fail = m_httpserver->NbFailedAttemptsForIp(peer_ip);
    if (nb_fail >= MAX_AUTH_FAILED_ATTEMPTS) {
      m_generator.setStatusLine(403, "Forbidden");
      m_generator.setMessage(tr("Your IP address has been banned after too many failed authentication attempts."));
      write();
      return;
    }
    QString auth = m_parser.header().value("Authorization");
    if (auth.isEmpty()) {
      // Return unauthorized header
      qDebug("Auth is Empty...");
      m_generator.setStatusLine(401, "Unauthorized");
      m_generator.setValue("WWW-Authenticate",  "Digest realm=\""+QString(QBT_REALM)+"\", nonce=\""+m_httpserver->generateNonce()+"\", opaque=\""+m_httpserver->generateNonce()+"\", stale=\"false\", algorithm=\"MD5\", qop=\"auth\"");
      write();
      return;
    }
    //qDebug("Auth: %s", qPrintable(auth.split(" ").first()));
    if (QString::compare(auth.split(" ").first(), "Digest", Qt::CaseInsensitive) != 0
        || !m_httpserver->isAuthorized(auth.toUtf8(), m_parser.header().method())) {
      // Update failed attempt counter
      m_httpserver->increaseNbFailedAttemptsForIp(peer_ip);
      qDebug("client IP: %s (%d failed attempts)", qPrintable(peer_ip), nb_fail);
      // Return unauthorized header
      m_generator.setStatusLine(401, "Unauthorized");
      m_generator.setValue("WWW-Authenticate",  "Digest realm=\""+QString(QBT_REALM)+"\", nonce=\""+m_httpserver->generateNonce()+"\", opaque=\""+m_httpserver->generateNonce()+"\", stale=\"false\", algorithm=\"MD5\", qop=\"auth\"");
      write();
      return;
    }
    // Client successfully authenticated, reset number of failed attempts
    m_httpserver->resetNbFailedAttemptsForIp(peer_ip);
  }
  QString url  = m_parser.url();
  // Favicon
  if (url.endsWith("favicon.ico")) {
    qDebug("Returning favicon");
    QFile favicon(":/Icons/skin/qbittorrent16.png");
    if (favicon.open(QIODevice::ReadOnly)) {
      const QByteArray data = favicon.readAll();
      favicon.close();
      m_generator.setStatusLine(200, "OK");
      m_generator.setContentTypeByExt("png");
      m_generator.setMessage(data);
      write();
    } else {
      respondNotFound();
    }
    return;
  }

  QStringList list = url.split('/', QString::SkipEmptyParts);
  if (list.contains(".") || list.contains("..")) {
    respondNotFound();
    return;
  }

  if (list.isEmpty())
    list.append("index.html");

  if (list.size() >= 2) {
    if (list[0] == "json") {
      if (list[1] == "torrents") {
        respondTorrentsJson();
        return;
      }
      if (list.size() > 2) {
        if (list[1] == "propertiesGeneral") {
          const QString& hash = list[2];
          respondGenPropertiesJson(hash);
          return;
        }
        if (list[1] == "propertiesTrackers") {
          const QString& hash = list[2];
          respondTrackersPropertiesJson(hash);
          return;
        }
        if (list[1] == "propertiesFiles") {
          const QString& hash = list[2];
          respondFilesPropertiesJson(hash);
          return;
        }
      } else {
        if (list[1] == "preferences") {
          respondPreferencesJson();
          return;
        } else {
          if (list[1] == "transferInfo") {
            respondGlobalTransferInfoJson();
            return;
          }
        }
      }
    }
    if (list[0] == "command") {
      const QString& command = list[1];
      if (command == "shutdown") {
        qDebug() << "Shutdown request from Web UI";
        // Special case handling for shutdown, we
        // need to reply to the Web UI before
        // actually shutting down.
        m_generator.setStatusLine(200, "OK");
        write();
        qApp->processEvents();
        // Exit application
        qApp->exit();
      } else {
        respondCommand(command);
        m_generator.setStatusLine(200, "OK");
        write();
      }
      return;
    }
  }

  // Icons from theme
  //qDebug() << "list[0]" << list[0];
  if (list[0] == "theme" && list.size() == 2) {
#ifdef DISABLE_GUI
    url = ":/Icons/oxygen/"+list[1]+".png";
#else
    url = IconProvider::instance()->getIconPath(list[1]);
#endif
    qDebug() << "There icon:" << url;
  } else {
    if (list[0] == "images") {
      list[0] = "Icons";
    } else {
      if (list.last().endsWith(".html"))
        list.prepend("html");
      list.prepend("webui");
    }
    url = ":/" + list.join("/");
  }
  QFile file(url);
  if (!file.open(QIODevice::ReadOnly)) {
    qDebug("File %s was not found!", qPrintable(url));
    respondNotFound();
    return;
  }
  QString ext = list.last();
  int index = ext.lastIndexOf('.') + 1;
  if (index > 0)
    ext.remove(0, index);
  else
    ext.clear();
  QByteArray data = file.readAll();
  file.close();

  // Translate the page
  if (ext == "html" || (ext == "js" && !list.last().startsWith("excanvas"))) {
    QString dataStr = QString::fromUtf8(data.constData());
    translateDocument(dataStr);
    if (url.endsWith("about.html")) {
      dataStr.replace("${VERSION}", VERSION);
    }
    data = dataStr.toUtf8();
  }
  m_generator.setStatusLine(200, "OK");
  m_generator.setContentTypeByExt(ext);
  m_generator.setMessage(data);
  write();
}
void UnifiedDiffEditorWidget::showDiff()
{
    QString diffText;

    int blockNumber = 0;
    int charNumber = 0;

    QMap<int, QList<DiffSelection> > selections;

    for (int i = 0; i < m_contextFileData.count(); i++) {
        const FileData &fileData = m_contextFileData.at(i);
        const QString leftFileInfo = QLatin1String("--- ")
                + fileData.leftFileInfo.fileName + QLatin1Char('\n');
        const QString rightFileInfo = QLatin1String("+++ ")
                + fileData.rightFileInfo.fileName + QLatin1Char('\n');
        setFileInfo(blockNumber, fileData.leftFileInfo, fileData.rightFileInfo);
        selections[blockNumber].append(DiffSelection(&m_fileLineFormat));
        blockNumber++;
        selections[blockNumber].append(DiffSelection(&m_fileLineFormat));
        blockNumber++;

        diffText += leftFileInfo;
        diffText += rightFileInfo;
        charNumber += leftFileInfo.count() + rightFileInfo.count();

        if (fileData.binaryFiles) {
            selections[blockNumber].append(DiffSelection(&m_chunkLineFormat));
            blockNumber++;
            const QString binaryLine = QLatin1String("Binary files ")
                    + fileData.leftFileInfo.fileName
                    + QLatin1String(" and ")
                    + fileData.rightFileInfo.fileName
                    + QLatin1String(" differ\n");
            diffText += binaryLine;
            charNumber += binaryLine.count();
        } else {
            for (int j = 0; j < fileData.chunks.count(); j++) {
                const int oldBlockNumber = blockNumber;
                diffText += showChunk(fileData.chunks.at(j),
                                      (j == fileData.chunks.count() - 1)
                                      && fileData.lastChunkAtTheEndOfFile,
                                      &blockNumber,
                                      &charNumber,
                                      &selections);
                if (!fileData.chunks.at(j).contextChunk)
                    setChunkIndex(oldBlockNumber, blockNumber - oldBlockNumber, j);
            }
        }

    }

    if (diffText.isEmpty()) {
        setPlainText(tr("No difference."));
        return;
    }

    diffText.replace(QLatin1Char('\r'), QLatin1Char(' '));
    const bool oldIgnore = m_ignoreCurrentIndexChange;
    m_ignoreCurrentIndexChange = true;
    setPlainText(diffText);
    m_ignoreCurrentIndexChange = oldIgnore;

    setSelections(selections);
}
Example #24
0
QT_BEGIN_NAMESPACE

void
UnixMakefileGenerator::init()
{
    if(init_flag)
        return;
    init_flag = true;

    if(project->isEmpty("QMAKE_EXTENSION_SHLIB")) {
        if(project->isEmpty("QMAKE_CYGWIN_SHLIB")) {
            project->values("QMAKE_EXTENSION_SHLIB").append("so");
        } else {
            project->values("QMAKE_EXTENSION_SHLIB").append("dll");
        }
    }

    if (project->isEmpty("QMAKE_PREFIX_SHLIB"))
        // Prevent crash when using the empty variable.
        project->values("QMAKE_PREFIX_SHLIB").append("");

    if(!project->isEmpty("QMAKE_FAILED_REQUIREMENTS")) /* no point */
        return;

    ProStringList &configs = project->values("CONFIG");
    if(project->isEmpty("ICON") && !project->isEmpty("RC_FILE"))
        project->values("ICON") = project->values("RC_FILE");
    if(project->isEmpty("QMAKE_EXTENSION_PLUGIN"))
        project->values("QMAKE_EXTENSION_PLUGIN").append(project->first("QMAKE_EXTENSION_SHLIB"));
    if(project->isEmpty("QMAKE_COPY_FILE"))
        project->values("QMAKE_COPY_FILE").append("$(COPY)");
    if(project->isEmpty("QMAKE_STREAM_EDITOR"))
        project->values("QMAKE_STREAM_EDITOR").append("sed");
    if(project->isEmpty("QMAKE_COPY_DIR"))
        project->values("QMAKE_COPY_DIR").append("$(COPY) -R");
    if(project->isEmpty("QMAKE_INSTALL_FILE"))
        project->values("QMAKE_INSTALL_FILE").append("$(COPY_FILE)");
    if(project->isEmpty("QMAKE_INSTALL_DIR"))
        project->values("QMAKE_INSTALL_DIR").append("$(COPY_DIR)");
    if(project->isEmpty("QMAKE_INSTALL_PROGRAM"))
        project->values("QMAKE_INSTALL_PROGRAM").append("$(COPY_FILE)");
    if(project->isEmpty("QMAKE_LIBTOOL"))
        project->values("QMAKE_LIBTOOL").append("libtool --silent");
    if(project->isEmpty("QMAKE_SYMBOLIC_LINK"))
        project->values("QMAKE_SYMBOLIC_LINK").append("ln -f -s");

    /* this should probably not be here, but I'm using it to wrap the .t files */
    if(project->first("TEMPLATE") == "app")
        project->values("QMAKE_APP_FLAG").append("1");
    else if(project->first("TEMPLATE") == "lib")
        project->values("QMAKE_LIB_FLAG").append("1");
    else if(project->first("TEMPLATE") == "subdirs") {
        MakefileGenerator::init();
        if(project->isEmpty("MAKEFILE"))
            project->values("MAKEFILE").append("Makefile");
        return; /* subdirs is done */
    }

    if (!project->isEmpty("TARGET"))
        project->values("TARGET") = escapeFilePaths(project->values("TARGET"));

    project->values("QMAKE_ORIG_TARGET") = project->values("TARGET");
    project->values("QMAKE_ORIG_DESTDIR") = project->values("DESTDIR");
    project->values("QMAKE_LIBS") += escapeFilePaths(project->values("LIBS"));
    project->values("QMAKE_LIBS_PRIVATE") += escapeFilePaths(project->values("LIBS_PRIVATE"));
    if((!project->isEmpty("QMAKE_LIB_FLAG") && !project->isActiveConfig("staticlib")) ||
       (project->isActiveConfig("qt") &&  project->isActiveConfig("plugin"))) {
        if(configs.indexOf("dll") == -1) configs.append("dll");
    } else if(!project->isEmpty("QMAKE_APP_FLAG") || project->isActiveConfig("dll")) {
        configs.removeAll("staticlib");
    }
    if(!project->isEmpty("QMAKE_INCREMENTAL"))
        project->values("QMAKE_LFLAGS") += project->values("QMAKE_LFLAGS_INCREMENTAL");
    else if(!project->isEmpty("QMAKE_LFLAGS_PREBIND") &&
            !project->values("QMAKE_LIB_FLAG").isEmpty() &&
            project->isActiveConfig("dll"))
        project->values("QMAKE_LFLAGS") += project->values("QMAKE_LFLAGS_PREBIND");
    if(!project->isEmpty("QMAKE_INCDIR"))
        project->values("INCLUDEPATH") += project->values("QMAKE_INCDIR");
    project->values("QMAKE_L_FLAG")
            << (project->isActiveConfig("rvct_linker") ? "--userlibpath "
              : project->isActiveConfig("armcc_linker") ? "-L--userlibpath="
              : project->isActiveConfig("ti_linker") ? "--search_path="
              : "-L");
    ProStringList ldadd;
    if(!project->isEmpty("QMAKE_LIBDIR")) {
        const ProStringList &libdirs = project->values("QMAKE_LIBDIR");
        for(int i = 0; i < libdirs.size(); ++i) {
            if(!project->isEmpty("QMAKE_LFLAGS_RPATH") && project->isActiveConfig("rpath_libdirs"))
                project->values("QMAKE_LFLAGS") += var("QMAKE_LFLAGS_RPATH") + libdirs[i];
            project->values("QMAKE_LIBDIR_FLAGS") += "-L" + escapeFilePath(libdirs[i]);
        }
    }
    ldadd += project->values("QMAKE_LIBDIR_FLAGS");
    if (project->isActiveConfig("mac")) {
        if (!project->isEmpty("QMAKE_FRAMEWORKPATH")) {
            const ProStringList &fwdirs = project->values("QMAKE_FRAMEWORKPATH");
            for (int i = 0; i < fwdirs.size(); ++i)
                project->values("QMAKE_FRAMEWORKPATH_FLAGS") += "-F" + escapeFilePath(fwdirs[i]);
        }
        ldadd += project->values("QMAKE_FRAMEWORKPATH_FLAGS");
    }
    ProStringList &qmklibs = project->values("QMAKE_LIBS");
    qmklibs = ldadd + qmklibs;
    if(!project->isEmpty("QMAKE_RPATHDIR")) {
        const ProStringList &rpathdirs = project->values("QMAKE_RPATHDIR");
        for(int i = 0; i < rpathdirs.size(); ++i) {
            if(!project->isEmpty("QMAKE_LFLAGS_RPATH"))
                project->values("QMAKE_LFLAGS") += var("QMAKE_LFLAGS_RPATH") + escapeFilePath(QFileInfo(rpathdirs[i].toQString()).absoluteFilePath());
        }
    }
    if (!project->isEmpty("QMAKE_RPATHLINKDIR")) {
        const ProStringList &rpathdirs = project->values("QMAKE_RPATHLINKDIR");
        for (int i = 0; i < rpathdirs.size(); ++i) {
            if (!project->isEmpty("QMAKE_LFLAGS_RPATHLINK"))
                project->values("QMAKE_LFLAGS") += var("QMAKE_LFLAGS_RPATHLINK") + escapeFilePath(QFileInfo(rpathdirs[i].toQString()).absoluteFilePath());
        }
    }

    if(project->isActiveConfig("GNUmake") && !project->isEmpty("QMAKE_CFLAGS_DEPS"))
        include_deps = true; //do not generate deps
    if(project->isActiveConfig("compile_libtool"))
        Option::obj_ext = ".lo"; //override the .o

    MakefileGenerator::init();

    QString comps[] = { "C", "CXX", "OBJC", "OBJCXX", QString() };
    for(int i = 0; !comps[i].isNull(); i++) {
        QString compile_flag = var("QMAKE_COMPILE_FLAG");
        if(compile_flag.isEmpty())
            compile_flag = "-c";

        if(doPrecompiledHeaders() && !project->isEmpty("PRECOMPILED_HEADER")) {
            QString pchFlags = var(ProKey("QMAKE_" + comps[i] + "FLAGS_USE_PRECOMPILE"));

            QString pchBaseName;
            if(!project->isEmpty("PRECOMPILED_DIR")) {
                pchBaseName = Option::fixPathToTargetOS(project->first("PRECOMPILED_DIR").toQString());
                if(!pchBaseName.endsWith(Option::dir_sep))
                    pchBaseName += Option::dir_sep;
            }
            pchBaseName += project->first("QMAKE_ORIG_TARGET").toQString();

            // replace place holders
            pchFlags = pchFlags.replace("${QMAKE_PCH_INPUT}",
                                        fileFixify(project->first("PRECOMPILED_HEADER").toQString()));
            pchFlags = pchFlags.replace("${QMAKE_PCH_OUTPUT_BASE}", pchBaseName);
            if (project->isActiveConfig("icc_pch_style")) {
                // icc style
                pchFlags = pchFlags.replace("${QMAKE_PCH_OUTPUT}",
                                            pchBaseName + project->first("QMAKE_PCH_OUTPUT_EXT"));
            } else {
                // gcc style (including clang_pch_style)
                QString headerSuffix;
                if (project->isActiveConfig("clang_pch_style"))
                    headerSuffix = project->first("QMAKE_PCH_OUTPUT_EXT").toQString();
                else
                    pchBaseName += project->first("QMAKE_PCH_OUTPUT_EXT").toQString();

                pchBaseName += Option::dir_sep;
                QString pchOutputFile;

                if(comps[i] == "C") {
                    pchOutputFile = "c";
                } else if(comps[i] == "CXX") {
                    pchOutputFile = "c++";
                } else if(project->isActiveConfig("objective_c")) {
                    if(comps[i] == "OBJC")
                        pchOutputFile = "objective-c";
                    else if(comps[i] == "OBJCXX")
                        pchOutputFile = "objective-c++";
                }

                if(!pchOutputFile.isEmpty()) {
                    pchFlags = pchFlags.replace("${QMAKE_PCH_OUTPUT}",
                            pchBaseName + pchOutputFile + headerSuffix);
                }
            }

            if (!pchFlags.isEmpty())
                compile_flag += " " + pchFlags;
        }

        QString cflags;
        if(comps[i] == "OBJC" || comps[i] == "OBJCXX")
            cflags += " $(CFLAGS)";
        else
            cflags += " $(" + comps[i] + "FLAGS)";
        compile_flag += cflags + " $(INCPATH)";

        QString compiler = comps[i];
        if (compiler == "C")
            compiler = "CC";

        const ProKey runComp("QMAKE_RUN_" + compiler);
        if(project->isEmpty(runComp))
            project->values(runComp).append("$(" + compiler + ") " + compile_flag + " " + var("QMAKE_CC_O_FLAG") + "$obj $src");
        const ProKey runCompImp("QMAKE_RUN_" + compiler + "_IMP");
        if(project->isEmpty(runCompImp))
            project->values(runCompImp).append("$(" + compiler + ") " + compile_flag + " " + var("QMAKE_CC_O_FLAG") + "\"$@\" \"$<\"");
    }

    if (project->isActiveConfig("mac") && !project->isEmpty("TARGET") && !project->isActiveConfig("compile_libtool") &&
       ((project->isActiveConfig("build_pass") || project->isEmpty("BUILDS")))) {
        ProString bundle;
        if(project->isActiveConfig("bundle") && !project->isEmpty("QMAKE_BUNDLE_EXTENSION")) {
            bundle = unescapeFilePath(project->first("TARGET"));
            if(!project->isEmpty("QMAKE_BUNDLE_NAME"))
                bundle = unescapeFilePath(project->first("QMAKE_BUNDLE_NAME"));
            if(!bundle.endsWith(project->first("QMAKE_BUNDLE_EXTENSION")))
                bundle += project->first("QMAKE_BUNDLE_EXTENSION");
        } else if(project->first("TEMPLATE") == "app" && project->isActiveConfig("app_bundle")) {
            bundle = unescapeFilePath(project->first("TARGET"));
            if(!project->isEmpty("QMAKE_APPLICATION_BUNDLE_NAME"))
                bundle = unescapeFilePath(project->first("QMAKE_APPLICATION_BUNDLE_NAME"));
            if(!bundle.endsWith(".app"))
                bundle += ".app";
            if(project->isEmpty("QMAKE_BUNDLE_LOCATION"))
                project->values("QMAKE_BUNDLE_LOCATION").append("Contents/MacOS");
            project->values("QMAKE_PKGINFO").append(project->first("DESTDIR") + bundle + "/Contents/PkgInfo");
            project->values("QMAKE_BUNDLE_RESOURCE_FILE").append(project->first("DESTDIR") + bundle + "/Contents/Resources/empty.lproj");
        } else if(project->first("TEMPLATE") == "lib" && !project->isActiveConfig("staticlib") &&
                  ((!project->isActiveConfig("plugin") && project->isActiveConfig("lib_bundle")) ||
                   (project->isActiveConfig("plugin") && project->isActiveConfig("plugin_bundle")))) {
            bundle = unescapeFilePath(project->first("TARGET"));
            if(project->isActiveConfig("plugin")) {
                if(!project->isEmpty("QMAKE_PLUGIN_BUNDLE_NAME"))
                    bundle = unescapeFilePath(project->first("QMAKE_PLUGIN_BUNDLE_NAME"));
                if(!project->isEmpty("QMAKE_BUNDLE_EXTENSION") && !bundle.endsWith(project->first("QMAKE_BUNDLE_EXTENSION")))
                    bundle += project->first("QMAKE_BUNDLE_EXTENSION");
                else if(!bundle.endsWith(".plugin"))
                    bundle += ".plugin";
                if(project->isEmpty("QMAKE_BUNDLE_LOCATION"))
                    project->values("QMAKE_BUNDLE_LOCATION").append("Contents/MacOS");
            } else {
                if(!project->isEmpty("QMAKE_FRAMEWORK_BUNDLE_NAME"))
                    bundle = unescapeFilePath(project->first("QMAKE_FRAMEWORK_BUNDLE_NAME"));
                if(!project->isEmpty("QMAKE_BUNDLE_EXTENSION") && !bundle.endsWith(project->first("QMAKE_BUNDLE_EXTENSION")))
                    bundle += project->first("QMAKE_BUNDLE_EXTENSION");
                else if(!bundle.endsWith(".framework"))
                    bundle += ".framework";
            }
        }
        if(!bundle.isEmpty()) {
            project->values("QMAKE_BUNDLE") = ProStringList(bundle);
            project->values("ALL_DEPS") += project->first("QMAKE_PKGINFO");
            project->values("ALL_DEPS") += project->first("QMAKE_BUNDLE_RESOURCE_FILE");
        } else {
            project->values("QMAKE_BUNDLE").clear();
            project->values("QMAKE_BUNDLE_LOCATION").clear();
        }
    } else { //no bundling here
        project->values("QMAKE_BUNDLE").clear();
        project->values("QMAKE_BUNDLE_LOCATION").clear();
    }

    if(!project->isEmpty("QMAKE_INTERNAL_INCLUDED_FILES"))
        project->values("DISTFILES") += project->values("QMAKE_INTERNAL_INCLUDED_FILES");
    project->values("DISTFILES") += project->projectFile();

    init2();
    project->values("QMAKE_INTERNAL_PRL_LIBS") << "QMAKE_LIBS";
    if(!project->isEmpty("QMAKE_MAX_FILES_PER_AR")) {
        bool ok;
        int max_files = project->first("QMAKE_MAX_FILES_PER_AR").toInt(&ok);
        ProStringList ar_sublibs, objs = project->values("OBJECTS");
        if(ok && max_files > 5 && max_files < (int)objs.count()) {
            QString lib;
            for(int i = 0, obj_cnt = 0, lib_cnt = 0; i != objs.size(); ++i) {
                if((++obj_cnt) >= max_files) {
                    if(lib_cnt) {
                        lib.sprintf("lib%s-tmp%d.a",
                                    project->first("QMAKE_ORIG_TARGET").toLatin1().constData(), lib_cnt);
                        ar_sublibs << lib;
                        obj_cnt = 0;
                    }
                    lib_cnt++;
                }
            }
        }
        if(!ar_sublibs.isEmpty()) {
            project->values("QMAKE_AR_SUBLIBS") = ar_sublibs;
            project->values("QMAKE_INTERNAL_PRL_LIBS") << "QMAKE_AR_SUBLIBS";
        }
    }

    if(project->isActiveConfig("compile_libtool")) {
        static const char * const libtoolify[] = {
            "QMAKE_RUN_CC", "QMAKE_RUN_CC_IMP", "QMAKE_RUN_CXX", "QMAKE_RUN_CXX_IMP",
            "QMAKE_LINK_THREAD", "QMAKE_LINK", "QMAKE_AR_CMD", "QMAKE_LINK_SHLIB_CMD", 0
        };
        for (int i = 0; libtoolify[i]; i++) {
            ProStringList &l = project->values(libtoolify[i]);
            if(!l.isEmpty()) {
                QString libtool_flags, comp_flags;
                if (!strncmp(libtoolify[i], "QMAKE_LINK", 10) || !strcmp(libtoolify[i], "QMAKE_AR_CMD")) {
                    libtool_flags += " --mode=link";
                    if(project->isActiveConfig("staticlib")) {
                        libtool_flags += " -static";
                    } else {
                        if(!project->isEmpty("QMAKE_LIB_FLAG")) {
                            int maj = project->first("VER_MAJ").toInt();
                            int min = project->first("VER_MIN").toInt();
                            int pat = project->first("VER_PAT").toInt();
                            comp_flags += " -version-info " + QString::number(10*maj + min) +
                                          ":" + QString::number(pat) + ":0";
                            if (strcmp(libtoolify[i], "QMAKE_AR_CMD")) {
                                QString rpath = Option::output_dir;
                                if(!project->isEmpty("DESTDIR")) {
                                    rpath = project->first("DESTDIR").toQString();
                                    if(QDir::isRelativePath(rpath))
                                        rpath.prepend(Option::output_dir + Option::dir_sep);
                                }
                                comp_flags += " -rpath " + Option::fixPathToTargetOS(rpath, false);
                            }
                        }
                    }
                    if(project->isActiveConfig("plugin"))
                        libtool_flags += " -module";
                } else {
                    libtool_flags += " --mode=compile";
                }
                l.first().prepend("$(LIBTOOL)" + libtool_flags + " ");
                if(!comp_flags.isEmpty())
                    l.first() += comp_flags;
            }
        }
    }
}
Example #25
0
/**
 * Formats the given angle with the given format.
 *
 * @param angle The angle (always in rad).
 * @param format Format of the string.
 * @param prec Precision of the value (e.g. 0.001 or 1/128 = 0.0078125)
 *
 * @ret String with the formatted angle.
 */
QString RS_Units::formatAngle(double angle, RS2::AngleFormat format,
                                int prec) {

    QString ret;
    double value;

    switch (format) {
    case RS2::Surveyors:
    case RS2::DegreesDecimal:
    case RS2::DegreesMinutesSeconds:
        value = RS_Math::rad2deg(angle);
        break;
    case RS2::Radians:
        value = angle;
        break;
    case RS2::Gradians:
        value = RS_Math::rad2gra(angle);
        break;
    default:
        RS_DEBUG->print(RS_Debug::D_WARNING,
                        "RS_Units::formatAngle: Unknown Angle Unit");
        return "";
        break;
    }

    switch (format) {
    case RS2::DegreesDecimal:
    case RS2::Radians:
    case RS2::Gradians:
        ret = RS_Math::doubleToString(value, prec);
        if (format==RS2::DegreesDecimal)
            ret+=QChar(0xB0);
        if (format==RS2::Radians)
            ret+="r";
        if (format==RS2::Gradians)
            ret+="g";
        break;

    case RS2::DegreesMinutesSeconds: {
            int vDegrees, vMinutes;
            double vSeconds;
            QString degrees, minutes, seconds;

            vDegrees = (int)floor(value);
            vMinutes = (int)floor((value - vDegrees) * 60.0);
            vSeconds = (value - vDegrees - (vMinutes/60.0)) * 3600.0;

            seconds = RS_Math::doubleToString(vSeconds, (prec>1 ? prec-2 : 0));

            if(seconds=="60") {
                seconds="0";
                ++vMinutes;
                if(vMinutes==60) {
                    vMinutes=0;
                    ++vDegrees;
                }
            }

            if (prec==0 && vMinutes>=30.0) {
                vDegrees++;
            } else if (prec==1 && vSeconds>=30.0) {
                vMinutes++;
            }

            degrees.setNum(vDegrees);
            minutes.setNum(vMinutes);

            switch (prec) {
            case 0:
                ret = degrees + QChar(0xB0);
                break;
            case 1:
                ret = degrees + QChar(0xB0) + " " + minutes + "'";
                break;
            default:
                ret = degrees + QChar(0xB0) + " " + minutes + "' "
                      + seconds + "\"";
                break;
            }
        }
        break;
    case RS2::Surveyors: {
        QString prefix,suffix;
        int quadrant;
        quadrant = ((int)floor(value)/90);
        switch(quadrant){
            case 0:
                prefix="N";
                suffix="E";
                break;
            case 1:
                prefix="S";
                suffix="E";
                value=180. - value;
                break;
            case 2:
                prefix="S";
                suffix="W";
                value=value - 180.;
                break;
            case 3:
                prefix="N";
                suffix="W";
                value=360. - value;
                break;
            }
            ret = prefix+formatAngle(RS_Math::deg2rad(value),RS2::DegreesMinutesSeconds,prec)+suffix;
            ret.replace(QChar(0xB0),"d");
            ret.replace(" ","");
        }
        break;
    default:
        break;
    }

    return ret;
}
Example #26
0
void
UnixMakefileGenerator::processPrlFiles()
{
    const QString libArg = project->first("QMAKE_L_FLAG").toQString();
    QList<QMakeLocalFileName> libdirs, frameworkdirs;
    int libidx = 0, fwidx = 0;
    foreach (const ProString &dlib, project->values("QMAKE_DEFAULT_LIBDIRS"))
        libdirs.append(QMakeLocalFileName(dlib.toQString()));
    frameworkdirs.append(QMakeLocalFileName("/System/Library/Frameworks"));
    frameworkdirs.append(QMakeLocalFileName("/Library/Frameworks"));
    static const char * const lflags[] = { "QMAKE_LIBS", "QMAKE_LIBS_PRIVATE", 0 };
    for (int i = 0; lflags[i]; i++) {
        ProStringList &l = project->values(lflags[i]);
        for(int lit = 0; lit < l.size(); ++lit) {
            QString opt = l.at(lit).trimmed().toQString();
            if(opt.startsWith("-")) {
                if (opt.startsWith(libArg)) {
                    QMakeLocalFileName l(opt.mid(libArg.length()));
                    if(!libdirs.contains(l))
                       libdirs.insert(libidx++, l);
                } else if(opt.startsWith("-l")) {
                    QString lib = opt.right(opt.length() - 2);
                    QString prl_ext = project->first(ProKey("QMAKE_" + lib.toUpper() + "_SUFFIX")).toQString();
                    for(int dep_i = 0; dep_i < libdirs.size(); ++dep_i) {
                        const QMakeLocalFileName &lfn = libdirs[dep_i];
                        if(!project->isActiveConfig("compile_libtool")) { //give them the .libs..
                            QString la = lfn.local() + Option::dir_sep + project->values("QMAKE_PREFIX_SHLIB").first() + lib + Option::libtool_ext;
                            if(exists(la) && QFile::exists(lfn.local() + Option::dir_sep + ".libs")) {
                                QString dot_libs = lfn.real() + Option::dir_sep + ".libs";
                                l.append("-L" + dot_libs);
                                libdirs.insert(libidx++, QMakeLocalFileName(dot_libs));
                            }
                        }

                        QString prl = lfn.local() + Option::dir_sep + project->values("QMAKE_PREFIX_SHLIB").first() + lib + prl_ext;
                        if(processPrlFile(prl)) {
                            if(prl.startsWith(lfn.local()))
                                prl.replace(0, lfn.local().length(), lfn.real());
                            opt = linkLib(prl, lib);
                            break;
                        }
                    }
                } else if (target_mode == TARG_MAC_MODE && opt.startsWith("-F")) {
                    QMakeLocalFileName f(opt.right(opt.length()-2));
                    if(!frameworkdirs.contains(f))
                        frameworkdirs.insert(fwidx++, f);
                } else if (target_mode == TARG_MAC_MODE && opt.startsWith("-framework")) {
                    if(opt.length() > 11)
                        opt = opt.mid(11);
                    else
                        opt = l.at(++lit).toQString();
                    opt = opt.trimmed();
                    foreach (const QMakeLocalFileName &dir, frameworkdirs) {
                        QString prl = dir.local() + "/" + opt + ".framework/" + opt + Option::prl_ext;
                        if(processPrlFile(prl))
                            break;
                    }
                }
            } else if(!opt.isNull()) {
                QString lib = opt;
                processPrlFile(lib);
#if 0
                if(ret)
                    opt = linkLib(lib, "");
#endif
                if(!opt.isEmpty())
                    for (int k = 0; k < l.size(); ++k)
                        l[k] = l.at(k).toQString().replace(lib, opt);
            }

            ProStringList &prl_libs = project->values("QMAKE_CURRENT_PRL_LIBS");
            if(!prl_libs.isEmpty()) {
                for(int prl = 0; prl < prl_libs.size(); ++prl)
                    l.insert(lit+prl+1, escapeFilePath(prl_libs.at(prl).toQString()));
                prl_libs.clear();
            }
        }
Example #27
0
static void parse_command(QString cmdline, const QString &id, const QString &whichCommand,
                          QString *command, QStringList *prefix, QStringList *suffix, ArchiveDefinition::ArgumentPassingMethod *method, bool parseFilePlaceholder)
{
    Q_ASSERT(prefix);
    Q_ASSERT(suffix);
    Q_ASSERT(method);

    KShell::Errors errors;
    QStringList l;

    if (cmdline.startsWith(NULL_SEPARATED_STDIN_INDICATOR)) {
        *method = ArchiveDefinition::NullSeparatedInputFile;
        cmdline.remove(0, 2);
    } else if (cmdline.startsWith(NEWLINE_SEPARATED_STDIN_INDICATOR)) {
        *method = ArchiveDefinition::NewlineSeparatedInputFile;
        cmdline.remove(0, 1);
    } else {
        *method = ArchiveDefinition::CommandLine;
    }
    if (*method != ArchiveDefinition::CommandLine && cmdline.contains(FILE_PLACEHOLDER)) {
        throw ArchiveDefinitionError(id, i18n("Cannot use both %f and | in '%1'", whichCommand));
    }
    cmdline.replace(FILE_PLACEHOLDER,        QLatin1String("__files_go_here__"))
    .replace(INSTALLPATH_PLACEHOLDER, QStringLiteral("__path_goes_here__"));
    l = KShell::splitArgs(cmdline, KShell::AbortOnMeta | KShell::TildeExpand, &errors);
    l = l.replaceInStrings(QStringLiteral("__files_go_here__"), FILE_PLACEHOLDER);
    if (l.indexOf(QRegExp(QLatin1String(".*__path_goes_here__.*"))) >= 0) {
        l = l.replaceInStrings(QStringLiteral("__path_goes_here__"), ArchiveDefinition::installPath());
    }
    if (errors == KShell::BadQuoting) {
        throw ArchiveDefinitionError(id, i18n("Quoting error in '%1' entry", whichCommand));
    }
    if (errors == KShell::FoundMeta) {
        throw ArchiveDefinitionError(id, i18n("'%1' too complex (would need shell)", whichCommand));
    }
    qCDebug(KLEOPATRA_LOG) << "ArchiveDefinition[" << id << ']' << l;
    if (l.empty()) {
        throw ArchiveDefinitionError(id, i18n("'%1' entry is empty/missing", whichCommand));
    }
    const QFileInfo fi1(l.front());
    if (fi1.isAbsolute()) {
        *command = try_extensions(l.front());
    } else {
        *command = QStandardPaths::findExecutable(fi1.fileName());
    }
    if (command->isEmpty()) {
        throw ArchiveDefinitionError(id, i18n("'%1' empty or not found", whichCommand));
    }
    if (parseFilePlaceholder) {
        const int idx1 = l.indexOf(FILE_PLACEHOLDER);
        if (idx1 < 0) {
            // none -> append
            *prefix = l.mid(1);
        } else {
            *prefix = l.mid(1, idx1 - 1);
            *suffix = l.mid(idx1 + 1);
        }
    } else {
        *prefix = l.mid(1);
    }
    switch (*method) {
    case ArchiveDefinition::CommandLine:
        qCDebug(KLEOPATRA_LOG) << "ArchiveDefinition[" << id << ']' << *command << *prefix << FILE_PLACEHOLDER << *suffix;
        break;
    case ArchiveDefinition::NewlineSeparatedInputFile:
        qCDebug(KLEOPATRA_LOG) << "ArchiveDefinition[" << id << ']' << "find | " << *command << *prefix;
        break;
    case ArchiveDefinition::NullSeparatedInputFile:
        qCDebug(KLEOPATRA_LOG) << "ArchiveDefinition[" << id << ']' << "find -print0 | " << *command << *prefix;
        break;
    case ArchiveDefinition::NumArgumentPassingMethods:
        Q_ASSERT(!"Should not happen");
        break;
    }
}
Example #28
0
void	ToyStream::loadFile(QString filePath)
{
  QRegExp isLogoLine("(\\|*)(\\s*)\xff");
  QRegExp isToyLine("^\\s*\\{(\\d+)\\}\\{(\\d+)\\}(.+)\n");
  QRegExp findOpt("\\{(.*)\\}");
  QRegExp findPipe("([^|]*)(\\|+)([^|]*)");
  QRegExp OptColor("\\{c:\\$([0-9A-F]+):?\\$?([0-9A-F]*)\\}");
  QRegExp OptPos("\\{o:(\\d+),(\\d+)\\}");

  QFile toyfile(filePath);
 
  if (!toyfile.open(QIODevice::ReadOnly | QIODevice::Text)) {
     cerr << "Can't read : " << filePath << "\n";
     exit(1);
  }
  while (!toyfile.atEnd()) {
    QByteArray line = toyfile.readLine();
    if (isToyLine.exactMatch(line)) {
      QString optAndText = isToyLine.cap(3);
      // Syl
      if (isLogoLine.indexIn(optAndText) != -1) {
        ToySyl newsyl;
	newsyl.pos = isLogoLine.cap(2).size();
	findPipe.exactMatch(optAndText);
        newsyl.nbpipe = findPipe.cap(2).size();
	newsyl.length = findPipe.cap(3).size();
	newsyl.start = isToyLine.cap(1).toInt();
	newsyl.stop = isToyLine.cap(2).toInt();
	syl.insert(newsyl);
	//show_ToySyl(newsyl);
      }
      //Text
      else {
        ToyText newtext;
	newtext.start = isToyLine.cap(1).toInt();
	newtext.stop = isToyLine.cap(2).toInt();
	newtext.nbpipe = 0;
        newtext.posx = -1;
        newtext.posy = -1;
	// Colors
	if (OptColor.indexIn(optAndText) != -1) {
          newtext.color1 = toycolor2QColor(OptColor.cap(1));
	  if (!OptColor.cap(2).isEmpty())
	    newtext.color2 = toycolor2QColor(OptColor.cap(2));
	}
	// Pos
	if (OptPos.indexIn(optAndText) != -1) {
          newtext.posx = OptPos.cap(1).toInt();
	  newtext.posy = OptPos.cap(2).toInt();
	}
	optAndText.replace(findOpt, "");
	if (findPipe.exactMatch(optAndText)) {
	  newtext.text = findPipe.cap(3);
	  newtext.nbpipe = findPipe.cap(2).size();
	}
	else {
	  newtext.text = optAndText;
	}
        text.insert(newtext);
      }
    }
  }
}
Example #29
0
/*!
 *\~english
 *	Converted currency value to string representation (ru currency).
 *\~russian
 *	Конвертирует валюту, записанную в виде рублей и копеек в ее текстовое представление.	
 *\~
 *	\return - \~english Converted value \~russian Сконвертированное значение \~
 *	\see number2money(double rubli)
 *	\see part2string(unsigned int st3, unsigned int st2, unsigned int st1, int stepen)
*/
QString 
aService::parts2money(Q_ULLONG rubli,
			 unsigned int kopeyki,
			 bool need_kopeyki,
			 bool positive,
			 bool male,
			 const QString &end1,
			 const QString &end2,
			 const QString &end3)
{
//	if(cur!=ru) return QString("%1 dollars %2 cents").arg(rubli).arg(kopeyki);
	QString chislo = (QString("%1").arg(rubli));
	int len = chislo.length();
	//printf("length=%d\n",len);
	int count=0;
	int a,b,c;
	int stepen=(len-1)/3;
	int offset=(len%3);
	if(offset) offset = 3-offset;
	//printf("offset=%d\n",offset);
	QString res = "";
	bool has_sum=false;
	if(!positive) res+="минус ";
	while(count<len)
	{
		a=b=c=0;
		if(offset<=0)
		{
			a = chislo.at(count++).digitValue();
		}
		if(count<len)
		{
			if(offset<=1)
			{
				b = chislo.at(count++).digitValue();
			}
		}
		if(count<len)
		{
			if(offset<=2)
			{
				c = chislo.at(count++).digitValue();
			}
		}
//		printf("a=%d, b=%d, c=%d, stepen=%d\n",a,b,c,stepen);
		if(a==0 && b==0 && c==0)
		{	
			if(stepen==0 && has_sum)
			{
				res+=part2string(a,b,c,stepen--,male,end1,end2,end3);
			}
			else
			{
				if(stepen==0)
				{
					res+=QString("ноль %1").arg(end1);
				}
				else
				{
					stepen--;
				}
			}
		}
		else
		{
			has_sum=true;
			res+=part2string(a,b,c,stepen--,male,end1,end2,end3);
		}
		offset=0;
	}
	if(need_kopeyki)
	{
		res+=part2string(0,kopeyki/10,kopeyki%10,-1,false,"копеек","копейка","копейки");
	}
	res = res.stripWhiteSpace();
	res = res.replace(0,1,res.at(0).upper());
	return res;
}
Example #30
0
void wizardDisk::generateConfirmationText()
{
  // If running in expert mode, we just create a simple config / confirmation
  if ( radioExpert->isChecked() ) {
    QStringList filesystem;
    filesystem << "MANUAL" << "/mnt" ;
    sysFinalDiskLayout << filesystem;
    textConfirmation->setText(tr("Installing to file-system mounted at /mnt"));
    return;
  }

  QList<QStringList> copyList;
  QStringList summaryList;
  QString tmp, workingDisk, workingSlice, tmpSlice, XtraTmp, startPart, sliceSize;
  int disk = 0;

  // Copy over the list to a new variable we can mangle without modifying the original
  copyList = sysFinalDiskLayout;

  // Start our summary
  summaryList << "";
  summaryList << "<b>" + tr("The disk will be setup with the following configuration:") + "</b>";

  while ( ! copyList.empty() )
  {
    workingDisk = copyList.at(0).at(0);
    workingSlice = copyList.at(0).at(1);
    tmpSlice = workingSlice;

    // Check if this is an install to "Unused Space"
    for (int z=0; z < sysDisks.count(); ++z)
      if ( sysDisks.at(z).at(0) == "SLICE" \
        && sysDisks.at(z).at(2) == workingDisk + workingSlice \
        && sysDisks.at(z).at(4) == "Unused Space" )
          tmpSlice = "free";

    // Check for any mirror for this device
    for (int i=0; i < copyList.count(); ++i) {
       if ( copyList.at(i).at(2).indexOf("MIRROR(" + workingDisk + ")") != -1 )
       {
         summaryList << tr("Disk:") + copyList.at(i).at(0) + " " + tr("Mirroring:") + workingDisk;
         copyList.removeAt(i);
         break;
       }
    }

    // If after doing the mirror, our list is empty, break out
    if ( copyList.empty() )
      break;
    
    // If there is a dedicated /boot partition, need to list that first, see what is found
    for (int i=0; i < copyList.count(); ++i) {
      QStringList mounts = copyList.at(i).at(2).split(",");
      for (int z = 0; z < mounts.size(); ++z) {
        if ( copyList.at(i).at(0) == workingDisk \
          && copyList.at(i).at(1) == workingSlice \
          && mounts.at(z) == "/boot" )
		startPart="/boot";
      }
    }

    // If no dedicated /boot partition, then lets list "/" first
    if(startPart.isEmpty())
	startPart="/";

    // Start by looking for the root partition
    for (int i=0; i < copyList.count(); ++i) {
      QStringList mounts = copyList.at(i).at(2).split(",");
      for (int z = 0; z < mounts.size(); ++z) {
        if ( copyList.at(i).at(0) == workingDisk \
          && copyList.at(i).at(1) == workingSlice \
          && mounts.at(z) == startPart ) {

          // Check if we have any extra arguments to throw on the end
          XtraTmp="";
          if ( ! copyList.at(i).at(5).isEmpty() )
            XtraTmp=" (" + copyList.at(i).at(5) + ")" ;

          // Write the user summary
          summaryList << "";
          summaryList << tr("Partition:") + " " + workingDisk + "(" + workingSlice + "):";
          summaryList << tr("FileSystem:") + " " + copyList.at(i).at(3);
          summaryList << tr("Size:") + " " + copyList.at(i).at(4) + "MB ";

	  if ( copyList.at(i).at(3) == "ZFS" || copyList.at(i).at(3) == "ZFS.eli" ) {
	    QStringList zDS = copyList.at(i).at(2).split(",/");
	    QString zTMP;
	    for (int ds = 0; ds < zDS.size(); ++ds) {
	      if ( zDS.at(ds) != "/" )
                zDS.replace(ds, "/" + zDS.at(ds));
	      if ( zDS.at(ds).indexOf("(") != -1 ) {
		zTMP = zDS.at(ds);
		zTMP.replace("(", " (");
                zDS.replace(ds, zTMP );
	      }
	    }
            summaryList << tr("ZFS Datasets:<br>") + " " + zDS.join("<br>");
	  } else {
            summaryList << tr("Mount:") + " " + copyList.at(i).at(2);
	  }
	  if ( ! XtraTmp.isEmpty() ) {
            summaryList << tr("Options:") + " " + copyList.at(i).at(5);
          }

          // Done with this item, remove it now
          copyList.removeAt(i);
          break;
        }
      }
    }


    // Now look for SWAP
    for (int i=0; i < copyList.count(); ++i) {
      if ( copyList.at(i).at(0) == workingDisk \
        && copyList.at(i).at(1) == workingSlice \
        && copyList.at(i).at(2) == "SWAP.eli" ) {

        // Write the user summary
        summaryList << "";
        summaryList << tr("Partition:") + " " + workingDisk + "(" + workingSlice + "):";
        summaryList << tr("FileSystem:") + " " + copyList.at(i).at(3);
        summaryList << tr("Size:") + " " + copyList.at(i).at(4) + "MB ";

        // Done with this item, remove it now
        copyList.removeAt(i);
        break;
      }
    }

 
    // Now look for any other partitions
    int count = copyList.count();
    for (int i=0; i < count; ++i) {
      if ( copyList.at(i).at(0) == workingDisk \
        && copyList.at(i).at(1) == workingSlice ) {

        // Check if we have any extra arguments to throw on the end
        XtraTmp="";
        if ( ! copyList.at(i).at(5).isEmpty() )
          XtraTmp=" (" + copyList.at(i).at(5) + ")" ;

	// If we are working on the last partition, set the size to 0 to use remaining disk
	if ( i == (count - 1) ) 
		sliceSize = "0";
	else
		sliceSize=copyList.at(i).at(4);

        // Write the user summary
        summaryList << "";
        summaryList << tr("Partition:") + " " + workingDisk + "(" + workingSlice + "):";
        summaryList << tr("FileSystem:") + " " + copyList.at(i).at(3);
        summaryList << tr("Size:") + " " + copyList.at(i).at(4) + "MB ";
        summaryList << tr("Mount:") + " " + copyList.at(i).at(2);
	if ( ! XtraTmp.isEmpty() ) {
          summaryList << tr("Options:") + " " + copyList.at(i).at(5);
        }

        // Done with this item, remove it now
        copyList.removeAt(i);
        i--;
        count--;
      }
    }

    // Increment our disk counter
    disk++;
  }

  textConfirmation->setText(summaryList.join("<br>"));
}