# -*- coding: iso-8859-1 -*-

# GNU Solfege - ear training for GNOME
# Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005  Tom Cato Amundsen
#
# 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

copyright = "Copyright © 1999-2005 Tom Cato Amundsen <tca@gnu.org>"

import __builtin__
__builtin__.app_running = True
__builtin__.__exdata__ = []

import sys
import os
import time
import runtime

import configureoutput

import optparse

opt_parser = optparse.OptionParser(usage='GNU Solfege %s\nType "man solfege" for more details.' % configureoutput.VERSION_STRING )
opt_parser.add_option('-v', '--version', action='store_true', dest='version')
opt_parser.add_option('-w', '--warranty', action='store_true', dest='warranty',
    help='show warranty and copyright')
opt_parser.add_option('--no-splash', action='store_false', dest='no_splash',
    default=False)
opt_parser.add_option('--verbose-sound-init', action='store_true',
    default=False,
    dest='verbose_sound_init', help='Display more info about the sound setup')
opt_parser.add_option('--no-sound', action='store_true', dest='no_sound',
    default=False,
    help='Do not play any sounds. Useful when porting.')
opt_parser.add_option('--no-random', action='store_true', dest='no_random',
    help='For debugging only: Select questions from lesson files in sequential order.')
opt_parser.add_option('--without-gtkhtml', action='store_true', 
    dest='without_gtkhtml',
    help='Run without gtkhtml2 even if it is installed')
opt_parser.add_option('--without-gnome', action='store_true', 
    dest='without_gnome',
    help='Run without the gnome module even if it is installed')


options, args = opt_parser.parse_args()

if options.version:
    print """GNU Solfege %s
This is free software. It is covered by the GNU General Public License,
and you are welcome to change it and/or distribute copies of it under
certain conditions. Invoke as `solfege --warranty` for more information.

%s
        """ % (configureoutput.VERSION_STRING, copyright)
    sys.exit()

if options.warranty:
    print """GNU Solfege %s
%s
    This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.

    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 (refer to the file COPYING) of the
GNU General Public License along with this program; if not, write to
the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139,
USA.
    """ % (configureoutput.VERSION_STRING, copyright)
    sys.exit()

# silent, GNOME, be silent!
sys.argv.append('--disable-sound')
runtime.init(options)

import gtk

if not runtime.has_gnome():
    sys.path.insert(0, "gnomeemu")

class SplashWin(gtk.Window):
    def __init__(self):
        gtk.Window.__init__(self, gtk.WINDOW_POPUP)
        self.set_position(gtk.WIN_POS_CENTER)
        self.set_resizable(True)
        frame = gtk.Frame()
        frame.set_shadow_type(gtk.SHADOW_OUT)
        self.add(frame)
        vbox = gtk.VBox()
        vbox.set_border_width(20)
        frame.add(vbox)
        l = gtk.Label(_("Starting GNU Solfege %s") % configureoutput.VERSION_STRING)
        l.set_name("Heading1")
        vbox.pack_start(l)
        l = gtk.Label("http://www.solfege.org")
        vbox.pack_start(l)
        self.g_infolabel = gtk.Label('')
        vbox.pack_start(self.g_infolabel)
        self.show_all()
    def show_progress(self, txt):
        self.g_infolabel.set_text(txt)
        while gtk.events_pending():
            gtk.main_iteration(0)

if not options.no_splash:
    splash_win = SplashWin()
    time.sleep(0.1)
    gtk.gdk.flush()
    while gtk.events_pending():
        gtk.main_iteration(0)
else:
    splash_win = None

if splash_win:
    splash_win.show_progress("importing GNOME modules")

import gnome, gnome.ui
# FIXME PAD AND PAD_SMALL are missing from some gnome-python releases.
try:
    gnome.ui.PAD
except:
    gnome.ui.PAD = 8
    gnome.ui.PAD_SMALL = 4

if splash_win:
    splash_win.show_progress("importing application modules")

import tracebackwindow
# redirect error messages to a window that will popup if
# something bad happens.

sys.stderr = tracebackwindow.TracebackWindow()

import const
import app
from htmlwidget import HtmlWidget
import utils
import history
from configwindow import ConfigWindow
import soundcard
import mpd
import mpd.musicdisplayer
import gu
import cfg
import stock

import chord
import chordvoicing
import harmonicinterval
import melodicinterval
import singinterval

import exercise_setup
exercise_setup.register_exercise({
    'exercise_name': 'id-by-name',
    'stock-icon': 'solfege-identify-scale',
    'menupath': '/Menubar/FileMenu/MiscMenu',
    'name': _("_Scales"),
    'exercise_config': 'solfege/scales',
    'action': 'start-exercise-scales',
})

import idbyname
import dictation
import twelvetone
import idtone
import compareintervals
import singchord
import rhythm
import identifybpm
import harmonicprogressiondictation
import singanswer
#import example

exercise_setup.register_exercise({
    'exercise_name': 'id-by-name',
    'stock-icon': 'solfege-identify-scale',
    'menupath': '/Menubar/FileMenu/MiscMenu',
    'name': _("Scales in t_hirds"),
    'exercise_config': 'solfege/scales-thirds',
    'action': 'start-exercise-scales-in-thirds',
    'notoolbar': True,
})


class DocViewer(gtk.VBox):
    def __init__(self, activate_cb):
        gtk.VBox.__init__(self)
        self.m_htmlwidget = HtmlWidget(activate_cb, self.on_anchor_track)
        self.m_htmlwidget.show_all()
        self.pack_start(self.m_htmlwidget)
        self.set_size_request(500, 300)
        #self.read_docfile = self.m_htmlwidget.read_docfile
        self.get_vadjustment = self.m_htmlwidget.get_vadjustment
        self.on_key_press_event = self.m_htmlwidget.on_key_press_event
        self.m_statusbar = gtk.Statusbar()
        self.m_statusbar.show()
        self.pack_start(self.m_statusbar, False)
        self.source = self.m_htmlwidget.source
        self.grab_focus = self.m_htmlwidget.grab_focus
    def read_docfile(self, fn, anchor):
        """
        We reread the docfile even if we are alreado displaying this file,
        just in case it has changed on disk.
        """
        if fn:
            self.m_htmlwidget.read_docfile(fn)
        #if anchor:
        #    #FIXME jump_to_anchor is not implemented yet it gnome-python,
        #    # or maybe I just don't understand how to use it.
        #    self.m_htmlwidget.g_view.jump_to_anchor(anchor)
        #else:
        a = self.m_htmlwidget.get_vadjustment()
        a.set_value(0.0)
    def on_anchor_track(self, url):
        if url:
            # remove newlines in url because it make the window resize
            s = url.replace("\n", "")
            self.m_statusbar.pop(1)
            self.m_statusbar.push(1, s)
        else:
            self.m_statusbar.pop(1)


class MusicViewerWindow(gtk.Dialog):
    def __init__(self, app):
        gtk.Dialog.__init__(self)
        self.m_app = app
        self.set_default_size(400, 200)
        self.g_music_displayer = mpd.musicdisplayer.MusicDisplayer(utils.play_tone)
        self.vbox.pack_start(self.g_music_displayer)
        b = gu.bButton(self.action_area, _("Close"), self.m_app.close_musicviewer)
        b.grab_focus()
        self.connect('destroy', self.m_app.close_musicviewer)
        self.show_all()
    def display_music(self, music):
        fontsize = cfg.get_int('config/feta_font_size=20')
        self.g_music_displayer.display(music, fontsize)

class MainWin(gnome.ui.App, cfg.ConfigUtils):
    def __init__(self, options, datadir):
        gnome.ui.App.__init__(self, 'solfege', 'GNU Solfege')
        self.icons = stock.SolfegeIconFactory(self, datadir)
        self.set_default_size(400, 400)
        pixbuf = self.render_icon('solfege-icon', gtk.ICON_SIZE_DIALOG)
        self.set_icon(pixbuf)
        cfg.ConfigUtils.__dict__['__init__'](self, 'mainwin')
        self.set_resizable(self.get_bool('gui/mainwin_user_resizeable'))
        self.add_watch('gui/mainwin_user_resizeable', lambda s: self.set_resizable(self.get_bool('gui/mainwin_user_resizeable')))
        self.connect('destroy', self.quit_program)
        self.connect('key_press_event', self.on_key_press_event)
        self.g_about_window = None
        self.main_box = gtk.VBox()
        self.main_box.show()
        self.set_contents(self.main_box)
        self.m_exercise = None
        self.m_viewer = None
        self.box_dict = {}
        self.g_config_window = None
        self.g_musicviewer_window = None
        self.m_history = history.History()
        self.m_key_bindings = {'history_back_ak': self.history_back,
                               'history_forward_ak': self.history_forward,
                               'history_reload_ak': self.history_reload}
        self.m_app = app.SolfegeApp(options, self)
        self.setup_menu_and_toolbar()
        self.m_app.handle_href('welcome.html')
    def setup_menu_and_toolbar(self):
        self.g_action_group = gtk.ActionGroup('SolfegeActions')
        self.g_action_group.add_actions([
          ('FileMenu', None, _('_File')),
          ('ChordsMenu', None, _('_Chords')),
          ('IntervalsMenu', None, _('_Intervals')),
          ('RhythmMenu', None, _('_Rhythm')),
          ('MiscMenu', None, _('_Misc exercises')),
          ('TheoryMenu', None, _('_Theory')),
          ('TheoryIntervals', None, _('_Intervals'), None, None,
            lambda o: self.m_app.handle_href('theory-intervals.html')),
          ('ExerciseMenu', None, ''),
          ('ViewMenu', None, _('_View')),
          ('OpenPreferencesWindow', 'gtk-preferences', None, '<ctrl>F12', None,
            self.open_preferences_window),
          ('HelpMenu', None, _('_Help')),
          ('HelpHelp', 'gtk-help', _('_Help on current exercise'), 'F1', None,
            lambda o: self.m_app.please_help_me()),
          ('HelpWelcome', None, _('_Welcome'), None, None,
            lambda o: self.m_app.handle_href('welcome.html')),
          ('HelpIndex', None, _('_All help files'), None, None,
            lambda o: self.m_app.handle_href('toc.html')),
          ('HelpAllLessonFiles', None, _('All installed _lesson files'), None,
            None, lambda o: self.m_app.handle_href('solfege:all-lessonfiles')),
          ('HelpCopyright', None, _('_Copyright notice'), None, None,
            lambda o: self.m_app.handle_href('copyright.html')),
          ('HelpCredits', None, _('C_redits'), None, None,
            lambda o: self.m_app.handle_href('AUTHORS.html')),
          ('HelpOnline', None, _('_Mailinglists, web page etc.'), None, None,
            lambda o: self.m_app.handle_href('online-resources.html')),
          ('HelpReportingBugs', None, _('Reporting _bugs'), None, None,
            lambda o: self.m_app.handle_href('bug-reporting.html')),
          ('HelpAbout', 'gtk-about', None, None, None, self.show_about_window),
          ('AppQuit', 'gtk-quit', None, None, None, self.quit_program),
          ('ViewZoomIn', 'gtk-zoom-in', _('Help viewer zoom in'), '<ctrl>plus', None,
           lambda w: self.box_dict['docviewer'].m_htmlwidget.g_view.zoom_in()),
          ('ViewZoomOut', 'gtk-zoom-out', _('Help viewer zoom out'), '<ctrl>minus', None,
           lambda w: self.box_dict['docviewer'].m_htmlwidget.g_view.zoom_out()),
          ('ViewZoom100', 'gtk-zoom-100', _('Help viewer zoom reset'), '<ctrl>equal', None,
           lambda w: self.box_dict['docviewer'].m_htmlwidget.g_view.zoom_reset()),
          ('BrowserGoBack', 'gtk-go-back', None, None, None, self.history_back),
          ('BrowserGoForward', 'gtk-go-forward', None, None, None, self.history_forward),
        ])
        self.g_ui_manager = gtk.UIManager()
        self.g_ui_manager.insert_action_group(self.g_action_group, 1)

        self.g_ui_manager.add_ui_from_file("ui.xml")

        a = gtk.ToggleAction('ToggleNavButtonsVisible', _('_Navigation buttons'), None, None)
        if self.get_bool('gui/navbar_visible'):
            a.set_active(True)
        self.add_watch('gui/navbar_visible', self.on_watch_navbar_visible)
        a.connect('activate', lambda w: self.set_bool('gui/navbar_visible', w.get_active()))
        self.g_action_group.add_action(a)

        a = gtk.ToggleAction('ToggleToolbarVisible', _('_Toolbar'), None, None)
        if self.get_bool('gui/toolbar_visible'):
            a.set_active(True)
        self.add_watch('gui/toolbar_visible', self.on_watch_toolbar_visible)
        a.connect('activate', lambda w: self.set_bool('gui/toolbar_visible', w.get_active()))
        self.g_action_group.add_action(a)

        if runtime.has_gtkhtml2():
            self.g_ui_manager.add_ui_from_string("""\
<menubar name='Menubar'>
 <menu action='ViewMenu'>
      <menuitem action='ViewZoomIn'/>
      <menuitem action='ViewZoomOut'/>
      <menuitem action='ViewZoom100'/>
 </menu>
</menubar>""")

        self.add_accel_group(self.g_ui_manager.get_accel_group())
        self.g_ui_manager.get_accel_group().connect_group(gtk.keysyms.KP_Equal,
           gtk.gdk.CONTROL_MASK, 0,
           lambda w, a, b, c: self.box_dict['docviewer'].m_htmlwidget.g_view.zoom_reset())
        self.g_ui_manager.get_accel_group().connect_group(gtk.keysyms.KP_Subtract,
           gtk.gdk.CONTROL_MASK, 0,
           lambda w, a, b, c: self.box_dict['docviewer'].m_htmlwidget.g_view.zoom_out())
        self.g_ui_manager.get_accel_group().connect_group(gtk.keysyms.KP_Add,
           gtk.gdk.CONTROL_MASK, 0,
           lambda w, a, b, c: self.box_dict['docviewer'].m_htmlwidget.g_view.zoom_in())
        for e in __exdata__:
            if 'menupath' in e:
                a = gtk.Action(e['action'], e['name'], e['exercise_pretty_name'], e['stock-icon'])
                self.g_action_group.add_action(a)
                a.connect('activate', lambda o, e=e:
                    self.m_app.handle_href('solfege:/%s/%s' % (
                      e['exercise_name'], e['exercise_config'])))
                if not self.g_ui_manager.get_widget(e['menupath']):
                    print "Miss:", e['menupath']
                self.g_ui_manager.add_ui(self.g_ui_manager.new_merge_id(),
                   e['menupath'], e['name'], e['action'],
                   gtk.UI_MANAGER_MENUITEM, False)
                if 'notoolbar' not in e:
                    self.g_ui_manager.add_ui(self.g_ui_manager.new_merge_id(),
                       '/Toolbar', e['name'], e['action'],
                       gtk.UI_MANAGER_TOOLITEM, False)
        self.set_menus(self.g_ui_manager.get_widget('/Menubar'))
        self.on_watch_toolbar_style('gui/toolbar_style')
        self.add_watch('gui/toolbar_style', self.on_watch_toolbar_style)
        self.main_box.pack_start(self.g_ui_manager.get_widget('/Toolbar'), False)
        if not self.get_bool('gui/toolbar_visible'):
            self.g_ui_manager.get_widget('/Toolbar').hide()
        if not self.get_bool('gui/navbar_visible'):
            self.g_ui_manager.get_widget('/Toolbar/BrowserGoBack').hide()
            self.g_ui_manager.get_widget('/Toolbar/BrowserGoForward').hide()
        #FIXME not using GnomeApp.add_toolbar
        #self.add_toolbar(self.g_ui_manager.get_widget('/Toolbar'),
        #  'toolbaren', 'normal', 'top', 1, 0,0)
    def dialog_yesno(self, text):
        """Return True if the answer is yes, False if the answer is no.
        """
        m = gtk.MessageDialog(self, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION,
                gtk.BUTTONS_YES_NO, text)
        ret = m.run()
        m.destroy()
        return ret == gtk.RESPONSE_YES
    def display_exception_message(self, exception, err_file=None):
        """Call this function only inside an except clause."""
        if err_file:
            msg = _("Exception catched in %s:%i\n") % (err_file, sys.exc_info()[2].tb_lineno) + "\n"
        else:
            msg = ""
        msg += str(exception)
        m = gtk.MessageDialog(self, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR,
                              gtk.BUTTONS_CLOSE, msg)
        m.set_title(sys.exc_info()[0].__name__)
        m.run()
        m.destroy()
    def display_error_message(self, msg, err_pos=None):
        if err_pos:
            msg = _("Error found in %s:\n") % err_pos + "\n" + msg
        m = gtk.MessageDialog(self, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR,
                              gtk.BUTTONS_CLOSE, None)
        m.set_markup(msg)
        m.run()
        m.destroy()
    def display_question_music_error_message(self, idx, lessonfile, exception, err_file=None):
        """Call this function only inside an except clause."""
        msg = _("Failed to parse the music for question number %(idx)i in '%(lf)s':\n%(ex)s") % {'idx': idx, 'lf': lessonfile, 'ex': exception}
        self.display_exception_message(msg, err_file)
    def show_about_window(self, widget):
        #if not self.g_about_window:
        if 1:
            trans = _("SOLFEGETRANSLATORS")
            if trans == 'SOLFEGETRANSLATORS':
                trans = ""
            pixbuf = self.render_icon('solfege-icon', gtk.ICON_SIZE_DIALOG)
            self.g_about_window = gnome.ui.About("GNU Solfege",
                  configureoutput.VERSION_STRING,
                  copyright,
                  _("GPL'ed ear training.") + "\n" + "http://www.solfege.org",
                  ["Tom Cato Amundsen",
                  'Oliver Vollmer %s' % _("(toolbar icons)"),
                  'Giovanni Chierico %s' % _("(some lessonfiles)"),
                  'Michael Becker %s' % _("(some lessonfiles)"),
                  'Joe Lee %s' % _("(sound code for the MS Windows port)"),
                  ],
                  ["Tom Cato Amundsen"],
                  trans, pixbuf)
            #self.g_about_window.connect('destroy', self.hide_about_window)
            #self.g_about_window.show()
            #FIXME this sucks.
            i = self.g_about_window.run()
            #self.g_about_window.destroy()
    def hide_about_window(self, widget):
        self.g_about_window.destroy()
        self.g_about_window = None
    def post_constructor(self):
        self.box_dict['docviewer'].grab_focus()
        if self.m_app.m_sound_init_exception is not None:
            self.m_app.display_sound_init_error_message(self.m_app.m_sound_init_exception)
    def activate_exercise(self, href):
        protocol, action, exname, anchor, collection, lessonfile, config = \
           utils.parse_url(href)
        assert protocol == 'solfege'
        if self.m_viewer:
            self.box_dict[self.m_viewer].hide()
        self.box_dict[exname].show()
        self.m_viewer = exname
        if action in ['practise', 'config', 'statistics']:
            # We need this test because not all exercises use a notebook.
            if self.box_dict[self.m_viewer].g_notebook:
                self.box_dict[self.m_viewer].g_notebook.set_current_page(
                   ['practise', 'config', 'statistics'].index(action))
        self.set_title("Solfege - " + self.box_dict[exname].get_pretty_name())
        self.m_history.add(href)
    def _show_docviewer(self):
        if 'docviewer' not in self.box_dict:
            self.box_dict['docviewer'] = DocViewer(self.m_app.handle_href)
            self.main_box.pack_start(self.box_dict['docviewer'])
        if self.m_viewer and (self.m_viewer != 'docviewer'):
            self.box_dict[self.m_viewer].hide()
        self.m_viewer = 'docviewer'
        self.box_dict['docviewer'].show()
    def display_docfile(self, fn, anchor):
        self._show_docviewer()
        self.box_dict['docviewer'].read_docfile(fn, anchor)
        self.set_title("Solfege - %s" % fn)
        self.m_history.add(fn)
    def display_html(self, html):
        self._show_docviewer()
        self.box_dict['docviewer'].source(html)
    def history_back(self, *v):
        if self.m_viewer == 'docviewer':
            self.m_history.set_adj_of_current(
              self.box_dict['docviewer'].get_vadjustment().get_value())
        self.m_history.back()
        self.m_history.lock()
        url, adj = self.m_history.get_current()
        self.m_app.handle_href(url, display_docfile_set_adj=0)
        if self.m_viewer == 'docviewer':
            self.box_dict['docviewer'].get_vadjustment().set_value(adj)
        self.m_history.unlock()
    def history_forward(self, *v):
        if self.m_viewer == 'docviewer':
            self.m_history.set_adj_of_current(
              self.box_dict['docviewer'].get_vadjustment().get_value())
        self.m_history.forward()
        self.m_history.lock()
        url, adj = self.m_history.get_current()
        self.m_app.handle_href(url, display_docfile_set_adj=0)
        if self.m_viewer == 'docviewer':
            self.box_dict['docviewer'].get_vadjustment().set_value(adj)
        self.m_history.unlock()
    def history_reload(self, *v):
        self.m_history.lock()
        self.m_app.handle_href(self.m_history.get_current()[0])
        self.m_history.unlock()
    def initialise_exercise(self, teacher):
        """
        Create a Gui object for the exercise and add it to
        the box_dict dict.
        """
        assert teacher.m_exname not in self.box_dict
        n = utils.exercise_name_to_module_name(teacher.m_exname)
        self.box_dict[teacher.m_exname] = globals()[n].Gui(teacher, self)
        self.main_box.pack_start(self.box_dict[teacher.m_exname])
    def on_key_press_event(self, widget, event):
        if event.type == gtk.gdk.KEY_PRESS:
            for s in self.m_key_bindings:
                if (event.state & (gtk.gdk.CONTROL_MASK|gtk.gdk.SHIFT_MASK|gtk.gdk.MOD1_MASK), event.keyval) \
                         == utils.parse_key_string(self.get_string(s)):
                    self.m_key_bindings[s]()
                    return 1
        self.box_dict[self.m_viewer].on_key_press_event(widget, event)
    def open_preferences_window(self, widget=None):
        if not self.g_config_window:
            self.g_config_window = ConfigWindow(self.m_app)
            self.g_config_window.show()
        else:
            self.g_config_window.show()
    def on_zoom_in(self, *v):
        self.box_dict['docviewer'].m_htmlwidget.g_view.zoom_in()
    def on_watch_toolbar_style(self, s):
        assert self.get_string('gui/toolbar_style') in ('text', 'icons', 'both')

        self.g_ui_manager.get_widget('/Toolbar').set_style({
            'text': gtk.TOOLBAR_TEXT,
            'icons': gtk.TOOLBAR_ICONS,
            'both': gtk.TOOLBAR_BOTH}[self.get_string('gui/toolbar_style')])
    def on_watch_toolbar_visible(self, s):
        self.g_ui_manager.get_widget('/Menubar/ViewMenu/ToggleToolbarVisible').set_active(self.get_bool('gui/toolbar_visible'))
        if self.get_bool('gui/toolbar_visible'):
            self.g_ui_manager.get_widget('/Toolbar').show()
        else:
            self.g_ui_manager.get_widget('/Toolbar').hide()
    def on_watch_navbar_visible(self, widget):
        self.g_ui_manager.get_widget('/Menubar/ViewMenu/ToggleNavButtonsVisible').set_active(self.get_bool('gui/navbar_visible'))
        if self.get_bool('gui/navbar_visible'):
            self.g_ui_manager.get_widget('/Toolbar/BrowserGoBack').show()
            self.g_ui_manager.get_widget('/Toolbar/BrowserGoForward').show()
        else:
            self.g_ui_manager.get_widget('/Toolbar/BrowserGoBack').hide()
            self.g_ui_manager.get_widget('/Toolbar/BrowserGoForward').hide()
    def quit_program(self, w=None):
        self.m_app.quit_program()
        gtk.main_quit()
    def display_in_musicviewer(self, music):
        if not self.g_musicviewer_window:
            self.g_musicviewer_window = MusicViewerWindow(self)
            self.g_musicviewer_window.show()
        self.g_musicviewer_window.display_music(music)
    def close_musicviewer(self, widget=None):
        self.g_musicviewer_window.destroy()
        self.g_musicviewer_window = None

if splash_win:
    splash_win.show_progress("running gnome.program_init")

gnome.program_init('solfege', configureoutput.VERSION_STRING)
prog = gnome.program_get()
prog.parse_args()

import locale
locale.setlocale(locale.LC_NUMERIC, "C")

cfg.set_bool('config/no_random', bool(options.no_random))

if splash_win:
    splash_win.show_progress("creating MainWin")

if splash_win:
    splash_win.destroy()

def start_app(prefix, datadir):
    w = MainWin(options, datadir)
    w.show()
    w.post_constructor()
    import gtk
    gtk.main()

