Example #1
0
 def saveDocumentAs(self, doc):
     """ Saves the document, always asking for a name.
     
     Returns True if saving succeeded.
     
     """
     filename = doc.url().toLocalFile()
     if filename:
         filetypes = app.filetypes(os.path.splitext(filename)[1])
     else:
         filename = app.basedir()  # default directory to save to
         import documentinfo
         import ly.lex
         filetypes = app.filetypes(
             ly.lex.extensions[documentinfo.mode(doc)])
     caption = app.caption(_("dialog title", "Save File"))
     filename = QFileDialog.getSaveFileName(self, caption, filename,
                                            filetypes)
     if not filename:
         return False  # cancelled
     if not util.iswritable(filename):
         QMessageBox.warning(
             self, app.caption(_("Error")),
             _("Can't write to destination:\n\n{url}").format(url=filename))
         return False
     url = QUrl.fromLocalFile(filename)
     doc.setUrl(url)
     recentfiles.add(url)
     return self.saveDocument(doc)
Example #2
0
 def saveDocument(self, doc):
     """ Saves the document, asking for a name if necessary.
     
     Returns True if saving succeeded.
     
     """
     if doc.url().isEmpty():
         return self.saveDocumentAs(doc)
     filename = dest = doc.url().toLocalFile()
     if not filename:
         dest = doc.url().toString()
     if not util.iswritable(filename):
         QMessageBox.warning(self, app.caption(_("Error")),
             _("Can't write to destination:\n\n{url}").format(url=dest))
         return False
     if QSettings().value("strip_trailing_whitespace", False, bool):
         import reformat
         reformat.remove_trailing_whitespace(QTextCursor(doc))
     b = backup.backup(filename)
     success = doc.save()
     if not success:
         QMessageBox.warning(self, app.caption(_("Error")),
             _("Can't write to destination:\n\n{url}").format(url=filename))
     elif b:
         backup.removeBackup(filename)
     return success
Example #3
0
def changeLanguage(cursor, language):
    """Changes the language of the pitch names."""
    c = lydocument.cursor(cursor, select_all=True)
    try:
        with qutil.busyCursor():
            changed = ly.pitch.translate.translate(c, language)
    except ly.pitch.PitchNameNotAvailable:
        QMessageBox.critical(None, app.caption(_("Pitch Name Language")), _(
            "Can't perform the requested translation.\n\n"
            "The music contains quarter-tone alterations, but "
            "those are not available in the pitch language \"{name}\"."
            ).format(name=language))
        return
    if changed:
        return
    if not cursor.hasSelection():
        # there was no selection and no language command, so insert one
        version = (documentinfo.docinfo(cursor.document()).version()
                   or lilypondinfo.preferred().version())
        ly.pitch.translate.insert_language(c.document, language, version)
        return
    # there was a selection but no command, user must insert manually.
    QMessageBox.information(None, app.caption(_("Pitch Name Language")),
        '<p>{0}</p>'
        '<p><code>\\include "{1}.ly"</code> {2}</p>'
        '<p><code>\\language "{1}"</code> {3}</p>'.format(
            _("The pitch language of the selected text has been "
                "updated, but you need to manually add the following "
                "command to your document:"),
            language,
            _("(for LilyPond below 2.14), or"),
            _("(for LilyPond 2.14 and higher.)")))
Example #4
0
 def exportColoredHtml(self):
     doc = self.currentDocument()
     name, ext = os.path.splitext(os.path.basename(doc.url().path()))
     if name:
         if ext.lower() == ".html":
             name += "_html"
         name += ".html"
     dir = os.path.dirname(doc.url().toLocalFile())
     if dir:
         name = os.path.join(dir, name)
     filename = QFileDialog.getSaveFileName(self, app.caption(_("Export as HTML")),
         name, "{0} (*.html)".format("HTML Files"))
     if not filename:
         return #cancelled
     number_lines = QSettings().value("source_export/number_lines", False, bool)
     inline_style = QSettings().value("source_export/inline_export", False, bool)
     import highlight2html
     html = highlight2html.html_document(doc, inline=inline_style, number_lines=number_lines)
     try:
         with open(filename, "wb") as f:
             f.write(html.encode('utf-8'))
     except IOError as e:
         msg = _("{message}\n\n{strerror} ({errno})").format(
             message = _("Could not write to: {url}").format(url=filename),
             strerror = e.strerror,
             errno = e.errno)
         QMessageBox.critical(self, app.caption(_("Error")), msg)
Example #5
0
 def validate(self):
     """Checks if the input is acceptable.
     
     If this method returns True, the dialog is accepted when OK is clicked.
     Otherwise a messagebox could be displayed, and the dialog will remain
     visible.
     """
     name = self.name.text().strip()
     self.name.setText(name)
     if not name:
         self.name.setFocus()
         QMessageBox.warning(self, app.caption(_("Warning")),
             _("Please enter a session name."))
         if self._originalName:
             self.name.setText(self._originalName)
         return False
     
     elif name == '-':
         self.name.setFocus()
         QMessageBox.warning(self, app.caption(_("Warning")),
             _("Please do not use the name '{name}'.".format(name="-")))
         return False
     
     elif self._originalName != name and name in sessions.sessionNames():
         self.name.setFocus()
         box = QMessageBox(QMessageBox.Warning, app.caption(_("Warning")),
             _("Another session with the name {name} already exists.\n\n"
               "Do you want to overwrite it?").format(name=name),
             QMessageBox.Discard | QMessageBox.Cancel, self)
         box.button(QMessageBox.Discard).setText(_("Overwrite"))
         result = box.exec_()
         if result != QMessageBox.Discard:
             return False
         
     return True
Example #6
0
def changeLanguage(cursor, language):
    """Changes the language of the pitch names."""
    selection = cursor.hasSelection()
    if selection:
        start = cursor.selectionStart()
        cursor.setPosition(cursor.selectionEnd())
        cursor.setPosition(0, QTextCursor.KeepAnchor)
        source = tokeniter.Source.selection(cursor)
    else:
        source = tokeniter.Source.document(cursor)
    
    pitches = PitchIterator(source)
    tokens = pitches.tokens()
    writer = ly.pitch.pitchWriter(language)
    
    if selection:
        # consume tokens before the selection, following the language
        source.consume(tokens, start)
    
    changed = False # track change of \language or \include language command
    with cursortools.compress_undo(cursor):
        try:
            with qutil.busyCursor():
                with cursortools.Editor() as e:
                    for t in tokens:
                        if isinstance(t, ly.lex.lilypond.Note):
                            # translate the pitch name
                            p = pitches.read(t)
                            if p:
                                n = writer(*p)
                                if n != t:
                                    e.insertText(source.cursor(t), n)
                        elif isinstance(t, LanguageName) and t != language:
                            # change the language name in a command
                            e.insertText(source.cursor(t), language)
                            changed = True
        except ly.pitch.PitchNameNotAvailable:
            QMessageBox.critical(None, app.caption(_("Pitch Name Language")), _(
                "Can't perform the requested translation.\n\n"
                "The music contains quarter-tone alterations, but "
                "those are not available in the pitch language \"{name}\"."
                ).format(name=language))
            return
        if changed:
            return
        if not selection:
            # there was no selection and no language command, so insert one
            insertLanguage(cursor.document(), language)
            return
    # there was a selection but no command, user must insert manually.
    QMessageBox.information(None, app.caption(_("Pitch Name Language")),
        '<p>{0}</p>'
        '<p><code>\\include "{1}.ly"</code> {2}</p>'
        '<p><code>\\language "{1}"</code> {3}</p>'.format(
            _("The pitch language of the selected text has been "
                "updated, but you need to manually add the following "
                "command to your document:"),
            language,
            _("(for LilyPond below 2.14), or"),
            _("(for LilyPond 2.14 and higher.)")))
Example #7
0
 def validate(self):
     """Checks if the input is acceptable.
     
     If this method returns True, the dialog is accepted when OK is clicked.
     Otherwise a messagebox could be displayed, and the dialog will remain
     visible.
     """
     name = self.name.text().strip()
     self.name.setText(name)
     if not name:
         self.name.setFocus()
         QMessageBox.warning(self, app.caption(_("Warning")),
             _("Please enter a session name."))
         if self._originalName:
             self.name.setText(self._originalName)
         return False
     
     elif name == '-':
         self.name.setFocus()
         QMessageBox.warning(self, app.caption(_("Warning")),
             _("Please do not use the name '{name}'.".format(name="-")))
         return False
     
     elif self._originalName != name and name in sessions.sessionNames():
         self.name.setFocus()
         box = QMessageBox(QMessageBox.Warning, app.caption(_("Warning")),
             _("Another session with the name {name} already exists.\n\n"
               "Do you want to overwrite it?").format(name=name),
             QMessageBox.Discard | QMessageBox.Cancel, self)
         box.button(QMessageBox.Discard).setText(_("Overwrite"))
         result = box.exec_()
         if result != QMessageBox.Discard:
             return False
         
     return True
Example #8
0
 def saveCopyAs(self):
     import ly.lex
     doc = self.currentDocument()
     if not self.currentView().textCursor().hasSelection():
         import documentinfo
         mode = documentinfo.mode(doc)
         data = doc.encodedText()
         caption = app.caption(_("dialog title", "Save Copy"))
     else:
         import fileinfo
         text = self.currentView().textCursor().selection().toPlainText()
         mode = fileinfo.textmode(text)
         data = util.encode(text)
         caption = app.caption(_("dialog title", "Save Selection"))
     filetypes = app.filetypes(ly.lex.extensions[mode])
     dirname = os.path.dirname(doc.url().toLocalFile()) or app.basedir()
     filename = QFileDialog.getSaveFileName(self, caption, dirname, filetypes)
     if not filename:
         return # cancelled
     try:
         with open(filename, "w") as f:
             f.write(data)
     except IOError as e:
         msg = _("{message}\n\n{strerror} ({errno})").format(
             message = _("Could not write to: {url}").format(url=filename),
             strerror = e.strerror,
             errno = e.errno)
         QMessageBox.critical(self, app.caption(_("Error")), msg)
Example #9
0
 def saveCopyAs(self):
     import ly.lex
     doc = self.currentDocument()
     if not self.currentView().textCursor().hasSelection():
         import documentinfo
         mode = documentinfo.mode(doc)
         data = doc.encodedText()
         caption = app.caption(_("dialog title", "Save Copy"))
     else:
         import fileinfo
         text = self.currentView().textCursor().selection().toPlainText()
         mode = fileinfo.textmode(text)
         data = util.encode(text)
         caption = app.caption(_("dialog title", "Save Selection"))
     filetypes = app.filetypes(ly.lex.extensions[mode])
     dirname = os.path.dirname(doc.url().toLocalFile()) or app.basedir()
     filename = QFileDialog.getSaveFileName(self, caption, dirname, filetypes)
     if not filename:
         return # cancelled
     try:
         with open(filename, "w") as f:
             f.write(data)
     except (IOError, OSError) as err:
         QMessageBox.warning(self, app.caption(_("Error")),
             _("Can't write to destination:\n\n{url}\n\n{error}").format(
                 url=filename, error=err.strerror))
Example #10
0
    def exportColoredHtml(self):
        doc = self.currentDocument()
        name, ext = os.path.splitext(os.path.basename(doc.url().path()))
        if name:
            if ext.lower() == ".html":
                name += "_html"
            name += ".html"
        dir = os.path.dirname(doc.url().toLocalFile())
        if dir:
            name = os.path.join(dir, name)
        filename = QFileDialog.getSaveFileName(self, app.caption(_("Export as HTML")),
            name, "{0} (*.html)".format("HTML Files"))[0]
        if not filename:
            return #cancelled

        s = QSettings()
        s.beginGroup("source_export")
        number_lines = s.value("number_lines", False, bool)
        inline_style = s.value("inline_export", False, bool)
        wrap_tag = s.value("wrap_tag", "pre", str)
        wrap_attrib = s.value("wrap_attrib", "id", str)
        wrap_attrib_name = s.value("wrap_attrib_name", "document", str)
        import highlight2html
        html = highlight2html.html_document(doc, inline=inline_style, number_lines=number_lines,
            wrap_tag=wrap_tag, wrap_attrib=wrap_attrib, wrap_attrib_name=wrap_attrib_name)
        try:
            with open(filename, "wb") as f:
                f.write(html.encode('utf-8'))
        except IOError as e:
            msg = _("{message}\n\n{strerror} ({errno})").format(
                message = _("Could not write to: {url}").format(url=filename),
                strerror = e.strerror,
                errno = e.errno)
            QMessageBox.critical(self, app.caption(_("Error")), msg)
Example #11
0
 def saveCopyAs(self):
     import ly.lex
     doc = self.currentDocument()
     if not self.currentView().textCursor().hasSelection():
         import documentinfo
         mode = documentinfo.mode(doc)
         data = doc.encodedText()
         caption = app.caption(_("dialog title", "Save Copy"))
     else:
         import fileinfo
         text = self.currentView().textCursor().selection().toPlainText()
         mode = fileinfo.textmode(text)
         data = util.encode(text)
         caption = app.caption(_("dialog title", "Save Selection"))
     filetypes = app.filetypes(ly.lex.extensions[mode])
     dirname = os.path.dirname(doc.url().toLocalFile()) or app.basedir()
     filename = QFileDialog.getSaveFileName(self, caption, dirname,
                                            filetypes)
     if not filename:
         return  # cancelled
     try:
         with open(filename, "w") as f:
             f.write(data)
     except (IOError, OSError) as err:
         QMessageBox.warning(
             self, app.caption(_("Error")),
             _("Can't write to destination:\n\n{url}\n\n{error}").format(
                 url=filename, error=err.strerror))
Example #12
0
 def saveDocument(self, doc):
     """ Saves the document, asking for a name if necessary.
     
     Returns True if saving succeeded.
     
     """
     if doc.url().isEmpty():
         return self.saveDocumentAs(doc)
     filename = dest = doc.url().toLocalFile()
     if not filename:
         dest = doc.url().toString()
     if not util.iswritable(filename):
         QMessageBox.warning(
             self, app.caption(_("Error")), _("Can't write to destination:\n\n{url}").format(url=dest)
         )
         return False
     b = backup.backup(filename)
     success = doc.save()
     if not success:
         QMessageBox.warning(
             self, app.caption(_("Error")), _("Can't write to destination:\n\n{url}").format(url=filename)
         )
     elif b:
         backup.removeBackup(filename)
     return success
Example #13
0
def changeLanguage(cursor, language):
    """Changes the language of the pitch names."""
    c = lydocument.cursor(cursor, select_all=True)
    try:
        with qutil.busyCursor():
            changed = ly.pitch.translate.translate(c, language)
    except ly.pitch.PitchNameNotAvailable:
        QMessageBox.critical(
            None, app.caption(_("Pitch Name Language")),
            _("Can't perform the requested translation.\n\n"
              "The music contains quarter-tone alterations, but "
              "those are not available in the pitch language \"{name}\".").
            format(name=language))
        return
    if changed:
        return
    if not cursor.hasSelection():
        # there was no selection and no language command, so insert one
        version = (documentinfo.docinfo(cursor.document()).version()
                   or lilypondinfo.preferred().version())
        ly.pitch.translate.insert_language(c.document, language, version)
        return
    # there was a selection but no command, user must insert manually.
    QMessageBox.information(
        None, app.caption(_("Pitch Name Language")), '<p>{0}</p>'
        '<p><code>\\include "{1}.ly"</code> {2}</p>'
        '<p><code>\\language "{1}"</code> {3}</p>'.format(
            _("The pitch language of the selected text has been "
              "updated, but you need to manually add the following "
              "command to your document:"), language,
            _("(for LilyPond below 2.14), or"),
            _("(for LilyPond 2.14 and higher.)")))
Example #14
0
 def saveDocument(self, doc):
     """ Saves the document, asking for a name if necessary.
     
     Returns True if saving succeeded.
     
     """
     if doc.url().isEmpty():
         return self.saveDocumentAs(doc)
     filename = dest = doc.url().toLocalFile()
     if not filename:
         dest = doc.url().toString()
     if not util.iswritable(filename):
         QMessageBox.warning(
             self, app.caption(_("Error")),
             _("Can't write to destination:\n\n{url}").format(url=dest))
         return False
     if QSettings().value("strip_trailing_whitespace", False, bool):
         import reformat
         reformat.remove_trailing_whitespace(QTextCursor(doc))
     b = backup.backup(filename)
     success = doc.save()
     if not success:
         QMessageBox.warning(
             self, app.caption(_("Error")),
             _("Can't write to destination:\n\n{url}").format(url=filename))
     elif b:
         backup.removeBackup(filename)
     return success
Example #15
0
    def exportColoredHtml(self):
        doc = self.currentDocument()
        name, ext = os.path.splitext(os.path.basename(doc.url().path()))
        if name:
            if ext.lower() == ".html":
                name += "_html"
            name += ".html"
        dir = os.path.dirname(doc.url().toLocalFile())
        if dir:
            name = os.path.join(dir, name)
        filename = QFileDialog.getSaveFileName(
            self, app.caption(_("Export as HTML")), name, "{0} (*.html)".format("HTML Files")
        )
        if not filename:
            return  # cancelled
        import highlight2html

        html = highlight2html.HtmlHighlighter().html_document(doc)
        try:
            with open(filename, "wb") as f:
                f.write(html.encode("utf-8"))
        except (IOError, OSError) as err:
            QMessageBox.warning(
                self,
                app.caption(_("Error")),
                _("Can't write to destination:\n\n{url}\n\n{error}").format(url=filename, error=err),
            )
Example #16
0
 def exportMusicXML(self):
     """ Convert the current document to MusicXML """
     doc = self.mainwindow().currentDocument()
     orgname = doc.url().toLocalFile()
     filename = os.path.splitext(orgname)[0] + '.xml'
     caption = app.caption(_("dialog title", "Export MusicXML File"))
     filetypes = '{0} (*.xml);;{1} (*)'.format(_("XML Files"),
                                               _("All Files"))
     filename = QFileDialog.getSaveFileName(self.mainwindow(), caption,
                                            filename, filetypes)[0]
     if not filename:
         return False  # cancelled
     import ly.musicxml
     writer = ly.musicxml.writer()
     writer.parse_text(doc.toPlainText())
     xml = writer.musicxml()
     # put the Frescobaldi version in the xml file
     software = xml.root.find('.//encoding/software')
     software.text = "{0} {1}".format(appinfo.appname, appinfo.version)
     try:
         xml.write(filename)
     except (IOError, OSError) as err:
         QMessageBox.warning(
             self.mainwindow(), app.caption(_("Error")),
             _("Can't write to destination:\n\n{url}\n\n{error}").format(
                 url=filename, error=err.strerror))
Example #17
0
 def exportColoredHtml(self):
     doc = self.currentDocument()
     name, ext = os.path.splitext(os.path.basename(doc.url().path()))
     if name:
         if ext.lower() == ".html":
             name += "_html"
         name += ".html"
     dir = os.path.dirname(doc.url().toLocalFile())
     if dir:
         name = os.path.join(dir, name)
     filename = QFileDialog.getSaveFileName(
         self, app.caption(_("Export as HTML")), name,
         "{0} (*.html)".format("HTML Files"))
     if not filename:
         return  #cancelled
     number_lines = QSettings().value("source_export/number_lines", False,
                                      bool)
     inline_style = QSettings().value("source_export/inline_export", False,
                                      bool)
     import highlight2html
     html = highlight2html.html_document(doc,
                                         inline=inline_style,
                                         number_lines=number_lines)
     try:
         with open(filename, "wb") as f:
             f.write(html.encode('utf-8'))
     except (IOError, OSError) as err:
         QMessageBox.warning(
             self, app.caption(_("Error")),
             _("Can't write to destination:\n\n{url}\n\n{error}").format(
                 url=filename, error=err))
Example #18
0
 def saveDocumentAs(self, doc):
     """ Saves the document, always asking for a name.
     
     Returns True if saving succeeded.
     
     """
     filename = doc.url().toLocalFile()
     if filename:
         filetypes = app.filetypes(os.path.splitext(filename)[1])
     else:
         filename = app.basedir() # default directory to save to
         import documentinfo
         import ly.lex
         filetypes = app.filetypes(ly.lex.extensions[documentinfo.mode(doc)])
     caption = app.caption(_("dialog title", "Save File"))
     filename = QFileDialog.getSaveFileName(self, caption, filename, filetypes)
     if not filename:
         return False # cancelled
     if not util.iswritable(filename):
         QMessageBox.warning(self, app.caption(_("Error")),
             _("Can't write to destination:\n\n{url}").format(url=filename))
         return False
     url = QUrl.fromLocalFile(filename)
     doc.setUrl(url)
     recentfiles.add(url)
     return self.saveDocument(doc)
Example #19
0
 def saveCopyAs(self):
     import ly.lex
     doc = self.currentDocument()
     if not self.currentView().textCursor().hasSelection():
         import documentinfo
         mode = documentinfo.mode(doc)
         data = doc.encodedText()
         caption = app.caption(_("dialog title", "Save Copy"))
     else:
         import fileinfo
         text = self.currentView().textCursor().selection().toPlainText()
         mode = fileinfo.textmode(text)
         data = util.encode(util.platform_newlines(text))
         caption = app.caption(_("dialog title", "Save Selection"))
     filetypes = app.filetypes(ly.lex.extensions[mode])
     dirname = os.path.dirname(doc.url().toLocalFile()) or app.basedir()
     filename = QFileDialog.getSaveFileName(self, caption, dirname, filetypes)[0]
     if not filename:
         return # cancelled
     try:
         with open(filename, "wb") as f:
             f.write(data)
     except IOError as e:
         msg = _("{message}\n\n{strerror} ({errno})").format(
             message = _("Could not write to: {url}").format(url=filename),
             strerror = e.strerror,
             errno = e.errno)
         QMessageBox.critical(self, app.caption(_("Error")), msg)
Example #20
0
 def translateUI(self):
     extension = self._ext_maintainer[0]
     self.errorLabel.setText(
         _("An internal error has occurred{}:").format(
             " in extension '{}'".format(extension) if extension else ""))
     title = (app.caption(_("Extension Error"))
              if extension else app.caption(_("Internal Error")))
     self.setWindowTitle(title)
     self.buttons.button(QDialogButtonBox.Ok).setText(
         _("Email Bug Report..."))
Example #21
0
    def print(self, printer=None, pageNumbers=None, showDialog=True):
        """Print the contents of the View."""
        import qpageview.poppler
        import qpageview.cupsprinter

        if printer is None:
            if self._printer is None:
                self._printer = QPrinter()
            printer = self._printer
        printer.setCopyCount(1)  # prevent embarrassing situations :-)
        if self.document() and self.document().filename():
            filename = os.path.basename(self.document().filename())
        else:
            filename = ""
        printer.setDocName(filename)
        if showDialog:
            qpageview.cupsprinter.clearPageSetSetting(printer)
            dlg = QPrintDialog(printer, self)
            if filename:
                title = app.caption(
                    _("Print {filename}").format(filename=filename))
            else:
                title = app.caption(_("Print"))
            dlg.setWindowTitle(title)
            dlg.setMinMax(1, self.pageCount())
            if not dlg.exec_():
                return  # cancelled
        s = QSettings()
        printer.setResolution(s.value("printing/dpi", 300, int))

        # is it possible and preferred to print a PDF directly with cups?
        # on Mac, when printing directly with cups, the system print window is shown
        # but its settings are ignored and any choice (including opening the PDF)
        # results in printing to cups' default printer
        if (s.value("printing/directcups",
                    False if sys.platform.startswith('darwin') else True, bool)
                and isinstance(self.document(),
                               qpageview.poppler.PopplerDocument)
                and os.path.isfile(self.document().filename())
                and not printer.outputFileName()):
            h = qpageview.cupsprinter.handle(printer)
            if h:
                if not h.printFile(self.document().filename()):
                    QMessageBox.warning(
                        self, _("Printing Error"), "{0}\n{1}".format(
                            _("An error occurred (code: {num}):").format(
                                num=h.status), h.error))
                return
        job = super().print(printer, pageNumbers, False)
        if job:
            progress = PrintProgressDialog(job, self)
            progress.setWindowTitle(title)
            progress.setLabelText(_("Preparing to print..."))
            progress.show()
Example #22
0
    def saveDocument(self, doc, save_as=False):
        """ Saves the document, asking for a name if necessary.

        If save_as is True, a name is always asked.
        Returns True if saving succeeded.

        """
        if save_as or doc.url().isEmpty():
            filename = doc.url().toLocalFile()
            if filename:
                filetypes = app.filetypes(os.path.splitext(filename)[1])
            else:
                # find a suitable directory to save to
                for d in self.historyManager.documents()[1::]:
                    if d.url().toLocalFile():
                        directory = os.path.dirname(d.url().toLocalFile())
                        break
                else:
                    directory = app.basedir() # default directory to save to
                
                import documentinfo
                import ly.lex
                filename = os.path.join(directory, documentinfo.defaultfilename(doc))
                filetypes = app.filetypes(ly.lex.extensions[documentinfo.mode(doc)])
            caption = app.caption(_("dialog title", "Save File"))
            filename = QFileDialog.getSaveFileName(self, caption, filename, filetypes)[0]
            if not filename:
                return False # cancelled
            url = QUrl.fromLocalFile(filename)
        else:
            url = doc.url()

        if QSettings().value("strip_trailing_whitespace", False, bool):
            import reformat
            reformat.remove_trailing_whitespace(QTextCursor(doc))

        # we only support local files for now
        filename = url.toLocalFile()
        b = backup.backup(filename)
        try:
            doc.save(url)
        except IOError as e:
            msg = _("{message}\n\n{strerror} ({errno})").format(
                message = _("Could not write to: {url}").format(url=filename),
                strerror = e.strerror,
                errno = e.errno)
            QMessageBox.critical(self, app.caption(_("Error")), msg)
            return False
        else:
            if b:
                backup.removeBackup(filename)
            recentfiles.add(doc.url())
        return True
Example #23
0
 def translateUI(self):
     extension = self._ext_maintainer[0]
     self.errorLabel.setText(
         _("An internal error has occurred{}:").format(
           " in extension '{}'".format(extension)
           if extension
           else ""))
     title = (
         app.caption(_("Extension Error"))
         if extension
         else app.caption(_("Internal Error")))
     self.setWindowTitle(title)
     self.buttons.button(QDialogButtonBox.Ok).setText(_("Email Bug Report..."))
Example #24
0
 def exportAudio(self):
     """ Convert the current document to Audio """
     mainwin = self.mainwindow()
     doc = mainwin.currentDocument()
     midfiles = resultfiles.results(doc).files('.mid*')
     if not midfiles:
         QMessageBox.critical(
             None, _("Error"),
             _("The audio file couldn't be created. Please create midi file first"
               ))
         return False
     orgname = doc.url().toLocalFile()
     midifile = midfiles[0]
     wavfile = os.path.splitext(orgname)[0] + '.wav'
     caption = app.caption(_("dialog title", "Export Audio File"))
     filetypes = '{0} (*.wav);;{1} (*)'.format(_("WAV Files"),
                                               _("All Files"))
     wavfile = QFileDialog.getSaveFileName(mainwin, caption, wavfile,
                                           filetypes)[0]
     if not wavfile:
         return False  # cancelled
     dlg = AudioExportDialog(mainwin, caption)
     dlg.setAttribute(Qt.WA_DeleteOnClose)  # we use it only once
     dlg.midi2wav(midifile, wavfile)
     dlg.show()
Example #25
0
 def printSource(self):
     cursor = self.currentView().textCursor()
     printer = QPrinter()
     dlg = QPrintDialog(printer, self)
     dlg.setWindowTitle(app.caption(_("dialog title", "Print Source")))
     options = QAbstractPrintDialog.PrintToFile | QAbstractPrintDialog.PrintShowPageSize
     if cursor.hasSelection():
         options |= QAbstractPrintDialog.PrintSelection
     dlg.setOptions(options)
     if dlg.exec_():
         doc = highlighter.htmlCopy(self.currentDocument(), "printer")
         doc.setMetaInformation(QTextDocument.DocumentTitle, self.currentDocument().url().toString())
         font = doc.defaultFont()
         font.setPointSizeF(font.pointSizeF() * 0.8)
         doc.setDefaultFont(font)
         if dlg.testOption(QAbstractPrintDialog.PrintSelection):
             # cut out not selected text
             start, end = cursor.selectionStart(), cursor.selectionEnd()
             cur1 = QTextCursor(doc)
             cur1.setPosition(start, QTextCursor.KeepAnchor)
             cur2 = QTextCursor(doc)
             cur2.setPosition(end)
             cur2.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
             cur2.removeSelectedText()
             cur1.removeSelectedText()
         doc.print_(printer)
Example #26
0
 def setCaption(self):
     if self._filename:
         filename = os.path.basename(self._filename)
     else:
         filename = _("<unknown>")
     title = _("Image from {filename}").format(filename = filename)
     self.setWindowTitle(app.caption(title))
Example #27
0
 def importAll(self):
     """Reads the file type and determines which import to use."""
     filetypes = ";;".join(
         (
             "{0} (*.xml *.mxl *.midi *.mid *.abc)".format(_("All importable formats")),
             "{0} (*.xml *.mxl)".format(_("MusicXML Files")),
             "{0} (*.midi *.mid)".format(_("Midi Files")),
             "{0} (*.abc)".format(_("ABC Files")),
             "{0} (*)".format(_("All Files")),
         )
     )
     caption = app.caption(_("dialog title", "Import"))
     directory = os.path.dirname(self.mainwindow().currentDocument().url().toLocalFile()) or app.basedir()
     importfiles = QFileDialog.getOpenFileNames(self.mainwindow(), caption, directory, filetypes)
     if not importfiles:
         return  # the dialog was cancelled by user
     for imp in importfiles:
         if self.isImportable(imp):
             self.openDialog(imp)
         else:
             QMessageBox.critical(
                 None,
                 _("Error"),
                 _("The file {filename} could not be converted. " "Wrong file type.").format(filename=imp),
             )
Example #28
0
def importShortcut(filename, widget, schemeWidget):
    """Loads shortcuts from a file"""
    try:
        d = ET.parse(filename)
        root = d.getroot()
        if root.tag != 'frescobaldi-shortcut':
            raise ValueError(_("No shortcuts found."))
    except Exception as e:
        QMessageBox.critical(widget, app.caption(_("Error")),
        _("Can't read from source:\n\n{url}\n\n{error}").format(
            url=filename, error=e))
        return
    
    schemeWidget.scheme.blockSignals(True)
    scheme = schemeWidget.addScheme(root.get('name'))
    schemeWidget.scheme.blockSignals(False)
    
    for col in root.findall('collection'):
        for name in col.findall('name'):
            shortcuts = [QKeySequence.fromString(shortcut.text) for shortcut in name.findall('shortcut')]
            item = widget.item(col.attrib['name'], name.attrib['name'])
            if item:
                item.setShortcuts(shortcuts, scheme)
            
    schemeWidget.disableDefault(False)
    schemeWidget.currentChanged.emit()
    schemeWidget.changed.emit()
Example #29
0
 def translateUI(self):
     self.setWindowTitle(app.caption(_("LilyPond")))
     self.lilypondLabel.setText(_("LilyPond Command:"))
     self.lilypond.lineEdit.setToolTip(_("Name or full path of the LilyPond program."))
     self.convert_lyLabel.setText(_("Convert-ly:"))
     self.lilypond_bookLabel.setText(_("LilyPond-book:"))
     self.auto.setText(_("Include in automatic version selection"))
Example #30
0
 def openDocuments(self, urls, encoding=None):
     """Open a list of urls, with error handling.
     
     The last loaded document is made current.
     
     """
     doc = None
     failures = []
     for url in urls:
         try:
             doc = self.openUrl(url)
         except IOError as e:
             failures.append((url, e))
     if doc:
         self.setCurrentDocument(doc)
     if failures:
         if len(failures) == 1:
             url, e = failures[0]
             filename = url.toLocalFile()
             msg = _("{message}\n\n{strerror} ({errno})").format(
                 message=_("Could not read from: {url}").format(
                     url=filename),
                 strerror=e.strerror,
                 errno=e.errno)
         else:
             msg = _("Could not read:") + "\n\n" + "\n".join(
                 "{url}: {strerror} ({errno})".format(url=url.toLocalFile(),
                                                      strerror=e.strerror,
                                                      errno=e.errno)
                 for url, e in failures)
         QMessageBox.critical(self, app.caption(_("Error")), msg)
Example #31
0
 def translateUI(self):
     title = _("Edit Snippet") if self._name else _("New Snippet")
     self.setWindowTitle(app.caption(title))
     self.topLabel.setText(_("Snippet Text:"))
     self.titleLabel.setText(_("Title:"))
     self.shortcutLabel.setText(_("Shortcut:"))
     self.shortcutButton.updateText()
Example #32
0
 def translateUI(self):
     self.setWindowTitle(app.caption(_("Modified Files")))
     self.setMessage(
         _("The following files were modified or deleted by other "
           "applications:"))
     self.buttonReload.setText(_("Reload"))
     self.buttonReload.setToolTip(
         _("Reloads the selected documents from disk. "
           "(You can still reach the previous state of the document "
           "using the Undo command.)"))
     self.buttonReloadAll.setText(_("Reload All"))
     self.buttonReloadAll.setToolTip(
         _("Reloads all externally modified documents from disk. "
           "(You can still reach the previous state of the document "
           "using the Undo command.)"))
     self.buttonSave.setText(_("Save"))
     self.buttonSave.setToolTip(
         _("Saves the selected documents to disk, overwriting the "
           "modifications by another program."))
     self.buttonSaveAll.setText(_("Save All"))
     self.buttonSaveAll.setToolTip(
         _("Saves all documents to disk, overwriting the modifications by "
           "another program."))
     self.buttonShowDiff.setText(_("Show Difference..."))
     self.buttonShowDiff.setToolTip(
         _("Shows the differences between the current document "
           "and the file on disk."))
     self.checkWatchingEnabled.setText(
         _("Enable watching documents for external changes"))
     self.checkWatchingEnabled.setToolTip(
         _("If checked, Frescobaldi will warn you when opened files are "
           "modified or deleted by other applications."))
Example #33
0
    def importMusicXML(self):
        """ Opens a MusicXML file. Converts it to ly by using musicxml2ly """
        filetypes = '{0} (*.xml);;{1} (*)'.format(_("XML Files"),
                                                  _("All Files"))
        caption = app.caption(_("dialog title", "Import a MusicXML file"))
        directory = os.path.dirname(self.mainwindow().currentDocument().url().
                                    toLocalFile()) or app.basedir()
        importfile = QFileDialog.getOpenFileName(self.mainwindow(), caption,
                                                 directory, filetypes)
        if not importfile:
            return  # the dialog was cancelled by user

        try:
            dlg = self._importDialog
        except AttributeError:
            from . import musicxml
            dlg = self._importDialog = musicxml.Dialog(self.mainwindow())
            dlg.addAction(self.mainwindow().actionCollection.help_whatsthis)
            dlg.setWindowModality(Qt.WindowModal)

        dlg.setDocument(importfile)
        if dlg.exec_():
            with qutil.busyCursor():
                stdout, stderr = dlg.run_command()
            if stdout:  #success
                dlg.saveSettings()
                lyfile = os.path.splitext(importfile)[0] + ".ly"
                doc = self.createDocument(lyfile, stdout.decode('utf-8'))
                self.postImport(dlg.getPostSettings(), doc)
                self.mainwindow().saveDocument(doc)
            else:  #failure to convert
                QMessageBox.critical(
                    None, _("Error"),
                    _("The file couldn't be converted. Error message:\n") +
                    stderr.decode('utf-8'))
Example #34
0
 def setCaption(self):
     if self._filename:
         filename = os.path.basename(self._filename)
     else:
         filename = _("<unknown>")
     title = _("Image from {filename}").format(filename = filename)
     self.setWindowTitle(app.caption(title))
Example #35
0
 def translateUI(self):
     self.setWindowTitle(app.caption(_("Modified Files")))
     self.setMessage(_(
         "The following files were modified or deleted by other "
         "applications:"))
     self.buttonReload.setText(_("Reload"))
     self.buttonReload.setToolTip(_(
         "Reloads the selected documents from disk. "
         "(You can still reach the previous state of the document "
         "using the Undo command.)"))
     self.buttonReloadAll.setText(_("Reload All"))
     self.buttonReloadAll.setToolTip(_(
         "Reloads all externally modified documents from disk. "
         "(You can still reach the previous state of the document "
         "using the Undo command.)"))
     self.buttonSave.setText(_("Save"))
     self.buttonSave.setToolTip(_(
         "Saves the selected documents to disk, overwriting the "
         "modifications by another program."))
     self.buttonSaveAll.setText(_("Save All"))
     self.buttonSaveAll.setToolTip(_(
         "Saves all documents to disk, overwriting the modifications by "
         "another program."))
     self.buttonShowDiff.setText(_("Show Difference..."))
     self.buttonShowDiff.setToolTip(_(
         "Shows the differences between the current document "
         "and the file on disk."))
     self.checkWatchingEnabled.setText(_(
         "Enable watching documents for external changes"))
     self.checkWatchingEnabled.setToolTip(_(
         "If checked, Frescobaldi will warn you when opened files are "
         "modified or deleted by other applications."))
Example #36
0
def importShortcut(filename, widget, schemeWidget):
    """Loads shortcuts from a file"""
    try:
        d = ET.parse(filename)
        root = d.getroot()
        if root.tag != 'frescobaldi-shortcut':
            raise ValueError(_("No shortcuts found."))
    except Exception as e:
        QMessageBox.critical(
            widget, app.caption(_("Error")),
            _("Can't read from source:\n\n{url}\n\n{error}").format(
                url=filename, error=e))
        return

    schemeWidget.scheme.blockSignals(True)
    scheme = schemeWidget.addScheme(root.get('name'))
    schemeWidget.scheme.blockSignals(False)

    for col in root.findall('collection'):
        for name in col.findall('name'):
            shortcuts = [
                QKeySequence.fromString(shortcut.text)
                for shortcut in name.findall('shortcut')
            ]
            item = widget.item(col.attrib['name'], name.attrib['name'])
            if item:
                item.setShortcuts(shortcuts, scheme)

    schemeWidget.disableDefault(False)
    schemeWidget.currentChanged.emit()
    schemeWidget.changed.emit()
Example #37
0
 def openDocuments(self, urls, encoding=None):
     """Open a list of urls, with error handling.
     
     The last loaded document is made current.
     
     """
     doc = None
     failures = []
     for url in urls:
         try:
             doc = self.openUrl(url)
         except IOError as e:
             failures.append((url, e))
     if doc:
         self.setCurrentDocument(doc)
     if failures:
         if len(failures) == 1:
             url, e = failures[0]
             filename = url.toLocalFile()
             msg = _("{message}\n\n{strerror} ({errno})").format(
                 message = _("Could not read from: {url}").format(url=filename),
                 strerror = e.strerror,
                 errno = e.errno)
         else:
             msg = _("Could not read:") + "\n\n" + "\n".join(
                 "{url}: {strerror} ({errno})".format(
                     url = url.toLocalFile(),
                     strerror = e.strerror,
                     errno = e.errno) for url, e in failures)
         QMessageBox.critical(self, app.caption(_("Error")), msg)
Example #38
0
    def slotExport(self):
        """Called when the user activates the export action."""
        allrows = [
            row for row in range(model.model().rowCount())
            if not self.treeView.isRowHidden(row, QModelIndex())
        ]
        selectedrows = [
            i.row() for i in self.treeView.selectedIndexes()
            if i.column() == 0 and i.row() in allrows
        ]
        names = self.treeView.model().names()
        names = [names[row] for row in selectedrows or allrows]

        filetypes = "{0} (*.xml);;{1} (*)".format(_("XML Files"),
                                                  _("All Files"))
        n = len(names)
        caption = app.caption(
            _("dialog title", "Export {num} Snippet", "Export {num} Snippets",
              n).format(num=n))
        filename = QFileDialog.getSaveFileName(self, caption, None,
                                               filetypes)[0]
        if filename:
            from . import import_export
            try:
                import_export.save(names, filename)
            except (IOError, OSError) as e:
                QMessageBox.critical(
                    self, _("Error"),
                    _("Can't write to destination:\n\n{url}\n\n{error}").
                    format(url=filename, error=e.strerror))
Example #39
0
 def translateUI(self):
     title = _("Edit Snippet") if self._name else _("New Snippet")
     self.setWindowTitle(app.caption(title))
     self.topLabel.setText(_("Snippet Text:"))
     self.titleLabel.setText(_("Title:"))
     self.shortcutLabel.setText(_("Shortcut:"))
     self.updateShortcutText()
Example #40
0
 def insertFromFile(self):
     ext = os.path.splitext(self.currentDocument().url().path())[1]
     filetypes = app.filetypes(ext)
     caption = app.caption(_("dialog title", "Insert From File"))
     directory = os.path.dirname(self.currentDocument().url().toLocalFile()) or app.basedir()
     filename = QFileDialog.getOpenFileName(self, caption, directory, filetypes)
     if filename:
         try:
             data = open(filename).read()
         except (IOError, OSError) as err:
             QMessageBox.warning(self, app.caption(_("Error")),
                 _("Can't read from source:\n\n{url}\n\n{error}").format(
                     url=filename, error=err.strerror))
         else:
             text = util.decode(data)
             self.currentView().textCursor().insertText(text)
Example #41
0
 def importAll(self):
     """Reads the file type and determines which import to use."""
     filetypes = ';;'.join((
         '{0} (*.xml *.mxl *.midi *.mid *.abc)'.format(
             _("All importable formats")),
         '{0} (*.xml *.mxl)'.format(_("MusicXML Files")),
         '{0} (*.midi *.mid)'.format(_("Midi Files")),
         '{0} (*.abc)'.format(_("ABC Files")),
         '{0} (*)'.format(_("All Files")),
     ))
     caption = app.caption(_("dialog title", "Import"))
     directory = os.path.dirname(self.mainwindow().currentDocument().url().
                                 toLocalFile()) or app.basedir()
     importfiles = QFileDialog.getOpenFileNames(self.mainwindow(), caption,
                                                directory, filetypes)
     if not importfiles:
         return  # the dialog was cancelled by user
     for imp in importfiles:
         if self.isImportable(imp):
             self.openDialog()
         else:
             QMessageBox.critical(
                 None, _("Error"),
                 _("The file {filename} could not be converted. "
                   "Wrong file type.").format(filename=imp))
Example #42
0
 def printSource(self):
     cursor = self.textCursor()
     try:
         printer = self._sourcePrinter
     except AttributeError:
         printer = self._sourcePrinter = QPrinter()
     else:
         printer.setCopyCount(1)
     dlg = QPrintDialog(printer, self)
     dlg.setWindowTitle(app.caption(_("dialog title", "Print Source")))
     options = QAbstractPrintDialog.PrintToFile | QAbstractPrintDialog.PrintShowPageSize
     if cursor.hasSelection():
         options |= QAbstractPrintDialog.PrintSelection
     dlg.setOptions(options)
     if dlg.exec_():
         if dlg.printRange() != QAbstractPrintDialog.Selection:
             cursor.clearSelection()
         number_lines = QSettings().value("source_export/number_lines",
                                          False, bool)
         doc = highlighter.html_copy(cursor, 'printer', number_lines)
         doc.setMetaInformation(QTextDocument.DocumentTitle,
                                self.currentDocument().url().toString())
         font = doc.defaultFont()
         font.setPointSizeF(font.pointSizeF() * 0.8)
         doc.setDefaultFont(font)
         doc.print_(printer)
Example #43
0
    def importMusicXML(self):
        """ Opens a MusicXML file. Converts it to ly by using musicxml2ly """
        filetypes = "{0} (*.xml);;{1} (*)".format(_("XML Files"), _("All Files"))
        caption = app.caption(_("dialog title", "Import a MusicXML file"))
        directory = os.path.dirname(self.mainwindow().currentDocument().url().toLocalFile()) or app.basedir()
        importfile = QFileDialog.getOpenFileName(self.mainwindow(), caption, directory, filetypes)
        if not importfile:
            return  # the dialog was cancelled by user

        try:
            dlg = self._importDialog
        except AttributeError:
            from . import musicxml

            dlg = self._importDialog = musicxml.Dialog(self.mainwindow())
            dlg.addAction(self.mainwindow().actionCollection.help_whatsthis)
            dlg.setWindowModality(Qt.WindowModal)

        dlg.setDocument(importfile)
        if dlg.exec_():
            with qutil.busyCursor():
                stdout, stderr = dlg.run_command()
            if stdout:  # success
                dlg.saveSettings()
                lyfile = os.path.splitext(importfile)[0] + ".ly"
                doc = self.createDocument(lyfile, stdout.decode("utf-8"))
                self.postImport(dlg.getPostSettings(), doc)
                self.mainwindow().saveDocument(doc)
            else:  # failure to convert
                QMessageBox.critical(
                    None, _("Error"), _("The file couldn't be converted. Error message:\n") + stderr.decode("utf-8")
                )
Example #44
0
 def slotButtonShowDiff(self):
     """Called when the user clicks Show Difference."""
     docs = self.selectedDocuments() or self.allDocuments()
     if not docs:
         return
     d = docs[0]
     if documentwatcher.DocumentWatcher.instance(d).isdeleted():
         return
     
     filename = d.url().toLocalFile()
     try:
         with open(filename) as f:
             disktext = util.decode(f.read())
     except (IOError, OSError):
         return
     
     currenttext = d.toPlainText()
     
     html = htmldiff.htmldiff(
         currenttext, disktext, 
         _("Current Document"), _("Document on Disk"), numlines=5)
     dlg = widgets.dialog.Dialog(self, buttons=('close',))
     view = QTextBrowser(lineWrapMode=QTextBrowser.NoWrap)
     view.setHtml(html)
     dlg.setMainWidget(view)
     dlg.setWindowTitle(app.caption("Differences"))
     dlg.setMessage(_(
         "Document: {url}\n"
         "Difference between the current document and the file on disk:").format(
             url=filename))
     dlg.setWindowModality(Qt.NonModal)
     dlg.setAttribute(Qt.WA_QuitOnClose, False)
     dlg.setAttribute(Qt.WA_DeleteOnClose)
     qutil.saveDialogSize(dlg, "externalchanges/diff/dialog/size", QSize(600, 300))
     dlg.show()
Example #45
0
 def translateUI(self):
     self.setWindowTitle(app.caption(_("Score Setup Wizard")))
     for i in range(self.tabs.count()):
         self.tabs.setTabText(i, self.tabs.widget(i).title())
     self.dialogButtons.button(QDialogButtonBox.Reset).setText(_("Clear"))
     self.dialogButtons.button(QDialogButtonBox.Reset).setToolTip(
         _("Clears the current page of the Score Wizard."))
     self.previewButton.setText(_("Preview"))
Example #46
0
 def slotImport(self):
     filetypes = "{0} (*.xml);;{1} (*)".format(_("XML Files"),
                                               _("All Files"))
     caption = app.caption(_("dialog title", "Import color theme"))
     filename = QFileDialog.getOpenFileName(self, caption, QDir.homePath(),
                                            filetypes)[0]
     if filename:
         self.parent().import_(filename)
Example #47
0
    def saveDocument(self, doc, save_as=False):
        """ Saves the document, asking for a name if necessary.
        
        If save_as is True, a name is always asked.
        Returns True if saving succeeded.
        
        """
        if save_as or doc.url().isEmpty():
            filename = doc.url().toLocalFile()
            if filename:
                filetypes = app.filetypes(os.path.splitext(filename)[1])
            else:
                directory = app.basedir() # default directory to save to
                import documentinfo
                import ly.lex
                filename = os.path.join(directory, documentinfo.defaultfilename(doc))
                filetypes = app.filetypes(ly.lex.extensions[documentinfo.mode(doc)])
            caption = app.caption(_("dialog title", "Save File"))
            filename = QFileDialog.getSaveFileName(self, caption, filename, filetypes)
            if not filename:
                return False # cancelled
            url = QUrl.fromLocalFile(filename)
        else:
            url = doc.url()
        
        if QSettings().value("strip_trailing_whitespace", False, bool):
            import reformat
            reformat.remove_trailing_whitespace(QTextCursor(doc))

        # we only support local files for now
        filename = url.toLocalFile()
        b = backup.backup(filename)
        try:
            doc.save(url)
        except IOError as e:
            msg = _("{message}\n\n{strerror} ({errno})").format(
                message = _("Could not write to: {url}").format(url=filename),
                strerror = e.strerror,
                errno = e.errno)
            QMessageBox.critical(self, app.caption(_("Error")), msg)
            return False
        else:
            if b:
                backup.removeBackup(filename)
            recentfiles.add(doc.url())
        return True
Example #48
0
 def translateUI(self):
     self.setWindowTitle(app.caption(_("window title", "Edit Shortcut")))
     self.buttonNone.setText(_("&No shortcut"))
     self.buttonCustom.setText(_("Use a &custom shortcut:"))
     for num in range(4):
         self.keylabels[num].setText(
             _("Alternative #{num}:").format(
                 num=num) if num else _("Primary shortcut:"))
Example #49
0
 def translateUI(self):
     self.setWindowTitle(app.caption(_("Score Setup Wizard")))
     for i in range(self.tabs.count()):
         self.tabs.setTabText(i, self.tabs.widget(i).title())
     self.dialogButtons.button(QDialogButtonBox.Reset).setText(_("Clear"))
     self.dialogButtons.button(QDialogButtonBox.Reset).setToolTip(_(
         "Clears the current page of the Score Wizard."))
     self.previewButton.setText(_("Preview"))
Example #50
0
 def translateUI(self):
     self.setWindowTitle(app.caption(_("Import Music XML")))
     self.noartCheck.setText(_("No articulation directions"))
     self.norestCheck.setText(_("No rest positions"))
     self.nolayoutCheck.setText(_("No page layout"))
     self.nobeamCheck.setText(_("Auto beaming"))
     self.commandLineLabel.setText(_("Command line:"))
     self.buttons.button(QDialogButtonBox.Ok).setText(_("Run musicxml2ly"))
Example #51
0
 def translateUI(self):
     self.setWindowTitle(app.caption(_("Manage Sessions")))
     self.imp.setText(_("&Import..."))
     self.imp.setToolTip(_("Opens a dialog to import a session from a file."))
     self.exp.setText(_("E&xport..."))
     self.exp.setToolTip(_("Opens a dialog to export a session to a file."))
     self.act.setText(_("&Activate"))
     self.act.setToolTip(_("Switches to the selected session."))
Example #52
0
 def translateUI(self):
     self.setWindowTitle(app.caption(_("Manage Sessions")))
     self.imp.setText(_("&Import..."))
     self.imp.setToolTip(_("Opens a dialog to import a session from a file."))
     self.exp.setText(_("E&xport..."))
     self.exp.setToolTip(_("Opens a dialog to export a session to a file."))
     self.act.setText(_("&Activate"))
     self.act.setToolTip(_("Switches to the selected session."))
Example #53
0
 def openDocument(self):
     """ Displays an open dialog to open one or more documents. """
     ext = os.path.splitext(self.currentDocument().url().path())[1]
     filetypes = app.filetypes(ext)
     caption = app.caption(_("dialog title", "Open File"))
     directory = os.path.dirname(self.currentDocument().url().toLocalFile()) or app.basedir()
     files = QFileDialog.getOpenFileNames(self, caption, directory, filetypes)
     urls = [QUrl.fromLocalFile(filename) for filename in files]
     self.openDocuments(urls)
Example #54
0
 def importSession(self):
     """Called when the user clicks Import."""
     filetypes = '{0} (*.json);;{1} (*)'.format(_("JSON Files"), _("All Files"))
     caption = app.caption(_("dialog title", "Import session"))
     mainwindow = self.parent()
     directory = os.path.dirname(mainwindow.currentDocument().url().toLocalFile()) or app.basedir()
     importfile = QFileDialog.getOpenFileName(mainwindow, caption, directory, filetypes)
     if not importfile:
         return # cancelled by user
     try:
         with open(importfile) as f:
             self.sessions.importItem(json.load(f))
     except IOError as e:
         msg = _("{message}\n\n{strerror} ({errno})").format(
             message = _("Could not read from: {url}").format(url=importfile),
             strerror = e.strerror,
             errno = e.errno)
         QMessageBox.critical(self, app.caption(_("Error")), msg)
Example #55
0
 def translateUI(self):
     self.setWindowTitle(app.caption(_("Global Fonts")))
     self.setMessage(
         _("Please select the three global fonts to use for "
           r"<code>\roman</code>, <code>\sans</code>, and <code>\typewriter</code> "
           "respectively."))
     self.romanLabel.setText(_("Roman Font:"))
     self.sansLabel.setText(_("Sans Font:"))
     self.typewriterLabel.setText(_("Typewriter Font:"))
Example #56
0
 def slotImport(self):
     """Called when the user activates the import action."""
     filetypes = "{0} (*.xml);;{1} (*)".format(_("XML Files"), _("All Files"))
     caption = app.caption(_("dialog title", "Import Snippets"))
     filename = None
     filename = QFileDialog.getOpenFileName(self, caption, filename, filetypes)
     if filename:
         from . import import_export
         import_export.load(filename, self)
Example #57
0
def show_available_fonts(mainwin, info):
    """Display a dialog with the available fonts of LilyPond specified by info."""
    dlg = Dialog(mainwin)
    dlg.setWindowTitle(app.caption("Available Fonts"))
    dlg.run_command(info, ['-dshow-available-fonts'], _("Available Fonts"))
    dlg.setMessage(_(
        "List of fonts detected by {version}").format(version=info.prettyName()))
    qutil.saveDialogSize(dlg, "engrave/tools/available-fonts/dialog/size", QSize(640, 400))
    dlg.show()
Example #58
0
 def translateUI(self):
     self.setWindowTitle(app.caption(_("LilyPond")))
     self.lilynameLabel.setText(_("Label:"))
     self.lilynameLabel.setToolTip(_("How this version of LilyPond will be displayed."))
     self.lilypondLabel.setText(_("LilyPond Command:"))
     self.lilypond.lineEdit.setToolTip(_("Name or full path of the LilyPond program."))
     self.convert_lyLabel.setText(_("Convert-ly:"))
     self.lilypond_bookLabel.setText(_("LilyPond-book:"))
     self.auto.setText(_("Include in automatic version selection"))
Example #59
0
 def slotImport(self):
     """Called when the user activates the import action."""
     filetypes = "{0} (*.xml);;{1} (*)".format(_("XML Files"), _("All Files"))
     caption = app.caption(_("dialog title", "Import Snippets"))
     filename = None
     filename = QFileDialog.getOpenFileName(self, caption, filename, filetypes)
     if filename:
         from . import import_export
         import_export.load(filename, self)
Example #60
0
 def importSession(self):
     """Called when the user clicks Import."""
     filetypes = '{0} (*.json);;{1} (*)'.format(_("JSON Files"), _("All Files"))
     caption = app.caption(_("dialog title", "Import session"))
     mainwindow = self.parent()
     directory = os.path.dirname(mainwindow.currentDocument().url().toLocalFile()) or app.basedir()
     importfile = QFileDialog.getOpenFileName(mainwindow, caption, directory, filetypes)[0]
     if not importfile:
         return # cancelled by user
     try:
         with open(importfile, 'r') as f:
             self.sessions.importItem(json.load(f))
     except IOError as e:
         msg = _("{message}\n\n{strerror} ({errno})").format(
             message = _("Could not read from: {url}").format(url=importfile),
             strerror = e.strerror,
             errno = e.errno)
         QMessageBox.critical(self, app.caption(_("Error")), msg)