Пример #1
0
 def on_rename_profile(self, w):
     if self.m_default_profile == self.get_profile():
         rename_default = True
     else:
         rename_default = False
     dlg = RenameProfileDialog(self.get_profile())
     dlg.show_all()
     ret = dlg.run()
     if ret == Gtk.ResponseType.ACCEPT:
         path, column = self.g_tw.get_cursor()
         it = self.g_liststore.get_iter(path)
         try:
             os.rename(
                 os.path.join(filesystem.app_data(), u"profiles",
                              self.get_profile()),
                 os.path.join(filesystem.app_data(), u"profiles",
                              dlg.g_entry.get_text().decode("utf-8")))
             if rename_default:
                 self.m_default_profile = dlg.g_entry.get_text().decode(
                     "utf-8")
         except OSError, e:
             gu.display_exception_message(e)
             dlg.destroy()
             return
         path, column = self.g_tw.get_cursor()
         self.g_liststore.set(self.g_liststore.get_iter(path), 0,
                              dlg.g_entry.get_text().decode("utf-8"))
Пример #2
0
    def on_rename_profile(self, w):
        if self.m_default_profile == self.get_profile():
            rename_default = True

        else:
            rename_default = False
        dlg = RenameProfileDialog(self.get_profile())
        dlg.show_all()
        ret = dlg.run()

        if ret == Gtk.ResponseType.ACCEPT:
            path, column = self.g_tw.get_cursor()
            it = self.g_liststore.get_iter(path)
            try:
                os.rename(os.path.join(
                    filesystem.app_data(), u"profiles", self.get_profile()),
                    os.path.join(filesystem.app_data(),
                        u"profiles", dlg.g_entry.get_text().decode("utf-8")))

                if rename_default:
                    self.m_default_profile = dlg.g_entry.get_text().decode("utf-8")
            except OSError, e:
                gu.display_exception_message(e)
                dlg.destroy()
                return
            path, column = self.g_tw.get_cursor()
            self.g_liststore.set(self.g_liststore.get_iter(path),
                0, dlg.g_entry.get_text().decode("utf-8"))
Пример #3
0
 def delete_obsolete_statistics(self, *w):
     if gu.dialog_delete(_("Delete obsolete statistics?"), self,
             _(u"This will delete the directory «%s».") % os.path.join(filesystem.app_data(), u"statistics")):
         try:
             shutil.rmtree(os.path.join(filesystem.app_data(), u"statistics"))
         except OSError, e:
             gu.display_exception_message(e)
         self.update_old_statistics_info()
Пример #4
0
    def __init__(self, default_profile):
        gtk.Dialog.__init__(self, _("GNU Solfege - Choose User Profile"))
        # We save the initially selected profile, because we need to keep
        # track of it if the user renames it and then presses cancel.
        self.m_default_profile = default_profile
        vbox = gu.hig_dlg_vbox()
        self.vbox.pack_start(vbox, False)
        l = gtk.Label(
            _("Solfege will save your statistics and test results in the user profile. By adding additional user profiles to Solfege, multiple users can share a user account on the operating system."
              ))
        l.set_alignment(0.0, 0.5)
        l.set_line_wrap(True)
        vbox.pack_start(l)

        hbox = gtk.HBox()
        hbox.set_spacing(gu.hig.SPACE_MEDIUM)
        vbox.pack_start(hbox)
        button_box = gtk.VBox()

        self.g_create_profile = gtk.Button(_(u"_Create profile\u2026"))
        self.g_create_profile.connect('clicked', self.on_create_profile)
        button_box.pack_start(self.g_create_profile, False)

        self.g_rename_profile = gtk.Button(_(u"_Rename profile\u2026"))
        self.g_rename_profile.connect('clicked', self.on_rename_profile)
        button_box.pack_start(self.g_rename_profile, False)

        self.g_delete_profile = gtk.Button(_(u"_Delete profile\u2026"))
        self.g_delete_profile.connect('clicked', self.on_delete_profile)
        button_box.pack_start(self.g_delete_profile, False)

        hbox.pack_start(button_box, False)
        self.g_liststore = liststore = gtk.ListStore(gobject.TYPE_STRING)
        liststore.append((_("Standard profile"), ))
        if os.path.exists(os.path.join(filesystem.app_data(), 'profiles')):
            for subdir in os.listdir(
                    os.path.join(filesystem.app_data(), 'profiles')):
                liststore.append((subdir, ))
        #
        self.g_tw = tw = gtk.TreeView(liststore)
        tw.connect('row-activated',
                   lambda a, b, c: self.response(gtk.RESPONSE_ACCEPT))
        tw.set_headers_visible(False)
        renderer = gtk.CellRendererText()
        column = gtk.TreeViewColumn(None, renderer, text=0)
        tw.append_column(column)
        hbox.pack_start(tw, False)
        tw.show()
        tw.connect('cursor-changed', self.on_cursor_changed)
        tw.set_cursor((0, ))
        for idx, s in enumerate(self.g_liststore):
            if s[0] == default_profile:
                tw.set_cursor((idx, ))
        #
        chk = gu.nCheckButton("app", "noprofilemanager",
                              _("D_on't ask at startup"))
        vbox.pack_start(chk, False)
        self.show_all()
Пример #5
0
    def __init__(self, parent, default_profile):
        Gtk.Dialog.__init__(self, _("GNU Solfege - Choose User Profile"),
                            parent)
        # Set a small size, and let the widgets expand the dialog
        self.set_default_size(100, 100)
        # We save the initially selected profile, because we need to keep
        # track of it if the user renames it and then presses cancel.
        self.m_default_profile = default_profile
        vbox = gu.hig_dlg_vbox()
        self.get_content_area().pack_start(vbox, False, False, 0)
        l = Gtk.Label(_("Solfege will save your statistics and test results in the user profile. By adding additional user profiles to Solfege, multiple users can share a user account on the operating system."))
        l.set_alignment(0.0, 0.5)
        l.set_line_wrap(True)
        vbox.pack_start(l, True, True, 0)

        hbox = Gtk.HBox()
        hbox.set_spacing(gu.hig.SPACE_MEDIUM)
        vbox.pack_start(hbox, True, True, 0)
        button_box = Gtk.VBox()

        self.g_create_profile = Gtk.Button.new_with_mnemonic(_("_Create profile\u2026"))
        self.g_create_profile.connect('clicked', self.on_create_profile)
        button_box.pack_start(self.g_create_profile, False, False, 0)

        self.g_rename_profile = Gtk.Button.new_with_mnemonic(_("_Rename profile\u2026"))
        self.g_rename_profile.connect('clicked', self.on_rename_profile)
        button_box.pack_start(self.g_rename_profile, False, False, 0)

        self.g_delete_profile = Gtk.Button.new_with_mnemonic(_("_Delete profile\u2026"))
        self.g_delete_profile.connect('clicked', self.on_delete_profile)
        button_box.pack_start(self.g_delete_profile, False, False, 0)

        hbox.pack_start(button_box, False, False, 0)
        self.g_liststore = liststore = Gtk.ListStore(GObject.TYPE_STRING)
        liststore.append((_("Standard profile"),))
        if os.path.exists(os.path.join(filesystem.app_data(), 'profiles')):
            for subdir in os.listdir(os.path.join(filesystem.app_data(),
                'profiles')):
                liststore.append((subdir,))
        #
        self.g_tw = tw = Gtk.TreeView(liststore)
        tw.connect('row-activated', lambda a, b, c: self.response(Gtk.ResponseType.ACCEPT))
        tw.set_headers_visible(False)
        renderer = Gtk.CellRendererText()
        column = Gtk.TreeViewColumn(None, renderer, text=0)
        tw.append_column(column)
        hbox.pack_start(tw, False, False, 0)
        tw.show()
        tw.connect('cursor-changed', self.on_cursor_changed)
        tw.set_cursor((0,))
        for idx, s in enumerate(self.g_liststore):
            if s[0] == default_profile:
                tw.set_cursor((idx, ))
        #
        chk = gu.nCheckButton("app", "noprofilemanager", _("D_on't ask at startup"))
        vbox.pack_start(chk, False, False, 0)
        self.show_all()
Пример #6
0
 def delete_obsolete_statistics(self, *w):
     if gu.dialog_delete(
             _("Delete obsolete statistics?"), self,
             _(u"This will delete the directory «%s».") %
             os.path.join(filesystem.app_data(), u"statistics")):
         try:
             shutil.rmtree(
                 os.path.join(filesystem.app_data(), u"statistics"))
         except OSError, e:
             gu.display_exception_message(e)
         self.update_old_statistics_info()
Пример #7
0
def win32_get_langenviron():
    """
    Return the language defined in filesystem.app_data()/langenviron.bat
    win32 only
    """
    assert sys.platform == 'win32'
    fn = os.path.join(filesystem.app_data(), "langenviron.txt")
    lang = None
    if os.path.isfile(fn):
        try:
            for line in open(fn, 'r').readlines():
                if not line.startswith("#"):
                    lang = line.strip()
        except IOError as e:
            # Try here too, just to be sure no unicode shit bothers us.

            try:
                print("IOError reading %s:" % fn, e)
            except Exception:
                pass
    else:
        lang = _pre_3_11_win32_get_langenviron()
    if lang:
        return lang
    else:
        return "system default"
Пример #8
0
def get_front_pages_list(debug):
    files = []
    def is_frontpage(fn):
            # no subdirs
            if not os.path.isfile(fn):
                return False
            # filter out bzr revert backups
            if fn.endswith("~"):
                return False
            if os.path.split(fn)[1] == u"Makefile":
                return False
            return True
    def add_subdir(subdir):
        if os.path.isdir(subdir):
            v = [os.path.join(subdir, fn) for fn in os.listdir(subdir)]
            return [x for x in v if is_frontpage(x)]
        return []
    files = [fn for fn in glob.glob(os.path.join(u"exercises", "*", "*"))
             if is_frontpage(fn)]
    # The next line is for pre 3.15 compat. We used to place learning
    # trees there.
    files.extend(add_subdir(os.path.join(filesystem.app_data(), u"learningtrees")))
    # This is the recommended place to save front page files
    files.extend([
        fn for fn in glob.glob(os.path.join(filesystem.user_data(), u"exercises", "*", "*"))
        if is_frontpage(fn)])
    if not debug:
        try:
            files.remove(os.path.join(lessonfile.exercises_dir, 'debugtree.txt'))
        except ValueError:
            # The debugtree.txtfile is for some reason missing
            pass
    return files
Пример #9
0
def presetup(app_defaults_filename, system_filename, user_filename):
    if not os.path.exists(filesystem.app_data()):
        os.makedirs(filesystem.app_data())
    if not os.path.exists(filesystem.user_data()):
        os.makedirs(filesystem.user_data())
    try:
        cfg.initialise(app_defaults_filename, system_filename, user_filename)
    except UnicodeDecodeError:
        traceback.print_exc()
        print(file=sys.stderr)
        print("\n".join(
            textwrap.wrap(
                "Your %s file is not properly utf8 encoded. Most likely"
                " it is the path to some external program that contain non-ascii"
                " characters. Please edit or delete the file. Or email it to"
                " [email protected], and he will tell you what the problem is." %
                filesystem.rcfile().encode("ascii", "backslashreplace"))),
              file=sys.stderr)
        print(file=sys.stderr)
        sys.exit("I give up (solfege.py)")
    except cfg.CfgParseException as e:
        i18n.setup(".")
        a, b = os.path.split(user_filename)
        renamed_fn = os.path.join(a, "BAD-" + b)
        m = Gtk.MessageDialog(None, Gtk.DialogFlags.MODAL,
                              Gtk.MessageType.ERROR, Gtk.ButtonsType.NONE,
                              _("Parsing %s failed") % filesystem.rcfile())
        m.format_secondary_text(
            str(e) + "\n\n" +
            _("We cannot recover from this, we can rename the corrupt file to %s and then start the program."
              % renamed_fn))
        m.add_buttons("Rename", 10)
        m.add_buttons(Gtk.STOCK_QUIT, 11)
        m.set_default_response(11)
        ret = m.run()
        if ret == 10:
            os.rename(user_filename, renamed_fn)
            m.destroy()
            cfg.initialise(app_defaults_filename, system_filename,
                           user_filename)
        else:
            sys.exit(1)
    # MIGRATION from 2.9.2 to 2.9.3
    if cfg.get_string("app/lc_messages") == 'C (english)':
        cfg.set_string("app/lc_messages", "C")
Пример #10
0
def presetup(app_defaults_filename, system_filename, user_filename):
    if not os.path.exists(filesystem.app_data()):
        os.makedirs(filesystem.app_data())

    if not os.path.exists(filesystem.user_data()):
        os.makedirs(filesystem.user_data())
    try:
        cfg.initialise(app_defaults_filename, system_filename, user_filename)
    except UnicodeDecodeError, e:
        traceback.print_exc()
        print >> sys.stderr
        print >> sys.stderr, "\n".join(textwrap.wrap(
              "Your %s file is not properly utf8 encoded. Most likely"
              " it is the path to some external program that contain non-ascii"
              " characters. Please edit or delete the file. Or email it to"
              " [email protected], and he will tell you what the problem is." % filesystem.rcfile().encode("ascii", "backslashreplace")))
        print >> sys.stderr
        sys.exit("I give up (solfege.py)")
Пример #11
0
def presetup(app_defaults_filename, system_filename, user_filename):
    if not os.path.exists(filesystem.app_data()):
        os.makedirs(filesystem.app_data())
    if not os.path.exists(filesystem.user_data()):
        os.makedirs(filesystem.user_data())
    try:
        cfg.initialise(app_defaults_filename, system_filename, user_filename)
    except UnicodeDecodeError, e:
        traceback.print_exc()
        print >> sys.stderr
        print >> sys.stderr, "\n".join(
            textwrap.wrap(
                "Your %s file is not properly utf8 encoded. Most likely"
                " it is the path to some external program that contain non-ascii"
                " characters. Please edit or delete the file. Or email it to"
                " [email protected], and he will tell you what the problem is." %
                filesystem.rcfile().encode("ascii", "backslashreplace")))
        print >> sys.stderr
        sys.exit("I give up (solfege.py)")
Пример #12
0
 def on_entry_changed(self, *w):
     pdir = os.path.join(filesystem.app_data(), "profiles",
                         self.g_entry.get_text())
     self.g_profile_location.set_text(pdir)
     if os.path.exists(pdir):
         self.g_status.set_text(_("The profile «%s» already exists.") % self.g_entry.get_text())
         self.g_statusbox.show()
         self.set_response_sensitive(Gtk.ResponseType.ACCEPT, False)
     else:
         self.g_statusbox.hide()
         self.g_status.set_text("")
         self.set_response_sensitive(Gtk.ResponseType.ACCEPT, True)
Пример #13
0
 def on_entry_changed(self, *w):
     pdir = os.path.join(filesystem.app_data(), u"profiles",
                         self.g_entry.get_text().decode("utf-8"))
     self.g_profile_location.set_text(pdir)
     if os.path.exists(pdir):
         self.g_status.set_text(_(u"The profile «%s» already exists.") % self.g_entry.get_text().decode("utf-8"))
         self.g_statusbox.show()
         self.set_response_sensitive(Gtk.ResponseType.ACCEPT, False)
     else:
         self.g_statusbox.hide()
         self.g_status.set_text(u"")
         self.set_response_sensitive(Gtk.ResponseType.ACCEPT, True)
Пример #14
0
def win32_put_langenviron(lang):
    """
    Write the filesystem.app_data()/langenviron.txt file.
    win32 only.
    """
    langfile = open(os.path.join(filesystem.app_data(), "langenviron.txt"), 'w')
    print("# rem Created by GNU Solfege %s" % buildinfo.VERSION_STRING, file=langfile)
    if lang:
        print(lang, file=langfile)
    else:
        print("# System default language. Not setting variable.", file=langfile)
    langfile.close()
Пример #15
0
 def on_delete_profile(self, w):
     if gu.dialog_yesno(_(u"Permanently delete the user profile «%s»?") % self.get_profile(), self):
         path, column = self.g_tw.get_cursor()
         it = self.g_liststore.get_iter(path)
         try:
             shutil.rmtree(os.path.join(filesystem.app_data(), u"profiles", self.get_profile()))
         except OSError, e:
             gu.display_exception_message(e)
             return
         self.g_liststore.remove(it)
         if not self.g_liststore.iter_is_valid(it):
             it = self.g_liststore[-1].iter
         self.g_tw.set_cursor(self.g_liststore.get_path(it))
Пример #16
0
 def on_delete_profile(self, w):
     if gu.dialog_yesno(_("Permanently delete the user profile «%s»?") % self.get_profile(), self):
         path, column = self.g_tw.get_cursor()
         it = self.g_liststore.get_iter(path)
         try:
             shutil.rmtree(os.path.join(filesystem.app_data(), "profiles", self.get_profile()))
         except OSError as e:
             gu.display_exception_message(e)
             return
         self.g_liststore.remove(it)
         if not self.g_liststore.iter_is_valid(it):
             it = self.g_liststore[-1].iter
         self.g_tw.set_cursor(self.g_liststore.get_path(it))
Пример #17
0
def win32_put_langenviron(lang):
    """
    Write the filesystem.app_data()/langenviron.txt file.
    win32 only.
    """
    langfile = open(os.path.join(filesystem.app_data(), "langenviron.txt"),
                    'w')
    print >> langfile, "# rem Created by GNU Solfege %s" % buildinfo.VERSION_STRING
    if lang:
        print >> langfile, lang
    else:
        print >> langfile, "# System default language. Not setting variable."
    langfile.close()
Пример #18
0
 def update_old_statistics_info(self):
     path = os.path.join(filesystem.app_data(), u'statistics')
     if os.path.exists(path):
         count = 1 # count app_data()/statistics too
     else:
         count = 0
     for dirpath, dirnames, filenames in os.walk(path):
         count += len(dirnames) + len(filenames)
     if count:
         self.g_old_stat_info.set_text(_("You have %i files and directories storing statistics in the old format that only Solfege 3.14 and older will use. These files are not useful any more unless you want to downgrade to Solfege 3.14.") % count)
     else:
         self.g_old_stat_info.set_text(_("No obsolete statistics found."))
     self.g_delete_old_statistics.set_sensitive(bool(count))
Пример #19
0
def presetup(app_defaults_filename, system_filename, user_filename):
    if not os.path.exists(filesystem.app_data()):
        os.makedirs(filesystem.app_data())
    if not os.path.exists(filesystem.user_data()):
        os.makedirs(filesystem.user_data())
    try:
        cfg.initialise(app_defaults_filename, system_filename, user_filename)
    except UnicodeDecodeError:
        traceback.print_exc()
        print(file=sys.stderr)
        print("\n".join(textwrap.wrap(
              "Your %s file is not properly utf8 encoded. Most likely"
              " it is the path to some external program that contain non-ascii"
              " characters. Please edit or delete the file. Or email it to"
              " [email protected], and he will tell you what the problem is." % filesystem.rcfile().encode("ascii", "backslashreplace"))), file=sys.stderr)
        print(file=sys.stderr)
        sys.exit("I give up (solfege.py)")
    except cfg.CfgParseException as e:
        i18n.setup(".")
        a, b = os.path.split(user_filename)
        renamed_fn = os.path.join(a, "BAD-" + b)
        m = Gtk.MessageDialog(None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR,
                Gtk.ButtonsType.NONE,
                _("Parsing %s failed") % filesystem.rcfile())
        m.format_secondary_text(str(e) + "\n\n" + _("We cannot recover from this, we can rename the corrupt file to %s and then start the program." % renamed_fn))
        m.add_buttons("Rename", 10)
        m.add_buttons(Gtk.STOCK_QUIT, 11)
        m.set_default_response(11)
        ret = m.run()
        if ret == 10:
            os.rename(user_filename, renamed_fn)
            m.destroy()
            cfg.initialise(app_defaults_filename, system_filename, user_filename)
        else:
            sys.exit(1)
    # MIGRATION from 2.9.2 to 2.9.3
    if cfg.get_string("app/lc_messages") == 'C (english)':
        cfg.set_string("app/lc_messages", "C")
Пример #20
0
 def on_entry_changed(self, w):
     s = self.g_entry.get_text()
     pdir = os.path.join(filesystem.app_data(), "profiles", s)
     ok = False
     if not s:
         self.g_info.show()
         self.g_info.set_text("Empty string not allowed")
     elif os.path.exists(pdir):
         self.g_info.show()
         self.g_info.set_text(_("The profile «%s» already exists.") % self.g_entry.get_text())
     else:
         self.g_info.hide()
         ok = True
     self.set_response_sensitive(Gtk.ResponseType.ACCEPT, ok)
Пример #21
0
 def on_entry_changed(self, w):
     s = self.g_entry.get_text().decode("utf-8")
     pdir = os.path.join(filesystem.app_data(), u"profiles", s)
     ok = False
     if not s:
         self.g_info.show()
         self.g_info.set_text("Empty string not allowed")
     elif os.path.exists(pdir):
         self.g_info.show()
         self.g_info.set_text(_(u"The profile «%s» already exists.") % self.g_entry.get_text().decode("utf-8"))
     else:
         self.g_info.hide()
         ok = True
     self.set_response_sensitive(Gtk.ResponseType.ACCEPT, ok)
Пример #22
0
 def on_create_profile(self, w):
     dlg = NewProfileDialog()
     dlg.show_all()
     ret = dlg.run()
     if ret == gtk.RESPONSE_ACCEPT:
         pdir = os.path.join(filesystem.app_data(), u"profiles",
                             dlg.g_entry.get_text())
         if not os.path.exists(pdir):
             try:
                 os.makedirs(pdir)
                 self.g_liststore.append((dlg.g_entry.get_text(), ))
                 self.g_tw.set_cursor((len(self.g_liststore) - 1, ))
             except OSError, e:
                 gu.display_exception_message(e)
Пример #23
0
 def on_create_profile(self, w):
     dlg = NewProfileDialog()
     dlg.show_all()
     ret = dlg.run()
     if ret == Gtk.ResponseType.ACCEPT:
         pdir = os.path.join(filesystem.app_data(),
                             u"profiles", dlg.g_entry.get_text().decode("utf-8"))
         if not os.path.exists(pdir):
             try:
                 os.makedirs(pdir)
                 self.g_liststore.append((dlg.g_entry.get_text().decode("utf-8"),))
                 self.g_tw.set_cursor((len(self.g_liststore)-1,))
             except OSError, e:
                 gu.display_exception_message(e)
Пример #24
0
 def update_old_statistics_info(self):
     path = os.path.join(filesystem.app_data(), u'statistics')
     if os.path.exists(path):
         count = 1  # count app_data()/statistics too
     else:
         count = 0
     for dirpath, dirnames, filenames in os.walk(path):
         count += len(dirnames) + len(filenames)
     if count:
         self.g_old_stat_info.set_text(
             _("You have %i files and directories storing statistics in the old format that only Solfege 3.14 and older will use. These files are not useful any more unless you want to downgrade to Solfege 3.14."
               ) % count)
     else:
         self.g_old_stat_info.set_text(_("No obsolete statistics found."))
     self.g_delete_old_statistics.set_sensitive(bool(count))
Пример #25
0
def _pre_3_11_win32_get_langenviron():
    """
    Old version of win32_get_langenviron.
    Return the language defined in filesystem.app_data()/langenviron.bat
    Return None if no language is defined or the file does not exist.
    win32 only
    """
    assert sys.platform == 'win32'
    s = ""
    try:
        langfile = open(os.path.join(filesystem.app_data(), "langenviron.bat"), 'rU')
        s = langfile.read()
        langfile.close()
    except IOError, e:
        # we get here for example when the file does not exist
        return None
Пример #26
0
def _pre_3_11_win32_get_langenviron():
    """
    Old version of win32_get_langenviron.
    Return the language defined in filesystem.app_data()/langenviron.bat
    Return None if no language is defined or the file does not exist.
    win32 only
    """
    assert sys.platform == 'win32'
    s = ""
    try:
        langfile = open(os.path.join(filesystem.app_data(), "langenviron.bat"),
                        'rU')
        s = langfile.read()
        langfile.close()
    except IOError, e:
        # we get here for example when the file does not exist
        return None
Пример #27
0
def get_front_pages_list(debug):
    files = []

    def is_frontpage(fn):
        # no subdirs
        if not os.path.isfile(fn):
            return False
        # filter out bzr revert backups
        if fn.endswith("~"):
            return False
        if os.path.split(fn)[1] == "Makefile":
            return False
        return True

    def add_subdir(subdir):
        if os.path.isdir(subdir):
            v = [os.path.join(subdir, fn) for fn in os.listdir(subdir)]
            return [x for x in v if is_frontpage(x)]
        return []

    files = [
        fn for fn in glob.glob(os.path.join("exercises", "*", "*"))
        if is_frontpage(fn)
    ]
    # The next line is for pre 3.15 compat. We used to place learning
    # trees there.
    files.extend(
        add_subdir(os.path.join(filesystem.app_data(), "learningtrees")))
    # This is the recommended place to save front page files
    files.extend([
        fn for fn in glob.glob(
            os.path.join(filesystem.user_data(), "exercises", "*", "*"))
        if is_frontpage(fn)
    ])
    if not debug:
        try:
            files.remove(
                os.path.join(lessonfile.exercises_dir, 'debugtree.txt'))
        except ValueError:
            # The debugtree.txtfile is for some reason missing
            pass
    return files
Пример #28
0
def win32_get_langenviron():
    """
    Return the language defined in filesystem.app_data()/langenviron.bat
    win32 only
    """
    assert sys.platform == 'win32'
    fn = os.path.join(filesystem.app_data(), "langenviron.txt")
    lang = None
    if os.path.isfile(fn):
        try:
            for line in open(fn, 'r').readlines():
                if not line.startswith("#"):
                    lang = line.strip()
        except IOError, e:
            # Try here too, just to be sure no unicode shit bothers us.

            try:
                print "IOError reading %s:" % fn, e
            except Exception:
                pass
Пример #29
0
def _pre_3_11_win32_get_langenviron():
    """
    Old version of win32_get_langenviron.
    Return the language defined in filesystem.app_data()/langenviron.bat
    Return None if no language is defined or the file does not exist.
    win32 only
    """
    assert sys.platform == 'win32'
    s = ""
    try:
        langfile = open(os.path.join(filesystem.app_data(), "langenviron.bat"), 'r')
        s = langfile.read()
        langfile.close()
    except IOError:
        # we get here for example when the file does not exist
        return None
    if s:
        r = re.compile("set LANGUAGE=(?P<lang>.*)")
        for line in s.split("\n"):
            m = r.match(line)
            if m:
                return m.groups()[0]
    return None
Пример #30
0
    def show_path_info(self, w):
        if not self.g_path_info_dlg:
            self.g_path_info_dlg = Gtk.Dialog(
                _("_File locations").replace("_", ""),
                self,
                buttons=(Gtk.STOCK_OK, Gtk.ResponseType.ACCEPT))
            sc = Gtk.ScrolledWindow()
            sc.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.NEVER)
            self.g_path_info_dlg.vbox.pack_start(sc, True, True, 0)
            #
            vbox = gu.hig_dlg_vbox()
            sc.add_with_viewport(vbox)

            box1, box2 = gu.hig_category_vbox(
                _("_File locations").replace("_", ""))
            vbox.pack_start(box1, True, True, 0)
            sizegroup = Gtk.SizeGroup(Gtk.SizeGroupMode.HORIZONTAL)
            # statistics.sqlite
            # win32 solfegerc
            # win32 langenviron.txt
            box2.pack_start(
                gu.hig_label_widget(_("Solfege application data:"),
                                    Gtk.Label(label=filesystem.app_data()),
                                    sizegroup), False, False, 0)
            box2.pack_start(
                gu.hig_label_widget(_("Solfege user data:"),
                                    Gtk.Label(label=filesystem.user_data()),
                                    sizegroup), False, False, 0)
            box2.pack_start(
                gu.hig_label_widget(_("Solfege config file:"),
                                    Gtk.Label(label=filesystem.rcfile()),
                                    sizegroup), False, False, 0)
            box2.pack_start(
                gu.hig_label_widget(_("Solfege installation directory:"),
                                    Gtk.Label(label=os.getcwd()), sizegroup),
                False, False, 0)
            box2.pack_start(
                gu.hig_label_widget(
                    _("User manual in HTML format:"),
                    Gtk.Label(label=os.path.join(os.getcwd(), "help")),
                    sizegroup), False, False, 0)
            box2.pack_start(
                gu.hig_label_widget("gtk:", Gtk.Label(label=str(Gtk)),
                                    sizegroup), False, False, 0)
            box2.pack_start(
                gu.hig_label_widget("pyalsa:", Gtk.Label(label=str(alsaseq)),
                                    sizegroup), False, False, 0)
            box2.pack_start(
                gu.hig_label_widget(
                    "PYTHONHOME",
                    Gtk.Label(os.environ.get('PYTHONHOME', 'Not defined')),
                    sizegroup), False, False, 0)
            self.g_path_info_dlg.show_all()

            def f(*w):
                self.g_path_info_dlg.hide()
                return True

            self.g_path_info_dlg.connect('response', f)
            self.g_path_info_dlg.connect('delete-event', f)
            sc.set_size_request(
                min(vbox.size_request().width + gu.hig.SPACE_LARGE * 2,
                    Gdk.Screen.width() * 0.9),
                vbox.size_request().height)
Пример #31
0
__builtin__.start_time = time.time()

import sys
import os
import os.path
import shutil
import traceback
import textwrap

from solfege import cfg
from solfege import filesystem

if sys.platform == 'win32':
    # Migration added in solfege 3.9.0.
    try:
        if not os.path.exists(filesystem.app_data()):
            if os.path.exists(os.path.join(filesystem.get_home_dir(), ".solfege")):
                shutil.copytree(os.path.join(filesystem.get_home_dir(), ".solfege"),
                                filesystem.app_data())
            else:
                os.mkdir(filesystem.app_data())
        if not os.path.exists(filesystem.rcfile()):
            if os.path.exists(os.path.join(filesystem.get_home_dir(), ".solfegerc")):
                shutil.copy(os.path.join(filesystem.get_home_dir(), ".solfegerc"),
                            filesystem.rcfile())
    except (IOError, os.error), e:
        print "Migration failed:", e

if not os.path.exists(filesystem.app_data()):
    os.makedirs(filesystem.app_data())
if not os.path.exists(filesystem.user_data()):
Пример #32
0
def do_profiles():
    return (os.path.isdir(os.path.join(filesystem.app_data(), 'profiles'))
           and os.listdir(os.path.join(filesystem.app_data(), 'profiles')))
Пример #33
0
def do_profiles():
    return (os.path.isdir(os.path.join(filesystem.app_data(), 'profiles'))
            and os.listdir(os.path.join(filesystem.app_data(), 'profiles')))
Пример #34
0
    def show_path_info(self, w):
        if not self.g_path_info_dlg:
            self.g_path_info_dlg = Gtk.Dialog(_("_File locations").replace("_", ""), self,
                buttons=(Gtk.STOCK_OK, Gtk.ResponseType.ACCEPT))
            sc = Gtk.ScrolledWindow()
            sc.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.NEVER)
            self.g_path_info_dlg.vbox.pack_start(sc, True, True, 0)
            #
            vbox = gu.hig_dlg_vbox()
            sc.add_with_viewport(vbox)

            box1, box2 = gu.hig_category_vbox(_("_File locations").replace("_", ""))
            vbox.pack_start(box1, True, True, 0)
            sizegroup = Gtk.SizeGroup(Gtk.SizeGroupMode.HORIZONTAL)
            # statistics.sqlite
            # win32 solfegerc
            # win32 langenviron.txt
            box2.pack_start(gu.hig_label_widget(_("Solfege application data:"), Gtk.Label(label=filesystem.app_data()), sizegroup), False, False, 0)
            box2.pack_start(gu.hig_label_widget(_("Solfege user data:"), Gtk.Label(label=filesystem.user_data()), sizegroup), False, False, 0)
            box2.pack_start(gu.hig_label_widget(_("Solfege config file:"), Gtk.Label(label=filesystem.rcfile()), sizegroup), False, False, 0)
            box2.pack_start(gu.hig_label_widget(_("Solfege installation directory:"), Gtk.Label(label=os.getcwd()), sizegroup), False, False, 0)
            box2.pack_start(gu.hig_label_widget(_("User manual in HTML format:"), Gtk.Label(label=os.path.join(os.getcwd(), "help")), sizegroup), False, False, 0)
            box2.pack_start(gu.hig_label_widget("gtk:", Gtk.Label(label=str(Gtk)), sizegroup), False, False, 0)
            box2.pack_start(gu.hig_label_widget("pyalsa:", Gtk.Label(label=str(alsaseq)), sizegroup), False, False, 0)
            box2.pack_start(gu.hig_label_widget("PYTHONHOME", Gtk.Label(os.environ.get('PYTHONHOME', 'Not defined')), sizegroup), False, False, 0)
            self.g_path_info_dlg.show_all()

            def f(*w):
                self.g_path_info_dlg.hide()
                return True
            self.g_path_info_dlg.connect('response', f)
            self.g_path_info_dlg.connect('delete-event', f)
            sc.set_size_request(min(vbox.size_request().width + gu.hig.SPACE_LARGE * 2,
                                    Gdk.Screen.width() * 0.9),
                                vbox.size_request().height)
Пример #35
0
 def get_statistics_filename(self):
     if self.m_profile:
         return os.path.join(filesystem.app_data(), "profiles", self.m_profile, "statistics.sqlite")
     else:
         return self.get_noprofile_statistics_filename()
Пример #36
0
 def get_noprofile_statistics_filename():
     return os.path.join(filesystem.app_data(), "statistics.sqlite")
Пример #37
0
    def get_statistics_filename(self):
        if self.m_profile:
            return os.path.join(filesystem.app_data(), "profiles", self.m_profile, "statistics.sqlite")

        else:
            return self.get_noprofile_statistics_filename()
Пример #38
0
 def get_noprofile_statistics_filename():
     return os.path.join(filesystem.app_data(), "statistics.sqlite")
Пример #39
0
import builtins
import time
builtins.start_time = time.time()

import sys
import os
import os.path
import shutil

from solfege import cfg
from solfege import filesystem

if sys.platform == 'win32':
    # Migration added in solfege 3.9.0.
    try:
        if not os.path.exists(filesystem.app_data()):
            if os.path.exists(
                    os.path.join(filesystem.get_home_dir(), ".solfege")):
                shutil.copytree(
                    os.path.join(filesystem.get_home_dir(), ".solfege"),
                    filesystem.app_data())
            else:
                os.mkdir(filesystem.app_data())
        if not os.path.exists(filesystem.rcfile()):
            if os.path.exists(
                    os.path.join(filesystem.get_home_dir(), ".solfegerc")):
                shutil.copy(
                    os.path.join(filesystem.get_home_dir(), ".solfegerc"),
                    filesystem.rcfile())
    except (IOError, os.error) as e:
        print("Migration failed:", e)
Пример #40
0
    def read_old_data(self, callback):
        """
        This function should be run once to import the old format statistics
        from ~/.solfege/statistics and into the sqlite database.
        We will import statistics for all uuids that exist in the lessonfiles table.
        """
        # Snippet from http://wiki.python.org/moin/UsingPickle/RenamingModules
        # that let us rename even though we have a renamed class
        renametable = {
            'src.dataparser': 'solfege.dataparser',
            }

        def mapname(name):
            if name in renametable:
                return renametable[name]
            return name

        def mapped_load_global(self):
            module = mapname(self.readline()[:-1])
            name = mapname(self.readline()[:-1])
            klass = self.find_class(module, name)
            self.append(klass)

        def load(file):
            unpickler = pickle.Unpickler(file)
            unpickler.dispatch[pickle.GLOBAL] = mapped_load_global
            return unpickler.load()

        imp, uuid_to_filename = self.get_uuid_to_filename_mapping(callback)
        def read_session_data(datadir, is_tests, counter):
            if not os.path.isdir(datadir):
                logging.debug("read_session_data: '%s' does not exist. Returning" % datadir)
                return
            for uuid in os.listdir(datadir):
                if not (os.path.isdir(os.path.join(datadir, uuid))
                    and os.path.isfile(os.path.join(datadir, '%s_hash' % uuid))):
                    continue
                # We do not add statistics for lesson files we don't have
                # access to.
                if not uuid in uuid_to_filename:
                    continue
                lessonfilename = uuid_to_filename[uuid]
                try:
                    fileid = self.get_fileid(lessonfilename)
                except self.FileNotInDB:
                    fileid = self.insert_file(lessonfilename)
                # saved_hashvalue will get the hash value as solfege 3.14 (or
                # older) calculated when the statistics was saved.
                try:
                    s = open(os.path.join(datadir, u"%s_hash" % uuid), "r").read()
                    try:
                        saved_hashvalue = int(s)
                    except ValueError:
                        saved_hashvalue = None
                except IOError:
                    saved_hashvalue = None
                real_lessonfilename = lessonfile.uri_expand(lessonfilename)
                s = open(real_lessonfilename, "r").read()
                # Check if the lesson file in this version of solfege is equal to the
                # one used when saving the statistics.
                if hash(s) != saved_hashvalue:
                    # header.replaces is not used when importing statistics.
                    # This because the old statistics saved the hash value
                    # using python standard hash function, and the function
                    # does not return the same value on all systems.
                    def bugfix_copy_fn(filename, subdir):
                        """
                        Return the filename of the copy of the file if it
                        exists. Return filename if not.
                        """
                        d, f = os.path.split(filename)
                        fn = os.path.join(subdir, f)
                        if (d == 'exercises%sstandard%slesson-files' % (os.sep, os.sep)
                            and os.path.isfile(fn)):
                            return fn
                        return filename

                    def bugfix_hash_file(filename, subdir):
                        copy_fn = bugfix_copy_fn(filename, subdir)
                        if os.path.isfile(copy_fn):
                            return hash(open(copy_fn, 'r').read())
                        return None

                    if not (saved_hashvalue == bugfix_hash_file(real_lessonfilename, "hash-bug-workaround")
                            or saved_hashvalue == bugfix_hash_file(real_lessonfilename, "hash-bug-workaround2")):
                        logging.debug("Ignoring statistics for '%s' since the saved hash value does not match." % lessonfilename)
                        continue

                for timestamp in os.listdir(os.path.join(datadir, uuid)):
                    if timestamp == u"passed":
                        continue
                    f = open(os.path.join(datadir, uuid, timestamp), 'r')
                    session = load(f)
                    f.close()
                    for correct in session.keys():
                        for guess in session[correct]:
                            self.conn.execute("insert into sessions "
                                "(fileid, timestamp, answerkey, guessed, count) "
                                "values(?, ?, ?, ?, ?)",
                            (fileid, timestamp, unicode(correct), unicode(guess), session[correct][guess]))
                    self.conn.execute("insert into sessioninfo "
                        "(fileid, timestamp, sessiontype) "
                        "values(?, ?, ?)",
                        (fileid, timestamp, int(bool(is_tests))))
                    counter += 1
                    callback(_("Files read: %i") % counter)
                if is_tests:
                    timestamp = self.conn.execute("select timestamp from sessioninfo "
                        "where fileid=? and sessiontype=1 "
                        "order by -timestamp ",
                        (fileid,)).fetchone()[0]
                    if timestamp:
                        if lessonfile.infocache.get(lessonfilename, "module") in ('melodicinterval', 'harmonicinterval', 'singinterval'):
                            parserclass = lessonfile.IntervalsLessonfile
                        else:
                            parserclass = lessonfile.IdByNameLessonfile
                        p = parserclass()
                        p.parse_file(lessonfilename)
                        self.cache_new_test_result(lessonfilename,
                            timestamp,
                            p.get_test_requirement(),
                            p.get_test_num_questions())
            return imp
        imp = read_session_data(
                os.path.join(filesystem.app_data(), 'statistics'),
                False, imp)
        imp = read_session_data(
                os.path.join(filesystem.app_data(), 'testresults'),
                True, imp)
        self.set_variable("database_version", 2)
        logging.info("imported statistics for %s lessonfiles" % imp)
        self.conn.commit()