Example #1
0
FixtureRemap::FixtureRemap(Doc *doc, QWidget *parent)
    : QDialog(parent)
    , m_doc(doc)
{
    Q_ASSERT(doc != NULL);

    setupUi(this);

    connect(m_addButton, SIGNAL(clicked()),
            this, SLOT(slotAddTargetFixture()));
    connect(m_removeButton, SIGNAL(clicked()),
            this, SLOT(slotRemoveTargetFixture()));
    connect(m_cloneButton, SIGNAL(clicked()),
            this, SLOT(slotCloneSourceFixture()));
    connect(m_remapButton, SIGNAL(clicked()),
            this, SLOT(slotAddRemap()));
    connect(m_unmapButton, SIGNAL(clicked()),
            this, SLOT(slotRemoveRemap()));

    m_cloneButton->setEnabled(false);

    remapWidget = new RemapWidget(m_sourceTree, m_targetTree, this);
    remapWidget->show();
    m_remapLayout->addWidget(remapWidget);

    m_targetDoc = new Doc(this);
    /* Load user fixtures first so that they override system fixtures */
    m_targetDoc->fixtureDefCache()->load(QLCFixtureDefCache::userDefinitionDirectory());
    m_targetDoc->fixtureDefCache()->load(QLCFixtureDefCache::systemDefinitionDirectory());

    m_sourceTree->setIconSize(QSize(24, 24));
    m_sourceTree->setAllColumnsShowFocus(true);
    fillFixturesTree(m_doc, m_sourceTree);

    m_targetTree->setIconSize(QSize(24, 24));
    m_targetTree->setAllColumnsShowFocus(true);

    connect(m_sourceTree->verticalScrollBar(), SIGNAL(valueChanged(int)),
            this, SLOT(slotUpdateConnections()));
    connect(m_sourceTree, SIGNAL(clicked(QModelIndex)),
            this, SLOT(slotUpdateConnections()));
    connect(m_sourceTree, SIGNAL(expanded(QModelIndex)),
            this, SLOT(slotUpdateConnections()));
    connect(m_sourceTree, SIGNAL(collapsed(QModelIndex)),
            this, SLOT(slotUpdateConnections()));
    connect(m_sourceTree, SIGNAL(itemSelectionChanged()),
            this, SLOT(slotSourceSelectionChanged()));

    connect(m_targetTree->verticalScrollBar(), SIGNAL(valueChanged(int)),
            this, SLOT(slotUpdateConnections()));
    connect(m_targetTree, SIGNAL(clicked(QModelIndex)),
            this, SLOT(slotUpdateConnections()));
    connect(m_targetTree, SIGNAL(expanded(QModelIndex)),
            this, SLOT(slotUpdateConnections()));
    connect(m_targetTree, SIGNAL(collapsed(QModelIndex)),
            this, SLOT(slotUpdateConnections()));

    // retrieve the original project name for QLC+ main class
    App *mainApp = (App *)m_doc->parent();
    QString prjName = mainApp->fileName();

    if (prjName.lastIndexOf(".") > 0)
        prjName.insert(prjName.lastIndexOf("."), tr(" (remapped)"));
    else
        prjName.append(tr(" (remapped)"));

    m_targetProjectLabel->setText(prjName);
}
// Parts of this function mirror code in QQmlExpressionPrivate::value() and v8value().
// Changes made here may need to be made there and vice versa.
void QQmlBoundSignalExpression::evaluate(void **a)
{
    Q_ASSERT (context() && engine());

    if (m_invalidParameterName)
        return;

    QQmlEnginePrivate *ep = QQmlEnginePrivate::get(engine());

    ep->referenceScarceResources(); // "hold" scarce resources in memory during evaluation.
    {
        v8::HandleScope handle_scope;
        v8::Context::Scope context_scope(ep->v8engine()->context());
        if (!m_expressionFunctionValid) {

            //TODO: look at using the property cache here (as in the compiler)
            //      for further optimization
            QMetaMethod signal = QMetaObjectPrivate::signal(m_target->metaObject(), m_index);
            QQmlRewrite::RewriteSignalHandler rewriter;

            QString expression;
            bool ok = true;

            if (m_expressionFunctionRewritten) {
                expression = QString::fromUtf8(m_expressionUtf8);

                //if we need parameters, and the rewrite doesn't include them,
                //create and insert the parameter string now
                if (m_parameterCountForJS == -1 && signal.parameterCount()) {
                    const QString &parameters = rewriter.createParameterString(signal.parameterNames(),
                                                ep->v8engine()->illegalNames());
                    int index = expression.indexOf(QLatin1Char('('), 1);
                    Q_ASSERT(index > -1);
                    expression.insert(index + 1, parameters);

                    setParameterCountForJS(rewriter.parameterCountForJS());
                }

                m_expressionUtf8.clear();
            } else {
                //expression is still in its original form, so perform a full rewrite
                expression = rewriter(m_expression, QString()/*no name hint available*/, &ok,
                                      signal.parameterNames(),
                                      ep->v8engine()->illegalNames());
                setParameterCountForJS(rewriter.parameterCountForJS());
                m_expression.clear();
            }

            if (rewriter.hasParameterError()) {
                qmlInfo(scopeObject()) << rewriter.parameterError();
                m_invalidParameterName = true;
                ep->dereferenceScarceResources();
                return;
            }

            if (ok) {
                m_v8function = evalFunction(context(), scopeObject(), expression,
                                            m_fileName, m_line, &m_v8qmlscope);
            }

            if (m_v8function.IsEmpty() || m_v8function->IsNull()) {
                ep->dereferenceScarceResources();
                return; // could not evaluate function.  Not valid.
            }

            setUseSharedContext(false);
            m_expressionFunctionValid = true;
        }

        if (!hasParameterInfo()) {
            QQmlJavaScriptExpression::evaluate(context(), m_v8function, 0);
        } else {
            QV8Engine *engine = ep->v8engine();
            QVarLengthArray<int, 9> dummy;
            //TODO: lookup via signal index rather than method index as an optimization
            int methodIndex = QMetaObjectPrivate::signal(m_target->metaObject(), m_index).methodIndex();
            int *argsTypes = QQmlPropertyCache::methodParameterTypes(m_target, methodIndex, dummy, 0);
            int argCount = argsTypes ? m_parameterCountForJS : 0;

            QVarLengthArray<v8::Handle<v8::Value>, 9> args(argCount);

            for (int ii = 0; ii < argCount; ++ii) {
                int type = argsTypes[ii + 1];
                //### ideally we would use metaTypeToJS, however it currently gives different results
                //    for several cases (such as QVariant type and QObject-derived types)
                //args[ii] = engine->metaTypeToJS(type, a[ii + 1]);
                if (type == QMetaType::QVariant) {
                    args[ii] = engine->fromVariant(*((QVariant *)a[ii + 1]));
                } else if (type == QMetaType::Int) {
                    //### optimization. Can go away if we switch to metaTypeToJS, or be expanded otherwise
                    args[ii] = v8::Integer::New(*reinterpret_cast<const int*>(a[ii + 1]));
                } else if (type == qMetaTypeId<QQmlV8Handle>()) {
                    args[ii] = reinterpret_cast<QQmlV8Handle *>(a[ii + 1])->toHandle();
                } else if (ep->isQObject(type)) {
                    if (!*reinterpret_cast<void* const *>(a[ii + 1]))
                        args[ii] = v8::Null();
                    else
                        args[ii] = engine->newQObject(*reinterpret_cast<QObject* const *>(a[ii + 1]));
                } else {
                    args[ii] = engine->fromVariant(QVariant(type, a[ii + 1]));
                }
            }

            QQmlJavaScriptExpression::evaluate(context(), m_v8function, argCount, args.data(), 0);
        }
    }
    ep->dereferenceScarceResources(); // "release" scarce resources if top-level expression evaluation is complete.
}
Example #3
0
QString Serveur::parseCommande(QString comm,bool serveur)
{
    if(comm.startsWith("/"))
    {
        comm.remove(0,1);
        QString pref=comm.split(" ").first();
        QStringList args=comm.split(" ");
        args.removeFirst();
        QString destChan=tab->tabText(tab->currentIndex());
        QString msg=args.join(" ");

        if(pref=="me")
            return "PRIVMSG "+destChan+" ACTION " + msg + "";
        else if(pref=="join")
        {
            join(msg);
            return " ";
        }
        else if(pref=="quit")
        {
            if(msg == "")
                return "QUIT "+msgQuit;
            else
                return "QUIT "+msg;
        }
        else if(pref=="part")
        {
            tab->removeTab(tab->currentIndex());

            if(msg == "")
            {
                if(msg.startsWith("#"))
                    destChan=msg.split(" ").first();

                if(msgQuit=="")
                    return "PART "+destChan+" using IrcLightClient";
                else
                    return "PART "+destChan+" "+msgQuit;
            }
            else
                return "PART "+destChan+" "+msg;

            conversations.remove(destChan);
        }
        else if(pref=="kick")
        {
            QStringList tableau=msg.split(" ");
            QString c1,c2,c3;
            if(tableau.count() > 0) c1=" "+tableau.first();
            else c1="";
            if(tableau.count() > 1) c2=" "+tableau.at(1);
            else c2="";
            if(tableau.count() > 2) c3=" "+tableau.at(2);
            else c3="";

            if(c1.startsWith("#"))
                return "KICK"+c1+c2+c3;
            else
                return "KICK "+destChan+c1+c2;
        }
        else if(pref=="update")
        {
            updateUsers=true;
            return "WHO "+destChan;
        }
        else if(pref=="ns")
        {
            return "NICKSERV "+msg;
        }
        else if(pref=="nick")
        {
            emit pseudoChanged(msg);
                        ecrire("-> Nickname changed to "+msg);
            return "NICK "+msg;
        }
        else
            return pref+" "+msg;
    }
    else if(!serveur)
	{
        QString destChan=tab->tabText(tab->currentIndex());
                if(comm.endsWith("<br />"))
                    comm=comm.remove(QRegExp("<br />$"));
                ecrire("<b>&lt;"+pseudo+"&gt;</b> "+comm,destChan);

        if(comm.startsWith(":"))
            comm.insert(0,":");

        return "PRIVMSG "+destChan+" "+comm.replace(" ",".")+"";
    }
	else
	{
		return "";
	}
}
void InsertCommand::redo()
{
    QVERIFY(m_str->length() >= m_idx);

    m_str->insert(m_idx, m_text);
}
void SpellChecker::check()
{
	setDisabled(true);

	QProgressDialog wait_dialog(tr("Checking spelling..."), tr("Cancel"), 0, m_total_blocks, this);
	wait_dialog.setWindowTitle(tr("Please wait"));
	wait_dialog.setValue(0);
	wait_dialog.setWindowModality(Qt::WindowModal);
	bool canceled = false;

	forever {
		// Update wait dialog
		wait_dialog.setValue(m_checked_blocks);
		if (wait_dialog.wasCanceled()) {
			canceled = true;
			break;
		}

		// Check current line
		QTextBlock block = m_cursor.block();
		QStringRef word =  m_dictionary.check(block.text(), m_cursor.position() - block.position());
		if (word.isNull()) {
			if (block.next().isValid()) {
				m_cursor.movePosition(QTextCursor::NextBlock);
				++m_checked_blocks;
				if (m_checked_blocks < m_total_blocks) {
					continue;
				} else {
					break;
				}
			} else if (m_loop_available) {
				wait_dialog.reset();
				if (QMessageBox::question(this, QString(), tr("Continue checking at beginning of file?"),
						QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) {
					m_loop_available = false;
					m_cursor.movePosition(QTextCursor::Start);
					wait_dialog.setRange(0, m_total_blocks);
					continue;
				} else {
					canceled = true;
					break;
				}
			} else {
				break;
			}
		}

		// Select misspelled word
		m_cursor.setPosition(word.position() + block.position());
		m_cursor.setPosition(m_cursor.position() + word.length(), QTextCursor::KeepAnchor);
		m_word = m_cursor.selectedText();

		if (!m_ignored.contains(m_word)) {
			wait_dialog.close();
			setEnabled(true);

			// Show misspelled word in context
			QTextCursor cursor = m_cursor;
			cursor.movePosition(QTextCursor::PreviousWord, QTextCursor::MoveAnchor, 10);
			int end = m_cursor.position() - cursor.position();
			int start = end - m_word.length();
			cursor.movePosition(QTextCursor::NextWord, QTextCursor::KeepAnchor, 21);
			QString context = cursor.selectedText();
			context.insert(end, "</span>");
			context.insert(start, "<span style=\"color: red;\">");
			context.replace("\n", "</p><p>");
			context.replace("\t", "<span style=\"white-space: pre;\">\t</span>");
			context = "<p>" + context + "</p>";
			m_context->setHtml(context);

			// Show suggestions
			m_suggestion->clear();
			m_suggestions->clear();
			QStringList words = m_dictionary.suggestions(m_word);
			if (!words.isEmpty()) {
				foreach (const QString& word, words) {
					m_suggestions->addItem(word);
				}
				m_suggestions->setCurrentRow(0);
			}
Example #6
0
void SimplePatternWizardDialog::insNoOfTracks() {
  QString text = ui.qlineedit_pattern->text();
  text.insert(ui.qlineedit_pattern->cursorPosition(), QString("$" VAR_NO_OF_TRACKS));
  ui.qlineedit_pattern->setText(text);
  update_example();
}
Example #7
0
void SpellChecker::check()
{
	setDisabled(true);
	QProgressDialog wait_dialog(tr("Checking spelling..."), tr("Cancel"), 0, m_document->document()->characterCount(), this);
	wait_dialog.setWindowTitle(tr("Please wait"));
	wait_dialog.setValue(0);
	wait_dialog.setWindowModality(Qt::WindowModal);

	forever {
		// Update wait dialog
		wait_dialog.setValue(m_cursor.position());
		if (wait_dialog.wasCanceled()) {
			m_document->setTextCursor(m_start_cursor);
			reject();
		}

		// Check current line
		QTextBlock block = m_cursor.block();
		QStringRef word =  m_dictionary->check(block.text(), m_cursor.position() - block.position());
		if (word.isNull()) {
			if (block.next().isValid()) {
				m_cursor.movePosition(QTextCursor::NextBlock);
				continue;
			} else {
				break;
			}
		}

		// Select misspelled word
		m_cursor.setPosition(word.position() + block.position());
		m_cursor.setPosition(m_cursor.position() + word.length(), QTextCursor::KeepAnchor);
		m_word = m_cursor.selectedText();

		if (!m_ignored.contains(m_word)) {
			wait_dialog.close();
			setEnabled(true);

			// Show misspelled word in context
			QTextCursor cursor = m_cursor;
			cursor.movePosition(QTextCursor::PreviousWord, QTextCursor::MoveAnchor, 10);
			int end = m_cursor.position() - cursor.position();
			int start = end - m_word.length();
			cursor.movePosition(QTextCursor::NextWord, QTextCursor::KeepAnchor, 21);
			QString context = cursor.selectedText();
			context.insert(end, "</span>");
			context.insert(start, "<span style=\"color: red;\">");
			context.replace("\n", "</p><p>");
			context.replace("\t", "<span style=\"white-space: pre;\">\t</span>");
			context = "<p>" + context + "</p>";
			m_context->setHtml(context);

			// Show suggestions
			m_suggestion->clear();
			m_suggestions->clear();
			QStringList words = m_dictionary->suggestions(m_word);
			if (!words.isEmpty()) {
				foreach (const QString& word, words) {
					m_suggestions->addItem(word);
				}
				m_suggestions->setCurrentRow(0);
			}
QString matematicaString::dividirFlotante(QString dividendo, QString divisor, int retorno)
{
    QString cociente;
    QString modulo;
    QString buffer;
    int contadorDividendo = 0;
    int contadorDividendo2 = 0;
    int contadorDivisor = 0;
    int contadorDivisor2 = 0;
    int newPosicion = 0;
    bool sDividendo = false;
    bool sDivisor = false;

    if(divisor.contains(".")==true){
        sDivisor = true;
        QStringList numReal;
        numReal = divisor.split(".");
        if(numReal.count()>1){
            contadorDivisor = numReal.value(1).count();
            contadorDivisor2 = numReal.value(0).count();
        }
    }

    if(dividendo.contains(".")==true){
        sDividendo = true;
        QStringList numReal;
        numReal = dividendo.split(".");
        if(numReal.count()>1){
            contadorDividendo = numReal.value(1).count();
            contadorDividendo2 = numReal.value(0).count();
        }
    }

    if(contadorDivisor == contadorDividendo){
         divisor.remove(".");
         dividendo.remove(".");
         newPosicion = 0;
    }
    else{
        if(contadorDivisor > contadorDividendo){
            dividendo.remove(".");
            newPosicion = contadorDivisor - contadorDividendo;
            for(int i=0;i<newPosicion;i++){
                dividendo.append("0");
            }
            newPosicion = 0;
        }
        else{
            if(contadorDivisor < contadorDividendo){
                divisor.remove(".");
                dividendo.remove(".");
                newPosicion = dividendo.count()-(contadorDividendo - contadorDivisor);
                dividendo.insert(newPosicion,".");
                newPosicion = 0;
            }
            else{
                if(cociente.count()!=0){
                    cociente.append("0");
                }
                modulo = buffer;
            }
        }
    }

    int divisorNum = divisor.toInt();

    while(dividendo.count()>0){
        buffer.append(dividendo.at(0));
        dividendo.remove(0,1);
        if(buffer.contains(".")==true){
            buffer.remove(".");
            if(cociente.count()==0){
                cociente.append("0");
            }
            cociente.append(".");
        }
        if(buffer.toInt()>=divisorNum){
            cociente.append(QString().setNum(buffer.toInt()/divisorNum));
            modulo = QString().setNum(buffer.toInt()%divisorNum);
            buffer = modulo;
        }
    }

        QStringList analisis;
        analisis = cociente.split(".");
        int bucle = 0;
        if(analisis.count()>1){
            bucle = this->precision - analisis.value(1).count();
        }
        else{
            bucle = this->precision;
        }

        bucle++;

        for(int i=0;i<bucle;i++){
            if(buffer.toInt()<divisorNum){
                buffer.append("0");
            }
            else{
                cociente.append(QString().setNum(buffer.toInt()/divisorNum));
                modulo = QString().setNum(buffer.toInt()/divisorNum);
                buffer = modulo;
            }
        }

        QString numA = cociente.at(cociente.count()-1);
        cociente.remove(cociente.count()-1,1);

        if(numA.toInt()>4){
            numA = cociente.at(cociente.count()-1);
            cociente.remove(cociente.count()-1,1);
            numA = QString().setNum(numA.toInt()+1);
            cociente.append(numA);
        }

    if(retorno == MODULO){
        return modulo;
    }
    return cociente;
}
//
// riceve i caratteri che sono stati digitati:
void widgetKeyBoard::receiptChildKey(QKeyEvent *event, QLineEdit *focusThisControl, bool reset)
{
        static QLineEdit    *nextInput = NULL;

	if (reset == true) { // reinizializza il controllo
                nextInput = this->getNextTextbox(focusThisControl, true);
		return;
	}        
	if (nextInput == NULL)
		return;        
	//
	// inizia l'analisi del carattere ricevuto:
	QString	newKey = event->text();
	QString tmpReceiptString = nextInput->text();
        int     tmpPos = nextInput->cursorPosition();

        if (NO_SPECIAL_KEY(newKey) == false) {
            if (IS_RETURN(newKey) == true || IS_TAB(newKey) == true) { // trattasi di TAB, si sposta alla text successiva
                nextInput = this->setDefaultTextStyle(nextInput);
                nextInput->deselect();
                nextInput = this->getNextTextbox();
                this->controlKeyEcho(nextInput); // status of key echo here
                if (nextInput != NULL) {
                    nextInput->setCursorPosition(nextInput->text().length()); // comment this line if you want caret position at current char inserted
                    nextInput->setFocus(Qt::TabFocusReason);
                }
            }
            else if (IS_BACK(newKey) == true || IS_BACK_EMB(newKey) == true) { // trattasi di CANCELLARE carattere, elimina il carattere a sinistra
                if (tmpPos-1 >= 0) {
                    tmpReceiptString = tmpReceiptString.remove(tmpPos-1, 1);
                    nextInput->setText(tmpReceiptString);
                    nextInput->setCursorPosition(tmpPos-1);
                    nextInput->setSelection(tmpPos-2, 1);
                }
            }
            else if (IS_CANC(newKey) == true) { // trattasi di CANC carattere, elimina il carattere a destra
                 tmpReceiptString = tmpReceiptString.remove(tmpPos, 1);
                 nextInput->setText(tmpReceiptString);
                 nextInput->setCursorPosition(tmpPos);
                 nextInput->setSelection(tmpPos-1, 1);
            }
            else if (IS_COPY(newKey) == true || IS_CUT_LEFT(newKey) == true) {
                QPushButton *button = this->findChild<QPushButton *>(KEY_PASTE);

                if (button != NULL) {
                    if (nextInput->text().length() != 0) {
                        this->m_clipboard->setText(nextInput->text());
                        if (IS_CUT_LEFT(newKey) == true)
                            nextInput->setText("");
                        button->setEnabled(true);
                    }
                    else
                        button->setEnabled(false);
                }
            }
            else if (IS_PASTE(newKey) == true)
                nextInput->setText(this->m_clipboard->text());
            else if (IS_ALT(newKey) == true || IS_CTRL_LEFT(newKey) == true)
                ; // non esegue nessuna operazione
        }
        else { // si tratta di un carattere da visualizzare nella casella di testo corrente
            tmpReceiptString = tmpReceiptString.insert(tmpPos, newKey);
            nextInput->setText(tmpReceiptString);
            nextInput->setCursorPosition(tmpPos+1);
            nextInput->setSelection(tmpPos, 1);
	}
}
    Base::Quantity validateAndInterpret(QString& input, int& pos, QValidator::State& state) const
    {
        Base::Quantity res;
        const double max = this->maximum;
        const double min = this->minimum;

        QString copy = input;

        int len = copy.size();

        const bool plus = max >= 0;
        const bool minus = min <= 0;

        switch (len) {
        case 0:
            state = max != min ? QValidator::Intermediate : QValidator::Invalid;
            goto end;
        case 1:
            if (copy.at(0) == locale.decimalPoint()) {
                state = QValidator::Intermediate;
                copy.prepend(QLatin1Char('0'));
                pos++;
                len++;
                goto end;
            }
            else if (copy.at(0) == QLatin1Char('+')) {
                // the quantity parser doesn't allow numbers of the form '+1.0'
                state = QValidator::Invalid;
                goto end;
            }
            else if (copy.at(0) == QLatin1Char('-')) {
                if (minus)
                    state = QValidator::Intermediate;
                else
                    state = QValidator::Invalid;
                goto end;
            }
            break;
        case 2:
            if (copy.at(1) == locale.decimalPoint()
                    && (plus && copy.at(0) == QLatin1Char('+'))) {
                state = QValidator::Intermediate;
                goto end;
            }
            if (copy.at(1) == locale.decimalPoint()
                    && (minus && copy.at(0) == QLatin1Char('-'))) {
                state = QValidator::Intermediate;
                copy.insert(1, QLatin1Char('0'));
                pos++;
                len++;
                goto end;
            }
            break;
        default:
            break;
        }

        {
            if (copy.at(0) == locale.groupSeparator()) {
                state = QValidator::Invalid;
                goto end;
            }
            else if (len > 1) {
                const int dec = copy.indexOf(locale.decimalPoint());
                if (dec != -1) {
                    if (dec + 1 < copy.size() && copy.at(dec + 1) == locale.decimalPoint() && pos == dec + 1) {
                        copy.remove(dec + 1, 1);
                    }
                    else if (copy.indexOf(locale.decimalPoint(), dec + 1) != -1) {
                        // trying to add a second decimal point is not allowed
                        state = QValidator::Invalid;
                        goto end;
                    }
                    for (int i=dec + 1; i<copy.size(); ++i) {
                        // a group separator after the decimal point is not allowed
                        if (copy.at(i) == locale.groupSeparator()) {
                            state = QValidator::Invalid;
                            goto end;
                        }
                    }
                }
            }

            bool ok = false;
            double value = min;

            if (locale.negativeSign() != QLatin1Char('-'))
                copy.replace(locale.negativeSign(), QLatin1Char('-'));
            if (locale.positiveSign() != QLatin1Char('+'))
                copy.replace(locale.positiveSign(), QLatin1Char('+'));

            try {
                QString copy2 = copy;
                copy2.remove(locale.groupSeparator());

                res = Base::Quantity::parse(copy2);
                value = res.getValue();
                ok = true;
            }
            catch (Base::Exception&) {
            }

            if (!ok) {
                // input may not be finished
                state = QValidator::Intermediate;
            }
            else if (value >= min && value <= max) {
                if (copy.endsWith(locale.decimalPoint())) {
                    // input shouldn't end with a decimal point
                    state = QValidator::Intermediate;
                }
                else if (res.getUnit().isEmpty() && !this->unit.isEmpty()) {
                    // if not dimensionless the input should have a dimension
                    state = QValidator::Intermediate;
                }
                else if (res.getUnit() != this->unit) {
                    state = QValidator::Invalid;
                }
                else {
                    state = QValidator::Acceptable;
                }
            }
            else if (max == min) { // when max and min is the same the only non-Invalid input is max (or min)
                state = QValidator::Invalid;
            }
            else {
                if ((value >= 0 && value > max) || (value < 0 && value < min)) {
                    state = QValidator::Invalid;
                }
                else {
                    state = QValidator::Intermediate;
                }
            }
        }
end:
        if (state != QValidator::Acceptable) {
            res.setValue(max > 0 ? min : max);
        }

        input = copy;
        return res;
    }
Example #11
0
void AppLauncherPlugin::loadButton(){
  QString def = this->ID().section("::",1,50).section("---",0,0).simplified();
  QString path = this->readSetting("applicationpath",def).toString(); //use the default if necessary
  //qDebug() << "Default Application Launcher:" << def << path;
  bool ok = QFile::exists(path);
  if(!ok){ emit RemovePlugin(this->ID()); return;}
  int icosize = this->height()-4 - 2.2*button->fontMetrics().height();
  button->setFixedSize( this->width()-4, this->height()-4);
  button->setIconSize( QSize(icosize,icosize) );
  QString txt;
  if(path.endsWith(".desktop") && ok){
    XDGDesktop file = LXDG::loadDesktopFile(path, ok);
    if(path.isEmpty() || !QFile::exists(path) || !ok){
      button->setWhatsThis("");
      button->setIcon( QIcon(LXDG::findIcon("quickopen-file","").pixmap(QSize(icosize,icosize)).scaledToHeight(icosize, Qt::SmoothTransformation) ) );
      txt = tr("Click to Set");
      if(!watcher->files().isEmpty()){ watcher->removePaths(watcher->files()); }
    }else{
      button->setWhatsThis(file.filePath);
      button->setIcon( QIcon(LXDG::findIcon(file.icon,"quickopen").pixmap(QSize(icosize,icosize)).scaledToHeight(icosize, Qt::SmoothTransformation) ) );
      txt = file.name;
      if(!watcher->files().isEmpty()){ watcher->removePaths(watcher->files()); }
      watcher->addPath(file.filePath); //make sure to update this shortcut if the file changes
    }
  }else if(ok){
    QFileInfo info(path);
    button->setWhatsThis(info.absoluteFilePath());
    if(info.isDir()){
	button->setIcon( LXDG::findIcon("folder","") );
    }else if(LUtils::imageExtensions().contains(info.suffix().toLower()) ){
      button->setIcon( QIcon(QPixmap(path).scaled(256,256)) ); //max size for thumbnails in memory	     
    }else{
      button->setIcon( QIcon(LXDG::findMimeIcon(path).pixmap(QSize(icosize,icosize)).scaledToHeight(icosize, Qt::SmoothTransformation) ) );
    }
    txt = info.fileName();
    if(!watcher->files().isEmpty()){ watcher->removePaths(watcher->files()); }
    watcher->addPath(path); //make sure to update this shortcut if the file changes
  }else{
    //InValid File
    button->setWhatsThis("");
    button->setIcon( QIcon(LXDG::findIcon("quickopen","").pixmap(QSize(icosize,icosize)).scaledToHeight(icosize, Qt::SmoothTransformation) ) );
    button->setText( tr("Click to Set") );
    if(!watcher->files().isEmpty()){ watcher->removePaths(watcher->files()); }
  }
  //If the file is a symlink, put the overlay on the icon
  if(QFileInfo(path).isSymLink()){
    QImage img = button->icon().pixmap(QSize(icosize,icosize)).toImage();
    int oSize = icosize/3; //overlay size
    QPixmap overlay = LXDG::findIcon("emblem-symbolic-link").pixmap(oSize,oSize).scaled(oSize,oSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    QPainter painter(&img);
      painter.drawPixmap(icosize-oSize,icosize-oSize,overlay); //put it in the bottom-right corner
    button->setIcon( QIcon(QPixmap::fromImage(img)) );
  }
  //Now adjust the visible text as necessary based on font/grid sizing
  button->setToolTip(txt);
  //Double check that the visual icon size matches the requested size - otherwise upscale the icon
    if(button->fontMetrics().width(txt) > (button->width()-OUTMARGIN) ){
      //Text too long, try to show it on two lines
      //txt = button->fontMetrics().elidedText(txt, Qt::ElideRight, 2*(button->width()-OUTMARGIN), Qt::TextWordWrap);
      txt =txt.section(" ",0,2).replace(" ","\n"); //First take care of any natural breaks
      //Go through and combine any lines
       if(txt.contains("\n")){
        //need to check each line
	QStringList txtL = txt.split("\n");
	for(int i=0; i<txtL.length(); i++){ 
	  if(( i+1<txtL.length()) && (button->fontMetrics().width(txtL[i]) < button->width()/2) ){
	    txtL[i] = txtL[i]+" "+txtL[i+1];
	    txtL.removeAt(i+1);
	  }
	}
	txt = txtL.join("\n").section("\n",0,2);
      }
            
      if(txt.contains("\n")){
        //need to check each line
	QStringList txtL = txt.split("\n");
	for(int i=0; i<txtL.length(); i++){ 
	  if(i>1){ txtL.removeAt(i); i--; } //Only take the first two lines
	  else{ txtL[i] = button->fontMetrics().elidedText(txtL[i], Qt::ElideRight, (button->width()-OUTMARGIN) );  }
	}
	txt = txtL.join("\n");
      }else{
        txt = this->fontMetrics().elidedText(txt,Qt::ElideRight, 2*(button->width()-OUTMARGIN));
        //Now split the line in half for the two lines
        txt.insert( ((txt.count())/2), "\n");
      }
    }
    if(!txt.contains("\n")){ txt.append("\n "); } //always use two lines
    //qDebug() << " - Setting Button Text:" << txt;
    button->setText(txt);

  QTimer::singleShot(100, this, SLOT(update()) ); //Make sure to re-draw the image in a moment
}
Example #12
0
QString MyMoneyMoney::formatMoney(const QString& currency, const int prec, bool showThousandSeparator) const
{
  QString res;
  QString tmpCurrency = currency;
  int tmpPrec = prec;
  mpz_class denom = 1;
  mpz_class value;

  // if prec == -1 we want the maximum possible but w/o trailing zeroes
  if (tmpPrec > -1) {
    while (tmpPrec--) {
      denom *= 10;
    }
  } else {
    // fix it to a max of 9 digits on the right side for now
    denom = 1000000000;
  }

  // as long as AlkValue::convertDenominator() does not take an
  // mpz_class as the denominator, we need to use a signed int
  // and limit the precision to 9 digits (the max we can
  // present with 31 bits
#if 1
  signed int d;
  if (mpz_fits_sint_p(denom.get_mpz_t())) {
    d = mpz_get_si(denom.get_mpz_t());
  } else {
    d = 1000000000;
  }
  value = static_cast<const MyMoneyMoney>(convertDenominator(d)).valueRef().get_num();
#else
  value = static_cast<const MyMoneyMoney>(convertDenominator(denom)).valueRef().get_num();
#endif

  // Once we really support multiple currencies then this method will
  // be much better than using KGlobal::locale()->formatMoney.
  bool bNegative = false;
  mpz_class left = value / static_cast<MyMoneyMoney>(convertDenominator(d)).valueRef().get_den();
  mpz_class right = mpz_class((valueRef() - mpq_class(left)) * denom);

  if (right < 0) {
    right = -right;
    bNegative = true;
  }
  if (left < 0) {
    left = -left;
    bNegative = true;
  }

  // convert the integer (left) part to a string
  res.append(left.get_str().c_str());

  // if requested, insert thousand separators every three digits
  if (showThousandSeparator) {
    int pos = res.length();
    while ((0 < (pos -= 3)) && thousandSeparator() != 0)
      res.insert(pos, thousandSeparator());
  }

  // take care of the fractional part
  if (prec > 0 || (prec == -1 && right != 0)) {
    if (decimalSeparator() != 0)
      res += decimalSeparator();

    QString rs  = QString("%1").arg(right.get_str().c_str());
    if (prec != -1)
      rs = rs.rightJustified(prec, '0', true);
    else {
      rs = rs.rightJustified(9, '0', true);
      // no trailing zeroes or decimal separators
      while (rs.endsWith('0'))
        rs.truncate(rs.length() - 1);
      while (rs.endsWith(QChar(decimalSeparator())))
        rs.truncate(rs.length() - 1);
    }
    res += rs;
  }

  signPosition signpos = bNegative ? _negativeMonetarySignPosition : _positiveMonetarySignPosition;
  QString sign = bNegative ? "-" : "";

  switch (signpos) {
    case ParensAround:
      res.prepend('(');
      res.append(')');
      break;
    case BeforeQuantityMoney:
      res.prepend(sign);
      break;
    case AfterQuantityMoney:
      res.append(sign);
      break;
    case BeforeMoney:
      tmpCurrency.prepend(sign);
      break;
    case AfterMoney:
      tmpCurrency.append(sign);
      break;
  }
  if (!tmpCurrency.isEmpty()) {
    if (bNegative ? _negativePrefixCurrencySymbol : _positivePrefixCurrencySymbol) {
      res.prepend(' ');
      res.prepend(tmpCurrency);
    } else {
      res.append(' ');
      res.append(tmpCurrency);
    }
  }

  return res;
}
Example #13
0
void Card::drawCard(QPainter &painter, int vector, QString value)
{
    bool drawText = false, drawRect = true;

    if(0 == vector)//Face Down cards
    {
        changeImage("../Bucci-Source/Images/card_back.png");

        if(!value.contains("This"))
        {
            painter.drawPixmap(posX, posY, 30, 40, *cardFace);
            drawRect = false;
        }
        else
        {
            drawRect = true;
        }

        drawText = false;
    }

    if(1 == vector || 2 == vector)//1 = Face up cards. 2 = Hand
    {
        if(value.contains('S'))
        {
            changeImage("../Bucci-Source/Images/card_spade.png");
            painter.drawPixmap(posX, posY, 30, 40, *cardFace);
            drawText = true;
            drawRect = true;
        }
        else if(value.contains('C'))
        {
            changeImage("../Bucci-Source/Images/card_club.png");
            painter.drawPixmap(posX, posY, 30, 40, *cardFace);
            drawText = true;
            drawRect = true;
        }
        else if(value.contains('D'))
        {
            changeImage("../Bucci-Source/Images/card_diamond.png");
            painter.drawPixmap(posX, posY, 30, 40, *cardFace);
            drawText = true;
            drawRect = true;
        }
        else if(value.contains('H'))
        {
            changeImage("../Bucci-Source/Images/card_heart.png");
            painter.drawPixmap(posX, posY, 30, 40, *cardFace);
            drawText = true;
            drawRect = true;
        }
        else
        {
            drawText = false;
            drawRect = false;
        }

        QString val = value;
        val.truncate(val.indexOf(' '));
        val.insert(0,' ');


        if(drawRect)
        {
            if(inQueue)
            {
                painter.setPen(Qt::green);
            }
            else
            {
                painter.setPen(Qt::black);
            }

            painter.drawRect(posX, posY, 30, 40);
        }

        if(drawText)
        {
            if(painter.pen().color() == Qt::green)
            {
                painter.setPen(Qt::black);
            }

            painter.drawText(posX, posY + 10, val);
        }


    }
}//end of drawCard
Example #14
0
bool GameUI::Create()
{
    if (!LoadWindowFromXML("game-ui.xml", "gameui", this))
        return false;

    bool err = false;
    UIUtilE::Assign(this, m_gameUITree, "gametreelist", &err);
    UIUtilW::Assign(this, m_gameTitleText, "title");
    UIUtilW::Assign(this, m_gameSystemText, "system");
    UIUtilW::Assign(this, m_gameYearText, "year");
    UIUtilW::Assign(this, m_gameGenreText, "genre");
    UIUtilW::Assign(this, m_gameFavouriteState, "favorite");
    UIUtilW::Assign(this, m_gamePlotText, "description");
    UIUtilW::Assign(this, m_gameImage, "screenshot");
    UIUtilW::Assign(this, m_fanartImage, "fanart");
    UIUtilW::Assign(this, m_boxImage, "coverart");

    if (err)
    {
        LOG(VB_GENERAL, LOG_ERR, "Cannot load screen 'gameui'");
        return false;
    }

    connect(m_gameUITree, SIGNAL(itemClicked(MythUIButtonListItem*)),
            this, SLOT(itemClicked(MythUIButtonListItem*)));

    connect(m_gameUITree, SIGNAL(nodeChanged(MythGenericTree*)),
            this, SLOT(nodeChanged(MythGenericTree*)));

    m_gameShowFileName = gCoreContext->GetSetting("GameShowFileNames").toInt();

    m_gameTree = new MythGenericTree("game root", 0, false);

    //  create system filter to only select games where handlers are present
    QString systemFilter;

    // The call to GameHandler::count() fills the handler list for us
    // to move through.
    unsigned handlercount = GameHandler::count();

    for (unsigned i = 0; i < handlercount; ++i)
    {
        QString system = GameHandler::getHandler(i)->SystemName();
        if (i == 0)
            systemFilter = "system in ('" + system + "'";
        else
            systemFilter += ",'" + system + "'";
    }
    if (systemFilter.isEmpty())
    {
        systemFilter = "1=0";
        LOG(VB_GENERAL, LOG_ERR, QString("Couldn't find any game handlers!"));
    }
    else
        systemFilter += ")";

    m_showHashed = gCoreContext->GetSetting("GameTreeView").toInt();

    //  create a few top level nodes - this could be moved to a config based
    //  approach with multiple roots if/when someone has the time to create
    //  the relevant dialog screens

    QString levels = gCoreContext->GetSetting("GameFavTreeLevels");

    MythGenericTree *new_node = new MythGenericTree(tr("Favorites"), 1, true);
    new_node->SetData(qVariantFromValue(
                new GameTreeInfo(levels, systemFilter + " and favorite=1")));
    m_favouriteNode = m_gameTree->addNode(new_node);

    levels = gCoreContext->GetSetting("GameAllTreeLevels");

    if (m_showHashed)
    {
        int pos = levels.indexOf("gamename");
        if (pos >= 0)
            levels.insert(pos, " hash ");
    }

    new_node = new MythGenericTree(tr("All Games"), 1, true);
    new_node->SetData(qVariantFromValue(
                new GameTreeInfo(levels, systemFilter)));
    m_gameTree->addNode(new_node);

    new_node = new MythGenericTree(tr("-   By Genre"), 1, true);
    new_node->SetData(qVariantFromValue(
                new GameTreeInfo("genre gamename", systemFilter)));
    m_gameTree->addNode(new_node);

    new_node = new MythGenericTree(tr("-   By Year"), 1, true);
    new_node->SetData(qVariantFromValue(
                new GameTreeInfo("year gamename", systemFilter)));
    m_gameTree->addNode(new_node);

    new_node = new MythGenericTree(tr("-   By Name"), 1, true);
    new_node->SetData(qVariantFromValue(
                new GameTreeInfo("gamename", systemFilter)));
    m_gameTree->addNode(new_node);

    new_node = new MythGenericTree(tr("-   By Publisher"), 1, true);
    new_node->SetData(qVariantFromValue(
                new GameTreeInfo("publisher gamename", systemFilter)));
    m_gameTree->addNode(new_node);

    m_gameUITree->AssignTree(m_gameTree);

    BuildFocusList();

    return true;
}
Example #15
0
void SimplePatternWizardDialog::insAlbumTitle() {
  QString text = ui.qlineedit_pattern->text();
  text.insert(ui.qlineedit_pattern->cursorPosition(), QString("$" VAR_ALBUM_TITLE));
  ui.qlineedit_pattern->setText(text);
  update_example();
}
Example #16
0
void Dialog::berechne() {

    long lsumme=summe;
    int  count=0;
    long tilgung=0;
    long zins=0;
    long sum_zins=0;
    long sum_tilgung=0;

    QDate startDate = ui.dateEdit->date();
    QString text,tail;
    ui.status->setText("");

    count = 0;

    text.append(QString("AnfangsTermin: ").rightJustified(30, ' '));

    text.append(startDate.toString("dd MMM yyyy") + "\n");

    QString tmp;
    tmp.setNum(lsumme);
    text.append(QString("KreditSumme: ").rightJustified(30, ' ') + tmp.insert((tmp.size())-2,'.') + " Euro\n");
    tmp.clear();
    tmp.setNum(zinssatz*100);
    text.append(QString("Zinssatz: ").rightJustified(30, ' ') + tmp + " %\n");
    tmp.setNum(zahlungenprojahr);
    text.append(QString("Zahlungen/Jahr: ").rightJustified(30, ' ') + tmp + "\n");
    tmp.setNum(abzahlung);
    text.append(QString("Zahlung/Rate: ").rightJustified(30, ' ') + tmp.insert((tmp.size())-2,'.') + " Euro\n");

    zins=(int)((float)(lsumme*zinssatz)/zahlungenprojahr+0.5);
    tmp.setNum(zins);
    text.append(QString("Zinsen bei erster Rate: ").rightJustified(30, ' ') + tmp.insert((tmp.size())-2,'.') + " Euro\n");

    if (zins >= abzahlung) {
        text.append("\n  ACHTUNG: DIE ZINSEN PRO RATE SIND GROESSER ALS DIE VORGEGEBENEN ZAHLUNGEN\n");
    } else {
        tail.append(" " +
                    QString("Rate").rightJustified(5, ' ') + " " +
                    QString("Datum").rightJustified(14, ' ') + " " +
                    QString("Tilgung").rightJustified(12, ' ') + " " +
                    QString("Zins").rightJustified(12, ' ') + " " +
                    QString("Restschuld").rightJustified(12, ' ') + "\n");
        while (lsumme > 0) {
            if (count != 0) {
                tmp.setNum(count);
                tmp=tmp.rightJustified(5, ' ', true);

                tail.append(" " + tmp + "    " + startDate.toString("dd-MMM-yyyy") + " ");

                tmp.setNum(tilgung);
                tmp.insert((tmp.size())-2,'.');
                tail.append(tmp.rightJustified(12, ' ') + " ");

                tmp.setNum(zins);
                tmp.insert((tmp.size())-2,'.');
                tail.append(tmp.rightJustified(12, ' ') + " ");

                tmp.setNum(lsumme);
                tmp.insert((tmp.size())-2,'.');
                tail.append(tmp.rightJustified(12, ' ') + " ");

                tail.append("\n");
                switch (zahlungenprojahr) {
                    case 12:
                        startDate=startDate.addMonths(1);
                        break;
                    case 4:
                        startDate=startDate.addMonths(3);
                        break;
                    case 2:
                        startDate=startDate.addMonths(6);
                        break;
                    case 1:
                        startDate=startDate.addMonths(12);
                        break;
                }
            }

            count++;
            zins=(int)((float)(lsumme*zinssatz)/zahlungenprojahr+0.5);

            sum_zins+=zins;

            tilgung=(abzahlung-zins);
            if (tilgung > lsumme)
                tilgung=lsumme;

            sum_tilgung+=tilgung;
            lsumme-=tilgung;

        }
        ui.restlaufzeit->setValue(count-1);
        ui.restlaufzeit->setSuffix(" raten");

        tmp.setNum(sum_zins);
        tmp.insert((tmp.size())-2,'.');
        ui.status->setText("Summe an Zinsen: " + tmp + " Euro");
        text.append(QString("Summe an Zinsen: ").rightJustified(30, ' ') + tmp + " Euro\n\n");
        text.append(tail);
        text.append("\n\n  Thanks for using http://sourceforge.net/projects/vertilgungsplan\n");
        text.append("  This software is distributed under the terms of the GPL V2\n");

        if (summe != sum_tilgung) {
            text.append("Achtung! Schwerer Ausnahmefehler 0E\n");
        }
    }
    ui.textBrowser->setPlainText(text);
}
Example #17
0
void SimplePatternWizardDialog::insSuffix() {
  QString text = ui.qlineedit_pattern->text();
  text.insert(ui.qlineedit_pattern->cursorPosition(), QString("$" VAR_SUFFIX));
  ui.qlineedit_pattern->setText(text);
  update_example();
}
Example #18
0
void sysLocale::sSave()
{
  XSqlQuery sysSave;
  if (_code->text().trimmed().length() == 0)
  {
    QMessageBox::critical( this, tr("Cannot Save Locale"),
                           tr("<p>You must enter a Code for this Locale before "
                              "you may save it.") );
    _code->setFocus();
    return;
  }

  sysSave.prepare( "SELECT locale_id "
             "FROM locale "
             "WHERE ( (locale_id<>:locale_id)"
             " AND (UPPER(locale_code)=UPPER(:locale_code)) );");
  sysSave.bindValue(":locale_id", _localeid);
  sysSave.bindValue(":locale_code", _code->text().trimmed());
  sysSave.exec();
  if (sysSave.first())
  {
    QMessageBox::critical( this, tr("Cannot Create Locale"),
			   tr( "A Locale with the entered code already exists."
			       "You may not create a Locale with this code." ) );
    _code->setFocus();
    return;
  }
  else if (sysSave.lastError().type() != QSqlError::NoError)
  {
    systemError(this, sysSave.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  QLocale sampleLocale = generateLocale();

  if (_mode == cNew)
  {
    sysSave.prepare( "INSERT INTO locale "
               "( locale_id, locale_code, locale_descrip,"
               "  locale_lang_id, locale_country_id, "
               "  locale_dateformat, locale_timeformat, locale_timestampformat,"
	       "  locale_intervalformat, locale_qtyformat,"
               "  locale_curr_scale,"
               "  locale_salesprice_scale, locale_purchprice_scale,"
               "  locale_extprice_scale, locale_cost_scale,"
               "  locale_qty_scale, locale_qtyper_scale,"
               "  locale_uomratio_scale, locale_percent_scale, "
               "  locale_weight_scale, locale_comments, "
               "  locale_error_color, locale_warning_color,"
               "  locale_emphasis_color, locale_altemphasis_color,"
               "  locale_expired_color, locale_future_color) "
               "VALUES "
               "( :locale_id, :locale_code, :locale_descrip,"
               "  :locale_lang_id, :locale_country_id,"
               "  :locale_dateformat, :locale_timeformat, :locale_timestampformat,"
	       "  :locale_intervalformat, :locale_qtyformat,"
               "  :locale_curr_scale,"
               "  :locale_salesprice_scale, :locale_purchprice_scale,"
               "  :locale_extprice_scale, :locale_cost_scale,"
               "  :locale_qty_scale, :locale_qtyper_scale,"
               "  :locale_uomratio_scale, :local_percent_scale, "
               "  :locale_weight_scale, :locale_comments,"
               "  :locale_error_color, :locale_warning_color,"
               "  :locale_emphasis_color, :locale_altemphasis_color,"
               "  :locale_expired_color, :locale_future_color);" );
  }
  else if ( (_mode == cEdit) || (_mode == cCopy) )
    sysSave.prepare( "UPDATE locale "
                "SET locale_code=:locale_code,"
                "    locale_descrip=:locale_descrip,"
                "    locale_lang_id=:locale_lang_id,"
                "    locale_country_id=:locale_country_id,"
                "    locale_dateformat=:locale_dateformat,"
                "    locale_timeformat=:locale_timeformat,"
                "    locale_timestampformat=:locale_timestampformat,"
                "    locale_intervalformat=:locale_intervalformat,"
                "    locale_qtyformat=:locale_qtyformat,"
		"    locale_curr_scale=:locale_curr_scale,"
                "    locale_salesprice_scale=:locale_salesprice_scale,"
                "    locale_purchprice_scale=:locale_purchprice_scale,"
                "    locale_extprice_scale=:locale_extprice_scale,"
                "    locale_cost_scale=:locale_cost_scale,"
                "    locale_qty_scale=:locale_qty_scale,"
                "    locale_qtyper_scale=:locale_qtyper_scale,"
                "    locale_weight_scale=:locale_weight_scale,"
                "    locale_uomratio_scale=:locale_uomratio_scale,"
                "    locale_percent_scale=:locale_percent_scale,"
                "    locale_comments=:locale_comments,"
                "    locale_error_color=:locale_error_color,"
                "    locale_warning_color=:locale_warning_color,"
                "    locale_emphasis_color=:locale_emphasis_color,"
                "    locale_altemphasis_color=:locale_altemphasis_color,"
                "    locale_expired_color=:locale_expired_color,"
                "    locale_future_color=:locale_future_color "
                "WHERE (locale_id=:locale_id);" );

  sysSave.bindValue(":locale_id",                _localeid);
  sysSave.bindValue(":locale_code",              _code->text());
  sysSave.bindValue(":locale_descrip",           _description->text());
  sysSave.bindValue(":locale_lang_id",           _language->id());
  sysSave.bindValue(":locale_country_id",        _country->id());
  sysSave.bindValue(":locale_curr_scale",        _currencyScale->text());
  sysSave.bindValue(":locale_salesprice_scale",  _salesPriceScale->text());
  sysSave.bindValue(":locale_purchprice_scale",  _purchPriceScale->text());
  sysSave.bindValue(":locale_extprice_scale",    _extPriceScale->text());
  sysSave.bindValue(":locale_cost_scale",        _costScale->text());
  sysSave.bindValue(":locale_qty_scale",         _qtyScale->text());
  sysSave.bindValue(":locale_qtyper_scale",      _qtyPerScale->text());
  sysSave.bindValue(":locale_weight_scale",      _weightScale->text());
  sysSave.bindValue(":locale_uomratio_scale",    _uomRatioScale->text());
  sysSave.bindValue(":locale_percent_scale",     _percentScale->text());
  sysSave.bindValue(":locale_comments",          _comments->toPlainText());
  sysSave.bindValue(":locale_error_color",       _error->text());
  sysSave.bindValue(":locale_warning_color",     _warning->text());
  sysSave.bindValue(":locale_emphasis_color",    _emphasis->text());
  sysSave.bindValue(":locale_altemphasis_color", _alternate->text());
  sysSave.bindValue(":locale_expired_color",     _expired->text());
  sysSave.bindValue(":locale_future_color",      _future->text());
  sysSave.bindValue(":locale_dateformat",     convert(sampleLocale.dateFormat(QLocale::ShortFormat)));
  sysSave.bindValue(":locale_timeformat",     convert(sampleLocale.timeFormat(QLocale::ShortFormat)));
  sysSave.bindValue(":locale_timestampformat",convert(sampleLocale.dateFormat(QLocale::ShortFormat)) +
                                  " " + convert(sampleLocale.timeFormat(QLocale::ShortFormat)));
  {
    QString intervalfmt = convert(sampleLocale.timeFormat(QLocale::ShortFormat).remove("ap", Qt::CaseInsensitive));
    intervalfmt.insert(intervalfmt.indexOf("HH") + 2, "24");
    sysSave.bindValue(":locale_intervalformat", intervalfmt);
  }
  sysSave.bindValue(":locale_qtyformat",      QString(sampleLocale.decimalPoint()) +
                                        QString(sampleLocale.negativeSign()) +
                                        QString(sampleLocale.groupSeparator()));
  sysSave.exec();
  if (sysSave.lastError().type() != QSqlError::NoError)
  {
    systemError(this, sysSave.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  done(_localeid);
}
/*!
    Returns this coordinate as a string in the specified \a format.

    For example, if this coordinate has a latitude of -27.46758, a longitude
    of 153.027892 and an altitude of 28.1, these are the strings
    returned depending on \a format:

    \table
    \header
        \o \a format value
        \o Returned string
    \row
        \o \l Degrees
        \o -27.46758\unicode{0xB0}, 153.02789\unicode{0xB0}, 28.1m
    \row
        \o \l DegreesWithHemisphere
        \o 27.46758\unicode{0xB0} S, 153.02789\unicode{0xB0} E, 28.1m
    \row
        \o \l DegreesMinutes
        \o -27\unicode{0xB0} 28.054', 153\unicode{0xB0} 1.673', 28.1m
    \row
        \o \l DegreesMinutesWithHemisphere
        \o 27\unicode{0xB0} 28.054 S', 153\unicode{0xB0} 1.673' E, 28.1m
    \row
        \o \l DegreesMinutesSeconds
        \o -27\unicode{0xB0} 28' 3.2", 153\unicode{0xB0} 1' 40.4", 28.1m
    \row
        \o \l DegreesMinutesSecondsWithHemisphere
        \o 27\unicode{0xB0} 28' 3.2" S, 153\unicode{0xB0} 1' 40.4" E, 28.1m
    \endtable

    The altitude field is omitted if no altitude is set.

    If the coordinate is invalid, an empty string is returned.
*/
QString QGeoCoordinate::toString(CoordinateFormat format) const
{
    if (type() == QGeoCoordinate::InvalidCoordinate)
        return QString();

    QString latStr;
    QString longStr;

    double absLat = qAbs(d->lat);
    double absLng = qAbs(d->lng);
    QChar symbol(0x00B0);   // degrees symbol

    switch (format) {
        case Degrees:
        case DegreesWithHemisphere: {
            latStr = QString::number(absLat, 'f', 5) + symbol;
            longStr = QString::number(absLng, 'f', 5) + symbol;
            break;
        }
        case DegreesMinutes:
        case DegreesMinutesWithHemisphere: {
            double latMin = (absLat - int(absLat)) * 60;
            double lngMin = (absLng - int(absLng)) * 60;
            latStr = QString("%1%2 %3'")
                     .arg(QString::number(int(absLat)))
                     .arg(symbol)
                     .arg(QString::number(latMin, 'f', 3));
            longStr = QString("%1%2 %3'")
                      .arg(QString::number(int(absLng)))
                      .arg(symbol)
                      .arg(QString::number(lngMin, 'f', 3));
            break;
        }
        case DegreesMinutesSeconds:
        case DegreesMinutesSecondsWithHemisphere: {
            double latMin = (absLat - int(absLat)) * 60;
            double lngMin = (absLng - int(absLng)) * 60;
            double latSec = (latMin - int(latMin)) * 60;
            double lngSec = (lngMin - int(lngMin)) * 60;

            latStr = QString("%1%2 %3' %4\"")
                     .arg(QString::number(int(absLat)))
                     .arg(symbol)
                     .arg(QString::number(int(latMin)))
                     .arg(QString::number(latSec, 'f', 1));
            longStr = QString("%1%2 %3' %4\"")
                      .arg(QString::number(int(absLng)))
                      .arg(symbol)
                      .arg(QString::number(int(lngMin)))
                      .arg(QString::number(lngSec, 'f', 1));
            break;
        }
    }

    // now add the "-" to the start, or append the hemisphere char
    switch (format) {
        case Degrees:
        case DegreesMinutes:
        case DegreesMinutesSeconds: {
            if (d->lat < 0)
                latStr.insert(0, "-");
            if (d->lng < 0)
                longStr.insert(0, "-");
            break;
        }
        case DegreesWithHemisphere:
        case DegreesMinutesWithHemisphere:
        case DegreesMinutesSecondsWithHemisphere: {
            if (d->lat < 0)
                latStr.append(" S");
            else if (d->lat > 0)
                latStr.append(" N");
            if (d->lng < 0)
                longStr.append(" W");
            else if (d->lng > 0)
                longStr.append(" E");
            break;
        }
    }

    if (qIsNaN(d->alt))
        return QString("%1, %2").arg(latStr, longStr);
    return QString("%1, %2, %3m").arg(latStr, longStr, QString::number(d->alt));
}
void QAccessibleSimpleEditableTextInterface::insertText(int offset, const QString &text)
{
    QString txt = iface->text(QAccessible::Value, 0);
    txt.insert(offset, text);
    iface->setText(QAccessible::Value, 0, txt);
}
bool FormClassWizardParametersPrivate::generateCpp(const FormClassWizardGenerationParameters &generationParameters,
                                                   QString *header, QString *source, int indentation) const
{
    const QString indent = QString(indentation, QLatin1Char(' '));
    QString formBaseClass;
    QString uiClassName;
    if (!FormClassWizardParameters::getUIXmlData(uiTemplate, &formBaseClass, &uiClassName)) {
        qWarning("Unable to determine the form base class from %s.", uiTemplate.toUtf8().constData());
        return false;
    }

    // Build the ui class (Ui::Foo) name relative to the namespace (which is the same):
    const FormClassWizardGenerationParameters::UiClassEmbedding embedding = generationParameters.embedding();
    const QString colonColon = QLatin1String("::");
    const int lastSeparator = uiClassName.lastIndexOf(colonColon);
    if (lastSeparator != -1)
        uiClassName.remove(0, lastSeparator + colonColon.size());
    uiClassName.insert(0, QLatin1String(uiNamespaceC) + colonColon);

    // Do we have namespaces?
    QStringList namespaceList = className.split(colonColon);
    if (namespaceList.empty()) // Paranoia!
        return false;

    const QString unqualifiedClassName = namespaceList.takeLast();

    const QString license = CppTools::AbstractEditorSupport::licenseTemplate();
    // Include guards
    const QString guard = Utils::headerGuard(headerFile);

    QString uiInclude = QLatin1String("ui_");
    uiInclude += QFileInfo(uiFile).completeBaseName();
    uiInclude += QLatin1String(".h");

    // 1) Header file
    QTextStream headerStr(header);
    headerStr << license << "#ifndef " << guard
              << "\n#define " <<  guard << '\n' << '\n';

    // Include 'ui_'
    if (embedding != FormClassWizardGenerationParameters::PointerAggregatedUiClass) {
        Utils::writeIncludeFileDirective(uiInclude, false, headerStr);
    } else {
        // Todo: Can we obtain the header from the code model for custom widgets?
        // Alternatively, from Designer.
        if (formBaseClass.startsWith(QLatin1Char('Q'))) {
            QString baseInclude = formBaseClass;
            if (generationParameters.includeQtModule())
                baseInclude.insert(0, QLatin1String("QtGui/"));
            Utils::writeIncludeFileDirective(baseInclude, true, headerStr);
        }
    }

    const QString namespaceIndent = Utils::writeOpeningNameSpaces(namespaceList,
                                                                        generationParameters.indentNamespace() ? indent : QString(),
                                                                        headerStr);

    // Forward-declare the UI class
    if (embedding == FormClassWizardGenerationParameters::PointerAggregatedUiClass) {
          headerStr << '\n'
                  << namespaceIndent << "namespace " <<  uiNamespaceC << " {\n"
                  << namespaceIndent << indent << "class " << Internal::FormTemplateWizardPage::stripNamespaces(uiClassName) << ";\n"
                  << namespaceIndent << "}\n";
    }

    // Class declaration
    headerStr << '\n' << namespaceIndent << "class " << unqualifiedClassName
              << " : public " << formBaseClass;
    if (embedding == FormClassWizardGenerationParameters::InheritedUiClass) {
        headerStr << ", private " << uiClassName;
    }
    headerStr << " {\n" << namespaceIndent << indent << "Q_OBJECT\n"
              << namespaceIndent << "public:\n"
              << namespaceIndent << indent << unqualifiedClassName << "(QWidget *parent = 0);\n";
    if (embedding == FormClassWizardGenerationParameters::PointerAggregatedUiClass)
        headerStr << namespaceIndent << indent << "~" << unqualifiedClassName << "();\n";
    // retranslation
    if (generationParameters.retranslationSupport())
        headerStr << '\n' << namespaceIndent << "protected:\n"
                  << namespaceIndent << indent << "void changeEvent(QEvent *e);\n";
    // Member variable
    if (embedding != FormClassWizardGenerationParameters::InheritedUiClass) {
        headerStr << '\n' << namespaceIndent << "private:\n"
                  << namespaceIndent << indent << uiClassName << ' ';
        if (embedding == FormClassWizardGenerationParameters::PointerAggregatedUiClass)
            headerStr << '*';
        headerStr << uiMemberC << ";\n";
    }
    headerStr << namespaceIndent << "};\n\n";
    Utils::writeClosingNameSpaces(namespaceList, generationParameters.indentNamespace() ? indent : QString(), headerStr);
    headerStr << "#endif // "<<  guard << '\n';

    // 2) Source file
    QTextStream sourceStr(source);
    sourceStr << license;
    Utils::writeIncludeFileDirective(headerFile, false, sourceStr);
    if (embedding == FormClassWizardGenerationParameters::PointerAggregatedUiClass)
        Utils::writeIncludeFileDirective(uiInclude, false, sourceStr);
    // NameSpaces(
    Utils::writeOpeningNameSpaces(namespaceList, generationParameters.indentNamespace() ? indent : QString(), sourceStr);
    // Constructor with setupUi
    sourceStr << '\n' << namespaceIndent << unqualifiedClassName << "::" << unqualifiedClassName << "(QWidget *parent) :\n"
               << namespaceIndent << indent << formBaseClass << "(parent)";
    if (embedding == FormClassWizardGenerationParameters::PointerAggregatedUiClass)
        sourceStr << ",\n"  << namespaceIndent << indent <<  uiMemberC << "(new " << uiClassName << ")\n";
    sourceStr <<  namespaceIndent << "{\n" <<  namespaceIndent << indent;
    writeUiMemberAccess(generationParameters, sourceStr);
    sourceStr <<  "setupUi(this);\n" << namespaceIndent << "}\n";
    // Deleting destructor for ptr
    if (embedding == FormClassWizardGenerationParameters::PointerAggregatedUiClass) {
        sourceStr << '\n' <<  namespaceIndent << unqualifiedClassName << "::~" << unqualifiedClassName
                  << "()\n" << namespaceIndent << "{\n"
                  << namespaceIndent << indent << "delete " << uiMemberC << ";\n"
                  << namespaceIndent << "}\n";
    }
    // retranslation
    if (generationParameters.retranslationSupport()) {
        sourceStr  << '\n' << namespaceIndent << "void " << unqualifiedClassName << "::" << "changeEvent(QEvent *e)\n"
        << namespaceIndent << "{\n"
        << namespaceIndent << indent << formBaseClass << "::changeEvent(e);\n"
        << namespaceIndent << indent << "switch (e->type()) {\n" << namespaceIndent << indent << "case QEvent::LanguageChange:\n"
        << namespaceIndent << indent << indent;
        writeUiMemberAccess(generationParameters, sourceStr);
        sourceStr << "retranslateUi(this);\n"
                  << namespaceIndent << indent <<  indent << "break;\n"
                  << namespaceIndent << indent << "default:\n"
                  << namespaceIndent << indent << indent << "break;\n"
                  << namespaceIndent << indent << "}\n"
                  << namespaceIndent << "}\n";
    }
    Utils::writeClosingNameSpaces(namespaceList, generationParameters.indentNamespace() ? indent : QString(), sourceStr);
    return true;
}
void ResultViewEntry::updateLine(QString& line)
{
  line.insert(m_pos, m_data);
  line.remove(m_pos + dataLength(), keyLength());
}
void RemoveCommand::undo()
{
    QVERIFY(m_str->length() >= m_idx);

    m_str->insert(m_idx, m_text);
}
Example #24
0
QString Calligra::Sheets::MSOOXML::convertFormula(const QString& formula)
{
    if (formula.isEmpty())
        return QString();
    enum { InStart, InArguments, InParenthesizedArgument, InString, InSheetOrAreaName, InCellReference } state;
    state = InStart;
    int cellReferenceStart = 0;
    int sheetOrAreaNameDelimiterCount = 0;
    QString result = formula.startsWith('=') ? formula : '=' + formula;
    for(int i = 1; i < result.length(); ++i) {
        QChar ch = result[i];
        switch (state) {
        case InStart:
            if(ch == '(')
                state = InArguments;
            break;
        case InArguments:
            if (ch == '"')
                state = InString;
            else if (ch.unicode() == '\'') {
                sheetOrAreaNameDelimiterCount = 1;
                for(int j = i + 1; j < result.length(); ++j) {
                    if (result[j].unicode() != '\'')
                        break;
                    ++sheetOrAreaNameDelimiterCount;
                }
                if (sheetOrAreaNameDelimiterCount >= 2)
                    result.remove(i + 1, sheetOrAreaNameDelimiterCount - 1);
                state = InSheetOrAreaName;
            } else if (isCellnameCharacter(ch)) {
                state = InCellReference;
                cellReferenceStart = i;
            } else if (ch == ',')
                result[i] = ';'; // replace argument delimiter
            else if (ch == '(' && !result[i-1].isLetterOrNumber())
                state = InParenthesizedArgument;
            else if (ch == ' ') {
                // check if it might be an intersection operator
                // for it to be an intersection operator the next non-space char must be a cell-name-character or '
                // and previous converted char cannot be ';'
                int firstNonSpace = i+1;
                while (firstNonSpace < result.length() && result[firstNonSpace] == ' ') {
                    firstNonSpace++;
                }
                bool wasDelimeter = (i-1 > 0) && (result[i-1] == ';');
                bool isIntersection = !wasDelimeter && firstNonSpace < result.length() && (result[firstNonSpace].isLetter() || result[firstNonSpace] == '$' || result[firstNonSpace] == '\'');
                if (isIntersection) {
                    result[i] = '!';
                    i = firstNonSpace-1;
                }
            }
            break;
        case InParenthesizedArgument:
            if (ch == ',')
                result[i] = '~'; // union operator
            else if (ch == ' ')
                result[i] = '!'; // intersection operator
            else if (ch == ')')
                state = InArguments;
            break;
        case InString:
            if (ch == '"')
                state = InArguments;
            break;
        case InSheetOrAreaName:
            Q_ASSERT( i >= 1 );
            if (ch == '\'' && result[i - 1].unicode() != '\\') {
                int count = 1;
                for(int j = i + 1; count < sheetOrAreaNameDelimiterCount && j < result.length(); ++j) {
                    if (result[j].unicode() != '\'')
                        break;
                    ++count;
                }
                if (count == sheetOrAreaNameDelimiterCount) {
                    if (sheetOrAreaNameDelimiterCount >= 2)
                        result.remove(i + 1, sheetOrAreaNameDelimiterCount - 1);
                    state = InArguments;
                } else {
                    result.insert(i, '\'');
                    ++i;
                }
            }
            break;
        case InCellReference:
            if (!isCellnameCharacter(ch)) {
                if (ch != '(') /* skip formula-names */ {
                    // Excel is able to use only the column-name to define a column
                    // where all rows are selected. Since that is not supproted in
                    // ODF we add to such definitions the minimum/maximum row-number.
                    // So, something like "A:B" would become "A$1:B$65536". Note that
                    // such whole column-definitions are only allowed for ranges like
                    // "A:B" but not for single column definitions like "A" or "B".
                    const QString ref = result.mid(qMax(0, cellReferenceStart - 1), i - cellReferenceStart + 2);
                    QRegExp rxStart(".*(|\\$)[A-Za-z]+\\:");
                    QRegExp rxEnd("\\:(|\\$)[A-Za-z]+(|(|\\$)[0-9]+).*");
                    if (rxEnd.exactMatch(ref) && rxEnd.cap(2).isEmpty()) {
                        result.insert(i, "$65536");
                        i += 6;
                    } else if (rxStart.exactMatch(ref)) {
                        result.insert(i, "$1");
                        i += 2;
                    }
                }
                state = InArguments;
                --i; // decrement again to handle the current char in the InArguments-switch.
            }
            break;
        };
    };
    return result;
}
Example #25
0
void aHistLineEdit::keyPressEvent ( QKeyEvent *e )
{
  if ( e->key() != Key_Tab)
    emit notTab();

  if ( e->state() == ControlButton ) {
    QString s;
    s.insert( 0, text() );
    int curPos = cursorPosition();
    switch ( e->key() ) {
    case Key_B:
      s.insert( cursorPosition(), 0xdf );
      setText(s);
      setCursorPosition(curPos + 1);
      break;
    case Key_U:
      s.insert( cursorPosition(), 0xdc );
      setText(s);
      setCursorPosition(curPos + 1);
      break;
    case Key_R:
      s.insert( cursorPosition(), 0x9f );
      setText(s);
      setCursorPosition(curPos + 1);
      break;
    case Key_K:
      s.insert(  cursorPosition(), 0xa9 );
      setText(s);
      setCursorPosition(curPos + 1);
      if ( kSircConfig->ColourPicker ) {
        ColourPickerPopUp();
      }
      break;
    case Key_O:
      s.insert( cursorPosition(), 0xa4 );
      setText(s);
      setCursorPosition(curPos + 1);
      break;
    case Key_I:
      s.insert( cursorPosition(), "~i");
      setText(s);
      setCursorPosition(curPos + 2);
      break;
    default:
      QLineEdit::keyPressEvent(e);
    }
  }
  else if(e->state() == 0){
    switch(e->key()){
    case Key_Up:
      if(hist.at() == current){ // same as Key_Down
	hist.remove(current);
	hist.insert(current, text());
      }
      if(hist.at() < 1){ // Same idea as Key_Down so look there for an
	hist.last();     // explanation
	setText(hist.current());
      }
      else
	setText(hist.prev()); // Set text to prev item
      break;
    case Key_Down:
      if(hist.at() == current){ // If we're leaving the active line, save it
	hist.remove(current);   // remove last line
	hist.insert(current, text()); // update it to the current line
      }
      if(hist.at() >= (int) hist.count()-1){ // If we're moving byond the end
	hist.first();                        // roll to first one
	setText(hist.current());             // set text to first line
      }
      else
	setText(hist.next());                // Set text to the next one
      break;
    case Key_Return:
    case Key_Enter:
      if(hist.count() > 20){
	hist.removeFirst(); // more than 20 entries? ick
        current--;          // backup counter
      }
      if(text() != ""){
	hist.remove(current); // remove the "dummy" entry
	hist.append(text()); // add the current text to the end
	hist.append(""); // set the next line to blank
	current = hist.count() - 1; // move ahead one.
      }
    default:
      QLineEdit::keyPressEvent(e);
    }
  }
  else{
    QLineEdit::keyPressEvent(e);
  }
}
Example #26
0
Filer::FileError Filer::setName(const QString &aFileName)
{
    fileName.clear();
    dirName.clear();
    patchedFileName.clear();

    // File Name
    if (aFileName.isNull()) {
        toLogArea(Error, tr("File name is empty!"));
        return FIsEmpty;
    }
    fileName = aFileName;
    QFileInfo fileInfo(fileName);
    FileError error = checkFileInfo(fileName);
    if (error != AllOk) {
        return error;
    }
    fileName = fileInfo.fileName();

    // Directory Name
    dirName = fileInfo.absolutePath();
    QFileInfo dirInfo(dirName);
    if (dirName.isNull()) {
        toLogArea(Error, tr("Directory name is empty!"));
        return DIsEmpty;
    }
    if (!dirInfo.isDir()) {
        toLogArea(Error, tr("This is not directory!"));
        return DIsFileIsNotDir;
    }
    if (!dirInfo.isReadable()) {
        toLogArea(Error, tr("Directory is not readable!"));
        return DIsNotReadable;
    }
    if (!dirInfo.isWritable()) {
        toLogArea(Error, tr("Directory is not writable!"));
        return DIsNotWritable;
    }
    dirName += QDir::separator();

    // Patched File Name
    QString date = QString("_") + QDateTime::currentDateTime().toString("dd-MM-yy_HH-mm-ss");
    QString patched = "_patched";
    if (!fileName.contains(patched)) {
        QString origFileName = fileInfo.fileName();
        int _size = origFileName.size() - 1;
        if (origFileName.contains('.')) {
            // Find last dot
            int i;
            for (i = _size; i >= 0; --i) {
                if (origFileName.at(i) == '.') {
                    break;
                }
            }
            // Insert string
            patchedFileName = origFileName.insert(i, date + patched);
        } else {
            patchedFileName = origFileName + date + patched;
        }
    } else {
        patchedFileName = fileName;
        if (patchedFileName.endsWith(".smg")) {
            generateName(true);
        } else {
            generateName(false);
        }
    }
    QFileInfo patchedFileInfo(dirName + QDir::separator() + patchedFileName);
    if (patchedFileInfo.exists()) {
        toLogArea(Error, tr("File exists!"));
        return FIsExists;
    }

    return AllOk;
}
Example #27
0
void breakLine(QString& str, QString& after, int textWidth)
{
    if (str.length() <= textWidth)
    {
        return;
    }

    // Найти слово, которое находится на границе textWidth.
    int beginWordPosition = str.lastIndexOf(' ', textWidth - 1) + 1;
    int endWordPosition = str.indexOf(' ', textWidth - 1) - 1;

    // Граничное слово находится в конце строки.
    if (endWordPosition == -2)
    {
        endWordPosition = str.length() - 1;
    }

    // Слово состоит из одной буквы.
    if (beginWordPosition == endWordPosition + 2)
    {
        endWordPosition = beginWordPosition;
    }

    int wordLength = endWordPosition - beginWordPosition + 1;
    QString word = str.mid(beginWordPosition, wordLength);

    // Слово начинается на границе ширины текста.
    if (beginWordPosition == textWidth - 1 && wordLength != 1)
    {
        QString temp = str.left(textWidth - 1);
        after = str.right(str.length() - temp.length());

		temp = temp.trimmed();
        if (temp.length() < textWidth)
        {
            fillSpaces(temp, textWidth);
        }
        str = temp.trimmed();
        return;
    }

    // Расставить в слове мягкие переносы.
    placeHyphens(word, word);

    // В слове нельзя сделать перенос.
    if (word.count('\1') == 0)
    {
        // Слово целиком умещается в ширину текста.
        if (beginWordPosition + wordLength <= textWidth)
        {
            after = str.right(str.length() - textWidth).trimmed();
            str.chop(str.length() - textWidth);
			str = str.trimmed();
			if (str.length() < textWidth)
			{
				fillSpaces(str, textWidth);
			}
			str = str.trimmed();
            return;
        }
        else
        {
            QString temp = str.left(textWidth);
            after = str.right(str.length() - temp.length());
            str = temp.trimmed();
			if (str.length() < textWidth)
			{
				fillSpaces(str, textWidth);
			}
			str = str.trimmed();
            return;
        }
    }

    // Вычислить максимальную длину слова до переноса, как разницу индексов
    // максимально допустимого символа, умещающегося в ширину текста, и начала
    // слова (символ переноса не входит в эту длину).
    int maxWordLengthBeforeBreak = (textWidth - 1) - beginWordPosition;

    // Так как в слове появились мягкие переносы, то нужно увеличить
    // максимальную длину слова до переноса на количество символов,
    // встретившихся перед прежней длиной.
    for (int i = 0; i < maxWordLengthBeforeBreak; ++i)
    {
        if (word[i] == '\1')
        {
            ++maxWordLengthBeforeBreak;
        }
    }
    if (word[maxWordLengthBeforeBreak] == '\1')
    {
        ++maxWordLengthBeforeBreak;
    }

    // Индекс переноса.
    int breakIndex = word.lastIndexOf('\1', maxWordLengthBeforeBreak - 1);

    // В слове можно сделать перенос с учетом ограничения на длину.
    if (breakIndex != -1)
    {
        // Заменить мягкий перенос на '\2' в позиции, не превышающей
        // максимальную длину слова до переноса. Замена производится именно на
        // '\2', а не на знак дефиса, т. к. в строке уже может быть знак дефиса.
        // Иначе не получится легко определить индекс, где нужно разделить
        // строки на две.
        word[breakIndex] = '\2';

        // Удалить все мягкие переносы.
        word.replace('\1', "");

        // Вставить слово с переносом в строку.
        str.remove(beginWordPosition, wordLength);
        str.insert(beginWordPosition, word);

        // Разделить строку на две.
        QStringList strings = str.split('\2');
        str = strings[0] + "-";
        if (str.length() < textWidth)
        {
            fillSpaces(str, textWidth);
        }
        after = strings[1];
		str = str.trimmed();
    }
    // В слове нельзя сделать перенос с учетом ограничения на длину.
    // Разделяем строку по границе начала граничного слова.
    else
    {
        after = str.right(str.length() - beginWordPosition);
        str.chop(str.length() - beginWordPosition);
        if (str.length() < textWidth)
        {
            fillSpaces(str, textWidth);
        }
		str = str.trimmed();
    }
}
double EqonomizeValueEdit::fixup_sub(QString &input, QStringList &errors, bool &calculated) const {
	input = input.trimmed();
	if(input.isEmpty()) {
		return 0.0;
	}
	if(o_currency) {
		input.remove(budget->monetary_group_separator);
		if(!budget->monetary_negative_sign.isEmpty()) input.replace(budget->monetary_negative_sign, "-");
		if(!budget->monetary_positive_sign.isEmpty()) input.replace(budget->monetary_positive_sign, "+");
	} else {
		input.remove(budget->group_separator);
		if(!budget->negative_sign.isEmpty()) input.replace(budget->negative_sign, "-");
		if(!budget->positive_sign.isEmpty()) input.replace(budget->positive_sign, "+");
	}
	input.replace(QLocale().negativeSign(), '-');
	input.replace(QLocale().positiveSign(), '+');
	int i = input.indexOf(')', 1);
	if(i < 1) {
		i = input.indexOf('(', 0);
		if(i == 0) {
			input.remove(0, 1);
			return fixup_sub(input, errors, calculated);
		} else if(i >= 0) {
			input += ')';
			i = input.length() - 1;
		} else {
			i = -1;
		}
	}
	if(i >= 1) {
		int i2 = input.lastIndexOf('(', i - 1);
		if(i2 < 0 || i2 > i) {
			if(i == input.length() - 1) {
				input.chop(1);
				return fixup_sub(input, errors, calculated);
			}
			input.prepend('(');
			i++;
			i2 = 0;
		}
		if(i2 == 0 && i == input.length() - 1) {
			input.remove(0, 1);
			input.chop(1);
			return fixup_sub(input, errors, calculated);
		}
		if(i < input.length() - 1 && (input[i + 1].isNumber() || input[i + 1] == '(')) input.insert(i + 1, '*');
		QString str = input.mid(i2 + 1, i - i2 - 1);
		double v = fixup_sub(str, errors, calculated);
		input.replace(i2, i - i2 + 1, o_currency ? o_currency->formatValue(0.5, decimals() + 2, false, false, true) : budget->formatValue(v, decimals() + 2));
		if(i2 > 0 && (input[i2 - 1].isNumber() || input[i2 - 1] == ')')) input.insert(i2, '*');
		calculated = true;
		return fixup_sub(input, errors, calculated);
	}
	i = input.indexOf(QRegExp("[-+]"), 1);
	if(i >= 1) {
		QStringList terms = input.split(QRegExp("[-+]"));
		i = 0;
		double v = 0.0;
		QList<bool> signs;
		signs << true;
		for(int terms_i = 0; terms_i < terms.size() - 1; terms_i++) {
			i += terms[terms_i].length();
			if(input[i] == '-') signs << false;
			else signs << true;
			i++;
		}
		for(int terms_i = 0; terms_i < terms.size() - 1; terms_i++) {
			if(terms[terms_i].endsWith('*') || terms[terms_i].endsWith('/') || terms[terms_i].endsWith('^')) {
				if(!signs[terms_i + 1]) terms[terms_i] += '-';
				else terms[terms_i] += '+';
				terms[terms_i] += terms[terms_i + 1];
				signs.removeAt(terms_i + 1);
				terms.removeAt(terms_i + 1);
				terms_i--;
			}
		}
		if(terms.size() > 1) {
			for(int terms_i = 0; terms_i < terms.size(); terms_i++) {
				if(terms[terms_i].isEmpty()) {
					if(!signs[terms_i] && terms_i + 1 < terms.size()) {
						signs[terms_i + 1] = !signs[terms_i + 1];
					}
				} else {					
					if(!signs[terms_i]) v -= fixup_sub(terms[terms_i], errors, calculated);
					else v += fixup_sub(terms[terms_i], errors, calculated);
				}
			}			
			calculated = true;
			return v;
		}
	}
	if(input.indexOf("**") >= 0) input.replace("**", "^");
	i = input.indexOf(QRegExp("[*/]"), 0);
	if(i >= 0) {
		QStringList terms = input.split(QRegExp("[*/]"));
		QChar c = '*';
		i = 0;
		double v = 1.0;
		for(int terms_i = 0; terms_i < terms.size(); terms_i++) {
			if(terms[terms_i].isEmpty()) {
				if(c == '/') {
					errors << tr("Empty denominator.");
				} else {
					errors << tr("Empty factor.");
				}
			} else {
				i += terms[terms_i].length();
				if(c == '/') {
					double den = fixup_sub(terms[terms_i], errors, calculated);
					if(den == 0.0) {
						errors << tr("Division by zero.");
					} else {
						v /= den;
					}
				} else {
					v *= fixup_sub(terms[terms_i], errors, calculated);
				}
				if(i < input.length()) c = input[i];
			}
			i++;
		}
		calculated = true;
		return v;
	}
	i = input.indexOf(QLocale().percent());
	if(i >= 0) {
		double v = 0.01;
		if(input.length() > 1) {
			if(i > 0 && i < input.length() - 1) {
				QString str = input.right(input.length() - 1 - i);
				input = input.left(i);
				i = 0;
				v = fixup_sub(str, errors, calculated) * v;
			} else if(i == input.length() - 1) {
				input = input.left(i);
			} else if(i == 0) {
				input = input.right(input.length() - 1);
			}
			v = fixup_sub(input, errors, calculated) * v;
		}
		calculated = true;
		return v;
	}	
	if(o_currency) {
		QString reg_exp_str = "[\\d\\+\\-\\^";
		reg_exp_str += '\\';
		reg_exp_str += budget->monetary_decimal_separator;
		reg_exp_str += '\\';
		reg_exp_str += budget->monetary_group_separator;
		if(budget->monetary_decimal_separator != "." && budget->monetary_group_separator != ".") {
			reg_exp_str += '\\';
			reg_exp_str += '.';
		}
		reg_exp_str += "]";
		int i = input.indexOf(QRegExp(reg_exp_str));
		if(i >= 1) {
			QString scur = input.left(i).trimmed();
			Currency *cur = budget->findCurrency(scur);
			if(!cur && budget->defaultCurrency()->symbol(false) == scur) cur = budget->defaultCurrency();
			if(!cur) cur = budget->findCurrencySymbol(scur, true);
			if(cur) {
				QString value = input.right(input.length() - i);				
				double v = fixup_sub(value, errors, calculated);
				if(cur != o_currency) {
					v = cur->convertTo(v, o_currency);
				}
				calculated = true;
				return v;
			}
			errors << tr("Unknown or ambiguous currency, or unrecognized characters, in expression: %1.").arg(scur);
		}
		if(i >= 0) {
			i = input.lastIndexOf(QRegExp(reg_exp_str));
			if(i >= 0 && i < input.length() - 1) {
				QString scur = input.right(input.length() - (i + 1)).trimmed();
				Currency *cur = budget->findCurrency(scur);
				if(!cur && budget->defaultCurrency()->symbol(false) == scur) cur = budget->defaultCurrency();
				if(!cur) cur = budget->findCurrencySymbol(scur, true);
				if(cur) {
					QString value = input.left(i + 1);
					double v = fixup_sub(value, errors, calculated);
					if(cur != o_currency) {
						v = cur->convertTo(v, o_currency);
					}
					calculated = true;
					return v;
				}
				errors << tr("Unknown or ambiguous currency, or unrecognized characters, in expression: %1.").arg(scur);
			}
		} else {
			Currency *cur = budget->findCurrency(input);
			if(!cur && budget->defaultCurrency()->symbol(false) == input) cur = budget->defaultCurrency();
			if(!cur) cur = budget->findCurrencySymbol(input, true);
			if(cur) {
				double v = 1.0;
				if(cur != o_currency) {
					v = cur->convertTo(v, o_currency);
				}
				calculated = true;
				return v;
			}
			errors << tr("Unknown or ambiguous currency, or unrecognized characters, in expression: %1.").arg(input);
		}
	}
	i = input.indexOf('^', 0);
	if(i >= 0 && i != input.length() - 1) {
		QString base = input.left(i);
		if(base.isEmpty()) {
			errors << tr("Empty base.");
		} else {
			QString exp = input.right(input.length() - (i + 1));
			double v;
			if(exp.isEmpty()) {
				errors << tr("Error"), tr("Empty exponent.");
				v = 1.0;
			} else {
				v = pow(fixup_sub(base, errors, calculated), fixup_sub(exp, errors, calculated));
			}
			calculated = true;
			return v;
		}
	}
	
	if(!o_currency) {
		QString reg_exp_str = "[^\\d\\+\\-";
		reg_exp_str += '\\';
		reg_exp_str += budget->decimal_separator;
		reg_exp_str += '\\';
		reg_exp_str += budget->group_separator;
		if(budget->decimal_separator != "." && budget->group_separator != ".") {
			reg_exp_str += '\\';
			reg_exp_str += '.';
		}
		reg_exp_str += "]";
		i = input.indexOf(QRegExp(reg_exp_str));
		if(i >= 0) {
			errors << tr("Unrecognized characters in expression.");
		}
		input.remove(budget->group_separator);
		input.replace(budget->decimal_separator, ".");
		return input.toDouble();
	}
	input.remove(budget->monetary_group_separator);
	input.replace(budget->monetary_decimal_separator, ".");
	return input.toDouble();
}
void LiteEditorWidget::keyPressEvent(QKeyEvent *e)
{
    if (!m_completer) {
        LiteEditorWidgetBase::keyPressEvent(e);
        return;
    }

    if (m_completer->popup()->isVisible()) {
        // The following keys are forwarded by the completer to the widget
        switch (e->key()) {
        case Qt::Key_Enter:
        case Qt::Key_Return:
        case Qt::Key_Escape:
        case Qt::Key_Tab:
        case Qt::Key_Backtab:
        case Qt::Key_Shift:
            e->ignore();
            return; // let the completer do default behavior
        case Qt::Key_N:
        case Qt::Key_P:
            if (e->modifiers() == Qt::ControlModifier) {
                e->ignore();
                return;
            }
        default:
            break;
        }
    }

    LiteEditorWidgetBase::keyPressEvent(e);

    bool isInImport = false;
    if (m_textLexer->isInStringOrComment(this->textCursor())) {
        isInImport = m_textLexer->isInImport(this->textCursor());
        if (!isInImport) {
            m_completer->hidePopup();
            return;
        }
    }

    const bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier);

    //always break if ctrl is pressed and there's a key
//    if (((e->modifiers() & Qt::ControlModifier) && !e->text().isEmpty())) {
//        return;
//    }
    if (e->modifiers() & Qt::ControlModifier) {
        if (!e->text().isEmpty()) {
            m_completer->hidePopup();
        }
        return;
    }

    if (e->key() == Qt::Key_Tab || e->key() == Qt::Key_Backtab) {
        return;
    }

    if (e->text().isEmpty()) {
        if (e->key() != Qt::Key_Backspace) {
            m_completer->hidePopup();
            return;
        }
    }
    //import line
    if (isInImport) {
        QString completionPrefix = importUnderCursor(textCursor());
        m_completer->setCompletionContext(LiteApi::CompleterImportContext);
        m_completer->setCompletionPrefix("");
        m_completer->startCompleter(completionPrefix);
        return;
    }

    //static QString eow("~!@#$%^&*()_+{}|:\"<>?,./;'[]\\-="); // end of word
    static QString eow("~!@#$%^&*()+{}|:\"<>?,/;'[]\\-="); // end of word
    bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift;
    QString completionPrefix = textUnderCursor(textCursor());
    if (completionPrefix.startsWith(".")) {
        completionPrefix.insert(0,'@');
    }

    if (hasModifier || e->text().isEmpty()||
                        ( completionPrefix.length() < m_completionPrefixMin && completionPrefix.right(1) != ".")
                        || eow.contains(e->text().right(1))) {
        if (m_completer->popup()->isVisible()) {
            m_completer->popup()->hide();
            //fmt.Print( -> Print
            if (e->text() == "(") {
                QTextCursor cur = textCursor();
                cur.movePosition(QTextCursor::Left);
                QString lastPrefix = textUnderCursor(cur);
                if (lastPrefix.startsWith(".")) {
                    lastPrefix.insert(0,"@");
                }
                if (!lastPrefix.isEmpty() &&
                        lastPrefix == m_completer->completionPrefix() ) {
                    if (lastPrefix == m_completer->currentCompletion() ||
                            lastPrefix.endsWith("."+m_completer->currentCompletion())) {
                        m_completer->updateCompleteInfo(m_completer->currentIndex());
                    }
                }
            }
        }
        return;
    }
    m_completer->setCompletionContext(LiteApi::CompleterCodeContext);
    emit completionPrefixChanged(completionPrefix,false);
    m_completer->startCompleter(completionPrefix);
}
Example #30
0
PGE_Size RasterFont::textSize(QString &text, int max_line_lenght, bool cut)
{
    if(text.isEmpty())
        return PGE_Size(0, 0);

    int lastspace = 0; //!< index of last found space character
    int count = 1;  //!< Count of lines
    int maxWidth = 0; //!< detected maximal width of message
    int widthSumm = 0;
    int widthSummMax = 0;

    if(cut)
    {
        for(int i = 0; i < text.size(); i++)
        {
            if(text[i] == QChar(QChar::LineFeed))
            {
                text.remove(i, text.size() - i);
                break;
            }
        }
    }

    /****************Word wrap*********************/
    for(int x = 0, i = 0; i < text.size(); i++, x++)
    {
        switch(text[i].toLatin1())
        {
        case '\t':
        case ' ':
            lastspace = i;
            widthSumm += space_width + interletter_space / 2;

            if(widthSumm > widthSummMax) widthSummMax = widthSumm;

            break;

        case '\n':
            lastspace = 0;

            if((maxWidth < x) && (maxWidth < max_line_lenght)) maxWidth = x;

            x = 0;
            widthSumm = 0;
            count++;
            break;

        default:
            RasChar rch = fontMap[text[i]];

            if(rch.valid)
            {
                widthSumm += (letter_width - rch.padding_left - rch.padding_right + interletter_space);

                if(widthSumm > widthSummMax) widthSummMax = widthSumm;
            }
            else
            {
                widthSumm += (letter_width + interletter_space);

                if(widthSumm > widthSummMax) widthSummMax = widthSumm;
            }

            break;
        }

        if((max_line_lenght > 0) && (x >= max_line_lenght)) //If lenght more than allowed
        {
            maxWidth = x;

            if(lastspace > 0)
            {
                text[lastspace] = '\n';
                i = lastspace - 1;
                lastspace = 0;
            }
            else
            {
                text.insert(i, QChar('\n'));
                x = 0;
                count++;
            }
        }
    }

    if(count == 1)
        maxWidth = text.length();

    /****************Word wrap*end*****************/
    return PGE_Size(widthSummMax, newline_offset * count);
}