示例#1
0
// The access function for guarded QObject pointers.
static void *qpointer_access_func(sipSimpleWrapper *w, AccessFuncOp op)
{
#if QT_VERSION >= 0x040500
    QWeakPointer<QObject> *guard = reinterpret_cast<QWeakPointer<QObject> *>(w->data);
#else
    QObjectGuard *guard = reinterpret_cast<QObjectGuard *>(w->data);
#endif
    void *addr;

    switch (op)
    {
    case UnguardedPointer:
#if QT_VERSION >= 0x040500
        addr = guard->data();
#else
        addr = guard->unguarded;
#endif
        break;

    case GuardedPointer:
#if QT_VERSION >= 0x040500
        addr = guard->isNull() ? 0 : guard->data();
#else
        addr = (QObject *)guard->guarded;
#endif
        break;

    case ReleaseGuard:
        delete guard;
        addr = 0;
        break;
    }

    return addr;
}
示例#2
0
void LocationEditor::buttonClicked() {
    const QWeakPointer<LocationDialog> dialogPtr(new LocationDialog(this));
    if (LocationDialog *const dialog = dialogPtr.data()) {
        dialog->setLongitude(this->startLongitude);
        dialog->setLatitude(this->startLatitude);
        dialog->setAltitude(this->startAltitude);
        dialog->exec();
    }

    if (LocationDialog *const dialog = dialogPtr.data()) {
        const double lon = dialog->getLongitude();
        const double lat = dialog->getLatitude();
        const double alt = dialog->getAltitude();
        startAltitude = alt;
        startLongitude = lon;
        startLatitude = lat;
        if (dialog->okPressed()) {
            NoteTable ntable(global.db);
            if (lon == 0.0 && lat == 0.0) {
                setText(defaultText);
                ntable.resetGeography(currentLid, true);
            } else {
                setText(dialog->locationText());
                ntable.setGeography(currentLid, lon,lat,alt, true);
            }
        }
        delete dialog;
    }
}
void
MetaQueryWidget::populateComboBox( QStringList results )
{
    QObject* query = sender();
    if( !query )
        return;

    QWeakPointer<KComboBox> combo = m_runningQueries.value(query);
    if( combo.isNull() )
        return;

    // note: adding items seems to reset the edit text, so we have
    //   to take care of that.
    disconnect( combo.data(), 0, this, 0 );

    // want the results unique and sorted
    const QSet<QString> dataSet = results.toSet();
    QStringList dataList = dataSet.toList();
    dataList.sort();
    combo.data()->addItems( dataList );

    KCompletion* comp = combo.data()->completionObject();
    comp->setItems( dataList );

    // reset the text and re-enable the signal
    combo.data()->setEditText( m_filter.value );
    connect( combo.data(), SIGNAL(editTextChanged( const QString& ) ),
            SLOT(valueChanged(const QString&)) );
}
示例#4
0
  void Workspace::addBrowseView(QString cubename) {
    /* Close the last browse window if necessary.  */
    if (subWindowList().size()) {
      QWeakPointer<QMdiSubWindow> windowToRemove =
          subWindowList()[subWindowList().size() - 1];

      removeSubWindow(windowToRemove.data());

      delete windowToRemove.data();
    }

    addCubeViewport(cubename);
  }
示例#5
0
	static QObject *createInstance()
	{
		static QWeakPointer<QObject> instance;
		if (!instance)
			instance = QWeakPointer<QObject>(new qutim_sdk_0_3::ScriptExtensionPlugin);
		return instance.data();
	}
示例#6
0
int onHeadersComplete(http_parser *parser)
{   
    TcpSocket *socket = static_cast<TcpSocket*>(parser->data);
#ifndef NO_LOG
    sLog(LogEndpoint::LogLevel::DEBUG) << " === parsed header ====";
    const QHash<QString, QSharedPointer<QString>> &headers = socket->getHeader().getHeaderInfo();

    QHash<QString, QSharedPointer<QString>>::const_iterator i = headers.constBegin();
    while (i != headers.constEnd())
    {
        sLog(LogEndpoint::LogLevel::DEBUG) << i.key() << *(i.value().data());
        ++i;
    }
    sLog(LogEndpoint::LogLevel::DEBUG) << " === ============= ====";
    sLogFlush();
#endif
    QWeakPointer<QString> host = socket->getHeader().getHeaderInfo("Host");

    if (!host.isNull())
    {
        socket->getHeader().setHost(*host.data());
    }

    return 0;
}
void QGraphicsWebViewPrivate::updateCompositingScrollPosition()
{
    if (rootGraphicsLayer && q->page() && q->page()->mainFrame()) {
        const QPoint scrollPosition = q->page()->mainFrame()->scrollPosition();
        rootGraphicsLayer.data()->setPos(-scrollPosition);
    }
}
示例#8
0
QNetworkAccessManager*
nam()
{
    if ( s_nam.isNull() )
        return 0;
    
    return s_nam.data();
}
示例#9
0
//static
void DrKonqi::saveReport(const QString & reportText, QWidget *parent)
{
    if (KCmdLineArgs::parsedArgs()->isSet("safer")) {
        KTemporaryFile tf;
        tf.setSuffix(".kcrash.txt");
        tf.setAutoRemove(false);

        if (tf.open()) {
            QTextStream textStream(&tf);
            textStream << reportText;
            textStream.flush();
            KMessageBox::information(parent, i18nc("@info",
                                                   "Report saved to <filename>%1</filename>.",
                                                   tf.fileName()));
        } else {
            KMessageBox::sorry(parent, i18nc("@info","Could not create a file in which to save the report."));
        }
    } else {
        QString defname = getSuggestedKCrashFilename(crashedApplication());

        QWeakPointer<KFileDialog> dlg = new KFileDialog(defname, QString(), parent);
        dlg.data()->setSelection(defname);
        dlg.data()->setCaption(i18nc("@title:window","Select Filename"));
        dlg.data()->setOperationMode(KFileDialog::Saving);
        dlg.data()->setMode(KFile::File);
        dlg.data()->setConfirmOverwrite(true);
        dlg.data()->exec();

        if (dlg.isNull()) {
            //Dialog is invalid, it was probably deleted (ex. via DBus call)
            //return and do not crash
            return;
        }

        KUrl fileUrl = dlg.data()->selectedUrl();
        delete dlg.data();

        if (fileUrl.isValid()) {
            KTemporaryFile tf;
            if (tf.open()) {
                QTextStream ts(&tf);
                ts << reportText;
                ts.flush();
            } else {
                KMessageBox::sorry(parent, i18nc("@info","Cannot open file <filename>%1</filename> "
                                                         "for writing.", tf.fileName()));
                return;
            }

            if (!KIO::NetAccess::upload(tf.fileName(), fileUrl, parent)) {
                KMessageBox::sorry(parent, KIO::NetAccess::lastErrorString());
            }
        }
    }
}
示例#10
0
void
setProxy( QNetworkProxy* proxy )
{
    s_proxy = proxy;
    s_nam.data()->setProxy( *proxy );
    qDebug() << Q_FUNC_INFO << "setting proxy to use proxy DNS?" << (TomahawkSettings::instance()->proxyDns() ? "true" : "false");
    if ( !TomahawkSettings::instance()->proxyDns() )
        s_proxy->setCapabilities( QNetworkProxy::TunnelingCapability | QNetworkProxy::ListeningCapability | QNetworkProxy::UdpTunnelingCapability );
}
void QGraphicsWebViewPrivate::setRootGraphicsLayer(QGraphicsItem* layer)
{
    if (rootGraphicsLayer) {
        rootGraphicsLayer.data()->setParentItem(0);
        q->scene()->removeItem(rootGraphicsLayer.data());
        QWebFramePrivate::core(q->page()->mainFrame())->view()->syncCompositingStateRecursive();
    }

    rootGraphicsLayer = layer ? layer->toGraphicsObject() : 0;

    if (layer) {
        layer->setFlag(QGraphicsItem::ItemClipsChildrenToShape, true);
        layer->setParentItem(q);
        layer->setZValue(RootGraphicsLayerZValue);
        updateCompositingScrollPosition();
    }
    createOrDeleteOverlay();
}
示例#12
0
/**
 * \brief Initialization
 *
 * Initializes the TabsApplet with default parameters
 */
void
TabsApplet::init()
{
    // applet base initialization
    Context::Applet::init();

    // create the header label
    enableHeader( true );
    setHeaderText( i18nc( "Guitar tablature", "Tabs" ) );

    // creates the tab view
    m_tabsView = new TabsView( this );

    // Set the collapse size
    setCollapseOffHeight( -1 );
    setCollapseHeight( m_header->height() );
    setMinimumHeight( collapseHeight() );
    setPreferredHeight( collapseHeight() );

    // create the reload icon
    QAction* reloadAction = new QAction( this );
    reloadAction->setIcon( KIcon( "view-refresh" ) );
    reloadAction->setVisible( true );
    reloadAction->setEnabled( true );
    reloadAction->setText( i18nc( "Guitar tablature", "Reload tabs" ) );
    m_reloadIcon = addLeftHeaderAction( reloadAction );
    m_reloadIcon.data()->setEnabled( false );
    connect( m_reloadIcon.data(), SIGNAL(clicked()), this, SLOT(reloadTabs()) );

    // create the settings icon
    QAction* settingsAction = new QAction( this );
    settingsAction->setIcon( KIcon( "preferences-system" ) );
    settingsAction->setEnabled( true );
    settingsAction->setText( i18n( "Settings" ) );
    QWeakPointer<Plasma::IconWidget> settingsIcon = addRightHeaderAction( settingsAction );
    connect( settingsIcon.data(), SIGNAL(clicked()), this, SLOT(showConfigurationInterface()) );

    m_layout = new QGraphicsLinearLayout( Qt::Vertical );
    m_layout->addItem( m_header );
    m_layout->addItem( m_tabsView );
    setLayout( m_layout );

    // read configuration data and update the engine.
    KConfigGroup config = Amarok::config("Tabs Applet");
    m_fetchGuitar = config.readEntry( "FetchGuitar", true );
    m_fetchBass = config.readEntry( "FetchBass", true );

    Plasma::DataEngine *engine = dataEngine( "amarok-tabs" );
    engine->setProperty( "fetchGuitarTabs", m_fetchGuitar );
    engine->setProperty( "fetchBassTabs", m_fetchBass );
    engine->connectSource( "tabs", this );

    updateInterface( InitState );
}
示例#13
0
 void addModel(QAbstractItemModel *model, ViewType viewtype, Kickoff::MenuView::ModelOptions options = Kickoff::MenuView::MergeFirstLevel, int formattype = -1)
 {
     Kickoff::MenuView* mainView = menuview.data();
     Kickoff::MenuView* m = mainView;
     if (viewtypes.count() > 1 || !m) {
         m = new Kickoff::MenuView(mainView, viewText(viewtype), KIcon(viewIcon(viewtype)));
         m->setFormatType((formattype >= 0 || !mainView) ? (Kickoff::MenuView::FormatType)formattype : mainView->formatType());
         mainView->addMenu(m);
     }
     m->addModel(model, options);
 }
示例#14
0
tSidebarPageTroll::tSidebarPageTroll(
    const QWeakPointer<tMercuryStyle>& xStyle,
    const QWeakPointer<tMercurySettings>& xSettings,
    const QWeakPointer<tMercuryDataManager>& xDataManager,
    QGraphicsItem* pParent)

    : Base(xStyle, xSettings, pParent)
    , m_xDataManager(xDataManager)
    , m_pStatus(0)
    , m_pIndicator(0)
    , m_pButton(0)
    , m_pUp(0)
    , m_pDown(0)
    , m_CurrentRPM(0)
    , m_TimeoutTicks(0)
    , m_TrollAllowed(true)
    , m_RotaryFocus(false)
{
    tSidebarPage::ItemsCollection items(this);

    tSidebarControlTitle* objTitle = new tSidebarControlTitle(xStyle.data(),
        tr("VESSEL CONTROL", "Mercury Vessel Control section heading"),
        tr("TROLL", "Mercury Troll Control page title"),
        tSidebarControlTitle::eModeBack);
    Connect(objTitle, SIGNAL(Triggered()), this, SIGNAL(Back()));

    items
        .Add(objTitle, 1.f, Qt::AlignAbsolute)
        .Add(m_pUp = new tSidebarControlSpinButton(xStyle.data(), tSidebarControlSpinButton::eDirectionUp),
            1.5f, Qt::AlignAbsolute)
        .Add(m_pIndicator = new tSidebarControlIndicator(
            xStyle.data(), "", "", "", tSidebarControlIndicator::eModeNormal, true),
            -1.f, Qt::AlignAbsolute)
        .Add(m_pDown = new tSidebarControlSpinButton(xStyle.data(), tSidebarControlSpinButton::eDirectionDown),
            1.5f, Qt::AlignAbsolute)
        .Add(m_pStatus = new tSidebarStaticText(xStyle.data(), ""), 0.5f, Qt::AlignAbsolute)
        .Add(m_pButton = new tSidebarControlButtonToggle(xStyle.data(), tr("Enable"), tr("Disable")),
            1.f, Qt::AlignBottom)
        .End();

    Connect(m_pUp, SIGNAL(Triggered()), this, SLOT(OnUpClicked()));
    Connect(m_pDown, SIGNAL(Triggered()), this, SLOT(OnDownClicked()));
    Connect(m_pButton, SIGNAL(Triggered()), this, SLOT(OnEnableClicked()));
    Connect(m_pIndicator, SIGNAL(Triggered()), this, SLOT(OnIndicatorTouched()));

    if( !m_xDataManager.isNull() )
    {
        tMercuryCommand* command = m_xDataManager.data()->MercuryCommand();
        if( command != 0 )
        {
            m_CurrentRPM = static_cast<int>(command->TrollRpmSetpoint());
            UpdateStatus(command->IsTrollActive());
            SetTrollAllowed(command->IsTrollAllowed());

            Connect(command, SIGNAL(TrollEngaged(int)), this, SLOT(StatusEnable()));
            Connect(command, SIGNAL(TrollDisengaged(int)), this, SLOT(StatusDisable()));
            Connect(command, SIGNAL(TrollActiveDetected()), this, SLOT(StatusEnable()));
            Connect(command, SIGNAL(TrollInactiveDetected()), this, SLOT(StatusDisable()));
            Connect(command, SIGNAL(TrollAllowedChanged(bool)), this, SLOT(SetTrollAllowed(bool)));
        }
示例#15
0
// The access function for guarded QObject pointers.
static void *qpointer_access_func(sipSimpleWrapper *w, AccessFuncOp op)
{
    QWeakPointer<QObject> *guard = reinterpret_cast<QWeakPointer<QObject> *>(w->data);
    void *addr;

    switch (op)
    {
    case UnguardedPointer:
        addr = guard->data();
        break;

    case GuardedPointer:
        addr = guard->isNull() ? 0 : guard->data();
        break;

    case ReleaseGuard:
        delete guard;
        addr = 0;
        break;
    }

    return addr;
}
示例#16
0
void ResourceCacheSharedItems::removeRequest(QWeakPointer<Resource> resource) {
    Lock lock(_mutex);

    // resource can only be removed if it still has a ref-count, as
    // QWeakPointer has no operator== implementation for two weak ptrs, so
    // manually loop in case resource has been freed.
    for (int i = 0; i < _loadingRequests.size();) {
        auto request = _loadingRequests.at(i);
        // Clear our resource and any freed resources
        if (!request || request.data() == resource.data()) {
            _loadingRequests.removeAt(i);
            continue;
        }
        i++;
    }
}
示例#17
0
void AvatarHashMap::processAvatarDataPacket(const QByteArray &datagram, const QWeakPointer<Node> &mixerWeakPointer) {
    int bytesRead = numBytesForPacketHeader(datagram);
    
    // enumerate over all of the avatars in this packet
    // only add them if mixerWeakPointer points to something (meaning that mixer is still around)
    while (bytesRead < datagram.size() && mixerWeakPointer.data()) {
        QUuid sessionUUID = QUuid::fromRfc4122(datagram.mid(bytesRead, NUM_BYTES_RFC4122_UUID));
        bytesRead += NUM_BYTES_RFC4122_UUID;
        
        if (sessionUUID != _lastOwnerSessionUUID) {
            AvatarSharedPointer matchingAvatarData = matchingOrNewAvatar(sessionUUID, mixerWeakPointer);
            
            // have the matching (or new) avatar parse the data from the packet
            bytesRead += matchingAvatarData->parseDataAtOffset(datagram, bytesRead);
        } else {
            // create a dummy AvatarData class to throw this data on the ground
            AvatarData dummyData;
            bytesRead += dummyData.parseDataAtOffset(datagram, bytesRead);
        }
    }
}
//public slot
void ProblemModelAdapter::setProblem(QWeakPointer<PlanningProblem> problem)
{
    /*
      We have to do this with the start and end markers to prevent and annoying save/load bug
      where the markers disappear and reappear upong loading over and over
    */
    if (!_startMarker.isNull())
    {
        disconnect(_startMarker.data(),
                   SIGNAL(destroyed()),
                   this,
                   SLOT(handleStartMarkerDestroyed()));
        _startMarker->deleteLater();
        _startMarker = 0;
    }

    _problem = problem;
    if (problem.isNull())
        return;

    _objectToArea.clear();

    PlanningProblem * raw = problem.data();


    connect(raw,
            SIGNAL(startPositionChanged(Position)),
            this,
            SLOT(handleStartPositionChanged(Position)));
    connect(raw,
            SIGNAL(startPositionRemoved()),
            this,
            SLOT(handleStartPositionRemoved()));

    connect(raw,
            SIGNAL(areaAdded(QSharedPointer<TaskArea>)),
            this,
            SLOT(handleAreaAdded(QSharedPointer<TaskArea>)));
}
示例#19
0
void myMessageOutput(QtMsgType type, const char *msg)
{
    QString strMsg = QString::fromLatin1(msg);

    if (!QCoreApplication::closingDown()) {
        if (!logger.isNull()) {
            if (recursiveLock.testAndSetOrdered(0, 1)) {
                QMetaObject::invokeMethod(logger.data(), "append", Q_ARG(QString, strMsg));
                recursiveLock = 0;
            }
        } else {
            warnings += strMsg;
            warnings += QLatin1Char('\n');
        }
    }
    if (systemMsgOutput) { // Windows
        systemMsgOutput(type, msg);
    } else { // Unix
        fprintf(stderr, "%s\n", msg);
        fflush(stderr);
    }
}
void JabberEditAccountWidget::removeAccount()
{
	QWeakPointer<QMessageBox> messageBox = new QMessageBox(this);
	messageBox.data()->setWindowTitle(tr("Confirm account removal"));
	messageBox.data()->setText(tr("Are you sure you want to remove account %1 (%2)?")
			.arg(account().accountIdentity().name())
			.arg(account().id()));

	QPushButton *removeButton = messageBox.data()->addButton(tr("Remove account"), QMessageBox::AcceptRole);
	messageBox.data()->addButton(QMessageBox::Cancel);
	messageBox.data()->setDefaultButton(QMessageBox::Cancel);
	messageBox.data()->exec();

	if (messageBox.isNull())
		return;

	if (messageBox.data()->clickedButton() == removeButton)
	{
		AccountManager::instance()->removeAccountAndBuddies(account());
		deleteLater();
	}

	delete messageBox.data();
}
示例#21
0
文件: main.cpp 项目: Suneal/qt
void myMessageOutput(QtMsgType type, const char *msg)
{
    QString strMsg = QString::fromLatin1(msg);

    if (!QCoreApplication::closingDown()) {
        if (!logger.isNull()) {
            if (recursiveLock.testAndSetOrdered(0, 1)) {
                QMetaObject::invokeMethod(logger.data(), "append", Q_ARG(QString, strMsg));
                recursiveLock = 0;
            }
        } else {
            warnings += strMsg;
            warnings += QLatin1Char('\n');
        }
    }
#if defined (Q_OS_SYMBIAN)
    static int fd = -1;
    if (fd == -1)
        fd = ::open("E:\\qml.log", O_WRONLY | O_CREAT);

    ::write(fd, msg, strlen(msg));
    ::write(fd, "\n", 1);
    ::fsync(fd);
    switch (type) {
    case QtFatalMsg:
        abort();
    }
#endif

    if (systemMsgOutput) {
        systemMsgOutput(type, msg);
    } else { // Unix
        fprintf(stderr, "%s\n", msg);
        fflush(stderr);
    }
}
bool BlackBerryRunControlFactory::canRun(ProjectExplorer::RunConfiguration *runConfiguration,
        ProjectExplorer::RunMode mode) const
{
    Q_UNUSED(mode);

    BlackBerryRunConfiguration *rc = qobject_cast<BlackBerryRunConfiguration *>(runConfiguration);
    if (!rc)
        return false;

    // The device can only run the same application once, any subsequent runs will
    // not launch a second instance. Disable the Run button if the application is already
    // running on the device.
    if (m_activeRunControls.contains(rc->key())) {
        QWeakPointer<ProjectExplorer::RunControl> activeRunControl = m_activeRunControls[rc->key()];
        if (activeRunControl && activeRunControl.data()->isRunning())
            return false;
        else
            m_activeRunControls.remove(rc->key());
    }

    BlackBerryDeployConfiguration *activeDeployConf = qobject_cast<BlackBerryDeployConfiguration *>(
                rc->target()->activeDeployConfiguration());
    return activeDeployConf != 0;
}
示例#23
0
bool
ViewUrlRunner::run( AmarokUrl url )
{
    DEBUG_BLOCK

    QMap< QString, QString > args = url.args();
    QWeakPointer<Dock> playlistDock = The::mainWindow()->playlistDock();

    if( args.keys().contains( "filter" ) )
    {
        QString filterExpr = args.value( "filter" );
        playlistDock.data()->searchWidget()->setCurrentFilter( filterExpr );
        if( args.keys().contains( "matches" ) )
        {
            QString onlyMatches = args.value( "matches" );
            playlistDock.data()->searchWidget()->slotShowOnlyMatches( ( onlyMatches == QString( "true" ) ) );
        }
    }
    if( args.keys().contains( "sort" ) )
    {
        playlistDock.data()->sortWidget()->trimToLevel();

        QString sortPath = args.value( "sort" );

        QStringList levels = sortPath.split( '-' );
        foreach( const QString &level, levels )
        {
            if( level == QString( "Random" ) || level == QString( "Shuffle" ) ) //we keep "Random" for compatibility
            {
                playlistDock.data()->sortWidget()->addLevel( QString( "Shuffle" ) );
                break;
            }
            QStringList levelParts = level.split( '_' );
            if( levelParts.count() > 2 )
                warning() << "Playlist view URL parse error: Invalid sort level " << level;
            if( levelParts.at( 1 ) == QString( "asc" ) )
                playlistDock.data()->sortWidget()->addLevel( levelParts.at( 0 ), Qt::AscendingOrder );
            else if( levelParts.at( 1 ) == QString( "des" ) )
                playlistDock.data()->sortWidget()->addLevel( levelParts.at( 0 ), Qt::DescendingOrder );
            else
                warning() << "Playlist view URL parse error: Invalid sort order for level " << level;
        }
    }
示例#24
0
bool AddToArchive::showAddDialog(void)
{
    QWeakPointer<Kerfuffle::AddDialog> dialog = new Kerfuffle::AddDialog(
        m_inputs, // itemsToAdd
        KUrl(m_firstPath), // startDir
        QLatin1String( "" ), // filter
        NULL, // parent
        NULL); // widget

    bool ret = dialog.data()->exec();

    if (ret) {
        kDebug() << "Returned URL:" << dialog.data()->selectedUrl();
        kDebug() << "Returned mime:" << dialog.data()->currentMimeFilter();
        setFilename(dialog.data()->selectedUrl());
        setMimeType(dialog.data()->currentMimeFilter());
    }

    delete dialog.data();

    return ret;
}
示例#25
0
 ~Private()
 {
     delete bookmarkmenu;
     delete bookmarkowner;
     delete menuview.data();
 }
示例#26
0
void DesignDocumentController::changeToSubComponent(const ModelNode &componentNode)
{
    Q_ASSERT(d->masterModel);
    QWeakPointer<Model> oldModel = d->model;
    Q_ASSERT(oldModel.data());

    if (d->model == d->subComponentModel) {
        changeToMasterModel();
    }

    QString componentText = d->rewriterView->extractText(QList<ModelNode>() << componentNode).value(componentNode);

    if (componentText.isEmpty())
        return;

    bool explicitComponent = false;
    if (componentText.contains("Component")) { //explicit component
        explicitComponent = true;
    }

    d->componentNode = componentNode;
    if (!componentNode.isRootNode()) {
        Q_ASSERT(d->model == d->masterModel);
        Q_ASSERT(componentNode.isValid());
        //change to subcomponent model
        ModelNode rootModelNode = componentNode.view()->rootModelNode();
        Q_ASSERT(rootModelNode.isValid());
        if (d->componentTextModifier)
            delete d->componentTextModifier;


        int componentStartOffset;
        int componentEndOffset;

        int rootStartOffset = d->rewriterView->nodeOffset(rootModelNode);

        if (explicitComponent) { //the component is explciit we have to find the first definition inside
            componentStartOffset = d->rewriterView->firstDefinitionInsideOffset(componentNode);
            componentEndOffset = componentStartOffset + d->rewriterView->firstDefinitionInsideLength(componentNode);
        } else { //the component is implicit
            componentStartOffset = d->rewriterView->nodeOffset(componentNode);
            componentEndOffset = componentStartOffset + d->rewriterView->nodeLength(componentNode);
        }

        d->componentTextModifier = new ComponentTextModifier (d->textModifier, componentStartOffset, componentEndOffset, rootStartOffset);


        d->model->detachView(d->rewriterView.data());

        d->rewriterView->setTextModifier(d->componentTextModifier);

        d->subComponentModel->attachView(d->rewriterView.data());

        Q_ASSERT(d->rewriterView->rootModelNode().isValid());

        d->model = d->subComponentModel;
    }

    Q_ASSERT(d->masterModel);
    Q_ASSERT(d->model);

    loadCurrentModel();
    d->componentView->setComponentNode(componentNode);
}
示例#27
0
tSidebarPageCruise::tSidebarPageCruise(
    const QWeakPointer<tMercuryStyle>& xStyle,
    const QWeakPointer<tMercurySettings>& xSettings,
    const QWeakPointer<tMercuryDataManager>& xDataManager,
    const QWeakPointer<tConvert> &xConvert,
    QGraphicsItem* pParent)

    : Base(xStyle, xSettings, pParent)
    , m_xDataManager(xDataManager)
    , m_xConvert(xConvert)
    , m_pStatus(0)
    , m_pIndicator(0)
    , m_pButton(0)
    , m_pUp(0)
    , m_pDown(0)
    , m_CurrentValue(0)
    , m_LastReceived(0)
    , m_TimeoutTicks(0)
    , m_IdleTimeoutTicks(0)
    , m_RotaryFocus(false)
{
    tSidebarPage::ItemsCollection items(this);

    tSidebarControlTitle* objTitle = new tSidebarControlTitle(xStyle.data(),
        tr("VESSEL CONTROL", "Mercury Vessel Control section heading"),
        tr("CRUISE", "Mercury Cruise Control page title"),
        tSidebarControlTitle::eModeBack);
    Connect(objTitle, SIGNAL(Triggered()), this, SIGNAL(Back()));

    items
        .Add(objTitle, 1.f, Qt::AlignAbsolute)
        .Add(m_pUp = new tSidebarControlSpinButton(xStyle.data(), tSidebarControlSpinButton::eDirectionUp),
            1.5f, Qt::AlignAbsolute)
        .Add(m_pIndicator = new tSidebarControlIndicator(
            xStyle.data(), "", "", "", tSidebarControlIndicator::eModeSimpleVertical, true), -1.f, Qt::AlignAbsolute)
        .Add(m_pDown = new tSidebarControlSpinButton(xStyle.data(), tSidebarControlSpinButton::eDirectionDown),
            1.5f, Qt::AlignAbsolute)
        .Add(m_pStatus = new tSidebarStaticText(xStyle.data(), ""), 0.5f, Qt::AlignAbsolute)
        .Add(m_pButton = new tSidebarControlButtonToggle(xStyle.data(), tr("Enable"), tr("Disable")),
            1.f, Qt::AlignAbsolute)
        .End();

    Connect(m_pUp, SIGNAL(Triggered()), this, SLOT(OnUpClicked()));
    Connect(m_pDown, SIGNAL(Triggered()), this, SLOT(OnDownClicked()));
    Connect(m_pButton, SIGNAL(Triggered()), this, SLOT(OnEnableClicked()));
    Connect(m_pIndicator, SIGNAL(Triggered()), this, SLOT(OnIndicatorTouched()));

    if( !m_xDataManager.isNull() )
    {
        tMercuryCommand* command = m_xDataManager.data()->MercuryCommand();
        if( command != 0 )
        {
            m_CurrentValue = static_cast<float>(m_xDataManager.data()->MercuryCommand()->CruiseSetpoint(false));
            UpdateStatus(command->IsBasicCruiseEngaged());

            Connect(command, SIGNAL(CruiseEngaged()), this, SLOT(StatusEnable()));
            Connect(command, SIGNAL(CruiseDisengaged()), this, SLOT(StatusDisable()));

            Connect(command, SIGNAL(SmartTowEngaged()), this, SLOT(UpdateControlsEnabledState()));
            Connect(command, SIGNAL(SmartTowDisengaged()), this, SLOT(UpdateControlsEnabledState()));
            Connect(command, SIGNAL(CruiseAllowedChanged(bool)), this, SLOT(UpdateControlsEnabledState()));
        }
示例#28
0
void GeometryReader::run() {
    DependencyManager::get<StatTracker>()->decrementStat("PendingProcessing");
    CounterStat counter("Processing");
    PROFILE_RANGE_EX(resource_parse_geometry, "GeometryReader::run", 0xFF00FF00, 0, { { "url", _url.toString() } });
    auto originalPriority = QThread::currentThread()->priority();
    if (originalPriority == QThread::InheritPriority) {
        originalPriority = QThread::NormalPriority;
    }
    QThread::currentThread()->setPriority(QThread::LowPriority);
    Finally setPriorityBackToNormal([originalPriority]() {
        QThread::currentThread()->setPriority(originalPriority);
    });

    if (!_resource.data()) {
        return;
    }

    try {
        if (_data.isEmpty()) {
            throw QString("reply is NULL");
        }

        // Ensure the resource has not been deleted
        auto resource = _resource.toStrongRef();
        if (!resource) {
            qCWarning(modelnetworking) << "Abandoning load of" << _url << "; could not get strong ref";
            return;
        }

        if (_url.path().isEmpty()) {
            throw QString("url is invalid");
        }

        HFMModel::Pointer hfmModel;
        QVariantHash serializerMapping = _mapping.second;
        serializerMapping["combineParts"] = _combineParts;
        serializerMapping["deduplicateIndices"] = true;

        if (_url.path().toLower().endsWith(".gz")) {
            QByteArray uncompressedData;
            if (!gunzip(_data, uncompressedData)) {
                throw QString("failed to decompress .gz model");
            }
            // Strip the compression extension from the path, so the loader can infer the file type from what remains.
            // This is okay because we don't expect the serializer to be able to read the contents of a compressed model file.
            auto strippedUrl = _url;
            strippedUrl.setPath(_url.path().left(_url.path().size() - 3));
            hfmModel = _modelLoader.load(uncompressedData, serializerMapping, strippedUrl, "");
        } else {
            hfmModel = _modelLoader.load(_data, serializerMapping, _url, _webMediaType.toStdString());
        }

        if (!hfmModel) {
            throw QString("unsupported format");
        }

        if (hfmModel->meshes.empty() || hfmModel->joints.empty()) {
            throw QString("empty geometry, possibly due to an unsupported model version");
        }

        // Add scripts to hfmModel
        if (!serializerMapping.value(SCRIPT_FIELD).isNull()) {
            QVariantList scripts = serializerMapping.values(SCRIPT_FIELD);
            for (auto &script : scripts) {
                hfmModel->scripts.push_back(script.toString());
            }
        }

        // Do processing on the model
        baker::Baker modelBaker(hfmModel, _mapping.second, _mapping.first);
        modelBaker.run();

        auto processedHFMModel = modelBaker.getHFMModel();
        auto materialMapping = modelBaker.getMaterialMapping();

        QMetaObject::invokeMethod(resource.data(), "setGeometryDefinition",
                Q_ARG(HFMModel::Pointer, processedHFMModel), Q_ARG(MaterialMapping, materialMapping));
    } catch (const std::exception&) {
        auto resource = _resource.toStrongRef();
        if (resource) {
            QMetaObject::invokeMethod(resource.data(), "finishedLoading",
                Q_ARG(bool, false));
        }
    } catch (QString& e) {
        qCWarning(modelnetworking) << "Exception while loading model --" << e;
        auto resource = _resource.toStrongRef();
        if (resource) {
            QMetaObject::invokeMethod(resource.data(), "finishedLoading",
                                      Q_ARG(bool, false));
        }
    }
}
示例#29
0
void InternalCoreConnection::onNewMessage(Common::MessageHeader::MessageType type, const google::protobuf::Message& message)
{
   // While we are not authenticated we accept only two message types.
   if (!this->authenticated && type != Common::MessageHeader::GUI_ASK_FOR_AUTHENTICATION && type != Common::MessageHeader::GUI_AUTHENTICATION_RESULT)
      return;

   switch (type)
   {
   case Common::MessageHeader::GUI_ASK_FOR_AUTHENTICATION:
      {
         const Protos::GUI::AskForAuthentication& askForAuthentication = static_cast<const Protos::GUI::AskForAuthentication&>(message);

         Protos::GUI::Authentication authentication;

         this->salt = askForAuthentication.salt();

         if (!this->password.isEmpty())
            this->connectionInfo.password = Common::Hasher::hashWithSalt(this->password, this->salt);

         authentication.mutable_password_challenge()->set_hash(Common::Hasher::hashWithSalt(this->connectionInfo.password, askForAuthentication.salt_challenge()).getData(), Common::Hash::HASH_SIZE);
         this->password.clear();
         this->send(Common::MessageHeader::GUI_AUTHENTICATION, authentication);
      }
      break;

   case Common::MessageHeader::GUI_AUTHENTICATION_RESULT:
      {
         const Protos::GUI::AuthenticationResult& authenticationResult = static_cast<const Protos::GUI::AuthenticationResult&>(message);

         if (authenticationResult.status() == Protos::GUI::AuthenticationResult::AUTH_OK)
         {
            this->connectedAndAuthenticated();
         }
         else
         {
            switch (authenticationResult.status())
            {
            case Protos::GUI::AuthenticationResult::AUTH_PASSWORD_NOT_DEFINED:
               emit connectingError(ICoreConnection::ERROR_NO_REMOTE_PASSWORD_DEFINED);
               break;

            case Protos::GUI::AuthenticationResult::AUTH_BAD_PASSWORD:
                emit connectingError(ICoreConnection::ERROR_WRONG_PASSWORD);
               break;

            case Protos::GUI::AuthenticationResult::AUTH_ERROR:
               emit connectingError(ICoreConnection::ERROR_UNKNOWN);
               break;

            default:;
            }
         }
      }
      break;

   case Common::MessageHeader::GUI_STATE:
      {
         const Protos::GUI::State& state = static_cast<const Protos::GUI::State&>(message);

         emit newState(state);
         this->send(Common::MessageHeader::GUI_STATE_RESULT);
      }
      break;

   case Common::MessageHeader::GUI_EVENT_CHAT_MESSAGES:
      {
         const Protos::GUI::EventChatMessages& eventChatMessages = static_cast<const Protos::GUI::EventChatMessages&>(message);
         if (eventChatMessages.message_size() > 0)
            emit newChatMessages(eventChatMessages);
      }
      break;

   case Common::MessageHeader::GUI_EVENT_LOG_MESSAGE:
      {
         const Protos::GUI::EventLogMessage& eventLogMessage = static_cast<const Protos::GUI::EventLogMessage&>(message);

         QDateTime dateTime = QDateTime::fromMSecsSinceEpoch(eventLogMessage.time());
         QString message = Common::ProtoHelper::getStr(eventLogMessage, &Protos::GUI::EventLogMessage::message);
         LM::Severity severity = LM::Severity(eventLogMessage.severity());
         emit newLogMessage(LM::Builder::newEntry(dateTime, severity, message));
      }
      break;

   case Common::MessageHeader::GUI_SEARCH_TAG:
      {
         const Protos::GUI::Tag& tagMessage = static_cast<const Protos::GUI::Tag&>(message);

         while (!this->searchResultsWithoutTag.isEmpty())
         {
            QWeakPointer<SearchResult> searchResult = this->searchResultsWithoutTag.takeFirst();
            if (!searchResult.isNull())
            {
               searchResult.data()->setTag(tagMessage.tag());
               break;
            }
         }
      }
      break;

   case Common::MessageHeader::GUI_SEARCH_RESULT:
      {
         const Protos::Common::FindResult& findResultMessage = static_cast<const Protos::Common::FindResult&>(message);

         emit searchResult(findResultMessage);
      }
      break;

   case Common::MessageHeader::GUI_BROWSE_TAG:
      {
         const Protos::GUI::Tag& tagMessage = static_cast<const Protos::GUI::Tag&>(message);

         while (!this->browseResultsWithoutTag.isEmpty())
         {
            QWeakPointer<BrowseResult> browseResult = this->browseResultsWithoutTag.takeFirst();
            if (!browseResult.isNull())
            {
               browseResult.data()->setTag(tagMessage.tag());
               break;
            }
         }
      }
      break;

   case Common::MessageHeader::GUI_BROWSE_RESULT:
      {
         const Protos::GUI::BrowseResult& browseResultMessage = static_cast<const Protos::GUI::BrowseResult&>(message);

         emit browseResult(browseResultMessage);
      }
      break;

   default:;
   }
}
void QApplicationPrivate::processMouseEvent(QWindowSystemInterfacePrivate::MouseEvent *e)
{
    if (!e->widget)
       return;

    // qDebug() << "handleMouseEvent" << tlw << ev.pos() << ev.globalPos() << hex << ev.buttons();
    static QWeakPointer<QWidget> implicit_mouse_grabber;

    QEvent::Type type;
    // move first
    Qt::MouseButtons stateChange = e->buttons ^ buttons;
    if (e->globalPos != QPoint(qt_last_x, qt_last_y) && (stateChange != Qt::NoButton)) {
        QWindowSystemInterfacePrivate::MouseEvent * newMouseEvent =
                new QWindowSystemInterfacePrivate::MouseEvent(e->widget.data(), e->timestamp, e->localPos, e->globalPos, e->buttons);
        QWindowSystemInterfacePrivate::windowSystemEventQueue.prepend(newMouseEvent); // just in case the move triggers a new event loop
        stateChange = Qt::NoButton;
    }

    QWidget * tlw = e->widget.data();

    QPoint localPoint = e->localPos;
    QPoint globalPoint = e->globalPos;
    QWidget *mouseWindow = tlw;

    Qt::MouseButton button = Qt::NoButton;


    if (qt_last_x != globalPoint.x() || qt_last_y != globalPoint.y()) {
        type = QEvent::MouseMove;
        qt_last_x = globalPoint.x();
        qt_last_y = globalPoint.y();
        if (qAbs(globalPoint.x() - mousePressX) > mouse_double_click_distance||
            qAbs(globalPoint.y() - mousePressY) > mouse_double_click_distance)
            mousePressButton = Qt::NoButton;
    }
    else { // check to see if a new button has been pressed/released
        for (int check = Qt::LeftButton;
             check <= Qt::XButton2;
             check = check << 1) {
            if (check & stateChange) {
                button = Qt::MouseButton(check);
                break;
            }
        }
        if (button == Qt::NoButton) {
            // Ignore mouse events that don't change the current state
            return;
        }
        buttons = e->buttons;
        if (button & e->buttons) {
            if ((e->timestamp - mousePressTime) < static_cast<ulong>(QApplication::doubleClickInterval()) && button == mousePressButton) {
                type = QEvent::MouseButtonDblClick;
                mousePressButton = Qt::NoButton;
            }
            else {
                type = QEvent::MouseButtonPress;
                mousePressTime = e->timestamp;
                mousePressButton = button;
                mousePressX = qt_last_x;
                mousePressY = qt_last_y;
            }
        }
        else
            type = QEvent::MouseButtonRelease;
    }

    if (self->inPopupMode()) {
        //popup mouse handling is magical...
        mouseWindow = qApp->activePopupWidget();

        implicit_mouse_grabber.clear();
        //### how should popup mode and implicit mouse grab interact?

    } else if (tlw && app_do_modal && !qt_try_modal(tlw, QEvent::MouseButtonRelease) ) {
        //even if we're blocked by modality, we should deliver the mouse release event..
        //### this code is not completely correct: multiple buttons can be pressed simultaneously
        if (!(implicit_mouse_grabber && buttons == Qt::NoButton)) {
            //qDebug() << "modal blocked mouse event to" << tlw;
            return;
        }
    }

    // find the tlw if we didn't get it from the plugin
    if (!mouseWindow) {
        mouseWindow = QApplication::topLevelAt(globalPoint);
    }

    if (!mouseWindow && !implicit_mouse_grabber)
        mouseWindow = QApplication::desktop();

    if (mouseWindow && mouseWindow != tlw) {
        //we did not get a sensible localPoint from the window system, so let's calculate it
        localPoint = mouseWindow->mapFromGlobal(globalPoint);
    }

    // which child should have it?
    QWidget *mouseWidget = mouseWindow;
    if (mouseWindow) {
        QWidget *w =  mouseWindow->childAt(localPoint);
        if (w) {
            mouseWidget = w;
        }
    }

    //handle implicit mouse grab
    if (type == QEvent::MouseButtonPress && !implicit_mouse_grabber) {
        implicit_mouse_grabber = mouseWidget;

        Q_ASSERT(mouseWindow);
        mouseWindow->activateWindow(); //focus
    } else if (implicit_mouse_grabber) {
        mouseWidget = implicit_mouse_grabber.data();
        mouseWindow = mouseWidget->window();
        if (mouseWindow != tlw)
            localPoint = mouseWindow->mapFromGlobal(globalPoint);
    }

    Q_ASSERT(mouseWidget);

    //localPoint is local to mouseWindow, but it needs to be local to mouseWidget
    localPoint = mouseWidget->mapFrom(mouseWindow, localPoint);

    if (buttons == Qt::NoButton) {
        //qDebug() << "resetting mouse grabber";
        implicit_mouse_grabber.clear();
    }

    if (mouseWidget != qt_last_mouse_receiver) {
        dispatchEnterLeave(mouseWidget, qt_last_mouse_receiver);
        qt_last_mouse_receiver = mouseWidget;
    }

    // Remember, we might enter a modal event loop when sending the event,
    // so think carefully before adding code below this point.

    // qDebug() << "sending mouse ev." << ev.type() << localPoint << globalPoint << ev.button() << ev.buttons() << mouseWidget << "mouse grabber" << implicit_mouse_grabber;

    QMouseEvent ev(type, localPoint, globalPoint, button, buttons, QApplication::keyboardModifiers());

    QList<QWeakPointer<QPlatformCursor> > cursors = QPlatformCursorPrivate::getInstances();
    foreach (QWeakPointer<QPlatformCursor> cursor, cursors) {
        if (cursor)
            cursor.data()->pointerEvent(ev);
    }

    int oldOpenPopupCount = openPopupCount;
    QApplication::sendSpontaneousEvent(mouseWidget, &ev);

#ifndef QT_NO_CONTEXTMENU
    if (type == QEvent::MouseButtonPress && button == Qt::RightButton && (openPopupCount == oldOpenPopupCount)) {
        QContextMenuEvent e(QContextMenuEvent::Mouse, localPoint, globalPoint, QApplication::keyboardModifiers());
        QApplication::sendSpontaneousEvent(mouseWidget, &e);
    }
#endif // QT_NO_CONTEXTMENU
}