pre select last used setup in qt gui
[lilass.git] / screen.py
index b096fb120382832979595c6f81d1bf9984f3d46d..456c0bdcd6b9eb08e716dd74b3cf7b54f45ea4db 100644 (file)
--- a/screen.py
+++ b/screen.py
@@ -18,6 +18,7 @@
 
 import re, subprocess
 from enum import Enum
 
 import re, subprocess
 from enum import Enum
+from fractions import Fraction
 
 ## utility functions
 
 
 ## utility functions
 
@@ -44,7 +45,7 @@ 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
 
 class Resolution:
         self.text = text
 
 class Resolution:
@@ -53,6 +54,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
@@ -66,13 +85,8 @@ class Resolution:
     
     def __str__(self):
         # get ratio
     
     def __str__(self):
         # get ratio
-        ratio = int(round(16.0*self.height/self.width))
-        if ratio == 12: # 16:12 = 4:3
-            strRatio = '4:3'
-        elif ratio == 13: # 16:12.8 = 5:4
-            strRatio = '5:4'
-        else: # let's just hope this will never be 14 or more...
-            strRatio = '16:%d' % ratio
+        ratio = Fraction(self.width, self.height) # automatically divides by the gcd
+        strRatio = "%d:%d" % (ratio.numerator, ratio.denominator)
         return '%dx%d (%s)' %(self.width, self.height, strRatio)
     
     def __repr__(self):
         return '%dx%d (%s)' %(self.width, self.height, strRatio)
     
     def __repr__(self):
@@ -80,9 +94,6 @@ class Resolution:
     
     def pixelCount(self):
         return self.width * self.height
     
     def pixelCount(self):
         return self.width * self.height
-    
-    def forXrandr(self):
-        return str(self.width)+'x'+str(self.height)
 
 
 class ScreenSetup:
 
 
 class ScreenSetup:
@@ -126,24 +137,40 @@ class ScreenSetup:
 
 class Connector:
     def __init__(self, name=None):
 
 class Connector:
     def __init__(self, name=None):
-        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.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.preferredResolution = None
+        self.__lastResolution = None
+        self.hasLastResolution = False
     
     def __str__(self):
         return str(self.name)
     
     def __repr__(self):
     
     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.resolutions))
+        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
     
     def addResolution(self, resolution):
         assert isinstance(resolution, Resolution)
         return self.edid is not None
     
     def addResolution(self, resolution):
         assert isinstance(resolution, Resolution)
-        self.resolutions.add(resolution)
+        self._resolutions.add(resolution)
     
     def appendToEdid(self, s):
         if self.edid is None:
     
     def appendToEdid(self, s):
         if self.edid is None:
@@ -151,10 +178,8 @@ class Connector:
         else:
             self.edid += s
     
         else:
             self.edid += s
     
-    def getPreferredResolution(self):
-        if self.preferredResolution:
-            return self.preferredResolution
-        return max(self.resolutions, key=lambda r: r.pixelCount())
+    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
@@ -183,6 +208,7 @@ class ScreenSituation:
         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)
         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):
@@ -235,13 +261,13 @@ 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):
     
     # return resolutions available for both internal and external screen
     def commonResolutions(self):
@@ -268,3 +294,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)