Example #1
0
QStringList gpu::getGLXInfo(QString gpuName) const {
    QStringList data, gpus = globalStuff::grabSystemInfo("lspci").filter(QRegExp(".+VGA.+|.+3D.+"));
    gpus.removeAt(gpus.indexOf(QRegExp(".+Audio.+"))); //remove radeon audio device

    // loop for multi gpu
    for (int i = 0; i < gpus.count(); i++)
        data << "VGA:"+gpus[i].split(":",QString::SkipEmptyParts)[2];

    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    if (!gpuName.isEmpty())
        env.insert("DRI_PRIME",gpuName.at(gpuName.length()-1));
    QStringList driver = globalStuff::grabSystemInfo("xdriinfo",env).filter("Screen 0:",Qt::CaseInsensitive);
    if (!driver.isEmpty())  // because of segfault when no xdriinfo
        data << "Driver:"+ driver.filter("Screen 0:",Qt::CaseInsensitive)[0].split(":",QString::SkipEmptyParts)[1];

    switch (currentDriver) {
    case XORG:
        data << dXorg::getGLXInfo(gpuName, env);
        break;
    case FGLRX:
        data << dFglrx::getGLXInfo();
        break;
    case DRIVER_UNKNOWN:
        break;
    }
    return data;
}
void SearchWidget::changeList2(QNetworkReply *reply)
{
    qDebug()<<"danny error type"<<reply->error();

    if(reply->error()== QNetworkReply::NoError)
    {
        lyricList.clear();
        //QString text = reply->readAll();

        QByteArray bytes = reply->readAll();  //获取字节
        QString result(bytes);  //转化为字符串
        qDebug()<<"changeList2 result:"<<result;
        qDebug()<<"changeList2 reply:"<<bytes;
        QTextCodec *codec = QTextCodec::codecForName("utf-8");
        //QString str = "0891683108500145F1240D91685143256178F0000831214281659423044F60597D";
        QString t = result;
        QStringList s;

        for(int i = 0;i < t.length();i += 4) {
        s.append(t.mid(i,4));
        }
        QString t1;

        foreach (const QString &t, s) {
        t1.append(t.toUShort(0,16));
        }
/*
 * Check for LameXP "portable" mode
 */
bool lamexp_portable_mode(void)
{
	QReadLocker readLock(&g_lamexp_portable.lock);

	if(g_lamexp_portable.bInitialized)
	{
		return g_lamexp_portable.bPortableModeEnabled;
	}
	
	readLock.unlock();
	QWriteLocker writeLock(&g_lamexp_portable.lock);

	if(!g_lamexp_portable.bInitialized)
	{
		if(VER_LAMEXP_PORTABLE_EDITION)
		{
			qWarning("LameXP portable edition!\n");
			g_lamexp_portable.bPortableModeEnabled = true;
		}
		else
		{
			QString baseName = QFileInfo(QApplication::applicationFilePath()).completeBaseName();
			int idx1 = baseName.indexOf("lamexp", 0, Qt::CaseInsensitive);
			int idx2 = baseName.lastIndexOf("portable", -1, Qt::CaseInsensitive);
			g_lamexp_portable.bPortableModeEnabled = (idx1 >= 0) && (idx2 >= 0) && (idx1 < idx2);
		}
		g_lamexp_portable.bInitialized = true;
	}
	
	return g_lamexp_portable.bPortableModeEnabled;
}
PagePartSelectionTracker::PagePartSelectionTracker(
    IWorkbenchPage* page, const QString& partId) :
    AbstractPartSelectionTracker(partId)
{
    postSelectionListener.reset(new PostSelectionListener(this));
    perspListener.reset(new SelTrackerPerspectiveListener(this));
    selChangedListener.reset(new SelTrackerSelectionChangedListener(this));
    partListener.reset(new SelTrackerPartListener(this));

    this->SetPage(page);
    page->AddPartListener(partListener.data());
    page->GetWorkbenchWindow()->AddPerspectiveListener(perspListener.data());
    QString secondaryId;
    QString primaryId = partId;
    int indexOfColon;
    if ((indexOfColon = partId.indexOf(':')) != -1)
    {
        secondaryId = partId.mid(indexOfColon + 1);
        primaryId = partId.left(indexOfColon);
    }
    IViewReference::Pointer part =
        page->FindViewReference(primaryId, secondaryId);
    if (part.IsNotNull() && part->GetView(false).IsNotNull())
    {
        this->SetPart(part->GetView(false), false);
    }
}
bool W3cXmlPlugin::process(const QString *infoListfile)
{
    LOG("BEGIN W3cXmlPlugin::process infoListfile=" << infoListfile);

    if (infoListfile == NULL && m_dir.exists()) {
        LOG("W3cXmlPlugin::process search for config.xml");
        // Search for config.xml file

        QFileInfoList tempExtract = m_dir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot);
        LOG("W3cXmlPlugin::process got entryInfoList");

        foreach (const QFileInfo &isWidgetDir, tempExtract ) {
            if (!isWidgetDir.fileName().compare("config.xml", Qt::CaseSensitive)) {
                // We found the config.xml
                QString filePath = isWidgetDir.absoluteFilePath();
                if (!filePath.isEmpty()) {
                    QFileInfo f = filePath;
                    m_dir = f.dir();
                    LOG("W3cXmlPlugin::process found config.xml at " << filePath);
                    m_parser->setFile(filePath);
                    if (m_parser->parseFile()) {
                       setAttributeMap();
                       LOG("END W3cXmlPlugin::process xml parsing successful");
                       return true;
                    }
                }
            }
        }   // end of foreach
    }
void FileFilterBaseItem::setFilter(const QString &filter)
{
    if (filter == m_filter)
        return;
    m_filter = filter;

    m_regExpList.clear();
    m_fileSuffixes.clear();

    foreach (const QString &pattern, filter.split(QLatin1Char(';'))) {
        if (pattern.isEmpty())
            continue;
        // decide if it's a canonical pattern like *.x
        if (pattern.startsWith(QLatin1String("*."))) {
            const QString suffix = pattern.right(pattern.size() - 1);
            if (!suffix.contains(QLatin1Char('*'))
                    && !suffix.contains(QLatin1Char('?'))
                    && !suffix.contains(QLatin1Char('['))) {
                m_fileSuffixes << suffix;
                continue;
            }
        }
        m_regExpList << QRegExp(pattern, Qt::CaseInsensitive, QRegExp::Wildcard);
    }

    updateFileList();
}
Example #7
0
QString QgsCustomizationDialog::widgetPath( QWidget * theWidget, const QString& thePath )
{
  // go up until QDialog is reached
  QString name = theWidget->objectName();

  QString path = thePath;

  if ( !QgsCustomization::mInternalWidgets.contains( name ) )
  {
    if ( !path.isEmpty() )
    {
      path = name + '/' + path;
    }
    else
    {
      path = name;
    }
  }

  QWidget * parent = theWidget->parentWidget();

  if ( !parent || theWidget->inherits( "QDialog" ) )
  {
    return '/' + path;
  }

  return widgetPath( parent, path );
}
Example #8
0
File: Util.cpp Project: Emdek/WMIT
inline QString getWZMTextureName(const QString& filePath)
{
	QFile f(filePath);
	if (!f.open(QFile::ReadOnly))
	{
		return QString();
	}
	QTextStream in(&f);
	QString qstr;
	unsigned uint;

	if (in.status() != QTextStream::Ok || qstr.compare("WZM") != 0)
	{
		return  QString();
	}

	in >> uint;
	if (in.status() != QTextStream::Ok)
	{
		return  QString();
	}

	in >> qstr;
	if (qstr.compare("TEXTURE") != 0)
	{
		return  QString();
	}
	in >> qstr;
	if (in.status() != QTextStream::Ok)
	{
		return  QString();
	}
	return qstr;
}
Example #9
0
void ProfileInner::onUpdatePhoto() {
	saveError();

	QStringList imgExtensions(cImgExtensions());	
	QString filter(qsl("Image files (*") + imgExtensions.join(qsl(" *")) + qsl(");;All files (*.*)"));

	QImage img;
	QString file;
	QByteArray remoteContent;
	if (filedialogGetOpenFile(file, remoteContent, lang(lng_choose_images), filter)) {
		if (!remoteContent.isEmpty()) {
			img = App::readImage(remoteContent);
		} else {
			if (!file.isEmpty()) {
				img = App::readImage(file);
			}
		}
	} else {
		return;
	}

	if (img.isNull() || img.width() > 10 * img.height() || img.height() > 10 * img.width()) {
		saveError(lang(lng_bad_photo));
		return;
	}
	PhotoCropBox *box = new PhotoCropBox(img, _peer->id);
	connect(box, SIGNAL(closed()), this, SLOT(onPhotoUpdateStart()));
	App::wnd()->showLayer(box);
}
Example #10
0
static int l_additem(lua_State* L)
{
	QLuaMenu* cc = lua_toluamenu(L, 1);
	QMenu* c = lua_tomenu(L, 1);
	if(!c) return 0;

	QString text = lua_tostring(L, 2);
	QString icon = lua_tostring(L, 3);

	QAction* a = 0;

	if(text.length())
	{
		if(icon.length())
		{
			a = c->addAction(QIcon(icon), text);
		}
		else
		{
			a = c->addAction(text);
		}
	}

	if(a)
	{
		lua_pushaction(L, a);
		cc->addChild(lua_toluaaction(L, -1));
		return 1;
	}

	return 0;
}
Example #11
0
void MainWindow::writeSettings() {
  ui->allWorks->writeSettings();

  QSettings settings;

  /*
  settings.beginGroup("MainWindow");
  settings.setValue("geometry", saveGeometry());
  settings.endGroup();
  */

  settings.beginGroup("WorkFilterModelCollection");

  int valid_index = 0;
  settings.beginWriteArray("filters");
  for (int i = 0; i < ui->workViews->count(); i++) {
    //make sure it is not the all view and the expression isn't empty
    QWidget * widget = ui->workViews->widget(i);
    WorkFilterView * view = dynamic_cast<WorkFilterView *>(widget);
    if (!view)
      continue;
    QString expression = view->filterExpression();
    if (expression.isEmpty())
      continue;

    settings.setArrayIndex(valid_index);
    valid_index++;
    settings.setValue("expression", expression);
    settings.setValue("label", ui->workViews->tabText(ui->workViews->indexOf(view)));
  }
  settings.endArray();

  settings.endGroup();
}
void SendMessagesEntry::on_sendTo_textChanged(const QString &address)
{
    if(!model)
        return;

    QString pubkey;
    QString sendTo = address;

    if(model->getAddressOrPubkey(sendTo, pubkey))
    {

        ui->publicKey->setText(pubkey);
    }
    else
    {
        ui->publicKey->show();
        ui->publicKeyLabel->show();
    }

    // Fill in label from address book, if address has an associated label
    QString associatedLabel = model->getWalletModel()->getAddressTableModel()->labelForAddress(address);

    if(!associatedLabel.isEmpty())
        ui->addAsLabel->setText(associatedLabel);
}
static QString absPath(const QString &path)
{
    QString ret;
    if (path[0] != QChar('/')) { // Not an absolute path
        int slashpos;
        if ((slashpos = path.lastIndexOf('/')) != -1) { // Relative path
            QDir dir = QDir::current();
            dir.cd(path.left(slashpos));
            ret = dir.absolutePath();
        } else { // Need to search $PATH
            char *envPath = ::getenv("PATH");
            if (envPath) {
                QStringList envPaths = QString::fromLocal8Bit(envPath).split(':');
                for (int i = 0; i < envPaths.size(); ++i) {
                    if (QFile::exists(envPaths.at(i) + QLatin1String("/") + QString(path))) {
                        QDir dir(envPaths.at(i));
                        ret = dir.absolutePath();
                        break;
                    }
                }
            }
        }
    } else {
        QFileInfo fi(path);
        ret = fi.absolutePath();
    }
    return ret;
}
void ossimQtTopographicCorrectionDialogController::importParametersButtonClicked()
{
   ossimConnectableObject* obj = theObject->findObjectOfType("ossimImageHandler",
                                                             ossimConnectableObject::CONNECTABLE_DIRECTION_INPUT);
   ossimImageHandler* handler = PTR_CAST(ossimImageHandler, obj);
   
   if(handler)
   {
      ossimFilename imageFile = handler->getFilename();
      ossimFilename result;

      result = getLandsatHeader(imageFile);

      if(result !="")
      {
         QString filename = Q3FileDialog::getOpenFileName(result.c_str(),
                                                         "Landsat header (*.fst *.FST);;All files (* *.*)",
                                                         theDialog,
                                                         NULL,
                                                         "Choose parameters file to import");
         if(filename != "")
         {
            ossimRefPtr<ossimFfL7> headerL7 = new ossimFfL7(filename.ascii());
            if(!headerL7->getErrorStatus())
            {
               transferParametersToDialog(headerL7->theGain,
                                          headerL7->theBias,
                                          headerL7->theSunElevation,
                                          headerL7->theSunAzimuth);
            }
         }
      }
   }
}
bool NamespaceSupport::processName(const QString& qname, NameType type, QXmlName &name) const
{
    int len = qname.size();
    const QChar *data = qname.constData();
    for (int pos = 0; pos < len; ++pos) {
        if (data[pos] == QLatin1Char(':')) {
            const QXmlName::PrefixCode prefixCode = m_namePool->allocatePrefix(qname.left(pos));
            if (!m_ns.contains(prefixCode))
                return false;
            const QXmlName::NamespaceCode namespaceCode = uri(prefixCode);
            const QXmlName::LocalNameCode localNameCode = m_namePool->allocateLocalName(qname.mid(pos + 1));
            name = QXmlName(namespaceCode, localNameCode, prefixCode);
            return true;
        }
    }

    // there was no ':'
    QXmlName::NamespaceCode namespaceCode = 0;
    // attributes don't take default namespace
    if (type == ElementName && !m_ns.isEmpty()) {
        namespaceCode = m_ns.value(0);   // get default namespace
    }

    const QXmlName::LocalNameCode localNameCode = m_namePool->allocateLocalName(qname);
    name = QXmlName(namespaceCode, localNameCode, 0);

    return true;
}
Example #16
0
void TcDownload::StartDownload(const QUrl &url,
                             QFile *file,
                             qint64 startPoint/* =0 */,
                             qint64 endPoint/* =-1 */)
{
    if( NULL == file )
        return;

    m_HaveDoneBytes = 0;
    m_StartPoint = startPoint;
    m_EndPoint = endPoint;
    m_File = file;

    //根据HTTP协议,写入RANGE头部,说明请求文件的范围
    QNetworkRequest qheader;
    qheader.setUrl(url);
    QString range;
    range.sprintf("Bytes=%lld-%lld", m_StartPoint, m_EndPoint);
    qheader.setRawHeader("Range", range.toLocal8Bit());

    //开始下载
    m_Reply = m_Qnam.get(QNetworkRequest(qheader));
    connect(m_Reply, SIGNAL(finished()), this, SLOT(FinishedSlot()));
    connect(m_Reply, SIGNAL(readyRead()), this, SLOT(HttpReadyRead()));
}
Example #17
0
QString TimeWidget::progressText(const TimeParts& times, bool short_version)
{
	unsigned int hours   = std::get<0>(times);
	unsigned int minutes = std::get<1>(times);
	unsigned int seconds = std::get<2>(times);

  QString format;

  if(hours > 0)
  {
		int days = 0;
		while( hours > hours_in_one_day )
		{
			hours -= hours_in_one_day;
			days++;
		}

		if( days > 0 )
			format.append( QString::number(days) + (short_version ? " " + tr("d") : tr("days")) + " " );

		format.append( QString::number(hours) + (short_version ? " " + tr("h") : tr("hours")) + " " );
  }

  if(minutes > 0)
		format.append( QString::number(minutes) + (short_version ? tr("m") : " " + tr("mins")) + " " );

	if(seconds > 0)
		format.append( QString::number(seconds) + (short_version ? tr("s") : " " + tr("secs")) );

  return format;
}
Example #18
0
void TcDownloadList::StartFileDownload(const QString &url, int count)
{
    m_DownloadCount = count;
    m_FinishedNum = 0;
    m_Url = QUrl(url);
    m_FileSize = GetFileSize(m_Url);
    //先获得文件的名字
    QFileInfo fileInfo(m_Url.path());
    QString fileName = fileInfo.fileName();
    if (fileName.isEmpty())
        fileName = "index.html";

    m_File->setFileName(fileName);
    //打开文件
    m_File->open(QIODevice::WriteOnly);
    TcDownload *tempDownload;

    //将文件分成PointCount段,用异步的方式下载
    //qDebug() << "Start download file from " << strUrl;
    for(int i=0; i<m_DownloadCount; i++)
    {
        //先算出每段的开头和结尾(HTTP协议所需要的信息)
        int start = m_FileSize * i / m_DownloadCount;
        int end = m_FileSize * (i+1) / m_DownloadCount;
        if( i != 0 )
            start--;

        //分段下载该文件
        tempDownload = new TcDownload(i + 1, this);
        connect(tempDownload, SIGNAL(DownloadFinished()), this, SLOT(SubPartFinished()));
        connect(tempDownload, SIGNAL(DownloadFinished()), tempDownload, SLOT(deleteLater()));
        tempDownload->StartDownload(m_Url, m_File, start, end);
    }
}
Example #19
0
bool CamHandler::service( HttpRequest& request, HttpResponse& response )
{
    if ( request.getPath() != "/jpg-image" )
        return false;

    QString data = QString::fromAscii( request.getBody() );
    QRegExp re( "(\\w{1,})\\s{0,}=\\s{0,}(-{0,1}\\d{1,})" );
    int pos = 0;
    while ( ( pos = re.indexIn( data, pos ) ) != -1 )
    {
        QString key   = re.cap( 1 );
        QString value = re.cap( 2 );
        pos += re.matchedLength();
        if ( key == "quality" )
        {
            pd->quality = value.toInt();
        }
    }
    
    QImage image = pd->image();

    QBuffer buffer( &pd->data );
    QSize sz = image.size();
    buffer.open(QIODevice::WriteOnly);
    bool res = image.save( &buffer, "JPG", pd->quality );

    response.setHeader("Content-Type", "image/JPG");
    response.write( pd->data, true );

    Sleep::msleep( 100 );

    return true;
}
Example #20
0
void AdBlockIcon::popupBlocked(const QString &ruleString, const QUrl &url)
{
    int index = ruleString.lastIndexOf(QLatin1String(" ("));

    const QString &subscriptionName = ruleString.left(index);
    const QString &filter = ruleString.mid(index + 2, ruleString.size() - index - 3);
    AdBlockSubscription* subscription = AdBlockManager::instance()->subscriptionByName(subscriptionName);
    if (filter.isEmpty() || !subscription) {
        return;
    }

    AdBlockRule rule(filter, subscription);

    QPair<AdBlockRule, QUrl> pair;
    pair.first = rule;
    pair.second = url;
    m_blockedPopups.append(pair);

    mApp->desktopNotifications()->showNotification(QPixmap(":html/adblock_big.png"), tr("Blocked popup window"), tr("AdBlock blocked unwanted popup window."));

    if (!m_flashTimer) {
        m_flashTimer = new QTimer(this);
    }

    if (m_flashTimer->isActive()) {
        stopAnimation();
    }

    m_flashTimer->setInterval(500);
    m_flashTimer->start();

    connect(m_flashTimer, SIGNAL(timeout()), this, SLOT(animateIcon()));
}
Example #21
0
void EditDrumset::load()
      {
      QString name = mscore->getDrumsetFilename(true);
      if (name.isEmpty())
            return;

      QFile fp(name);
      if (!fp.open(QIODevice::ReadOnly))
            return;

      XmlReader e(&fp);
      nDrumset.clear();
      while (e.readNextStartElement()) {
            if (e.name() == "museScore") {
                  if (e.attribute("version") != MSC_VERSION) {
                        QMessageBox::critical(this, tr("Drumset too old"), tr("MuseScore cannot load this drumset file."));
                        return;
                        }
                  while (e.readNextStartElement()) {
                        if (e.name() == "Drum")
                              nDrumset.load(e);
                        else
                              e.unknown();
                        }
                  }
            }
      fp.close();
      updatePitchesList();
      }
Example #22
0
void FileItem::determineFileType( void )
{
	m_handling = NotSupported;

	const QString ext = extension();
	if( ext == "mmp" || ext == "mpt" || ext == "mmpz" )
	{
		m_type = ProjectFile;
		m_handling = LoadAsProject;
	}
	else if( ext == "xpf" || ext == "xml" )
	{
		m_type = PresetFile;
		m_handling = LoadAsPreset;
	}
	else if( ext == "xiz" && Engine::pluginFileHandling().contains( ext ) )
	{
		m_type = PresetFile;
		m_handling = LoadByPlugin;
	}
	else if( ext == "sf2" )
	{
		m_type = SoundFontFile;
	}
	else if( ext == "pat" )
	{
		m_type = PatchFile;
	}
	else if( ext == "mid" )
	{
		m_type = MidiFile;
		m_handling = ImportAsProject;
	}
	else if( ext == "flp" )
	{
		m_type = FlpFile;
		m_handling = ImportAsProject;
	}
	else if( ext == "dll" )
	{
		m_type = VstPluginFile;
		m_handling = LoadByPlugin;
	}
	else
	{
		m_type = UnknownFile;
	}

	if( m_handling == NotSupported &&
		!ext.isEmpty() && Engine::pluginFileHandling().contains( ext ) )
	{
		m_handling = LoadByPlugin;
		// classify as sample if not classified by anything yet but can
		// be handled by a certain plugin
		if( m_type == UnknownFile )
		{
			m_type = SampleFile;
		}
	}
}
Example #23
0
QString LinePort::generate(QString const &lineTemplate, bool isScaled) const
{
	QString result = lineTemplate;
	result.replace(startXTag, mStartX.toString(isScaled)).replace(startYTag, mStartY.toString(isScaled))
		.replace(endXTag, mEndX.toString(isScaled)).replace(endYTag, mEndY.toString(isScaled));
	return result;
}
Example #24
0
void MainParser::parse(const QCoreApplication& app)
{
    m_parser.process(app);

    int pos;
    bool ok;

    // server address

    QString serverAddress = m_parser.value(m_serverAddressOption);

    QString ipRange = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])";
    QRegExp ipRegex ("^" + ipRange
                     + "\\." + ipRange
                     + "\\." + ipRange
                     + "\\." + ipRange + "$");
    QRegExpValidator ipValidator(ipRegex);

    if (ipValidator.validate(serverAddress, pos) == QValidator::Acceptable) {
        m_serverAddress = serverAddress;
    } else {
        qWarning() << "MainParser::parse: server address invalid. Defaulting to " << m_serverAddress;
    }

    // server port

    QString serverPortStr = m_parser.value(m_serverPortOption);
    int serverPort = serverPortStr.toInt(&ok);

    if (ok && (serverPort > 1023) && (serverPort < 65536)) {
        m_serverPort = serverPort;
    } else {
        qWarning() << "MainParser::parse: server port invalid. Defaulting to " << m_serverPort;
    }
}
/**
 * Simple open
 ***/
QStringList DialogsProvider::showSimpleOpen( const QString& help,
                                             int filters,
                                             const QString& path )
{
    QString fileTypes = "";
    if( filters & EXT_FILTER_MEDIA ) {
        ADD_EXT_FILTER( fileTypes, EXTENSIONS_MEDIA );
    }
    if( filters & EXT_FILTER_VIDEO ) {
        ADD_EXT_FILTER( fileTypes, EXTENSIONS_VIDEO );
    }
    if( filters & EXT_FILTER_AUDIO ) {
        ADD_EXT_FILTER( fileTypes, EXTENSIONS_AUDIO );
    }
    if( filters & EXT_FILTER_PLAYLIST ) {
        ADD_EXT_FILTER( fileTypes, EXTENSIONS_PLAYLIST );
    }
    if( filters & EXT_FILTER_SUBTITLE ) {
        ADD_EXT_FILTER( fileTypes, EXTENSIONS_SUBTITLE );
    }
    ADD_EXT_FILTER( fileTypes, EXTENSIONS_ALL );
    fileTypes.replace( ";*", " *");

    QStringList files = QFileDialog::getOpenFileNames( NULL,
        help.isEmpty() ? qtr(I_OP_SEL_FILES ) : help,
        path.isEmpty() ? p_intf->p_sys->filepath : path,
        fileTypes );

    if( !files.isEmpty() ) savedirpathFromFile( files.last() );

    return files;
}
Example #26
0
/*!
    Returns the first charset from the preferred list that is capable of encoding
    the content of \a text.

    \since 1.0
    \sa preferredCharsets(), setBody()
*/
QByteArray QMessage::preferredCharsetFor(const QString &text)
{
    QList<QTextCodec*> codecs;
    foreach (const QByteArray &name, charsets) {
        if (QTextCodec* codec = QTextCodec::codecForName(name)) {
            codecs.append(codec);
        } else {
            qWarning() << "No codec is available for:" << name;
        }
    }

    if (!codecs.isEmpty()) {
        // See if any of these codecs can encode the data
        QString::const_iterator sit = text.begin(), end = text.end();
        for ( ; sit != end; ++sit) {
            QList<QTextCodec*>::iterator cit = codecs.begin();
            if (!(*cit)->canEncode(*sit)) {
                // This codec is not acceptable
                cit = codecs.erase(cit);
                if (codecs.isEmpty()) {
                    break;
                }
            } else {
                ++cit;
            }
        }

        if (!codecs.isEmpty()) {
            // Return the first remaining codec
            return codecs.first()->name();
        }
    }

    return QByteArray();
}
Example #27
0
bool inList(const QStringList& list, const QString& text)
{
    QStringListIterator iter(list);
    while(iter.hasNext())
    {
        const QString& str=iter.next();
        if(str.startsWith("+re:"))
        {
            QRegExp re(str.mid(4));
            if(re.isValid() && !re.isEmpty())
            {
                re.setCaseSensitivity(Qt::CaseInsensitive);
                re.setMinimal(true);
                if(text.contains(re))return true;
            }
        }else
        if(str.startsWith("-re:"))
        {
            QRegExp re(str.mid(4));
            if(re.isValid() && !re.isEmpty())
            {
                re.setCaseSensitivity(Qt::CaseInsensitive);
                re.setMinimal(true);
                if(text.contains(re))return false;
            }
        }else
        if(text.contains(str, Qt::CaseInsensitive)) return true;
    }
    return false;
}
Example #28
0
void TRasterImageUtils::addGlobalNumbering(const TRasterImageP &ri, const std::wstring &sceneName, int globalIndex)
{
	if (!ri)
		return;
	TRasterP raster = ri->getRaster();
	int lx = raster->getLx(), ly = raster->getLy();
	QColor greyOverlay(100, 100, 100, 140);
	QImage image = rasterToQImage(raster, true, false);
	QPainter p(&image);
	QFont numberingFont = QFont();
	numberingFont.setPixelSize(ly * 0.04);
	numberingFont.setBold(true);
	p.setFont(numberingFont);
	QMatrix matrix;
	p.setMatrix(matrix.translate(0, ly).scale(1, -1), true);
	QFontMetrics fm = p.fontMetrics();
	int fontHeight = fm.height();
	int offset = fontHeight * 0.2;
	QString globalFrame = QString::number(globalIndex);
	while (globalFrame.size() < 4)
		globalFrame.push_front("0");
	QString globalNumberingString = QString::fromStdWString(sceneName) + ": " + globalFrame;

	int globalNumberingWidth = fm.width(globalNumberingString);
	p.setPen(Qt::NoPen);
	p.setBrush(QColor(255, 255, 255, 255));
	p.drawRect(offset, ly - offset - fontHeight, globalNumberingWidth + offset * 2, fontHeight);
	p.setBrush(greyOverlay);
	p.drawRect(offset, ly - offset - fontHeight, globalNumberingWidth + offset * 2, fontHeight);
	p.setPen(Qt::white);
	p.drawText(2 * offset, ly - 2 * offset, globalNumberingString);
	p.end();
}
void QgsCoordinateTransformPrivate::addNullGridShifts( QString &srcProjString, QString &destProjString,
    int sourceDatumTransform, int destinationDatumTransform ) const
{
  //if one transformation uses ntv2, the other one needs to be null grid shift
  if ( destinationDatumTransform == -1 && srcProjString.contains( QLatin1String( "+nadgrids" ) ) ) //add null grid if source transformation is ntv2
  {
    destProjString += QLatin1String( " +nadgrids=@null" );
    return;
  }
  if ( sourceDatumTransform == -1 && destProjString.contains( QLatin1String( "+nadgrids" ) ) )
  {
    srcProjString += QLatin1String( " +nadgrids=@null" );
    return;
  }

  //add null shift grid for google mercator
  //(see e.g. http://trac.osgeo.org/proj/wiki/FAQ#ChangingEllipsoidWhycantIconvertfromWGS84toGoogleEarthVirtualGlobeMercator)
  if ( mSourceCRS.authid().compare( QLatin1String( "EPSG:3857" ), Qt::CaseInsensitive ) == 0 && sourceDatumTransform == -1 )
  {
    srcProjString += QLatin1String( " +nadgrids=@null" );
  }
  if ( mDestCRS.authid().compare( QLatin1String( "EPSG:3857" ), Qt::CaseInsensitive ) == 0 && destinationDatumTransform == -1 )
  {
    destProjString += QLatin1String( " +nadgrids=@null" );
  }
}
Example #30
0
void HDTSpecForm::on_inputFileButton_clicked()
{
    static QString lastDir = QDir::currentPath();
    QString file = QFileDialog::getOpenFileName(this,tr("Select Input RDF File"), lastDir, tr("RDF Files(*)"), 0, 0 );
    if(file!="") {
        lastDir=file;
        if(getBaseUri()=="") {
            ui->baseUriText->setText("<file://"+file+">");
        }

        QString noCompression=file;

        if(file.endsWith(".gz", Qt::CaseInsensitive)) {
            noCompression = file.left(file.length()-3);
        }

        if(noCompression.endsWith(".ttl", Qt::CaseInsensitive)) {
            ui->rdfInputCombo->setCurrentIndex(2);
        } else if(noCompression.endsWith(".nt", Qt::CaseInsensitive)) {
            ui->rdfInputCombo->setCurrentIndex(0);
        } else if(noCompression.endsWith(".n3", Qt::CaseInsensitive)) {
            ui->rdfInputCombo->setCurrentIndex(1);
        } else if(noCompression.endsWith(".rdf", Qt::CaseInsensitive) || noCompression.endsWith(".xml", Qt::CaseInsensitive)) {
            ui->rdfInputCombo->setCurrentIndex(3);
        }
    }
    ui->rdfInputFile->setText(file);
}