Example #1
1
void K3b::FillStatusDisplay::slotCustomSize()
{
    // allow the units to be translated
    QString gbS = i18n("GB");
    QString mbS = i18n("MB");
    QString minS = i18n("min");

    QLocale const locale = QLocale::system();

    // we certainly do not have BD- or HD-DVD-only projects
    QString defaultCustom;
    if( d->doc->supportedMediaTypes() & K3b::Device::MEDIA_CD_ALL ) {
        defaultCustom = d->showTime ? QString("74") + minS : QString("650") + mbS;
    }
    else {
        defaultCustom = locale.toString(4.4,'g',1) + gbS;
    }

    QRegExp rx( QString("(\\d+\\") + locale.decimalPoint() + "?\\d*)(" + gbS + '|' + mbS + '|' + minS + ")?" );
    QRegExpValidator validator( rx, this );
    bool ok;
    QString size = QInputDialog::getText( this,
                                          i18n("Custom Size"),
                                          i18n("<p>Please specify the size of the medium. Use suffixes <b>GB</b>,<b>MB</b>, "
                                               "and <b>min</b> for <em>gigabytes</em>, <em>megabytes</em>, and <em>minutes</em>"
                                               " respectively."),
                                          QLineEdit::Normal,
                                          defaultCustom,
                                          &ok );

    int validatorPos;
    if( ok && validator.validate( size, validatorPos ) ) {
        // determine size
        if( rx.exactMatch( size ) ) {
            QString valStr = rx.cap(1);
            if( valStr.endsWith( locale.decimalPoint() ) )
                valStr += '0';
            double val = locale.toDouble( valStr, &ok );
            if( ok ) {
                QString s = rx.cap(2);
                if( s == gbS )
                    val *= 1024*512;
                else if( s == mbS || (s.isEmpty() && !d->showTime) )
                    val *= 512;
                else
                    val *= 60*75;
                d->setCdSize( static_cast<int>( val ) );
            }
        }
    }
}
Example #2
0
dvec3 RawDataReaderDialogQt::getSpacing() const {
    QLocale locale = spaceX_->locale();
    glm::dvec3 space(0.01f);
    
    space.x = locale.toDouble(spaceX_->text().remove(QChar(' ')));
    space.y = locale.toDouble(spaceY_->text().remove(QChar(' ')));
    space.z = locale.toDouble(spaceZ_->text().remove(QChar(' ')));

    return space;
}
QStringList NonLinearFit::guessParameters(const QString& s, bool *error, string *errMsg)
{
	QString text = s;
	text.remove(QRegExp("\\s")).remove(".");

	QStringList parList;
	try {
		MyParser parser;
		ParserTokenReader reader(&parser);

		QLocale locale = QLocale();

		const char *formula = text.toAscii().data();
		int length = text.toAscii().length();
		reader.SetFormula (formula);
		reader.IgnoreUndefVar(true);
		int pos = 0;
		while(pos < length){
			ParserToken<value_type, string_type> token = reader.ReadNextToken();
			QString str = QString(token.GetAsString().c_str());

			bool isNumber;
			locale.toDouble(str, &isNumber);

			if (token.GetCode () == cmVAR && str.contains(QRegExp("\\D"))
				&& str != "x" && !parList.contains(str) && !isNumber){
				if (str.endsWith("e", Qt::CaseInsensitive) &&
					str.count("e", Qt::CaseInsensitive) == 1){

					QString aux = str;
					aux.remove("e", Qt::CaseInsensitive);

					bool auxIsNumber;
					locale.toDouble(aux, &auxIsNumber);
					if (!auxIsNumber)
						parList << str;
				} else
					parList << str;
			}

			pos = reader.GetPos();
		}
		parList.sort();
	} catch(mu::ParserError &e) {
		if (error){
			*error = true;
			*errMsg = e.GetMsg();
		}
		return parList;
	}
	if (error)
		*error = false;
	return parList;
}
Example #4
0
void VectorCurve::loadData() {
  if (!plot())
    return;

  int xcol = d_table->colIndex(d_x_column);
  int ycol = d_table->colIndex(title().text());
  int endXCol = d_table->colIndex(d_end_x_a);
  int endYCol = d_table->colIndex(d_end_y_m);

  int rows = abs(d_end_row - d_start_row) + 1;
  QVector<double> X(rows), Y(rows), X2(rows), Y2(rows);
  int size = 0;
  QLocale locale = plot()->locale();
  for (int i = d_start_row; i <= d_end_row; i++) {
    QString xval = d_table->text(i, xcol);
    QString yval = d_table->text(i, ycol);
    QString xend = d_table->text(i, endXCol);
    QString yend = d_table->text(i, endYCol);
    if (!xval.isEmpty() && !yval.isEmpty() && !xend.isEmpty() &&
        !yend.isEmpty()) {
      bool valid_data = true;
      X[size] = locale.toDouble(xval, &valid_data);
      if (!valid_data)
        continue;
      Y[size] = locale.toDouble(yval, &valid_data);
      if (!valid_data)
        continue;
      X2[size] = locale.toDouble(xend, &valid_data);
      if (!valid_data)
        continue;
      Y2[size] = locale.toDouble(yend, &valid_data);
      if (valid_data)
        size++;
    }
  }

  if (!size)
    return;

  X.resize(size);
  Y.resize(size);
  X2.resize(size);
  Y2.resize(size);
  setData(X.data(), Y.data(), size);
  foreach (DataCurve *c, d_error_bars)
    c->setData(X.data(), Y.data(), size);
  setVectorEnd(X2, Y2);
}
Example #5
0
QV4::ReturnedValue QQmlNumberExtension::method_fromLocaleString(QV4::CallContext *ctx)
{
    if (ctx->argc() < 1 || ctx->argc() > 2)
        V4THROW_ERROR("Locale: Number.fromLocaleString(): Invalid arguments");

    int numberIdx = 0;
    QLocale locale;

    QV4::Scope scope(ctx);

    if (ctx->argc() == 2) {
        if (!isLocaleObject(ctx->args()[0]))
            V4THROW_ERROR("Locale: Number.fromLocaleString(): Invalid arguments");

        GET_LOCALE_DATA_RESOURCE(ctx->args()[0]);
        locale = r->d()->locale;

        numberIdx = 1;
    }

    QString ns = ctx->args()[numberIdx].toQString();
    if (!ns.length())
        return QV4::Encode(Q_QNAN);

    bool ok = false;
    double val = locale.toDouble(ns, &ok);

    if (!ok)
        V4THROW_ERROR("Locale: Number.fromLocaleString(): Invalid format")

    return QV4::Encode(val);
}
MapValidator::QValidator::State MapValidator::validate(QString &s, int &i) const
{
    qDebug()<<"validating table input";
    if (s.isEmpty() || s == "-") {
        return QValidator::Intermediate;
    }

    QLocale locale;

    QChar decimalPoint = locale.decimalPoint();
    int charsAfterPoint = s.length() - s.indexOf(decimalPoint) -1;

    if (charsAfterPoint > decimals() && s.indexOf(decimalPoint) != -1) {
        return QValidator::Invalid;
    }

    bool ok;
    double d = locale.toDouble(s, &ok);

    if (ok && d >= bottom() && d <= top()) {
        return QValidator::Acceptable;
    } else {
        return QValidator::Invalid;
    }
}
Example #7
0
void KeyframeEdit::slotAdjustKeyframeInfo(bool seek)
{
    QTableWidgetItem *item = keyframe_list->currentItem();
    if (!item)
        return;
    int min = m_min;
    int max = m_max;
    QTableWidgetItem *above = keyframe_list->item(item->row() - 1, item->column());
    QTableWidgetItem *below = keyframe_list->item(item->row() + 1, item->column());
    if (above)
        min = getPos(above->row()) + 1;
    if (below)
        max = getPos(below->row()) - 1;

    m_position->blockSignals(true);
    m_position->setRange(min, max, true);
    m_position->setPosition(getPos(item->row()));
    m_position->blockSignals(false);
    QLocale locale;

    for (int col = 0; col < keyframe_list->columnCount(); ++col) {
        DoubleParameterWidget *doubleparam = static_cast <DoubleParameterWidget*>(m_slidersLayout->itemAtPosition(col, 0)->widget());
        if (!doubleparam)
            continue;
        doubleparam->blockSignals(true);
        if (keyframe_list->item(item->row(), col)) {
            doubleparam->setValue(locale.toDouble(keyframe_list->item(item->row(), col)->text()));
        } else {
            //qDebug() << "Null pointer exception caught: http://www.kdenlive.org/mantis/view.php?id=1771";
        }
        doubleparam->blockSignals(false);
    }
    if (KdenliveSettings::keyframeseek() && seek)
        emit seekToPos(m_position->getPosition() - m_min);
}
void CubicBezierSpline::fromString(const QString& spline)
{
    m_points.clear();
    QLocale locale;
    const QStringList bpoints = spline.split(QLatin1Char('|'));
    foreach(const QString &bpoint, bpoints) {
        const QStringList points = bpoint.split(QLatin1Char('#'));
        QVector <QPointF> values;
        foreach(const QString &point, points) {
            QStringList xy = point.split(QLatin1Char(';'));
            if (xy.count() == 2)
                values.append(QPointF(locale.toDouble(xy.at(0)), locale.toDouble(xy.at(1))));
        }
        if (values.count() == 3) {
            m_points.append(BPoint(values.at(0), values.at(1), values.at(2)));
        }
    }
Example #9
0
double LonLatParser::parseDouble(const QString& input)
{
    // Decide by decimalpoint if system locale or C locale should be tried.
    // Otherwise if first trying with a system locale when the string is in C locale,
    // the "." might be misinterpreted as thousands group separator and thus a wrong
    // value yielded
    QLocale locale = QLocale::system();
    return input.contains(locale.decimalPoint()) ? locale.toDouble(input) : input.toDouble();
}
Example #10
0
void BitcoinAmountField::setText(const QString &text)
{
    if (text.isEmpty())
        amount->clear();
    else {
        QLocale locale;
        amount->setValue(locale.toDouble(text));
    }
}
void PreviewTable::updateDecimalSeparators(const QLocale& oldSeparators)
{
	QLocale locale = ((QWidget *)parent())->locale();
	for (int i=0; i<numCols(); i++){
        for (int j=0; j<numRows(); j++){
            if (!text(j, i).isEmpty()){
				double val = oldSeparators.toDouble(text(j, i));
                setText(j, i, locale.toString(val, 'g', d_numeric_precision));
			}
		}
	}
}
Example #12
0
/*!
 * \brief GUI::ChangeDeleteUserDialog::slotSetValue
 * Ersetzt Komma durch Punkt für eine einheithliche Eingabe.
 * Überprüft ob der eingetragene Wert ein double ist.
 * \param value
 */
void GUI::ChangeDeleteUserDialog::slotSetValue(QString value)
{
    if(value.contains(",",Qt::CaseSensitive))
        value.replace(",",".");

    QLocale locale = QLocale(QLocale::English, QLocale::UnitedStates);

    if(!locale.toDouble(value) && value != "0"  && value != "0." && value != "-0" && value != "-0." && value != "-" && value !="")
    {
        QMessageBox::information(this, "Wert", tr("Betrag ungueltig").toLatin1());
    }
    ui->balanceLineEdit->setText(value);
}
Example #13
0
void AbstractClipItem::insertKeyframe(QDomElement effect, int pos, double val, bool defaultValue)
{
    if (effect.attribute(QStringLiteral("disable")) == QLatin1String("1")) return;
    QLocale locale;
    locale.setNumberOptions(QLocale::OmitGroupSeparator);
    effect.setAttribute(QStringLiteral("active_keyframe"), pos);
    QDomNodeList params = effect.elementsByTagName(QStringLiteral("parameter"));
    for (int i = 0; i < params.count(); ++i) {
        QDomElement e = params.item(i).toElement();
        if (e.isNull()) continue;
        QString paramName = e.attribute(QStringLiteral("name"));
        if (e.attribute(QStringLiteral("type")) == QLatin1String("animated")) {
            if (!m_keyframeView.activeParam(paramName)) {
                continue;
            }
	    if (defaultValue) {
		m_keyframeView.addDefaultKeyframe(pos, m_keyframeView.type(pos));
	    } else {
		m_keyframeView.addKeyframe(pos, val, m_keyframeView.type(pos));
	    }
            e.setAttribute(QStringLiteral("value"), m_keyframeView.serialize());
        }
        else if (e.attribute(QStringLiteral("type")) == QLatin1String("keyframe")
            || e.attribute(QStringLiteral("type")) == QLatin1String("simplekeyframe")) {
            QString kfr = e.attribute(QStringLiteral("keyframes"));
            const QStringList keyframes = kfr.split(';', QString::SkipEmptyParts);
            QStringList newkfr;
            bool added = false;
            foreach(const QString &str, keyframes) {
                int kpos = str.section('=', 0, 0).toInt();
                double newval = locale.toDouble(str.section('=', 1, 1));
                if (kpos < pos) {
                    newkfr.append(str);
                } else if (!added) {
                    if (i == m_visibleParam)
                        newkfr.append(QString::number(pos) + '=' + QString::number((int)val));
                    else
                        newkfr.append(QString::number(pos) + '=' + locale.toString(newval));
                    if (kpos > pos) newkfr.append(str);
                    added = true;
                } else newkfr.append(str);
            }
            if (!added) {
                if (i == m_visibleParam)
                    newkfr.append(QString::number(pos) + '=' + QString::number((int)val));
                else
                    newkfr.append(QString::number(pos) + '=' + e.attribute(QStringLiteral("default")));
            }
            e.setAttribute(QStringLiteral("keyframes"), newkfr.join(QStringLiteral(";")));
        }
Example #14
0
QMap<QString, QString> TransitionHandler::getTransitionParamsFromXml(const QDomElement &xml)
{
    QDomNodeList attribs = xml.elementsByTagName(QStringLiteral("parameter"));
    QMap<QString, QString> map;
    QLocale locale;
    for (int i = 0; i < attribs.count(); ++i) {
        QDomElement e = attribs.item(i).toElement();
        QString name = e.attribute(QStringLiteral("name"));
        map[name] = e.attribute(QStringLiteral("default"));
        if (e.hasAttribute(QStringLiteral("value"))) {
            map[name] = e.attribute(QStringLiteral("value"));
        }
        double factor = e.attribute(QStringLiteral("factor"), QStringLiteral("1")).toDouble();
        double offset = e.attribute(QStringLiteral("offset"), QStringLiteral("0")).toDouble();
        if (factor!= 1 || offset != 0) {
            if (e.attribute(QStringLiteral("type")) == QLatin1String("simplekeyframe")) {
                QStringList values = e.attribute(QStringLiteral("value")).split(';', QString::SkipEmptyParts);
                for (int j = 0; j < values.count(); ++j) {
                    QString pos = values.at(j).section(QLatin1Char('='), 0, 0);
                    double val = (values.at(j).section(QLatin1Char('='), 1, 1).toDouble() - offset) / factor;
                    values[j] = pos + '=' + locale.toString(val);
                }
                map[name] = values.join(QLatin1Char(';'));
            } else if (e.attribute(QStringLiteral("type")) != QLatin1String("addedgeometry")) {
                map[name] = locale.toString((locale.toDouble(map.value(name)) - offset) / factor);
                //map[name]=map[name].replace(".",","); //FIXME how to solve locale conversion of . ,
            }
        }
        if (e.attribute(QStringLiteral("namedesc")).contains(';')) {
            //TODO: Deprecated, does not seem used anywhere...
            QString format = e.attribute(QStringLiteral("format"));
            QStringList separators = format.split(QStringLiteral("%d"), QString::SkipEmptyParts);
            QStringList values = e.attribute(QStringLiteral("value")).split(QRegExp("[,:;x]"));
            QString neu;
            QTextStream txtNeu(&neu);
            if (values.size() > 0)
                txtNeu << (int)values[0].toDouble();
            int i = 0;
            for (i = 0; i < separators.size() && i + 1 < values.size(); ++i) {
                txtNeu << separators[i];
                txtNeu << (int)(values[i+1].toDouble());
            }
            if (i < separators.size())
                txtNeu << separators[i];
            map[e.attribute(QStringLiteral("name"))] = neu;
        }

    }
    return map;
}
Example #15
0
void QwtPieCurve::loadData() {
  // Limit number of slices to 1000 - seems plenty and avoids potential crash
  // (#4470)
  if (abs(d_end_row - d_start_row) > 1000) {
    QString mess = QString("Pie charts are limited to 1000 segments!\n") +
                   QString("You asked for ") +
                   QString::number(abs(d_end_row - d_start_row)) +
                   QString(" - plotting only the first 1000.");
    QMessageBox::warning(qApp->topLevelWidgets()[0], "Pie chart", mess);
    d_end_row = d_start_row + 1000;
  }

  Plot *d_plot = static_cast<Plot *>(plot());
  QLocale locale = d_plot->locale();
  QVarLengthArray<double> X(abs(d_end_row - d_start_row) + 1);
  d_table_rows.resize(abs(d_end_row - d_start_row) + 1);

  int size = 0;
  int ycol = d_table->colIndex(title().text());
  for (int i = d_start_row; i <= d_end_row; i++) {
    QString xval = d_table->text(i, ycol);
    bool valid_data = true;
    if (!xval.isEmpty()) {
      X[size] = locale.toDouble(xval, &valid_data);
      if (valid_data) {
        d_table_rows[size] = i + 1;
        size++;
      }
    }
  }
  X.resize(size);
  d_table_rows.resize(size);
  setData(X.data(), X.data(), size);

  int labels = d_texts_list.size();
  // If there are no labels (initLabels() wasn't called yet) or if we have
  // enough labels: do nothing!
  if (d_texts_list.isEmpty() || labels == size)
    return;

  // Else add new pie labels.
  for (int i = labels; i < size; i++) {
    PieLabel *l = new PieLabel(d_plot, this);
    d_texts_list << l;
    l->hide();
  }
}
Example #16
0
QValidator::State LengthValidator::validate(QString & qtext, int &) const
{
	QLocale loc;
	bool ok;
	double d = loc.toDouble(qtext.trimmed(), &ok);
	// QLocale::toDouble accepts something like "1."
	// We don't.
	bool dp = qtext.endsWith(loc.decimalPoint());
	if (!ok) {
		// Fall back to C
		QLocale c(QLocale::C);
		d = c.toDouble(qtext.trimmed(), &ok);
		dp = qtext.endsWith(c.decimalPoint());
	}

	if (ok && unsigned_ && d < 0)
		return QValidator::Invalid;

	if (qtext.isEmpty() || (ok && !dp))
		return QValidator::Acceptable;

	string const text = fromqstr(qtext);

	if (glue_length_) {
		GlueLength gl;
		if (unsigned_ && gl.len().value() < 0)
			return QValidator::Invalid;
		return (isValidGlueLength(text, &gl)) ?
			QValidator::Acceptable : QValidator::Intermediate;
	}

	Length l;
	bool const valid_length = isValidLength(text, &l);
	if (!valid_length)
		return QValidator::Intermediate;

	if (no_bottom_)
		return QValidator::Acceptable;

	if (unsigned_ && l.value() < 0)
		return QValidator::Invalid;

	return b_.inPixels(100) <= l.inPixels(100) ?
		QValidator::Acceptable : QValidator::Intermediate;
}
Example #17
0
void
MainWindow::PreviewImage()
{
	if (list->count() == 0)
		return;

	int maxw = 0, maxh = 0;
	for (int x = 0; x < list->count(); x++)
	{
		QLocale loc;
		ImageView * view = list->item(x)->data(Qt::UserRole).value<ImageView *>();
		int top = view->offsetY->text().toInt();
		int left = view->offsetX->text().toInt();
		int croptop = view->cropTopY->text().toInt();
		int cropleft = view->cropTopX->text().toInt();
		int cropbottom = view->cropBottomY->text().toInt();
		int cropright = view->cropBottomX->text().toInt();
		double scale = loc.toDouble(view->scale->text());
		int width = left;
		int height = top;
		int subwidth = view->image->width() - cropleft - cropright;
		int subheight = view->image->height() - croptop - cropbottom;
		if (scale != 0.0)
		{
			subwidth *= scale;
			subheight *= scale;
		}
		width += subwidth;
		height += subheight;
		if (width > maxw)
			maxw = width;
		if (height > maxh)
			maxh = height;
	}
	if (preview == NULL)
		preview = new Preview();

	if (preview)
	{
		preview->SetImageSize(maxw, maxh);
		preview->ShowPreview(this);
		preview->show();
	}
}
Example #18
0
QMap<double,QString> BinController::takeGuidesData()
{
    QLocale locale;
    // Load guides
    Mlt::Properties guidesProperties;
    Mlt::Properties playlistProps(m_binPlaylist->get_properties());
    guidesProperties.pass_values(playlistProps, "kdenlive:guide.");

    qDebug()<<"***********\nFOUND GUIDES: "<<guidesProperties.count()<<"\n**********";
    QMap <double,QString> guidesData;
    for (int i = 0; i < guidesProperties.count(); i++) {
        double time = locale.toDouble(guidesProperties.get_name(i));
        guidesData.insert(time, guidesProperties.get(i));
        // Clear bin data
        QString propertyName = "kdenlive:guide." + QString(guidesProperties.get_name(i));
        m_binPlaylist->set(propertyName.toUtf8().constData(), (char *) NULL);
    }
    return guidesData;
}
Example #19
0
void Matrix::cellEdited(int row,int col)
{
	QString cell_text = text(row,col);
	if(cell_text.isEmpty()) return;

	QString cell_formula = cell_text;

	bool ok = true;
    QLocale locale;
  	double res = locale.toDouble(cell_text, &ok);
	if (ok)
		setText(row, col, locale.toString(res, txt_format.toAscii(), num_precision));
	else
	{
		Script *script = scriptEnv->newScript(cell_formula, this, QString("<%1_%2_%3>").arg(name()).arg(row).arg(col));
		connect(script, SIGNAL(error(const QString&,const QString&,int)), scriptEnv, SIGNAL(error(const QString&,const QString&,int)));

		script->setInt(row+1, "row");
		script->setInt(row+1, "i");
		script->setInt(col+1, "col");
		script->setInt(col+1, "j");

		QVariant ret = script->eval();
		if(ret.type()==QVariant::Int || ret.type()==QVariant::UInt || ret.type()==QVariant::LongLong
				|| ret.type()==QVariant::ULongLong)
			setText(row, col, ret.toString());
		else if(ret.canConvert(QVariant::Double))
			setText(row, col, locale.toString(ret.toDouble(), txt_format.toAscii(), num_precision));
		else
			setText(row, col, "");
	}

    if(row+1 >= numRows())
        d_table->setRowCount(row + 2);

	d_table->setCurrentCell(row+1, col);

	if(allow_modification_signals)
		emit modifiedWindow(this);
}
void PreviewTable::importASCII(const QString &fname, const QString &sep, int ignoredLines, bool renameCols,
    bool stripSpaces, bool simplifySpaces, bool importComments, const QString& commentString,
	int importMode, const QLocale& importLocale, int endLine, int maxRows)
{
	int rows;
	QString name = MdiSubWindow::parseAsciiFile(fname, commentString, endLine, ignoredLines, maxRows, rows);
	if (name.isEmpty())
		return;

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

	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

	QLocale locale = this->locale();
	bool updateDecimalSeparators = (importLocale != locale) ? true : false;

	QTextStream t(&f);
	QString s = t.readLine();//read first line
	if (simplifySpaces)
		s = s.simplifyWhiteSpace();
	else if (stripSpaces)
		s = s.stripWhiteSpace();

	QStringList line = s.split(sep);
	int cols = line.size();

	bool allNumbers = true;
	for (int i=0; i<cols; i++)
	{//verify if the strings in the line used to rename the columns are not all numbers
		locale.toDouble(line[i], &allNumbers);
		if (!allNumbers)
			break;
	}

	if (renameCols && !allNumbers)
		rows--;
	if (importComments)
		rows--;

	int startRow = 0, startCol = 0;
	int c = numCols();
	int r = numRows();
	switch(importMode){
		case Table::Overwrite:
			if (numRows() != rows)
				setNumRows(rows);

			if (c != cols){
				if (c < cols)
					addColumns(cols - c);
				else
					setNumCols(cols);
			}
		break;
		case Table::NewColumns:
			startCol = d_start_col;
			if (abs(c - d_start_col) < cols)
				addColumns(cols);
			if (r < rows)
				setNumRows(rows);
		break;
		case Table::NewRows:
			startRow = r;
			if (c < cols)
				addColumns(cols - c);
			setNumRows(r + rows);
		break;
	}

	if (renameCols && !allNumbers){//use first line to set the table header
		for (int i = 0; i<cols; i++){
			int aux = i + startCol;
			col_label[aux] = QString::null;
			if (!importComments)
				comments[aux] = line[i];
			s = line[i].replace("-","_").remove(QRegExp("\\W")).replace("_","-");
			int n = col_label.count(s);
			if(n){//avoid identical col names
				while (col_label.contains(s + QString::number(n)))
					n++;
				s += QString::number(n);
			}
			col_label[aux] = s;
		}
	}

	if (importComments){//import comments
		if (renameCols && !allNumbers)
			s = t.readLine();//read 2nd line

		if (simplifySpaces)
			s = s.simplifyWhiteSpace();
		else if (stripSpaces)
			s = s.stripWhiteSpace();
		line = s.split(sep, QString::SkipEmptyParts);
		for (int i=0; i<line.size(); i++){
			int aux = startCol + i;
			if (aux < comments.size())
				comments[aux] = line[i];
		}
		qApp->processEvents(QEventLoop::ExcludeUserInput);
	}

	if ((!renameCols || allNumbers)&& !importComments && rows > 0){
		//put values in the first line of the table
		for (int i = 0; i<cols; i++){
			bool ok;
			double val = importLocale.toDouble(line[i], &ok);
			if (ok && updateDecimalSeparators)
				setText(startRow, startCol + i, locale.toString(val, 'g', d_numeric_precision));
			else
				setText(startRow, startCol + i, line[i]);
		}
		startRow++;
	}

	blockSignals(true);
	setHeader();

	QApplication::restoreOverrideCursor();

	int row = startRow;
	rows = numRows();
	while (!t.atEnd() && row < rows){
		s = t.readLine();
		if (simplifySpaces)
			s = s.simplifyWhiteSpace();
		else if (stripSpaces)
			s = s.stripWhiteSpace();
		line = s.split(sep);
		int lc = line.size();
		if (lc > cols) {
			addColumns(lc - cols);
			cols = lc;
		}
		for (int j = 0; j < cols && j < lc; j++){
			bool ok;
			double val = importLocale.toDouble(line[j], &ok);
			if (ok && updateDecimalSeparators)
				setText(row, startCol + j, locale.toString(val, 'g', d_numeric_precision));
			else
				setText(row, startCol + j, line[j]);
		}

		row++;
		qApp->processEvents(QEventLoop::ExcludeUserInput);
	}
	blockSignals(false);
	f.remove();
}
Example #21
0
bool MatrixModel::importASCII(const QString &fname, const QString &sep,
                              int ignoredLines, bool stripSpaces,
                              bool simplifySpaces, const QString &commentString,
                              int importAs, const QLocale &locale,
                              int endLineChar, int maxRows) {
  int rows = 0;
  QString name = MdiSubWindow::parseAsciiFile(fname, commentString, endLineChar,
                                              ignoredLines, maxRows, rows);
  if (name.isEmpty())
    return false;
  QFile f(name);
  if (!f.open(QIODevice::ReadOnly))
    return false;

  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

  QTextStream t(&f);
  QLocale l = d_locale;
  if (d_matrix)
    l = d_matrix->locale();
  bool updateDecimalSeparators = (l != locale);

  QString s = t.readLine();
  if (simplifySpaces)
    s = s.simplified();
  else if (stripSpaces)
    s = s.trimmed();

  QStringList line = s.split(sep);
  int cols = line.size();

  int startRow = 1, startCol = 0;
  switch (importAs) {
  case Matrix::Overwrite:
    if (d_cols != cols)
      setColumnCount(cols);
    if (d_rows != rows)
      setRowCount(rows);
    break;
  case Matrix::NewColumns:
    startCol = d_cols;
    setColumnCount(d_cols + cols);
    if (d_rows < rows)
      setRowCount(rows);
    break;
  case Matrix::NewRows:
    startRow = d_rows;
    if (d_cols < cols)
      setColumnCount(cols);
    setRowCount(d_rows + rows);
    break;
  }

  for (int j = startCol; j < d_cols; j++) {
    int aux = j - startCol;
    if (cols > aux) {
      if (updateDecimalSeparators)
        setCell(0, j, locale.toDouble(line[aux]));
      else
        setText(0, j, line[aux]);
    }
  }

  qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
  for (int i = startRow; i < d_rows; i++) {
    s = t.readLine();
    if (simplifySpaces)
      s = s.simplified();
    else if (stripSpaces)
      s = s.trimmed();
    line = s.split(sep);
    int lc = line.size();
    if (lc > cols)
      setColumnCount(d_cols + lc - cols);

    for (int j = startCol; j < d_cols; j++) {
      int aux = j - startCol;
      if (lc > aux) {
        if (updateDecimalSeparators)
          setCell(i, j, locale.toDouble(line[aux]));
        else
          setText(i, j, line[aux]);
      }
    }
  }
  f.remove(); // remove temp file
  if (d_matrix)
    d_matrix->resetView();
  QApplication::restoreOverrideCursor();
  return true;
}
Example #22
0
void CtrlList::read(Xml& xml)
{
    QLocale loc = QLocale::c();
    bool ok;
    for (;;)
    {
        Xml::Token token = xml.parse();
        const QString& tag = xml.s1();
        switch (token)
        {
            case Xml::Error:
            case Xml::End:
                return;
            case Xml::Attribut:
                if (tag == "id")
                {
                    _id = loc.toInt(xml.s2(), &ok);
                    if (!ok)
                    {
                        printf("CtrlList::read failed reading _id string: %s\n", xml.s2().toLatin1().constData());
                        initColor(0); //Set the default color if we have an error
                    }
                    else {
                        initColor(_id);
                    }
                }
                else if (tag == "cur")
                {
                    _curVal = loc.toDouble(xml.s2(), &ok);
                    if (!ok)
                        printf("CtrlList::read failed reading _curVal string: %s\n", xml.s2().toLatin1().constData());
                }
                else if(tag == "visible")
                {
                    _visible = (bool)xml.s2().toInt();
                }
                else if(tag == "color")
                {
                    ;//xml.skip(tag);
                }
                else
                    printf("unknown tag %s\n", tag.toLatin1().constData());
                break;
            case Xml::Text:
            {
                int len = tag.length();
                int frame;
                double val;

                int i = 0;
                for (;;)
                {
                    while (i < len && (tag[i] == ',' || tag[i] == ' ' || tag[i] == '\n'))
                        ++i;
                    if (i == len)
                        break;

                    QString fs;
                    while (i < len && tag[i] != ' ')
                    {
                        fs.append(tag[i]);
                        ++i;
                    }
                    if (i == len)
                        break;

                    // Works OK, but only because if current locale fails it falls back on 'C' locale.
                    // So, let's skip the fallback and force use of 'C' locale.
                    frame = loc.toInt(fs, &ok);
                    if (!ok)
                    {
                        printf("CtrlList::read failed reading frame string: %s\n", fs.toLatin1().constData());
                        break;
                    }

                    while (i < len && (tag[i] == ' ' || tag[i] == '\n'))
                        ++i;
                    if (i == len)
                        break;

                    QString vs;
                    while (i < len && tag[i] != ' ' && tag[i] != ',')
                    {
                        vs.append(tag[i]);
                        ++i;
                    }

                    // Works OK, but only because if current locale fails it falls back on 'C' locale.
                    // So, let's skip the fallback and force use of 'C' locale.
                    //val = vs.toDouble(&ok);
                    val = loc.toDouble(vs, &ok);
                    if (!ok)
                    {
                        printf("CtrlList::read failed reading value string: %s\n", vs.toLatin1().constData());
                        break;
                    }

                    //printf("CtrlList::read i:%d len:%d fs:%s frame %d: vs:%s val %f \n", i, len, fs.toLatin1().constData(), frame, vs.toLatin1().constData(), val);

                    add(frame, val);

                    if (i == len)
                        break;
                }
            }
                break;
            case Xml::TagEnd:
                if (xml.s1() == "controller")
                {
                    return;
                }
            default:
                break;
        }
    }
}
Example #23
0
void Matrix::pasteSelection()
{
     if (d_view_type == ImageView)
        return;

	QString text = QApplication::clipboard()->text();
	if (text.isEmpty())
		return;

	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

	QStringList linesList = text.split(applicationWindow()->endOfLine(), QString::SkipEmptyParts);
	int rows = linesList.size();
	if (!rows)
		return;

	int cols = linesList[0].split("\t").count();
	for (int i = 1; i < rows; i++){
		int aux = linesList[i].split("\t").count();
		if (aux > cols)
            cols = aux;
	}

	int topRow = 0, leftCol = 0;
	QItemSelectionModel *selModel = d_table_view->selectionModel();
	if (selModel->hasSelection()){
		QItemSelectionRange sel = selModel->selection()[0];
		topRow = sel.top();
		leftCol = sel.left();
	}

	int oldRows = numRows();
	int bottomRow = topRow + rows - 1;
	if (bottomRow > oldRows - 1)
		bottomRow = oldRows - 1;

	int oldCols = numCols();
	int rightCol = leftCol + cols - 1;
	if (rightCol > oldCols - 1)
		rightCol = oldCols - 1;

	double *clipboardBuffer = (double *)malloc(rows*cols*sizeof(double));
	if (!clipboardBuffer){
		QMessageBox::critical(this, tr("QtiPlot") + " - " + tr("Memory Allocation Error"),
		tr("Not enough memory, operation aborted!"));
		QApplication::restoreOverrideCursor();
		return;
	}

	QLocale locale = this->locale(); //Better use QLocale::system() ??
	int cell = 0;
	for(int i = 0; i < rows; i++){
		QStringList cells = linesList[i].split("\t");
		int size = cells.count();
		for(int j = 0; j<cols; j++){
			if (j >= size){
                clipboardBuffer[cell++] = GSL_NAN;
				continue;
			}
			bool numeric = true;
			double value = locale.toDouble(cells[j], &numeric);
			if (numeric)
				clipboardBuffer[cell++] = value;
			else
				clipboardBuffer[cell++] = GSL_NAN;
		}
	}

	QApplication::restoreOverrideCursor();

	double *backupBuffer = d_matrix_model->dataCopy(topRow, bottomRow, leftCol, rightCol);
	if (backupBuffer){
		d_undo_stack->push(new MatrixPasteCommand(d_matrix_model, topRow, bottomRow,
					leftCol, rightCol, clipboardBuffer, rows, cols, backupBuffer, oldRows,
					oldCols, tr("Paste")));
		emit modifiedWindow(this);
	} else if (ignoreUndo()){
		d_matrix_model->pasteData(clipboardBuffer, topRow, leftCol, rows, cols);
		emit modifiedWindow(this);
	}
}
Example #24
0
File: ctrl.cpp Project: faesong/oom
void CtrlList::read(Xml& xml)
{
	QLocale loc = QLocale::c();
	bool ok;
	for (;;)
	{
		Xml::Token token = xml.parse();
		const QString& tag = xml.s1();
		switch (token)
		{
			case Xml::Error:
			case Xml::End:
				return;
			case Xml::Attribut:
				if (tag == "id")
				{
					//_id = xml.s2().toInt();
					_id = loc.toInt(xml.s2(), &ok);
					if (!ok)
					{
						printf("CtrlList::read failed reading _id string: %s\n", xml.s2().toLatin1().constData());
						initColor(0); //Set the default color if we have an error
					}
					else {
						initColor(_id);
					}
				}
				else if (tag == "cur")
				{
					//_curVal = xml.s2().toDouble();
					_curVal = loc.toDouble(xml.s2(), &ok);
					if (!ok)
						printf("CtrlList::read failed reading _curVal string: %s\n", xml.s2().toLatin1().constData());
				}
				else if(tag == "visible")
				{
					_visible = (bool)xml.s2().toInt();
				}
				else if(tag == "color")
				{
					;//xml.skip(tag);
				}
				else
					printf("unknown tag %s\n", tag.toLatin1().constData());
				break;
			case Xml::Text:
			{
				// Changed by Tim. Users in some locales reported corrupt reading,
				//  because of the way floating point is represented (2,3456 not 2.3456).
				/*
				QByteArray ba = tag.toLatin1();
				const char* s = ba;.constData();
				int frame;
				double val;

				for (;;) {
					  char* endp;
					  while (*s == ' ' || *s == '\n')
							++s;
					  if (*s == 0)
							break;
					  frame = strtol(s, &endp, 10);
					  s     = endp;
					  while (*s == ' ' || *s == '\n')
							++s;
					  val = strtod(s, &endp);
					  add(frame, val);
					  s = endp;
					  ++s;
					  }
				 */

				// Added by Tim. p3.3.6
				//printf("CtrlList::read tag:%s\n", tag.toLatin1().constData());

				int len = tag.length();
				int frame;
				double val;

				int i = 0;
				for (;;)
				{
					while (i < len && (tag[i] == ',' || tag[i] == ' ' || tag[i] == '\n'))
						++i;
					if (i == len)
						break;

					QString fs;
					while (i < len && tag[i] != ' ')
					{
						fs.append(tag[i]);
						++i;
					}
					if (i == len)
						break;

					// Works OK, but only because if current locale fails it falls back on 'C' locale.
					// So, let's skip the fallback and force use of 'C' locale.
					//frame = fs.toInt(&ok);
					frame = loc.toInt(fs, &ok);
					if (!ok)
					{
						printf("CtrlList::read failed reading frame string: %s\n", fs.toLatin1().constData());
						break;
					}

					while (i < len && (tag[i] == ' ' || tag[i] == '\n'))
						++i;
					if (i == len)
						break;

					QString vs;
					while (i < len && tag[i] != ' ' && tag[i] != ',')
					{
						vs.append(tag[i]);
						++i;
					}

					// Works OK, but only because if current locale fails it falls back on 'C' locale.
					// So, let's skip the fallback and force use of 'C' locale.
					//val = vs.toDouble(&ok);
					val = loc.toDouble(vs, &ok);
					if (!ok)
					{
						printf("CtrlList::read failed reading value string: %s\n", vs.toLatin1().constData());
						break;
					}

					// Added by Tim. p3.3.6
					//printf("CtrlList::read i:%d len:%d fs:%s frame %d: vs:%s val %f \n", i, len, fs.toLatin1().constData(), frame, vs.toLatin1().constData(), val);

					add(frame, val);

					if (i == len)
						break;
				}
			}
				break;
			case Xml::TagEnd:
				if (xml.s1() == "controller")
				{
					// Added by Tim. p3.3.6
					//printf("CtrlList::read _id:%d _curVal:%f\n", _id, _curVal);

					return;
				}
			default:
				break;
		}
	}
}
Example #25
0
void CtrlList::read(Xml& xml)
      {
      QLocale loc = QLocale::c();
      bool ok;
      for (;;) {
            Xml::Token token = xml.parse();
            const QString& tag = xml.s1();
            switch (token) {
                  case Xml::Error:
                  case Xml::End:
                        return;
                  case Xml::Attribut:
                        if (tag == "id")
                        {
                              _id = loc.toInt(xml.s2(), &ok);
                              if(!ok)
                                printf("CtrlList::read failed reading _id string: %s\n", xml.s2().toLatin1().constData());
                        }
                        else if (tag == "cur")
                        {
                              _curVal = loc.toDouble(xml.s2(), &ok);
                              if(!ok)
                                printf("CtrlList::read failed reading _curVal string: %s\n", xml.s2().toLatin1().constData());
                        }        
                        else if (tag == "visible")
                        {
                              _visible = loc.toInt(xml.s2(), &ok);
                              if(!ok)
                                printf("CtrlList::read failed reading _visible string: %s\n", xml.s2().toLatin1().constData());
                        }
                        else if (tag == "color")
                        {
#if QT_VERSION >= 0x040700
                              ok = _displayColor.isValidColor(xml.s2());
                              if (!ok) {
                                printf("CtrlList::read failed reading color string: %s\n", xml.s2().toLatin1().constData());
                                break;
                              }
#endif
                              _displayColor.setNamedColor(xml.s2());
                        }
                        else
                              printf("unknown tag %s\n", tag.toLatin1().constData());
                        break;
                  case Xml::Text:
                        {
                          int len = tag.length();
                          int frame;
                          double val;
  
                          int i = 0;
                          for(;;) 
                          {
                                while(i < len && (tag[i] == ',' || tag[i] == ' ' || tag[i] == '\n'))
                                  ++i;
                                if(i == len)
                                      break;
                                
                                QString fs;
                                while(i < len && tag[i] != ' ')
                                {
                                  fs.append(tag[i]); 
                                  ++i;
                                }
                                if(i == len)
                                      break;
                                
                                frame = loc.toInt(fs, &ok);
                                if(!ok)
                                {
                                  printf("CtrlList::read failed reading frame string: %s\n", fs.toLatin1().constData());
                                  break;
                                }
                                  
                                while(i < len && (tag[i] == ' ' || tag[i] == '\n'))
                                  ++i;
                                if(i == len)
                                      break;
                                
                                QString vs;
                                while(i < len && tag[i] != ' ' && tag[i] != ',')
                                {
                                  vs.append(tag[i]); 
                                  ++i;
                                }
                                
                                val = loc.toDouble(vs, &ok);
                                if(!ok)
                                {
                                  printf("CtrlList::read failed reading value string: %s\n", vs.toLatin1().constData());
                                  break;
                                }
                                  
                                add(frame, val);
                                
                                if(i == len)
                                      break;
                          }
                        }
                        break;
                  case Xml::TagEnd:
                        if (xml.s1() == "controller")
                              return;
                  default:
                        break;
                  }
            }
      }
void QwtErrorPlotCurve::loadData()
{
	if (!d_master_curve)
		return;

    if (!plot())
        return;

	Table *mt = d_master_curve->table();
	if (!mt)
		return;

	int xcol = mt->colIndex(d_master_curve->xColumnName());
	int ycol = mt->colIndex(d_master_curve->title().text());
	int errcol = d_table->colIndex(title().text());
	if (xcol<0 || ycol<0 || errcol<0)
		return;

	int xColType = mt->columnType(xcol);
	int yColType = mt->columnType(ycol);

	d_start_row = d_master_curve->startRow();
	d_end_row = d_master_curve->endRow();
    int r = abs(d_end_row - d_start_row) + 1;
	QVector<double> X(r), Y(r), err(r);
    int data_size = 0;
    QLocale locale = ((Graph *)plot())->multiLayer()->locale();
	for (int i = d_start_row; i <= d_end_row; i++){
		QString xval = mt->text(i, xcol);
		QString yval = mt->text(i, ycol);
		QString errval = d_table->text(i, errcol);
		if (!xval.isEmpty() && !yval.isEmpty() && !errval.isEmpty()){
		    bool ok = true;
			if (xColType == Table::Text)
				X[data_size] = (double)(data_size + 1);
			else
				X[data_size] = locale.toDouble(xval, &ok);

			if (yColType == Table::Text)
				Y[data_size] = (double)(data_size + 1);
			else
				Y[data_size] = locale.toDouble(yval, &ok);

            if (!ok)
                continue;

			err[data_size] = locale.toDouble(errval, &ok);
			if (ok)
                data_size++;
		}
	}

	if (!data_size)
		remove();

    X.resize(data_size);
	Y.resize(data_size);
	err.resize(data_size);

	setData(X.data(), Y.data(), data_size);
	setErrors(err);
}