Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/src/jarabe/util/emulator.py
blob: dfdbfa84697074028cf23201870e49fad6241c8b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# Copyright (C) 2006-2008, Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import errno
import os
import signal
import subprocess
import sys
import time
from optparse import OptionParser
from gettext import gettext as _

import gtk

from sugar import env

DEFAULT_DIMENSIONS = (800, 600)
ERROR_NO_DISPLAY = 30
ERROR_NO_SERVER = 31
_DEV_NULL = open(os.devnull, 'w')

server = None


def _run_pipe(command, stdin=None):
    """Run a program with optional input and return output.

    Will raise CalledProcessError if program exits with non-zero return
    code.
    """
    pipe = subprocess.Popen(command, close_fds=True, stdin=subprocess.PIPE,
        stdout=subprocess.PIPE)
    stdout, stderr_ = pipe.communicate(stdin)
    if pipe.returncode:
        raise subprocess.CalledProcessError(pipe.returncode, command)

    return stdout


def _get_distro():
    """Run lsb_release to get distribution name.
    Return None if distribution name cannot be determined.
    """
    try:
        distro = ''.join(_run_pipe(['lsb_release', '-is'])).strip()
    except subprocess.CalledProcessError:
        return None

    return distro or None


def _run_xauth(display):
    """Set up Xauthority file for new display.

    Returns name of Xauthority file."""
    # pylint: disable-msg=E1103,W0612
    xauth_file = os.environ.get('XAUTHORITY',
        os.path.expanduser('~/.Xauthority'))
    host = _run_pipe(['uname', '-n']).strip()
    cookie = _run_pipe(['mcookie']).strip()
    xauth_pipe = subprocess.Popen(['xauth', '-f', xauth_file],
        stdin=subprocess.PIPE, close_fds=True)
    xauth_pipe.communicate('add %(host)s:%(display)s . %(cookie)s\n'
        'add %(host)s/unix:%(display)s . %(cookie)s\n' % locals())
    return xauth_file


def _run_server(display, dpi, dimensions, fullscreen):
    """Start the X server."""
    screen_size = (gtk.gdk.screen_width(), gtk.gdk.screen_height())

    if (not dimensions) and (fullscreen is None) and \
       (screen_size <= DEFAULT_DIMENSIONS):
        dimensions = '%dx%d' % screen_size
    elif fullscreen:
        dimensions = '%dx%d' % screen_size
    elif not dimensions:
        dimensions = '%dx%d' % DEFAULT_DIMENSIONS

    if not dpi:
        dpi = gtk.settings_get_default().get_property('gtk-xft-dpi') / 1024

    xauth_file = _run_xauth(display)
    command = ['Xvnc', '-DisconnectClients', '-NeverShared', '-localhost',
        '-SecurityTypes', 'None',
        '-auth', xauth_file,
        '-desktop', _('Sugar in a window')]
    if dimensions:
        command.append('-geometry')
        command.append(dimensions)
    if dpi:
        command.append('-dpi')
        command.append('%d' % dpi)

    if _get_distro() == 'Ubuntu':
        # workaround for Ubuntu bug #110263
        command += ['-extension', 'XFIXES']

    command.append(':%d' % (display, ))
    pipe = subprocess.Popen(command, close_fds=True)
    try:
        pipe = subprocess.Popen(cmd)

    except OSError, exc:
        sys.stderr.write('Error executing server: %s\n' % (exc, ))
        sys.exit(ERROR_NO_SERVER)

    return pipe


def _kill_pipe(pipe):
    """Terminate and wait for child process (if any)."""
    try:
        os.kill(pipe.pid, signal.SIGTERM)
    except OSError, exception:
        if exception.errno != errno.ESRCH:
            raise

    try:
        pipe.wait()
    except OSError, exception:
        if exception.errno != errno.ECHILD:
            raise


def _wait_pipe(pipe):
    """Wait for pipe to finish.

    Retries on EINTR to work around <http://bugs.python.org/issue1068268>.
    """
    while pipe.returncode is None:
        try:
            pipe.wait()
        except OSError, exception:
            if exception.errno != errno.EINTR:
                raise


def _start_server(dpi, dimensions, fullscreen):
    """Try running the X server on a free display."""
    for display in range(30, 40):
        if not _check_server(display):
            pipe = _run_server(display, dpi, dimensions, fullscreen)

            for i_ in range(10):
                if _check_server(display):
                    return display, pipe

                time.sleep(0.1)

            _kill_pipe(pipe)

    return None, None


def _start_viewer(display, fullscreen):
    """Start the VNC viewer."""
    command = ['vncviewer']
    if fullscreen:
        command.append('-fullscreen')

    command.append(':%d' % (display, ))
    pipe = subprocess.Popen(command, close_fds=True)
    return pipe


def _check_server(display):
    """Check the X server on the given display is reachable."""
    result = subprocess.call(['xdpyinfo', '-display', ':%d' % (display, )],
                             stdout=_DEV_NULL, stderr=_DEV_NULL)
    return result == 0


def _start_window_manager():
    """Start the window manager inside the new X server."""
    command = ['metacity', '--no-force-fullscreen']
    pipe_ = subprocess.Popen(command)



def _setup_env(display, scaling, emulator_pid):
    """Set up environment variables for running Sugar inside the new X server.
    """
    os.environ['SUGAR_EMULATOR'] = 'yes'
    os.environ['GABBLE_LOGFILE'] = os.path.join(
            env.get_profile_path(), 'logs', 'telepathy-gabble.log')
    os.environ['SALUT_LOGFILE'] = os.path.join(
            env.get_profile_path(), 'logs', 'telepathy-salut.log')
    os.environ['MC_LOGFILE'] = os.path.join(
            env.get_profile_path(), 'logs', 'mission-control.log')
    os.environ['STREAM_ENGINE_LOGFILE'] = os.path.join(
            env.get_profile_path(), 'logs', 'telepathy-stream-engine.log')
    os.environ['DISPLAY'] = ':%d' % (display, )
    if scaling:
        os.environ['SUGAR_SCALING'] = scaling
    os.environ['SUGAR_EMULATOR_PID'] = emulator_pid
    os.environ['MC_ACCOUNT_DIR'] = os.path.join(
            env.get_profile_path(), 'accounts')

    if scaling:
        os.environ['SUGAR_SCALING'] = scaling

def _parse_args():
    """Parse command line arguments."""
    parser = OptionParser()
    parser.add_option('-d', '--dpi', dest='dpi', type='int',
                      help='Emulator dpi')
    parser.add_option('-s', '--scaling', dest='scaling',
                      help='Sugar scaling in %')
    parser.add_option('-i', '--dimensions', dest='dimensions',
                      help='Emulator dimensions (ex. 1200x900)')
    parser.add_option('-f', '--fullscreen', dest='fullscreen',
                      action='store_true', default=None,
                      help='Run emulator in fullscreen mode')
    parser.add_option('-F', '--no-fullscreen', dest='fullscreen',
                      action='store_false',
                      help='Do not run emulator in fullscreen mode')
    return parser.parse_args()


def _sigchld_handler(number_, frame_):
    """Kill server when any (direct) child exits.

    So closing the viewer will close the server as well."""
    if server.returncode is not None:
        return

    signal.signal(signal.SIGCHLD, signal.SIG_DFL)

    print 'sugar-emulator: Child exited, shutting down server'
    _kill_pipe(server)
    return


def main():
    """Script-level operations"""
    global server

    if not os.environ.get('DISPLAY'):
        sys.stderr.write('DISPLAY not set, cannot connect to host X server.\n')
        return ERROR_NO_DISPLAY

    options, args = _parse_args()
    display, server = _start_server(options.dpi, options.dimensions,
        options.fullscreen)

    if server is None:
        sys.stderr.write('Failed to start server. Please check output above'
            ' for any error message.\n')
        return ERROR_NO_SERVER

    viewer = _start_viewer(display, options.fullscreen)
    _setup_env(display, options.scaling, str(server.pid))

    command = ['dbus-launch', '--exit-with-session']

    if not args:
        command.append('sugar')
    else:
        _start_window_manager()
        command += args

    signal.signal(signal.SIGCHLD, _sigchld_handler)
    session = subprocess.Popen(command, close_fds=True)
    _wait_pipe(session)

    _kill_pipe(viewer)
    _kill_pipe(server)