Beispiel #1
0
  def IsInitialized(self, errors=None):
    """Checks if all required fields of a message are set.

    Args:
      errors:  A list which, if provided, will be populated with the field
               paths of all missing required fields.

    Returns:
      True iff the specified message has all required fields set.
    """

    # Performance is critical so we avoid HasField() and ListFields().

    for field in required_fields:
      if (field not in self._fields or
          (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
           not self._fields[field]._is_present_in_parent)):
        if errors is not None:
          errors.extend(self.FindInitializationErrors())
        return False

    for field, value in six.iteritems(self._fields):
      if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
        if field.label == _FieldDescriptor.LABEL_REPEATED:
          for element in value:
            if not element.IsInitialized():
              if errors is not None:
                errors.extend(self.FindInitializationErrors())
              return False
        elif value._is_present_in_parent and not value.IsInitialized():
          if errors is not None:
            errors.extend(self.FindInitializationErrors())
          return False

    return True
Beispiel #2
0
  def MergeFrom(self, msg):
    if not isinstance(msg, cls):
      raise TypeError(
          "Parameter to MergeFrom() must be instance of same class.")

    assert msg is not self
    self._Modified()

    fields = self._fields

    for field, value in six.iteritems(msg._fields):
      if field.label == LABEL_REPEATED:
        field_value = fields.get(field)
        if field_value is None:
          # Construct a new object to represent this field.
          field_value = field._default_constructor(self)
          fields[field] = field_value
        field_value.MergeFrom(value)
      elif field.cpp_type == CPPTYPE_MESSAGE:
        if value._is_present_in_parent:
          field_value = fields.get(field)
          if field_value is None:
            # Construct a new object to represent this field.
            field_value = field._default_constructor(self)
            fields[field] = field_value
          field_value.MergeFrom(value)
      else:
        self._fields[field] = value
Beispiel #3
0
    def IsInitialized(self, errors=None):
        """Checks if all required fields of a message are set.

    Args:
      errors:  A list which, if provided, will be populated with the field
               paths of all missing required fields.

    Returns:
      True iff the specified message has all required fields set.
    """

        # Performance is critical so we avoid HasField() and ListFields().

        for field in required_fields:
            if (field not in self._fields
                    or (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE
                        and not self._fields[field]._is_present_in_parent)):
                if errors is not None:
                    errors.extend(self.FindInitializationErrors())
                return False

        for field, value in six.iteritems(self._fields):
            if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
                if field.label == _FieldDescriptor.LABEL_REPEATED:
                    for element in value:
                        if not element.IsInitialized():
                            if errors is not None:
                                errors.extend(self.FindInitializationErrors())
                            return False
                elif value._is_present_in_parent and not value.IsInitialized():
                    if errors is not None:
                        errors.extend(self.FindInitializationErrors())
                    return False

        return True
Beispiel #4
0
    def MergeFrom(self, msg):
        if not isinstance(msg, cls):
            raise TypeError(
                "Parameter to MergeFrom() must be instance of same class.")

        assert msg is not self
        self._Modified()

        fields = self._fields

        for field, value in six.iteritems(msg._fields):
            if field.label == LABEL_REPEATED:
                field_value = fields.get(field)
                if field_value is None:
                    # Construct a new object to represent this field.
                    field_value = field._default_constructor(self)
                    fields[field] = field_value
                field_value.MergeFrom(value)
            elif field.cpp_type == CPPTYPE_MESSAGE:
                if value._is_present_in_parent:
                    field_value = fields.get(field)
                    if field_value is None:
                        # Construct a new object to represent this field.
                        field_value = field._default_constructor(self)
                        fields[field] = field_value
                    field_value.MergeFrom(value)
            else:
                self._fields[field] = value
Beispiel #5
0
 def init(self, **kwargs):
     self._cached_byte_size = 0
     self._cached_byte_size_dirty = len(kwargs) > 0
     self._fields = {}
     self._is_present_in_parent = False
     self._listener = message_listener_mod.NullMessageListener()
     self._listener_for_children = _Listener(self)
     for field_name, field_value in six.iteritems(kwargs):
         field = _GetFieldByName(message_descriptor, field_name)
         if field is None:
             raise TypeError(
                 "%s() got an unexpected keyword argument '%s'" %
                 (message_descriptor.name, field_name))
         if field.label == _FieldDescriptor.LABEL_REPEATED:
             copy = field._default_constructor(self)
             if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
                 for val in field_value:
                     copy.add().MergeFrom(val)
             else:  # Scalar
                 copy.extend(field_value)
             self._fields[field] = copy
         elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
             copy = field._default_constructor(self)
             copy.MergeFrom(field_value)
             self._fields[field] = copy
         else:
             setattr(self, field_name, field_value)
Beispiel #6
0
 def init(self, **kwargs):
   self._cached_byte_size = 0
   self._cached_byte_size_dirty = len(kwargs) > 0
   self._fields = {}
   self._is_present_in_parent = False
   self._listener = message_listener_mod.NullMessageListener()
   self._listener_for_children = _Listener(self)
   for field_name, field_value in six.iteritems(kwargs):
     field = _GetFieldByName(message_descriptor, field_name)
     if field is None:
       raise TypeError("%s() got an unexpected keyword argument '%s'" %
                       (message_descriptor.name, field_name))
     if field.label == _FieldDescriptor.LABEL_REPEATED:
       copy = field._default_constructor(self)
       if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:  # Composite
         for val in field_value:
           copy.add().MergeFrom(val)
       else:  # Scalar
         copy.extend(field_value)
       self._fields[field] = copy
     elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
       copy = field._default_constructor(self)
       copy.MergeFrom(field_value)
       self._fields[field] = copy
     else:
       setattr(self, field_name, field_value)
Beispiel #7
0
    def _loadConfigFile(self, path):
        """load color definitions from file"""

        config = ConfigObj(path)

        # try to get theme name from the config
        try:
            name = config['theme']['name']
            if name:
                self._name = name
        except KeyError:
            pass

        # load color definitions
        if 'colors' in config:
            colors = config['colors']
            colorObjects = {}
            for key, color in six.iteritems(colors):
                if len(color) == 2: # hex color/color name and alpha as float 0-1
                    colorString = color[0]
                    colorObjects[key] = colorString
                    # TODO: alpha support, other formats
                    # TODO: use the Color object
            self._colors = colorObjects
        else:
            self._colors = {}
Beispiel #8
0
 def wrappedLayers(self):
     # make sure the wrapped layer dict has benn initialized
     # (we can't do that at init, as at that time the
     # map layers module is not yet loaded)
     if self._wrappedLayers is None:
         self._wrappedLayers = {}
         for layerId, layer in six.iteritems(self.gui._mapLayers.getLayerDict()):
             self.wrappedLayers[layerId] = wrappers.MapLayerWrapper(layer)
     return self._wrappedLayers
Beispiel #9
0
 def _removeNonPersistentOptions(self, inputDict):
     """keys that begin with # are not saved
     (as they mostly contain data that is either time sensitive or is
     reloaded on startup)
     ASSUMPTION: keys are strings of length>=1"""
     try:
         return dict((k, v) for k, v in six.iteritems(inputDict) if k[0] != '#')
     except Exception:
         log.exception('options: error while filtering options\nsome nonpersistent keys might have been left in\nNOTE: keys should be strings of length>=1')
         return self.d
Beispiel #10
0
 def wrappedLayers(self):
     # make sure the wrapped layer dict has benn initialized
     # (we can't do that at init, as at that time the
     # map layers module is not yet loaded)
     if self._wrappedLayers is None:
         self._wrappedLayers = {}
         for layerId, layer in six.iteritems(
                 self.gui._mapLayers.getLayerDict()):
             self.wrappedLayers[layerId] = wrappers.MapLayerWrapper(layer)
     return self._wrappedLayers
Beispiel #11
0
 def _parseGroups(self):
     """Parse all map layer group definitions"""
     # as groups are not strictly needed for modRana
     # to show at least one map layer, we don't check if the
     # configuration file has any
     if self.modrana.configs.mapConfig:
         groupsDict = self.modrana.configs.mapConfig.get('groups', {})
         for groupId, groupDefinition in six.iteritems(groupsDict):
             if self._hasRequiredKeys(groupDefinition, MAP_LAYER_GROUP_REQUIRED_KEYS):
                 self._groups[groupId] = MapLayerGroup(self, groupId, groupDefinition)
Beispiel #12
0
 def _parseGroups(self):
     """Parse all map layer group definitions"""
     # as groups are not strictly needed for modRana
     # to show at least one map layer, we don't check if the
     # configuration file has any
     if self.modrana.configs.map_config:
         groupsDict = self.modrana.configs.map_config.get('groups', {})
         for groupId, groupDefinition in six.iteritems(groupsDict):
             if self._hasRequiredKeys(groupDefinition,
                                      MAP_LAYER_GROUP_REQUIRED_KEYS):
                 self._groups[groupId] = MapLayerGroup(
                     self, groupId, groupDefinition)
Beispiel #13
0
    def _parseLayers(self):
        """Parse all map layer definitions"""
        # check if there is at least one valid layer

        layerDefinitions = self.modrana.configs.map_config.get("layers", {})
        for layerId, layerDefinition in six.iteritems(layerDefinitions):
            if self._hasRequiredKeys(layerDefinition, MAP_LAYER_REQUIRED_KEYS):
                self._layers[layerId] = MapLayer(layerId, layerDefinition)
            else:
                self.log.error("layer %s definition is missing required keys", layerId)
        if self._layers == {}:
            self.log.error("map layer config has no valid layers," " using Mapnik fallback layer")
            self._layers["mapnik"] = self._getFallbackLayer()
Beispiel #14
0
 def _removeNonPersistentOptions(self, inputDict):
     """keys that begin with # are not saved
     (as they mostly contain data that is either time sensitive or is
     reloaded on startup)
     ASSUMPTION: keys are strings of length>=1"""
     try:
         return dict(
             (k, v) for k, v in six.iteritems(inputDict) if k[0] != '#')
     except Exception:
         log.exception(
             'options: error while filtering options\nsome nonpersistent keys might have been left in\nNOTE: keys should be strings of length>=1'
         )
         return self.d
Beispiel #15
0
    def _parseLayers(self):
        """Parse all map layer definitions"""
        # check if there is at least one valid layer

        layerDefinitions = self.modrana.configs.mapConfig.get('layers', {})
        for layerId, layerDefinition in six.iteritems(layerDefinitions):
            if self._hasRequiredKeys(layerDefinition, MAP_LAYER_REQUIRED_KEYS):
                self._layers[layerId] = MapLayer(layerId, layerDefinition)
            else:
                print('MapLAyers: layer %s definition is missing required keys')
        if self._layers == {}:
            print('MapLayers: map config has no valid layers,'
                  ' using Mapnik fallback layer')
            self._layers['mapnik'] = self._getFallbackLayer()
Beispiel #16
0
    def _parseLayers(self):
        """Parse all map layer definitions"""
        # check if there is at least one valid layer

        layerDefinitions = self.modrana.configs.map_config.get('layers', {})
        for layerId, layerDefinition in six.iteritems(layerDefinitions):
            if self._hasRequiredKeys(layerDefinition, MAP_LAYER_REQUIRED_KEYS):
                self._layers[layerId] = MapLayer(layerId, layerDefinition)
            else:
                self.log.error('layer %s definition is missing required keys',
                               layerId)
        if self._layers == {}:
            self.log.error('map layer config has no valid layers,'
                           ' using Mapnik fallback layer')
            self._layers['mapnik'] = self._getFallbackLayer()
Beispiel #17
0
 def _parse_type(self, element, type_def):
     attr_types, child_types = type_def
     attrs = {}
     children = {}
     for attr, handler in six.iteritems(attr_types):
         value = element.get(attr)
         type_func = self.type_handlers[handler]
         attrs[attr] = type_func(_Attr(value))
     for tag, handler in six.iteritems(child_types):
         values = []
         all = False
         if isinstance(handler, list):
             all = True
             type_func = self.type_handlers[handler[0]]
         else:
             type_func = self.type_handlers[handler]
         for e in element.findall(self._get_qname(tag)):
             values.append(type_func(e))
         if len(values) > 0:
             if all:
                 children[tag] = values
             else:
                 children[tag] = values[-1]
     return attrs, children
Beispiel #18
0
    def _loadConfigFile(self, path):
        """load color definitions from file"""

        try:
            if qrc.is_qrc:
                if utils.internal_isfile(path):
                    config_content = utils.internal_get_file_contents(path)
                    config = ConfigObj(
                        config_content.decode('utf-8').split("\n"))
                else:
                    log.error("theme config file %s does not exist", path)
                    return
            else:
                # Python 2.5 lack the bytearray builtin and Android where qrc is
                # needed is Python 3 only, so just access the theme conf directly
                # when not running from qrc
                config = ConfigObj(path)

        except Exception:
            log.exception("loading theme config file from %s failed", path)
            return

        # try to get theme name from the config
        try:
            name = config['theme']['name']
            if name:
                self._name = name
        except KeyError:
            pass

        # load color definitions
        if 'colors' in config:
            colors = config['colors']
            colorObjects = {}
            for key, color in six.iteritems(colors):
                if len(color
                       ) == 2:  # hex color/color name and alpha as float 0-1
                    colorString = color[0]
                    colorObjects[key] = colorString
                    # TODO: alpha support, other formats
                    # TODO: use the Color object
            self._colors = colorObjects
        else:
            self._colors = {}
Beispiel #19
0
    def _loadConfigFile(self, path):
        """load color definitions from file"""

        try:
            if qrc.is_qrc:
                if utils.internal_isfile(path):
                    config_content = utils.internal_get_file_contents(path)
                    config = ConfigObj(config_content.decode("utf-8").split("\n"))
                else:
                    log.error("theme config file %s does not exist", path)
                    return
            else:
                # Python 2.5 lack the bytearray builtin and Android where qrc is
                # needed is Python 3 only, so just access the theme conf directly
                # when not running from qrc
                config = ConfigObj(path)

        except Exception:
            log.exception("loading theme config file from %s failed", path)
            return

        # try to get theme name from the config
        try:
            name = config["theme"]["name"]
            if name:
                self._name = name
        except KeyError:
            pass

        # load color definitions
        if "colors" in config:
            colors = config["colors"]
            colorObjects = {}
            for key, color in six.iteritems(colors):
                if len(color) == 2:  # hex color/color name and alpha as float 0-1
                    colorString = color[0]
                    colorObjects[key] = colorString
                    # TODO: alpha support, other formats
                    # TODO: use the Color object
            self._colors = colorObjects
        else:
            self._colors = {}
Beispiel #20
0
    def drawWorkInProgressOverlay(self, cr):
        proj = self.m.get('projection', None) # we also need the projection module
        viewport = self.get('viewport', None)
        menus = self.m.get('menu', None)
        with self._tasksLock:
            if self._tasks and proj and viewport and menus:
                # we need to have both the viewport and projection modules available
                # also the menu module for the text

                taskCount = len(self._tasks)

                # background
                cr.set_source_rgba(0.5, 0.5, 1, 0.5)
                (sx, sy, w, h) = viewport
                itemHeight = h * 0.2
                (bx, by, bw, bh) = (0, 0, w, itemHeight * taskCount)
                cr.rectangle(bx, by, bw, bh)
                cr.fill()

                taskIndex = 0
                for taskName, taskState in six.iteritems(self._tasks):
                    # cancel button coordinates
                    cbdx = min(w, h) / 5.0
                    cbdy = cbdx
                    cbx1 = (sx + w) - cbdx
                    cby1 = sy + cbdy * taskIndex

                    # cancel button
                    self.drawCancelButton(cr, coords=(cbx1, cby1, cbdx, cbdy), taskName=taskName)

                    status, progress = taskState

                    # draw the text
                    border = min(w / 20.0, h / 20.0)
                    menus.showText(cr, status, bx + border, by + border + itemHeight * taskIndex,
                                   bw - 2 * border - cbdx, 30, "white")
                    taskIndex += 1
Beispiel #21
0
def _AddPropertiesForExtensions(descriptor, cls):
    """Adds properties for all fields in this protocol message type."""
    extension_dict = descriptor.extensions_by_name
    for extension_name, extension_field in six.iteritems(extension_dict):
        constant_name = extension_name.upper() + "_FIELD_NUMBER"
        setattr(cls, constant_name, extension_field.number)
Beispiel #22
0
 def ListFields(self):
     all_fields = [
         item for item in six.iteritems(self._fields) if _IsPresent(item)
     ]
     all_fields.sort(key=lambda item: item[0].number)
     return all_fields
Beispiel #23
0
def _AddClassAttributesForNestedExtensions(descriptor, dictionary):
    extension_dict = descriptor.extensions_by_name
    for extension_name, extension_field in six.iteritems(extension_dict):
        assert extension_name not in dictionary
        dictionary[extension_name] = extension_field
Beispiel #24
0
def _AddClassAttributesForNestedExtensions(descriptor, dictionary):
  extension_dict = descriptor.extensions_by_name
  for extension_name, extension_field in six.iteritems(extension_dict):
    assert extension_name not in dictionary
    dictionary[extension_name] = extension_field
Beispiel #25
0
 def ListFields(self):
   all_fields = [item for item in six.iteritems(self._fields) if _IsPresent(item)]
   all_fields.sort(key = lambda item: item[0].number)
   return all_fields
Beispiel #26
0
def _AddPropertiesForExtensions(descriptor, cls):
  """Adds properties for all fields in this protocol message type."""
  extension_dict = descriptor.extensions_by_name
  for extension_name, extension_field in six.iteritems(extension_dict):
    constant_name = extension_name.upper() + "_FIELD_NUMBER"
    setattr(cls, constant_name, extension_field.number)