Revert "made aspect ratio accurate"
[lilass.git] / screen.py
index 26ffddbfaf38d844989707f240256a4a67785cbc..6ba9418ae39058429b092aa4e1a646d91582e489 100644 (file)
--- a/screen.py
+++ b/screen.py
@@ -44,9 +44,10 @@ class RelativeScreenPosition(Enum):
     def __init__(self, text):
         # auto numbering
         cls = self.__class__
     def __init__(self, text):
         # auto numbering
         cls = self.__class__
-        self._value_ = len(cls.__members__)
+        self._value_ = len(cls.__members__) + 1
         self.text = text
         self.text = text
-
+    def __str__(self):
+        return self.text
 
 class Resolution:
     '''Represents a resolution of a screen'''
 
 class Resolution:
     '''Represents a resolution of a screen'''
@@ -54,6 +55,24 @@ class Resolution:
         self.width = width
         self.height = height
     
         self.width = width
         self.height = height
     
+    @classmethod
+    def fromDatabase(cls, dbstr):
+        if dbstr is None:
+            return None
+        parts = dbstr.split("x")
+        if len(parts) != 2:
+            raise ValueError(xrandrstr)
+        return Resolution(*map(int,parts))
+    
+    def forDatabase(self):
+        return str(self.width)+'x'+str(self.height)
+    
+    def forXrandr(self):
+        return self.forDatabase()
+    
+    def toTuple(self):
+        return (self.width, self.height)
+    
     def __eq__(self, other):
         if not isinstance(other, Resolution):
             return False
     def __eq__(self, other):
         if not isinstance(other, Resolution):
             return False
@@ -62,6 +81,9 @@ class Resolution:
     def __ne__(self, other):
         return not self.__eq__(other)
     
     def __ne__(self, other):
         return not self.__eq__(other)
     
+    def __hash__(self):
+        return hash(("Resolution",self.width,self.height))
+    
     def __str__(self):
         # get ratio
         ratio = int(round(16.0*self.height/self.width))
     def __str__(self):
         # get ratio
         ratio = int(round(16.0*self.height/self.width))
@@ -76,8 +98,8 @@ class Resolution:
     def __repr__(self):
         return 'screen.Resolution('+self.forXrandr()+')'
     
     def __repr__(self):
         return 'screen.Resolution('+self.forXrandr()+')'
     
-    def forXrandr(self):
-        return str(self.width)+'x'+str(self.height)
+    def pixelCount(self):
+        return self.width * self.height
 
 
 class ScreenSetup:
 
 
 class ScreenSetup:
@@ -118,27 +140,59 @@ class ScreenSetup:
                 RelativeScreenPosition.MIRROR: '--same-as',
             }[self.relPosition], intName]
         return args
                 RelativeScreenPosition.MIRROR: '--same-as',
             }[self.relPosition], intName]
         return args
+    
+    def __str__(self):
+        if self.intResolution is None:
+            return "External display only, at "+str(self.extResolution)
+        if self.extResolution is None:
+            return "Internal display only, at "+str(self.intResolution)
+        return "External display %s at %s %s internal display %s at %s" % ("(primary)" if self.extIsPrimary else "", str(self.extResolution), str(self.relPosition), "" if self.extIsPrimary else "(primary)", str(self.intResolution))
 
 class Connector:
 
 class Connector:
-    name = None # connector name, e.g. "HDMI1"
-    edid = None # EDID string for the connector, or None if disconnected
-    resolutions = [] # list of Resolution objects, empty if disconnected
-    
     def __init__(self, name=None):
     def __init__(self, name=None):
-        self.name = name
+        self.name = name # connector name, e.g. "HDMI1"
+        self.edid = None # EDID string for the connector, or None if disconnected
+        self._resolutions = set() # list of Resolution objects, empty if disconnected
+        self.preferredResolution = None
+        self.__lastResolution = None
+        self.hasLastResolution = False
+    
     def __str__(self):
         return str(self.name)
     def __str__(self):
         return str(self.name)
+    
+    def __repr__(self):
+        return """<Connector "%s" EDID="%s" resolutions="%s">""" % (str(self.name), str(self.edid), ", ".join(str(r) for r in self.getResolutionList()))
+    
+    def __setLastRes(self, res):
+        # res == None means this display was last switched off
+        if res is not None and not res in self._resolutions:
+            raise ValueError("Resolution "+res+" not available for "+self.name+".")
+        self.__lastResolution = res
+        self.hasLastResolution = True
+    
+    def __getLastRes(self):
+        if not self.hasLastResolution:
+            raise ValueError("Connector %s has no last known resolution." % self.name)
+        return self.__lastResolution
+    
+    lastResolution = property(__getLastRes, __setLastRes)
+    
     def isConnected(self):
     def isConnected(self):
-        assert (self.edid is None) == (len(self.resolutions)==0)
+        assert (self.edid is None) == (len(self._resolutions)==0)
         return self.edid is not None
         return self.edid is not None
+    
     def addResolution(self, resolution):
         assert isinstance(resolution, Resolution)
     def addResolution(self, resolution):
         assert isinstance(resolution, Resolution)
-        self.resolutions.append(resolution)
+        self._resolutions.add(resolution)
+    
     def appendToEdid(self, s):
         if self.edid is None:
             self.edid = s
         else:
             self.edid += s
     def appendToEdid(self, s):
         if self.edid is None:
             self.edid = s
         else:
             self.edid += s
+    
+    def getResolutionList(self):
+        return sorted(self._resolutions, key=lambda r: (0 if self.hasLastResolution and r==self.lastResolution else 1, 0 if r==self.preferredResolution else 1, -r.pixelCount()))
 
 class ScreenSituation:
     connectors = [] # contains all the Connector objects
 
 class ScreenSituation:
     connectors = [] # contains all the Connector objects
@@ -151,6 +205,9 @@ class ScreenSituation:
            just choose any remaining connector.'''
         # which connectors are there?
         self._getXrandrInformation()
            just choose any remaining connector.'''
         # which connectors are there?
         self._getXrandrInformation()
+        for c in self.connectors:
+            print(repr(c))
+            print()
         # figure out which is the internal connector
         self.internalConnector = self._findAvailableConnector(internalConnectorNames)
         if self.internalConnector is None:
         # figure out which is the internal connector
         self.internalConnector = self._findAvailableConnector(internalConnectorNames)
         if self.internalConnector is None:
@@ -159,11 +216,12 @@ class ScreenSituation:
         # and the external one
         if externalConnectorNames is None:
             externalConnectorNames = map(lambda c: c.name, self.connectors)
         # and the external one
         if externalConnectorNames is None:
             externalConnectorNames = map(lambda c: c.name, self.connectors)
-            externalConnectorNames = filter(lambda name: name != self.internalConnector.name, externalConnectorNames)
+            externalConnectorNames = set(filter(lambda name: name != self.internalConnector.name, externalConnectorNames))
         self.externalConnector = self._findAvailableConnector(externalConnectorNames)
         if self.internalConnector == self.externalConnector:
             raise Exception("Internal and external connector are the same. This must not happen. Please fix ~/.dsl.conf.");
         print("Detected external connector:",self.externalConnector)
         self.externalConnector = self._findAvailableConnector(externalConnectorNames)
         if self.internalConnector == self.externalConnector:
             raise Exception("Internal and external connector are the same. This must not happen. Please fix ~/.dsl.conf.");
         print("Detected external connector:",self.externalConnector)
+        # self.lastSetup is left uninitialized so you can't access it before trying a lookup in the database
     
     # Run xrandr and fill the dict of connector names mapped to lists of available resolutions.
     def _getXrandrInformation(self):
     
     # Run xrandr and fill the dict of connector names mapped to lists of available resolutions.
     def _getXrandrInformation(self):
@@ -196,6 +254,8 @@ class ScreenSituation:
                 resolution = Resolution(int(m.group(1)), int(m.group(2)))
                 assert connector is not None
                 connector.addResolution(resolution)
                 resolution = Resolution(int(m.group(1)), int(m.group(2)))
                 assert connector is not None
                 connector.addResolution(resolution)
+                if '+preferred' in line:
+                    connector.preferredResolution = resolution
                 continue
             # EDID?
             m = re.search(r'^\s*EDID:\s*$', line)
                 continue
             # EDID?
             m = re.search(r'^\s*EDID:\s*$', line)
@@ -204,7 +264,7 @@ class ScreenSituation:
                 continue
             # unknown line
             # not fatal, e.g. xrandr shows strange stuff when a display is enabled, but not connected
                 continue
             # unknown line
             # not fatal, e.g. xrandr shows strange stuff when a display is enabled, but not connected
-            print("Warning: Unknown xrandr line %s" % line)
+            #print("Warning: Unknown xrandr line %s" % line)
     
     # return the first available connector from those listed in <tryConnectorNames>, skipping disabled connectors
     def _findAvailableConnector(self, tryConnectorNames):
     
     # return the first available connector from those listed in <tryConnectorNames>, skipping disabled connectors
     def _findAvailableConnector(self, tryConnectorNames):
@@ -214,20 +274,20 @@ class ScreenSituation:
     
     # return available internal resolutions
     def internalResolutions(self):
     
     # return available internal resolutions
     def internalResolutions(self):
-        return self.internalConnector.resolutions
+        return self.internalConnector.getResolutionList()
     
     # return available external resolutions (or None, if there is no external screen connected)
     def externalResolutions(self):
         if self.externalConnector is None:
             return None
     
     # return available external resolutions (or None, if there is no external screen connected)
     def externalResolutions(self):
         if self.externalConnector is None:
             return None
-        return self.externalConnector.resolutions
+        return self.externalConnector.getResolutionList()
     
     # return resolutions available for both internal and external screen
     def commonResolutions(self):
         internalRes = self.internalResolutions()
         externalRes = self.externalResolutions()
         assert externalRes is not None
     
     # return resolutions available for both internal and external screen
     def commonResolutions(self):
         internalRes = self.internalResolutions()
         externalRes = self.externalResolutions()
         assert externalRes is not None
-        return [res for res in externalRes if res in internalRes]
+        return sorted(set(externalRes).intersection(internalRes), key=lambda r: -r.pixelCount())
     
     # compute the xrandr call
     def forXrandr(self, setup):
     
     # compute the xrandr call
     def forXrandr(self, setup):
@@ -247,3 +307,19 @@ class ScreenSituation:
             call += ["--output", name] + connectorArgs[name]
         return call
 
             call += ["--output", name] + connectorArgs[name]
         return call
 
+    def fetchDBInfo(self, db):
+        if self.externalConnector and self.externalConnector.edid:
+            self.lastSetup = db.getConfig(self.externalConnector.edid) # may also return None
+        else:
+            self.lastSetup = None
+        if self.lastSetup:
+            print("SETUP FOUND", self.lastSetup)
+            self.externalConnector.lastResolution = self.lastSetup.extResolution
+            self.internalConnector.lastResolution = self.lastSetup.intResolution
+        else:
+            print("NO SETUP FOUND")
+    
+    def putDBInfo(self, db, setup):
+        if not self.externalConnector or not self.externalConnector.edid:
+            return
+        db.putConfig(self.externalConnector.edid, setup)