drop old Depends, downgrade grml-etc-core to Recommends
[grml-x.git] / grml-x
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 # vim: set et ts=4:
4
5 # Filename:      grml-x
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 ###############################################################################
11
12 import fileinput, os, subprocess, sys, tempfile, time, traceback
13 from optparse import OptionParser
14
15 class Section(object):
16     def __init__(self, name, identifier, data):
17         self.name = name
18         self.identifer = identifier
19         self.data = data
20         self.subsect = ""
21     def __str__(self):
22         s = "Section \"%s\"\n\tIdentifier \"%s\"\n" % (self.name, self.identifer)
23         for k in self.data:
24             v = self.data[k]
25             if isinstance(v, list):
26                 v = '" "'.join(v)
27             elif '-' in v: # sync range
28                 pass
29             else:
30                 v = '"%s"' % v
31             s += "\t%s %s\n" % (k, v)
32         s += self.subsect
33         s += 'EndSection\n'
34         return s
35
36 def get_monitor_section(options, force):
37     if not options.hsync and not options.vsync and not force:
38         return None
39     d = {}
40     d['HorizSync'] = options.hsync or '28.0 - 96.0'
41     d['VertRefresh'] = options.vsync or '50.0 - 60.0'
42     return Section('Monitor', 'Monitor0', d)
43
44 def get_device_section(options):
45     if not options.module:
46         return None
47     d = {}
48     d['Driver'] = options.module
49     d['VendorName'] = 'All'
50     d['BoardName'] = 'All'
51     return Section('Device', 'Card0', d)
52
53 def build_bootparams():
54     lines = []
55     def walk_bootparams_path(p):
56         try:
57             if not os.path.exists(p): return
58             for root, dirs, files in os.walk(p):
59                 for name in files:
60                     f = open(os.path.join(root, name))
61                     lines.extend(f.readlines())
62                     f.close()
63         except:
64             print 'W: Error while getting bootparams from %s' % p
65     f = open('/proc/cmdline')
66     lines.append(f.readline())
67     f.close()
68     walk_bootparams_path('/cdrom/bootparams')
69     walk_bootparams_path('/live/image/bootparams')
70     params = {}
71     for p in ' '.join(lines).split(' '):
72         if '=' in p:
73             (k,v) = p.split('=', 2)
74             params[k] = v
75         else:
76             params[p] = True
77     return params
78
79 def detect_qemu():
80     f = open('/proc/cpuinfo')
81     x = ''.join(f.readlines())
82     f.close()
83     if 'QEMU' in x: return True
84     return False
85
86 def get_program_output(args):
87     p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)
88     return p.communicate()[0]
89
90 def run_program(args):
91     subprocess.Popen(args, close_fds=True).wait()
92
93 def which(program):
94     def is_exe(fpath):
95         return os.path.exists(fpath) and os.access(fpath, os.X_OK)
96
97     fpath, fname = os.path.split(program)
98     if fpath:
99         if is_exe(program):
100             return program
101     else:
102         for path in os.environ["PATH"].split(os.pathsep):
103             exe_file = os.path.join(path, program)
104             if is_exe(exe_file):
105                 return exe_file
106
107     return None
108
109 XORG_CONF_HEADER = "# Automatically generated by grml-x."
110 def check_old_xorg_conf(filename, overwrite):
111     # True: no problem, we can create/overwrite the config file
112     # False: pre-existing config file, and we are not to overwrite it
113     if overwrite: return True
114     if not os.path.exists(filename): return True
115     try:
116         f = file(filename, 'r')
117         lines = f.readlines()
118         f.close()
119         return (not XORG_CONF_HEADER in lines)
120     except IOError:
121         return False
122
123 parser = OptionParser(usage="usage: %prog [options] [window-manager]")
124 parser.add_option("--nostart", action="store_false", dest="start_server", default=True,
125                 help="Don't start X server")
126 parser.add_option("--display", action="store", type="string", dest="display",
127                 help="Start X server on display DISPLAY")
128 parser.add_option("--hsync", action="store", type="string", dest="hsync",
129                 help="Force writing a HorizSync range")
130 parser.add_option("--vsync", action="store", type="string", dest="vsync",
131                 help="Force writing a VertRefresh range")
132 parser.add_option("--mode", action="store", type="string", dest="mode",
133                 help="Force a specific resolution")
134 parser.add_option("--module", action="store", type="string", dest="module",
135                 help="Force driver MODULE instead of Xorg autodetection")
136 parser.add_option("-o", action="store", type="string", dest="xorg_conf", default="/etc/X11/xorg.conf",
137                 help="Specify alternate xorg.conf file [default: %default]")
138 parser.add_option("-f", "--force", action="store_true", dest="overwrite", default=False,
139                 help="Overwrite xorg.conf if it exists [default: %default]")
140
141 def main():
142     (options, args) = parser.parse_args()
143     bootparams = build_bootparams()
144
145     if os.getuid() == 0:
146         print "W: running as root is unsupported and may not work."
147         time.sleep(1)
148
149     if not check_old_xorg_conf(options.xorg_conf, options.overwrite):
150         print "E: Not overwriting existing %r without --force." % options.xorg_conf
151         print "I: If you previously ran grml-x, use startx /usr/bin/x-window-manager"
152         return 1
153
154     if 'xmode' in bootparams and not options.mode: options.mode = bootparams['xmode']
155     if 'xmodule' in bootparams and not options.module: options.module = bootparams['xmodule']
156
157     force_monitor = False
158     # cirrus driver for QEMU doesn't do 1024x768 without HorizSync set
159     if detect_qemu(): force_monitor = True
160
161     monitor = get_monitor_section(options, force_monitor)
162     device = get_device_section(options)
163
164     # build Screen section ourselves
165     d = {}
166     if monitor: d['Monitor'] = monitor.identifer
167     if device: d['Device'] = device.identifer
168     screen = Section('Screen', 'Screen0', d)
169     if options.mode:
170         d['DefaultColorDepth'] = 16
171         for depth in [8, 15, 16, 24, 32]:
172             screen.subsect += "SubSection \"Display\"\n\tDepth %d\n\tModes \"%s\"\t\nEndSubSection\n" % (depth, options.mode)
173
174     xinitrc = '~/.xinitrc'
175     if 'XINITRC' in os.environ: xinitrc = os.environ['XINITRC']
176     xinitrc = os.path.expanduser(xinitrc)
177
178     window_manager = 'x-window-manager'
179     if len(args) == 1: window_manager = args[0]
180     window_manager_path = which(window_manager)
181     if not window_manager_path:
182         print "E: Cannot find window manager %r, aborting." % window_manager
183         return 2
184
185     wm_exec = "exec %s\n" % window_manager_path
186     if not os.path.exists(xinitrc):
187         f = open(xinitrc, 'w')
188         f.write("#!/bin/sh\n")
189         f.write(wm_exec)
190         f.close()
191     else:
192         f = open(xinitrc, 'r')
193         lines = f.readlines()
194         f.close()
195         f = open(xinitrc, 'w')
196         for line in lines:
197             if line.startswith('exec '): line = wm_exec
198             f.write(line)
199         os.fchmod(f.fileno(), 0750)
200         f.close()
201
202     # write new config
203     if monitor or device or len(screen.data) > 0 or screen.subsect != '':
204         try:
205             f = tempfile.NamedTemporaryFile(delete=False)
206             f.write(XORG_CONF_HEADER + "\n")
207             f.write("# DO NOT MODIFY, YOUR CHANGES WILL BE LOST - OR REMOVE ALL HEADER LINES\n")
208             f.write("# See man xorg.conf or /etc/X11/xorg.conf.example for more\n")
209             if monitor: f.write(str(monitor))
210             if device: f.write(str(device))
211             f.write(str(screen))
212             f.flush()
213             os.fchmod(f.fileno(), 0644)
214             run_program(['sudo', 'mv', '-f', f.name, options.xorg_conf])
215         finally:
216             f.close()
217
218     if options.start_server:
219         startx = ['startx', xinitrc, '--']
220         if options.display: startx.append(':' + options.display)
221         print "Starting X: %r" % startx
222         run_program(startx)
223
224     return 0
225
226 if __name__ == '__main__':
227     rc = 1
228     try:
229         rc = main()
230     except Exception:
231         print "E: Exception: ",
232         traceback.print_exc()
233     sys.exit(1)
234