Example #1
0
void MessagesDialog::sinkMessage( const MsgEvent *msg )
{
    QMutexLocker locker( &messageLocker );

    QPlainTextEdit *messages = ui.messages;
    /* Only scroll if the viewport is at the end.
       Don't bug user by auto-changing/losing viewport on insert(). */
    bool b_autoscroll = ( messages->verticalScrollBar()->value()
                          + messages->verticalScrollBar()->pageStep()
                          >= messages->verticalScrollBar()->maximum() );

    /* Copy selected text to the clipboard */
    if( messages->textCursor().hasSelection() )
        messages->copy();

    /* Fix selected text bug */
    if( !messages->textCursor().atEnd() ||
         messages->textCursor().anchor() != messages->textCursor().position() )
         messages->moveCursor( QTextCursor::End );

    /* Start a new logic block so we can hide it on-demand */
    messages->textCursor().insertBlock();

    QString buf = QString( "<i><font color='darkblue'>%1</font>" ).arg( msg->module );

    switch ( msg->priority )
    {
        case VLC_MSG_INFO:
            buf += "<font color='blue'> info: </font>";
            break;
        case VLC_MSG_ERR:
            buf += "<font color='red'> error: </font>";
            break;
        case VLC_MSG_WARN:
            buf += "<font color='green'> warning: </font>";
            break;
        case VLC_MSG_DBG:
        default:
            buf += "<font color='grey'> debug: </font>";
            break;
    }

    /* Insert the prefix */
    messages->textCursor().insertHtml( buf /* + "</i>" */ );

    /* Insert the message */
    messages->textCursor().insertHtml( msg->text );

    /* Pass the new message thru the filter */
    QTextBlock b = messages->document()->lastBlock();
    b.setVisible( matchFilter( b.text() ) );

    /* Tell the QTextDocument to recompute the size of the given area */
    messages->document()->markContentsDirty( b.position(), b.length() );

    if ( b_autoscroll ) messages->ensureCursorVisible();
}
QTextDocument *ReplaceDocument::fileDocument(const QString &fileName, QTextCursor &cursor, bool &crlf)
{
    LiteApi::IEditor *editor = m_liteApp->editorManager()->findEditor(fileName,true);
    if (editor) {
        QPlainTextEdit *ed = LiteApi::getPlainTextEdit(editor);
        if (ed) {
            cursor = ed->textCursor();
            return ed->document();
        }
    }
    QFile file(fileName);
    if (file.open(QFile::ReadOnly)) {
        QByteArray data = file.readAll();
        QString text = QString::fromUtf8(data);
        int lf = text.indexOf('\n');
        if (lf <= 0) {
            crlf = false;
        } else {
            lf = text.indexOf(QRegExp("[^\r]\n"),lf-1);
            if (lf >= 0) {
                crlf = false;
            } else {
                crlf = true;
            }
        }
        m_document = new QTextDocument(text);
        cursor = QTextCursor(m_document);
        return m_document;
    }
    return 0;
}
Example #3
0
Notepad::Notepad(MainWindow *main, QWidget *parent) :
    QDockWidget(parent),
    ui(new Ui::Notepad)
{
    ui->setupUi(this);

    // Radare core found in:
    this->main = main;

    highlighter = new MdHighlighter(ui->notepadTextEdit->document());
    ui->splitter->setStretchFactor(0, 2);
    isFirstTime = true;
    this->notesTextEdit = ui->notepadTextEdit;

    // Increase notes document inner margin
    QTextDocument *docu = this->notesTextEdit->document();
    docu->setDocumentMargin(10);
    // Increase preview notes document inner margin
    QPlainTextEdit *preview = ui->previewTextEdit;
    QTextDocument *preview_docu = preview->document();
    preview_docu->setDocumentMargin(10);

    // Context menu
    ui->notepadTextEdit->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->notepadTextEdit, SIGNAL(customContextMenuRequested(const QPoint &)),
            this, SLOT(showNotepadContextMenu(const QPoint &)));
}
//-------------------------------------------------------------------------
void MainWindow::checkSelection()
{
  QPlainTextEdit *sourceCode = getCurrentText();
  bool bHasSelect = sourceCode->textCursor().hasSelection();
  ui.actionCopy->setEnabled(bHasSelect);
  ui.actionCut->setEnabled(bHasSelect);
  ui.actionDelete->setEnabled(bHasSelect);

  ui.actionUndo->setEnabled(sourceCode->document()->isUndoAvailable());
  ui.actionRedo->setEnabled(sourceCode->document()->isRedoAvailable());
}
Example #5
0
void MessagesDialog::filterMessages()
{
    QMutexLocker locker( &messageLocker );
    QPlainTextEdit *messages = ui.messages;
    QTextBlock block = messages->document()->firstBlock();

    while( block.isValid() )
    {
        block.setVisible( matchFilter( block.text().toLower() ) );
        block = block.next();
    }

    /* Consider the whole QTextDocument as dirty now */
    messages->document()->markContentsDirty( 0, messages->document()->characterCount() );

    /* FIXME This solves a bug (Qt?) with the viewport not resizing the
       vertical scroll bar when one or more QTextBlock are hidden */
    QSize vsize = messages->viewport()->size();
    messages->viewport()->resize( vsize + QSize( 1, 1 ) );
    messages->viewport()->resize( vsize );
}
QTextDocument* QsvTextOperationsWidget::getTextDocument()
{
	QTextEdit *t = qobject_cast<QTextEdit*>(parent());
	if (t) {
		return t->document();
	} else {
		QPlainTextEdit *pt = qobject_cast<QPlainTextEdit*>(parent());
		if (pt) {
			return pt->document();
		}
	}
	return NULL;
}
//-------------------------------------------------------------------------
void MainWindow::insertTextAtLine(int lineNr, const char* pText)
{
  QPlainTextEdit *sourceCode = getCurrentSourceCode();
  if (lineNr >= 0)
  {
    QTextCursor sourceCursor = sourceCode->textCursor();
    sourceCursor.setPosition(sourceCode->document()->findBlockByLineNumber(lineNr).position());
    sourceCode->setTextCursor(sourceCursor);
  }
  else
  {
    sourceCode->moveCursor(QTextCursor::StartOfLine);
  }
  sourceCode->insertPlainText(QString::fromUtf8(pText));
}
Example #8
0
void PlainTextViewWidget::searchDocument(const QString &text, Qt::CaseSensitivity caseSensitive)
{
   m_currentSearchResult = QTextCursor();
   m_searchResults.clear();

   QTextDocument::FindFlags findFlags;
   if (caseSensitive == Qt::CaseSensitive) {
      findFlags |= QTextDocument::FindCaseSensitively;
   }

   QPlainTextEdit *textEdit = ui->plainTextEdit;
   QTextDocument *textDocument = textEdit->document();
   QTextCursor currentCursor = textEdit->textCursor();
   currentCursor.clearSelection(); // To get QTextDocument::find to work properly

   // Find all results forwards beginning from current cursor
   QTextCursor findCursor = textDocument->find(text, currentCursor, findFlags);
   if (!findCursor.isNull()) {
      // Set to first result after current cursor pos
      m_currentSearchResult = findCursor;
   }

   while (!findCursor.isNull()) {
      m_searchResults.append(findCursor);
      findCursor = textDocument->find(text, findCursor, findFlags);
   }

   // Find all results backwards beginning from current cursor
   findFlags |= QTextDocument::FindBackward;
   findCursor = textDocument->find(text, currentCursor, findFlags);
   while (!findCursor.isNull()) {
      m_searchResults.prepend(findCursor);
      findCursor = textDocument->find(text, findCursor, findFlags);
   }

   if (m_searchResults.isEmpty()) {
      ui->searchBar->setResultNumberAndCount(0, 0);
      return;
   }

   if (m_currentSearchResult.isNull()) {
      // Set to first result because after current cursor pos wasn't a search match
      m_currentSearchResult = m_searchResults.at(0);
   }

   jumpToHighlightResult(m_currentSearchResult);
}
Example #9
0
void FakeVimProxy::indentRegion(int beginBlock, int endBlock, QChar typedChar) {
    QPlainTextEdit *ed = qobject_cast<QPlainTextEdit *>(m_widget);
    if (!ed)
        return;

    const auto indentSize = theFakeVimSetting(FakeVim::Internal::ConfigShiftWidth)
            ->value().toInt();

    QTextDocument *doc = ed->document();
    QTextBlock startBlock = doc->findBlockByNumber(beginBlock);

    // Record line lengths for mark adjustments
    QVector<int> lineLengths(endBlock - beginBlock + 1);
    QTextBlock block = startBlock;

    for (int i = beginBlock; i <= endBlock; ++i) {
        const auto line = block.text();
        lineLengths[i - beginBlock] = line.length();
        if (typedChar.unicode() == 0 && line.simplified().isEmpty()) {
            // clear empty lines
            QTextCursor cursor(block);
            while (!cursor.atBlockEnd())
                cursor.deleteChar();
        } else {
            const auto previousBlock = block.previous();
            const auto previousLine = previousBlock.isValid() ? previousBlock.text() : QString();

            int indent = firstNonSpace(previousLine);
            if (typedChar == '}')
                indent = std::max(0, indent - indentSize);
            else if ( previousLine.endsWith("{") )
                indent += indentSize;
            const auto indentString = QString(" ").repeated(indent);

            QTextCursor cursor(block);
            cursor.beginEditBlock();
            cursor.movePosition(QTextCursor::StartOfBlock);
            cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, firstNonSpace(line));
            cursor.removeSelectedText();
            cursor.insertText(indentString);
            cursor.endEditBlock();
        }
        block = block.next();
    }
}
Example #10
0
//-------------------------------------------------------------------------
QPlainTextEdit* MainWindow::addNewTab(const QString& fileName)
{
  QFileInfo file(fileName);
  QString base = file.fileName();

  int tabIndex = 0;
  if (ui.tabWidget->count() == 1 && ui.tabWidget->tabToolTip(0).isEmpty())
  {
    ui.tabWidget->setTabText(0, base);
  }
  else
  {
    tabIndex = ui.tabWidget->addTab(createSourceTextEdit(), base);
  }

  ui.tabWidget->setCurrentIndex(tabIndex);
  ui.tabWidget->setTabToolTip(tabIndex, fileName);
  QPlainTextEdit *result = getCurrentSourceCode();
  new CPPHighlighter(result->document());
  return result;
}
Example #11
0
void FindEditor::findHelper(FindOption *opt)
{
    bool bFocus = m_findEdit->hasFocus();
    LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor();
    if (!editor) {
        return;
    }
    LiteApi::ITextEditor *textEditor = LiteApi::getTextEditor(editor);
    QTextCursor find;
    if (textEditor) {
        QPlainTextEdit *ed = LiteApi::getPlainTextEdit(editor);
        if (ed) {
            find = findEditor(ed->document(),ed->textCursor(),opt);
            if (!find.isNull()) {
                ed->setTextCursor(find);
            }
        }
    } else {
        QTextBrowser *ed = LiteApi::findExtensionObject<QTextBrowser*>(editor,"LiteApi.QTextBrowser");
        if (ed) {
            find = findEditor(ed->document(),ed->textCursor(),opt);
            if (!find.isNull()) {
                ed->setTextCursor(find);
            }
        }
    }
    if (find.isNull()) {
        m_status->setText(tr("Not find"));
    } else {
        m_status->setText(QString("Ln:%1 Col:%2").
                              arg(find.blockNumber()+1).
                              arg(find.columnNumber()+1));
    }
    if (bFocus) {
        m_findEdit->setFocus();
    } else if (textEditor) {
        textEditor->onActive();
    }
}
Example #12
0
void FakeVimProxy::highlightMatches(const QString &pattern) {
    QPlainTextEdit *ed = qobject_cast<QPlainTextEdit *>(m_widget);
    if (!ed)
        return;

    QTextCursor cur = ed->textCursor();

    QTextEdit::ExtraSelection selection;
    selection.format.setBackground(Qt::yellow);
    selection.format.setForeground(Qt::black);

    // Highlight matches.
    QTextDocument *doc = ed->document();
    QRegExp re(pattern);
    cur = doc->find(re);

    m_searchSelection.clear();

    int a = cur.position();
    while ( !cur.isNull() ) {
        if ( cur.hasSelection() ) {
            selection.cursor = cur;
            m_searchSelection.append(selection);
        } else {
            cur.movePosition(QTextCursor::NextCharacter);
        }
        cur = doc->find(re, cur);
        int b = cur.position();
        if (a == b) {
            cur.movePosition(QTextCursor::NextCharacter);
            cur = doc->find(re, cur);
            b = cur.position();
            if (a == b) break;
        }
        a = b;
    }

    updateExtraSelections();
}
QsvTextOperationsWidget::QsvTextOperationsWidget( QWidget *parent )
	: QObject(parent)
{
	setObjectName("QsvTextOperationWidget");
	m_gotoLine    = NULL;
	m_search      = NULL;
	m_replace     = NULL;
	m_document    = NULL;
	searchFormUi  = NULL;
	replaceFormUi = NULL;
	searchFoundColor	= QColor( "#DDDDFF" ); //QColor::fromRgb( 220, 220, 255)
	searchNotFoundColor	= QColor( "#FFAAAA" ); //QColor::fromRgb( 255, 102, 102) "#FF6666"
	
	m_replaceTimer.setInterval(100);
	m_replaceTimer.setSingleShot(true);
	connect(&m_replaceTimer,SIGNAL(timeout()),this,SLOT(updateReplaceInput()));

	// this one is slower, to let the user think about his action
	// this is a modifying command, unlike a passive search
	m_searchTimer.setInterval(250);
	m_searchTimer.setSingleShot(true);
	connect(&m_searchTimer,SIGNAL(timeout()),this,SLOT(updateSearchInput()));
	
	// TODO clean this up, this is too ugly to be in a constructor
	QTextEdit *t = qobject_cast<QTextEdit*>(parent);
	if (t) {
		m_document = t->document();
	}
	else {
		QPlainTextEdit *pt = qobject_cast<QPlainTextEdit*>(parent);
		if (pt) {
			m_document = pt->document();
		}
	}
	connect(parent,SIGNAL(widgetResized()),this,SLOT(adjustBottomWidget()));
	parent->installEventFilter(this);
}
Example #14
0
bool QgsAttributeEditor::retrieveValue( QWidget *widget, QgsVectorLayer *vl, int idx, QVariant &value )
{
  if ( !widget )
    return false;

  const QgsField &theField = vl->pendingFields()[idx];
  QgsVectorLayer::EditType editType = vl->editType( idx );
  bool modified = false;
  QString text;

  QSettings settings;
  QString nullValue = settings.value( "qgis/nullValue", "NULL" ).toString();

  QLineEdit *le = qobject_cast<QLineEdit *>( widget );
  if ( le )
  {
    text = le->text();
    modified = le->isModified();
    if ( text == nullValue )
    {
      text = QString::null;
    }
  }

  QTextEdit *te = qobject_cast<QTextEdit *>( widget );
  if ( te )
  {
    text = te->toHtml();
    modified = te->document()->isModified();
    if ( text == nullValue )
    {
      text = QString::null;
    }
  }

  QPlainTextEdit *pte = qobject_cast<QPlainTextEdit *>( widget );
  if ( pte )
  {
    text = pte->toPlainText();
    modified = pte->document()->isModified();
    if ( text == nullValue )
    {
      text = QString::null;
    }
  }

  QComboBox *cb = qobject_cast<QComboBox *>( widget );
  if ( cb )
  {
    if ( editType == QgsVectorLayer::UniqueValues ||
         editType == QgsVectorLayer::ValueMap ||
         editType == QgsVectorLayer::Classification ||
         editType == QgsVectorLayer::ValueRelation )
    {
      text = cb->itemData( cb->currentIndex() ).toString();
      if ( text == nullValue )
      {
        text = QString::null;
      }
    }
    else
    {
      text = cb->currentText();
    }
    modified = true;
  }

  QListWidget *lw = qobject_cast<QListWidget *>( widget );
  if ( lw )
  {
    if ( editType == QgsVectorLayer::ValueRelation )
    {
      text = '{';
      for ( int i = 0, n = 0; i < lw->count(); i++ )
      {
        if ( lw->item( i )->checkState() == Qt::Checked )
        {
          if ( n > 0 )
          {
            text.append( ',' );
          }
          text.append( lw->item( i )->data( Qt::UserRole ).toString() );
          n++;
        }
      }
      text.append( '}' );
    }
    else
    {
      text = QString::null;
    }
    modified = true;
  }

  QSpinBox *sb = qobject_cast<QSpinBox *>( widget );
  if ( sb )
  {
    text = QString::number( sb->value() );
  }

  QAbstractSlider *slider = qobject_cast<QAbstractSlider *>( widget );
  if ( slider )
  {
    text = QString::number( slider->value() );
  }

  QDoubleSpinBox *dsb = qobject_cast<QDoubleSpinBox *>( widget );
  if ( dsb )
  {
    text = QString::number( dsb->value() );
  }

  QCheckBox *ckb = qobject_cast<QCheckBox *>( widget );
  if ( ckb )
  {
    QPair<QString, QString> states = vl->checkedState( idx );
    text = ckb->isChecked() ? states.first : states.second;
  }

  QCalendarWidget *cw = qobject_cast<QCalendarWidget *>( widget );
  if ( cw )
  {
    text = cw->selectedDate().toString();
  }

  le = widget->findChild<QLineEdit *>();
  if ( le )
  {
    text = le->text();
  }

  switch ( theField.type() )
  {
    case QVariant::Int:
    {
      bool ok;
      int myIntValue = text.toInt( &ok );
      if ( ok && !text.isEmpty() )
      {
        value = QVariant( myIntValue );
        modified = true;
      }
      else if ( modified )
      {
        value = QVariant();
      }
    }
    break;
    case QVariant::LongLong:
    {
      bool ok;
      qlonglong myLongValue = text.toLong( &ok );
      if ( ok && !text.isEmpty() )
      {
        value = QVariant( myLongValue );
        modified = true;
      }
      else if ( modified )
      {
        value = QVariant();
      }
    }
    case QVariant::Double:
    {
      bool ok;
      double myDblValue = text.toDouble( &ok );
      if ( ok && !text.isEmpty() )
      {
        value = QVariant( myDblValue );
        modified = true;
      }
      else if ( modified )
      {
        value = QVariant();
      }
    }
    break;
    case QVariant::Date:
    {
      QDate myDateValue = QDate::fromString( text, Qt::ISODate );
      if ( myDateValue.isValid() && !text.isEmpty() )
      {
        value = myDateValue;
        modified = true;
      }
      else if ( modified )
      {
        value = QVariant();
      }
    }
    break;
    default: //string
      modified = true;
      value = QVariant( text );
      break;
  }

  return modified;
}
Example #15
0
void FindEditor::replaceHelper(LiteApi::ITextEditor *editor, FindOption *opt, int replaceCount)
{
    bool bFocus = m_replaceEdit->hasFocus();

    QPlainTextEdit *ed = LiteApi::getPlainTextEdit(editor);
    if (!ed) {
        return;
    }

    QTextCursor find;
    QTextCursor cursor = ed->textCursor();
    int line = cursor.blockNumber();
    int col = cursor.columnNumber();
    Qt::CaseSensitivity cs = Qt::CaseInsensitive;
    if (opt->matchCase) {
        cs = Qt::CaseSensitive;
    }
    if ( cursor.hasSelection() ) {
        QString text = cursor.selectedText();
        if (opt->useRegexp) {
            if (text.indexOf(QRegExp(opt->findText,cs),0) != -1) {
                find = cursor;
            }
        } else {
            if (text.indexOf(opt->findText,0,cs) != -1) {
                find = cursor;
            }
        }
    }
    int number = 0;
    bool wrap = opt->wrapAround;
    do {
        if (!find.isNull()) {
            number++;
            find.beginEditBlock();
            QString text = find.selectedText();
            if (opt->useRegexp) {
                text.replace(QRegExp(opt->findText,cs),opt->replaceText);
            } else {
                text.replace(opt->findText,opt->replaceText);
            }
            find.removeSelectedText();
            find.insertText(text);
            find.endEditBlock();
            ed->setTextCursor(find);
        }
        cursor = ed->textCursor();
        find = findEditor(ed->document(),cursor,opt,false);
        if (find.isNull() && wrap) {
            wrap = false;
            find = findEditor(ed->document(),cursor,opt,true);
        }
        if (opt->wrapAround && !wrap) {
            if (find.blockNumber() > line ||
                    (find.blockNumber() >= line && find.columnNumber() > col) )  {
                break;
            }
        }
        if (replaceCount != -1 && number >= replaceCount) {
            if (!find.isNull()) {
                ed->setTextCursor(find);
                m_status->setText(QString("Ln:%1 Col:%2").
                                      arg(find.blockNumber()+1).
                                      arg(find.columnNumber()+1));
            } else {
                m_status->setText(tr("Not find"));
            }
            break;
        }
    } while(!find.isNull());
    if (replaceCount == -1) {
        m_status->setText(QString("Replace:%1").arg(number));
    }

    if (bFocus) {
        m_replaceEdit->setFocus();
    } else if (editor) {
        editor->onActive();
    }
}
Example #16
0
void FindEditor::replaceHelper(LiteApi::ITextEditor *editor, FindOption *opt, int replaceCount)
{
    bool bFocus = m_replaceEdit->hasFocus();

    QPlainTextEdit *ed = LiteApi::getPlainTextEdit(editor);
    if (!ed) {
        return;
    }

    QTextCursor find;
    QTextCursor cursor = ed->textCursor();
    int startLine = cursor.blockNumber();
    int startColumn = cursor.columnNumber();
    Qt::CaseSensitivity cs = Qt::CaseInsensitive;
    if (opt->matchCase) {
        cs = Qt::CaseSensitive;
    }
    int from = cursor.position();
    if ( cursor.hasSelection() ) {
//        QString text = cursor.selectedText();
//        if (opt->useRegexp) {
//            if (text.indexOf(QRegExp(opt->findText,cs),0) != -1) {
//                find = cursor;
//            }
//        } else {
//            if (text.indexOf(opt->findText,0,cs) != -1) {
//                find = cursor;
//            }
//        }
        from = cursor.selectionStart();
        startColumn -= cursor.selectedText().length();
    }
    int number = 0;
    bool wrap = opt->wrapAround;
    ed->textCursor().beginEditBlock();
    do {
        if (!find.isNull()) {
            number++;
            //find.beginEditBlock();
            QString text = find.selectedText();
            bool changed = find.blockNumber() == startLine && find.columnNumber() < startColumn;
            if (changed) {
                startColumn -= text.length();
            }
            if (opt->useRegexp) {
                text.replace(QRegExp(opt->findText,cs),opt->replaceText);
            } else {
                text.replace(QRegExp(opt->findText,cs,QRegExp::FixedString),opt->replaceText);
            }
            find.removeSelectedText();
            from = find.position()+ text.length();
            find.insertText(text);
            //find.endEditBlock();
            //ed->setTextCursor(find);
            if (changed) {
                startColumn += text.length();
            }
        }
        //cursor = ed->textCursor();
        find = findEditorHelper(ed->document(),from,opt,false);
        if (find.isNull() && wrap) {
            wrap = false;
            find = findEditorHelper(ed->document(),0,opt,true);
        }
        if (!find.isNull() && opt->wrapAround && !wrap) {
             if (find.blockNumber() > startLine ||
                    (find.blockNumber() == startLine && (find.columnNumber()-find.selectedText().length()) >= startColumn) )  {
                break;
            }
        }
        if (replaceCount != -1 && number >= replaceCount) {
            if (!find.isNull()) {
                ed->setTextCursor(find);
                m_status->setText(QString("Ln:%1 Col:%2").
                                      arg(find.blockNumber()+1).
                                      arg(find.columnNumber()+1));
            } else {
                m_status->setText(tr("Not found"));
            }
            break;
        }
    } while(!find.isNull());
    ed->textCursor().endEditBlock();
    if (replaceCount == -1) {
        m_status->setText(QString("Replace:%1").arg(number));
    }

    if (bFocus) {
        m_replaceEdit->setFocus();
    } else if (editor) {
        editor->onActive();
    }
}