Example #1
0
int UPNPSubscription::SendSubscribeRequest(const QString &callback,
        const QString &usn,
        const QUrl    &url,
        const QString &path,
        const QString &uuidin,
        QString       &uuidout)
{
    QString host = url.host();
    int     port = url.port();

    QByteArray sub;
    QTextStream data(&sub);
    data.setCodec(QTextCodec::codecForName("UTF-8"));
    // N.B. Play On needs an extra space between SUBSCRIBE and path...
    data << QString("SUBSCRIBE  %1 HTTP/1.1\r\n").arg(path);
    data << QString("HOST: %1:%2\r\n").arg(host).arg(QString::number(port));


    if (uuidin.isEmpty()) // new subscription
    {
        data << QString("CALLBACK: <%1%2>\r\n")
             .arg(callback).arg(usn);
        data << "NT: upnp:event\r\n";
    }
    else // renewal
        data << QString("SID: uuid:%1\r\n").arg(uuidin);

    data << QString("TIMEOUT: Second-%1\r\n").arg(SUBSCRIPTION_TIME);
    data << "\r\n";
    data.flush();

    LOG(VB_UPNP, LOG_DEBUG, LOC + "\n\n" + sub);

    MSocketDevice *sockdev = new MSocketDevice(MSocketDevice::Stream);
    BufferedSocketDevice *sock = new BufferedSocketDevice(sockdev);
    sockdev->setBlocking(true);

    QString uuid;
    QString timeout;
    uint result = 0;

    if (sock->Connect(QHostAddress(host), port))
    {
        if (sock->WriteBlockDirect(sub.constData(), sub.size()) != -1)
        {
            bool ok = false;
            QString line = sock->ReadLine(MAX_WAIT);
            while (!line.isEmpty())
            {
                LOG(VB_UPNP, LOG_DEBUG, LOC + line);
                if (line.contains("HTTP/1.1 200 OK", Qt::CaseInsensitive))
                    ok = true;
                if (line.startsWith("SID:", Qt::CaseInsensitive))
                    uuid = line.mid(4).trimmed().mid(5).trimmed();
                if (line.startsWith("TIMEOUT:", Qt::CaseInsensitive))
                    timeout = line.mid(8).trimmed().mid(7).trimmed();
                if (ok && !uuid.isEmpty() && !timeout.isEmpty())
                    break;
                line = sock->ReadLine(MAX_WAIT);
            }

            if (ok && !uuid.isEmpty() && !timeout.isEmpty())
            {
                uuidout = uuid;
                result  = timeout.toUInt();
            }
            else
            {
                LOG(VB_GENERAL, LOG_ERR, LOC +
                    QString("Failed to subscribe to %1").arg(usn));
            }
        }
        else
        {
            LOG(VB_GENERAL, LOG_ERR, LOC +
                QString("Socket write error for %1:%2") .arg(host).arg(port));
        }
        sock->Close();
    }
    else
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            QString("Failed to open socket for %1:%2") .arg(host).arg(port));
    }

    delete sock;
    delete sockdev;
    return result;
}
QList<ScColorProfileInfo> ScLcms2ColorMgmtEngineImpl::getAvailableProfileInfo(const QString& directory, bool recursive)
{
	QList<ScColorProfileInfo> profileInfos;

	QDir d(directory, "*", QDir::Name, QDir::Files | QDir::Readable | QDir::Dirs | QDir::NoSymLinks);
	if ((!d.exists()) || (d.count() == 0))
		return profileInfos;

	QString nam = "";
	cmsHPROFILE hIn = NULL;

	for (uint dc = 0; dc < d.count(); ++dc)
	{
		QString file = d[dc];
		if (file == "." ||  file == "..")
			continue;
		QFileInfo fi(directory + "/" + file);
		if (fi.isDir() && !recursive)
			continue;
		else if (fi.isDir() && !file.startsWith('.'))
		{
			QList<ScColorProfileInfo> profileInfos2 = getAvailableProfileInfo(fi.filePath()+"/", true);
			profileInfos.append(profileInfos2);
			continue;
		}

		ScColorProfileInfo profileInfo;
		profileInfo.file = fi.filePath();

		QFile f(fi.filePath());
		QByteArray bb(40, ' ');
		if (!f.open(QIODevice::ReadOnly)) {
			profileInfo.debug = QString("couldn't open %1 as color profile").arg(fi.filePath());
			profileInfos.append(profileInfo);
			continue;
		}
		int len = f.read(bb.data(), 40);
		f.close();
		if (len == 40 && bb[36] == 'a' && bb[37] == 'c' && bb[38] == 's' && bb[39] == 'p')
		{
			const QByteArray profilePath( QString(directory + "/" + file).toLocal8Bit() );
			hIn = cmsOpenProfileFromFile(profilePath.data(), "r");
			if (hIn == NULL)
				continue;
#ifdef _WIN32
			cmsUInt32Number descSize = cmsGetProfileInfo(hIn, cmsInfoDescription, "en", "US", NULL, 0);
			if (descSize > 0)
			{
				wchar_t* descData = (wchar_t*) malloc(descSize + sizeof(wchar_t));
				descSize = cmsGetProfileInfo(hIn, cmsInfoDescription, "en", "US", descData, descSize);
				if (descSize > 0)
				{
					uint stringLen = descSize / sizeof(wchar_t);
					descData[stringLen] = 0;
					if (sizeof(wchar_t) == sizeof(QChar)) {
						profileInfo.description = QString::fromUtf16((ushort *) descData);
					} else {
						profileInfo.description = QString::fromUcs4((uint *) descData);
					}
					free(descData);
				}
			}
#else
			cmsUInt32Number descSize = cmsGetProfileInfoASCII(hIn, cmsInfoDescription, "en", "US", NULL, 0);
			if (descSize > 0)
			{
				char* descData = (char*) malloc(descSize + sizeof(char));
				descSize = cmsGetProfileInfoASCII(hIn, cmsInfoDescription, "en", "US", descData, descSize);
				if (descSize > 0)
				{
					profileInfo.description = QString(descData);
					free(descData);
				}
			}
#endif
			if (profileInfo.description.isEmpty())
			{
				cmsCloseProfile(hIn);
				profileInfo.debug = QString("Color profile %1 is broken : no valid description").arg(fi.filePath());
				profileInfos.append(profileInfo);
				continue;
			}
			profileInfo.colorSpace  = translateLcmsColorSpaceType( cmsGetColorSpace(hIn) );
			profileInfo.deviceClass = translateLcmsProfileClass( cmsGetDeviceClass(hIn) );
			profileInfos.append(profileInfo);
			cmsCloseProfile(hIn);
			hIn = NULL;
		}
	}

	return profileInfos;
}
Example #3
0
bool RemSection::fixOptionForQChem(QString& name, QString& value) {
   //qDebug() << "Fixing option for QChem" << name << "=" << value;
   bool shouldPrint(true);
   bool isInt;
   Option opt;
   OptionDatabase& db = OptionDatabase::instance();
   bool inDatabase(db.get(name, opt));

   // Skip internal QUI options
   if (name.startsWith("qui_",Qt::CaseInsensitive)) shouldPrint = false;

   if (name == "METHOD" && value == "Custom")  shouldPrint = false;

   // Perform some ad hoc conversions.  These are all triggered in the database
   // by having an entry of the form a|b where a is replaced by b in the input
   // file.  These are set in the InputDialog::initializeControl member function
   QString key = name + "::" + value;
   if (m_adHoc.count(key)) value = m_adHoc[key];

   //fix logicals
   if (inDatabase && opt.getType() == Option::Type_Logical) {
      if (name == "GUI") {
         value = value.toInt() == 0 ? QString::number(0) : QString::number(2);
      }else if (value.toInt() == Qt::Checked) {
         value = QString::number(1);
      }
   }

   //fix reals
   if (name == "CC_DIIS_MAXIMUM_OVERLAP" || 
       name == "CC_DOV_THRESH" ||
       name == "CC_DTHRESHOLD" ||
       name == "CC_HESSIAN_THRESH" ||
       name == "CC_THETA_STEPSIZE") {

       bool ok(true);
       double val = value.toDouble(&ok);

       int exp = floor(log10(val));
       int man = 100 * val * pow(10,-exp);
       //qDebug() << "2) " << man << "x10e" << exp+2;

       value = QString::number(man) + QString("%1").arg(exp+2,2,10,QChar('0'));

   }else if (inDatabase && opt.getType() == Option::Type_Real) {
      value = QString::number(value.toDouble() / opt.doubleStep());
   }


   if (name == "SCF_GUESS_MIX") {
      value = QString::number(value.toInt()/10);
   }

   if (name == "QUI_FROZEN_CORE" && value.toInt() != 0) {
      name = "N_FROZEN_CORE";
      value = "FC";
      shouldPrint = true;
   }

   if (name == "XC_GRID" || name == "NL_GRID") {
      QStringList tokens(value.split(","));
      if (tokens.size() == 2) {
         bool angularIsInt(false);
         bool radialIsInt(false);
         int  rad(tokens[0].toInt(&radialIsInt));
         int  ang(tokens[1].toInt(&angularIsInt));

         if (angularIsInt && radialIsInt) {
            value = QString("%1").arg(ang);
            value = QString::number(rad) + value.rightJustified(6,'0');
         }
      } 
   }

  
   if (name == "QUI_XOPT1" && value.toInt() > 0) {
      name = "XOPT_STATE_1";
      shouldPrint = true;

      // This is crappy
      key = "QUI_XOPT_SPIN1::";      
      key += m_options["QUI_XOPT_SPIN1"];
      if (m_adHoc.count(key)) m_options["QUI_XOPT_SPIN1"] = m_adHoc[key];

      value = "[" + m_options["QUI_XOPT_SPIN1"]  + ", "
                  + m_options["QUI_XOPT_IRREP1"] + ", "
                  + m_options["QUI_XOPT_STATE1"] + "]";

   }

   if (name == "QUI_XOPT2" && value.toInt() > 0)  {
      name = "XOPT_STATE_2";
      shouldPrint = true;

      key = "QUI_XOPT_SPIN2::";      
      key += m_options["QUI_XOPT_SPIN2"];
      if (m_adHoc.count(key)) m_options["QUI_XOPT_SPIN2"] = m_adHoc[key];

      value = "[" + m_options["QUI_XOPT_SPIN2"]  + ", "
                  + m_options["QUI_XOPT_IRREP2"] + ", "
                  + m_options["QUI_XOPT_STATE2"] + "]";
   }
 

   //qDebug() << "Fixing option for QChem" << name << "=" << value << "print = " << shouldPrint;
   return shouldPrint;
}
Example #4
0
void ValueSetters::MagnetAssociationValueSetter(QString group, QString name, QVariant value)
{
	bool associate = value.toBool();
#ifdef Q_WS_WIN
	QSettings asocSettings("HKEY_CLASSES_ROOT", QSettings::NativeFormat);
	QString applicationFilePath = QDir::toNativeSeparators(QFileInfo(QApplication::applicationFilePath()).absoluteFilePath());
	
	if (associate)
	{
		asocSettings.setValue("Magnet/.", "Magnet URI");
		asocSettings.setValue("Magnet/Content Type", "application/x-magnet");
		asocSettings.setValue("Magnet/URL Protocol", "");
		asocSettings.setValue("Magnet/shell/open/command/.",
			"\"" + applicationFilePath + "\"" + " \"%1\"");
	}
	else
	{
		asocSettings.remove("Magnet/.");
		asocSettings.remove("Magnet/Content Type");
		asocSettings.remove("Magnet/URL Protocol");
		asocSettings.remove("Magnet/shell/open/command/.");
	}
#elif Q_WS_X11
	QFile associtaionGnomeConfig(StaticHelpers::CombinePathes(QDir::homePath() , ".config/mimeapps.list"));

	if (associtaionGnomeConfig.open(QFile::ReadOnly))
	{
		QByteArray asscoiationData = associtaionGnomeConfig.readAll();
		associtaionGnomeConfig.close();
		QString associationStr = QString::fromUtf8(asscoiationData);
		QStringList lines = associationStr.split('\n');
		bool magnetFound = false;

		for (int i = 0; i < lines.size(); i++)
		{
			QString line = lines[i];

			if (line.startsWith("x-scheme-handler/magnet", Qt::CaseInsensitive))
			{
				magnetFound = true;

				if (associate)
				{
					lines[i] = "x-scheme-handler/magnet=CuteTorrent.desktop;";
				}
				else
				{
					lines[i] = "";
				}
			}
		}

		if (!magnetFound && associate)
		{
			lines.append("x-scheme-handler/magnet=CuteTorrent.desktop;\n");
		}

		if (associtaionGnomeConfig.open(QFile::WriteOnly))
		{
			for (int i = 0; i < lines.size(); i++)
			{
				QString line = lines[i];

				if (!line.isEmpty())
				{
					associtaionGnomeConfig.write((line + "\n").toUtf8());
				}
			}

			associtaionGnomeConfig.close();
		}
		else
		{
			qCritical() << "Unable to open gnome config file for writing file asscoiations" << associtaionGnomeConfig.errorString();
		}
	}
	else
	{
		qCritical() << "Unable to open gnome config file for reading file asscoiations" << associtaionGnomeConfig.errorString();
	}
#endif
}
Example #5
0
/** \fn     GalleryView::customEvent(QEvent *)
 *  \brief  Translates the keypresses to specific actions within the plugin
 *  \param  event The custom event
 *  \return void
 */
void GalleryView::customEvent(QEvent *event)
{
    if ((MythEvent::Type)(event->type()) == MythEvent::MythEventMessage)
    {
        MythEvent *me = (MythEvent *)event;
        QString message = me->Message();

        if (message.startsWith("IMAGE_THUMB_CREATED"))
        {
            QStringList tokens = message.simplified().split(" ");
            int fileid = 0;
            if (tokens.size() >= 2)
            {
                fileid = tokens[1].toUInt();

                // FIXME: This sucks, must be a better way to do this
                //
                // get through the entire list of image items and find
                // the fileid that matches the created thumbnail filename
                for (int i = 0; i < m_imageList->GetCount(); i++)
                {
                    MythUIButtonListItem *item = m_imageList->GetItemAt(i);
                    if (!item)
                        continue;

                    ImageMetadata *im = GetImageMetadataFromButton(item);
                    if (!im)
                        continue;

                    if (im->m_id == fileid)
                    {
                        UpdateThumbnail(item, true);
                        break;
                    }
                }
            }
        }
    }
    else if (event->type() == DialogCompletionEvent::kEventType)
    {
        DialogCompletionEvent *dce = (DialogCompletionEvent*)(event);

        QString resultid  = dce->GetId();
        int     buttonnum = dce->GetResult();

        // Confirm current file deletion
        if (resultid == "confirmdelete")
        {
            switch (buttonnum)
            {
            case 0 :
                break;
            case 1 :
                FileDelete();
                break;
            }
        }

        // Confirm all selected file deletion
        if (resultid == "confirmdeleteselected")
        {
            switch (buttonnum)
            {
            case 0 :
                break;
            case 1 :
                FileDeleteSelected();
                break;
            }
        }

        // Synchronize the database
        if (resultid == "confirmstartsync")
        {
            switch (buttonnum)
            {
            case 0 :
                break;
            case 1 :
                // Start the sync, the API call will
                // check if a sync is running already
                m_galleryViewHelper->m_fileHelper->StartSyncImages();

                if (!m_syncStatusThread->isRunning())
                    m_syncStatusThread->start();

                break;
            }
        }

        // Stop the database sync
        if (resultid == "confirmstopsync")
        {
            switch (buttonnum)
            {
            case 0 :
                break;
            case 1 :
                if (m_syncStatusThread->isRunning())
                    m_syncStatusThread->quit();

                m_galleryViewHelper->m_fileHelper->StopSyncImages();
                break;
            }
        }

        if (resultid == "filerename")
        {
            QString newName = dce->GetResultText();
            FileRename(newName);
        }
    }
}
void ComponentModelLibrary::loadModels()
{
	QTime ct;
	ct.start();

	QStringList files;
	files << "transistors.lib";

	// Used to check that maxComponentModels isn't too small
	typedef QMap< ModelType, int > IntMap;
	IntMap modelCount;
	
	QStringList::iterator end = files.end();
	for ( QStringList::iterator it = files.begin(); it != end; ++it )
	{
		QString fileName = locate( "appdata", "models/" + *it );
		if ( fileName.isEmpty() )
		{
			kdWarning() << k_funcinfo << "Could not find library file \""<<*it<<"\".\n";
			continue;
		}

		QFile file( fileName );
		if ( !file.open( QIODevice::ReadOnly ) )
		{
			kdWarning() << k_funcinfo << "Could not open library file \""<<fileName<<"\" for reading.\n";
			continue;
		}

		QString id;
		QString typeString;
		ComponentModel *model = 0;

		Q3TextStream stream( & file );
		while ( !stream.atEnd() )
		{
			QString line = stream.readLine();

			if ( line.isEmpty() ) continue;

			if ( line == "[/]" )
			{
				// End of previous model

				assert( model );

				ModelType type = None;
				if ( typeString == "NPN" ) type = NPN;
				else if ( typeString == "PNP" ) type = PNP;
				else	kdError() << k_funcinfo << "Unknown type \""<<typeString<<"\".\n";

				if ( m_componentModelIDs[type].contains( id ) )
					kdError() << k_funcinfo << "Already have model with id=\""<<id<<"\" for type=\""<<typeString<<"\".\n";

				if ( !m_componentModels.contains( type ) )
				{
					m_componentModels[type] = ComponentModelDict( maxComponentModels );
					m_componentModels[type].setAutoDelete( true );
				}

				m_componentModels[type].insert( id, model );
				m_componentModelIDs[type] << id;

				if ( int(modelCount[type] * 1.2) > maxComponentModels )
				{
					kdWarning() << k_funcinfo << "There are "<<modelCount[type]<<" models for component type \""<<typeString<<"\". Consider enlarging the dictionary.\n";
				}

				// Reset the model
				model = 0l;
				id = QString::null;
				typeString = QString::null;

				modelCount[type]++;
			} else if ( line.startsWith("[" ) ) {
				// Already handled the case with "[/]", so must be beginning of
				// new model

				// Check that their isn't a previous model that hasn't saved
				assert( !model );

				model = new ComponentModel;
				id = line.mid( 1, line.length()-2 ); // extract the text between the square brackets
			} else {
				// Setting a property of the model
				assert( model );

				int pos = line.find( '=' );
				assert( pos != -1 );

				QString name = line.left( pos );
				QString value = line.mid( pos+1 );

				if ( name == "Description" )
					model->setDescription( value );
				else if ( name == "Type" )
					typeString = value;
				else {
					bool ok;
					double realValue = value.toDouble( & ok );
					
					if ( !ok )
						kdError() << k_funcinfo << "Could not convert \""<<value<<"\" to a real number (for property \""<<name<<"\".\n";
					else	model->setProperty( name, realValue );
				}
			}
		}
	}

	kdDebug() << k_funcinfo << "It took " << ct.elapsed() << " milliseconds to read in the component models.\n";
}
Example #7
0
bool QgsDistanceArea::setEllipsoid( const QString& ellipsoid )
{
  QString radius, parameter2;
  //
  // SQLITE3 stuff - get parameters for selected ellipsoid
  //
  sqlite3      *myDatabase;
  const char   *myTail;
  sqlite3_stmt *myPreparedStatement;
  int           myResult;

  // Shortcut if ellipsoid is none.
  if ( ellipsoid == GEO_NONE )
  {
    mEllipsoid = GEO_NONE;
    return true;
  }

  // Check if we have a custom projection, and set from text string.
  // Format is "PARAMETER:<semi-major axis>:<semi minor axis>
  // Numbers must be with (optional) decimal point and no other separators (C locale)
  // Distances in meters.  Flattening is calculated.
  if ( ellipsoid.startsWith( "PARAMETER" ) )
  {
    QStringList paramList = ellipsoid.split( ":" );
    bool semiMajorOk, semiMinorOk;
    double semiMajor = paramList[1].toDouble( & semiMajorOk );
    double semiMinor = paramList[2].toDouble( & semiMinorOk );
    if ( semiMajorOk && semiMinorOk )
    {
      return setEllipsoid( semiMajor, semiMinor );
    }
    else
    {
      return false;
    }
  }

  // Continue with PROJ.4 list of ellipsoids.

  //check the db is available
  myResult = sqlite3_open_v2( QgsApplication::srsDbFilePath().toUtf8().data(), &myDatabase, SQLITE_OPEN_READONLY, NULL );
  if ( myResult )
  {
    QgsMessageLog::logMessage( QObject::tr( "Can't open database: %1" ).arg( sqlite3_errmsg( myDatabase ) ) );
    // XXX This will likely never happen since on open, sqlite creates the
    //     database if it does not exist.
    return false;
  }
  // Set up the query to retrieve the projection information needed to populate the ELLIPSOID list
  QString mySql = "select radius, parameter2 from tbl_ellipsoid where acronym='" + ellipsoid + "'";
  myResult = sqlite3_prepare( myDatabase, mySql.toUtf8(), mySql.toUtf8().length(), &myPreparedStatement, &myTail );
  // XXX Need to free memory from the error msg if one is set
  if ( myResult == SQLITE_OK )
  {
    if ( sqlite3_step( myPreparedStatement ) == SQLITE_ROW )
    {
      radius = QString(( char * )sqlite3_column_text( myPreparedStatement, 0 ) );
      parameter2 = QString(( char * )sqlite3_column_text( myPreparedStatement, 1 ) );
    }
  }
  // close the sqlite3 statement
  sqlite3_finalize( myPreparedStatement );
  sqlite3_close( myDatabase );

  // row for this ellipsoid wasn't found?
  if ( radius.isEmpty() || parameter2.isEmpty() )
  {
    QgsDebugMsg( QString( "setEllipsoid: no row in tbl_ellipsoid for acronym '%1'" ).arg( ellipsoid ) );
    return false;
  }

  // get major semiaxis
  if ( radius.left( 2 ) == "a=" )
    mSemiMajor = radius.mid( 2 ).toDouble();
  else
  {
    QgsDebugMsg( QString( "setEllipsoid: wrong format of radius field: '%1'" ).arg( radius ) );
    return false;
  }

  // get second parameter
  // one of values 'b' or 'f' is in field parameter2
  // second one must be computed using formula: invf = a/(a-b)
  if ( parameter2.left( 2 ) == "b=" )
  {
    mSemiMinor = parameter2.mid( 2 ).toDouble();
    mInvFlattening = mSemiMajor / ( mSemiMajor - mSemiMinor );
  }
  else if ( parameter2.left( 3 ) == "rf=" )
  {
    mInvFlattening = parameter2.mid( 3 ).toDouble();
    mSemiMinor = mSemiMajor - ( mSemiMajor / mInvFlattening );
  }
  else
  {
    QgsDebugMsg( QString( "setEllipsoid: wrong format of parameter2 field: '%1'" ).arg( parameter2 ) );
    return false;
  }

  QgsDebugMsg( QString( "setEllipsoid: a=%1, b=%2, 1/f=%3" ).arg( mSemiMajor ).arg( mSemiMinor ).arg( mInvFlattening ) );


  // get spatial ref system for ellipsoid
  QString proj4 = "+proj=longlat +ellps=" + ellipsoid + " +no_defs";
  QgsCoordinateReferenceSystem destCRS;
  destCRS.createFromProj4( proj4 );
  //TODO: createFromProj4 used to save to the user database any new CRS
  // this behavior was changed in order to separate creation and saving.
  // Not sure if it necessary to save it here, should be checked by someone
  // familiar with the code (should also give a more descriptive name to the generated CRS)
  if ( destCRS.srsid() == 0 )
  {
    QString myName = QString( " * %1 (%2)" )
                     .arg( QObject::tr( "Generated CRS", "A CRS automatically generated from layer info get this prefix for description" ) )
                     .arg( destCRS.toProj4() );
    destCRS.saveAsUserCRS( myName );
  }
  //

  // set transformation from project CRS to ellipsoid coordinates
  mCoordTransform->setDestCRS( destCRS );

  // precalculate some values for area calculations
  computeAreaInit();

  mEllipsoid = ellipsoid;
  return true;
}
Example #8
0
bool FileServerHandler::HandleDeleteFile(SocketHandler *socket,
                                QString filename, QString storagegroup)
{
    StorageGroup sgroup(storagegroup, "", false);
    QStringList res;

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

    QString fullfile = sgroup.FindFile(filename);

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

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

    return true;
}
Example #9
0
void ChatEdit::send()
{
	if (!isEnabled())
		return;

	ChatEditLocker locker(this);

	QString text = textEditToPlainText();
	QString trimmed = text.trimmed();
	if(!m_session || trimmed.isEmpty())
		return;

	ChatUnit *unit = m_session.data()->getCurrentUnit();
	if (trimmed.startsWith(QLatin1Char('/')) && trimmed.size() > 1) {
		int index = trimmed.indexOf(QLatin1Char(' '));
		QStringRef cmd = trimmed.midRef(1, (index == -1 ? trimmed.size() : index) - 1);
		const QMetaObject *meta = unit->metaObject();
		for (int i = meta->propertyCount() - 1; i >= 0; --i) {
			QMetaProperty prop = meta->property(i);
			if (prop.isWritable() && QLatin1String(prop.name()) == cmd) {
				prop.write(unit, trimmed.mid(index + 1));
				clear();
				return;
			}
		}
		QByteArray signature = cmd.toString().toLatin1();
		int methodIndex = meta->indexOfMethod(signature + "(QString)");
		if (methodIndex != -1) {
			QMetaMethod method = meta->method(methodIndex);
			QString arg = trimmed.mid(index + 1);
			if (method.invoke(unit, Q_ARG(QString, arg))) {
				clear();
				return;
			}
		}
		methodIndex = meta->indexOfMethod(signature + "(QVariant)");
		if (methodIndex != -1) {
			QMetaMethod method = meta->method(methodIndex);
			QVariant arg = trimmed.mid(index + 1);
			if (method.invoke(unit, Q_ARG(QVariant, arg))) {
				clear();
				return;
			}
		}
		methodIndex = meta->indexOfMethod(signature + "()");
		if (methodIndex != -1) {
			QMetaMethod method = meta->method(methodIndex);
			if (method.invoke(unit)) {
				clear();
				return;
			}
		}
	}
	Message message(text);
	message.setIncoming(false);
	message.setChatUnit(unit);
	message.setTime(QDateTime::currentDateTime());
	MessageHandler::traceHandlers();

	auto lockerPtr = QSharedPointer<ChatEditLocker>::create(std::move(locker));
	QPointer<ChatEdit> edit(this);
	m_session->append(message, [edit, lockerPtr] (qint64 result, const Message &, const QString &) mutable {
		if (MessageHandler::Error != -result && edit)
			edit->clear();
		lockerPtr.reset();
	});
}
Example #10
0
/**
 * Reads the polyline text file and creates a list of polylines.
 *
 * \param fileName File name of input data file
 *
 * \param mwList polyline list to be filled
 *
 * \return true on success otherwise false
 */
bool readPolylineFile(QString fileName, QList<QPolygonF>& mwList)
{
  QFile file(fileName);

  if (!file.open(QIODevice::ReadOnly))
    {
      qWarning() << "Cannot open input file: " << fileName;
      return false;
    }

  QTextStream in(&file);

  /*
    L  42
     6.02994332   51.86150315
     6.03443202   51.86138736
  */

  bool suppress = true;
  int lineNo = 0;

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

      if( line.isEmpty() )
        {
          continue;
        }

      if( ! line.startsWith("L  ") )
        {
          if( ! suppress )
            {
              QString txt = QString("Error line %1: Expecting a 'L' here: %2").arg(lineNo).arg(line);
              qDebug() << txt;
            }

          continue;
        }

      suppress = false;

      QStringList list = line.split( " ", QString::SkipEmptyParts );

      if( list.size() != 2 )
        {
          QString txt = QString("Error line %1: Expecting length info here: %2").arg(lineNo).arg(line);
          qDebug() << txt;
          continue;
        }

      bool ok;

      // extract polygon element member count
      int members = list[1].toInt( &ok );

      if( ! ok )
        {
          continue;
        }

      QPolygonF pg;

      // read all polygon members
      for( int i = 0; i < members && in.atEnd() == false; i++ )
        {
          line = in.readLine().trimmed();
          lineNo++;

          QStringList ll = line.split( " ", QString::SkipEmptyParts );

          if( ll.size() != 2 )
            {
              // To be sure, do a check and report errors.
              QString txt = QString("Error line %1: Expecting 2 coordinates here: %2").arg(lineNo).arg(line);
              qDebug() << txt;
              continue;
            }

          QPointF p;

          bool ok1, ok2;
          p.setX( ll[1].toFloat( &ok1 ));
          p.setY( ll[0].toFloat( &ok2 ));

          if( !ok1 || ! ok2 )
            {
              QString txt = QString("Error line %1: Expecting 2 floating point numbers here: %2").arg(lineNo).arg(line);
              qDebug() << txt;
              continue;
            }

          pg.append(p);
        }

      //qDebug() << "Add polygon:" << pg.size() << "Members:" << members;
      mwList.append( pg );
    }

  file.close();
  return true;
}
Example #11
0
void WikiEdit::ProcessWords()
{
    QString text = this->DiffText.toLower();
    int xx = 0;
    if (this->Page->Contents.length() > 0)
    {
        text = this->Page->Contents.toLower();
    }
    while (xx<Configuration::HuggleConfiguration->ProjectConfig->ScoreParts.count())
    {
        QString w = Configuration::HuggleConfiguration->ProjectConfig->ScoreParts.at(xx).word;
        if (text.contains(w))
        {
            this->Score += Configuration::HuggleConfiguration->ProjectConfig->ScoreParts.at(xx).score;
            ScoreWords.append(w);
        }
        xx++;
    }
    xx = 0;
    while (xx<Configuration::HuggleConfiguration->ProjectConfig->ScoreWords.count())
    {
        QString w = Configuration::HuggleConfiguration->ProjectConfig->ScoreWords.at(xx).word;
        // if there is no such a string in text we can skip it
        if (!text.contains(w))
        {
            xx++;
            continue;
        }
        int SD = 0;
        bool found = false;
        if (text == w)
            found = true;
        while (!found && SD < Configuration::HuggleConfiguration->SystemConfig_WordSeparators.count())
        {
            if (text.startsWith(w + Configuration::HuggleConfiguration->SystemConfig_WordSeparators.at(SD)))
            {
                found = true;
                break;
            }
            if (text.endsWith(Configuration::HuggleConfiguration->SystemConfig_WordSeparators.at(SD) + w))
            {
                found = true;
                break;
            }
            int SL = 0;
            while (SL <Configuration::HuggleConfiguration->SystemConfig_WordSeparators.count())
            {
                if (text.contains(Configuration::HuggleConfiguration->SystemConfig_WordSeparators.at(SD) +
                             w + Configuration::HuggleConfiguration->SystemConfig_WordSeparators.at(SL)))
                {
                    found = true;
                    break;
                }
                if (found)
                    break;
                SL++;
            }
            SD++;
        }
        if (found)
        {
            this->Score += Configuration::HuggleConfiguration->ProjectConfig->ScoreWords.at(xx).score;
            ScoreWords.append(w);
        }
        xx++;
    }
}
Example #12
0
int
main(int argc,
     char** argv)
{
    if (argc != 6) {
        std::cout << "This program takes in input glad.h and outputs the include and implementation files for OSMesa OpenGL function and regular OpenGL functions." << std::endl;
        std::cout << "Usage: generateGLIncludes <glad.h path> <output dir path> <namespace name> <baseFileName>" << std::endl;
        std::cout << "Example: generateGLIncludes /Users/alexandre/development/Natron/Global/gladRel/include/glad/glad.h /Users/alexandre/development/Natron/Engine Natron OSGLFunctions 1" << std::endl;

        return 1;
    }

    QFile f(argv[1]);
    if ( !f.open(QIODevice::ReadOnly) ) {
        std::cout << "Could not open " << argv[1] << std::endl;

        return 1;
    }

    // Check that output path exists

    QDir outputDir(argv[2]);
    if ( !outputDir.exists() ) {
        std::cout << argv[2] << " does not seem to be a valid directory" << std::endl;

        return 1;
    }

    QString namespaceName(argv[3]);
    QString baseFilename(argv[4]);
    QString absoluteDirPath = outputDir.absolutePath();
    QString outputHeaderFilename = absoluteDirPath + "/" + baseFilename + ".h";
    QFile of_header(outputHeaderFilename);
    if ( !of_header.open(QIODevice::WriteOnly) ) {
        std::cout << "Could not open " << outputHeaderFilename.toStdString() << std::endl;

        return 1;
    }
    QTextStream ots_header(&of_header);
    QTextStream its(&f);
    QString definesStr;

    std::list<FunctionSignature> signatures;
    QString functionTypedefsStr;
    QString prevLine;
    while ( !its.atEnd() ) {
        // Read each line of glad.h
        QString line = its.readLine();

        {
            // Search for a define
            QString toFind = "#define GL_";
            int found = line.indexOf(toFind);
            if (found != -1) {
                definesStr += line;
                definesStr += "\n";
            }
        }

        // Search for a function
        QString typedefToken("typedef ");
        QString pfnToken("(APIENTRYP PFNGL");
        int foundFuncDef = line.indexOf(typedefToken);
        int foundPNFToken = line.indexOf(pfnToken);
        if ( (foundFuncDef != -1) && (foundPNFToken != -1) ) {
            int pos = foundPNFToken + pfnToken.size();
            int foundFirstEndParenthesis = line.indexOf(')', pos);
            assert(foundFirstEndParenthesis != -1);


            FunctionSignature signature;
            QString lastFuncNameCaps = line.mid(pos, foundFirstEndParenthesis - pos);
            signature.signature = line.mid(foundFirstEndParenthesis);
            // "near" and "far" are defined as macros in windows.h
            signature.signature.replace("GLdouble near, GLdouble far", "GLdouble nearVal, GLdouble farVal");

            signature.returnType = line.mid( foundFuncDef + typedefToken.size(), foundPNFToken - 1 - ( foundFuncDef + typedefToken.size() ) );
            QString funcTypeDefStr = "typedef ";
            funcTypeDefStr += signature.returnType;
            funcTypeDefStr += " (*PFNGL";
            funcTypeDefStr += lastFuncNameCaps;
            funcTypeDefStr += signature.signature;
            funcTypeDefStr += "\n";
            functionTypedefsStr += funcTypeDefStr;

            // Remove the extraneous ; at the end of the signature
            // Also remove the prepending )
            signature.signature.remove(0, 1);
            signature.signature.remove(signature.signature.size() - 1, 1);

            signature.funcPNType = "PFNGL";
            signature.funcPNType += lastFuncNameCaps;

            // extract parameters
            {
                int i = 1; // start after the leading (
                while ( i < signature.signature.size() ) {
                    QString param;
                    while ( signature.signature[i] != QChar(',') && signature.signature[i] != QChar(')') ) {
                        param.append(signature.signature[i]);
                        ++i;
                    }

                    // Now only keep the name of the parameter
                    {
                        int j = param.size() - 1;
                        while ( j >= 0 && param[j].isLetterOrNumber() ) {
                            --j;
                        }
                        param = param.mid(j + 1);
                    }
                    signature.parameters.append(param);

                    assert( signature.signature[i] == QChar(',') || signature.signature[i] == QChar(')') );
                    ++i; // bypass last character

                    if ( signature.signature[i] == QChar(')') ) {
                        break;
                    }
                }
            }

            // we caught a function typedef before, we expect to read the following #define glXxxx function with the appropriate case
            // in release glad.h, the next line is of the type GLAPI PFNGLCOLOR4FVPROC glad_glColor4fv;
            // the line after that is the one we want #define glColor4fv glad_glColor4fv
            line = its.readLine();
            assert( !its.atEnd() );
            line = its.readLine();

            QString toFind("#define gl");
            int foundDefine = line.indexOf(toFind);
            if (foundDefine == -1) {
                std::cout << "Parser failed to find #define glXXX statement 2 lines after a function typedef, make sure that you are running this program against a release version of glad.h" << std::endl;

                return 1;
            }

            // Check that this is the same symbol
            // Remove the PROC at the end of the func def
            lastFuncNameCaps.remove("PROC");
            int checkIndex = toFind.size();
            QString symbolStart = line.mid(checkIndex);
            assert( symbolStart.startsWith(lastFuncNameCaps, Qt::CaseInsensitive) );

            {
                int i = 8; // start on the g
                //extract the function name
                while ( i < line.size() && line.at(i) != QChar(' ') ) {
                    signature.funcName.push_back( line.at(i) );
                    ++i;
                }
            }
            signature.funcNameNoGL = signature.funcName;
            signature.funcNameNoGL.remove(0,2); // remove "gl"
            signatures.push_back(signature);
        } // if (foundFuncDef != -1 && foundPNFToken != -1) {

        prevLine = line;
    }

    writeHeader(ots_header);
#if 0 // moved to Global/GLObfuscate.h
    ots_header <<
        "// remove global macro definitions of OpenGL functions by glad.h\n"
        "// fgrep \"#define gl\" glad.h |sed -e 's/#define/#undef/g' |awk '{print $1, $2}'\n";
    // undef glad's defines
    for (std::list<FunctionSignature>::iterator it = signatures.begin(); it != signatures.end(); ++it) {
      ots_header << "#undef " << it->funcName << '\n';
    }
#endif

    writeStartClass(namespaceName, ots_header);

    // Define the singleton
    ots_header <<
        "    static OSGLFunctions<USEOPENGL>& getInstance()\n"
        "    {\n"
        "        static OSGLFunctions<USEOPENGL> instance;\n"
        "\n"
        "        return instance;\n"
        "    }\n"
        "\n"
        "    // load function, implemented in _gl.h and _mesa.h\n"
        "    void load_functions();\n"
        "\n"
        "    // private constructor\n"
        "    OSGLFunctions() { std::memset(this, 0, sizeof(*this)); load_functions(); }\n"
        "\n";

    // Declare member functions
    for (std::list<FunctionSignature>::iterator it = signatures.begin(); it != signatures.end(); ++it) {
        ots_header << "    " << it->funcPNType << " _" << it->funcName << ";\n";
    }

    ots_header <<
        "\n";

    ots_header <<
        "public:\n"
        "\n";


    ots_header <<
        "    // static non MT-safe load function that must be called once to initialize functions\n"
        "    static void load()\n"
        "    {\n"
        "        (void)getInstance();\n"
        "    }\n"
        "\n"
        "    static bool isGPU()\n"
        "    {\n"
        "        return USEOPENGL;\n"
        "    }\n";

    for (std::list<FunctionSignature>::iterator it = signatures.begin(); it != signatures.end(); ++it) {
        QString lineStart = "    static " +  it->returnType + " " + it->funcNameNoGL;
        QString indentedSig = it->signature;
        indentedSig.replace( ", ", ",\n" + QString(lineStart.size() + 1, ' ') );
        ots_header << "\n" <<
            lineStart << indentedSig << "\n"
            "    {\n";
        if (it->returnType == "void") {
            ots_header << "        ";
        } else {
            ots_header << "        return ";
        }
        ots_header << "getInstance()._" << it->funcName << "(";
        QStringList::const_iterator next = it->parameters.begin();
        if ( !it->parameters.isEmpty() ) {
            ++next;
        }
        for (QStringList::const_iterator it2 = it->parameters.begin(); it2 != it->parameters.end(); ++it2) {
            ots_header << *it2;
            if ( next != it->parameters.end() ) {
                ots_header << ", ";
                ++next;
            }
        }

        ots_header <<
            ");\n"
            "    }\n";
    }
    writeEndClass(namespaceName, ots_header);

    writeFooter(ots_header);

    writeImplementationCppFile(namespaceName, baseFilename, signatures, absoluteDirPath, "gl", true);
    writeImplementationCppFile(namespaceName, baseFilename, signatures, absoluteDirPath, "mesa", false);


    return 0;
} // main
Example #13
0
static bool LoginNeeded(const QString& repository)
{
    return repository.startsWith(QLatin1String(":pserver:")) ||
           repository.startsWith(QLatin1String(":sspi:"));
}
Example #14
0
void GwtCallback::browseUrl(QString url)
{
    QUrl qurl(url);

#ifdef Q_WS_MAC
    if (qurl.scheme() == QString::fromAscii("file"))
    {
        QProcess open;
        QStringList args;
        // force use of Preview for PDFs (Adobe Reader 10.01 crashes)
        if (url.toLower().endsWith(QString::fromAscii(".pdf")))
        {
            args.append(QString::fromAscii("-a"));
            args.append(QString::fromAscii("Preview"));
            args.append(url);
        }
        else
        {
            args.append(url);
        }
        open.start(QString::fromAscii("open"), args);
        open.waitForFinished(5000);
        if (open.exitCode() != 0)
        {
            // Probably means that the file doesn't have a registered
            // application or something.
            QProcess reveal;
            reveal.startDetached(QString::fromAscii("open"), QStringList() << QString::fromAscii("-R") << url);
        }
        return;
    }
#endif

    if (qurl.isRelative())
    {
        // TODO: this should really be handled within GlobalDisplay -- rather
        // than checking for a relative URL here GlobalDisplay should determine
        // that a URL is relative and do the right thing (note this needs to
        // account for our policy regarding /custom/* urls -- below we allow
        // these to be opened in a standard browser window to match the
        // behavior of standard CRAN desktop R).

        // compute local url
        QUrl localUrl;
        localUrl.setScheme(QString::fromAscii("http"));
        localUrl.setHost(QString::fromAscii("localhost"));
        localUrl.setPort(options().portNumber().toInt());
        localUrl.setEncodedPath(url.toAscii());

        // show it in a browser or a secondary window as appropriate
        if (url.startsWith(QString::fromAscii("custom/")) ||
                url.startsWith(QString::fromAscii("help/")))
        {
            QDesktopServices::openUrl(localUrl);
        }
        else
        {
            SecondaryWindow* pBrowser = new SecondaryWindow(localUrl);
            pBrowser->webView()->load(localUrl);
            pBrowser->show();
            pBrowser->activateWindow();
        }
    }
    else
    {
        QDesktopServices::openUrl(qurl);
    };
}
Example #15
0
ObjectPtr Private::JSONToContact(const QVariantMap& data)
{
    ContactPtr contact(new Contact);

    /* Google contact ID */
    contact->setUid(Private::stringFromXMLMap(data, QStringLiteral("id")));

    /* Google ETAG. This can be used to identify if the item was changed remotly */
    contact->setEtag(data.value(QStringLiteral("gd$etag")).toString());

    /* Date and time when contact was updated on the remote server */
    contact->setUpdated(QDateTime::fromString(Private::stringFromXMLMap(data, QStringLiteral("updated")), Qt::ISODate));

    /* If the contact was deleted, we don't need more info about it.
     * Just store our own flag, which will be then parsed by the resource
     * itself. */
    contact->setDeleted(data.value(QStringLiteral("gd$deleted")).isValid());

    /* Store URL of the picture. The URL will be used later by PhotoJob to fetch the picture
     * itself. */
    const QVariantList links = data.value(QStringLiteral("link")).toList();
    Q_FOREACH(const QVariant &link, links) {
        const QVariantMap linkMap = link.toMap();
        if (linkMap.value(QStringLiteral("rel")).toString() == QLatin1String("http://schemas.google.com/contacts/2008/rel#photo")) {
            contact->setPhotoUrl(linkMap.value(QStringLiteral("href")).toString());
        }
    }

    /* Name */
    if (data.contains(QStringLiteral("title"))) {
        contact->setName(Private::stringFromXMLMap(data, QStringLiteral("title")));
    }

    /* Formatted name */
    if (data.contains(QStringLiteral("gd$name"))) {
        const QVariantMap name = data.value(QStringLiteral("gd$name")).toMap();

        if (name.contains(QStringLiteral("gd$fullName"))) {
            contact->setFormattedName(Private::stringFromXMLMap(name, QStringLiteral("gd$fullName")));
        }
        if (name.contains(QStringLiteral("gd$givenName"))) {
            contact->setGivenName(Private::stringFromXMLMap(name, QStringLiteral("gd$givenName")));
        }
        if (name.contains(QStringLiteral("gd$familyName"))) {
            contact->setFamilyName(Private::stringFromXMLMap(name, QStringLiteral("gd$familyName")));
        }
        if (name.contains(QStringLiteral("gd$additionalName"))) {
            contact->setAdditionalName(Private::stringFromXMLMap(name, QStringLiteral("gd$additionalName")));
        }
        if (name.contains(QStringLiteral("gd$namePrefix"))) {
            contact->setPrefix(Private::stringFromXMLMap(name, QStringLiteral("gd$namePrefix")));
        }
        if (name.contains(QStringLiteral("gd$nameSuffix"))) {
            contact->setSuffix(Private::stringFromXMLMap(name, QStringLiteral("gd$nameSuffix")));
        }
    }

    /* Note */
    if (data.contains(QStringLiteral("content"))) {
        contact->setNote(Private::stringFromXMLMap(data, QStringLiteral("content")));
    }

    /* Organization (work) - KABC supports only one organization */
    if (data.contains(QStringLiteral("gd$organization"))) {
        const QVariantList organizations = data.value(QStringLiteral("gd$organization")).toList();
        const QVariantMap organization = organizations.first().toMap();

        if (organization.contains(QStringLiteral("gd$orgName"))) {
            contact->setOrganization(Private::stringFromXMLMap(organization, QStringLiteral("gd$orgName")));
        }
        if (organization.contains(QStringLiteral("gd$orgDepartment"))) {
            contact->setDepartment(Private::stringFromXMLMap(organization, QStringLiteral("gd$orgDepartment")));
        }
        if (organization.contains(QStringLiteral("gd$orgTitle"))) {
            contact->setTitle(Private::stringFromXMLMap(organization, QStringLiteral("gd$orgTitle")));
        }
        if (organization.contains(QStringLiteral("gd$where"))) {
            contact->setOffice(Private::stringFromXMLMap(organization, QStringLiteral("gd$where")));
        }
    }

    /* Nickname */
    if (data.contains(QStringLiteral("gContact$nickname"))) {
        contact->setNickName(Private::stringFromXMLMap(data, QStringLiteral("gContact$nickname")));
    }

    /* Occupation (= organization/title) */
    if (data.contains(QStringLiteral("gContact$occupation"))) {
        contact->setProfession(Private::stringFromXMLMap(data, QStringLiteral("gContact$occupation")));
    }

    /* Relationships */
    if (data.contains(QStringLiteral("gContact$relation"))) {
        const QVariantList relations = data.value(QStringLiteral("gContact$relation")).toList();
        Q_FOREACH(const QVariant &r, relations) {
            const QVariantMap relation = r.toMap();
            if (relation.value(QStringLiteral("rel")).toString() == QLatin1String("spouse")) {
                contact->setSpousesName(relation.value(QStringLiteral("$t")).toString());
                continue;
            }

            if (relation.value(QStringLiteral("rel")).toString() == QLatin1String("manager")) {
                contact->setManagersName(relation.value(QStringLiteral("$t")).toString());
                continue;
            }

            if (relation.value(QStringLiteral("rel")).toString() == QLatin1String("assistant")) {
                contact->setAssistantsName(relation.value(QStringLiteral("$t")).toString());
                continue;
            }
        }
    }

    /* Anniversary */
    if (data.contains(QStringLiteral("gContact$event"))) {
        const QVariantList events = data.value(QStringLiteral("gContact$event")).toList();
        Q_FOREACH(const QVariant &e, events) {
            const QVariantMap event = e.toMap();

            if (event.value(QStringLiteral("rel")).toString() == QLatin1String("anniversary")) {
                QVariantMap when = event.value(QStringLiteral("gd$when")).toMap();
                contact->setAnniversary(when.value(QStringLiteral("startTime")).toString());
            }
        }
    }

    /* Websites */
    if (data.contains(QStringLiteral("gContact$website"))) {
        const QVariantList websites = data.value(QStringLiteral("gContact$website")).toList();
        Q_FOREACH(const QVariant &w, websites) {
            const QVariantMap web = w.toMap();

            if (web.value(QStringLiteral("rel")).toString() == QLatin1String("home-page")) {
                KContacts::ResourceLocatorUrl url;
                url.setUrl(QUrl(web.value(QStringLiteral("href")).toString()));
                contact->setUrl(url);
                continue;
            }

            if (web.value(QStringLiteral("rel")).toString() == QLatin1String("blog")) {
                contact->setBlogFeed(web.value(QStringLiteral("href")).toString());
                continue;
            }
        }
    }

    /* Emails */
    const QVariantList emails = data.value(QStringLiteral("gd$email")).toList();
    Q_FOREACH(const QVariant & em, emails) {
        const QVariantMap email = em.toMap();
        contact->insertEmail(email.value(QStringLiteral("address")).toString(),
                            email.value(QStringLiteral("primary")).toBool());
    }

    /* IMs */
    const QVariantList ims = data.value(QStringLiteral("gd$im")).toList();
    Q_FOREACH(const QVariant & i, ims) {
        const QVariantMap im = i.toMap();
        const QString protocol = Contact::IMSchemeToProtocolName(im.value(QStringLiteral("protocol")).toString());
        contact->insertCustom(QLatin1String("messaging/") + protocol,
                             QStringLiteral("All"),
                             im.value(QStringLiteral("address")).toString());
    }

    /* Phone numbers */
    const QVariantList phones = data.value(QStringLiteral("gd$phoneNumber")).toList();
    Q_FOREACH(const QVariant & p, phones) {
        const QVariantMap phone = p.toMap();
        contact->insertPhoneNumber(KContacts::PhoneNumber(phone.value(QStringLiteral("$t")).toString(),
                                  Contact::phoneSchemeToType(phone.value(QStringLiteral("rel")).toString())));
    }

    /* Addresses */
    const QVariantList addresses = data.value(QStringLiteral("gd$structuredPostalAddress")).toList();
    Q_FOREACH(const QVariant & a, addresses) {
        const QVariantMap address = a.toMap();
        KContacts::Address addr;
        if (!address.contains(QStringLiteral("gd$city")) &&
                !address.contains(QStringLiteral("gd$country")) &&
                !address.contains(QStringLiteral("gd$postcode")) &&
                !address.contains(QStringLiteral("gd$region")) &&
                !address.contains(QStringLiteral("gd$pobox")))
        {
            addr.setExtended(Private::stringFromXMLMap(address, QStringLiteral("gd$street")));
        } else {
            if (address.contains(QStringLiteral("gd$street"))) {
                addr.setStreet(Private::stringFromXMLMap(address, QStringLiteral("gd$street")));
            }
            if (address.contains(QStringLiteral("gd$country"))) {
                addr.setCountry(Private::stringFromXMLMap(address, QStringLiteral("gd$country")));
            }
            if (address.contains(QStringLiteral("gd$city"))) {
                addr.setLocality(Private::stringFromXMLMap(address, QStringLiteral("gd$city")));
            }
            if (address.contains(QStringLiteral("gd$postcode"))) {
                addr.setPostalCode(Private::stringFromXMLMap(address, QStringLiteral("gd$postcode")));
            }
            if (address.contains(QStringLiteral("gdregion"))) {
                addr.setRegion(Private::stringFromXMLMap(address, QStringLiteral("gd$region")));
            }
            if (address.contains(QStringLiteral("gd$pobox"))) {
                addr.setPostOfficeBox(Private::stringFromXMLMap(address, QStringLiteral("gd$pobox")));
            }
        }
        addr.setType(Contact::addressSchemeToType(address.value(QStringLiteral("rel")).toString()));

        contact->insertAddress(addr);
    }

    /* Birthday */
    const QVariantMap bDay = data.value(QStringLiteral("gContact$birthday")).toMap();
    if (!bDay.isEmpty()) {
        QString birthday = bDay.value(QStringLiteral("when")).toString();
        /* Birthdays in format "--MM-DD" are valid and mean that no year has
         * been specified. Since KABC does not support birthdays without year,
         * we simulate that by specifying a fake year - 1900 */
        if (birthday.startsWith(QLatin1String("--"))) {
            birthday = QLatin1String("1900") + birthday.mid(1);
        }
        contact->setBirthday(QDateTime::fromString(birthday, QStringLiteral("yyyy-MM-dd")));
    }

    /* User-defined fields */
    const QVariantList userDefined = data.value(QStringLiteral("gContact$userDefinedField")).toList();
    Q_FOREACH(const QVariant & u, userDefined) {
        const QVariantMap field = u.toMap();
        contact->insertCustom(QStringLiteral("KADDRESSBOOK"),
                             field.value(QStringLiteral("key")).toString(),
                             field.value(QStringLiteral("value")).toString());
    }

    /* Groups */
    const QVariantList groups = data.value(QStringLiteral("gContact$groupMembershipInfo")).toList();
    QStringList groupsList;
    Q_FOREACH(const QVariant & g, groups) {
        const QVariantMap group = g.toMap();
        if (group.value(QStringLiteral("deleted")).toBool() == false) {
            groupsList.append(group.value(QStringLiteral("href")).toString());
        }
    }
    contact->insertCustom(QStringLiteral("GCALENDAR"), QStringLiteral("groupMembershipInfo"),
                         groupsList.join(QStringLiteral(",")));

    return contact;
}
Example #16
0
/**
 * \addtogroup myth_network_protocol
 * \par        QUERY_FILE_EXISTS \e storagegroup \e filename
 */
bool FileServerHandler::HandleQueryFileExists(SocketHandler *socket,
                                              QStringList &slist)
{
    QString storageGroup = "Default";
    QStringList res;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    slist.clear();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    ft->BlockShutdown(true);

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

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

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

    socket->writeStringList(slist);
    m_parent->AddSocketHandler(ft);
    return true;
}
Example #18
0
QString Serveur::parseCommande(QString comm,bool serveur)
{
    if(comm.startsWith("/"))
    {
        comm.remove(0,1);
        QString pref=comm.split(" ").first();
        QStringList args=comm.split(" ");
        args.removeFirst();
        QString destChan=tab->tabText(tab->currentIndex());
        QString msg=args.join(" ");

        if(pref=="me")
            return "PRIVMSG "+destChan+" ACTION " + msg + "";
        else if(pref=="join")
        {
            join(msg);
            return " ";
        }
        else if(pref=="quit")
        {
            if(msg == "")
                return "QUIT "+msgQuit;
            else
                return "QUIT "+msg;
        }
        else if(pref=="part")
        {
            tab->removeTab(tab->currentIndex());

            if(msg == "")
            {
                if(msg.startsWith("#"))
                    destChan=msg.split(" ").first();

                if(msgQuit=="")
                    return "PART "+destChan+" using IrcLightClient";
                else
                    return "PART "+destChan+" "+msgQuit;
            }
            else
                return "PART "+destChan+" "+msg;

            conversations.remove(destChan);
        }
        else if(pref=="kick")
        {
            QStringList tableau=msg.split(" ");
            QString c1,c2,c3;
            if(tableau.count() > 0) c1=" "+tableau.first();
            else c1="";
            if(tableau.count() > 1) c2=" "+tableau.at(1);
            else c2="";
            if(tableau.count() > 2) c3=" "+tableau.at(2);
            else c3="";

            if(c1.startsWith("#"))
                return "KICK"+c1+c2+c3;
            else
                return "KICK "+destChan+c1+c2;
        }
        else if(pref=="update")
        {
            updateUsers=true;
            return "WHO "+destChan;
        }
        else if(pref=="ns")
        {
            return "NICKSERV "+msg;
        }
        else if(pref=="nick")
        {
            emit pseudoChanged(msg);
                        ecrire("-> Nickname changed to "+msg);
            return "NICK "+msg;
        }
        else
            return pref+" "+msg;
    }
    else if(!serveur)
	{
        QString destChan=tab->tabText(tab->currentIndex());
                if(comm.endsWith("<br />"))
                    comm=comm.remove(QRegExp("<br />$"));
                ecrire("<b>&lt;"+pseudo+"&gt;</b> "+comm,destChan);

        if(comm.startsWith(":"))
            comm.insert(0,":");

        return "PRIVMSG "+destChan+" "+comm.replace(" ",".")+"";
    }
	else
	{
		return "";
	}
}
Example #19
0
int main(int argc, char *argv[])
{
    QString  sourcefilename;
    QString  targetfilename;

    QCoreApplication  app( argc, argv );

    for ( int i = 1; i < argc; ++i ) {
        if ( strcmp( argv[ i ], "-o" ) != 0 )
            continue;

        targetfilename = QString(argv[i+1]);
        sourcefilename = QString(argv[i+2]);

        qDebug() << "Source: " << sourcefilename;
        qDebug() << "Target: " << targetfilename;

        QFile  sourcefile( sourcefilename );
        sourcefile.open( QIODevice::ReadOnly );

        // Read the data serialized from the file.
        QTextStream  sourcestream( &sourcefile );
        sourcestream.setCodec("UTF-8");

        QFile  targetfile( targetfilename );
        targetfile.open( QIODevice::ReadWrite );

        QTextStream  targetstream( &targetfile );
        targetstream.setCodec("UTF-8");

        // gzFile gzDoc = gzopen( targetfilename.toLatin1(), "w");
        // QTextStream targetstream( new QString() );

        targetstream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n"
                     << "<kml xmlns=\"http://earth.google.com/kml/2.1\"> \n"
                     << "<Document> \n";

        targetstream << "    <Schema name=\"MarblePlacemark\" parent=\"Placemark\"> \n";
        targetstream << "       <SimpleField name=\"pop\" type=\"int\"></SimpleField> \n";
        targetstream << "       <SimpleField name=\"role\" type=\"string\"></SimpleField> \n";
        targetstream << "    </Schema> \n";

        targetstream << "\n";

        QString  rawline;
        QString  nameString;
        QString  latString;
        QString  lonString;
        QString  popString;
        QString  roleString;
        QString  description;
        float    lat;
        float    lon;
        int          population;
        QStringList  splitline;

        while ( !sourcestream.atEnd() ) {

            rawline = sourcestream.readLine();
//            if ( !rawline.startsWith("\"E\"|\"m\"|\"" ) ) {
            if ( !rawline.startsWith(QLatin1String( "\"V\"|\"V\"|\"" ) ) ) {
                continue;
            }
            rawline = rawline.replace( "\"|", "|" );
            rawline = rawline.replace( "|\"", "|" );
            if ( rawline.startsWith('\"') && rawline.endsWith('\"') ) {
                rawline = rawline.left( rawline.length() - 1 );
                rawline = rawline.right( rawline.length() - 2 );
            }

            splitline = rawline.split('|');

            nameString  = splitline[2];
            latString   = splitline[3];
            lonString   = splitline[4];
            popString   = splitline[10];
            roleString  = splitline[18];
            description = splitline[19];

            // if ( roleString == "SF" ) continue;

            QString marbleRoleString = QLatin1String( "o" );

            if ( roleString == "AA" || roleString == "SF" ) marbleRoleString = "c";
            if (    roleString == "ME" || roleString == "OC" 
                 || roleString == "LC" || roleString == "SI" ) marbleRoleString = "a";
            if ( roleString == "MO" ) marbleRoleString = "m";
            if ( roleString == "VA" ) marbleRoleString = "v";

            population = (int) ( 1000.0 * popString.toFloat() );

            lon = lonString.toFloat();

            if ( lon > 180.0 ) lon = lon - 360.0;

            if ( rawline.startsWith(QLatin1String( "\"M\"|\"M\"|\"" ) ) || rawline.startsWith("\"V\"|\"V\"|\"" ) ) {
                lon = -lon;
            }

            lat = latString.toFloat();

            description = description.remove('"');

            targetstream << "    <MarblePlacemark> \n";
            targetstream << "        <name>" << escapeXml( nameString ) << "</name> \n";
            targetstream << "        <role>" << escapeXml( marbleRoleString ) << "</role> \n";
            targetstream << "        <pop>"
                         << escapeXml( QString::number( population ) ) << "</pop> \n";
            targetstream << "        <description>" << escapeXml( description ) << "</description> \n";
            targetstream << "        <Point>\n"
                         << "            <coordinates>"
                         << escapeXml( QString::number( lon ) )
                         << ","
                         << escapeXml( QString::number( lat ) )
                         << "</coordinates> \n"
                         << "        </Point> \n";
            targetstream << "    </MarblePlacemark> \n";
        }

        targetstream << "</Document> \n"
                     << "</kml> \n";
        qDebug("...");

        sourcefile.close();
        targetfile.close();

        qDebug("Finished!");
        return 0;
    }

    qDebug(" iau2kml -o targetfile sourcefile");
    app.exit();
}
Example #20
0
void
NmakeMakefileGenerator::init()
{
    if(init_flag)
        return;
    init_flag = TRUE;

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

    if(project->isEmpty("QMAKE_INSTALL_FILE"))
        project->variables()["QMAKE_INSTALL_FILE"].append("$(COPY_FILE)");
    if(project->isEmpty("QMAKE_INSTALL_DIR"))
        project->variables()["QMAKE_INSTALL_DIR"].append("$(COPY_DIR)");

    bool is_qt = (project->first("TARGET") == "qt"QTDLL_POSTFIX || project->first("TARGET") == "qt-mt"QTDLL_POSTFIX);
    project->variables()["QMAKE_ORIG_TARGET"] = project->variables()["TARGET"];

    QString targetfilename = project->variables()["TARGET"].first();
    QStringList &configs = project->variables()["CONFIG"];
    if (project->isActiveConfig("qt") && project->isActiveConfig("shared"))
        project->variables()["DEFINES"].append("QT_DLL");
    if (project->isActiveConfig("qt_dll"))
        if(configs.findIndex("qt") == -1) configs.append("qt");
    if ( project->isActiveConfig("qtopia") ) {
        if(configs.findIndex("qtopialib") == -1)
            configs.append("qtopialib");
        if(configs.findIndex("qtopiainc") == -1)
            configs.append("qtopiainc");
    }
    if ( project->isActiveConfig("qt") ) {
        if ( project->isActiveConfig( "plugin" ) ) {
            project->variables()["CONFIG"].append("dll");
            if(project->isActiveConfig("qt"))
                project->variables()["DEFINES"].append("QT_PLUGIN");
        }
        if ( (project->variables()["DEFINES"].findIndex("QT_NODLL") == -1) &&
                ((project->variables()["DEFINES"].findIndex("QT_MAKEDLL") != -1 ||
                  project->variables()["DEFINES"].findIndex("QT_DLL") != -1) ||
                 (getenv("QT_DLL") && !getenv("QT_NODLL"))) ) {
            project->variables()["QMAKE_QT_DLL"].append("1");
            if ( is_qt && !project->variables()["QMAKE_LIB_FLAG"].isEmpty() )
                project->variables()["CONFIG"].append("dll");
        }
        if ( project->isActiveConfig("thread") )
            project->variables()[is_qt ? "PRL_EXPORT_DEFINES" : "DEFINES"].append("QT_THREAD_SUPPORT");
        if ( project->isActiveConfig("accessibility" ) )
            project->variables()[is_qt ? "PRL_EXPORT_DEFINES" : "DEFINES"].append("QT_ACCESSIBILITY_SUPPORT");
        if ( project->isActiveConfig("tablet") )
            project->variables()[is_qt ? "PRL_EXPORT_DEFINES" : "DEFINES"].append("QT_TABLET_SUPPORT");
    }
    if ( project->isActiveConfig("dll") || !project->variables()["QMAKE_APP_FLAG"].isEmpty() ) {
        project->variables()["CONFIG"].remove("staticlib");
        project->variables()["QMAKE_APP_OR_DLL"].append("1");
    } else {
        project->variables()["CONFIG"].append("staticlib");
    }
    if ( project->isActiveConfig("warn_off") ) {
        project->variables()["QMAKE_CFLAGS"] += project->variables()["QMAKE_CFLAGS_WARN_OFF"];
        project->variables()["QMAKE_CXXFLAGS"] += project->variables()["QMAKE_CXXFLAGS_WARN_OFF"];
    } else if ( project->isActiveConfig("warn_on") ) {
        project->variables()["QMAKE_CFLAGS"] += project->variables()["QMAKE_CFLAGS_WARN_ON"];
        project->variables()["QMAKE_CXXFLAGS"] += project->variables()["QMAKE_CXXFLAGS_WARN_ON"];
    }
    if ( project->isActiveConfig("debug") ) {
        if ( project->isActiveConfig("thread") ) {
            // use the DLL RT even here
            if ( project->variables()["DEFINES"].contains("QT_DLL") ) {
                project->variables()["QMAKE_CFLAGS"] += project->variables()["QMAKE_CFLAGS_MT_DLLDBG"];
                project->variables()["QMAKE_CXXFLAGS"] += project->variables()["QMAKE_CXXFLAGS_MT_DLLDBG"];
            } else {
                project->variables()["QMAKE_CFLAGS"] += project->variables()["QMAKE_CFLAGS_MT_DBG"];
                project->variables()["QMAKE_CXXFLAGS"] += project->variables()["QMAKE_CXXFLAGS_MT_DBG"];
            }
        }
        project->variables()["QMAKE_CFLAGS"] += project->variables()["QMAKE_CFLAGS_DEBUG"];
        project->variables()["QMAKE_CXXFLAGS"] += project->variables()["QMAKE_CXXFLAGS_DEBUG"];
        project->variables()["QMAKE_LFLAGS"] += project->variables()["QMAKE_LFLAGS_DEBUG"];
    } else {
        if ( project->isActiveConfig("thread") ) {
            if ( project->variables()["DEFINES"].contains("QT_DLL") ) {
                project->variables()["QMAKE_CFLAGS"] += project->variables()["QMAKE_CFLAGS_MT_DLL"];
                project->variables()["QMAKE_CXXFLAGS"] += project->variables()["QMAKE_CXXFLAGS_MT_DLL"];
            } else {
                project->variables()["QMAKE_CFLAGS"] += project->variables()["QMAKE_CFLAGS_MT"];
                project->variables()["QMAKE_CXXFLAGS"] += project->variables()["QMAKE_CXXFLAGS_MT"];
            }
        }
        project->variables()["QMAKE_CFLAGS"] += project->variables()["QMAKE_CFLAGS_RELEASE"];
        project->variables()["QMAKE_CXXFLAGS"] += project->variables()["QMAKE_CXXFLAGS_RELEASE"];
        project->variables()["QMAKE_LFLAGS"] += project->variables()["QMAKE_LFLAGS_RELEASE"];
    }
    if ( project->isActiveConfig("thread") && !project->variables()["DEFINES"].contains("QT_DLL")
            && !is_qt && project->first("TARGET") != "qtmain") {
        project->variables()["QMAKE_LFLAGS"].append("/NODEFAULTLIB:\"libc\"");
    }

    if ( !project->variables()["QMAKE_INCDIR"].isEmpty())
        project->variables()["INCLUDEPATH"] += project->variables()["QMAKE_INCDIR"];
    if ( project->isActiveConfig("qt") || project->isActiveConfig("opengl") )
        project->variables()["CONFIG"].append("windows");
    if ( project->isActiveConfig("qtopiainc") )
        project->variables()["INCLUDEPATH"] += project->variables()["QMAKE_INCDIR_QTOPIA"];
    if ( project->isActiveConfig("qtopialib") ) {
        if(!project->isEmpty("QMAKE_LIBDIR_QTOPIA"))
            project->variables()["QMAKE_LIBDIR"] += project->variables()["QMAKE_LIBDIR_QTOPIA"];
        project->variables()["QMAKE_LIBS"] += project->variables()["QMAKE_LIBS_QTOPIA"];
    }
    if ( project->isActiveConfig("qt") ) {
        project->variables()["CONFIG"].append("moc");
        project->variables()["INCLUDEPATH"] +=	project->variables()["QMAKE_INCDIR_QT"];
        project->variables()["QMAKE_LIBDIR"] += project->variables()["QMAKE_LIBDIR_QT"];
        if ( !project->isActiveConfig("debug") )
            project->variables()[is_qt ? "PRL_EXPORT_DEFINES" : "DEFINES"].append("QT_NO_DEBUG");
        if ( is_qt && !project->variables()["QMAKE_LIB_FLAG"].isEmpty() ) {
            if ( !project->variables()["QMAKE_QT_DLL"].isEmpty()) {
                project->variables()["DEFINES"].append("QT_MAKEDLL");
                project->variables()["QMAKE_LFLAGS"] += project->variables()["QMAKE_LFLAGS_QT_DLL"];
            }
        } else {
            if(project->isActiveConfig("thread"))
                project->variables()["QMAKE_LIBS"] += project->variables()["QMAKE_LIBS_QT_THREAD"];
            else
                project->variables()["QMAKE_LIBS"] += project->variables()["QMAKE_LIBS_QT"];
            if ( !project->variables()["QMAKE_QT_DLL"].isEmpty() ) {
                int hver = findHighestVersion(project->first("QMAKE_LIBDIR_QT"), "qt");
                if ( hver == -1 )
                    hver = findHighestVersion(project->first("QMAKE_LIBDIR_QT"), "qt-mt");
                if(hver != -1) {
                    QString ver;
                    ver.sprintf("qt%s" QTDLL_POSTFIX "%d.lib", (project->isActiveConfig("thread") ? "-mt" : ""), hver);
                    QStringList &libs = project->variables()["QMAKE_LIBS"];
                    for(QStringList::Iterator libit = libs.begin(); libit != libs.end(); ++libit)
                        (*libit).replace(QRegExp("qt(-mt)?\\.lib"), ver);
                }
            }
            if ( project->isActiveConfig( "activeqt" ) ) {
                project->variables().remove("QMAKE_LIBS_QT_ENTRY");
                project->variables()["QMAKE_LIBS_QT_ENTRY"] = "qaxserver.lib";
                if ( project->isActiveConfig( "dll" ) )
                    project->variables()["QMAKE_LIBS"] += project->variables()["QMAKE_LIBS_QT_ENTRY"];
            }
            if ( !project->isActiveConfig("dll") && !project->isActiveConfig("plugin") ) {
                project->variables()["QMAKE_LIBS"] +=project->variables()["QMAKE_LIBS_QT_ENTRY"];
            }
        }
    }
    if ( project->isActiveConfig("opengl") ) {
        project->variables()["QMAKE_LIBS"] += project->variables()["QMAKE_LIBS_OPENGL"];
        project->variables()["QMAKE_LFLAGS"] += project->variables()["QMAKE_LFLAGS_OPENGL"];
    }
    if ( project->isActiveConfig("dll") ) {
        project->variables()["QMAKE_CFLAGS_CONSOLE_ANY"] = project->variables()["QMAKE_CFLAGS_CONSOLE_DLL"];
        project->variables()["QMAKE_CXXFLAGS_CONSOLE_ANY"] = project->variables()["QMAKE_CXXFLAGS_CONSOLE_DLL"];
        project->variables()["QMAKE_LFLAGS_CONSOLE_ANY"] = project->variables()["QMAKE_LFLAGS_CONSOLE_DLL"];
        project->variables()["QMAKE_LFLAGS_WINDOWS_ANY"] = project->variables()["QMAKE_LFLAGS_WINDOWS_DLL"];
        if ( !project->variables()["QMAKE_LIB_FLAG"].isEmpty()) {
            project->variables()["TARGET_EXT"].append(
                QStringList::split('.',project->first("VERSION")).join("") + ".dll");
        } else {
            project->variables()["TARGET_EXT"].append(".dll");
        }
    } else {
        project->variables()["QMAKE_CFLAGS_CONSOLE_ANY"] = project->variables()["QMAKE_CFLAGS_CONSOLE"];
        project->variables()["QMAKE_CXXFLAGS_CONSOLE_ANY"] = project->variables()["QMAKE_CXXFLAGS_CONSOLE"];
        project->variables()["QMAKE_LFLAGS_CONSOLE_ANY"] = project->variables()["QMAKE_LFLAGS_CONSOLE"];
        project->variables()["QMAKE_LFLAGS_WINDOWS_ANY"] = project->variables()["QMAKE_LFLAGS_WINDOWS"];
        if ( !project->variables()["QMAKE_APP_FLAG"].isEmpty()) {
            project->variables()["TARGET_EXT"].append(".exe");
        } else {
            project->variables()["TARGET_EXT"].append(".lib");
        }
    }
    if ( project->isActiveConfig("windows") ) {
        if ( project->isActiveConfig("console") ) {
            project->variables()["QMAKE_CFLAGS"] += project->variables()["QMAKE_CFLAGS_CONSOLE_ANY"];
            project->variables()["QMAKE_CXXFLAGS"] += project->variables()["QMAKE_CXXFLAGS_CONSOLE_ANY"];
            project->variables()["QMAKE_LFLAGS"] += project->variables()["QMAKE_LFLAGS_CONSOLE_ANY"];
            project->variables()["QMAKE_LIBS"] += project->variables()["QMAKE_LIBS_CONSOLE"];
        } else {
            project->variables()["QMAKE_LFLAGS"] += project->variables()["QMAKE_LFLAGS_WINDOWS_ANY"];
        }
        project->variables()["QMAKE_LIBS"] += project->variables()["QMAKE_LIBS_WINDOWS"];
    } else {
        project->variables()["QMAKE_CFLAGS"] += project->variables()["QMAKE_CFLAGS_CONSOLE_ANY"];
        project->variables()["QMAKE_CXXFLAGS"] += project->variables()["QMAKE_CXXFLAGS_CONSOLE_ANY"];
        project->variables()["QMAKE_LFLAGS"] += project->variables()["QMAKE_LFLAGS_CONSOLE_ANY"];
        project->variables()["QMAKE_LIBS"] += project->variables()["QMAKE_LIBS_CONSOLE"];
    }
    if ( project->isActiveConfig("stl") ) {
        project->variables()["QMAKE_CFLAGS"] += project->variables()["QMAKE_CFLAGS_STL_ON"];
        project->variables()["QMAKE_CXXFLAGS"] += project->variables()["QMAKE_CXXFLAGS_STL_ON"];
    } else {
        project->variables()["QMAKE_CFLAGS"] += project->variables()["QMAKE_CFLAGS_STL_OFF"];
        project->variables()["QMAKE_CXXFLAGS"] += project->variables()["QMAKE_CXXFLAGS_STL_OFF"];
    }
    if ( project->isActiveConfig("exceptions") ) {
        project->variables()["QMAKE_CFLAGS"] += project->variables()["QMAKE_CFLAGS_EXCEPTIONS_ON"];
        project->variables()["QMAKE_CXXFLAGS"] += project->variables()["QMAKE_CXXFLAGS_EXCEPTIONS_ON"];
    } else {
        project->variables()["QMAKE_CFLAGS"] += project->variables()["QMAKE_CFLAGS_EXCEPTIONS_OFF"];
        project->variables()["QMAKE_CXXFLAGS"] += project->variables()["QMAKE_CXXFLAGS_EXCEPTIONS_OFF"];
    }
    if ( project->isActiveConfig("rtti") ) {
        project->variables()["QMAKE_CFLAGS"] += project->variables()["QMAKE_CFLAGS_RTTI_ON"];
        project->variables()["QMAKE_CXXFLAGS"] += project->variables()["QMAKE_CXXFLAGS_RTTI_ON"];
    } else {
        project->variables()["QMAKE_CFLAGS"] += project->variables()["QMAKE_CFLAGS_RTTI_OFF"];
        project->variables()["QMAKE_CXXFLAGS"] += project->variables()["QMAKE_CXXFLAGS_RTTI_OFF"];
    }


    if ( project->isActiveConfig("moc") )
        setMocAware(TRUE);
    project->variables()["QMAKE_LIBS"] += project->variables()["LIBS"];

    QStringList &libList = project->variables()["QMAKE_LIBS"];
    for( QStringList::Iterator stIt = libList.begin(); stIt != libList.end(); ) {
        QString s = *stIt;
        if( s.startsWith( "-l" ) ) {
            stIt = libList.remove( stIt );
            stIt = libList.insert( stIt, s.mid( 2 ) + ".lib" );
        } else if( s.startsWith( "-L" ) ) {
            stIt = libList.remove( stIt );
            project->variables()["QMAKE_LIBDIR"].append(QDir::convertSeparators(s.mid( 2 )));
        } else {
            stIt++;
        }
    }

    project->variables()["QMAKE_FILETAGS"] += QStringList::split(' ',
            "HEADERS SOURCES DEF_FILE RC_FILE TARGET QMAKE_LIBS DESTDIR DLLDESTDIR INCLUDEPATH");
    QStringList &l = project->variables()["QMAKE_FILETAGS"];
    QStringList::Iterator it;
    for(it = l.begin(); it != l.end(); ++it) {
        QStringList &gdmf = project->variables()[(*it)];
        for(QStringList::Iterator inner = gdmf.begin(); inner != gdmf.end(); ++inner)
            (*inner) = Option::fixPathToTargetOS((*inner), FALSE);
    }

    if ( !project->variables()["DEF_FILE"].isEmpty() )
        project->variables()["QMAKE_LFLAGS"].append(QString("/DEF:") + project->first("DEF_FILE"));
    if(!project->isActiveConfig("incremental"))
        project->variables()["QMAKE_LFLAGS"].append(QString("/incremental:no"));

    if ( !project->variables()["VERSION"].isEmpty() ) {
        QString version = project->variables()["VERSION"][0];
        int firstDot = version.find( "." );
        QString major = version.left( firstDot );
        QString minor = version.right( version.length() - firstDot - 1 );
        minor.replace( ".", "" );
        project->variables()["QMAKE_LFLAGS"].append( "/VERSION:" + major + "." + minor );
    }
    if ( !project->variables()["RC_FILE"].isEmpty()) {
        if ( !project->variables()["RES_FILE"].isEmpty()) {
            fprintf(stderr, "Both .rc and .res file specified.\n");
            fprintf(stderr, "Please specify one of them, not both.");
            exit(666);
        }
        project->variables()["RES_FILE"] = project->variables()["RC_FILE"];
        project->variables()["RES_FILE"].first().replace(".rc",".res");
        project->variables()["POST_TARGETDEPS"] += project->variables()["RES_FILE"];
        project->variables()["CLEAN_FILES"] += project->variables()["RES_FILE"];
    }
    if ( !project->variables()["RES_FILE"].isEmpty())
        project->variables()["QMAKE_LIBS"] += project->variables()["RES_FILE"];

    // Base class init!
    MakefileGenerator::init();

    // Setup PCH variables
    precompH = project->first("PRECOMPILED_HEADER");
    usePCH = !precompH.isEmpty() && project->isActiveConfig("precompile_header");
    if (usePCH) {
        // Created files
        precompObj = var("OBJECTS_DIR") + project->first("TARGET") + "_pch" + Option::obj_ext;
        precompPch = var("OBJECTS_DIR") + project->first("TARGET") + "_pch.pch";
        // Add linking of precompObj (required for whole precompiled classes)
        project->variables()["OBJECTS"]		  += precompObj;
        // Add pch file to cleanup
        project->variables()["QMAKE_CLEAN"]	  += precompPch;
        // Return to variable pool
        project->variables()["PRECOMPILED_OBJECT"] = precompObj;
        project->variables()["PRECOMPILED_PCH"]    = precompPch;
    }

    if ( !project->variables()["VERSION"].isEmpty()) {
        QStringList l = QStringList::split('.', project->first("VERSION"));
        project->variables()["VER_MAJ"].append(l[0]);
        project->variables()["VER_MIN"].append(l[1]);
    }

    QString version = QStringList::split('.', project->first("VERSION")).join("");
    if(project->isActiveConfig("dll")) {
        project->variables()["QMAKE_CLEAN"].append(project->first("DESTDIR") + project->first("TARGET") + version + ".exp");
    }
    if(project->isActiveConfig("debug")) {
        project->variables()["QMAKE_CLEAN"].append(project->first("DESTDIR") + project->first("TARGET") + version + ".pdb");
        project->variables()["QMAKE_CLEAN"].append(project->first("DESTDIR") + project->first("TARGET") + version + ".ilk");
        project->variables()["QMAKE_CLEAN"].append("vc*.pdb");
        project->variables()["QMAKE_CLEAN"].append("vc*.idb");
    }

    QStringList &quc = project->variables()["QMAKE_EXTRA_WIN_COMPILERS"];
    for(it = quc.begin(); it != quc.end(); ++it) {
        QString tmp_out = project->variables()[(*it) + ".output"].first();
        if(tmp_out.isEmpty())
            continue;
        QStringList &tmp = project->variables()[(*it) + ".input"];
        for(QStringList::Iterator it2 = tmp.begin(); it2 != tmp.end(); ++it2) {
            QStringList &inputs = project->variables()[(*it2)];
            for(QStringList::Iterator input = inputs.begin(); input != inputs.end(); ++input) {
                QFileInfo fi(Option::fixPathToLocalOS((*input)));
                QString in = Option::fixPathToTargetOS((*input), FALSE),
                        out = tmp_out;
                out.replace("${QMAKE_FILE_BASE}", fi.baseName());
                out.replace("${QMAKE_FILE_NAME}", fi.filePath());
                if(project->variables()[(*it) + ".CONFIG"].findIndex("no_link") == -1)
                    project->variables()["OBJCOMP"] += out;
            }
        }
    }
}
Example #21
0
void
NmakeMakefileGenerator::writeNmakeParts(QTextStream &t)
{
    t << "####### Compiler, tools and options" << endl << endl;
    t << "CC		=	" << var("QMAKE_CC") << endl;
    t << "CXX		=	" << var("QMAKE_CXX") << endl;
    t << "LEX		= " << var("QMAKE_LEX") << endl;
    t << "YACC		= " << var("QMAKE_YACC") << endl;
    t << "CFLAGS	=	" << var("QMAKE_CFLAGS") << " "
      << varGlue("PRL_EXPORT_DEFINES","-D"," -D","") << " "
      <<  varGlue("DEFINES","-D"," -D","") << endl;
    t << "CXXFLAGS	=	" << var("QMAKE_CXXFLAGS") << " "
      << varGlue("PRL_EXPORT_DEFINES","-D"," -D","") << " "
      << varGlue("DEFINES","-D"," -D","") << endl;
    t << "LEXFLAGS	=" << var("QMAKE_LEXFLAGS") << endl;
    t << "YACCFLAGS	=" << var("QMAKE_YACCFLAGS") << endl;

    t << "INCPATH	=	";
    QStringList &incs = project->variables()["INCLUDEPATH"];
    for(QStringList::Iterator incit = incs.begin(); incit != incs.end(); ++incit) {
        QString inc = (*incit);
        if (inc.endsWith("\\"))
            inc.truncate(inc.length()-1);
        if (inc.startsWith("\"") && inc.endsWith("\""))
            inc = inc.mid(1, inc.length() - 2);
        t << " -I\"" << inc << "\"";
    }
    t << " -I\"" << specdir() << "\""
      << endl;
    if(!project->variables()["QMAKE_APP_OR_DLL"].isEmpty()) {
        t << "LINK	=	" << var("QMAKE_LINK") << endl;
        t << "LFLAGS	=	" << var("QMAKE_LFLAGS");
        if ( !project->variables()["QMAKE_LIBDIR"].isEmpty() )
            t << " " << varGlue("QMAKE_LIBDIR","/LIBPATH:\"","\" /LIBPATH:\"","\"");
        t << endl;
        t << "LIBS	=	";
        QStringList &libs = project->variables()["QMAKE_LIBS"];
        for(QStringList::Iterator libit = libs.begin(); libit != libs.end(); ++libit) {
            QString lib = (*libit);
            if (lib.endsWith("\\"))
                lib.truncate(lib.length()-1);
            t << " \"" << lib << "\"";
        }
        t << endl;
    }
    else {
        t << "LIB	=	" << var("QMAKE_LIB") << endl;
    }
    t << "MOC		=	" << (project->isEmpty("QMAKE_MOC") ? QString("moc") :
                              Option::fixPathToTargetOS(var("QMAKE_MOC"), FALSE)) << endl;
    t << "UIC		=	" << (project->isEmpty("QMAKE_UIC") ? QString("uic") :
                              Option::fixPathToTargetOS(var("QMAKE_UIC"), FALSE)) << endl;
    t << "QMAKE		=	" << (project->isEmpty("QMAKE_QMAKE") ? QString("qmake") :
                              Option::fixPathToTargetOS(var("QMAKE_QMAKE"), FALSE)) << endl;
    t << "IDC		=	" << (project->isEmpty("QMAKE_IDC") ? QString("idc") :
                              Option::fixPathToTargetOS(var("QMAKE_IDC"), FALSE)) << endl;
    t << "IDL		=	" << (project->isEmpty("QMAKE_IDL") ? QString("midl") :
                              Option::fixPathToTargetOS(var("QMAKE_IDL"), FALSE)) << endl;
    t << "ZIP		=	" << var("QMAKE_ZIP") << endl;
    t << "COPY_FILE	=       " << var("QMAKE_COPY") << endl;
    t << "COPY_DIR	=       " << var("QMAKE_COPY") << endl;
    t << "DEL_FILE	=       " << var("QMAKE_DEL_FILE") << endl;
    t << "DEL_DIR	=       " << var("QMAKE_DEL_DIR") << endl;
    t << "MOVE		=       " << var("QMAKE_MOVE") << endl;
    t << "CHK_DIR_EXISTS =	" << var("QMAKE_CHK_DIR_EXISTS") << endl;
    t << "MKDIR		=	" << var("QMAKE_MKDIR") << endl;
    t << "INSTALL_FILE= " << var("QMAKE_INSTALL_FILE") << endl;
    t << "INSTALL_DIR = " << var("QMAKE_INSTALL_DIR") << endl;
    t << endl;

    t << "####### Files" << endl << endl;
    t << "HEADERS =	" << varList("HEADERS") << endl;
    t << "SOURCES =	" << varList("SOURCES") << endl;
    t << "OBJECTS =	" << varList("OBJECTS") << endl;
    t << "FORMS =	" << varList("FORMS") << endl;
    t << "UICDECLS =	" << varList("UICDECLS") << endl;
    t << "UICIMPLS =	" << varList("UICIMPLS") << endl;
    t << "SRCMOC	=	" << varList("SRCMOC") << endl;
    t << "OBJMOC	=	" << varList("OBJMOC") << endl;

    QString extraCompilerDeps;
    if(!project->isEmpty("QMAKE_EXTRA_WIN_COMPILERS")) {
        t << "OBJCOMP = " << varList("OBJCOMP") << endl;
        extraCompilerDeps += " $(OBJCOMP) ";

        QStringList &comps = project->variables()["QMAKE_EXTRA_WIN_COMPILERS"];
        for(QStringList::Iterator compit = comps.begin(); compit != comps.end(); ++compit) {
            QStringList &vars = project->variables()[(*compit) + ".variables"];
            for(QStringList::Iterator varit = vars.begin(); varit != vars.end(); ++varit) {
                QStringList vals = project->variables()[(*varit)];
                if(!vals.isEmpty())
                    t << "QMAKE_COMP_" << (*varit) << " = " << valList(vals) << endl;
            }
        }
    }

    t << "DIST	=	" << varList("DISTFILES") << endl;
    t << "TARGET	=	";
    if( !project->variables()[ "DESTDIR" ].isEmpty() )
        t << varGlue("TARGET",project->first("DESTDIR"),"",project->first("TARGET_EXT"));
    else
        t << project->variables()[ "TARGET" ].first() << project->variables()[ "TARGET_EXT" ].first();
    t << endl;
    t << endl;

    t << "####### Implicit rules" << endl << endl;
    t << ".SUFFIXES: .c";
    QStringList::Iterator cppit;
    for(cppit = Option::cpp_ext.begin(); cppit != Option::cpp_ext.end(); ++cppit)
        t << " " << (*cppit);
    t << endl << endl;

    if(!project->isActiveConfig("no_batch")) {
        // Batchmode doesn't use the non implicit rules QMAKE_RUN_CXX & QMAKE_RUN_CC
        project->variables().remove("QMAKE_RUN_CXX");
        project->variables().remove("QMAKE_RUN_CC");

        QDict<void> source_directories;
        source_directories.insert(".", (void*)1);
        QString directories[] = { QString("MOC_DIR"), QString("UI_SOURCES_DIR"), QString("UI_DIR"), QString::null };
        for(int y = 0; !directories[y].isNull(); y++) {
            QString dirTemp = project->first(directories[y]);
            if (dirTemp.endsWith("\\"))
                dirTemp.truncate(dirTemp.length()-1);
            if(!dirTemp.isEmpty())
                source_directories.insert(dirTemp, (void*)1);
        }
        QString srcs[] = { QString("SOURCES"), QString("UICIMPLS"), QString("SRCMOC"), QString::null };
        for(int x = 0; !srcs[x].isNull(); x++) {
            QStringList &l = project->variables()[srcs[x]];
            for(QStringList::Iterator sit = l.begin(); sit != l.end(); ++sit) {
                QString sep = "\\";
                if((*sit).find(sep) == -1)
                    sep = "/";
                QString dir = (*sit).section(sep, 0, -2);
                if(!dir.isEmpty() && !source_directories[dir])
                    source_directories.insert(dir, (void*)1);
            }
        }

        for(QDictIterator<void> it(source_directories); it.current(); ++it) {
            if(it.currentKey().isEmpty())
                continue;
            for(cppit = Option::cpp_ext.begin(); cppit != Option::cpp_ext.end(); ++cppit)
                t << "{" << it.currentKey() << "}" << (*cppit) << "{" << var("OBJECTS_DIR") << "}" << Option::obj_ext << "::\n\t"
                  << var("QMAKE_RUN_CXX_IMP_BATCH").replace( QRegExp( "\\$@" ), var("OBJECTS_DIR") ) << endl << "\t$<" << endl << "<<" << endl << endl;
            t << "{" << it.currentKey() << "}" << ".c{" << var("OBJECTS_DIR") << "}" << Option::obj_ext << "::\n\t"
              << var("QMAKE_RUN_CC_IMP_BATCH").replace( QRegExp( "\\$@" ), var("OBJECTS_DIR") ) << endl << "\t$<" << endl << "<<" << endl << endl;
        }
    } else {
        for(cppit = Option::cpp_ext.begin(); cppit != Option::cpp_ext.end(); ++cppit)
            t << (*cppit) << Option::obj_ext << ":\n\t" << var("QMAKE_RUN_CXX_IMP") << endl << endl;
        t << ".c" << Option::obj_ext << ":\n\t" << var("QMAKE_RUN_CC_IMP") << endl << endl;
    }

    t << "####### Build rules" << endl << endl;
    t << "all: " << fileFixify(Option::output.name()) << " " << varGlue("ALL_DEPS"," "," "," ") << "$(TARGET)" << endl << endl;
    t << "$(TARGET): " << var("PRE_TARGETDEPS") << " $(UICDECLS) $(OBJECTS) $(OBJMOC) "
      << extraCompilerDeps << var("POST_TARGETDEPS");
    if(!project->variables()["QMAKE_APP_OR_DLL"].isEmpty()) {
        t << "\n\t" << "$(LINK) $(LFLAGS) /OUT:$(TARGET) @<< " << "\n\t  "
          << "$(OBJECTS) $(OBJMOC) $(LIBS)";
    } else {
        t << "\n\t" << "$(LIB) /OUT:$(TARGET) @<<" << "\n\t  "
          << "$(OBJECTS) $(OBJMOC)";
    }
    t << extraCompilerDeps;
    t << endl << "<<" << endl;
    if ( !project->variables()["QMAKE_POST_LINK"].isEmpty() )
        t << "\t" << var( "QMAKE_POST_LINK" ) << endl;
    if(project->isActiveConfig("dll") && !project->variables()["DLLDESTDIR"].isEmpty()) {
        QStringList dlldirs = project->variables()["DLLDESTDIR"];
        for ( QStringList::Iterator dlldir = dlldirs.begin(); dlldir != dlldirs.end(); ++dlldir ) {
            t << "\n\t" << "-$(COPY_FILE) \"$(TARGET)\" " << *dlldir;
        }
    }
    QString targetfilename = project->variables()["TARGET"].first();
    if(project->isActiveConfig("activeqt")) {
        QString version = project->variables()["VERSION"].first();
        if ( version.isEmpty() )
            version = "1.0";

        if ( project->isActiveConfig("dll")) {
            t << "\n\t" << ("-$(IDC) $(TARGET) /idl " + var("OBJECTS_DIR") + targetfilename + ".idl -version " + version);
            t << "\n\t" << ("-$(IDL) /nologo " + var("OBJECTS_DIR") + targetfilename + ".idl /tlb " + var("OBJECTS_DIR") + targetfilename + ".tlb");
            t << "\n\t" << ("-$(IDC) $(TARGET) /tlb " + var("OBJECTS_DIR") + targetfilename + ".tlb");
            t << "\n\t" << ("-$(IDC) $(TARGET) /regserver" );
        } else {
            t << "\n\t" << ("-$(TARGET) -dumpidl " + var("OBJECTS_DIR") + targetfilename + ".idl -version " + version);
            t << "\n\t" << ("-$(IDL) /nologo " + var("OBJECTS_DIR") + targetfilename + ".idl /tlb " + var("OBJECTS_DIR") + targetfilename + ".tlb");
            t << "\n\t" << ("-$(IDC) $(TARGET) /tlb " + var("OBJECTS_DIR") + targetfilename + ".tlb");
            t << "\n\t" << "-$(TARGET) -regserver";
        }
    }
    t << endl << endl;

    if(!project->variables()["RC_FILE"].isEmpty()) {
        t << var("RES_FILE") << ": " << var("RC_FILE") << "\n\t"
          << var("QMAKE_RC") << " " << var("RC_FILE") << endl << endl;
    }

    t << "mocables: $(SRCMOC)" << endl
      << "uicables: $(UICIMPLS) $(UICDECLS)" << endl << endl;

    writeMakeQmake(t);

    QStringList dist_files = Option::mkfile::project_files;
    if(!project->isEmpty("QMAKE_INTERNAL_INCLUDED_FILES"))
        dist_files += project->variables()["QMAKE_INTERNAL_INCLUDED_FILES"];
    if(!project->isEmpty("TRANSLATIONS"))
        dist_files << var("TRANSLATIONS");
    if(!project->isEmpty("FORMS")) {
        QStringList &forms = project->variables()["FORMS"];
        for(QStringList::Iterator formit = forms.begin(); formit != forms.end(); ++formit) {
            QString ui_h = fileFixify((*formit) + Option::h_ext.first());
            if(QFile::exists(ui_h) )
                dist_files << ui_h;
        }
    }
    t << "dist:" << "\n\t"
      << "$(ZIP) " << var("QMAKE_ORIG_TARGET") << ".zip " << "$(SOURCES) $(HEADERS) $(DIST) $(FORMS) "
      << dist_files.join(" ") << " " << var("TRANSLATIONS") << " " << var("IMAGES") << endl << endl;

    t << "uiclean:"
      << varGlue("UICDECLS" ,"\n\t-$(DEL_FILE) ","\n\t-$(DEL_FILE) ","")
      << varGlue("UICIMPLS" ,"\n\t-$(DEL_FILE) ","\n\t-$(DEL_FILE) ","") << endl;

    t << "mocclean:"
      << varGlue("SRCMOC" ,"\n\t-$(DEL_FILE) ","\n\t-$(DEL_FILE) ","")
      << varGlue("OBJMOC" ,"\n\t-$(DEL_FILE) ","\n\t-$(DEL_FILE) ","") << endl;

    t << "clean: uiclean mocclean"
      << varGlue("OBJECTS","\n\t-$(DEL_FILE) ","\n\t-$(DEL_FILE) ","")
      << varGlue("QMAKE_CLEAN","\n\t-$(DEL_FILE) ","\n\t-$(DEL_FILE) ","\n")
      << varGlue("CLEAN_FILES","\n\t-$(DEL_FILE) ","\n\t-$(DEL_FILE) ","\n");
    if ( project->isActiveConfig("activeqt")) {
        t << ("\n\t-$(DEL_FILE) " + var("OBJECTS_DIR") + targetfilename + ".idl");
        t << ("\n\t-$(DEL_FILE) " + var("OBJECTS_DIR") + targetfilename + ".tlb");
    }
    if(!project->isEmpty("IMAGES"))
        t << varGlue("QMAKE_IMAGE_COLLECTION", "\n\t-$(DEL_FILE) ", "\n\t-$(DEL_FILE) ", "");
    t << endl;

    // user defined targets

    QStringList::Iterator it;
    QStringList &qut = project->variables()["QMAKE_EXTRA_WIN_TARGETS"];
    for(it = qut.begin(); it != qut.end(); ++it) {
        QString targ = var((*it) + ".target"),
                cmd = var((*it) + ".commands"), deps;
        if(targ.isEmpty())
            targ = (*it);
        QStringList &deplist = project->variables()[(*it) + ".depends"];
        for(QStringList::Iterator dep_it = deplist.begin(); dep_it != deplist.end(); ++dep_it) {
            QString dep = var((*dep_it) + ".target");
            if(dep.isEmpty())
                dep = (*dep_it);
            deps += " " + dep;
        }
        if(!project->variables()["QMAKE_NOFORCE"].isEmpty() &&
                project->variables()[(*it) + ".CONFIG"].findIndex("phony") != -1)
            deps += QString(" ") + "FORCE";
        t << "\n\n" << targ << ":" << deps << "\n\t"
          << cmd;
    }
    t << endl << endl;

    QStringList &quc = project->variables()["QMAKE_EXTRA_WIN_COMPILERS"];
    for(it = quc.begin(); it != quc.end(); ++it) {
        QString tmp_out = project->variables()[(*it) + ".output"].first();
        QString tmp_cmd = project->variables()[(*it) + ".commands"].join(" ");
        QString tmp_dep = project->variables()[(*it) + ".depends"].join(" ");
        QStringList &vars = project->variables()[(*it) + ".variables"];
        if(tmp_out.isEmpty() || tmp_cmd.isEmpty())
            continue;
        QStringList &tmp = project->variables()[(*it) + ".input"];
        for(QStringList::Iterator it2 = tmp.begin(); it2 != tmp.end(); ++it2) {
            QStringList &inputs = project->variables()[(*it2)];
            for(QStringList::Iterator input = inputs.begin(); input != inputs.end(); ++input) {
                QFileInfo fi(Option::fixPathToLocalOS((*input)));
                QString in = Option::fixPathToTargetOS((*input), FALSE),
                        out = tmp_out, cmd = tmp_cmd, deps;
                out.replace("${QMAKE_FILE_BASE}", fi.baseName());
                out.replace("${QMAKE_FILE_NAME}", fi.filePath());
                cmd.replace("${QMAKE_FILE_BASE}", fi.baseName());
                cmd.replace("${QMAKE_FILE_OUT}", out);
                cmd.replace("${QMAKE_FILE_NAME}", fi.filePath());
                for(QStringList::Iterator it3 = vars.begin(); it3 != vars.end(); ++it3)
                    cmd.replace("$(" + (*it3) + ")", "$(QMAKE_COMP_" + (*it3)+")");
                if(!tmp_dep.isEmpty()) {
                    char buff[256];
                    QString dep_cmd = tmp_dep;
                    dep_cmd.replace("${QMAKE_FILE_NAME}", fi.filePath());
                    if(FILE *proc = QT_POPEN(dep_cmd.latin1(), "r")) {
                        while(!feof(proc)) {
                            int read_in = int(fread(buff, 1, 255, proc));
                            if(!read_in)
                                break;
                            int l = 0;
                            for(int i = 0; i < read_in; i++) {
                                if(buff[i] == '\n' || buff[i] == ' ') {
                                    deps += " " + QCString(buff+l, (i - l) + 1);
                                    l = i;
                                }
                            }
                        }
                        fclose(proc);
                    }
                }
                t << out << ": " << in << deps << "\n\t"
                  << cmd << endl << endl;
            }
        }
    }
    t << endl;

    if(project->variables()["QMAKE_NOFORCE"].isEmpty())
        t << "FORCE:" << endl << endl;

    t << "distclean: clean"
      << "\n\t-$(DEL_FILE) $(TARGET)"
      << endl << endl;

    // precompiled header
    if(usePCH) {
        QString precompRule = QString("-c -Yc -Fp%1 -Fo%2").arg(precompPch).arg(precompObj);
        t << precompObj << ": " << precompH << " " << findDependencies(precompH).join(" \\\n\t\t")
          << "\n\t" << ("$(CXX) " + precompRule + " $(CXXFLAGS) $(INCPATH) -TP ") << precompH << endl << endl;
    }
}
//4 columns: name, type, value, comment
//name:type=value - comment
CMakeCacheModel::CMakeCacheModel(QObject *parent, const KUrl &path)
    : QStandardItemModel(parent), m_filePath(path), m_changed(false)
{
    QStringList labels;
    labels.append(i18n("Name"));
    labels.append(i18n("Type"));
    labels.append(i18n("Value"));
    labels.append(i18n("Comment"));
    labels.append(i18n("Advanced"));
    setHorizontalHeaderLabels(labels);
    
    QFile file(path.toLocalFile());
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        kDebug(9032) << "error. Could not find the file";
        return;
    }

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

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

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

    minerProcess->reset();

    output = minerProcess->readAll();

    QString outputString(output);

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

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

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

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

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

                threadSpeed[threadID] = speed;

                updateSpeed();
            }
        }
    }
}
Example #24
0
void NetSearch::showMenu(void)
{
    QMutexLocker locker(&m_lock);

    QString label = tr("Search Options");

    MythDialogBox *menuPopup = new MythDialogBox(label, m_popupStack,
                                                    "mythnetvisionmenupopup");

    if (menuPopup->Create())
    {
        m_popupStack->AddScreen(menuPopup);

        menuPopup->SetReturnEvent(this, "options");

        if (m_searchResultList->GetCount() > 0)
        {
            ResultItem *item =
                  qVariantValue<ResultItem *>(m_searchResultList->GetDataValue());

            QString filename;
            bool exists = false;

            if (item)
            {
                menuPopup->AddButton(tr("Open Web Link"), SLOT(showWebVideo()));

                filename = getDownloadFilename(item);

                if (filename.startsWith("myth://"))
                    exists = RemoteFile::Exists(filename);
                else
                    exists = QFile::exists(filename);
            }

            if (item && item->GetDownloadable() &&
                GetFocusWidget() == m_searchResultList)
            {
                if (exists)
                    menuPopup->AddButton(tr("Play"), SLOT(doPlayVideo()));
                else
                    menuPopup->AddButton(tr("Save This Video"), SLOT(doDownloadAndPlay()));
            }

            if (item && item->GetDownloadable() &&
                GetFocusWidget() == m_searchResultList &&
                exists)
            {
                menuPopup->AddButton(tr("Delete"), SLOT(slotDeleteVideo()));
            }


            if (m_pagenum > 1)
                menuPopup->AddButton(tr("Previous Page"), SLOT(getLastResults()));
            if (m_searchResultList->GetCount() > 0 && m_pagenum < m_maxpage)
                menuPopup->AddButton(tr("Next Page"), SLOT(getMoreResults()));
        }
        menuPopup->AddButton(tr("Manage Search Scripts"), SLOT(runSearchEditor()));

    }
    else
    {
        delete menuPopup;
    }
}
Example #25
0
bool RCCResourceLibrary::interpretResourceFile(QIODevice *inputDevice,
    const QString &fname, QString currentPath, bool ignoreErrors)
{
    Q_ASSERT(m_errorDevice);
    const QChar slash = QLatin1Char('/');
    if (!currentPath.isEmpty() && !currentPath.endsWith(slash))
        currentPath += slash;

    QDomDocument document;
    {
        QString errorMsg;
        int errorLine = 0;
        int errorColumn = 0;
        if (!document.setContent(inputDevice, &errorMsg, &errorLine, &errorColumn)) {
            if (ignoreErrors)
                return true;
            const QString msg = QString::fromUtf8("RCC Parse Error: '%1' Line: %2 Column: %3 [%4]\n").arg(fname).arg(errorLine).arg(errorColumn).arg(errorMsg);
            m_errorDevice->write(msg.toUtf8());
            return false;
        }
    }

    QDomElement domRoot = document.firstChildElement(m_strings.TAG_RCC).toElement();
    if (!domRoot.isNull() && domRoot.tagName() == m_strings.TAG_RCC) {
        for (QDomNode node = domRoot.firstChild(); !node.isNull(); node = node.nextSibling()) {
            if (!node.isElement())
                continue;

            QDomElement child = node.toElement();
            if (!child.isNull() && child.tagName() == m_strings.TAG_RESOURCE) {
                QLocale::Language language = QLocale::c().language();
                QLocale::Country country = QLocale::c().country();

                if (child.hasAttribute(m_strings.ATTRIBUTE_LANG)) {
                    QString attribute = child.attribute(m_strings.ATTRIBUTE_LANG);
                    QLocale lang = QLocale(attribute);
                    language = lang.language();
                    if (2 == attribute.length()) {
                        // Language only
                        country = QLocale::AnyCountry;
                    } else {
                        country = lang.country();
                    }
                }

                QString prefix;
                if (child.hasAttribute(m_strings.ATTRIBUTE_PREFIX))
                    prefix = child.attribute(m_strings.ATTRIBUTE_PREFIX);
                if (!prefix.startsWith(slash))
                    prefix.prepend(slash);
                if (!prefix.endsWith(slash))
                    prefix += slash;

                for (QDomNode res = child.firstChild(); !res.isNull(); res = res.nextSibling()) {
                    if (res.isElement() && res.toElement().tagName() == m_strings.TAG_FILE) {

                        QString fileName(res.firstChild().toText().data());
                        if (fileName.isEmpty()) {
                            const QString msg = QString::fromUtf8("RCC: Warning: Null node in XML of '%1'\n").arg(fname);
                            m_errorDevice->write(msg.toUtf8());
                        }
                        QString alias;
                        if (res.toElement().hasAttribute(m_strings.ATTRIBUTE_ALIAS))
                            alias = res.toElement().attribute(m_strings.ATTRIBUTE_ALIAS);
                        else
                            alias = fileName;

                        int compressLevel = m_compressLevel;
                        if (res.toElement().hasAttribute(m_strings.ATTRIBUTE_COMPRESS))
                            compressLevel = res.toElement().attribute(m_strings.ATTRIBUTE_COMPRESS).toInt();
                        int compressThreshold = m_compressThreshold;
                        if (res.toElement().hasAttribute(m_strings.ATTRIBUTE_THRESHOLD))
                            compressThreshold = res.toElement().attribute(m_strings.ATTRIBUTE_THRESHOLD).toInt();

                        // Special case for -no-compress. Overrides all other settings.
                        if (m_compressLevel == -2)
                            compressLevel = 0;

                        alias = QDir::cleanPath(alias);
                        while (alias.startsWith(QLatin1String("../")))
                            alias.remove(0, 3);
                        alias = QDir::cleanPath(m_resourceRoot) + prefix + alias;

                        QString absFileName = fileName;
                        if (QDir::isRelativePath(absFileName))
                            absFileName.prepend(currentPath);
                        QFileInfo file(absFileName);
                        if (!file.exists()) {
                            m_failedResources.push_back(absFileName);
                            const QString msg = QString::fromUtf8("RCC: Error in '%1': Cannot find file '%2'\n").arg(fname).arg(fileName);
                            m_errorDevice->write(msg.toUtf8());
                            if (ignoreErrors)
                                continue;
                            else
                                return false;
                        } else if (file.isFile()) {
                            const bool arc =
                                addFile(alias,
                                        RCCFileInfo(alias.section(slash, -1),
                                                    file,
                                                    language,
                                                    country,
                                                    RCCFileInfo::NoFlags,
                                                    compressLevel,
                                                    compressThreshold)
                                        );
                            if (!arc)
                                m_failedResources.push_back(absFileName);
                        } else {
                            QDir dir;
                            if (file.isDir()) {
                                dir.setPath(file.filePath());
                            } else {
                                dir.setPath(file.path());
                                dir.setNameFilters(QStringList(file.fileName()));
                                if (alias.endsWith(file.fileName()))
                                    alias = alias.left(alias.length()-file.fileName().length());
                            }
                            if (!alias.endsWith(slash))
                                alias += slash;
                            QDirIterator it(dir, QDirIterator::FollowSymlinks|QDirIterator::Subdirectories);
                            while (it.hasNext()) {
                                it.next();
                                QFileInfo child(it.fileInfo());
                                if (child.fileName() != QLatin1String(".") && child.fileName() != QLatin1String("..")) {
                                    const bool arc =
                                        addFile(alias + child.fileName(),
                                                RCCFileInfo(child.fileName(),
                                                            child,
                                                            language,
                                                            country,
                                                            RCCFileInfo::NoFlags,
                                                            compressLevel,
                                                            compressThreshold)
                                                );
                                    if (!arc)
                                        m_failedResources.push_back(child.fileName());
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    if (m_root == 0) {
        const QString msg = QString::fromUtf8("RCC: Warning: No resources in '%1'.\n").arg(fname);
        m_errorDevice->write(msg.toUtf8());
        if (!ignoreErrors && m_format == Binary) {
            // create dummy entry, otherwise loading qith QResource will crash
            m_root = new RCCFileInfo(QString(), QFileInfo(),
                    QLocale::C, QLocale::AnyCountry, RCCFileInfo::Directory);
        }
    }

    return true;
}
Example #26
0
bool QPEvents::handleEvent(const EventAction& ev)
{
  if (ev.type == EventAction::Internal)
  {
    if (ev.action == "email")
    {
       QString receiver = ev.arguments[0];
       TeamMember member;
       if (receiver == "teamleader")
         member = Project::ref()->teamLeader();
       else if (receiver.startsWith("subprojectleader-"))
       {
         QString s = receiver.remove("subprojectleader-");
         member = Project::ref()->subprojectLeader(s);
         SubProject subProject;
         QValueList<SubProject> *subprojects = Project::ref()->subprojects();
         for (uint i = 0 ; i < subprojects->count(); i++)
         {
           if ((*subprojects)[i].name == s)
           {
              subProject = (*subprojects)[i];
              break;
           }
         }
         if (!subProject.location.isEmpty() && !ev.arguments[2].startsWith(subProject.location))
         {
            kdDebug(24000) << ev.arguments[2] << " is not part of the " << subProject.name << "subproject \"" << subProject.location << "\". " << endl;
            return true;
         }
       }
       else if (receiver.startsWith("taskleader-"))
         member = Project::ref()->taskLeader(receiver.remove("taskleader-"));

       QString body;
       for (uint i = 2; i < ev.arguments.count(); i++)
          body += ev.arguments[i] + "\n";
       kapp->invokeMailer(member.name + "<" + member.email + ">", "", "", ev.arguments[1], body, "", QStringList(), "");

       return true;
    }
    if (ev.action == "log")
    {
      QString logFile = ev.arguments[0];
      KURL url = KURL::fromPathOrURL(logFile);
      if (url.isValid() && !url.isLocalFile())
      {
        KMessageBox::sorry(0L, i18n("Logging to remote files is not supported."));
        return false;
      }
      if (!logFile.startsWith("/"))
      {
        url = Project::ref()->projectBaseURL();
        url.addPath(logFile);
        if (!url.isLocalFile())
        {
          KMessageBox::sorry(0L, i18n("Logging to files inside a remote project is not supported."));
          return false;
        }
      }
      QFile file(url.path());
      bool result;
      if (ev.arguments[2] == "create_new")
        result = file.open(IO_WriteOnly);
      else
        result = file.open(IO_WriteOnly | IO_Append);
      if (result)
      {
        QTextStream stream(&file);
        stream.setEncoding(QTextStream::UnicodeUTF8);
        //Note: the log text should not be translated.
        QString s = QDateTime::currentDateTime().toString(Qt::ISODate) + ": ";
        s.append( "Event : " + m_eventName + " : ");
        s.append( "Action: " + ev.action + " : ");
        if (ev.arguments[1] == "full")
        {
          s.append( "Arguments: ");
          for (uint i = 1; i < ev.arguments.count(); i++)
            s.append(ev.arguments[i] + " | ");
        }
        s[s.length() - 1] = '\n';
        stream << s;
        file.close();
      }
      if (!result)
      {
        KMessageBox::sorry(0L, i18n("<qt>Logging failed. Check that you have write access to <i>%1</i>.").arg(url.path()));
        return false;
      }
    } else
      KMessageBox::sorry(0L, i18n("<qt>Unsupported internal event action : <b>%1</b>.</qt>").arg(ev.action));
  } else
  if (ev.type == EventAction::External)
  {
      //KMessageBox::sorry(0L, i18n("External event actions are not yet supported."));
      if (ev.action == "script" || ev.action =="action")
      {
          QString name = ev.arguments[0];
          KAction *action = quantaApp->actionCollection()->action(name);
          TagAction *tagAction = dynamic_cast<TagAction*>(action);
          if (tagAction)
          {
            bool blocking = (ev.arguments[1] == "yes");
            EventAction event = ev;
            event.arguments.remove(event.arguments.at(1));
            tagAction->addArguments(event.arguments);
            tagAction->execute(blocking);
          }
          else
          if (action)
          {
            action->activate();
          } else
            KMessageBox::sorry(0L, i18n("<qt>The <b>%1</b> script action was not found on your system.</qt>").arg(name), i18n("Action Execution Error"));
      }  else
      KMessageBox::sorry(0L, i18n("Unsupported external event action."));
  } else
      KMessageBox::sorry(0L, i18n("Unknown event type."));
  return false;
}
Example #27
0
QString UBSettings::userRelativeWidgetPath()
{
    QString result = userWidgetPath().replace(userInteractiveDirectory(), "");
    return result.startsWith("/") ? result.right(result.count() - 1) : result;
}
Example #28
0
bool QgsMapLayer::readXML( const QDomNode& layer_node )
{
  QgsCoordinateReferenceSystem savedCRS;
  CUSTOM_CRS_VALIDATION savedValidation;
  bool layerError;

  QDomElement element = layer_node.toElement();

  QDomNode mnl;
  QDomElement mne;

  // read provider
  QString provider;
  mnl = layer_node.namedItem( "provider" );
  mne = mnl.toElement();
  provider = mne.text();

  // set data source
  mnl = layer_node.namedItem( "datasource" );
  mne = mnl.toElement();
  mDataSource = mne.text();

  // TODO: this should go to providers
  if ( provider == "spatialite" )
  {
    QgsDataSourceURI uri( mDataSource );
    uri.setDatabase( QgsProject::instance()->readPath( uri.database() ) );
    mDataSource = uri.uri();
  }
  else if ( provider == "ogr" )
  {
    QStringList theURIParts = mDataSource.split( "|" );
    theURIParts[0] = QgsProject::instance()->readPath( theURIParts[0] );
    mDataSource = theURIParts.join( "|" );
  }
  else if ( provider == "delimitedtext" )
  {
    QUrl urlSource = QUrl::fromEncoded( mDataSource.toAscii() );

    if ( !mDataSource.startsWith( "file:" ) )
    {
      QUrl file = QUrl::fromLocalFile( mDataSource.left( mDataSource.indexOf( "?" ) ) );
      urlSource.setScheme( "file" );
      urlSource.setPath( file.path() );
    }

    QUrl urlDest = QUrl::fromLocalFile( QgsProject::instance()->readPath( urlSource.toLocalFile() ) );
    urlDest.setQueryItems( urlSource.queryItems() );
    mDataSource = QString::fromAscii( urlDest.toEncoded() );
  }
  else if ( provider == "wms" )
  {
    // >>> BACKWARD COMPATIBILITY < 1.9
    // For project file backward compatibility we must support old format:
    // 1. mode: <url>
    //    example: http://example.org/wms?
    // 2. mode: tiled=<width>;<height>;<resolution>;<resolution>...,ignoreUrl=GetMap;GetFeatureInfo,featureCount=<count>,username=<name>,password=<password>,url=<url>
    //    example: tiled=256;256;0.703;0.351,url=http://example.org/tilecache?
    //    example: featureCount=10,http://example.org/wms?
    //    example: ignoreUrl=GetMap;GetFeatureInfo,username=cimrman,password=jara,url=http://example.org/wms?
    // This is modified version of old QgsWmsProvider::parseUri
    // The new format has always params crs,format,layers,styles and that params
    // should not appear in old format url -> use them to identify version
    if ( !mDataSource.contains( "crs=" ) && !mDataSource.contains( "format=" ) )
    {
      QgsDebugMsg( "Old WMS URI format detected -> converting to new format" );
      QgsDataSourceURI uri;
      if ( !mDataSource.startsWith( "http:" ) )
      {
        QStringList parts = mDataSource.split( "," );
        QStringListIterator iter( parts );
        while ( iter.hasNext() )
        {
          QString item = iter.next();
          if ( item.startsWith( "username="******"username", item.mid( 9 ) );
          }
          else if ( item.startsWith( "password="******"password", item.mid( 9 ) );
          }
          else if ( item.startsWith( "tiled=" ) )
          {
            // in < 1.9 tiled= may apper in to variants:
            // tiled=width;height - non tiled mode, specifies max width and max height
            // tiled=width;height;resolutions-1;resolution2;... - tile mode

            QStringList params = item.mid( 6 ).split( ";" );

            if ( params.size() == 2 ) // non tiled mode
            {
              uri.setParam( "maxWidth", params.takeFirst() );
              uri.setParam( "maxHeight", params.takeFirst() );
            }
            else if ( params.size() > 2 ) // tiled mode
            {
              // resolutions are no more needed and size limit is not used for tiles
              // we have to tell to the provider however that it is tiled
              uri.setParam( "tileMatrixSet", "" );
            }
          }
          else if ( item.startsWith( "featureCount=" ) )
          {
            uri.setParam( "featureCount", item.mid( 13 ) );
          }
          else if ( item.startsWith( "url=" ) )
          {
            uri.setParam( "url", item.mid( 4 ) );
          }
          else if ( item.startsWith( "ignoreUrl=" ) )
          {
            uri.setParam( "ignoreUrl", item.mid( 10 ).split( ";" ) );
          }
        }
      }
      else
      {
        uri.setParam( "url", mDataSource );
      }
      mDataSource = uri.encodedUri();
      // At this point, the URI is obviously incomplete, we add additional params
      // in QgsRasterLayer::readXml
    }
    // <<< BACKWARD COMPATIBILITY < 1.9
  }
  else
  {
    mDataSource = QgsProject::instance()->readPath( mDataSource );
  }

  // Set the CRS from project file, asking the user if necessary.
  // Make it the saved CRS to have WMS layer projected correctly.
  // We will still overwrite whatever GDAL etc picks up anyway
  // further down this function.
  mnl = layer_node.namedItem( "layername" );
  mne = mnl.toElement();

  QDomNode srsNode = layer_node.namedItem( "srs" );
  mCRS->readXML( srsNode );
  mCRS->setValidationHint( tr( "Specify CRS for layer %1" ).arg( mne.text() ) );
  mCRS->validate();
  savedCRS = *mCRS;

  // Do not validate any projections in children, they will be overwritten anyway.
  // No need to ask the user for a projections when it is overwritten, is there?
  savedValidation = QgsCoordinateReferenceSystem::customSrsValidation();
  QgsCoordinateReferenceSystem::setCustomSrsValidation( NULL );

  // now let the children grab what they need from the Dom node.
  layerError = !readXml( layer_node );

  // overwrite CRS with what we read from project file before the raster/vector
  // file readnig functions changed it. They will if projections is specfied in the file.
  // FIXME: is this necessary?
  QgsCoordinateReferenceSystem::setCustomSrsValidation( savedValidation );
  *mCRS = savedCRS;

  // Abort if any error in layer, such as not found.
  if ( layerError )
  {
    return false;
  }

  // the internal name is just the data source basename
  //QFileInfo dataSourceFileInfo( mDataSource );
  //internalName = dataSourceFileInfo.baseName();

  // set ID
  mnl = layer_node.namedItem( "id" );
  if ( ! mnl.isNull() )
  {
    mne = mnl.toElement();
    if ( ! mne.isNull() && mne.text().length() > 10 ) // should be at least 17 (yyyyMMddhhmmsszzz)
    {
      mID = mne.text();
    }
  }

  // use scale dependent visibility flag
  toggleScaleBasedVisibility( element.attribute( "hasScaleBasedVisibilityFlag" ).toInt() == 1 );
  setMinimumScale( element.attribute( "minimumScale" ).toFloat() );
  setMaximumScale( element.attribute( "maximumScale" ).toFloat() );

  // set name
  mnl = layer_node.namedItem( "layername" );
  mne = mnl.toElement();
  setLayerName( mne.text() );

  //title
  QDomElement titleElem = layer_node.firstChildElement( "title" );
  if ( !titleElem.isNull() )
  {
    mTitle = titleElem.text();
  }

  //abstract
  QDomElement abstractElem = layer_node.firstChildElement( "abstract" );
  if ( !abstractElem.isNull() )
  {
    mAbstract = abstractElem.text();
  }

  //read transparency level
  QDomNode transparencyNode = layer_node.namedItem( "transparencyLevelInt" );
  if ( ! transparencyNode.isNull() )
  {
    // set transparency level only if it's in project
    // (otherwise it sets the layer transparent)
    QDomElement myElement = transparencyNode.toElement();
    setTransparency( myElement.text().toInt() );
  }

  readCustomProperties( layer_node );

  return true;
} // void QgsMapLayer::readXML
Example #29
0
QWidget *PartWidgetFactory::create(const QModelIndex &partIndex, int recursionDepth, const PartLoadingMode loadingMode)
{
    using namespace Imap::Mailbox;
    Q_ASSERT(partIndex.isValid());

    if (recursionDepth > 1000) {
        return new QLabel(tr("This message contains too deep nesting of MIME message parts.\n"
                             "To prevent stack exhaustion and your head from exploding, only\n"
                             "the top-most thousand items or so are shown."), 0);
    }

    bool userPrefersPlaintext = QSettings().value(Common::SettingsNames::guiPreferPlaintextRendering, QVariant(true)).toBool();

    QString mimeType = partIndex.data(Imap::Mailbox::RolePartMimeType).toString();
    if (mimeType.startsWith(QLatin1String("multipart/"))) {
        // it's a compound part
        if (mimeType == QLatin1String("multipart/alternative")) {
            return new MultipartAlternativeWidget(0, this, partIndex, recursionDepth,
                                                  userPrefersPlaintext ?
                                                      QLatin1String("text/plain") :
                                                      QLatin1String("text/html"));
        } else if (mimeType == QLatin1String("multipart/signed")) {
            return new MultipartSignedWidget(0, this, partIndex, recursionDepth);
        } else if (mimeType == QLatin1String("multipart/related")) {
            // The purpose of this section is to find a text/html e-mail, along with its associated body parts, and hide
            // everything else than the HTML widget.

            // At this point, it might be interesting to somehow respect the user's preference about using text/plain
            // instead of text/html. However, things are a bit complicated; the widget used at this point really wants
            // to either show just a single part or alternatively all of them in a sequence.
            // Furthermore, if someone sends a text/plain and a text/html together inside a multipart/related, they're
            // just wrong.

            // Let's see if we know what the root part is
            QModelIndex mainPartIndex;
            QVariant mainPartCID = partIndex.data(RolePartMultipartRelatedMainCid);
            if (mainPartCID.isValid()) {
                const Imap::Mailbox::Model *constModel = 0;
                Imap::Mailbox::TreeItemPart *part = dynamic_cast<Imap::Mailbox::TreeItemPart *>(Imap::Mailbox::Model::realTreeItem(partIndex, &constModel));
                Imap::Mailbox::Model *model = const_cast<Imap::Mailbox::Model *>(constModel);
                Imap::Mailbox::TreeItemPart *mainPartPtr = Imap::Network::MsgPartNetAccessManager::cidToPart(mainPartCID.toByteArray(), model, part);
                if (mainPartPtr) {
                    mainPartIndex = mainPartPtr->toIndex(model);
                }
            }

            if (!mainPartIndex.isValid()) {
                // The Content-Type-based start parameter was not terribly useful. Let's find the HTML part manually.
                QModelIndex candidate = partIndex.child(0, 0);
                while (candidate.isValid()) {
                    if (candidate.data(RolePartMimeType).toString() == QLatin1String("text/html")) {
                        mainPartIndex = candidate;
                        break;
                    }
                    candidate = candidate.sibling(candidate.row() + 1, 0);
                }
            }

            if (mainPartIndex.isValid()) {
                if (mainPartIndex.data(RolePartMimeType).toString() == QLatin1String("text/html")) {
                    return PartWidgetFactory::create(mainPartIndex, recursionDepth+1);
                } else {
                    // Sorry, but anything else than text/html is by definition suspicious here. Better than picking some random
                    // choice, let's just show everything.
                    return new GenericMultipartWidget(0, this, partIndex, recursionDepth);
                }
            } else {
                // The RFC2387's wording is clear that in absence of an explicit START argument, the first part is the starting one.
                // On the other hand, I've seen real-world messages whose first part is some utter garbage (an image sent as
                // application/octet-stream, for example) and some *other* part is an HTML text. In that case (and if we somehow
                // failed to pick the HTML part by a heuristic), it's better to show everything.
                return new GenericMultipartWidget(0, this, partIndex, recursionDepth);
            }
        } else {
            return new GenericMultipartWidget(0, this, partIndex, recursionDepth);
        }
    } else if (mimeType == QLatin1String("message/rfc822")) {
        return new Message822Widget(0, this, partIndex, recursionDepth);
    } else {
        QStringList allowedMimeTypes;
        allowedMimeTypes << "text/html" << "text/plain" << "image/jpeg" <<
                         "image/jpg" << "image/pjpeg" << "image/png" << "image/gif";
        // The problem is that some nasty MUAs (hint hint Thunderbird) would
        // happily attach a .tar.gz and call it "inline"
        bool showInline = partIndex.data(Imap::Mailbox::RolePartBodyDisposition).toByteArray().toLower() != "attachment" &&
                          allowedMimeTypes.contains(mimeType);

        if (showInline) {
            const Imap::Mailbox::Model *constModel = 0;
            Imap::Mailbox::TreeItemPart *part = dynamic_cast<Imap::Mailbox::TreeItemPart *>(Imap::Mailbox::Model::realTreeItem(partIndex, &constModel));
            Imap::Mailbox::Model *model = const_cast<Imap::Mailbox::Model *>(constModel);
            Q_ASSERT(model);
            Q_ASSERT(part);
            part->fetchFromCache(model);

            bool showDirectly = loadingMode == LOAD_IMMEDIATELY;
            if (!part->fetched())
                showDirectly &= model->isNetworkOnline() || part->octets() <= ExpensiveFetchThreshold;

            QWidget *widget = 0;
            if (showDirectly) {
                widget = new SimplePartWidget(0, manager, partIndex, m_messageView);
            } else if (model->isNetworkAvailable() || part->fetched()) {
                widget = new LoadablePartWidget(0, manager, partIndex, m_messageView,
                                                loadingMode == LOAD_ON_SHOW && part->octets() <= ExpensiveFetchThreshold ?
                                                    LoadablePartWidget::LOAD_ON_SHOW :
                                                    LoadablePartWidget::LOAD_ON_CLICK);
            } else {
                widget = new QLabel(tr("Offline"), 0);
            }
            return widget;
        } else {
            return new AttachmentView(0, manager, partIndex);
        }
    }
    QLabel *lbl = new QLabel(mimeType, 0);
    return lbl;
}
Example #30
-1
bool FileServerHandler::HandleDownloadFile(SocketHandler *socket,
                                           QStringList &slist)
{
    QStringList res;

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

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

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

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

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

    outFile = outDir + "/" + filename;

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

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

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