Ejemplo n.º 1
0
void QgsComposerPicture::loadPicture( const QFile& file )
{
  if ( !file.exists()
       || ( mUseSourceExpression && mPictureExpr->hasEvalError() ) )
  {
    mMode = Unknown;
  }
  else
  {
    QFileInfo sourceFileInfo( file );
    QString sourceFileSuffix = sourceFileInfo.suffix();
    if ( sourceFileSuffix.compare( "svg", Qt::CaseInsensitive ) == 0 )
    {
      //try to open svg
      mSVG.load( file.fileName() );
      if ( mSVG.isValid() )
      {
        mMode = SVG;
        QRect viewBox = mSVG.viewBox(); //take width/height ratio from view box instead of default size
        mDefaultSvgSize.setWidth( viewBox.width() );
        mDefaultSvgSize.setHeight( viewBox.height() );
      }
      else
      {
        mMode = Unknown;
      }
    }
    else
    {
      //try to open raster with QImageReader
      QImageReader imageReader( file.fileName() );
      if ( imageReader.read( &mImage ) )
      {
        mMode = RASTER;
      }
      else
      {
        mMode = Unknown;
      }
    }
  }

  if ( mMode != Unknown ) //make sure we start with a new QImage
  {
    recalculateSize();
  }
  else if ( !( file.fileName().isEmpty() ) || ( mUseSourceExpression && mPictureExpr && mPictureExpr->hasEvalError() ) )
  {
    //trying to load an invalid file or bad expression, show cross picture
    mMode = SVG;
    QString badFile = QString( ":/images/composer/missing_image.svg" );
    mSVG.load( badFile );
    if ( mSVG.isValid() )
    {
      mMode = SVG;
      QRect viewBox = mSVG.viewBox(); //take width/height ratio from view box instead of default size
      mDefaultSvgSize.setWidth( viewBox.width() );
      mDefaultSvgSize.setHeight( viewBox.height() );
      recalculateSize();
    }
  }

  emit itemChanged();
}
// 改变相机提示灯
void ImageViewer::changeCamera(QString cameraindex, bool status)
{
    QString img;
    if (status)
        img = ":/image/lightgreen.png";
    else
    {
        img = ":/image/lightyellow.png";
        ui->A1Label_work->setPixmap(QPixmap(img));
        ui->A2Label_work->setPixmap(QPixmap(img));
        ui->B1Label_work->setPixmap(QPixmap(img));
        ui->B2Label_work->setPixmap(QPixmap(img));
        ui->C1Label_work->setPixmap(QPixmap(img));
        ui->C2Label_work->setPixmap(QPixmap(img));
        ui->D1Label_work->setPixmap(QPixmap(img));
        ui->D2Label_work->setPixmap(QPixmap(img));
        ui->E1Label_work->setPixmap(QPixmap(img));
        ui->E2Label_work->setPixmap(QPixmap(img));
        ui->F1Label_work->setPixmap(QPixmap(img));
        ui->F2Label_work->setPixmap(QPixmap(img));
        ui->G1Label_work->setPixmap(QPixmap(img));
        ui->G2Label_work->setPixmap(QPixmap(img));
        ui->H1Label_work->setPixmap(QPixmap(img));
        ui->H2Label_work->setPixmap(QPixmap(img));
        ui->I1Label_work->setPixmap(QPixmap(img));
        ui->I2Label_work->setPixmap(QPixmap(img));
        ui->J1Label_work->setPixmap(QPixmap(img));
        ui->J2Label_work->setPixmap(QPixmap(img));
        ui->K1Label_work->setPixmap(QPixmap(img));
        ui->K2Label_work->setPixmap(QPixmap(img));
        ui->L1Label_work->setPixmap(QPixmap(img));
        ui->L2Label_work->setPixmap(QPixmap(img));
        ui->M1Label_work->setPixmap(QPixmap(img));
        ui->M2Label_work->setPixmap(QPixmap(img));
        ui->N1Label_work->setPixmap(QPixmap(img));
        ui->N2Label_work->setPixmap(QPixmap(img));
        ui->O1Label_work->setPixmap(QPixmap(img));
        ui->O2Label_work->setPixmap(QPixmap(img));
        ui->P1Label_work->setPixmap(QPixmap(img));
        ui->P2Label_work->setPixmap(QPixmap(img));
        ui->Q1Label_work->setPixmap(QPixmap(img));
        ui->Q2Label_work->setPixmap(QPixmap(img));
        ui->R1Label_work->setPixmap(QPixmap(img));
        ui->R2Label_work->setPixmap(QPixmap(img));
        return;
    }
    //qDebug() << cameraindex;
    if (cameraindex.compare("A1") == 0)
        ui->A1Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("A2") == 0)
        ui->A2Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("B1") == 0)
        ui->B1Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("B2") == 0)
        ui->B2Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("C1") == 0)
        ui->C1Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("C2") == 0)
        ui->C2Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("D1") == 0)
        ui->D1Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("D2") == 0)
        ui->D2Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("E1") == 0)
        ui->E1Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("E2") == 0)
        ui->E2Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("F1") == 0)
        ui->F1Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("F2") == 0)
        ui->F2Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("G1") == 0)
        ui->G1Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("G2") == 0)
        ui->G2Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("H1") == 0)
        ui->H1Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("H2") == 0)
        ui->H2Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("I1") == 0)
        ui->I1Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("I2") == 0)
        ui->I2Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("J1") == 0)
        ui->J1Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("J2") == 0)
        ui->J2Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("K1") == 0)
        ui->K1Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("K2") == 0)
        ui->K2Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("L1") == 0)
        ui->L1Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("L2") == 0)
        ui->L2Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("M1") == 0)
        ui->M1Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("M2") == 0)
        ui->M2Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("N1") == 0)
        ui->N1Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("N2") == 0)
        ui->N2Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("O1") == 0)
        ui->O1Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("O2") == 0)
        ui->O2Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("P1") == 0)
        ui->P1Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("P2") == 0)
        ui->P2Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("Q1") == 0)
        ui->Q1Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("Q2") == 0)
        ui->Q2Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("R1") == 0)
        ui->R1Label_work->setPixmap(QPixmap(img));
    else if (cameraindex.compare("R2") == 0)
        ui->R2Label_work->setPixmap(QPixmap(img));
}
void TextDetection::process(Mat &image)
{
	QMutexLocker mutexLocker(&m_mutex);
	try
	{
		if (p_tesseract == NULL)
			initTesseract();

		if (p_tesseract != NULL)
		{
			tesseract::PageSegMode pagesegmode = static_cast<tesseract::PageSegMode>(7); // treat the image as a single text line
			p_tesseract->SetPageSegMode(pagesegmode);

			Mat dst, image_grey, image_grey_blurred, image_grey_res, image_otsu_thresh, image_otsu_thresh_blurred, image_otsu_thresh_smooth;
			Mat element, element2;
			cvtColor(image, image_grey, CV_RGB2GRAY);

			float ratio = (float)image_grey.cols / (float)image_grey.rows;
			// Case where image is a landscape
			if (ratio >= 2)
				resize(image_grey, image_grey, Size(200 * ratio, 200), 0, 0, CV_INTER_CUBIC | CV_WINDOW_KEEPRATIO);

			// Case where image is a square
			else if (ratio < 2)
				resize(image_grey, image_grey, Size(image_grey.cols * ratio * 2, image_grey.rows * ratio * 2), 0, 0, CV_INTER_CUBIC | CV_WINDOW_KEEPRATIO);

			// Case where image is a portrait
			else if (((float)image_grey.rows / (float)image_grey.cols) > 2)
				resize(image_grey, image_grey, Size(image_grey.rows * ratio, 800), 0, 0, CV_INTER_CUBIC | CV_WINDOW_KEEPRATIO);

			cv::GaussianBlur(image_grey, image_grey_res, cv::Size(11, 11), 3);						// Blur to remove noise


			if (m_fontIndex == 0)	// --> English
			{
				// Measure range of greyscale
				double min, max;
				cv::minMaxIdx(image_grey_res, &min, &max);

				if ((max - min) <= 30) // if only one color in image
					threshold(image_grey_res, image_grey_res, max, 255, CV_THRESH_BINARY);		// Threshold to make black all black if image is empty (nothing to read)

				int size2 = 3;
				element2 = getStructuringElement(MORPH_RECT, Size(size2, size2));
				dilate(image_grey_res, image_grey_res, element2);									// Dilate too fill in the edge

				threshold(image_grey_res, dst, 0, 255, CV_THRESH_BINARY_INV | CV_THRESH_OTSU);		// Threshold to make black and white
			}

			else					// --> PR4G
			{
				image_grey_res.convertTo(image_grey_res, -1, 0.3, 70);

				threshold(image_grey_res, image_otsu_thresh, 0, 255, CV_THRESH_BINARY_INV | CV_THRESH_OTSU);		// Threshold to make black and white

				int size = 5;
				element = getStructuringElement(MORPH_RECT, Size(size, size));
				erode(image_otsu_thresh, image_otsu_thresh, element);

				Mat img_dilate;
				int size2 = 20;
				element2 = getStructuringElement(MORPH_RECT, Size(size2, size2));
				dilate(image_otsu_thresh, dst, element2);
			}

			if (m_debug)
			{
				imshow("res text", dst);
			}

			p_tesseract->SetImage((uchar*)dst.data, dst.size().width, dst.size().height, dst.channels(), dst.step1());

			// Get OCR result	
			QString res = QString::fromUtf8(p_tesseract->GetUTF8Text());

			res = res.simplified();
			m_currentValue = res;

			res = res.remove(" ");

			if (m_debug)
			{
				qDebug() << "m_currentValue: " << m_currentValue;
				qDebug() << "res txt: " << res;
				qDebug() << "m_text : " << m_text;
			}

			setAlarmValid(true);

			QString temp = m_text;
			if (res.compare(temp.remove(" "), Qt::CaseInsensitive) == 0)
			{
				if (m_alarmOnEquals)
					setAlarm(true);
				else
					setAlarm(false);
			}
			else if (m_alarmOnEquals)
			{
				setAlarm(false);
			}
			else
				setAlarm(true);

		}
	}
	catch (Exception e)
	{
		qDebug() << QString("Exception in process TextDetection : %1").arg(QString::fromStdString(e.msg));
	}

}
Ejemplo n.º 4
0
/*!
    \fn void ExtensionInfoPrivate::readExtensionInfo(QXmlStreamReader &reader)
    \internal
*/
void ExtensionInfoPrivate::readExtensionInfo(QXmlStreamReader &reader)
{
    QString element = reader.name().toString();
    if (element != QString(EXTENSION)) {
        reader.raiseError(QCoreApplication::translate("ExtensionInfo", "Expected element '%1' as top level element").arg(EXTENSION));
        return;
    }
    name = reader.attributes().value(EXTENSION_NAME).toString();
    if (name.isEmpty()) {
        reader.raiseError(msgAttributeMissing(EXTENSION, EXTENSION_NAME));
        return;
    }
    version = reader.attributes().value(EXTENSION_VERSION).toString();
    if (version.isEmpty()) {
        reader.raiseError(msgAttributeMissing(EXTENSION, EXTENSION_VERSION));
        return;
    }
    if (!isValidVersion(version)) {
        reader.raiseError(msgInvalidFormat(EXTENSION_VERSION));
        return;
    }
    compatVersion = reader.attributes().value(EXTENSION_COMPATVERSION).toString();
    if (!compatVersion.isEmpty() && !isValidVersion(compatVersion)) {
        reader.raiseError(msgInvalidFormat(EXTENSION_COMPATVERSION));
        return;
    } else if (compatVersion.isEmpty()) {
        compatVersion = version;
    }
    QString experimentalString = reader.attributes().value(EXTENSION_EXPERIMENTAL).toString();
    experimental = (experimentalString.compare(QLatin1String("true"), Qt::CaseInsensitive) == 0);
    if (!experimentalString.isEmpty() && !experimental
            && experimentalString.compare(QLatin1String("false"), Qt::CaseInsensitive) != 0) {
        reader.raiseError(msgInvalidFormat(EXTENSION_EXPERIMENTAL));
        return;
    }
    enabled = !experimental;
    while (!reader.atEnd()) {
        reader.readNext();
        switch (reader.tokenType()) {
        case QXmlStreamReader::StartElement:
            element = reader.name().toString();
            if (element == VENDOR)
                vendor = reader.readElementText().trimmed();
            else if (element == COPYRIGHT)
                copyright = reader.readElementText().trimmed();
            else if (element == LICENSE)
                license = reader.readElementText().trimmed();
            else if (element == DESCRIPTION)
                description = reader.readElementText().trimmed();
            else if (element == URL)
                url = reader.readElementText().trimmed();
            else if (element == CATEGORY)
                category = reader.readElementText().trimmed();
            else if (element == DEPENDENCYLIST)
                readDependencies(reader);
            else if (element == ARGUMENTLIST)
                readArgumentDescriptions(reader);
            else
                reader.raiseError(msgInvalidElement(name));
            break;
        case QXmlStreamReader::EndDocument:
        case QXmlStreamReader::Comment:
        case QXmlStreamReader::EndElement:
        case QXmlStreamReader::Characters:
            break;
        default:
            reader.raiseError(msgUnexpectedToken());
            break;
        }
    }
}
Ejemplo n.º 5
0
void SxEditor::on_common_command_clicked()
{
	QObject *btn = sender();
	QString name = btn->objectName();

	if(name.compare("selectAll") == 0)
	{
		m_pTextEdit->selectAll();
	}
	if(name.compare("save") == 0)
	{
		m_pTextEdit->save();
	}
	else if(name.compare("copy") == 0)
	{
		m_pTextEdit->copy();
	}
	else if(name.compare("paste") == 0)
	{
		m_pTextEdit->paste();
	}
	else if(name.compare("cut") == 0)
	{
		m_pTextEdit->cut();
	}
	else if(name.compare("redo") == 0)
	{
		m_pTextEdit->redo();
	}
	else if(name.compare("undo") == 0)
	{
		m_pTextEdit->undo();
	}
	else if(name.compare("delete") == 0)
	{
		m_pTextEdit->deleteText();
	}
	else if(name.compare("bold") == 0)
	{
		m_pTextEdit->setFontBold(!m_pTextEdit->fontBold());
	}
	else if(name.compare("italic") == 0)
	{
		m_pTextEdit->setFontItalic(!m_pTextEdit->fontItalic());
	}
	else if(name.compare("underline") == 0)
	{
		m_pTextEdit->setFontUnderline(!m_pTextEdit->fontUnderline());
	}
	else if(name.compare("throughout") == 0)
	{
		m_pTextEdit->setFontStrikeOut(!m_pTextEdit->fontStrikeOut());
	}
	else if(name.compare("alignleft") == 0)
	{
		m_pTextEdit->setTextAlignment(Qt::AlignLeft);
	}
	else if(name.compare("aligncenter") == 0)
	{
		m_pTextEdit->setTextAlignment(Qt::AlignCenter);
	}
	else if(name.compare("alignright") == 0)
	{
		m_pTextEdit->setTextAlignment(Qt::AlignRight);
	}
	else if(name.compare("textcolor") == 0)
	{
		QColor clr = QColorDialog::getColor(m_pTextEdit->textColor(), m_pTextEdit->view());
		m_pTextEdit->setTextColor(clr);
	}
	else if(name.compare("link") == 0)
	{
		m_pUrlInsert = qobject_cast<KDialogBase*>(KXmlUI::windowFromFile("res:/Resources/layout/urlinsert.xml", m_pWindow));
		KPushButton *btnApply = m_pUrlInsert->findChild<KPushButton*>("btnApply");
		KPushButton *btnCancel = m_pUrlInsert->findChild<KPushButton*>("btnCancel");
		QObject::connect(btnApply, SIGNAL(clicked()), this, SLOT("on_urlInsert_button_clicked()"));
		QObject::connect(btnCancel, SIGNAL(clicked()), m_pUrlInsert, SLOT("setRejected()"));
		m_pUrlInsert->doModal(m_pWindow->rootWidget());
	}
	else if(name.compare("replace") == 0)
	{

	}
	else if(name.compare("find") == 0)
	{

	}
}
bool QAudioDeviceInfoInternal::testSettings(const QAudioFormat& format) const
{
    // Set nearest to closest settings that do work.
    // See if what is in settings will work (return value).
    int err = 0;
    snd_pcm_t* handle;
    snd_pcm_hw_params_t *params;
    QString dev = device;

    QList<QByteArray> devices = QAudioDeviceInfoInternal::availableDevices(QAudio::AudioOutput);

    if(dev.compare(QLatin1String("default")) == 0) {
#if(SND_LIB_MAJOR == 1 && SND_LIB_MINOR == 0 && SND_LIB_SUBMINOR >= 14)
        dev = QLatin1String(devices.first().constData());
#else
        dev = QLatin1String("hw:0,0");
#endif
    } else {
#if(SND_LIB_MAJOR == 1 && SND_LIB_MINOR == 0 && SND_LIB_SUBMINOR >= 14)
        dev = device;
#else
        int idx = 0;
        char *name;

        QString shortName = device.mid(device.indexOf(QLatin1String("="),0)+1);

        while(snd_card_get_name(idx,&name) == 0) {
            if(shortName.compare(QLatin1String(name)) == 0)
                break;
            idx++;
        }
        dev = QString(QLatin1String("hw:%1,0")).arg(idx);
#endif
    }
    if(mode == QAudio::AudioOutput) {
        err=snd_pcm_open( &handle,dev.toLocal8Bit().constData(),SND_PCM_STREAM_PLAYBACK,0);
    } else {
        err=snd_pcm_open( &handle,dev.toLocal8Bit().constData(),SND_PCM_STREAM_CAPTURE,0);
    }
    if(err < 0) {
        handle = 0;
        return false;
    }

    bool testChannel = false;
    bool testCodec = false;
    bool testFreq = false;
    bool testType = false;
    bool testSize = false;

    int  dir = 0;

    snd_pcm_nonblock( handle, 0 );
    snd_pcm_hw_params_alloca( &params );
    snd_pcm_hw_params_any( handle, params );

    // set the values!
    snd_pcm_hw_params_set_channels(handle,params,format.channels());
    snd_pcm_hw_params_set_rate(handle,params,format.frequency(),dir);
    switch(format.sampleSize()) {
        case 8:
            if(format.sampleType() == QAudioFormat::SignedInt)
                snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_S8);
            else if(format.sampleType() == QAudioFormat::UnSignedInt)
                snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_U8);
            break;
        case 16:
            if(format.sampleType() == QAudioFormat::SignedInt) {
                if(format.byteOrder() == QAudioFormat::LittleEndian)
                    snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_S16_LE);
                else if(format.byteOrder() == QAudioFormat::BigEndian)
                    snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_S16_BE);
            } else if(format.sampleType() == QAudioFormat::UnSignedInt) {
                if(format.byteOrder() == QAudioFormat::LittleEndian)
                    snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_U16_LE);
                else if(format.byteOrder() == QAudioFormat::BigEndian)
                    snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_U16_BE);
            }
            break;
        case 32:
            if(format.sampleType() == QAudioFormat::SignedInt) {
                if(format.byteOrder() == QAudioFormat::LittleEndian)
                    snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_S32_LE);
                else if(format.byteOrder() == QAudioFormat::BigEndian)
                    snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_S32_BE);
            } else if(format.sampleType() == QAudioFormat::UnSignedInt) {
                if(format.byteOrder() == QAudioFormat::LittleEndian)
                    snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_U32_LE);
                else if(format.byteOrder() == QAudioFormat::BigEndian)
                    snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_U32_BE);
            }
    }

    // For now, just accept only audio/pcm codec
    if(!format.codec().startsWith(QLatin1String("audio/pcm"))) {
        err=-1;
    } else
        testCodec = true;

    if(err>=0 && format.channels() != -1) {
        err = snd_pcm_hw_params_test_channels(handle,params,format.channels());
        if(err>=0)
            err = snd_pcm_hw_params_set_channels(handle,params,format.channels());
        if(err>=0)
            testChannel = true;
    }

    if(err>=0 && format.frequency() != -1) {
        err = snd_pcm_hw_params_test_rate(handle,params,format.frequency(),0);
        if(err>=0)
            err = snd_pcm_hw_params_set_rate(handle,params,format.frequency(),dir);
        if(err>=0)
            testFreq = true;
    }

    if((err>=0 && format.sampleSize() != -1) &&
            (format.sampleType() != QAudioFormat::Unknown)) {
        switch(format.sampleSize()) {
            case 8:
                if(format.sampleType() == QAudioFormat::SignedInt)
                    err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_S8);
                else if(format.sampleType() == QAudioFormat::UnSignedInt)
                    err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_U8);
                break;
            case 16:
                if(format.sampleType() == QAudioFormat::SignedInt) {
                    if(format.byteOrder() == QAudioFormat::LittleEndian)
                        err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_S16_LE);
                    else if(format.byteOrder() == QAudioFormat::BigEndian)
                        err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_S16_BE);
                } else if(format.sampleType() == QAudioFormat::UnSignedInt) {
                    if(format.byteOrder() == QAudioFormat::LittleEndian)
                        err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_U16_LE);
                    else if(format.byteOrder() == QAudioFormat::BigEndian)
                        err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_U16_BE);
                }
                break;
            case 32:
                if(format.sampleType() == QAudioFormat::SignedInt) {
                    if(format.byteOrder() == QAudioFormat::LittleEndian)
                        err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_S32_LE);
                    else if(format.byteOrder() == QAudioFormat::BigEndian)
                        err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_S32_BE);
                } else if(format.sampleType() == QAudioFormat::UnSignedInt) {
                    if(format.byteOrder() == QAudioFormat::LittleEndian)
                        err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_U32_LE);
                    else if(format.byteOrder() == QAudioFormat::BigEndian)
                        err = snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_U32_BE);
                }
        }
        if(err>=0) {
            testSize = true;
            testType = true;
        }
    }
    if(err>=0)
        err = snd_pcm_hw_params(handle, params);

    if(err == 0) {
        // settings work
        // close()
        if(handle)
            snd_pcm_close(handle);
        return true;
    }
    if(handle)
        snd_pcm_close(handle);

    return false;
}
Ejemplo n.º 7
0
/*!
	\param e target editor
	\param file filename displayed by the editor

	The \a file parameter may actuall be either a filename, an extension or the name of the language,
	checked in that order.

	If it is a filename, complete extension as higher priority than simple extension
	(see QFileInfo suffix() and completeSuffix()).

	Matches are first done case-sensitively.

	If no matching language definition is found for all three possible interpretations of the \a file
	parameter, the same search is done case-insensitively.

	If no matching language is found the previous language definition/completion engine of the editor
	are removed, leaving it blank, and the format scheme of the document is set to the defaultFormatScheme()
*/
void QLanguageFactory::setLanguage(QEditor *e, const QString& file)
{
	QString lang;
	QFileInfo inf(file);
	const QString ext = inf.suffix(),
				cext = inf.completeSuffix();

	//qDebug("suff:%s; compSuff:%s", qPrintable(ext), qPrintable(cext));

	QLanguageDefinition *oldLang = e->languageDefinition();

	if ( file.count() )
	{
		QList<Qt::CaseSensitivity> lcs;
		lcs << Qt::CaseSensitive << Qt::CaseInsensitive;

		foreach ( Qt::CaseSensitivity cs, lcs )
		{
			int n = 0, idx = -1;
			QStringList ext_langs, cext_langs, fcext_langs;

			foreach ( QString lang, m_languages )
			{
				const QStringList& exts = m_data[lang].extensions;

				//qDebug("%s in (%s) ?", qPrintable(ext), qPrintable(exts.join(" ")));

				foreach ( QString x, exts )
				{
					if ( !x.compare(ext, cs) )
						ext_langs << lang;

					if ( !x.compare(cext, cs) )
						cext_langs << lang;

					if ( !x.compare(file, cs) )
						fcext_langs << lang;
				}

				if ( !lang.compare(file, cs) )
					idx = n;

				++n;
			}

			if ( cext_langs.count() )
			{
				// TODO : use MIME types to resolve ambiguity
				lang = cext_langs.first();
			} else if ( ext_langs.count() ) {
				// TODO : use MIME types to resolve ambiguity
				lang = ext_langs.first();
			} else if ( fcext_langs.count() ) {
				// TODO : use MIME types to resolve ambiguity
				lang = fcext_langs.first();
			} else if ( idx != -1 ) {
				lang = m_languages.at(idx);
			}

			if ( lang.count() )
				break;
		}
Ejemplo n.º 8
0
bool QAudioOutputPrivate::open()
{
    if(opened)
        return true;

#ifdef DEBUG_AUDIO
    QTime now(QTime::currentTime());
    qDebug()<<now.second()<<"s "<<now.msec()<<"ms :open()";
#endif
    timeStamp.restart();
    elapsedTimeOffset = 0;

    int dir;
    int err = 0;
    int count=0;
    unsigned int freakuency=settings.frequency();

    if (!settings.isValid()) {
        qWarning("QAudioOutput: open error, invalid format.");
    } else if (settings.sampleRate() <= 0) {
        qWarning("QAudioOutput: open error, invalid sample rate (%d).",
                 settings.sampleRate());
    } else {
        err = -1;
    }

    if (err == 0) {
        errorState = QAudio::OpenError;
        deviceState = QAudio::StoppedState;
        emit errorChanged(errorState);
        return false;
    }

    QString dev = QString(QLatin1String(m_device.constData()));
    QList<QByteArray> devices = QAudioDeviceInfoInternal::availableDevices(QAudio::AudioOutput);
    if(dev.compare(QLatin1String("default")) == 0) {
#if(SND_LIB_MAJOR == 1 && SND_LIB_MINOR == 0 && SND_LIB_SUBMINOR >= 14)
        if (devices.size() > 0)
            dev = QLatin1String(devices.first());
        else
            return false;
#else
        dev = QLatin1String("hw:0,0");
#endif
    } else {
#if(SND_LIB_MAJOR == 1 && SND_LIB_MINOR == 0 && SND_LIB_SUBMINOR >= 14)
        dev = QLatin1String(m_device);
#else
        int idx = 0;
        char *name;

        QString shortName = QLatin1String(m_device.mid(m_device.indexOf('=',0)+1).constData());

        while(snd_card_get_name(idx,&name) == 0) {
            if(qstrncmp(shortName.toLocal8Bit().constData(),name,shortName.length()) == 0)
                break;
            idx++;
        }
        dev = QString(QLatin1String("hw:%1,0")).arg(idx);
#endif
    }

    // Step 1: try and open the device
    while((count < 5) && (err < 0)) {
        err=snd_pcm_open(&handle,dev.toLocal8Bit().constData(),SND_PCM_STREAM_PLAYBACK,0);
        if(err < 0)
            count++;
    }
    if (( err < 0)||(handle == 0)) {
        errorState = QAudio::OpenError;
        emit errorChanged(errorState);
        deviceState = QAudio::StoppedState;
        return false;
    }
    snd_pcm_nonblock( handle, 0 );

    // Step 2: Set the desired HW parameters.
    snd_pcm_hw_params_alloca( &hwparams );

    bool fatal = false;
    QString errMessage;
    unsigned int chunks = 8;

    err = snd_pcm_hw_params_any( handle, hwparams );
    if ( err < 0 ) {
        fatal = true;
        errMessage = QString::fromLatin1("QAudioOutput: snd_pcm_hw_params_any: err = %1").arg(err);
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_rate_resample( handle, hwparams, 1 );
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioOutput: snd_pcm_hw_params_set_rate_resample: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_access( handle, hwparams, access );
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioOutput: snd_pcm_hw_params_set_access: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = setFormat();
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioOutput: snd_pcm_hw_params_set_format: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_channels( handle, hwparams, (unsigned int)settings.channels() );
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioOutput: snd_pcm_hw_params_set_channels: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_rate_near( handle, hwparams, &freakuency, 0 );
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioOutput: snd_pcm_hw_params_set_rate_near: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        unsigned int maxBufferTime = 0;
        unsigned int minBufferTime = 0;
        unsigned int maxPeriodTime = 0;
        unsigned int minPeriodTime = 0;

        err = snd_pcm_hw_params_get_buffer_time_max(hwparams, &maxBufferTime, &dir);
        if ( err >= 0)
            err = snd_pcm_hw_params_get_buffer_time_min(hwparams, &minBufferTime, &dir);
        if ( err >= 0)
            err = snd_pcm_hw_params_get_period_time_max(hwparams, &maxPeriodTime, &dir);
        if ( err >= 0)
            err = snd_pcm_hw_params_get_period_time_min(hwparams, &minPeriodTime, &dir);

        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioOutput: buffer/period min and max: err = %1").arg(err);
        } else {
            if (maxBufferTime < buffer_time || buffer_time < minBufferTime || maxPeriodTime < period_time || minPeriodTime > period_time) {
#ifdef DEBUG_AUDIO
                qDebug()<<"defaults out of range";
                qDebug()<<"pmin="<<minPeriodTime<<", pmax="<<maxPeriodTime<<", bmin="<<minBufferTime<<", bmax="<<maxBufferTime;
#endif
                period_time = minPeriodTime;
                if (period_time*4 <= maxBufferTime) {
                    // Use 4 periods if possible
                    buffer_time = period_time*4;
                    chunks = 4;
                } else if (period_time*2 <= maxBufferTime) {
                    // Use 2 periods if possible
                    buffer_time = period_time*2;
                    chunks = 2;
                } else {
                    qWarning()<<"QAudioOutput: alsa only supports single period!";
                    fatal = true;
                }
#ifdef DEBUG_AUDIO
                qDebug()<<"used: buffer_time="<<buffer_time<<", period_time="<<period_time;
#endif
            }
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_buffer_time_near(handle, hwparams, &buffer_time, &dir);
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioOutput: snd_pcm_hw_params_set_buffer_time_near: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_period_time_near(handle, hwparams, &period_time, &dir);
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioOutput: snd_pcm_hw_params_set_period_time_near: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_periods_near(handle, hwparams, &chunks, &dir);
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioOutput: snd_pcm_hw_params_set_periods_near: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params(handle, hwparams);
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioOutput: snd_pcm_hw_params: err = %1").arg(err);
        }
    }
    if( err < 0) {
        qWarning()<<errMessage;
        errorState = QAudio::OpenError;
        emit errorChanged(errorState);
        deviceState = QAudio::StoppedState;
        return false;
    }
    snd_pcm_hw_params_get_buffer_size(hwparams,&buffer_frames);
    buffer_size = snd_pcm_frames_to_bytes(handle,buffer_frames);
    snd_pcm_hw_params_get_period_size(hwparams,&period_frames, &dir);
    period_size = snd_pcm_frames_to_bytes(handle,period_frames);
    snd_pcm_hw_params_get_buffer_time(hwparams,&buffer_time, &dir);
    snd_pcm_hw_params_get_period_time(hwparams,&period_time, &dir);

    // Step 3: Set the desired SW parameters.
    snd_pcm_sw_params_t *swparams;
    snd_pcm_sw_params_alloca(&swparams);
    snd_pcm_sw_params_current(handle, swparams);
    snd_pcm_sw_params_set_start_threshold(handle,swparams,period_frames);
    snd_pcm_sw_params_set_stop_threshold(handle,swparams,buffer_frames);
    snd_pcm_sw_params_set_avail_min(handle, swparams,period_frames);
    snd_pcm_sw_params(handle, swparams);

    // Step 4: Prepare audio
    if(audioBuffer == 0)
        audioBuffer = new char[snd_pcm_frames_to_bytes(handle,buffer_frames)];
    snd_pcm_prepare( handle );
    snd_pcm_start(handle);

    // Step 5: Setup callback and timer fallback
    snd_async_add_pcm_handler(&ahandler, handle, async_callback, this);
    bytesAvailable = bytesFree();

    // Step 6: Start audio processing
    timer->start(period_time/1000);

    clockStamp.restart();
    timeStamp.restart();
    elapsedTimeOffset = 0;
    errorState  = QAudio::NoError;
    totalTimeValue = 0;
    opened = true;

    return true;
}
Ejemplo n.º 9
0
void QgsHttpRequestHandler::requestStringToParameterMap( const QString& request, QMap<QString, QString>& parameters )
{
  parameters.clear();


  //insert key and value into the map (parameters are separated by &)
  Q_FOREACH ( const QString& element, request.split( "&" ) )
  {
    int sepidx = element.indexOf( "=", 0, Qt::CaseSensitive );
    if ( sepidx == -1 )
    {
      continue;
    }

    QString key = element.left( sepidx );
    key = QUrl::fromPercentEncoding( key.toUtf8() ); //replace encoded special characters and utf-8 encodings

    QString value = element.mid( sepidx + 1 );
    value.replace( "+", " " );
    value = QUrl::fromPercentEncoding( value.toUtf8() ); //replace encoded special characters and utf-8 encodings

    if ( key.compare( "SLD_BODY", Qt::CaseInsensitive ) == 0 )
    {
      key = "SLD";
    }
    else if ( key.compare( "SLD", Qt::CaseInsensitive ) == 0 )
    {
      QByteArray fileContents;
      if ( value.startsWith( "http", Qt::CaseInsensitive ) )
      {
        QgsHttpTransaction http( value );
        if ( !http.getSynchronously( fileContents ) )
        {
          continue;
        }
      }
      else if ( value.startsWith( "ftp", Qt::CaseInsensitive ) )
      {
        QgsFtpTransaction ftp;
        if ( !ftp.get( value, fileContents ) )
        {
          continue;
        }
        value = QUrl::fromPercentEncoding( fileContents );
      }
      else
      {
        continue; //only http and ftp supported at the moment
      }
      value = QUrl::fromPercentEncoding( fileContents );

    }
    parameters.insert( key.toUpper(), value );
    QgsMessageLog::logMessage( "inserting pair " + key.toUpper() + " // " + value + " into the parameter map" );
  }

  //feature info format?
  QString infoFormat = parameters.value( "INFO_FORMAT" );
  if ( !infoFormat.isEmpty() )
  {
    mFormat = infoFormat;
  }
  else //capabilities format or GetMap format
  {
    mFormatString = parameters.value( "FORMAT" );
    QString formatString = mFormatString;
    if ( !formatString.isEmpty() )
    {
      QgsMessageLog::logMessage( QString( "formatString is: %1" ).arg( formatString ) );

      //remove the image/ in front of the format
      if ( formatString.contains( "image/png", Qt::CaseInsensitive ) || formatString.compare( "png", Qt::CaseInsensitive ) == 0 )
      {
        formatString = "PNG";
      }
      else if ( formatString.contains( "image/jpeg", Qt::CaseInsensitive ) || formatString.contains( "image/jpg", Qt::CaseInsensitive )
                || formatString.compare( "jpg", Qt::CaseInsensitive ) == 0 )
      {
        formatString = "JPG";
      }
      else if ( formatString.compare( "svg", Qt::CaseInsensitive ) == 0 )
      {
        formatString = "SVG";
      }
      else if ( formatString.contains( "pdf", Qt::CaseInsensitive ) )
      {
        formatString = "PDF";
      }

      mFormat = formatString;
    }
  }

}
Ejemplo n.º 10
0
void MixerCurve::UpdateCurveUI()
{
    // get the user settings
    QString curveType = m_mixerUI->CurveType->currentText();


    m_mixerUI->CurveStep->setMinimum(0.0);
    m_mixerUI->CurveStep->setMaximum(100.0);
    m_mixerUI->CurveStep->setSingleStep(1.00);

    // set default visible
    m_mixerUI->minLabel->setVisible(true);
    m_mixerUI->CurveMin->setVisible(true);
    m_mixerUI->maxLabel->setVisible(false);
    m_mixerUI->CurveMax->setVisible(false);
    m_mixerUI->stepLabel->setVisible(false);
    m_mixerUI->CurveStep->setVisible(false);

    if (curveType.compare("Flat") == 0) {
        m_mixerUI->minLabel->setVisible(false);
        m_mixerUI->CurveMin->setVisible(false);
        m_mixerUI->stepLabel->setVisible(true);
        m_mixerUI->CurveStep->setVisible(true);
        m_mixerUI->CurveStep->setMinimum(m_mixerUI->CurveMin->minimum());
        m_mixerUI->CurveStep->setMaximum(m_mixerUI->CurveMax->maximum());
        m_mixerUI->CurveStep->setSingleStep(0.01);
        m_mixerUI->CurveStep->setValue(m_mixerUI->CurveMax->value() / 2);
    }
    if (curveType.compare("Linear") == 0) {
        m_mixerUI->maxLabel->setVisible(true);
        m_mixerUI->CurveMax->setVisible(true);
    }
    if (curveType.compare("Step") == 0) {
        m_mixerUI->maxLabel->setVisible(true);
        m_mixerUI->CurveMax->setVisible(true);
        m_mixerUI->stepLabel->setText("Step at");
        m_mixerUI->stepLabel->setVisible(true);
        m_mixerUI->CurveStep->setVisible(true);

        m_mixerUI->CurveStep->setMinimum(1.0);
    }
    if (curveType.compare("Exp") == 0) {
        m_mixerUI->maxLabel->setVisible(true);
        m_mixerUI->CurveMax->setVisible(true);
        m_mixerUI->stepLabel->setText("Power");
        m_mixerUI->stepLabel->setVisible(true);
        m_mixerUI->CurveStep->setVisible(true);

        m_mixerUI->CurveStep->setMinimum(1.0);
    }
    if (curveType.compare("Log") == 0) {
        m_mixerUI->maxLabel->setVisible(true);
        m_mixerUI->CurveMax->setVisible(true);
        m_mixerUI->stepLabel->setText("Power");
        m_mixerUI->stepLabel->setVisible(true);
        m_mixerUI->CurveStep->setVisible(true);
        m_mixerUI->CurveStep->setMinimum(1.0);
    }

    GenerateCurve();
}
Ejemplo n.º 11
0
QVariant QSystemLocale::query(QueryType type, QVariant in) const
{
    QSystemLocaleData *d = qSystemLocaleData();

    if (type == LocaleChanged) {
        d->readEnvironment();
        return QVariant();
    }

    QReadLocker locker(&d->lock);

    const QLocale &lc_numeric = d->lc_numeric;
    const QLocale &lc_time = d->lc_time;
    const QLocale &lc_monetary = d->lc_monetary;
    const QLocale &lc_messages = d->lc_messages;

    switch (type) {
    case DecimalPoint:
        return lc_numeric.decimalPoint();
    case GroupSeparator:
        return lc_numeric.groupSeparator();
    case ZeroDigit:
        return lc_numeric.zeroDigit();
    case NegativeSign:
        return lc_numeric.negativeSign();
    case DateFormatLong:
        return lc_time.dateFormat(QLocale::LongFormat);
    case DateFormatShort:
        return lc_time.dateFormat(QLocale::ShortFormat);
    case TimeFormatLong:
        return lc_time.timeFormat(QLocale::LongFormat);
    case TimeFormatShort:
        return lc_time.timeFormat(QLocale::ShortFormat);
    case DayNameLong:
        return lc_time.dayName(in.toInt(), QLocale::LongFormat);
    case DayNameShort:
        return lc_time.dayName(in.toInt(), QLocale::ShortFormat);
    case MonthNameLong:
        return lc_time.monthName(in.toInt(), QLocale::LongFormat);
    case MonthNameShort:
        return lc_time.monthName(in.toInt(), QLocale::ShortFormat);
    case StandaloneMonthNameLong:
        return lc_time.standaloneMonthName(in.toInt(), QLocale::LongFormat);
    case StandaloneMonthNameShort:
        return lc_time.standaloneMonthName(in.toInt(), QLocale::ShortFormat);
    case DateToStringLong:
        return lc_time.toString(in.toDate(), QLocale::LongFormat);
    case DateToStringShort:
        return lc_time.toString(in.toDate(), QLocale::ShortFormat);
    case TimeToStringLong:
        return lc_time.toString(in.toTime(), QLocale::LongFormat);
    case TimeToStringShort:
        return lc_time.toString(in.toTime(), QLocale::ShortFormat);
    case DateTimeFormatLong:
        return lc_time.dateTimeFormat(QLocale::LongFormat);
    case DateTimeFormatShort:
        return lc_time.dateTimeFormat(QLocale::ShortFormat);
    case DateTimeToStringLong:
        return lc_time.toString(in.toDateTime(), QLocale::LongFormat);
    case DateTimeToStringShort:
        return lc_time.toString(in.toDateTime(), QLocale::ShortFormat);
    case PositiveSign:
        return lc_numeric.positiveSign();
    case AMText:
        return lc_time.amText();
    case PMText:
        return lc_time.pmText();
    case FirstDayOfWeek:
        return lc_time.firstDayOfWeek();
    case CurrencySymbol:
        return lc_monetary.currencySymbol(QLocale::CurrencySymbolFormat(in.toUInt()));
    case CurrencyToString: {
        switch (in.type()) {
        case QVariant::Int:
            return lc_monetary.toCurrencyString(in.toInt());
        case QVariant::UInt:
            return lc_monetary.toCurrencyString(in.toUInt());
        case QVariant::Double:
            return lc_monetary.toCurrencyString(in.toDouble());
        case QVariant::LongLong:
            return lc_monetary.toCurrencyString(in.toLongLong());
        case QVariant::ULongLong:
            return lc_monetary.toCurrencyString(in.toULongLong());
        default:
            break;
        }
        return QString();
    }
    case MeasurementSystem: {
        const QString meas_locale = QString::fromLatin1(d->lc_measurement_var.constData(), d->lc_measurement_var.size());
        if (meas_locale.compare(QLatin1String("Metric"), Qt::CaseInsensitive) == 0)
            return QLocale::MetricSystem;
        if (meas_locale.compare(QLatin1String("Other"), Qt::CaseInsensitive) == 0)
            return QLocale::MetricSystem;
        return QVariant((int)QLocale(meas_locale).measurementSystem());
    }
    case UILanguages: {
        if (!d->uiLanguages.isEmpty())
            return d->uiLanguages;
        QString languages = QString::fromLatin1(qgetenv("LANGUAGE"));
        QStringList lst;
        if (languages.isEmpty())
            lst.append(QString::fromLatin1(d->lc_messages_var));
        else
            lst = languages.split(QLatin1Char(':'));

        for (int i = 0; i < lst.size(); ++i) {
            const QString &name = lst.at(i);
            QString lang, script, cntry;
            if (qt_splitLocaleName(name, lang, script, cntry)) {
                if (!cntry.length())
                    d->uiLanguages.append(lang);
                else
                    d->uiLanguages.append(lang % QLatin1Char('-') % cntry);
            }
        }
        return d->uiLanguages.isEmpty() ? QVariant() : QVariant(d->uiLanguages);
    }
    case StringToStandardQuotation:
        return lc_messages.quoteString(in.value<QStringRef>());
    case StringToAlternateQuotation:
        return lc_messages.quoteString(in.value<QStringRef>(), QLocale::AlternateQuotation);
    case ListToSeparatedString:
        return lc_messages.createSeparatedList(in.value<QStringList>());
    case LocaleChanged:
        Q_ASSERT(false);
    default:
        break;
    }
    return QVariant();
}
Ejemplo n.º 12
0
void Tree::charger(QString fileName)
{
    m_file = fileName;
    if (!fileName.endsWith(".ply")){
        qDebug() << "L'objet 3D doit etre defini dans un fichier au format ply";
        return;
    }

    QFile fichier(fileName);
    if (!fichier.open(QIODevice::ReadOnly | QIODevice::Text)){
        qDebug() << "Erreur lors de l'ouveture du fichier";
    }
    QTextStream flux(&fichier);

    int nbVertices = -1, nbFaces = -1;

    while ( !flux.atEnd() ){
        QString data = flux.readLine();
        if (data.section(" ", 0,0).compare("element")==0 || data.section(" ", 1,1).compare("vertex")==0){
            nbVertices = data.section(" ", 2,2).toInt();
            break;
        }
    }

    while ( !flux.atEnd() ){
        QString data = flux.readLine();
        if (data.section(" ", 0,0).compare("element")==0 || data.section(" ", 1,1).compare("face")==0){
            nbFaces = data.section(" ", 2,2).toInt();
            break;
        }
    }

    while ( !flux.atEnd() ){
        QString data = flux.readLine();
        if (data.compare("end_header")==0){
            break;
        }
    }

    if (nbVertices == -1 || nbFaces == -1 || flux.atEnd()){
        qDebug() << "Probleme de lecture du fichier ply";
        return;
    }

    m_nbVertices = nbVertices;

    m_vertices = new point[nbVertices];
    m_normales = new point[nbVertices];

    for (int i=0; i<nbVertices; i++){
        flux >> m_vertices[i].x; flux >> m_vertices[i].y; flux >> m_vertices[i].z;
        flux >> m_normales[i].x; flux >> m_normales[i].y; flux >> m_normales[i].z;
    }

    m_indices = new int[nbFaces*6];
    QString nb, t0, t1, t2, t3;
    int k=0;
    for (int i=0; i<nbFaces; i++){
        flux >> nb;
        //TRIANGLE
        if (nb.toInt() == 3){
            flux >> t0; flux >> t1; flux >> t2;
            m_indices[k] = t0.toInt(); m_indices[k+1] = t1.toInt(); m_indices[k+2] = t2.toInt();
            k+=3;
        }
        //QUAD
        if (nb.toInt() == 4){
            flux >> t0; flux >> t1; flux >> t2; flux >> t3;
            m_indices[k] = t0.toInt(); m_indices[k+1] = t1.toInt(); m_indices[k+2] = t2.toInt();
            m_indices[k+3] = t0.toInt(); m_indices[k+4] = t2.toInt(); m_indices[k+5] = t3.toInt();
            k+=6;
        }
Ejemplo n.º 13
0
void UpgradeMessage::saveHeaderData (DbPlugin &db, QString &k, QString &d, QString &sym, DBIndexItem &item)
{
  // is this a co key?
  bool ok = FALSE;
  double t = k.toDouble(&ok);
  if (ok)
  {
    if (t < 10000)
    {
      // its a chart object
      Setting t;
      t.parse(d);
      QString s = "Plugin";
      QString s2;
      t.getData(s,s2);
      if (s2.length())
      {
        t.remove(s);
        s = "Type";
        t.setData(s, s2);
      }

      s = "Plot";
      t.getData(s, s2);
      if (! s2.compare("Main Plot"))
      {
        s2 = "Bars";
        t.setData(s, s2);
      }
      else
        return;

      index.setChartObject(sym, k, t);
      return;
    }
  }

  if (! k.compare("Type"))
  {
    item.setType(d);
    return;
  }

  if (! k.compare("FuturesType"))
  {
    item.setFuturesType(d);
    return;
  }

  if (! k.compare("FuturesMonth"))
  {
    item.setFuturesMonth(d);
    return;
  }

  if (! k.compare("BarType"))
  {
    item.setBarType(d);
    return;
  }

  if (! k.compare("Fundamentals"))
  {
    index.setFundamentals(sym, d);
    return;
  }

  if (! k.compare("LocalIndicators"))
  {
    index.addIndicator(sym, d);
    return;
  }

  if (! k.compare("QuotePlugin"))
  {
    item.setQuotePlugin(d);
    return;
  }

  if (! k.compare("Symbol"))
  {
    item.setSymbol(d);
    return;
  }

  if (! k.compare("Title"))
  {
    item.setTitle(d);
    return;
  }

  if (! k.compare("Path"))
  {
    item.setPath(d);
    return;
  }

  if (! k.compare("SpreadFirstSymbol"))
  {
    int t = d.find("/data0/", 0, TRUE);
    d.replace(t + 5, 1, "1");
    QString ts = "FirstSymbol";
    db.setData(ts, d);
    return;
  }

  if (! k.compare("SpreadSecondSymbol"))
  {
    int t = d.find("/data0/", 0, TRUE);
    d.replace(t + 5, 1, "1");
    QString ts = "SecondSymbol";
    db.setData(ts, d);
    return;
  }

  if (! k.compare("IndexList"))
  {
    while (1)
    {
      int t = d.find("/data0/", 0, TRUE);
      if (t == -1)
        break;
      else
        d.replace(t + 5, 1, "1");
    }
    QString ts = "List";
    db.setData(ts, d);
    return;
  }

  if (! k.compare("CCAdjustment"))
  {
    QString ts = "Adjustment";
    db.setData(ts, d);
    return;
  }
}
Ejemplo n.º 14
0
bool SqliteDriver::drv_isSystemFieldName(const QString& name) const
{
    return    0 == name.compare(QLatin1String("_rowid_"), Qt::CaseInsensitive)
              || 0 == name.compare(QLatin1String("rowid"), Qt::CaseInsensitive)
              || 0 == name.compare(QLatin1String("oid"), Qt::CaseInsensitive);
}
Ejemplo n.º 15
0
QStringList QgsServerProjectParser::supportedOutputCrsList() const
{
  QStringList crsList;
  if ( !mXMLDoc )
  {
    return crsList;
  }

  QDomElement qgisElem = mXMLDoc->documentElement();
  if ( qgisElem.isNull() )
  {
    return crsList;
  }
  QDomElement propertiesElem = qgisElem.firstChildElement( "properties" );
  if ( propertiesElem.isNull() )
  {
    return crsList;
  }
  QDomElement wmsCrsElem = propertiesElem.firstChildElement( "WMSCrsList" );
  if ( !wmsCrsElem.isNull() )
  {
    QDomNodeList valueList = wmsCrsElem.elementsByTagName( "value" );
    for ( int i = 0; i < valueList.size(); ++i )
    {
      crsList.append( valueList.at( i ).toElement().text() );
    }
  }
  else
  {
    QDomElement wmsEpsgElem = propertiesElem.firstChildElement( "WMSEpsgList" );
    if ( !wmsEpsgElem.isNull() )
    {
      QDomNodeList valueList = wmsEpsgElem.elementsByTagName( "value" );
      bool conversionOk;
      for ( int i = 0; i < valueList.size(); ++i )
      {
        int epsgNr = valueList.at( i ).toElement().text().toInt( &conversionOk );
        if ( conversionOk )
        {
          crsList.append( QString( "EPSG:%1" ).arg( epsgNr ) );
        }
      }
    }
    else
    {
      //no CRS restriction defined in the project. Provide project CRS, wgs84 and pseudo mercator
      QString projectCrsId = projectCRS().authid();
      crsList.append( projectCrsId );
      if ( projectCrsId.compare( "EPSG:4326", Qt::CaseInsensitive ) != 0 )
      {
        crsList.append( QString( "EPSG:%1" ).arg( 4326 ) );
      }
      if ( projectCrsId.compare( "EPSG:3857", Qt::CaseInsensitive ) != 0 )
      {
        crsList.append( QString( "EPSG:%1" ).arg( 3857 ) );
      }
    }
  }

  return crsList;
}
Ejemplo n.º 16
0
void PgxConsole::showView(QString cmd)
{
    if(cmd.isEmpty()) {
        if(!textCursor().atEnd()) {
            QTextCursor cursor = textCursor();
            cursor.movePosition(QTextCursor::End);
            setTextCursor(cursor);
        }
        QTextBlock block = document()->end();
        if(!block.isValid())
            block = block.previous();
        cmd = block.text().trimmed();
        for (block = block.previous(); block.text().endsWith("\\"); block = block.previous())
            cmd.insert(0, block.text().trimmed().replace(QString("\\"), QString(" ")));
        // Do nothing on whitespace input.
        if(cmd.trimmed().isEmpty()) {
            appendPlainText("");
            return;
        }
    }
    // Save the command into the command history and
    // reassign the history iterator.
    history << cmd;
    hit = history.size();
    // 'clear' command to clear the console keeping the
    // history intact.
    if(cmd.compare("clear", Qt::CaseInsensitive) == 0) {
        clear();
    }
    // 'clear' command to clear the history alone. Console
    // is not cleared.
    else if(cmd.compare("clearh", Qt::CaseInsensitive) == 0) {
        history.clear();
        hit = 0;
        appendPlainText("");
    }
    // 'clearall' command to clear console and history
    else if(cmd.compare("clearall", Qt::CaseInsensitive) == 0) {
        history.clear();
        hit =0;
        clear();
    }
    // 'quit' command to clear console and history
    else if(cmd.compare("quit", Qt::CaseInsensitive) == 0) {
        history.clear();
        hit =0;
        clear();
        this->close();
        return;
    }
    // 'exit' command to clear console and history
    else if(cmd.compare("exit", Qt::CaseInsensitive) == 0) {
        history.clear();
        hit =0;
        clear();
        this->close();
    }
    else {
        // Reduce all groups of whitespace characters
        // to a single space between words.
        cmd = cmd.simplified();
        // Start a timer to count the seconds taken to display the
        // required output (used for queries and tables only).
        QTime t;
        t.start();
        emit showQueryView(database, cmd);
        this->appendPlainText("");
    }
}
Ejemplo n.º 17
0
int main( int argc, char * argv[] )
{
#ifndef _MSC_VER
  qInstallMsgHandler( dummyMessageHandler );
#endif

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

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

#if defined(MAPSERVER_SKIP_ECW)
  QgsDebugMsg( "Skipping GDAL ECW drivers in server." );
  QgsApplication::skipGdalDriver( "ECW" );
  QgsApplication::skipGdalDriver( "JP2ECW" );
#endif

  QSettings settings;

  QgsNetworkAccessManager *nam = QgsNetworkAccessManager::instance();
  QNetworkDiskCache *cache = new QNetworkDiskCache( 0 );

  QString cacheDirectory = settings.value( "cache/directory", QgsApplication::qgisSettingsDirPath() + "cache" ).toString();
  qint64 cacheSize = settings.value( "cache/size", 50 * 1024 * 1024 ).toULongLong();
  QgsDebugMsg( QString( "setCacheDirectory: %1" ).arg( cacheDirectory ) );
  QgsDebugMsg( QString( "setMaximumCacheSize: %1" ).arg( cacheSize ) );
  cache->setCacheDirectory( cacheDirectory );
  cache->setMaximumCacheSize( cacheSize );
  QgsDebugMsg( QString( "cacheDirectory: %1" ).arg( cache->cacheDirectory() ) );
  QgsDebugMsg( QString( "maximumCacheSize: %1" ).arg( cache->maximumCacheSize() ) );

  nam->setCache( cache );

  QDomImplementation::setInvalidDataPolicy( QDomImplementation::DropInvalidChars );

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

  QgsDebugMsg( qgsapp.applicationDirPath() + "/qgis_wms_server.log" );
  QgsApplication::createDB(); //init qgis.db (e.g. necessary for user crs)

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

  //create cache for capabilities XML
  QgsCapabilitiesCache capabilitiesCache;

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

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

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

    QMap<QString, QString> parameterMap;

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

    QMap<QString, QString>::const_iterator paramIt;

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

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

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

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

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

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

      theServer->setAdminConfigParser( adminConfigParser );


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

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

      return 0;
    }

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

    theServer->setAdminConfigParser( adminConfigParser );


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

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

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

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

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

      QString infoFormat = parameterMap.value( "INFO_FORMAT" );
      theRequestHandler->sendGetFeatureInfoResponse( featureInfoDoc, infoFormat );
      delete theRequestHandler;
      delete theServer;
      continue;
    }
    else if ( request.compare( "GetContext", Qt::CaseInsensitive ) == 0 )
    {
      try
      {
        QDomDocument doc = theServer->getContext();
        theRequestHandler->sendGetStyleResponse( doc );
      }
      catch ( QgsMapServiceException& ex )
      {
        theRequestHandler->sendServiceException( ex );
      }

      delete theRequestHandler;
      delete theServer;
      continue;
    }
    else if ( request.compare( "GetStyles", Qt::CaseInsensitive ) == 0 || request.compare( "GetStyle", Qt::CaseInsensitive ) == 0 ) // GetStyle for compatibility with earlier QGIS versions
    {
      try
      {
        QDomDocument doc = theServer->getStyle();
        theRequestHandler->sendGetStyleResponse( doc );
      }
      catch ( QgsMapServiceException& ex )
      {
        theRequestHandler->sendServiceException( ex );
      }

      delete theRequestHandler;
      delete theServer;
      continue;
    }
    else if ( request.compare( "GetLegendGraphic", Qt::CaseInsensitive ) == 0 ||
              request.compare( "GetLegendGraphics", Qt::CaseInsensitive ) == 0 )
      // GetLegendGraphics for compatibility with earlier QGIS versions
    {
      QImage* result = 0;
      try
      {
        result = theServer->getLegendGraphics();
      }
      catch ( QgsMapServiceException& ex )
      {
        QgsDebugMsg( "Caught exception during GetLegendGraphic request" );
        theRequestHandler->sendServiceException( ex );
      }

      if ( result )
      {
        QgsDebugMsg( "Sending GetLegendGraphic response" );
        //sending is the same for GetMap and GetLegendGraphic
        theRequestHandler->sendGetMapResponse( serviceString, result );
        QgsDebugMsg( "Response sent" );
      }
      else
      {
        //do some error handling
        QgsDebugMsg( "result image is 0" );
      }
      delete result;
      delete theRequestHandler;
      delete theServer;
      continue;
    }
    else if ( request.compare( "GetPrint", Qt::CaseInsensitive ) == 0 )
    {
      QByteArray* printOutput = 0;
      try
      {
        printOutput = theServer->getPrint( theRequestHandler->format() );
      }
      catch ( QgsMapServiceException& ex )
      {
        theRequestHandler->sendServiceException( ex );
      }

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

  delete theMapRenderer;
  QgsDebugMsg( "************* all done ***************" );
  return 0;
}
Ejemplo n.º 18
0
void WirelessFrame::getInterfaceInfo()
{
    const QString cur_iface = ui->interfaceComboBox->currentText();

    ui->channelComboBox->clear();
    ui->channelTypeComboBox->clear();
    ui->fcsComboBox->clear();

    if (cur_iface.isEmpty()) {
        updateWidgets();
        return;
    }

    for (guint i = 0; i < interfaces_->len; i++) {
        struct ws80211_interface *iface = g_array_index(interfaces_, struct ws80211_interface *, i);
        if (cur_iface.compare(iface->ifname) == 0) {
            struct ws80211_iface_info iface_info;
            QString units = " GHz";

            ws80211_get_iface_info(iface->ifname, &iface_info);

            for (guint i = 0; i < iface->frequencies->len; i++) {
                guint32 frequency = g_array_index(iface->frequencies, guint32, i);
                double ghz = frequency / 1000.0;
                QString chan_str = QString("%1 " UTF8_MIDDLE_DOT " %2%3")
                        .arg(ws80211_frequency_to_channel(frequency))
                        .arg(ghz, 0, 'f', 3)
                        .arg(units);
                ui->channelComboBox->addItem(chan_str, frequency);
                if ((int)frequency == iface_info.current_freq) {
                    ui->channelComboBox->setCurrentIndex(ui->channelComboBox->count() - 1);
                }
                units = QString();
            }
            // XXX - Do we need to make a distinction between WS80211_CHAN_NO_HT
            // and WS80211_CHAN_HT20? E.g. is there a driver that won't capture
            // HT frames if you use WS80211_CHAN_NO_HT?
            ui->channelTypeComboBox->addItem("20 MHz", WS80211_CHAN_NO_HT);
            if (iface_info.current_chan_type == WS80211_CHAN_NO_HT || iface_info.current_chan_type == WS80211_CHAN_HT20) {
                ui->channelTypeComboBox->setCurrentIndex(0);
            }
            if (iface->channel_types & (1 << WS80211_CHAN_HT40MINUS)) {
                ui->channelTypeComboBox->addItem("HT 40-", WS80211_CHAN_HT40MINUS);
                if (iface_info.current_chan_type == WS80211_CHAN_HT40MINUS) {
                    ui->channelTypeComboBox->setCurrentIndex(ui->channelTypeComboBox->count() - 1);
                }
            }
            if (iface->channel_types & (1 << WS80211_CHAN_HT40PLUS)) {
                ui->channelTypeComboBox->addItem("HT 40+", WS80211_CHAN_HT40PLUS);
                if (iface_info.current_chan_type == WS80211_CHAN_HT40PLUS) {
                    ui->channelTypeComboBox->setCurrentIndex(ui->channelTypeComboBox->count() - 1);
                }
            }

            if (ws80211_has_fcs_filter()) {
                ui->fcsComboBox->setCurrentIndex(iface_info.current_fcs_validation);
            }
        }
    }

    updateWidgets();
}
Ejemplo n.º 19
0
bool QgsMapToolIdentify::identifyRasterLayer( QList<IdentifyResult> *results, QgsRasterLayer *layer, QgsPointXY point, const QgsRectangle &viewExtent, double mapUnitsPerPixel )
{
  QgsDebugMsg( "point = " + point.toString() );
  if ( !layer )
    return false;

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

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

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

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

  QMap< QString, QString > attributes, derivedAttributes;

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

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

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

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

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

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

  derivedAttributes.insert( tr( "(clicked coordinate X)" ), formatXCoordinate( pointInCanvasCrs ) );
  derivedAttributes.insert( tr( "(clicked coordinate Y)" ), formatYCoordinate( pointInCanvasCrs ) );

  if ( identifyResult.isValid() )
  {
    QMap<int, QVariant> values = identifyResult.results();
    QgsGeometry geometry;
    if ( format == QgsRaster::IdentifyFormatValue )
    {
      for ( auto it = values.constBegin(); it != values.constEnd(); ++it )
      {
        QString valueString;
        if ( it.value().isNull() )
        {
          valueString = tr( "no data" );
        }
        else
        {
          QVariant value( it.value() );
          // The cast is legit. Quoting QT doc :
          // "Although this function is declared as returning QVariant::Type,
          // the return value should be interpreted as QMetaType::Type"
          if ( static_cast<QMetaType::Type>( value.type() ) == QMetaType::Float )
          {
            valueString = QgsRasterBlock::printValue( value.toFloat() );
          }
          else
          {
            valueString = QgsRasterBlock::printValue( value.toDouble() );
          }
        }
        attributes.insert( dprovider->generateBandName( it.key() ), valueString );
      }
      QString label = layer->name();
      results->append( IdentifyResult( qobject_cast<QgsMapLayer *>( layer ), label, attributes, derivedAttributes ) );
    }
    else if ( format == QgsRaster::IdentifyFormatFeature )
    {
      for ( auto it = values.constBegin(); it != values.constEnd(); ++it )
      {
        QVariant value = it.value();
        if ( value.type() == QVariant::Bool && !value.toBool() )
        {
          // sublayer not visible or not queryable
          continue;
        }

        if ( value.type() == QVariant::String )
        {
          // error
          // TODO: better error reporting
          QString label = layer->subLayers().value( it.key() );
          attributes.clear();
          attributes.insert( tr( "Error" ), value.toString() );

          results->append( IdentifyResult( qobject_cast<QgsMapLayer *>( layer ), label, attributes, derivedAttributes ) );
          continue;
        }

        // list of feature stores for a single sublayer
        const QgsFeatureStoreList featureStoreList = it.value().value<QgsFeatureStoreList>();

        for ( const QgsFeatureStore &featureStore : featureStoreList )
        {
          const QgsFeatureList storeFeatures = featureStore.features();
          for ( QgsFeature feature : storeFeatures )
          {
            attributes.clear();
            // WMS sublayer and feature type, a sublayer may contain multiple feature types.
            // Sublayer name may be the same as layer name and feature type name
            // may be the same as sublayer. We try to avoid duplicities in label.
            QString sublayer = featureStore.params().value( QStringLiteral( "sublayer" ) ).toString();
            QString featureType = featureStore.params().value( QStringLiteral( "featureType" ) ).toString();
            // Strip UMN MapServer '_feature'
            featureType.remove( QStringLiteral( "_feature" ) );
            QStringList labels;
            if ( sublayer.compare( layer->name(), Qt::CaseInsensitive ) != 0 )
            {
              labels << sublayer;
            }
            if ( featureType.compare( sublayer, Qt::CaseInsensitive ) != 0 || labels.isEmpty() )
            {
              labels << featureType;
            }

            QMap< QString, QString > derAttributes = derivedAttributes;
            derAttributes.unite( featureDerivedAttributes( &feature, layer ) );

            IdentifyResult identifyResult( qobject_cast<QgsMapLayer *>( layer ), labels.join( QStringLiteral( " / " ) ), featureStore.fields(), feature, derAttributes );

            identifyResult.mParams.insert( QStringLiteral( "getFeatureInfoUrl" ), featureStore.params().value( QStringLiteral( "getFeatureInfoUrl" ) ) );
            results->append( identifyResult );
          }
        }
      }
    }
    else // text or html
    {
      QgsDebugMsg( QString( "%1 HTML or text values" ).arg( values.size() ) );
      for ( auto it = values.constBegin(); it != values.constEnd(); ++it )
      {
        QString value = it.value().toString();
        attributes.clear();
        attributes.insert( QLatin1String( "" ), value );

        QString label = layer->subLayers().value( it.key() );
        results->append( IdentifyResult( qobject_cast<QgsMapLayer *>( layer ), label, attributes, derivedAttributes ) );
      }
    }
  }
  else
  {
    attributes.clear();
    QString value = identifyResult.error().message( QgsErrorMessage::Text );
    attributes.insert( tr( "Error" ), value );
    QString label = tr( "Identify error" );
    results->append( IdentifyResult( qobject_cast<QgsMapLayer *>( layer ), label, attributes, derivedAttributes ) );
  }

  return true;
}
Ejemplo n.º 20
0
bool SafetStats::checkExtraInfo(SafetWorkflow *wf, QStringList& fields, const QString& info) {

    if (wf->getExtrainfoRols().count() == 0 ) {

        for(int i = 0; wf->getTasklist().count(); i++) {

            SafetYAWL::ExtraInfoTask myextra;
            QString myidtask ;
            SafetTask *mytask = qobject_cast<SafetTask*>(wf->getTasklist().at(i));
            if (mytask == NULL ) {
                  qDebug("....generateExtraInfo mytask is NULL");
                break;
            }
            if (mytask->getVariables().count() == 0 ) {
//                qDebug("tokensForKey...TAREA no tiene variables....");
                continue;
            }
            myidtask = mytask->id().trimmed();
            SafetVariable* myvar = mytask->getVariables().at(0);
            QString myrolfield, mytsfield;
            myrolfield = myvar->rolfield();
            mytsfield = myvar->timestampfield();
            QRegExp rxCN("cn::(\\d+)");
            bool ok;
            int indexRolCN = -1;
            int indexTSCN = -1;
            QString derror;
            QString cnrol, cnts;
            //**********************************************************
            // Para ROL

            if (myrolfield.startsWith("cn::") || mytsfield.startsWith("cn::") &&
                info != "coloured") {
            QList<SafetWorkflow::InfoSigner> infosigners;
            infosigners = wf->getSignersDocument(myvar,info,derror);

            if (myrolfield.startsWith("cn::")) {
                int pos = myrolfield.indexOf(rxCN);
                if (pos >= 0) {
                    indexRolCN = rxCN.cap(1).toUInt(&ok);
                    if (indexRolCN < 0 ) {
                        SYE
                                << tr("Uno de los campos extra (Rol) no tiene una sintáxis"
                                      " adecuada cn::<numero>");
                        return false;
                    }
                }
                if ( info.compare("coloured",Qt::CaseInsensitive) != 0) {                    
                    if (indexRolCN < infosigners.count() ) {
                       cnrol = infosigners.at(indexRolCN).commonName;
                    }
                }

            }
            else if (!myrolfield.isEmpty() && !fields.contains(myrolfield)) {
                //myfields.append(myrolfield);
                SafetYAWL::_hasextrainfo = true;
                if (!wf->getExtrainfoRols().contains(myrolfield)) {
                    wf->getExtrainfoRols().append(myrolfield);

                }
            }
            //**********************************************************
            // Para Timestamp
            SYD << tr("...mytsfield...:%1")
                    .arg(mytsfield);
            if (mytsfield.startsWith("cn::")) {
                int pos = mytsfield.indexOf(rxCN);
                if (pos >= 0) {
                    indexTSCN = rxCN.cap(1).toUInt(&ok);
                    if (indexRolCN < 0 ) {
                            SYE
                                << tr("Uno de los campos extra (Rol) no tiene una sint�xis"
                                      " adecuada cn::<numero>");
                        qDebug("Rol no tiene sintaxis adecuada");
                        return false;
                    }
                }
                if ( info.compare("coloured",Qt::CaseInsensitive) != 0) {
                    if (indexTSCN < infosigners.count() ) {
                       cnts = infosigners.at(indexTSCN).date + " "
                              + infosigners.at(indexTSCN).hour;
                    }

                }

            }
            else if (!mytsfield.isEmpty() && !fields.contains(mytsfield)) {
                //myfields.append(mytsfield);
                if (!wf->getExtrainfoTSs().contains(mytsfield)) {
                    wf->getExtrainfoTSs().append(mytsfield);
                }
                SafetYAWL::_hasextrainfo = true;
            }
            if ( !cnrol.isEmpty() && !cnts.isEmpty()) {
                myextra.rolfied = myrolfield;
                myextra.timestampfield = mytsfield;
                myextra.rolvalue = cnrol;
                cnts.chop(1);
                QDateTime mydate = QDateTime::fromString(cnts,"dd-MM-yyyy hh:mm:ss");
                mydate = mydate.addSecs(-16200 ); // -4:30 horas //Venezuela TICKET PARA LOS DEMÁS ZONAS
                myextra.timestampvalue = mydate.toTime_t();

                SafetYAWL::_extrainfomap[ myidtask ] = myextra;

            }

        }
        }

    }

    fields += wf->getExtrainfoRols();
    fields += wf->getExtrainfoTSs();
    return true;

}
Ejemplo n.º 21
0
void InfoServer::incommingCommand(QString data){
    if(data.compare("LAST_SCANNED_TOKEN#") == 0){
        this->broadcastMessage(QString("%1").arg(HostStation::instance()->lastScannedToken()));
        return;
    }
}
Ejemplo n.º 22
0
QStringList SafetStats::processInfo(SafetNode* node, SafetStats::StatsType t,
                                    const QString& a,bool  norender,
                                    const QString& info) {
     QStringList result;
     QString newinfo;
     QString textualinfo;

     bool actived = SafetYAWL::getConf()["Stats/actived"] == QString("on");



     int fromdate = -1;
     int todate = -1;



     //Q_CHECK_PTR( wf );
     if ( node  == NULL) {
                 SYW << tr("Nodo con la informaci�n: \"%1\" es Nulo")
                 .arg(a);
         return result;

     }

     QString idtask =  node->id();
     SafetStats::AttrType attr = parseAttrType(a);
     int fichas = 0;
     if ( _totaltokens == -1 ) {
        if ( SafetYAWL::_isstatstokenfound ) {
           _totaltokens = 1;
        }
        else {
        _totaltokens =  numberAllOfTokens(norender,info);
        }
    }

     mywf->setNumberOfTokens( _totaltokens );

     if (node->numtokens() == -1 ) {
         if ( SafetYAWL::_isstatstokenfound ) {
              fichas = 0;
         }
         else {
            fichas = numberOfTokens(idtask,norender, info);
        }
        node->setNumtokens(fichas);
    }
     else {
         fichas = node->numtokens();
     }


     double porc = 0;
     bool isreported = false;
     QString reportvalue = SafetYAWL::getConf()["DefaultValues/report"].trimmed();
     
     QString currkey = mywf->id().trimmed()+idtask.trimmed();
     if (node->report().isEmpty() )  {
         if ( reportvalue == "yes") {
            isreported = true;
         }
         else  {
            isreported = false;
         }

     }
     else  if ( node->report().compare("no", Qt::CaseInsensitive)  != 0)  {

         if ( reportvalue.compare("yes",Qt::CaseInsensitive) == 0 ) {

             isreported = true;
         }
         else {

             isreported =  node->report().compare("yes", Qt::CaseInsensitive)  == 0;

             isreported = isreported || (info.length() > 0
                                         && info.compare("coloured",Qt::CaseInsensitive) != 0);

         }
     }
     else {
         isreported = false;
     }

     QString extrainfo;
     if (isreported ) {
         if ( _totaltokens != 0 ) {
             porc = double(fichas) / double(_totaltokens) ;
         }
         switch ( t ) {
         case Coloured:
             newinfo += tr(", ")+getInfoString(attr).arg(porc, 0, 'g', 2);
             newinfo += tr(", %1...%2").arg(fichas).arg(_totaltokens);

             if ( actived ) {
                 QString trydate = SafetYAWL::getConf()["Stats/fromdate"];
                 SYD << tr("....SafetStats::processInfo...trydate (init):|%1|")
                        .arg(trydate);
                 if (trydate != "*" ) {
                     fromdate = QDateTime::fromString(trydate,Safet::DateFormat).toTime_t();
                 }

                 trydate = SafetYAWL::getConf()["Stats/todate"];
                 SYD << tr("....afetStats::processInfo...trydate (end):|%1|")
                        .arg(trydate);

                 if (trydate != "*" ) {
                     todate = QDateTime::fromString(trydate,Safet::DateFormat).toTime_t();
                 }

                 SafetBinaryRepo myrepo;
                 if (myrepo.fileExists() ) {
                     myrepo.open();
                 }


                 if (myrepo.fileExists() ) {
                     extrainfo = myrepo.calculateAverage("graphs",currkey,
                                                         fromdate,
                                                         todate);

                     if (!extrainfo.isEmpty()) {
                         newinfo += QString("...%1...%2")
                                 .arg(tr("n/a"))
                                 .arg(extrainfo+ tr("(Promedio/Espera)"));
                     }
                 }
             }


             break;
         case ForTokenKey:

             if ( porc == 1 ) {
                 SafetYAWL::_isstatstokenfound = true; // Es el �nico token
                 textualinfo =  trUtf8("*El documento o solicitud se encuentra <b>aquí</b>");
             }

             newinfo +=  tr(", ")+getInfoString(attr).arg(porc, 0, 'g', 2);
             newinfo += tr(", %1...%2...").arg(fichas).arg(_totaltokens);
             break;
         default:;
         }
     }
     result.append(newinfo);
     if ( textualinfo.length() > 0 ) {
         result.append(textualinfo);
     }
     return result;
}
Ejemplo n.º 23
0
void QgsGrassEdit::alterTable( void )
{
  QgsDebugMsg( "entered." );

  // Create new table if first column name is editable otherwise alter table
  int field = mTableField->currentText().toInt();

  QString sql;
  QString type;

  if ( mAttributeTable->item( 0, 0 )->flags() & Qt::ItemIsEnabled )
  {
    QgsDebugMsg( "Create new table" );

    for ( int i = 0; i < mAttributeTable->rowCount(); i++ )
    {
      if ( i > 0 )
        sql.append( ", " );

      type = mAttributeTable->item( i, 1 )->text();
      sql.append( mAttributeTable->item( i, 0 )->text() + " " + type );

      if ( type.compare( "varchar" ) == 0 )
      {
        sql.append( " (" + mAttributeTable->item( i, 2 )->text() + ")" );
      }
    }

    QString *error = mProvider->createTable( field, mAttributeTable->item( 0, 0 )->text(), sql );

    if ( !error->isEmpty() )
    {
      QMessageBox::warning( 0, tr( "Warning" ), *error );
    }
    else
    {
      QMessageBox::information( 0, tr( "Info" ), tr( "The table was created" ) );
      QString str;
      str.sprintf( "%d", field );
      mFieldBox->addItem( str );
    }
    delete error;
  }
  else
  {
    QgsDebugMsg( "Alter table" );

    for ( int i = 0; i < mAttributeTable->rowCount(); i++ )
    {
      if ( !( mAttributeTable->item( i, 0 )->flags() & Qt::ItemIsEnabled ) )
        continue;

      type = mAttributeTable->item( i, 1 )->text();
      sql = mAttributeTable->item( i, 0 )->text() + " " + type;

      if ( type.compare( "varchar" ) == 0 )
      {
        sql.append( " (" + mAttributeTable->item( i, 2 )->text() + ")" );
      }

      QString *error = mProvider->addColumn( field, sql );

      if ( !error->isEmpty() )
      {
        QMessageBox::warning( 0, tr( "Warning" ), *error );
      }
      delete error;
    }
  }

  setAttributeTable( field );
}
Ejemplo n.º 24
0
BlockField::dataGenericBlock::dataGenericBlock(QXmlStreamReader & xml)
{

	QXmlStreamAttributes attributes = xml.attributes();
	if(attributes.hasAttribute("id")) {
		id = attributes.value("id").toInt();
	} else {
		id = -1;
	}

	xml.readNext(); // Next element
	while(!(xml.tokenType() == QXmlStreamReader::EndElement && (xml.name() == "block"))) {
		if(xml.tokenType() == QXmlStreamReader::StartElement) {
			if(xml.name() == "adaptors") {
				xml.readNext();
				while(!(xml.tokenType() == QXmlStreamReader::EndElement && xml.name() == "adaptors")) {
					if(xml.tokenType() == QXmlStreamReader::StartElement && xml.name() == "adaptor") {
						dataGenericBlock::_adaptor att;
						QXmlStreamAttributes attributes = xml.attributes();
						if(attributes.hasAttribute("end")) {
							QString end = attributes.value("end").toString();
							if(end.compare("3p")) {
								att.end = dataGenericBlock::_adaptor::p3;
							} else if (end.compare("5p")) {
								att.end = dataGenericBlock::_adaptor::p5;
							} else if (end.compare("both")) {
								att.end = dataGenericBlock::_adaptor::both;
							}
						} else {
							att.end = dataGenericBlock::_adaptor::both;
						}
						xml.readNext();
						if(xml.tokenType() == QXmlStreamReader::Characters) {
							att.sequence = xml.text().toString();
							adaptor.append(att);
						}
					}
					xml.readNext();
				}
			} else if(xml.name() == "arguments") {
				xml.readNext();
				while(!(xml.tokenType() == QXmlStreamReader::EndElement && xml.name() == "arguments")) {
					_file tempFile;
					tempFile.fileType = _file::invalid;
					xml.readNext();
					if(xml.tokenType() == QXmlStreamReader::StartElement && xml.name() == "argument") {
						QXmlStreamAttributes attributes = xml.attributes();
						if(attributes.hasAttribute("type")) {
							QString end = attributes.value("type").toString();
							if(!end.compare("infile")) {
								tempFile.fileType = dataGenericBlock::_file::fileIn;
							} else if (!end.compare("outfile")) {
								tempFile.fileType = dataGenericBlock::_file::fileOut;
							}
						} else {
							tempFile.fileType = dataGenericBlock::_file::invalid;
						}
						//xml.readNext();
						while(!(xml.tokenType() == QXmlStreamReader::EndElement && xml.name() == "argument")) {
							if(xml.tokenType() == QXmlStreamReader::StartElement && xml.name() == "description") {
								xml.readNext();
								if(xml.tokenType() == QXmlStreamReader::Characters) {
									tempFile.description = xml.text().toString();
								}
							}
							if(xml.tokenType() == QXmlStreamReader::StartElement && xml.name() == "formats") {
								while(!(xml.tokenType() == QXmlStreamReader::EndElement && xml.name() == "format")) {
									xml.readNext();
									if(xml.tokenType() == QXmlStreamReader::Characters) {
										tempFile.format.append(xml.text().toString());
									}
								}
							}
							xml.readNext();
						}
					}
					if(tempFile.fileType != _file::invalid) {
						argument.append(tempFile);
					}
				}
			} else {
				QString nameTemp = xml.name().toString();
				xml.readNext();
				if(xml.tokenType() == QXmlStreamReader::Characters && !xml.text().isEmpty()) {
					data.insert(nameTemp, xml.text().toString());
				}
			}
		} else {
			xml.readNext(); // we dont have StartElement, read next
		}
	}

	if(data.contains("section")) {
		QString sec = data["section"].split("/")[0];
		if(!sec.compare("script")) {
			type = dataGenericBlock::script;
		} else if(!sec.compare("sample")) {
			type = dataGenericBlock::sample;
		} else {
			type = dataGenericBlock::invalid;
		}
	} else {
		data["section"] = "other";
	}
}
Ejemplo n.º 25
0
QStringList QFontconfigDatabase::fallbacksForFamily(const QString &family, QFont::Style style, QFont::StyleHint styleHint, QChar::Script script) const
{
    QStringList fallbackFamilies;
    FcPattern *pattern = FcPatternCreate();
    if (!pattern)
        return fallbackFamilies;

    FcValue value;
    value.type = FcTypeString;
    QByteArray cs = family.toUtf8();
    value.u.s = (const FcChar8 *)cs.data();
    FcPatternAdd(pattern,FC_FAMILY,value,true);

    int slant_value = FC_SLANT_ROMAN;
    if (style == QFont::StyleItalic)
        slant_value = FC_SLANT_ITALIC;
    else if (style == QFont::StyleOblique)
        slant_value = FC_SLANT_OBLIQUE;
    FcPatternAddInteger(pattern, FC_SLANT, slant_value);

    Q_ASSERT(uint(script) < QChar::ScriptCount);
    if (*specialLanguages[script] != '\0') {
        FcLangSet *ls = FcLangSetCreate();
        FcLangSetAdd(ls, (const FcChar8*)specialLanguages[script]);
        FcPatternAddLangSet(pattern, FC_LANG, ls);
        FcLangSetDestroy(ls);
    } else if (!family.isEmpty()) {
        // If script is Common or Han, then it may include languages like CJK,
        // we should attach system default language set to the pattern
        // to obtain correct font fallback list (i.e. if LANG=zh_CN
        // then we normally want to use a Chinese font for CJK text;
        // while a Japanese font should be used for that if LANG=ja)
        FcPattern *dummy = FcPatternCreate();
        FcDefaultSubstitute(dummy);
        FcChar8 *lang = 0;
        FcResult res = FcPatternGetString(dummy, FC_LANG, 0, &lang);
        if (res == FcResultMatch)
            FcPatternAddString(pattern, FC_LANG, lang);
        FcPatternDestroy(dummy);
    }

    const char *stylehint = getFcFamilyForStyleHint(styleHint);
    if (stylehint) {
        value.u.s = (const FcChar8 *)stylehint;
        FcPatternAddWeak(pattern, FC_FAMILY, value, FcTrue);
    }

    FcConfigSubstitute(0, pattern, FcMatchPattern);
    FcDefaultSubstitute(pattern);

    FcResult result = FcResultMatch;
    FcFontSet *fontSet = FcFontSort(0,pattern,FcFalse,0,&result);
    FcPatternDestroy(pattern);

    if (fontSet) {
        for (int i = 0; i < fontSet->nfont; i++) {
            FcChar8 *value = 0;
            if (FcPatternGetString(fontSet->fonts[i], FC_FAMILY, 0, &value) != FcResultMatch)
                continue;
            //         capitalize(value);
            QString familyName = QString::fromUtf8((const char *)value);
            if (!fallbackFamilies.contains(familyName,Qt::CaseInsensitive) &&
                familyName.compare(family, Qt::CaseInsensitive)) {
                fallbackFamilies << familyName;
            }
        }
        FcFontSetDestroy(fontSet);
    }
//    qDebug() << "fallbackFamilies for:" << family << style << styleHint << script << fallbackFamilies;

    return fallbackFamilies;
}
Ejemplo n.º 26
0
bool WhisperPeers::isCurrentTopicAll() const
{
	QString const topic = m_ui->topics->currentText();
	return !topic.compare(c_filterAll);
}
Ejemplo n.º 27
0
void QgsMarkerLineSymbolLayerV2::renderPolyline( const QPolygonF& points, QgsSymbolV2RenderContext& context )
{
  double offset = mOffset;
  QgsExpression* offsetExpression = expression( "offset" );
  if ( offsetExpression )
  {
    offset = offsetExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toDouble();
  }

  Placement placement = mPlacement;
  QgsExpression* placementExpression = expression( "placement" );
  if ( placementExpression )
  {
    QString placementString = placementExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString();
    if ( placementString.compare( "vertex", Qt::CaseInsensitive ) == 0 )
    {
      placement = Vertex;
    }
    else if ( placementString.compare( "lastvertex", Qt::CaseInsensitive ) == 0 )
    {
      placement = LastVertex;
    }
    else if ( placementString.compare( "firstvertex", Qt::CaseInsensitive ) == 0 )
    {
      placement = FirstVertex;
    }
    else if ( placementString.compare( "centerpoint", Qt::CaseInsensitive ) == 0 )
    {
      placement = CentralPoint;
    }
    else
    {
      placement = Interval;
    }
  }

  if ( offset == 0 )
  {
    if ( placement == Interval )
      renderPolylineInterval( points, context );
    else if ( placement == CentralPoint )
      renderPolylineCentral( points, context );
    else
      renderPolylineVertex( points, context, placement );
  }
  else
  {
    QList<QPolygonF> mline = ::offsetLine( points, offset * QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mOffsetUnit, mOffsetMapUnitScale ), context.feature() ? context.feature()->geometry()->type() : QGis::Line );

    for ( int part = 0; part < mline.count(); ++part )
    {
      const QPolygonF &points2 = mline[ part ];

      if ( placement == Interval )
        renderPolylineInterval( points2, context );
      else if ( placement == CentralPoint )
        renderPolylineCentral( points2, context );
      else
        renderPolylineVertex( points2, context, placement );
    }
  }
}
Ejemplo n.º 28
0
void QgsServerProjectParser::serviceCapabilities( QDomElement& parentElement, QDomDocument& doc, const QString& service, bool sia2045 ) const
{
  QDomElement propertiesElement = propertiesElem();
  if ( propertiesElement.isNull() )
  {
    QgsConfigParserUtils::fallbackServiceCapabilities( parentElement, doc );
    return;
  }
  QDomElement serviceElem = doc.createElement( "Service" );

  QDomElement serviceCapabilityElem = propertiesElement.firstChildElement( "WMSServiceCapabilities" );
  if ( serviceCapabilityElem.isNull() || serviceCapabilityElem.text().compare( "true", Qt::CaseInsensitive ) != 0 )
  {
    QgsConfigParserUtils::fallbackServiceCapabilities( parentElement, doc );
    return;
  }

  //Service name
  QDomElement wmsNameElem = doc.createElement( "Name" );
  QDomText wmsNameText = doc.createTextNode( service );
  wmsNameElem.appendChild( wmsNameText );
  serviceElem.appendChild( wmsNameElem );

  //WMS title
  //why not use project title ?
  QDomElement titleElem = propertiesElement.firstChildElement( "WMSServiceTitle" );
  if ( !titleElem.isNull() )
  {
    QDomElement wmsTitleElem = doc.createElement( "Title" );
    QDomText wmsTitleText = doc.createTextNode( titleElem.text() );
    wmsTitleElem.appendChild( wmsTitleText );
    serviceElem.appendChild( wmsTitleElem );
  }

  //WMS abstract
  QDomElement abstractElem = propertiesElement.firstChildElement( "WMSServiceAbstract" );
  if ( !abstractElem.isNull() )
  {
    QDomElement wmsAbstractElem = doc.createElement( "Abstract" );
    QDomText wmsAbstractText = doc.createTextNode( abstractElem.text() );
    wmsAbstractElem.appendChild( wmsAbstractText );
    serviceElem.appendChild( wmsAbstractElem );
  }

  //keyword list
  QDomElement keywordListElem = propertiesElement.firstChildElement( "WMSKeywordList" );
  if ( service.compare( "WMS", Qt::CaseInsensitive ) == 0 )
  {
    QDomElement wmsKeywordElem = doc.createElement( "KeywordList" );
    //add default keyword
    QDomElement keywordElem = doc.createElement( "Keyword" );
    keywordElem.setAttribute( "vocabulary", "ISO" );
    QDomText keywordText = doc.createTextNode( "infoMapAccessService" );
    /* If WFS and WCS 2.0 is implemented
    if ( service.compare( "WFS", Qt::CaseInsensitive ) == 0 )
      keywordText = doc.createTextNode( "infoFeatureAccessService" );
    else if ( service.compare( "WCS", Qt::CaseInsensitive ) == 0 )
      keywordText = doc.createTextNode( "infoCoverageAccessService" );*/
    keywordElem.appendChild( keywordText );
    wmsKeywordElem.appendChild( keywordElem );
    serviceElem.appendChild( wmsKeywordElem );
    //add config keywords
    if ( !keywordListElem.isNull() && !keywordListElem.text().isEmpty() )
    {
      QDomNodeList keywordList = keywordListElem.elementsByTagName( "value" );
      for ( int i = 0; i < keywordList.size(); ++i )
      {
        keywordElem = doc.createElement( "Keyword" );
        keywordText = doc.createTextNode( keywordList.at( i ).toElement().text() );
        keywordElem.appendChild( keywordText );
        if ( sia2045 )
        {
          keywordElem.setAttribute( "vocabulary", "SIA_Geo405" );
        }
        wmsKeywordElem.appendChild( keywordElem );
      }
    }
  }
  else if ( !keywordListElem.isNull() && !keywordListElem.text().isEmpty() )
  {
    QDomNodeList keywordNodeList = keywordListElem.elementsByTagName( "value" );
    QStringList keywordList;
    for ( int i = 0; i < keywordNodeList.size(); ++i )
    {
      keywordList.push_back( keywordNodeList.at( i ).toElement().text() );
    }
    QDomElement wmsKeywordElem = doc.createElement( "Keywords" );
    if ( service.compare( "WCS", Qt::CaseInsensitive ) == 0 )
      wmsKeywordElem = doc.createElement( "keywords" );
    QDomText keywordText = doc.createTextNode( keywordList.join( ", " ) );
    wmsKeywordElem.appendChild( keywordText );
    serviceElem.appendChild( wmsKeywordElem );
  }

  //OnlineResource element is mandatory according to the WMS specification
  QDomElement wmsOnlineResourceElem = propertiesElement.firstChildElement( "WMSOnlineResource" );
  if ( !wmsOnlineResourceElem.isNull() )
  {
    QDomElement onlineResourceElem = doc.createElement( "OnlineResource" );
    if ( service.compare( "WFS", Qt::CaseInsensitive ) == 0 )
    {
      QDomText onlineResourceText = doc.createTextNode( wmsOnlineResourceElem.text() );
      onlineResourceElem.appendChild( onlineResourceText );
    }
    else
    {
      onlineResourceElem.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" );
      onlineResourceElem.setAttribute( "xlink:type", "simple" );
      onlineResourceElem.setAttribute( "xlink:href", wmsOnlineResourceElem.text() );
    }
    serviceElem.appendChild( onlineResourceElem );
  }

  if ( service.compare( "WMS", Qt::CaseInsensitive ) == 0 ) //no contact information in WFS 1.0 and WCS 1.0
  {
    //Contact information
    QDomElement contactInfoElem = doc.createElement( "ContactInformation" );

    //Contact person primary
    QDomElement contactPersonPrimaryElem = doc.createElement( "ContactPersonPrimary" );

    //Contact person
    QDomElement contactPersonElem = propertiesElement.firstChildElement( "WMSContactPerson" );
    QString contactPersonString;
    if ( !contactPersonElem.isNull() )
    {
      contactPersonString = contactPersonElem.text();
    }
    QDomElement wmsContactPersonElem = doc.createElement( "ContactPerson" );
    QDomText contactPersonText = doc.createTextNode( contactPersonString );
    wmsContactPersonElem.appendChild( contactPersonText );
    contactPersonPrimaryElem.appendChild( wmsContactPersonElem );


    //Contact organisation
    QDomElement contactOrganizationElem = propertiesElement.firstChildElement( "WMSContactOrganization" );
    QString contactOrganizationString;
    if ( !contactOrganizationElem.isNull() )
    {
      contactOrganizationString = contactOrganizationElem.text();
    }
    QDomElement wmsContactOrganizationElem = doc.createElement( "ContactOrganization" );
    QDomText contactOrganizationText = doc.createTextNode( contactOrganizationString );
    wmsContactOrganizationElem.appendChild( contactOrganizationText );
    contactPersonPrimaryElem.appendChild( wmsContactOrganizationElem );

    //Contact position
    QDomElement contactPositionElem = propertiesElement.firstChildElement( "WMSContactPosition" );
    QString contactPositionString;
    if ( !contactPositionElem.isNull() )
    {
      contactPositionString = contactPositionElem.text();
    }
    QDomElement wmsContactPositionElem = doc.createElement( "ContactPosition" );
    QDomText contactPositionText = doc.createTextNode( contactPositionString );
    wmsContactPositionElem.appendChild( contactPositionText );
    contactPersonPrimaryElem.appendChild( wmsContactPositionElem );
    contactInfoElem.appendChild( contactPersonPrimaryElem );

    //phone
    QDomElement phoneElem = propertiesElement.firstChildElement( "WMSContactPhone" );
    if ( !phoneElem.isNull() )
    {
      QDomElement wmsPhoneElem = doc.createElement( "ContactVoiceTelephone" );
      QDomText wmsPhoneText = doc.createTextNode( phoneElem.text() );
      wmsPhoneElem.appendChild( wmsPhoneText );
      contactInfoElem.appendChild( wmsPhoneElem );
    }

    //mail
    QDomElement mailElem = propertiesElement.firstChildElement( "WMSContactMail" );
    if ( !mailElem.isNull() )
    {
      QDomElement wmsMailElem = doc.createElement( "ContactElectronicMailAddress" );
      QDomText wmsMailText = doc.createTextNode( mailElem.text() );
      wmsMailElem.appendChild( wmsMailText );
      contactInfoElem.appendChild( wmsMailElem );
    }

    serviceElem.appendChild( contactInfoElem );
  }

  //Fees
  QDomElement feesElem = propertiesElement.firstChildElement( "WMSFees" );
  QDomElement wmsFeesElem = doc.createElement( "Fees" );
  QDomText wmsFeesText = doc.createTextNode( "conditions unknown" ); // default value if access conditions are unknown
  if ( !feesElem.isNull() && !feesElem.text().isEmpty() )
  {
    wmsFeesText = doc.createTextNode( feesElem.text() );
  }
  wmsFeesElem.appendChild( wmsFeesText );
  serviceElem.appendChild( wmsFeesElem );

  //AccessConstraints
  QDomElement accessConstraintsElem = propertiesElement.firstChildElement( "WMSAccessConstraints" );
  QDomElement wmsAccessConstraintsElem = doc.createElement( "AccessConstraints" );
  QDomText wmsAccessConstraintsText = doc.createTextNode( "None" ); // default value if access constraints are unknown
  if ( !accessConstraintsElem.isNull() && !accessConstraintsElem.text().isEmpty() )
  {
    wmsAccessConstraintsText = doc.createTextNode( accessConstraintsElem.text() );
  }
  wmsAccessConstraintsElem.appendChild( wmsAccessConstraintsText );
  serviceElem.appendChild( wmsAccessConstraintsElem );

  //max width, max height for WMS
  if ( service.compare( "WMS", Qt::CaseInsensitive ) == 0 )
  {
    QString version = doc.documentElement().attribute( "version" );
    if ( version != "1.1.1" )
    {
      //max width
      QDomElement mwElem = propertiesElement.firstChildElement( "WMSMaxWidth" );
      if ( !mwElem.isNull() )
      {
        QDomElement maxWidthElem = doc.createElement( "MaxWidth" );
        QDomText maxWidthText = doc.createTextNode( mwElem.text() );
        maxWidthElem.appendChild( maxWidthText );
        serviceElem.appendChild( maxWidthElem );
      }
      //max height
      QDomElement mhElem = propertiesElement.firstChildElement( "WMSMaxHeight" );
      if ( !mhElem.isNull() )
      {
        QDomElement maxHeightElem = doc.createElement( "MaxHeight" );
        QDomText maxHeightText = doc.createTextNode( mhElem.text() );
        maxHeightElem.appendChild( maxHeightText );
        serviceElem.appendChild( maxHeightElem );
      }
    }
  }
  parentElement.appendChild( serviceElem );
}
Ejemplo n.º 29
0
bool QAudioInputPrivate::open()
{
#ifdef DEBUG_AUDIO
    QTime now(QTime::currentTime());
    qDebug()<<now.second()<<"s "<<now.msec()<<"ms :open()";
#endif
    clockStamp.restart();
    timeStamp.restart();
    elapsedTimeOffset = 0;

    int dir;
    int err = 0;
    int count=0;
    unsigned int sampleRate=settings.sampleRate();

    if (!settings.isValid()) {
        qWarning("QAudioInput: open error, invalid format.");
    } else if (settings.sampleRate() <= 0) {
        qWarning("QAudioInput: open error, invalid sample rate (%d).",
                 settings.sampleRate());
    } else {
        err = -1;
    }

    if (err == 0) {
        errorState = QAudio::OpenError;
        deviceState = QAudio::StoppedState;
        emit errorChanged(errorState);
        return false;
    }


    QString dev = QString(QLatin1String(m_device.constData()));
    QList<QByteArray> devices = QAudioDeviceInfoInternal::availableDevices(QAudio::AudioInput);
    if(dev.compare(QLatin1String("default")) == 0) {
#if(SND_LIB_MAJOR == 1 && SND_LIB_MINOR == 0 && SND_LIB_SUBMINOR >= 14)
        if (devices.size() > 0)
            dev = QLatin1String(devices.first());
        else
            return false;
#else
        dev = QLatin1String("hw:0,0");
#endif
    } else {
#if(SND_LIB_MAJOR == 1 && SND_LIB_MINOR == 0 && SND_LIB_SUBMINOR >= 14)
        dev = QLatin1String(m_device);
#else
        int idx = 0;
        char *name;

        QString shortName = QLatin1String(m_device.mid(m_device.indexOf('=',0)+1).constData());

        while(snd_card_get_name(idx,&name) == 0) {
            if(qstrncmp(shortName.toLocal8Bit().constData(),name,shortName.length()) == 0)
                break;
            idx++;
        }
        dev = QString(QLatin1String("hw:%1,0")).arg(idx);
#endif
    }

    // Step 1: try and open the device
    while((count < 5) && (err < 0)) {
        err=snd_pcm_open(&handle,dev.toLocal8Bit().constData(),SND_PCM_STREAM_CAPTURE,0);
        if(err < 0)
            count++;
    }
    if (( err < 0)||(handle == 0)) {
        errorState = QAudio::OpenError;
        deviceState = QAudio::StoppedState;
        emit stateChanged(deviceState);
        return false;
    }
    snd_pcm_nonblock( handle, 0 );

    // Step 2: Set the desired HW parameters.
    snd_pcm_hw_params_alloca( &hwparams );

    bool fatal = false;
    QString errMessage;
    unsigned int chunks = 8;

    err = snd_pcm_hw_params_any( handle, hwparams );
    if ( err < 0 ) {
        fatal = true;
        errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_any: err = %1").arg(err);
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_rate_resample( handle, hwparams, 1 );
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_rate_resample: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_access( handle, hwparams, access );
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_access: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = setFormat();
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_format: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_channels( handle, hwparams, (unsigned int)settings.channelCount() );
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_channels: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_rate_near( handle, hwparams, &sampleRate, 0 );
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_rate_near: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_buffer_time_near(handle, hwparams, &buffer_time, &dir);
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_buffer_time_near: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_period_time_near(handle, hwparams, &period_time, &dir);
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_period_time_near: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_periods_near(handle, hwparams, &chunks, &dir);
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_periods_near: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params(handle, hwparams);
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params: err = %1").arg(err);
        }
    }
    if( err < 0) {
        qWarning()<<errMessage;
        errorState = QAudio::OpenError;
        deviceState = QAudio::StoppedState;
        emit stateChanged(deviceState);
        return false;
    }
    snd_pcm_hw_params_get_buffer_size(hwparams,&buffer_frames);
    buffer_size = snd_pcm_frames_to_bytes(handle,buffer_frames);
    snd_pcm_hw_params_get_period_size(hwparams,&period_frames, &dir);
    period_size = snd_pcm_frames_to_bytes(handle,period_frames);
    snd_pcm_hw_params_get_buffer_time(hwparams,&buffer_time, &dir);
    snd_pcm_hw_params_get_period_time(hwparams,&period_time, &dir);

    // Step 3: Set the desired SW parameters.
    snd_pcm_sw_params_t *swparams;
    snd_pcm_sw_params_alloca(&swparams);
    snd_pcm_sw_params_current(handle, swparams);
    snd_pcm_sw_params_set_start_threshold(handle,swparams,period_frames);
    snd_pcm_sw_params_set_stop_threshold(handle,swparams,buffer_frames);
    snd_pcm_sw_params_set_avail_min(handle, swparams,period_frames);
    snd_pcm_sw_params(handle, swparams);

    // Step 4: Prepare audio
    ringBuffer.resize(buffer_size);
    snd_pcm_prepare( handle );
    snd_pcm_start(handle);

    // Step 5: Setup timer
    bytesAvailable = checkBytesReady();

    if(pullMode)
        connect(audioSource,SIGNAL(readyRead()),this,SLOT(userFeed()));

    // Step 6: Start audio processing
    chunks = buffer_size/period_size;
    timer->start(period_time*chunks/2000);

    errorState  = QAudio::NoError;

    totalTimeValue = 0;

    return true;
}
Ejemplo n.º 30
0
QString LoadData::checkSpecialCases(QString name) {
	if (name.compare("Erin Mills&Eglinton") == 0)
		return "Mississauga Erin Mills&Eglinton";
	else if (name.compare("St.Catharines Fairview M.") == 0)
		return "St.Catharines Fairview Mall";
	else if (name.compare("Grimsby ") == 0)
		return "Grimsby Carpool Lot";
	else if (name.compare("Stoney Creek") == 0)
		return "Stoney Creek Nash Rd & Barton St.";
	else if (name.compare("Mdwvale Derry & Winston") == 0)
		return "Meadowvale Derry & Winston Ch.";
	else if (name.compare("Mdwvale Erin Mills&Miss.") == 0)
		return "Meadowvale Erin Mills & Miss.";
	else if (name.compare("Meadowvale  Business Park") == 0)
		return "Meadowvale Business Park Syntex & Financial";
	else if (name.compare("Rockwood") == 0)
		return "Rockwood Alma St. & Main St.";
	else if (name.compare("Brampton Hwy10 & Bovaird") == 0)
		return "Brampton Hurontario & Bovaird";
	else if (name.compare("Bronte   Hwy407/Bronte Rd") == 0)
		return "Bronte Carpool Lot Hwy407&Bronte Rd";
	else if (name.compare("TrinityCommon Hwy410&Bova") == 0)
		return "Trinity Common Hwy. 410 & Bovaird";
	else if (name.compare("Hwy 27 & Rexdale Blvd.") == 0)
		return "Etobicoke Hwy 27 & Rexdale";
	else if (name.compare("Dixon @ Martin Grove") == 0)
		return "Etobicoke Dixon @ Martin Grove";
	else if (name.compare("Broadway & Blind Line") == 0)
		return "Orangeville Broadway & Blind Line";
	else if (name.compare("Broadway & Hwy 10") == 0)
		return "Orangeville Broadway & Hwy 10";
	else if (name.compare("Snelgrove at Mayfield") == 0)
		return "Snelgrove Hurontario & Mayfield Rd.";
	else if (name.compare("Nobleton at Hwy 27") == 0)
		return "Nobleton King Rd @ Hwy. 27";
	else if (name.compare("Woodbridge Rutherford") == 0)
		return "Woodbrige Rutherford & Vaughan Mills";
	else if (name.compare("Woodbridge (7 & Hwy 50)") == 0)
		return "Woodbridge (Hwy 50 & 7)";
	else if (name.compare("Humber College Blvd&Hwy27") == 0)
		return "Toronto Hwy. 27 @ Humber College Blvd";
	else if (name.compare("Hurontario and 407") == 0)
		return "Mississauga Hurontario & 407";
	else if (name.compare("Centennial Progress Camp.") == 0)
		return "Centennial College Progress Campus";
	else if (name.compare("U of T @ Scarborough") == 0)
		return "University Of Toronto @ Scarborough";
	else if (name.compare("Hwy 407 at Brock Road") == 0)
		return "Brougham Hwy 407 @ Brock Road";
	else if (name.compare("Brooklin") == 0)
		return "Brooklin Winchester @ Anderson";
	else if (name.compare("Aurora Rd. & Hwy. 404") == 0)
		return "Aurora Carpool Lot Aurora Rd. & Hwy 404";
	else if (name.compare("Newmarket 9&400 MTO") == 0)
		return "Newmarket Hwy. 9 & Hwy. 400";
	else if (name.compare("Major Mack & 400") == 0)
		return "Maple Major Mackenzie & Hwy. 400";
	else if (name.compare("Port Bolster Lake R./Hw48") == 0)
		return "Port Bolster Lake Ridge Rd. @ Hwy. 48";
	else if (name.compare("Whitby Brock @ Dundas") == 0)
		return "Whitby Dundas @ Brock";
	else if (name.compare("Port Union & Kingston") == 0)
		return "North Rouge Kingston Rd. & Port Union";
	else if (name.compare("Clarington N. P&R/Carpool") == 0)
		return "Clarington North Carpool Lot";
	else if (name.compare("Peterborough South P&R/Ca") == 0)
		return "Peterborough South Carpool Lot";
	else if (name.compare("Cavan P&R/Carpool") == 0)
		return "Cavan Carpool Lot";
	else
		return name;
}