void WaitZarInstance::loadProperties()
{
    //Add our properties to a proplist
    PropertyList proplist;
    proplist.push_back (_waitzar_encoding_prop);
    proplist.push_back (_waitzar_encoding_unicode_prop);
    proplist.push_back (_waitzar_encoding_zawgyi_prop);
    proplist.push_back (_waitzar_encoding_wininnwa_prop);

    //Now, register these properties
    register_properties(proplist);

    //Set tooltips
    _waitzar_encoding_prop.set_tip (_("The encoding of the text WaitZar outputs. Change this only if you know what you're doing."));
    _waitzar_encoding_unicode_prop.set_tip (_("The encoding as defined in Unicode 5.1 and later. The default & recommended option."));
    update_property (_waitzar_encoding_unicode_prop);
    _waitzar_encoding_zawgyi_prop.set_tip (_("The encoding used by the Zawgyi-One font, a popular font on the web which conflicts with Unicode."));
    update_property (_waitzar_encoding_zawgyi_prop);
    _waitzar_encoding_wininnwa_prop.set_tip (_("The encoding used by the Win Innwa font family (inc. Win Kalaw), a popular legacy font which conflicts with ASCII."));
    update_property (_waitzar_encoding_wininnwa_prop);

    //Finally, double-check the label... although this really shouldn't change.
    String newLbl = "";
    int encoding = model->getOutputEncoding();
    if (encoding == ENCODING_UNICODE)
	    newLbl = "UNI";
    else if (encoding == ENCODING_ZAWGYI)
	newLbl = "ZG";
    else if (encoding == ENCODING_WININNWA)
	newLbl = "WI";
    else
	newLbl = "??";
    _waitzar_encoding_prop.set_label (newLbl);
    update_property (_waitzar_encoding_prop);
}
PyObject *
PyIMEngine::py_register_properties (PyIMEngineObject *self, PyObject *args)
{
	PyObject *props = NULL;
	PropertyList proplist;
	int i;

	if (!PyArg_ParseTuple (args, "O:register_properties", &props))
		return NULL;

	if (PyList_Check (props)) {
		for (i = 0; i < PyList_Size (props); i++) {
			PyObject *prop = PyList_GetItem (props, i);
			proplist.push_back (PyProperty_AsProperty (prop));
		}
	}
	else if (PyTuple_Check (props)) {
		for (i = 0; i < PyTuple_Size (props); i++) {
			PyObject *prop = PyTuple_GetItem (props, i);
			proplist.push_back (PyProperty_AsProperty (prop));
		}

	}
	else {
		PyErr_SetString (PyExc_TypeError, "the argument must be a list or a tuple that contains propertys");
		return NULL;
	}

	self->engine.register_properties (proplist);

	Py_INCREF (Py_None);
	return Py_None;
}
Пример #3
0
    void Action::listProperties(PropertyList& list, bool self, bool child)
    {
        Bindable::listProperties(list);

        list.push_back("ActionName");
        list.push_back("ParentActionSchemaName");
    }
Пример #4
0
PropertyList CUnitDiskUIHandler::GetPropertyList(CDiskObjectPtr obj) const
{
	PropertyList propList;
	PropertyListItem propItem;
	WTL::CString strBuffer;
	CUnitDiskObjectPtr unitDisk = 
		boost::dynamic_pointer_cast<CUnitDiskObject>(obj);
	CUnitDiskInfoHandlerPtr handler = unitDisk->GetInfoHandler();
	CHDDDiskInfoHandler *pHDDHandler = 
		dynamic_cast<CHDDDiskInfoHandler*>(handler.get());
	if ( pHDDHandler != NULL )
	{
		// TODO : String resources
		propItem.strName.LoadString( IDS_UIHANDLER_PROPERTY_MODEL );
		propItem.strValue = pHDDHandler->GetModelName();
		propItem.strToolTip.LoadString( IDS_UIHANDLER_PROPERTY_MODEL_TOOLTIP );
		propList.push_back( propItem );

		propItem.strName.LoadString( IDS_UIHANDLER_PROPERTY_SERIALNO );
		propItem.strValue = pHDDHandler->GetSerialNo();
		propItem.strToolTip.LoadString( IDS_UIHANDLER_PROPERTY_SERIALNO_TOOLTIP );
		propList.push_back( propItem );
	}
	return propList;
}
Пример #5
0
void
SunPyInstance::initialize_all_properties ()
{
    PropertyList proplist;

    proplist.push_back (_status_property);
    proplist.push_back (_letter_property);
    proplist.push_back (_punct_property);

    register_properties (proplist);
    refresh_all_properties ();
}
Пример #6
0
Layer::PropertyList
TimeInstantLayer::getProperties() const
{
    PropertyList list = SingleColourLayer::getProperties();
    list.push_back("Plot Type");
    return list;
}
Пример #7
0
// Get XML for a new form from the widget box. Change objectName/geometry
// properties to be suitable for new forms
static QString xmlFromWidgetBox(const QDesignerFormEditorInterface *core, const QString &className, const QString &objectName)
{
    typedef QList<DomProperty*> PropertyList;

    QDesignerWidgetBoxInterface::Widget widget;
    const bool found = QDesignerWidgetBox::findWidget(core->widgetBox(), className, QString(), &widget);
    if (!found)
        return QString();
    QScopedPointer<DomUI> domUI(QDesignerWidgetBox::xmlToUi(className, widget.domXml(), false));
    if (domUI.isNull())
        return QString();
    domUI->setAttributeVersion(QLatin1String("4.0"));
    DomWidget *domWidget = domUI->elementWidget();
    if (!domWidget)
        return QString();
    // Properties: Remove the "objectName" property in favour of the name attribute and check geometry.
    domWidget->setAttributeName(objectName);
    const QString geometryProperty = QLatin1String("geometry");
    const QString objectNameProperty  = QLatin1String("objectName");
    PropertyList properties = domWidget->elementProperty();
    for (PropertyList::iterator it = properties.begin(); it != properties.end(); ) {
        DomProperty *property = *it;
        if (property->attributeName() == objectNameProperty) { // remove  "objectName"
            it = properties.erase(it);
            delete property;
        } else {
            if (property->attributeName() == geometryProperty) { // Make sure form is at least 400, 300
                if (DomRect *geom = property->elementRect()) {
                    if (geom->elementWidth() < NewFormWidth)
                        geom->setElementWidth(NewFormWidth);
                    if (geom->elementHeight() < NewFormHeight)
                        geom->setElementHeight(NewFormHeight);
                }
            }
            ++it;
        }
    }
    // Add a window title property
    DomString *windowTitleString = new DomString;
    windowTitleString->setText(objectName);
    DomProperty *windowTitleProperty = new DomProperty;
    windowTitleProperty->setAttributeName(QLatin1String("windowTitle"));
    windowTitleProperty->setElementString(windowTitleString);
    properties.push_back(windowTitleProperty);
    // ------
    domWidget->setElementProperty(properties);
    // Embed in in DomUI and get string. Omit the version number.
    domUI->setElementClass(objectName);

    QString rc;
    { // Serialize domUI
        QXmlStreamWriter writer(&rc);
        writer.setAutoFormatting(true);
        writer.setAutoFormattingIndent(1);
        writer.writeStartDocument();
        domUI->write(writer);
        writer.writeEndDocument();
    }
    return rc;
}
PropertyList OpenCvLuxPlugin::supported()
{
	PropertyList props;
	props.push_back(VehicleProperty::ExteriorBrightness);
	
	return props;
}
void PropertyHolder::BuildPropertyList(PropertyList& output, const IRI& iri) const
{
    if ( iri.IsEmpty() )
        return;
    
    for ( auto& i : _properties )
    {
        if ( i->PropertyIdentifier() == iri || i->HasExtensionWithIdentifier(iri) )
            output.push_back(i);
    }
}
Пример #10
0
void
ArrayInstance::initialize_properties ()
{
    PropertyList proplist;

    proplist.push_back(m_factory->m_status_property);
    proplist.push_back(m_factory->m_letter_property);

    register_properties (proplist);

    refresh_status_property();
    refresh_letter_property();
}
Пример #11
0
PropertyList CEmptyDiskUIHandler::GetPropertyList(CDiskObjectPtr obj) const
{
	PropertyList propList;
	PropertyListItem propItem;

	// TODO : String resources
	propItem.strName.LoadString( IDS_UIHANDLER_PROPERTY_MODEL );
	propItem.strValue.LoadString(IDS_UNIDEV_TYPE_DISK_EMPTY);
	propItem.strToolTip.LoadString(IDS_UNIDEV_TYPE_DISK_EMPTY);
	propList.push_back( propItem );

	return propList;
}
Пример #12
0
PropertyList CRAID4DiskUIHandler::GetPropertyList(CDiskObjectPtr obj) const
{
	PropertyList propList;
	PropertyListItem propItem;
	WTL::CString strBuffer;

	//propItem[0] = _T("Binding type");
	propItem.strName.LoadString( IDS_UIHANDLER_PROPERTY_NUM_BOUND_DISK );
	strBuffer.Format( _T("%d"), obj->GetDiskCountInBind() );
	propItem.strValue = strBuffer;
	propItem.strToolTip.LoadString( IDS_UIHANDLER_PROPERTY_NUM_BOUND_DISK_TOOLTIP );
	propList.push_back( propItem );
	return propList;	
}
void BluemonkeySink::getHistory(QStringList properties, QDateTime begin, QDateTime end, QScriptValue cbFunction)
{
	double b = (double)begin.toMSecsSinceEpoch() / 1000.0;
	double e = (double)end.toMSecsSinceEpoch() / 1000.0;
	AsyncRangePropertyRequest request;
	request.timeBegin = b;
	request.timeEnd = e;

	PropertyList reqlist;

	foreach(QString prop, properties)
	{
		reqlist.push_back(prop.toStdString());
	}
Пример #14
0
void
HangulInstance::register_all_properties()
{
    PropertyList proplist;

    if (use_ascii_mode()) {
	if (m_hangul_mode) {
	    hangul_mode.set_label("한");
	} else {
	    hangul_mode.set_label("A");
	}
	proplist.push_back(hangul_mode);
    }

    if (m_factory->m_hanja_mode) {
	hanja_mode.set_icon(SCIM_HANGUL_ICON_ON);
    } else {
	hanja_mode.set_icon(SCIM_HANGUL_ICON_OFF);
    }
    hanja_mode.set_label(_("Hanja Lock"));
    proplist.push_back(hanja_mode);

    register_properties(proplist);
}
Пример #15
0
PropertyList CMirDiskUIHandler::GetPropertyList(CDiskObjectPtr obj) const
{
	PropertyList propList;
	PropertyListItem propItem;
	WTL::CString strBuffer;
	CMirDiskObjectPtr mirDisk = 
		boost::dynamic_pointer_cast<CMirDiskObject>(obj);

	propItem.strName.LoadString( IDS_UIHANDLER_PROPERTY_DIRTY );
	if ( mirDisk->IsDirty() )
        propItem.strValue.LoadString( IDS_UIHANDLER_PROPERTY_DIRTY_TRUE );
	else
		propItem.strValue.LoadString( IDS_UIHANDLER_PROPERTY_DIRTY_FALSE );
	propItem.strToolTip.LoadString( IDS_UIHANDLER_PROPERTY_DIRTY_TOOLTIP );
	propList.push_back( propItem );
	return propList;	
}
Пример #16
0
void
HangulInstance::register_all_properties()
{
    PropertyList proplist;

    const char* layout_label;
    if (m_factory->m_keyboard_layout == "2") {
	layout_label = _("2bul");
    } else if (m_factory->m_keyboard_layout == "32") {
	layout_label = _("3bul 2bul-shifted");
    } else if (m_factory->m_keyboard_layout == "3f") {
	layout_label = _("3bul Final");
    } else if (m_factory->m_keyboard_layout == "39") {
	layout_label = _("3bul 390");
    } else if (m_factory->m_keyboard_layout == "3s") {
	layout_label = _("3bul No-Shift");
    } else if (m_factory->m_keyboard_layout == "3y") {
	layout_label = _("3bul Yetgeul");
    }
    keyboard_layout.set_label(layout_label);
    proplist.push_back(keyboard_layout);
    proplist.push_back(keyboard_layout_2);
    proplist.push_back(keyboard_layout_32);
    proplist.push_back(keyboard_layout_3f);
    proplist.push_back(keyboard_layout_39);
    proplist.push_back(keyboard_layout_3s);
    proplist.push_back(keyboard_layout_3y);

    if (use_ascii_mode()) {
	if (m_hangul_mode) {
	    hangul_mode.set_label("한");
	} else {
	    hangul_mode.set_label("A");
	}
	proplist.push_back(hangul_mode);
    }

    if (is_hanja_mode()) {
	hanja_mode.set_label("漢");
    } else {
	hanja_mode.set_label("韓");
    }
    proplist.push_back(hanja_mode);

    register_properties(proplist);
}
bool TestPlugin::testCoreUpdateSupported()
{
	bool success = false;

	PropertyList toAdd;
	toAdd.push_back(VehicleProperty::ClutchStatus);

	routingEngine->updateSupported(toAdd,PropertyList());

	PropertyList supported = routingEngine->supported();

	success = ListPlusPlus<VehicleProperty::Property>(&supported).contains(VehicleProperty::ClutchStatus);

	PropertyList toRemove = toAdd;

	routingEngine->updateSupported(PropertyList(),toRemove);

	supported = routingEngine->supported();

	success &= !ListPlusPlus<VehicleProperty::Property>(&supported).contains(VehicleProperty::ClutchStatus);

	return success;
}
Пример #18
0
      /// <summary>Reads the entire tag and advances the iterator</summary>
      /// <param name="pos">position of opening bracket</param>
      /// <returns></returns>
      /// <exception cref="Logic::Language::AlgorithmException">Unable to read tag</exception>
      /// <exception cref="Logic::Language::RichTextException">Closing tag doesn't match currently open tag</exception>
      /// <remarks>Advances the iterator to the last character of the tag, so Parse() loop advances correctly to the next character</remarks>
      RichStringParser::RichTag  RichStringParser::ReadTag(CharIterator& pos)
      {
         wsmatch matches;

         // BASIC: Open/Close Tag without properties
         if (regex_search(pos, Input.cend(), matches, IsBasicTag))
         {
            // Identify open/close
            bool opening = (pos[1] != '/');
            wstring name = matches[1].str();
            
            // Identify type
            switch (TagType type = IdentifyTag(name))
            {
            // Title: Return title
            case TagType::Author:
            case TagType::Select:
            case TagType::Title:
               // Match [title](text)[/title]
               if (!regex_search(pos, Input.cend(), matches, type == TagType::Title  ? IsTitleDefinition
                                                           : type == TagType::Author ? IsAuthorDefinition
                                                                                     : IsButtonDefinition)) 
                  throw RichTextException(HERE, VString(L"Invalid [%s] tag", ::GetString(type).c_str()));

               // Advance iterator.  Return title text
               pos += matches[0].length()-1;
               return RichTag(type, matches[1].str());

            // Default: Advance iterator to ']' + return
            default:
               pos += matches[0].length()-1;
               return RichTag(type, opening);
            }
         }
         // COMPLEX: Open tag with properties
         else if (regex_search(pos, Input.cend(), matches, IsOpeningTag))  // Match tag name, identify start/end of properties
         {
            PropertyList props;

            // Match properties
            for (wsregex_iterator it(pos+matches[1].length(), pos+matches[0].length(), IsTagProperty), eof; it != eof; ++it)
               // Extract {name,value} from 2st/3rd match
               props.push_back( Property(it->str(1), it->str(2)) );
            
            // Advance Iterator + create tag
            pos += matches[0].length()-1;
            auto tag = RichTag(IdentifyTag(matches[1].str()), props);

            // Button: Extract text
            if (tag.Type == TagType::Select)
            {
               if (!regex_search(pos, Input.cend(), matches, IsButtonText))
                  throw RichTextException(HERE, GuiString(L"Invalid [select] tag"));

               // Extract text + Advance Iterator
               tag.Text = matches[1].str();
               pos += matches[0].length()-1;
            }

            // Return tag
            return tag;
         }

         // Error: No match
         throw AlgorithmException(HERE, L"Cannot read previously matched opening tag");
      }
Пример #19
0
int main(int argc, char* argv[])
{
    String config_name("simple");
    String display_name;
    bool daemon = false;
    bool should_resident = true;

    //parse command options
    int i = 1;
    while (i < argc) {
        if (String("-l") == argv[i] || String("--list") == argv[i]) {
            std::cout << "\n";
            std::cout << "Available Config module:\n";
            // get config module list
            std::vector<String> config_list;
            scim_get_config_module_list(config_list);
            config_list.push_back("dummy");
            std::vector<String>::iterator it = config_list.begin();
            for (; it != config_list.end(); ++it) {
                std::cout << "    " << *it << "\n";
            }
            return 0;
        }
        else if (String("-c") == argv[i] || String("--config") == argv[i]) {
            if (++i >= argc) {
                std::cerr << "no argument for option " << argv[i-1] << "\n";
                return -1;
            }
            config_name = argv[i];
        }
        else if (String("-h") == argv[i] || String("--help") == argv[i]) {
            std::cout << "Usage: " << argv [0] << " [option]...\n\n"
                      << "The options are: \n"
                      << "  --display DISPLAY    Run on display DISPLAY.\n"
                      << "  -l, --list           List all of available config modules.\n"
                      << "  -c, --config NAME    Uses specified Config module.\n"
                      << "  -d, --daemon         Run " << argv [0] << " as a daemon.\n"
                      << "  -ns, --no-stay       Quit if no connected client.\n"
                      << "  -h, --help           Show this help message.\n";
            return 0;
        }
        else if (String("-d") == argv[i] || String("--daemon") == argv[i]) {
            daemon = true;
        }
        else if (String("-ns") == argv[i] || String("--no-stay") == argv[i]) {
            should_resident = false;
        }
        else if (String("--display") == argv[i]) {
            if (++i >= argc) {
                std::cerr << "No argument for option " << argv[i-1] << "\n";
                return -1;
            }
            display_name = argv[i];
        }
        else {
            std::cerr << "Invalid command line option: " << argv[i] << "\n";
            return -1;
        }
        ++i;
    }

    // Make up DISPLAY env.
    if (display_name.length()) {
        setenv("DISPLAY", display_name.c_str(), 1);
    }

    if (config_name == "dummy") {
        _config = new DummyConfig();
    }
    else {
        _config_module = new ConfigModule(config_name);
        if (!_config_module || !_config_module->valid()) {
            std::cerr << "Can not load " << config_name << " Config module.\n";
            return -1;
        }
        _config = _config_module->create_config();
    }

    if (_config.null()) {
        std::cerr << "Failed to create instance from " << config_name << " Config module.\n";
        return -1;
    }


    signal(SIGTERM, niam);
    signal(SIGINT, niam);

    if (!initialize_panel_agent(config_name, display_name, should_resident)) {
        std::cerr << "Failed to initialize PanelAgent.\n";
        return -1;
    }

    if (daemon)
        scim_daemon();

    if (!run_panel_agent()) {
        std::cerr << "Failed to run Socket Server!\n";
        return -1;
    }

    start_auto_start_helpers();

    DBus::default_dispatcher = &dispatcher;

    DBus::Connection conn = DBus::Connection::SessionBus();
    conn.request_name("org.kde.impanel.inputmethod");

    panel = new Panel(conn);

    /// add initial helper as helper property
    PropertyList props;
    std::vector<HelperInfo>::const_iterator it = _helper_list.begin();
    std::vector<HelperInfo>::const_iterator end = _helper_list.end();
    while (it != end) {
        if ((it->option & SCIM_HELPER_STAND_ALONE)
                && !(it->option & SCIM_HELPER_AUTO_START)) {
            props.push_back(Property(String(helper_prop_prefix) + it->uuid,
                                     it->name,
                                     it->icon,
                                     it->description));
        }
        ++it;
    }
    if (props.size()) {
        helper_props_map[0] = props;
    }

    dispatcher.enter();

    delete panel;

    return 0;
}
void ExampleSink::supportedChanged(const PropertyList & supportedProperties)
{
	DebugOut()<<"Support changed!"<<endl;

	if(contains(supportedProperties, VehicleProperty::VehicleSpeed))
	{
		AsyncPropertyRequest velocityRequest;
		velocityRequest.property = VehicleProperty::VehicleSpeed;
		velocityRequest.completed = [](AsyncPropertyReply* reply)
		{
			if(!reply->success)
				DebugOut(DebugOut::Error)<<"Velocity Async request failed ("<<reply->error<<")"<<endl;
			else
				DebugOut(0)<<"Velocity Async request completed: "<<reply->value->toString()<<endl;
			delete reply;
		};

		routingEngine->getPropertyAsync(velocityRequest);
	}

	if(contains(supportedProperties, VehicleProperty::VIN))
	{
		AsyncPropertyRequest vinRequest;
		vinRequest.property = VehicleProperty::VIN;
		vinRequest.completed = [](AsyncPropertyReply* reply)
		{
			if(!reply->success)
				DebugOut(DebugOut::Error)<<"VIN Async request failed ("<<reply->error<<")"<<endl;
			else
				DebugOut(0)<<"VIN Async request completed: "<<reply->value->toString()<<endl;
			delete reply;
		};

		routingEngine->getPropertyAsync(vinRequest);
	}
	if(contains(supportedProperties, VehicleProperty::WMI))
	{
		AsyncPropertyRequest wmiRequest;
		wmiRequest.property = VehicleProperty::WMI;
		wmiRequest.completed = [](AsyncPropertyReply* reply)
		{
			if(!reply->success)
				DebugOut(DebugOut::Error)<<"WMI Async request failed ("<<reply->error<<")"<<endl;
			else
				DebugOut(1)<<"WMI Async request completed: "<<reply->value->toString()<<endl;
			delete reply;
		};

		routingEngine->getPropertyAsync(wmiRequest);
	}
	if(contains(supportedProperties, VehicleProperty::BatteryVoltage))
	{
		AsyncPropertyRequest batteryVoltageRequest;
		batteryVoltageRequest.property = VehicleProperty::BatteryVoltage;
		batteryVoltageRequest.completed = [](AsyncPropertyReply* reply)
		{
			if(!reply->success)
				DebugOut(DebugOut::Error)<<"BatteryVoltage Async request failed ("<<reply->error<<")"<<endl;
			else
				DebugOut(1)<<"BatteryVoltage Async request completed: "<<reply->value->toString()<<endl;
			delete reply;
		};

		routingEngine->getPropertyAsync(batteryVoltageRequest);
	}
	if(contains(supportedProperties, VehicleProperty::DoorsPerRow))
	{
		AsyncPropertyRequest doorsPerRowRequest;
		doorsPerRowRequest.property = VehicleProperty::DoorsPerRow;
		doorsPerRowRequest.completed = [](AsyncPropertyReply* reply)
		{
			if(!reply->success)
				DebugOut(DebugOut::Error)<<"Doors per row Async request failed ("<<reply->error<<")"<<endl;
			else
				DebugOut(1)<<"Doors per row: "<<reply->value->toString()<<endl;
			delete reply;
		};

		routingEngine->getPropertyAsync(doorsPerRowRequest);
	}

	if(contains(supportedProperties,VehicleProperty::AirbagStatus))
	{
		AsyncPropertyRequest airbagStatus;
		airbagStatus.property = VehicleProperty::AirbagStatus;
		airbagStatus.zoneFilter = Zone::FrontRight | Zone::FrontSide;
		airbagStatus.completed = [](AsyncPropertyReply* reply)
		{
			if(!reply->success)
			{
				DebugOut(DebugOut::Error)<<"Airbag Async request failed ("<<reply->error<<")"<<endl;
			}
			else
				DebugOut(1)<<"Airbag Status: "<<reply->value->toString()<<endl;
			delete reply;
		};

		routingEngine->getPropertyAsync(airbagStatus);
	}

	if(contains(supportedProperties, VehicleProperty::ExteriorBrightness))
	{
		AsyncPropertyRequest exteriorBrightness;
		exteriorBrightness.property = VehicleProperty::ExteriorBrightness;
		exteriorBrightness.completed = [](AsyncPropertyReply* reply)
		{
			if(!reply->success)
				DebugOut(DebugOut::Error)<<"Exterior Brightness Async request failed ("<<reply->error<<")"<<endl;
			else
				DebugOut(1)<<"Exterior Brightness: "<<reply->value->toString()<<endl;
			delete reply;
		};

		routingEngine->getPropertyAsync(exteriorBrightness);
	}

	auto getRangedCb = [](gpointer data)
	{
		AbstractRoutingEngine* routingEngine = (AbstractRoutingEngine*)data;

		AsyncRangePropertyRequest vehicleSpeedFromLastWeek;

		vehicleSpeedFromLastWeek.timeBegin = amb::Timestamp::instance()->epochTime() - 10;
		vehicleSpeedFromLastWeek.timeEnd = amb::Timestamp::instance()->epochTime();

		PropertyList requestList;
		requestList.push_back(VehicleProperty::VehicleSpeed);
		requestList.push_back(VehicleProperty::EngineSpeed);

		vehicleSpeedFromLastWeek.properties = requestList;
		vehicleSpeedFromLastWeek.completed = [](AsyncRangePropertyReply* reply)
		{
			std::list<AbstractPropertyType*> values = reply->values;
			for(auto itr = values.begin(); itr != values.end(); itr++)
			{
				auto val = *itr;
				DebugOut(1) <<"Value from past: (" << val->name << "): " << val->toString()
						   <<" time: " << val->timestamp << " sequence: " << val->sequence << endl;
			}

			delete reply;
		};

		routingEngine->getRangePropertyAsync(vehicleSpeedFromLastWeek);

		return 0;
	};

	g_timeout_add(10000, getRangedCb, routingEngine);
}
Пример #21
0
// Set a fixed size on a XML template
QString WidgetDataBase::scaleFormTemplate(const QString &xml, const QSize &size, bool fixed)
{
    typedef QList<DomProperty*> PropertyList;
    DomUI *domUI = QDesignerWidgetBox::xmlToUi(QLatin1String("Form"), xml, false);
    if (!domUI)
        return QString();
    DomWidget *domWidget = domUI->elementWidget();
    if (!domWidget)
        return QString();
    // Properties: Find/Ensure the geometry, minimum and maximum sizes properties
    const QString geometryPropertyName = QLatin1String("geometry");
    const QString minimumSizePropertyName = QLatin1String("minimumSize");
    const QString maximumSizePropertyName = QLatin1String("maximumSize");
    DomProperty *geomProperty = 0;
    DomProperty *minimumSizeProperty = 0;
    DomProperty *maximumSizeProperty = 0;

    PropertyList properties = domWidget->elementProperty();
    const PropertyList::const_iterator cend = properties.constEnd();
    for (PropertyList::const_iterator it = properties.constBegin(); it != cend; ++it) {
        const QString name = (*it)->attributeName();
        if (name == geometryPropertyName) {
            geomProperty = *it;
        } else {
            if (name == minimumSizePropertyName) {
                minimumSizeProperty = *it;
            } else {
                if (name == maximumSizePropertyName)
                    maximumSizeProperty = *it;
            }
        }
    }
    if (!geomProperty) {
        geomProperty = new DomProperty;
        geomProperty->setAttributeName(geometryPropertyName);
        geomProperty->setElementRect(new DomRect);
        properties.push_front(geomProperty);
    }
    if (fixed) {
        if (!minimumSizeProperty) {
            minimumSizeProperty = new DomProperty;
            minimumSizeProperty->setAttributeName(minimumSizePropertyName);
            minimumSizeProperty->setElementSize(new DomSize);
            properties.push_back(minimumSizeProperty);
        }
        if (!maximumSizeProperty) {
            maximumSizeProperty = new DomProperty;
            maximumSizeProperty->setAttributeName(maximumSizePropertyName);
            maximumSizeProperty->setElementSize(new DomSize);
            properties.push_back(maximumSizeProperty);
        }
    }
    // Set values of geometry, minimum and maximum sizes properties
    const int width = size.width();
    const int height = size.height();
    if (DomRect *geom = geomProperty->elementRect()) {
        geom->setElementWidth(width);
        geom->setElementHeight(height);
    }
    if (fixed) {
        if (DomSize *s = minimumSizeProperty->elementSize()) {
            s->setElementWidth(width);
            s->setElementHeight(height);
        }
        if (DomSize *s = maximumSizeProperty->elementSize()) {
            s->setElementWidth(width);
            s->setElementHeight(height);
        }
    }
    // write back
    domWidget->setElementProperty(properties);

    QString rc;
    { // serialize domUI
        QXmlStreamWriter writer(&rc);
        writer.setAutoFormatting(true);
        writer.setAutoFormattingIndent(1);
        writer.writeStartDocument();
        domUI->write(writer);
        writer.writeEndDocument();
    }

    delete domUI;
    return rc;
}
Пример #22
0
bool Audio::getSupportedProperties(PropertyList& pl)
{
    pl.push_back(ObjectDescription(new osg::StringValueObject("filename",""), std::string("Audio filename to load.")));
    pl.push_back(ObjectDescription(new osg::DoubleValueObject("volume",1.0), std::string("Audio volume.")));
    return true;
}
static int websocket_callback(struct libwebsocket_context *context,struct libwebsocket *wsi,enum libwebsocket_callback_reasons reason, void *user,void *in, size_t len)
{
	//printf("Switch: %i\n",reason);
	DebugOut(5) << __SMALLFILE__ << ":" << __LINE__ << "websocket_callback:" << reason << endl;


	switch (reason)
	{
		case LWS_CALLBACK_CLIENT_WRITEABLE:
		{
			break;
		}
		case LWS_CALLBACK_CLOSED:
		{
			sinkManager->disconnectAll(wsi);
			break;
		}
		case LWS_CALLBACK_CLIENT_RECEIVE:
		{
			break;
		}
		case LWS_CALLBACK_SERVER_WRITEABLE:
		{
			break;
		}

		case LWS_CALLBACK_RECEIVE:
		{

		}
		case LWS_CALLBACK_HTTP:
		{
			//TODO: Verify that ALL requests get sent via LWS_CALLBACK_HTTP, so we can use that instead of LWS_CALLBACK_RECIEVE
			//TODO: Do we want exceptions, or just to return an invalid json reply? Probably an invalid json reply.
			DebugOut() << __SMALLFILE__ << ":" << __LINE__ << " Requested: " << (char*)in << "\n";

			QByteArray d((char*)in,len);

			WebSocketSinkManager * manager = sinkManager;

			if(manager->expectedMessageFrames && manager->partialMessageIndex < manager->expectedMessageFrames)
			{
				manager->incompleteMessage += d;
				manager->partialMessageIndex++;
				break;
			}
			else if(manager->expectedMessageFrames && manager->partialMessageIndex == manager->expectedMessageFrames)
			{
				d = manager->incompleteMessage + d;
				manager->expectedMessageFrames = 0;
			}

			QJsonDocument doc;
			if(doBinary)
				doc = QJsonDocument::fromBinaryData(d);
			else
				doc = QJsonDocument::fromJson(d);

			if(doc.isNull())
			{
				DebugOut(DebugOut::Error)<<"Invalid message"<<endl;
				return 0;
			}

			QVariantMap call = doc.toVariant().toMap();

			string type = call["type"].toString().toStdString();
			string name = call["name"].toString().toStdString();
			string id = call["transactionid"].toString().toStdString();

			if (type == "multiframe")
			{

				manager->expectedMessageFrames = call["frames"].toInt();
				manager->partialMessageIndex = 1;
				manager->incompleteMessage = "";
			}
			else if (type == "method")
			{
				if(name == "getRanged")
				{
					QVariantMap data = call["data"].toMap();

					PropertyList propertyList;

					propertyList.push_back(data["property"].toString().toStdString());

					double timeBegin = data["timeBegin"].toDouble();
					double timeEnd = data["timeEnd"].toDouble();
					double sequenceBegin = data["sequenceBegin"].toInt();
					double sequenceEnd = data["sequenceEnd"].toInt();

					if ((timeBegin < 0 && timeEnd > 0) || (timeBegin > 0 && timeEnd < 0))
					{
						DebugOut(DebugOut::Warning)<<"Invalid time begin/end pair"<<endl;
					}
					else if ((sequenceBegin < 0 && sequenceEnd > 0) || (sequenceBegin > 0 && sequenceEnd < 0))
					{
						DebugOut(DebugOut::Warning)<<"Invalid sequence begin/end pair"<<endl;
					}
					else
					{
						sinkManager->addSingleShotRangedSink(wsi,propertyList,timeBegin,timeEnd,sequenceBegin,sequenceEnd,id);
					}
				}
				else if (name == "get")
				{
					QVariantMap data = call["data"].toMap();
					Zone::Type zone = Zone::None;
					if(data.contains("zone"))
					{
						zone = data["zone"].toInt();
					}
					sinkManager->addSingleShotSink(wsi,data["property"].toString().toStdString(),zone,id);

				}
				else if (name == "set")
				{
					QVariantMap data = call["data"].toMap();
					Zone::Type zone(Zone::None);
					if(data.contains("zone"))
					{
						zone = data["zone"].toInt();
					}
					sinkManager->setValue(wsi,data["property"].toString().toStdString(), data["value"].toString().toStdString(), zone, id);
				}
				else if (name == "subscribe")
				{
					std::string data = call["data"].toString().toStdString();
					sinkManager->addSink(wsi, data, id);

				}
				else if (name == "unsubscribe")
				{
					std::string data = call["data"].toString().toStdString();
					sinkManager->removeSink(wsi,data,id);

				}
				else if (name == "getSupportedEventTypes")
				{
					QVariantMap reply;
					QStringList list;

					PropertyList supported = sinkManager->getSupportedProperties();
					for(VehicleProperty::Property i : supported)
					{
						list.append(i.c_str());
					}

					reply["type"] = "methodReply";
					reply["name"] = "getSupportedEventTypes";
					reply["transactionid"] = id.c_str();
					reply["data"] = list;

					QByteArray replystr;

					if(doBinary)
						replystr = QJsonDocument::fromVariant(reply).toBinaryData();
					else
					{
						replystr = QJsonDocument::fromVariant(reply).toJson();
						cleanJson(replystr);
					}

					lwsWrite(wsi, replystr, replystr.length());
				}
				else
				{
					DebugOut(0)<<"Unknown method called."<<endl;
				}
			}
			break;
		}
		case LWS_CALLBACK_ADD_POLL_FD:
		{
			//printf("Adding poll %i\n",sinkManager);
			DebugOut(5) << __SMALLFILE__ <<":"<< __LINE__ << "Adding poll" << endl;
			if (sinkManager != 0)
			{
				//sinkManager->addPoll((int)(long)user);
				sinkManager->addPoll(libwebsocket_get_socket_fd(wsi));
			}
			else
			{
				DebugOut(5) << "Error, invalid sink manager!!" << endl;
			}
			break;
		}
		case LWS_CALLBACK_DEL_POLL_FD:
		{
			sinkManager->removePoll(libwebsocket_get_socket_fd(wsi));
			break;
		}
		case LWS_CALLBACK_SET_MODE_POLL_FD:
		{
			//Set the poll mode
			break;
		}
		case LWS_CALLBACK_CLEAR_MODE_POLL_FD:
		{
			//Don't handle this yet.
			break;
		}
		default:
		{
			//printf("Unhandled callback: %i\n",reason);
			DebugOut() << __SMALLFILE__ <<":"<< __LINE__ << "Unhandled callback:" << reason << "\n";
			break;
		}
	}
	return 0; 
}
void AbstractDBusInterface::handleMyMethodCall(GDBusConnection       *connection,
							 const gchar           *sender,
							 const gchar           *object_path,
							 const gchar           *interface_name,
							 const gchar           *method_name,
							 GVariant              *parameters,
							 GDBusMethodInvocation *invocation,
							 gpointer               user_data)
{

	std::string method = method_name;
	AbstractDBusInterface* iface = static_cast<AbstractDBusInterface*>(user_data);

	if(DebugOut::getDebugThreshhold() >= 6)
	{
		DebugOut(6)<<"DBus method call from: "<<sender<< " pid: " <<getPid(sender)<< " interface: "<<interface_name<<" method: "<<method<<endl;
		DebugOut(6)<<"DBus method call path: "<<object_path<<endl;
	}

	g_assert(iface);

	if(std::string(interface_name) == "org.freedesktop.DBus.Properties")
	{
		if(method == "Get")
		{
			gchar* propertyName = nullptr;
			gchar* ifaceName = nullptr;
			g_variant_get(parameters, "(ss)", &ifaceName, &propertyName);

			DebugOut(6) << "Parameter signature: " << g_variant_get_type_string(parameters) << endl;
//			DebugOut(6) << "Get property " << propertyName << " for interface " << ifaceName << endl;

			GError* error = nullptr;
			auto value = AbstractDBusInterface::getProperty(connection, sender, object_path, ifaceName, propertyName, &error, iface);
			amb::make_super(error);

			if(!value)
			{
				g_dbus_method_invocation_return_dbus_error(invocation, std::string(std::string(ifaceName)+".PropertyNotFound").c_str(), "Property not found in interface");
			}

			g_dbus_method_invocation_return_value(invocation, g_variant_new("(v)", value));
			return;
		}
		else if(method == "GetAll")
		{
			gchar* ifaceName = nullptr;
			g_variant_get(parameters, "(s)", &ifaceName);

			GVariantBuilder builder;
			g_variant_builder_init(&builder, G_VARIANT_TYPE("a{sv}"));

			auto propertyMap = iface->getProperties();

			for(auto itr : propertyMap)
			{
				auto prop = itr.second;
				GError* error = nullptr;
				auto value = AbstractDBusInterface::getProperty(connection, sender, object_path, ifaceName, prop->name().c_str(), &error, iface);
				amb::make_super(error);
				g_variant_builder_add(&builder, "{sv}", prop->name().c_str(), g_variant_new("v", value));
				//sequence
				auto sequence = AbstractDBusInterface::getProperty(connection, sender, object_path, ifaceName, std::string(prop->name()+"Sequence").c_str(), &error, iface);
				g_variant_builder_add(&builder, "{sv}", std::string(prop->name()+"Sequence").c_str(), g_variant_new("v", sequence));

				auto quality = AbstractDBusInterface::getProperty(connection, sender, object_path, ifaceName, std::string(prop->name()+"ValueQuality").c_str(), &error, iface);
				g_variant_builder_add(&builder, "{sv}", std::string(prop->name()+"ValueQuality").c_str(), g_variant_new("v", quality));

				auto freq = AbstractDBusInterface::getProperty(connection, sender, object_path, ifaceName, std::string(prop->name()+"UpdateFrequency").c_str(), &error, iface);
				g_variant_builder_add(&builder, "{sv}", std::string(prop->name()+"UpdateFrequency").c_str(), g_variant_new("v", freq));
			}

			auto time = AbstractDBusInterface::getProperty(connection, sender, object_path, ifaceName, "Time", nullptr, iface);
			auto zone = AbstractDBusInterface::getProperty(connection, sender, object_path, ifaceName, "Zone", nullptr, iface);
			g_variant_builder_add(&builder, "{sv}", "Time", g_variant_new("v", time));
			g_variant_builder_add(&builder, "{sv}", "Zone", g_variant_new("v", zone));

			g_dbus_method_invocation_return_value(invocation, g_variant_new("(a{sv})", &builder));
			return;
		}
		else if(method == "Set")
		{
			gchar* ifaceName = nullptr;
			gchar* propName = nullptr;
			GVariant* value;
			g_variant_get(parameters, "(ssv)", &ifaceName, &propName, &value);

			AbstractDBusInterface::setProperty(connection, sender, object_path, ifaceName, propName, value, nullptr, iface,
											   [&invocation, &ifaceName](bool success, AsyncPropertyReply::Error error) {
				if(success)
				{
					g_dbus_method_invocation_return_value(invocation, nullptr);
				}
				else
				{
					g_dbus_method_invocation_return_dbus_error(invocation, ifaceName, AsyncPropertyReply::errorToStr(error).c_str());
				}
			});
			return;
		}
	}
	else if(method == "GetHistory")
	{
		double beginTime = 0;
		double endTime = 0;

		g_variant_get(parameters, "(dd)", &beginTime, &endTime);

		auto propertyMap = iface->getProperties();

		PropertyList propertyList;

		for(auto itr = propertyMap.begin(); itr != propertyMap.end(); itr++)
		{
			VariantType* prop = (*itr).second;

			if(!contains(propertyList, prop->ambPropertyName()))
				propertyList.push_back(prop->ambPropertyName());
		}

		std::string ifaceName = iface->interfaceName();

		AsyncRangePropertyRequest request;

		request.properties = propertyList;
		request.timeBegin = beginTime;
		request.timeEnd = endTime;
		request.zone = iface->zone();
		//request.sourceUuid = iface->source();

		request.completed = [&invocation,&ifaceName](AsyncRangePropertyReply* r)
		{
			auto reply = amb::make_unique(r);
			if(!reply->success)
			{
				stringstream str;
				str<<"Error during request: "<<AsyncPropertyReply::errorToStr(reply->error);
				ifaceName += ".Error";
				g_dbus_method_invocation_return_dbus_error(invocation, ifaceName.c_str(), str.str().c_str());
				return;
			}

			if(!reply->values.size())
			{
				ifaceName += ".Error";
				g_dbus_method_invocation_return_dbus_error(invocation, ifaceName.c_str(), "No results");
				return;
			}

			GVariantBuilder builder;
			g_variant_builder_init(&builder, G_VARIANT_TYPE("a{svd}"));


			for(auto itr = reply->values.begin(); itr != reply->values.end(); itr++)
			{
				AbstractPropertyType* value = *itr;

				g_variant_builder_add(&builder, "{svd}", value->name.c_str(), g_variant_ref(value->toVariant()),value->timestamp);
			}

			g_dbus_method_invocation_return_value(invocation,g_variant_new("(a{svd})",&builder));
		};

		iface->re->getRangePropertyAsync(request);

		return;
	}

	g_dbus_method_invocation_return_error(invocation,G_DBUS_ERROR,G_DBUS_ERROR_UNKNOWN_METHOD, "Unknown method.");
}