Esempio n. 1
0
void BinaryWidget::setData( const QByteArray &data )
{
  delete mMainWidget;

  QString mimetype;
  KMimeType::Ptr mime = KMimeType::findByContent( data );
  if ( mime && !mime->isDefault() )
    mimetype = mime->name();

  if ( !mimetype.isEmpty() ) {
    KParts::ReadOnlyPart *part = KParts::ComponentFactory::createPartInstanceFromQuery<KParts::ReadOnlyPart>( mimetype, QString(), this, this );
    if ( part ) {
      KTemporaryFile file;
      file.setAutoRemove(false);
      file.open();
      file.write( data );
      file.flush();
      part->openUrl( KUrl( file.fileName() ) );
      mMainWidget = part->widget();
    } else {
      mMainWidget = new QLabel( i18n( "No part found for visualization of mimetype %1", mimetype ), this );
    }

    mData = data;
    mSaveButton->setEnabled( true );
  } else {
    mMainWidget = new QLabel( i18n( "Got data of unknown mimetype" ), this );
  }

  mLayout->addWidget( mMainWidget, 0, 0, 3, 1);
  mMainWidget->show();
}
Esempio n. 2
0
void KShellCmdPlugin::slotExecuteShellCommand()
{
    KParts::ReadOnlyPart *part = qobject_cast<KParts::ReadOnlyPart *>(parent());
    if (!part)  {
        KMessageBox::sorry(0L, i18n("KShellCmdPlugin::slotExecuteShellCommand: Program error, please report a bug."));
        return;
    }

    KUrl url = KIO::NetAccess::mostLocalUrl(part->url(), NULL);
    if (!url.isLocalFile()) {
        KMessageBox::sorry(part->widget(), i18n("Executing shell commands works only on local directories."));
        return;
    }

    QString path;
    KParts::FileInfoExtension *ext = KParts::FileInfoExtension::childObject(part);

    if (ext && ext->hasSelection() && (ext->supportedQueryModes() & KParts::FileInfoExtension::SelectedItems)) {
        KFileItemList list = ext->queryFor(KParts::FileInfoExtension::SelectedItems);
        QStringList fileNames;
        Q_FOREACH (const KFileItem &item, list) {
            fileNames << item.name();
        }
        path = KShell::joinArgs(fileNames);
    }
Esempio n. 3
0
KParts::ReadOnlyPart *KGraphEditor::slotNewGraph()
{
  kDebug();
  KPluginFactory *factory = KPluginLoader("kgraphviewerpart").factory();
  if (!factory)
  {
    // if we couldn't find our Part, we exit since the Shell by
    // itself can't do anything useful
    KMessageBox::error(this, i18n("Could not find the KGraphViewer part."));
    kapp->quit();
    // we return here, cause kapp->quit() only means "exit the
    // next time we enter the event loop...
    return NULL;
  }
  KParts::ReadOnlyPart* part = factory->create<KParts::ReadOnlyPart>("kgraphviewerpart", this);
  KGraphViewerInterface *view = qobject_cast<KGraphViewerInterface *>(part);
  if (!view)
  {
    // This should not happen
    kError() << "Failed to get KPart" << endl;
    return NULL;
  }
  view->setReadWrite();

    QWidget *w = part->widget();
    m_widget->addTab(w, QIcon( DesktopIcon("kgraphviewer") ), "");
    m_widget->setCurrentWidget(w);
//     createGUI(view);

    m_tabsPartsMap[w] = part;
    m_tabsFilesMap[w] = "";
//     connect(this,SIGNAL(hide(KParts::Part*)),view,SLOT(slotHide(KParts::Part*)));
  slotSetActiveGraph(part);
  return part;
}
Esempio n. 4
0
void KShellCmdPlugin::slotExecuteShellCommand()
{
    KParts::ReadOnlyPart * part = dynamic_cast<KParts::ReadOnlyPart *>(parent());
    if ( !part )
    {
        KMessageBox::sorry(0L, i18n("KShellCmdPlugin::slotExecuteShellCommand: Program error, please report a bug."));
        return;
    }
    KUrl url = KIO::NetAccess::mostLocalUrl(part->url(),NULL);
    if ( !url.isLocalFile() )
    {
        KMessageBox::sorry(part->widget(),i18n("Executing shell commands works only on local directories."));
        return;
    }
    QString path;
#if 0 // to be ported if still needed
    if ( part->currentItem() )
    {
        // Putting the complete path to the selected file isn't really necessary,
        // since we'll cd to the directory first. But we do need to get the
        // complete relative path.
        path = KUrl::relativePath( url.path(),
                                   part->currentItem()->url().path() );
    }
    else
#endif
    {
        path = url.toLocalFile();
    }
   bool ok;
   QString cmd = KInputDialog::getText( i18nc("@title:window", "Execute Shell Command"),
      i18n( "Execute shell command in current directory:" ),
      KShell::quoteArg( path ), &ok, part->widget() );
   if ( ok )
   {
      QString chDir;
      chDir="cd ";
      chDir+=KShell::quoteArg(part->url().path());
      chDir+="; ";
      chDir+=cmd;

      KShellCommandDialog *shellCmdDialog=new KShellCommandDialog(i18n("Output from command: \"%1\"", cmd),chDir,part->widget(),true);
      shellCmdDialog->resize(500,300);
      shellCmdDialog->executeCommand();
      delete shellCmdDialog;
   }
}
Esempio n. 5
0
void KHTMLPluginKTTSD::slotReadOut()
{
    // The parent is a KParts::ReadOnlyPart (checked in constructor)
    KParts::ReadOnlyPart* part = static_cast<KParts::ReadOnlyPart *>(parent());

    if (!QDBusConnection::sessionBus().interface()->isServiceRegistered("org.kde.kttsd"))
    {
        QString error;
        if (KToolInvocation::startServiceByDesktopName("kttsd", QStringList(), &error)) {
            KMessageBox::error(part->widget(), error, i18nc("@title:window", "Starting Jovie Text-to-Speech Service Failed") );
            return;
        }
    }
    // Find out if KTTSD supports xhtml (rich speak).
    bool supportsXhtml = false;
    org::kde::KSpeech kttsd( "org.kde.kttsd", "/KSpeech", QDBusConnection::sessionBus() );
    QString talker = kttsd.defaultTalker();
    QDBusReply<int> reply = kttsd.getTalkerCapabilities2(talker);
    if ( !reply.isValid())
        kDebug() << "D-Bus call getTalkerCapabilities2() failed, assuming non-XHTML support.";
    else
    {
        supportsXhtml = reply.value() & KSpeech::tcCanParseHtml;
        if (supportsXhtml)
            kDebug() << "KTTS claims to support rich speak (XHTML to SSML).";
    }

    KParts::TextExtension* textExt = KParts::TextExtension::childObject(parent());
    QString query;
    const KParts::TextExtension::Format format = supportsXhtml ? KParts::TextExtension::HTML : KParts::TextExtension::PlainText;
    if (textExt->hasSelection()) {
        query = textExt->selectedText(format);
    } else {
        query = textExt->completeText(format);
    }

    // kDebug() << "query =" << query;

    reply = kttsd.say(query, KSpeech::soNone);
    if ( !reply.isValid()) {
        KMessageBox::sorry(part->widget(), i18n("The D-Bus call say() failed."),
                            i18nc("@title:window", "D-Bus Call Failed"));
    }
}
Esempio n. 6
0
QObject* FormModule::loadPart(QWidget* parent, const QString& name, const QUrl& url)
{
    //name e.g. "libkghostview"
    KPluginFactory* factory = KPluginLoader( name.toLatin1() ).factory();
    if( ! factory ) {
        kWarning() << QString("Kross::FormModule::loadPart: No such library \"%1\"").arg(name);
        return 0;
    }
    KParts::ReadOnlyPart* part = factory->create< KParts::ReadOnlyPart >( parent );
    if( ! part ) {
        kWarning() << QString("Kross::FormModule::loadPart: Library \"%1\" is not a KPart").arg(name);
        return 0;
    }
    if( url.isValid() )
        part->openUrl(url);
    if( parent && parent->layout() && part->widget() )
        parent->layout()->addWidget( part->widget() );
    return part;
}
Esempio n. 7
0
KStatusBar * StatusBarExtension::statusBar() const
{
  if ( !d->m_statusBar )  {
    KParts::ReadOnlyPart* part = qobject_cast<KParts::ReadOnlyPart*>(parent());
    QWidget* w = part ? part->widget() : 0;
    KMainWindow* mw = w ? qobject_cast<KMainWindow *>( w->topLevelWidget() ) : 0;
    if ( mw )
      d->m_statusBar = mw->statusBar();
  }
  return d->m_statusBar;
}
Esempio n. 8
0
KParts::ReadOnlyPart *KonqViewFactory::create( QWidget *parentWidget, QObject * parent )
{
    if ( !m_factory )
        return 0;

    KParts::ReadOnlyPart* part = m_factory->create<KParts::ReadOnlyPart>( parentWidget, parent, QString(), m_args );

    if ( !part ) {
        kError() << "No KParts::ReadOnlyPart created from" << m_libName;
    } else {
        QFrame* frame = qobject_cast<QFrame*>( part->widget() );
        if ( frame ) {
            frame->setFrameStyle( QFrame::NoFrame );
        }
    }
    return part;
}
Esempio n. 9
0
QWidget* createTerminalWidget(QWidget* parent = 0)
{
    KPluginFactory* factory = KPluginLoader("libkonsolepart").factory();
    KParts::ReadOnlyPart* part = factory ? (factory->create<KParts::ReadOnlyPart>(parent)) : 0;

    if (!part) {
        printf("Failed to initialize part\n");
        return 0;
    }

    TerminalInterface* terminal = qobject_cast<TerminalInterface*>(part);
    if (!terminal) {
        printf("Failed to initialize terminal\n");
        return 0;
    }

    terminal->showShellInDir(KUrl().path());
    terminal->sendInput("cd " + KShell::quoteArg(KUrl().path()) + '\n');
    terminal->sendInput("clear\n");
    return part->widget();
}
Esempio n. 10
0
QObject* KWebPluginFactory::create(const QString& _mimeType, const QUrl& url, const QStringList& argumentNames, const QStringList& argumentValues) const
{
    // Only attempt to find a KPart for the supported mime types...
    QVariantList arguments;
    const int count = argumentNames.count();

    for (int i = 0; i < count; ++i) {
        arguments << QString(argumentNames.at(i) + QL1S("=\"") + argumentValues.at(i) + QL1C('\"'));
    }

    QString mimeType (_mimeType.trimmed());
    // If no mimetype is provided, we do our best to correctly determine it here...
    if (mimeType.isEmpty()) {
      kDebug(800) << "Looking up missing mimetype for plugin resource:" << url;
      const KUrl reqUrl (url);
      KMimeType::Ptr ptr = KMimeType::findByUrl(reqUrl, 0, reqUrl.isLocalFile());
      if (ptr->isDefault())
          mimeType = ptr->name();

       // Disregard inode/* mime-types...
       if (mimeType.startsWith(QLatin1String("inode/"), Qt::CaseInsensitive))
          mimeType.clear();
       kDebug(800) << "Updated mimetype to" << mimeType;
    }

    KParts::ReadOnlyPart* part = 0;

    // Defer handling of flash content to QtWebKit's builtin viewer.
    // If you want to use/test KDE's nspluginviewer, comment out the
    // if statement below.
    if (!mimeType.isEmpty() && !excludedMimeType(mimeType))
        part = KMimeTypeTrader::createPartInstanceFromQuery<KParts::ReadOnlyPart>(mimeType, 0, parent(), QString(), arguments);

    kDebug(800) << "Asked for" << mimeType << "plugin, got" << part;

    if (part) {
        QMap<QString, QString> metaData = part->arguments().metaData();
        QString urlStr = url.toString(QUrl::RemovePath | QUrl::RemoveQuery | QUrl::RemoveFragment);
        metaData.insert("PropagateHttpHeader", "true");
        metaData.insert("referrer", urlStr);
        metaData.insert("cross-domain", urlStr);
        metaData.insert("main_frame_request", "TRUE");
        metaData.insert("ssl_activate_warnings", "TRUE");

        KWebPage *page = qobject_cast<KWebPage *>(parent());

        if (page) {
            const QString scheme = page->mainFrame()->url().scheme();
            if (page && (QString::compare(scheme, QL1S("https"), Qt::CaseInsensitive) == 0 ||
                         QString::compare(scheme, QL1S("webdavs"), Qt::CaseInsensitive) == 0))
              metaData.insert("ssl_was_in_use", "TRUE");
            else
              metaData.insert("ssl_was_in_use", "FALSE");
        }

        KParts::OpenUrlArguments openUrlArgs = part->arguments();
        openUrlArgs.metaData() = metaData;
        openUrlArgs.setMimeType(mimeType);
        part->setArguments(openUrlArgs);
        part->openUrl(url);
        return part->widget();
    }

    return 0;
}
Esempio n. 11
0
void GenHash::calcGenHash()
{
    sandbox_init();

    // cannot excute execve
    prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
    kDebug() << "execve" << execve("ls",NULL,NULL);

    if (child_pid){

        KParts::ReadOnlyPart * part = qobject_cast<KParts::ReadOnlyPart *>(parent());

        QFile file(KFileDialog::getOpenFileName(KUrl("kfiledialog:///konqueror"), i18n("*"), part->widget(), i18n("Open File To make MD5.")));

        if (!file.open(QIODevice::ReadOnly))
        {
            return;
        }

        // TODO QFile
        //char s[1024];

        // write file content
        {
            close(pipe_fd[0]);
            QByteArray s = file.readAll();
            char *ch = s.data();
            if (write(pipe_fd[1], ch, s.size()) < 0) {
                perror("write");
            }
            close(pipe_fd[1]);
        }

        //read result
        {
            close(pipe_result_fd[1]);
            char result[128];
            if (read(pipe_result_fd[0], &result[0], 128) < 0){
                perror("read");
            }
            close(pipe_result_fd[0]);

            KMessageBox::information(part->widget(),i18n("Md5 : %1").arg(QString(QByteArray(result, 128))));
        }

    }else{

        scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_KILL);
        seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(close), 0);
        seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(read), 3,
                                   SCMP_A0(SCMP_CMP_EQ, (scmp_datum_t)pipe_fd[0]),
                                   SCMP_A1(SCMP_CMP_EQ, (scmp_datum_t)buff),
                                   SCMP_A2(SCMP_CMP_LE, 1024));
        seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(write), 1,
                                    SCMP_CMP(0, SCMP_CMP_EQ, (scmp_datum_t)pipe_result_fd[1]));

        seccomp_load(ctx);
        seccomp_release(ctx);

        calcMD5();
    }
}
QObject* WebPluginFactory::create (const QString& _mimeType, const QUrl& url, const QStringList& argumentNames, const QStringList& argumentValues) const
{
    //kDebug() << _mimeType << url << argumentNames;
    QString mimeType (_mimeType.trimmed());
    if (mimeType.isEmpty()) {
        extractGuessedMimeType (url, &mimeType);
    }

    const bool noPluginHandling = WebKitSettings::self()->isInternalPluginHandlingDisabled();

    if (!noPluginHandling && WebKitSettings::self()->isLoadPluginsOnDemandEnabled()) {
        const uint id = pluginId(url, argumentNames, argumentValues);
        if (!mPluginsLoadedOnDemand.contains(id)) {
            FakePluginWidget* widget = new FakePluginWidget(id, url, mimeType);
            connect(widget, SIGNAL(pluginLoaded(uint)), this, SLOT(loadedPlugin(uint)));
            return widget;
        }
    }

    Q_ASSERT(mPart); // should never happen!!
    KParts::ReadOnlyPart* part = 0;
    QWebView* view = (mPart ? mPart->view() : 0);

    if (noPluginHandling || !excludedMimeType(mimeType)) {
        QWebFrame* frame = (view ? view->page()->currentFrame() : 0);
        if (frame) {
            part = createPartInstanceFrom(mimeType, argumentNames, argumentValues, view, frame);
        }
    }

    kDebug() << "Asked for" << mimeType << "plugin, got" << part;

    if (part) {
        connect (part->browserExtension(), SIGNAL (openUrlNotify()),
                 mPart->browserExtension(), SIGNAL (openUrlNotify()));

        connect (part->browserExtension(), SIGNAL (openUrlRequest (KUrl, KParts::OpenUrlArguments, KParts::BrowserArguments)),
                 mPart->browserExtension(), SIGNAL (openUrlRequest (KUrl, KParts::OpenUrlArguments, KParts::BrowserArguments)));

        // Check if this part is scriptable
        KParts::ScriptableExtension* scriptExt = KParts::ScriptableExtension::childObject(part);
        if (!scriptExt) {
            // Try to fall back to LiveConnectExtension compat
            KParts::LiveConnectExtension* lc = KParts::LiveConnectExtension::childObject(part);
            if (lc) {
                scriptExt = KParts::ScriptableExtension::adapterFromLiveConnect(part, lc);
            }
        }

        if (scriptExt) {
            scriptExt->setHost(KParts::ScriptableExtension::childObject(mPart));
        }

        QMap<QString, QString> metaData = part->arguments().metaData();
        QString urlStr = url.toString (QUrl::RemovePath | QUrl::RemoveQuery | QUrl::RemoveFragment);
        metaData.insert ("PropagateHttpHeader", "true");
        metaData.insert ("referrer", urlStr);
        metaData.insert ("cross-domain", urlStr);
        metaData.insert ("main_frame_request", "TRUE");
        metaData.insert ("ssl_activate_warnings", "TRUE");

        KWebPage *page = (view ? qobject_cast<KWebPage*>(view->page()) : 0);

        if (page) {
            const QString scheme = page->currentFrame()->url().scheme();
            if (page && (QString::compare (scheme, QL1S ("https"), Qt::CaseInsensitive) == 0 ||
                         QString::compare (scheme, QL1S ("webdavs"), Qt::CaseInsensitive) == 0))
                metaData.insert ("ssl_was_in_use", "TRUE");
            else
                metaData.insert ("ssl_was_in_use", "FALSE");
        }

        KParts::OpenUrlArguments openUrlArgs = part->arguments();
        openUrlArgs.metaData() = metaData;
        openUrlArgs.setMimeType(mimeType);
        part->setArguments(openUrlArgs);
        QMetaObject::invokeMethod(part, "openUrl", Qt::QueuedConnection, Q_ARG(KUrl, KUrl(url)));
        return part->widget();
    }

    return 0;
}
Esempio n. 13
0
//---------------------------------------------------------------------------
bool ProjectSession::saveToFile( const QString & sessionFileName, const QValueList< KDevPlugin * > plugins )
{
  QString section, keyword;
  QDomElement session = domdoc.documentElement();

  int nDocs = 0;
  QString docIdStr;

////  // read the information about the mainframe widget
////  QDomElement mainframeEl = session.namedItem("Mainframe").toElement();
////  if(mainframeEl.isNull()){
////    mainframeEl=domdoc.createElement("Mainframe");
////    session.appendChild( mainframeEl);
////  }
////  bool bMaxMode = ((QextMdiMainFrm*)m_pDocViewMan->parent())->isInMaximizedChildFrmMode();
////  mainframeEl.setAttribute("MaximizeMode", bMaxMode);


  // read the information about the documents
  QDomElement docsAndViewsEl = session.namedItem("DocsAndViews").toElement();
  if (docsAndViewsEl.isNull()) {
    docsAndViewsEl = domdoc.createElement("DocsAndViews");
    session.appendChild( docsAndViewsEl);
  }
  else {
    // we need to remove the old ones before memorizing the current ones (to avoid merging)
    QDomNode n = docsAndViewsEl.firstChild();
    while ( !n.isNull() ) {
      QDomNode toBeRemoved = n;
      n = n.nextSibling();
      docsAndViewsEl.removeChild(toBeRemoved);
    }
  }

	QPtrListIterator<KParts::Part> it( *PartController::getInstance()->parts() );
	for ( ; it.current(); ++it )
	{

		KParts::ReadOnlyPart* pReadOnlyPart = dynamic_cast<KParts::ReadOnlyPart*>(it.current());
		if (!pReadOnlyPart)
			continue;

		QString url = pReadOnlyPart->url().url();

		docIdStr.setNum(nDocs);
		QDomElement docEl = domdoc.createElement("Doc" + docIdStr);
		docEl.setAttribute( "URL", url);
		docsAndViewsEl.appendChild( docEl);
		nDocs++;
		docEl.setAttribute( "NumberOfViews", 1);

		QDomElement viewEl = domdoc.createElement( "View0");
		docEl.appendChild( viewEl);

		if ( dynamic_cast<HTMLDocumentationPart*>(pReadOnlyPart) )
		{
			viewEl.setAttribute("Type", "Documentation");
		}
		else if ( pReadOnlyPart->inherits("KTextEditor::Document") )
		{
			viewEl.setAttribute("Type", "Source");
			KTextEditor::ViewCursorInterface *iface = dynamic_cast<KTextEditor::ViewCursorInterface*>(pReadOnlyPart->widget());
			if (iface) {
				unsigned int line, col;
				iface->cursorPosition(&line, &col);
				viewEl.setAttribute( "line", line );
			}
			if ( KTextEditor::EncodingInterface * ei = dynamic_cast<KTextEditor::EncodingInterface*>( pReadOnlyPart ) )
			{
				QString encoding = ei->encoding();
				if ( !encoding.isNull() )
				{
					viewEl.setAttribute( "Encoding", encoding );
				}
			}
		}
		else
		{
			viewEl.setAttribute("Type", "Other");
		}
	}

/*
  QPtrListIterator<KParts::Part> it( *PartController::getInstance()->parts() );
  for ( ; it.current(); ++it ) {
////    QString partName = it.current()->name();
////    QMessageBox::information(0L,"",partName);

    KParts::ReadOnlyPart* pReadOnlyPart = dynamic_cast<KParts::ReadOnlyPart*>(it.current());
    if (!pReadOnlyPart)
      continue; // note: read-write parts are also a read-only part, they inherit from it

    HTMLDocumentationPart* pDocuPart = dynamic_cast<HTMLDocumentationPart*>(pReadOnlyPart);

    /// @todo Save relative path for project sharing?
    QString url = pReadOnlyPart->url().url();

    docIdStr.setNum(nDocs);
    QDomElement docEl = domdoc.createElement("Doc" + docIdStr);
    docEl.setAttribute( "URL", url);
    docsAndViewsEl.appendChild( docEl);
    nDocs++;
////    docEl.setAttribute( "Type", "???");
////    // get the view list
////    QPtrList<KWpEditorPartriteView> viewList = pDoc->viewList();
////    // write the number of views
////    docEl.setAttribute( "NumberOfViews", viewList.count());
    docEl.setAttribute( "NumberOfViews", 1);
    // loop over all views of this document
    int nView = 0;
////    KWriteView* pView = 0L;
    QString viewIdStr;
////    for (viewList.first(), nView = 0; viewList.current() != 0; viewList.next(), nView++) {
////      pView = viewList.current();
////      if (pView != 0L) {
        viewIdStr.setNum( nView);
        QDomElement viewEl = domdoc.createElement( "View"+viewIdStr);
        docEl.appendChild( viewEl);
        // focus?
////        viewEl.setAttribute("Focus", (((CEditWidget*)pView->parentWidget()) == m_pDocViewMan->currentEditView()));
        viewEl.setAttribute("Type", "???");

    QDomElement viewPropertiesEl = domdoc.createElement("AdditionalSettings");
    viewEl.appendChild(viewPropertiesEl);
    emit sig_saveAdditionalViewProperties(url, &viewPropertiesEl);

    if (pReadOnlyPart->inherits("KTextEditor::Document")) {
      KTextEditor::ViewCursorInterface *iface = dynamic_cast<KTextEditor::ViewCursorInterface*>(pReadOnlyPart->widget());
      if (iface) {
        unsigned int line, col;
        iface->cursorPosition(&line, &col);
        viewEl.setAttribute( "line", line );
      }
    }

    if (pDocuPart) {
      docEl.setAttribute( "context", pDocuPart->context() );
    }
  }
*/
  docsAndViewsEl.setAttribute("NumberOfDocuments", nDocs);


  // now also let the project-related plugins save their session stuff
  // read the information about the documents
  QDomElement pluginListEl = session.namedItem("pluginList").toElement();
  if (pluginListEl.isNull()) {
    pluginListEl = domdoc.createElement("pluginList");
    session.appendChild( pluginListEl);
  }
  else {
    // we need to remove the old ones before memorizing the current ones (to avoid merging)
    QDomNode n = pluginListEl.firstChild();
    while ( !n.isNull() ) {
      QDomNode toBeRemoved = n;
      n = n.nextSibling();
      pluginListEl.removeChild(toBeRemoved);
    }
  }

	QValueList<KDevPlugin*>::ConstIterator itt = plugins.begin();
	while( itt != plugins.end() )
	{
		KDevPlugin* pPlugin = (*itt);
		QString pluginName = pPlugin->instance()->instanceName();
		QDomElement pluginEl = domdoc.createElement(pluginName);

		// now plugin, save what you have!
		pPlugin->savePartialProjectSession(&pluginEl);

		// if the plugin wrote anything, accept itt for the session, otherwise forget itt
		if (pluginEl.hasChildNodes() || pluginEl.hasAttributes())
		{
			pluginListEl.appendChild(pluginEl);
		}
		++itt;
	}

  // Write it out to the session file on disc
  QFile f(sessionFileName);
  if ( f.open(IO_WriteOnly) ) {    // file opened successfully
    QTextStream t( &f );        // use a text stream
    t << domdoc.toCString();
    f.close();
  }
  initXMLTree();  // clear and initialize the tree again

  return true;
}
Esempio n. 14
0
MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags f)
    : KParts::MainWindow(parent, f)
    , m_recentFiles(0)
    , m_close(0)
    , m_allocatorModel(new QStringListModel(this))
    , m_newAllocator(0)
    , m_removeAllocator(0)
    , m_shortenTemplates(0)
    , m_selectPeak(0)
    , m_currentDocument(0)
    , m_dataTreeModel(new DataTreeModel(this))
    , m_dataTreeFilterModel(new FilteredDataTreeModel(m_dataTreeModel))
    , m_settingSelection(false)
{
    ui.setupUi(this);

    //BEGIN KGraphViewer
    bool haveGraphViewer = false;

    // NOTE: just check if kgraphviewer is available at runtime.
    // The former logic has been moved to DocumentWidget constructor.
#ifdef HAVE_KGRAPHVIEWER
    KPluginFactory *factory = KPluginLoader("kgraphviewerpart").factory();
    if (factory) {
        KParts::ReadOnlyPart* readOnlyPart = factory->create<KParts::ReadOnlyPart>("kgraphviewerpart", this);
        if (readOnlyPart) {
            readOnlyPart->widget()->hide();
            haveGraphViewer = true;
        }
    }
#endif

    if (!haveGraphViewer) {
        // cleanup UI when we installed with kgraphviewer but it's not available at runtime
        KToolBar* callgraphToolbar = toolBar(QStringLiteral("callgraphToolBar"));
        removeToolBar(callgraphToolbar);
        delete callgraphToolbar;
    }
    //END KGraphViewer

    ui.documents->setMovable(true);
    ui.documents->setTabsClosable(true);
    connect(ui.documents, &QTabWidget::currentChanged,
            this, &MainWindow::documentChanged);
    connect(ui.documents, &QTabWidget::tabCloseRequested,
            this, &MainWindow::closeFileTab);

    //BEGIN custom allocators
    tabifyDockWidget(ui.allocatorDock, ui.dataTreeDock);
    ui.allocatorView->setModel(m_allocatorModel);

    int iconSize = style()->pixelMetric(QStyle::PM_SmallIconSize);
    ui.dockMenuBar->setIconSize(QSize(iconSize, iconSize));
    ui.dockMenuBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
    ui.dockMenuBar->setFloatable(false);
    ui.dockMenuBar->setMovable(false);

    KConfigGroup cfg = allocatorConfig();
    m_allocatorModel->setStringList(cfg.entryMap().values());

    connect(m_allocatorModel, &QStringListModel::modelReset,
            this, &MainWindow::allocatorsChanged);

    connect(m_allocatorModel, &QStringListModel::dataChanged,
            this, &MainWindow::allocatorsChanged);

    connect(ui.dataTreeView, &QTreeView::customContextMenuRequested,
            this, &MainWindow::dataTreeContextMenuRequested);
    ui.dataTreeView->setContextMenuPolicy(Qt::CustomContextMenu);

    connect(ui.allocatorView, &QTreeView::customContextMenuRequested,
            this, &MainWindow::allocatorViewContextMenuRequested);
    ui.allocatorView->setContextMenuPolicy(Qt::CustomContextMenu);
    //END custom allocators

    setupActions();
    setupGUI(StandardWindowOptions(Default ^ StatusBar));
    statusBar()->hide();

    ui.dataTreeView->setModel(m_dataTreeFilterModel);

    connect(ui.filterDataTree, &KLineEdit::textChanged,
            m_dataTreeFilterModel, &FilteredDataTreeModel::setFilter);
    connect(ui.dataTreeView->selectionModel(), &QItemSelectionModel::currentChanged,
            this, &MainWindow::treeSelectionChanged);

    // open page
    ui.stackedWidget->setCurrentWidget(ui.openPage);
}
Esempio n. 15
0
bool KJSDebugWin::exception(ExecState *exec, const Value &value, bool inTryCatch)
{
    assert(value.isValid());

    // Ignore exceptions that will be caught by the script
    if(inTryCatch)
        return true;

    KParts::ReadOnlyPart *part = static_cast< ScriptInterpreter * >(exec->interpreter())->part();
    KHTMLPart *khtmlpart = ::qt_cast< KHTMLPart * >(part);
    if(khtmlpart && !khtmlpart->settings()->isJavaScriptErrorReportingEnabled())
        return true;

    QWidget *dlgParent = (m_evalDepth == 0) ? (QWidget *)part->widget() : (QWidget *)this;

    QString exceptionMsg = value.toString(exec).qstring();

    // Syntax errors are a special case. For these we want to display the url & lineno,
    // which isn't included in the exception messeage. So we work it out from the values
    // passed to sourceParsed()
    Object valueObj = Object::dynamicCast(value);
    Object syntaxError = exec->interpreter()->builtinSyntaxError();
    if(valueObj.isValid() && valueObj.get(exec, "constructor").imp() == syntaxError.imp())
    {
        Value sidValue = valueObj.get(exec, "sid");
        if(sidValue.isA(NumberType))
        { // sid is not set for Function() constructor
            int sourceId = (int)sidValue.toNumber(exec);
            assert(m_sourceFragments[sourceId]);
            exceptionMsg = i18n("Parse error at %1 line %2")
                               .arg(m_sourceFragments[sourceId]->sourceFile->url)
                               .arg(m_sourceFragments[sourceId]->baseLine + m_sourceFragments[sourceId]->errorLine - 1);
        }
    }

    bool dontShowAgain = false;
    if(m_execsCount == 0)
    {
        // An exception occurred and we're not currently executing any code... this can
        // happen in some cases e.g. a parse error, or native code accessing funcitons like
        // Object::put()
        QString msg = i18n("An error occurred while attempting to run a script on this page.\n\n%1").arg(exceptionMsg);
        KJSErrorDialog dlg(dlgParent, msg, false);
        dlg.exec();
        dontShowAgain = dlg.dontShowAgain();
    }
    else
    {
        Context ctx = m_execs[m_execsCount - 1]->context();
        SourceFragment *sourceFragment = m_sourceFragments[ctx.sourceId()];
        QString msg = i18n("An error occurred while attempting to run a script on this page.\n\n%1 line %2:\n%3")
                          .arg(KStringHandler::rsqueeze(sourceFragment->sourceFile->url, 80),
                               QString::number(sourceFragment->baseLine + ctx.curStmtFirstLine() - 1), exceptionMsg);

        KJSErrorDialog dlg(dlgParent, msg, true);
        dlg.exec();
        dontShowAgain = dlg.dontShowAgain();

        if(dlg.debugSelected())
        {
            m_mode = Next;
            m_steppingDepth = m_execsCount - 1;
            enterSession(exec);
        }
    }

    if(dontShowAgain)
    {
        KConfig *config = kapp->config();
        KConfigGroupSaver saver(config, QString::fromLatin1("Java/JavaScript Settings"));
        config->writeEntry("ReportJavaScriptErrors", QVariant(false, 0));
        config->sync();
        QByteArray data;
        kapp->dcopClient()->send("konqueror*", "KonquerorIface", "reparseConfiguration()", data);
    }

    return (m_mode != Stop);
}
void
InteractiveTerminalPage::onActivate()
{
    if ( m_termHostWidget )
        return;
    // For whatever reason, instead of simply linking against a library we
    // need to do a runtime query to KService just to get a sodding terminal
    // widget.
    KService::Ptr service = KService::serviceByDesktopName( "konsolepart" );
    if ( !service )
    {
        // And all of this hoping the Konsole application is installed. If not,
        // tough cookies.
        // Maybe linking against a library seemed too simple and elegant so
        // someone decided to have a terminal widget depend on over 9000 other
        // KDElibs things that have nothing to do with a terminal widget, and
        // have the loading happen at runtime so it's more likely to fail at
        // an inconvenient time.
        QMessageBox::critical( this,
                               tr( "Konsole not installed"),
                               tr( "Please install the kde konsole and try again!" ),
                               QMessageBox::Ok);
        return ;
    }

    // Create one instance of konsolepart.
    KParts::ReadOnlyPart* p =
        service->createInstance< KParts::ReadOnlyPart >( this,
                                                         this,
                                                         {} );
    if ( !p )
    {
        // One more opportunity for the loading operation to fail.
        QMessageBox::critical( this,
                               tr( "Konsole not installed"),
                               tr( "Please install the kde konsole and try again!" ),
                               QMessageBox::Ok);
        return;
    }

    // Cast the konsolepart to the TerminalInterface...
    TerminalInterface* t = qobject_cast< TerminalInterface* >( p );
    if ( !t )
    {
        // This is why we can't have nice things.
        QMessageBox::critical( this,
                               tr( "Konsole not installed"),
                               tr( "Please install the kde konsole and try again!" ),
                               QMessageBox::Ok);
        return;
    }

    // Make the widget persist even if the KPart goes out of scope...
    p->setAutoDeleteWidget( false );
    // ... but kill the KPart if the widget goes out of scope.
    p->setAutoDeletePart( true );

    m_termHostWidget = p->widget();
    m_layout->addWidget( m_termHostWidget );
    cDebug() << "Part widget ought to be"
             << m_termHostWidget->metaObject()->className();

    t->showShellInDir( QDir::home().path() );
    t->sendInput( QString( "%1\n" ).arg( m_command ) );
}