Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/bin/sugar-session
blob: c011cbf974ae3efa1bb692db27fa141fc11b89d0 (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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
#!/usr/bin/env python
# Copyright (C) 2006, Red Hat, Inc.
# Copyright (C) 2009, One Laptop Per Child Association 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 os
import sys
import time
import subprocess
import shutil


# Change the default encoding to avoid UnicodeDecodeError
# http://lists.sugarlabs.org/archive/sugar-devel/2012-August/038928.html
reload(sys)
sys.setdefaultencoding('utf-8')

if os.environ.get('SUGAR_LOGGER_LEVEL', '') == 'debug':
    print '%r STARTUP: Starting the shell' % time.time()
    sys.stdout.flush()

import gettext
import logging
import sys

from gi.repository import GLib
from gi.repository import GConf
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GdkX11
from gi.repository import GObject
from gi.repository import Gst
import dbus.glib
from gi.repository import Wnck
from gi.repository import Gio

MONITORS = []
MONITOR_ACTION_TAKEN = False

OSK_APPEARENCE_MONITOR_FILE    = '~/.sugar/default/osk_just_appeared'
OSK_DISAPPEARENCE_MONITOR_FILE = '~/.sugar/default/osk_just_disappeared'

_USE_XKL = False
try:
    from gi.repository import Xkl
    _USE_XKL = True
except ImportError:
    logging.debug('Could not load xklavier for keyboard configuration')

GLib.threads_init()
Gdk.threads_init()
dbus.glib.threads_init()

Gst.init(sys.argv)

def cleanup_logs(logs_dir):
    """Clean up the log directory, moving old logs into a numbered backup
    directory.  We only keep `_MAX_BACKUP_DIRS` of these backup directories
    around; the rest are removed."""
    if not os.path.isdir(logs_dir):
        os.makedirs(logs_dir)

    backup_logs = []
    backup_dirs = []
    for f in os.listdir(logs_dir):
        path = os.path.join(logs_dir, f)
        if os.path.isfile(path):
            backup_logs.append(f)
        elif os.path.isdir(path):
            backup_dirs.append(path)

    if len(backup_dirs) > 3:
        backup_dirs.sort()
        root = backup_dirs[0]
        for f in os.listdir(root):
            os.remove(os.path.join(root, f))
        os.rmdir(root)

    if len(backup_logs) > 0:
        name = str(int(time.time()))
        backup_dir = os.path.join(logs_dir, name)
        os.mkdir(backup_dir)
        for log in backup_logs:
            source_path = os.path.join(logs_dir, log)
            dest_path = os.path.join(backup_dir, log)
            os.rename(source_path, dest_path)

def show_welcome_screen():
    path = os.path.expanduser('~/.welcome_screen')
    if os.path.exists(path):
        welcome_file_flag = open(path, 'r')
        welcome_file_command = welcome_file_flag.read()
        welcome_file_flag.close()
        os.remove(path)
        if subprocess.call(welcome_file_command.split()):
            logging.warning('Can not display welcome screen.')

def start_ui_service():
    from jarabe.view.service import UIService

    ui_service = UIService()

def start_session_manager():
    from jarabe.model.session import get_session_manager

    session_manager = get_session_manager()
    session_manager.start()

def unfreeze_dcon_cb():
    logging.debug('STARTUP: unfreeze_dcon_cb')
    from jarabe.model import screen

    screen.set_dcon_freeze(0)

def setup_frame_cb():
    logging.debug('STARTUP: setup_frame_cb')
    from jarabe import frame
    frame.get_view()

def setup_keyhandler_cb():
    logging.debug('STARTUP: setup_keyhandler_cb')
    from jarabe.view import keyhandler
    from jarabe import frame
    keyhandler.setup(frame.get_view())

def setup_gesturehandler_cb():
    logging.debug('STARTUP: setup_gesturehandler_cb')
    from jarabe.view import gesturehandler
    from jarabe import frame
    gesturehandler.setup(frame.get_view())

def setup_cursortracker_cb():
    logging.debug('STARTUP: setup_cursortracker_cb')
    from jarabe.view import cursortracker
    cursortracker.setup()

def setup_journal_cb():
    logging.debug('STARTUP: setup_journal_cb')
    from jarabe.journal import journalactivity
    journalactivity.start()

def show_software_updates_cb():
    logging.debug('STARTUP: show_software_updates_cb')
    if os.path.isfile(os.path.expanduser('~/.sugar-update')):
        from jarabe.desktop import homewindow
        home_window = homewindow.get_instance()
        home_window.get_home_box().show_software_updates_alert()

def setup_notification_service_cb():
    from jarabe.model import notifications
    notifications.init()

def show_notifications_cb():
    client = GConf.Client.get_default()
    if not client.get_bool('/desktop/sugar/frame/show_notifications'):
        return

    from ceibal.notifier import Notifier
    n = Notifier()
    n.show_messages_from_shell()

def setup_file_transfer_cb():
    from jarabe.model import filetransfer
    filetransfer.init()

def setup_keyboard_cb():
    logging.debug('STARTUP: setup_keyboard_cb')

    gconf_client = GConf.Client.get_default()
    have_config = False

    try:
        display = GdkX11.x11_get_default_xdisplay()
        if display is not None:
            engine = Xkl.Engine.get_instance(display)
        else:
            logging.debug('setup_keyboard_cb: Could not get default display.')
            return

        configrec = Xkl.ConfigRec()
        configrec.get_from_server(engine)

        # FIXME, gconf_client_get_list not introspectable #681433
        layouts_from_gconf = gconf_client.get(
            '/desktop/sugar/peripherals/keyboard/layouts')
        layouts_list = []
        variants_list = []
        if layouts_from_gconf:
            for gval in layouts_from_gconf.get_list():
                layout = gval.get_string()
                layouts_list.append(layout.split('(')[0])
                variants_list.append(layout.split('(')[1][:-1])

            if layouts_list and variants_list:
                have_config = True
                configrec.set_layouts(layouts_list)
                configrec.set_variants(variants_list)

        model = gconf_client.get_string(\
            '/desktop/sugar/peripherals/keyboard/model')
        if model:
            have_config = True
            configrec.set_model(model)

        options = []
        # FIXME, gconf_client_get_list not introspectable #681433
        options_from_gconf = gconf_client.get(\
            '/desktop/sugar/peripherals/keyboard/options')
        if options_from_gconf:
            for gval in options_from_gconf.get_list():
                option = gval.get_string()
                options.append(option)
            if options:
                have_config = True
                configrec.set_options(options)

        if have_config:
            configrec.activate(engine)
    except Exception:
        logging.exception('Error during keyboard configuration')


def show_hidden_wireless_networks():
    from jarabe.journal.misc import get_hidden_ssids
    for ssid in get_hidden_ssids():
        subprocess.call('sudo iwlist eth0 scanning essid ' + ssid, shell=True)
	subprocess.call('sleep 10', shell=True)


def setup_window_manager():
    logging.debug('STARTUP: window_manager')

    # have to reset cursor(metacity sets it on startup)
    if subprocess.call('echo $DISPLAY; xsetroot -cursor_name left_ptr', shell=True):
        logging.warning('Can not reset cursor')

    if subprocess.call('metacity-message disable-keybindings',
            shell=True):
        logging.warning('Can not disable metacity keybindings')

    if subprocess.call('metacity-message disable-mouse-button-modifiers',
            shell=True):
        logging.warning('Can not disable metacity mouse button modifiers')

def file_monitor_changed_cb(monitor, one_file, other_file, event_type):
    global MONITOR_ACTION_TAKEN
    if (not MONITOR_ACTION_TAKEN) and \
       (one_file.get_path() == os.path.expanduser('~/.sugar/journal_created')):
        if event_type == Gio.FileMonitorEvent.CREATED:
            GObject.idle_add(show_notifications_cb)
            GObject.idle_add(setup_frame_cb)
            MONITOR_ACTION_TAKEN = True

def arrange_for_setup_frame_cb():
    path = Gio.File.new_for_path(os.path.expanduser('~/.sugar/journal_created'))
    monitor = path.monitor_file(Gio.FileMonitorFlags.NONE, None)
    monitor.connect('changed', file_monitor_changed_cb)
    MONITORS.append(monitor)

def osk_appeared_cb(monitor, one_file, other_file, event_type):
    if event_type != Gio.FileMonitorEvent.CHANGED:
        return

    if one_file.get_path() == os.path.expanduser(OSK_APPEARENCE_MONITOR_FILE):
        from jarabe.view.keyhandler import get_handle_accumulate_osk_func
	get_handle_accumulate_osk_func()(None)

def osk_disappeared_cb(monitor, one_file, other_file, event_type):
    if event_type != Gio.FileMonitorEvent.CHANGED:
        return

    if one_file.get_path() == os.path.expanduser(OSK_DISAPPEARENCE_MONITOR_FILE):
        from jarabe.view.keyhandler import get_handle_unaccumulate_osk_func
	get_handle_unaccumulate_osk_func()(None)

def arrange_for_osk_appearence_disappearence_hacks():
    osk_appearence_monitor_file_path = \
            Gio.File.new_for_path(os.path.expanduser(OSK_APPEARENCE_MONITOR_FILE))
    appearence_monitor = osk_appearence_monitor_file_path.monitor_file(Gio.FileMonitorFlags.NONE, None)
    appearence_monitor.connect('changed', osk_appeared_cb)
    MONITORS.append(appearence_monitor)

    osk_disappearence_monitor_file_path = \
            Gio.File.new_for_path(os.path.expanduser(OSK_DISAPPEARENCE_MONITOR_FILE))
    disappearence_monitor = osk_disappearence_monitor_file_path.monitor_file(Gio.FileMonitorFlags.NONE, None)
    disappearence_monitor.connect('changed', osk_disappeared_cb)
    MONITORS.append(disappearence_monitor)

def bootstrap():
    show_hidden_wireless_networks()
    setup_window_manager()

    from jarabe.view import launcher
    launcher.setup()

    GObject.idle_add(setup_keyhandler_cb)

    arrange_for_setup_frame_cb()
    arrange_for_osk_appearence_disappearence_hacks()

    GObject.idle_add(setup_gesturehandler_cb)
    GObject.idle_add(setup_journal_cb)
    GObject.idle_add(setup_notification_service_cb)
    GObject.idle_add(setup_file_transfer_cb)
    GObject.idle_add(show_software_updates_cb)
    GObject.idle_add(setup_accessibility_cb)

    if _USE_XKL:
        GObject.idle_add(setup_keyboard_cb)

def set_fonts():
    client = GConf.Client.get_default()
    face = client.get_string('/desktop/sugar/font/default_face')
    size = client.get_float('/desktop/sugar/font/default_size')
    settings = Gtk.Settings.get_default()
    settings.set_property("gtk-font-name", "%s %f" % (face, size))

def set_theme():
    settings = Gtk.Settings.get_default()
    sugar_theme = 'sugar-72'

    """
    Fetch the theme from Gconf.
    """
    client = GConf.Client.get_default()
    theme = client.get_string('/desktop/sugar/interface/gtk_theme')

    """
    See if 'SUGAR_SCALING' is set.
    """
    scaling_set = False
    if 'SUGAR_SCALING' in os.environ:
        if os.environ['SUGAR_SCALING'] == '100':
            scaling_set = True

    if (theme == 'sugar-contrast') and (scaling_set):
	sugar_theme = 'sugar-100-contrast'
    elif (theme == 'sugar-contrast') and (not scaling_set):
	sugar_theme = 'sugar-72-contrast'
    elif scaling_set:
	sugar_theme = 'sugar-100'

    settings.set_property('gtk-theme-name', sugar_theme)
    settings.set_property('gtk-icon-theme-name', 'sugar')

def setup_accessibility_cb():
    from jarabe.model import accessibility
    accessibility_manager = accessibility.AccessibilityManager()
    accessibility_manager.setup_accessibility()

def export_proxy_settings():
    """
    Export manual proxy settings from GConf as environment variables

    Some applications and tools and even some parts of Sugar will use
    the http_proxy environment variable if set, but don't use the Gnome
    (GConf) proxy settings.
    """
    client = GConf.Client.get_default()

    # Note: See https://dev.laptop.org.au/issues/1179#note-9
    if client.get_string('/system/proxy/mode') == 'none':
        return

    http_host = client.get_string('/system/http_proxy/host')
    http_port = client.get_int('/system/http_proxy/port')
    use_auth = client.get_bool('/system/http_proxy/use_authentication')
    if use_auth:
        user = client.get_string('/system/http_proxy/authentication_user')
        pw = client.get_string('/system/http_proxy/authentication_password')
        http_proxy = 'http://%s:%s@%s:%d/' % (user, pw, http_host, http_port)
    else:
        http_proxy = 'http://%s:%d/' % (http_host, http_port)

    os.environ['http_proxy'] = http_proxy

    ignore_hosts = []
    ignore_hosts_list = client.get('/system/http_proxy/ignore_hosts')

    # Process, only if the "ignore_hosts_list" is non-empty.
    if ignore_hosts_list:
        for entry in ignore_hosts_list.get_list():
            ignore_hosts.append(entry.get_string())
        os.environ['no_proxy'] = ','.join(ignore_hosts)

def start_home():
    from jarabe.desktop import homewindow

    start_ui_service()
    start_session_manager()

    # open homewindow before window_manager to let desktop appear fast
    home_window = homewindow.get_instance()
    home_window.show()

    screen = Wnck.Screen.get_default()
    screen.connect('window-manager-changed', __window_manager_changed_cb)
    _check_for_window_manager(screen)

def intro_window_done_cb(window):
    start_home()


def main():
    try:
        from sugar3 import env
        # Remove temporary files. See http://bugs.sugarlabs.org/ticket/1876
        data_dir = os.path.join(env.get_profile_path(), 'data')
        shutil.rmtree(data_dir, ignore_errors=True)
        os.makedirs(data_dir)
        cleanup_logs(env.get_logs_path())
    except OSError, e:
        # logs cleanup is not critical; it should not prevent sugar from
        # starting if (for example) the disk is full or read-only.
        print 'logs cleanup failed: %s' % e

    from sugar3 import logger
    # NOTE: This needs to happen so early because some modules register translatable
    # strings in the module scope.
    from jarabe import config
    gettext.bindtextdomain('sugar', config.locale_path)
    gettext.bindtextdomain('sugar-toolkit', config.locale_path)
    gettext.textdomain('sugar')

    from jarabe.model import sound
    from jarabe import intro
    from jarabe.intro.window import IntroWindow

    logger.start('shell')

    client = GConf.Client.get_default()
    client.set_string('/apps/metacity/general/mouse_button_modifier',
                      '<Super>')

    timezone = client.get_string('/desktop/sugar/date/timezone')
    if timezone is not None and timezone:
        os.environ['TZ'] = timezone

    export_proxy_settings()
    set_fonts()
    set_theme()

    # this must be added early, so that it executes and unfreezes the screen
    # even when we initially get blocked on the intro screen
    GObject.idle_add(unfreeze_dcon_cb)


    GObject.idle_add(setup_cursortracker_cb)
    # make sure we have the correct cursor in the intro screen
    # TODO #3204
    if subprocess.call('echo $DISPLAY; xsetroot -cursor_name left_ptr', shell=True):
        logging.warning('Can not reset cursor')

    sound.restore()

    sys.path.append(config.ext_path)

    icons_path = os.path.join(config.data_path, 'icons')
    Gtk.IconTheme.get_default().append_search_path(icons_path)

    # OLPC: open welcome screen if booted for the first time
    show_welcome_screen()

    if not intro.check_profile():
        win = IntroWindow()
        win.connect("done", intro_window_done_cb)
        win.show_all()
    else:
        start_home()

    try:
        Gtk.main()
    except KeyboardInterrupt:
        print 'Ctrl+C pressed, exiting...'


def __window_manager_changed_cb(screen):
    _check_for_window_manager(screen)


def _check_for_window_manager(screen):
    wm_name = screen.get_window_manager_name()
    if wm_name is not None:
        screen.disconnect_by_func(__window_manager_changed_cb)
        bootstrap()


main()