Commits

Aleš Erjavec  committed 8a0b98c

Added 'SegmentationContextHandler' class.

  • Participants
  • Parent commits 3a71479

Comments (0)

Files changed (1)

File _textable/widgets/TextableUtils.py

         OWContexts.ContextHandler.__init__(self, contextName,
                                            findImperfect=False, **kwargs)
 
-        fields = [ContextField(field) if isinstance(field, basestring)
-                  else field
+        fields = [ContextField(field) if isinstance(field, str) else field
                   for field in fields]
 
         self.fields = fields
             context.values[field.name] = field.save(widget)
 
 
+class SegmentationContextHandler(OWContexts.ContextHandler):
+    """
+    Context handler for a single Segmentation instance.
+
+    Two Segmentations are matched if they have the same label and
+    annotation keys.
+
+    """
+    def __init__(self, contextName, fields=[], findImperfect=False, **kwargs):
+        if findImperfect != False:
+            raise ValueError("'findImperfect' is not supported")
+
+        OWContexts.ContextHandler.__init__(self, contextName,
+                                           findImperfect=False, **kwargs)
+
+        self.fields = [ContextField(field) if isinstance(field, str) else field
+                       for field in fields]
+
+    def encode(self, segmentation):
+        return (segmentation.label,
+                tuple(sorted(segmentation.get_annotation_keys())))
+
+    def findOrCreateContext(self, widget, segmentation):
+        encoded = self.encode(segmentation)
+        context, isnew = OWContexts.ContextHandler.findOrCreateContext(
+            self, widget, encoded)
+
+        # Store the encoded context
+        context.encoded = encoded
+
+        if isnew:
+            context.values = {}
+
+        return context, isnew
+
+    def match(self, context, imperfect, encoded):
+        """
+        Match the `context` to the encoded segmentation context
+        """
+        return 2 if context.encoded == encoded else 0
+
+    def settingsToWidget(self, widget, context):
+        for field in self.fields:
+            if field.name in context.values:
+                field.restore(widget, context.values[field.name])
+
+    def settingsFromWidget(self, widget, context):
+        for field in self.fields:
+            context.values[field.name] = field.save(widget)
+
+
 def getWidgetUuid(widget, uuid_name="uuid"):
     """
     Return a persistent universally unique id for a widget.