Ejemplo n.º 1
0
int main( int argc, char * argv[] )
{
#ifndef _MSC_VER
  qInstallMsgHandler( dummyMessageHandler );
#endif

  QgsApplication qgsapp( argc, argv, getenv( "DISPLAY" ) );

  //Default prefix path may be altered by environment variable
  char* prefixPath = getenv( "QGIS_PREFIX_PATH" );
  if ( prefixPath )
  {
    QgsApplication::setPrefixPath( prefixPath, TRUE );
  }
#if !defined(Q_OS_WIN)
  else
  {
    // init QGIS's paths - true means that all path will be inited from prefix
    QgsApplication::setPrefixPath( CMAKE_INSTALL_PREFIX, TRUE );
  }
#endif

  QDomImplementation::setInvalidDataPolicy( QDomImplementation::DropInvalidChars );

  // Instantiate the plugin directory so that providers are loaded
  QgsProviderRegistry::instance( QgsApplication::pluginPath() );
  QgsDebugMsg( "Prefix  PATH: " + QgsApplication::prefixPath() );
  QgsDebugMsg( "Plugin  PATH: " + QgsApplication::pluginPath() );
  QgsDebugMsg( "PkgData PATH: " + QgsApplication::pkgDataPath() );
  QgsDebugMsg( "User DB PATH: " + QgsApplication::qgisUserDbFilePath() );

  QgsDebugMsg( qgsapp.applicationDirPath() + "/qgis_wms_server.log" );

  //create config cache and search for config files in the current directory.
  //These configurations are used if no mapfile parameter is present in the request
  QString defaultConfigFilePath;
  QFileInfo projectFileInfo = defaultProjectFile(); //try to find a .qgs file in the server directory
  if ( projectFileInfo.exists() )
  {
    defaultConfigFilePath = projectFileInfo.absoluteFilePath();
  }
  else
  {
    QFileInfo adminSLDFileInfo = defaultAdminSLD();
    if ( adminSLDFileInfo.exists() )
    {
      defaultConfigFilePath = adminSLDFileInfo.absoluteFilePath();
    }
  }

  //create cache for capabilities XML
  QgsCapabilitiesCache capabilitiesCache;

  //creating QgsMapRenderer is expensive (access to srs.db), so we do it here before the fcgi loop
  QgsMapRenderer* theMapRenderer = new QgsMapRenderer();
  theMapRenderer->setLabelingEngine( new QgsPalLabeling() );

  while ( fcgi_accept() >= 0 )
  {
    printRequestInfos(); //print request infos if in debug mode

    //use QgsGetRequestHandler in case of HTTP GET and QgsSOAPRequestHandler in case of HTTP POST
    QgsRequestHandler* theRequestHandler = 0;
    char* requestMethod = getenv( "REQUEST_METHOD" );
    if ( requestMethod != NULL )
    {
      if ( strcmp( requestMethod, "POST" ) == 0 )
      {
        //QgsDebugMsg( "Creating QgsSOAPRequestHandler" );
        //theRequestHandler = new QgsSOAPRequestHandler();
        theRequestHandler = new QgsPostRequestHandler();
      }
      else
      {
        QgsDebugMsg( "Creating QgsGetRequestHandler" );
        theRequestHandler = new QgsGetRequestHandler();
      }
    }
    else
    {
      QgsDebugMsg( "Creating QgsGetRequestHandler" );
      theRequestHandler = new QgsGetRequestHandler();
    }

    QMap<QString, QString> parameterMap;

    try
    {
      parameterMap = theRequestHandler->parseInput();
    }
    catch ( QgsMapServiceException& e )
    {
      QgsDebugMsg( "An exception was thrown during input parsing" );
      theRequestHandler->sendServiceException( e );
      continue;
    }

    QMap<QString, QString>::const_iterator paramIt;

    //set admin config file to wms server object
    QString configFilePath( defaultConfigFilePath );

    paramIt = parameterMap.find( "MAP" );
    if ( paramIt == parameterMap.constEnd() )
    {
      QgsDebugMsg( QString( "Using default configuration file path: %1" ).arg( defaultConfigFilePath ) );
    }
    else
    {
      configFilePath = paramIt.value();
    }

    QgsConfigParser* adminConfigParser = QgsConfigCache::instance()->searchConfiguration( configFilePath );
    if ( !adminConfigParser )
    {
      QgsDebugMsg( "parse error on config file " + configFilePath );
      theRequestHandler->sendServiceException( QgsMapServiceException( "", "Configuration file problem : perhaps you left off the .qgs extension?" ) );
      continue;
    }

    //sld parser might need information about request parameters
    adminConfigParser->setParameterMap( parameterMap );

    //request to WMS?
    QString serviceString;
    paramIt = parameterMap.find( "SERVICE" );
    if ( paramIt == parameterMap.constEnd() )
    {
#ifndef QGISDEBUG
      serviceString = parameterMap.value( "SERVICE", "WMS" );
#else
      QgsDebugMsg( "unable to find 'SERVICE' parameter, exiting..." );
      theRequestHandler->sendServiceException( QgsMapServiceException( "ServiceNotSpecified", "Service not specified. The SERVICE parameter is mandatory" ) );
      delete theRequestHandler;
      continue;
#endif
    }
    else
    {
      serviceString = paramIt.value();
    }

    QgsWMSServer* theServer = 0;
    if ( serviceString == "WFS" )
    {
      delete theServer;
      QgsWFSServer* theServer = 0;
      try
      {
        theServer = new QgsWFSServer( parameterMap );
      }
      catch ( QgsMapServiceException e ) //admin.sld may be invalid
      {
        theRequestHandler->sendServiceException( e );
        continue;
      }

      theServer->setAdminConfigParser( adminConfigParser );


      //request type
      QString request = parameterMap.value( "REQUEST" );
      if ( request.isEmpty() )
      {
        //do some error handling
        QgsDebugMsg( "unable to find 'REQUEST' parameter, exiting..." );
        theRequestHandler->sendServiceException( QgsMapServiceException( "OperationNotSupported", "Please check the value of the REQUEST parameter" ) );
        delete theRequestHandler;
        delete theServer;
        continue;
      }

      if ( request.toLower() == QString( "GetCapabilities" ).toLower() )
      {
        QDomDocument capabilitiesDocument;
        try
        {
          capabilitiesDocument = theServer->getCapabilities();
        }
        catch ( QgsMapServiceException& ex )
        {
          theRequestHandler->sendServiceException( ex );
          delete theRequestHandler;
          delete theServer;
          continue;
        }
        QgsDebugMsg( "sending GetCapabilities response" );
        theRequestHandler->sendGetCapabilitiesResponse( capabilitiesDocument );
        delete theRequestHandler;
        delete theServer;
        continue;
      }
      else if ( request.toLower() == QString( "DescribeFeatureType" ).toLower() )
      {
        QDomDocument describeDocument;
        try
        {
          describeDocument = theServer->describeFeatureType();
        }
        catch ( QgsMapServiceException& ex )
        {
          theRequestHandler->sendServiceException( ex );
          delete theRequestHandler;
          delete theServer;
          continue;
        }
        QgsDebugMsg( "sending GetCapabilities response" );
        theRequestHandler->sendGetCapabilitiesResponse( describeDocument );
        delete theRequestHandler;
        delete theServer;
        continue;
      }
      else if ( request.toLower() == QString( "GetFeature" ).toLower() )
      {
        //output format for GetFeature
        QString outputFormat = parameterMap.value( "OUTPUTFORMAT" );
        try
        {
          if ( theServer->getFeature( *theRequestHandler, outputFormat ) != 0 )
          {
            delete theRequestHandler;
            delete theServer;
            continue;
          }
          else
          {
            delete theRequestHandler;
            delete theServer;
            continue;
          }
        }
        catch ( QgsMapServiceException& ex )
        {
          theRequestHandler->sendServiceException( ex );
          delete theRequestHandler;
          delete theServer;
          continue;
        }
      }
      else if ( request.toLower() == QString( "Transaction" ).toLower() )
      {
        QDomDocument transactionDocument;
        try
        {
          transactionDocument = theServer->transaction( parameterMap.value( "REQUEST_BODY" ) );
        }
        catch ( QgsMapServiceException& ex )
        {
          theRequestHandler->sendServiceException( ex );
          delete theRequestHandler;
          delete theServer;
          continue;
        }
        QgsDebugMsg( "sending Transaction response" );
        theRequestHandler->sendGetCapabilitiesResponse( transactionDocument );
        delete theRequestHandler;
        delete theServer;
        continue;
      }

      return 0;
    }

    try
    {
      theServer = new QgsWMSServer( parameterMap, theMapRenderer );
    }
    catch ( QgsMapServiceException e ) //admin.sld may be invalid
    {
      theRequestHandler->sendServiceException( e );
      continue;
    }

    theServer->setAdminConfigParser( adminConfigParser );


    //request type
    QString request = parameterMap.value( "REQUEST" );
    if ( request.isEmpty() )
    {
      //do some error handling
      QgsDebugMsg( "unable to find 'REQUEST' parameter, exiting..." );
      theRequestHandler->sendServiceException( QgsMapServiceException( "OperationNotSupported", "Please check the value of the REQUEST parameter" ) );
      delete theRequestHandler;
      delete theServer;
      continue;
    }

    QString version = parameterMap.value( "VERSION", "1.3.0" );
    bool getProjectSettings = ( request.toLower() == QString( "GetProjectSettings" ).toLower() );
    if ( getProjectSettings )
    {
      version = "1.3.0"; //getProjectSettings extends WMS 1.3.0 capabilities
    }

    if ( request.toLower() == QString( "GetCapabilities" ).toLower() || getProjectSettings )
    {
      const QDomDocument* capabilitiesDocument = capabilitiesCache.searchCapabilitiesDocument( configFilePath, getProjectSettings ? "projectSettings" : version );
      if ( !capabilitiesDocument ) //capabilities xml not in cache. Create a new one
      {
        QgsDebugMsg( "Capabilities document not found in cache" );
        QDomDocument doc;
        try
        {
          doc = theServer->getCapabilities( version, getProjectSettings );
        }
        catch ( QgsMapServiceException& ex )
        {
          theRequestHandler->sendServiceException( ex );
          delete theRequestHandler;
          delete theServer;
          continue;
        }
        capabilitiesCache.insertCapabilitiesDocument( configFilePath, getProjectSettings ? "projectSettings" : version, &doc );
        capabilitiesDocument = capabilitiesCache.searchCapabilitiesDocument( configFilePath, getProjectSettings ? "projectSettings" : version );
      }
      else
      {
        QgsDebugMsg( "Found capabilities document in cache" );
      }

      if ( capabilitiesDocument )
      {
        theRequestHandler->sendGetCapabilitiesResponse( *capabilitiesDocument );
      }
      delete theRequestHandler;
      delete theServer;
      continue;
    }
    else if ( request.toLower() == QString( "GetMap" ).toLower() )
    {
      QImage* result = 0;
      try
      {
        result = theServer->getMap();
      }
      catch ( QgsMapServiceException& ex )
      {
        QgsDebugMsg( "Caught exception during GetMap request" );
        theRequestHandler->sendServiceException( ex );
        delete theRequestHandler;
        delete theServer;
        continue;
      }

      if ( result )
      {
        QgsDebugMsg( "Sending GetMap response" );
        theRequestHandler->sendGetMapResponse( serviceString, result );
        QgsDebugMsg( "Response sent" );
      }
      else
      {
        //do some error handling
        QgsDebugMsg( "result image is 0" );
      }
      delete result;
      delete theRequestHandler;
      delete theServer;
      continue;
    }
    else if ( request.toLower() == QString( "GetFeatureInfo" ).toLower() )
    {
      QDomDocument featureInfoDoc;
      try
      {
        if ( theServer->getFeatureInfo( featureInfoDoc, version ) != 0 )
        {
          delete theRequestHandler;
          delete theServer;
          continue;
        }
      }
      catch ( QgsMapServiceException& ex )
      {
        theRequestHandler->sendServiceException( ex );
        delete theRequestHandler;
        delete theServer;
        continue;
      }

      QString infoFormat = parameterMap.value( "INFO_FORMAT" );
      theRequestHandler->sendGetFeatureInfoResponse( featureInfoDoc, infoFormat );
      delete theRequestHandler;
      delete theServer;
      continue;
    }
    else if ( request.toLower() == QString( "GetStyles" ).toLower() || request.toLower() == QString( "GetStyle" ).toLower() ) // GetStyle for compatibility with earlier QGIS versions
    {
      try
      {
        QDomDocument doc = theServer->getStyle();
        theRequestHandler->sendGetStyleResponse( doc );
      }
      catch ( QgsMapServiceException& ex )
      {
        theRequestHandler->sendServiceException( ex );
      }

      delete theRequestHandler;
      delete theServer;
      continue;
    }
    else if ( request.toLower() == QString( "GetLegendGraphic" ).toLower() || request.toLower() == QString( "GetLegendGraphics" ).toLower() ) // GetLegendGraphics for compatibility with earlier QGIS versions
    {
      QImage* result = 0;
      try
      {
        result = theServer->getLegendGraphics();
      }
      catch ( QgsMapServiceException& ex )
      {
        theRequestHandler->sendServiceException( ex );
      }

      if ( result )
      {
        QgsDebugMsg( "Sending GetLegendGraphic response" );
        //sending is the same for GetMap and GetLegendGraphic
        theRequestHandler->sendGetMapResponse( serviceString, result );
      }
      else
      {
        //do some error handling
        QgsDebugMsg( "result image is 0" );
      }
      delete result;
      delete theRequestHandler;
      delete theServer;
      continue;

    }
    else if ( request.toLower() == QString( "GetPrint" ).toLower() )
    {
      QByteArray* printOutput = 0;
      try
      {
        printOutput = theServer->getPrint( theRequestHandler->format() );
      }
      catch ( QgsMapServiceException& ex )
      {
        theRequestHandler->sendServiceException( ex );
      }

      if ( printOutput )
      {
        theRequestHandler->sendGetPrintResponse( printOutput );
      }
      delete printOutput;
      delete theRequestHandler;
      delete theServer;
      continue;
    }
    else//unknown request
    {
      QgsMapServiceException e( "OperationNotSupported", "Operation " + request + " not supported" );
      theRequestHandler->sendServiceException( e );
      delete theRequestHandler;
      delete theServer;
    }
  }

  delete theMapRenderer;
  QgsDebugMsg( "************* all done ***************" );
  return 0;
}
Ejemplo n.º 2
0
bool
PathGroups::keyPressEvent(QKeyEvent *event)
{
  for(int i=0; i<m_paths.count(); i++)
    {
      if (m_paths[i]->grabsMouse())
	{
	  if (event->key() == Qt::Key_G)
	    {
	      m_paths[i]->removeFromMouseGrabberPool();
	      return true;
	    }
	  if (event->key() == Qt::Key_C)
	    {
	      bool b = m_paths[i]->closed();
	      m_paths[i]->setClosed(!b);
	      return true;
	    }
	  else if (event->key() == Qt::Key_P)
	    {
	      bool b = m_paths[i]->showPoints();
	      m_paths[i]->setShowPoints(!b);    
	      return true;
	    }
	  else if (event->key() == Qt::Key_L)
	    {
	      bool b = m_paths[i]->showLength();
	      m_paths[i]->setShowLength(!b);    
	      return true;
	    }
	  else if (event->key() == Qt::Key_X)
	    {
	      m_paths[i]->setMoveAxis(PathGroupGrabber::MoveX);
	      return true;
	    }
	  else if (event->key() == Qt::Key_Y)
	    {
	      if (event->modifiers() & Qt::ControlModifier ||
		  event->modifiers() & Qt::MetaModifier)
		m_paths[i]->redo();
	      else
		m_paths[i]->setMoveAxis(PathGroupGrabber::MoveY);
	      return true;
	    }
	  else if (event->key() == Qt::Key_Z)
	    {
	      if (event->modifiers() & Qt::ControlModifier ||
		  event->modifiers() & Qt::MetaModifier)
		m_paths[i]->undo();
	      else
		m_paths[i]->setMoveAxis(PathGroupGrabber::MoveZ);
	      return true;
	    }
	  else if (event->key() == Qt::Key_W)
	    {
	      m_paths[i]->setMoveAxis(PathGroupGrabber::MoveAll);
	      return true;
	    }
	  else if (event->key() == Qt::Key_S)
	    {
	      int idx = m_paths[i]->pointPressed();
	      if (idx > -1)
		{
		  float radx = m_paths[i]->getRadX(idx);
		  if (event->modifiers() & Qt::ShiftModifier)
		    radx--;
		  else
		    radx++;
		  radx = qMax(1.0f, radx);
		  m_paths[i]->setRadX(idx, radx, m_sameForAll);
		  return true;
		}
	    }
	  else if (event->key() == Qt::Key_T)
	    {
	      int idx = m_paths[i]->pointPressed();
	      if (idx > -1)
		{
		  float rady = m_paths[i]->getRadY(idx);
		  if (event->modifiers() & Qt::ShiftModifier)
		    rady--;
		  else
		    rady++;
		  rady = qMax(1.0f, rady);
		  m_paths[i]->setRadY(idx, rady, m_sameForAll);
		}
	      else // switch to tube mode
		{
		  if (event->modifiers() & Qt::ShiftModifier)
		    {
		      m_paths[i]->loadCaption();
		    }
		  else
		    {
		      bool b = m_paths[i]->tube();
		      m_paths[i]->setTube(!b);
		    }
		}

	      return true;
	    }
	  else if (event->key() == Qt::Key_A)
	    {
	      int idx = m_paths[i]->pointPressed();
	      if (idx > -1)
		{
		  float a = m_paths[i]->getAngle(idx);
		  if (event->modifiers() & Qt::ShiftModifier)
		    a--;
		  else
		    a++;
		  m_paths[i]->setAngle(idx, a, m_sameForAll);
		  return true;
		}
	    }
	  else if (event->key() == Qt::Key_Delete ||
		   event->key() == Qt::Key_Backspace ||
		   event->key() == Qt::Key_Backtab)
	    {
	      m_paths[i]->removeFromMouseGrabberPool();
	      m_paths.removeAt(i);
	      return true;
	    }

	  if (event->key() == Qt::Key_Space)
	    {
	      PropertyEditor propertyEditor;
	      QMap<QString, QVariantList> plist;

	      QVariantList vlist;

	      vlist.clear();
	      vlist << QVariant("double");
	      vlist << QVariant(m_paths[i]->opacity());
	      vlist << QVariant(0.0);
	      vlist << QVariant(1.0);
	      vlist << QVariant(0.1); // singlestep
	      vlist << QVariant(1); // decimals
	      plist["opacity"] = vlist;

	      vlist.clear();
	      vlist << QVariant("colorgradient");
	      QGradientStops stops = m_paths[i]->stops();
	      for(int s=0; s<stops.size(); s++)
		{
		  float pos = stops[s].first;
		  QColor color = stops[s].second;
		  int r = color.red();
		  int g = color.green();
		  int b = color.blue();
		  int a = color.alpha();
		  vlist << QVariant(pos);
		  vlist << QVariant(r);
		  vlist << QVariant(g);
		  vlist << QVariant(b);
		  vlist << QVariant(a);
		}
	      plist["color"] = vlist;

	      vlist.clear();
	      vlist << QVariant("checkbox");
	      vlist << QVariant(m_paths[i]->filterPathLen());
	      plist["filter on length"] = vlist;

	      float vmin, vmax;
	      m_paths[i]->userPathlenMinmax(vmin, vmax);
	      vlist.clear();
	      vlist << QVariant("string");
	      vlist << QVariant(QString("%1 %2").arg(vmin).arg(vmax));
	      plist["length bounds"] = vlist;

	      vlist.clear();
	      vlist << QVariant("checkbox");
	      vlist << QVariant(m_paths[i]->scaleType());
	      plist["scale type"] = vlist;

	      vlist.clear();
	      vlist << QVariant("checkbox");
	      vlist << QVariant(m_paths[i]->depthcue());
	      plist["depthcue"] = vlist;

	      vlist.clear();
	      vlist << QVariant("int");
	      vlist << QVariant(m_paths[i]->segments());
	      vlist << QVariant(1);
	      vlist << QVariant(100);
	      plist["smoothness"] = vlist;

	      vlist.clear();
	      vlist << QVariant("int");
	      vlist << QVariant(m_paths[i]->sections());
	      vlist << QVariant(1);
	      vlist << QVariant(100);
	      plist["sections"] = vlist;

	      vlist.clear();
	      vlist << QVariant("int");
	      vlist << QVariant(m_paths[i]->sparseness());
	      vlist << QVariant(1);
	      vlist << QVariant(100);
	      plist["sparseness"] = vlist;

	      vlist.clear();
	      vlist << QVariant("int");
	      vlist << QVariant(m_paths[i]->separation());
	      vlist << QVariant(0);
	      vlist << QVariant(10);
	      plist["screen separation"] = vlist;

	      vlist.clear();
	      vlist << QVariant("combobox");
	      vlist << QVariant(m_paths[i]->capType());
	      vlist << QVariant("flat");
	      vlist << QVariant("round");
	      vlist << QVariant("arrow");
	      plist["cap style"] = vlist;

	      vlist.clear();
	      vlist << QVariant("combobox");
	      vlist << QVariant(m_paths[i]->arrowDirection());
	      vlist << QVariant("forward");
	      vlist << QVariant("backward");
	      plist["arrow direction"] = vlist;

	      vlist.clear();
	      vlist << QVariant("checkbox");
	      vlist << QVariant(m_paths[i]->animate());
	      plist["animate"] = vlist;

	      vlist.clear();
	      vlist << QVariant("checkbox");
	      vlist << QVariant(m_paths[i]->allowInterpolate());
	      plist["interpolate"] = vlist;

	      vlist.clear();
	      vlist << QVariant("int");
	      vlist << QVariant(m_paths[i]->animateSpeed());
	      vlist << QVariant(10);
	      vlist << QVariant(100);
	      plist["animation speed"] = vlist;

	      vlist.clear();
	      vlist << QVariant("checkbox");
	      vlist << QVariant(m_paths[i]->arrowForAll());
	      plist["arrows for all"] = vlist;

	      vlist.clear();
	      vlist << QVariant("checkbox");
	      vlist << QVariant(m_sameForAll);
	      plist["same for all"] = vlist;

	      vlist.clear();
	      vlist << QVariant("checkbox");
	      vlist << QVariant(m_paths[i]->clip());
	      plist["clip"] = vlist;

	      vlist.clear();
	      vlist << QVariant("checkbox");
	      vlist << QVariant(m_paths[i]->allowEditing());
	      plist["allow editing"] = vlist;

	      vlist.clear();
	      vlist << QVariant("checkbox");
	      vlist << QVariant(m_paths[i]->blendMode());
	      plist["blend with volume"] = vlist;

	      vlist.clear();
	      plist["command"] = vlist;

	      vlist.clear();
	      QFile helpFile(":/pathgroups.help");
	      if (helpFile.open(QFile::ReadOnly))
		{
		  QTextStream in(&helpFile);
		  QString line = in.readLine();
		  while (!line.isNull())
		    {
		      if (line == "#begin")
			{
			  QString keyword = in.readLine();
			  QString helptext;
			  line = in.readLine();
			  while (!line.isNull())
			    {
			      helptext += line;
			      helptext += "\n";
			      line = in.readLine();
			      if (line == "#end") break;
			    }
			  vlist << keyword << helptext;
			}
		      line = in.readLine();
		    }
		}	      
	      plist["commandhelp"] = vlist;


	      vlist.clear();
	      QString mesg;
	      float pmin, pmax;
	      m_paths[i]->pathlenMinmax(pmin, pmax);
	      mesg = QString("min/max path lengths : %1 %2\n").arg(pmin).arg(pmax);
	      float mins,maxs;
	      mins = m_paths[i]->minScale();
	      maxs = m_paths[i]->maxScale();
	      mesg += QString("min/max scale : %1 %2\n").arg(mins).arg(maxs);
	      vlist << mesg;
	      plist["message"] = vlist;


	      QStringList keys;
	      keys << "color";
	      keys << "opacity";
	      keys << "depthcue";
	      keys << "gap";
	      keys << "filter on length";
	      keys << "length bounds";
	      keys << "scale type";
	      keys << "gap";
	      keys << "smoothness";
	      keys << "sections";
	      keys << "sparseness";
	      keys << "screen separation";
	      keys << "gap";
	      keys << "cap style";
	      keys << "arrow direction";
	      keys << "arrows for all";
	      keys << "gap";
	      keys << "animate";
	      keys << "interpolate";
	      keys << "animation speed";
	      keys << "gap";
	      keys << "same for all";
	      keys << "clip";
	      keys << "blend with volume";
	      keys << "allow editing";
	      keys << "command";
	      keys << "commandhelp";
	      keys << "message";
	      

	      propertyEditor.set("Path Group Parameters", plist, keys);

	      
	      QMap<QString, QPair<QVariant, bool> > vmap;

	      if (propertyEditor.exec() == QDialog::Accepted)
		vmap = propertyEditor.get();
	      else
		return true;

	      keys = vmap.keys();

	      for(int ik=0; ik<keys.count(); ik++)
		{
		  QPair<QVariant, bool> pair = vmap.value(keys[ik]);


		  if (pair.second)
		    {
		      if (keys[ik] == "color")
			{
			  QGradientStops stops = propertyEditor.getGradientStops(keys[ik]);
			  m_paths[i]->setStops(stops);
			}
		      else if (keys[ik] == "opacity")
			m_paths[i]->setOpacity(pair.first.toDouble());
		      else if (keys[ik] == "scale type")
			m_paths[i]->setScaleType(pair.first.toBool());
		      else if (keys[ik] == "sections")
			m_paths[i]->setSections(pair.first.toInt());
		      else if (keys[ik] == "smoothness")
			m_paths[i]->setSegments(pair.first.toInt());
		      else if (keys[ik] == "sparseness")
			m_paths[i]->setSparseness(pair.first.toInt());
		      else if (keys[ik] == "screen separation")
			m_paths[i]->setSeparation(pair.first.toInt());
		      else if (keys[ik] == "depthcue")
			m_paths[i]->setDepthcue(pair.first.toBool());
		      else if (keys[ik] == "animate")
			m_paths[i]->setAnimate(pair.first.toBool());
		      else if (keys[ik] == "interpolate")
			m_paths[i]->setAllowInterpolate(pair.first.toBool());
		      else if (keys[ik] == "animation speed")
			m_paths[i]->setAnimateSpeed(pair.first.toInt());
		      else if (keys[ik] == "cap style")
			m_paths[i]->setCapType(pair.first.toInt());
		      else if (keys[ik] == "arrow direction")
			m_paths[i]->setArrowDirection(pair.first.toInt());
		      else if (keys[ik] == "arrows for all")
			m_paths[i]->setArrowForAll(pair.first.toBool());
		      else if (keys[ik] == "same for all")
			{
			  m_sameForAll = pair.first.toBool();
			  m_paths[i]->setSameForAll(m_sameForAll);
			}
		      else if (keys[ik] == "clip")
			m_paths[i]->setClip(pair.first.toBool());
		      else if (keys[ik] == "allow editing")
			m_paths[i]->setAllowEditing(pair.first.toBool());
		      else if (keys[ik] == "blend with volume")
			m_paths[i]->setBlendMode(pair.first.toBool());
		      else if (keys[ik] == "filter on length")
			m_paths[i]->setFilterPathLen(pair.first.toBool());
		      else if (keys[ik] == "length bounds")
			{
			  QString vstr = pair.first.toString();
			  QStringList vl = vstr.split(" ", QString::SkipEmptyParts);
			  if (vl.count() == 2)
			    m_paths[i]->setUserPathlenMinmax(vl[0].toDouble(),
							     vl[1].toDouble());
			}
		    }
		}

	      QString cmd = propertyEditor.getCommandString();
	      if (!cmd.isEmpty())
		processCommand(i, cmd);	
	      	      
	      updateGL();
	    }
	}
    }
  
  return true;
}
Ejemplo n.º 3
0
bool QgsMapToolIdentify::identifyRasterLayer( QList<IdentifyResult> *results, QgsRasterLayer *layer, QgsPoint point, const QgsRectangle& viewExtent, double mapUnitsPerPixel )
{
  QgsDebugMsg( "point = " + point.toString() );
  if ( !layer )
    return false;

  QgsRasterDataProvider *dprovider = layer->dataProvider();
  if ( !dprovider )
    return false;

  int capabilities = dprovider->capabilities();
  if ( !( capabilities & QgsRasterDataProvider::Identify ) )
    return false;

  QgsPoint pointInCanvasCrs = point;
  try
  {
    point = toLayerCoordinates( layer, point );
  }
  catch ( QgsCsException &cse )
  {
    Q_UNUSED( cse );
    QgsDebugMsg( QString( "coordinate not reprojectable: %1" ).arg( cse.what() ) );
    return false;
  }
  QgsDebugMsg( QString( "point = %1 %2" ).arg( point.x() ).arg( point.y() ) );

  if ( !layer->extent().contains( point ) )
    return false;

  QMap< QString, QString > attributes, derivedAttributes;

  QgsRaster::IdentifyFormat format = QgsRasterDataProvider::identifyFormatFromName( layer->customProperty( "identify/format" ).toString() );

  // check if the format is really supported otherwise use first supported format
  if ( !( QgsRasterDataProvider::identifyFormatToCapability( format ) & capabilities ) )
  {
    if ( capabilities & QgsRasterInterface::IdentifyFeature ) format = QgsRaster::IdentifyFormatFeature;
    else if ( capabilities & QgsRasterInterface::IdentifyValue ) format = QgsRaster::IdentifyFormatValue;
    else if ( capabilities & QgsRasterInterface::IdentifyHtml ) format = QgsRaster::IdentifyFormatHtml;
    else if ( capabilities & QgsRasterInterface::IdentifyText ) format = QgsRaster::IdentifyFormatText;
    else return false;
  }

  QgsRasterIdentifyResult identifyResult;
  // We can only use current map canvas context (extent, width, height) if layer is not reprojected,
  if ( mCanvas->hasCrsTransformEnabled() && dprovider->crs() != mCanvas->mapSettings().destinationCrs() )
  {
    // To get some reasonable response for point/line WMS vector layers we must
    // use a context with approximately a resolution in layer CRS units
    // corresponding to current map canvas resolution (for examplei UMN Mapserver
    // in msWMSFeatureInfo() -> msQueryByRect() is using requested pixel
    // + TOLERANCE (layer param) for feature selection)
    //
    QgsRectangle r;
    r.setXMinimum( pointInCanvasCrs.x() - mapUnitsPerPixel / 2. );
    r.setXMaximum( pointInCanvasCrs.x() + mapUnitsPerPixel / 2. );
    r.setYMinimum( pointInCanvasCrs.y() - mapUnitsPerPixel / 2. );
    r.setYMaximum( pointInCanvasCrs.y() + mapUnitsPerPixel / 2. );
    r = toLayerCoordinates( layer, r ); // will be a bit larger
    // Mapserver (6.0.3, for example) does not work with 1x1 pixel box
    // but that is fixed (the rect is enlarged) in the WMS provider
    identifyResult = dprovider->identify( point, format, r, 1, 1 );
  }
  else
  {
    // It would be nice to use the same extent and size which was used for drawing,
    // so that WCS can use cache from last draw, unfortunately QgsRasterLayer::draw()
    // is doing some tricks with extent and size to allign raster to output which
    // would be difficult to replicate here.
    // Note: cutting the extent may result in slightly different x and y resolutions
    // and thus shifted point calculated back in QGIS WMS (using average resolution)
    //viewExtent = dprovider->extent().intersect( &viewExtent );

    // Width and height are calculated from not projected extent and we hope that
    // are similar to source width and height used to reproject layer for drawing.
    // TODO: may be very dangerous, because it may result in different resolutions
    // in source CRS, and WMS server (QGIS server) calcs wrong coor using average resolution.
    int width = qRound( viewExtent.width() / mapUnitsPerPixel );
    int height = qRound( viewExtent.height() / mapUnitsPerPixel );

    QgsDebugMsg( QString( "viewExtent.width = %1 viewExtent.height = %2" ).arg( viewExtent.width() ).arg( viewExtent.height() ) );
    QgsDebugMsg( QString( "width = %1 height = %2" ).arg( width ).arg( height ) );
    QgsDebugMsg( QString( "xRes = %1 yRes = %2 mapUnitsPerPixel = %3" ).arg( viewExtent.width() / width ).arg( viewExtent.height() / height ).arg( mapUnitsPerPixel ) );

    identifyResult = dprovider->identify( point, format, viewExtent, width, height );
  }

  derivedAttributes.insert( tr( "(clicked coordinate)" ), point.toString() );

  if ( identifyResult.isValid() )
  {
    QMap<int, QVariant> values = identifyResult.results();
    QgsGeometry geometry;
    if ( format == QgsRaster::IdentifyFormatValue )
    {
      Q_FOREACH ( int bandNo, values.keys() )
      {
        QString valueString;
        if ( values.value( bandNo ).isNull() )
        {
          valueString = tr( "no data" );
        }
        else
        {
          double value = values.value( bandNo ).toDouble();
          valueString = QgsRasterBlock::printValue( value );
        }
        attributes.insert( dprovider->generateBandName( bandNo ), valueString );
      }
      QString label = layer->name();
      results->append( IdentifyResult( qobject_cast<QgsMapLayer *>( layer ), label, attributes, derivedAttributes ) );
    }
Ejemplo n.º 4
0
void SoftwareController::service(HttpRequest& request, HttpResponse& response) {
    MainWindow *mw_ptr = (MainWindow *) rm_ptr->mw_ptr;
    QMap<QString, TableItem *> map;

    //map.insert("", new TableItem(rm_ptr, "", "", mw_ptr->ui->));
    map.insert("mode", new TableItem(rm_ptr, "mode", "run in Mini Mide", mw_ptr->ui->checkBox_mini_mode));
    //map.insert("toolbar", new TableItem(rm_ptr, "toolbar", "Show ToolBar", mw_ptr->toolBarIsVisible);
    map.insert("ontop", new TableItem(rm_ptr, "ontop", "be on top in mini mode", mw_ptr->ui->checkBox_be_on_the_top));
    map.insert("intray", new TableItem(rm_ptr, "intray", "hide in tray after start-up", mw_ptr->ui->checkBox_sw_hideInTray));
    //map.insert("language", new TableItem(rm_ptr, "language", "", mw_ptr->UsedLanguage);

    map.insert("flag", new TableItem(rm_ptr, "flag", "Send RDS time stamps", mw_ptr->ui->checkBox_rds_time));
    map.insert("interval", new TableItem(rm_ptr, "interval", "RDS time stamps interval", mw_ptr->ui->spinBox_rds_time_int));

    map.insert("softcfg", new TableItem(rm_ptr, "softcfg", "Use software config instead of EEPROM", mw_ptr->ui->checkBox_rewriteCfg));
    map.insert("autoconnect", new TableItem(rm_ptr, "autoconnect", "Auto-connect device to FmStick software", mw_ptr->ui->checkBox_sw_autoconnect));
    map.insert("liveedit", new TableItem(rm_ptr, "liveedit", "Enable live-editing device's parameters", mw_ptr->ui->checkBox_sw_live_edit));
    map.insert("http_serve", new TableItem(rm_ptr, "http_serve", "Enable remote HTTP access (WARNING!)", mw_ptr->ui->checkBox_sw_remote));
    map.insert("http_port", new TableItem(rm_ptr, "http_port", "HTTP port (WARNING!)", mw_ptr->ui->spinBox_sw_remote_port));
    map.insert("http_login", new TableItem(rm_ptr, "http_login", "HTTP login (WARNING!)", mw_ptr->ui->lineEdit_sw_remote_login));
    map.insert("http_password", new TableItem(rm_ptr, "http_password", "HTTP password (WARNING!)", mw_ptr->ui->lineEdit_sw_remote_pwd));

    response.setHeader("Content-Type", "text/html; charset=UTF-8");
    QFile file(":/fmstick/html/index.html");
    if (file.open(QIODevice::ReadOnly)) {
        response.write(file.readAll());
        file.close();
    }

    response.write("<div class=\"logo_style\">"
                   "<img src=\"/images/Administrative Tools-64 (1).png\">"
                   "<h2>Software Configuration Controller</h2>");
    response.write("</div><div class=\"container\">");

    QString action(request.getParameter("action"));

    bool have_any_action=FALSE;
    if (map.contains(action)) {
        TableItem *table_data = map.value(action);
        response.write(table_data->doHTMLParse(&request));
        have_any_action=TRUE;
    }

    if(!have_any_action && action == "Software_custom"){
        qDebug() << "TODO: custom_Software action";
        have_any_action=TRUE;
    }
    if(have_any_action){
        response.write("<br/><a href=\"/sw\">[Back To Software Section]</a> | <a href=\"/\">[Back To Main Section]</a>");
    } else {
        response.write("<form><input type=\"hidden\" name=\"action\" value=\"dummy\">"
                       "<div class=\"row\">"
                       "<div class=\"prop\">"
                       "<p><b>Property</b></p>"
                       "</div>"
                       "<div class=\"val\">"
                       "<p><b>Value</b></p>"
                       "</div>"
                       "<div class=\"submit\">"
                       "<p><b>Action</b></p>"
                       "</div>"
                       "<div class=\"tooltip\">"
                       "<p><b>Tooltip</b></p>"
                       "</div>"
                       "</div></form>");
        QMapIterator<QString, TableItem *> i(map);
        while (i.hasNext()) {
            i.next();
            response.write(i.value()->GenHTMLForm());
        }
#if 0
        /* forcer */
        QString Software_custom = QString(
                    "<form method=\"post\">"
                    "  <input type=\"hidden\" name=\"action\" value=\"Software_custom\">"
                    "<div class=\"form_info\">Custom Software message:</div>"
                    "<div class=\"form_editor\">"
                    "<input type=\"text\" name=\"Software_custom_b\" value=\"4000\" size=\"4\">"
                    "<input type=\"text\" name=\"Software_custom_c\" value=\"0000\" size=\"4\">"
                    "<input type=\"text\" name=\"Software_custom_d\" value=\"0000\" size=\"4\">"
                    "Circular:<input type=\"checkbox\" name=\"Software_custom_circular\" value=\"0\">"
                    "</div>"
                    "<div class=\"form_submitter\"><input type=\"submit\" value=\"&gt;&gt;\"></div>"
                    "<div class=\"form_tooltip\"></div>"
                    "</form>");
         response.write(Software_custom.toUtf8());
#endif
    }

    response.write("</div></div></div></body></html>", true);

}
Ejemplo n.º 5
0
void QgisAppStyleSheet::buildStyleSheet( const QMap<QString, QVariant>& opts )
{
  QString ss = QString( "" );


  // QgisApp-wide font
  QString fontSize = opts.value( "fontPointSize" ).toString();
  QgsDebugMsg( QString( "fontPointSize: %1" ).arg( fontSize ) );
  if ( fontSize.isEmpty() ) { return; }

  QString fontFamily = opts.value( "fontFamily" ).toString();
  QgsDebugMsg( QString( "fontFamily: %1" ).arg( fontFamily ) );
  if ( fontFamily.isEmpty() ) { return; }

  ss += QString( "* { font: %1pt \"%2\"} " ).arg( fontSize ).arg( fontFamily );

  // QGroupBox and QgsCollapsibleGroupBox, mostly for Ubuntu and Mac
  bool gbxCustom = opts.value( "groupBoxCustom" ).toBool();
  QgsDebugMsg( QString( "groupBoxCustom: %1" ).arg( gbxCustom ) );
  bool gbxBoldTitle = opts.value( "groupBoxBoldTitle" ).toBool();
  QgsDebugMsg( QString( "groupBoxBoldTitle: %1" ).arg( gbxBoldTitle ) );
  bool sidebar = opts.value( "sidebarStyle" ).toBool();
  if ( gbxCustom || gbxBoldTitle )
  {
    ss += "QGroupBox{";
    if ( gbxBoldTitle )
    {
      // doesn't work for QGroupBox::title
      ss += QString( "color: rgb(%1,%1,%1);" ).arg( mMacStyle ? 25 : 60 );
      ss += "font-weight: bold;";
    }
    if ( gbxCustom )
    {
      ss += QString( "background-color: rgba(0,0,0,%1%);" )
            .arg( mWinOS && mStyle.startsWith( "windows" ) ? 0 : 3 );
      ss += "border: 1px solid rgba(0,0,0,20%);";
      ss += "border-radius: 5px;";
      ss += "margin-top: 2.5ex;";
      ss += QString( "margin-bottom: %1ex;" ).arg( mMacStyle ? 1.5 : 1 );
    }
    ss += "} ";
    if ( gbxCustom )
    {
      ss += "QGroupBox:flat{";
      ss += "background-color: rgba(0,0,0,0);";
      ss += "border: rgba(0,0,0,0);";
      ss += "} ";

      ss += "QGroupBox::title{";
      ss += "subcontrol-origin: margin;";
      ss += "subcontrol-position: top left;";
      ss += "margin-left: 6px;";
      if ( !( mWinOS && mStyle.startsWith( "windows" ) ) && !mOxyStyle )
      {
        ss += "background-color: rgba(0,0,0,0);";
      }
      ss += "} ";
    }
  }

  if ( sidebar )
  {
    QString style = "QListWidget#mOptionsListWidget {"
                    "    background-color: rgb(69, 69, 69, 220);"
                    "    outline: 0;"
                    "}"
                    "QListWidget#mOptionsListWidget::item {"
                    "    color: white;"
                    "    padding: 3px;"
                    "}"
                    "QListWidget#mOptionsListWidget::item::selected {"
                    "    color: black;"
                    "    background-color:palette(Window);"
                    "    padding-right: 0px;"
                    "}";
    ss += style;
  }

  //fix background issue for gnome desktop
  if ( mLinuxOS && mGtkStyle && !sidebar )
  {
    ss += "QListWidget#mOptionsListWidget{";
    ss += "background-color: white;";
    ss += "} ";
  }

  // Fix selection color on loosing focus (Windows)
  const QPalette palette = qApp->palette();

  ss += QString( "QTableView {"
                 "selection-background-color: %1;"
                 "selection-color: %2;"
                 "}" )
        .arg( palette.highlight().color().name() )
        .arg( palette.highlightedText().color().name() );

  QgsDebugMsg( QString( "Stylesheet built: %1" ).arg( ss ) );

  emit appStyleSheetChanged( ss );
}
Ejemplo n.º 6
0
/**
 * @brief Get's the correct object from the device.
 * !Important! Release Device after using the returned object
 * @param pathItems A QStringList containing the items of the filepath
 * @return QPair with the object and its device. pair.fist is a nullpointer if the object doesn't exist or for root or, depending on the pathItems size device (1), storage (2) or file (>=3)
 */
QPair<void*, LIBMTP_mtpdevice_t*> MTPSlave::getPath ( const QString& path )
{
    QStringList pathItems = path.split ( QLatin1Char ( '/' ), QString::SkipEmptyParts );

    kDebug ( KIO_MTP ) << path << pathItems.size();

    QPair<void*, LIBMTP_mtpdevice_t*> ret;

    // Don' handle the root directory
    if ( pathItems.size() <= 0 )
    {
        return ret;
    }

    QMap<QString, LIBMTP_raw_device_t*> devices = getRawDevices();

    if ( devices.contains ( pathItems.at ( 0 ) ) )
    {
        LIBMTP_mtpdevice_t *device = LIBMTP_Open_Raw_Device_Uncached ( devices.value ( pathItems.at ( 0 ) ) );

        // return specific device
        if ( pathItems.size() == 1 )
        {
            ret.first = device;
            ret.second = device;

            kDebug(KIO_MTP) << "returning LIBMTP_mtpdevice_t";
        }

        if ( pathItems.size() > 2 )
        {
            // Query Cache after we have the device
            uint32_t c_fileID = fileCache->queryPath ( path );
            if ( c_fileID != 0 )
            {
                kDebug() << "Match found in cache, checking device";

                LIBMTP_file_t* file = LIBMTP_Get_Filemetadata ( device, c_fileID );
                if ( file )
                {
                    kDebug ( KIO_MTP ) << "Found file in cache";
                    ret.first = file;
                    ret.second = device;

                    kDebug(KIO_MTP) << "returning LIBMTP_file_t";

                    return ret;
                }
            }
            // Query cache for parent
            else if ( pathItems.size() > 3 )
            {
                QString parentPath = convertToPath ( pathItems, pathItems.size() - 1 );
                uint32_t c_parentID = fileCache->queryPath ( parentPath );

                kDebug() << "Match for parent found in cache, checking device";

                LIBMTP_file_t* parent = LIBMTP_Get_Filemetadata ( device, c_parentID );
                if ( parent )
                {
                    kDebug ( KIO_MTP ) << "Found parent in cache";
                    fileCache->addPath( parentPath, c_parentID );

                    QMap<QString, LIBMTP_file_t*> files = getFiles ( device, parent->storage_id, c_parentID );

                    if ( files.contains ( pathItems.last() ) )
                    {
                        LIBMTP_file_t* file = files.value( pathItems.last() );

                        ret.first = file;
                        ret.second = device;

                        kDebug(KIO_MTP) << "returning LIBMTP_file_t";

                        fileCache->addPath( path, file->item_id );
                    }

                    return ret;
                }
            }
        }

        QMap<QString, LIBMTP_devicestorage_t*> storages = getDevicestorages ( device );

        if ( pathItems.size() > 1 && storages.contains ( pathItems.at ( 1 ) ) )
        {
            LIBMTP_devicestorage_t *storage = storages.value ( pathItems.at ( 1 ) );

            if ( pathItems.size() == 2 )
            {
                ret.first = storage;
                ret.second = device;

                kDebug(KIO_MTP) << "returning LIBMTP_devicestorage_t";

                return ret;
            }

            int currentLevel = 2, currentParent = 0xFFFFFFFF;

            QMap<QString, LIBMTP_file_t*> files;

            // traverse further while depth not reached
            while ( currentLevel < pathItems.size() )
            {
                files = getFiles ( device, storage->id, currentParent );

                if ( files.contains ( pathItems.at ( currentLevel ) ) )
                {
                    currentParent = files.value ( pathItems.at ( currentLevel ) )->item_id;
                }
                else
                {

                    kDebug(KIO_MTP) << "returning LIBMTP_file_t";

                    return ret;
                }
                currentLevel++;
            }

            ret.first = LIBMTP_Get_Filemetadata ( device, currentParent );
            ret.second = device;

            fileCache->addPath ( path, currentParent );
        }
    }

    return ret;
}
Ejemplo n.º 7
0
void UVManager::insertUV(QString code, QString titre, QMap<QString,int> cat,bool a, bool p){
    DatabaseManager& db = DatabaseManager::getInstanceDB();


    db.updateTableUV(a,p,code,titre,cat.value("CS"),cat.value("TM"),cat.value("TSH"),cat.value("SP"));
}
Ejemplo n.º 8
0
int FlickrPrivate::upload(const FlickrPhoto &photo,
                          const FlickrRequest &request,
                          void* userData) {
    QByteArray boundary = generateBoundary();
    QByteArray payload;
    QDataStream dataStream(&payload, QIODevice::WriteOnly);

    QMap<QString,QString> map = photo.args;

    map.insert("api_key", _apiKey);
    if(!_token.isEmpty()) {
        map.insert("auth_token", _token);
    }

    bool uploading = photo.photoId.isEmpty();
    if(!uploading){
        map.insert("photo_id", photo.photoId);
    }

    QMapIterator<QString, QString> i(map);
    QStringList keyList;
    while(i.hasNext())
    {
        i.next();
        keyList << i.key();
    }
    qSort(keyList.begin(), keyList.end());

    QString apiSig(_apiSecret);
    for(int i = 0; i < keyList.size(); ++i) {
        apiSig.append(keyList.at(i) + map.value(keyList.at(i)));

        QByteArray field = constructField(keyList.at(i),map.value(keyList.at(i)),boundary);
        dataStream.writeRawData(field.data(), field.length());

    }

    apiSig = md5(apiSig);

    QByteArray sigField = constructField("api_sig", apiSig, boundary);
    dataStream.writeRawData(sigField.data(), sigField.length());

    QByteArray fileField = constructField("photo", "", boundary, photo.file);
    dataStream.writeRawData(fileField.data(), fileField.length());

    QFile file(photo.file);
    file.open(QIODevice::ReadOnly);
    while(!file.atEnd()) {
        QByteArray line = file.readLine();
        dataStream.writeRawData(line.data(),line.length());
    }

    file.close();

    QByteArray endField;
    endField.append("\r\n--");
    endField.append(boundary);
    endField.append("--\r\n\r\n");
    dataStream.writeRawData(endField.data(), endField.length());

    QString urlTmp("http://api.flickr.com/services/");
    urlTmp.append((uploading)?"upload/":"replace/");

    QNetworkRequest uploadRequest(urlTmp);
    uploadRequest.setRawHeader("Content-Type","multipart/form-data; boundary="+boundary);
    uploadRequest.setRawHeader("Host","ww.api.flickr.com");

    _requestCounter++;
    RequestData requestData;
    requestData.request = request.requests;
    requestData.userData = userData;
    requestData.requestId = _requestCounter;

    QNetworkReply *reply = _networkAccessManager->post(uploadRequest,payload);
    connect(reply,SIGNAL(uploadProgress(qint64, qint64)),
            this, SLOT(uploadProgress(qint64, qint64)));

    requestDataMap.insert(reply,requestData);
    return requestData.requestId;
}
Ejemplo n.º 9
0
QVariantMap simulatorCache(int i, QIODevice *connection,
	const QSqlDatabase& db, const QSqlDatabase& user_db,
	const QVariantMap& action, const QString& email)
{
	Q_UNUSED(email);
	Q_UNUSED(user_db);
	Q_UNUSED(connection);

	QVariantMap map;

	// Check for the 'lang' paramater
	if( !action.contains("lang") )
		return param_error(tr("simulator_cache action"), tr("lang"),
			tr("action %1").arg(i));

	bool reload = false;
	if( action.contains("reload") )
	{
		if( !action.value("reload").canConvert(QVariant::Bool) )
			return herror("simulator_cache action", tr("reload must be a "
				"boolean value for action %1").arg(i));

		reload = action.value("reload").toBool();
	}

	QString lang = action.value("lang").toString().toLower();
	if(lang != "en" && lang != "ja")
		return herror("simulator_cache action", tr("parmater 'lang' for action "
			"%1 contains an illegal value").arg(i));

	if(simulator_cache.contains(lang) && !reload)
		return simulator_cache.value(lang);

	QString sql = "SELECT db_skills.id id, db_skills.name_{$lang} name, "
		"db_skills.icon icon, db_affinity.name_{$lang} affinity, "
		"db_expert.name_{$lang} expert, db_category.name_{$lang} category, "
		"db_skills.mp_cost mp_cost, db_skills.hp_cost hp_cost, "
		"db_skills.mag_cost mag_cost, db_action_type.name_{$lang} action_type, "
		"db_skills.desc_{$lang} desc, db_skills.class class, "
		"db_skills.rank rank, db_skills.inheritance inheritance, "
		"db_related_stat.name_{$lang} related_stat FROM db_skills LEFT JOIN "
		"db_affinity ON db_skills.affinity = db_affinity.id LEFT JOIN "
		"db_expert ON db_skills.expert = db_expert.id LEFT JOIN db_category ON "
		"db_skills.category = db_category.id LEFT JOIN db_action_type ON "
		"db_skills.action_type = db_action_type.id LEFT JOIN db_related_stat "
		"ON db_skills.related_stat = db_related_stat.id "
		"WHERE db_skills.player_only = 0 OR db_skills.player_only = 'false'";
	sql = sql.replace("{$lang}", lang);

	QSqlQuery query(db);
	if( !query.prepare(sql) )
		return herror_sql(db, "simulator_cache action", tr("SQL error for "
			"action %1: %2").arg(i).arg( query.lastError().text() ));

	if( !query.exec() )
		return herror_sql(db, "simulator_cache action", tr("SQL error for "
			"action %1: %2").arg(i).arg( query.lastError().text() ));

	QVariantList skills;
	while( query.next() )
	{
		QSqlRecord record = query.record();

		QVariantMap skill;
		for(int j = 0; j < record.count(); j++)
			skill[record.fieldName(j)] = record.value(j);

		skills << skill;
	}

	map["skills"] = skills;

	sql = "SELECT id, name_{$lang} name, desc_{$lang} desc FROM db_traits";
	sql = sql.replace("{$lang}", lang);

	if( !query.prepare(sql) )
		return herror_sql(db, "simulator_cache action", tr("SQL error for "
			"action %1: %2").arg(i).arg( query.lastError().text() ));

	if( !query.exec() )
		return herror_sql(db, "simulator_cache action", tr("SQL error for "
			"action %1: %2").arg(i).arg( query.lastError().text() ));

	QVariantList traits;
	while( query.next() )
	{
		QSqlRecord record = query.record();

		QVariantMap trait;
		for(int j = 0; j < record.count(); j++)
			trait[record.fieldName(j)] = record.value(j);

		traits << trait;
	}

	map["traits"] = traits;

	sql = "SELECT db_devils.id id, db_devils.name_{$lang} name, "
		"db_devils.icon icon, db_devils.lvl lvl, db_genus.name_{$lang} genus, "
		"db_growth_type.name_{$lang} growth_type, db_devils.lnc lnc, "
		"db_devils.hp hp, db_devils.mp mp, db_devils.mag mag, "
		"db_mashou.fusion1_desc_{$lang} mashou_desc1, "
		"db_mashou.fusion2_desc_{$lang} mashou_desc2, "
		"db_equip_type.name_{$lang} mashou_equip_type, "
		"db_devils.fusion2 fusion2, db_devils.fusion3 fusion3, "
		"db_devils.fuse_min_lvl fuse_min_lvl, db_devils.parent parent_id, "
		"db_devils.fuse_max_lvl fuse_max_lvl, db_devils.genus genus_id, "
		"db_devils.fuse_chance fuse_chance, db_devils.breath breath, "
		"db_devils.wing wing, db_devils.pierce pierce, db_devils.fang fang, "
		"db_devils.claw claw, db_devils.needle needle, db_devils.sword sword, "
		"db_devils.strange strange, db_devils.eye eye, db_devils.notes notes, "
		"db_devils.fusion_cost fuse_cost, db_devils.mashou_gem mashou_gem "
		"FROM db_devils LEFT JOIN db_genus ON db_devils.genus = db_genus.id "
		"LEFT JOIN db_growth_type ON db_devils.growth = db_growth_type.id "
		"LEFT JOIN db_mashou ON db_devils.mashou = db_mashou.id LEFT JOIN "
		"db_equip_type ON db_mashou.equip_type = db_equip_type.id ORDER BY "
		"db_devils.genus, db_devils.lvl";
	sql = sql.replace("{$lang}", lang);

	if( !query.prepare(sql) )
		return herror_sql(db, "simulator_cache action", tr("SQL error for "
			"action %1: %2").arg(i).arg( query.lastError().text() ));

	if( !query.exec() )
		return herror_sql(db, "simulator_cache action", tr("SQL error for "
			"action %1: %2").arg(i).arg( query.lastError().text() ));

	QVariantList devils;
	while( query.next() )
	{
		QSqlRecord record = query.record();

		QVariantMap devil;
		for(int j = 0; j < record.count(); j++)
			devil[record.fieldName(j)] = record.value(j);

		sql = "SELECT skill, lvl FROM db_devil_skills WHERE devil = :devil";

		QSqlQuery query2(db);
		if( !query2.prepare(sql) )
			return herror_sql(db, "simulator_cache action", tr("SQL error for "
				"action %1: %2").arg(i).arg( query2.lastError().text() ));

		query2.bindValue(":devil", devil.value("id"), QSql::In);

		if( !query2.exec() )
			return herror_sql(db, "simulator_cache action", tr("SQL error for "
				"action %1: %2").arg(i).arg( query2.lastError().text() ));

		QVariantList devil_skills;
		while( query2.next() )
		{
			QSqlRecord record2 = query2.record();

			QVariantMap devil_skill;
			for(int j = 0; j < record2.count(); j++)
				devil_skill[record2.fieldName(j)] = record2.value(j);

			devil_skills << devil_skill;
		}

		devil["skills"] = devil_skills;

		sql = "SELECT trait FROM db_devil_traits WHERE devil = :devil";

		if( !query2.prepare(sql) )
			return herror_sql(db, "simulator_cache action", tr("SQL error for "
				"action %1: %2").arg(i).arg( query2.lastError().text() ));

		query2.bindValue(":devil", devil.value("id"), QSql::In);

		if( !query2.exec() )
			return herror_sql(db, "simulator_cache action", tr("SQL error for "
				"action %1: %2").arg(i).arg( query2.lastError().text() ));

		QVariantList devil_traits;
		while( query2.next() )
			devil_traits << query2.value(0);

		devil["traits"] = devil_traits;

		devils << devil;
	}

	map["devils"] = devils;


	sql = "SELECT id, name_ja FROM db_genus";

	if( !query.prepare(sql) )
		return herror_sql(db, "simulator_cache action", tr("SQL error for "
			"action %1: %2").arg(i).arg( query.lastError().text() ));

	if( !query.exec() )
		return herror_sql(db, "simulator_cache action", tr("SQL error for "
			"action %1: %2").arg(i).arg( query.lastError().text() ));

	QVariantMap genus;
	while( query.next() )
		genus[query.value(1).toString()] = query.value(0);

	map["genus"] = genus;

	Q_ASSERT( genus.contains(QString::fromUtf8("精霊")) );

	sql = "SELECT id, name_ja FROM db_devils WHERE genus = :genus";

	if( !query.prepare(sql) )
		return herror_sql(db, "simulator_cache action", tr("SQL error for "
			"action %1: %2").arg(i).arg( query.lastError().text() ));

	query.bindValue(":genus", genus.value(QString::fromUtf8("精霊")), QSql::In);

	if( !query.exec() )
		return herror_sql(db, "simulator_cache action", tr("SQL error for "
			"action %1: %2").arg(i).arg( query.lastError().text() ));

	QVariantMap seirei;
	while( query.next() )
		seirei[query.value(1).toString()] = query.value(0);

	map["seirei"] = seirei;

	// Update the cache
	simulator_cache[lang] = map;

	return map;
}
Ejemplo n.º 10
0
bool ContextPrivate::loadSettings( QSettings &pSettings, bool pPartial )
{
	QSettings		CFG( pSettings.fileName(), pSettings.format() );

	QList<QSharedPointer<fugio::NodeInterface>>		NodeLst;

	QMap<QUuid,QUuid>		NodeMap;
	QMap<QUuid,QUuid>		PinsMap;

	pSettings.beginGroup( "nodes" );

	for( const QString &K : pSettings.childKeys() )
	{
		QString			NodeName     = K;
		const QUuid		NodeOrigUuid = fugio::utils::string2uuid( K );
		const QUuid		NodeUuid     = ( findNode( NodeOrigUuid ).isNull() ? NodeOrigUuid : QUuid::createUuid() );
		const QUuid		ControlUuid  = fugio::utils::string2uuid( pSettings.value( K ).toString() );
		QVariantHash	NodeData;

		if( CFG.childGroups().contains( K ) )
		{
			CFG.beginGroup( K );

			NodeName = CFG.value( "name", NodeName ).toString();

			if( CFG.childGroups().contains( "settings" ) )
			{
				QStringList		VarBse;

				CFG.beginGroup( "settings" );

				loadNodeSettings( CFG, NodeData, VarBse );

				CFG.endGroup();
			}

			CFG.endGroup();
		}

		QSharedPointer<fugio::NodeInterface>	N = createNode( NodeName, NodeUuid, ControlUuid, NodeData );

		if( !N )
		{
			qWarning() << "Can't create node" << NodeName;

			continue;
		}

		NodeLst << N;

		NodeMap.insert( NodeUuid, NodeOrigUuid );
	}

	pSettings.endGroup();

	//-------------------------------------------------------------------------

	for( QSharedPointer<fugio::NodeInterface> N : NodeLst )
	{
		const QUuid		NodeUuid = N->uuid();
		const QUuid		OrigUuid = NodeMap.value( N->uuid() );

		// do this before we registerNode() to give everyone a chance to record the relabel
		// and look up data

		if( NodeUuid != OrigUuid )
		{
			emit qobject()->nodeRelabled( OrigUuid, NodeUuid );
		}

		registerNode( N );

		pSettings.beginGroup( fugio::utils::uuid2string( OrigUuid ) );

		N->loadSettings( pSettings, PinsMap, pPartial );

		pSettings.endGroup();
	}

	//-------------------------------------------------------------------------

//	CFG.beginGroup( "connections" );

//	foreach( const QString &NodeDst, CFG.childGroups() )
//	{
//		CF2.beginGroup( NodeDst );

//		foreach( const QString &PinDst, CFG.childKeys() )
//		{
//			QStringList		 SrcList = CFG.value( PinDst ).toString().split( '\\' );

//			if( SrcList.size() != 2 )
//			{
//				continue;
//			}

//			mConnectionMap.insert( ConnectionPair( SrcList.at( 0 ), SrcList.at( 1 ) ), ConnectionPair( NodeDst, PinDst ) );
//		}

//		CFG.endGroup();
//	}

//	CFG.endGroup();

	//-------------------------------------------------------------------------

	pSettings.beginGroup( "connections" );

	for( const QString &G : pSettings.childKeys() )
	{
		QUuid		SrcId = PinsMap.value( fugio::utils::string2uuid( G ) );

		PinHash::iterator		SrcIt = mPinHash.find( SrcId );

		if( SrcIt == mPinHash.end() )
		{
			qWarning() << "SRC PIN NOT FOUND" << SrcId;

			continue;
		}

		QSharedPointer<fugio::PinInterface>	SrcP = SrcIt.value();

		if( SrcP == 0 )
		{
			continue;
		}

		QUuid		DstId = PinsMap.value( fugio::utils::string2uuid( pSettings.value( G ).toString() ) );

		PinHash::iterator		DstIt = mPinHash.find( DstId );

		if( DstIt == mPinHash.end() )
		{
			qWarning() << "DST PIN NOT FOUND" << DstId;

			continue;
		}

		QSharedPointer<fugio::PinInterface>	DstP = DstIt.value();

		if( DstP == 0 )
		{
			continue;
		}

		connectPins( SrcP->globalId(), DstP->globalId() );
	}

	pSettings.endGroup();

	return( true );
}
Ejemplo n.º 11
0
QString Conversion::computeAutoColor(const wvWare::Word97::SHD& shd, const QString& bgColor, const QString& fontColor)
{
    // NOTE: by definition, see
    // http://social.msdn.microsoft.com/Forums/en-US/os_binaryfile/thread/a02a9a24-efb6-4ba0-a187-0e3d2704882b

#ifdef CONVERSION_DEBUG_SHD
    qDebug() << Q_FUNC_INFO;
    qDebug() << "bgColor:" << bgColor;
    qDebug() << "fontColor:" << fontColor;
    qDebug() << "ipat:" << shd.ipat;
    qDebug() << "cvBack:" << hex << shd.cvBack;
    qDebug() << "cvFore:" << hex << shd.cvFore;
#endif

    if (shd.isShdAuto() || shd.isShdNil()) {
        return contrastColor(bgColor);
    }

    QColor foreColor;
    QColor backColor;

    if (shd.cvFore == wvWare::Word97::cvAuto) {
        if (fontColor.isEmpty()) {
            foreColor = QColor(contrastColor(bgColor));
        } else {
            foreColor = QColor(fontColor);
        }
    } else {
        foreColor = QColor(QRgb(shd.cvFore));
    }

    if (shd.cvBack == wvWare::Word97::cvAuto) {
        if (bgColor.isEmpty()) {
            backColor = QColor(Qt::white).name();
        } else {
            backColor = QColor(bgColor);
        }
    } else {
        backColor = QColor(QRgb(shd.cvBack));
    }

    int luminosity = 0;

    if (shd.ipat == ipatAuto) {
        luminosity = luma(backColor);
    }
    else if (shd.ipat == ipatSolid) {
        luminosity = luma(foreColor);
    }
    else if ((shd.ipat > 13) && (shd.ipat < 34)) {
        luminosity = 61;
    } else {
        if (SHADING_TABLE.contains(shd.ipat)) {
            qreal pct = SHADING_TABLE.value(shd.ipat);
            luminosity = yMix( luma(foreColor), luma(backColor), pct);
        } else {
            // this should not happen, but it's binary data
            luminosity = 61;
        }
    }

#ifdef CONVERSION_DEBUG_SHD
    qDebug() << "ooooooooooooooooooooooooooooooo    chp: oooooooooooooooo bgColor:" << bgColor;
    qDebug() << "fontColor:" << fontColor;
    qDebug() << (shd.cvFore == wvWare::Word97::cvAuto);
    qDebug() << (shd.cvBack == wvWare::Word97::cvAuto);
    qDebug() << "ipat" << shd.ipat;
    qDebug() << "fore" << QString::number(shd.cvFore | 0xff000000, 16).right(6) << foreColor.name();
    qDebug() << "back" << QString::number(shd.cvBack | 0xff000000, 16).right(6) << backColor.name();
    qDebug() << "luminosity " << luminosity;
#endif

    if (luminosity <= 60) { // it is dark color
        // window background color
        return QColor(Qt::white).name();
    } else {
        // window text color
        return QColor(Qt::black).name();
    }

} //computeAutoColor
Ejemplo n.º 12
0
QVariantMap QgsSplitWithLinesAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
{
  std::unique_ptr< QgsFeatureSource > source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
  if ( !source )
    throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );

  std::unique_ptr< QgsFeatureSource > linesSource( parameterAsSource( parameters, QStringLiteral( "LINES" ), context ) );
  if ( !linesSource )
    throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "LINES" ) ) );

  bool sameLayer = parameters.value( QStringLiteral( "INPUT" ) ) == parameters.value( QStringLiteral( "LINES" ) );

  QString dest;
  std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, source->fields(),
                                          QgsWkbTypes::multiType( source->wkbType() ),  source->sourceCrs() ) );
  if ( !sink )
    throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );

  QgsSpatialIndex spatialIndex;
  QMap< QgsFeatureId, QgsGeometry > splitGeoms;
  QgsFeatureRequest request;
  request.setSubsetOfAttributes( QgsAttributeList() );
  request.setDestinationCrs( source->sourceCrs(), context.transformContext() );

  QgsFeatureIterator splitLines = linesSource->getFeatures( request );
  QgsFeature aSplitFeature;
  while ( splitLines.nextFeature( aSplitFeature ) )
  {
    if ( feedback->isCanceled() )
    {
      break;
    }

    splitGeoms.insert( aSplitFeature.id(), aSplitFeature.geometry() );
    spatialIndex.addFeature( aSplitFeature );
  }

  QgsFeature outFeat;
  QgsFeatureIterator features = source->getFeatures();

  double step = source->featureCount() > 0 ? 100.0 / source->featureCount() : 1;
  int i = 0;
  QgsFeature inFeatureA;
  while ( features.nextFeature( inFeatureA ) )
  {
    i++;
    if ( feedback->isCanceled() )
    {
      break;
    }

    if ( !inFeatureA.hasGeometry() )
    {
      sink->addFeature( inFeatureA, QgsFeatureSink::FastInsert );
      continue;
    }

    QgsGeometry inGeom = inFeatureA.geometry();
    outFeat.setAttributes( inFeatureA.attributes() );

    QVector< QgsGeometry > inGeoms = inGeom.asGeometryCollection();

    const QgsFeatureIds lines = spatialIndex.intersects( inGeom.boundingBox() ).toSet();
    if ( !lines.empty() ) // has intersection of bounding boxes
    {
      QVector< QgsGeometry > splittingLines;

      // use prepared geometries for faster intersection tests
      std::unique_ptr< QgsGeometryEngine > engine;

      for ( QgsFeatureId line : lines )
      {
        // check if trying to self-intersect
        if ( sameLayer && inFeatureA.id() == line )
          continue;

        QgsGeometry splitGeom = splitGeoms.value( line );
        if ( !engine )
        {
          engine.reset( QgsGeometry::createGeometryEngine( inGeom.constGet() ) );
          engine->prepareGeometry();
        }

        if ( engine->intersects( splitGeom.constGet() ) )
        {
          QVector< QgsGeometry > splitGeomParts = splitGeom.asGeometryCollection();
          splittingLines.append( splitGeomParts );
        }
      }

      if ( !splittingLines.empty() )
      {
        for ( const QgsGeometry &splitGeom : qgis::as_const( splittingLines ) )
        {
          QVector<QgsPointXY> splitterPList;
          QVector< QgsGeometry > outGeoms;

          // use prepared geometries for faster intersection tests
          std::unique_ptr< QgsGeometryEngine > splitGeomEngine( QgsGeometry::createGeometryEngine( splitGeom.constGet() ) );
          splitGeomEngine->prepareGeometry();
          while ( !inGeoms.empty() )
          {
            if ( feedback->isCanceled() )
            {
              break;
            }

            QgsGeometry inGeom = inGeoms.takeFirst();
            if ( !inGeom )
              continue;

            if ( splitGeomEngine->intersects( inGeom.constGet() ) )
            {
              QgsGeometry before = inGeom;
              if ( splitterPList.empty() )
              {
                const QgsCoordinateSequence sequence = splitGeom.constGet()->coordinateSequence();
                for ( const QgsRingSequence &part : sequence )
                {
                  for ( const QgsPointSequence &ring : part )
                  {
                    for ( const QgsPoint &pt : ring )
                    {
                      splitterPList << QgsPointXY( pt );
                    }
                  }
                }
              }

              QVector< QgsGeometry > newGeometries;
              QVector<QgsPointXY> topologyTestPoints;
              QgsGeometry::OperationResult result = inGeom.splitGeometry( splitterPList, newGeometries, false, topologyTestPoints );

              // splitGeometry: If there are several intersections
              // between geometry and splitLine, only the first one is considered.
              if ( result == QgsGeometry::Success ) // split occurred
              {
                if ( inGeom.isGeosEqual( before ) )
                {
                  // bug in splitGeometry: sometimes it returns 0 but
                  // the geometry is unchanged
                  outGeoms.append( inGeom );
                }
                else
                {
                  inGeoms.append( inGeom );
                  inGeoms.append( newGeometries );
                }
              }
              else
              {
                outGeoms.append( inGeom );
              }
            }
            else
            {
              outGeoms.append( inGeom );
            }

          }
          inGeoms = outGeoms;
        }
      }
    }

    QVector< QgsGeometry > parts;
    for ( const QgsGeometry &aGeom : qgis::as_const( inGeoms ) )
    {
      if ( feedback->isCanceled() )
      {
        break;
      }

      bool passed = true;
      if ( QgsWkbTypes::geometryType( aGeom.wkbType() ) == QgsWkbTypes::LineGeometry )
      {
        int numPoints = aGeom.constGet()->nCoordinates();

        if ( numPoints <= 2 )
        {
          if ( numPoints == 2 )
            passed = !static_cast< const QgsCurve * >( aGeom.constGet() )->isClosed(); // tests if vertex 0 = vertex 1
          else
            passed = false; // sometimes splitting results in lines of zero length
        }
      }

      if ( passed )
        parts.append( aGeom );
    }

    for ( const QgsGeometry &g : parts )
    {
      outFeat.setGeometry( g );
      sink->addFeature( outFeat, QgsFeatureSink::FastInsert );
    }

    feedback->setProgress( i * step );
  }

  QVariantMap outputs;
  outputs.insert( QStringLiteral( "OUTPUT" ), dest );
  return outputs;
}
Ejemplo n.º 13
0
bool QXmppSaslClientDigestMd5::respond(const QByteArray &challenge, QByteArray &response)
{
    Q_UNUSED(challenge);
    const QByteArray digestUri = QString("%1/%2").arg(serviceType(), host()).toUtf8();

    if (m_step == 0) {
        response = QByteArray();
        m_step++;
        return true;
    } else if (m_step == 1) {
        const QMap<QByteArray, QByteArray> input = QXmppSaslDigestMd5::parseMessage(challenge);

        if (!input.contains("nonce")) {
            warning("QXmppSaslClientDigestMd5 : Invalid input on step 1");
            return false;
        }

        // determine realm
        const QByteArray realm = input.value("realm");

        // determine quality of protection
        const QList<QByteArray> qops = input.value("qop", "auth").split(',');
        if (!qops.contains("auth")) {
            warning("QXmppSaslClientDigestMd5 : Invalid quality of protection");
            return false;
        }

        m_nonce = input.value("nonce");
        m_secret = QCryptographicHash::hash(
            username().toUtf8() + ":" + realm + ":" + password().toUtf8(),
            QCryptographicHash::Md5);

        // Build response
        QMap<QByteArray, QByteArray> output;
        output["username"] = username().toUtf8();
        if (!realm.isEmpty())
            output["realm"] = realm;
        output["nonce"] = m_nonce;
        output["qop"] = "auth";
        output["cnonce"] = m_cnonce;
        output["nc"] = m_nc;
        output["digest-uri"] = digestUri;
        output["response"] = calculateDigest("AUTHENTICATE", digestUri, m_secret, m_nonce, m_cnonce, m_nc);
        output["charset"] = "utf-8";

        response = QXmppSaslDigestMd5::serializeMessage(output);
        m_step++;
        return true;
    } else if (m_step == 2) {
        const QMap<QByteArray, QByteArray> input = QXmppSaslDigestMd5::parseMessage(challenge);

        // check new challenge
        if (input.value("rspauth") != calculateDigest(QByteArray(), digestUri, m_secret, m_nonce, m_cnonce, m_nc)) {
            warning("QXmppSaslClientDigestMd5 : Invalid challenge on step 2");
            return false;
        }

        response = QByteArray();
        m_step++;
        return true;
    } else {
        warning("QXmppSaslClientDigestMd5 : Invalid step");
        return false;
    }
}
Ejemplo n.º 14
0
const PalettePreset::Coeffs PalettePreset::CoeffsGet(const QString &name)
{
    return presets.value(name);
}
Ejemplo n.º 15
0
QHash <ProjectClip *, AbstractClipJob *> FilterJob::prepareJob(QList <ProjectClip*> clips, QStringList parameters)
{
    QHash <ProjectClip *, AbstractClipJob *> jobs;
    QStringList sources;
    for (int i = 0; i < clips.count(); i++) {
        sources << clips.at(i)->url().toLocalFile();
    }
    QString filterName = parameters.first();
    if (filterName == QLatin1String("framebuffer")) {
        QMap <QString, QString> producerParams = QMap <QString, QString> ();
        QMap <QString, QString> filterParams = QMap <QString, QString> ();
        QMap <QString, QString> consumerParams = QMap <QString, QString> ();
        QMap <QString, QString> extraParams = QMap <QString, QString> ();
        producerParams.insert(QStringLiteral("in"), QStringLiteral("0"));
        producerParams.insert(QStringLiteral("out"), QStringLiteral("-1"));
        extraParams.insert(QStringLiteral("projecttreefilter"), QStringLiteral("1"));
        extraParams.insert(QStringLiteral("producer_profile"), QStringLiteral("1"));
        for (int i = 0; i < clips.count(); i++) {
            QString prodstring = QString("framebuffer:" + sources.at(i) + "?-1");
            producerParams.insert(QStringLiteral("producer"), prodstring);
            consumerParams.insert(QStringLiteral("consumer"), "xml:" + sources.at(i) + ".mlt");
            ProjectClip *clip = clips.at(i);
            MeltJob *job = new MeltJob(clip->clipType(), clip->clipId(), producerParams, filterParams, consumerParams, extraParams);
            job->description = i18n("Reverse clip");
            job->setAddClipToProject(true);
            jobs.insert(clip, job);
        }
        return jobs;
    }
    if (filterName == QLatin1String("motion_est")) {
        // Show config dialog
        QPointer<QDialog> d = new QDialog(QApplication::activeWindow());
        Ui::SceneCutDialog_UI ui;
        ui.setupUi(d);
        // Set  up categories
        for (int i = 0; i < 5; ++i) {
            ui.marker_type->insertItem(i, i18n("Category %1", i));
            ui.marker_type->setItemData(i, CommentedTime::markerColor(i), Qt::DecorationRole);
        }
        ui.marker_type->setCurrentIndex(KdenliveSettings::default_marker_type());
        if (d->exec() != QDialog::Accepted) {
            delete d;
            return jobs;
        }
        // Autosplit filter
        QMap <QString, QString> producerParams = QMap <QString, QString> ();
        QMap <QString, QString> filterParams = QMap <QString, QString> ();
        QMap <QString, QString> consumerParams = QMap <QString, QString> ();
        
        // Producer params
        // None

        // Filter params, use a smaller region of the image to speed up operation
        // In fact, it's faster to rescale whole image than using part of it (bounding=\"25%x25%:15%x15\")
        filterParams.insert(QStringLiteral("filter"), filterName);
        filterParams.insert(QStringLiteral("shot_change_list"), QStringLiteral("0"));
        filterParams.insert(QStringLiteral("denoise"), QStringLiteral("0"));
        
        // Consumer
        consumerParams.insert(QStringLiteral("consumer"), QStringLiteral("null"));
        consumerParams.insert(QStringLiteral("all"), QStringLiteral("1"));
        consumerParams.insert(QStringLiteral("terminate_on_pause"), QStringLiteral("1"));
        consumerParams.insert(QStringLiteral("real_time"), QStringLiteral("-1"));
        // We just want to find scene change, set all mathods to the fastests
        consumerParams.insert(QStringLiteral("rescale"), QStringLiteral("nearest"));
        consumerParams.insert(QStringLiteral("deinterlace_method"), QStringLiteral("onefield"));
        consumerParams.insert(QStringLiteral("top_field_first"), QStringLiteral("-1"));
        
        // Extra
        QMap <QString, QString> extraParams;
        extraParams.insert(QStringLiteral("key"), QStringLiteral("shot_change_list"));
        extraParams.insert(QStringLiteral("projecttreefilter"), QStringLiteral("1"));
        QString keyword(QStringLiteral("%count"));
        extraParams.insert(QStringLiteral("resultmessage"), i18n("Found %1 scenes.", keyword));
        extraParams.insert(QStringLiteral("resize_profile"), QStringLiteral("160"));
        if (ui.store_data->isChecked()) {
            // We want to save result as clip metadata
            extraParams.insert(QStringLiteral("storedata"), QStringLiteral("1"));
        }
        if (ui.zone_only->isChecked()) {
            // We want to analyze only clip zone
            extraParams.insert(QStringLiteral("zoneonly"), QStringLiteral("1"));
        }
        if (ui.add_markers->isChecked()) {
            // We want to create markers
            extraParams.insert(QStringLiteral("addmarkers"), QString::number(ui.marker_type->currentIndex()));
            extraParams.insert(QStringLiteral("label"), i18n("Scene "));
        }
        if (ui.cut_scenes->isChecked()) {
            // We want to cut scenes
            extraParams.insert(QStringLiteral("cutscenes"), QStringLiteral("1"));
        }
        delete d;
        
        for (int i = 0; i < clips.count(); i++) {
            // Set clip specific infos

            // in and out
            int in = 0;
            int out = -1;
            ProjectClip *clip = clips.at(i);
            if (extraParams.contains(QStringLiteral("zoneonly"))) {
                // Analyse clip zone only, remove in / out and replace with zone
                QPoint zone = clip->zone();
                in = zone.x();
                out = zone.y();
            }
            producerParams.insert(QStringLiteral("in"), QString::number(in));
            producerParams.insert(QStringLiteral("out"), QString::number(out));
            producerParams.insert(QStringLiteral("producer"), sources.at(i));
            
            // Destination
            // Since this job is only doing analysis, we have a null consumer and no destination
            MeltJob *job = new MeltJob(clip->clipType(), clip->clipId(), producerParams, filterParams, consumerParams, extraParams);
            job->description = i18n("Auto split");
            jobs.insert(clip, job);
        }
        return jobs;
    }
    if (filterName == QLatin1String("vidstab")) {
        // vidstab 
        QPointer<ClipStabilize> d = new ClipStabilize(sources, filterName);
        if (d->exec() == QDialog::Accepted) {
            QMap <QString, QString> producerParams = d->producerParams();
            QMap <QString, QString> filterParams = d->filterParams();
            QMap <QString, QString> consumerParams = d->consumerParams();
            QMap <QString, QString> extraParams;
            extraParams.insert(QStringLiteral("producer_profile"), QStringLiteral("1"));
            QString destination = d->destination();
            QUrl trffile;
            for (int i = 0; i < clips.count(); i++) {
                // Set clip specific infos

                // in and out
                int in = 0;
                int out = -1;
                ProjectClip *clip = clips.at(i);
                if (extraParams.contains(QStringLiteral("zoneonly"))) {
                    // Analyse clip zone only, remove in / out and replace with zone
                    QPoint zone = clip->zone();
                    in = zone.x();
                    out = zone.y();
                }
                producerParams.insert(QStringLiteral("in"), QString::number(in));
                producerParams.insert(QStringLiteral("out"), QString::number(out));
                producerParams.insert(QStringLiteral("producer"), sources.at(i));

                // Consumer
                QString consumerName = consumerParams.value(QStringLiteral("consumer"));
                if (clips.count() == 1) {
                    // We only have one clip, destination points to the final url
                    consumerParams.insert(QStringLiteral("consumer"), consumerName + ':' + destination);
                    trffile = QUrl::fromLocalFile(destination + ".trf");
                } else {
                    // Filter several clips, destination points to a folder
                    QString mltfile = destination + clip->url().fileName() + ".mlt";
                    consumerParams.insert(QStringLiteral("consumer"), consumerName + ':' + mltfile);
                    trffile = QUrl::fromLocalFile(mltfile + ".trf");
                }
                // Append a 'filename' parameter for saving vidstab data
                filterParams.insert(QStringLiteral("filename"), trffile.path());
                MeltJob *job = new MeltJob(clip->clipType(), clip->clipId(), producerParams, filterParams, consumerParams, extraParams);
                job->setAddClipToProject(d->autoAddClip());
                job->description = d->desc();
                jobs.insert(clip, job);
            }
        }
        delete d;
        return jobs;
    }
    return jobs;
}
Ejemplo n.º 16
0
void TrackerClient::httpRequestDone(bool error)
{
    if (lastTrackerRequest) {
        emit stopped();
        return;
    }

    if (error) {
        emit connectionError(http.error());
        return;
    }

    QByteArray response = http.readAll();
    http.abort();

    BencodeParser parser;
    if (!parser.parse(response)) {
        qWarning("Error parsing bencode response from tracker: %s",
                 qPrintable(parser.errorString()));
        http.abort();
        return;
    }

    QMap<QByteArray, QVariant> dict = parser.dictionary();

    if (dict.contains("failure reason")) {
        // no other items are present
        emit failure(QString::fromUtf8(dict.value("failure reason").toByteArray()));
        return;
    }

    if (dict.contains("warning message")) {
        // continue processing
        emit warning(QString::fromUtf8(dict.value("warning message").toByteArray()));
    }

    if (dict.contains("tracker id")) {
        // store it
        trackerId = dict.value("tracker id").toByteArray();
    }

    if (dict.contains("interval")) {
        // Mandatory item
        if (requestIntervalTimer != -1)
            killTimer(requestIntervalTimer);
        requestIntervalTimer = startTimer(dict.value("interval").toInt() * 1000);
    }

    if (dict.contains("peers")) {
        // store it
        peers.clear();
        QVariant peerEntry = dict.value("peers");
        if (peerEntry.type() == QVariant::List) {
            QList<QVariant> peerTmp = peerEntry.toList();
            for (int i = 0; i < peerTmp.size(); ++i) {
                TorrentPeer tmp;
                QMap<QByteArray, QVariant> peer = qVariantValue<QMap<QByteArray, QVariant> >(peerTmp.at(i));
                tmp.id = QString::fromUtf8(peer.value("peer id").toByteArray());
                tmp.address.setAddress(QString::fromUtf8(peer.value("ip").toByteArray()));
                tmp.port = peer.value("port").toInt();
                peers << tmp;
            }
        } else {
            QByteArray peerTmp = peerEntry.toByteArray();
            for (int i = 0; i < peerTmp.size(); i += 6) {
                TorrentPeer tmp;
                uchar *data = (uchar *)peerTmp.constData() + i;
                tmp.port = (int(data[4]) << 8) + data[5];
                uint ipAddress = 0;
                ipAddress += uint(data[0]) << 24;
                ipAddress += uint(data[1]) << 16;
                ipAddress += uint(data[2]) << 8;
                ipAddress += uint(data[3]);
                tmp.address.setAddress(ipAddress);
                peers << tmp;
            }
        }
        emit peerListUpdated(peers);
    }
}
Ejemplo n.º 17
0
void PropertyEditor::setObject(QObject *object)
{
    QDesignerFormWindowInterface *oldFormWindow = QDesignerFormWindowInterface::findFormWindow(m_object);
    // In the first setObject() call following the addition of a dynamic property, focus and edit it.
    const bool editNewDynamicProperty = object != 0 && m_object == object && !m_recentlyAddedDynamicProperty.isEmpty();
    m_object = object;
    m_propertyManager->setObject(object);
    QDesignerFormWindowInterface *formWindow = QDesignerFormWindowInterface::findFormWindow(m_object);
    FormWindowBase *fwb = qobject_cast<FormWindowBase *>(formWindow);
    m_treeFactory->setFormWindowBase(fwb);
    m_groupFactory->setFormWindowBase(fwb);

    storeExpansionState();

    UpdateBlocker ub(this);

    updateToolBarLabel();

    QMap<QString, QtVariantProperty *> toRemove = m_nameToProperty;

    const QDesignerDynamicPropertySheetExtension *dynamicSheet =
            qt_extension<QDesignerDynamicPropertySheetExtension*>(m_core->extensionManager(), m_object);
    const QDesignerPropertySheet *sheet = qobject_cast<QDesignerPropertySheet*>(m_core->extensionManager()->extension(m_object, Q_TYPEID(QDesignerPropertySheetExtension)));

    // Optimizization: Instead of rebuilding the complete list every time, compile a list of properties to remove,
    // remove them, traverse the sheet, in case property exists just set a value, otherwise - create it.
    QExtensionManager *m = m_core->extensionManager();

    m_propertySheet = qobject_cast<QDesignerPropertySheetExtension*>(m->extension(object, Q_TYPEID(QDesignerPropertySheetExtension)));
    if (m_propertySheet) {
        const int propertyCount = m_propertySheet->count();
        for (int i = 0; i < propertyCount; ++i) {
            if (!m_propertySheet->isVisible(i))
                continue;

            const QString propertyName = m_propertySheet->propertyName(i);
            if (m_propertySheet->indexOf(propertyName) != i)
                continue;
            const QString groupName = m_propertySheet->propertyGroup(i);
            const QMap<QString, QtVariantProperty *>::const_iterator rit = toRemove.constFind(propertyName);
            if (rit != toRemove.constEnd()) {
                QtVariantProperty *property = rit.value();
                if (m_propertyToGroup.value(property) == groupName && toBrowserType(m_propertySheet->property(i), propertyName) == property->propertyType())
                    toRemove.remove(propertyName);
            }
        }
    }

    QMapIterator<QString, QtVariantProperty *> itRemove(toRemove);
    while (itRemove.hasNext()) {
        itRemove.next();

        QtVariantProperty *property = itRemove.value();
        m_nameToProperty.remove(itRemove.key());
        m_propertyToGroup.remove(property);
        delete property;
    }

    if (oldFormWindow != formWindow)
        reloadResourceProperties();

    bool isMainContainer = false;
    if (QWidget *widget = qobject_cast<QWidget*>(object)) {
        if (QDesignerFormWindowInterface *fw = QDesignerFormWindowInterface::findFormWindow(widget)) {
            isMainContainer = (fw->mainContainer() == widget);
        }
    }
    m_groups.clear();

    if (m_propertySheet) {
        QtProperty *lastProperty = 0;
        QtProperty *lastGroup = 0;
        const int propertyCount = m_propertySheet->count();
        for (int i = 0; i < propertyCount; ++i) {
            if (!m_propertySheet->isVisible(i))
                continue;

            const QString propertyName = m_propertySheet->propertyName(i);
            if (m_propertySheet->indexOf(propertyName) != i)
                continue;
            const QVariant value = m_propertySheet->property(i);

            const int type = toBrowserType(value, propertyName);

            QtVariantProperty *property = m_nameToProperty.value(propertyName, 0);
            bool newProperty = property == 0;
            if (newProperty) {
                property = m_propertyManager->addProperty(type, propertyName);
                if (property) {
                    newProperty = true;
                    if (type == DesignerPropertyManager::enumTypeId()) {
                        const PropertySheetEnumValue e = qvariant_cast<PropertySheetEnumValue>(value);
                        QStringList names;
                        QStringListIterator it(e.metaEnum.keys());
                        while (it.hasNext())
                            names.append(it.next());
                        m_updatingBrowser = true;
                        property->setAttribute(m_strings.m_enumNamesAttribute, names);
                        m_updatingBrowser = false;
                    } else if (type == DesignerPropertyManager::designerFlagTypeId()) {
                        const PropertySheetFlagValue f = qvariant_cast<PropertySheetFlagValue>(value);
                        QList<QPair<QString, uint> > flags;
                        QStringListIterator it(f.metaFlags.keys());
                        while (it.hasNext()) {
                            const QString name = it.next();
                            const uint val = f.metaFlags.keyToValue(name);
                            flags.append(qMakePair(name, val));
                        }
                        m_updatingBrowser = true;
                        QVariant v;
                        qVariantSetValue(v, flags);
                        property->setAttribute(m_strings.m_flagsAttribute, v);
                        m_updatingBrowser = false;
                    }
                }
            }

            if (property != 0) {
                const bool dynamicProperty = (dynamicSheet && dynamicSheet->isDynamicProperty(i))
                            || (sheet && sheet->isDefaultDynamicProperty(i));
                switch (type) {
                case QVariant::Palette:
                    setupPaletteProperty(property);
                    break;
                case QVariant::KeySequence:
                    //addCommentProperty(property, propertyName);
                    break;
                default:
                    break;
                }
                if (type == QVariant::String || type == qMetaTypeId<PropertySheetStringValue>())
                    setupStringProperty(property, isMainContainer);
                property->setAttribute(m_strings.m_resettableAttribute, m_propertySheet->hasReset(i));

                const QString groupName = m_propertySheet->propertyGroup(i);
                QtVariantProperty *groupProperty = 0;

                if (newProperty) {
                    QMap<QString, QtVariantProperty*>::const_iterator itPrev = m_nameToProperty.insert(propertyName, property);
                    m_propertyToGroup[property] = groupName;
                    if (m_sorting) {
                        QtProperty *previous = 0;
                        if (itPrev != m_nameToProperty.constBegin())
                            previous = (--itPrev).value();
                        m_currentBrowser->insertProperty(property, previous);
                    }
                }
                const QMap<QString, QtVariantProperty*>::const_iterator gnit = m_nameToGroup.constFind(groupName);
                if (gnit != m_nameToGroup.constEnd()) {
                    groupProperty = gnit.value();
                } else {
                    groupProperty = m_propertyManager->addProperty(QtVariantPropertyManager::groupTypeId(), groupName);
                    QtBrowserItem *item = 0;
                    if (!m_sorting)
                         item = m_currentBrowser->insertProperty(groupProperty, lastGroup);
                    m_nameToGroup[groupName] = groupProperty;
                    m_groups.append(groupProperty);
                    if (dynamicProperty)
                        m_dynamicGroup = groupProperty;
                    if (m_currentBrowser == m_treeBrowser && item) {
                        m_treeBrowser->setBackgroundColor(item, propertyColor(groupProperty));
                        groupProperty->setModified(true);
                    }
                }
                /*  Group changed or new group. Append to last subproperty of
                 * that group. Note that there are cases in which a derived
                 * property sheet appends fake properties for the class
                 * which will appear after the layout group properties
                 * (QWizardPage). To make them appear at the end of the
                 * actual class group, goto last element. */
                if (lastGroup != groupProperty) {
                    lastGroup = groupProperty;
                    lastProperty = 0;  // Append at end
                    const QList<QtProperty*> subProperties = lastGroup->subProperties();
                    if (!subProperties.empty())
                        lastProperty = subProperties.back();
                    lastGroup = groupProperty;
                }
                if (!m_groups.contains(groupProperty))
                    m_groups.append(groupProperty);
                if (newProperty)
                    groupProperty->insertSubProperty(property, lastProperty);

                lastProperty = property;

                updateBrowserValue(property, value);

                property->setModified(m_propertySheet->isChanged(i));
                if (propertyName == QLatin1String("geometry") && type == QVariant::Rect) {
                    QList<QtProperty *> subProperties = property->subProperties();
                    foreach (QtProperty *subProperty, subProperties) {
                        const QString subPropertyName = subProperty->propertyName();
                        if (subPropertyName == QLatin1String("X") || subPropertyName == QLatin1String("Y"))
                            subProperty->setEnabled(!isMainContainer);
                    }
                }
            } else {
                qWarning("%s", qPrintable(msgUnsupportedType(propertyName, type)));
            }
        }
Ejemplo n.º 18
0
Archivo: job.cpp Proyecto: JoelB/BITS
bool Job::generateReport(QDateTime startDate,QDateTime endDate,QString filename)
{
	QString currentLine;
	QStringList sessionParts;
	int taskId;

	QMultiMap<int,taskSession> taskSessions;
	
	QFile sessionFile(attributeValues["Filename"].toString().replace(QString(".xml"),QString(".session")));
	if (!sessionFile.open(QIODevice::ReadOnly | QIODevice::Text))
		qDebug() << "Failed to session file!";

	while (!sessionFile.atEnd())
	{
		currentLine = QString(sessionFile.readLine());
		sessionParts = currentLine.split("%");
		taskSession tempsession;
		taskId = sessionParts.at(0).toInt();
		tempsession.start = QDateTime::fromString(sessionParts.at(1),Qt::ISODate);
		tempsession.end = QDateTime::fromString(sessionParts.at(2),Qt::ISODate);
		taskSessions.insert(taskId,tempsession);
	}
	sessionFile.close();
	
	QMap<int,int> totalTimes;
	QMapIterator<int,taskSession> iter(taskSessions);
	while (iter.hasNext())
	{
		iter.next();
		int timeSum = 0;
		QList<taskSession> sessions = taskSessions.values(iter.key());
		for (int i = 0; i < sessions.size(); i++)
		{
			taskSession tempSession = sessions.at(i);
			if (tempSession.start >= startDate && tempSession.end <= endDate) // session happened completely in range
				timeSum += tempSession.start.secsTo(tempSession.end);
			else if (tempSession.start <= startDate && tempSession.end <=endDate) // started out of range, ended in range
				timeSum += startDate.secsTo(tempSession.end);
			else if (tempSession.start >= startDate && tempSession.end >= endDate) // started in range, ended out of range
				timeSum += tempSession.start.secsTo(endDate);
			else if (tempSession.start <= startDate && tempSession.end >= endDate) // continued through entire range
				timeSum += startDate.secsTo(endDate);
		}
		totalTimes.insert(iter.key(),timeSum);
	}
	
	QFile reportFile(filename);
	if (!reportFile.open(QIODevice::WriteOnly | QIODevice::Text))
	{
		qDebug() << "Failed to open new report file!";
		return false;
	}
	
	QTextStream out(&reportFile);
	out << "Job Session Report for " << startDate.toString() << " to " << endDate.toString() << "\n\n";
	out << "Job Name: " << getAttributeValue("Name").toString() << "\n";
	out << "Job Start Date: " << getAttributeValue("StartDate").toDateTime().toString() << "\n";
	out << "Job End Date: " << getAttributeValue("EndDate").toDateTime().toString() << "\n\n";
	Task *tempTask;
	int allTime = 0;
	QStringList completedTasksOutput;
	QStringList otherTasksOutput;
	for (int i=0;i<taskCount();i++)
	{
		tempTask = getTask(i);
		QString name = tempTask->getAttributeValue("Name").toString();
		QString taskNum = QString::number(tempTask->getAttributeValue("TaskID").toInt()).prepend("   ");
		
		for (int j=taskNum.size(); j < 12; j++)
			taskNum.append(" ");
		for (int j=name.size(); j < 25; j++)
			name.append(" ");
		int timeSpent = totalTimes.value(tempTask->getAttributeValue("TaskID").toInt());
		allTime += timeSpent; // keep track of total time for percentages
		QString timeTotal = QString::number(timeSpent/3600) + "hr " + QString::number((timeSpent%3600)/60) + "min " + QString::number((timeSpent%3600)%60) + "sec";

		QDateTime completedDate = QDateTime::fromString(tempTask->getAttributeValue("Completed").toString(),Qt::ISODate);
		if (completedDate >= startDate && completedDate <= endDate)
			completedTasksOutput.append(QString(taskNum + name + timeTotal));
		else if (timeSpent > 0)
			otherTasksOutput.append(QString(taskNum + name + timeTotal));
	}
	completedTasksOutput.sort();
	otherTasksOutput.sort();
	
	out << "Tasks completed during selected time:\n\n";
	out << "\tTask ID     Task Name                 Time Spent            % of Total Time\n";
	out << "\t------------------------------------------------------------------------\n";
	QString tempOutput;
	for (int i = 0; i < completedTasksOutput.size(); i++)
	{
		tempOutput = completedTasksOutput.at(i);
		for (int j = tempOutput.size(); j < 65; j++)
			tempOutput.append(" ");
		QString percentage = QString::number(((double)totalTimes.value(tempOutput.left(10).simplified().toInt())/(double)allTime)*100.0,'f',2);
		out << "\t" << tempOutput << percentage << "\n";
	}
		
	out << "\n\nTasks worked on but not completed during selected time:\n\n";
	out << "\tTask ID     Task Name                 Time Spent            % of Total Time\n";
	out << "\t------------------------------------------------------------------------\n";
	for (int i = 0; i < otherTasksOutput.size(); i++)
	{
		tempOutput = otherTasksOutput.at(i);
		for (int j = tempOutput.size(); j < 65; j++)
			tempOutput.append(" ");
		QString percentage = QString::number((double)(totalTimes.value(tempOutput.left(10).simplified().toInt())/(double)allTime)*100.0,'f',2);
		out << "\t" << tempOutput << percentage << "\n";
	}
		
	reportFile.close();
	return true;
}
Ejemplo n.º 19
0
void MusicControl::showTags() //We have to use the Phonon's metadata resolver to recup a flux's metadata
{
    QMap <QString, QString> metaData = m_c->metaData();
    QString text;
    text.append("<b>");
    if(metaData.value("TITLE") != QString::Null())
    {
        text.append(metaData.value("TITLE"));
        parentWidget()->setWindowTitle(QString("Xound - " + metaData.value("TITLE")));
    }
    else
        parentWidget()->setWindowTitle(QString("Xound - What's a life whithout music?"));
    if(metaData.value("ARTIST") != QString::Null())
        text.append(QString(" - ") + metaData.value("ARTIST"));
    text.append("</b><br>");
    if(metaData.value("TRACKNUMBER") != QString::Null())
        text.append(tr("Track ") + metaData.value("TRACKNUMBER"));
    if(metaData.value("ALBUM") != QString::Null())
        text.append(tr(" of the album ") + metaData.value("ALBUM"));
    if(metaData.value("DATE") != QString::Null())
        text.append(tr(" in ") + metaData.value("DATE"));

    m_musicTagsLabel->setText(text);
}
Ejemplo n.º 20
0
bool Dip::otherPropsChange(const QMap<QString, QString> & propsMap) {
	QString layout = modelPart()->properties().value("package", "");
	return (layout.compare(propsMap.value("package", "")) != 0);
}
Ejemplo n.º 21
0
void qMapBench() {
    QElapsedTimer timer;
    timer.start();
    QMap<int,triple> data;
    triple point;
    int i;

    for (i = 0; i < RAND_COUNT; ++i) {
        point.x = i;
        point.y = rand();
        point.z = rand();
        //printf("%d %d %d %d\n", i, point.x, point.y, point.z);
        data[i] = point;
    }
    qDebug() << Q_FUNC_INFO << "creation: elapsed" << timer.elapsed();
    timer.restart();
    foreach (const triple &t, data) {
        if (t.x % 1000 == 0)
            doSomething(t.x);
    }
#if QT_VERSION >= 0x050700
    qDebug() << "   foreach: elapsed" << timer.elapsed();
    timer.restart();
    foreach (const triple &t, qAsConst(data)) {
        if (t.x % 1000 == 0)
            doSomething(t.x);
    }
    qDebug() << "   qAsConst foreach: elapsed" << timer.elapsed();
#endif
    timer.restart();
    for( auto it = data.begin(); it != data.end(); ++it ) {
        if (it->x % 1000 == 0)
            doSomething(it->x);
    }
    qDebug() << "   range-based for: elapsed" << timer.elapsed();
#if QT_VERSION >= 0x050700
    timer.restart();
    for( auto it = qAsConst(data).begin(); it != qAsConst(data).end(); ++it ) {
        if (it->x % 1000 == 0)
            doSomething(it->x);
    }
    qDebug() << "   qAsConst range-based for: elapsed" << timer.elapsed();
#endif

    timer.restart();
    for (i = 0; i < RAND_COUNT; ++i) {
        auto it = data.find(i);
        Q_ASSERT(it.value().x == i);
        if (it->x % 1000 == 0)
            doSomething(it.value().x);
    }
    qDebug() << "   find: elapsed" << timer.elapsed();

    timer.restart();
    for (i = 0; i < RAND_COUNT; ++i) {
        auto val = data.value(i);
        if (val.x % 1000 == 0)
            doSomething(val.x);
    }
    qDebug() << "   value: elapsed" << timer.elapsed();
}
Ejemplo n.º 22
0
void DiscoverySingleDirectoryJob::directoryListingIteratedSlot(QString file, const QMap<QString, QString> &map)
{
    if (!_ignoredFirst) {
        // The first entry is for the folder itself, we should process it differently.
        _ignoredFirst = true;
        if (map.contains("permissions")) {
            auto perm = RemotePermissions::fromServerString(map.value("permissions"));
            emit firstDirectoryPermissions(perm);
            _isExternalStorage = perm.hasPermission(RemotePermissions::IsMounted);
        }
        if (map.contains("data-fingerprint")) {
            _dataFingerprint = map.value("data-fingerprint").toUtf8();
            if (_dataFingerprint.isEmpty()) {
                // Placeholder that means that the server supports the feature even if it did not set one.
                _dataFingerprint = "[empty]";
            }
        }
    } else {
        // Remove <webDAV-Url>/folder/ from <webDAV-Url>/folder/subfile.txt
        file.remove(0, _lsColJob->reply()->request().url().path().length());
        // remove trailing slash
        while (file.endsWith('/')) {
            file.chop(1);
        }
        // remove leading slash
        while (file.startsWith('/')) {
            file = file.remove(0, 1);
        }

        std::unique_ptr<csync_file_stat_t> file_stat(new csync_file_stat_t);
        file_stat->path = file.toUtf8();
        file_stat->size = -1;
        propertyMapToFileStat(map, file_stat.get());
        if (file_stat->type == ItemTypeDirectory)
            file_stat->size = 0;
        if (file_stat->type == ItemTypeSkip
            || file_stat->size == -1
            || file_stat->remotePerm.isNull()
            || file_stat->etag.isEmpty()
            || file_stat->file_id.isEmpty()) {
            _error = tr("The server file discovery reply is missing data.");
            qCWarning(lcDiscovery)
                << "Missing properties:" << file << file_stat->type << file_stat->size
                << file_stat->modtime << file_stat->remotePerm.toString()
                << file_stat->etag << file_stat->file_id;
        }

        if (_isExternalStorage && file_stat->remotePerm.hasPermission(RemotePermissions::IsMounted)) {
            /* All the entries in a external storage have 'M' in their permission. However, for all
               purposes in the desktop client, we only need to know about the mount points.
               So replace the 'M' by a 'm' for every sub entries in an external storage */
            file_stat->remotePerm.unsetPermission(RemotePermissions::IsMounted);
            file_stat->remotePerm.setPermission(RemotePermissions::IsMountedSub);
        }

        QStringRef fileRef(&file);
        int slashPos = file.lastIndexOf(QLatin1Char('/'));
        if (slashPos > -1) {
            fileRef = file.midRef(slashPos + 1);
        }
        _results.push_back(std::move(file_stat));
    }

    //This works in concerto with the RequestEtagJob and the Folder object to check if the remote folder changed.
    if (map.contains("getetag")) {
        _etagConcatenation += map.value("getetag");

        if (_firstEtag.isEmpty()) {
            _firstEtag = map.value("getetag"); // for directory itself
        }
    }
}
Ejemplo n.º 23
0
bool
ClipObject::commandEditor()
{
  PropertyEditor propertyEditor;
  QMap<QString, QVariantList> plist;
  QVariantList vlist;
  vlist.clear();
  plist["command"] = vlist;


  vlist.clear();
  vlist << QVariant("double");
  vlist << QVariant(m_opacity);
  vlist << QVariant(0.0);
  vlist << QVariant(1.0);
  vlist << QVariant(0.1); // singlestep
  vlist << QVariant(1); // decimals
  plist["opacity"] = vlist;
  
  vlist.clear();
  vlist << QVariant("color");
  Vec pcolor = m_color;
  QColor dcolor = QColor::fromRgbF(pcolor.x,
				   pcolor.y,
				   pcolor.z);
  vlist << dcolor;
  plist["color"] = vlist;
  
  vlist.clear();
  vlist << QVariant("checkbox");
  vlist << QVariant(m_apply);
  plist["apply clipping"] = vlist;

  vlist.clear();
  vlist << QVariant("int");
  vlist << QVariant(m_tfset);
  vlist << QVariant(-1);
  vlist << QVariant(15);
  plist["tfset"] = vlist;

  vlist.clear();
  vlist << QVariant("int");
  vlist << QVariant(m_thickness);
  vlist << QVariant(0);
  vlist << QVariant(200);
  plist["thickness"] = vlist;

  vlist.clear();
  vlist << QVariant("checkbox");
  vlist << QVariant(m_solidColor);
  plist["solid color"] = vlist;

  vlist.clear();
  vlist << QVariant("checkbox");
  vlist << QVariant(m_showSlice);
  plist["show slice"] = vlist;

  vlist.clear();
  vlist << QVariant("checkbox");
  vlist << QVariant(m_showThickness);
  plist["show thickness"] = vlist;

  vlist.clear();
  vlist << QVariant("combobox");
  if (m_viewportType)
    vlist << QVariant(1);
  else
    vlist << QVariant(0);
  vlist << QVariant("orthographic");
  vlist << QVariant("perspective");
  plist["camera type"] = vlist;

  vlist.clear();
  vlist << QVariant("double");
  vlist << QVariant(m_stereo);
  vlist << QVariant(0.0);
  vlist << QVariant(1.0);
  vlist << QVariant(0.1); // singlestep
  vlist << QVariant(1); // decimals
  plist["stereo"] = vlist;
  
  vlist.clear();
  vlist << QVariant("checkbox");
  vlist << QVariant(m_showOtherSlice);
  plist["show other slice"] = vlist;


  QString vpstr = QString("%1 %2 %3 %4").\
                  arg(m_viewport.x()).\
                  arg(m_viewport.y()).\
                  arg(m_viewport.z()).\
                  arg(m_viewport.w());
  vlist.clear();
  vlist << QVariant("string");
  vlist << QVariant(vpstr);
  plist["viewport"] = vlist;

  vlist.clear();
  vlist << QVariant("double");
  vlist << QVariant(m_viewportScale);
  vlist << QVariant(0.5);
  vlist << QVariant(30.0);
  vlist << QVariant(0.1); // singlestep
  vlist << QVariant(1); // decimals
  plist["viewport scale"] = vlist;  


  vlist.clear();
  QFile helpFile(":/clipobject.help");
  if (helpFile.open(QFile::ReadOnly))
    {
      QTextStream in(&helpFile);
      QString line = in.readLine();
      while (!line.isNull())
	{
	  if (line == "#begin")
	    {
	      QString keyword = in.readLine();
	      QString helptext;
	      line = in.readLine();
	      while (!line.isNull())
		{
		  helptext += line;
		  helptext += "\n";
		  line = in.readLine();
		  if (line == "#end") break;
		}
	      vlist << keyword << helptext;
	    }
	  line = in.readLine();
	}
    }
  
  plist["commandhelp"] = vlist;
  
  //---------------------
  vlist.clear();
  QString mesg;
  if (m_scale1 < 0 || m_scale2 < 0)
    mesg += QString("scales : %1 %2\n").arg(-m_scale1).arg(-m_scale2);
  else
    mesg += QString("vscales : %1 %2\n").arg(m_scale1).arg(m_scale2);

  mesg += QString("opacity : %1\n").arg(m_opacity);
  mesg += QString("position : %1 %2 %3\n").			\
    arg(m_position.x).arg(m_position.y).arg(m_position.z);

  Quaternion q = orientation();
  Vec axis;
  qreal angle;
  q.getAxisAngle(axis, angle);
  mesg += QString("rotation : %1 %2 %3 : %4\n").			\
    arg(axis.x).arg(axis.y).arg(axis.z).arg(RAD2DEG(angle));
  
  
  mesg += QString("Red axis : %1 %2 %3\n").		\
    arg(m_xaxis.x).arg(m_xaxis.y).arg(m_xaxis.z);
  mesg += QString("Green axis : %1 %2 %3\n").		\
    arg(m_yaxis.x).arg(m_yaxis.y).arg(m_yaxis.z);
  mesg += QString("Blue axis : %1 %2 %3\n").		\
    arg(m_tang.x).arg(m_tang.y).arg(m_tang.z);
  
  vlist << mesg;
  
  plist["message"] = vlist;
  //---------------------



  QStringList keys;
  keys << "apply clipping";
  keys << "solid color";
  keys << "show slice";
  keys << "show thickness";
  keys << "show other slice";
  keys << "gap";
  keys << "color";
  keys << "opacity";
  keys << "gap";
  keys << "viewport";
  keys << "tfset";
  keys << "thickness";
  keys << "viewport scale";
  keys << "camera type";
  keys << "stereo";
  keys << "gap";
  keys << "command";
  keys << "commandhelp";
  keys << "message";
  
  propertyEditor.set("Clip Plane Dialog", plist, keys);
  
  QMap<QString, QPair<QVariant, bool> > vmap;

  if (propertyEditor.exec() == QDialog::Accepted)
    vmap = propertyEditor.get();
  else
    return true;
	      
  keys = vmap.keys();

  for(int ik=0; ik<keys.count(); ik++)
    {
      QPair<QVariant, bool> pair = vmap.value(keys[ik]);
      
      
      if (pair.second)
	{
	  if (keys[ik] == "color")
	    {
	      QColor color = pair.first.value<QColor>();
	      float r = color.redF();
	      float g = color.greenF();
	      float b = color.blueF();
	      m_color = Vec(r,g,b);
	    }
	  else if (keys[ik] == "opacity")
	    m_opacity = pair.first.toDouble();
	  else if (keys[ik] == "solid color")
	    m_solidColor = pair.first.toBool();
	  else if (keys[ik] == "apply clipping")
	    m_apply = pair.first.toBool();
	  else if (keys[ik] == "show slice")
	    m_showSlice = pair.first.toBool();
	  else if (keys[ik] == "show thickness")
	    m_showThickness = pair.first.toBool();
	  else if (keys[ik] == "show other slice")
	    m_showOtherSlice = pair.first.toBool();
	  else if (keys[ik] == "tfset")
	    m_tfset = pair.first.toInt();
	  else if (keys[ik] == "thickness")
	    m_thickness = pair.first.toInt();
	  else if (keys[ik] == "viewport scale")
	    m_viewportScale = pair.first.toDouble();
	  else if (keys[ik] == "camera type")
	    m_viewportType = (pair.first.toInt() == 1);
	  else if (keys[ik] == "stereo")
	    m_stereo = pair.first.toDouble();
	  else if (keys[ik] == "viewport")
	    {
	      vpstr = pair.first.toString();
	      QStringList list = vpstr.split(" ", QString::SkipEmptyParts);
	      if (list.count() == 4)
		{
		  float x = list[0].toFloat();
		  float y = list[1].toFloat();
		  float z = list[2].toFloat();
		  float w = list[3].toFloat();
		  if (x < 0.0f || x > 1.0f ||
		      y < 0.0f || y > 1.0f ||
		      z < 0.0f || z > 1.0f ||
		      w < 0.0f || w > 1.0f)
		    QMessageBox::information(0, "",
		      QString("Values for viewport must be between 0.0 and 1.0 : %1 %2 %3 %4").\
					     arg(x).arg(y).arg(z).arg(w));
		  else
		    m_viewport = QVector4D(x,y,z,w);
		}
	      else if (list.count() == 3)
		{
		  float x = list[0].toFloat();
		  float y = list[1].toFloat();
		  float z = list[2].toFloat();
		  if (x < 0.0f || x > 1.0f ||
		      y < 0.0f || y > 1.0f ||
		      z < 0.0f || z > 1.0f)
		    QMessageBox::information(0, "",
		      QString("Values for viewport must be between 0.0 and 1.0 : %1 %2 %3").\
					     arg(x).arg(y).arg(z));
		  else
		    m_viewport = QVector4D(x,y,z,z);
		}
	      else if (list.count() == 2)
		{
		  float x = list[0].toFloat();
		  float y = list[1].toFloat();
		  if (x < 0.0f || x > 1.0f ||
		      y < 0.0f || y > 1.0f)
		    QMessageBox::information(0, "",
		      QString("Values for viewport must be between 0.0 and 1.0 : %1 %2").\
					     arg(x).arg(y));
		  else
		    m_viewport = QVector4D(x,y,0.5,0.5);
		}
	      else
		{
		  QMessageBox::information(0, "", "Switching off the viewport");
		  m_viewport = QVector4D(-1,-1,-1,-1);
		}
	    }
	}
    }

  QString cmd = propertyEditor.getCommandString();
  if (!cmd.isEmpty())
    return processCommand(cmd);
  else
    return true;

//  if (propertyEditor.exec() == QDialog::Accepted)
//    {
//      QString cmd = propertyEditor.getCommandString();
//      if (!cmd.isEmpty())
//	return processCommand(cmd);
//    }
//  else
//    return true;
}
Ejemplo n.º 24
0
// Purpose: Parsing all the folder and playlists of Traktor
// This is a complex operation since Traktor uses the concept of folders and playlist.
// A folder can contain folders and playlists. A playlist contains entries but no folders.
// In other words, Traktor uses a tree structure to organize music.
// Inner nodes represent folders while leaves are playlists.
TreeItem* TraktorFeature::parsePlaylists(QXmlStreamReader &xml) {

    qDebug() << "Process RootFolder";
    //Each playlist is unique and can be identified by a path in the tree structure.
    QString current_path = "";
    QMap<QString,QString> map;

    QString delimiter = "-->";

    TreeItem *rootItem = new TreeItem();
    TreeItem * parent = rootItem;

    bool inPlaylistTag = false;

    QSqlQuery query_insert_to_playlists(m_database);
    query_insert_to_playlists.prepare("INSERT INTO traktor_playlists (name) "
                  "VALUES (:name)");

    QSqlQuery query_insert_to_playlist_tracks(m_database);
    query_insert_to_playlist_tracks.prepare(
        "INSERT INTO traktor_playlist_tracks (playlist_id, track_id, position) "
        "VALUES (:playlist_id, :track_id, :position)");

    while (!xml.atEnd() && !m_cancelImport) {
        //read next XML element
        xml.readNext();

        if (xml.isStartElement()) {
            if (xml.name() == "NODE") {
                QXmlStreamAttributes attr = xml.attributes();
                QString name = attr.value("NAME").toString();
                QString type = attr.value("TYPE").toString();
               //TODO: What happens if the folder node is a leaf (empty folder)
               // Idea: Hide empty folders :-)
               if (type == "FOLDER") {
                    current_path += delimiter;
                    current_path += name;
                    //qDebug() << "Folder: " +current_path << " has parent " << parent->data().toString();
                    map.insert(current_path, "FOLDER");
                    TreeItem * item = new TreeItem(name,current_path, this, parent);
                    parent->appendChild(item);
                    parent = item;
               }
               if (type == "PLAYLIST") {
                    current_path += delimiter;
                    current_path += name;
                    //qDebug() << "Playlist: " +current_path << " has parent " << parent->data().toString();
                    map.insert(current_path, "PLAYLIST");

                    TreeItem * item = new TreeItem(name,current_path, this, parent);
                    parent->appendChild(item);
                    // process all the entries within the playlist 'name' having path 'current_path'
                    parsePlaylistEntries(xml, current_path,
                                         query_insert_to_playlists,
                                         query_insert_to_playlist_tracks);
                }
            }
            if (xml.name() == "ENTRY" && inPlaylistTag) {
            }
        }

        if (xml.isEndElement()) {
            if (xml.name() == "NODE") {
                if (map.value(current_path) == "FOLDER") {
                    parent = parent->parent();
                }

                //Whenever we find a closing NODE, remove the last component of the path
                int lastSlash = current_path.lastIndexOf (delimiter);
                int path_length = current_path.size();

                current_path.remove(lastSlash, path_length - lastSlash);
            }
            if (xml.name() == "PLAYLIST") {
                inPlaylistTag = false;
            }
            //We leave the infinte loop, if twe have the closing "PLAYLIST" tag
            if (xml.name() == "PLAYLISTS") {
                break;
            }
        }
    }
    return rootItem;
}
Ejemplo n.º 25
0
int main( int argc, char *argv[] )
{
#ifdef Q_OS_MACX
  // Increase file resource limits (i.e., number of allowed open files)
  // (from code provided by Larry Biehl, Purdue University, USA, from 'MultiSpec' project)
  // This is generally 256 for the soft limit on Mac
  // NOTE: setrlimit() must come *before* initialization of stdio strings,
  //       e.g. before any debug messages, or setrlimit() gets ignored
  // see: http://stackoverflow.com/a/17726104/2865523
  struct rlimit rescLimit;
  if ( getrlimit( RLIMIT_NOFILE, &rescLimit ) == 0 )
  {
    rlim_t oldSoft( rescLimit.rlim_cur );
    rlim_t oldHard( rescLimit.rlim_max );
#ifdef OPEN_MAX
    rlim_t newSoft( OPEN_MAX );
    rlim_t newHard( std::min( oldHard, newSoft ) );
#else
    rlim_t newSoft( 4096 );
    rlim_t newHard( std::min(( rlim_t )8192, oldHard ) );
#endif
    if ( rescLimit.rlim_cur < newSoft )
    {
      rescLimit.rlim_cur = newSoft;
      rescLimit.rlim_max = newHard;

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

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

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

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

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

  // initialize random number seed
  srand( time( NULL ) );

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

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

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

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

  bool myRestorePlugins = true;
  bool myCustomization = true;

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

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

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

  QString pythonfile;

  QString customizationfile;

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

  QStringList args;

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

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

      if ( arg == "--help" || arg == "-?" )
      {
        usage( args[0].toStdString() );
        return 2;
      }
      else if ( arg == "--nologo" || arg == "-n" )
      {
        myHideSplash = true;
      }
      else if ( arg == "--noplugins" || arg == "-P" )
      {
        myRestorePlugins = false;
      }
      else if ( arg == "--nocustomization" || arg == "-C" )
      {
        myCustomization = false;
      }
      else if ( i + 1 < argc && ( arg == "--snapshot" || arg == "-s" ) )
      {
        mySnapshotFileName = QDir::convertSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
      }
      else if ( i + 1 < argc && ( arg == "--width" || arg == "-w" ) )
      {
        mySnapshotWidth = QString( args[++i] ).toInt();
      }
      else if ( i + 1 < argc && ( arg == "--height" || arg == "-h" ) )
      {
        mySnapshotHeight = QString( args[++i] ).toInt();
      }
      else if ( i + 1 < argc && ( arg == "--lang" || arg == "-l" ) )
      {
        myTranslationCode = args[++i];
      }
      else if ( i + 1 < argc && ( arg == "--project" || arg == "-p" ) )
      {
        myProjectFileName = QDir::convertSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
      }
      else if ( i + 1 < argc && ( arg == "--extent" || arg == "-e" ) )
      {
        myInitialExtent = args[++i];
      }
      else if ( i + 1 < argc && ( arg == "--optionspath" || arg == "-o" ) )
      {
        optionpath = QDir::convertSeparators( QDir( args[++i] ).absolutePath() );
      }
      else if ( i + 1 < argc && ( arg == "--configpath" || arg == "-c" ) )
      {
        configpath = QDir::convertSeparators( QDir( args[++i] ).absolutePath() );
      }
      else if ( i + 1 < argc && ( arg == "--code" || arg == "-f" ) )
      {
        pythonfile = QDir::convertSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
      }
      else if ( i + 1 < argc && ( arg == "--customizationfile" || arg == "-z" ) )
      {
        customizationfile = QDir::convertSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
      }
      else
      {
        myFileList.append( QDir::convertSeparators( QFileInfo( args[i] ).absoluteFilePath() ) );
      }
    }
  }

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


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

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

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

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

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

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

// (if Windows/Mac, use icon from resource)
#if !defined(Q_WS_WIN) && !defined(Q_WS_MAC)
  myApp.setWindowIcon( QIcon( QgsApplication::iconsPath() + "qgis-icon-60x60.png" ) );
#endif

  //
  // Set up the QSettings environment must be done after qapp is created
  QCoreApplication::setOrganizationName( "QGIS" );
  QCoreApplication::setOrganizationDomain( "qgis.org" );
  QCoreApplication::setApplicationName( "QGIS2" );
  QCoreApplication::setAttribute( Qt::AA_DontShowIconsInMenus, false );

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

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

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

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

  QSettings mySettings;

  // update any saved setting for older themes to new default 'gis' theme (2013-04-15)
  if ( mySettings.contains( "/Themes" ) )
  {
    QString theme = mySettings.value( "/Themes", "default" ).toString();
    if ( theme == QString( "gis" )
         || theme == QString( "classic" )
         || theme == QString( "nkids" ) )
    {
      mySettings.setValue( "/Themes", QString( "default" ) );
    }
  }


  // custom environment variables
  QMap<QString, QString> systemEnvVars = QgsApplication::systemEnvVars();
  bool useCustomVars = mySettings.value( "qgis/customEnvVarsUse", QVariant( false ) ).toBool();
  if ( useCustomVars )
  {
    QStringList customVarsList = mySettings.value( "qgis/customEnvVars", "" ).toStringList();
    if ( !customVarsList.isEmpty() )
    {
      foreach ( const QString &varStr, customVarsList )
      {
        int pos = varStr.indexOf( QLatin1Char( '|' ) );
        if ( pos == -1 )
          continue;
        QString envVarApply = varStr.left( pos );
        QString varStrNameValue = varStr.mid( pos + 1 );
        pos = varStrNameValue.indexOf( QLatin1Char( '=' ) );
        if ( pos == -1 )
          continue;
        QString envVarName = varStrNameValue.left( pos );
        QString envVarValue = varStrNameValue.mid( pos + 1 );

        if ( systemEnvVars.contains( envVarName ) )
        {
          if ( envVarApply == "prepend" )
          {
            envVarValue += systemEnvVars.value( envVarName );
          }
          else if ( envVarApply == "append" )
          {
            envVarValue = systemEnvVars.value( envVarName ) + envVarValue;
          }
        }

        if ( systemEnvVars.contains( envVarName ) && envVarApply == "unset" )
        {
#ifdef Q_WS_WIN
          putenv( envVarName.toUtf8().constData() );
#else
          unsetenv( envVarName.toUtf8().constData() );
#endif
        }
        else
        {
#ifdef Q_WS_WIN
          if ( envVarApply != "undefined" || !getenv( envVarName.toUtf8().constData() ) )
            putenv( QString( "%1=%2" ).arg( envVarName ).arg( envVarValue ).toUtf8().constData() );
#else
          setenv( envVarName.toUtf8().constData(), envVarValue.toUtf8().constData(), envVarApply == "undefined" ? 0 : 1 );
#endif
        }
      }
    }
Ejemplo n.º 26
0
LuaSkillCard *LuaSkillCard::Parse(const QString &str) {
    QRegExp rx("#(\\w+):(.*):(.*)");
    QRegExp e_rx("#(\\w*)\\[(\\w+):(.+)\\]:(.*):(.*)");

    static QMap<QString, Card::Suit> suit_map;
    if (suit_map.isEmpty()) {
        suit_map.insert("spade", Card::Spade);
        suit_map.insert("club", Card::Club);
        suit_map.insert("heart", Card::Heart);
        suit_map.insert("diamond", Card::Diamond);
        suit_map.insert("no_suit_red", Card::NoSuitRed);
        suit_map.insert("no_suit_black", Card::NoSuitBlack);
        suit_map.insert("no_suit", Card::NoSuit);
    }

    QStringList texts;
    QString name, suit, number;
    QString subcard_str;
    QString user_string;

    if (rx.exactMatch(str)) {
        texts = rx.capturedTexts();
        name = texts.at(1);
        subcard_str = texts.at(2);
        user_string = texts.at(3);
    } else if (e_rx.exactMatch(str)) {
        texts = e_rx.capturedTexts();
        name = texts.at(1);
        suit = texts.at(2);
        number = texts.at(3);
        subcard_str = texts.at(4);
        user_string = texts.at(5);
    } else
        return NULL;

    const LuaSkillCard *c = LuaSkillCards.value(name, NULL);
    if (c == NULL)
        return NULL;

    LuaSkillCard *new_card = c->clone();

    if (subcard_str != ".")
        new_card->addSubcards(StringList2IntList(subcard_str.split("+")));

    if (!suit.isEmpty())
        new_card->setSuit(suit_map.value(suit, Card::NoSuit));
    if (!number.isEmpty()) {
        int num = 0;
        if (number == "A")
            num = 1;
        else if (number == "J")
            num = 11;
        else if (number == "Q")
            num = 12;
        else if (number == "K")
            num = 13;
        else
            num = number.toInt();

        new_card->setNumber(num);
    }

    new_card->setUserString(user_string);
    QString skillName = LuaSkillCardsSkillName.value(name, QString());
    if (skillName.isEmpty())
        skillName = name.toLower().remove("card");
    new_card->setSkillName(skillName);
    return new_card;
}
Ejemplo n.º 27
0
  QPair<QString, QString> GUI_EXPORT getSaveAsImageName( QWidget *parent, const QString &message, const QString &defaultFilename )
  {
    // get a list of supported output image types
    QMap<QString, QString> filterMap;
    Q_FOREACH ( const QByteArray &format, QImageWriter::supportedImageFormats() )
    {
      //svg doesn't work so skip it
      if ( format == "svg" )
        continue;

      filterMap.insert( createFileFilter_( format ), format );
    }

#ifdef QGISDEBUG
    QgsDebugMsg( QStringLiteral( "Available Filters Map: " ) );
    for ( QMap<QString, QString>::iterator it = filterMap.begin(); it != filterMap.end(); ++it )
    {
      QgsDebugMsg( it.key() + "  :  " + it.value() );
    }
#endif

    QgsSettings settings;  // where we keep last used filter in persistent state
    QString lastUsedDir = settings.value( QStringLiteral( "UI/lastSaveAsImageDir" ), QDir::homePath() ).toString();

    // Prefer "png" format unless the user previously chose a different format
    QString pngExtension = QStringLiteral( "png" );
    QString pngFilter = createFileFilter_( pngExtension );
    QString selectedFilter = settings.value( QStringLiteral( "UI/lastSaveAsImageFilter" ), pngFilter ).toString();

    QString initialPath;
    if ( defaultFilename.isNull() )
    {
      //no default filename provided, just use last directory
      initialPath = lastUsedDir;
    }
    else
    {
      //a default filename was provided, so use it to build the initial path
      initialPath = QDir( lastUsedDir ).filePath( defaultFilename );
    }

    QString outputFileName;
    QString ext;
#if defined(Q_OS_WIN) || defined(Q_OS_MAC) || defined(Q_OS_LINUX)
    outputFileName = QFileDialog::getSaveFileName( parent, message, initialPath, QStringList( filterMap.keys() ).join( QStringLiteral( ";;" ) ), &selectedFilter );

    if ( !outputFileName.isNull() )
    {
      ext = filterMap.value( selectedFilter, QString() );
      if ( !ext.isNull() )
        settings.setValue( QStringLiteral( "UI/lastSaveAsImageFilter" ), selectedFilter );
      settings.setValue( QStringLiteral( "UI/lastSaveAsImageDir" ), QFileInfo( outputFileName ).absolutePath() );
    }
#else

    //create a file dialog using the filter list generated above
    std::unique_ptr<QFileDialog> fileDialog( new QFileDialog( parent, message, initialPath, QStringList( filterMap.keys() ).join( ";;" ) ) );

    // allow for selection of more than one file
    fileDialog->setFileMode( QFileDialog::AnyFile );
    fileDialog->setAcceptMode( QFileDialog::AcceptSave );
    fileDialog->setOption( QFileDialog::DontConfirmOverwrite, false );

    if ( !selectedFilter.isEmpty() )     // set the filter to the last one used
    {
      fileDialog->selectNameFilter( selectedFilter );
    }

    //prompt the user for a fileName
    if ( fileDialog->exec() == QDialog::Accepted )
    {
      outputFileName = fileDialog->selectedFiles().first();
    }

    selectedFilter = fileDialog->selectedNameFilter();
    QgsDebugMsg( "Selected filter: " + selectedFilter );
    ext = filterMap.value( selectedFilter, QString() );

    if ( !ext.isNull() )
      settings.setValue( "/UI/lastSaveAsImageFilter", selectedFilter );

    settings.setValue( "/UI/lastSaveAsImageDir", fileDialog->directory().absolutePath() );
#endif

    // Add the file type suffix to the fileName if required
    if ( !ext.isNull() && !outputFileName.endsWith( '.' + ext.toLower(), Qt::CaseInsensitive ) )
    {
      outputFileName += '.' + ext;
    }

    return qMakePair<QString, QString>( outputFileName, ext );
  }
Ejemplo n.º 28
0
void MTextureManager::loadTextures(QMap<Imiks, QString> map){
 for(Imiks k : map.keys()){
	 loadTexture(k, map.value(k));
 }
}
Ejemplo n.º 29
0
bool Compiler::compile(QStringList *msgs)
{
	if(!precompile(msgs))
		return false;

	QList<int> words;
	QList<LabelItem> labelQueue;
	int address = 0;

	auto packValue = [&](const int &value)
	{
		if(words.isEmpty())
			return;

		words.last() += value;
	};

	auto packOperand = [&](const int &operand)
	{
		if(words.isEmpty())
			return;

		words.last() += operand * 10000;
	};

	auto parseOperand = [&](QString operand, const int &n, const int &line)
	{
		operand.replace('\t', "").replace('\n', "");

		bool isPointer = false;
		if((operand[0] == '[') && (operand[operand.length() - 1] == ']')) {
			isPointer = true;
			operand = operand.mid(1, operand.length() - 2);
		}

		bool isConst = false;
		if(!isPointer && operand.startsWith('$')) {
			isConst = true;
			operand = operand.mid(1);
		}

		bool isNumber = false;
		operand.toInt(&isNumber);

		if((operand[0] == '"') && (operand[operand.length() - 1] == '"')) {
			//string literal
			operand = operand.mid(1, operand.length() - 2);

			words.clear();

			for(int i = 0; i < operand.length(); ++i) {
				char c = operand[i].toLatin1();

				if(c == '\\') {
					switch(operand[i + 1].toLatin1()) {
						case 'n':  c = 10; break;
						case 'r':  c = 13; break;
						case 'a':  c = 7;  break;
						case '\\': c = 92; break;
						case '"':  c = 34; break;
						case '0':  c = 0;  break;

						default:
						{
							if(msgs) *msgs << tr("%1:Unrecognised string escape \\%2").arg(line).arg(operand[i+1]);

							return false;
						}
					}

					++i;
				}

				words << c;
			}
		} else if(isPointer && (operand.split('+').size() == 2)) {
			//register + offset
			const QString errorStr = tr("%1:Invalid offset pointer, must be one literal/label and one register");

			const QStringList split = operand.replace(' ', "").split('+');
			QString reg;
			QString offset;

			for(int i = 0; i < 2; ++i) {
				bool isOffset = false;
				int number = split[i].toInt(&isOffset);

				if(isOffset) {
					if(offset.isEmpty()) {
						offset = QString::number(number);
					} else {
						if(msgs) *msgs << errorStr.arg(line);

						return false;
					}

					packValue(number);
				} else if(registerList.contains(split[i].toUpper())) {
					if(reg.isEmpty()) {
						reg = split[i].toUpper();
					} else {
						if(msgs) *msgs << errorStr.arg(line);

						return false;
					}
				} else if(offset.isEmpty() && labelPattern.match(split[i]).hasMatch()) {
					LabelItem label;
					label.name = split[i];
					label.address = address;
					labelQueue << label;
				} else {
					if(msgs) *msgs << errorStr.arg(line);

					return false;
				}
			}

			if(reg == "AX") {
				packOperand(8);
			} else if(reg == "IP") {
				packOperand(9);
			} else if(reg == "SP") {
				packOperand(10);
			} else if(reg == "SB") {
				packOperand(11);
			} else if(reg == "DI") {
				packOperand(12);
			}
		} else if(isNumber) {
			const int value = operand.toInt();

			const int intValue = VirtualMachine::memoryToInt(value);
			if((intValue < -999) || (intValue > 999)) {
				if(msgs) *msgs << tr("%1:Value out of range \"%2\"").arg(line).arg(value);
				return false;
			}

			if(n > 0)
				words << 0;

			if(isPointer) {
				packOperand(1);
			} else if(isConst) {
				packOperand(2);
			} else {
				packOperand(0);
			}

			packValue(value);
		} else {
			if(registerList.contains(operand.toUpper())) {
				if(operand.toUpper() == "AX") {
					packOperand(isPointer ? 8 : 3);
				} else if(operand.toUpper() == "IP") {
					packOperand(isPointer ? 9 : 4);
				} else if(operand.toUpper() == "SP") {
					packOperand(isPointer ? 10 : 5);
				} else if(operand.toUpper() == "SB") {
					packOperand(isPointer ? 11 : 6);
				} else if(operand.toUpper() == "DI") {
					packOperand(isPointer ? 12 : 7);
				}
			} else {
				if(isPointer) {
					packOperand(1);
				} else if(isConst) {
					packOperand(2);
				} else {
					packOperand(0);
				}

				if(labelPattern.match(operand).hasMatch()) {
					LabelItem label;
					label.name = operand;
					label.address = address;
					labelQueue << label;
				} else {
					if(msgs) *msgs << tr("%1:Illegal symbol in label \"%2\"").arg(line).arg(operand);

					return false;
				}
			}
		}

		return true;
	};

	QHash<int, int> memory;

	for(int i = 0; i < m_instructions.size(); ++i) {
		const QString mnemonic = m_instructions[i].mnemonic.toUpper();
		const QStringList operands = m_instructions[i].operands;

		if((mnemonic == ".CODE") || (mnemonic == ".DATA")) {
			if(operands.size()) {
				address = operands[0].toInt();

				if((mnemonic == ".CODE") && (m_startCell == -1)) {
					m_startCell = address;
				}
			}
		} else {
			if(mnemonicMap.value(mnemonic).operands > operands.size()) {
				if(msgs) *msgs << tr("%1:Invalid operand count for \"%2\" (expecting %3)").arg(m_instructionMap[i])
																						  .arg(mnemonic)
																						  .arg(mnemonicMap.value(mnemonic).operands);

				return false;
			}

			if(mnemonicMap.value(mnemonic.toUpper()).code > -1) {
				words = { mnemonicMap.value(mnemonic.toUpper()).code * 1000000 };
			} else {
				words = { 0 };
			}

			for(int j = 0; j < operands.size(); ++j) {
				if(!parseOperand(operands[j], j, m_instructionMap[i]))
					return false;
			}

			const int prevAddress = address;
			for(int j = 0; j < words.size(); ++j)
				memory.insert(address++, words[j]);

			for(int j = prevAddress; j <= address; ++j) {
				if(!m_addressMap.values().contains(i))
					m_addressMap.insert(j, i);
			}
		}
	}

	for(int i = 0; i < labelQueue.size(); ++i) {
		if(!m_labelMap.contains(labelQueue[i].name)) {
			if(msgs) *msgs << tr("%1:Undefined label \"%2\"").arg(-1).arg(labelQueue[i].name);

			return false;
		}

		int value = address;
		const int key = m_addressMap.key(m_labelMap.value(labelQueue[i].name), -1);
		if(key > -1)
			value = key;

		memory[labelQueue[i].address] += value;
	}

	QHashIterator<int, int> it(memory);
	while(it.hasNext()) {
		it.next();

		emit memoryChanged(it.key(), it.value());
	}

	return true;
}
Ejemplo n.º 30
0
void QgisAppStyleSheet::buildStyleSheet( const QMap<QString, QVariant> &opts )
{
  QString ss;

  // QgisApp-wide font
  QString fontSize = opts.value( QStringLiteral( "fontPointSize" ) ).toString();
  QgsDebugMsg( QStringLiteral( "fontPointSize: %1" ).arg( fontSize ) );
  if ( fontSize.isEmpty() ) { return; }

  QString fontFamily = opts.value( QStringLiteral( "fontFamily" ) ).toString();
  QgsDebugMsg( QStringLiteral( "fontFamily: %1" ).arg( fontFamily ) );
  if ( fontFamily.isEmpty() ) { return; }

  const QString defaultSize = QString::number( mDefaultFont.pointSize() );
  const QString defaultFamily = mDefaultFont.family();
  if ( fontSize != defaultSize || fontFamily != defaultFamily )
    ss += QStringLiteral( "* { font: %1pt \"%2\"} " ).arg( fontSize, fontFamily );

  // Fix for macOS Qt 5.9+, where close boxes do not show on document mode tab bar tabs
  // See: https://bugreports.qt.io/browse/QTBUG-61092
  //      https://bugreports.qt.io/browse/QTBUG-61742
  // Setting any stylesheet makes the default close button disappear.
  // Specifically setting a custom close button temporarily works around issue.
  // TODO: Remove when regression is fixed (Qt 5.9.3 or 5.10?); though hard to tell,
  //       since we are overriding the default close button image now.
  if ( mMacStyle )
  {
    ss += QLatin1String( "QTabBar::close-button{ image: url(:/images/themes/default/mIconCloseTab.svg); }" );
    ss += QLatin1String( "QTabBar::close-button:hover{ image: url(:/images/themes/default/mIconCloseTabHover.svg); }" );
  }

  // QGroupBox and QgsCollapsibleGroupBox, mostly for Ubuntu and Mac
  bool gbxCustom = opts.value( QStringLiteral( "groupBoxCustom" ) ).toBool();
  QgsDebugMsg( QStringLiteral( "groupBoxCustom: %1" ).arg( gbxCustom ) );

  ss += QLatin1String( "QGroupBox{" );
  // doesn't work for QGroupBox::title
  ss += QStringLiteral( "color: rgb(%1,%1,%1);" ).arg( mMacStyle ? 25 : 60 );
  ss += QLatin1String( "font-weight: bold;" );

  if ( gbxCustom )
  {
    ss += QStringLiteral( "background-color: rgba(0,0,0,%1%);" )
          .arg( mWinOS && mStyle.startsWith( QLatin1String( "windows" ) ) ? 0 : 3 );
    ss += QLatin1String( "border: 1px solid rgba(0,0,0,20%);" );
    ss += QLatin1String( "border-radius: 5px;" );
    ss += QLatin1String( "margin-top: 2.5ex;" );
    ss += QStringLiteral( "margin-bottom: %1ex;" ).arg( mMacStyle ? 1.5 : 1 );
  }
  ss += QLatin1String( "} " );
  if ( gbxCustom )
  {
    ss += QLatin1String( "QGroupBox:flat{" );
    ss += QLatin1String( "background-color: rgba(0,0,0,0);" );
    ss += QLatin1String( "border: rgba(0,0,0,0);" );
    ss += QLatin1String( "} " );

    ss += QLatin1String( "QGroupBox::title{" );
    ss += QLatin1String( "subcontrol-origin: margin;" );
    ss += QLatin1String( "subcontrol-position: top left;" );
    ss += QLatin1String( "margin-left: 6px;" );
    if ( !( mWinOS && mStyle.startsWith( QLatin1String( "windows" ) ) ) && !mOxyStyle )
    {
      ss += QLatin1String( "background-color: rgba(0,0,0,0);" );
    }
    ss += QLatin1String( "} " );
  }

  //sidebar style
  QString style = "QListWidget#mOptionsListWidget {"
                  "    background-color: rgb(69, 69, 69, 0);"
                  "    outline: 0;"
                  "}"
                  "QFrame#mOptionsListFrame {"
                  "    background-color: rgb(69, 69, 69, 220);"
                  "}"
                  "QListWidget#mOptionsListWidget::item {"
                  "    color: white;"
                  "    padding: 3px;"
                  "}"
                  "QListWidget#mOptionsListWidget::item::selected {"
                  "    color: black;"
                  "    background-color:palette(Window);"
                  "    padding-right: 0px;"
                  "}";
  ss += style;

  // Fix selection color on losing focus (Windows)
  const QPalette palette = qApp->palette();

  ss += QString( "QTableView {"
                 "selection-background-color: %1;"
                 "selection-color: %2;"
                 "}" )
        .arg( palette.highlight().color().name(),
              palette.highlightedText().color().name() );

  QString toolbarSpacing = opts.value( QStringLiteral( "toolbarSpacing" ), QString() ).toString();
  if ( !toolbarSpacing.isEmpty() )
  {
    bool ok = false;
    int toolbarSpacingInt = toolbarSpacing.toInt( &ok );
    if ( ok )
    {
      ss += QStringLiteral( "QToolBar > QToolButton { padding: %1px; } " ).arg( toolbarSpacingInt );
    }
  }

  QgsDebugMsg( QStringLiteral( "Stylesheet built: %1" ).arg( ss ) );

  emit appStyleSheetChanged( ss );
}