// DescribeLayer is defined for WMS1.1.1/SLD1.0 and in WMS 1.3.0 SLD Extension
  QDomDocument describeLayer( QgsServerInterface *serverIface, const QgsProject *project, const QString &version,
                              const QgsServerRequest &request )
  {
    Q_UNUSED( version );

    QgsServerRequest::Parameters parameters = request.parameters();

    if ( !parameters.contains( QStringLiteral( "SLD_VERSION" ) ) )
    {
      throw QgsServiceException( QStringLiteral( "MissingParameterValue" ),
                                 QStringLiteral( "SLD_VERSION is mandatory for DescribeLayer operation" ), 400 );
    }
    if ( parameters[ QStringLiteral( "SLD_VERSION" )] != QLatin1String( "1.1.0" ) )
    {
      throw QgsServiceException( QStringLiteral( "InvalidParameterValue" ),
                                 QStringLiteral( "SLD_VERSION = %1 is not supported" ).arg( parameters[ QStringLiteral( "SLD_VERSION" )] ), 400 );
    }

    if ( !parameters.contains( QStringLiteral( "LAYERS" ) ) )
    {
      throw QgsServiceException( QStringLiteral( "MissingParameterValue" ),
                                 QStringLiteral( "LAYERS is mandatory for DescribeLayer operation" ), 400 );
    }

    QStringList layersList = parameters[ QStringLiteral( "LAYERS" )].split( ',', QString::SkipEmptyParts );
    if ( layersList.isEmpty() )
    {
      throw QgsServiceException( QStringLiteral( "InvalidParameterValue" ), QStringLiteral( "Layers is empty" ), 400 );
    }
    QDomDocument myDocument = QDomDocument();

    QDomNode header = myDocument.createProcessingInstruction( QStringLiteral( "xml" ), QStringLiteral( "version=\"1.0\" encoding=\"UTF-8\"" ) );
    myDocument.appendChild( header );

    // Create the root element
    QDomElement root = myDocument.createElementNS( QStringLiteral( "http://www.opengis.net/sld" ), QStringLiteral( "DescribeLayerResponse" ) );
    root.setAttribute( QStringLiteral( "xsi:schemaLocation" ), QStringLiteral( "http://www.opengis.net/sld http://schemas.opengis.net/sld/1.1.0/DescribeLayer.xsd" ) );
    root.setAttribute( QStringLiteral( "xmlns:ows" ), QStringLiteral( "http://www.opengis.net/ows" ) );
    root.setAttribute( QStringLiteral( "xmlns:se" ), QStringLiteral( "http://www.opengis.net/se" ) );
    root.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) );
    root.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) );
    myDocument.appendChild( root );

    // store the Version element
    QDomElement versionNode = myDocument.createElement( QStringLiteral( "Version" ) );
    versionNode.appendChild( myDocument.createTextNode( QStringLiteral( "1.1.0" ) ) );
    root.appendChild( versionNode );

    // get the wms service url defined in project or keep the one from the
    // request url
    QString wmsHrefString = serviceUrl( request, project ).toString();

    // get the wfs service url defined in project or take the same as the
    // wms service url
    QString wfsHrefString = QgsServerProjectUtils::wfsServiceUrl( *project );
    if ( wfsHrefString.isEmpty() )
    {
      wfsHrefString = wmsHrefString;
    }

    // get the wcs service url defined in project or take the same as the
    // wms service url
    QString wcsHrefString = QgsServerProjectUtils::wcsServiceUrl( *project );
    if ( wcsHrefString.isEmpty() )
    {
      wcsHrefString = wmsHrefString;
    }

    // access control
#ifdef HAVE_SERVER_PYTHON_PLUGINS
    QgsAccessControl *accessControl = serverIface->accessControls();
#endif
    // Use layer ids
    bool useLayerIds = QgsServerProjectUtils::wmsUseLayerIds( *project );
    // WMS restricted layers
    QStringList restrictedLayers = QgsServerProjectUtils::wmsRestrictedLayers( *project );
    // WFS layers
    QStringList wfsLayerIds = QgsServerProjectUtils::wfsLayerIds( *project );
    // WCS layers
    QStringList wcsLayerIds = QgsServerProjectUtils::wcsLayerIds( *project );

    for ( QgsMapLayer *layer : project->mapLayers() )
    {
      QString name = layer->name();
      if ( useLayerIds )
        name = layer->id();
      else if ( !layer->shortName().isEmpty() )
        name = layer->shortName();

      if ( !layersList.contains( name ) )
      {
        continue;
      }

      //unpublished layer
      if ( restrictedLayers.contains( layer->name() ) )
      {
        throw QgsSecurityException( QStringLiteral( "You are not allowed to access to this layer" ) );
      }

#ifdef HAVE_SERVER_PYTHON_PLUGINS
      if ( accessControl && !accessControl->layerReadPermission( layer ) )
      {
        throw QgsSecurityException( QStringLiteral( "You are not allowed to access to this layer" ) );
      }
#endif

      // Create the NamedLayer element
      QDomElement layerNode = myDocument.createElement( QStringLiteral( "LayerDescription" ) );
      root.appendChild( layerNode );

      // store the owsType element
      QDomElement typeNode = myDocument.createElement( QStringLiteral( "owsType" ) );
      // store the se:OnlineResource element
      QDomElement oResNode = myDocument.createElement( QStringLiteral( "se:OnlineResource" ) );
      oResNode.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) );
      // store the TypeName element
      QDomElement nameNode = myDocument.createElement( QStringLiteral( "TypeName" ) );
      switch ( layer->type() )
      {
        case QgsMapLayer::VectorLayer:
        {
          typeNode.appendChild( myDocument.createTextNode( QStringLiteral( "wfs" ) ) );

          if ( wfsLayerIds.indexOf( layer->id() ) != -1 )
          {
            oResNode.setAttribute( QStringLiteral( "xlink:href" ), wfsHrefString );
          }

          // store the se:FeatureTypeName element
          QDomElement typeNameNode = myDocument.createElement( QStringLiteral( "se:FeatureTypeName" ) );
          typeNameNode.appendChild( myDocument.createTextNode( name ) );
          nameNode.appendChild( typeNameNode );
          break;
        }
        case QgsMapLayer::RasterLayer:
        {
          typeNode.appendChild( myDocument.createTextNode( QStringLiteral( "wcs" ) ) );

          if ( wcsLayerIds.indexOf( layer->id() ) != -1 )
          {
            oResNode.setAttribute( QStringLiteral( "xlink:href" ), wcsHrefString );
          }

          // store the se:CoverageTypeName element
          QDomElement typeNameNode = myDocument.createElement( QStringLiteral( "se:CoverageTypeName" ) );
          typeNameNode.appendChild( myDocument.createTextNode( name ) );
          nameNode.appendChild( typeNameNode );
          break;
        }

        case QgsMapLayer::MeshLayer:
        case QgsMapLayer::PluginLayer:
          break;
      }
      layerNode.appendChild( typeNode );
      layerNode.appendChild( oResNode );
      layerNode.appendChild( nameNode );
    }

    return myDocument;
  }
Esempio n. 2
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    app.setApplicationVersion(KSTARS_VERSION);

    /**
    * enable high dpi support
    */
    app.setAttribute(Qt::AA_UseHighDpiPixmaps, true);

    KCrash::initialize();

    KLocalizedString::setApplicationDomain("kstars");

    KAboutData aboutData( "kstars", i18n("KStars"), KSTARS_VERSION, i18n(description), KAboutLicense::GPL,
                          i18n("(c) 2001-2015, The KStars Team"), i18n(notice), "http://edu.kde.org/kstars");
    aboutData.addAuthor(i18n("Jason Harris"), i18n("Original Author"), "*****@*****.**", "http://www.30doradus.org");
    aboutData.addAuthor(i18n("Jasem Mutlaq"), i18n("Current Maintainer"), "*****@*****.**", "http://www.indilib.org");
    aboutData.addAuthor(i18n("James Bowlin"), QString(), "*****@*****.**");
    aboutData.addAuthor(i18n("Pablo de Vicente"), QString(), "*****@*****.**");
    aboutData.addAuthor(i18n("Thomas Kabelmann"), QString(), "*****@*****.**");
    aboutData.addAuthor(i18n("Heiko Evermann"),QString(), "*****@*****.**", "http://www.evermann.de");
    aboutData.addAuthor(i18n("Carsten Niehaus"), QString(), "*****@*****.**");
    aboutData.addAuthor(i18n("Mark Hollomon"), QString(), "*****@*****.**");
    aboutData.addAuthor(i18n("Alexey Khudyakov"), QString(), "*****@*****.**");
    aboutData.addAuthor(i18n("Médéric Boquien"), QString(), "*****@*****.**");
    aboutData.addAuthor(i18n("Akarsh Simha"), QString(), "*****@*****.**", "http://www.ph.utexas.edu/~asimha");
    aboutData.addAuthor(i18n("Jérôme Sonrier"), QString(), "*****@*****.**");
    aboutData.addAuthor(i18n("Prakash Mohan"), QString(), "*****@*****.**");
    aboutData.addAuthor(i18n("Victor Cărbune"), QString(), "*****@*****.**");
    aboutData.addAuthor(i18n("Henry de Valence"), QString(), "*****@*****.**");
    aboutData.addAuthor(i18n("Samikshan Bairagya"), QString(), "*****@*****.**");
    aboutData.addAuthor(i18n("Rafał Kułaga"), QString(), "*****@*****.**");
    aboutData.addAuthor(i18n("Rishab Arora"), QString(), "*****@*****.**");

    aboutData.addCredit(i18n("Valery Kharitonov"), i18n("Converted labels containing technical terms to links to documentation") );
    aboutData.addCredit(i18n("Ana-Maria Constantin"), i18n("Technical documentation on Astronomy and KStars") );
    aboutData.addCredit(i18n("Andrew Stepanenko"), i18n("Guiding code based on lin_guider") );
    aboutData.addCredit(i18n("Nuno Pinheiro"), i18n("Artwork") );
    aboutData.addCredit(i18n("Utkarsh Simha"), i18n("Improvements to observation plan execution, star hopper etc.") );    
    aboutData.addCredit(i18n("Daniel Holler"), i18n("Extensive testing and suggestions for Ekos/INDI.") );
    aboutData.addCredit(i18n("Stephane Lucas"), i18n("Extensive testing and suggestions for Ekos Scheduler.") );

    KAboutData::setApplicationData(aboutData);

    QCommandLineParser parser;
    aboutData.setupCommandLine(&parser);
    parser.setApplicationDescription(aboutData.shortDescription());
    parser.addVersionOption();
    parser.addHelpOption();

    //parser.addHelpOption(INSERT_DESCRIPTION_HERE);
    parser.addOption(QCommandLineOption(QStringList() << "dump", i18n( "Dump sky image to file" )));
    parser.addOption(QCommandLineOption(QStringList() << "script ", i18n( "Script to execute" )));
    parser.addOption(QCommandLineOption(QStringList() << "width ", i18n( "Width of sky image" ),  "640"));
    parser.addOption(QCommandLineOption(QStringList() << "height ", i18n( "Height of sky image" ), "480"));
    parser.addOption(QCommandLineOption(QStringList() << "filename ", i18n( "Filename for sky image" ), "kstars.png"));
    parser.addOption(QCommandLineOption(QStringList() << "date", i18n( "Date and time" )));
    parser.addOption(QCommandLineOption(QStringList() << "paused", i18n( "Start with clock paused" )));

    // urls to open
    parser.addPositionalArgument(QStringLiteral("urls"), i18n("FITS file(s) to open."), QStringLiteral("[urls...]"));

    parser.process(app);
    aboutData.processCommandLine(&parser);

    if ( parser.isSet( "dump" ) )
    {
        qDebug() << "Dumping sky image";

        //parse filename and image format
        const char* format = "PNG";
        QString fname = parser.value( "filename" );
        QString ext = fname.mid( fname.lastIndexOf(".")+1 );
        if ( ext.toLower() == "png" ) { format = "PNG"; }
        else if ( ext.toLower() == "jpg" || ext.toLower() == "jpeg" ) { format = "JPG"; }
        else if ( ext.toLower() == "gif" ) { format = "GIF"; }
        else if ( ext.toLower() == "pnm" ) { format = "PNM"; }
        else if ( ext.toLower() == "bmp" ) { format = "BMP"; }
        else { qWarning() << i18n( "Could not parse image format of %1; assuming PNG.", fname ) ; }

        //parse width and height
        bool ok(false);
        int w(0), h(0);
        w = parser.value( "width" ).toInt( &ok );
        if ( ok ) h =  parser.value( "height" ).toInt( &ok );
        if ( !ok ) {
            qWarning() << "Unable to parse arguments: " ;
            qWarning() << "Width: " << parser.value( "width" )
            << "  Height: " << parser.value( "height" ) << endl;
            return 1;
        }

        KStarsData *dat = KStarsData::Create();
        QObject::connect( dat, SIGNAL( progressText(QString) ), dat, SLOT( slotConsoleMessage(QString) ) );
        dat->initialize();

        //Set Geographic Location
        dat->setLocationFromOptions();

        //Set color scheme
        dat->colorScheme()->loadFromConfig();

        //set clock now that we have a location:
        //Check to see if user provided a date/time string.  If not, use current CPU time
        QString datestring = parser.value( "date" );
        KStarsDateTime kdt;
        if ( ! datestring.isEmpty() ) {
            if ( datestring.contains( "-" ) ) { //assume ISODate format
                if ( datestring.contains( ":" ) ) { //also includes time
                    //kdt = QDateTime::fromString( datestring, QDateTime::ISODate );
                    kdt = QDateTime::fromString( datestring, Qt::ISODate );
                } else { //string probably contains date only
                    //kdt.setDate( QDate::fromString( datestring, Qt::ISODate ) );
                    kdt.setDate( QDate::fromString( datestring, Qt::ISODate ) );
                    kdt.setTime( QTime( 0, 0, 0 ) );
                }
            } else { //assume Text format for date string
                kdt = dat->geo()->LTtoUT( QDateTime::fromString( datestring, Qt::TextDate ) );
            }

            if ( ! kdt.isValid() ) {
                qWarning() << i18n( "Using CPU date/time instead." ) ;

                kdt = KStarsDateTime::currentDateTimeUtc();
            }
        } else {
            kdt = KStarsDateTime::currentDateTimeUtc();
        }
        dat->clock()->setUTC( kdt );

        SkyMap *map = SkyMap::Create();
        map->resize( w, h );
        QPixmap sky( w, h );

        dat->setFullTimeUpdate();
        dat->updateTime(dat->geo(), map );

        SkyPoint dest( Options::focusRA(), Options::focusDec() );
        map->setDestination( dest );
        map->destination()->EquatorialToHorizontal( dat->lst(), dat->geo()->lat() );
        map->setFocus( map->destination() );
        map->focus()->EquatorialToHorizontal( dat->lst(), dat->geo()->lat() );

        //Execute the specified script
        QString scriptfile = parser.value( "script" );
        if ( ! scriptfile.isEmpty() ) {
            if ( dat->executeScript( scriptfile, map ) ) {
                std::cout << i18n( "Script executed." ).toUtf8().data() << std::endl;
            } else {
                qWarning() << i18n( "Could not execute script." ) ;
            }
        }

        qApp->processEvents();
        map->setupProjector();
        map->exportSkyImage( &sky );
        qApp->processEvents();

        if ( ! sky.save( fname, format ) )
            qWarning() << "Unable to save image: " << fname;
        else
            qDebug() << "Saved to file: %1" << fname;

        delete map;
        delete dat;
        return 0;
    }

    //Try to parse the given date string
    QString datestring = parser.value( "date" );

    if ( ! datestring.isEmpty() && ! KStarsDateTime::fromString( datestring ).isValid() )
    {
        qWarning() << i18n( "Using CPU date/time instead." ) ;
        datestring.clear();
    }

    // Create writable data dir if it does not exist
    QDir writableDir;
    writableDir.mkdir(QStandardPaths::writableLocation(QStandardPaths::DataLocation));

    KStars::createInstance( true, ! parser.isSet( "paused" ), datestring );

    // no session.. just start up normally
    const QStringList urls = parser.positionalArguments();

    // take arguments
    if( ! urls.isEmpty() )
    {
        const QRegExp withProtocolChecker( QStringLiteral("^[a-zA-Z]+:") );
        foreach (const QString &url, urls) {
            const QUrl u = (withProtocolChecker.indexIn(url) == 0) ?
                QUrl::fromUserInput( url ) :
                QUrl::fromLocalFile(QDir::current().absoluteFilePath(url));

            KStars::Instance()->openFITS(u);
        }
    }

    QObject::connect(qApp, SIGNAL(lastWindowClosed()), qApp, SLOT(quit()));
    return app.exec();

}
Esempio n. 3
0
int main(int argc, char *argv[])
{
    /* Workaround Qt platform integration plugin not advertising itself
       as having the following capabilities:
        - QPlatformIntegration::ThreadedOpenGL
        - QPlatformIntegration::BufferQueueingOpenGL
    */
    setenv("QML_FORCE_THREADED_RENDERER", "1", 1);
    setenv("QML_FIXED_ANIMATION_STEP", "1", 1);

    // ignore favorites in unity-scopes-shell plugin
    setenv("UNITY_SCOPES_NO_FAVORITES", "1", 1);

    QGuiApplication::setApplicationName("Unity Scope Tool");
    QGuiApplication *application;
    application = new QGuiApplication(argc, argv);

    QCommandLineParser parser;
    parser.setApplicationDescription("Unity Scope Tool\n\n"
    "This tool allows development and testing of scopes. Running it without\n"
    "any arguments will open a session to all scopes available on the system.\n"
    "Otherwise passing a path to a scope config file will open a session with\n"
    "only that scope (assuming that the binary implementing the scope can be\n"
    "found in the same directory as the config file).");
    QCommandLineOption helpOption = parser.addHelpOption();
    parser.addPositionalArgument("scopes", "Paths to scope config files to spawn, optionally.", "[scopes...]");

    QCommandLineOption includeSystemScopes("include-system-scopes",
        "Initialize the registry with scopes installed on this system");
    QCommandLineOption includeServerScopes("include-server-scopes",
        "Initialize the registry with scopes on the default server");

    parser.addOption(includeServerScopes);
    parser.addOption(includeSystemScopes);

    parser.parse(application->arguments());

    if (parser.isSet(helpOption)) {
        parser.showHelp();
    }

    QStringList extraScopes = parser.positionalArguments();

    QScopedPointer<RegistryTracker> tracker;
    if (!extraScopes.isEmpty()) {
        bool systemScopes = parser.isSet(includeSystemScopes);
        bool serverScopes = parser.isSet(includeServerScopes);
        tracker.reset(new RegistryTracker(extraScopes, systemScopes, serverScopes));
    }

    bindtextdomain("unity8", translationDirectory().toUtf8().data());
    textdomain("unity8");

    QQuickView* view = new QQuickView();
    view->setResizeMode(QQuickView::SizeRootObjectToView);
    view->setTitle(QGuiApplication::applicationName());
    view->engine()->setBaseUrl(QUrl::fromLocalFile(::qmlDirectory()));

    QUrl source(::qmlDirectory() + "/ScopeTool.qml");
    prependImportPaths(view->engine(), ::overrideImportPaths());
    prependImportPaths(view->engine(), ::nonMirImportPaths());
    appendImportPaths(view->engine(), ::fallbackImportPaths());

    view->setSource(source);

    view->show();

    UnixSignalHandler signal_handler([]{
        QGuiApplication::exit(0);
    });
    signal_handler.setupUnixSignalHandlers();

    int result = application->exec();

    delete view;
    delete application;

    return result;
}
Esempio n. 4
0
void HttpConnection::respond() {
  if ((m_socket->peerAddress() != QHostAddress::LocalHost
      && m_socket->peerAddress() != QHostAddress::LocalHostIPv6)
     || m_httpserver->isLocalAuthEnabled()) {
    // Authentication
    const QString peer_ip = m_socket->peerAddress().toString();
    const int nb_fail = m_httpserver->NbFailedAttemptsForIp(peer_ip);
    if (nb_fail >= MAX_AUTH_FAILED_ATTEMPTS) {
      m_generator.setStatusLine(403, "Forbidden");
      m_generator.setMessage(tr("Your IP address has been banned after too many failed authentication attempts."));
      write();
      return;
    }
    QString auth = m_parser.header().value("Authorization");
    if (auth.isEmpty()) {
      // Return unauthorized header
      qDebug("Auth is Empty...");
      m_generator.setStatusLine(401, "Unauthorized");
      m_generator.setValue("WWW-Authenticate",  "Digest realm=\""+QString(QBT_REALM)+"\", nonce=\""+m_httpserver->generateNonce()+"\", opaque=\""+m_httpserver->generateNonce()+"\", stale=\"false\", algorithm=\"MD5\", qop=\"auth\"");
      write();
      return;
    }
    //qDebug("Auth: %s", qPrintable(auth.split(" ").first()));
    if (QString::compare(auth.split(" ").first(), "Digest", Qt::CaseInsensitive) != 0
        || !m_httpserver->isAuthorized(auth.toUtf8(), m_parser.header().method())) {
      // Update failed attempt counter
      m_httpserver->increaseNbFailedAttemptsForIp(peer_ip);
      qDebug("client IP: %s (%d failed attempts)", qPrintable(peer_ip), nb_fail);
      // Return unauthorized header
      m_generator.setStatusLine(401, "Unauthorized");
      m_generator.setValue("WWW-Authenticate",  "Digest realm=\""+QString(QBT_REALM)+"\", nonce=\""+m_httpserver->generateNonce()+"\", opaque=\""+m_httpserver->generateNonce()+"\", stale=\"false\", algorithm=\"MD5\", qop=\"auth\"");
      write();
      return;
    }
    // Client successfully authenticated, reset number of failed attempts
    m_httpserver->resetNbFailedAttemptsForIp(peer_ip);
  }
  QString url  = m_parser.url();
  // Favicon
  if (url.endsWith("favicon.ico")) {
    qDebug("Returning favicon");
    QFile favicon(":/Icons/skin/qbittorrent16.png");
    if (favicon.open(QIODevice::ReadOnly)) {
      const QByteArray data = favicon.readAll();
      favicon.close();
      m_generator.setStatusLine(200, "OK");
      m_generator.setContentTypeByExt("png");
      m_generator.setMessage(data);
      write();
    } else {
      respondNotFound();
    }
    return;
  }

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

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

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

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

  // Translate the page
  if (ext == "html" || (ext == "js" && !list.last().startsWith("excanvas"))) {
    QString dataStr = QString::fromUtf8(data.constData());
    translateDocument(dataStr);
    if (url.endsWith("about.html")) {
      dataStr.replace("${VERSION}", VERSION);
    }
    data = dataStr.toUtf8();
  }
  m_generator.setStatusLine(200, "OK");
  m_generator.setContentTypeByExt(ext);
  m_generator.setMessage(data);
  write();
}
Esempio n. 5
0
void JoCASSViewer::saveFile(QString filename, QStringList keys) const
{
  if (_viewers.isEmpty())
    return;

  /** if not filename was given ask for one */
  if (filename.isEmpty())
  {
    QString filter("Data Files (*.png *.csv *.hst *.h5 *.hdf5 *.cbf)");
    filename = QFileDialog::getSaveFileName(0, tr("Save Data to File"),
                                            QDir::currentPath(), filter);
    if(filename.isEmpty())
      return;
  }

  /** if no keys are given, request at least one using the iteminput dialog
   *  The preselected item in the dialog should be the currently highlighted
   *  window or, in case of a container file, "all"
   */
  if (keys.isEmpty())
  {
    QStringList items(displayedItems());
    items.prepend("**ALL**");
    QWidget *focusWiget(QApplication::focusWidget());
    int preselectItemId(items.indexOf("**ALL**"));
    if (!FileHandler::isContainerFile(filename) && (focusWiget))
      preselectItemId = items.indexOf(focusWiget->windowTitle());
    bool ok(false);
    QString item(QInputDialog::getItem(0, QObject::tr("Select Key"),
                                       QObject::tr("Key:"), items,
                                       preselectItemId, false, &ok));
    if (!ok || item.isEmpty())
      return;
    if (item.contains("***ALL***"))
      keys = displayedItems();
    else
      keys.append(item);
  }

  /** if the file is a container file, create the container first before adding
   *  data to it.
   */
  if (FileHandler::isContainerFile(filename))
    FileHandler::createContainer(filename);

  /** go through the list and tell the viewer to save the data
   *  Append the name of the viewer to the filaname in case this is not a
   *  container file and more that one file should be saved with data so that
   *  the files are not overwritten.
   */
  QStringList::const_iterator cIt;
  for (cIt = keys.constBegin(); cIt != keys.constEnd(); ++cIt)
  {
    if (_viewers.value(*cIt))
    {
      QString fname(filename);
      if(!FileHandler::isContainerFile(filename) && keys.size() > 1)
        fname.insert(fname.lastIndexOf("."),"_" + *cIt);
      _viewers.value(*cIt)->saveData(fname);
    }
  }
}
Esempio n. 6
0
void GrepViewWidget::searchActivated()
{
	if ( grepdlg->keepOutputFlag() )
		slotKeepOutput();

	m_tabWidget->showPage( m_curOutput );

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

	QString command, files;

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

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

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

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

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

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

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

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

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

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

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

		command = filepattern + " " ;
	}

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

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

	command += "| xargs " ;

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

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

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

	m_part->mainWindow()->raiseView(this);
	m_part->core()->running(m_part, true);
}
Esempio n. 7
0
int main(int argc, char *argv[])
{
    FillData fill_data;
    int fromfile_id = 1;
    int fromfile_offset = 0;
    QString fromfile_name;
    bool from_file = false;
    bool mark_repeats = true;

    bool usingDataDirect = false;

    bool from_dd_file = false;
    int sourceid = -1;
    QString fromddfile_lineupid;

    MythFillDatabaseCommandLineParser cmdline;
    if (!cmdline.Parse(argc, argv))
    {
        cmdline.PrintHelp();
        return GENERIC_EXIT_INVALID_CMDLINE;
    }

    if (cmdline.toBool("showhelp"))
    {
        cmdline.PrintHelp();
        return GENERIC_EXIT_OK;
    }

    if (cmdline.toBool("showversion"))
    {
        cmdline.PrintVersion();
        return GENERIC_EXIT_OK;
    }

    QCoreApplication a(argc, argv);
    QCoreApplication::setApplicationName(MYTH_APPNAME_MYTHFILLDATABASE);

    myth_nice(19);

    int retval;
    if ((retval = cmdline.ConfigureLogging()) != GENERIC_EXIT_OK)
        return retval;

    if (cmdline.toBool("manual"))
    {
        cout << "###\n";
        cout << "### Running in manual channel configuration mode.\n";
        cout << "### This will ask you questions about every channel.\n";
        cout << "###\n";
        fill_data.chan_data.m_interactive = true;
    }

    if (cmdline.toBool("onlyguide") || cmdline.toBool("update"))
    {
        LOG(VB_GENERAL, LOG_NOTICE,
            "Only updating guide data, channel and icon updates will be ignored");
        fill_data.chan_data.m_guideDataOnly = true;
    }

    if (cmdline.toBool("preset"))
    {
        cout << "###\n";
        cout << "### Running in preset channel configuration mode.\n";
        cout << "### This will assign channel ";
        cout << "preset numbers to every channel.\n";
        cout << "###\n";
        fill_data.chan_data.m_channelPreset = true;
    }

    if (cmdline.toBool("file"))
    {
        // manual file mode
        if (!cmdline.toBool("sourceid") ||
            !cmdline.toBool("xmlfile"))
        {
            cerr << "The --file option must be used in combination" << endl
                 << "with both --sourceid and --xmlfile." << endl;
            return GENERIC_EXIT_INVALID_CMDLINE;
        }

        fromfile_id = cmdline.toInt("sourceid");
        fromfile_name = cmdline.toString("xmlfile");

        LOG(VB_GENERAL, LOG_INFO,
            "Bypassing grabbers, reading directly from file");
        from_file = true;
    }

    if (cmdline.toBool("ddfile"))
    {
        // datadirect file mode
        if (!cmdline.toBool("sourceid") || 
            !cmdline.toBool("offset") ||
            !cmdline.toBool("lineupid") ||
            !cmdline.toBool("xmlfile"))
        {
            cerr << "The --dd-file option must be used in combination" << endl
                 << "with each of --sourceid, --offset, --lineupid," << endl
                 << "and --xmlfile." << endl;
            return GENERIC_EXIT_INVALID_CMDLINE;
        }

        fromfile_id         = cmdline.toInt("sourceid");
        fromfile_offset     = cmdline.toInt("offset");
        fromddfile_lineupid = cmdline.toString("lineupid");
        fromfile_name       = cmdline.toString("xmlfile");

        LOG(VB_GENERAL, LOG_INFO,
            "Bypassing grabbers, reading directly from file");
        from_dd_file = true;
    }

    if (cmdline.toBool("dochannelupdates"))
        fill_data.chan_data.m_channelUpdates = true;
    if (cmdline.toBool("removechannels"))
        fill_data.chan_data.m_removeNewChannels = true;
    if (cmdline.toBool("nofilterchannels"))
        fill_data.chan_data.m_filterNewChannels = false;
    if (!cmdline.GetPassthrough().isEmpty())
        fill_data.graboptions = " " + cmdline.GetPassthrough();
    if (cmdline.toBool("sourceid"))
        sourceid = cmdline.toInt("sourceid");
    if (cmdline.toBool("cardtype"))
    {
        if (!cmdline.toBool("sourceid"))
        {
            cerr << "The --cardtype option must be used in combination" << endl
                 << "with a --sourceid option." << endl;
            return GENERIC_EXIT_INVALID_CMDLINE;
        }

        fill_data.chan_data.m_cardType = cmdline.toString("cardtype")
                                                .trimmed().toUpper();
    }
    if (cmdline.toBool("maxdays") && cmdline.toInt("maxdays") > 0)
    {
        fill_data.maxDays = cmdline.toInt("maxdays");
        if (fill_data.maxDays == 1)
            fill_data.SetRefresh(0, true);
    }

    if (cmdline.toBool("refreshtoday"))
        cmdline.SetValue("refresh",
                cmdline.toStringList("refresh") << "today");
    if (cmdline.toBool("dontrefreshtomorrow"))
        cmdline.SetValue("refresh", 
                cmdline.toStringList("refresh") << "nottomorrow");
    if (cmdline.toBool("refreshsecond"))
        cmdline.SetValue("refresh", 
                cmdline.toStringList("refresh") << "second");
    if (cmdline.toBool("refreshall"))
        cmdline.SetValue("refresh", 
                cmdline.toStringList("refresh") << "all");
    if (cmdline.toBool("refreshday"))
        cmdline.SetValue("refresh",
                cmdline.toStringList("refresh") << 
                                        cmdline.toStringList("refreshday"));

    QStringList sl = cmdline.toStringList("refresh");
    if (!sl.isEmpty())
    {
        QStringList::const_iterator i = sl.constBegin();
        for (; i != sl.constEnd(); ++i)
        {
            QString warn = QString("Invalid entry in --refresh list: %1")
                                .arg(*i);

            bool enable = (*i).contains("not") ? false : true;

            if ((*i).contains("today"))
                fill_data.SetRefresh(0, enable);
            else if ((*i).contains("tomorrow"))
                fill_data.SetRefresh(1, enable);
            else if ((*i).contains("second"))
                fill_data.SetRefresh(2, enable);
            else if ((*i).contains("all"))
                fill_data.SetRefresh(FillData::kRefreshAll, enable);
            else if ((*i).contains("-"))
            {
                bool ok;
                QStringList r = (*i).split("-");

                uint lower = r[0].toUInt(&ok);
                if (!ok)
                {
                    cerr << warn.toLocal8Bit().constData() << endl;
                    return false;
                }

                uint upper = r[1].toUInt(&ok);
                if (!ok)
                {
                    cerr << warn.toLocal8Bit().constData() << endl;
                    return false;
                }

                if (lower > upper)
                {
                    cerr << warn.toLocal8Bit().constData() << endl;
                    return false;
                }

                for (uint j = lower; j <= upper; ++j)
                    fill_data.SetRefresh(j, true);
            }
            else
            {
                bool ok;
                uint day = (*i).toUInt(&ok);
                if (!ok)
                {
                    cerr << warn.toLocal8Bit().constData() << endl;
                    return false;
                }

                fill_data.SetRefresh(day, true);
            }
        }
    }

    if (cmdline.toBool("dontrefreshtba"))
        fill_data.refresh_tba = false;
    if (cmdline.toBool("ddgraball"))
    {
        fill_data.SetRefresh(FillData::kRefreshClear, false);
        fill_data.dd_grab_all = true;
    }
    if (cmdline.toBool("onlychannels"))
        fill_data.only_update_channels = true;

    mark_repeats = cmdline.toBool("markrepeats");

    CleanupGuard callCleanup(cleanup);

#ifndef _WIN32
    QList<int> signallist;
    signallist << SIGINT << SIGTERM << SIGSEGV << SIGABRT << SIGBUS << SIGFPE
               << SIGILL;
#if ! CONFIG_DARWIN
    signallist << SIGRTMIN;
#endif
    SignalHandler::Init(signallist);
    signal(SIGHUP, SIG_IGN);
#endif

    gContext = new MythContext(MYTH_BINARY_VERSION);
    if (!gContext->Init(false))
    {
        LOG(VB_GENERAL, LOG_ERR, "Failed to init MythContext, exiting.");
        return GENERIC_EXIT_NO_MYTHCONTEXT;
    }

    setHttpProxy();

    MythTranslation::load("mythfrontend");

    if (!UpgradeTVDatabaseSchema(false))
    {
        LOG(VB_GENERAL, LOG_ERR, "Incorrect database schema");
        return GENERIC_EXIT_DB_OUTOFDATE;
    }

    if (gCoreContext->SafeConnectToMasterServer(true, false))
        LOG(VB_GENERAL, LOG_INFO,
            "Opening blocking connection to master backend");
    else
        LOG(VB_GENERAL, LOG_WARNING,
            "Failed to connect to master backend. MythFillDatabase will "
            "continue running but will be unable to prevent backend from "
            "shutting down, or triggering a reschedule when complete.");

    if (from_file)
    {
        QString status = QObject::tr("currently running.");
        QDateTime GuideDataBefore, GuideDataAfter;

        updateLastRunStart();
        updateLastRunStatus(status);

        MSqlQuery query(MSqlQuery::InitCon());
        query.prepare("SELECT MAX(endtime) FROM program p LEFT JOIN channel c "
                      "ON p.chanid=c.chanid WHERE c.sourceid= :SRCID "
                      "AND manualid = 0 AND c.xmltvid != '';");
        query.bindValue(":SRCID", fromfile_id);

        if (query.exec() && query.next())
        {
            if (!query.isNull(0))
                GuideDataBefore =
                    MythDate::fromString(query.value(0).toString());
        }

        if (!fill_data.GrabDataFromFile(fromfile_id, fromfile_name))
        {
            return GENERIC_EXIT_NOT_OK;
        }

        updateLastRunEnd();

        query.prepare("SELECT MAX(endtime) FROM program p LEFT JOIN channel c "
                      "ON p.chanid=c.chanid WHERE c.sourceid= :SRCID "
                      "AND manualid = 0 AND c.xmltvid != '';");
        query.bindValue(":SRCID", fromfile_id);

        if (query.exec() && query.next())
        {
            if (!query.isNull(0))
                GuideDataAfter =
                    MythDate::fromString(query.value(0).toString());
        }

        if (GuideDataAfter == GuideDataBefore)
            status = QObject::tr("mythfilldatabase ran, but did not insert "
                    "any new data into the Guide.  This can indicate a "
                    "potential problem with the XML file used for the update.");
        else
            status = QObject::tr("Successful.");

        updateLastRunStatus(status);
    }
    else if (from_dd_file)
    {
        fill_data.GrabDataFromDDFile(
            fromfile_id, fromfile_offset, fromfile_name, fromddfile_lineupid);
    }
    else
    {
        SourceList sourcelist;

        MSqlQuery sourcequery(MSqlQuery::InitCon());
        QString where;

        if (sourceid != -1)
        {
            LOG(VB_GENERAL, LOG_INFO,
                QString("Running for sourceid %1 ONLY because --sourceid "
                        "was given on command-line").arg(sourceid));
            where = QString("WHERE sourceid = %1").arg(sourceid);
        }

        QString querystr = QString("SELECT sourceid,name,xmltvgrabber,userid,"
                                   "password,lineupid "
                                   "FROM videosource ") + where +
                                   QString(" ORDER BY sourceid;");

        if (sourcequery.exec(querystr))
        {
             if (sourcequery.size() > 0)
             {
                  while (sourcequery.next())
                  {
                       Source newsource;

                       newsource.id = sourcequery.value(0).toInt();
                       newsource.name = sourcequery.value(1).toString();
                       newsource.xmltvgrabber = sourcequery.value(2).toString();
                       newsource.userid = sourcequery.value(3).toString();
                       newsource.password = sourcequery.value(4).toString();
                       newsource.lineupid = sourcequery.value(5).toString();

                       newsource.xmltvgrabber_baseline = false;
                       newsource.xmltvgrabber_manualconfig = false;
                       newsource.xmltvgrabber_cache = false;
                       newsource.xmltvgrabber_prefmethod = "";

                       sourcelist.push_back(newsource);
                       usingDataDirect |=
                           is_grabber_datadirect(newsource.xmltvgrabber);
                  }
             }
             else
             {
                  LOG(VB_GENERAL, LOG_ERR,
                      "There are no channel sources defined, did you run "
                      "the setup program?");
                  return GENERIC_EXIT_SETUP_ERROR;
             }
        }
        else
        {
             MythDB::DBError("loading channel sources", sourcequery);
             return GENERIC_EXIT_DB_ERROR;
        }

        if (!fill_data.Run(sourcelist))
            LOG(VB_GENERAL, LOG_ERR, "Failed to fetch some program info");
        else
            LOG(VB_GENERAL, LOG_NOTICE, "Data fetching complete.");
    }

    if (fill_data.only_update_channels && !fill_data.need_post_grab_proc)
    {
        return GENERIC_EXIT_OK;
    }

    LOG(VB_GENERAL, LOG_INFO, "Adjusting program database end times.");
    int update_count = ProgramData::fix_end_times();
    if (update_count == -1)
        LOG(VB_GENERAL, LOG_ERR, "fix_end_times failed!");
    else
        LOG(VB_GENERAL, LOG_INFO,
            QString("    %1 replacements made").arg(update_count));

    LOG(VB_GENERAL, LOG_INFO, "Marking generic episodes.");

    MSqlQuery query(MSqlQuery::InitCon());
    query.prepare("UPDATE program SET generic = 1 WHERE "
        "((programid = '' AND subtitle = '' AND description = '') OR "
        " (programid <> '' AND category_type = 'series' AND "
        "  program.programid LIKE '%0000'));");

    if (!query.exec())
        MythDB::DBError("mark generic", query);
    else
        LOG(VB_GENERAL, LOG_INFO,
            QString("    Found %1").arg(query.numRowsAffected()));

    LOG(VB_GENERAL, LOG_INFO, "Extending non-unique programids "
                                "with multiple parts.");

    int found = 0;
    MSqlQuery sel(MSqlQuery::InitCon());
    sel.prepare("SELECT DISTINCT programid, partnumber, parttotal "
                "FROM program WHERE partnumber > 0 AND parttotal > 0 AND "
                "programid LIKE '%0000'");
    if (sel.exec())
    {
        MSqlQuery repl(MSqlQuery::InitCon());
        repl.prepare("UPDATE program SET programid = :NEWID "
                        "WHERE programid = :OLDID AND "
                        "partnumber = :PARTNUM AND "
                        "parttotal = :PARTTOTAL");

        while (sel.next())
        {
            QString orig_programid = sel.value(0).toString();
            QString new_programid = orig_programid.left(10);
            int     partnum, parttotal;
            QString part;

            partnum   = sel.value(1).toInt();
            parttotal = sel.value(2).toInt();

            part.setNum(parttotal);
            new_programid.append(part.rightJustified(2, '0'));
            part.setNum(partnum);
            new_programid.append(part.rightJustified(2, '0'));

            LOG(VB_GENERAL, LOG_INFO,
                QString("    %1 -> %2 (part %3 of %4)")
                    .arg(orig_programid).arg(new_programid)
                    .arg(partnum).arg(parttotal));

            repl.bindValue(":NEWID", new_programid);
            repl.bindValue(":OLDID", orig_programid);
            repl.bindValue(":PARTNUM",   partnum);
            repl.bindValue(":PARTTOTAL", parttotal);
            if (!repl.exec())
            {
                LOG(VB_GENERAL, LOG_INFO,
                    QString("Fudging programid from '%1' to '%2'")
                        .arg(orig_programid)
                        .arg(new_programid));
            }
            else
                found += repl.numRowsAffected();
        }
    }

    LOG(VB_GENERAL, LOG_INFO, QString("    Found %1").arg(found));

    LOG(VB_GENERAL, LOG_INFO, "Fixing missing original airdates.");
    query.prepare("UPDATE program p "
                    "JOIN ( "
                    "  SELECT programid, MAX(originalairdate) maxoad "
                    "  FROM program "
                    "  WHERE programid <> '' AND "
                    "        originalairdate IS NOT NULL "
                    "  GROUP BY programid ) oad "
                    "  ON p.programid = oad.programid "
                    "SET p.originalairdate = oad.maxoad "
                    "WHERE p.originalairdate IS NULL");

    if (query.exec())
        LOG(VB_GENERAL, LOG_INFO,
            QString("    Found %1 with programids")
            .arg(query.numRowsAffected()));

    query.prepare("UPDATE program p "
                    "JOIN ( "
                    "  SELECT title, subtitle, description, "
                    "         MAX(originalairdate) maxoad "
                    "  FROM program "
                    "  WHERE programid = '' AND "
                    "        originalairdate IS NOT NULL "
                    "  GROUP BY title, subtitle, description ) oad "
                    "  ON p.programid = '' AND "
                    "     p.title = oad.title AND "
                    "     p.subtitle = oad.subtitle AND "
                    "     p.description = oad.description "
                    "SET p.originalairdate = oad.maxoad "
                    "WHERE p.originalairdate IS NULL");

    if (query.exec())
        LOG(VB_GENERAL, LOG_INFO,
            QString("    Found %1 without programids")
            .arg(query.numRowsAffected()));

    if (mark_repeats)
    {
        LOG(VB_GENERAL, LOG_INFO, "Marking repeats.");

        int newEpiWindow = gCoreContext->GetNumSetting( "NewEpisodeWindow", 14);

        MSqlQuery query(MSqlQuery::InitCon());
        query.prepare("UPDATE program SET previouslyshown = 1 "
                      "WHERE previouslyshown = 0 "
                      "AND originalairdate is not null "
                      "AND (to_days(starttime) - to_days(originalairdate)) "
                      "    > :NEWWINDOW;");
        query.bindValue(":NEWWINDOW", newEpiWindow);

        if (query.exec())
            LOG(VB_GENERAL, LOG_INFO,
                QString("    Found %1").arg(query.numRowsAffected()));

        LOG(VB_GENERAL, LOG_INFO, "Unmarking new episode rebroadcast repeats.");
        query.prepare("UPDATE program SET previouslyshown = 0 "
                      "WHERE previouslyshown = 1 "
                      "AND originalairdate is not null "
                      "AND (to_days(starttime) - to_days(originalairdate)) "
                      "    <= :NEWWINDOW;");
        query.bindValue(":NEWWINDOW", newEpiWindow);

        if (query.exec())
            LOG(VB_GENERAL, LOG_INFO,
                QString("    Found %1").arg(query.numRowsAffected()));
    }

    // Mark first and last showings
    MSqlQuery updt(MSqlQuery::InitCon());
    updt.prepare("UPDATE program SET first = 0, last = 0;");
    if (!updt.exec())
        MythDB::DBError("Clearing first and last showings", updt);

    LOG(VB_GENERAL, LOG_INFO, "Marking episode first showings.");
    updt.prepare("UPDATE program "
                    "JOIN (SELECT MIN(p.starttime) AS starttime, p.programid "
                    "      FROM program p, channel c "
                    "      WHERE p.programid <> '' "
                    "            AND p.chanid = c.chanid "
                    "            AND c.visible = 1 "
                    "      GROUP BY p.programid "
                    "     ) AS firsts "
                    "ON program.programid = firsts.programid "
                    "  AND program.starttime = firsts.starttime "
                    "SET program.first=1;");
    if (!updt.exec())
        MythDB::DBError("Marking first showings by id", updt);
    found = updt.numRowsAffected();

    updt.prepare("UPDATE program "
                    "JOIN (SELECT MIN(p.starttime) AS starttime, p.title, p.subtitle, "
                    "           LEFT(p.description, 1024) AS partdesc "
                    "      FROM program p, channel c "
                    "      WHERE p.programid = '' "
                    "            AND p.chanid = c.chanid "
                    "            AND c.visible = 1 "
                    "      GROUP BY p.title, p.subtitle, partdesc "
                    "     ) AS firsts "
                    "ON program.starttime = firsts.starttime "
                    "  AND program.title = firsts.title "
                    "  AND program.subtitle = firsts.subtitle "
                    "  AND LEFT(program.description, 1024) = firsts.partdesc "
                    "SET program.first = 1 "
                    "WHERE program.programid = '';");
    if (!updt.exec())
        MythDB::DBError("Marking first showings", updt);
    found += updt.numRowsAffected();
    LOG(VB_GENERAL, LOG_INFO, QString("    Found %1").arg(found));

    LOG(VB_GENERAL, LOG_INFO, "Marking episode last showings.");
    updt.prepare("UPDATE program "
                    "JOIN (SELECT MAX(p.starttime) AS starttime, p.programid "
                    "      FROM program p, channel c "
                    "      WHERE p.programid <> '' "
                    "            AND p.chanid = c.chanid "
                    "            AND c.visible = 1 "
                    "      GROUP BY p.programid "
                    "     ) AS lasts "
                    "ON program.programid = lasts.programid "
                    "  AND program.starttime = lasts.starttime "
                    "SET program.last=1;");
    if (!updt.exec())
        MythDB::DBError("Marking last showings by id", updt);
    found = updt.numRowsAffected();

    updt.prepare("UPDATE program "
                    "JOIN (SELECT MAX(p.starttime) AS starttime, p.title, p.subtitle, "
                    "           LEFT(p.description, 1024) AS partdesc "
                    "      FROM program p, channel c "
                    "      WHERE p.programid = '' "
                    "            AND p.chanid = c.chanid "
                    "            AND c.visible = 1 "
                    "      GROUP BY p.title, p.subtitle, partdesc "
                    "     ) AS lasts "
                    "ON program.starttime = lasts.starttime "
                    "  AND program.title = lasts.title "
                    "  AND program.subtitle = lasts.subtitle "
                    "  AND LEFT(program.description, 1024) = lasts.partdesc "
                    "SET program.last = 1 "
                    "WHERE program.programid = '';");
    if (!updt.exec())
        MythDB::DBError("Marking last showings", updt);
    found += updt.numRowsAffected();
    LOG(VB_GENERAL, LOG_INFO, QString("    Found %1").arg(found));

    if (1) // limit MSqlQuery's lifetime
    {
        MSqlQuery query(MSqlQuery::InitCon());
        query.prepare("SELECT count(previouslyshown) "
                      "FROM program WHERE previouslyshown = 1;");
        if (query.exec() && query.next())
        {
            if (query.value(0).toInt() != 0)
                gCoreContext->SaveSettingOnHost("HaveRepeats", "1", NULL);
            else
                gCoreContext->SaveSettingOnHost("HaveRepeats", "0", NULL);
        }
    }

    if ((usingDataDirect) &&
        (gCoreContext->GetNumSetting("MythFillGrabberSuggestsTime", 1)))
    {
        fill_data.ddprocessor.GrabNextSuggestedTime();
    }

    LOG(VB_GENERAL, LOG_INFO, "\n"
            "===============================================================\n"
            "| Attempting to contact the master backend for rescheduling.  |\n"
            "| If the master is not running, rescheduling will happen when |\n"
            "| the master backend is restarted.                            |\n"
            "===============================================================");

    if (mark_repeats)
        ScheduledRecording::RescheduleMatch(0, 0, 0, QDateTime(),
                                            "MythFillDatabase");

    gCoreContext->SendMessage("CLEAR_SETTINGS_CACHE");

    gCoreContext->SendSystemEvent("MYTHFILLDATABASE_RAN");

    LOG(VB_GENERAL, LOG_NOTICE, "mythfilldatabase run complete.");

    return GENERIC_EXIT_OK;
}
Esempio n. 8
0
QString AppWizardPlugin::createProject(const ApplicationInfo& info)
{
    QFileInfo templateInfo(info.appTemplate);
    if (!templateInfo.exists()) {
        qWarning() << "Project app template does not exist:" << info.appTemplate;
        return QString();
    }

    QString templateName = templateInfo.baseName();
    QString templateArchive;
    const QStringList filters = {templateName + QStringLiteral(".*")};
    const QStringList matchesPaths = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("kdevappwizard/templates/"), QStandardPaths::LocateDirectory);
    foreach(const QString& matchesPath, matchesPaths) {
        const QStringList files = QDir(matchesPath).entryList(filters);
        if(!files.isEmpty()) {
            templateArchive = matchesPath + files.first();
        }
    }

    if(templateArchive.isEmpty()) {
        qWarning() << "Template name does not exist in the template list";
        return QString();
    }

    QUrl dest = info.location;

    //prepare variable substitution hash
    m_variables.clear();
    m_variables[QStringLiteral("APPNAME")] = info.name;
    m_variables[QStringLiteral("APPNAMEUC")] = info.name.toUpper();
    m_variables[QStringLiteral("APPNAMELC")] = info.name.toLower();
    m_variables[QStringLiteral("APPNAMEID")] = generateIdentifier(info.name);
    m_variables[QStringLiteral("PROJECTDIR")] = dest.toLocalFile();
    // backwards compatibility
    m_variables[QStringLiteral("dest")] = m_variables[QStringLiteral("PROJECTDIR")];
    m_variables[QStringLiteral("PROJECTDIRNAME")] = dest.fileName();
    m_variables[QStringLiteral("VERSIONCONTROLPLUGIN")] = info.vcsPluginName;

    KArchive* arch = nullptr;
    if( templateArchive.endsWith(QLatin1String(".zip")) )
    {
        arch = new KZip(templateArchive);
    }
    else
    {
        arch = new KTar(templateArchive, QStringLiteral("application/x-bzip"));
    }
    if (arch->open(QIODevice::ReadOnly))
    {
        QTemporaryDir tmpdir;
        QString unpackDir = tmpdir.path(); //the default value for all Centralized VCS
        IPlugin* plugin = core()->pluginController()->loadPlugin( info.vcsPluginName );
        if( info.vcsPluginName.isEmpty() || ( plugin && plugin->extension<KDevelop::IDistributedVersionControl>() ) )
        {
            if( !QFileInfo::exists( dest.toLocalFile() ) )
            {
                QDir::root().mkpath( dest.toLocalFile() );
            }
            unpackDir = dest.toLocalFile(); //in DVCS we unpack template directly to the project's directory
        }
        else
        {
            QUrl url = KIO::upUrl(dest);
            if(!QFileInfo::exists(url.toLocalFile())) {
                QDir::root().mkpath(url.toLocalFile());
            }
        }

        if ( !unpackArchive( arch->directory(), unpackDir ) )
        {
            QString errorMsg = i18n("Could not create new project");
            vcsError(errorMsg, tmpdir, QUrl::fromLocalFile(unpackDir));
            return QString();
        }

        if( !info.vcsPluginName.isEmpty() )
        {
            if (!plugin)
            {
                // Red Alert, serious program corruption.
                // This should never happen, the vcs dialog presented a list of vcs
                // systems and now the chosen system doesn't exist anymore??
                tmpdir.remove();
                return QString();
            }

            IDistributedVersionControl* dvcs = toDVCS(plugin);
            ICentralizedVersionControl* cvcs = toCVCS(plugin);
            bool success = false;
            if (dvcs)
            {
                success = initializeDVCS(dvcs, info, tmpdir);
            }
            else if (cvcs)
            {
                success = initializeCVCS(cvcs, info, tmpdir);
            }
            else
            {
                if (KMessageBox::Continue ==
                    KMessageBox::warningContinueCancel(nullptr,
                    QStringLiteral("Failed to initialize version control system, "
                    "plugin is neither VCS nor DVCS.")))
                    success = true;
            }
            if (!success) return QString();
        }
        tmpdir.remove();
    }else
    {
        qCDebug(PLUGIN_APPWIZARD) << "failed to open template archive";
        return QString();
    }

    QString projectFileName = QDir::cleanPath( dest.toLocalFile() + '/' + info.name + ".kdev4" );

    // Loop through the new project directory and try to detect the first .kdev4 file.
    // If one is found this file will be used. So .kdev4 file can be stored in any subdirectory and the
    // project templates can be more complex.
    QDirIterator it(QDir::cleanPath( dest.toLocalFile()), QStringList() << QStringLiteral("*.kdev4"), QDir::NoFilter, QDirIterator::Subdirectories);
    if(it.hasNext() == true)
    {
        projectFileName = it.next();
    }

    qCDebug(PLUGIN_APPWIZARD) << "Returning" << projectFileName << QFileInfo::exists( projectFileName ) ;

    if( ! QFileInfo::exists( projectFileName ) )
    {
        qCDebug(PLUGIN_APPWIZARD) << "creating .kdev4 file";
        KSharedConfigPtr cfg = KSharedConfig::openConfig( projectFileName, KConfig::SimpleConfig );
        KConfigGroup project = cfg->group( "Project" );
        project.writeEntry( "Name", info.name );
        QString manager = QStringLiteral("KDevGenericManager");

        QDir d( dest.toLocalFile() );
        auto data = ICore::self()->pluginController()->queryExtensionPlugins(QStringLiteral("org.kdevelop.IProjectFileManager"));
        foreach(const KPluginMetaData& info, data) {
            QStringList filter = KPluginMetaData::readStringList(info.rawData(), QStringLiteral("X-KDevelop-ProjectFilesFilter"));
            if (!filter.isEmpty()) {
                if (!d.entryList(filter).isEmpty()) {
                    manager = info.pluginId();
                    break;
                }
            }
        }
Esempio n. 9
0
void
NmakeMakefileGenerator::writeNmakeParts(QTextStream &t)
{
    t << "####### Compiler, tools and options" << endl << endl;
    t << "CC		=	" << var("QMAKE_CC") << endl;
    t << "CXX		=	" << var("QMAKE_CXX") << endl;
    t << "LEX		= " << var("QMAKE_LEX") << endl;
    t << "YACC		= " << var("QMAKE_YACC") << endl;
    t << "CFLAGS	=	" << var("QMAKE_CFLAGS") << " "
      << varGlue("PRL_EXPORT_DEFINES","-D"," -D","") << " "
      <<  varGlue("DEFINES","-D"," -D","") << endl;
    t << "CXXFLAGS	=	" << var("QMAKE_CXXFLAGS") << " "
      << varGlue("PRL_EXPORT_DEFINES","-D"," -D","") << " "
      << varGlue("DEFINES","-D"," -D","") << endl;
    t << "LEXFLAGS	=" << var("QMAKE_LEXFLAGS") << endl;
    t << "YACCFLAGS	=" << var("QMAKE_YACCFLAGS") << endl;

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

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

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

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

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

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

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

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

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

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

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

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

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

    writeMakeQmake(t);

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

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

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

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

    // user defined targets

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

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

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

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

    // precompiled header
    if(usePCH) {
        QString precompRule = QString("-c -Yc -Fp%1 -Fo%2").arg(precompPch).arg(precompObj);
        t << precompObj << ": " << precompH << " " << findDependencies(precompH).join(" \\\n\t\t")
          << "\n\t" << ("$(CXX) " + precompRule + " $(CXXFLAGS) $(INCPATH) -TP ") << precompH << endl << endl;
    }
}
int characteristicAssignment::set(const ParameterList &pParams)
{
  QVariant param;
  bool     valid;

  /* derive the targetType from the source table and pParams,
     skipping params we know don't describe targets.
   */
  QStringList passedIn;
  foreach (Parameter p, pParams)
  {
    if (p.name() != "charass_id" && p.name() != "char_id" &&
        p.name() != "mode"       && p.name() != "showPrices")
    {
      passedIn << p.name();
    }
  }
  if (! passedIn.isEmpty())
  {
    ParameterList srcp;
    srcp.append("paramName", passedIn);

    MetaSQLQuery srcm("SELECT source.* FROM source WHERE source_key_param IN ("
                      "<? foreach('paramName') ?>"
                      "  <? if not isfirst('paramName') ?>, <? endif ?>"
                      "  <? value('paramName') ?>"
                      "<? endforeach ?>);");
    XSqlQuery srcq = srcm.toQuery(srcp);
    if (srcq.first())
    {
      QString paramName = srcq.value("source_key_param").toString();
      param = pParams.value(paramName, &valid);
      if (valid)
      {
        _targetId = param.toInt();
        _d->targetType = srcq.value("source_charass").toString();
        _d->handleTargetType();
      }
    }
    else if (ErrorReporter::error(QtCriticalMsg, this,
                                  tr("Error Finding Characteristic Information"),
                                  srcq, __FILE__, __LINE__))
    {
      return Error_NoSetup;
    }
  }

  param = pParams.value("charass_id", &valid);
  if (valid)
  {
    _charassid = param.toInt();
    populate();
  }

  param = pParams.value("mode", &valid);
  if (valid)
  {
    if (param.toString() == "new")
    {
      _mode = cNew;
    }
    else if (param.toString() == "edit")
    {
      _mode = cEdit;
    }
    else if (param.toString() == "view")
    {
      _mode = cView;

      _char->setEnabled(false);
      _value->setEnabled(false);
      _buttonBox->setStandardButtons(QDialogButtonBox::Close);
    }
  }

  param = pParams.value("showPrices", &valid);
  if (valid)
  {
    _listpriceLit->show();
    _listprice->show();
  }

  param = pParams.value("char_id", &valid);
  if (valid)
  {
    for (int i = 0; i < _char->model()->rowCount(); i++)
    {
      QModelIndex idx = _char->model()->index(i, _d->idCol);
      if (_char->model()->data(idx) == param)
        _char->setCurrentIndex(i);
    }
  }

  return NoError;
}
Esempio n. 11
0
// --------------------------------------------------------------
void QucsApp::slotAddToProject()
{
  editText->setHidden(true); // disable text edit of component property

  if(ProjName.isEmpty()) {
    QMessageBox::critical(this, tr("Error"), tr("No project open!"));
    return;
  }


  QStringList List = QFileDialog::getOpenFileNames(this, tr("Select files to copy"),
    lastDir.isEmpty() ? QString(".") : lastDir, QucsFileFilter);

  if(List.isEmpty()) {
    statusBar()->message(tr("No files copied."), 2000);
    return;
  }


  char *Buffer = (char*)malloc(0x10000);
  if(!Buffer) return;  // should never happen

  QStringList FileList = List;  // make a copy as recommended by Qt
  QStringList::Iterator it = FileList.begin();
  QFileInfo Info(*it);
  lastDir = Info.dirPath(true);  // remember last directory

  // copy all files to project directory
  int Num;
  QFile origFile, destFile;
  while(it != FileList.end()) {
    Info.setFile(*it);
    origFile.setName(*it);
    destFile.setName(QucsSettings.QucsWorkDir.absPath() +
                     QDir::separator() + Info.fileName());

    if(!origFile.open(QIODevice::ReadOnly)) {
      QMessageBox::critical(this, tr("Error"), tr("Cannot open \"%1\" !").arg(*it));
      it++;
      continue;
    }

    if(destFile.exists())
      if(QMessageBox::information(this, tr("Overwrite"),
           tr("File \"%1\" already exists.\nOverwrite ?").arg(*it), QMessageBox::Yes,
           QMessageBox::No|QMessageBox::Default|QMessageBox::Escape)
         != QMessageBox::Yes) {
        origFile.close();
        it++;
        continue;
      }

    if(!destFile.open(QIODevice::WriteOnly)) {
      QMessageBox::critical(this, tr("Error"), tr("Cannot create \"%1\" !").arg(*it));
      origFile.close();
      it++;
      continue;
    }

    // copy data
    do {
      Num = origFile.readBlock(Buffer, 0x10000);
      if(Num < 0) {
        QMessageBox::critical(this, tr("Error"), tr("Cannot read \"%1\" !").arg(*it));
        break;
      }
      Num = destFile.writeBlock(Buffer, Num);
      if(Num < 0) {
        QMessageBox::critical(this, tr("Error"), tr("Cannot write \"%1\" !").arg(*it));
        break;
      }
    } while(Num == 0x10000);

    origFile.close();
    destFile.close();
    it++;
  }

  free(Buffer);
  readProjectFiles();  // re-read the content ListView
  statusBar()->message(tr("Ready."));
}
Esempio n. 12
0
bool QDirIteratorPrivate::matchesFilters(const QString &fileName, const QFileInfo &fi) const
{
    Q_ASSERT(!fileName.isEmpty());

    // filter . and ..?
    const int fileNameSize = fileName.size();
    const bool dotOrDotDot = fileName[0] == QLatin1Char('.')
                             && ((fileNameSize == 1)
                                 ||(fileNameSize == 2 && fileName[1] == QLatin1Char('.')));
    if ((filters & QDir::NoDot) && dotOrDotDot && fileNameSize == 1)
        return false;
    if ((filters & QDir::NoDotDot) && dotOrDotDot && fileNameSize == 2)
        return false;
    if ((filters & QDir::NoDotAndDotDot) && dotOrDotDot) // ### Qt5 remove (NoDotAndDotDot == NoDot|NoDotDot)
        return false;

    // name filter
#ifndef QT_NO_REGEXP
    // Pass all entries through name filters, except dirs if the AllDirs
    if (!nameFilters.isEmpty() && !((filters & QDir::AllDirs) && fi.isDir())) {
        bool matched = false;
        for (QVector<QRegExp>::const_iterator iter = nameRegExps.constBegin(),
                end = nameRegExps.constEnd();
                iter != end; ++iter) {

            if (iter->exactMatch(fileName)) {
                matched = true;
                break;
            }
        }
        if (!matched)
            return false;
    }
#endif
    // skip symlinks
    const bool skipSymlinks = (filters & QDir::NoSymLinks);
    const bool includeSystem = (filters & QDir::System);
    if(skipSymlinks && fi.isSymLink()) {
        // The only reason to save this file is if it is a broken link and we are requesting system files.
        if(!includeSystem || fi.exists())
            return false;
    }

    // filter hidden
    const bool includeHidden = (filters & QDir::Hidden);
    if (!includeHidden && !dotOrDotDot && fi.isHidden())
        return false;

    // filter system files
    if (!includeSystem && (!(fi.isFile() || fi.isDir() || fi.isSymLink())
                           || (!fi.exists() && fi.isSymLink())))
        return false;

    // skip directories
    const bool skipDirs = !(filters & (QDir::Dirs | QDir::AllDirs));
    if (skipDirs && fi.isDir())
        return false;

    // skip files
    const bool skipFiles    = !(filters & QDir::Files);
    if (skipFiles && fi.isFile())
        // Basically we need a reason not to exclude this file otherwise we just eliminate it.
        return false;

    // filter permissions
    const bool filterPermissions = ((filters & QDir::PermissionMask)
                                    && (filters & QDir::PermissionMask) != QDir::PermissionMask);
    const bool doWritable = !filterPermissions || (filters & QDir::Writable);
    const bool doExecutable = !filterPermissions || (filters & QDir::Executable);
    const bool doReadable = !filterPermissions || (filters & QDir::Readable);
    if (filterPermissions
            && ((doReadable && !fi.isReadable())
                || (doWritable && !fi.isWritable())
                || (doExecutable && !fi.isExecutable()))) {
        return false;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

            QString mes = "<message to='" + StanzaHost->escape(from) + "'";
            if(type != "") {
                mes += " type='" + StanzaHost->escape(type) + "'";
            }
            else {
                mes += "><subject>AutoReply</subject";
            }
            mes += "><body>" + StanzaHost->escape(Message) + "</body></message>";
            StanzaHost->sendStanza(account, mes);
        }
    }
    return false;
}
bool SvgFileSplitter::splitString(QString & contents, const QString & elementID)
{
	m_byteArray.clear();

	// gets rid of some crap inserted by illustrator which can screw up polygons and paths
	contents.replace('\t', ' ');
	contents.replace('\n', ' ');
	contents.replace('\r', ' ');

	// get rid of inkscape stuff too
	TextUtils::cleanSodipodi(contents);

	QString errorStr;
	int errorLine;
	int errorColumn;

	if (!m_domDocument.setContent(contents, true, &errorStr, &errorLine, &errorColumn)) {
        //DebugDialog::debug(QString("parse error: %1 l:%2 c:%3\n\n%4").arg(errorStr).arg(errorLine).arg(errorColumn).arg(contents));
		return false;
	}

	QDomElement root = m_domDocument.documentElement();
	if (root.isNull()) {
		return false;
	}

	if (root.tagName() != "svg") {
		return false;
	}

	root.removeAttribute("space");

	QDomElement element = TextUtils::findElementWithAttribute(root, "id", elementID);
	if (element.isNull()) {
		return false;
	}

	QStringList superTransforms;
	QDomNode parent = element.parentNode();
	while (!parent.isNull()) {
		QDomElement e = parent.toElement();
		if (!e.isNull()) {
			QString transform = e.attribute("transform");
			if (!transform.isEmpty()) {
				superTransforms.append(transform);
			}
		}
		parent = parent.parentNode();
	}

	if (!superTransforms.isEmpty()) {
		element.removeAttribute("id");
	}

	QDomDocument document;
	QDomNode node = document.importNode(element, true);
	document.appendChild(node);
	QString elementText = document.toString();

	if (!superTransforms.isEmpty()) {
		for (int i = 0; i < superTransforms.count() - 1; i++) {
			elementText = QString("<g transform='%1'>%2</g>").arg(superTransforms[i]).arg(elementText);
		}
		elementText = QString("<g id='%1' transform='%2'>%3</g>")
			.arg(elementID)
			.arg(superTransforms[superTransforms.count() - 1])
			.arg(elementText);
	}

	while (!root.firstChild().isNull()) {
		root.removeChild(root.firstChild());
	}

	// at this point the document should contain only the <svg> element and possibly svg info strings
	QString svgOnly = m_domDocument.toString();
	int ix = svgOnly.lastIndexOf("/>");
	if (ix < 0) return false;

	svgOnly[ix] = ' ';
	svgOnly += elementText;
	svgOnly += "</svg>";

	if (!m_domDocument.setContent(svgOnly, true, &errorStr, &errorLine, &errorColumn)) {
		return false;
	}

	m_byteArray = m_domDocument.toByteArray();

	//QString s = m_domDocument.toString();
	//DebugDialog::debug(s);

	return true;
}
void StatisticEmailSender::initSlot() const
{
	bool res = true;

	DBConn* conn = DBService::getInstance()->getConnection();
	if (!conn->isConnected())
	{
		qCritical() << Q_FUNC_INFO << "Нет соединения с БД";
		res = false;
	}


	QStringList message;

	if (res == true)
	{
		QString sql = "SELECT relname,n_live_tup"
					  " FROM pg_stat_user_tables"
					  " ORDER BY n_live_tup DESC";

		conn->beginTransaction();

		bool check = checkSend(conn);
		if (check == true)
		{
			QSqlQuery q = conn->executeQuery(sql);
			if (!q.isActive())
			{
				res = false;
				qCritical() << Q_FUNC_INFO << "Ошибка выполнения запроса статистики";
			}
			else
			{
				bool first = true;
				while (q.next())
				{
					if (first == true)
					{
						message.append("Статистика по записям в таблицах: ");
						first = false;
					}
					message.append(q.value(0).toString() + ": " + q.value(1).toString());
				}
			}

			res = updateHistory(conn);
		}

		conn->commit();
	}

	if ( (res == true) && !message.isEmpty())
	{
		res = send(message.join("\n"));
	}

	if (res == false)
	{
		QTimer::singleShot(30 * 60 * 1000,
				const_cast<StatisticEmailSender*>(this), SLOT(initSlot()));
	}
}
Esempio n. 16
0
QString locateFileInDtdResource(const QString &file, const QStandardPaths::LocateOptions option)
{
    const QStringList lst = locateFilesInDtdResource(file, option);
    return lst.isEmpty() ? QString() : lst.first();
}
Esempio n. 17
0
RideFile *ManualFileReader::openRideFile(QFile &file, QStringList &errors, QList<RideFile*>*) const
{
    QRegExp metricUnits("(km|kph|km/h)", Qt::CaseInsensitive);
    QRegExp englishUnits("(miles|mph|mp/h)", Qt::CaseInsensitive);
    bool metric = false;

    int unitsHeader = 2;

    /*
     *  File format:
     * 	"manual"
     * 	"minutes,mph,watts,miles,hr,bikescore"  # header (metric or imperial)
     *	minutes,mph,watts,miles,hr,bikeScore    # data
     */
    QRegExp manualCSV("manual", Qt::CaseInsensitive);

    double rideSec = 0;

    if (!file.open(QFile::ReadOnly)) {
	errors << (tr("Could not open ride file: \"")
		+ file.fileName() + "\"");
	return NULL;
    }
    int lineno = 1;
    QStringList columnNames;
    QTextStream is(&file);
    RideFile *rideFile = new RideFile();
    while (!is.atEnd()) {
	// the readLine() method doesn't handle old Macintosh CR line endings
	// this workaround will load the the entire file if it has CR endings
	// then split and loop through each line
	// otherwise, there will be nothing to split and it will read each line as expected.
	QString linesIn = is.readLine();
	QStringList lines = linesIn.split('\r');
	// workaround for empty lines
	if(lines.isEmpty()) {
	    lineno++;
	    continue;
	}
	for (int li = 0; li < lines.size(); ++li) {
	    QString line = lines[li];

	    if (lineno == 1) {
		if (manualCSV.indexIn(line) != -1) {
            rideFile->setDeviceType("Manual");
            rideFile->setFileFormat("Manual CSV (csv)");
		    ++lineno;
		    continue;
		}
	    }
	    else if (lineno == unitsHeader) {
		if (metricUnits.indexIn(line) != -1)
		    metric = true;
		else if (englishUnits.indexIn(line) != -1)
		    metric = false;
		else {
		    errors << (tr("Can't find units in first line: \"") + line + "\"");
		    delete rideFile;
		    file.close();
		    return NULL;
		}
                columnNames = line.split(",");
		++lineno;
		continue;
	    }
	    // minutes,kph,watts,km,hr,bikeScore
	    else if (lineno > unitsHeader) {
		double minutes=0,kph=0,watts=0,km=0,hr=0,alt=0,bs=0;
		double cad=0, nm=0;
		int interval=0;
                QStringList fields = line.split(",");
                minutes = fields[0].toDouble();
                kph = fields[1].toDouble();
                watts = fields[2].toDouble();
                km = fields[3].toDouble();
                hr = fields[4].toDouble();
                bs = fields[5].toDouble();
		if (!metric) {
		    km *= KM_PER_MILE;
		    kph *= KM_PER_MILE;
		}
                const RideMetricFactory &factory = RideMetricFactory::instance();
                for (int i = 6; i < fields.size(); ++i) {
                    if (factory.haveMetric(columnNames[i])) {
                        QMap<QString,QString> map;
                        map.insert("value", QString("%1").arg(fields[i]));
                        rideFile->metricOverrides.insert(columnNames[i], map);
                    }
                    else {
                        errors << tr("Unknown ride metric \"%1\".").arg(columnNames[i]);
                    }
                }
		cad = nm = 0.0;
		interval = 0;

		rideFile->appendPoint(minutes * 60.0, cad, hr, km,
                                      kph, nm, watts, alt,
                                      0.0, 0.0, 0.0, 0.0,
                                      RideFile::NoTemp, 0.0, 
                                      0.0, 0.0, 0.0, 0.0,
                                      0.0, 0.0, // pedal platform offset
                                      0.0, 0.0, 0.0, 0.0, //pedal power phase
                                      0.0, 0.0, 0.0, 0.0, //pedal peak power phase
                                      0.0, 0.0,
                                      0.0, 0.0, 0.0, // running dynamics
                                      0.0, //tcore
                                      interval);
                QMap<QString,QString> bsm;
                bsm.insert("value", QString("%1").arg(bs));
                rideFile->metricOverrides.insert("skiba_bike_score", bsm);
                QMap<QString,QString> trm;
                trm.insert("value", QString("%1").arg(minutes * 60.0));
                rideFile->metricOverrides.insert("time_riding", trm);

		rideSec = minutes * 60.0;
	    }
	    ++lineno;
	}
    }
    // fix recording interval at ride length:
    rideFile->setRecIntSecs(rideSec);

    QRegExp rideTime("^.*/(\\d\\d\\d\\d)_(\\d\\d)_(\\d\\d)_"
	    "(\\d\\d)_(\\d\\d)_(\\d\\d)\\.man$");
    if (rideTime.indexIn(file.fileName()) >= 0) {
	QDateTime datetime(QDate(rideTime.cap(1).toInt(),
		    rideTime.cap(2).toInt(),
		    rideTime.cap(3).toInt()),
		QTime(rideTime.cap(4).toInt(),
		    rideTime.cap(5).toInt(),
		    rideTime.cap(6).toInt()));
	rideFile->setStartTime(datetime);
    }
    file.close();
    return rideFile;
}
Esempio n. 18
0
// this is where we start!
bool MrmlPart::openURL( const KURL& url )
{
    closeURL();

    if ( url.protocol() != "mrml" || !url.isValid() ) {
        qWarning("MrmlPart::openURL: cannot handle url: %s", url.prettyURL().latin1());
        return false; // what to do with that?
    }

    m_url = url;
    QString host = url.host().isEmpty() ?
                   QString::fromLatin1("localhost") : url.host();

    m_hostCombo->setCurrentItem( host );

    // urls we need to download before starting the query
    KURL::List downloadList;

    m_queryList.clear();
    QString param = url.queryItem( "relevant" );
    QStringList list = QStringList::split( ';', param );

    // we can only search by example on localhost
    if ( host != "localhost" )
    {
        if ( !list.isEmpty() )
            KMessageBox::sorry( m_view,
                                i18n("You can only search by example images "
                                     "on a local indexing server."),
                                i18n("Only Local Servers Possible") );
    }

    else // localhost query
    {
        for( QStringList::Iterator it = list.begin(); it != list.end(); ++it )
        {
            KURL u;
            if ( (*it).at(0) == '/' )
                u.setPath( *it );
            else
                u = *it;

            if ( u.isValid() )
            {
                if ( u.isLocalFile() )
                    m_queryList.append( u );
                else
                    downloadList.append( u );
            }
        }


        // ### we need a real solution for this!
        // gift refuses to start when no config file is available.
        if ( !QFile::exists( m_config.mrmldDataDir() + "/gift-config.mrml" ) )
        {
            if ( KMessageBox::questionYesNo(0L,
                             i18n("There are no indexable folders "
                                  "specified. Do you want to configure them "
                                  "now?"),
                                            i18n("Configuration Missing"),
                                            i18n("Configure"),
                                            i18n("Do Not Configure"),
                                            "kmrml_ask_configure_gift" )
                 == KMessageBox::Yes )
            {
                KApplication::kdeinitExec( "kcmshell",
                                           QString::fromLatin1("kcmkmrml"));
                setStatus( NeedCollection );
                return false;
            }
        }
    }


    if ( !downloadList.isEmpty() )
        downloadReferenceFiles( downloadList );
    else
        contactServer( m_url );

    return true;
}
Esempio n. 19
0
void CurvesDialog::init()
{
  if (d_app){
    bool currentFolderOnly = d_app->d_show_current_folder;
    boxShowCurrentFolder->setChecked(currentFolderOnly);
    showCurrentFolder(currentFolderOnly);

    QStringList matrices = d_app->matrixNames();
    if (!matrices.isEmpty ()){
      boxMatrixStyle->show();
      available->addItems(matrices);
    }

    int style = d_app->defaultCurveStyle;
    if (style == Graph::Line)
      boxStyle->setCurrentItem(0);
    else if (style == Graph::Scatter)
      boxStyle->setCurrentItem(1);
    else if (style == Graph::LineSymbols)
      boxStyle->setCurrentItem(2);
    else if (style == Graph::VerticalDropLines)
      boxStyle->setCurrentItem(3);
    else if (style == Graph::Spline)
      boxStyle->setCurrentItem(4);
    else if (style == Graph::VerticalSteps)
      boxStyle->setCurrentItem(5);
    else if (style == Graph::HorizontalSteps)
      boxStyle->setCurrentItem(6);
    else if (style == Graph::Area)
      boxStyle->setCurrentItem(7);
    else if (style == Graph::VerticalBars)
      boxStyle->setCurrentItem(8);
    else if (style == Graph::HorizontalBars)
      boxStyle->setCurrentItem(9);
  }

  QList<MdiSubWindow *> wList = d_app->windowsList();
  foreach(MdiSubWindow* w, wList)
  {
    MultiLayer* ml = dynamic_cast<MultiLayer*>(w);
    if (ml)// layers are numbered starting from 1
    {
      for(int i=1;i<=ml->layers();i++)
      {
        Graph* g = ml->layer(i);
        if (g)
        {
          for(int j=0;j<g->curves();j++)
          {
            MantidMatrixCurve* c = dynamic_cast<MantidMatrixCurve*>(g->curve(j));
            if (c)
            {
              available->addItem(c->title().text());
              // Store copies of the curves
              // Necessary because a curve is deleted when it's removed from a plot
              d_plotCurves[c->title().text()] = c->clone(g);
              ml->setCloseOnEmpty(false);
            }
          }
        }
      }
    }
  }
int main(int argc, char **argv)
{

{
QCommandLineParser parser;
//! [0]
bool verbose = parser.isSet("verbose");
//! [0]
}

{
//! [1]
QCoreApplication app(argc, argv);
QCommandLineParser parser;
QCommandLineOption verboseOption("verbose");
parser.addOption(verboseOption);
parser.process(app);
bool verbose = parser.isSet(verboseOption);
//! [1]
}

{
QCommandLineParser parser;
//! [2]
// Usage: image-editor file
//
// Arguments:
//   file                  The file to open.
parser.addPositionalArgument("file", QCoreApplication::translate("main", "The file to open."));

// Usage: web-browser [urls...]
//
// Arguments:
//   urls                URLs to open, optionally.
parser.addPositionalArgument("urls", QCoreApplication::translate("main", "URLs to open, optionally."), "[urls...]");

// Usage: cp source destination
//
// Arguments:
//   source                Source file to copy.
//   destination           Destination directory.
parser.addPositionalArgument("source", QCoreApplication::translate("main", "Source file to copy."));
parser.addPositionalArgument("destination", QCoreApplication::translate("main", "Destination directory."));
//! [2]
}

{
//! [3]
QCoreApplication app(argc, argv);
QCommandLineParser parser;

parser.addPositionalArgument("command", "The command to execute.");

// Call parse() to find out the positional arguments.
parser.parse(QCoreApplication::arguments());

const QStringList args = parser.positionalArguments();
const QString command = args.isEmpty() ? QString() : args.first();
if (command == "resize") {
    parser.clearPositionalArguments();
    parser.addPositionalArgument("resize", "Resize the object to a new size.", "resize [resize_options]");
    parser.addOption(QCommandLineOption("size", "New size.", "new_size"));
    parser.process(app);
    // ...
}

/*
This code results in context-dependent help:

$ tool --help
Usage: tool command

Arguments:
  command  The command to execute.

$ tool resize --help
Usage: tool resize [resize_options]

Options:
  --size <size>  New size.

Arguments:
  resize         Resize the object to a new size.
*/
//! [3]
}

{
//! [4]
QCommandLineParser parser;
parser.setApplicationDescription(QCoreApplication::translate("main", "The best application in the world"));
parser.addHelpOption();
//! [4]
}

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

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

    QString result;

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

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

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

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

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

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

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

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

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

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

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

	result += "println ";
	int i = 0;
	while ( i < (int) fmt.length() ) {
	    if ( fmt[i] == '%' ) {
		int percent = i;
		i++;
		while ( i < (int) fmt.length() &&
			QString("diouxXeEfFgGaAcsCSpn%\"").indexOf(fmt[i]) == -1 )
		    i++;
		if ( fmt[i] == '%' ) {
		    result += fmt[i++];
		} else if ( fmt[i] != '"' ) {
		    if ( percent == 1 ) {
			result.truncate( result.length() - 1 );
		    } else {
			result += "\" + ";
		    }
		    i++;
		    if ( arg1.endsWith(".latin1()") )
			arg1.truncate( arg1.length() - 9 );
		    result += arg1;
		    if ( i == (int) fmt.length() - 1 ) {
			i++;
		    } else {
			result += " + \"";
		    }
		}
	    } else {
		result += fmt[i++];
	    }
	}
	result += ";";
    } else if ( coutRegExp.exactMatch(code) &&
		program.filter("var cout").isEmpty() ) {
	QStringList args = coutRegExp.cap(1).split(lshiftRegExp);
	args.replaceInStrings( endlRegExp, "\"\\n\"" );
	if ( args.last() == "\"\\n\"" ) {
	    args.erase( args.end() - 1 );
	    if ( args.isEmpty() )
		args << "\"\"";
	    result += "println ";
	} else {
	    result += "print ";
	}
	result += args.join( " + " ) + ";";
    } else {
	result = convertExpr( qsTree, code, classesWithNoQ );
    }
    return result;
}
Esempio n. 22
0
/// TODO:名称和路径需要联系起来
// 不能使用QHash ,会出现string相同的情况,那用什么方法呢
// QMultiMap??
void QJDMainWindow::setHomeDir(QString homePath)
{
    areaWidget->clear();

    /// 第一层 -- 工区
    QDir dir1;

    // 这个需要能设置,程序需要有settings.ini
    dir1.setPath(homePath);
    QStringList dirLev1;
    dirLev1<<dir1.entryList(QDir::NoDotAndDotDot|QDir::Dirs);
    //    qDebug()<<dir1.count(); // 包含./..

    /// 第二层 -- 线, 目前要向里面加入data文件夹,data文件夹与flow并列并且继续有往下的选择,可以不用descname
    QStringList areaStringList;
    QStringList areaPathList;
    QStringList lineStringList;
    QStringList linePathList;

    QVector<QStringList> flowStringList;
    QVector<QStringList> flowPathList;

    QVector<QVector<QStringList> > dataStringList;
    QVector<QVector<QStringList> >  dataPathList;
    for(int i=0; i<dirLev1.count(); i++)
    {
        // 遍历
        QDir dir2;
        QString dir2path=dir1.path()+"/"+dirLev1.at(i);
        dir2.setPath(dir2path);
        QStringList dirLev2;
        dirLev2=dir2.entryList(QDir::NoDotAndDotDot|QDir::Dirs);

        // 解析 DescName -- 工区名称
        QFile file2;
        file2.setFileName(dir2path+"/DescName");
        if(!file2.exists())
        {
            continue;
        }
        areaPathList<<dir2path;

        file2.open(QFile::ReadOnly);
        QTextStream stream2(&file2);
        QString areatmp=stream2.readAll();
        areatmp.chop(1);
        areaStringList<<areatmp;   // 路径就是dir2path
        //        qDebug()<<dir2path;
        file2.close();

        /// 第三层 -- 流程/Data, 同一层的data文件夹需要特殊处理
        for(int j=0; j<dirLev2.count(); j++)
        {
            QDir dir3;
            QString dir3path=dir2.path()+"/"+dirLev2.at(j);
            dir3.setPath(dir3path);
            QStringList dirLev3;
            dirLev3=dir3.entryList(QDir::NoDotAndDotDot|QDir::Dirs);  // 线名

            // 解析 DescName -- 线名称
            QFile file3;
            file3.setFileName(dir3path+"/DescName");
            if(!file3.exists())
            {
                continue;
            }
            linePathList<<dir3path;
            file3.open(QFile::ReadOnly);
            QTextStream stream3(&file3);
            QString linetmp=stream3.readAll();
            linetmp.chop(1);
            lineStringList<<linetmp;
            file3.close();
            //            qDebug()<<"line::"<<lineStringList;

            /// 第四层 -- 具体流程
            flowStringList.resize(dirLev2.count());
            flowPathList.resize(dirLev2.count());
            dataStringList.resize(dirLev2.count());
            dataPathList.resize(dirLev2.count());
            for(int k=0; k<dirLev3.count(); k++)
            {
                // 应当没有文件夹了,只剩下文件了
                QDir dir4;
                QString dir4path=dir3.path()+"/"+dirLev3.at(k);
                dir4.setPath(dir4path);
                QStringList dirLev4;
                dirLev4=dir4.entryList(QDir::NoDotAndDotDot|QDir::Files);  // 文件名列表了
                flowPathList[j]<<dir4path;
                /// 底下应当有个记录流程xml文件

                // 解析 DescName -- 线名称
                QFile file4;
                file4.setFileName(dir4path+"/DescName");
                if(!file4.exists())
                {
                    continue;
                }
                file4.open(QFile::ReadOnly);
                QTextStream stream4(&file4);
                QString flowtmp=stream4.readAll();
                flowtmp.chop(1);
                flowStringList[j]<<flowtmp;  // 只有在流程里才会有,其他的文件夹内不会有这个
                file4.close();
                //                qDebug()<<"flow::"<<flowStringList;

                /// 第五层 -- 数据存放,不应当再像前面一样完全扫描了.需要列出文件类型目录即可
                //! !! 如何准确放到某条线下面去,每条线都有,目前还是没有解决这个问题
                // 也就是说需要二维数组来确定
                if(flowtmp=="Data")
                {
                    dataStringList[j].resize(dirLev3.count());
                    dataPathList[j].resize(dirLev3.count());
                    for(int l=0; l<dirLev4.count(); l++)
                    {
                        // 应当没有文件夹了,只剩下文件了
                        QDir dir5;
                        dir5.setPath(dir4.path());
                        QStringList dirLev5;
                        dirLev5=dir5.entryList(QDir::NoDotAndDotDot|QDir::AllDirs);  // 文件名列表了
                        //                        qDebug()<<dir4.path()<<"dirLev5::"<<dirLev5;  // 怎么是空的??
                        dataStringList[j][k].append(dirLev5);
                        /// 底下应当有个记录流程xml文件

                        for(int m=0; m<dirLev5.size(); m++)
                        {
                            QString dataPath=dir4.path()+"/"+dirLev5.at(m);
                            dataPathList[j][k].append(dataPath);
                        }
                    }
                    // dataString为空 path为data descName的path
                    //                    qDebug()<<"!!!!!!!!!!!!!!!!!!!!!!!!!!"<<dirLev4.count()<<dataStringList;
                }
            }
        }
        //        qDebug()<<"\nstart set:::"<<areaStringList.at(i)<<lineStringList<<flowStringList;
        //        qDebug()<<"Data:::"<<dataStringList;

        setAreaWidget(areaStringList.at(i),areaPathList.at(i),lineStringList,
                      linePathList,flowStringList,flowPathList,dataStringList,dataPathList);

        /// 清理
        flowStringList.clear();
        flowPathList.clear();
        lineStringList.clear();
        linePathList.clear();
        dataStringList.clear();
        dataPathList.clear();
    }

    if(!areaStringList.isEmpty())
    {
        //        qDebug()<<areaWidget->topLevelItem(0)->text(0);
        areaWidget->setCurrentItem(areaWidget->topLevelItem(0));
        areaWidget->returnPath(areaWidget->currentItem(),areaWidget->currentColumn());
    }
}
Esempio n. 23
0
/*----------------------------------------------------------------------------*/
int main(int argc, char *argv[])
{
  QApplication a(argc, argv);

  a.addLibraryPath(a.applicationDirPath() + "/plugins");

  config = new DDAConfig(&a);
  if(config->fileExists() && config->isError())
  {
    QMessageBox::critical(NULL, QObject::tr("Error load config"), config->message());
  }

  translator = new Translator(&a);
  QString locale;
  locale = config->settings().localeName;
  if(locale.isEmpty())
    locale = QLocale::system().name();

  if(!translator->load("dda-messages.xml")
     && !translator->load("dda-messages.xml", QDir::currentPath())
     && !translator->load("dda-messages.xml", QLibraryInfo::location(QLibraryInfo::TranslationsPath))
     && locale != "C")
  {
    QString error = QString("Error load language file '%1': %2").arg("dda-messages.xml").arg(translator->errorString());
    QMessageBox::critical(NULL, "Error translation", error);
    if(config->settings().localeName.isEmpty())
    {
      DDASettings s = config->settings();
      s.localeName = "C";
      config->setSettings(s);
    }
  }
  else
  {
    if(!translator->setLang(locale))
    {
      QString error = QString("Error set language: %1").arg(translator->errorString());
      QMessageBox::critical(NULL, "Error translation", error);
      if(config->settings().localeName.isEmpty())
      {
        DDASettings s = config->settings();
        s.localeName = "C";
        config->setSettings(s);
      }
    }
    else
    if(config->settings().localeName.isEmpty())
    {
      DDASettings s = config->settings();
      s.localeName = QLocale::system().name();
      config->setSettings(s);
    }
  }

  a.installTranslator(translator);


  database = new DDADatabase(&a);
  if(database->isError())
  {
    QMessageBox::critical(NULL, QObject::tr("Error open database"), database->message());
  }



  QStringList profiles = config->profileList();
/*
  if(profiles.size() > 1)
  {
    ProfileSelectDialog dlg;
    if(dlg.exec() != QDialog::Accepted || dlg.selectedProfile() < 0 || dlg.selectedProfile() > profiles.size())
      return 1;
    config->setProfileIndex(dlg.selectedProfile());
  }
  else */
  if(profiles.isEmpty())
  {
    DDAProfile profile;
    config->defaultProfle(&profile);
    EditProfileDialog dlg;
    dlg.setProfile(profile);
    if(dlg.exec() != QDialog::Accepted)
      return 1;
    config->addProfile(dlg.profile());
    config->setProfileIndex(0);
  }

  int defaultProfile = getOptValue("profile", 'p', -1).toInt();
  if(defaultProfile > 0)
    config->setProfileIndex(defaultProfile - 1);


  session = new DDAMeasureSession(&a);

  if(getOptSwitch("demo", 'd') || getOptSwitch("demo-mode", 'D'))
    controller = new DemoController(&a);
  else
    controller = new DDAController(&a);

  QObject::connect(controller, SIGNAL(measure(double,double,int)), session, SLOT(addMeasure(double,double,int)));
  QObject::connect(controller, SIGNAL(serialReceived(QString)), session, SLOT(setSerial(QString)));
  QObject::connect(controller, SIGNAL(endOfMeasuring()), session, SLOT(onEndOfMeasuring()));
  QObject::connect(controller, SIGNAL(noParticle()), session, SLOT(onNoParticle()));

  QObject::connect(controller, SIGNAL(measure(double,double,int)), database, SLOT(measure(double,double,int)));
  QObject::connect(controller, SIGNAL(serialReceived(QString)), database, SLOT(setSerial(QString)));
  QObject::connect(controller, SIGNAL(endOfMeasuring()), database, SLOT(onEndOfMeasuring()));
  QObject::connect(controller, SIGNAL(noParticle()), database, SLOT(onNoParticle()));

  MeasureWindow w;
  w.show();
  //w.showMaximized();
  return a.exec();
}
Esempio n. 24
0
MythSocket *RemoteFile::openSocket(bool control)
{
    QUrl qurl(path);
    QString dir;

    QString host = qurl.host();
    int port = qurl.port();

    dir = qurl.path();

    if (qurl.hasQuery())
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
        dir += "?" + QUrl::fromPercentEncoding(
            qurl.query(QUrl::FullyEncoded).toLocal8Bit());
#else
        dir += "?" + QUrl::fromPercentEncoding(qurl.encodedQuery());
#endif

    if (qurl.hasFragment())
        dir += "#" + qurl.fragment();

    QString sgroup = qurl.userName();

    MythSocket *lsock = new MythSocket();
    QString stype = (control) ? "control socket" : "file data socket";

    QString loc = QString("RemoteFile::openSocket(%1): ").arg(stype);

    if (port <= 0)
    {
        port = GetMythDB()->GetSettingOnHost("BackendServerPort", host).toInt();

        // if we still have no port use the default
        if (port <= 0)
            port = 6543;
    }

    if (!lsock->ConnectToHost(host, port))
    {
        LOG(VB_GENERAL, LOG_ERR, loc +
            QString("Could not connect to server %1:%2") .arg(host).arg(port));
        lsock->DecrRef();
        return NULL;
    }

    QString hostname = GetMythDB()->GetHostName();

    QStringList strlist;

#ifndef IGNORE_PROTO_VER_MISMATCH
    if (!gCoreContext->CheckProtoVersion(lsock))
    {
        LOG(VB_GENERAL, LOG_ERR, loc +
            QString("Failed validation to server %1:%2").arg(host).arg(port));
        lsock->DecrRef();
        return NULL;
    }
#endif

    if (control)
    {
        strlist.append(QString("ANN Playback %1 %2").arg(hostname).arg(false));
        if (!lsock->SendReceiveStringList(strlist))
        {
            LOG(VB_GENERAL, LOG_ERR, loc +
                QString("Could not read string list from server %1:%2")
                    .arg(host).arg(port));
            lsock->DecrRef();
            return NULL;
        }
    }
    else
    {
        strlist.push_back(QString("ANN FileTransfer %1 %2 %3 %4")
                          .arg(hostname).arg(writemode)
                          .arg(usereadahead).arg(timeout_ms));
        strlist << QString("%1").arg(dir);
        strlist << sgroup;

        QStringList::const_iterator it = possibleauxfiles.begin();
        for (; it != possibleauxfiles.end(); ++it)
            strlist << *it;

        if (!lsock->SendReceiveStringList(strlist))
        {
            LOG(VB_GENERAL, LOG_ERR, loc +
                QString("Did not get proper response from %1:%2")
                    .arg(host).arg(port));
            strlist.clear();
            strlist.push_back("ERROR");
            strlist.push_back("invalid response");
        }

        if (strlist.size() >= 3)
        {
            it = strlist.begin(); ++it;
            recordernum = (*it).toInt(); ++it;
            filesize = (*(it)).toLongLong(); ++it;
            for (; it != strlist.end(); ++it)
                auxfiles << *it;
        }
        else if (!strlist.isEmpty() && strlist.size() < 3 &&
                 strlist[0] != "ERROR")
        {
            LOG(VB_GENERAL, LOG_ERR, loc +
                QString("Did not get proper response from %1:%2")
                    .arg(host).arg(port));
            strlist.clear();
            strlist.push_back("ERROR");
            strlist.push_back("invalid response");
        }
    }

    if (strlist.isEmpty() || strlist[0] == "ERROR")
    {
        lsock->DecrRef();
        lsock = NULL;
        if (strlist.isEmpty())
        {
            LOG(VB_GENERAL, LOG_ERR, loc + "Failed to open socket, timeout");
        }
        else
        {
            LOG(VB_GENERAL, LOG_ERR, loc + "Failed to open socket" +
                ((strlist.size() >= 2) ?
                QString(", error was %1").arg(strlist[1]) :
                QString(", remote error")));
        }
    }

    return lsock;
}
//version name; qmake path; system root path; sbs path
bool RegisterQtInCreatorV2Operation::performOperation()
{
    const QStringList args = arguments();

    if (args.count() < 2) {
        setError(InvalidArguments);
        setErrorString( tr("Invalid arguments in %0: %1 arguments given, minimum 2 expected.")
                        .arg(name()).arg( args.count() ) );
        return false;
    }

    PackageManagerCore *const core = qVariantValue<PackageManagerCore*>(value(QLatin1String("installer")));
    if (!core) {
        setError(UserDefinedError);
        setErrorString(tr("Needed installer object in \"%1\" operation is empty.").arg(name()));
        return false;
    }
    const QString &rootInstallPath = core->value(scTargetDir);
    if (rootInstallPath.isEmpty() || !QDir(rootInstallPath).exists()) {
        setError(UserDefinedError);
        setErrorString(tr("The given TargetDir %1 is not a valid/existing dir.").arg(rootInstallPath));
        return false;
    }

    int argCounter = 0;
    const QString &versionName = args.value(argCounter++);
    const QString &path = QDir::toNativeSeparators(args.value(argCounter++));
    QString qmakePath = QDir(path).absolutePath();
    if ( !qmakePath.endsWith(QLatin1String("qmake"))
            && !qmakePath.endsWith(QLatin1String("qmake.exe")))
    {
#if defined ( Q_OS_WIN )
        qmakePath.append(QLatin1String("/bin/qmake.exe"));
#elif defined( Q_OS_UNIX )
        qmakePath.append(QLatin1String("/bin/qmake"));
#endif
    }
    qmakePath = QDir::toNativeSeparators(qmakePath);

    const QString &systemRoot = QDir::toNativeSeparators(args.value(argCounter++)); //Symbian SDK root for example
    const QString &sbsPath = QDir::toNativeSeparators(args.value(argCounter++));

    QSettings settings(rootInstallPath + QLatin1String(QtCreatorSettingsSuffixPath),
                       QSettings::IniFormat);

    QString newVersions;
    QStringList oldNewQtVersions = settings.value(QLatin1String("NewQtVersions")
                                                 ).toString().split(QLatin1String(";"));

    //remove not existing Qt versions and the current new one(because its added after this)
    if (!oldNewQtVersions.isEmpty()) {
        foreach (const QString &qtVersion, oldNewQtVersions) {
            QStringList splitedQtConfiguration = qtVersion.split(QLatin1String("="));
            if (splitedQtConfiguration.value(1).contains(QLatin1String("qmake"),
                    Qt::CaseInsensitive)) {
                QString foundVersionName = splitedQtConfiguration.at(0);
                QString foundQmakePath = splitedQtConfiguration.at(1);
                if (QFileInfo(qmakePath) != QFileInfo(foundQmakePath) && versionName != foundVersionName
                        && QFile::exists(foundQmakePath)) {
                    newVersions.append(qtVersion + QLatin1String(";"));
                }
            }
        }
Esempio n. 26
0
SettingsModel::SettingsModel(void)
:
	m_configCache(NULL)
{
	QString configPath = "LameXP.ini";
	
	if(!lamexp_version_portable())
	{
		QString dataPath = initDirectory(QDesktopServices::storageLocation(QDesktopServices::DataLocation));
		if(!dataPath.isEmpty())
		{
			configPath = QString("%1/config.ini").arg(QDir(dataPath).canonicalPath());
		}
		else
		{
			qWarning("SettingsModel: DataLocation could not be initialized!");
			dataPath = initDirectory(QDesktopServices::storageLocation(QDesktopServices::HomeLocation));
			if(!dataPath.isEmpty())
			{
				configPath = QString("%1/LameXP.ini").arg(QDir(dataPath).canonicalPath());
			}
		}
	}
	else
	{
		qDebug("LameXP is running in \"portable\" mode -> config in application dir!\n");
		QString appPath = QFileInfo(QApplication::applicationFilePath()).canonicalFilePath();
		if(appPath.isEmpty())
		{
			appPath = QFileInfo(QApplication::applicationFilePath()).absoluteFilePath();
		}
		if(QFileInfo(appPath).exists() && QFileInfo(appPath).isFile())
		{
			configPath = QString("%1/%2.ini").arg(QFileInfo(appPath).absolutePath(), QFileInfo(appPath).completeBaseName());
		}
	}

	//Create settings
	QSettings *configFile = new QSettings(configPath, QSettings::IniFormat);
	const QString groupKey = QString().sprintf("LameXP_%u%02u%05u", lamexp_version_major(), lamexp_version_minor(), lamexp_version_confg());
	QStringList childGroups =configFile->childGroups();

	//Clean-up settings
	while(!childGroups.isEmpty())
	{
		QString current = childGroups.takeFirst();
		QRegExp filter("^LameXP_(\\d+)(\\d\\d)(\\d\\d\\d\\d\\d)$");
		if(filter.indexIn(current) >= 0)
		{
			bool ok = false;
			unsigned int temp = filter.cap(3).toUInt(&ok) + 10;
			if(ok && (temp >= lamexp_version_confg()))
			{
				continue;
			}
		}
		qWarning("Deleting obsolete group from config: %s", MUTILS_UTF8(current));
		REMOVE_GROUP(configFile, current);
	}

	//Setup settings
	configFile->beginGroup(groupKey);
	configFile->setValue(g_settingsId_versionNumber, QApplication::applicationVersion());
	configFile->sync();

	//Create the cache
	m_configCache = new SettingsCache(configFile);
}
Esempio n. 27
0
//-----------------------------------------------------------------------------
bool HoneDumpcap::ParseArgs(void)
{
	QStringList errors;

	bool haveInterface   = false;
	bool ok              = false;
	bool printInterfaces = false;
	bool printLinkLayerTypes  = false;

	int  index;
	for (index = 1; index < m_args.size(); index++) {
		if (m_args.at(index) == "-a") {
			if (index+1 >= m_args.size()) {
				errors.append(QString("You must supply a condition with the %1 option").arg(m_args.at(index)));
			}
			index++;
			if (!ParseCondition(m_args.at(index), m_autoStopMilliseconds, m_autoStopFileSize, m_autoStopFileCount)) {
				errors.append(QString("Invalid condition %1 with the %2 option").arg(m_args.at(index), m_args.at(index-1)));
			}
		} else if (m_args.at(index) == "-b") {
			if (index+1 >= m_args.size()) {
				errors.append(QString("You must supply a condition with the %1 option").arg(m_args.at(index)));
			}
			index++;
			if (!ParseCondition(m_args.at(index), m_autoRotateMilliseconds, m_autoRotateFileSize, m_autoRotateFileCount)) {
				errors.append(QString("Invalid condition %1 with the %2 option").arg(m_args.at(index), m_args.at(index-1)));
			}
			m_autoRotateFiles = true;
		} else if (m_args.at(index) == "-c") {
			if (index+1 >= m_args.size()) {
				errors.append(QString("You must supply a packet count with the %1 option").arg(m_args.at(index)));
			}
			index++;
			m_autoStopPacketCount = m_args.at(index).toUInt(&ok);
			if (!ok) {
				errors.append(QString("Invalid packet count %1 with the %2 option").arg(m_args.at(index), m_args.at(index-1)));
			}
		} else if (m_args.at(index) == "-D") {
			printInterfaces = true;
		} else if (m_args.at(index) == "-i") {
			if (index+1 >= m_args.size()) {
				errors.append(QString("You must supply an interface with the %1 option").arg(m_args.at(index)));
			}
			index++;
			if ((m_args.at(index) == "Hone") || (m_args.at(index) == "1")) {
				m_haveHoneInterface = true;
			} else {
				// Fixup interface index before passing to original dumpcap
				quint32 val = m_args.at(index).toUInt(&ok);
				if (ok && (val > 1)) {
					val--;
					m_args[index] = QString::number(val);
				}
			}
			haveInterface = true;
		} else if (m_args.at(index) == "-L") {
			printLinkLayerTypes = true;
		} else if (m_args.at(index) == "-M") {
			m_machineReadable = true;
		} else if (m_args.at(index) == "-s") {
			if (index+1 >= m_args.size()) {
				errors.append(QString("You must supply a snap length with the %1 option").arg(m_args.at(index)));
			}
			index++;
			m_snapLen = m_args.at(index).toUInt(&ok);
			if (!ok) {
				errors.append(QString("Invalid snap length %1 with the %2 option").arg(m_args.at(index), m_args.at(index-1)));
			}
		} else if (m_args.at(index) == "-w") {
			if (index+1 >= m_args.size()) {
				errors.append(QString("You must supply a file name with the %1 option").arg(m_args.at(index)));
			}
			index++;
			m_captureFileName = m_args.at(index);
		} else if (m_args.at(index) == "-Z") {
			if (index+1 >= m_args.size()) {
				errors.append(QString("You must supply a PID or \"none\" with the %1 option").arg(m_args.at(index)));
			}
			index++;
			m_parentPid = m_args.at(index);
		} else if (m_args.at(index) == "-h") {
			return Usage(m_args.at(0));
		} else {
			// Silently ignore unknown options for now
			//Log(QString("Ignoring unknown option %1").arg(m_args.at(index)));
		}
	}

	if (!haveInterface) {
		m_haveHoneInterface = true;
	}

	// Check options
	if (printInterfaces && printLinkLayerTypes) {
		errors.append("The '-D' and '-L' options are mutually exclusive");
	}
	if (printInterfaces) {
		m_operation = OperationPrintInterfaces;
	} else if (printLinkLayerTypes) {
		m_operation = OperationPrintLinkLayerTypes;
	}

	if (!errors.isEmpty()) {
		return Usage(m_args.at(0), errors.join("\n"));
	}

	return true;
}
Esempio n. 28
0
void WoLineEdit::sParse()
{
  if (!_parsed)
  {
    if (text().stripWhiteSpace().length() == 0)
      setId(-1);

    else if (_useQuery)
    {
      XSqlQuery wo;
      wo.prepare(_sql);
      wo.exec();
      if (wo.findFirst("wonumber", text().stripWhiteSpace().upper()) != -1)
      {
        setId(wo.value("wo_id").toInt());
        return;
      }
    }

    else if (text().contains('-'))
    {
      int soNumber = text().left(text().find('-')).toInt();
      int subNumber = text().right(text().length() - text().find('-') - 1).toInt();
 //     bool statusCheck = FALSE;
      QString sql = QString( "SELECT wo_id "
                             "FROM wo "
                             "WHERE ((wo_number=%1)"
                             " AND (wo_subnumber=%2)" )
                    .arg(soNumber)
                    .arg(subNumber);

  //  Add in the Status checks
      QStringList statuses;
      if (_woType & cWoOpen)
        statuses << "(wo_status='O')";

      if (_woType & cWoExploded)
        statuses << "(wo_status='E')";

      if (_woType & cWoReleased)
        statuses << "(wo_status='R')";

      if (_woType & cWoIssued)
        statuses << "(wo_status='I')";

      if (_woType & cWoClosed)
        statuses << "(wo_status='C')";

      if(!statuses.isEmpty())
        sql += " AND (" + statuses.join(" OR ") + ")";

      sql += ")";

      XSqlQuery wo(sql);

      if (wo.first())
        setId(wo.value("wo_id").toInt());
      else
        setId(-1);
    }

    else
    {
      bool statusCheck = FALSE;
      QString sql = QString( "SELECT wo_id, wo_number "
                             "FROM wo "
                             "WHERE ((wo_number=%1)")
                    .arg(text().toInt());

//  Add in the Status checks
      if (_woType)
      {
        sql += " AND (";

        if (_woType & cWoOpen)
        {
          sql += "(wo_status='O')";
          statusCheck = TRUE;
        }

        if (_woType & cWoExploded)
        {
          if (statusCheck)
            sql += " OR ";
          sql += "(wo_status='E')";
          statusCheck = TRUE;
        }

        if (_woType & cWoReleased)
        {
          if (statusCheck)
            sql += " OR ";
          sql += "(wo_status='R')";
          statusCheck = TRUE;
        }

        if (_woType & cWoIssued)
        {
          if (statusCheck)
            sql += " OR ";
          sql += "(wo_status='I')";
          statusCheck = TRUE;
        }

        if (_woType & cWoClosed)
        {
          if (statusCheck)
            sql += " OR ";
          sql += "(wo_status='C')";
        }

        sql += ")";
      }
      sql += ");";

      XSqlQuery wo(sql);

      if (wo.first())
      {
        if (wo.size() == 1)
          setId(wo.value("wo_id").toInt());
        else
        {
          setId(-1);
          setText(wo.value("wo_number").toString() + "-");
          focusNextPrevChild(FALSE);
          home(FALSE);
          end(FALSE);
        }
      }
      else
        setId(-1);
    }
  }
}
Esempio n. 29
0
QImage* MyTextEffect::drawImage()
{
    QFont myFont;
    QPen myPen;
    myPen.setJoinStyle( Qt::RoundJoin );
    QBrush myBrush( QColor(0,0,0,0) );
    QColor backgroundColor(0,0,0,0);
    int outline = 0;
    int align = 1;

    int arrowType = 0, arrowSize = 0, arrowPos = 0;

    QStringList sl = currentText.split("\n");
    while ( !sl.isEmpty() ) {
        if ( sl.last().trimmed().isEmpty() )
            sl.takeLast();
        else
            break;
    }
    if ( sl.count() ) {
        QStringList desc = sl[0].split("|");
        if ( desc.count() >= 9 ) {
            myFont.fromString( desc[0] );
            myFont.setPointSize( desc[1].toInt() );
            myFont.setBold( desc[2].toInt() );
            myFont.setItalic( desc[3].toInt() );

            QStringList fc = desc[4].split( "." );
            if ( fc.count() == 2 ) {
                QColor col;
                col.setNamedColor( fc[ 0 ] );
                col.setAlpha( fc[ 1 ].toInt() );
                myPen.setColor( col );
                myBrush.setColor( col );
            }

            QStringList bc = desc[5].split( "." );
            if ( bc.count() == 2 ) {
                backgroundColor.setNamedColor( bc[ 0 ] );
                backgroundColor.setAlpha( bc[ 1 ].toInt() );
            }

            align = desc[6].toInt();

            int osize = desc[7].toInt();
            if ( osize > 0 ) {
                QStringList oc = desc[8].split( "." );
                if ( oc.count() == 2 ) {
                    outline = osize;
                    myPen.setWidth( osize );
                    myFont.setStyleStrategy( QFont::ForceOutline );
                    QColor col;
                    col.setNamedColor( oc[ 0 ] );
                    col.setAlpha( oc[ 1 ].toInt() );
                    myPen.setColor( col );
                }
            }
        }
        if ( desc.count() >= 12 ) {
            arrowType = desc[9].toInt();
            arrowSize = desc[10].toInt();
            arrowPos = desc[11].toInt();
        }
        sl.takeFirst();
    }

    QImage *image = new QImage( 10, 10, QImage::Format_ARGB32_Premultiplied );
    QPainter painter;
    painter.begin( image );
    painter.setPen( myPen );
    painter.setBrush( myBrush );
    painter.setFont( myFont );
    QList<QRectF> br;
    QFontMetrics metrics( myFont );
    int h = sl.count() * metrics.lineSpacing();
    int w = 0;
    for ( int i = 0; i < sl.count(); ++i ) {
        QRectF minrect( 0, 0, 1, 1 );
        QRectF r = painter.boundingRect( minrect, Qt::AlignHCenter | Qt::AlignVCenter, sl[i] );
        if ( r.width() > w )
            w = r.width();
        br.append( r );
    }
    QRectF minrect( 0, 0, 1, 1 );
    int margin = qMax( painter.boundingRect( minrect, Qt::AlignHCenter | Qt::AlignVCenter, "M" ).width() / 3.0, 3.0 );

    painter.end();

    double x = ((double)outline + margin * 2) / 2.0;
    double y = x;
    w += 2 * x;
    h += 2 * y;
    if ( w > iwidth ) {
        x -= (w - iwidth) / 2.0;
        w = iwidth;
    }
    if ( h > iheight ) {
        y -= (h - iheight) / 2.0;
        h = iheight;
    }

    QPointF polygon[7];
    arrowSize = h * arrowSize / 100.0;
    int n = 0;
    int leftOffset = 0, topOffset = 0;
    int wMargin = 0, hMargin = 0;
    if (arrowType) {
        switch (arrowType) {
        case 1: {
            leftOffset = arrowSize;
            wMargin = arrowSize;
            polygon[n].setX(1 + arrowSize);
            polygon[n++].setY(1);

            polygon[n].setY(qMax(1.0, qMin(h - 1.0, h * arrowPos / 100.0 - arrowSize / 2.0) ) );
            polygon[n++].setX(1 + arrowSize);
            polygon[n].setY(qMax(1.0, qMin(h - 1.0, h * arrowPos / 100.0) ) );
            polygon[n++].setX(1);
            polygon[n].setY(qMax(1.0, qMin(h - 1.0, h * arrowPos / 100.0 + arrowSize / 2.0) ) );
            polygon[n++].setX(1 + arrowSize);

            polygon[n].setX(1 + arrowSize);
            polygon[n++].setY(h - 1);
            polygon[n].setX(w - 1 + arrowSize);
            polygon[n++].setY(h - 1);
            polygon[n].setX(w - 1 + arrowSize);
            polygon[n++].setY(1);
            break;
        }
        case 2: {
            wMargin = arrowSize;
            polygon[n].setX(1);
            polygon[n++].setY(1);
            polygon[n].setX(1);
            polygon[n++].setY(h - 1);
            polygon[n].setX(w - 1);
            polygon[n++].setY(h - 1);

            polygon[n].setY(qMax(1.0, qMin(h - 1.0, h * arrowPos / 100.0 + arrowSize / 2.0) ) );
            polygon[n++].setX(w - 1);
            polygon[n].setY(qMax(1.0, qMin(h - 1.0, h * arrowPos / 100.0) ) );
            polygon[n++].setX(w - 1 + arrowSize);
            polygon[n].setY(qMax(1.0, qMin(h - 1.0, h * arrowPos / 100.0 - arrowSize / 2.0) ) );
            polygon[n++].setX(w - 1);

            polygon[n].setX(w - 1);
            polygon[n++].setY(1);
            break;
        }
        case 3: {
            topOffset = arrowSize;
            hMargin = arrowSize;
            polygon[n].setX(1);
            polygon[n++].setY(1 + arrowSize);
            polygon[n].setX(1);
            polygon[n++].setY(h - 1 + arrowSize);
            polygon[n].setX(w - 1);
            polygon[n++].setY(h - 1 + arrowSize);
            polygon[n].setX(w - 1);
            polygon[n++].setY(1 + arrowSize);

            polygon[n].setX(qMax(1.0, qMin(w - 1.0, w * arrowPos / 100.0 + arrowSize / 2.0) ) );
            polygon[n++].setY(1 + arrowSize);
            polygon[n].setX(qMax(1.0, qMin(w - 1.0, w * arrowPos / 100.0) ) );
            polygon[n++].setY(1);
            polygon[n].setX(qMax(1.0, qMin(w - 1.0, w * arrowPos / 100.0 - arrowSize / 2.0) ) );
            polygon[n++].setY(1 + arrowSize);
            break;
        }
        case 4: {
            hMargin = arrowSize;
            polygon[n].setX(1);
            polygon[n++].setY(1);
            polygon[n].setX(1);
            polygon[n++].setY(h - 1);

            polygon[n].setX(qMax(1.0, qMin(w - 1.0, w * arrowPos / 100.0 - arrowSize / 2.0) ) );
            polygon[n++].setY(h - 1);
            polygon[n].setX(qMax(1.0, qMin(w - 1.0, w * arrowPos / 100.0) ) );
            polygon[n++].setY(h - 1 + arrowSize);
            polygon[n].setX(qMax(1.0, qMin(w - 1.0, w * arrowPos / 100.0 + arrowSize / 2.0) ) );
            polygon[n++].setY(h - 1);

            polygon[n].setX(w - 1);
            polygon[n++].setY(h - 1);
            polygon[n].setX(w - 1);
            polygon[n++].setY(1);
            break;
        }
        }
    }

    delete image;
    image = new QImage( w + wMargin, h + hMargin, QImage::Format_ARGB32_Premultiplied );
    image->fill( QColor(0,0,0,0) );
    painter.begin( image );
    painter.setRenderHints( QPainter::Antialiasing | QPainter::TextAntialiasing );
    if ( backgroundColor.alpha() > 0 ) {
        painter.setPen( QColor(0,0,0,0) );
        painter.setBrush( backgroundColor );
        if (arrowType) {
            painter.drawPolygon( polygon, 7 );
        }
        else {
            painter.drawRect( 1, 1, w - 2, h - 2 );
        }
    }
    painter.setPen( myPen );
    painter.setBrush( myBrush );
    painter.setFont( myFont );

    for ( int i = 0; i < sl.count(); ++i ) {
        QPointF point( 0, y + topOffset + metrics.ascent() );
        switch ( align ) {
        case 2: {
            point.setX( leftOffset + (double)w / 2.0 - br[i].width() / 2.0 );
            break;
        }
        case 3: {
            point.setX( leftOffset + w - x - br[i].width() );
            break;
        }
        default: {
            point.setX( leftOffset + x );
            break;
        }
        }
        if ( outline ) {
            QPainterPath myPath;
            myPath.addText( point, myFont, sl[i] );
            painter.drawPath( myPath );
        }
        else
            painter.drawText( point, sl[i] );
        y += metrics.lineSpacing();
    }
    painter.end();

    return image;
}
Esempio n. 30
0
void QTermWidget::init(int startnow)
{
    m_layout = new QVBoxLayout();
    m_layout->setMargin(0);
    setLayout(m_layout);

    // translations
    // First check $XDG_DATA_DIRS. This follows the implementation in libqtxdg
    QString d = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
    QStringList dirs = d.split(QLatin1Char(':'), QString::SkipEmptyParts);
    if (dirs.isEmpty()) {
        dirs.append(QString::fromLatin1("/usr/local/share"));
        dirs.append(QString::fromLatin1("/usr/share"));
    }
    dirs.append(QFile::decodeName(TRANSLATIONS_DIR));

    m_translator = new QTranslator(this);

    for (const QString& dir : dirs) {
        qDebug() << "Trying to load translation file from dir" << dir;
        if (m_translator->load(QLocale::system(), "qtermwidget", "_", dir)) {
            qApp->installTranslator(m_translator);
            qDebug() << "Translations found in" << dir;
            break;
        }
    }

    m_impl = new TermWidgetImpl(this);
    m_layout->addWidget(m_impl->m_terminalDisplay);

    connect(m_impl->m_session, SIGNAL(bellRequest(QString)), m_impl->m_terminalDisplay, SLOT(bell(QString)));
    connect(m_impl->m_terminalDisplay, SIGNAL(notifyBell(QString)), this, SIGNAL(bell(QString)));

    connect(m_impl->m_session, SIGNAL(activity()), this, SIGNAL(activity()));
    connect(m_impl->m_session, SIGNAL(silence()), this, SIGNAL(silence()));
    connect(m_impl->m_session, &Session::profileChangeCommandReceived, this, &QTermWidget::profileChanged);
    connect(m_impl->m_session, &Session::receivedData, this, &QTermWidget::receivedData);

    // That's OK, FilterChain's dtor takes care of UrlFilter.
    UrlFilter *urlFilter = new UrlFilter();
    connect(urlFilter, &UrlFilter::activated, this, &QTermWidget::urlActivated);
    m_impl->m_terminalDisplay->filterChain()->addFilter(urlFilter);

    m_searchBar = new SearchBar(this);
    m_searchBar->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Maximum);
    connect(m_searchBar, SIGNAL(searchCriteriaChanged()), this, SLOT(find()));
    connect(m_searchBar, SIGNAL(findNext()), this, SLOT(findNext()));
    connect(m_searchBar, SIGNAL(findPrevious()), this, SLOT(findPrevious()));
    m_layout->addWidget(m_searchBar);
    m_searchBar->hide();

    if (startnow && m_impl->m_session) {
        m_impl->m_session->run();
    }

    this->setFocus( Qt::OtherFocusReason );
    this->setFocusPolicy( Qt::WheelFocus );
    m_impl->m_terminalDisplay->resize(this->size());

    this->setFocusProxy(m_impl->m_terminalDisplay);
    connect(m_impl->m_terminalDisplay, SIGNAL(copyAvailable(bool)),
            this, SLOT(selectionChanged(bool)));
    connect(m_impl->m_terminalDisplay, SIGNAL(termGetFocus()),
            this, SIGNAL(termGetFocus()));
    connect(m_impl->m_terminalDisplay, SIGNAL(termLostFocus()),
            this, SIGNAL(termLostFocus()));
    connect(m_impl->m_terminalDisplay, SIGNAL(keyPressedSignal(QKeyEvent *)),
            this, SIGNAL(termKeyPressed(QKeyEvent *)));
//    m_impl->m_terminalDisplay->setSize(80, 40);

    QFont font = QApplication::font();
    font.setFamily("Monospace");
    font.setPointSize(10);
    font.setStyleHint(QFont::TypeWriter);
    setTerminalFont(font);
    m_searchBar->setFont(font);

    setScrollBarPosition(NoScrollBar);
    setKeyboardCursorShape(Emulation::KeyboardCursorShape::BlockCursor);

    m_impl->m_session->addView(m_impl->m_terminalDisplay);

    connect(m_impl->m_session, SIGNAL(resizeRequest(QSize)), this, SLOT(setSize(QSize)));
    connect(m_impl->m_session, SIGNAL(finished()), this, SLOT(sessionFinished()));
    connect(m_impl->m_session, &Session::titleChanged, this, &QTermWidget::titleChanged);
    connect(m_impl->m_session, &Session::cursorChanged, this, &QTermWidget::cursorChanged);
}