PacketDialog::PacketDialog(QWidget &parent, CaptureFile &cf, frame_data *fdata) :
    WiresharkDialog(parent, cf),
    ui(new Ui::PacketDialog),
    packet_data_(NULL)
{
    ui->setupUi(this);
    ui->hintLabel->setSmallText();

    // XXX Use recent settings instead
    resize(parent.width() * 4 / 5, parent.height() * 4 / 5);

    setWindowSubtitle(tr("Packet %1").arg(fdata->num));

    phdr_ = cap_file_.capFile()->phdr;
    packet_data_ = (guint8 *) g_memdup(ws_buffer_start_ptr(&(cap_file_.capFile()->buf)), fdata->cap_len);

    if (!cf_read_record(cap_file_.capFile(), fdata)) reject();
    /* proto tree, visible. We need a proto tree if there's custom columns */
    epan_dissect_init(&edt_, cap_file_.capFile()->epan, TRUE, TRUE);
    col_custom_prime_edt(&edt_, &(cap_file_.capFile()->cinfo));

    epan_dissect_run(&edt_, cap_file_.capFile()->cd_t, &phdr_,
                     frame_tvbuff_new(fdata, packet_data_),
                     fdata, &(cap_file_.capFile()->cinfo));
    epan_dissect_fill_in_columns(&edt_, TRUE, TRUE);

    proto_tree_ = new ProtoTree(ui->packetSplitter);
    proto_tree_->fillProtocolTree(edt_.tree);
    proto_tree_->expandAll();

    byte_view_tab_ = new ByteViewTab(ui->packetSplitter);
    byte_view_tab_->setCaptureFile(cap_file_.capFile());
    byte_view_tab_->clear();

    GSList *src_le;
    for (src_le = edt_.pi.data_src; src_le != NULL; src_le = src_le->next) {
        struct data_source *source;
        char* source_name;
        source = (struct data_source *)src_le->data;
        source_name = get_data_source_name(source);
        byte_view_tab_->addTab(source_name, get_data_source_tvb(source), edt_.tree, proto_tree_,
                               cap_file_.capFile()->current_frame->flags.encoding);
        wmem_free(NULL, source_name);
    }
    byte_view_tab_->setCurrentIndex(0);

    ui->packetSplitter->setStretchFactor(0, 5);
    ui->packetSplitter->setStretchFactor(1, 1);

    QStringList col_parts;
    for (int i = 0; i < cap_file_.capFile()->cinfo.num_cols; ++i) {
        // ElidedLabel doesn't support rich text / HTML
        col_parts << QString("%1: %2")
                     .arg(get_column_title(i))
                     .arg(cap_file_.capFile()->cinfo.col_data[i]);
    }
    col_info_ = col_parts.join(" " UTF8_MIDDLE_DOT " ");
    setHintText();

    connect(this, SIGNAL(monospaceFontChanged(QFont)),
            proto_tree_, SLOT(setMonospaceFont(QFont)));
    connect(this, SIGNAL(monospaceFontChanged(QFont)),
            byte_view_tab_, SLOT(setMonospaceFont(QFont)));

    connect(proto_tree_, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),
            byte_view_tab_, SLOT(protoTreeItemChanged(QTreeWidgetItem*)));
    connect(byte_view_tab_, SIGNAL(byteFieldHovered(QString&)),
            this, SLOT(setHintText(QString&)));
}
Example #2
0
File: qte.cpp Project: Kafay/vlc
/*****************************************************************************
 * main loop of qtapplication
 *****************************************************************************/
static void* RunQtThread( vlc_object_t *p_this )
{
    event_thread_t *p_event = (event_thread_t *)p_this;
    int canc = vlc_savecancel ();
    msg_Dbg( p_event->p_vout, "RunQtThread starting" );

#ifdef NEED_QTE_MAIN
    if (qApp)
    {
        p_event->p_vout->p_sys->p_QApplication = qApp;
        p_event->p_vout->p_sys->bOwnsQApp = FALSE;
        p_event->p_vout->p_sys->p_VideoWidget = qApp->mainWidget();
        msg_Dbg( p_event->p_vout, "RunQtThread applicaton attached" );
    }
#else
    if (qApp==NULL)
    {
        int argc = 0;
        QApplication* pApp = new QApplication(argc, NULL);
        if(pApp)
        {
            p_event->p_vout->p_sys->p_QApplication = pApp;
            p_event->p_vout->p_sys->bOwnsQApp = TRUE;
        }
        QWidget* pWidget = new QWidget();
        if (pWidget)
            {
            p_event->p_vout->p_sys->p_VideoWidget = pWidget;
        }
    }
#endif
    /* signal the creation of the window */
    vlc_thread_ready( p_event );
    msg_Dbg( p_event->p_vout, "RunQtThread ready" );

    if (p_event->p_vout->p_sys->p_QApplication)
    {
        /* Set default window width and heigh to exactly preferred size. */
            QWidget *desktop = p_event->p_vout->p_sys->p_QApplication->desktop();
            p_event->p_vout->p_sys->p_VideoWidget->setMinimumWidth( 10 );
             p_event->p_vout->p_sys->p_VideoWidget->setMinimumHeight( 10 );
            p_event->p_vout->p_sys->p_VideoWidget->setBaseSize( p_event->p_vout->p_sys->i_width,
            p_event->p_vout->p_sys->i_height );
        p_event->p_vout->p_sys->p_VideoWidget->setMaximumWidth( desktop->width() );
        p_event->p_vout->p_sys->p_VideoWidget->setMaximumHeight( desktop->height() );
        /* Check on fullscreen */
        if (p_event->p_vout->b_fullscreen)
                  p_event->p_vout->p_sys->p_VideoWidget->showFullScreen();
        else
                p_event->p_vout->p_sys->p_VideoWidget->showNormal();

        p_event->p_vout->p_sys->p_VideoWidget->show();
        p_event->p_vout->p_sys->bRunning = TRUE;

#ifdef NEED_QTE_MAIN
        while(vlc_object_alive (p_event) && p_event->p_vout->p_sys->bRunning)
              {
               /* Check if we are asked to exit */
           if( !vlc_object_alive (p_event) )
               break;

               msleep(100);
            }
#else
        // run the main loop of qtapplication until someone says: 'quit'
        p_event->p_vout->p_sys->pcQApplication->exec();
#endif
    }

#ifndef NEED_QTE_MAIN
    if(p_event->p_vout->p_sys->p_QApplication)
    {
        delete p_event->p_vout->p_sys->p_VideoWidget;
        p_event->p_vout->p_sys->p_VideoWidget = NULL;
        delete p_event->p_vout->p_sys->p_QApplication;
        p_event->p_vout->p_sys->p_QApplication = NULL;
    }
#else
    p_event->p_vout->p_sys->p_VideoWidget = NULL;
#endif

    msg_Dbg( p_event->p_vout, "RunQtThread terminating" );
    vlc_restorecancel (canc);
    return NULL;
}
Example #3
0
QStringList qt_mac_get_open_file_names(const QFileDialogArgs &args, QString *pwd,
                                       QString *selectedFilter)
{
    QWidget *parent = args.parent;
    OSErr err;
    QStringList retstrl;

    NavDialogCreationOptions options;
    NavGetDefaultDialogCreationOptions(&options);
    options.modality = kWindowModalityAppModal;
    options.optionFlags |= kNavSupportPackages;
    if (args.options & QFileDialog::DontConfirmOverwrite)
        options.optionFlags |= kNavDontConfirmReplacement;
    if (args.mode != QFileDialog::ExistingFiles)
        options.optionFlags &= ~kNavAllowMultipleFiles;

    if (!args.caption.isEmpty())
        options.windowTitle = QCFString::toCFStringRef(args.caption);

    static const int w = 450, h = 350;
    options.location.h = options.location.v = -1;
    if (parent && parent->isVisible()) {
        WindowClass wclass;
        GetWindowClass(qt_mac_window_for(parent), &wclass);
        if (!(args.options & QFileDialog::DontUseSheet) && (wclass == kDocumentWindowClass ||
                                                            wclass == kFloatingWindowClass || wclass == kMovableModalWindowClass)) {
            options.modality = kWindowModalityWindowModal;
            options.parentWindow = qt_mac_window_for(parent);
        } else {
            parent = parent->window();
            QString s = parent->windowTitle();
            options.clientName = QCFString::toCFStringRef(s);
            options.location.h = (parent->x() + (parent->width() / 2)) - (w / 2);
            options.location.v = (parent->y() + (parent->height() / 2)) - (h / 2);

            QRect r = QApplication::desktop()->screenGeometry(
                QApplication::desktop()->screenNumber(parent));
            const int border = 10;
            if (options.location.h + w > r.right())
                options.location.h -= (options.location.h + w) - r.right() + border;
            if (options.location.v + h > r.bottom())
                options.location.v -= (options.location.v + h) - r.bottom() + border;
            if (options.location.h < r.left())
                options.location.h = r.left() + border;
            if (options.location.v < r.top())
                options.location.v = r.top() + border;
        }
#if 0
    } else if (QWidget *p = qApp->mainWidget()) {
        static int last_screen = -1;
        int scr = QApplication::desktop()->screenNumber(p);
        if (last_screen != scr) {
            QRect r = QApplication::desktop()->screenGeometry(scr);
            options.location.h = (r.x() + (r.width() / 2)) - (w / 2);
            options.location.v = (r.y() + (r.height() / 2)) - (h / 2);
        }
#endif
    }

    QList<qt_mac_filter_name*> filts = qt_mac_make_filters_list(args.filter);
    qt_mac_nav_filter_type t;
    t.saveDialog = false;
    t.index = 0;
    t.filts = &filts;
    if (filts.count() > 1) {
        int i = 0;
        CFStringRef *arr = static_cast<CFStringRef *>(malloc(sizeof(CFStringRef) * filts.count()));
        for (QList<qt_mac_filter_name*>::const_iterator it = filts.constBegin();
             it != filts.constEnd(); ++it)
            arr[i++] = QCFString::toCFStringRef((*it)->description);
        options.popupExtension = CFArrayCreate(0, reinterpret_cast<const void **>(arr), filts.count(), 0);
    }

    NavDialogRef dlg;
    if (args.mode == QFileDialog::DirectoryOnly ||
        args.mode == QFileDialog::Directory) {
        if (NavCreateChooseFolderDialog(&options, make_navProcUPP(), 0, 0, &dlg)) {
            qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__);
            return retstrl;
        }
    } else {
        if (NavCreateGetFileDialog(&options, 0, make_navProcUPP(), 0,
                                  make_navFilterUPP(), (void *) (filts.isEmpty() ? 0 : &t),
                                  &dlg)) {
            qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__);
            return retstrl;
        }
    }
    if (pwd && !pwd->isEmpty()) {
        FSRef fsref;
        if (qt_mac_create_fsref(*pwd, &fsref) == noErr) {
            AEDesc desc;
            if (AECreateDesc(typeFSRef, &fsref, sizeof(FSRef), &desc) == noErr)
                NavCustomControl(dlg, kNavCtlSetLocation, (void*)&desc);
        }
    }

    NavDialogRun(dlg);

    if (selectedFilter) {
        NavMenuItemSpec navSpec;
        bzero(&navSpec, sizeof(NavMenuItemSpec));
        qt_mac_filter_name *sel_filt_name = qt_mac_make_filters_list(*selectedFilter).at(0);
        for (int i = 0; i < filts.count(); ++i) {
            const qt_mac_filter_name *filter = filts.at(i);
            if (sel_filt_name->description == filter->description
                    && sel_filt_name->regxp == filter->regxp
                    && sel_filt_name->filter == filter->filter) {
                navSpec.menuType = i;
                break;
            }
        }
        NavCustomControl(dlg, kNavCtlSelectCustomType, &navSpec);
    }

    if (options.modality == kWindowModalityWindowModal) { //simulate modality
        QWidget modal_widg(parent, Qt::Sheet);
        modal_widg.createWinId();
        QApplicationPrivate::enterModal(&modal_widg);
        while (g_nav_blocking)
            qApp->processEvents(QEventLoop::WaitForMoreEvents);
        QApplicationPrivate::leaveModal(&modal_widg);
    }

    if (!(NavDialogGetUserAction(dlg) &
          (kNavUserActionOpen | kNavUserActionChoose | kNavUserActionNewFolder))) {
        NavDialogDispose(dlg);
        return retstrl;
    }
    NavReplyRecord ret;
    NavDialogGetReply(dlg, &ret);
    NavDialogDispose(dlg);

    long count;
    err = AECountItems(&(ret.selection), &count);
    if (!ret.validRecord || err != noErr || !count) {
        NavDisposeReply(&ret);
        return retstrl;
    }

    for (long index = 1; index <= count; index++) {
        FSRef ref;
        err = AEGetNthPtr(&(ret.selection), index, typeFSRef, 0, 0, &ref, sizeof(ref), 0);
        if (err != noErr)
            break;

        if (!str_buffer) {
            qAddPostRoutine(cleanup_str_buffer);
            str_buffer = (UInt8 *)malloc(1024);
        }
        FSRefMakePath(&ref, str_buffer, 1024);
        retstrl.append(QString::fromUtf8((const char *)str_buffer));
    }
    NavDisposeReply(&ret);
    if (selectedFilter)
        *selectedFilter = filts.at(t.index)->filter;
    while (!filts.isEmpty())
        delete filts.takeFirst();
    return retstrl;
}
Example #4
0
CityTime::CityTime( QWidget *parent, const char* name,
                            WFlags fl )
    : CityTimeBase( parent, name, fl ),
      strRealTz(0),
      bAdded(false)
{
    Config config( "qpe" );
    config.setGroup( "Time" );
    bWhichClock = config.readBoolEntry( "AMPM", TRUE );
    odebug << QString("%1").arg(bWhichClock) << oendl;
    frmMap->changeClock( bWhichClock );

    char *pEnv;
    pEnv = NULL;
    pEnv = getenv("TZ");
    if ( pEnv )
        strRealTz = pEnv;
    pEnv = NULL;
    pEnv = getenv("HOME");
    if ( pEnv )
        strHome = pEnv;
    // append the labels to their respective lists...
    listCities.setAutoDelete( true );
    listTimes.setAutoDelete( true );

    listCities.append( cmdCity1 );
    listCities.append( cmdCity2 );
    listCities.append( cmdCity3 );

    listTimes.append( lblCTime1 );
    listTimes.append( lblCTime2 );
    listTimes.append( lblCTime3 );


    // kludgy way of getting the screen size so we don't have to depend
    // on a resize event...
    QWidget *d = QApplication::desktop();
    if ( d->width() < d->height() ) {
        // append for that 4 down look
        listCities.append( cmdCity4 );
        listCities.append( cmdCity5 );
        listCities.append( cmdCity6 );
        listTimes.append( lblCTime4 );
        listTimes.append( lblCTime5 );
        listTimes.append( lblCTime6 );
        lblCTime7->hide();
        lblCTime8->hide();
        lblCTime9->hide();
        cmdCity7->hide();
        cmdCity8->hide();
        cmdCity9->hide();
    } else {
        listCities.append( cmdCity7 );
        listCities.append( cmdCity8 );
        listCities.append( cmdCity9 );
        listTimes.append( lblCTime7 );
        listTimes.append( lblCTime8 );
        listTimes.append( lblCTime9 );
        lblCTime4->hide();
        lblCTime5->hide();
        lblCTime6->hide();
        cmdCity4->hide();
        cmdCity5->hide();
        cmdCity6->hide();
    }

    selWidget = frmMap->selectionWidget( this );
    selWidget->hide();
    CityTimeBaseLayout->addWidget( selWidget );
    bAdded = true;
    readInTimes();
    changed = FALSE;
    QObject::connect( qApp, SIGNAL( clockChanged(bool) ),
                      this, SLOT( changeClock(bool) ) );
    // now start the timer so we can update the time quickly every second
    timerEvent( 0 );
}
Example #5
0
bool BookmarkToolBar::eventFilter(QObject *watched, QEvent *event)
{
    if (m_currentMenu && m_currentMenu->isVisible()
            && !m_currentMenu->rect().contains(m_currentMenu->mapFromGlobal(QCursor::pos())))
    {
        // To switch root folders as in a menubar

        KBookmarkActionMenu* act = dynamic_cast<KBookmarkActionMenu *>(actionAt(mapFromGlobal(QCursor::pos())));

        if (event->type() == QEvent::MouseMove && act && act->menu() != m_currentMenu)
        {
            m_currentMenu->hide();
            QPoint pos = mapToGlobal(widgetForAction(act)->pos());
            act->menu()->popup(QPoint(pos.x(), pos.y() + widgetForAction(act)->height()));
        }
        else if (event->type() == QEvent::MouseButtonPress && act)
        {
            m_currentMenu->hide();
        }

        return QObject::eventFilter(watched, event);
    }

    switch (event->type())
    {
    case QEvent::Show:
    {
        if (!m_filled)
        {
            BookmarkManager::self()->fillBookmarkBar(this);
            m_filled = true;
        }
    }
    break;

    case QEvent::ActionRemoved:
    {
        QActionEvent *actionEvent = static_cast<QActionEvent*>(event);
        if (actionEvent && actionEvent->action() != m_dropAction)
        {
            QWidget *widget = widgetForAction(actionEvent->action());
            if (widget)
            {
                widget->removeEventFilter(this);
            }
        }
    }
    break;

    case QEvent::ParentChange:
    {
        QActionEvent *actionEvent = static_cast<QActionEvent*>(event);
        if (actionEvent && actionEvent->action() != m_dropAction)
        {
            QWidget *widget = widgetForAction(actionEvent->action());
            if (widget)
            {
                widget->removeEventFilter(this);
            }
        }
    }
    break;

    case QEvent::DragEnter:
    {
        QDragEnterEvent *dragEvent = static_cast<QDragEnterEvent*>(event);
        if (dragEvent->mimeData()->hasFormat(BookmarkManager::bookmark_mime_type())
                || dragEvent->mimeData()->hasFormat("text/uri-list")
                || dragEvent->mimeData()->hasFormat("text/plain"))
        {
            QFrame* dropIndicatorWidget = new QFrame(this);
            dropIndicatorWidget->setFrameShape(QFrame::VLine);
            m_dropAction = insertWidget(actionAt(dragEvent->pos()), dropIndicatorWidget);

            dragEvent->accept();
        }
    }
    break;

    case QEvent::DragLeave:
    {
        QDragLeaveEvent *dragEvent = static_cast<QDragLeaveEvent*>(event);

        if (m_checkedAction)
        {
            m_checkedAction->setCheckable(false);
            m_checkedAction->setChecked(false);
        }

        delete m_dropAction;
        m_dropAction = 0;
        dragEvent->accept();
    }
    break;

    case QEvent::DragMove:
    {
        QDragMoveEvent *dragEvent = static_cast<QDragMoveEvent*>(event);
        if (dragEvent->mimeData()->hasFormat(BookmarkManager::bookmark_mime_type())
                || dragEvent->mimeData()->hasFormat("text/uri-list")
                || dragEvent->mimeData()->hasFormat("text/plain"))
        {
            QAction *overAction = actionAt(dragEvent->pos());
            KBookmarkActionInterface *overActionBK = dynamic_cast<KBookmarkActionInterface*>(overAction);
            QWidget *widgetAction = widgetForAction(overAction);

            if (overAction != m_dropAction && overActionBK && widgetAction && m_dropAction)
            {
                removeAction(m_dropAction);
                if (m_checkedAction)
                {
                    m_checkedAction->setCheckable(false);
                    m_checkedAction->setChecked(false);
                }

                if (!overActionBK->bookmark().isGroup())
                {
                    if ((dragEvent->pos().x() - widgetAction->pos().x()) > (widgetAction->width() / 2))
                    {
                        if (actions().count() >  actions().indexOf(overAction) + 1)
                        {
                            insertAction(actions().at(actions().indexOf(overAction) + 1), m_dropAction);
                        }
                        else
                        {
                            addAction(m_dropAction);
                        }
                    }
                    else
                    {
                        insertAction(overAction, m_dropAction);
                    }
                }
                else
                {
                    if ((dragEvent->pos().x() - widgetAction->pos().x()) >= (widgetAction->width() * 0.75))
                    {
                        if (actions().count() >  actions().indexOf(overAction) + 1)
                        {
                            insertAction(actions().at(actions().indexOf(overAction) + 1), m_dropAction);
                        }
                        else
                        {
                            addAction(m_dropAction);
                        }
                    }
                    else if ((dragEvent->pos().x() - widgetAction->pos().x()) <= (widgetAction->width() * 0.25))
                    {
                        insertAction(overAction, m_dropAction);
                    }
                    else
                    {
                        overAction->setCheckable(true);
                        overAction->setChecked(true);
                        m_checkedAction = overAction;
                    }
                }

                dragEvent->accept();
            }
        }
    }
    break;


    case QEvent::Drop:
    {
        QDropEvent *dropEvent = static_cast<QDropEvent*>(event);
        KBookmark bookmark;
        KBookmarkGroup root = BookmarkManager::self()->manager()->toolbar();

        if (m_checkedAction)
        {
            m_checkedAction->setCheckable(false);
            m_checkedAction->setChecked(false);
        }

        if (dropEvent->mimeData()->hasFormat(BookmarkManager::bookmark_mime_type()))
        {
            QByteArray addresses = dropEvent->mimeData()->data(BookmarkManager::bookmark_mime_type());
            bookmark =  BookmarkManager::self()->findByAddress(QString::fromLatin1(addresses.data()));
            if (bookmark.isNull())
                return false;
        }
        else if (dropEvent->mimeData()->hasFormat("text/uri-list"))
        {
            // DROP is URL
            QString url = dropEvent->mimeData()->urls().at(0).toString();
            WebWindow *w = qobject_cast<WebWindow *>(parent());
            QString title = url.contains(w->url().url())
                            ? w->title()
                            : url;
            bookmark = root.addBookmark(title, url);
        }
        else if (dropEvent->mimeData()->hasFormat("text/plain"))
        {
            // DROP is TEXT
            QString url = dropEvent->mimeData()->text();
            KUrl u(url);
            if (u.isValid())
            {
                WebWindow *w = qobject_cast<WebWindow *>(parent());
                QString title = url.contains(w->url().url())
                                ? w->title()
                                : url;
                bookmark = root.addBookmark(title, url);
            }
        }
        else
        {
            return false;
        }

        QAction *destAction = actionAt(dropEvent->pos());
        if (destAction && destAction == m_dropAction)
        {
            if (actions().indexOf(m_dropAction) > 0)
            {
                destAction = actions().at(actions().indexOf(m_dropAction) - 1);
            }
            else
            {
                destAction = actions().at(1);
            }
        }

        if (destAction)
        {
            KBookmarkActionInterface *destBookmarkAction = dynamic_cast<KBookmarkActionInterface *>(destAction);
            QWidget *widgetAction = widgetForAction(destAction);

            if (destBookmarkAction && !destBookmarkAction->bookmark().isNull() && widgetAction
                    && bookmark.address() != destBookmarkAction->bookmark().address())
            {
                KBookmark destBookmark = destBookmarkAction->bookmark();

                if (!destBookmark.isGroup())
                {
                    if ((dropEvent->pos().x() - widgetAction->pos().x()) >= (widgetAction->width() / 2))
                    {
                        root.moveBookmark(bookmark, destBookmark);
                    }
                    else
                    {
                        root.moveBookmark(bookmark, destBookmark.parentGroup().previous(destBookmark));
                    }
                }
                else
                {
                    if ((dropEvent->pos().x() - widgetAction->pos().x()) >= (widgetAction->width() * 0.75))
                    {
                        root.moveBookmark(bookmark, destBookmark);
                    }
                    else if ((dropEvent->pos().x() - widgetAction->pos().x()) <= (widgetAction->width() * 0.25))
                    {
                        root.moveBookmark(bookmark, destBookmark.parentGroup().previous(destBookmark));
                    }
                    else
                    {
                        destBookmark.toGroup().addBookmark(bookmark);
                    }
                }


                BookmarkManager::self()->emitChanged();
            }
        }
        else
        {
            root.deleteBookmark(bookmark);
            bookmark = root.addBookmark(bookmark);
            if (dropEvent->pos().x() < widgetForAction(actions().first())->pos().x())
            {
                root.moveBookmark(bookmark, KBookmark());
            }

            BookmarkManager::self()->emitChanged();
        }
        dropEvent->accept();
    }
    break;

    default:
        break;
    }

    QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);

    // These events need to be handled only for Bookmark actions and not the bar
    if (watched != this && mouseEvent)
    {
        switch (event->type())
        {
        case QEvent::MouseButtonPress: // drag handling
        {
            QPoint pos = mapFromGlobal(QCursor::pos());
            KBookmarkActionInterface *action = dynamic_cast<KBookmarkActionInterface *>(actionAt(pos));

            if (action && mouseEvent->button() != Qt::MiddleButton)
            {
                m_dragAction = actionAt(pos);
                m_startDragPos = pos;

                // The menu is displayed only when the mouse button is released
                if (action->bookmark().isGroup())
                    return true;
            }
        }
        break;

        case QEvent::MouseMove:
        {
            int distance = (mapFromGlobal(QCursor::pos()) - m_startDragPos).manhattanLength();
            if (!m_currentMenu && distance >= QApplication::startDragDistance())
            {
                startDrag();
            }
        }
        break;

        case QEvent::MouseButtonRelease:
        {
            QPoint destPos = mapFromGlobal(QCursor::pos());
            int distance = (destPos - m_startDragPos).manhattanLength();
            KBookmarkActionInterface *action = dynamic_cast<KBookmarkActionInterface *>(actionAt(destPos));

            if (action)
            {
                if (action->bookmark().isGroup())
                {
                    if (mouseEvent->button() == Qt::MiddleButton)
                    {
                        BookmarkManager::self()->owner()->loadBookmarkFolder(action->bookmark());
                    }
                    else if (distance < QApplication::startDragDistance())
                    {
                        KBookmarkActionMenu *menu = dynamic_cast<KBookmarkActionMenu *>(actionAt(m_startDragPos));
                        QPoint actionPos = mapToGlobal(widgetForAction(menu)->pos());
                        menu->menu()->popup(QPoint(actionPos.x(), actionPos.y() + widgetForAction(menu)->height()));
                    }
                }
                else
                {
                    if (!action->bookmark().isNull() && !action->bookmark().isSeparator())
                    {
                        if (mouseEvent->button() == Qt::MiddleButton)
                        {
                            BookmarkManager::self()->owner()->loadBookmarkInNewTab(action->bookmark());
                        }
                    }
                }
            }
        }
        break;

        default:
            break;
        }
    }

    return QObject::eventFilter(watched, event);
}
QGLWidgetTest::QGLWidgetTest(const QGLFormat& Format, QWidget *parent) : QGLWidget(Format, parent) {
#else
QGLWidgetTest::QGLWidgetTest(QWidget * parent) : QGLWidget(parent) {
#endif

#ifdef _DEBUG
	SysUtils::RedirectIOToConsole();
#endif

	GError err;

	// create a new kernel
	gKernel = new GKernel();
	// build path for data
	GString dataPath = SysUtils::AmanithPath();
	if (dataPath.length() > 0)
		dataPath += "data/";

	// load glyphs and triangulate them
	err = LoadAndTesselateGlyphs(dataPath + "cards.ttf", (GReal)1e-7);
	if (err != G_NO_ERROR) {
		perror("Fail to load cards.ttf");
		abort();
	}
	// load cards and animations
	err = LoadCardsAndAnimations(dataPath + "cards.xml");
	if (err != G_NO_ERROR) {
		perror("Fail to load cards.xml");
		abort();
	}
	// load and initialize background
	LoadBackGraoundAndLogo(dataPath + "stars.png");
	// initialize random generator
	GMath::SeedRandom();
	// begin with 9 cards
	gMaxCards = 9;
	gBlockAnim = G_FALSE;
	gLogicTick = 0.5;
	gAnimCards.resize(gMaxCards);
	// resize the window
	QWidget *d = (QWidget *)QApplication::desktop();
	GInt32 winSize = GMath::Min(d->width(), d->height());
	this->resize(winSize-64, winSize-64);
}

//------------------------------------------------------------
void QGLWidgetTest::LoadBackGraoundAndLogo(const GString& FileName) {

	GError err;

	// create and load background texture
	gBackGround = (GPixelMap *)gKernel->CreateNew(G_PIXELMAP_CLASSID);
	if (!gBackGround)  {
		perror("Fail to create background GPixelMap");
		abort();
	}
	// use 'expandpalette' option just to ensure full color format (so artists can manipulate starts.png as
	// they want to do
	err = gBackGround->Load(StrUtils::ToAscii(FileName), "expandpalette=true");
	if (err != G_NO_ERROR) {
		perror("Fail to load stars.png");
		abort();
	}

	gBackGroundAnimUV = (GAnimTRSNode2D *)gKernel->CreateNew(G_ANIMTRSNODE2D_CLASSID);
	gBackGroundAnimColor = (GThreeHermiteProperty1D *)gKernel->CreateNew(G_THREEHERMITEPROPERTY1D_CLASSID);
	if (!gBackGroundAnimUV || !gBackGroundAnimColor) {
		perror("Fail to create background animations");
		abort();
	}
	// set uv animation
	gBackGroundAnimUV->SetPivotPosition(GPoint2(0.5, 0.5), G_FALSE);
	GHermiteProperty1D *p;
	GDynArray<GKeyValue> tmpKeys;

	// x-position
	tmpKeys.clear();
	p = (GHermiteProperty1D *)gBackGroundAnimUV->Property("transform")->Property("position")->Property("x");
	p->SetOORAfter(G_LOOP_OOR);
	tmpKeys.push_back(GKeyValue((GTimeValue)0.00, (GReal)-2));
	tmpKeys.push_back(GKeyValue((GTimeValue)0.33, (GReal)2));
	tmpKeys.push_back(GKeyValue((GTimeValue)0.67, (GReal)0));
	tmpKeys.push_back(GKeyValue((GTimeValue)1.00, (GReal)-2));
	p->SetKeys(tmpKeys);
	// y-position
	tmpKeys.clear();
	p = (GHermiteProperty1D *)gBackGroundAnimUV->Property("transform")->Property("position")->Property("y");
	p->SetOORAfter(G_LOOP_OOR);
	tmpKeys.push_back(GKeyValue((GTimeValue)0.00, (GReal)1));
	tmpKeys.push_back(GKeyValue((GTimeValue)0.33, (GReal)2));
	tmpKeys.push_back(GKeyValue((GTimeValue)0.67, (GReal)-2));
	tmpKeys.push_back(GKeyValue((GTimeValue)1.00, (GReal)1));
	p->SetKeys(tmpKeys);
	// rotation
	tmpKeys.clear();
	p = (GHermiteProperty1D *)gBackGroundAnimUV->Property("transform")->Property("rotation");
	p->SetOORAfter(G_LOOP_OOR);
	tmpKeys.push_back(GKeyValue((GTimeValue)0.00, (GReal)0));
	tmpKeys.push_back(GKeyValue((GTimeValue)0.25, (GReal)1.57 * 2));
	tmpKeys.push_back(GKeyValue((GTimeValue)0.50, (GReal)3.14 * 2));
	tmpKeys.push_back(GKeyValue((GTimeValue)0.75, (GReal)4.71 * 2));
	tmpKeys.push_back(GKeyValue((GTimeValue)1.00, (GReal)6.28 * 2));
	p->SetKeys(tmpKeys);
	// x-scale
	tmpKeys.clear();
	p = (GHermiteProperty1D *)gBackGroundAnimUV->Property("transform")->Property("scale")->Property("x");
	p->SetOORAfter(G_LOOP_OOR);
	tmpKeys.push_back(GKeyValue((GTimeValue)0.00, (GReal)1));
	tmpKeys.push_back(GKeyValue((GTimeValue)0.33, (GReal)3));
	tmpKeys.push_back(GKeyValue((GTimeValue)0.67, (GReal)0.9));
	tmpKeys.push_back(GKeyValue((GTimeValue)1.00, (GReal)1));
	p->SetKeys(tmpKeys);
	// y-scale
	tmpKeys.clear();
	p = (GHermiteProperty1D *)gBackGroundAnimUV->Property("transform")->Property("scale")->Property("y");
	p->SetOORAfter(G_LOOP_OOR);
	tmpKeys.push_back(GKeyValue((GTimeValue)0.00, (GReal)1));
	tmpKeys.push_back(GKeyValue((GTimeValue)0.33, (GReal)3));
	tmpKeys.push_back(GKeyValue((GTimeValue)0.67, (GReal)0.9));
	tmpKeys.push_back(GKeyValue((GTimeValue)1.00, (GReal)1));
	p->SetKeys(tmpKeys);

	// red color
	tmpKeys.clear();
	p = (GHermiteProperty1D *)gBackGroundAnimColor->Property("x");
	p->SetOORAfter(G_LOOP_OOR);
	tmpKeys.push_back(GKeyValue((GTimeValue)0.00, (GReal)0.7));
	tmpKeys.push_back(GKeyValue((GTimeValue)0.50, (GReal)0.0));
	tmpKeys.push_back(GKeyValue((GTimeValue)0.75, (GReal)0.0));
	tmpKeys.push_back(GKeyValue((GTimeValue)1.00, (GReal)0.7));
	p->SetKeys(tmpKeys);
	// green color
	tmpKeys.clear();
	p = (GHermiteProperty1D *)gBackGroundAnimColor->Property("y");
	p->SetOORAfter(G_LOOP_OOR);
	tmpKeys.push_back(GKeyValue((GTimeValue)0.00, (GReal)0.0));
	tmpKeys.push_back(GKeyValue((GTimeValue)0.50, (GReal)0.1));
	tmpKeys.push_back(GKeyValue((GTimeValue)0.75, (GReal)0.7));
	tmpKeys.push_back(GKeyValue((GTimeValue)1.00, (GReal)0.0));
	p->SetKeys(tmpKeys);
	// blue color
	tmpKeys.clear();
	p = (GHermiteProperty1D *)gBackGroundAnimColor->Property("z");
	p->SetOORAfter(G_LOOP_OOR);
	tmpKeys.push_back(GKeyValue((GTimeValue)0.00, (GReal)0.5));
	tmpKeys.push_back(GKeyValue((GTimeValue)0.50, (GReal)0.6));
	tmpKeys.push_back(GKeyValue((GTimeValue)0.75, (GReal)0.3));
	tmpKeys.push_back(GKeyValue((GTimeValue)1.00, (GReal)0.5));
	p->SetKeys(tmpKeys);

	// now set up logo
	gAnimLogo = (GAnimTRSNode2D *)gKernel->CreateNew(G_ANIMTRSNODE2D_CLASSID);	
	gAnimLogo->SetPivotPosition(GPoint2((GReal)0.550, (GReal)0.540), G_FALSE);

	gAnimLogo->Property("transform")->Property("position")->Property("x")->SetDefaultValue(GKeyValue((GReal)0.6));
	gAnimLogo->Property("transform")->Property("position")->Property("y")->SetDefaultValue(GKeyValue((GReal)-1.23));

	// x-scale
	tmpKeys.clear();
	gAnimLogo->Property("transform")->Property("scale")->Property("y")->SetDefaultValue(GKeyValue((GReal)1.5));
	p = (GHermiteProperty1D *)gAnimLogo->Property("transform")->Property("scale")->Property("x");
	p->SetOORAfter(G_LOOP_OOR);
	tmpKeys.push_back(GKeyValue((GTimeValue)0.00, (GReal)1.5));
	tmpKeys.push_back(GKeyValue((GTimeValue)0.50, (GReal)-1.5));
	tmpKeys.push_back(GKeyValue((GTimeValue)1.00, (GReal)1.5));
	p->SetKeys(tmpKeys);

	gBackGroundTime = 0;
	gBackGroundTimeStep = (GReal)0.001;
}
Example #7
0
//-----------------------------------------------------------------------------
int ctkVTKMagnifyViewTest2(int argc, char * argv [] )
{
  QApplication app(argc, argv);

  // Command line parser
  ctkCommandLineParser parser;
  parser.addArgument("", "-D", QVariant::String);
  parser.addArgument("", "-V", QVariant::String);
  parser.addArgument("", "-I", QVariant::String);
  parser.addArgument("", "-T", QVariant::String);
  parser.addArgument("", "-S", QVariant::String);
  parser.addArgument("", "-M", QVariant::String);
  bool ok = false;
  QHash<QString, QVariant> parsedArgs = parser.parseArguments(app.arguments(), &ok);
  if (!ok)
    {
    std::cerr << qPrintable(parser.errorString()) << std::endl;
    return EXIT_FAILURE;
    }
  QString dataDirectory = parsedArgs["-D"].toString();
  QString baselineDirectory = parsedArgs["-V"].toString();
  QString testType = parsedArgs["-T"].toString();
  bool interactive = parsedArgs["-I"].toBool();
  int size = parsedArgs["-S"].toInt();
  double magnification = parsedArgs["-M"].toDouble();

  // Create the parent widget
  QWidget parentWidget;
  QHBoxLayout layout(&parentWidget);

  // Magnify widget parameters (we want an odd widget size and odd bullsEye)
  bool showCrosshair = true;
  QPen crosshairPen(Qt::yellow);
  crosshairPen.setJoinStyle(Qt::MiterJoin);
  ctkCrosshairLabel::CrosshairType crosshairType
      = ctkCrosshairLabel::BullsEyeCrosshair;
  double bullsEyeWidth = magnification + 2;
  QColor marginColor = Qt::magenta;
  bool observeRenderWindowEvents = false;
  int updateInterval = 0;

  // Create the magnify widget
  ctkVTKMagnifyView * magnify = new ctkVTKMagnifyView(&parentWidget);
  magnify->setMinimumSize(size,size);
  magnify->setMaximumSize(size,size);
  magnify->setShowCrosshair(showCrosshair);
  magnify->setCrosshairPen(crosshairPen);
  magnify->setCrosshairType(crosshairType);
  magnify->setBullsEyeWidth(bullsEyeWidth);
  magnify->setMarginColor(marginColor);
  magnify->setMagnification(magnification);
  magnify->setObserveRenderWindowEvents(observeRenderWindowEvents);
  magnify->setUpdateInterval(updateInterval);
  layout.addWidget(magnify);

  // Test magnify widget parameters
  if (magnify->showCrosshair() != showCrosshair)
    {
    std::cerr << "ctkVTKMagnifyView:setShowCrosshair failed. "
              << magnify->showCrosshair() << std::endl;
    return EXIT_FAILURE;
    }
  if (magnify->crosshairPen() != crosshairPen)
    {
    std::cerr << "ctkVTKMagnifyView:setCrosshairPen failed. "
              << qPrintable(magnify->crosshairPen().color().name()) << std::endl;
    return EXIT_FAILURE;
    }
  if (magnify->crosshairType() != crosshairType)
    {
    std::cerr << "ctkVTKMagnifyView:setCrosshairType failed. "
              << magnify->crosshairType() << std::endl;
    return EXIT_FAILURE;
    }
  if (magnify->bullsEyeWidth() != bullsEyeWidth)
    {
    std::cerr << "ctkVTKMagnifyView:setBullsEyeWidth failed. "
              << magnify->bullsEyeWidth() << std::endl;
    return EXIT_FAILURE;
    }
  if (magnify->marginColor() != marginColor)
    {
    std::cerr << "ctkVTKMagnifyView:setMarginColor failed. "
              << qPrintable(magnify->marginColor().name()) << std::endl;
    return EXIT_FAILURE;
    }
  if (magnify->magnification() != magnification)
    {
    std::cerr << "ctkVTKMagnifyView:setMagnification failed. "
              << magnify->magnification() << std::endl;
    return EXIT_FAILURE;
    }
  if (magnify->observeRenderWindowEvents() != observeRenderWindowEvents)
    {
    std::cerr << "ctkVTKMagnifyView:setObserveRenderWindowEvents failed. "
              << magnify->observeRenderWindowEvents() << std::endl;
    }
  if (magnify->updateInterval() != updateInterval)
    {
    std::cerr << "ctkVTKMagnifyView:setUpdateInterval failed. "
              << magnify->updateInterval() << std::endl;
    return EXIT_FAILURE;
    }

  // The remainder is interactive, so abort now if command line args specify otherwise
  if (interactive)
    {
    return EXIT_SUCCESS;
    }

  // Add observed ctkVTKSliceViews (there are three, and the first two are observed)
  QList<ctkVTKSliceView *> allSliceViews;
  int numSliceViews = 3;
  for (int i = 0; i < numSliceViews; i++)
    {
    allSliceViews.append(new ctkVTKSliceView(&parentWidget));
    layout.addWidget(allSliceViews[i]);
    }

  // Observe the first two widgets
  magnify->observe(allSliceViews[0]->VTKWidget());
  magnify->observe(allSliceViews[1]->VTKWidget());
  if (!magnify->isObserved(allSliceViews[0]->VTKWidget()) ||
      !magnify->isObserved(allSliceViews[1]->VTKWidget()) ||
      magnify->isObserved(allSliceViews[2]->VTKWidget()) ||
      magnify->numberObserved() != 2)
    {
    std::cerr << "ctkVTKMagnifyView:observe(QVTKWidget*) failed. "
              << "Number observed = " << magnify->numberObserved() << std::endl;
    return EXIT_FAILURE;
    }

  QString imageFilename = dataDirectory + "/" + "computerIcon.png";

  // Instanciate the reader factory
  vtkSmartPointer<vtkImageReader2Factory> imageFactory =
      vtkSmartPointer<vtkImageReader2Factory>::New();

  // Instanciate an image reader
  vtkSmartPointer<vtkImageReader2> imageReader;
  imageReader.TakeReference(imageFactory->CreateImageReader2(imageFilename.toLatin1()));
  if (!imageReader)
    {
    std::cerr << "Failed to instanciate image reader using: "
              << qPrintable(imageFilename) << std::endl;
    return EXIT_FAILURE;
    }

  // Read image
  imageReader->SetFileName(imageFilename.toLatin1());
  imageReader->Update();
#if (VTK_MAJOR_VERSION <= 5)
  vtkImageData* image = imageReader->GetOutput();
#else
  vtkAlgorithmOutput* imagePort = imageReader->GetOutputPort();
#endif

  // Setup the slice views
  for (int i = 0; i < numSliceViews; i++)
    {
    allSliceViews[i]->setRenderEnabled(true);
    allSliceViews[i]->setMinimumSize(350,350);
#if (VTK_MAJOR_VERSION <= 5)
    allSliceViews[i]->setImageData(image);
#else
    allSliceViews[i]->setImageDataConnection(imagePort);
#endif
    allSliceViews[i]->setHighlightedBoxColor(Qt::yellow);
    allSliceViews[i]->scheduleRender();
    }

  int time = 200;

  // Get crosshair points of interest, used in the following tests
  parentWidget.move(0,0);
  parentWidget.show();
  QTimer::singleShot(time, &app, SLOT(quit()));
  if (app.exec() == EXIT_FAILURE)
    {
    std::cerr << "ctkVTKMagnifyView:show failed the first time." << std::endl;
    return EXIT_FAILURE;
    }
  QPoint insideSlice0 = allSliceViews[0]->mapToGlobal(
        QPoint(allSliceViews[0]->width()/2 + 100, allSliceViews[0]->height()/2 + 100));
  QPoint outside = parentWidget.mapToGlobal(
        QPoint(parentWidget.width(), parentWidget.height()));
  QPoint insideSlice1 = allSliceViews[1]->mapToGlobal(
        QPoint(allSliceViews[1]->width()/2 - 50, allSliceViews[1]->height() - 50));
  QPoint insideSlice1edge = allSliceViews[1]->mapToGlobal(
        QPoint(allSliceViews[1]->width() - 5, allSliceViews[1]->height() - 100));
  QPoint insideSlice2 = allSliceViews[2]->mapToGlobal(
        QPoint(allSliceViews[2]->width()/2, allSliceViews[2]->height()/2));
  QPoint insideSlice0bottomRightCorner = allSliceViews[0]->mapToGlobal(
        QPoint(allSliceViews[0]->width()-1, allSliceViews[0]->height()-1));
  QPoint insideSlice0topLeftCorner = allSliceViews[0]->mapToGlobal(
        QPoint(0,0));
  parentWidget.hide();

  // Make sure the magnify widget magnifies right away when shown with the crosshair inside
  // an observed QVTKWidget
  QCursor::setPos(insideSlice0);
  parentWidget.show();
  if (!runBaselineTest(time, app, magnify, allSliceViews[0], true,
                       baselineDirectory, testType, "a",
                       "magnify widget first shown with crosshair inside observed widget"))
    {
    return EXIT_FAILURE;
    }
  parentWidget.hide();

  // Make sure the magnify widget shows blank right away when shown with the crosshair
  // outside the observed QVTKWidgets
  QCursor::setPos(outside);
  parentWidget.show();
  if (!runBaselineTest(time, app, magnify, &parentWidget, false,
                       baselineDirectory, testType, "b",
                       "magnify widget first shown with crosshair outside observed widget"))
    {
    return EXIT_FAILURE;
    }

  // Test magnification after move to allSliceViews[1]
  QCursor::setPos(insideSlice1);
  if (!runBaselineTest(time, app, magnify, allSliceViews[1], true,
                       baselineDirectory, testType, "c",
                       "crosshair moved inside 2nd observed widget the first time"))
    {
    return EXIT_FAILURE;
    }

  // Test magnification after move within allSliceViews[1] close to border
  QCursor::setPos(insideSlice1edge);
  if (!runBaselineTest(time, app, magnify, allSliceViews[1], true,
                       baselineDirectory, testType, "d",
                       "crosshair moved inside 2nd observed widget the second time"))
    {
    return EXIT_FAILURE;
    }

  // Test magnification after move outside an observed widget (should be blank)
  QCursor::setPos(insideSlice2);
  if (!runBaselineTest(time, app, magnify, allSliceViews[2], true,
                       baselineDirectory, testType, "e",
                       "crosshair moved inside unobserved widget"))
    {
    return EXIT_FAILURE;
    }

  // Test magnification after move back inside an observed widget (at extreme bottom
  // right corner)
  QCursor::setPos(insideSlice0bottomRightCorner);
  if (!runBaselineTest(time, app, magnify, allSliceViews[0], true,
                       baselineDirectory, testType, "f",
                       "crosshair moved to bottom-right corner of observed widget"))
    {
    return EXIT_FAILURE;
    }

  // Test magnification after move back inside an observed widget (at extreme top left
  // corner)
  QCursor::setPos(insideSlice0topLeftCorner);
  if (!runBaselineTest(time, app, magnify, allSliceViews[0], true,
                       baselineDirectory, testType, "g",
                       "crosshair moved to top-left corner of observed widget"))
    {
    return EXIT_FAILURE;
    }

  // Go back inside the widget
  QCursor::setPos(insideSlice0);
  if (!runBaselineTest(time, app, magnify, allSliceViews[0], true,
                       baselineDirectory, testType, "a",
                       "crosshair moved again inside observed widget"))
    {
    return EXIT_FAILURE;
    }

  // Test enabling observing render window events (trigger a render window event by
  // changing the image data)
  observeRenderWindowEvents = true;
  magnify->setObserveRenderWindowEvents(observeRenderWindowEvents);
  if (magnify->observeRenderWindowEvents() != observeRenderWindowEvents)
    {
    std::cerr << "ctkVTKMagnifyView:setObserveRenderWindowEvents failed. "
              << magnify->observeRenderWindowEvents() << std::endl;
    return EXIT_FAILURE;
    }

  vtkImageGaussianSmooth * gaussian = vtkImageGaussianSmooth::New();
#if (VTK_MAJOR_VERSION <= 5)
  gaussian->SetInput(image);
#else
  gaussian->SetInputConnection(imagePort);
#endif
  gaussian->SetRadiusFactors(5,5);
  gaussian->Update();
#if (VTK_MAJOR_VERSION <= 5)
  allSliceViews[0]->setImageData(gaussian->GetOutput());
#else
  allSliceViews[0]->setImageDataConnection(gaussian->GetOutputPort());
#endif
  allSliceViews[0]->scheduleRender();
  if (!runBaselineTest(time, app, magnify, allSliceViews[0], true,
                       baselineDirectory, testType, "h",
                       "after Gaussian blur when observing render window events"))
    {
    return EXIT_FAILURE;
    }

  // Test disabling observing render window events (trigger a render window event by
  // changing the image data)
  observeRenderWindowEvents = false;
  magnify->setObserveRenderWindowEvents(observeRenderWindowEvents);
  if (magnify->observeRenderWindowEvents() != observeRenderWindowEvents)
    {
    std::cerr << "ctkVTKMagnifyView:setObserveRenderWindowEvents failed. "
              << magnify->observeRenderWindowEvents() << std::endl;
    return EXIT_FAILURE;
    }

#if (VTK_MAJOR_VERSION <= 5)
  gaussian->SetInput(image);
#else
  gaussian->SetInputConnection(imageReader->GetOutputPort());
#endif
  gaussian->SetRadiusFactors(0,0);
  gaussian->Update();
#if (VTK_MAJOR_VERSION <= 5)
  allSliceViews[0]->setImageData(gaussian->GetOutput());
#else
  allSliceViews[0]->setImageDataConnection(gaussian->GetOutputPort());
#endif
  allSliceViews[0]->scheduleRender();
  if (!runBaselineTest(time, app, magnify, allSliceViews[0], true,
                       baselineDirectory, testType, "h",
                       "after Gaussian blur when not observing render window events"))
    {
    return EXIT_FAILURE;
    }

  // Test changing the update interval
  magnify->setUpdateInterval(time * 2);
  magnify->setObserveRenderWindowEvents(true);
#if (VTK_MAJOR_VERSION <= 5)
  allSliceViews[0]->setImageData(image);
#else
  allSliceViews[0]->setImageDataConnection(imagePort);
#endif
  allSliceViews[0]->scheduleRender();
  QCursor::setPos(insideSlice0bottomRightCorner);
  // It should be waiting to update here
  if (!runBaselineTest(time, app, magnify, allSliceViews[0], true,
                       baselineDirectory, testType, "h",
                       "after changing update interval: updated too quickly"))
    {
    return EXIT_FAILURE;
    }
  // It should have updated by now
  if (!runBaselineTest(time + 50, app, magnify, allSliceViews[0], true,
                       baselineDirectory, testType, "f",
                       "after changing update interval: didn't update after waiting"))
    {
    return EXIT_FAILURE;
    }

  gaussian->Delete();

  return EXIT_SUCCESS;

}
Example #8
0
SequenceDialog::SequenceDialog(QWidget &parent, CaptureFile &cf, SequenceInfo *info) :
    WiresharkDialog(parent, cf),
    ui(new Ui::SequenceDialog),
    info_(info),
    num_items_(0),
    packet_num_(0),
    sequence_w_(1)
{
    ui->setupUi(this);
    loadGeometry(parent.width(), parent.height() * 4 / 5);

    QCustomPlot *sp = ui->sequencePlot;
    setWindowSubtitle(info_ ? tr("Call Flow") : tr("Flow"));

    if (!info_) {
        info_ = new SequenceInfo(sequence_analysis_info_new());
        info_->sainfo()->type = SEQ_ANALYSIS_ANY;
        info_->sainfo()->all_packets = TRUE;
    } else {
        info_->ref();
        num_items_ = sequence_analysis_get_nodes(info_->sainfo());
    }

    seq_diagram_ = new SequenceDiagram(sp->yAxis, sp->xAxis2, sp->yAxis2);
    sp->addPlottable(seq_diagram_);

    // When dragging is enabled it's easy to drag past the lower and upper
    // bounds of each axis. Disable it for now.
    //sp->axisRect()->setRangeDragAxes(sp->xAxis2, sp->yAxis);
    //sp->setInteractions(QCP::iRangeDrag);

    sp->xAxis->setVisible(false);
    sp->xAxis->setPadding(0);
    sp->xAxis->setLabelPadding(0);
    sp->xAxis->setTickLabelPadding(0);

    QPen base_pen(ColorUtils::alphaBlend(palette().text(), palette().base(), 0.25));
    base_pen.setWidthF(0.5);
    sp->xAxis2->setBasePen(base_pen);
    sp->yAxis->setBasePen(base_pen);
    sp->yAxis2->setBasePen(base_pen);

    sp->xAxis2->setVisible(true);
    sp->yAxis2->setVisible(true);

    key_text_ = new QCPItemText(sp);
    key_text_->setText(tr("Time"));
    sp->addItem(key_text_);

    key_text_->setPositionAlignment(Qt::AlignRight | Qt::AlignVCenter);
    key_text_->position->setType(QCPItemPosition::ptAbsolute);
    key_text_->setClipToAxisRect(false);

    comment_text_ = new QCPItemText(sp);
    comment_text_->setText(tr("Comment"));
    sp->addItem(comment_text_);

    comment_text_->setPositionAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    comment_text_->position->setType(QCPItemPosition::ptAbsolute);
    comment_text_->setClipToAxisRect(false);

    one_em_ = QFontMetrics(sp->yAxis->labelFont()).height();
    ui->horizontalScrollBar->setSingleStep(100 / one_em_);
    ui->verticalScrollBar->setSingleStep(100 / one_em_);

    ui->gridLayout->setSpacing(0);
    connect(sp->yAxis, SIGNAL(rangeChanged(QCPRange)), sp->yAxis2, SLOT(setRange(QCPRange)));

    ctx_menu_.addAction(ui->actionReset);
    ctx_menu_.addSeparator();
    ctx_menu_.addAction(ui->actionMoveRight10);
    ctx_menu_.addAction(ui->actionMoveLeft10);
    ctx_menu_.addAction(ui->actionMoveUp10);
    ctx_menu_.addAction(ui->actionMoveDown10);
    ctx_menu_.addAction(ui->actionMoveRight1);
    ctx_menu_.addAction(ui->actionMoveLeft1);
    ctx_menu_.addAction(ui->actionMoveUp1);
    ctx_menu_.addAction(ui->actionMoveDown1);
    ctx_menu_.addSeparator();
    ctx_menu_.addAction(ui->actionGoToPacket);
    ctx_menu_.addAction(ui->actionGoToNextPacket);
    ctx_menu_.addAction(ui->actionGoToPreviousPacket);

    ui->showComboBox->setCurrentIndex(0);
    ui->addressComboBox->setCurrentIndex(0);

    QComboBox *fcb = ui->flowComboBox;
    fcb->addItem(ui->actionFlowAny->text(), SEQ_ANALYSIS_ANY);
    fcb->addItem(ui->actionFlowTcp->text(), SEQ_ANALYSIS_TCP);

    ui->flowComboBox->setCurrentIndex(info_->sainfo()->type);

    if (info_->sainfo()->type == SEQ_ANALYSIS_VOIP) {
        ui->flowComboBox->blockSignals(true);
        ui->controlFrame->hide();
    }

    QPushButton *save_bt = ui->buttonBox->button(QDialogButtonBox::Save);
    save_bt->setText(tr("Save As" UTF8_HORIZONTAL_ELLIPSIS));

    ProgressFrame::addToButtonBox(ui->buttonBox, &parent);

    connect(ui->horizontalScrollBar, SIGNAL(valueChanged(int)), this, SLOT(hScrollBarChanged(int)));
    connect(ui->verticalScrollBar, SIGNAL(valueChanged(int)), this, SLOT(vScrollBarChanged(int)));
    connect(sp->xAxis2, SIGNAL(rangeChanged(QCPRange)), this, SLOT(xAxisChanged(QCPRange)));
    connect(sp->yAxis, SIGNAL(rangeChanged(QCPRange)), this, SLOT(yAxisChanged(QCPRange)));
    connect(sp, SIGNAL(mousePress(QMouseEvent*)), this, SLOT(diagramClicked(QMouseEvent*)));
    connect(sp, SIGNAL(mouseMove(QMouseEvent*)), this, SLOT(mouseMoved(QMouseEvent*)));
    connect(sp, SIGNAL(mouseWheel(QWheelEvent*)), this, SLOT(mouseWheeled(QWheelEvent*)));
    connect(this, SIGNAL(goToPacket(int)), seq_diagram_, SLOT(setSelectedPacket(int)));

    disconnect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
}
FollowStreamDialog::FollowStreamDialog(QWidget &parent, CaptureFile &cf, follow_type_t type) :
    WiresharkDialog(parent, cf),
    ui(new Ui::FollowStreamDialog),
    follow_type_(type),
    follower_(NULL),
    show_type_(SHOW_ASCII),
    truncated_(false),
    save_as_(false)
{
    ui->setupUi(this);

    switch(type)
    {
    case FOLLOW_TCP:
        follower_ = get_follow_by_name("TCP");
        break;
    case FOLLOW_SSL:
        follower_ = get_follow_by_name("SSL");
        break;
    case FOLLOW_UDP:
        follower_ = get_follow_by_name("UDP");
        break;
    case FOLLOW_HTTP:
        follower_ = get_follow_by_name("HTTP");
        break;
    default :
        g_assert_not_reached();
    }

    memset(&follow_info_, 0, sizeof(follow_info_));
    follow_info_.show_stream = BOTH_HOSTS;

    ui->teStreamContent->installEventFilter(this);

    // XXX Use recent settings instead
    resize(parent.width() * 2 / 3, parent.height());

    QComboBox *cbcs = ui->cbCharset;
    cbcs->blockSignals(true);
    cbcs->addItem(tr("ASCII"), SHOW_ASCII);
    cbcs->addItem(tr("C Arrays"), SHOW_CARRAY);
    cbcs->addItem(tr("EBCDIC"), SHOW_EBCDIC);
    cbcs->addItem(tr("Hex Dump"), SHOW_HEXDUMP);
    cbcs->addItem(tr("UTF-8"), SHOW_UTF8);
    cbcs->addItem(tr("YAML"), SHOW_YAML);
    cbcs->addItem(tr("Raw"), SHOW_RAW);
    cbcs->blockSignals(false);

    b_filter_out_ = ui->buttonBox->addButton(tr("Hide this stream"), QDialogButtonBox::ActionRole);
    connect(b_filter_out_, SIGNAL(clicked()), this, SLOT(filterOut()));

    b_print_ = ui->buttonBox->addButton(tr("Print"), QDialogButtonBox::ActionRole);
    connect(b_print_, SIGNAL(clicked()), this, SLOT(printStream()));

    b_save_ = ui->buttonBox->addButton(tr("Save as" UTF8_HORIZONTAL_ELLIPSIS), QDialogButtonBox::ActionRole);
    connect(b_save_, SIGNAL(clicked()), this, SLOT(saveAs()));

    ProgressFrame::addToButtonBox(ui->buttonBox, &parent);

    connect(ui->buttonBox, SIGNAL(helpRequested()), this, SLOT(helpButton()));
    connect(ui->teStreamContent, SIGNAL(mouseMovedToTextCursorPosition(int)),
            this, SLOT(fillHintLabel(int)));
    connect(ui->teStreamContent, SIGNAL(mouseClickedOnTextCursorPosition(int)),
            this, SLOT(goToPacketForTextPos(int)));
    connect(&cap_file_, SIGNAL(captureFileClosing()), this, SLOT(captureFileClosing()));

    fillHintLabel(-1);
}
Example #10
0
// (Re)create the complete view pixmap.
void qtractorMidiEditTime::updatePixmap ( int cx, int /*cy*/)
{
	QWidget *pViewport = qtractorScrollView::viewport();
	const int w = pViewport->width();
	const int h = pViewport->height();

	if (w < 1 || h < 1)
		return;

	const QPalette& pal = qtractorScrollView::palette();

	m_pixmap = QPixmap(w, h);
	m_pixmap.fill(pal.window().color());

	qtractorSession *pSession = qtractorSession::getInstance();
	if (pSession == NULL)
		return;

	qtractorTimeScale *pTimeScale = m_pEditor->timeScale();
	if (pTimeScale == NULL)
		return;

	QPainter painter(&m_pixmap);
	painter.initFrom(this);

	//
	// Draw the time scale...
	//

	const QFontMetrics& fm = painter.fontMetrics();
	int x, x1, y1, y2 = h - 1;

	// Account for the editing offset:
	const int dx = cx + pTimeScale->pixelFromFrame(m_pEditor->offset());

	qtractorTimeScale::Cursor cursor(pTimeScale);
	qtractorTimeScale::Node *pNode = cursor.seekPixel(dx);

	unsigned short iPixelsPerBeat = pNode->pixelsPerBeat();
	unsigned int iBeat = pNode->beatFromPixel(dx);
	if (iBeat > 0) pNode = cursor.seekBeat(--iBeat);
	x = x1 = pNode->pixelFromBeat(iBeat) - dx;

	while (x < w) {
		const bool bBeatIsBar = pNode->beatIsBar(iBeat);
		if (bBeatIsBar || iPixelsPerBeat > 8) {
			y1 = (bBeatIsBar && x >= x1 ? 0 : fm.ascent());
			painter.setPen(pal.mid().color());
			painter.drawLine(x, y1, x, y2);
			painter.setPen(pal.light().color());
			++x; painter.drawLine(x, y1, x, y2);
		}
		if (bBeatIsBar) {
			y1 = fm.ascent();
			if (x >= x1) {
				x1 = x + 2;
				const unsigned short iBar = pNode->barFromBeat(iBeat);
				const QString& sBeat = QString::number(iBar + 1);
				painter.setPen(pal.windowText().color());
				painter.drawText(x1, y1, sBeat);
				x1 += fm.width(sBeat) + 2;
			}
			x1 += 2;
			if (iBeat == pNode->beat) {
				iPixelsPerBeat = pNode->pixelsPerBeat();
				const QString& sTempo = QString("%1 %2/%3")
					.arg(pNode->tempo, 0, 'g', 3)
					.arg(pNode->beatsPerBar)
					.arg(1 << pNode->beatDivisor);
				painter.setPen(pal.base().color().value() < 0x7f
					? pal.light().color() : pal.dark().color());
				painter.drawText(x1, y1, sTempo);
				x1 += fm.width(sTempo) + 2;
			}
		}
		pNode = cursor.seekBeat(++iBeat);
		x = pNode->pixelFromBeat(iBeat) - dx;
	}

	// Draw location markers, if any...
	qtractorTimeScale::Marker *pMarker
		= pTimeScale->markers().seekPixel(dx);
	while (pMarker) {
		x = pTimeScale->pixelFromFrame(pMarker->frame) - dx + 4;
		if (x > w) break;
		painter.setPen(pMarker->color);
		painter.drawText(x, y2, pMarker->text);
		pMarker = pMarker->next();
	}

	// Draw loop boundaries, if applicable...
	if (pSession->isLooping()) {
		QPolygon polyg(3);
	//	h -= 4;
		const int d = (h >> 2) + 1;
		painter.setPen(Qt::darkCyan);
		painter.setBrush(Qt::cyan);
		x = pTimeScale->pixelFromFrame(pSession->loopStart()) - dx;
		if (x >= 0 && x < w) {
			polyg.putPoints(0, 3,
				x + d, h - d,
				x, h,
				x, h - d);
			painter.drawPolygon(polyg);
		}
		x = pTimeScale->pixelFromFrame(pSession->loopEnd()) - dx;
		if (x >= 0 && x < w) {
			polyg.putPoints(0, 3,
				x, h - d,
				x, h,
				x - d, h - d);
			painter.drawPolygon(polyg);
		}
	}
Example #11
0
Container::Container(unsigned id, const char *cfg)
{
    m_bInit   = false;
    m_bInSize = false;
    m_bStatusSize = false;
    m_bBarChanged = false;
    m_bReceived = false;
    m_bNoSwitch = false;

    SET_WNDPROC("container")
    setWFlags(WDestructiveClose);
    QFrame *frm = new QFrame(this);
    setCentralWidget(frm);

    connect(CorePlugin::m_plugin, SIGNAL(modeChanged()), this, SLOT(modeChanged()));

    QVBoxLayout *lay = new QVBoxLayout(frm);
    m_wnds = new QWidgetStack(frm);
    m_wnds->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
    lay->addWidget(m_wnds);

    m_tabSplitter = new Splitter(frm);
    m_tabSplitter->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum));
    m_tabBar = new UserTabBar(m_tabSplitter);
    m_tabBar->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding));
    m_tabBar->hide();

    m_status = new ContainerStatus(m_tabSplitter);
    lay->addWidget(m_tabSplitter);

    load_data(containerData, &data, cfg);

    bool bPos = true;
    if (cfg == NULL){
        setId(id);
        memcpy(data.barState, CorePlugin::m_plugin->data.containerBar, sizeof(data.barState));
        memcpy(data.geometry, CorePlugin::m_plugin->data.containerGeo, sizeof(data.geometry));
        if ((data.geometry[WIDTH] == -1) || (data.geometry[HEIGHT] == -1)){
            QWidget *desktop = QApplication::desktop();
            data.geometry[WIDTH] = desktop->width() / 3;
            data.geometry[HEIGHT] = desktop->height() / 3;
        }
        bPos = false;
        if ((data.geometry[TOP] != -1) || (data.geometry[LEFT] != -1)){
            bPos = true;
            QWidgetList  *list = QApplication::topLevelWidgets();
            for (int i = 0; i < 2; i++){
                bool bOK = true;
                QWidgetListIt it(*list);
                QWidget * w;
                while ((w = it.current()) != NULL){
                    if (w == this){
                        ++it;
                        continue;
                    }
                    if (w->inherits("Container")){
                        int dw = w->pos().x() - data.geometry[LEFT];
                        int dh = w->pos().y() - data.geometry[TOP];
                        if (dw < 0) dw = -dw;
                        if (dh < 0) dh = -dh;
                        if ((dw < 3) && (dh < 3)){
                            int nl = data.geometry[LEFT];
                            int nt = data.geometry[TOP];
                            nl += 21;
                            nt += 20;
                            QWidget *desktop = QApplication::desktop();
                            if (nl + data.geometry[WIDTH] > desktop->width())
                                nl = 0;
                            if (nt + data.geometry[WIDTH] > desktop->width())
                                nt = 0;
                            if ((nl != data.geometry[LEFT]) && (nt != data.geometry[TOP])){
                                data.geometry[LEFT] = nl;
                                data.geometry[TOP]  = nt;
                                bOK = false;
                            }
                        }
                    }
                    ++it;
                }
                if (bOK)
                    break;
            }
            delete list;
        }
        setStatusSize(CorePlugin::m_plugin->getContainerStatusSize());
        showBar();
        m_bInit = true;
    }
    m_bInSize = true;
    restoreGeometry(this, data.geometry, bPos, true);
    m_bInSize = false;
    connect(m_tabBar, SIGNAL(selected(int)), this, SLOT(contactSelected(int)));
    connect(this, SIGNAL(toolBarPositionChanged(QToolBar*)), this, SLOT(toolbarChanged(QToolBar*)));
    connect(m_status, SIGNAL(sizeChanged(int)), this, SLOT(statusChanged(int)));

    m_accel = new QAccel(this);
    connect(m_accel, SIGNAL(activated(int)), this, SLOT(accelActivated(int)));
    setupAccel();
}
Example #12
0
Timeline::Timeline(QWidget *parent) :
    QWidget(parent),
    mScene(NULL),
    mEditor(NULL),
    mFrameIndex(0),
    mLayerIndex(-1),
    mMaxFrames(0),
    mCellSize(8, 16),
    mOffset(0),
    mCompositeImage(NULL)
{
//    QVBoxLayout* l = new QVBoxLayout;
//    l->setSpacing(2);
//    l->setMargin(1);
//    setLayout(l);

//    QSplitter* splitter = new QSplitter(Qt::Horizontal);
//    l->addWidget(splitter);

//    QWidget* left = new QWidget();
//    QWidget* right = new QWidget();
//    left->setLayout(new QVBoxLayout);
//    right->setLayout(new QVBoxLayout);
//    left->layout()->setSpacing(0);
//    right->layout()->setSpacing(0);
//    splitter->addWidget(left);
//    splitter->addWidget(right);
//    splitter->setSizes( QList<int>() << 100 << 600 );

//    QLabel* dummy = new QLabel("Layers");
//    dummy->resize(left->width(), mCellSize.height());
//    left->layout()->addWidget(dummy);
//    mNavBar = new TimelineNavBar(this);
//    right->layout()->addWidget(mNavBar);

//    QScrollArea* propertyScroolPanel = new QScrollArea();
//    QScrollArea* timeLineScroolPanel = new QScrollArea();

//    left->layout()->addWidget(propertyScroolPanel);
//    right->layout()->addWidget(timeLineScroolPanel);

//    mPropertyPanel = new QWidget();
//    mTimeLinePanel = new QWidget();
//    mPropertyPanel->setLayout(new QVBoxLayout);
//    mTimeLinePanel->setLayout(new QVBoxLayout);
//    mPropertyPanel->layout()->setSpacing(2);
//    mTimeLinePanel->layout()->setSpacing(2);
//    mPropertyPanel->layout()->setContentsMargins(0, 0, 0, 1);
//    mTimeLinePanel->layout()->setContentsMargins(0, 0, 0, 1);

//    propertyScroolPanel->setWidget(mPropertyPanel);
//    propertyScroolPanel->setWidgetResizable(true);
//    timeLineScroolPanel->setWidget(mTimeLinePanel);
//    timeLineScroolPanel->setWidgetResizable(true);

    QHBoxLayout* l = new QHBoxLayout;
    l->setSpacing(0);
    l->setMargin(0);
    setLayout(l);

    QWidget* left = new QWidget();
    QWidget* right = new QWidget();
    QVBoxLayout* leftLayout = new QVBoxLayout();
    QVBoxLayout* rightLayout = new QVBoxLayout();
    left->setLayout(leftLayout);
    right->setLayout(rightLayout);
    leftLayout->setSpacing(0);
    leftLayout->setMargin(0);
    rightLayout->setSpacing(0);
    rightLayout->setMargin(0);
    QScrollBar* vScroll = new QScrollBar(Qt::Vertical);

    l->addWidget(left);
    l->addWidget(vScroll);
    l->addWidget(right, 1);

    QLabel* dummy = new QLabel("Layers");
    dummy->resize(left->width(), mCellSize.height());
    leftLayout->addWidget(dummy);
    mNavBar = new TimelineNavBar(this);
    rightLayout->addWidget(mNavBar);

    QWidget* propertyScroolPanel = new QWidget();
    QWidget* timeLineScroolPanel = new QWidget();
    mTimeScroll = new QScrollBar(Qt::Horizontal);

    leftLayout->addWidget(propertyScroolPanel, 1);
    rightLayout->addWidget(timeLineScroolPanel, 1);
    rightLayout->addWidget(mTimeScroll);

    mPropertyPanel = propertyScroolPanel;
    mTimeLinePanel = timeLineScroolPanel;
    mPropertyPanel->setLayout(new QVBoxLayout);
    mTimeLinePanel->setLayout(new QVBoxLayout);
    mPropertyPanel->layout()->setSpacing(2);
    mTimeLinePanel->layout()->setSpacing(2);
    mPropertyPanel->layout()->setContentsMargins(0, 0, 0, 1);
    mTimeLinePanel->layout()->setContentsMargins(0, 0, 0, 1);

    connect(mTimeScroll, SIGNAL(valueChanged(int)), this, SLOT(OnTimeScroll(int)));
}
Example #13
0
ValidationResultType MovieExporter::validate(const PlugInArgList* pArgList, string& errorMessage) const
{
   /* validate some arguments */
   ValidationResultType result = ExporterShell::validate(pArgList, errorMessage);
   if (result != VALIDATE_SUCCESS)
   {
      return result;
   }
   View* pView = pArgList->getPlugInArgValue<View>(Exporter::ExportItemArg());
   if (pView == NULL)
   {
      errorMessage = "No view specified. Nothing to export.";
      return VALIDATE_FAILURE;
   }
   AnimationController* pController = pView->getAnimationController();
   if (pController == NULL)
   {
      errorMessage = "No animation is associated with this view. Nothing to export.";
      return VALIDATE_FAILURE;
   }

   /* validate the framerate */
   boost::rational<int> expectedFrameRate;

   // first, get the framerate from the arg list
   // next, try the option widget
   // next, get from the animation controller
   // finally, default to the config settings
   int framerateNum = 0;
   int framerateDen = 0;
   if (pArgList->getPlugInArgValue("Framerate Numerator", framerateNum) &&
      pArgList->getPlugInArgValue("Framerate Denominator", framerateDen))
   {
      try
      {
         expectedFrameRate.assign(framerateNum, framerateDen);
      }
      catch (const boost::bad_rational&)
      {
         errorMessage = "Invalid framerate specified";
         return VALIDATE_FAILURE;
      }
   }
   if (expectedFrameRate == 0)
   {
      if (mpOptionWidget.get() != NULL)
      {
         FramerateWidget* pFramerateWidget = mpOptionWidget->getFramerateWidget();
         VERIFYRV(pFramerateWidget != NULL, VALIDATE_FAILURE);

         expectedFrameRate = pFramerateWidget->getFramerate();
      }
      if (expectedFrameRate == 0)
      {
         expectedFrameRate = getFrameRate(pController);
      }
      if (expectedFrameRate == 0)
      {
         errorMessage = "No framerate specified";
         return VALIDATE_FAILURE;
      }
   }

   boost::rational<int> actualFrameRate = convertToValidFrameRate(expectedFrameRate);
   if (actualFrameRate != 0)
   {
      if (actualFrameRate < getFrameRate(pController))
      {
         errorMessage = "The selected output frame rate may not encode all the frames in the movie.  "
                        "Frames may be dropped.";
         result = VALIDATE_INFO;
      }
      if (actualFrameRate != expectedFrameRate)
      {
         QString msg = QString("The selected animation frame rate (%1/%2 fps) can not be represented in the "
            "selected movie format. A frame rate of %3/%4 fps is being used instead.")
            .arg(expectedFrameRate.numerator())
            .arg(expectedFrameRate.denominator())
            .arg(actualFrameRate.numerator())
            .arg(actualFrameRate.denominator());
         if (!errorMessage.empty())
         {
            errorMessage += "\n\n";
         }
         errorMessage += msg.toStdString();
         result = VALIDATE_INFO;
      }
   }

   // check the frame resolution
   int resolutionX(-1);
   int resolutionY(-1);
   bool fullResolution(false);
   bool fixedResolution(false);
   if (!pArgList->getPlugInArgValue("Resolution X", resolutionX) ||
       !pArgList->getPlugInArgValue("Resolution Y", resolutionY))
   {
      if (mpOptionWidget.get() != NULL)
      {
         ViewResolutionWidget* pResolutionWidget = mpOptionWidget->getResolutionWidget();
         VERIFYRV(pResolutionWidget != NULL, VALIDATE_FAILURE);

         switch(pResolutionWidget->getResolutionType())
         {
         case OptionsMovieExporter::VIEW_RESOLUTION:
            resolutionX = -1;
            resolutionY = -1;
            fullResolution = false;
            break;
         case OptionsMovieExporter::FULL_RESOLUTION:
            resolutionX = -1;
            resolutionY = -1;
            fullResolution = true;
            break;
         case OptionsMovieExporter::FIXED_RESOLUTION:
         {
            QSize resolution = pResolutionWidget->getResolution();
            resolutionX = resolution.width();
            resolutionY = resolution.height();
            fullResolution = false;
            fixedResolution = true;
            break;
         }
         default:
            break; // nothing
         }
      }
      else
      {
         switch(StringUtilities::fromXmlString<OptionsMovieExporter::ResolutionType>(
            OptionsMovieExporter::getSettingResolutionType()))
         {
         case OptionsMovieExporter::VIEW_RESOLUTION:
            resolutionX = -1;
            resolutionY = -1;
            fullResolution = false;
            break;
         case OptionsMovieExporter::FULL_RESOLUTION:
            resolutionX = -1;
            resolutionY = -1;
            fullResolution = true;
            break;
         case OptionsMovieExporter::FIXED_RESOLUTION:
            resolutionX = OptionsMovieExporter::getSettingWidth();
            resolutionY = OptionsMovieExporter::getSettingHeight();
            fullResolution = false;
            fixedResolution = true;
            break;
         default:
            break; // nothing
         }
      }
   }

   if (resolutionX <= 0 || resolutionY <= 0)
   {
      QWidget* pWidget = pView->getWidget();
      if (pWidget != NULL)
      {
         resolutionX = pWidget->width();
         resolutionY = pWidget->height();
         if (fullResolution)
         {
            PerspectiveView* pPersp = dynamic_cast<PerspectiveView*>(pView);
            if (pPersp != NULL && pPersp->getZoomPercentage() > 100.)
            {
               fullResolution = false;
               if (mpProgress != NULL)
               {
                  errorMessage += "Full resolution export will be smaller than "
                     "view export, export resolution will be changed to current view size.\n";
                  if (result == VALIDATE_SUCCESS)
                  {
                     result = VALIDATE_INFO;
                  }
               }
            }
            else
            {
               // translate to data coordinate
               double x1 = 0.0;
               double y1 = 0.0;
               double x2 = 0.0;
               double y2 = 0.0;
               pView->translateScreenToWorld(0.0, 0.0, x1, y1);
               pView->translateScreenToWorld(resolutionX, resolutionY, x2, y2);
               resolutionX = (x2 > x1) ? (x2 - x1 + 0.5) : (x1 - x2 + 0.5);
               resolutionY = (y2 > y1) ? (y2 - y1 + 0.5) : (y1 - y2 + 0.5);
            }
         }
      }
      else
      {
         errorMessage += "Can't determine output resolution.\n";
         return VALIDATE_FAILURE;
      }
   }

   int oldResX = resolutionX;
   int oldResY = resolutionY;
   if (!convertToValidResolution(resolutionX, resolutionY) ||
         (fixedResolution && (resolutionX != oldResX || resolutionY != oldResY)))
   {
      if (mpOptionWidget.get() != NULL)
      {
         ViewResolutionWidget* pResolutionWidget = mpOptionWidget->getResolutionWidget();
         VERIFYRV(pResolutionWidget != NULL, VALIDATE_FAILURE);
         pResolutionWidget->setResolution(QSize(resolutionX, resolutionY), pResolutionWidget->getResolutionType());
      }
      errorMessage +=
         "The export resolution does not meet the requirements of the the selected CODEC and will be adjusted.\n";
      if (result != VALIDATE_FAILURE)
      {
         result = VALIDATE_INFO;
      }
   }

   return result;
}
Example #14
0
bool MovieExporter::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   FileDescriptor* pFileDescriptor(NULL);
   string filename;
   View* pView(NULL);
   AnimationController* pController(NULL);
   FrameType eType;
   AVOutputFormat* pOutFormat(NULL);
   int resolutionX(-1);
   int resolutionY(-1);
   rational<int> framerate(0);
   unsigned int bitrate(0);
   double startExport(0.0);
   double stopExport(0.0);
   bool fullResolution(false);

   mpProgress = NULL;
   mpStep = StepResource("Export movie", "app", "2233BFC9-9C51-4e31-A8C5-2512925CBE6D");

   // get input arguments and log some useful info about them
   { // scope the MessageResource
      MessageResource pMsg("Input arguments", "app", "4551F478-E182-4b56-B88F-6682F0E3A2CF");

      mpProgress = pInArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());
      pMsg->addBooleanProperty("Progress Present", (mpProgress != NULL));

      pFileDescriptor = pInArgList->getPlugInArgValue<FileDescriptor>(Exporter::ExportDescriptorArg());
      if (pFileDescriptor == NULL)
      {
         log_error("No file specified");
         return false;
      }
      pMsg->addProperty("Destination", pFileDescriptor->getFilename());
      filename = pFileDescriptor->getFilename().getFullPathAndName();

      pView = pInArgList->getPlugInArgValue<View>(Exporter::ExportItemArg());
      if (pView == NULL)
      {
         log_error("No view specified");
         return false;
      }

      pController = pView->getAnimationController();
      if (pController == NULL)
      {
         log_error("No animation controller specified");
         return false;
      }
      pMsg->addProperty("Animation Controller Name", pController->getName());

      pOutFormat = getOutputFormat();
      if (pOutFormat == NULL)
      {
         log_error("Can't determine output format or format not supported.");
         return false;
      }
      pMsg->addProperty("Format", pOutFormat->long_name);

      bool resolutionFromInputArgs(false);
      if (!pInArgList->getPlugInArgValue("Resolution X", resolutionX) ||
         !pInArgList->getPlugInArgValue("Resolution Y", resolutionY))
      {
         if (mpOptionWidget.get() != NULL)
         {
            ViewResolutionWidget* pResolutionWidget = mpOptionWidget->getResolutionWidget();
            VERIFY(pResolutionWidget != NULL);

            switch(pResolutionWidget->getResolutionType())
            {
            case OptionsMovieExporter::VIEW_RESOLUTION:
               resolutionX = -1;
               resolutionY = -1;
               fullResolution = false;
               break;
            case OptionsMovieExporter::FULL_RESOLUTION:
               resolutionX = -1;
               resolutionY = -1;
               fullResolution = true;
               break;
            case OptionsMovieExporter::FIXED_RESOLUTION:
            {
               QSize resolution = pResolutionWidget->getResolution();
               resolutionX = resolution.width();
               resolutionY = resolution.height();
               fullResolution = false;
               break;
            }
            default:
               break; // nothing
            }
         }
         else
         {
            switch(StringUtilities::fromXmlString<OptionsMovieExporter::ResolutionType>(
               OptionsMovieExporter::getSettingResolutionType()))
            {
            case OptionsMovieExporter::VIEW_RESOLUTION:
               resolutionX = -1;
               resolutionY = -1;
               fullResolution = false;
               break;
            case OptionsMovieExporter::FULL_RESOLUTION:
               resolutionX = -1;
               resolutionY = -1;
               fullResolution = true;
               break;
            case OptionsMovieExporter::FIXED_RESOLUTION:
               resolutionX = OptionsMovieExporter::getSettingWidth();
               resolutionY = OptionsMovieExporter::getSettingHeight();
               fullResolution = false;
               break;
            default:
               break; // nothing
            }
         }
      }
      else
      {
         resolutionFromInputArgs = true;
      }

      if (resolutionX <= 0 || resolutionY <= 0)
      {
         QWidget* pWidget = pView->getWidget();
         if (pWidget != NULL)
         {
            resolutionX = pWidget->width();
            resolutionY = pWidget->height();
            resolutionFromInputArgs = false;
            if (fullResolution)
            {
               PerspectiveView* pPersp = dynamic_cast<PerspectiveView*>(pView);
               if (pPersp != NULL && pPersp->getZoomPercentage() > 100.)
               {
                  fullResolution = false;
                  if (mpProgress != NULL)
                  {
                     mpProgress->updateProgress("Full resolution export will be smaller than "
                        "view export, changing export resolution to current view size.", 0, WARNING);
                  }
               }
               else
               {
                  // translate to data coordinate
                  double x1 = 0.0;
                  double y1 = 0.0;
                  double x2 = 0.0;
                  double y2 = 0.0;
                  pView->translateScreenToWorld(0.0, 0.0, x1, y1);
                  pView->translateScreenToWorld(resolutionX, resolutionY, x2, y2);
                  resolutionX = (x2 > x1) ? (x2 - x1 + 0.5) : (x1 - x2 + 0.5);
                  resolutionY = (y2 > y1) ? (y2 - y1 + 0.5) : (y1 - y2 + 0.5);
               }
            }
         }
         else
         {
            log_error("Can't determine output resolution.");
            return false;
         }
      }

      int oldResX = resolutionX;
      int oldResY = resolutionY;
      if (!convertToValidResolution(resolutionX, resolutionY) ||
            (resolutionFromInputArgs && (resolutionX != oldResX || resolutionY != oldResY)))
      {
         stringstream msg;
         msg << "The export resolution does not meet the requirements of the the selected CODEC. "
                "The input arguments were X resolution of "
             << oldResX << " and Y resolution of " << oldResY << "."
             << "The adjusted resolution was (" << resolutionX << ", " << resolutionY << ")";
         log_error(msg.str());
         return false;
      }

      pMsg->addProperty("Resolution", QString("%1 x %2").arg(resolutionX).arg(resolutionY).toStdString());

      int framerateNum = 0;
      int framerateDen = 0;
      // first, get the framerate from the arg list
      // next, try the option widget
      // next, get from the animation controller
      if (pInArgList->getPlugInArgValue("Framerate Numerator", framerateNum) &&
         pInArgList->getPlugInArgValue("Framerate Denominator", framerateDen))
      {
         try
         {
            framerate.assign(framerateNum, framerateDen);
         }
         catch (const boost::bad_rational&)
         {
            // Do nothing; the code below handles this case
         }
      }
      if (framerate == 0)
      {
         if (mpOptionWidget.get() != NULL)
         {
            FramerateWidget* pFramerateWidget = mpOptionWidget->getFramerateWidget();
            VERIFY(pFramerateWidget != NULL);

            framerate = pFramerateWidget->getFramerate();
         }
         else
         {
            framerate = getFrameRate(pController);
         }
      }

      if (framerate == 0)
      {
         log_error("No framerate specified");
         return false;
      }

      // Validate the framerate
      boost::rational<int> validFrameRate = convertToValidFrameRate(framerate);
      if (validFrameRate != framerate)
      {
         QString msg = QString("The selected animation frame rate (%1/%2 fps) can not be represented in the "
                               "selected movie format. A frame rate of %3/%4 fps is being used instead.")
                              .arg(framerate.numerator())
                              .arg(framerate.denominator())
                              .arg(validFrameRate.numerator())
                              .arg(validFrameRate.denominator());
         mpProgress->updateProgress(msg.toStdString(), 0, WARNING);

         framerate = validFrameRate;
      }

      pMsg->addProperty("Framerate",
         QString("%1/%2").arg(framerate.numerator()).arg(framerate.denominator()).toStdString());

      if (!pInArgList->getPlugInArgValue("Bitrate", bitrate))
      {
         if (mpOptionWidget.get() != NULL)
         {
            BitrateWidget* pBitrateWidget = mpOptionWidget->getBitrateWidget();
            VERIFY(pBitrateWidget != NULL);

            bitrate = pBitrateWidget->getBitrate();
         }
         else
         {
            bitrate = OptionsMovieExporter::getSettingBitrate();
         }
      }
      pMsg->addProperty("Bitrate", QString::number(bitrate).toStdString());

      eType = pController->getFrameType();
      if (!pInArgList->getPlugInArgValue("Start Export", startExport))
      {
         if (mpOptionWidget.get() != NULL)
         {
            AnimationFrameSubsetWidget* pSubsetWidget = mpOptionWidget->getSubsetWidget();
            VERIFY(pSubsetWidget != NULL);

            startExport = pSubsetWidget->getStartFrame();
         }
         else
         {
            if (pController->getBumpersEnabled())
            {
               startExport = pController->getStartBumper();
            }
            else
            {
               startExport = pController->getStartFrame();
            }
         }
      }
      else
      {
         // adjust to 0-based since the input arg uses 1-based
         --startExport;
      }

      if (!pInArgList->getPlugInArgValue("Stop Export", stopExport))
      {
         if (mpOptionWidget.get() != NULL)
         {
            AnimationFrameSubsetWidget* pSubsetWidget = mpOptionWidget->getSubsetWidget();
            VERIFY(pSubsetWidget != NULL);

            stopExport = pSubsetWidget->getStopFrame();
         }
         else
         {
            if (pController->getBumpersEnabled())
            {
               stopExport = pController->getStopBumper();
            }
            else
            {
               stopExport = pController->getStopFrame();
            }
         }
      }
      else
      {
         // adjust to 0-based since the input arg users 1-based
         --stopExport;
      }
      string valueType("Time");
      if (eType == FRAME_ID)
      {
         valueType = "Frame";
      }

      pMsg->addProperty("Start "+valueType, QString::number(startExport).toStdString());
      pMsg->addProperty("Stop "+valueType, QString::number(stopExport).toStdString());
   }

   AvFormatContextResource pFormat(pOutFormat);
   VERIFY(pFormat != NULL);
   snprintf(pFormat->filename, sizeof(pFormat->filename), "%s", filename.c_str());
   AvStreamResource pVideoStream(pFormat, pOutFormat->video_codec);
   if (pVideoStream == NULL)
   {
      log_error("Unable to create video stream.");
      return false;
   }

   /**
    * allow changing of:
    *    dia_size/
    */
   AVCodecContext* pCodecContext = pVideoStream->codec;
   if (!setAvCodecOptions(pCodecContext))
   {
      log_error("Unable to initialize CODEC options");
      return false;
   }
   // set time_base, width, height, and bitrate here since
   // they can be passed in via the input args
   pCodecContext->width = resolutionX;
   pCodecContext->height = resolutionY;
   pCodecContext->bit_rate = bitrate * 1000;
   // the AVCodecContext wants a time_base which is
   // the inverse of fps.
   pCodecContext->time_base.num = framerate.denominator();
   pCodecContext->time_base.den = framerate.numerator();

   if (av_set_parameters(pFormat, NULL) < 0)
   {
      log_error("Invalid output format parameters.");
      return false;
   }
   if (!open_video(pFormat, pVideoStream))
   {
      log_error("Unable to initialize video stream.");
      return false;
   }
   if (url_fopen(&pFormat->pb, filename.c_str(), URL_WRONLY) < 0)
   {
      log_error("Could not open the output file. Ensure the destination directory is writable.");
      return false;
   }
   av_write_header(pFormat);

   // calculate time interval
   if ((framerate < getFrameRate(pController)) && (mpProgress != NULL))
   {
      mpProgress->updateProgress("The selected output frame rate may not encode all the frames in the movie.  "
                                 "Frames may be dropped.", 0, WARNING);
   }

   // do not use the boost::rational<int> overloaded operator '/' since it truncates type double to int
   double interval = pController->getIntervalMultiplier() * framerate.denominator() / framerate.numerator();

   // export the frames
   AVFrame* pTmpPicture = alloc_picture(PIX_FMT_RGBA32, pCodecContext->width, pCodecContext->height);
   if (pTmpPicture == NULL)
   {
      QString msg("Unable to allocate frame buffer of size %1 x %2");
      log_error(msg.arg(pCodecContext->width).arg(pCodecContext->height).toStdString());
      return false;
   }
   QImage image(pTmpPicture->data[0], pCodecContext->width, pCodecContext->height, QImage::Format_ARGB32);

   // For frame id based animation, each band of the data set fills one second of animation. 
   // If the requested frame rate for export is 15 fps, then each band is replicated 15 times. The execution
   // loop uses a pseudo time value, video_pts, to walk through the animation. The interval between 
   // exported frames is the inverse of the frame rate, e.g., for 15 fps the interval is 0.06667.
   // To fully export the last requested frame, we need to add just under an extra pseudo second to
   // the end time - stopExport. If we added a full extra second, we would export one video frame of the band past
   // the last requested frame - could cause crash if the last request frame was the last band.
   if (eType == FRAME_ID)
   {
      stopExport += 0.99;
   }

   bool drawClassMarkings = fullResolution &&
      Service<ConfigurationSettings>()->getSettingDisplayClassificationMarkings();
   QString classText;
   QFont classFont;
   QColor classColor;
   QPoint classPositionTop;
   QPoint classPositionBottom;
   const int shadowOffset = 2;
   if (drawClassMarkings)
   {
      const int topMargin = 1;
      const int bottomMargin = 4;
      const int leftMargin = 5;
      const int rightMargin = 5;

      classText = QString::fromStdString(pView->getClassificationText());
      classColor = COLORTYPE_TO_QCOLOR(pView->getClassificationColor());
      pView->getClassificationFont(classFont);
      QFontMetrics fontMetrics(classFont);
      int classWidth = fontMetrics.width(classText);
      int classHeight = fontMetrics.ascent();
      int topX((pCodecContext->width / 2) - (classWidth / 2) + shadowOffset);
      int bottomX((pCodecContext->width / 2) - (classWidth / 2));
      // determine the classification position
      switch (pView->getClassificationPosition())
      {
      case TOP_LEFT_BOTTOM_LEFT:
         topX = leftMargin + shadowOffset;
         bottomX = leftMargin + shadowOffset;
         break;
      case TOP_LEFT_BOTTOM_RIGHT:
         topX = leftMargin + shadowOffset;
         bottomX = pCodecContext->width - rightMargin - classWidth + shadowOffset;
         break;
      case TOP_RIGHT_BOTTOM_LEFT:
         topX = pCodecContext->width - rightMargin - classWidth + shadowOffset;
         bottomX = leftMargin + shadowOffset;
         break;
      case TOP_RIGHT_BOTTOM_RIGHT:
         topX = pCodecContext->width - rightMargin - classWidth + shadowOffset;
         bottomX = pCodecContext->width - rightMargin - classWidth + shadowOffset;
         break;
      default:
         // nothing to do, markings centered by default
         break;
      }
      int screenY = 1 + classHeight;
      classPositionTop = QPoint(topX, 1 + classHeight);
      classPositionBottom = QPoint(bottomX, pCodecContext->height - 1);
   }

   // make sure controller is not running prior to export. Save current state and restore after export finished
   AnimationState savedAnimationState = pController->getAnimationState();
   pController->setAnimationState(STOP);

   for (double video_pts = startExport; video_pts <= stopExport; video_pts += interval)
   {
      if (isAborted() == true)
      {
         // reset resources to close output file so it can be deleted
         pVideoStream = AvStreamResource();
         pFormat = AvFormatContextResource(NULL);
         mpPicture = NULL;
         free(mpVideoOutbuf);
         mpVideoOutbuf = NULL;
         remove(filename.c_str());

         if (mpProgress != NULL)
         {
            mpProgress->updateProgress("Export aborted", 0, ABORT);
         }
         pController->setAnimationState(savedAnimationState);
         mpStep->finalize(Message::Abort);
         return false;
      }

      // generate the next frame
      pController->setCurrentFrame(video_pts);
      if (mpProgress != NULL)
      {
         double progressValue = (video_pts - startExport) / (stopExport - startExport) * 100.0;
         mpProgress->updateProgress("Saving movie", static_cast<int>(progressValue), NORMAL);
      }
      if (fullResolution)
      {
         QSize totalSize(pCodecContext->width, pCodecContext->height);
         QSize subImageSize(pView->getWidget()->width(), pView->getWidget()->height());
         // Make sure that the sub-image and the main image have the same aspect ratio to
         // minimize wasted tile space
         if (pCodecContext->width > pCodecContext->height)
         {
            subImageSize.setWidth(
               totalSize.width() / static_cast<float>(totalSize.height()) * subImageSize.height() + 0.5);
         }
         else
         {
            subImageSize.setHeight(
               totalSize.height() / static_cast<float>(totalSize.width()) * subImageSize.width() + 0.5);
         }
         // Remove pan and zoom limits so they don't interfere with the subimage grab
         // and restore them when done
         SpatialDataView* pSdv = dynamic_cast<SpatialDataView*>(pView);
         PanLimitType panLimit;
         if (pSdv != NULL)
         {
            panLimit = pSdv->getPanLimit();
            pSdv->setPanLimit(NO_LIMIT);
         }
         View::SubImageIterator* pSubImage(pView->getSubImageIterator(totalSize, subImageSize));
         if (pSubImage == NULL)
         {
            if (pSdv != NULL)
            {
               pSdv->setPanLimit(panLimit);
            }
            if (mpProgress != NULL)
            {
               mpProgress->updateProgress("Unable to render full scale data", 0, ERRORS);
            }
            pController->setAnimationState(savedAnimationState);
            mpStep->finalize(Message::Failure);
            return false;
         }
         QPainter outPainter(&image);
         QPoint origin(0, image.height() - subImageSize.height());
         while (pSubImage->hasNext())
         {
            QImage subImage;
            if (!pSubImage->next(subImage))
            {
               if (pSdv != NULL)
               {
                  pSdv->setPanLimit(panLimit);
               }
               if (mpProgress != NULL)
               {
                  mpProgress->updateProgress("An error occurred when generating the image", 0, ERRORS);
               }
               pController->setAnimationState(savedAnimationState);
               mpStep->finalize(Message::Failure);
               delete pSubImage;
               return false;
            }
            // copy this subimage to the output buffer
            outPainter.drawImage(origin, subImage);

            int newX = origin.x() + subImage.width();
            int newY = origin.y();
            if (newX >= totalSize.width())
            {
               newY -= subImage.height();
               newX = 0;
            }
            origin = QPoint(newX, newY);
         }
         delete pSubImage;
         if (drawClassMarkings)
         {
            outPainter.setFont(classFont);
            outPainter.setPen(Qt::black);
            outPainter.drawText(classPositionTop, classText);
            outPainter.drawText(classPositionBottom, classText);
            outPainter.setPen(classColor);
            outPainter.drawText(classPositionTop - QPoint(shadowOffset, shadowOffset), classText);
            outPainter.drawText(classPositionBottom - QPoint(shadowOffset, shadowOffset), classText);
         }
         if (pSdv != NULL)
         {
            pSdv->setPanLimit(panLimit);
         }
      }
      else
      {
         pView->getCurrentImage(image);
      }
      img_convert(reinterpret_cast<AVPicture*>(mpPicture),
         pCodecContext->pix_fmt,
         reinterpret_cast<AVPicture*>(pTmpPicture),
         PIX_FMT_RGBA32,
         pCodecContext->width,
         pCodecContext->height);
      if (!write_video_frame(pFormat, pVideoStream))
      {
         // reset resources to close output file so it can be deleted
         pVideoStream = AvStreamResource();
         pFormat = AvFormatContextResource(NULL);
         mpPicture = NULL;
         free(mpVideoOutbuf);
         mpVideoOutbuf = NULL;
         remove(filename.c_str());
         string msg = "Can't write frame.";
         log_error(msg.c_str());
         pController->setAnimationState(savedAnimationState);
         return false;
      }
   }
   for (int frame = 0; frame < pCodecContext->delay; ++frame)
   {
      write_video_frame(pFormat, pVideoStream);
   }

   av_write_trailer(pFormat);

   if (mpProgress != NULL)
   {
      mpProgress->updateProgress("Finished saving movie", 100, NORMAL);
   }

   free(mpVideoOutbuf);
   mpVideoOutbuf = NULL;
   pController->setAnimationState(savedAnimationState);
   mpStep->finalize(Message::Success);
   return true;
}
SequenceDialog::SequenceDialog(QWidget &parent, CaptureFile &cf, seq_analysis_info_t *sainfo) :
    WiresharkDialog(parent, cf),
    ui(new Ui::SequenceDialog),
    sainfo_(sainfo),
    num_items_(0),
    packet_num_(0),
    node_label_w_(20)
{
    ui->setupUi(this);
    QCustomPlot *sp = ui->sequencePlot;
    setWindowSubtitle(sainfo ? tr("Call Flow") : tr("Flow"));

    if (!sainfo_) {
        sainfo_ = sequence_analysis_info_new();
        sainfo_->type = SEQ_ANALYSIS_ANY;
        sainfo_->all_packets = TRUE;
    } else {
        num_items_ = sequence_analysis_get_nodes(sainfo_);
    }

    seq_diagram_ = new SequenceDiagram(sp->yAxis, sp->xAxis2, sp->yAxis2);
    sp->addPlottable(seq_diagram_);
    sp->axisRect()->setRangeDragAxes(sp->xAxis2, sp->yAxis);

    sp->xAxis->setVisible(false);
    sp->xAxis->setPadding(0);
    sp->xAxis->setLabelPadding(0);
    sp->xAxis->setTickLabelPadding(0);
    sp->xAxis2->setVisible(true);
    sp->yAxis2->setVisible(true);

    one_em_ = QFontMetrics(sp->yAxis->labelFont()).height();
    ui->horizontalScrollBar->setSingleStep(100 / one_em_);
    ui->verticalScrollBar->setSingleStep(100 / one_em_);

    sp->setInteractions(QCP::iRangeDrag);

    ui->gridLayout->setSpacing(0);
    connect(sp->yAxis, SIGNAL(rangeChanged(QCPRange)), sp->yAxis2, SLOT(setRange(QCPRange)));

    ctx_menu_.addAction(ui->actionReset);
    ctx_menu_.addSeparator();
    ctx_menu_.addAction(ui->actionMoveRight10);
    ctx_menu_.addAction(ui->actionMoveLeft10);
    ctx_menu_.addAction(ui->actionMoveUp10);
    ctx_menu_.addAction(ui->actionMoveDown10);
    ctx_menu_.addAction(ui->actionMoveRight1);
    ctx_menu_.addAction(ui->actionMoveLeft1);
    ctx_menu_.addAction(ui->actionMoveUp1);
    ctx_menu_.addAction(ui->actionMoveDown1);
    ctx_menu_.addSeparator();
    ctx_menu_.addAction(ui->actionGoToPacket);

    ui->showComboBox->blockSignals(true);
    ui->showComboBox->setCurrentIndex(0);
    ui->showComboBox->blockSignals(false);
    ui->addressComboBox->blockSignals(true);
    ui->addressComboBox->setCurrentIndex(0);
    ui->addressComboBox->blockSignals(false);

    QComboBox *fcb = ui->flowComboBox;
    fcb->addItem(ui->actionFlowAny->text(), SEQ_ANALYSIS_ANY);
    fcb->addItem(ui->actionFlowTcp->text(), SEQ_ANALYSIS_TCP);

    ui->flowComboBox->blockSignals(true);
    ui->flowComboBox->setCurrentIndex(sainfo_->type);

    if (sainfo_->type == SEQ_ANALYSIS_VOIP) {
        ui->controlFrame->hide();
    } else {
        ui->flowComboBox->blockSignals(false);
    }

    QPushButton *save_bt = ui->buttonBox->button(QDialogButtonBox::Save);
    save_bt->setText(tr("Save As" UTF8_HORIZONTAL_ELLIPSIS));

    // XXX Use recent settings instead
    resize(parent.width(), parent.height() * 4 / 5);

    connect(ui->horizontalScrollBar, SIGNAL(valueChanged(int)), this, SLOT(hScrollBarChanged(int)));
    connect(ui->verticalScrollBar, SIGNAL(valueChanged(int)), this, SLOT(vScrollBarChanged(int)));
    connect(sp->xAxis2, SIGNAL(rangeChanged(QCPRange)), this, SLOT(xAxisChanged(QCPRange)));
    connect(sp->yAxis, SIGNAL(rangeChanged(QCPRange)), this, SLOT(yAxisChanged(QCPRange)));
    connect(sp, SIGNAL(mousePress(QMouseEvent*)), this, SLOT(diagramClicked(QMouseEvent*)));
    connect(sp, SIGNAL(mouseMove(QMouseEvent*)), this, SLOT(mouseMoved(QMouseEvent*)));
    connect(sp, SIGNAL(mouseRelease(QMouseEvent*)), this, SLOT(mouseReleased(QMouseEvent*)));
    connect(this, SIGNAL(goToPacket(int)), seq_diagram_, SLOT(setSelectedPacket(int)));

    disconnect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept()));

    fillDiagram();
}
Example #16
0
QT_BEGIN_NAMESPACE

QPixmap QPixmap::grabWindow(WId window, int x, int y, int w, int h)
{
    QWidget *widget = QWidget::find(window);
    if (!widget)
        return QPixmap();

    QRect grabRect = widget->frameGeometry();
    if (!widget->isWindow())
        grabRect.translate(widget->parentWidget()->mapToGlobal(QPoint()));
    if (w < 0)
        w = widget->width() - x;
    if (h < 0)
        h = widget->height() - y;
    grabRect &= QRect(x, y, w, h).translated(widget->mapToGlobal(QPoint()));

    QScreen *screen = qt_screen;
    QDesktopWidget *desktop = QApplication::desktop();
    if (!desktop)
        return QPixmap();
    if (desktop->numScreens() > 1) {
        const int screenNo = desktop->screenNumber(widget);
        if (screenNo != -1)
            screen = qt_screen->subScreens().at(screenNo);
        grabRect = grabRect.translated(-screen->region().boundingRect().topLeft());
    }

    if (screen->pixelFormat() == QImage::Format_Invalid) {
        qWarning("QPixmap::grabWindow(): Unable to copy pixels from framebuffer");
        return QPixmap();
    }

    if (screen->isTransformed()) {
        const QSize screenSize(screen->width(), screen->height());
        grabRect = screen->mapToDevice(grabRect, screenSize);
    }

    QWSDisplay::grab(false);
    QPixmap pixmap;
    QImage img(screen->base(),
               screen->deviceWidth(), screen->deviceHeight(),
               screen->linestep(), screen->pixelFormat());
    img = img.copy(grabRect);
    QWSDisplay::ungrab();

    if (screen->isTransformed()) {
        QMatrix matrix;
        switch (screen->transformOrientation()) {
        case 1: matrix.rotate(90); break;
        case 2: matrix.rotate(180); break;
        case 3: matrix.rotate(270); break;
        default: break;
        }
        img = img.transformed(matrix);
    }

    if (screen->pixelType() == QScreen::BGRPixel)
        img = img.rgbSwapped();

    return QPixmap::fromImage(img);
}
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    installEventFilter(this);

    QPixmap *pixmap = NULL;
    pixmap = new QPixmap(200, 150);
    pixmap->load(":/f");
    QIcon *icon = new QIcon(*pixmap);
    chatPicture = new QPushButton(*icon, tr("P"), this);
    chatPicture->setIconSize(QSize(190, 150));
    chatPicture->setFixedSize(25, 25);
//    chatPicture->setStyleSheet("background:white");   //设置背景色

    QPixmap *pixmap1 = NULL;
    pixmap1 = new QPixmap(200, 150);
    pixmap1->load(":/e");
    QIcon *icon1 = new QIcon(*pixmap1);
    chatEmotion1 = new QPushButton(*icon1, tr("E"), this);
    chatEmotion1->setIconSize(QSize(190, 150));
    chatEmotion1->setFixedSize(24, 24);
//    chatEmotion1->setStyleSheet("background:white");

    QPixmap *pixmap2 = NULL;
    pixmap2 = new QPixmap(200, 150);
    pixmap2->load(":/c.png");
    QIcon *icon2 = new QIcon(*pixmap2);
    chatSend = new QPushButton(*icon2, tr("发送(S)"), this);
    chatSend->setIconSize(QSize(190, 150));
    chatSend->setFixedSize(60, 25);
//    chatSend->setStyleSheet("background:white");
    chatSend->setFocus(); //设置默认焦点
    //chatSend->setDefault(true); //设置默认按钮,设置了这个属性,当用户按下回车的时候,就会按下该按钮
    chatSend->setShortcut(QKeySequence::InsertParagraphSeparator);

    tein = new TextEdit;
//    tein->setFocus();

    QGridLayout *layout = new QGridLayout;

//    layout->addWidget(pArea, 0, 0, 13, 9);
    layout->addWidget(chatEmotion1, 0, 0, 1, 1);
    layout->addWidget(chatPicture, 0, 1, 1, 1);
    layout->addWidget(chatSend, 0, 2, 1, 1);
    layout->addWidget(tein, 1, 0, 1, 11);


    pArea= new QScrollArea(this);
    teout = new QWidget(pArea);//需要滚动的是一个Qwidget,而如果是在设计器里面拖入控件,会自动添加一个

    pArea->setWidget(teout);//这里设置滚动窗口qw,

//    pArea->setWidgetResizable(false);


    QGridLayout *layout1 = new QGridLayout;
    layout1->addWidget(pArea);

    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addLayout(layout1, 5);
    mainLayout->addLayout(layout, 2);

    QWidget *mainWidget = new QWidget;
    mainWidget->setMinimumSize(400, 550);
    mainWidget->setLayout(mainLayout);
    setCentralWidget(mainWidget);

//    QVBoxLayout* mainLayout1 = new QVBoxLayout;
//    mainLayout1->addWidget(mainWidget);
//    setLayout(mainLayout1);

    teout->setWindowFlags(Qt::FramelessWindowHint);//隐藏边框
    pArea->setWindowFlags(Qt::FramelessWindowHint);//隐藏边框
    this->setGeometry(0, 0, 400, 400);
    teout->setGeometry(0, 0, this->size().width() - 37, 1000000);

    qDebug() <<  mainWidget->width();

    connect(chatEmotion1, &QPushButton::clicked, this, &MainWindow::Emotion); //插入表情
    connect(chatPicture, SIGNAL(clicked()), this, SLOT(insertImage()));//插入图片
    connect(chatSend, &QPushButton::clicked, this, &MainWindow::sendfun);//发送消息
}
Example #18
0
static int getSourceByPosition(int x, int y, float ratio)
{
	int pos = -1;
	QWidget *rec = QApplication::activeWindow();
	if (!rec)
		return pos;
	int     cx    = rec->width();
	int     cy    = rec->height();
	int     minX  = 0;
	int     minY  = 0;
	int     maxX  = cx;
	int     maxY  = cy;

	switch (multiviewLayout) {
	case MultiviewLayout::HORIZONTAL_TOP_24_SCENES:
		if (float(cx) / float(cy) > ratio) {
			int validX = cy * ratio;
			minX = (cx / 2) - (validX / 2);
			maxX = (cx / 2) + (validX / 2);
			minY = cy / 3;
		} else {
			int validY = cx / ratio;
			maxY = (cy / 2) + (validY / 2);
			minY = (cy / 2) - (validY / 6);
		}

		if (x < minX || x > maxX || y < minY || y > maxY)
			break;

		pos = (x - minX) / ((maxX - minX) / 6);
		pos += ((y - minY) / ((maxY - minY) / 4)) * 6;

		break;
	case MultiviewLayout::VERTICAL_LEFT_8_SCENES:
		if (float(cx) / float(cy) > ratio) {
			int validX = cy * ratio;
			maxX = (cx / 2) + (validX / 2);
		} else {
			int validY = cx / ratio;
			minY = (cy / 2) - (validY / 2);
			maxY = (cy / 2) + (validY / 2);
		}

		minX = cx / 2;

		if (x < minX || x > maxX || y < minY || y > maxY)
			break;

		pos = 2 * ((y - minY) / ((maxY - minY) / 4));
		if (x > minX + ((maxX - minX) / 2))
			pos++;
		break;
	case MultiviewLayout::VERTICAL_RIGHT_8_SCENES:
		if (float(cx) / float(cy) > ratio) {
			int validX = cy * ratio;
			minX = (cx / 2) - (validX / 2);
		} else {
			int validY = cx / ratio;
			minY = (cy / 2) - (validY / 2);
			maxY = (cy / 2) + (validY / 2);
		}

		maxX = (cx / 2);

		if (x < minX || x > maxX || y < minY || y > maxY)
			break;

		pos = 2 * ((y - minY) / ((maxY - minY) / 4));
		if (x > minX + ((maxX - minX) / 2))
			pos++;
		break;
	case MultiviewLayout::HORIZONTAL_BOTTOM_8_SCENES:
		if (float(cx) / float(cy) > ratio) {
			int validX = cy * ratio;
			minX = (cx / 2) - (validX / 2);
			maxX = (cx / 2) + (validX / 2);
		} else {
			int validY = cx / ratio;
			minY = (cy / 2) - (validY / 2);
		}

		maxY = (cy / 2);

		if (x < minX || x > maxX || y < minY || y > maxY)
			break;

		pos = (x - minX) / ((maxX - minX) / 4);
		if (y > minY + ((maxY - minY) / 2))
			pos += 4;
		break;
	default: // MultiviewLayout::HORIZONTAL_TOP_8_SCENES
		if (float(cx) / float(cy) > ratio) {
			int validX = cy * ratio;
			minX = (cx / 2) - (validX / 2);
			maxX = (cx / 2) + (validX / 2);
		} else {
			int validY = cx / ratio;
			maxY = (cy / 2) + (validY / 2);
		}

		minY = (cy / 2);

		if (x < minX || x > maxX || y < minY || y > maxY)
			break;

		pos = (x - minX) / ((maxX - minX) / 4);
		if (y > minY + ((maxY - minY) / 2))
			pos += 4;
	}

	return pos;
}
void Q3TextBrowser::popupDetail(const QString& contents, const QPoint& pos)
{

    const int shadowWidth = 6;   // also used as '5' and '6' and even '8' below
    const int vMargin = 8;
    const int hMargin = 12;

    QWidget* popup = new QTextDetailPopup;
    popup->setAttribute(Qt::WA_NoSystemBackground, true);

    Q3SimpleRichText* doc = new Q3SimpleRichText(contents, popup->font());
    doc->adjustSize();
    QRect r(0, 0, doc->width(), doc->height());

    int w = r.width() + 2*hMargin;
    int h = r.height() + 2*vMargin;

    popup->resize(w + shadowWidth, h + shadowWidth);

    // okay, now to find a suitable location
    //###### we need a global fancy popup positioning somewhere
    popup->move(pos - popup->rect().center());
    if (popup->geometry().right() > QApplication::desktop()->width())
        popup->move(QApplication::desktop()->width() - popup->width(),
                     popup->y());
    if (popup->geometry().bottom() > QApplication::desktop()->height())
        popup->move(popup->x(),
                     QApplication::desktop()->height() - popup->height());
    if (popup->x() < 0)
        popup->move(0, popup->y());
    if (popup->y() < 0)
        popup->move(popup->x(), 0);


    popup->show();

    // now for super-clever shadow stuff.  super-clever mostly in
    // how many window system problems it skirts around.

    QPainter p(popup);
    p.setPen(QApplication::palette().color(QPalette::Active, QPalette::WindowText));
    p.drawRect(0, 0, w, h);
    p.setPen(QApplication::palette().color(QPalette::Active, QPalette::Mid));
    p.setBrush(QColor(255, 255, 240));
    p.drawRect(1, 1, w-2, h-2);
    p.setPen(Qt::black);

    doc->draw(&p, hMargin, vMargin, r, popup->palette(), 0);
    delete doc;

    p.drawPoint(w + 5, 6);
    p.drawLine(w + 3, 6,
                w + 5, 8);
    p.drawLine(w + 1, 6,
                w + 5, 10);
    int i;
    for(i=7; i < h; i += 2)
        p.drawLine(w, i,
                    w + 5, i + 5);
    for(i = w - i + h; i > 6; i -= 2)
        p.drawLine(i, h,
                    i + 5, h + 5);
    for(; i > 0 ; i -= 2)
        p.drawLine(6, h + 6 - i,
                    i + 5, h + 5);
}
Example #20
0
// NOTE: The X11 version of createSurface will re-create the native drawable if it's visual doesn't
// match the one for the passed in EGLConfig
EGLSurface QEgl::createSurface(QPaintDevice *device, EGLConfig config, const QEglProperties *properties)
{
    int devType = device->devType();

    if (devType == QInternal::Pbuffer) {
        // TODO
        return EGL_NO_SURFACE;
    }

    QX11PixmapData *x11PixmapData = 0;
    if (devType == QInternal::Pixmap) {
        QPixmapData *pmd = static_cast<QPixmap*>(device)->data_ptr().data();
        if (pmd->classId() == QPixmapData::X11Class)
            x11PixmapData = static_cast<QX11PixmapData*>(pmd);
        else {
            // TODO: Replace the pixmap's data with a new QX11PixmapData
            qWarning("WARNING: Creating an EGL surface on a QPixmap is only supported for QX11PixmapData");
            return EGL_NO_SURFACE;
        }
    } else if ((devType != QInternal::Widget) && (devType != QInternal::Pbuffer)) {
        qWarning("WARNING: Creating an EGLSurface for device type %d isn't supported", devType);
        return EGL_NO_SURFACE;
    }

    VisualID visualId = QEgl::getCompatibleVisualId(config);
    EGLint alphaSize;
    eglGetConfigAttrib(QEgl::display(), config, EGL_ALPHA_SIZE, &alphaSize);

    if (devType == QInternal::Widget) {
        QWidget *widget = static_cast<QWidget*>(device);

        VisualID currentVisualId = 0;
        if (widget->testAttribute(Qt::WA_WState_Created))
            currentVisualId = XVisualIDFromVisual((Visual*)widget->x11Info().visual());

        if (currentVisualId != visualId) {
            // The window is either not created or has the wrong visual. Either way, we need
            // to create a window with the correct visual and call create() on the widget:

            bool visible = widget->isVisible();
            if (visible)
                widget->hide();

            XVisualInfo visualInfo;
            visualInfo.visualid = visualId;
            {
                XVisualInfo *visualInfoPtr;
                int matchingCount = 0;
                visualInfoPtr = XGetVisualInfo(widget->x11Info().display(), VisualIDMask,
                                               &visualInfo, &matchingCount);
                Q_ASSERT(visualInfoPtr); // visualId really should be valid!
                visualInfo = *visualInfoPtr;
                XFree(visualInfoPtr);
            }

            Window parentWindow = RootWindow(widget->x11Info().display(), widget->x11Info().screen());
            if (widget->parentWidget())
                parentWindow = widget->parentWidget()->winId();

            XSetWindowAttributes windowAttribs;
            QColormap colmap = QColormap::instance(widget->x11Info().screen());
            windowAttribs.background_pixel = colmap.pixel(widget->palette().color(widget->backgroundRole()));
            windowAttribs.border_pixel = colmap.pixel(Qt::black);

            unsigned int valueMask = CWBackPixel|CWBorderPixel;
            if (alphaSize > 0) {
                windowAttribs.colormap = XCreateColormap(widget->x11Info().display(), parentWindow,
                                                         visualInfo.visual, AllocNone);
                valueMask |= CWColormap;
            }

            Window window = XCreateWindow(widget->x11Info().display(), parentWindow,
                                          widget->x(), widget->y(), widget->width(), widget->height(),
                                          0, visualInfo.depth, InputOutput, visualInfo.visual,
                                          valueMask, &windowAttribs);

            // This is a nasty hack to get round the fact that we can't be a friend of QWidget:
            qt_set_winid_on_widget(widget, window);

            if (visible)
                widget->show();
        }

        // At this point, the widget's window should be created and have the correct visual. Now we
        // just need to create the EGL surface for it:
        const int *props;
        if (properties)
            props = properties->properties();
        else
            props = 0;
        EGLSurface surf = eglCreateWindowSurface(QEgl::display(), config, (EGLNativeWindowType)widget->winId(), props);
        if (surf == EGL_NO_SURFACE)
            qWarning("QEglContext::createSurface(): Unable to create EGL surface, error = 0x%x", eglGetError());
        return surf;
    }

    if (x11PixmapData) {
        // X11 Pixmaps are only created with a depth, so that's all we need to check
        EGLint configDepth;
        eglGetConfigAttrib(QEgl::display(), config, EGL_BUFFER_SIZE , &configDepth);
        if (x11PixmapData->depth() != configDepth) {
            // The bit depths are wrong which means the EGLConfig isn't compatable with
            // this pixmap. So we need to replace the pixmap's existing data with a new
            // one which is created with the correct depth:

#ifndef QT_NO_XRENDER
            if (configDepth == 32) {
                qWarning("Warning: EGLConfig's depth (32) != pixmap's depth (%d), converting to ARGB32",
                         x11PixmapData->depth());
                x11PixmapData->convertToARGB32(true);
            } else
#endif
            {
                qWarning("Warning: EGLConfig's depth (%d) != pixmap's depth (%d)",
                         configDepth, x11PixmapData->depth());
            }
        }

        QEglProperties surfaceAttribs;

        // If the pixmap can't be bound to a texture, it's pretty useless
        surfaceAttribs.setValue(EGL_TEXTURE_TARGET, EGL_TEXTURE_2D);
        if (alphaSize > 0)
            surfaceAttribs.setValue(EGL_TEXTURE_FORMAT, EGL_TEXTURE_RGBA);
        else
            surfaceAttribs.setValue(EGL_TEXTURE_FORMAT, EGL_TEXTURE_RGB);

        EGLSurface surf = eglCreatePixmapSurface(QEgl::display(), config,
                                                 (EGLNativePixmapType) x11PixmapData->handle(),
                                                 surfaceAttribs.properties());
        x11PixmapData->gl_surface = (void*)surf;
        QImagePixmapCleanupHooks::enableCleanupHooks(x11PixmapData);
        return surf;
    }

    return EGL_NO_SURFACE;
}
Example #21
0
void OSDWidget::showOSD(const QString &str, OSDUserData *data)
{
    setFont(FontEdit::str2font(data->Font, baseFont));
    QPainter p(this);
    p.setFont(font());
    QWidget *d = qApp->desktop();
    QRect rc(0, 0,
             d->width() - SHADOW_OFFS - XOSD_MARGIN * 2 - data->Offset,
             d->height() - SHADOW_OFFS - XOSD_MARGIN * 2 - data->Offset);
    rc = p.boundingRect(rc, AlignLeft | AlignTop | WordBreak, str);
    p.end();
    int w = rc.width();
    int h = rc.height();
    if (data->Shadow){
        w += SHADOW_OFFS;
        h += SHADOW_OFFS;
    }
    if (data->Background){
        w += XOSD_MARGIN * 2;
        h += XOSD_MARGIN * 2;
    }
    resize(QSize(w, h));
    switch (data->Position){
    case 1:
        move(data->Offset, data->Offset);
        break;
    case 2:
        move(d->width() - data->Offset - w, d->height() - data->Offset - h);
        break;
    case 3:
        move(d->width() - data->Offset - w, data->Offset);
        break;
    case 4:
        move((d->width() - w) / 2, d->height() - data->Offset - h);
        break;
    case 5:
        move((d->width() - w) / 2, data->Offset);
        break;
    case 6:
        move((d->width() - w) / 2, (d->height() - h) /2);
        break;
    default:
        move(data->Offset, d->height() - data->Offset - h);
    }
    if (!data->Background || data->Shadow){
        QBitmap mask(w, h);
        p.begin(&mask);
#ifdef WIN32
        QColor bg(255, 255, 255);
        QColor fg(0, 0, 0);
#else
        QColor bg(0, 0, 0);
        QColor fg(255, 255, 255);
#endif
        p.fillRect(0, 0, w, h, bg);
        if (data->Background){
            p.fillRect(0, 0, w - SHADOW_OFFS, h - SHADOW_OFFS, fg);
            p.fillRect(SHADOW_OFFS, SHADOW_OFFS, w - SHADOW_OFFS, h - SHADOW_OFFS, fg);
        }else{
            p.setPen(fg);
            p.setFont(font());
            if (data->Shadow){
                rc = QRect(SHADOW_OFFS, SHADOW_OFFS, w - SHADOW_OFFS, h - SHADOW_OFFS);
                p.drawText(rc, AlignLeft | AlignTop | WordBreak, str);
            }
            rc = QRect(0, 0, w - SHADOW_OFFS, h - SHADOW_OFFS);
            p.drawText(rc, AlignLeft | AlignTop | WordBreak, str);
        }
        p.end();
        setMask(mask);
    }
    qApp->syncX();
    QPixmap pict = QPixmap::grabWindow(QApplication::desktop()->winId(), x(), y(), width(), height());
    intensity(pict, -0.50f);
    p.begin(&pict);
    rc = QRect(0, 0, w, h);
    if (data->Background){
        if (data->Shadow){
            w -= SHADOW_OFFS;
            h -= SHADOW_OFFS;
            rc = QRect(0, 0, w, h);
        }
        QBrush bg(data->BgColor);
        p.fillRect(rc, bg);
#if QT_VERSION < 300
        style().drawPopupPanel(&p, 0, 0, w, h, colorGroup(), 2, &bg);
#else
        style().drawPrimitive(QStyle::PE_PanelPopup, &p, rc, colorGroup());
#endif
        rc = QRect(XOSD_MARGIN, XOSD_MARGIN, w - XOSD_MARGIN * 2, h - XOSD_MARGIN * 2);
    }
    p.setFont(font());
    p.setPen(QColor(data->Color));
    p.drawText(rc, AlignLeft | AlignTop | WordBreak, str);
    p.end();
    bgPict = pict;
    QWidget::show();
    raise();
}
Example #22
0
void Q3TitleBar::mouseMoveEvent(QMouseEvent *e)
{
    Q_D(Q3TitleBar);
    e->accept();
    switch (d->buttonDown) {
    case QStyle::SC_None:
        if(autoRaise())
            repaint();
        break;
    case QStyle::SC_TitleBarSysMenu:
        break;
    case QStyle::SC_TitleBarShadeButton:
    case QStyle::SC_TitleBarUnshadeButton:
    case QStyle::SC_TitleBarNormalButton:
    case QStyle::SC_TitleBarMinButton:
    case QStyle::SC_TitleBarMaxButton:
    case QStyle::SC_TitleBarCloseButton:
        {
            QStyle::SubControl last_ctrl = d->buttonDown;
            QStyleOptionTitleBar opt = d->getStyleOption();
            d->buttonDown = style()->hitTestComplexControl(QStyle::CC_TitleBar, &opt, e->pos(), this);
            if (d->buttonDown != last_ctrl)
                d->buttonDown = QStyle::SC_None;
            repaint();
            d->buttonDown = last_ctrl;
        }
        break;

    case QStyle::SC_TitleBarLabel:
        if (d->buttonDown == QStyle::SC_TitleBarLabel && d->movable && d->pressed) {
            if ((d->moveOffset - mapToParent(e->pos())).manhattanLength() >= 4) {
                QPoint p = mapFromGlobal(e->globalPos());

                QWidget *parent = d->window ? d->window->parentWidget() : 0;
                if(parent && parent->inherits("Q3WorkspaceChild")) {
                    QWidget *workspace = parent->parentWidget();
                    p = workspace->mapFromGlobal(e->globalPos());
                    if (!workspace->rect().contains(p)) {
                        if (p.x() < 0)
                            p.rx() = 0;
                        if (p.y() < 0)
                            p.ry() = 0;
                        if (p.x() > workspace->width())
                            p.rx() = workspace->width();
                        if (p.y() > workspace->height())
                            p.ry() = workspace->height();
                    }
                }

                QPoint pp = p - d->moveOffset;
                if (!parentWidget()->isMaximized())
                    parentWidget()->move(pp);
            }
        } else {
            QStyle::SubControl last_ctrl = d->buttonDown;
            d->buttonDown = QStyle::SC_None;
            if(d->buttonDown != last_ctrl)
                repaint();
        }
        break;
    default:
        break;
    }
}
Example #23
0
void PeersDialog::smileyWidgetgroupchat()
{ 
	qDebug("MainWindow::smileyWidget()");
	QWidget *smWidget = new QWidget(this , Qt::Popup );
	smWidget->setWindowTitle("Emoticons");
	smWidget->setWindowIcon(QIcon(QString(":/images/rstray3.png")));
	//smWidget->setFixedSize(256,256);

	smWidget->setBaseSize( 4*24, (smileys.size()/4)*24  );

    //Warning: this part of code was taken from kadu instant messenger;
    //         It was EmoticonSelector::alignTo(QWidget* w) function there
    //         comments are Polish, I dont' know how does it work...
    // oblicz pozycj� widgetu do kt�rego r�wnamy
    QWidget* w = ui.emoticonBtn;
    QPoint w_pos = w->mapToGlobal(QPoint(0,0));
    // oblicz rozmiar selektora
    QSize e_size = smWidget->sizeHint();
    // oblicz rozmiar pulpitu
    QSize s_size = QApplication::desktop()->size();
    // oblicz dystanse od widgetu do lewego brzegu i do prawego
    int l_dist = w_pos.x();
    int r_dist = s_size.width() - (w_pos.x() + w->width());
    // oblicz pozycj� w zale�no�ci od tego czy po lewej stronie
    // jest wi�cej miejsca czy po prawej
    int x;
    if (l_dist >= r_dist)
        x = w_pos.x() - e_size.width();
    else
        x = w_pos.x() + w->width();
    // oblicz pozycj� y - centrujemy w pionie
    int y = w_pos.y() + w->height()/2 - e_size.height()/2;
    // je�li wychodzi poza doln� kraw�d� to r�wnamy do niej
    if (y + e_size.height() > s_size.height())
        y = s_size.height() - e_size.height();
    // je�li wychodzi poza g�rn� kraw�d� to r�wnamy do niej
    if (y < 0)
         y = 0;
    // ustawiamy selektor na wyliczonej pozycji
    smWidget->move(x, y);
	
	x = 0;
    y = 0;
	
	QHashIterator<QString, QString> i(smileys);
	while(i.hasNext())
	{
		i.next();
		QPushButton *smButton = new QPushButton("", smWidget);
		smButton->setGeometry(x*24, y*24, 24,24);
		smButton->setIconSize(QSize(24,24));
		smButton->setIcon(QPixmap(i.value()));
		smButton->setToolTip(i.key());
		//smButton->setFixedSize(24,24);
		++x;
		if(x > 4)
		{
			x = 0;
			y++;
		}
		connect(smButton, SIGNAL(clicked()), this, SLOT(addSmileys()));
        connect(smButton, SIGNAL(clicked()), smWidget, SLOT(close()));
	}
	
	smWidget->show();
}
Example #24
0
void TabWidget::Private::setTitle( const QString &title, QWidget* sender)
{
    int senderIndex = q->indexOf(sender);

    q->setTabToolTip( senderIndex, QString() );

    uint lcw=0, rcw=0;
    int tabBarHeight = q->tabBar()->sizeHint().height();

    QWidget* leftCorner = q->cornerWidget( Qt::TopLeftCorner );

    if ( leftCorner  && leftCorner->isVisible() )
        lcw = qMax( leftCorner->width(), tabBarHeight );

    QWidget* rightCorner = q->cornerWidget( Qt::TopRightCorner );

    if ( rightCorner && rightCorner->isVisible() )
        rcw = qMax( rightCorner->width(), tabBarHeight );
    uint maxTabBarWidth = q->width() - lcw - rcw;

    int newMaxLength = 30;

    for ( ; newMaxLength > 3; newMaxLength-- )
    {
        if ( tabBarWidthForMaxChars( newMaxLength ) < maxTabBarWidth )
            break;
    }

    QString newTitle = title;
    if ( newTitle.length() > newMaxLength )
    {
        q->setTabToolTip( senderIndex, newTitle );
        newTitle = newTitle.left( newMaxLength-3 ) + "...";
    }

    newTitle.replace( '&', "&&" );

    if ( q->tabText(senderIndex) != newTitle )
        q->setTabText( senderIndex, newTitle );

    if( newMaxLength != currentMaxLength )
    {
        for( int i = 0; i < q->count(); ++i)
        {
            Frame* f = frames.value(q->widget(i));
            if ( !f ) {
                continue; // frames is out of sync, e.g. because tabInserted wasn't called yet - #185597
            }
            newTitle = f->title();
            int index = q->indexOf(q->widget( i ));
            q->setTabToolTip( index, QString() );

            if ( newTitle.length() > newMaxLength )
            {
                q->setTabToolTip( index, newTitle );
                newTitle = newTitle.left( newMaxLength-3 ) + "...";
            }

            newTitle.replace( '&', "&&" );
            if ( newTitle != q->tabText( index ) )
                q->setTabText( index, newTitle );
        }
        currentMaxLength = newMaxLength;
    }
}
Example #25
0
 void takeScreenshot()
 {
     QDateTime createdDate = QDateTime::currentDateTime();
     //QPixmap originalPixmap = QPixmap::grabWindow(QApplication::activeWindow()->winId());
     QWidget *widget = QApplication::activeWindow();
     QPixmap originalPixmap = QPixmap::grabWindow(QApplication::desktop()->winId());
     QPixmap windowPixmap = originalPixmap.copy(widget->geometry().x(), widget->geometry().y(), widget->width(), widget->height());
     QString format = "png";
     QString fileName = getAppPath() + "/" + createdDate.toString("yyyyMMdd_HHmmss") + "_gideros." + format;
     windowPixmap.save(fileName, format.toAscii());
     onMediaReceived(fileName.toStdString().c_str());
 }
void QmlProfilerStateWidget::reposition()
{
    QWidget *parentWidget = qobject_cast<QWidget *>(parent());
    // positioning it at 2/3 height (it looks better)
    move(parentWidget->width()/2 - width()/2, parentWidget->height()/3 - height()/2);
}
void KexiFormScrollAreaWidget::mouseMoveEvent(QMouseEvent *e)
{
    //qDebug() << e->pos() << scrollArea->widget()->size();
    if (!scrollArea->isResizingEnabled()) {
        return;
    }

    QWidget *mainAreaWidget = scrollArea->mainAreaWidget();
    if (m_resizing) { // resize widget
        int tmpx = e->x();
        int tmpy = e->y();
        const int exceeds_x = tmpx + 5 - scrollArea->widget()->width();
        const int exceeds_y = tmpy + 5 - scrollArea->widget()->height();
        if (exceeds_x > 0) {
            tmpx -= exceeds_x;
        }
        if (exceeds_y > 0) {
            tmpy -= exceeds_y;
        }
        if ((tmpx - scrollArea->horizontalScrollBar()->value()) < 0) {
            tmpx = scrollArea->horizontalScrollBar()->value();
        }
        if ((tmpy - scrollArea->verticalScrollBar()->value()) < 0) {
            tmpy = scrollArea->verticalScrollBar()->value();
        }
        // we look for the max widget right() (or bottom()),
        // which would be the limit for form resizing (not to hide widgets)
        const QList<QWidget*> list(mainAreaWidget->findChildren<QWidget*>()); /* not recursive*/
        foreach(QWidget *w, list) {
            tmpx = qMax(tmpx, (w->geometry().right() + 10));
            tmpy = qMax(tmpy, (w->geometry().bottom() + 10));
        }

        int neww = -1, newh;
        const int gridSize = (scrollArea->form()->isSnapToGridEnabled()
                              && scrollArea->form()->gridSize() > 1)
                             ? scrollArea->form()->gridSize() : 0;
        if (cursor().shape() == Qt::SizeHorCursor) {
            if (gridSize > 0) {
                neww = int(float(tmpx) / float(gridSize) + 0.5) * gridSize;
            }
            else {
                neww = tmpx;
            }
            newh = mainAreaWidget->height();
        } else if (cursor().shape() == Qt::SizeVerCursor) {
            neww = mainAreaWidget->width();
            if (gridSize > 0) {
                newh = int(float(tmpy) / float(gridSize) + 0.5) * gridSize;
            }
            else {
                newh = tmpy;
            }
        } else if (cursor().shape() == Qt::SizeFDiagCursor) {
            if (gridSize > 0) {
                neww = int(float(tmpx) / float(gridSize) + 0.5) * gridSize;
                newh = int(float(tmpy) / float(gridSize) + 0.5) * gridSize;
            } else {
                neww = tmpx;
                newh = tmpy;
            }
        }
        // needs update?
        if (neww != -1 && mainAreaWidget->size() != QSize(neww, newh)) {
            qDebug() << "mainAreaWidget->size():" << mainAreaWidget->size()
                     << "neww, newh:" << neww << newh;
            mainAreaWidget->resize(neww, newh);
            scrollArea->refreshContentsSize();
            emit resized();
        }
    }
Iax2AnalysisDialog::Iax2AnalysisDialog(QWidget &parent, CaptureFile &cf) :
    WiresharkDialog(parent, cf),
    ui(new Ui::Iax2AnalysisDialog),
    port_src_fwd_(0),
    port_dst_fwd_(0),
    port_src_rev_(0),
    port_dst_rev_(0)
{
    ui->setupUi(this);
    setWindowSubtitle(tr("IAX2 Stream Analysis"));

    // XXX Use recent settings instead
    resize(parent.width() * 4 / 5, parent.height() * 4 / 5);
    ui->progressFrame->hide();

    stream_ctx_menu_.addAction(ui->actionGoToPacket);
    stream_ctx_menu_.addAction(ui->actionNextProblem);
    stream_ctx_menu_.addSeparator();
    stream_ctx_menu_.addAction(ui->actionSaveAudio);
    stream_ctx_menu_.addAction(ui->actionSaveForwardAudio);
    stream_ctx_menu_.addAction(ui->actionSaveReverseAudio);
    stream_ctx_menu_.addSeparator();
    stream_ctx_menu_.addAction(ui->actionSaveCsv);
    stream_ctx_menu_.addAction(ui->actionSaveForwardCsv);
    stream_ctx_menu_.addAction(ui->actionSaveReverseCsv);
    stream_ctx_menu_.addSeparator();
    stream_ctx_menu_.addAction(ui->actionSaveGraph);
    ui->forwardTreeWidget->installEventFilter(this);
    ui->forwardTreeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->forwardTreeWidget, SIGNAL(customContextMenuRequested(QPoint)),
                SLOT(showStreamMenu(QPoint)));
    ui->reverseTreeWidget->installEventFilter(this);
    ui->reverseTreeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->reverseTreeWidget, SIGNAL(customContextMenuRequested(QPoint)),
                SLOT(showStreamMenu(QPoint)));
    connect(ui->streamGraph, SIGNAL(mousePress(QMouseEvent*)),
            this, SLOT(graphClicked(QMouseEvent*)));

    graph_ctx_menu_.addAction(ui->actionSaveGraph);

    QStringList header_labels;
    for (int i = 0; i < ui->forwardTreeWidget->columnCount(); i++) {
        header_labels << ui->forwardTreeWidget->headerItem()->text(i);
    }
    ui->reverseTreeWidget->setHeaderLabels(header_labels);

    memset(&src_fwd_, 0, sizeof(address));
    memset(&dst_fwd_, 0, sizeof(address));
    memset(&src_rev_, 0, sizeof(address));
    memset(&dst_rev_, 0, sizeof(address));

    QList<QCheckBox *> graph_cbs = QList<QCheckBox *>()
            << ui->fJitterCheckBox << ui->fDiffCheckBox
            << ui->rJitterCheckBox << ui->rDiffCheckBox;

    for (int i = 0; i < num_graphs_; i++) {
        QCPGraph *graph = ui->streamGraph->addGraph();
        graph->setPen(QPen(ColorUtils::graph_colors_[i]));
        graph->setName(graph_cbs[i]->text());
        graphs_ << graph;
        graph_cbs[i]->setChecked(true);
        graph_cbs[i]->setIcon(StockIcon::colorIcon(ColorUtils::graph_colors_[i], QPalette::Text));
    }
    ui->streamGraph->xAxis->setLabel("Arrival Time");
    ui->streamGraph->yAxis->setLabel("Value (ms)");

    // We keep our temp files open for the lifetime of the dialog. The GTK+
    // UI opens and closes at various points.
    QString tempname = QString("%1/wireshark_iax2_f").arg(QDir::tempPath());
    fwd_tempfile_ = new QTemporaryFile(tempname, this);
    fwd_tempfile_->open();
    tempname = QString("%1/wireshark_iax2_r").arg(QDir::tempPath());
    rev_tempfile_ = new QTemporaryFile(tempname, this);
    rev_tempfile_->open();

    if (fwd_tempfile_->error() != QFile::NoError || rev_tempfile_->error() != QFile::NoError) {
        err_str_ = tr("Unable to save RTP data.");
        ui->actionSaveAudio->setEnabled(false);
        ui->actionSaveForwardAudio->setEnabled(false);
        ui->actionSaveReverseAudio->setEnabled(false);
    }

    QMenu *save_menu = new QMenu();
    save_menu->addAction(ui->actionSaveAudio);
    save_menu->addAction(ui->actionSaveForwardAudio);
    save_menu->addAction(ui->actionSaveReverseAudio);
    save_menu->addSeparator();
    save_menu->addAction(ui->actionSaveCsv);
    save_menu->addAction(ui->actionSaveForwardCsv);
    save_menu->addAction(ui->actionSaveReverseCsv);
    save_menu->addSeparator();
    save_menu->addAction(ui->actionSaveGraph);
    ui->buttonBox->button(QDialogButtonBox::Save)->setMenu(save_menu);

    const gchar *filter_text = "iax2 && (ip || ipv6)";
    dfilter_t *sfcode;
    gchar *err_msg;

    if (!dfilter_compile(filter_text, &sfcode, &err_msg)) {
        QMessageBox::warning(this, tr("No IAX2 packets found"), QString("%1").arg(err_msg));
        g_free(err_msg);
        close();
    }

    if (!cap_file_.capFile() || !cap_file_.capFile()->current_frame) close();

    frame_data *fdata = cap_file_.capFile()->current_frame;

    if (!cf_read_record(cap_file_.capFile(), fdata)) close();

    epan_dissect_t edt;

    epan_dissect_init(&edt, cap_file_.capFile()->epan, TRUE, FALSE);
    epan_dissect_prime_dfilter(&edt, sfcode);
    epan_dissect_run(&edt, cap_file_.capFile()->cd_t, &cap_file_.capFile()->phdr,
                     frame_tvbuff_new_buffer(fdata, &cap_file_.capFile()->buf), fdata, NULL);

    // This shouldn't happen (the menu item should be disabled) but check anyway
    if (!dfilter_apply_edt(sfcode, &edt)) {
        epan_dissect_cleanup(&edt);
        dfilter_free(sfcode);
        err_str_ = tr("Please select an IAX2 packet");
        updateWidgets();
        return;
    }

    dfilter_free(sfcode);

    /* ok, it is a IAX2 frame, so let's get the ip and port values */
    COPY_ADDRESS(&(src_fwd_), &(edt.pi.src));
    COPY_ADDRESS(&(dst_fwd_), &(edt.pi.dst));
    port_src_fwd_ = edt.pi.srcport;
    port_dst_fwd_ = edt.pi.destport;

    /* assume the inverse ip/port combination for the reverse direction */
    COPY_ADDRESS(&(src_rev_), &(edt.pi.dst));
    COPY_ADDRESS(&(dst_rev_), &(edt.pi.src));
    port_src_rev_ = edt.pi.destport;
    port_dst_rev_ = edt.pi.srcport;

#if 0
    /* check if it is Voice or MiniPacket */
    bool ok;
    getIntFromProtoTree(edt.tree, "iax2", "iax2.call", &ok);
    if (!ok) {
        err_str_ = tr("Please select an IAX2 packet.");
        updateWidgets();
        return;
    }
#endif

#ifdef IAX2_RTP_STREAM_CHECK
    rtpstream_tapinfot tapinfo;

    /* Register the tap listener */
    memset(&tapinfo, 0, sizeof(rtpstream_tapinfot));
    tapinfo.tap_data = this;
    tapinfo.mode = TAP_ANALYSE;

//    register_tap_listener_rtp_stream(&tapinfo, NULL);
    /* Scan for RTP streams (redissect all packets) */
    rtpstream_scan(&tapinfo, cap_file_.capFile(), NULL);

    int num_streams = 0;
    GList *filtered_list = NULL;
    for (GList *strinfo_list = g_list_first(tapinfo.strinfo_list); strinfo_list; strinfo_list = g_list_next(strinfo_list)) {
        rtp_stream_info_t * strinfo = (rtp_stream_info_t*)(strinfo_list->data);
                 << address_to_qstring(&strinfo->dest_addr) << address_to_qstring(&src_rev_) << address_to_qstring(&dst_rev_);
        if (ADDRESSES_EQUAL(&(strinfo->src_addr), &(src_fwd_))
            && (strinfo->src_port == port_src_fwd_)
            && (ADDRESSES_EQUAL(&(strinfo->dest_addr), &(dst_fwd_)))
            && (strinfo->dest_port == port_dst_fwd_))
        {
            ++num_streams;
            filtered_list = g_list_prepend(filtered_list, strinfo);
        }

        if (ADDRESSES_EQUAL(&(strinfo->src_addr), &(src_rev_))
            && (strinfo->src_port == port_src_rev_)
            && (ADDRESSES_EQUAL(&(strinfo->dest_addr), &(dst_rev_)))
            && (strinfo->dest_port == port_dst_rev_))
        {
            ++num_streams;
            filtered_list = g_list_append(filtered_list, strinfo);
        }
    }
Example #29
0
QString qt_mac_get_save_file_name(const QFileDialogArgs &args, QString *pwd,
                                  QString *selectedFilter)
{
    QWidget *parent = args.parent;
    OSErr err;
    QString retstr;
    NavDialogCreationOptions options;
    NavGetDefaultDialogCreationOptions(&options);
    static const int w = 450, h = 350;
    if (args.options & QFileDialog::DontConfirmOverwrite)
        options.optionFlags |= kNavDontConfirmReplacement;
    options.modality = kWindowModalityAppModal;
    options.location.h = options.location.v = -1;
    if (!args.directory.isEmpty())
        options.saveFileName = QCFString::toCFStringRef(args.selection);
    if (!args.caption.isEmpty())
        options.windowTitle = QCFString::toCFStringRef(args.caption);
    if (parent && parent->isVisible()) {
        WindowClass wclass;
        GetWindowClass(qt_mac_window_for(parent), &wclass);
        if (!(args.options & QFileDialog::DontUseSheet) && (wclass == kDocumentWindowClass ||
                                                            wclass == kFloatingWindowClass || wclass == kMovableModalWindowClass)) {
            options.modality = kWindowModalityWindowModal;
            options.parentWindow = qt_mac_window_for(parent);

            // The parent needs to be active for the sheet to get keyboard focus.
            if (!parent->isActiveWindow())
                parent->activateWindow();
        } else {
            parent = parent->window();
            QString s = parent->windowTitle();
            options.clientName = CFStringCreateWithCharacters(0, (UniChar *)s.unicode(), s.length());
            options.location.h = (parent->x() + (parent->width() / 2)) - (w / 2);
            options.location.v = (parent->y() + (parent->height() / 2)) - (h / 2);

            QRect r = QApplication::desktop()->screenGeometry(
                QApplication::desktop()->screenNumber(parent));
            if (options.location.h + w > r.right())
                options.location.h -= (options.location.h + w) - r.right() + 10;
            if (options.location.v + h > r.bottom())
                options.location.v -= (options.location.v + h) - r.bottom() + 10;
        }
#if 0
    } else if (QWidget *p = qApp->mainWidget()) {
        static int last_screen = -1;
        int scr = QApplication::desktop()->screenNumber(p);
        if (last_screen != scr) {
            QRect r = QApplication::desktop()->screenGeometry(scr);
            options.location.h = (r.x() + (r.width() / 2)) - (w / 2);
            options.location.v = (r.y() + (r.height() / 2)) - (h / 2);
        }
#endif
    }

    QList<qt_mac_filter_name*> filts = qt_mac_make_filters_list(args.filter);
    qt_mac_nav_filter_type t;
    t.saveDialog = true;
    t.index = 0;
    t.filts = &filts;
    if (filts.count() > 1) {
        int i = 0;
        CFStringRef *arr = static_cast<CFStringRef *>(malloc(sizeof(CFStringRef) * filts.count()));
        for (QList<qt_mac_filter_name*>::const_iterator it = filts.constBegin();
             it != filts.constEnd(); ++it)
            arr[i++] = QCFString::toCFStringRef((*it)->description);
        options.popupExtension = CFArrayCreate(0, reinterpret_cast<const void **>(arr), filts.count(), 0);
    }

    NavDialogRef dlg;
    if (NavCreatePutFileDialog(&options, 'cute', kNavGenericSignature, make_navProcUPP(),
                               static_cast<void *>(filts.isEmpty() ? 0 : &t), &dlg)) {
        qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__);
        return retstr;
    }
    if (pwd && !pwd->isEmpty()) {
        FSRef fsref;
        if (qt_mac_create_fsref(*pwd, &fsref) == noErr) {
            AEDesc desc;
            if (AECreateDesc(typeFSRef, &fsref, sizeof(FSRef), &desc) == noErr)
                NavCustomControl(dlg, kNavCtlSetLocation, (void*)&desc);
        }
    }
    NavDialogRun(dlg);
    if (selectedFilter) {
        NavMenuItemSpec navSpec;
        bzero(&navSpec, sizeof(NavMenuItemSpec));
        qt_mac_filter_name *sel_filt_name = qt_mac_make_filters_list(*selectedFilter).at(0);
        for (int i = 0; i < filts.count(); ++i) {
            const qt_mac_filter_name *filter = filts.at(i);
            if (sel_filt_name->description == filter->description
                    && sel_filt_name->regxp == filter->regxp
                    && sel_filt_name->filter == filter->filter) {
                navSpec.menuType = i;
                break;
            }
        }
        NavCustomControl(dlg, kNavCtlSelectCustomType, &navSpec);
    }
    if (options.modality == kWindowModalityWindowModal) { //simulate modality
        QWidget modal_widg(parent, Qt::Sheet);
        modal_widg.createWinId();
        QApplicationPrivate::enterModal(&modal_widg);
        while (g_nav_blocking)
            qApp->processEvents(QEventLoop::WaitForMoreEvents);
        QApplicationPrivate::leaveModal(&modal_widg);
    }

    if (NavDialogGetUserAction(dlg) != kNavUserActionSaveAs) {
        NavDialogDispose(dlg);
        return retstr;
    }
    NavReplyRecord ret;
    NavDialogGetReply(dlg, &ret);
    NavDialogDispose(dlg);

    long count;
    err = AECountItems(&(ret.selection), &count);
    if (!ret.validRecord || err != noErr || !count) {
        NavDisposeReply(&ret);
        return retstr;
    }

    AEKeyword        keyword;
    DescType    type;
    Size        size;
    FSRef ref;
    err = AEGetNthPtr(&(ret.selection), 1, typeFSRef, &keyword,
                      &type, &ref, sizeof(ref), &size);
    if (err == noErr) {
        if (!str_buffer) {
            qAddPostRoutine(cleanup_str_buffer);
            str_buffer = (UInt8 *)malloc(1024);
        }
        FSRefMakePath(&ref, str_buffer, 1024);
        retstr = QString::fromUtf8((const char *)str_buffer);
        //now filename
        CFStringGetCString(ret.saveFileName, (char *)str_buffer, 1024, kCFStringEncodingUTF8);
        retstr += QLatin1String("/") + QString::fromUtf8((const char *)str_buffer);
    }
    NavDisposeReply(&ret);
    if (selectedFilter)
        *selectedFilter = filts.at(t.index)->filter;
    while (!filts.isEmpty())
        delete filts.takeFirst();
    return retstr;
}
Example #30
0
Container::Container(unsigned id, const char *cfg)
{
    m_bInit   = false;
    m_bInSize = false;
    m_bStatusSize = false;
    m_bBarChanged = false;
    m_bReceived = false;
    m_bNoSwitch = false;
    m_bNoRead   = false;
	m_wnds		= NULL;
	m_tabBar	= NULL;

    SET_WNDPROC("container")
    setWFlags(WDestructiveClose);

    if (cfg && *cfg){
        Buffer config;
        config << "[Title]\n" << cfg;
        config.setWritePos(0);
        config.getSection();
        load_data(containerData, &data, &config);
    }else{
        load_data(containerData, &data, NULL);
    }

    bool bPos = true;
    if (cfg == NULL){
        setId(id);
        memcpy(data.barState, CorePlugin::m_plugin->data.containerBar, sizeof(data.barState));
        memcpy(data.geometry, CorePlugin::m_plugin->data.containerGeo, sizeof(data.geometry));
        if ((data.geometry[WIDTH].value == (unsigned long)-1) || (data.geometry[HEIGHT].value == (unsigned long)-1)){
            QWidget *desktop = QApplication::desktop();
            data.geometry[WIDTH].value = desktop->width() / 3;
            data.geometry[HEIGHT].value = desktop->height() / 3;
        }
        bPos = false;
        if ((data.geometry[TOP].value != (unsigned long)-1) || (data.geometry[LEFT].value != (unsigned long)-1)){
            bPos = true;
            QWidgetList  *list = QApplication::topLevelWidgets();
            for (int i = 0; i < 2; i++){
                bool bOK = true;
                QWidgetListIt it(*list);
                QWidget * w;
                while ((w = it.current()) != NULL){
                    if (w == this){
                        ++it;
                        continue;
                    }
                    if (w->inherits("Container")){
                        int dw = w->pos().x() - data.geometry[LEFT].value;
                        int dh = w->pos().y() - data.geometry[TOP].value;
                        if (dw < 0) dw = -dw;
                        if (dh < 0) dh = -dh;
                        if ((dw < 3) && (dh < 3)){
                            int nl = data.geometry[LEFT].value;
                            int nt = data.geometry[TOP].value;
                            nl += 21;
                            nt += 20;
                            QWidget *desktop = QApplication::desktop();
                            if (nl + (int)data.geometry[WIDTH].value > desktop->width())
                                nl = 0;
                            if (nt + (int)data.geometry[WIDTH].value > desktop->width())
                                nt = 0;
                            if ((nl != (int)data.geometry[LEFT].value) && (nt != (int)data.geometry[TOP].value)){
                                data.geometry[LEFT].value = nl;
                                data.geometry[TOP].value  = nt;
                                bOK = false;
                            }
                        }
                    }
                    ++it;
                }
                if (bOK)
                    break;
            }
            delete list;
        }
        setStatusSize(CorePlugin::m_plugin->getContainerStatusSize());
    }
    m_bInSize = true;
    restoreGeometry(this, data.geometry, bPos, true);
    m_bInSize = false;
}