Example #1
0
NS_IMETHODIMP
nsClipboard::HasDataMatchingFlavors(const char** aFlavorList, uint32_t aLength,
                                    int32_t aWhichClipboard, bool *_retval)
{
    *_retval = false;
    if (aWhichClipboard != kGlobalClipboard)
        return NS_OK;

    // Which kind of data in the clipboard
    QClipboard *cb = QGuiApplication::clipboard();
    const QMimeData *mimeData = cb->mimeData();
    const char *flavor=nullptr;
    QStringList formats = mimeData->formats();
    for (uint32_t i = 0; i < aLength; ++i)
    {
        flavor = aFlavorList[i];
        if (flavor)
        {
            QString qflavor(flavor);

            if (strcmp(flavor,kTextMime) == 0)
            {
                NS_WARNING("DO NOT USE THE text/plain DATA FLAVOR ANY MORE. USE text/unicode INSTEAD");
            }

            // QClipboard says it has text/plain, mozilla wants to
            // know if the data is text/unicode -> interpret text/plain to text/unicode
            if (formats.contains(qflavor) ||
                strcmp(flavor, kUnicodeMime) == 0)
            {
                // A match has been found, return'
                *_retval = true;
                break;
            }
        }
    }
    return NS_OK;
}
void ClipboardSingleton::clipboardData(QVariant& data /* out */, ClipboardType& type /* out */)
{
    QClipboard *clipboard = QApplication::clipboard();
    const QMimeData *mime = clipboard->mimeData();

    type = NONE;

    if (mime->hasText())
    {
        data = mime->text();
        type = TEXT;
    }
    else if (mime->hasHtml())
    {
        data = mime->html();
        type = RICHTEXT;
    }
    else if (mime->hasImage())
    {
        data = mime->imageData();
        type = IMAGE;
    }
}
Example #3
0
void WizWebEnginePage::triggerAction(WizWebEnginePage::WebAction action, bool checked /*= false*/)
{
    QWebEnginePage::triggerAction(action, checked);
    //
    if (action == Copy)
    {
#ifdef Q_OS_MAC
        //fix
        //从webengine复制的文字,粘贴到mac的备忘录的时候,中文会乱码。
        //webengine复制到剪贴板的纯文字有bug,编码有问题。因此延迟等到webengine处理完成后再重新粘贴纯文本
        //避免这个错误
        //
        //
        QTimer::singleShot(500, [=]{
            //
            QClipboard* clipboard = QApplication::clipboard();
            const QMimeData *mimeData = clipboard->mimeData();
            QMimeData* newData = new QMimeData();
            for (auto format : mimeData->formats()) {
                //
                if (format == "text/html") {
                    //
                    QByteArray htmlData = mimeData->data(format);
                    QString html = QString::fromUtf8(htmlData);
                    html = "<meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\">" + html;
                    newData->setHtml(html);
                    //
                } else {
                    newData->setData(format, mimeData->data(format));
                }
            }
            //
            clipboard->setMimeData(newData);
        });
#endif
    }
}
Example #4
0
void pasteFilesFromClipboard(FmPath* destPath, QWidget* parent) {
  QClipboard* clipboard = QApplication::clipboard();
  const QMimeData* data = clipboard->mimeData();
  bool isCut = false;
  FmPathList* paths = NULL;

  if(data->hasFormat("x-special/gnome-copied-files")) {
    // Gnome, LXDE, and XFCE
    QByteArray gnomeData = data->data("x-special/gnome-copied-files");
    char* pdata = gnomeData.data();
    char* eol = strchr(pdata, '\n');

    if(eol) {
      *eol = '\0';
      isCut = (strcmp(pdata, "cut") == 0 ? true : false);
      paths = fm_path_list_new_from_uri_list(eol + 1);
    }
  }

  if(!paths && data->hasUrls()) {
    // The KDE way
    paths = Fm::pathListFromQUrls(data->urls());
    QByteArray cut = data->data("x-kde-cut-selection");

    if(!cut.isEmpty() && cut.at(0) == '1')
      isCut = true;
  }

  if(paths) {
    if(isCut)
      FileOperation::moveFiles(paths, destPath, parent);
    else
      FileOperation::copyFiles(paths, destPath, parent);

    fm_path_list_unref(paths);
  }
}
Example #5
0
void QgsComposerView::pasteItems( PasteMode mode )
{
  if ( !composition() )
  {
    return;
  }

  QDomDocument doc;
  QClipboard *clipboard = QApplication::clipboard();
  if ( doc.setContent( clipboard->mimeData()->data( "text/xml" ) ) )
  {
    QDomElement docElem = doc.documentElement();
    if ( docElem.tagName() == "ComposerItemClipboard" )
    {
      if ( composition() )
      {
        QPointF pt;
        if ( mode == QgsComposerView::PasteModeCursor || mode == QgsComposerView::PasteModeInPlace )
        {
          // place items at cursor position
          pt = mapToScene( mapFromGlobal( QCursor::pos() ) );
        }
        else
        {
          // place items in center of viewport
          pt = mapToScene( viewport()->rect().center() );
        }
        bool pasteInPlace = ( mode == PasteModeInPlace );
        composition()->addItemsFromXML( docElem, doc, 0, true, &pt, pasteInPlace );
      }
    }
  }

  //switch back to select tool so that pasted items can be moved/resized (#8958)
  setCurrentTool( QgsComposerView::Select );
}
/*!
 * Test Copy, Paste Rich Text.
 */
void Ut_MRichTextEdit::testCopyPaste()
{
    const char *text = "abcde";
    m_subject->setText(text);
    m_subject->setSelection(0, 3, false);

    QKeyEvent *event = new QKeyEvent(QEvent::KeyPress, Qt::Key_C, Qt::ControlModifier, QString(""));
    m_subject->keyPressEvent(event);

    QClipboard *clipboard = QApplication::clipboard();
    const QMimeData *mimeData = clipboard->mimeData();

    bool hasHtml = mimeData->hasHtml();
    QCOMPARE(hasHtml, true);

    QString htmlText = "<b>bold</b>";
    m_subject->document()->setHtml(htmlText);
    m_subject->setSelection(0, 4, false);

    event = new QKeyEvent(QEvent::KeyPress, Qt::Key_C, Qt::ControlModifier, QString(""));
    m_subject->keyPressEvent(event);

    htmlText = "text";
    m_subject->document()->setHtml(htmlText);

    QFont curFont = m_subject->currentFont();
    bool curBoldStyle = curFont.bold();
    QCOMPARE(curBoldStyle, false);
    delete event;

    event = new QKeyEvent(QEvent::KeyPress, Qt::Key_V, Qt::ControlModifier, QString(""));
    m_subject->keyPressEvent(event);

    curFont = m_subject->currentFont();
    curBoldStyle = curFont.bold();
    QCOMPARE(curBoldStyle, true);
    delete event;

    htmlText = "<i>italic</i>";
    m_subject->document()->setHtml(htmlText);
    m_subject->setSelection(0, 4, false);

    event = new QKeyEvent(QEvent::KeyPress, Qt::Key_C, Qt::ControlModifier, QString(""));
    m_subject->keyPressEvent(event);

    htmlText = "text";
    m_subject->document()->setHtml(htmlText);

    curFont = m_subject->currentFont();
    bool curItalicStyle = curFont.italic();
    QCOMPARE(curItalicStyle, false);
    delete event;

    event = new QKeyEvent(QEvent::KeyPress, Qt::Key_V, Qt::ControlModifier, QString(""));
    m_subject->keyPressEvent(event);

    curFont = m_subject->currentFont();
    curItalicStyle = curFont.italic();
    QCOMPARE(curItalicStyle, true);
    delete event;
    event = 0;
}
Example #7
0
void
NodeGraph::showMenu(const QPoint & pos)
{
    _imp->_menu->clear();

    QAction* findAction = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphFindNode,
                                                 kShortcutActionGraphFindNodeLabel, _imp->_menu);
    _imp->_menu->addAction(findAction);
    _imp->_menu->addSeparator();

    //QFont font(appFont,appFontSize);
    Menu* editMenu = new Menu(tr("Edit"), _imp->_menu);
    //editMenu->setFont(font);
    _imp->_menu->addAction( editMenu->menuAction() );

    QAction* copyAction = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphCopy,
                                                 kShortcutActionGraphCopyLabel, editMenu);
    QObject::connect( copyAction, SIGNAL(triggered()), this, SLOT(copySelectedNodes()) );
    editMenu->addAction(copyAction);

    QAction* cutAction = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphCut,
                                                kShortcutActionGraphCutLabel, editMenu);
    QObject::connect( cutAction, SIGNAL(triggered()), this, SLOT(cutSelectedNodes()) );
    editMenu->addAction(cutAction);


    QAction* pasteAction = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphPaste,
                                                  kShortcutActionGraphPasteLabel, editMenu);
    bool cbEnabled = false;
    {
        QClipboard* clipboard = QApplication::clipboard();
        const QMimeData* data = clipboard->mimeData();
        if (data && data->hasFormat(QLatin1String("text/plain"))) {
            cbEnabled = true;
        }
    }
    pasteAction->setEnabled(cbEnabled);
    editMenu->addAction(pasteAction);

    QAction* deleteAction = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphRemoveNodes,
                                                   kShortcutActionGraphRemoveNodesLabel, editMenu);
    QObject::connect( deleteAction, SIGNAL(triggered()), this, SLOT(deleteSelection()) );
    editMenu->addAction(deleteAction);

    QAction* renameAction = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphRenameNode,
                                                   kShortcutActionGraphRenameNodeLabel, editMenu);
    QObject::connect( renameAction, SIGNAL(triggered()), this, SLOT(renameNode()) );
    editMenu->addAction(renameAction);

    QAction* duplicateAction = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphDuplicate,
                                                      kShortcutActionGraphDuplicateLabel, editMenu);
    editMenu->addAction(duplicateAction);

    QAction* cloneAction = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphClone,
                                                  kShortcutActionGraphCloneLabel, editMenu);
    editMenu->addAction(cloneAction);

    QAction* decloneAction = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphDeclone,
                                                    kShortcutActionGraphDecloneLabel, editMenu);
    QObject::connect( decloneAction, SIGNAL(triggered()), this, SLOT(decloneSelectedNodes()) );
    editMenu->addAction(decloneAction);

    QAction* switchInputs = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphExtractNode,
                                                   kShortcutActionGraphExtractNodeLabel, editMenu);
    QObject::connect( switchInputs, SIGNAL(triggered()), this, SLOT(extractSelectedNode()) );
    editMenu->addAction(switchInputs);

    QAction* extractNode = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphSwitchInputs,
                                                  kShortcutActionGraphSwitchInputsLabel, editMenu);
    QObject::connect( extractNode, SIGNAL(triggered()), this, SLOT(switchInputs1and2ForSelectedNodes()) );
    editMenu->addAction(extractNode);

    QAction* disableNodes = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphDisableNodes,
                                                   kShortcutActionGraphDisableNodesLabel, editMenu);
    QObject::connect( disableNodes, SIGNAL(triggered()), this, SLOT(toggleSelectedNodesEnabled()) );
    editMenu->addAction(disableNodes);

    QAction* groupFromSel = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphMakeGroup,
                                                   kShortcutActionGraphMakeGroupLabel, editMenu);
    QObject::connect( groupFromSel, SIGNAL(triggered()), this, SLOT(createGroupFromSelection()) );
    editMenu->addAction(groupFromSel);

    QAction* expandGroup = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphExpandGroup,
                                                  kShortcutActionGraphExpandGroupLabel, editMenu);
    QObject::connect( expandGroup, SIGNAL(triggered()), this, SLOT(expandSelectedGroups()) );
    editMenu->addAction(expandGroup);

    QAction* displayCacheInfoAction = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphShowCacheSize,
                                                             kShortcutActionGraphShowCacheSizeLabel, _imp->_menu);
    displayCacheInfoAction->setCheckable(true);
    displayCacheInfoAction->setChecked( _imp->_cacheSizeText->isVisible() );
    QObject::connect( displayCacheInfoAction, SIGNAL(triggered()), this, SLOT(toggleCacheInfo()) );
    _imp->_menu->addAction(displayCacheInfoAction);

    NodesGuiList selectedNodes = getSelectedNodes();
    if ( !selectedNodes.empty() ) {
        QAction* turnOffPreviewAction = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphTogglePreview,
                                                               kShortcutActionGraphTogglePreviewLabel, _imp->_menu);
        turnOffPreviewAction->setCheckable(true);
        turnOffPreviewAction->setChecked(false);
        QObject::connect( turnOffPreviewAction, SIGNAL(triggered()), this, SLOT(togglePreviewsForSelectedNodes()) );
        _imp->_menu->addAction(turnOffPreviewAction);

        if (selectedNodes.size() == 1) {
            QAction* openNodePanelAction = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphOpenNodePanel,
                                                                  kShortcutActionGraphOpenNodePanelLabel, _imp->_menu);
            openNodePanelAction->setCheckable(true);
            openNodePanelAction->setChecked(false);
            QObject::connect( openNodePanelAction, SIGNAL(triggered()), this, SLOT(showSelectedNodeSettingsPanel()) );
            _imp->_menu->addAction(openNodePanelAction);
        }
    }

    QAction* autoHideInputs = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphAutoHideInputs,
                                                     kShortcutActionGraphAutoHideInputsLabel, _imp->_menu);
    autoHideInputs->setCheckable(true);
    autoHideInputs->setChecked( appPTR->getCurrentSettings()->areOptionalInputsAutoHidden() );
    QObject::connect( autoHideInputs, SIGNAL(triggered()), this, SLOT(toggleAutoHideInputs()) );
    _imp->_menu->addAction(autoHideInputs);

    QAction* hideInputs = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphHideInputs,
                                                 kShortcutActionGraphHideInputsLabel, _imp->_menu);
    hideInputs->setCheckable(true);
    bool hideInputsVal = false;
    if ( !selectedNodes.empty() ) {
        hideInputsVal = selectedNodes.front()->getNode()->getEffectInstance()->getHideInputsKnobValue();
    }
    hideInputs->setChecked(hideInputsVal);
    QObject::connect( hideInputs, SIGNAL(triggered()), this, SLOT(toggleHideInputs()) );
    _imp->_menu->addAction(hideInputs);


    QAction* knobLinks = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphShowExpressions,
                                                kShortcutActionGraphShowExpressionsLabel, _imp->_menu);
    knobLinks->setCheckable(true);
    knobLinks->setChecked( areKnobLinksVisible() );
    QObject::connect( knobLinks, SIGNAL(triggered()), this, SLOT(toggleKnobLinksVisible()) );
    _imp->_menu->addAction(knobLinks);

    QAction* autoPreview = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphToggleAutoPreview,
                                                  kShortcutActionGraphToggleAutoPreviewLabel, _imp->_menu);
    autoPreview->setCheckable(true);
    autoPreview->setChecked( getGui()->getApp()->getProject()->isAutoPreviewEnabled() );
    QObject::connect( autoPreview, SIGNAL(triggered()), this, SLOT(toggleAutoPreview()) );
    QObject::connect( getGui()->getApp()->getProject().get(), SIGNAL(autoPreviewChanged(bool)), autoPreview, SLOT(setChecked(bool)) );
    _imp->_menu->addAction(autoPreview);

    QAction* autoTurbo = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphToggleAutoTurbo,
                                                kShortcutActionGraphToggleAutoTurboLabel, _imp->_menu);
    autoTurbo->setCheckable(true);
    autoTurbo->setChecked( appPTR->getCurrentSettings()->isAutoTurboEnabled() );
    QObject::connect( autoTurbo, SIGNAL(triggered()), this, SLOT(toggleAutoTurbo()) );
    _imp->_menu->addAction(autoTurbo);


    QAction* forceRefreshPreviews = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphForcePreview,
                                                           kShortcutActionGraphForcePreviewLabel, _imp->_menu);
    QObject::connect( forceRefreshPreviews, SIGNAL(triggered()), this, SLOT(forceRefreshAllPreviews()) );
    _imp->_menu->addAction(forceRefreshPreviews);

    QAction* frameAllNodes = new ActionWithShortcut(kShortcutGroupNodegraph, kShortcutActionGraphFrameNodes,
                                                    kShortcutActionGraphFrameNodesLabel, _imp->_menu);
    QObject::connect( frameAllNodes, SIGNAL(triggered()), this, SLOT(centerOnAllNodes()) );
    _imp->_menu->addAction(frameAllNodes);

    _imp->_menu->addSeparator();

    std::list<ToolButton*> orederedToolButtons = getGui()->getToolButtonsOrdered();
    for (std::list<ToolButton*>::iterator it = orederedToolButtons.begin(); it != orederedToolButtons.end(); ++it) {
        (*it)->getMenu()->setIcon( (*it)->getMenuIcon() );
        _imp->_menu->addAction( (*it)->getMenu()->menuAction() );
    }

    QAction* ret = _imp->_menu->exec(pos);
    if (ret == findAction) {
        popFindDialog();
    } else if (ret == duplicateAction) {
        QRectF rect = visibleSceneRect();
        duplicateSelectedNodes( rect.center() );
    } else if (ret == cloneAction) {
        QRectF rect = visibleSceneRect();
        cloneSelectedNodes( rect.center() );
    } else if (ret == pasteAction) {
        QRectF rect = visibleSceneRect();
        pasteClipboard( rect.center() );
    }
} // NodeGraph::showMenu
void QgsComposerView::keyPressEvent( QKeyEvent * e )
{
  if ( e->key() == Qt::Key_Shift )
  {
    mShiftKeyPressed = true;
  }

  if ( !composition() )
  {
    return;
  }

  QList<QgsComposerItem*> composerItemList = composition()->selectedComposerItems();
  QList<QgsComposerItem*>::iterator itemIt = composerItemList.begin();

  if ( e->matches( QKeySequence::Copy ) || e->matches( QKeySequence::Cut ) )
  {
    QDomDocument doc;
    QDomElement documentElement = doc.createElement( "ComposerItemClipboard" );
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      // copy each item in a group
      QgsComposerItemGroup* itemGroup = dynamic_cast<QgsComposerItemGroup*>( *itemIt );
      if ( itemGroup && composition() )
      {
        QSet<QgsComposerItem*> groupedItems = itemGroup->items();
        QSet<QgsComposerItem*>::iterator it = groupedItems.begin();
        for ( ; it != groupedItems.end(); ++it )
        {
          ( *it )->writeXML( documentElement, doc );
        }
      }
      ( *itemIt )->writeXML( documentElement, doc );
      if ( e->matches( QKeySequence::Cut ) )
      {
        composition()->removeComposerItem( *itemIt );
      }
    }
    doc.appendChild( documentElement );
    QMimeData *mimeData = new QMimeData;
    mimeData->setData( "text/xml", doc.toByteArray() );
    QClipboard *clipboard = QApplication::clipboard();
    clipboard->setMimeData( mimeData );
  }

  if ( e->matches( QKeySequence::Paste ) )
  {
    QDomDocument doc;
    QClipboard *clipboard = QApplication::clipboard();
    if ( doc.setContent( clipboard->mimeData()->data( "text/xml" ) ) )
    {
      QDomElement docElem = doc.documentElement();
      if ( docElem.tagName() == "ComposerItemClipboard" )
      {
        if ( composition() )
        {
          QPointF pt = mapToScene( mapFromGlobal( QCursor::pos() ) );
          composition()->addItemsFromXML( docElem, doc, true, &pt );
        }
      }
    }
  }

  //delete selected items
  if ( e->key() == Qt::Key_Delete || e->key() == Qt::Key_Backspace )
  {
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      if ( composition() )
      {
        composition()->removeComposerItem( *itemIt );
      }
    }
  }

  else if ( e->key() == Qt::Key_Left )
  {
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      ( *itemIt )->move( -1.0, 0.0 );
    }
  }
  else if ( e->key() == Qt::Key_Right )
  {
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      ( *itemIt )->move( 1.0, 0.0 );
    }
  }
  else if ( e->key() == Qt::Key_Down )
  {
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      ( *itemIt )->move( 0.0, 1.0 );
    }
  }
  else if ( e->key() == Qt::Key_Up )
  {
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      ( *itemIt )->move( 0.0, -1.0 );
    }
  }
}
Example #9
0
// nsClipboard::GetNativeClipboardData ie. Paste
//
NS_IMETHODIMP
nsClipboard::GetNativeClipboardData(nsITransferable *aTransferable,
                                    QClipboard::Mode clipboardMode)
{
    if (nullptr == aTransferable)
    {
        NS_WARNING("GetNativeClipboardData: Transferable is null!");
        return NS_ERROR_FAILURE;
    }

    // get flavor list that includes all acceptable flavors (including
    // ones obtained through conversion)
    nsCOMPtr<nsISupportsArray> flavorList;
    nsresult errCode = aTransferable->FlavorsTransferableCanImport(
        getter_AddRefs(flavorList));

    if (NS_FAILED(errCode))
    {
        NS_WARNING("nsClipboard::GetNativeClipboardData(): no FlavorsTransferable!");
        return NS_ERROR_FAILURE;
    }

    QClipboard *cb = QGuiApplication::clipboard();
    const QMimeData *mimeData = cb->mimeData(clipboardMode);

    // Walk through flavors and see which flavor matches the one being pasted
    uint32_t flavorCount;
    flavorList->Count(&flavorCount);
    nsAutoCString foundFlavor;

    for (uint32_t i = 0; i < flavorCount; ++i)
    {
        nsCOMPtr<nsISupports> genericFlavor;
        flavorList->GetElementAt(i,getter_AddRefs(genericFlavor));
        nsCOMPtr<nsISupportsCString> currentFlavor(do_QueryInterface( genericFlavor) );

        if (currentFlavor)
        {
            nsXPIDLCString flavorStr;
            currentFlavor->ToString(getter_Copies(flavorStr));

            // Ok, so which flavor the data being pasted could be?
            // Text?
            if (!strcmp(flavorStr.get(), kUnicodeMime) && mimeData->hasText())
            {
                // Clipboard has text and flavor accepts text, so lets
                // handle the data as text
                foundFlavor = nsAutoCString(flavorStr);

                // Get the text data from clipboard
                QString text = mimeData->text();
                const QChar *unicode = text.unicode();
                // Is there a more correct way to get the size in UTF16?
                uint32_t len = (uint32_t) 2*text.size();

                // And then to genericDataWrapper
                nsCOMPtr<nsISupports> genericDataWrapper;
                nsPrimitiveHelpers::CreatePrimitiveForData(
                        foundFlavor.get(),
                        (void*)unicode,
                        len,
                        getter_AddRefs(genericDataWrapper));
                // Data is good, set it to the transferable
                aTransferable->SetTransferData(foundFlavor.get(),
                                               genericDataWrapper,len);
                // And thats all
                break;
            }

            // html?
            if (!strcmp(flavorStr.get(), kHTMLMime) && mimeData->hasHtml())
            {
                // Clipboard has text/html and flavor accepts text/html, so lets
                // handle the data as text/html
                foundFlavor = nsAutoCString(flavorStr);

                // Get the text data from clipboard
                QString html = mimeData->html();
                const QChar *unicode = html.unicode();
                // Is there a more correct way to get the size in UTF16?
                uint32_t len = (uint32_t) 2*html.size();

                // And then to genericDataWrapper
                nsCOMPtr<nsISupports> genericDataWrapper;
                nsPrimitiveHelpers::CreatePrimitiveForData(
                        foundFlavor.get(),
                        (void*)unicode,
                        len,
                        getter_AddRefs(genericDataWrapper));
                // Data is good, set it to the transferable
                aTransferable->SetTransferData(foundFlavor.get(),
                                               genericDataWrapper,len);
                // And thats all
                break;
            }

            // Image?
            if ((  !strcmp(flavorStr.get(), kJPEGImageMime)
                || !strcmp(flavorStr.get(), kJPGImageMime)
                || !strcmp(flavorStr.get(), kPNGImageMime)
                || !strcmp(flavorStr.get(), kGIFImageMime))
                && mimeData->hasImage())
            {
                // Try to retrieve an image from clipboard
                QImage image = cb->image();
                if(image.isNull())
                    continue;

                // Lets set the image format
                QByteArray imageFormat;
                if (!strcmp(flavorStr.get(), kJPEGImageMime) || !strcmp(flavorStr.get(), kJPGImageMime))
                    imageFormat = "jpeg";
                else if (!strcmp(flavorStr.get(), kPNGImageMime))
                    imageFormat = "png";
                else if (!strcmp(flavorStr.get(), kGIFImageMime))
                    imageFormat = "gif";
                else
                    continue;

                // Write image from clippboard to a QByteArrayBuffer
                QByteArray imageData;
                QBuffer imageBuffer(&imageData);
                QImageWriter imageWriter(&imageBuffer, imageFormat);
                if(!imageWriter.write(image))
                    continue;

                // Add the data to inputstream
                nsCOMPtr<nsIInputStream> byteStream;
                NS_NewByteInputStream(getter_AddRefs(byteStream), imageData.constData(),
                                      imageData.size(), NS_ASSIGNMENT_COPY);
                // Data is good, set it to the transferable
                aTransferable->SetTransferData(flavorStr, byteStream, sizeof(nsIInputStream*));

                imageBuffer.close();

                // And thats all
                break;
            }

            // Other mimetype?
            // Trying to forward the data "as is"
            if(mimeData->hasFormat(flavorStr.get()))
            {
                // get the data from the clipboard
                QByteArray clipboardData = mimeData->data(flavorStr.get());
                // And add it to genericDataWrapper
                nsCOMPtr<nsISupports> genericDataWrapper;
                nsPrimitiveHelpers::CreatePrimitiveForData(
                        foundFlavor.get(),
                        (void*) clipboardData.data(),
                        clipboardData.size(),
                        getter_AddRefs(genericDataWrapper));

                // Data is good, set it to the transferable
                aTransferable->SetTransferData(foundFlavor.get(),
                                               genericDataWrapper,clipboardData.size());
                // And thats all
                break;
            }
        }
    }

    return NS_OK;
}
Example #10
0
//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
void RicPasteFeatureImpl::referencesFromClipboard(std::vector<QString>& referenceList)
{
    QClipboard* clipboard = QApplication::clipboard();
    if (!clipboard) return;

    const MimeDataWithReferences* mimeDataReferences = dynamic_cast<const MimeDataWithReferences*>(clipboard->mimeData());
    if (!mimeDataReferences) return;

    referenceList = mimeDataReferences->references();
}
Example #11
0
void VerifyMessageWindow::on_pastePushButton_clicked()
{
    QClipboard *clipboard = QApplication::clipboard();
    if (clipboard->mimeData()->hasText())
        inputTextEdit->setText(clipboard->text());
}
Example #12
0
bool TextObjectEditorHelper::keyPressEvent(QKeyEvent* event)
{
// FIXME: repair weird Shift+Left/Right - needs some cursor position
	if (event->key() == Qt::Key_Backspace)
	{
		QString text = object->getText();
		
		if (selection_end == 0)
			return false;
		if (selection_end != selection_start)
		{
			text.remove(selection_start, selection_end - selection_start);
			selection_end = selection_start;
		}
		else
		{
			text.remove(selection_start - 1, 1);
			--selection_end;
			--selection_start;
		}
		object->setText(text);
		emit(selectionChanged(true));
	}
	else if (event->key() == Qt::Key_Delete)
	{
		QString text = object->getText();
		
		if (selection_start == text.size())
			return false;
		if (selection_end != selection_start)
		{
			text.remove(selection_start, selection_end - selection_start);
			selection_end = selection_start;
		}
		else
			text.remove(selection_start, 1);
		object->setText(text);
		emit(selectionChanged(true));
	}
	else if (event->matches(QKeySequence::MoveToPreviousChar) || event->matches(QKeySequence::SelectPreviousChar))
	{
		if (selection_start == 0)
		{
			if (selection_end != 0)
			{
				selection_end = 0;
				emit(selectionChanged(false));
			}
			return true;
		}
		--selection_start;
		if (!event->matches(QKeySequence::SelectPreviousChar))
			selection_end = selection_start;
		emit(selectionChanged(false));
	}
	else if (event->matches(QKeySequence::MoveToNextChar) || event->matches(QKeySequence::SelectNextChar))
	{
		if (selection_end == object->getText().length())
		{
			if (selection_start != object->getText().length())
			{
				selection_start = object->getText().length();
				emit(selectionChanged(false));
			}
			return true;
		}
		++selection_end;
		if (!event->matches(QKeySequence::SelectNextChar))
			selection_start = selection_end;
		emit(selectionChanged(false));
	}
	else if (event->matches(QKeySequence::MoveToPreviousLine) || event->matches(QKeySequence::SelectPreviousLine))
	{
		int line_num = object->findLineForIndex(selection_start);
		TextObjectLineInfo* line_info = object->getLineInfo(line_num);
		if (line_info->start_index == 0)
			return true;
		
		double x = line_info->getX(selection_start);
		TextObjectLineInfo* prev_line_info = object->getLineInfo(line_num-1);
		double y = prev_line_info->line_y;
		x = qMax( prev_line_info->line_x, qMin(x, prev_line_info->line_x + prev_line_info->width));
		
		selection_start = object->calcTextPositionAt(QPointF(x,y), false);
		if (!event->matches(QKeySequence::SelectPreviousLine))
			selection_end = selection_start;
		emit(selectionChanged(false));
	}
	else if (event->matches(QKeySequence::MoveToNextLine) || event->matches(QKeySequence::SelectNextLine))
	{
		int line_num = object->findLineForIndex(selection_end);
		TextObjectLineInfo* line_info = object->getLineInfo(line_num);
		if (line_info->end_index >= object->getText().length())
			return true;
		
		double x = line_info->getX(selection_end);
		TextObjectLineInfo* next_line_info = object->getLineInfo(line_num+1);
		double y = next_line_info->line_y;
		x = qMax( next_line_info->line_x, qMin(x, next_line_info->line_x + next_line_info->width));
		
		selection_end = object->calcTextPositionAt(QPointF(x,y), false);
		if (!event->matches(QKeySequence::SelectNextLine))
			selection_start = selection_end;
		emit(selectionChanged(false));
	}
	else if (event->matches(QKeySequence::MoveToStartOfLine) || event->matches(QKeySequence::SelectStartOfLine) ||
		     event->matches(QKeySequence::MoveToStartOfDocument) || event->matches(QKeySequence::SelectStartOfDocument))
	{
		int destination = (event->matches(QKeySequence::MoveToStartOfDocument) || event->matches(QKeySequence::SelectStartOfDocument)) ?
		                      0 : (object->findLineInfoForIndex(selection_start).start_index);
		if (event->matches(QKeySequence::SelectStartOfLine) || event->matches(QKeySequence::SelectStartOfDocument))
		{
			if (selection_start == destination)
				return true;
			selection_start = destination;
		}
		else
		{
			if (selection_end == destination)
				return true;
			selection_start = destination;
			selection_end = destination;
		}
		emit(selectionChanged(false));
	}
	else if (event->matches(QKeySequence::MoveToEndOfLine) || event->matches(QKeySequence::SelectEndOfLine) ||
		     event->matches(QKeySequence::MoveToEndOfDocument) || event->matches(QKeySequence::SelectEndOfDocument))
	{
		int destination;
		if (event->matches(QKeySequence::MoveToEndOfDocument) || event->matches(QKeySequence::SelectEndOfDocument))
			destination = object->getText().length();
		else
			destination = object->findLineInfoForIndex(selection_start).end_index;
		
		if (event->matches(QKeySequence::SelectEndOfLine) || event->matches(QKeySequence::SelectEndOfDocument))
		{
			if (selection_end == destination)
				return true;
			selection_end = destination;
		}
		else
		{
			if (selection_start == destination)
				return true;
			selection_start = destination;
			selection_end = destination;
		}
		emit(selectionChanged(false));
	}
	else if (event->matches(QKeySequence::SelectAll))
	{
		if (selection_start == 0 && selection_end == object->getText().length())
			return true;
		selection_start = 0;
		selection_end = object->getText().length();
		emit(selectionChanged(false));
	}
	else if (event->matches(QKeySequence::Copy) || event->matches(QKeySequence::Cut))
	{
		if (selection_end - selection_start > 0)
		{
			QClipboard* clipboard = QApplication::clipboard();
			clipboard->setText(object->getText().mid(selection_start, selection_end - selection_start));
			
			if (event->matches(QKeySequence::Cut))
				insertText(QString{});
		}
	}
	else if (event->matches(QKeySequence::Paste))
	{
		QClipboard* clipboard = QApplication::clipboard();
		const QMimeData* mime_data = clipboard->mimeData();
		
		if (mime_data->hasText())
			insertText(clipboard->text());
	}
	else if (event->key() == Qt::Key_Tab)
		insertText(QString(QLatin1Char('\t')));
	else if (event->key() == Qt::Key_Return)
		insertText(QString(QLatin1Char('\n')));
	else if (!event->text().isEmpty() && event->text()[0].isPrint() )
		insertText(event->text());
	else
		return false;
	return true;
}
void QgsComposerView::keyPressEvent( QKeyEvent * e )
{
  //TODO : those should be actions (so we could also display menu items and/or toolbar items)

  if ( !composition() )
  {
    return;
  }

  QList<QgsComposerItem*> composerItemList = composition()->selectedComposerItems();
  QList<QgsComposerItem*>::iterator itemIt = composerItemList.begin();

  if ( e->matches( QKeySequence::Copy ) || e->matches( QKeySequence::Cut ) )
  {
    QDomDocument doc;
    QDomElement documentElement = doc.createElement( "ComposerItemClipboard" );
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      // copy each item in a group
      QgsComposerItemGroup* itemGroup = dynamic_cast<QgsComposerItemGroup*>( *itemIt );
      if ( itemGroup && composition() )
      {
        QSet<QgsComposerItem*> groupedItems = itemGroup->items();
        QSet<QgsComposerItem*>::iterator it = groupedItems.begin();
        for ( ; it != groupedItems.end(); ++it )
        {
          ( *it )->writeXML( documentElement, doc );
        }
      }
      ( *itemIt )->writeXML( documentElement, doc );
      if ( e->matches( QKeySequence::Cut ) )
      {
        composition()->removeComposerItem( *itemIt );
      }
    }
    doc.appendChild( documentElement );

    //if it's a copy, we have to remove the UUIDs since we don't want any duplicate UUID
    if ( e->matches( QKeySequence::Copy ) )
    {
      // remove all uuid attributes
      QDomNodeList composerItemsNodes = doc.elementsByTagName( "ComposerItem" );
      for ( int i = 0; i < composerItemsNodes.count(); ++i )
      {
        QDomNode composerItemNode = composerItemsNodes.at( i );
        if ( composerItemNode.isElement() )
        {
          composerItemNode.toElement().removeAttribute( "uuid" );
        }
      }
    }

    QMimeData *mimeData = new QMimeData;
    mimeData->setData( "text/xml", doc.toByteArray() );
    QClipboard *clipboard = QApplication::clipboard();
    clipboard->setMimeData( mimeData );
  }

  //TODO : "Ctrl+Shift+V" is one way to paste, but on some platefoms you can use Shift+Ins and F18
  if ( e->matches( QKeySequence::Paste ) || ( e->key() == Qt::Key_V && e->modifiers() & Qt::ControlModifier && e->modifiers() & Qt::ShiftModifier ) )
  {
    QDomDocument doc;
    QClipboard *clipboard = QApplication::clipboard();
    if ( doc.setContent( clipboard->mimeData()->data( "text/xml" ) ) )
    {
      QDomElement docElem = doc.documentElement();
      if ( docElem.tagName() == "ComposerItemClipboard" )
      {
        if ( composition() )
        {
          QPointF pt = mapToScene( mapFromGlobal( QCursor::pos() ) );
          bool pasteInPlace = ( e->modifiers() & Qt::ShiftModifier );
          composition()->addItemsFromXML( docElem, doc, 0, true, &pt, pasteInPlace );
        }
      }
    }
  }

  //delete selected items
  if ( e->key() == Qt::Key_Delete || e->key() == Qt::Key_Backspace )
  {
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      if ( composition() )
      {
        composition()->removeComposerItem( *itemIt );
      }
    }
  }

  else if ( e->key() == Qt::Key_Left )
  {
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      ( *itemIt )->beginCommand( tr( "Item moved" ), QgsComposerMergeCommand::ItemMove );
      ( *itemIt )->move( -1.0, 0.0 );
      ( *itemIt )->endCommand();
    }
  }
  else if ( e->key() == Qt::Key_Right )
  {
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      ( *itemIt )->beginCommand( tr( "Item moved" ), QgsComposerMergeCommand::ItemMove );
      ( *itemIt )->move( 1.0, 0.0 );
      ( *itemIt )->endCommand();
    }
  }
  else if ( e->key() == Qt::Key_Down )
  {
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      ( *itemIt )->beginCommand( tr( "Item moved" ), QgsComposerMergeCommand::ItemMove );
      ( *itemIt )->move( 0.0, 1.0 );
      ( *itemIt )->endCommand();
    }
  }
  else if ( e->key() == Qt::Key_Up )
  {
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      ( *itemIt )->beginCommand( tr( "Item moved" ), QgsComposerMergeCommand::ItemMove );
      ( *itemIt )->move( 0.0, -1.0 );
      ( *itemIt )->endCommand();
    }
  }
}
Example #14
0
// nsClipboard::GetNativeClipboardData ie. Paste
//
NS_IMETHODIMP
nsClipboard::GetNativeClipboardData(nsITransferable *aTransferable,
                                    QClipboard::Mode clipboardMode)
{
    if (nsnull == aTransferable)
    {
        qDebug("  GetNativeClipboardData: Transferable is null!");
        return NS_ERROR_FAILURE;
    }

    // get flavor list that includes all acceptable flavors (including
    // ones obtained through conversion)
    nsCOMPtr<nsISupportsArray> flavorList;
    nsresult errCode = aTransferable->FlavorsTransferableCanImport(
        getter_AddRefs(flavorList));

    if (NS_FAILED(errCode))
    {
        qDebug("nsClipboard::GetNativeClipboardData(): no FlavorsTransferable %i !",
               errCode);
        return NS_ERROR_FAILURE;
    }

    QClipboard *cb = QApplication::clipboard();
    const QMimeData *mimeData = cb->mimeData(clipboardMode);

    // Walk through flavors and see which flavor matches the one being pasted
    PRUint32 flavorCount;
    flavorList->Count(&flavorCount);
    nsCAutoString foundFlavor;

    for (PRUint32 i = 0; i < flavorCount; ++i)
    {
        nsCOMPtr<nsISupports> genericFlavor;
        flavorList->GetElementAt(i,getter_AddRefs(genericFlavor));
        nsCOMPtr<nsISupportsCString> currentFlavor(do_QueryInterface( genericFlavor) );

        if (currentFlavor)
        {
            nsXPIDLCString flavorStr;
            currentFlavor->ToString(getter_Copies(flavorStr));

            // Ok, so which flavor the data being pasted could be?
            // Text?
            if (!strcmp(flavorStr.get(), kUnicodeMime)) 
            {
                if (mimeData->hasText())
                {
                    // Clipboard has text and flavor accepts text, so lets
                    // handle the data as text
                    foundFlavor = nsCAutoString(flavorStr);

                    // Get the text data from clipboard
                    QString text = mimeData->text();
                    const QChar *unicode = text.unicode();
                    // Is there a more correct way to get the size in UTF16?
                    PRUint32 len = (PRUint32) 2*text.size();

                    // And then to genericDataWrapper
                    nsCOMPtr<nsISupports> genericDataWrapper;
                    nsPrimitiveHelpers::CreatePrimitiveForData(
                        foundFlavor.get(),
                        (void*)unicode,
                        len,
                        getter_AddRefs(genericDataWrapper));

                    // Data is good, set it to the transferable
                    aTransferable->SetTransferData(foundFlavor.get(),
                                                   genericDataWrapper,len);
                    // And thats all
                    break;
                }
            }

            // Image?
            if (!strcmp(flavorStr.get(), kJPEGImageMime)
             || !strcmp(flavorStr.get(), kPNGImageMime)
             || !strcmp(flavorStr.get(), kGIFImageMime))
            {
                qDebug("nsClipboard::GetNativeClipboardData(): Pasting image data not implemented!");
                break;
            }
        }
    }

    return NS_OK;
}
Example #15
0
void Widget::onClipboardUpdated()
{
    QClipboard *clip = qApp->clipboard();

    if (clip->mimeData()->hasImage()) {
        QImage image = clip->image();
        QSize origSize = image.size();
        const int minWidth = minimumWidth() - 20;
        const int minHeight = minimumHeight() - 20;
        if (image.width() <= image.height() && image.height() < minimumHeight() - 20) {
            image = image.scaledToHeight(minHeight);
        } else if (image.width() < minWidth) {
            image = image.scaledToWidth(minWidth);
        }
        if (image.width() > maximumWidth() - 10) {
            image = image.scaledToWidth(maximumWidth() - 10);
        }
        if (image.height() > maximumHeight() - 10) {
            image = image.scaledToHeight(maximumHeight() - 10);
        }

        {
            QPainter p(&image);
            QFont font;
            font.setPixelSize(15);
            p.setFont(font);
            QFontMetrics metrics(font);
            QString text = QString::number(origSize.width()) + "x" + QString::number(origSize.height());
            QRect rect = metrics.boundingRect(text).marginsAdded(QMargins(5, 5, 5, 5));
            rect.moveTopLeft(QPoint(0, 0));
            p.fillRect(rect, QColor(0, 0, 0, 128));
            p.setPen(Qt::white);
            p.drawText(rect, Qt::AlignCenter, text);
        }

        m_label->setPixmap(QPixmap::fromImage(image));
        resize(image.size());
        updateGeometry();
        m_hasTrimmed = false;
        return;
    }

    QString text = clip->text();

    const QStringList formats = clip->mimeData()->formats();
    bool onlyTextPlain = formats.contains("text/plain");
    if (onlyTextPlain) {
        for (const QString &format : formats) {
            // "Special" fake mimetypes to indicate multiselections etc.
            if (!format.contains('/') || format.toUpper() == format) {
                continue;
            }
            if (format == "text/plain" || format == "text/html") {
                continue;
            }
            onlyTextPlain = false;
            break;
        }

        QString trimmed = text.trimmed();

        if (onlyTextPlain && trimmed != text && !m_hasTrimmed) {
            clip->setText(trimmed);
            m_hasTrimmed = true;
            return;
        }
    }

    m_hasTrimmed = false;

    QFontMetrics metrics(font());

    QString filteredText;
    for (const QChar &c : text) {
        if ((c.isPrint() || c == '\n' || c == '\t') && (c.script() == QChar::Script_Latin || c.script() == QChar::Script_Common)) {
            filteredText += c;
            continue;
        }

        qDebug() << c << c.script() << c.category();

        filteredText += "0x" + QString::number(c.unicode(), 16);
    }
    text = filteredText;

    QRect boundingRect = QRect(0, 0, maximumWidth(), maximumHeight());
    boundingRect = metrics.boundingRect(boundingRect, Qt::TextWordWrap, text);
    boundingRect = boundingRect.marginsAdded(QMargins(20, 20, 20, 20));

    if (boundingRect.height() > maximumHeight()) {
        m_label->setWordWrap(false);

        QString newText;
        int h = metrics.height() * 2;
        for (const QString &line : text.split('\n')) {
            newText.append(metrics.elidedText(line, Qt::ElideRight, m_label->width() - 20) + '\n');
            h += metrics.height();
        }
        text = newText;
        boundingRect.setHeight(h);
    } else {
        m_label->setWordWrap(true);
    }
    resize(boundingRect.size());

    m_label->setText(text);
    m_label->setSelection(0, text.length());
    updateGeometry();
}