Example #1
0
static QCFType<CFPropertyListRef> macValue(const QVariant &value)
{
    CFPropertyListRef result = 0;

    switch (value.type()) {
    case QVariant::ByteArray:
        {
            QByteArray ba = value.toByteArray();
            result = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(ba.data()),
                                  CFIndex(ba.size()));
        }
        break;
    // should be same as below (look for LIST)
    case QVariant::List:
    case QVariant::StringList:
    case QVariant::Polygon:
        result = macList(value.toList());
        break;
    case QVariant::Map:
        {
            /*
                QMap<QString, QVariant> is potentially a multimap,
                whereas CFDictionary is a single-valued map. To allow
                for multiple values with the same key, we store
                multiple values in a CFArray. To avoid ambiguities,
                we also wrap lists in a CFArray singleton.
            */
            QMap<QString, QVariant> map = value.toMap();
            QMap<QString, QVariant>::const_iterator i = map.constBegin();

            int maxUniqueKeys = map.size();
            int numUniqueKeys = 0;
            QVarLengthArray<QCFType<CFPropertyListRef> > cfkeys(maxUniqueKeys);
            QVarLengthArray<QCFType<CFPropertyListRef> > cfvalues(maxUniqueKeys);

            while (i != map.constEnd()) {
                const QString &key = i.key();
                QList<QVariant> values;

                do {
                    values << i.value();
                    ++i;
                } while (i != map.constEnd() && i.key() == key);

                bool singleton = (values.count() == 1);
                if (singleton) {
                    switch (values.first().type()) {
                    // should be same as above (look for LIST)
                    case QVariant::List:
                    case QVariant::StringList:
                    case QVariant::Polygon:
                        singleton = false;
                    default:
                        ;
                    }
                }

                cfkeys[numUniqueKeys] = QCFString::toCFStringRef(key);
                cfvalues[numUniqueKeys] = singleton ? macValue(values.first()) : macList(values);
                ++numUniqueKeys;
            }

            result = CFDictionaryCreate(kCFAllocatorDefault,
                                        reinterpret_cast<const void **>(cfkeys.data()),
                                        reinterpret_cast<const void **>(cfvalues.data()),
                                        CFIndex(numUniqueKeys),
                                        &kCFTypeDictionaryKeyCallBacks,
                                        &kCFTypeDictionaryValueCallBacks);
        }
        break;
    case QVariant::DateTime:
        {
            /*
                CFDate, unlike QDateTime, doesn't store timezone information.
            */
            QDateTime dt = value.toDateTime();
            if (dt.timeSpec() == Qt::LocalTime) {
                QDateTime reference;
                reference.setTime_t((uint)kCFAbsoluteTimeIntervalSince1970);
                result = CFDateCreate(kCFAllocatorDefault, CFAbsoluteTime(reference.secsTo(dt)));
            } else {
                goto string_case;
            }
        }
        break;
    case QVariant::Bool:
        result = value.toBool() ? kCFBooleanTrue : kCFBooleanFalse;
        break;
    case QVariant::Int:
    case QVariant::UInt:
        {
            int n = value.toInt();
            result = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &n);
        }
        break;
    case QVariant::Double:
        {
            double n = value.toDouble();
            result = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &n);
        }
        break;
    case QVariant::LongLong:
    case QVariant::ULongLong:
        {
            qint64 n = value.toLongLong();
            result = CFNumberCreate(0, kCFNumberLongLongType, &n);
        }
        break;
    case QVariant::String:
    string_case:
    default:
        result = QCFString::toCFStringRef(QSettingsPrivate::variantToString(value));
    }
    return result;
}
Example #2
0
/*!
    Sets the \a newValue for \a option and returns \c true on success; \c false
    otherwise.

    \note If the option's associated type is \c quint8 or \c quint16 and the
    type of \a newValue is larger, the data will be truncated or conversation
    will fail.

    \table
        \header
            \li Key
            \li Description
        \row
            \li \l QModbusServer::DiagnosticRegister
            \li Sets the diagnostic register of the server in a device specific
                encoding to \a newValue. The default value preset is \c 0x0000.
                The bit values of the register need device specific documentation.
        \row
            \li \l QModbusServer::ExceptionStatusOffset
            \li Sets the exception status byte offset of the server to
                \a newValue which is the absolute offset address in the coils
                (0x register). Modbus register table starting with \c 0x0000h.
                The default value preset is \c 0x0000, using the exception
                status coils similar to Modicon 984 CPUs (coils 1-8).

                The function returns \c true if the coils register contains the
                8 bits required for storing and retrieving the status coils,
                otherwise \c false.
        \row
            \li \l QModbusServer::DeviceBusy
            \li Sets a flag that signals that the server is engaged in
                processing a long-duration program command. Valid values are
                \c 0x0000 (not busy) and \c 0xffff (busy).
                The default value preset is \c 0x0000.
        \row
            \li \l QModbusServer::AsciiInputDelimiter
            \li The \a newValue becomes the end of message delimiter for future
                Modbus ASCII messages. The default value preset is \c {\n}.
        \row
            \li \l QModbusServer::ListenOnlyMode
            \li Ss the server's listen only state to \a newValue. If listen only
                mode is set to \c true, messages are monitored but no response
                will be sent. The default value preset is \c false.
        \row
            \li \l QModbusServer::ServerIdentifier
            \li Sets the server's manufacturer identifier to \a newValue.
                Possible values are in the range of \c 0x00 to 0xff.
                The default value preset is \c 0x0a.
        \row
            \li \l QModbusServer::RunIndicatorStatus
            \li Sets the servers' run indicator status to \a newValue. This
                data is used as addendum by the \l QModbusPdu::ReportServerId
                function code. Valid values are \c 0x00 (OFF) and \c 0xff (ON).
                The default value preset is \c 0xff (ON).
        \row
            \li \l QModbusServer::AdditionalData
            \li Sets the server's additional data to \a newValue. This data is
                used as addendum by the \l QModbusPdu::ReportServerId function
                code. The maximum data size cannot exceed 249 bytes to match
                response message size restrictions.
                The default value preset is \c {Qt Modbus Server}.
        \row
            \li \l QModbusServer::UserOption
            \li Sets the value of a user option to \a newValue.

                \note For user options, it is up to the developer to decide
                which types to use and ensure that components use the correct
                types when accessing and setting values.
    \endtable
*/
bool QModbusServer::setValue(int option, const QVariant &newValue)
{
#define CHECK_INT_OR_UINT(val) \
    do { \
        if ((val.type() != QVariant::Int) && (val.type() != QVariant::UInt)) \
            return false; \
    } while (0)

    Q_D(QModbusServer);
    switch (option) {
    case DiagnosticRegister:
        CHECK_INT_OR_UINT(newValue);
        d->m_serverOptions.insert(option, newValue);
        return true;
    case ExceptionStatusOffset: {
        CHECK_INT_OR_UINT(newValue);
        const quint16 tmp = newValue.value<quint16>();
        QModbusDataUnit coils(QModbusDataUnit::Coils, tmp, 8);
        if (!data(&coils))
            return false;
        d->m_serverOptions.insert(option, tmp);
        return true;
    }
    case DeviceBusy: {
        CHECK_INT_OR_UINT(newValue);
        const quint16 tmp = newValue.value<quint16>();
        if ((tmp != 0x0000) && (tmp != 0xffff))
            return false;
        d->m_serverOptions.insert(option, tmp);
        return true;
    }
    case AsciiInputDelimiter: {
        CHECK_INT_OR_UINT(newValue);
        bool ok = false;
        if (newValue.toUInt(&ok) > 0xff || !ok)
            return false;
        d->m_serverOptions.insert(option, newValue);
        return true;
    }
    case ListenOnlyMode: {
        if (newValue.type() != QVariant::Bool)
            return false;
        d->m_serverOptions.insert(option, newValue);
        return true;
    }
    case ServerIdentifier:
        CHECK_INT_OR_UINT(newValue);
        d->m_serverOptions.insert(option, newValue);
        return true;
    case RunIndicatorStatus: {
        CHECK_INT_OR_UINT(newValue);
        const quint8 tmp = newValue.value<quint8>();
        if ((tmp != 0x00) && (tmp != 0xff))
            return false;
        d->m_serverOptions.insert(option, tmp);
        return true;
    }
    case AdditionalData: {
        if (newValue.type() != QVariant::ByteArray)
            return false;
        const QByteArray additionalData = newValue.toByteArray();
        if (additionalData.size() > 249)
            return false;
        d->m_serverOptions.insert(option, additionalData);
        return true;
    }
    default:
        break;
    };

    if (option < UserOption)
        return false;
    d->m_serverOptions.insert(option, newValue);
    return true;

#undef CHECK_INT_OR_UINT
}
Example #3
0
ExternalHelpWindow::ExternalHelpWindow(QWidget *parent)
    : QMainWindow(parent)
{
    QSettings *settings = Core::ICore::instance()->settings();
    settings->beginGroup(Help::Constants::ID_MODE_HELP);

    const QVariant geometry = settings->value(QLatin1String("geometry"));
    if (geometry.isValid())
        restoreGeometry(geometry.toByteArray());
    else
        resize(640, 480);

    settings->endGroup();

    QAction *action = new QAction(this);
    action->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_I));
    connect(action, SIGNAL(triggered()), this, SIGNAL(activateIndex()));
    addAction(action);

    action = new QAction(this);
    action->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_C));
    connect(action, SIGNAL(triggered()), this, SIGNAL(activateContents()));
    addAction(action);

    action = new QAction(this);
    action->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_Slash));
    connect(action, SIGNAL(triggered()), this, SIGNAL(activateSearch()));
    addAction(action);

    action = new QAction(this);
    action->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_B));
    connect(action, SIGNAL(triggered()), this, SIGNAL(activateBookmarks()));
    addAction(action);

    action = new QAction(this);
    action->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_O));
    connect(action, SIGNAL(triggered()), this, SIGNAL(activateOpenPages()));
    addAction(action);

    CentralWidget *centralWidget = CentralWidget::instance();

    action = new QAction(this);
    action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Plus));
    connect(action, SIGNAL(triggered()), centralWidget, SLOT(zoomIn()));
    addAction(action);

    action = new QAction(this);
    action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Minus));
    connect(action, SIGNAL(triggered()), centralWidget, SLOT(zoomOut()));
    addAction(action);

    action = new QAction(this);
    action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_M));
    connect(action, SIGNAL(triggered()), this, SIGNAL(addBookmark()));
    addAction(action);

    action = new QAction(this);
    action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_C));
    connect(action, SIGNAL(triggered()), centralWidget, SLOT(copy()));
    addAction(action);

    action = new QAction(this);
    action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_P));
    connect(action, SIGNAL(triggered()), centralWidget, SLOT(print()));
    addAction(action);

    action = new QAction(this);
    action->setShortcut(QKeySequence::Back);
    action->setEnabled(centralWidget->isBackwardAvailable());
    connect(action, SIGNAL(triggered()), centralWidget, SLOT(backward()));
    connect(centralWidget, SIGNAL(backwardAvailable(bool)), action,
        SLOT(setEnabled(bool)));

    action = new QAction(this);
    action->setShortcut(QKeySequence::Forward);
    action->setEnabled(centralWidget->isForwardAvailable());
    connect(action, SIGNAL(triggered()), centralWidget, SLOT(forward()));
    connect(centralWidget, SIGNAL(forwardAvailable(bool)), action,
        SLOT(setEnabled(bool)));

    QAction *reset = new QAction(this);
    connect(reset, SIGNAL(triggered()), centralWidget, SLOT(resetZoom()));
    addAction(reset);

    QAction *ctrlTab = new QAction(this);
    connect(ctrlTab, SIGNAL(triggered()), &OpenPagesManager::instance(),
        SLOT(gotoPreviousPage()));
    addAction(ctrlTab);

    QAction *ctrlShiftTab = new QAction(this);
    connect(ctrlShiftTab, SIGNAL(triggered()), &OpenPagesManager::instance(),
        SLOT(gotoNextPage()));
    addAction(ctrlShiftTab);

    action = new QAction(QIcon(Core::Constants::ICON_TOGGLE_SIDEBAR),
        tr("Show Sidebar"), this);
    connect(action, SIGNAL(triggered()), this, SIGNAL(showHideSidebar()));

#ifdef Q_WS_MAC
    reset->setShortcut(QKeySequence(Qt::ALT + Qt::Key_0));
    action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_0));
    ctrlTab->setShortcut(QKeySequence(Qt::ALT + Qt::Key_Tab));
    ctrlShiftTab->setShortcut(QKeySequence(Qt::ALT + Qt::SHIFT + Qt::Key_Tab));
#else
    reset->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_0));
    action->setShortcut(QKeySequence(Qt::ALT + Qt::Key_0));
    ctrlTab->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Tab));
    ctrlShiftTab->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_Tab));
#endif

    QToolButton *button = new QToolButton;
    button->setDefaultAction(action);

    QStatusBar *statusbar = statusBar();
    statusbar->show();
    statusbar->setProperty("p_styled", true);
    statusbar->addPermanentWidget(button);

    QWidget *w = new QWidget;
    QHBoxLayout *layout = new QHBoxLayout(w);
    layout->addStretch(1);
    statusbar->insertWidget(1, w, 1);

    installEventFilter(this);
    setWindowTitle(tr("Qt Creator Offline Help"));
}
Example #4
0
PyObject* scribus_getproperty(PyObject* /*self*/, PyObject* args, PyObject* kw)
{
	PyObject* objArg = NULL;
	char* propertyName = NULL;
	char* kwargs[] = {const_cast<char*>("object"),
					  const_cast<char*>("property"),
					  NULL};
	if (!PyArg_ParseTupleAndKeywords(args, kw, "Oes", kwargs,
				&objArg, "ascii", &propertyName))
		return NULL;

	// Get the QObject* the object argument refers to
	QObject* obj = getQObjectFromPyArg(objArg);
	if (!obj)
		return NULL;
	objArg = NULL; // no need to decref, it's borrowed

	// Get the QMetaProperty for the property, so we can check
	// if it's a set/enum and do name/value translation.
	const QMetaObject* objmeta = obj->metaObject();
	int i = objmeta->indexOfProperty(propertyName);
	if (i == -1)
	{
		PyErr_SetString(PyExc_ValueError,
				QObject::tr("Property not found").toLocal8Bit().data());
		return NULL;
	}

	QMetaProperty propmeta = objmeta->property(i);
	if (!propmeta.isValid())
	{
		PyErr_SetString(PyExc_ValueError,
				QObject::tr("Invalid property").toLocal8Bit().data());
		return NULL;
	}

	// Get the property value as a variant type
	QVariant prop = obj->property(propertyName);

	// Convert the property to an instance of the closest matching Python type.
	PyObject* resultobj = NULL;
	// NUMERIC TYPES
	if (prop.type() == QVariant::Int)
		resultobj = PyLong_FromLong(prop.toInt());
	else if (prop.type() == QVariant::Double)
		resultobj = PyFloat_FromDouble(prop.toDouble());
	// BOOLEAN
	else if (prop.type() == QVariant::Bool)
		resultobj = PyBool_FromLong(prop.toBool());
	// STRING TYPES
	else if (prop.type() == QVariant::ByteArray)
		resultobj = PyString_FromString(prop.toByteArray().data());
	else if (prop.type() == QVariant::String)
		resultobj = PyString_FromString(prop.toString().toUtf8().data());
	// HIGHER ORDER TYPES
	else if (prop.type() == QVariant::Point)
	{
		// Return a QPoint as an (x,y) tuple.
		QPoint pt = prop.toPoint();
		return Py_BuildValue("(ii)", pt.x(), pt.y());
	}
	else if (prop.type() == QVariant::Rect)
	{
		// Return a QRect as an (x,y,width,height) tuple.
		// FIXME: We should really construct and return an object that
		// matches the API of QRect and has properties to keep
		// left/top/right/bottom and x/y/width/height in sync.
		QRect r = prop.toRect();
		return Py_BuildValue("(iiii)", r.x(), r.y(), r.width(), r.height());
	}
	else if (prop.type() == QVariant::StringList)
	{
		QStringList tmp = prop.toStringList();
		return convert_QStringList_to_PyListObject(tmp);
	}
	// UNHANDLED TYPE
	else
	{
		PyErr_SetString(PyExc_TypeError, QObject::tr("Couldn't convert result type '%1'.").arg(prop.typeName()).toLocal8Bit().constData() );
		return resultobj;
	}

	// Return the resulting Python object
	if (resultobj == NULL)
	{
		// An exception was set while assigning to resultobj
		assert(PyErr_Occurred());
		return NULL;
	}
	else
		return resultobj;
}
Example #5
0
	QList<QByteArray> convertFromMime(const QString & /* mime */, QVariant data, QString /* flav */) {
		QByteArray a = data.toByteArray();
		QList<QByteArray> l;
		l.append(a);
		return l;
	}
Example #6
0
void App::init()
{
    QSettings settings;

    setWindowIcon(QIcon(":/qlcplus.png"));

    m_tab = new QTabWidget(this);
    m_tab->setTabPosition(QTabWidget::South);
    setCentralWidget(m_tab);

    QVariant var = settings.value(SETTINGS_GEOMETRY);
    if (var.isValid() == true)
    {
        this->restoreGeometry(var.toByteArray());
    }
    else
    {
        /* Application geometry and window state */
        QSize size = settings.value("/workspace/size").toSize();
        if (size.isValid() == true)
            resize(size);
        else
        {
            if (QLCFile::isRaspberry())
            {
                QRect geometry = qApp->desktop()->availableGeometry();
                int w = geometry.width();
                int h = geometry.height();
                if (m_overscan == true)
                {
                    // if we're on a Raspberry Pi, introduce a 5% margin
                    w = (float)geometry.width() * 0.95;
                    h = (float)geometry.height() * 0.95;
                }
                setGeometry((geometry.width() - w) / 2, (geometry.height() - h) / 2,
                            w, h);
            }
            else
                resize(800, 600);
        }

        QVariant state = settings.value("/workspace/state", Qt::WindowNoState);
        if (state.isValid() == true)
            setWindowState(Qt::WindowState(state.toInt()));
    }

    QVariant dir = settings.value(SETTINGS_WORKINGPATH);
    if (dir.isValid() == true)
        m_workingDirectory = QDir(dir.toString());

    // The engine object
    initDoc();
    // Main view actions
    initActions();
    // Main tool bar
    initToolBar();

    m_dumpProperties = new DmxDumpFactoryProperties(KUniverseCount);

    // Create primary views.
    m_tab->setIconSize(QSize(24, 24));
    QWidget* w = new FixtureManager(m_tab, m_doc);
    m_tab->addTab(w, QIcon(":/fixture.png"), tr("Fixtures"));
    w = new FunctionManager(m_tab, m_doc);
    m_tab->addTab(w, QIcon(":/function.png"), tr("Functions"));
    w = new ShowManager(m_tab, m_doc);
    m_tab->addTab(w, QIcon(":/show.png"), tr("Shows"));
    w = new VirtualConsole(m_tab, m_doc);
    m_tab->addTab(w, QIcon(":/virtualconsole.png"), tr("Virtual Console"));
    w = new SimpleDesk(m_tab, m_doc);
    m_tab->addTab(w, QIcon(":/slidermatrix.png"), tr("Simple Desk"));
    w = new InputOutputManager(m_tab, m_doc);
    m_tab->addTab(w, QIcon(":/input_output.png"), tr("Inputs/Outputs"));

    // Listen to blackout changes and toggle m_controlBlackoutAction
    connect(m_doc->inputOutputMap(), SIGNAL(blackoutChanged(bool)), this, SLOT(slotBlackoutChanged(bool)));

    // Enable/Disable panic button
    connect(m_doc->masterTimer(), SIGNAL(functionListChanged()), this, SLOT(slotRunningFunctionsChanged()));
    slotRunningFunctionsChanged();

    // Start up in non-modified state
    m_doc->resetModified();

    QString ssDir;

#if defined(WIN32) || defined(Q_OS_WIN)
    /* User's input profile directory on Windows */
    LPTSTR home = (LPTSTR) malloc(256 * sizeof(TCHAR));
    GetEnvironmentVariable(TEXT("UserProfile"), home, 256);
    ssDir = QString("%1/%2").arg(QString::fromUtf16(reinterpret_cast<ushort*> (home)))
                            .arg(USERQLCPLUSDIR);
    free(home);
#else
    /* User's input profile directory on *NIX systems */
    ssDir = QString("%1/%2").arg(getenv("HOME")).arg(USERQLCPLUSDIR);
#endif

    QFile ssFile(ssDir + QDir::separator() + "qlcplusStyle.qss");
    if (ssFile.exists() == true)
    {
        ssFile.open(QFile::ReadOnly);
        QString styleSheet = QLatin1String(ssFile.readAll());
        this->setStyleSheet(styleSheet);
    }

#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
    m_videoProvider = new VideoProvider(m_doc, this);
#endif
}
Example #7
0
AddFixture::AddFixture(QWidget* parent, const Doc* doc, const Fixture* fxi)
    : QDialog(parent)
    , m_doc(doc)
{
    m_addressValue = 0;
    m_universeValue = 0;
    m_amountValue = 1;
    m_gapValue = 0;
    m_channelsValue = 1;
    m_fixtureDef = NULL;
    m_mode = NULL;
    m_fxiCount = 0;
    m_fixtureID = Fixture::invalidId();
    m_invalidAddressFlag = false;

    setupUi(this);
    m_addrErrorLabel->hide();

    QAction* action = new QAction(this);
    action->setShortcut(QKeySequence(QKeySequence::Close));
    connect(action, SIGNAL(triggered(bool)), this, SLOT(reject()));
    addAction(action);

    connect(m_tree, SIGNAL(itemSelectionChanged()),
            this, SLOT(slotSelectionChanged()));
    connect(m_tree, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),
            this, SLOT(slotTreeDoubleClicked(QTreeWidgetItem*)));
    connect(m_modeCombo, SIGNAL(activated(const QString&)),
            this, SLOT(slotModeActivated(const QString&)));
    connect(m_universeCombo, SIGNAL(activated(int)),
            this, SLOT(slotUniverseActivated(int)));
    connect(m_addressSpin, SIGNAL(valueChanged(int)),
            this, SLOT(slotAddressChanged(int)));
    connect(m_channelsSpin, SIGNAL(valueChanged(int)),
            this, SLOT(slotChannelsChanged(int)));
    connect(m_nameEdit, SIGNAL(textEdited(const QString&)),
            this, SLOT(slotNameEdited(const QString&)));
    connect(m_gapSpin, SIGNAL(valueChanged(int)),
            this, SLOT(slotGapSpinChanged(int)));
    connect(m_amountSpin, SIGNAL(valueChanged(int)),
            this, SLOT(slotAmountSpinChanged(int)));
    connect(m_searchEdit, SIGNAL(textChanged(QString)),
            this, SLOT(slotSearchFilterChanged(QString)));
    connect(m_diptoolButton, SIGNAL(clicked()),
            this, SLOT(slotDiptoolButtonClicked()));

    /* Fill fixture definition tree (and select a fixture def) */
    if (fxi != NULL)
    {
        fillTree(fxi->fixtureDef()->manufacturer(), fxi->fixtureDef()->model());
        m_fixtureID = fxi->id();
    }
    else
        fillTree(KXMLFixtureGeneric, KXMLFixtureGeneric);

    m_fixturesCount->setText(tr("Fixtures found: %1").arg(m_fxiCount));

    /* Fill universe combo with available universes */
    m_universeCombo->addItems(m_doc->inputOutputMap()->universeNames());

    /* Simulate first selection and find the next free address */
    slotSelectionChanged();

    if (fxi != NULL)
    {
        // Universe
        m_universeCombo->setCurrentIndex(fxi->universe());
        slotUniverseActivated(fxi->universe());

        m_addressSpin->setValue(fxi->address() + 1);
        m_addressValue = fxi->address();

        m_multipleGroup->setEnabled(false);

        // Name
        m_nameEdit->setText(fxi->name());
        slotNameEdited(fxi->name());
        m_nameEdit->setModified(true); // Prevent auto-naming

        // Mode
        int index = m_modeCombo->findText(fxi->fixtureMode()->name());
        if (index != -1)
        {
            m_channelsSpin->setValue(fxi->channels());
            m_modeCombo->setCurrentIndex(index);
            slotModeActivated(m_modeCombo->itemText(index));
        }
    }
    else
    {
        slotUniverseActivated(0);
        findAddress();

        m_channelsSpin->setValue(1);
    }

    QSettings settings;
    QVariant var = settings.value(SETTINGS_GEOMETRY);
    if (var.isValid() == true)
        restoreGeometry(var.toByteArray());
    AppUtil::ensureWidgetIsVisible(this);
}
Example #8
0
File: qgis.cpp Project: GeoCat/QGIS
uint qHash( const QVariant &variant )
{
  if ( !variant.isValid() || variant.isNull() )
    return std::numeric_limits<uint>::max();

  switch ( variant.type() )
  {
    case QVariant::Int:
      return qHash( variant.toInt() );
    case QVariant::UInt:
      return qHash( variant.toUInt() );
    case QVariant::Bool:
      return qHash( variant.toBool() );
    case QVariant::Double:
      return qHash( variant.toDouble() );
    case QVariant::LongLong:
      return qHash( variant.toLongLong() );
    case QVariant::ULongLong:
      return qHash( variant.toULongLong() );
    case QVariant::String:
      return qHash( variant.toString() );
    case QVariant::Char:
      return qHash( variant.toChar() );
    case QVariant::List:

#if QT_VERSION >= 0x050600
      return qHash( variant.toList() );
#else
      {
        QVariantList list = variant.toList();
        if ( list.isEmpty() )
          return -1;
        else
          return qHash( list.at( 0 ) );
      }
#endif
    case QVariant::StringList:
#if QT_VERSION >= 0x050600
      return qHash( variant.toStringList() );
#else
      {
        QStringList list = variant.toStringList();
        if ( list.isEmpty() )
          return -1;
        else
          return qHash( list.at( 0 ) );
      }
#endif
    case QVariant::ByteArray:
      return qHash( variant.toByteArray() );
    case QVariant::Date:
      return qHash( variant.toDate() );
    case QVariant::Time:
      return qHash( variant.toTime() );
    case QVariant::DateTime:
      return qHash( variant.toDateTime() );
    case QVariant::Url:
    case QVariant::Locale:
    case QVariant::RegExp:
      return qHash( variant.toString() );
    default:
      break;
  }

  return std::numeric_limits<uint>::max();
}
Example #9
0
void QPpmHandler::setOption(ImageOption option, const QVariant &value)
{
    if (option == SubType)
        subType = value.toByteArray().toLower();
}
Example #10
0
QDomElement MaiaObject::toXml(QVariant arg) {
	
	//dummy document
	QDomDocument doc;
	//value element, we need this in each case
	QDomElement tagValue = doc.createElement("value");

	/* qDebug("type: %d (%s)", arg.type(), arg.typeName()); */

	switch(arg.type()) {
	case QVariant::String: {

		QDomElement tagString = doc.createElement("string"); 
		QDomText textString = doc.createTextNode(arg.toString());
		
		tagValue.appendChild(tagString);
		tagString.appendChild(textString);

		return tagValue;

	} case QVariant::Int: {

		QDomElement tagInt = doc.createElement("int"); 
		QDomText textInt = doc.createTextNode(QString::number(arg.toInt()));
		
		tagValue.appendChild(tagInt);
		tagInt.appendChild(textInt);

		return tagValue;

	} case QVariant::Double: {

		QDomElement tagDouble = doc.createElement("double"); 
		QDomText textDouble = doc.createTextNode(QString::number(arg.toDouble()));
		
		tagValue.appendChild(tagDouble);
		tagDouble.appendChild(textDouble);

		return tagValue;

	} case QVariant::Bool: {
	
		QString textValue = arg.toBool() ? "1" : "0";

		QDomElement tag = doc.createElement("boolean"); 
		QDomText text = doc.createTextNode(textValue);
		
		tagValue.appendChild(tag);
		tag.appendChild(text);

		return tagValue;

	} case QVariant::ByteArray: {

		QString textValue = arg.toByteArray().toBase64();

		QDomElement tag = doc.createElement("base64"); 
		QDomText text = doc.createTextNode(textValue);
		
		tagValue.appendChild(tag);
		tag.appendChild(text);

		return tagValue;

	} case QVariant::DateTime: {
	
		QString textValue = arg.toDateTime().toString("yyyyMMddThh:mm:ss");

		QDomElement tag = doc.createElement("datetime.iso8601"); 
		QDomText text = doc.createTextNode(textValue);
		
		tagValue.appendChild(tag);
		tag.appendChild(text);

		return tagValue;

	} case QVariant::List: {

		QDomElement tagArray = doc.createElement("array");
		QDomElement tagData = doc.createElement("data");
		tagArray.appendChild(tagData);
		tagValue.appendChild(tagArray);

		const QList<QVariant> args = arg.toList();
		for(int i = 0; i < args.size(); ++i) {
			tagData.appendChild(toXml(args.at(i)));
		}
	
		return tagValue;

	} case QVariant::Map: {

		QDomElement tagStruct = doc.createElement("struct");
		QDomElement member;
		QDomElement name;

		tagValue.appendChild(tagStruct);

		QMap<QString, QVariant> map = arg.toMap();
		QMapIterator<QString, QVariant> i(map);
		while(i.hasNext()) {
			i.next();

			member = doc.createElement("member");
			name = doc.createElement("name");

			// (key) -> name -> member -> struct
			tagStruct.appendChild(member);
			member.appendChild(name);
			name.appendChild(doc.createTextNode(i.key()));

			// add variables by recursion
			member.appendChild(toXml(i.value()));
		}

		return tagValue;

	} default:
		qDebug() << "Failed to marshal unknown variant type: " << arg.type() << endl;
	}
	return QDomElement(); //QString::null;
}
/*!
    Client side method call that directly accesses the object through the DBus interface.
    All arguments and return types are processed and converted accordingly so that all functions
    satisfy the QtDBus type system.
*/
QVariant ObjectEndPoint::invokeRemote(int metaIndex, const QVariantList& args, int returnType)
{
    QMetaMethod method = service->metaObject()->method(metaIndex);

    Q_ASSERT(d->endPointType == ObjectEndPoint::Client);
   
    // Check is this is a signal relay
    if (method.methodType() == QMetaMethod::Signal) {
        // Convert custom arguments
        QVariantList convertedList;
        QList<QByteArray> params = method.parameterTypes();
        for (int i = 0; i < params.size(); i++) {
            const QByteArray& type = params[i];
            int variantType = QVariant::nameToType(type);
            if (variantType == QVariant::UserType) {
                variantType = QMetaType::type(type);
                
                QDBusVariant dbusVariant = qvariant_cast<QDBusVariant>(args[i]);
                QVariant variant = dbusVariant.variant();

                if (type == "QVariant") {
                    convertedList << variant; 
                } else {
                    QByteArray buffer = variant.toByteArray();
                    QDataStream stream(&buffer, QIODevice::ReadWrite);
                    QVariant *customType = new QVariant(variantType, (const void*)0);
                    QMetaType::load(stream, QMetaType::type("QVariant"), customType);
                    convertedList << *customType;
                }
            } else {
                convertedList << args[i];
            }
        }

        // Signal relay
        const int numArgs = convertedList.size();
        QVarLengthArray<void *, 32> a( numArgs+1 );
        a[0] = 0;

        const QList<QByteArray> pTypes = method.parameterTypes();
        for ( int arg = 0; arg < numArgs; ++arg ) {
            if (pTypes.at(arg) == "QVariant") {
                a[arg+1] = (void *)&( convertedList[arg] );
            } else {
                a[arg+1] = (void *)( convertedList[arg].data() );
            }
        }

        // Activate the service proxy signal call
        QMetaObject::activate(service, metaIndex, a.data());
        return QVariant();
    }

    // Method call so process arguments and convert if not a supported DBus type
    QVariantList convertedList;
    QList<QByteArray> params = method.parameterTypes();
    for (int i = 0; i < params.size(); i++) {
        QVariant converted = toDBusVariant(params[i], args[i]);
        convertedList << converted;
    }

    bool validDBus = false;
    QDBusMessage msg;
  
    // Find the method name and try a direct DBus call
    QString methodName(method.signature());
    methodName.truncate(methodName.indexOf("("));
    
    if (method.methodType() == QMetaMethod::Slot || method.methodType() == QMetaMethod::Method) {
        // Slot or Invokable method
        msg = iface->callWithArgumentList(QDBus::Block, methodName, convertedList);
        if (msg.type() == QDBusMessage::ReplyMessage) { 
            validDBus = true;
        }
    }

    // DBus call should only fail for methods with invalid type definitions 
    if (validDBus) {
	if (returnType == QMetaType::Void) {
	    // Void method call
            return QVariant();
	}
	else {
            // Use DBus message return value
            QVariantList retList = msg.arguments();

            // Process return
            const QByteArray& retType = QByteArray(method.typeName());
            int variantType = QVariant::nameToType(retType);
                if (variantType == QVariant::UserType) {
                    variantType = QMetaType::type(retType);

                    if (retType == "QVariant") {
                        // QVariant return from QDBusVariant wrapper
                        QDBusVariant dbusVariant = qvariant_cast<QDBusVariant>(retList[0]);
                        return dbusVariant.variant();
                    } else {
                        // Custom return type
                        QDBusVariant dbusVariant = qvariant_cast<QDBusVariant>(retList[0]);
                        QVariant convert = dbusVariant.variant();

                        QServiceUserTypeDBus customType = qdbus_cast<QServiceUserTypeDBus>(convert);
                        QByteArray buffer = customType.variantBuffer;
                        QDataStream stream(&buffer, QIODevice::ReadWrite);

                        // Load our buffered variant-wrapped custom return
                        QVariant *customReturn = new QVariant(variantType, (const void*)0);
                        QMetaType::load(stream, QMetaType::type("QVariant"), customReturn);

                        return QVariant(variantType, customReturn->data());
                    }
            } else {
                // Standard return type
                return retList[0];
            }
        }
    } else {  
        qWarning( "%s::%s cannot be called.", service->metaObject()->className(), method.signature());
    }

    return QVariant();
}
static QString variantToTextValue(const QVariant& value, const QString& typeNs, const QString& type)
{
    switch (value.userType())
    {
    case QVariant::Char:
        // fall-through
    case QVariant::String:
        return value.toString();
    case QVariant::Url:
        // xmlpatterns/data/qatomicvalue.cpp says to do this:
        return value.toUrl().toString();
    case QVariant::ByteArray:
    {
        const QByteArray data = value.toByteArray();
        if (typeNs == KDSoapNamespaceManager::xmlSchema1999() || typeNs == KDSoapNamespaceManager::xmlSchema2001()) {
            if (type == QLatin1String("hexBinary")) {
                const QByteArray hb = data.toHex();
                return QString::fromLatin1(hb.constData(), hb.size());
            }
        }
        // default to base64Binary, like variantToXMLType() does.
        const QByteArray b64 = value.toByteArray().toBase64();
        return QString::fromLatin1(b64.constData(), b64.size());
    }
    case QVariant::Int:
        // fall-through
    case QVariant::LongLong:
        // fall-through
    case QVariant::UInt:
        return QString::number(value.toLongLong());
    case QVariant::ULongLong:
        return QString::number(value.toULongLong());
    case QVariant::Bool:
    case QMetaType::Float:
    case QVariant::Double:
        return value.toString();
    case QVariant::Time:
    {
        const QTime time = value.toTime();
        if (time.msec()) {
            // include milli-seconds
            return time.toString(QLatin1String("hh:mm:ss.zzz"));
        } else {
            return time.toString(Qt::ISODate);
        }
    }
    case QVariant::Date:
        return value.toDate().toString(Qt::ISODate);
    case QVariant::DateTime: // http://www.w3.org/TR/xmlschema-2/#dateTime
        return KDDateTime(value.toDateTime()).toDateString();
    case QVariant::Invalid:
        qDebug() << "ERROR: Got invalid QVariant in a KDSoapValue";
        return QString();
    default:
        if (value.canConvert<KDDateTime>()) {
            return value.value<KDDateTime>().toDateString();
        }

        if (value.userType() == qMetaTypeId<float>())
            return QString::number(value.value<float>());

        qDebug() << QString::fromLatin1("QVariants of type %1 are not supported in "
                                        "KDSoap, see the documentation").arg(QLatin1String(value.typeName()));
        return value.toString();
    }
}
Example #13
0
QString App::convertToUtf8String(const QVariant &pushContent)
{
    return QString::fromUtf8(pushContent.toByteArray().data());
}
Example #14
0
bool QDBusMarshaller::appendVariantInternal(const QVariant &arg)
{
    int id = arg.userType();
    if (id == QVariant::Invalid) {
        qWarning("QDBusMarshaller: cannot add an invalid QVariant");
        error(QLatin1String("Variant containing QVariant::Invalid passed in arguments"));
        return false;
    }

    // intercept QDBusArgument parameters here
    if (id == QDBusMetaTypeId::argument()) {
        QDBusArgument dbusargument = qvariant_cast<QDBusArgument>(arg);
        QDBusArgumentPrivate *d = QDBusArgumentPrivate::d(dbusargument);
        if (!d->message)
            return false;       // can't append this one...

        QDBusDemarshaller demarshaller(capabilities);
        demarshaller.message = q_dbus_message_ref(d->message);

        if (d->direction == Demarshalling) {
            // it's demarshalling; just copy
            demarshaller.iterator = static_cast<QDBusDemarshaller *>(d)->iterator;
        } else {
            // it's marshalling; start over
            if (!q_dbus_message_iter_init(demarshaller.message, &demarshaller.iterator))
                return false;   // error!
        }

        return appendCrossMarshalling(&demarshaller);
    }

    const char *signature = QDBusMetaType::typeToSignature( QVariant::Type(id) );
    if (!signature) {
        qWarning("QDBusMarshaller: type `%s' (%d) is not registered with D-BUS. "
                 "Use qDBusRegisterMetaType to register it",
                 QMetaType::typeName(id), id);
        error(QString::fromLatin1("Unregistered type %1 passed in arguments")
              .arg(QLatin1String(QMetaType::typeName(id))));
        return false;
    }

    switch (*signature) {
#ifdef __OPTIMIZE__
    case DBUS_TYPE_BYTE:
    case DBUS_TYPE_INT16:
    case DBUS_TYPE_UINT16:
    case DBUS_TYPE_INT32:
    case DBUS_TYPE_UINT32:
    case DBUS_TYPE_INT64:
    case DBUS_TYPE_UINT64:
    case DBUS_TYPE_DOUBLE:
        qIterAppend(&iterator, ba, *signature, arg.constData());
        return true;
    case DBUS_TYPE_BOOLEAN:
        append( arg.toBool() );
        return true;
#else
    case DBUS_TYPE_BYTE:
        append( qvariant_cast<uchar>(arg) );
        return true;
    case DBUS_TYPE_BOOLEAN:
        append( arg.toBool() );
        return true;
    case DBUS_TYPE_INT16:
        append( qvariant_cast<short>(arg) );
        return true;
    case DBUS_TYPE_UINT16:
        append( qvariant_cast<ushort>(arg) );
        return true;
    case DBUS_TYPE_INT32:
        append( static_cast<dbus_int32_t>(arg.toInt()) );
        return true;
    case DBUS_TYPE_UINT32:
        append( static_cast<dbus_uint32_t>(arg.toUInt()) );
        return true;
    case DBUS_TYPE_INT64:
        append( arg.toLongLong() );
        return true;
    case DBUS_TYPE_UINT64:
        append( arg.toULongLong() );
        return true;
    case DBUS_TYPE_DOUBLE:
        append( arg.toDouble() );
        return true;
#endif

    case DBUS_TYPE_STRING:
        append( arg.toString() );
        return true;
    case DBUS_TYPE_OBJECT_PATH:
        append( qvariant_cast<QDBusObjectPath>(arg) );
        return true;
    case DBUS_TYPE_SIGNATURE:
        append( qvariant_cast<QDBusSignature>(arg) );
        return true;

    // compound types:
    case DBUS_TYPE_VARIANT:
        // nested QVariant
        return append( qvariant_cast<QDBusVariant>(arg) );

    case DBUS_TYPE_ARRAY:
        // could be many things
        // find out what kind of array it is
        switch (arg.type()) {
        case QVariant::StringList:
            append( arg.toStringList() );
            return true;

        case QVariant::ByteArray:
            append( arg.toByteArray() );
            return true;

        default:
            ;                   // fall through
        }
        // fall through

    case DBUS_TYPE_STRUCT:
    case DBUS_STRUCT_BEGIN_CHAR:
        return appendRegisteredType( arg );

    case DBUS_TYPE_DICT_ENTRY:
    case DBUS_DICT_ENTRY_BEGIN_CHAR:
        qFatal("QDBusMarshaller::appendVariantInternal got a DICT_ENTRY!");
        return false;

    case DBUS_TYPE_UNIX_FD:
        if (capabilities & QDBusConnection::UnixFileDescriptorPassing || ba) {
            append(qvariant_cast<QDBusUnixFileDescriptor>(arg));
            return true;
        }
        // fall through

    default:
        qWarning("QDBusMarshaller::appendVariantInternal: Found unknown D-BUS type '%s'",
                 signature);
        return false;
    }

    return true;
}
Example #15
0
bool RawData::startsWith(const QVariant &data)
{
    return mByteArray.startsWith(data.toByteArray());
}
Example #16
0
bool RawData::contains(const QVariant &data)
{
    return mByteArray.contains(data.toByteArray());
}
Example #17
0
void MVariant::tostring(QVariant params )
{
    
//    qDebug()<<"\n"<<params.type()<<"\n"<<params;
    switch ( params.type() ) {
    case QVariant::Int:
    case QVariant::UInt:
        this->items << QString::number( params.toInt() );
      this->ret<<this->items;
      //this->items.clear();
        break;

    case QVariant::String:
        this->items <<params.toString();
        this->ret<<this->items;
       //this->items.clear();
        break;

    case QVariant::Double:
        this->items << QString::number( params.toDouble() );
        this->ret<<this->items;
        //this->items.clear();
        break;

    case QVariant::DateTime:
        this->items << params.toDateTime().toString();
		this->ret<<this->items;
        //this->items.clear();
          break;

    case QVariant::Bool:
        this->items << ( params.toBool() ? "true" : "false" );
        this->ret<<this->items;
        //this->items.clear();
        break;

    case QVariant::ByteArray:
        {
            QString data = params.toByteArray().toBase64();
            if ( data.length() > 128 ) {
                data = data.left(64)+"...";
            }
            this->items << data;
          this->ret<<this->items;
          // this->items.clear();
            break;
        }

    case QVariant::StringList:
    case QVariant::List:
        {   //this->items.clear();    
            QListIterator<QVariant> it( params.toList() );
            while( it.hasNext() ) {
				//it.next();
                this->tostring(it.next());
            }
            break;
        }
    case QVariant::Map:
        {
			
			//QStringList item;
            QMapIterator<QString,QVariant> it( params.toMap());
            while( it.hasNext() ) {
               it.next();
               //this->items.clear();
				this->items<<it.key();		
				this->tostring(it.value());
				//this->ret<<this->items;
				this->items.clear();
            }
            
            break;
        }
      default:
			break;
    
    }
   
}
Example #18
0
int RawData::count(const QVariant &data) const
{
    return mByteArray.count(data.toByteArray());
}
Example #19
0
QVariant QDbfSqlModel::data(const QModelIndex &index, int role) const
{

    QVariant value = QSqlQueryModel::data(index, role);
    int i,j,k;

    QByteArray tempDateArray;
    QDate tempDate;
    QTime tempTime;
    quint32 l;
    qint32 l1;
    qint64 l2;
    double db;
    bool ok;
    QString currency;
    //QLocale clocale(QLocale::German);
    QLocale clocale(QLocale::C);
    quint8 r,g,b;
    QByteArray tempByteArray;

    //QList<int> charFields;
    for (i=0;i<charFields.count();i++)
    {
        if (index.column() == charFields.at(i))
        {
            switch (role)
            {
                case Qt::DisplayRole:
                    break;
                case Qt::TextAlignmentRole:
                    value = QVariant(Qt::AlignLeft | Qt::AlignVCenter);
                    break;
                case Qt::TextColorRole:
                    tempByteArray.append(charFieldColorString);
                    tempByteArray = QByteArray::fromHex(tempByteArray);
                    r = tempByteArray.at(0);
                    g = tempByteArray.at(1);
                    b = tempByteArray.at(2);
                    QColor tempColor(r,g,b);
                    value = qVariantFromValue(tempColor);
                    break;
            }
        }
    }

    //QList<int> currencyFields;
    for (i=0;i<currencyFields.count();i++)
    {
        if (index.column() == currencyFields.at(i))
        {
            switch (role)
            {
            case Qt::DisplayRole:
                tempDateArray = value.toByteArray();
                tempDateArray = QByteArray::fromHex(tempDateArray);

                l2 = *(qint64 *)tempDateArray.data();

                db = l2;
                currency.setNum(db/10000,'f',4);

                value = clocale.toString(db/10000,'f',4);
                break;
            case Qt::TextAlignmentRole:
                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                break;
            case Qt::TextColorRole:
                tempByteArray.append(currencyFieldColorString);
                tempByteArray = QByteArray::fromHex(tempByteArray);
                r = tempByteArray.at(0);
                g = tempByteArray.at(1);
                b = tempByteArray.at(2);
                QColor tempColor(r,g,b);
                value = qVariantFromValue(tempColor);
                break;
            }
        }
    }

    //QList<int> numericFields;
    for (i=0;i<numericFields.count();i++)
    {
        if (index.column() == numericFields.at(i))
        {
            switch (role)
            {
            case Qt::DisplayRole:
                currency=value.toString().simplified();
                k=currency.count()-1;
                j=0;
                ok=false;
                while (k>0)
                {
                    if (currency.at(k) == '.')
                    {
                        ok = true;
                        break;
                    }
                    k--;
                    j++;
                }
                if (!ok) j=0;
                value = clocale.toString(currency.toDouble(&ok),'f',j);
                break;
            case Qt::TextAlignmentRole:
                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                break;
            case Qt::TextColorRole:
                tempByteArray.append(numericFieldColorString);
                tempByteArray = QByteArray::fromHex(tempByteArray);
                r = tempByteArray.at(0);
                g = tempByteArray.at(1);
                b = tempByteArray.at(2);
                QColor tempColor(r,g,b);
                value = qVariantFromValue(tempColor);
                break;
            }
        }
    }

    //QList<int> dateFields;
    for (i=0;i<dateFields.count();i++)
    {
        if (index.column() == dateFields.at(i))
        {
            switch (role)
            {
            case Qt::DisplayRole:
                value = value.toDate().toString("dd.MM.yyyy");
                break;
            case Qt::TextAlignmentRole:
                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                break;
            case Qt::TextColorRole:
                tempByteArray.append(dateFieldColorString);
                tempByteArray = QByteArray::fromHex(tempByteArray);
                r = tempByteArray.at(0);
                g = tempByteArray.at(1);
                b = tempByteArray.at(2);
                QColor tempColor(r,g,b);
                value = qVariantFromValue(tempColor);
                break;
            }
        }
    }

    //QList<int> timeFields;
    for (i=0;i<timeFields.count();i++)
    {
        if (index.column() == timeFields.at(i))
        {
            switch (role)
            {
            case Qt::DisplayRole:
                tempDateArray = value.toByteArray();
                tempDateArray = QByteArray::fromHex(tempDateArray);

                l = *(quint32 *)tempDateArray.data();

                tempDate = QDate::fromJulianDay(l);

                l = *(quint32 *)(tempDateArray.data()+4);

                tempTime.setHMS(0,0,0);
                tempTime = tempTime.addMSecs(l);

                value = tempDate.toString("dd.MM.yyyy")+" "+tempTime.toString("hh:mm:ss.zzz");

                break;
            case Qt::TextAlignmentRole:
                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                break;
            case Qt::TextColorRole:
                tempByteArray.append(timeFieldColorString);
                tempByteArray = QByteArray::fromHex(tempByteArray);
                r = tempByteArray.at(0);
                g = tempByteArray.at(1);
                b = tempByteArray.at(2);
                QColor tempColor(r,g,b);
                value = qVariantFromValue(tempColor);
                break;
            }
        }
    }

    //QList<int> doubleFields;
    for (i=0;i<doubleFields.count();i++)
    {
        if (index.column() == doubleFields.at(i))
        {
            switch (role)
            {
            case Qt::DisplayRole:
                tempDateArray = value.toByteArray();
                tempDateArray = QByteArray::fromHex(tempDateArray);

                db = *(double *)tempDateArray.data();

                value = db;
                //value = clocale.toString(db,'f',4);
                break;
            case Qt::TextAlignmentRole:
                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                break;
            case Qt::TextColorRole:
                tempByteArray.append(doubleFieldColorString);
                tempByteArray = QByteArray::fromHex(tempByteArray);
                r = tempByteArray.at(0);
                g = tempByteArray.at(1);
                b = tempByteArray.at(2);
                QColor tempColor(r,g,b);
                value = qVariantFromValue(tempColor);
                break;
            }
        }
    }

    //QList<int> intFields;
    for (i=0;i<intFields.count();i++)
    {
        if (index.column() == intFields.at(i))
        {
            switch (role)
            {
            case Qt::DisplayRole:
                tempDateArray = value.toByteArray();
                tempDateArray = QByteArray::fromHex(tempDateArray);

                l1 = *(quint32 *)tempDateArray.data();

                value = l1;

                break;
            case Qt::TextAlignmentRole:
                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                break;
            case Qt::TextColorRole:
                tempByteArray.append(intFieldColorString);
                tempByteArray = QByteArray::fromHex(tempByteArray);
                r = tempByteArray.at(0);
                g = tempByteArray.at(1);
                b = tempByteArray.at(2);
                QColor tempColor(r,g,b);
                value = qVariantFromValue(tempColor);
                break;
            }
        }
    }

    //QList<int> logicalFields;
    for (i=0;i<logicalFields.count();i++)
    {
        if (index.column() == logicalFields.at(i))
        {
            switch (role)
            {
            case Qt::DisplayRole:
                break;
            case Qt::TextAlignmentRole:
                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                break;
            case Qt::TextColorRole:
                tempByteArray.append(logicalFieldColorString);
                tempByteArray = QByteArray::fromHex(tempByteArray);
                r = tempByteArray.at(0);
                g = tempByteArray.at(1);
                b = tempByteArray.at(2);
                QColor tempColor(r,g,b);
                value = qVariantFromValue(tempColor);
                break;
            }
        }
    }

    //QList<int> memoFields;
    for (i=0;i<memoFields.count();i++)
    {
        if (index.column() == memoFields.at(i))
        {
            switch (role)
            {
            case Qt::DisplayRole:
                break;
            case Qt::TextAlignmentRole:
                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                break;
            case Qt::TextColorRole:
                tempByteArray.append(memoFieldColorString);
                tempByteArray = QByteArray::fromHex(tempByteArray);
                r = tempByteArray.at(0);
                g = tempByteArray.at(1);
                b = tempByteArray.at(2);
                QColor tempColor(r,g,b);
                value = qVariantFromValue(tempColor);
                break;
            }
        }
    }
    //QList<int> memo4Fields;
    for (i=0;i<memo4Fields.count();i++)
    {
        if (index.column() == memo4Fields.at(i))
        {
            switch (role)
            {
            case Qt::DisplayRole:
                tempDateArray = value.toByteArray();
                tempDateArray = QByteArray::fromHex(tempDateArray);

                l = *(quint32 *)tempDateArray.data();

                value = l;

                break;
            case Qt::TextAlignmentRole:
                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                break;
            case Qt::TextColorRole:
                tempByteArray.append(memo4FieldColorString);
                tempByteArray = QByteArray::fromHex(tempByteArray);
                r = tempByteArray.at(0);
                g = tempByteArray.at(1);
                b = tempByteArray.at(2);
                QColor tempColor(r,g,b);
                value = qVariantFromValue(tempColor);
                break;
            }
        }
    }
    //QList<int> generalFields;
    for (i=0;i<generalFields.count();i++)
    {
        if (index.column() == generalFields.at(i))
        {
            switch (role)
            {
            case Qt::DisplayRole:
                break;
            case Qt::TextAlignmentRole:
                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                break;
            case Qt::TextColorRole:
                tempByteArray.append(generalFieldColorString);
                tempByteArray = QByteArray::fromHex(tempByteArray);
                r = tempByteArray.at(0);
                g = tempByteArray.at(1);
                b = tempByteArray.at(2);
                QColor tempColor(r,g,b);
                value = qVariantFromValue(tempColor);
                break;
            }
        }
    }
    return value;
}
Example #20
0
bool RawData::endsWith(const QVariant &data) const
{
    return mByteArray.endsWith(data.toByteArray());
}
Example #21
0
static bool variantToString(const QVariant &arg, QString &out)
{
    int argType = arg.userType();

    if (argType == QVariant::StringList) {
        out += QLatin1Char('{');
        const QStringList list = arg.toStringList();
        for (const QString &item : list)
            out += QLatin1Char('\"') + item + QLatin1String("\", ");
        if (!list.isEmpty())
            out.chop(2);
        out += QLatin1Char('}');
    } else if (argType == QVariant::ByteArray) {
        out += QLatin1Char('{');
        QByteArray list = arg.toByteArray();
        for (int i = 0; i < list.count(); ++i) {
            out += QString::number(list.at(i));
            out += QLatin1String(", ");
        }
        if (!list.isEmpty())
            out.chop(2);
        out += QLatin1Char('}');
    } else if (argType == QVariant::List) {
        out += QLatin1Char('{');
        const QList<QVariant> list = arg.toList();
        for (const QVariant &item : list) {
            if (!variantToString(item, out))
                return false;
            out += QLatin1String(", ");
        }
        if (!list.isEmpty())
            out.chop(2);
        out += QLatin1Char('}');
    } else if (argType == QMetaType::Char || argType == QMetaType::Short || argType == QMetaType::Int
               || argType == QMetaType::Long || argType == QMetaType::LongLong) {
        out += QString::number(arg.toLongLong());
    } else if (argType == QMetaType::UChar || argType == QMetaType::UShort || argType == QMetaType::UInt
               || argType == QMetaType::ULong || argType == QMetaType::ULongLong) {
        out += QString::number(arg.toULongLong());
    } else if (argType == QMetaType::Double) {
        out += QString::number(arg.toDouble());
    } else if (argType == QMetaType::Bool) {
        out += QLatin1String(arg.toBool() ? "true" : "false");
    } else if (argType == qMetaTypeId<QDBusArgument>()) {
        argToString(qvariant_cast<QDBusArgument>(arg), out);
    } else if (argType == qMetaTypeId<QDBusObjectPath>()) {
        const QString path = qvariant_cast<QDBusObjectPath>(arg).path();
        out += QLatin1String("[ObjectPath: ");
        out += path;
        out += QLatin1Char(']');
    } else if (argType == qMetaTypeId<QDBusSignature>()) {
        out += QLatin1String("[Signature: ") + qvariant_cast<QDBusSignature>(arg).signature();
        out += QLatin1Char(']');
    } else if (argType == qMetaTypeId<QDBusUnixFileDescriptor>()) {
        out += QLatin1String("[Unix FD: ");
        out += QLatin1String(qvariant_cast<QDBusUnixFileDescriptor>(arg).isValid() ? "valid" : "not valid");
        out += QLatin1Char(']');
    } else if (argType == qMetaTypeId<QDBusVariant>()) {
        const QVariant v = qvariant_cast<QDBusVariant>(arg).variant();
        out += QLatin1String("[Variant");
        int vUserType = v.userType();
        if (vUserType != qMetaTypeId<QDBusVariant>()
                && vUserType != qMetaTypeId<QDBusSignature>()
                && vUserType != qMetaTypeId<QDBusObjectPath>()
                && vUserType != qMetaTypeId<QDBusArgument>())
            out += QLatin1Char('(') + QLatin1String(v.typeName()) + QLatin1Char(')');
        out += QLatin1String(": ");
        if (!variantToString(v, out))
            return false;
        out += QLatin1Char(']');
    } else if (arg.canConvert(QVariant::String)) {
        out += QLatin1Char('\"') + arg.toString() + QLatin1Char('\"');
    } else {
        out += QLatin1Char('[');
        out += QLatin1String(arg.typeName());
        out += QLatin1Char(']');
    }

    return true;
}
Example #22
0
int RawData::indexOf(const QVariant &data, int from) const
{
    return mByteArray.indexOf(data.toByteArray(), from);
}
Example #23
0
QT_BEGIN_NAMESPACE

static void copyArgument(void *to, int id, const QVariant &arg)
{
    if (id == arg.userType()) {
        switch (id) {
        case QVariant::Bool:
            *reinterpret_cast<bool *>(to) = arg.toBool();
            return;

        case QMetaType::UChar:
            *reinterpret_cast<uchar *>(to) = arg.value<uchar>();
            return;

        case QMetaType::Short:
            *reinterpret_cast<short *>(to) = arg.value<short>();
            return;

        case QMetaType::UShort:
            *reinterpret_cast<ushort *>(to) = arg.value<ushort>();
            return;

        case QVariant::Int:
            *reinterpret_cast<int *>(to) = arg.toInt();
            return;

        case QVariant::UInt:
            *reinterpret_cast<uint *>(to) = arg.toUInt();
            return;

        case QVariant::LongLong:
            *reinterpret_cast<qlonglong *>(to) = arg.toLongLong();
            return;

        case QVariant::ULongLong:
            *reinterpret_cast<qulonglong *>(to) = arg.toULongLong();
            return;

        case QVariant::Double:
            *reinterpret_cast<double *>(to) = arg.toDouble();
            return;

        case QVariant::String:
            *reinterpret_cast<QString *>(to) = arg.toString();
            return;

        case QVariant::ByteArray:
            *reinterpret_cast<QByteArray *>(to) = arg.toByteArray();
            return;

        case QVariant::StringList:
            *reinterpret_cast<QStringList *>(to) = arg.toStringList();
            return;
        }

        if (id == QDBusMetaTypeId::variant) {
            *reinterpret_cast<QDBusVariant *>(to) = arg.value<QDBusVariant>();
            return;
        } else if (id == QDBusMetaTypeId::objectpath) {
            *reinterpret_cast<QDBusObjectPath *>(to) = arg.value<QDBusObjectPath>();
            return;
        } else if (id == QDBusMetaTypeId::signature) {
            *reinterpret_cast<QDBusSignature *>(to) = arg.value<QDBusSignature>();
            return;
        }

        // those above are the only types possible
        // the demarshaller code doesn't demarshall anything else
        qFatal("Found a decoded basic type in a D-Bus reply that shouldn't be there");
    }

    // if we got here, it's either an un-dermarshalled type or a mismatch
    if (arg.userType() != QDBusMetaTypeId::argument) {
        // it's a mismatch
        //qWarning?
        return;
    }

    // is this type registered?
    const char *userSignature = QDBusMetaType::typeToSignature(id);
    if (!userSignature || !*userSignature) {
        // type not registered
        //qWarning?
        return;
    }

    // is it the same signature?
    QDBusArgument dbarg = arg.value<QDBusArgument>();
    if (dbarg.currentSignature() != QLatin1String(userSignature)) {
        // not the same signature, another mismatch
        //qWarning?
        return;
    }

    // we can demarshall
    QDBusMetaType::demarshall(dbarg, id, to);
}
Example #24
0
int RawData::lastIndexOf(const QVariant &data) const
{
    return mByteArray.lastIndexOf(data.toByteArray());
}
Example #25
0
void KexiBlobTableEdit::handleCopyAction(const QVariant& value, const QVariant& visibleValue)
{
    Q_UNUSED(visibleValue);
    executeCopyAction(value.toByteArray());
}
Example #26
0
QScriptValue RawData::prepend(const QVariant &data)
{
    mByteArray.prepend(data.toByteArray());

    return thisObject();
}
Example #27
0
void DXAudioInputRegistrar::setDeviceChoice(const QVariant &choice, Settings &s) {
	s.qbaDXInput = choice.toByteArray();
}
Example #28
0
QScriptValue RawData::setData(const QVariant &data)
{
    mByteArray = data.toByteArray();

    return thisObject();
}
Example #29
0
bool DomConvenience::variantToElement(const QVariant& v, QDomElement& e)
{
	bool ok = true;

	clearAttributes(e);

	switch (v.type())
	{
		case QVariant::String:
			e.setTagName("string");
			e.setAttribute("value", v.toString());
			break;
#if 0
		case QVariant::CString:
			e.setTagName("string");
			e.setAttribute("value", v.toString());
			break;
#endif
		case QVariant::Int:
			e.setTagName("int");
			e.setAttribute("value", v.toInt());
			break;
		case QVariant::UInt:
			e.setTagName("uint");
			e.setAttribute("value", v.toUInt());
			break;
		case QVariant::Double:
			e.setTagName("double");
			e.setAttribute("value", v.toDouble());
			break;
		case QVariant::Bool:
			e.setTagName("bool");
			e.setAttribute("value", boolString(v.toBool()));
			break;
		case QVariant::Color:
		{
			e.setTagName("color");
			QColor color = v.value<QColor>();
			e.setAttribute("red", color.red());
			e.setAttribute("green", color.green());
			e.setAttribute("blue", color.blue());
		}
			break;
		case QVariant::Pen:
		{
			e.setTagName("pen");
			QPen pen = v.value<QPen>();
			e.setAttribute("red", pen.color().red());
			e.setAttribute("green", pen.color().green());
			e.setAttribute("blue", pen.color().blue());
			e.setAttribute("style", pen.style());
			e.setAttribute("cap", pen.capStyle());
			e.setAttribute("join", pen.joinStyle());
		}
			break;
		case QVariant::Brush:
		{
			e.setTagName("brush");
			QBrush brush = v.value<QBrush>();
			e.setAttribute("red", brush.color().red());
			e.setAttribute("green", brush.color().green());
			e.setAttribute("blue", brush.color().blue());
			e.setAttribute("style", brush.style());
		}
			break;
		case QVariant::Point:
		{
			e.setTagName("point");
			QPoint point = v.toPoint();
			e.setAttribute("x", point.x());
			e.setAttribute("y", point.y());
		}
			break;
		case QVariant::Rect:
		{
			e.setTagName("rect");
			QRect rect = v.toRect();
			e.setAttribute("x", rect.x());
			e.setAttribute("y", rect.y());
			e.setAttribute("width", rect.width());
			e.setAttribute("height", rect.height());
		}
			break;
		case QVariant::Size:
		{
			e.setTagName("size");
			QSize qsize = v.toSize();
			e.setAttribute("width", qsize.width());
			e.setAttribute("height", qsize.height());
		}
			break;
		case QVariant::Font:
		{
			e.setTagName("font");
			QFont f(v.value<QFont>());
			e.setAttribute("family", f.family());
			e.setAttribute("pointsize", f.pointSize());
			e.setAttribute("bold", boolString(f.bold()));
			e.setAttribute("italic", boolString(f.italic()));
			e.setAttribute("underline", boolString(f.underline()));
			e.setAttribute("strikeout", boolString(f.strikeOut()));
		}
			break;
		case QVariant::SizePolicy:
		{
			e.setTagName("sizepolicy");
			QSizePolicy sp(v.value<QSizePolicy>());
			e.setAttribute("hsizetype", sp.horData());
			e.setAttribute("vsizetype", sp.verData());
			e.setAttribute("horstretch", sp.horStretch());
			e.setAttribute("verstretch", sp.verStretch());
		}
			break;
		case QVariant::Cursor:
			e.setTagName("cursor");
			e.setAttribute("shape", v.value<QCursor>().shape());
			break;

		case QVariant::StringList:
		{
			e.setTagName("stringlist");
			int32_t j;

			QDomNode n;
			QDomNodeList stringNodeList = e.elementsByTagName("string");
			QDomElement stringElem;
			QStringList stringList = v.toStringList();
			QStringList::Iterator it = stringList.begin();

			for (j = 0;
				 ((j < (int32_t)stringNodeList.length()) && (it != stringList.end()));
				 j++)
			{
				// get the current string element
				stringElem = stringNodeList.item(j).toElement();

				// set it to the current string
				variantToElement(QVariant(*it), stringElem);

				// iterate to the next string
				++it;
			}

			// more nodes in previous stringlist then current, remove excess nodes
			if (stringNodeList.count() > stringList.count())
			{
				while (j < (int32_t)stringNodeList.count())
					e.removeChild(stringNodeList.item(j).toElement());
			}
			else if (j < (int32_t)stringList.count())
			{
				while (it != stringList.end())
				{
					// create a new element
					stringElem = m_doc.createElement("string");

					// set it to the currentstring
					variantToElement(QVariant(*it), stringElem);

					// append it to the current element
					e.appendChild(stringElem);

					// iterate to the next string
					++it;
				}
			}
		}
			break;

		case QVariant::KeySequence:
			e.setTagName("key");
			e.setAttribute("sequence", (QString)v.value<QKeySequence>().toString());
			break;

		case QVariant::ByteArray: // this is only for [u]int64_t
		{
			e.setTagName("data");

			// set the value
			e.setAttribute("value", getStringFromByteArray(v.toByteArray()));
		}
			break;

		default:
			qWarning("Don't know how to persist variant of type: %s (%d)!",
					 v.typeName(), v.type());
			ok = false;
			break;
	}

	return ok;
}
bool XQCentralRepositoryUtilsPrivate::createKey(const XQCentralRepositorySettingsKey& key, const QVariant& value)
{
    CCentralRepositoryHandler* handler = m_settingsManagerPrivate.cenRepHandlerInstance(key.uid());

    if (handler)
    {
        switch (value.type())
        {
        case QVariant::Int:
        {
            m_settingsManagerPrivate.iError = handler->createKey(key.key(), value.toInt());
            break;
        }
        case QVariant::Double:
        {
            m_settingsManagerPrivate.iError = handler->createKey(key.key(), value.toDouble());
            break;
        }
        case QVariant::String:
        {
            m_settingsManagerPrivate.iError = handler->createKey(key.key(), TPtrC16(reinterpret_cast<const TUint16*>(value.toString().utf16())));
            break;
        }
        case QVariant::ByteArray:
        {
            m_settingsManagerPrivate.iError = handler->createKey(key.key(), TPtrC8((TUint8*)(value.toByteArray().constData())));
            break;
        }
        default:
        {
            m_settingsManagerPrivate.iError = KErrArgument;
            break;
        }
        }
    }
    else
    {
        m_settingsManagerPrivate.iError = XQSettingsManager::UnknownError;
    }
    return m_settingsManagerPrivate.iError == KErrNone;
}