Advertisement
Guest User

Untitled

a guest
Dec 20th, 2017
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.54 KB | None | 0 0
  1. #!/usr/bin/python2
  2.  
  3.  
  4. # Python
  5. import sys
  6. import os
  7. import subprocess
  8. import time
  9.  
  10.  
  11. def getOutputs():
  12.     """
  13.    For the first screen, get the names of the outputs and whether they're currently connected.
  14.  
  15.    Returns:
  16.     (list)
  17.     Each element is:
  18.      (tuple)
  19.      Tuple has elements:
  20.       0:
  21.        (str)
  22.        Name of output
  23.       1:
  24.        (bool)
  25.        Whether the output is currently connected.
  26.    """
  27.     # Run xrandr
  28.     popen = subprocess.Popen(["xrandr", "--screen", "0", "--query"], stdout=subprocess.PIPE)
  29.     popen.wait()
  30.     (out, err) = popen.communicate()
  31.  
  32.     # Parse output
  33.     lines = out.split("\n")
  34.     if lines[0][:9] != "Screen 0:":
  35.         raise RuntimeError("Unexpected preamble from xrandr --query")
  36.  
  37.     outputs = []
  38.     for line in lines[1:]:
  39.         print line
  40.         if len(line) > 0 and line[1] != " ":
  41.             lineFields = line.split(" ")
  42.             outputs.append((lineFields[0], lineFields[1] == "connected"))
  43.  
  44.     return outputs
  45.  
  46. def generateTimings(i_timingCommand, i_width, i_height, i_fieldRate, i_interlaced=False):
  47.     """
  48.    Params:
  49.     i_timingCommand:
  50.      (str)
  51.     i_width, i_height:
  52.      Either (int)
  53.      or (str)
  54.       String representations of an integer.
  55.     i_fieldRate:
  56.      (str)
  57.      String representations of a float.
  58.     i_interlaced:
  59.      (bool)
  60.      True: Make an interlaced mode
  61.  
  62.    Returns:
  63.     (list)
  64.     eg. ['Modeline', '1920x1080i60.00', '86.5', '1920', '2048', '2248', '2576', '1080', '1083', '1088', '1120', '+hsync', '+vsync', 'Interlace']
  65.    """
  66.     # Run cvt or gtf
  67.     popen = subprocess.Popen([i_timingCommand, str(i_width), str(i_height), i_fieldRate], stdout=subprocess.PIPE)
  68.     popen.wait()
  69.     (out, err) = popen.communicate()
  70.  
  71.     # Parse output
  72.     lines = out.split("\n")
  73.     modespec = None
  74.     for line in lines:
  75.         line = line.strip()
  76.         if line.startswith("Modeline "):
  77.             parts = line.split(" ")
  78.             modespec = [p  for p in parts  if p != ""]
  79.             break
  80.  
  81.     # Remove enclosing quotes in mode name
  82.     modespec[1] = modespec[1].replace('"', '')
  83.  
  84.     # Modify mode name (which was generated by cvt/gtf)
  85.     # to show whether progressive or interlaced,
  86.     # and add actual interlacing options if desired
  87.     if not i_interlaced:
  88.         modespec[1] = modespec[1].replace('_', 'p')
  89.     else:
  90.         modespec[1] = modespec[1].replace('_', 'i')
  91.  
  92.         modespec.append("Interlace")
  93.         modespec[2] = str(float(modespec[2]) / 2.0)
  94.  
  95.     #
  96.     return modespec
  97.  
  98. def recreateMode(i_outputName, i_modespec, i_printXrandrCommands = False):
  99.     """
  100.    Params:
  101.     i_outputName:
  102.      (str)
  103.     i_modespec:
  104.      (list)
  105.     i_printXrandrCommands:
  106.      (bool)
  107.    """
  108.     #print "i_modespec: " + str(i_modespec)
  109.     xrandrCommand = ["xrandr", "--delmode", i_outputName]
  110.     xrandrCommand += [i_modespec[1]]
  111.     if i_printXrandrCommands:
  112.         print(subprocess.list2cmdline(xrandrCommand))
  113.     subprocess.Popen(xrandrCommand)
  114.  
  115.     time.sleep(0.25)
  116.  
  117.     xrandrCommand = ["xrandr", "--rmmode"]
  118.     xrandrCommand += [i_modespec[1]]
  119.     if i_printXrandrCommands:
  120.         print(subprocess.list2cmdline(xrandrCommand))
  121.     subprocess.Popen(xrandrCommand)
  122.  
  123.     time.sleep(0.25)
  124.  
  125.     xrandrCommand = ["xrandr", "--newmode"]
  126.     xrandrCommand += i_modespec[1:]
  127.     if i_printXrandrCommands:
  128.         print(subprocess.list2cmdline(xrandrCommand))
  129.     subprocess.Popen(xrandrCommand)
  130.  
  131.     time.sleep(0.25)
  132.  
  133.     xrandrCommand = ["xrandr", "--addmode", i_outputName]
  134.     xrandrCommand += [i_modespec[1]]
  135.     if i_printXrandrCommands:
  136.         print(subprocess.list2cmdline(xrandrCommand))
  137.     subprocess.Popen(xrandrCommand)
  138.  
  139. def setMode(i_outputName, i_modespec, i_printXrandrCommands = False):
  140.     """
  141.    Params:
  142.     i_outputName:
  143.      (str)
  144.     i_modespec:
  145.      (list)
  146.     i_printXrandrCommands:
  147.      (bool)
  148.    """
  149.     xrandrCommand = ["xrandr", "--output", i_outputName]
  150.     xrandrCommand += ["--mode", i_modespec[1]]
  151.     if i_printXrandrCommands:
  152.         print(subprocess.list2cmdline(xrandrCommand))
  153.     subprocess.Popen(xrandrCommand)
  154.  
  155.  
  156. if __name__ == "__main__":
  157.  
  158.     # + Parse command line {{{
  159.  
  160.     COMMAND_NAME = "easy_xrandr"
  161.  
  162.     def printUsage(i_outputStream):
  163.         i_outputStream.write('''\
  164. ''' + COMMAND_NAME + ''' by Daniel Lopez, 04/12/2016
  165. xrandr wrapper
  166.  
  167. Usage:
  168. ======
  169. ''' + COMMAND_NAME + ''' <action> <width> <height> <field rate> [options...]
  170.  
  171. Params:
  172. action:
  173.  Either 'add'
  174.   Just add the new mode to xrandr's list
  175.  or 'set'
  176.   Add the new mode and also switch to it now.
  177. width, height:
  178.  Desired resolution width and height in integer pixels
  179.  eg. 1024 and 768
  180. field rate:
  181.  Desired field rate in floating point Hz
  182.  eg. 60.1
  183.  In non-interlaced modes, this is the same as the frame rate,
  184.  and in interlaced modes, this is double the actual full frame rate.
  185.  
  186. Options:
  187. Output selection
  188.  --output <name>
  189.   Choose which output to control
  190.  
  191. Interlace
  192.  --interlace
  193.   Create an interlaced mode.
  194.   In this case the actual full frame rate will turn out to be half of
  195.   the number given for the <field rate> parameter.
  196.  
  197. Generating timings
  198.  --cvt
  199.   Use the 'cvt' command to generate the timings
  200.   (This is the default).
  201.  --gtf
  202.   Use the 'gtf' command to generate the timings.
  203. ''')
  204.  
  205.     #
  206.     param_action = None  # "add" or "set"
  207.     param_width = None
  208.     param_height = None
  209.     param_fieldRate = None
  210.     interlaced = False
  211.     timingCommand = "cvt"
  212.     outputName = "DVI-I-1"
  213.  
  214.     import sys
  215.     argNo = 1
  216.     while argNo < len(sys.argv):
  217.         arg = sys.argv[argNo]
  218.         argNo += 1
  219.  
  220.         if arg[0] == "-":
  221.  
  222.             if arg == "--help":
  223.                 printUsage(sys.stdout)
  224.                 sys.exit(0)
  225.  
  226.             if arg == "--cvt":
  227.                 timingCommand = "cvt"
  228.             elif arg == "--gtf":
  229.                 timingCommand = "gtf"
  230.             elif arg == "--interlace":
  231.                 interlaced = True
  232.             elif arg == "--output":
  233.                 if argNo >= len(sys.argv):
  234.                     print("--output requires an argument")
  235.                     sys.exit(-1)
  236.  
  237.                 arg = sys.argv[argNo]
  238.                 argNo += 1
  239.  
  240.                 outputName = arg
  241.             else:
  242.                 print("Unrecognised option: " + arg)
  243.                 sys.exit(-1)
  244.  
  245.         else:
  246.             # Collect command-line arguments
  247.             if param_action == None:
  248.                 param_action = arg
  249.             elif param_width == None:
  250.                 param_width = arg
  251.             elif param_height == None:
  252.                 param_height = arg
  253.             elif param_fieldRate == None:
  254.                 param_fieldRate = arg
  255.             else:
  256.                 print("Too many arguments.")
  257.                 sys.exit(-1)
  258.  
  259.     if param_fieldRate == None:
  260.         print("Insufficient arguments.")
  261.         sys.exit(-1)
  262.  
  263.     # + }}}
  264.  
  265.     # + Generate timings {{{
  266.  
  267.     print("Generating timings with " + timingCommand)
  268.     modespec = generateTimings(timingCommand, param_width, param_height, param_fieldRate, interlaced)
  269.     #print modespec
  270.     if modespec == None:
  271.         print("Failed to parse timings.")
  272.         sys.exit(1)
  273.  
  274.     ##
  275.     #modespec = modespec[:-2]
  276.     #modespec.append("-hsync")
  277.     #modespec.append("-vsync")
  278.  
  279.     #
  280.     print modespec
  281.     #sys.exit(0)
  282.  
  283.     # + }}}
  284.  
  285.     recreateMode(outputName, modespec, True)
  286.  
  287.     if param_action == "set":
  288.         time.sleep(0.25)
  289.         setMode(outputName, modespec)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement