Пример #1
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)
Пример #2
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))
Пример #3
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)
Пример #4
0
 def openDocument(self):
     """ Displays an open dialog to open one or more documents. """
     d = self.currentDocument()
     if d:
         ext = os.path.splitext(d.url().path())[1]
         directory = os.path.dirname(d.url().toLocalFile()) or app.basedir()
     else:
         ext = ".ly"
         directory = app.basedir()
     filetypes = app.filetypes(ext)
     caption = app.caption(_("dialog title", "Open File"))
     files = QFileDialog.getOpenFileNames(self, caption, directory, filetypes)[0]
     urls = [QUrl.fromLocalFile(filename) for filename in files]
     docs = self.openUrls(urls)
     if docs:
         self.setCurrentDocument(docs[-1])
Пример #5
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)
Пример #6
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)
Пример #7
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))
Пример #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, 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))
Пример #9
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'))
Пример #10
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)
Пример #11
0
def file_open():
    filetypes = app.filetypes('.ly')
    caption = app.caption(_("dialog title", "Open File"))
    directory = app.basedir()
    files = QFileDialog.getOpenFileNames(None, caption, directory, filetypes)
    if files:
        w = mainwindow()
        docs = [w.openUrl(QUrl.fromLocalFile(f)) for f in files]
        if docs:
            w.setCurrentDocument(docs[-1])
Пример #12
0
def file_open():
    filetypes = app.filetypes(".ly")
    caption = app.caption(_("dialog title", "Open File"))
    directory = app.basedir()
    files = QFileDialog.getOpenFileNames(None, caption, directory, filetypes)
    if files:
        w = mainwindow()
        docs = [w.openUrl(QUrl.fromLocalFile(f)) for f in files]
        if docs:
            w.setCurrentDocument(docs[-1])
Пример #13
0
def file_open():
    filetypes = app.filetypes('.ly')
    caption = app.caption(_("dialog title", "Open File"))
    directory = app.basedir()
    files = QFileDialog.getOpenFileNames(None, caption, directory, filetypes)[0]
    if files:
        w = mainwindow()
        w.openUrls([QUrl.fromLocalFile(f) for f in files])
        if not app.documents:
            w.cleanStart()
Пример #14
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)
Пример #15
0
 def openViewdocs(self):
     """ Displays an open dialog to open music document(s). """
     caption = self._openViewdocsCaption()
     current_viewer_doc = self.widget().currentViewdoc()
     current_filename = current_viewer_doc.filename() if current_viewer_doc else None
     current_editor_document = self.mainwindow().currentDocument().url().toLocalFile()
     directory = os.path.dirname(current_filename or current_editor_document or app.basedir())
     filenames = QFileDialog().getOpenFileNames(self, caption, directory, '*.pdf',)[0]
     if filenames:
         # TODO: This has to be generalized too
         self.actionCollection.viewer_document_select.loadFiles(filenames)
Пример #16
0
 def openViewdocs(self):
     """ Displays an open dialog to open music document(s). """
     caption = self._openViewdocsCaption()
     current_viewer_doc = self.widget().currentViewdoc()
     current_filename = current_viewer_doc.filename() if current_viewer_doc else None
     current_editor_document = self.mainwindow().currentDocument().url().toLocalFile()
     directory = os.path.dirname(current_filename or current_editor_document or app.basedir())
     filenames = QFileDialog().getOpenFileNames(self, caption, directory, '*.pdf',)[0]
     if filenames:
         # TODO: This has to be generalized too
         self.actionCollection.viewer_document_select.loadFiles(filenames)
Пример #17
0
 def currentDirectory(self):
     """Returns the current directory of the current document.
     
     If the document has no filename yet, returns the configured default
     directory, or the user's home directory.
     Is that is not set as well, returns the current directory
     of the application.
     
     """
     import resultfiles
     return (resultfiles.results(self.currentDocument()).currentDirectory()
             or app.basedir() or QDir.homePath() or os.getcwdu())
Пример #18
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
Пример #19
0
 def currentDirectory(self):
     """Returns the current directory of the current document.
     
     If the document has no filename yet, returns the configured default
     directory, or the user's home directory.
     Is that is not set as well, returns the current directory
     of the application.
     
     """
     import resultfiles
     return (resultfiles.results(self.currentDocument()).currentDirectory()
             or app.basedir() or QDir.homePath() or os.getcwdu())
Пример #20
0
 def importMusicXML(self):
     """Opens a MusicXML file. Converts it to ly by using musicxml2ly."""
     filetypes = '{0} (*.xml *.mxl);;{1} (*)'.format(
         _("MusicXML Files"), _("All Files"))
     caption = app.caption(_("dialog title", "Import a MusicXML file"))
     directory = os.path.dirname(self.mainwindow().currentDocument().url().
                                 toLocalFile()) or app.basedir()
     self.importfile = QFileDialog.getOpenFileName(self.mainwindow(),
                                                   caption, directory,
                                                   filetypes)
     if not self.importfile:
         return  # the dialog was cancelled by user
     self.openMusicxmlDialog()
Пример #21
0
 def openDocument(self):
     """ Displays an open dialog to open one or more documents. """
     if app.documents:
         ext = os.path.splitext(self.currentDocument().url().path())[1]
         directory = os.path.dirname(self.currentDocument().url().toLocalFile()) or app.basedir()
     else:
         ext = ".ly"
         directory = app.basedir()
     filetypes = app.filetypes(ext)
     caption = app.caption(_("dialog title", "Open File"))
     files = QFileDialog.getOpenFileNames(self, caption, directory, filetypes)[0]
     urls = [QUrl.fromLocalFile(filename) for filename in files]
     docs = self.openUrls(urls)
     if docs:
         self.setCurrentDocument(docs[-1])
Пример #22
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)
Пример #23
0
    def get_import_file(self, filetypes, caption, multiple=False):
        """Open a File Open dialog for the requested filetype(s),
        return a list with one or multiple existing file names
        or an empty list in case the user has canceled the dialog."""
        caption = app.caption(caption)
        directory = (os.path.dirname(
            self.mainwindow().currentDocument().url().toLocalFile())
                     or app.basedir())

        if multiple:
            result = QFileDialog.getOpenFileNames(self.mainwindow(), caption,
                                                  directory, filetypes)[0]
            return result if result else []
        else:
            result = QFileDialog.getOpenFileName(self.mainwindow(), caption,
                                                 directory, filetypes)[0]
            return [result] if result else []
Пример #24
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
Пример #25
0
    def get_import_file(self, filetypes, caption, multiple=False):
        """Open a File Open dialog for the requested filetype(s),
        return a list with one or multiple existing file names
        or an empty list in case the user has canceled the dialog."""
        caption = app.caption(caption)
        directory = (os.path.dirname(
            self.mainwindow().currentDocument().url().toLocalFile())
            or app.basedir())

        if multiple:
            result = QFileDialog.getOpenFileNames(
                self.mainwindow(), caption, directory, filetypes)[0]
            return result if result else []
        else:
            result = QFileDialog.getOpenFileName(
                self.mainwindow(), caption, directory, filetypes)[0]
            return [result] if result else []
Пример #26
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)[0]
     if filename:
         try:
             with open(filename, 'rb') as f:
                 data = f.read()
         except IOError as e:
             msg = _("{message}\n\n{strerror} ({errno})").format(
                 message = _("Could not read from: {url}").format(url=filename),
                 strerror = e.strerror,
                 errno = e.errno)
             QMessageBox.critical(self, app.caption(_("Error")), msg)
         else:
             text = util.universal_newlines(util.decode(data))
             self.currentView().textCursor().insertText(text)
Пример #27
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)
Пример #28
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:
             with open(filename) as f:
                 data = f.read()
         except IOError as e:
             msg = _("{message}\n\n{strerror} ({errno})").format(
                 message = _("Could not read from: {url}").format(url=filename),
                 strerror = e.strerror,
                 errno = e.errno)
             QMessageBox.critical(self, app.caption(_("Error")), msg)
         else:
             text = util.decode(data)
             self.currentView().textCursor().insertText(text)
Пример #29
0
def move_to_include_file(cursor, parent_widget=None):
    """Opens a dialog to save the cursor's selection to a file.

    The cursor's selection is then replaced with an \\include statement.
    This function does its best to supply a good default filename and
    use it correctly in a relative \\include statement.

    Of course it only works well if the document already has a filename.

    """
    doc = cursor.document()
    text = cursor.selection().toPlainText()
    mode = fileinfo.textmode(text)
    caption = app.caption(_("dialog title", "Move to include file"))
    filetypes = app.filetypes(ly.lex.extensions[mode])
    name, ext = os.path.splitext(os.path.basename(doc.url().path()))
    if not ext or mode == "lilypond":
        ext = ".ily"
        version = documentinfo.docinfo(doc).version_string()
        if version:
            text = '\\version "{0}"\n\n{1}'.format(version, text)
    docname = name + "-include" + ext
    dirname = os.path.dirname(doc.url().toLocalFile()) or app.basedir()
    filename = os.path.join(dirname, docname)
    filename = QFileDialog.getSaveFileName(parent_widget, caption, filename,
                                           filetypes)[0]
    if not filename:
        return  # cancelled
    data = util.encode(util.platform_newlines(text))
    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(parent_widget, app.caption(_("Error")), msg)
        return
    filename = os.path.relpath(filename, dirname)
    command = '\\include "{0}"\n'.format(filename)
    cursor.insertText(command)
Пример #30
0
def move_to_include_file(cursor, parent_widget=None):
    """Opens a dialog to save the cursor's selection to a file.
    
    The cursor's selection is then replaced with an \\include statement.
    This function does its best to supply a good default filename and
    use it correctly in a relative \\include statement.
    
    Of course it only works well if the document already has a filename.
    
    """
    doc = cursor.document()
    text = cursor.selection().toPlainText()
    mode = fileinfo.textmode(text)
    caption = app.caption(_("dialog title", "Move to include file"))
    filetypes = app.filetypes(ly.lex.extensions[mode])
    name, ext = os.path.splitext(os.path.basename(doc.url().path()))
    if not ext or mode == "lilypond":
        ext = ".ily"
        version = documentinfo.docinfo(doc).version_string()
        if version:
            text = '\\version "{0}"\n\n{1}'.format(version, text)
    docname = name + "-include" + ext
    dirname = os.path.dirname(doc.url().toLocalFile()) or app.basedir()
    filename = os.path.join(dirname, docname)
    filename = QFileDialog.getSaveFileName(parent_widget, caption, filename, filetypes)[0]
    if not filename:
        return # cancelled
    data = util.encode(util.platform_newlines(text))
    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)
        return
    filename = os.path.relpath(filename, dirname)
    command = '\\include "{0}"\n'.format(filename)
    cursor.insertText(command)
Пример #31
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)
Пример #32
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)
Пример #33
0
 def exportSession(self):
     """Called when the user clicks Export."""
     itemname, jsondict = self.sessions.exportItem()
     caption = app.caption(_("dialog title", "Export session"))
     filetypes = '{0} (*.json);;{1} (*)'.format(
         _("JSON Files"), _("All Files"))
     mainwindow = self.parent()
     directory = os.path.dirname(
         mainwindow.currentDocument().url().toLocalFile()) or app.basedir()
     filename = os.path.join(directory, itemname + ".json")
     filename = QFileDialog.getSaveFileName(mainwindow, caption, filename,
                                            filetypes)[0]
     if not filename:
         return False  # cancelled
     try:
         with open(filename, 'w') as f:
             json.dump(jsondict, f, indent=4)
     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)
Пример #34
0
 def exportSession(self):
     """Called when the user clicks Export."""
     itemname, jsondict = self.sessions.exportItem()
     caption = app.caption(_("dialog title", "Export session"))
     filetypes = '{0} (*.json);;{1} (*)'.format(_("JSON Files"),
                                                _("All Files"))
     mainwindow = self.parent()
     directory = os.path.dirname(
         mainwindow.currentDocument().url().toLocalFile()) or app.basedir()
     filename = os.path.join(directory, itemname + ".json")
     filename = QFileDialog.getSaveFileName(mainwindow, caption, filename,
                                            filetypes)[0]
     if not filename:
         return False  # cancelled
     try:
         with open(filename, 'w') as f:
             json.dump(jsondict, f, indent=4)
     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)
Пример #35
0
 def importAbc(self):
     """Opens an abc file. Converts it to ly by using abc2ly."""
     filetypes = "{0} (*.abc);;{1} (*)".format(_("ABC Files"), _("All Files"))
     caption = app.caption(_("dialog title", "Import an abc file"))
     directory = os.path.dirname(self.mainwindow().currentDocument().url().toLocalFile()) or app.basedir()
     self.importfile = QFileDialog.getOpenFileName(self.mainwindow(), caption, directory, filetypes)
     if not self.importfile:
         return  # the dialog was cancelled by user
     self.openAbcDialog()
Пример #36
0
    def importMusicXML(self):
        """ Opens a MusicXML file. Converts it to ly by using musicxml2ly """
        filetypes = app.filetypes('*.xml')
        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()
                print stderr #put this in log window instead
                lyfile = os.path.splitext(importfile)[0] + ".ly"
                self.createDocument(lyfile, stdout.decode('utf-8'))
Пример #37
0
 def importAbc(self):
     """Opens an abc file. Converts it to ly by using abc2ly."""
     filetypes = '{0} (*.abc);;{1} (*)'.format(
         _("ABC Files"), _("All Files"))
     caption = app.caption(_("dialog title", "Import an abc file"))
     directory = os.path.dirname(self.mainwindow().currentDocument().url().toLocalFile()) or app.basedir()
     self.importfile = QFileDialog.getOpenFileName(self.mainwindow(), caption, directory, filetypes)[0]
     if not self.importfile:
         return # the dialog was cancelled by user
     self.openAbcDialog()
Пример #38
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")
                )
Пример #39
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)[0]
     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))
Пример #40
0
 def importMusicXML(self):
     """Opens a MusicXML file. Converts it to ly by using musicxml2ly."""
     filetypes = '{0} (*.xml *.mxl);;{1} (*)'.format(
         _("MusicXML Files"), _("All Files"))
     caption = app.caption(_("dialog title", "Import a MusicXML file"))
     directory = os.path.dirname(self.mainwindow().currentDocument().url().toLocalFile()) or app.basedir()
     self.importfile = QFileDialog.getOpenFileName(self.mainwindow(), caption, directory, filetypes)[0]
     if not self.importfile:
         return # the dialog was cancelled by user
     self.openMusicxmlDialog()