/*
    Sets the socket option \a opt to \a v.
*/
bool QNativeSocketEnginePrivate::setOption(QNativeSocketEngine::SocketOption opt, int v)
{
    Q_Q(QNativeSocketEngine);
    if (!q->isValid())
        return false;

    int n = 0;
    int level = SOL_SOCKET; // default

    switch (opt) {
    case QNativeSocketEngine::ReceiveBufferSocketOption:
        n = SO_RCVBUF;
        break;
    case QNativeSocketEngine::SendBufferSocketOption:
        n = SO_SNDBUF;
        break;
    case QNativeSocketEngine::BroadcastSocketOption:
        n = SO_BROADCAST;
        break;
    case QNativeSocketEngine::NonBlockingSocketOption: {
        // Make the socket nonblocking

        int flags = ::fcntl(socketDescriptor, F_GETFL, 0);
        if (flags == -1) {
#ifdef QNATIVESOCKETENGINE_DEBUG
            perror("QNativeSocketEnginePrivate::setOption(): fcntl(F_GETFL) failed");
#endif
            return false;
        }
        if (::fcntl(socketDescriptor, F_SETFL, flags | O_NONBLOCK) == -1) {
#ifdef QNATIVESOCKETENGINE_DEBUG
            perror("QNativeSocketEnginePrivate::setOption(): fcntl(F_SETFL) failed");
#endif
            return false;
        }

        return true;
    }
    case QNativeSocketEngine::AddressReusable:
#if defined(SO_REUSEPORT)
        // on OS X, SO_REUSEADDR isn't sufficient to allow multiple binds to the
        // same port (which is useful for multicast UDP). SO_REUSEPORT is, but
        // we most definitely do not want to use this for TCP. See QTBUG-6305.
        if (socketType == QAbstractSocket::UdpSocket)
            n = SO_REUSEPORT;
        else
            n = SO_REUSEADDR;
#else
        n = SO_REUSEADDR;
#endif
        break;
    case QNativeSocketEngine::BindExclusively:
        return true;
    case QNativeSocketEngine::ReceiveOutOfBandData:
        n = SO_OOBINLINE;
        break;
    case QNativeSocketEngine::LowDelayOption:
        level = IPPROTO_TCP;
        n = TCP_NODELAY;
        break;
    case QNativeSocketEngine::KeepAliveOption:
        n = SO_KEEPALIVE;
        break;
    case QNativeSocketEngine::MulticastTtlOption:

        if (socketProtocol == QAbstractSocket::IPv6Protocol) {
            level = IPPROTO_IPV6;
            n = IPV6_MULTICAST_HOPS;
        } else

        {
            level = IPPROTO_IP;
            n = IP_MULTICAST_TTL;
        }
        break;
    case QNativeSocketEngine::MulticastLoopbackOption:

        if (socketProtocol == QAbstractSocket::IPv6Protocol) {
            level = IPPROTO_IPV6;
            n = IPV6_MULTICAST_LOOP;
        } else

        {
            level = IPPROTO_IP;
            n = IP_MULTICAST_LOOP;
        }
        break;
    }

    return ::setsockopt(socketDescriptor, level, n, (char *) &v, sizeof(v)) == 0;
}
示例#2
0
void QProcessPrivate::startProcess()
{
    Q_Q(QProcess);

    bool success = false;

    if (pid) {
        CloseHandle(pid->hThread);
        CloseHandle(pid->hProcess);
        delete pid;
        pid = 0;
    }
    pid = new PROCESS_INFORMATION;
    memset(pid, 0, sizeof(PROCESS_INFORMATION));

    q->setProcessState(QProcess::Starting);

    if (!createChannel(stdinChannel) ||
        !createChannel(stdoutChannel) ||
        !createChannel(stderrChannel))
        return;

    QString args = qt_create_commandline(program, arguments);
    QByteArray envlist;
    if (environment.d.constData())
        envlist = qt_create_environment(environment.d.constData()->hash);
    if (!nativeArguments.isEmpty()) {
        if (!args.isEmpty())
             args += QLatin1Char(' ');
        args += nativeArguments;
    }

#if defined QPROCESS_DEBUG
    qDebug("Creating process");
    qDebug("   program : [%s]", program.toLatin1().constData());
    qDebug("   args : %s", args.toLatin1().constData());
    qDebug("   pass environment : %s", environment.isEmpty() ? "no" : "yes");
#endif

    // Forwarded channels must not set the CREATE_NO_WINDOW flag because this
    // will render the stdout/stderr handles we're passing useless.
    DWORD dwCreationFlags = (processChannelMode == QProcess::ForwardedChannels ? 0 : CREATE_NO_WINDOW);
    dwCreationFlags |= CREATE_UNICODE_ENVIRONMENT;
    STARTUPINFOW startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
                                 (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT,
                                 (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT,
                                 0, 0, 0,
                                 STARTF_USESTDHANDLES,
                                 0, 0, 0,
                                 stdinChannel.pipe[0], stdoutChannel.pipe[1], stderrChannel.pipe[1]
    };
    success = CreateProcess(0, (wchar_t*)args.utf16(),
                            0, 0, TRUE, dwCreationFlags,
                            environment.isEmpty() ? 0 : envlist.data(),
                            workingDirectory.isEmpty() ? 0 : (wchar_t*)QDir::toNativeSeparators(workingDirectory).utf16(),
                            &startupInfo, pid);
    if (!success) {
        // Capture the error string before we do CloseHandle below
        q->setErrorString(QProcess::tr("Process failed to start: %1").arg(qt_error_string()));
    }

    if (stdinChannel.pipe[0] != INVALID_Q_PIPE) {
        CloseHandle(stdinChannel.pipe[0]);
        stdinChannel.pipe[0] = INVALID_Q_PIPE;
    }
    if (stdoutChannel.pipe[1] != INVALID_Q_PIPE) {
        CloseHandle(stdoutChannel.pipe[1]);
        stdoutChannel.pipe[1] = INVALID_Q_PIPE;
    }
    if (stderrChannel.pipe[1] != INVALID_Q_PIPE) {
        CloseHandle(stderrChannel.pipe[1]);
        stderrChannel.pipe[1] = INVALID_Q_PIPE;
    }

    if (!success) {
        cleanup();
        processError = QProcess::FailedToStart;
        emit q->error(processError);
        q->setProcessState(QProcess::NotRunning);
        return;
    }

    q->setProcessState(QProcess::Running);
    // User can call kill()/terminate() from the stateChanged() slot
    // so check before proceeding
    if (!pid)
        return;

    if (threadData->hasEventDispatcher()) {
        processFinishedNotifier = new QWinEventNotifier(pid->hProcess, q);
        QObject::connect(processFinishedNotifier, SIGNAL(activated(HANDLE)), q, SLOT(_q_processDied()));
        processFinishedNotifier->setEnabled(true);
        notifier = new QTimer(q);
        QObject::connect(notifier, SIGNAL(timeout()), q, SLOT(_q_notified()));
        notifier->start(NOTIFYTIMEOUT);
    }

    _q_startupNotification();
}
void LibInputHandlerPrivate::_q_liEventHandler()
{
    Q_Q(LibInputHandler);

    if (libinput_dispatch(li) != 0) {
        qCWarning(lcInput) << "Failed to dispatch libinput events";
        return;
    }

    libinput_event *event;
    while ((event = libinput_get_event(li)) != Q_NULLPTR) {
        libinput_event_type type = libinput_event_get_type(event);
        libinput_device *device = libinput_event_get_device(event);

        switch (type) {
        // Devices
        case LIBINPUT_EVENT_DEVICE_ADDED:
            if (libinput_device_has_capability(device, LIBINPUT_DEVICE_CAP_KEYBOARD)) {
                ++keyboardCount;
                Q_EMIT q->capabilitiesChanged();
                Q_EMIT q->keyboardCountChanged(keyboardCount);
            }

            if (libinput_device_has_capability(device, LIBINPUT_DEVICE_CAP_POINTER)) {
                ++pointerCount;
                Q_EMIT q->capabilitiesChanged();
                Q_EMIT q->pointerCountChanged(pointerCount);
            }

            if (libinput_device_has_capability(device, LIBINPUT_DEVICE_CAP_TOUCH)) {
                QTouchDevice *td = touch->registerDevice(device);
                Q_EMIT q->touchDeviceRegistered(td);

                ++touchCount;
                Q_EMIT q->capabilitiesChanged();
                Q_EMIT q->touchCountChanged(touchCount);
            }

            if (libinput_device_has_capability(device, LIBINPUT_DEVICE_CAP_GESTURE)) {
                ++gestureCount;
                Q_EMIT q->capabilitiesChanged();
                Q_EMIT q->gestureCountChanged(gestureCount);
            }
            break;
        case LIBINPUT_EVENT_DEVICE_REMOVED:
            if (libinput_device_has_capability(device, LIBINPUT_DEVICE_CAP_KEYBOARD)) {
                --keyboardCount;
                Q_EMIT q->capabilitiesChanged();
                Q_EMIT q->keyboardCountChanged(keyboardCount);
            }

            if (libinput_device_has_capability(device, LIBINPUT_DEVICE_CAP_POINTER)) {
                --pointerCount;
                Q_EMIT q->capabilitiesChanged();
                Q_EMIT q->pointerCountChanged(pointerCount);
            }

            if (libinput_device_has_capability(device, LIBINPUT_DEVICE_CAP_TOUCH)) {
                QTouchDevice *td = Q_NULLPTR;
                touch->unregisterDevice(device, &td);
                Q_EMIT q->touchDeviceUnregistered(td);

                --touchCount;
                Q_EMIT q->capabilitiesChanged();
                Q_EMIT q->touchCountChanged(touchCount);
            }

            if (libinput_device_has_capability(device, LIBINPUT_DEVICE_CAP_GESTURE)) {
                --gestureCount;
                Q_EMIT q->capabilitiesChanged();
                Q_EMIT q->gestureCountChanged(gestureCount);
            }
            break;
            // Keyboard
        case LIBINPUT_EVENT_KEYBOARD_KEY:
            keyboard->handleKey(libinput_event_get_keyboard_event(event));
            break;
            // Pointer
        case LIBINPUT_EVENT_POINTER_BUTTON:
            pointer->handleButton(libinput_event_get_pointer_event(event));
            break;
        case LIBINPUT_EVENT_POINTER_AXIS:
            pointer->handleAxis(libinput_event_get_pointer_event(event));
            break;
        case LIBINPUT_EVENT_POINTER_MOTION:
            pointer->handleMotion(libinput_event_get_pointer_event(event));
            break;
        case LIBINPUT_EVENT_POINTER_MOTION_ABSOLUTE:
            pointer->handleAbsoluteMotion(libinput_event_get_pointer_event(event));
            break;
            // Touch
        case LIBINPUT_EVENT_TOUCH_UP:
            touch->handleTouchUp(libinput_event_get_touch_event(event));
            break;
        case LIBINPUT_EVENT_TOUCH_DOWN:
            touch->handleTouchDown(libinput_event_get_touch_event(event));
            break;
        case LIBINPUT_EVENT_TOUCH_FRAME:
            touch->handleTouchFrame(libinput_event_get_touch_event(event));
            break;
        case LIBINPUT_EVENT_TOUCH_MOTION:
            touch->handleTouchMotion(libinput_event_get_touch_event(event));
            break;
        case LIBINPUT_EVENT_TOUCH_CANCEL:
            touch->handleTouchCancel(libinput_event_get_touch_event(event));
            break;
            // Gesture
        case LIBINPUT_EVENT_GESTURE_PINCH_BEGIN:
            gesture->handlePinchBegin(libinput_event_get_gesture_event(event));
            break;
        case LIBINPUT_EVENT_GESTURE_PINCH_END:
            gesture->handlePinchEnd(libinput_event_get_gesture_event(event));
            break;
        case LIBINPUT_EVENT_GESTURE_PINCH_UPDATE:
            gesture->handlePinchUpdate(libinput_event_get_gesture_event(event));
            break;
        case LIBINPUT_EVENT_GESTURE_SWIPE_BEGIN:
            gesture->handleSwipeBegin(libinput_event_get_gesture_event(event));
            break;
        case LIBINPUT_EVENT_GESTURE_SWIPE_END:
            gesture->handleSwipeEnd(libinput_event_get_gesture_event(event));
            break;
        case LIBINPUT_EVENT_GESTURE_SWIPE_UPDATE:
            gesture->handleSwipeUpdate(libinput_event_get_gesture_event(event));
            break;
        default:
            break;
        }

        libinput_event_destroy(event);
    }
}
示例#4
0
uchar *QFSFileEnginePrivate::map(qint64 offset, qint64 size,
                                 QFile::MemoryMapFlags flags)
{
#ifndef Q_OS_WINPHONE
    Q_Q(QFSFileEngine);
    Q_UNUSED(flags);
    if (openMode == QFile::NotOpen) {
        q->setError(QFile::PermissionsError, qt_error_string(ERROR_ACCESS_DENIED));
        return 0;
    }
    if (offset == 0 && size == 0) {
        q->setError(QFile::UnspecifiedError, qt_error_string(ERROR_INVALID_PARAMETER));
        return 0;
    }

    // check/setup args to map
    DWORD access = 0;
    if (flags & QFileDevice::MapPrivateOption) {
#ifdef FILE_MAP_COPY
        access = FILE_MAP_COPY;
#else
        q->setError(QFile::UnspecifiedError, "MapPrivateOption unsupported");
        return 0;
#endif
    } else if (openMode & QIODevice::WriteOnly) {
        access = FILE_MAP_WRITE;
    } else if (openMode & QIODevice::ReadOnly) {
        access = FILE_MAP_READ;
    }

    if (mapHandle == NULL) {
        // get handle to the file
        HANDLE handle = fileHandle;

#ifndef Q_OS_WINCE
        if (handle == INVALID_HANDLE_VALUE && fh)
            handle = (HANDLE)::_get_osfhandle(QT_FILENO(fh));
#endif

#ifdef Q_USE_DEPRECATED_MAP_API
        nativeClose();
        // handle automatically closed by kernel with mapHandle (below).
        handle = ::CreateFileForMapping((const wchar_t*)fileEntry.nativeFilePath().utf16(),
                GENERIC_READ | (openMode & QIODevice::WriteOnly ? GENERIC_WRITE : 0),
                0,
                NULL,
                OPEN_EXISTING,
                FILE_ATTRIBUTE_NORMAL,
                NULL);
        // Since this is a special case, we check if the return value was NULL and if so
        // we change it to INVALID_HANDLE_VALUE to follow the logic inside this function.
        if(0 == handle)
            handle = INVALID_HANDLE_VALUE;
#endif

        if (handle == INVALID_HANDLE_VALUE) {
            q->setError(QFile::PermissionsError, qt_error_string(ERROR_ACCESS_DENIED));
            return 0;
        }

        // first create the file mapping handle
        DWORD protection = (openMode & QIODevice::WriteOnly) ? PAGE_READWRITE : PAGE_READONLY;
#ifndef Q_OS_WINRT
        mapHandle = ::CreateFileMapping(handle, 0, protection, 0, 0, 0);
#else
        mapHandle = ::CreateFileMappingFromApp(handle, 0, protection, 0, 0);
#endif
        if (mapHandle == NULL) {
            q->setError(QFile::PermissionsError, qt_error_string());
#ifdef Q_USE_DEPRECATED_MAP_API
            ::CloseHandle(handle);
#endif
            return 0;
        }
    }

    DWORD offsetHi = offset >> 32;
    DWORD offsetLo = offset & Q_UINT64_C(0xffffffff);
    SYSTEM_INFO sysinfo;
#ifndef Q_OS_WINRT
    ::GetSystemInfo(&sysinfo);
#else
    ::GetNativeSystemInfo(&sysinfo);
#endif
    DWORD mask = sysinfo.dwAllocationGranularity - 1;
    DWORD extra = offset & mask;
    if (extra)
        offsetLo &= ~mask;

    // attempt to create the map
#ifndef Q_OS_WINRT
    LPVOID mapAddress = ::MapViewOfFile(mapHandle, access,
                                      offsetHi, offsetLo, size + extra);
#else
    LPVOID mapAddress = ::MapViewOfFileFromApp(mapHandle, access,
                                               (ULONG64(offsetHi) << 32) + offsetLo, size + extra);
#endif
    if (mapAddress) {
        uchar *address = extra + static_cast<uchar*>(mapAddress);
        maps[address] = extra;
        return address;
    }

    switch(GetLastError()) {
    case ERROR_ACCESS_DENIED:
        q->setError(QFile::PermissionsError, qt_error_string());
        break;
    case ERROR_INVALID_PARAMETER:
        // size are out of bounds
    default:
        q->setError(QFile::UnspecifiedError, qt_error_string());
    }

    ::CloseHandle(mapHandle);
    mapHandle = NULL;
#else // !Q_OS_WINPHONE
    Q_UNUSED(offset);
    Q_UNUSED(size);
    Q_UNUSED(flags);
    Q_UNIMPLEMENTED();
#endif // Q_OS_WINPHONE
    return 0;
}
示例#5
0
void QLocalSocketPrivate::_q_canWrite()
{
    Q_Q(QLocalSocket);
    if (state == QLocalSocket::ClosingState)
        q->close();
}
示例#6
0
void QAbstractTransitionPrivate::emitTriggered()
{
    Q_Q(QAbstractTransition);
    emit q->triggered();
}
示例#7
0
//------------------------------------------------------------------------------
void ctkDICOMDatabasePrivate::init(QString databaseFilename)
{
  Q_Q(ctkDICOMDatabase);

  q->openDatabase(databaseFilename);
}
示例#8
0
void QToolButtonPrivate::popupTimerDone()
{
    Q_Q(QToolButton);
    popupTimer.stop();
    if (!menuButtonDown && !down)
        return;

    menuButtonDown = true;
    QPointer<QMenu> actualMenu;
    bool mustDeleteActualMenu = false;
    if(menuAction) {
        actualMenu = menuAction->menu();
    } else if (defaultAction && defaultAction->menu()) {
        actualMenu = defaultAction->menu();
    } else {
        actualMenu = new QMenu(q);
        mustDeleteActualMenu = true;
        for(int i = 0; i < actions.size(); i++)
            actualMenu->addAction(actions.at(i));
    }
    repeat = q->autoRepeat();
    q->setAutoRepeat(false);
    bool horizontal = true;
#if !defined(QT_NO_TOOLBAR)
    QToolBar *tb = qobject_cast<QToolBar*>(parent);
    if (tb && tb->orientation() == Qt::Vertical)
        horizontal = false;
#endif
    QPoint p;
    QRect screen = QApplication::desktop()->availableGeometry(q);
    QSize sh = ((QToolButton*)(QMenu*)actualMenu)->receivers(SIGNAL(aboutToShow()))? QSize() : actualMenu->sizeHint();
    QRect rect = q->rect();
    if (horizontal) {
        if (q->isRightToLeft()) {
            if (q->mapToGlobal(QPoint(0, rect.bottom())).y() + sh.height() <= screen.height()) {
                p = q->mapToGlobal(rect.bottomRight());
            } else {
                p = q->mapToGlobal(rect.topRight() - QPoint(0, sh.height()));
            }
            p.rx() -= sh.width();
        } else {
            if (q->mapToGlobal(QPoint(0, rect.bottom())).y() + sh.height() <= screen.height()) {
                p = q->mapToGlobal(rect.bottomLeft());
            } else {
                p = q->mapToGlobal(rect.topLeft() - QPoint(0, sh.height()));
            }
        }
    } else {
        if (q->isRightToLeft()) {
            if (q->mapToGlobal(QPoint(rect.left(), 0)).x() - sh.width() <= screen.x()) {
                p = q->mapToGlobal(rect.topRight());
            } else {
                p = q->mapToGlobal(rect.topLeft());
                p.rx() -= sh.width();
            }
        } else {
            if (q->mapToGlobal(QPoint(rect.right(), 0)).x() + sh.width() <= screen.right()) {
                p = q->mapToGlobal(rect.topRight());
            } else {
                p = q->mapToGlobal(rect.topLeft() - QPoint(sh.width(), 0));
            }
        }
    }
    p.rx() = qMax(screen.left(), qMin(p.x(), screen.right() - sh.width()));
    p.ry() += 1;
    QPointer<QToolButton> that = q;
    actualMenu->setNoReplayFor(q);
    if (!mustDeleteActualMenu) //only if action are not in this widget
        QObject::connect(actualMenu, SIGNAL(triggered(QAction*)), q, SLOT(_q_menuTriggered(QAction*)));
    QObject::connect(actualMenu, SIGNAL(aboutToHide()), q, SLOT(_q_updateButtonDown()));
    actualMenu->d_func()->causedPopup.widget = q;
    actualMenu->d_func()->causedPopup.action = defaultAction;
    actionsCopy = q->actions(); //(the list of action may be modified in slots)
    actualMenu->exec(p);
    QObject::disconnect(actualMenu, SIGNAL(aboutToHide()), q, SLOT(_q_updateButtonDown()));
    if (mustDeleteActualMenu)
        delete actualMenu;
    else
        QObject::disconnect(actualMenu, SIGNAL(triggered(QAction*)), q, SLOT(_q_menuTriggered(QAction*)));

    if (!that)
        return;

    actionsCopy.clear();

    if (repeat)
        q->setAutoRepeat(true);
}
示例#9
0
void QToolButtonPrivate::_q_menuTriggered(QAction *action)
{
    Q_Q(QToolButton);
    if (action && !actionsCopy.contains(action))
        emit q->triggered(action);
}
示例#10
0
int QDBusInterfacePrivate::metacall(QMetaObject::Call c, int id, void **argv)
{
    Q_Q(QDBusInterface);

    if (c == QMetaObject::InvokeMetaMethod) {
        int offset = metaObject->methodOffset();
        QMetaMethod mm = metaObject->method(id + offset);

        if (mm.methodType() == QMetaMethod::Signal) {
            // signal relay from D-Bus world to Qt world
            QMetaObject::activate(q, metaObject, id, argv);

        } else if (mm.methodType() == QMetaMethod::Slot) {
            // method call relay from Qt world to D-Bus world
            // get D-Bus equivalent signature
            QString methodName = QLatin1String(metaObject->dbusNameForMethod(id));
            const int *inputTypes = metaObject->inputTypesForMethod(id);
            int inputTypesCount = *inputTypes;

            // we will assume that the input arguments were passed correctly
            QVariantList args;
            for (int i = 1; i <= inputTypesCount; ++i)
                args << QVariant(inputTypes[i], argv[i]);

            // make the call
            QPointer<QDBusInterface> qq = q;
            QDBusMessage reply = q->callWithArgumentList(QDBus::Block, methodName, args);
            args.clear();

            // we ignore return values

            // access to "this" or to "q" below this point must check for "qq"
            // we may have been deleted!

            if (!qq.isNull())
                lastError = reply;

            // done
            return -1;
        }
    } else if (c == QMetaObject::ReadProperty) {
        // Qt doesn't support non-readable properties
        // we have to re-check
        QMetaProperty mp = metaObject->property(id + metaObject->propertyOffset());
        if (!mp.isReadable())
            return -1;          // don't read

        QVariant *value = reinterpret_cast<QVariant*>(argv[1]);
        argv[1] = 0;
        *value = property(mp);

        return -1;              // handled, error or not
    } else if (c == QMetaObject::WriteProperty) {
        // QMetaProperty::write has already checked that we're writable
        // it has also checked that the type is right
        QVariant *value = reinterpret_cast<QVariant *>(argv[1]);
        QMetaProperty mp = metaObject->property(id + metaObject->propertyOffset());

        setProperty(mp, *value);
        return -1;
    }
    return id;
}
示例#11
0
void QToolButtonPrivate::_q_actionTriggered()
{
    Q_Q(QToolButton);
    if (QAction *action = qobject_cast<QAction *>(q->sender()))
        emit q->triggered(action);
}
示例#12
0
QT_BEGIN_NAMESPACE

/*!
    \class QScrollBar
    \brief The QScrollBar widget provides a vertical or horizontal scroll bar.

    \ingroup basicwidgets
    \inmodule QtWidgets

    A scroll bar is a control that enables the user to access parts of a
    document that is larger than the widget used to display it. It provides
    a visual indication of the user's current position within the document
    and the amount of the document that is visible. Scroll bars are usually
    equipped with other controls that enable more accurate navigation.
    Qt displays scroll bars in a way that is appropriate for each platform.

    If you need to provide a scrolling view onto another widget, it may be
    more convenient to use the QScrollArea class because this provides a
    viewport widget and scroll bars. QScrollBar is useful if you need to
    implement similar functionality for specialized widgets using QAbstractScrollArea;
    for example, if you decide to subclass QAbstractItemView.
    For most other situations where a slider control is used to obtain a value
    within a given range, the QSlider class may be more appropriate for your
    needs.

    \table
    \row \li \image qscrollbar-picture.png
    \li Scroll bars typically include four separate controls: a slider,
    scroll arrows, and a page control.

    \list
    \li a. The slider provides a way to quickly go to any part of the
    document, but does not support accurate navigation within large
    documents.
    \li b. The scroll arrows are push buttons which can be used to accurately
    navigate to a particular place in a document. For a vertical scroll bar
    connected to a text editor, these typically move the current position one
    "line" up or down, and adjust the position of the slider by a small
    amount. In editors and list boxes a "line" might mean one line of text;
    in an image viewer it might mean 20 pixels.
    \li c. The page control is the area over which the slider is dragged (the
    scroll bar's background). Clicking here moves the scroll bar towards
    the click by one "page". This value is usually the same as the length of
    the slider.
    \endlist
    \endtable

    Each scroll bar has a value that indicates how far the slider is from
    the start of the scroll bar; this is obtained with value() and set
    with setValue(). This value always lies within the range of values
    defined for the scroll bar, from \l{QAbstractSlider::minimum()}{minimum()}
    to \l{QAbstractSlider::minimum()}{maximum()} inclusive. The range of
    acceptable values can be set with setMinimum() and setMaximum().
    At the minimum value, the top edge of the slider (for a vertical scroll
    bar) or left edge (for a horizontal scroll bar) will be at the top (or
    left) end of the scroll bar. At the maximum value, the bottom (or right)
    edge of the slider will be at the bottom (or right) end of the scroll bar.

    The length of the slider is usually related to the value of the page step,
    and typically represents the proportion of the document area shown in a
    scrolling view. The page step is the amount that the value changes by
    when the user presses the \uicontrol{Page Up} and \uicontrol{Page Down} keys, and is
    set with setPageStep(). Smaller changes to the value defined by the
    line step are made using the cursor keys, and this quantity is set with
    \l{QAbstractSlider::}{setSingleStep()}.

    Note that the range of values used is independent of the actual size
    of the scroll bar widget. You do not need to take this into account when
    you choose values for the range and the page step.

    The range of values specified for the scroll bar are often determined
    differently to those for a QSlider because the length of the slider
    needs to be taken into account. If we have a document with 100 lines,
    and we can only show 20 lines in a widget, we may wish to construct a
    scroll bar with a page step of 20, a minimum value of 0, and a maximum
    value of 80. This would give us a scroll bar with five "pages".

    \table
    \row \li \inlineimage qscrollbar-values.png
    \li The relationship between a document length, the range of values used
    in a scroll bar, and the page step is simple in many common situations.
    The scroll bar's range of values is determined by subtracting a
    chosen page step from some value representing the length of the document.
    In such cases, the following equation is useful:
    \e{document length} = maximum() - minimum() + pageStep().
    \endtable

    QScrollBar only provides integer ranges. Note that although
    QScrollBar handles very large numbers, scroll bars on current
    screens cannot usefully represent ranges above about 100,000 pixels.
    Beyond that, it becomes difficult for the user to control the
    slider using either the keyboard or the mouse, and the scroll
    arrows will have limited use.

    ScrollBar inherits a comprehensive set of signals from QAbstractSlider:
    \list
    \li \l{QAbstractSlider::valueChanged()}{valueChanged()} is emitted when the
       scroll bar's value has changed. The tracking() determines whether this
       signal is emitted during user interaction.
    \li \l{QAbstractSlider::rangeChanged()}{rangeChanged()} is emitted when the
       scroll bar's range of values has changed.
    \li \l{QAbstractSlider::sliderPressed()}{sliderPressed()} is emitted when
       the user starts to drag the slider.
    \li \l{QAbstractSlider::sliderMoved()}{sliderMoved()} is emitted when the user
       drags the slider.
    \li \l{QAbstractSlider::sliderReleased()}{sliderReleased()} is emitted when
       the user releases the slider.
    \li \l{QAbstractSlider::actionTriggered()}{actionTriggered()} is emitted
       when the scroll bar is changed by user interaction or via the
       \l{QAbstractSlider::triggerAction()}{triggerAction()} function.
    \endlist

    A scroll bar can be controlled by the keyboard, but it has a
    default focusPolicy() of Qt::NoFocus. Use setFocusPolicy() to
    enable keyboard interaction with the scroll bar:
    \list
         \li Left/Right move a horizontal scroll bar by one single step.
         \li Up/Down move a vertical scroll bar by one single step.
         \li PageUp moves up one page.
         \li PageDown moves down one page.
         \li Home moves to the start (mininum).
         \li End moves to the end (maximum).
     \endlist

    The slider itself can be controlled by using the
    \l{QAbstractSlider::triggerAction()}{triggerAction()} function to simulate
    user interaction with the scroll bar controls. This is useful if you have
    many different widgets that use a common range of values.

    Most GUI styles use the pageStep() value to calculate the size of the
    slider.

    \table 100%
    \row \li \inlineimage macintosh-horizontalscrollbar.png Screenshot of a Macintosh style scroll bar
         \li A scroll bar shown in the \l{Macintosh Style Widget Gallery}{Macintosh widget style}.
    \row \li \inlineimage windowsvista-horizontalscrollbar.png Screenshot of a Windows Vista style scroll bar
         \li A scroll bar shown in the \l{Windows Vista Style Widget Gallery}{Windows Vista widget style}.
    \row \li \inlineimage fusion-horizontalscrollbar.png Screenshot of a Fusion style scroll bar
         \li A scroll bar shown in the \l{Fusion Style Widget Gallery}{Fusion widget style}.
    \endtable

    \sa QScrollArea, QSlider, QDial, QSpinBox, {fowler}{GUI Design Handbook: Scroll Bar}, {Sliders Example}
*/

bool QScrollBarPrivate::updateHoverControl(const QPoint &pos)
{
    Q_Q(QScrollBar);
    QRect lastHoverRect = hoverRect;
    QStyle::SubControl lastHoverControl = hoverControl;
    bool doesHover = q->testAttribute(Qt::WA_Hover);
    if (lastHoverControl != newHoverControl(pos) && doesHover) {
        q->update(lastHoverRect);
        q->update(hoverRect);
        return true;
    }
    return !doesHover;
}
示例#13
0
// -----------------------------------------------------------------------------
void ctkDynamicSpacerPrivate::init()
{
  Q_Q(ctkDynamicSpacer);
  this->ActiveSizePolicy = q->sizePolicy();
  this->InactiveSizePolicy = q->sizePolicy();
}
void QAbstractAnimationPrivate::setState(QAbstractAnimation::State newState)
{
    Q_Q(QAbstractAnimation);
    if (state == newState)
        return;

    if (loopCount == 0)
        return;

    QAbstractAnimation::State oldState = state;
    int oldCurrentTime = currentTime;
    int oldCurrentLoop = currentLoop;
    QAbstractAnimation::Direction oldDirection = direction;

    // check if we should Rewind
    if ((newState == QAbstractAnimation::Paused || newState == QAbstractAnimation::Running)
        && oldState == QAbstractAnimation::Stopped) {
            //here we reset the time if needed
            //we don't call setCurrentTime because this might change the way the animation
            //behaves: changing the state or changing the current value
            totalCurrentTime = currentTime = (direction == QAbstractAnimation::Forward) ?
                0 : (loopCount == -1 ? q->duration() : q->totalDuration());
    }

    state = newState;
    QWeakPointer<QAbstractAnimation> guard(q);

    //(un)registration of the animation must always happen before calls to
    //virtual function (updateState) to ensure a correct state of the timer
    bool isTopLevel = !group || group->state() == QAbstractAnimation::Stopped;
    if (oldState == QAbstractAnimation::Running) {
        if (newState == QAbstractAnimation::Paused && hasRegisteredTimer)
            QUnifiedTimer::ensureTimerUpdate();
        //the animation, is not running any more
        QUnifiedTimer::unregisterAnimation(q);
    } else if (newState == QAbstractAnimation::Running) {
        QUnifiedTimer::registerAnimation(q, isTopLevel);
    }

    q->updateState(newState, oldState);
    if (!guard || newState != state) //this is to be safe if updateState changes the state
        return;

    // Notify state change
    emit q->stateChanged(newState, oldState);
    if (!guard || newState != state) //this is to be safe if updateState changes the state
        return;

    switch (state) {
    case QAbstractAnimation::Paused:
        break;
    case QAbstractAnimation::Running:
        {

            // this ensures that the value is updated now that the animation is running
            if (oldState == QAbstractAnimation::Stopped) {
                if (isTopLevel) {
                    // currentTime needs to be updated if pauseTimer is active
                    QUnifiedTimer::ensureTimerUpdate();
                    q->setCurrentTime(totalCurrentTime);
                }
            }
        }
        break;
    case QAbstractAnimation::Stopped:
        // Leave running state.
        int dura = q->duration();

        if (deleteWhenStopped)
            q->deleteLater();

        if (dura == -1 || loopCount < 0
            || (oldDirection == QAbstractAnimation::Forward && (oldCurrentTime * (oldCurrentLoop + 1)) == (dura * loopCount))
            || (oldDirection == QAbstractAnimation::Backward && oldCurrentTime == 0)) {
                emit q->finished();
        }
        break;
    }
}
示例#15
0
bool QAbstractTransitionPrivate::callEventTest(QEvent *e)
{
    Q_Q(QAbstractTransition);
    return q->eventTest(e);
}
示例#16
0
void QItemDelegatePrivate::_q_commitDataAndCloseEditor(QWidget *editor)
{
    Q_Q(QItemDelegate);
    emit q->commitData(editor);
    emit q->closeEditor(editor, QAbstractItemDelegate::SubmitModelCache);
}
示例#17
0
void QAbstractTransitionPrivate::callOnTransition(QEvent *e)
{
    Q_Q(QAbstractTransition);
    q->onTransition(e);
}
示例#18
0
bool QSerialPortPrivate::open(QIODevice::OpenMode mode)
{
    Q_Q(QSerialPort);

    DWORD desiredAccess = 0;
    originalEventMask = EV_ERR | EV_CTS | EV_DSR | EV_RING /*| EV_RLSD*/;

    if (mode & QIODevice::ReadOnly) {
        desiredAccess |= GENERIC_READ;
        originalEventMask |= EV_RXCHAR;
    }
    if (mode & QIODevice::WriteOnly)
        desiredAccess |= GENERIC_WRITE;

    handle = ::CreateFile(reinterpret_cast<const wchar_t*>(systemLocation.utf16()),
                              desiredAccess, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);

    if (handle == INVALID_HANDLE_VALUE) {
        q->setError(decodeSystemError());
        return false;
    }

    ::ZeroMemory(&restoredDcb, sizeof(restoredDcb));
    restoredDcb.DCBlength = sizeof(restoredDcb);

    if (!::GetCommState(handle, &restoredDcb)) {
        q->setError(decodeSystemError());
        return false;
    }

    currentDcb = restoredDcb;
    currentDcb.fBinary = TRUE;
    currentDcb.fInX = FALSE;
    currentDcb.fOutX = FALSE;
    currentDcb.fAbortOnError = FALSE;
    currentDcb.fNull = FALSE;
    currentDcb.fErrorChar = FALSE;

    if (currentDcb.fDtrControl ==  DTR_CONTROL_HANDSHAKE)
        currentDcb.fDtrControl = DTR_CONTROL_DISABLE;

    if (!updateDcb())
        return false;

    if (!::GetCommTimeouts(handle, &restoredCommTimeouts)) {
        q->setError(decodeSystemError());
        return false;
    }

    ::ZeroMemory(&currentCommTimeouts, sizeof(currentCommTimeouts));
    currentCommTimeouts.ReadIntervalTimeout = MAXDWORD;

    if (!updateCommTimeouts())
        return false;

    if (mode & QIODevice::ReadOnly)
        readCompletionNotifier->setEnabled(true);

    if (mode & QIODevice::WriteOnly)
        writeCompletionNotifier->setEnabled(true);

    if (!::SetCommMask(handle, originalEventMask)) {
        q->setError(decodeSystemError());
        return false;
    }

    if (!startAsyncCommunication())
        return false;

    communicationNotifier->setEnabled(true);

    return true;
}
示例#19
0
/*
    Initializes the data structure needed by qGeomCalc and
    recalculates max/min and size hint.
*/
void QBoxLayoutPrivate::setupGeom()
{
    if (!dirty)
        return;

    Q_Q(QBoxLayout);
    int maxw = horz(dir) ? 0 : QLAYOUTSIZE_MAX;
    int maxh = horz(dir) ? QLAYOUTSIZE_MAX : 0;
    int minw = 0;
    int minh = 0;
    int hintw = 0;
    int hinth = 0;

    bool horexp = false;
    bool verexp = false;

    hasHfw = false;

    int n = list.count();
    geomArray.clear();
    QVector<QLayoutStruct> a(n);

    QSizePolicy::ControlTypes controlTypes1;
    QSizePolicy::ControlTypes controlTypes2;
    int fixedSpacing = q->spacing();
    int previousNonEmptyIndex = -1;

    QStyle *style = 0;
    if (fixedSpacing < 0) {
        if (QWidget *parentWidget = q->parentWidget())
            style = parentWidget->style();
    }

    for (int i = 0; i < n; i++) {
        QBoxLayoutItem *box = list.at(i);
        QSize max = box->item->maximumSize();
        QSize min = box->item->minimumSize();
        QSize hint = box->item->sizeHint();
        Qt::Orientations exp = box->item->expandingDirections();
        bool empty = box->item->isEmpty();
        int spacing = 0;

        if (!empty) {
            if (fixedSpacing >= 0) {
                spacing = (previousNonEmptyIndex >= 0) ? fixedSpacing : 0;
#ifdef Q_OS_MAC
                if (!horz(dir) && previousNonEmptyIndex >= 0) {
                    QBoxLayoutItem *sibling = (dir == QBoxLayout::TopToBottom  ? box : list.at(previousNonEmptyIndex));
                    if (sibling) {
                        QWidget *wid = sibling->item->widget();
                        if (wid)
                            spacing = qMax(spacing, sibling->item->geometry().top() - wid->geometry().top());
                    }
                }
#endif
            } else {
                controlTypes1 = controlTypes2;
                controlTypes2 = box->item->controlTypes();
                if (previousNonEmptyIndex >= 0) {
                    QSizePolicy::ControlTypes actual1 = controlTypes1;
                    QSizePolicy::ControlTypes actual2 = controlTypes2;
                    if (dir == QBoxLayout::RightToLeft || dir == QBoxLayout::BottomToTop)
                        qSwap(actual1, actual2);

                    if (style) {
                        spacing = style->combinedLayoutSpacing(actual1, actual2,
                                             horz(dir) ? Qt::Horizontal : Qt::Vertical,
                                             0, q->parentWidget());
                        if (spacing < 0)
                            spacing = 0;
                    }
                }
            }

            if (previousNonEmptyIndex >= 0)
                a[previousNonEmptyIndex].spacing = spacing;
            previousNonEmptyIndex = i;
        }

        bool ignore = empty && box->item->widget(); // ignore hidden widgets
        bool dummy = true;
        if (horz(dir)) {
            bool expand = (exp & Qt::Horizontal || box->stretch > 0);
            horexp = horexp || expand;
            maxw += spacing + max.width();
            minw += spacing + min.width();
            hintw += spacing + hint.width();
            if (!ignore)
                qMaxExpCalc(maxh, verexp, dummy,
                            max.height(), exp & Qt::Vertical, box->item->isEmpty());
            minh = qMax(minh, min.height());
            hinth = qMax(hinth, hint.height());

            a[i].sizeHint = hint.width();
            a[i].maximumSize = max.width();
            a[i].minimumSize = min.width();
            a[i].expansive = expand;
            a[i].stretch = box->stretch ? box->stretch : box->hStretch();
        } else {
            bool expand = (exp & Qt::Vertical || box->stretch > 0);
            verexp = verexp || expand;
            maxh += spacing + max.height();
            minh += spacing + min.height();
            hinth += spacing + hint.height();
            if (!ignore)
                qMaxExpCalc(maxw, horexp, dummy,
                            max.width(), exp & Qt::Horizontal, box->item->isEmpty());
            minw = qMax(minw, min.width());
            hintw = qMax(hintw, hint.width());

            a[i].sizeHint = hint.height();
            a[i].maximumSize = max.height();
            a[i].minimumSize = min.height();
            a[i].expansive = expand;
            a[i].stretch = box->stretch ? box->stretch : box->vStretch();
        }

        a[i].empty = empty;
        a[i].spacing = 0;   // might be initialized with a non-zero value in a later iteration
        hasHfw = hasHfw || box->item->hasHeightForWidth();
    }

    geomArray = a;

    expanding = (Qt::Orientations)
                       ((horexp ? Qt::Horizontal : 0)
                         | (verexp ? Qt::Vertical : 0));

    minSize = QSize(minw, minh);
    maxSize = QSize(maxw, maxh).expandedTo(minSize);
    sizeHint = QSize(hintw, hinth).expandedTo(minSize).boundedTo(maxSize);

    q->getContentsMargins(&leftMargin, &topMargin, &rightMargin, &bottomMargin);
    int left, top, right, bottom;
    effectiveMargins(&left, &top, &right, &bottom);
    QSize extra(left + right, top + bottom);

    minSize += extra;
    maxSize += extra;
    sizeHint += extra;

    dirty = false;
}
示例#20
0
void QLCDNumberPrivate::drawSegment(const QPoint &pos, char segmentNo, QPainter &p,
                                    int segLen, bool erase)
{
    Q_Q(QLCDNumber);
    QPoint ppt;
    QPoint pt = pos;
    int width = segLen/5;

    const QPalette &pal = q->palette();
    QColor lightColor,darkColor,fgColor;
    if (erase){
        lightColor = pal.color(q->backgroundRole());
        darkColor  = lightColor;
        fgColor    = lightColor;
    } else {
        lightColor = pal.light().color();
        darkColor  = pal.dark().color();
        fgColor    = pal.color(q->foregroundRole());
    }


#define LINETO(X,Y) addPoint(a, QPoint(pt.x() + (X),pt.y() + (Y)))
#define LIGHT
#define DARK

    if (fill) {
        QPolygon a(0);
        //The following is an exact copy of the switch below.
        //don't make any changes here
        switch (segmentNo) {
        case 0 :
            ppt = pt;
            LIGHT;
            LINETO(segLen - 1,0);
            DARK;
            LINETO(segLen - width - 1,width);
            LINETO(width,width);
            LINETO(0,0);
            break;
        case 1 :
            pt += QPoint(0 , 1);
            ppt = pt;
            LIGHT;
            LINETO(width,width);
            DARK;
            LINETO(width,segLen - width/2 - 2);
            LINETO(0,segLen - 2);
            LIGHT;
            LINETO(0,0);
            break;
        case 2 :
            pt += QPoint(segLen - 1 , 1);
            ppt = pt;
            DARK;
            LINETO(0,segLen - 2);
            LINETO(-width,segLen - width/2 - 2);
            LIGHT;
            LINETO(-width,width);
            LINETO(0,0);
            break;
        case 3 :
            pt += QPoint(0 , segLen);
            ppt = pt;
            LIGHT;
            LINETO(width,-width/2);
            LINETO(segLen - width - 1,-width/2);
            LINETO(segLen - 1,0);
            DARK;
            if (width & 1) {            // adjust for integer division error
                LINETO(segLen - width - 3,width/2 + 1);
                LINETO(width + 2,width/2 + 1);
            } else {
                LINETO(segLen - width - 1,width/2);
                LINETO(width,width/2);
            }
            LINETO(0,0);
            break;
        case 4 :
            pt += QPoint(0 , segLen + 1);
            ppt = pt;
            LIGHT;
            LINETO(width,width/2);
            DARK;
            LINETO(width,segLen - width - 2);
            LINETO(0,segLen - 2);
            LIGHT;
            LINETO(0,0);
            break;
        case 5 :
            pt += QPoint(segLen - 1 , segLen + 1);
            ppt = pt;
            DARK;
            LINETO(0,segLen - 2);
            LINETO(-width,segLen - width - 2);
            LIGHT;
            LINETO(-width,width/2);
            LINETO(0,0);
            break;
        case 6 :
            pt += QPoint(0 , segLen*2);
            ppt = pt;
            LIGHT;
            LINETO(width,-width);
            LINETO(segLen - width - 1,-width);
            LINETO(segLen - 1,0);
            DARK;
            LINETO(0,0);
            break;
        case 7 :
            if (smallPoint)   // if smallpoint place'.' between other digits
                pt += QPoint(segLen + width/2 , segLen*2);
            else
                pt += QPoint(segLen/2 , segLen*2);
            ppt = pt;
            DARK;
            LINETO(width,0);
            LINETO(width,-width);
            LIGHT;
            LINETO(0,-width);
            LINETO(0,0);
            break;
        case 8 :
            pt += QPoint(segLen/2 - width/2 + 1 , segLen/2 + width);
            ppt = pt;
            DARK;
            LINETO(width,0);
            LINETO(width,-width);
            LIGHT;
            LINETO(0,-width);
            LINETO(0,0);
            break;
        case 9 :
            pt += QPoint(segLen/2 - width/2 + 1 , 3*segLen/2 + width);
            ppt = pt;
            DARK;
            LINETO(width,0);
            LINETO(width,-width);
            LIGHT;
            LINETO(0,-width);
            LINETO(0,0);
            break;
        default :
            qWarning("QLCDNumber::drawSegment: (%s) Illegal segment id: %d\n",
                     q->objectName().toLocal8Bit().constData(), segmentNo);
        }
        // End exact copy
        p.setPen(Qt::NoPen);
        p.setBrush(fgColor);
        p.drawPolygon(a);
        p.setBrush(Qt::NoBrush);

        pt = pos;
    }
#undef LINETO
#undef LIGHT
#undef DARK

#define LINETO(X,Y) p.drawLine(ppt.x(), ppt.y(), pt.x()+(X), pt.y()+(Y)); \
                    ppt = QPoint(pt.x()+(X), pt.y()+(Y))
#define LIGHT p.setPen(lightColor)
#define DARK  p.setPen(darkColor)
    if (shadow)
        switch (segmentNo) {
        case 0 :
            ppt = pt;
            LIGHT;
            LINETO(segLen - 1,0);
            DARK;
            LINETO(segLen - width - 1,width);
            LINETO(width,width);
            LINETO(0,0);
            break;
        case 1 :
            pt += QPoint(0,1);
            ppt = pt;
            LIGHT;
            LINETO(width,width);
            DARK;
            LINETO(width,segLen - width/2 - 2);
            LINETO(0,segLen - 2);
            LIGHT;
            LINETO(0,0);
            break;
        case 2 :
            pt += QPoint(segLen - 1 , 1);
            ppt = pt;
            DARK;
            LINETO(0,segLen - 2);
            LINETO(-width,segLen - width/2 - 2);
            LIGHT;
            LINETO(-width,width);
            LINETO(0,0);
            break;
        case 3 :
            pt += QPoint(0 , segLen);
            ppt = pt;
            LIGHT;
            LINETO(width,-width/2);
            LINETO(segLen - width - 1,-width/2);
            LINETO(segLen - 1,0);
            DARK;
            if (width & 1) {            // adjust for integer division error
                LINETO(segLen - width - 3,width/2 + 1);
                LINETO(width + 2,width/2 + 1);
            } else {
                LINETO(segLen - width - 1,width/2);
                LINETO(width,width/2);
            }
            LINETO(0,0);
            break;
        case 4 :
            pt += QPoint(0 , segLen + 1);
            ppt = pt;
            LIGHT;
            LINETO(width,width/2);
            DARK;
            LINETO(width,segLen - width - 2);
            LINETO(0,segLen - 2);
            LIGHT;
            LINETO(0,0);
            break;
        case 5 :
            pt += QPoint(segLen - 1 , segLen + 1);
            ppt = pt;
            DARK;
            LINETO(0,segLen - 2);
            LINETO(-width,segLen - width - 2);
            LIGHT;
            LINETO(-width,width/2);
            LINETO(0,0);
            break;
        case 6 :
            pt += QPoint(0 , segLen*2);
            ppt = pt;
            LIGHT;
            LINETO(width,-width);
            LINETO(segLen - width - 1,-width);
            LINETO(segLen - 1,0);
            DARK;
            LINETO(0,0);
            break;
        case 7 :
            if (smallPoint)   // if smallpoint place'.' between other digits
                pt += QPoint(segLen + width/2 , segLen*2);
            else
                pt += QPoint(segLen/2 , segLen*2);
            ppt = pt;
            DARK;
            LINETO(width,0);
            LINETO(width,-width);
            LIGHT;
            LINETO(0,-width);
            LINETO(0,0);
            break;
        case 8 :
            pt += QPoint(segLen/2 - width/2 + 1 , segLen/2 + width);
            ppt = pt;
            DARK;
            LINETO(width,0);
            LINETO(width,-width);
            LIGHT;
            LINETO(0,-width);
            LINETO(0,0);
            break;
        case 9 :
            pt += QPoint(segLen/2 - width/2 + 1 , 3*segLen/2 + width);
            ppt = pt;
            DARK;
            LINETO(width,0);
            LINETO(width,-width);
            LIGHT;
            LINETO(0,-width);
            LINETO(0,0);
            break;
        default :
            qWarning("QLCDNumber::drawSegment: (%s) Illegal segment id: %d\n",
                     q->objectName().toLocal8Bit().constData(), segmentNo);
        }

#undef LINETO
#undef LIGHT
#undef DARK
}
示例#21
0
//------------------------------------------------------------------------------
void ctkDICOMDatabasePrivate::insert( const ctkDICOMDataset& ctkDataset, const QString& filePath, bool storeFile, bool generateThumbnail)
{
  Q_Q(ctkDICOMDatabase);

  // Check to see if the file has already been loaded
  // TODO:
  // It could make sense to actually remove the dataset and re-add it. This needs the remove
  // method we still have to write.
  //

  QString sopInstanceUID ( ctkDataset.GetElementAsString(DCM_SOPInstanceUID) );

  QSqlQuery fileExists ( Database );
  fileExists.prepare("SELECT InsertTimestamp,Filename FROM Images WHERE SOPInstanceUID == ?");
  fileExists.bindValue(0,sopInstanceUID);
  fileExists.exec();
  if ( fileExists.next() && QFileInfo(fileExists.value(1).toString()).lastModified() < QDateTime::fromString(fileExists.value(0).toString(),Qt::ISODate) )
  {
    logger.debug ( "File " + fileExists.value(1).toString() + " already added" );
    return;
  }

  //If the following fields can not be evaluated, cancel evaluation of the DICOM file
  QString patientsName(ctkDataset.GetElementAsString(DCM_PatientName) );
  QString studyInstanceUID(ctkDataset.GetElementAsString(DCM_StudyInstanceUID) );
  QString seriesInstanceUID(ctkDataset.GetElementAsString(DCM_SeriesInstanceUID) );
  QString patientID(ctkDataset.GetElementAsString(DCM_PatientID) );
  if ( patientsName.isEmpty() || studyInstanceUID.isEmpty() || patientID.isEmpty() )
  {
    logger.error("Dataset is missing necessary information!");
    return;
  } 

  QString patientsBirthDate(ctkDataset.GetElementAsString(DCM_PatientBirthDate) );
  QString patientsBirthTime(ctkDataset.GetElementAsString(DCM_PatientBirthTime) );
  QString patientsSex(ctkDataset.GetElementAsString(DCM_PatientSex) );
  QString patientsAge(ctkDataset.GetElementAsString(DCM_PatientAge) );
  QString patientComments(ctkDataset.GetElementAsString(DCM_PatientComments) );
  QString studyID(ctkDataset.GetElementAsString(DCM_StudyID) );
  QString studyDate(ctkDataset.GetElementAsString(DCM_StudyDate) );
  QString studyTime(ctkDataset.GetElementAsString(DCM_StudyTime) );
  QString accessionNumber(ctkDataset.GetElementAsString(DCM_AccessionNumber) );
  QString modalitiesInStudy(ctkDataset.GetElementAsString(DCM_ModalitiesInStudy) );
  QString institutionName(ctkDataset.GetElementAsString(DCM_InstitutionName) );
  QString performingPhysiciansName(ctkDataset.GetElementAsString(DCM_PerformingPhysicianName) );
  QString referringPhysician(ctkDataset.GetElementAsString(DCM_ReferringPhysicianName) );
  QString studyDescription(ctkDataset.GetElementAsString(DCM_StudyDescription) );

  QString seriesDate(ctkDataset.GetElementAsString(DCM_SeriesDate) );
  QString seriesTime(ctkDataset.GetElementAsString(DCM_SeriesTime) );
  QString seriesDescription(ctkDataset.GetElementAsString(DCM_SeriesDescription) );
  QString bodyPartExamined(ctkDataset.GetElementAsString(DCM_BodyPartExamined) );
  QString frameOfReferenceUID(ctkDataset.GetElementAsString(DCM_FrameOfReferenceUID) );
  QString contrastAgent(ctkDataset.GetElementAsString(DCM_ContrastBolusAgent) );
  QString scanningSequence(ctkDataset.GetElementAsString(DCM_ScanningSequence) );

  long seriesNumber(ctkDataset.GetElementAsInteger(DCM_SeriesNumber) );
  long acquisitionNumber(ctkDataset.GetElementAsInteger(DCM_AcquisitionNumber) );
  long echoNumber(ctkDataset.GetElementAsInteger(DCM_EchoNumbers) );
  long temporalPosition(ctkDataset.GetElementAsInteger(DCM_TemporalPositionIdentifier) );

  // store the file if the database is not in memomry
  // TODO: if we are called from insert(file) we
  // have to do something else
  // 
  QString filename = filePath;
  if ( storeFile && !q->isInMemory() && !seriesInstanceUID.isEmpty() )
  {
    // QString studySeriesDirectory = studyInstanceUID + "/" + seriesInstanceUID;
    QString destinationDirectoryName = q->databaseDirectory() + "/dicom/";
    QDir destinationDir(destinationDirectoryName);
    filename = destinationDirectoryName +
        studyInstanceUID + "/" +
        seriesInstanceUID + "/" +
        sopInstanceUID;

    destinationDir.mkpath(studyInstanceUID + "/" +
                          seriesInstanceUID);

    if(filePath.isEmpty())
    {
      logger.debug ( "Saving file: " + filename );

      if ( !ctkDataset.SaveToFile( filename) )
      {
        logger.error ( "Error saving file: " + filename );
        return;
      }
    }
    else
    {
      // we're inserting an existing file

      QFile currentFile( filePath );
      currentFile.copy(filename);
      logger.debug( "Copy file from: " + filePath );
      logger.debug( "Copy file to  : " + filename );
    }
  }

  QSqlQuery checkPatientExistsQuery(Database);
  //The dbPatientID  is a unique number within the database, 
  //generated by the sqlite autoincrement
  //The patientID  is the (non-unique) DICOM patient id
  int dbPatientID = -1;

  if ( patientID != "" && patientsName != "" )
    {
    //Speed up: Check if patient is the same as in last file; 
    // very probable, as all images belonging to a study have the same patient
    if ( lastPatientID != patientID 
          || lastPatientsBirthDate != patientsBirthDate 
          || lastPatientsName != patientsName )
      {
      // Ok, something is different from last insert, let's insert him if he's not
      // already in the db.
      //

      // Check if patient is already present in the db
      // TODO: maybe add birthdate check for extra safety
      checkPatientExistsQuery.prepare ( "SELECT * FROM Patients WHERE PatientID = ? AND PatientsName = ?" );
      checkPatientExistsQuery.bindValue ( 0, patientID );
      checkPatientExistsQuery.bindValue ( 1, patientsName );
      loggedExec(checkPatientExistsQuery);

      if (checkPatientExistsQuery.next())
      {
        // we found him
        dbPatientID = checkPatientExistsQuery.value(checkPatientExistsQuery.record().indexOf("UID")).toInt();
      }
      else
        {
        // Insert it
        QSqlQuery insertPatientStatement ( Database );
        insertPatientStatement.prepare ( "INSERT INTO Patients ('UID', 'PatientsName', 'PatientID', 'PatientsBirthDate', 'PatientsBirthTime', 'PatientsSex', 'PatientsAge', 'PatientsComments' ) values ( NULL, ?, ?, ?, ?, ?, ?, ? )" );
        insertPatientStatement.bindValue ( 0, patientsName );
        insertPatientStatement.bindValue ( 1, patientID );
        insertPatientStatement.bindValue ( 2, patientsBirthDate );
        insertPatientStatement.bindValue ( 3, patientsBirthTime );
        insertPatientStatement.bindValue ( 4, patientsSex );
        // TODO: shift patient's age to study, 
        // since this is not a patient level attribute in images
        // insertPatientStatement.bindValue ( 5, patientsAge );
        insertPatientStatement.bindValue ( 6, patientComments );
        loggedExec(insertPatientStatement);
        dbPatientID = insertPatientStatement.lastInsertId().toInt();
        logger.debug ( "New patient inserted: " + QString().setNum ( dbPatientID ) );
        }
      /// keep this for the next image
      lastPatientUID = dbPatientID;
      lastPatientID = patientID;
      lastPatientsBirthDate = patientsBirthDate;
      lastPatientsName = patientsName;
      }

    // Patient is in now. Let's continue with the study

    if ( studyInstanceUID != "" && lastStudyInstanceUID != studyInstanceUID )
    {
      QSqlQuery checkStudyExistsQuery (Database);
      checkStudyExistsQuery.prepare ( "SELECT * FROM Studies WHERE StudyInstanceUID = ?" );
      checkStudyExistsQuery.bindValue ( 0, studyInstanceUID );
      checkStudyExistsQuery.exec();
      if(!checkStudyExistsQuery.next())
      {
        QSqlQuery insertStudyStatement ( Database );
        insertStudyStatement.prepare ( "INSERT INTO Studies ( 'StudyInstanceUID', 'PatientsUID', 'StudyID', 'StudyDate', 'StudyTime', 'AccessionNumber', 'ModalitiesInStudy', 'InstitutionName', 'ReferringPhysician', 'PerformingPhysiciansName', 'StudyDescription' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" );
        insertStudyStatement.bindValue ( 0, studyInstanceUID );
        insertStudyStatement.bindValue ( 1, dbPatientID );
        insertStudyStatement.bindValue ( 2, studyID );
        insertStudyStatement.bindValue ( 3, QDate::fromString ( studyDate, "yyyyMMdd" ) );
        insertStudyStatement.bindValue ( 4, studyTime );
        insertStudyStatement.bindValue ( 5, accessionNumber );
        insertStudyStatement.bindValue ( 6, modalitiesInStudy );
        insertStudyStatement.bindValue ( 7, institutionName );
        insertStudyStatement.bindValue ( 8, referringPhysician );
        insertStudyStatement.bindValue ( 9, performingPhysiciansName );
        insertStudyStatement.bindValue ( 10, studyDescription );
        if ( !insertStudyStatement.exec() )
        {
          logger.error ( "Error executing statament: " + insertStudyStatement.lastQuery() + " Error: " + insertStudyStatement.lastError().text() );
        }
        else
        {
          lastStudyInstanceUID = studyInstanceUID;
        }

      }
    }

    if ( seriesInstanceUID != "" && seriesInstanceUID != lastSeriesInstanceUID )
    {
      QSqlQuery checkSeriesExistsQuery (Database);
      checkSeriesExistsQuery.prepare ( "SELECT * FROM Series WHERE SeriesInstanceUID = ?" );
      checkSeriesExistsQuery.bindValue ( 0, seriesInstanceUID );
      logger.warn ( "Statement: " + checkSeriesExistsQuery.lastQuery() );
      loggedExec(checkSeriesExistsQuery);
      if(!checkSeriesExistsQuery.next())
      {
        QSqlQuery insertSeriesStatement ( Database );
        insertSeriesStatement.prepare ( "INSERT INTO Series ( 'SeriesInstanceUID', 'StudyInstanceUID', 'SeriesNumber', 'SeriesDate', 'SeriesTime', 'SeriesDescription', 'BodyPartExamined', 'FrameOfReferenceUID', 'AcquisitionNumber', 'ContrastAgent', 'ScanningSequence', 'EchoNumber', 'TemporalPosition' ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" );
        insertSeriesStatement.bindValue ( 0, seriesInstanceUID );
        insertSeriesStatement.bindValue ( 1, studyInstanceUID );
        insertSeriesStatement.bindValue ( 2, static_cast<int>(seriesNumber) );
        insertSeriesStatement.bindValue ( 3, seriesDate );
        insertSeriesStatement.bindValue ( 4, QDate::fromString ( seriesTime, "yyyyMMdd" ) );
        insertSeriesStatement.bindValue ( 5, seriesDescription );
        insertSeriesStatement.bindValue ( 6, bodyPartExamined );
        insertSeriesStatement.bindValue ( 7, frameOfReferenceUID );
        insertSeriesStatement.bindValue ( 8, static_cast<int>(acquisitionNumber) );
        insertSeriesStatement.bindValue ( 9, contrastAgent );
        insertSeriesStatement.bindValue ( 10, scanningSequence );
        insertSeriesStatement.bindValue ( 11, static_cast<int>(echoNumber) );
        insertSeriesStatement.bindValue ( 12, static_cast<int>(temporalPosition) );
        if ( !insertSeriesStatement.exec() )
        {
          logger.error ( "Error executing statament: " 
            + insertSeriesStatement.lastQuery() 
            + " Error: " + insertSeriesStatement.lastError().text() );
          lastSeriesInstanceUID = "";
        }
        else
        {
          lastSeriesInstanceUID = seriesInstanceUID;
        }

      }
    }
    // TODO: what to do with imported files
    //
   if ( !filename.isEmpty() && !seriesInstanceUID.isEmpty() )
   {
     QSqlQuery checkImageExistsQuery (Database);
     checkImageExistsQuery.prepare ( "SELECT * FROM Images WHERE Filename = ?" );
     checkImageExistsQuery.bindValue ( 0, filename );
     checkImageExistsQuery.exec();
     if(!checkImageExistsQuery.next())
      {
        QSqlQuery insertImageStatement ( Database );
        insertImageStatement.prepare ( "INSERT INTO Images ( 'SOPInstanceUID', 'Filename', 'SeriesInstanceUID', 'InsertTimestamp' ) VALUES ( ?, ?, ?, ? )" );
        insertImageStatement.bindValue ( 0, sopInstanceUID );
        insertImageStatement.bindValue ( 1, filename );
        insertImageStatement.bindValue ( 2, seriesInstanceUID );
        insertImageStatement.bindValue ( 3, QDateTime::currentDateTime() );
        insertImageStatement.exec();
      }
    }

    if( generateThumbnail && thumbnailGenerator && !seriesInstanceUID.isEmpty() )
      {
      QString studySeriesDirectory = studyInstanceUID + "/" + seriesInstanceUID;
      //Create thumbnail here
      QString thumbnailPath = q->databaseDirectory() +
        "/thumbs/" + studyInstanceUID + "/" + seriesInstanceUID 
        + "/" + sopInstanceUID + ".png";
      QFileInfo thumbnailInfo(thumbnailPath);
      if( !(thumbnailInfo.exists() 
            && (thumbnailInfo.lastModified() > QFileInfo(filename).lastModified())))
        {
        QDir(q->databaseDirectory() + "/thumbs/").mkpath(studySeriesDirectory);
        DicomImage dcmImage(QDir::toNativeSeparators(filename).toAscii());
        thumbnailGenerator->generateThumbnail(&dcmImage, thumbnailPath);
        }
      }

    if (q->isInMemory())
      {
      emit q->databaseChanged();
      }
    }
}
示例#22
0
void QGraphicsWidgetPrivate::windowFrameMouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    Q_Q(QGraphicsWidget);
    ensureWindowData();
    if (!(event->buttons() & Qt::LeftButton) || windowData->hoveredSubControl != QStyle::SC_TitleBarLabel)
        return;

    QLineF delta(q->mapFromScene(event->buttonDownScenePos(Qt::LeftButton)), event->pos());
    QLineF parentDelta(q->mapToParent(delta.p1()), q->mapToParent(delta.p2()));
    QLineF parentXDelta(q->mapToParent(QPointF(delta.p1().x(), 0)), q->mapToParent(QPointF(delta.p2().x(), 0)));
    QLineF parentYDelta(q->mapToParent(QPointF(0, delta.p1().y())), q->mapToParent(QPointF(0, delta.p2().y())));

    QRectF newGeometry;
    switch (windowData->grabbedSection) {
    case Qt::LeftSection:
        newGeometry = QRectF(windowData->startGeometry.topLeft()
                             + QPointF(parentXDelta.dx(), parentXDelta.dy()),
                             windowData->startGeometry.size() - QSizeF(delta.dx(), delta.dy()));
        break;
    case Qt::TopLeftSection:
        newGeometry = QRectF(windowData->startGeometry.topLeft()
                             + QPointF(parentDelta.dx(), parentDelta.dy()),
                             windowData->startGeometry.size() - QSizeF(delta.dx(), delta.dy()));
        break;
    case Qt::TopSection:
        newGeometry = QRectF(windowData->startGeometry.topLeft()
                             + QPointF(parentYDelta.dx(), parentYDelta.dy()),
                             windowData->startGeometry.size() - QSizeF(0, delta.dy()));
        break;
    case Qt::TopRightSection:
        newGeometry = QRectF(windowData->startGeometry.topLeft()
                             + QPointF(parentYDelta.dx(), parentYDelta.dy()),
                             windowData->startGeometry.size() - QSizeF(-delta.dx(), delta.dy()));
        break;
    case Qt::RightSection:
        newGeometry = QRectF(windowData->startGeometry.topLeft(),
                             windowData->startGeometry.size() + QSizeF(delta.dx(), 0));
        break;
    case Qt::BottomRightSection:
        newGeometry = QRectF(windowData->startGeometry.topLeft(),
                             windowData->startGeometry.size() + QSizeF(delta.dx(), delta.dy()));
        break;
    case Qt::BottomSection:
        newGeometry = QRectF(windowData->startGeometry.topLeft(),
                             windowData->startGeometry.size() + QSizeF(0, delta.dy()));
        break;
    case Qt::BottomLeftSection:
        newGeometry = QRectF(windowData->startGeometry.topLeft()
                             + QPointF(parentXDelta.dx(), parentXDelta.dy()),
                             windowData->startGeometry.size() - QSizeF(delta.dx(), -delta.dy()));
        break;
    case Qt::TitleBarArea:
        newGeometry = QRectF(windowData->startGeometry.topLeft()
                             + QPointF(parentDelta.dx(), parentDelta.dy()),
                             windowData->startGeometry.size());
        break;
    case Qt::NoSection:
        break;
    }

    if (windowData->grabbedSection != Qt::NoSection) {
        _q_boundGeometryToSizeConstraints(windowData->startGeometry, &newGeometry,
                                          windowData->grabbedSection,
                                          q->effectiveSizeHint(Qt::MinimumSize),
                                          q->effectiveSizeHint(Qt::MaximumSize),
                                          q);
        q->setGeometry(newGeometry);
    }
}
示例#23
0
void QLocalSocketPrivate::_q_pipeClosed()
{
    Q_Q(QLocalSocket);
    q->close();
}
示例#24
0
void QGraphicsWidgetPrivate::windowFrameHoverMoveEvent(QGraphicsSceneHoverEvent *event)
{
    Q_Q(QGraphicsWidget);
    if (!hasDecoration())
        return;

    ensureWindowData();

    if (q->rect().contains(event->pos())) {
        if (windowData->buttonMouseOver || windowData->hoveredSubControl != QStyle::SC_None)
            windowFrameHoverLeaveEvent(event);
        return;
    }

    bool wasMouseOver = windowData->buttonMouseOver;
    QRect oldButtonRect = windowData->buttonRect;
    windowData->buttonRect = QRect();
    windowData->buttonMouseOver = false;
    QPointF pos = event->pos();
    QStyleOptionTitleBar bar;
    // make sure that the coordinates (rect and pos) we send to the style are positive.
    if (windowFrameMargins) {
        pos.rx() += windowFrameMargins[Left];
        pos.ry() += windowFrameMargins[Top];
    }
    initStyleOptionTitleBar(&bar);
    bar.rect = q->windowFrameRect().toRect();
    bar.rect.moveTo(0,0);
    bar.rect.setHeight(int(titleBarHeight(bar)));

    Qt::CursorShape cursorShape = Qt::ArrowCursor;
    bool needsSetCursorCall = true;
    switch (q->windowFrameSectionAt(event->pos())) {
    case Qt::TopLeftSection:
    case Qt::BottomRightSection:
        cursorShape = Qt::SizeFDiagCursor;
        break;
    case Qt::TopRightSection:
    case Qt::BottomLeftSection:
        cursorShape = Qt::SizeBDiagCursor;
        break;
    case Qt::LeftSection:
    case Qt::RightSection:
        cursorShape = Qt::SizeHorCursor;
        break;
    case Qt::TopSection:
    case Qt::BottomSection:
        cursorShape = Qt::SizeVerCursor;
        break;
    case Qt::TitleBarArea:
        windowData->buttonRect = q->style()->subControlRect(
                                     QStyle::CC_TitleBar, &bar, QStyle::SC_TitleBarCloseButton, 0);
#ifdef Q_WS_MAC
        // On mac we should hover if we are in the 'area' of the buttons
        windowData->buttonRect |= q->style()->subControlRect(
                                      QStyle::CC_TitleBar, &bar, QStyle::SC_TitleBarMinButton, 0);
        windowData->buttonRect |= q->style()->subControlRect(
                                      QStyle::CC_TitleBar, &bar, QStyle::SC_TitleBarMaxButton, 0);
#endif
        if (windowData->buttonRect.contains(pos.toPoint()))
            windowData->buttonMouseOver = true;
        event->ignore();
        break;
    default:
        needsSetCursorCall = false;
        event->ignore();
    }
#ifndef QT_NO_CURSOR
    if (needsSetCursorCall)
        q->setCursor(cursorShape);
#endif
    // update buttons if we hover over them
    windowData->hoveredSubControl = q->style()->hitTestComplexControl(QStyle::CC_TitleBar, &bar, pos.toPoint(), 0);
    if (windowData->hoveredSubControl != QStyle::SC_TitleBarCloseButton)
        windowData->hoveredSubControl = QStyle::SC_TitleBarLabel;

    if (windowData->buttonMouseOver != wasMouseOver) {
        if (!oldButtonRect.isNull())
            q->update(QRectF(oldButtonRect).translated(q->windowFrameRect().topLeft()));
        if (!windowData->buttonRect.isNull())
            q->update(QRectF(windowData->buttonRect).translated(q->windowFrameRect().topLeft()));
    }
}
示例#25
0
/*
    Create the pipes to a QProcessPrivate::Channel.

    This function must be called in order: stdin, stdout, stderr
*/
bool QProcessPrivate::createChannel(Channel &channel)
{
    Q_Q(QProcess);

    if (&channel == &stderrChannel && processChannelMode == QProcess::MergedChannels) {
        return DuplicateHandle(GetCurrentProcess(), stdoutChannel.pipe[1], GetCurrentProcess(),
                               &stderrChannel.pipe[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
    }

    if (channel.type == Channel::Normal) {
        // we're piping this channel to our own process
        const bool isStdInChannel = (&channel == &stdinChannel);
        if (isStdInChannel || processChannelMode != QProcess::ForwardedChannels)
            qt_create_pipe(channel.pipe, isStdInChannel);
        else
            duplicateStdWriteChannel(channel.pipe, (&channel == &stdoutChannel) ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE);

        if (processChannelMode != QProcess::ForwardedChannels) {
            QWindowsPipeReader *pipeReader = 0;
            if (&channel == &stdoutChannel) {
                if (!stdoutReader) {
                    stdoutReader = new QWindowsPipeReader(q);
                    q->connect(stdoutReader, SIGNAL(readyRead()), SLOT(_q_canReadStandardOutput()));
                }
                pipeReader = stdoutReader;
            } else if (&channel == &stderrChannel) {
                if (!stderrReader) {
                    stderrReader = new QWindowsPipeReader(q);
                    q->connect(stderrReader, SIGNAL(readyRead()), SLOT(_q_canReadStandardError()));
                }
                pipeReader = stderrReader;
            }
            if (pipeReader) {
                pipeReader->setHandle(channel.pipe[0]);
                pipeReader->startAsyncRead();
            }
        }

        return true;
    } else if (channel.type == Channel::Redirect) {
        // we're redirecting the channel to/from a file
        SECURITY_ATTRIBUTES secAtt = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };

        if (&channel == &stdinChannel) {
            // try to open in read-only mode
            channel.pipe[1] = INVALID_Q_PIPE;
            channel.pipe[0] =
                CreateFile((const wchar_t*)QFSFileEnginePrivate::longFileName(channel.file).utf16(),
                           GENERIC_READ,
                           FILE_SHARE_READ | FILE_SHARE_WRITE,
                           &secAtt,
                           OPEN_EXISTING,
                           FILE_ATTRIBUTE_NORMAL,
                           NULL);

            if (channel.pipe[0] != INVALID_Q_PIPE)
                return true;

            q->setErrorString(QProcess::tr("Could not open input redirection for reading"));
        } else {
            // open in write mode
            channel.pipe[0] = INVALID_Q_PIPE;
            channel.pipe[1] =
                CreateFile((const wchar_t *)QFSFileEnginePrivate::longFileName(channel.file).utf16(),
                           GENERIC_WRITE,
                           FILE_SHARE_READ | FILE_SHARE_WRITE,
                           &secAtt,
                           channel.append ? OPEN_ALWAYS : CREATE_ALWAYS,
                           FILE_ATTRIBUTE_NORMAL,
                           NULL);

            if (channel.pipe[1] != INVALID_Q_PIPE) {
                if (channel.append) {
                    SetFilePointer(channel.pipe[1], 0, NULL, FILE_END);
                }
                return true;
            }

            q->setErrorString(QProcess::tr("Could not open output redirection for writing"));
        }

        // could not open file
        processError = QProcess::FailedToStart;
        emit q->error(processError);
        cleanup();
        return false;
    } else {
        Q_ASSERT_X(channel.process, "QProcess::start", "Internal error");

        Channel *source;
        Channel *sink;

        if (channel.type == Channel::PipeSource) {
            // we are the source
            source = &channel;
            sink = &channel.process->stdinChannel;

            if (source->pipe[1] != INVALID_Q_PIPE) {
                // already constructed by the sink
                // make it inheritable
                HANDLE tmpHandle = source->pipe[1];
                if (!DuplicateHandle(GetCurrentProcess(), tmpHandle,
                                     GetCurrentProcess(), &source->pipe[1],
                                     0, TRUE, DUPLICATE_SAME_ACCESS))
                    return false;

                CloseHandle(tmpHandle);
                return true;
            }

            Q_ASSERT(source == &stdoutChannel);
            Q_ASSERT(sink->process == this && sink->type == Channel::PipeSink);

            qt_create_pipe(source->pipe, /* in = */ false); // source is stdout
            sink->pipe[0] = source->pipe[0];
            source->pipe[0] = INVALID_Q_PIPE;

            return true;
        } else {
            // we are the sink;
            source = &channel.process->stdoutChannel;
            sink = &channel;

            if (sink->pipe[0] != INVALID_Q_PIPE) {
                // already constructed by the source
                // make it inheritable
                HANDLE tmpHandle = sink->pipe[0];
                if (!DuplicateHandle(GetCurrentProcess(), tmpHandle,
                                     GetCurrentProcess(), &sink->pipe[0],
                                     0, TRUE, DUPLICATE_SAME_ACCESS))
                    return false;

                CloseHandle(tmpHandle);
                return true;
            }
            Q_ASSERT(sink == &stdinChannel);
            Q_ASSERT(source->process == this && source->type == Channel::PipeSource);

            qt_create_pipe(sink->pipe, /* in = */ true); // sink is stdin
            source->pipe[1] = sink->pipe[1];
            sink->pipe[1] = INVALID_Q_PIPE;

            return true;
        }
    }
}
示例#26
0
void QGraphicsWidgetPrivate::resetHeight()
{
    Q_Q(QGraphicsWidget);
    q->setGeometry(QRectF(q->x(), q->y(), width(), 0));
}
示例#27
0
bool QProcessPrivate::waitForBytesWritten(int msecs)
{
    Q_Q(QProcess);

    QIncrementalSleepTimer timer(msecs);

    forever {
        // Check if we have any data pending: the pipe writer has
        // bytes waiting to written, or it has written data since the
        // last time we called pipeWriter->waitForWrite().
        bool pendingDataInPipe = pipeWriter && (pipeWriter->bytesToWrite() || pipeWriter->hadWritten());

        // If we don't have pending data, and our write buffer is
        // empty, we fail.
        if (!pendingDataInPipe && writeBuffer.isEmpty())
            return false;

        // If we don't have pending data and we do have data in our
        // write buffer, try to flush that data over to the pipe
        // writer.  Fail on error.
        if (!pendingDataInPipe) {
            if (!_q_canWrite())
                return false;
        }

        // Wait for the pipe writer to acknowledge that it has
        // written. This will succeed if either the pipe writer has
        // already written the data, or if it manages to write data
        // within the given timeout. If the write buffer was non-empty
        // and the pipeWriter is now dead, that means _q_canWrite()
        // destroyed the writer after it successfully wrote the last
        // batch.
        if (!pipeWriter || pipeWriter->waitForWrite(0))
            return true;

        // If we wouldn't write anything, check if we can read stdout.
        if (bytesAvailableFromStdout() != 0) {
            _q_canReadStandardOutput();
            timer.resetIncrements();
        }

        // Check if we can read stderr.
        if (bytesAvailableFromStderr() != 0) {
            _q_canReadStandardError();
            timer.resetIncrements();
        }

        // Check if the process died while reading.
        if (!pid)
            return false;

        // Wait for the process to signal any change in its state,
        // such as incoming data, or if the process died.
        if (WaitForSingleObject(pid->hProcess, 0) == WAIT_OBJECT_0) {
            _q_processDied();
            return false;
        }

        // Only wait for as long as we've been asked.
        if (timer.hasTimedOut())
            break;
    }

    processError = QProcess::Timedout;
    q->setErrorString(QProcess::tr("Process operation timed out"));
    return false;
}
示例#28
0
void EffectWidgetPrivate::autogenerateUi()
{
    Q_Q(EffectWidget);
    QVBoxLayout *mainLayout = new QVBoxLayout(q);
    mainLayout->setMargin(0);
    foreach (const EffectParameter &para, effect->parameters()) {
        QVariant value = effect->parameterValue(para);
        QHBoxLayout *pLayout = new QHBoxLayout;
        mainLayout->addLayout(pLayout);

        QLabel *label = new QLabel(q);
        pLayout->addWidget(label);
        label->setText(para.name());
#ifndef QT_NO_TOOLTIP
        label->setToolTip(para.description());
#endif

        QWidget *control = 0;
        switch (para.type()) {
        case QVariant::String:
            {
                QComboBox *cb = new QComboBox(q);
                control = cb;
                if (value.type() == QVariant::Int) {
                    //value just defines the item index
                    foreach (const QVariant &item, para.possibleValues()) {
                        cb->addItem(item.toString());
                    }
                    cb->setCurrentIndex(value.toInt());
                    QObject::connect(cb, SIGNAL(currentIndexChanged(int)), q, SLOT(_k_setIntParameter(int)));
                } else {
                    foreach (const QVariant &item, para.possibleValues()) {
                        cb->addItem(item.toString());
                        if (item == value) {
                            cb->setCurrentIndex(cb->count() - 1);
                        }
                    }
                    QObject::connect(cb, SIGNAL(currentIndexChanged(QString)), q, SLOT(_k_setStringParameter(QString)));
                }
            }
            break;
        case QVariant::Bool:
            {
                QCheckBox *cb = new QCheckBox(q);
                control = cb;
                cb->setChecked(value.toBool());
                QObject::connect(cb, SIGNAL(toggled(bool)), q, SLOT(_k_setToggleParameter(bool)));
            }
            break;
        case QVariant::Int:
            {
                QSpinBox *sb = new QSpinBox(q);
                control = sb;
                bool minValueOk = false;
                bool maxValueOk = false;
                const int minValue = para.minimumValue().toInt(&minValueOk);
                const int maxValue = para.minimumValue().toInt(&maxValueOk);

                sb->setRange(minValueOk ? minValue : DEFAULT_MIN_INT, maxValueOk ? maxValue : DEFAULT_MAX_INT);
                sb->setValue(value.toInt());
                QObject::connect(sb, SIGNAL(valueChanged(int)), q, SLOT(_k_setIntParameter(int)));
            }
            break;
        case QVariant::Double:
            {
                const double minValue = (para.minimumValue().type() == QVariant::Double ?
                    para.minimumValue().toDouble() : DEFAULT_MIN);
                const double maxValue = (para.maximumValue().type() == QVariant::Double ?
                    para.maximumValue().toDouble() : DEFAULT_MAX);

                if (minValue == -1. && maxValue == 1.) {
                    //Special case values between -1 and 1.0 to use a slider for improved usability
                    QSlider *slider = new QSlider(Qt::Horizontal, q);
                    slider->setRange(-SLIDER_RANGE, +SLIDER_RANGE);
                    slider->setValue(int(SLIDER_RANGE * value.toDouble()));
                    slider->setTickPosition(QSlider::TicksBelow);
                    slider->setTickInterval(TICKINTERVAL);
                    QObject::connect(slider, SIGNAL(valueChanged(int)), q, SLOT(_k_setSliderParameter(int)));
                } else {
                    double step = 0.1;
                    if (qAbs(maxValue - minValue) > 50)
                        step = 1.0;
                    QDoubleSpinBox *sb = new QDoubleSpinBox(q);
                    control = sb;
                    sb->setRange(minValue, maxValue);
                    sb->setValue(value.toDouble());
                    sb->setSingleStep(step);
                    QObject::connect(sb, SIGNAL(valueChanged(double)), q,
                        SLOT(_k_setDoubleParameter(double)));
                }
            }
            break;
        default:
            break;
        }
void QDeclarativeImplicitSizeItemPrivate::implicitHeightChanged()
{
    Q_Q(QDeclarativeImplicitSizeItem);
    emit q->implicitHeightChanged();
}
示例#30
0
void QAbstractKineticScrollerPrivate::handleMove(QMouseEvent *me, QPoint &delta)
{
    Q_Q(QAbstractKineticScroller);

    if (mode == QAbstractKineticScroller::AccelerationMode) {
        // we need delta to be the delta to ipos, not pos in this case
        delta = me->globalPos() - ipos;
    }

    if (axisLockThreshold) {
        int dx = qAbs(delta.x());
        int dy = qAbs(delta.y());
        if (dx || dy) {
            bool vertical = (dy > dx);
            qreal alpha = qreal(vertical ? dx : dy) / qreal(vertical ? dy : dx);
            qKSDebug() << "axis lock: " << alpha << " / " << axisLockThreshold << " - isvertical: " << vertical << " - dx: " << dx << " - dy: " << dy;
            if (alpha <= axisLockThreshold) {
                if (vertical)
                    delta.setX(0);
                else
                    delta.setY(0);
            }
        }
    }

    switch (mode) {
    case QAbstractKineticScroller::PushMode:
        // Scroll by the amount of pixels the cursor has moved
        // since the last motion event.
        scrollUpdate(delta);
        pos = me->globalPos();
        break;

    case QAbstractKineticScroller::AccelerationMode: {
        // Set acceleration relative to the initial click
        QSize size = q->viewportSize();
        qreal signX = 0, signY = 0;
        if (delta.x() < 0)
            signX = -1;
        else if (delta.x() > 0)
            signX = 1;
        if (delta.y() < 0)
            signY = -1;
        else if (delta.y() > 0)
            signY = 1;

        velocity.setX(signX * ((qreal(qAbs(delta.x())) / qreal(size.width()) * (maxVelocity - minVelocity)) + minVelocity));
        velocity.setY(signY * ((qreal(qAbs(delta.y())) / qreal(size.height()) * (maxVelocity - minVelocity)) + minVelocity));
        break;
    }
    case QAbstractKineticScroller::AutoMode:
        QPointF newVelocity = calculateVelocity(delta, lastTime.elapsed());
        QPoint maxPos = q->maximumScrollPosition();

        bool alwaysOvershoot = (overshootPolicy == QAbstractKineticScroller::OvershootAlwaysOn);

        if (!maxPos.x() && !alwaysOvershoot) {
            delta.setX(0);
            newVelocity.setX(0);
        }
        if (!maxPos.y() && !alwaysOvershoot) {
            delta.setY(0);
            newVelocity.setY(0);
        }
        velocity = newVelocity;

        scrollUpdate(delta);

        if (maxPos.x() || alwaysOvershoot)
            pos.setX(me->globalPos().x());
        if (maxPos.y() || alwaysOvershoot)
            pos.setY(me->globalPos().y());
        break;
    }
}