2 # -*- coding: utf-8 -*-
6 # Purpose: wrapper for startx on grml [providing new xconfiguration tool]
7 # Authors: grml-team (grml.org), (c) Christian Hofstaedtler <ch@grml.org>
8 # Bug-Reports: see http://grml.org/bugs/
9 # License: This file is licensed under the GPL v2.
10 ###############################################################################
12 import fileinput, os, subprocess, sys, tempfile, time, traceback
13 from optparse import OptionParser
15 class Section(object):
16 def __init__(self, name, identifier, data):
18 self.identifer = identifier
22 s = "Section \"%s\"\n\tIdentifier \"%s\"\n" % (self.name, self.identifer)
25 if isinstance(v, list):
27 elif not isinstance(v, str): # int, others
29 elif '-' in v: # sync range
33 s += "\t%s %s\n" % (k, v)
38 def get_monitor_section(options, force):
39 if not options.hsync and not options.vsync and not force:
42 d['HorizSync'] = options.hsync or '28.0 - 96.0'
43 d['VertRefresh'] = options.vsync or '50.0 - 60.0'
44 return Section('Monitor', 'Monitor0', d)
46 def get_device_section(options):
47 if not options.module:
50 d['Driver'] = options.module
51 d['VendorName'] = 'All'
52 d['BoardName'] = 'All'
53 return Section('Device', 'Card0', d)
55 def build_bootparams():
57 def walk_bootparams_path(p):
59 if not os.path.exists(p): return
60 for root, dirs, files in os.walk(p):
62 f = open(os.path.join(root, name))
63 lines.extend(f.readlines())
66 print('W: Error while getting bootparams from %s' % p)
67 f = open('/proc/cmdline')
68 lines.append(f.readline())
70 walk_bootparams_path('/lib/live/mount/medium/bootparams')
71 walk_bootparams_path('/run/live/medium/bootparams')
73 for p in ' '.join(lines).split(' '):
75 (k,v) = p.split('=', 1)
82 f = open('/proc/cpuinfo')
83 x = ''.join(f.readlines())
85 if 'QEMU' in x: return True
88 def get_program_output(args):
89 p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)
90 return p.communicate()[0]
92 def run_program(args):
93 subprocess.Popen(args, close_fds=True).wait()
97 return os.path.exists(fpath) and os.access(fpath, os.X_OK)
99 fpath, fname = os.path.split(program)
104 for path in os.environ["PATH"].split(os.pathsep):
105 exe_file = os.path.join(path, program)
111 XORG_CONF_HEADER = "# Automatically generated by grml-x.\n"
112 def check_old_xorg_conf(filename, overwrite):
113 # True: no problem, we can create/overwrite the config file
114 # False: pre-existing config file, and we are not to overwrite it
115 if overwrite: return True
116 if not os.path.exists(filename): return True
118 f = open(filename, 'r')
119 lines = f.readlines()
121 return (not XORG_CONF_HEADER in lines)
125 parser = OptionParser(usage="usage: %prog [options] [window-manager]")
126 parser.add_option("--nostart", action="store_false", dest="start_server", default=True,
127 help="Don't start X server")
128 parser.add_option("--display", action="store", type="string", dest="display",
129 help="Start X server on display DISPLAY")
130 parser.add_option("--hsync", action="store", type="string", dest="hsync",
131 help="Force writing a HorizSync range")
132 parser.add_option("--vsync", action="store", type="string", dest="vsync",
133 help="Force writing a VertRefresh range")
134 parser.add_option("--mode", action="store", type="string", dest="mode",
135 help="Force a specific resolution")
136 parser.add_option("--module", action="store", type="string", dest="module",
137 help="Force driver MODULE instead of Xorg autodetection")
138 parser.add_option("-o", action="store", type="string", dest="xorg_conf", default="/etc/X11/xorg.conf",
139 help="Specify alternate xorg.conf file [default: %default]")
140 parser.add_option("-f", "--force", action="store_true", dest="overwrite", default=False,
141 help="Overwrite xorg.conf if it exists [default: %default]")
144 (options, args) = parser.parse_args()
145 bootparams = build_bootparams()
147 if os.getuid() == 0 and options.start_server:
148 print("W: running as root is unsupported and may not work.")
151 if not check_old_xorg_conf(options.xorg_conf, options.overwrite):
152 print("E: Not overwriting existing %r without --force." % options.xorg_conf)
153 print("I: If you previously ran grml-x, use startx /usr/bin/x-window-manager")
156 if 'xmode' in bootparams and not options.mode: options.mode = bootparams['xmode']
157 if 'xmodule' in bootparams and not options.module: options.module = bootparams['xmodule']
159 force_monitor = False
160 # cirrus driver for QEMU doesn't do 1024x768 without HorizSync set
161 if detect_qemu(): force_monitor = True
163 monitor = get_monitor_section(options, force_monitor)
164 device = get_device_section(options)
166 # build Screen section ourselves
168 if monitor: d['Monitor'] = monitor.identifer
169 if device: d['Device'] = device.identifer
170 screen = Section('Screen', 'Screen0', d)
172 d['DefaultColorDepth'] = 16
173 for depth in [8, 15, 16, 24, 32]:
174 screen.subsect += "SubSection \"Display\"\n\tDepth %d\n\tModes \"%s\"\t\nEndSubSection\n" % (depth, options.mode)
176 xinitrc = '~/.xinitrc'
177 if 'XINITRC' in os.environ: xinitrc = os.environ['XINITRC']
178 xinitrc = os.path.expanduser(xinitrc)
180 window_manager = 'x-window-manager'
181 if len(args) == 1: window_manager = args[0]
182 window_manager_path = which(window_manager)
183 if not window_manager_path:
184 print("E: Cannot find window manager %r, aborting." % window_manager)
187 wm_exec = "exec %s\n" % window_manager_path
188 if not os.path.exists(xinitrc):
189 f = open(xinitrc, 'w')
190 f.write("#!/bin/sh\n")
194 f = open(xinitrc, 'r')
195 lines = f.readlines()
197 f = open(xinitrc, 'w')
199 if line.strip().startswith('exec '): line = wm_exec
201 os.fchmod(f.fileno(), 0o750)
205 if monitor or device or len(screen.data) > 0 or screen.subsect != '':
207 f = tempfile.NamedTemporaryFile(mode='w+', delete=False)
208 f.write(XORG_CONF_HEADER)
209 f.write("# DO NOT MODIFY, YOUR CHANGES WILL BE LOST - OR REMOVE ALL HEADER LINES\n")
210 f.write("# See man xorg.conf or /etc/X11/xorg.conf.example for more\n")
211 if monitor: f.write(str(monitor))
212 if device: f.write(str(device))
215 os.fchmod(f.fileno(), 0o644)
216 run_program(['sudo', 'mv', '-f', f.name, options.xorg_conf])
220 if options.start_server:
221 startx = ['startx', xinitrc, '--']
222 if options.display: startx.append(':' + options.display)
223 print("Starting X: %r" % startx)
228 if __name__ == '__main__':
233 print("E: Exception: ", end=' ')
234 traceback.print_exc()