File: __init__.py

package info (click to toggle)
frescobaldi 3.3.0%2Bds1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 24,216 kB
  • sloc: python: 39,014; javascript: 263; sh: 238; makefile: 80
file content (140 lines) | stat: -rw-r--r-- 5,369 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# This file is part of the Frescobaldi project, http://www.frescobaldi.org/
#
# Copyright (c) 2008 - 2014 by Wilbert Berendsen
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
# See http://www.gnu.org/licenses/ for more information.

"""
Export to non-lilypond file types.
"""


import os

from PyQt5.QtCore import Qt, QUrl, QSize
from PyQt5.QtGui import QKeySequence
from PyQt5.QtWidgets import QAction, QFileDialog, QMessageBox

import app
import icons
import actioncollection
import actioncollectionmanager
import documentinfo
import plugin
import tokeniter
import appinfo
import codecs
import job
import qutil
import resultfiles
import externalcommand


class FileExport(plugin.MainWindowPlugin):
    def __init__(self, mainwindow):
        ac = self.actionCollection = Actions()
        actioncollectionmanager.manager(mainwindow).addActionCollection(ac)
        ac.export_musicxml.triggered.connect(self.exportMusicXML)
        ac.export_audio.triggered.connect(self.exportAudio)

    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(), orgname)
        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))

    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()


class AudioExportDialog(externalcommand.ExternalCommandDialog):

    """Dialog to show timidity output."""

    def __init__(self, parent, caption):
        super(AudioExportDialog, self).__init__(parent)
        self.setWindowModality(Qt.NonModal)
        self.setWindowTitle(caption)
        qutil.saveDialogSize(self, "audio_export/dialog/size", QSize(640, 400))

    def midi2wav(self, midfile, wavfile):
        """Run timidity to convert the MIDI to WAV."""
        self.wavfile = wavfile # we could need to clean it up...
        j = job.Job()
        j.decoder_stdout = j.decoder_stderr = codecs.getdecoder('utf-8')
        j.command = ["timidity", midfile, "-Ow", "-o", wavfile]
        self.run_job(j)

    def cleanup(self, state):
        if state == "aborted":
            try:
                os.remove(self.wavfile)
            except OSError:
                pass


class Actions(actioncollection.ActionCollection):
    name = "file_export"
    def createActions(self, parent):
        self.export_musicxml = QAction(parent)
        self.export_audio = QAction(parent)

        self.export_musicxml.setIcon(icons.get("document-export"))
        self.export_audio.setIcon(icons.get("document-export"))

    def translateUI(self):
        self.export_musicxml.setText(_("Export Music&XML..."))
        self.export_musicxml.setToolTip(_("Export current document as MusicXML."))

        self.export_audio.setText(_("Export Audio..."))
        self.export_audio.setToolTip(_("Export to different audio formats."))