]> git.donarmstrong.com Git - lilypond.git/blob - scripts/musicxml2ly.py
Merge branch 'master' into lilypond/translation
[lilypond.git] / scripts / musicxml2ly.py
1 #!@TARGET_PYTHON@
2 # -*- coding: utf-8 -*-
3 import optparse
4 import sys
5 import re
6 import os
7 import string
8 import codecs
9 import zipfile
10 import StringIO
11
12 """
13 @relocate-preamble@
14 """
15
16 import lilylib as ly
17 _ = ly._
18
19 import musicxml
20 import musicexp
21
22 from rational import Rational
23
24 # Store command-line options in a global variable, so we can access them everythwere
25 options = None
26
27 class Conversion_Settings:
28     def __init__(self):
29        self.ignore_beaming = False
30
31 conversion_settings = Conversion_Settings ()
32 # Use a global variable to store the setting needed inside a \layout block.
33 # whenever we need to change a setting or add/remove an engraver, we can access
34 # this layout and add the corresponding settings
35 layout_information = musicexp.Layout ()
36
37 def progress (str):
38     ly.stderr_write (str + '\n')
39     sys.stderr.flush ()
40
41 def error_message (str):
42     ly.stderr_write (str + '\n')
43     sys.stderr.flush ()
44
45 needed_additional_definitions = []
46 additional_definitions = {
47
48   "tuplet-note-wrapper": """      % a formatter function, which is simply a wrapper around an existing
49       % tuplet formatter function. It takes the value returned by the given
50       % function and appends a note of given length.
51   #(define-public ((tuplet-number::append-note-wrapper function note) grob)
52     (let* ((txt (if function (function grob) #f)))
53       (if txt
54         (markup txt #:fontsize -5 #:note note UP)
55         (markup #:fontsize -5 #:note note UP)
56       )
57     )
58   )""",
59
60   "tuplet-non-default-denominator": """#(define ((tuplet-number::non-default-tuplet-denominator-text denominator) grob)
61   (number->string (if denominator
62                       denominator
63                       (ly:event-property (event-cause grob) 'denominator))))
64 """,
65
66   "tuplet-non-default-fraction": """#(define ((tuplet-number::non-default-tuplet-fraction-text denominator numerator) grob)
67     (let* ((ev (event-cause grob))
68            (den (if denominator denominator (ly:event-property ev 'denominator)))
69            (num (if numerator numerator (ly:event-property ev 'numerator))))
70        (format "~a:~a" den num)))
71 """,
72
73   "compound-time-signature": """%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
74 % Formatting of (possibly complex) compound time signatures
75 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
76
77 #(define-public (insert-markups l m)
78   (let* ((ll (reverse l)))
79     (let join-markups ((markups (list (car ll)))
80                        (remaining (cdr ll)))
81       (if (pair? remaining)
82         (join-markups (cons (car remaining) (cons m markups)) (cdr remaining))
83         markups))))
84
85 % Use a centered-column inside a left-column, because the centered column
86 % moves its reference point to the center, which the left-column undoes.
87 % The center-column also aligns its contented centered, which is not undone...
88 #(define-public (format-time-fraction time-sig-fraction)
89   (let* ((revargs (reverse (map number->string time-sig-fraction)))
90          (den (car revargs))
91          (nums (reverse (cdr revargs))))
92     (make-override-markup '(baseline-skip . 0)
93       (make-number-markup
94         (make-left-column-markup (list
95           (make-center-column-markup (list
96             (make-line-markup (insert-markups nums "+"))
97             den))))))))
98
99 #(define-public (format-complex-compound-time time-sig)
100   (let* ((sigs (map format-time-fraction time-sig)))
101     (make-override-markup '(baseline-skip . 0)
102       (make-number-markup
103         (make-line-markup
104           (insert-markups sigs (make-vcenter-markup "+")))))))
105
106 #(define-public (format-compound-time time-sig)
107   (cond
108     ((not (pair? time-sig)) (null-markup))
109     ((pair? (car time-sig)) (format-complex-compound-time time-sig))
110     (else (format-time-fraction time-sig))))
111
112
113 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
114 % Measure length calculation of (possibly complex) compound time signatures
115 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
116
117 #(define-public (calculate-time-fraction time-sig-fraction)
118   (let* ((revargs (reverse time-sig-fraction))
119          (den (car revargs))
120          (nums (cdr revargs)))
121     (ly:make-moment (apply + nums) den)))
122
123 #(define-public (calculate-complex-compound-time time-sig)
124   (let* ((sigs (map calculate-time-fraction time-sig)))
125     (let add-moment ((moment ZERO-MOMENT)
126                      (remaining sigs))
127       (if (pair? remaining)
128         (add-moment (ly:moment-add moment (car remaining)) (cdr remaining))
129         moment))))
130
131 #(define-public (calculate-compound-measure-length time-sig)
132   (cond
133     ((not (pair? time-sig)) (ly:make-moment 4 4))
134     ((pair? (car time-sig)) (calculate-complex-compound-time time-sig))
135     (else (calculate-time-fraction time-sig))))
136
137
138 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
139 % Base beat lenth
140 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
141
142 #(define-public (calculate-compound-base-beat-full time-sig)
143   (let* ((den (map last time-sig)))
144     (apply max den)))
145
146 #(define-public (calculate-compound-base-beat time-sig)
147   (ly:make-moment 1 (cond
148     ((not (pair? time-sig)) 4)
149     ((pair? (car time-sig)) (calculate-compound-base-beat-full time-sig))
150     (else (calculate-compound-base-beat-full (list time-sig))))))
151
152
153 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
154 % The music function to set the complex time signature
155 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
156
157 compoundMeter =
158 #(define-music-function (parser location args) (pair?)
159   (let ((mlen (calculate-compound-measure-length args))
160         (beat (calculate-compound-base-beat args)))
161   #{
162 \once \override Staff.TimeSignature #'stencil = #ly:text-interface::print
163 \once \override Staff.TimeSignature #'text = #(format-compound-time $args)
164 % \set Staff.beatGrouping = #(reverse (cdr (reverse $args)))
165 \set Timing.measureLength = $mlen
166 \set Timing.timeSignatureFraction = #(cons (ly:moment-main-numerator $mlen)
167                                            (ly:moment-main-denominator $mlen))
168 \set Timing.baseMoment = $beat
169
170 % TODO: Implement beatGrouping and auto-beam-settings!!!
171 #} ))
172 """
173 }
174
175 def round_to_two_digits (val):
176     return round (val * 100) / 100
177
178 def extract_paper_information (tree):
179     paper = musicexp.Paper ()
180     defaults = tree.get_maybe_exist_named_child ('defaults')
181     if not defaults:
182         return None
183     tenths = -1
184     scaling = defaults.get_maybe_exist_named_child ('scaling')
185     if scaling:
186         mm = scaling.get_named_child ('millimeters')
187         mm = string.atof (mm.get_text ())
188         tn = scaling.get_maybe_exist_named_child ('tenths')
189         tn = string.atof (tn.get_text ())
190         tenths = mm / tn
191         paper.global_staff_size = mm * 72.27 / 25.4
192     # We need the scaling (i.e. the size of staff tenths for everything!
193     if tenths < 0:
194         return None
195
196     def from_tenths (txt):
197         return round_to_two_digits (string.atof (txt) * tenths / 10)
198     def set_paper_variable (varname, parent, element_name):
199         el = parent.get_maybe_exist_named_child (element_name)
200         if el: # Convert to cm from tenths
201             setattr (paper, varname, from_tenths (el.get_text ()))
202
203     pagelayout = defaults.get_maybe_exist_named_child ('page-layout')
204     if pagelayout:
205         # TODO: How can one have different margins for even and odd pages???
206         set_paper_variable ("page_height", pagelayout, 'page-height')
207         set_paper_variable ("page_width", pagelayout, 'page-width')
208
209         pmargins = pagelayout.get_named_children ('page-margins')
210         for pm in pmargins:
211             set_paper_variable ("left_margin", pm, 'left-margin')
212             set_paper_variable ("right_margin", pm, 'right-margin')
213             set_paper_variable ("bottom_margin", pm, 'bottom-margin')
214             set_paper_variable ("top_margin", pm, 'top-margin')
215
216     systemlayout = defaults.get_maybe_exist_named_child ('system-layout')
217     if systemlayout:
218         sl = systemlayout.get_maybe_exist_named_child ('system-margins')
219         if sl:
220             set_paper_variable ("system_left_margin", sl, 'left-margin')
221             set_paper_variable ("system_right_margin", sl, 'right-margin')
222         set_paper_variable ("system_distance", systemlayout, 'system-distance')
223         set_paper_variable ("top_system_distance", systemlayout, 'top-system-distance')
224
225     stafflayout = defaults.get_named_children ('staff-layout')
226     for sl in stafflayout:
227         nr = getattr (sl, 'number', 1)
228         dist = sl.get_named_child ('staff-distance')
229         #TODO: the staff distance needs to be set in the Staff context!!!
230
231     # TODO: Finish appearance?, music-font?, word-font?, lyric-font*, lyric-language*
232     appearance = defaults.get_named_child ('appearance')
233     if appearance:
234         lws = appearance.get_named_children ('line-width')
235         for lw in lws:
236             # Possible types are: beam, bracket, dashes,
237             #    enclosure, ending, extend, heavy barline, leger,
238             #    light barline, octave shift, pedal, slur middle, slur tip,
239             #    staff, stem, tie middle, tie tip, tuplet bracket, and wedge
240             tp = lw.type
241             w = from_tenths (lw.get_text  ())
242             # TODO: Do something with these values!
243         nss = appearance.get_named_children ('note-size')
244         for ns in nss:
245             # Possible types are: cue, grace and large
246             tp = ns.type
247             sz = from_tenths (ns.get_text ())
248             # TODO: Do something with these values!
249         # <other-appearance> elements have no specified meaning
250
251     rawmusicfont = defaults.get_named_child ('music-font')
252     if rawmusicfont:
253         # TODO: Convert the font
254         pass
255     rawwordfont = defaults.get_named_child ('word-font')
256     if rawwordfont:
257         # TODO: Convert the font
258         pass
259     rawlyricsfonts = defaults.get_named_children ('lyric-font')
260     for lyricsfont in rawlyricsfonts:
261         # TODO: Convert the font
262         pass
263
264     return paper
265
266
267
268 # score information is contained in the <work>, <identification> or <movement-title> tags
269 # extract those into a hash, indexed by proper lilypond header attributes
270 def extract_score_information (tree):
271     header = musicexp.Header ()
272     def set_if_exists (field, value):
273         if value:
274             header.set_field (field, musicxml.escape_ly_output_string (value))
275
276     movement_title = tree.get_maybe_exist_named_child ('movement-title')
277     if movement_title:
278         set_if_exists ('title', movement_title.get_text ())
279     work = tree.get_maybe_exist_named_child ('work')
280     if work:
281         # Overwrite the title from movement-title with work->title
282         set_if_exists ('title', work.get_work_title ())
283         set_if_exists ('worknumber', work.get_work_number ())
284         set_if_exists ('opus', work.get_opus ())
285
286     identifications = tree.get_named_children ('identification')
287     for ids in identifications:
288         set_if_exists ('copyright', ids.get_rights ())
289         set_if_exists ('composer', ids.get_composer ())
290         set_if_exists ('arranger', ids.get_arranger ())
291         set_if_exists ('editor', ids.get_editor ())
292         set_if_exists ('poet', ids.get_poet ())
293
294         set_if_exists ('tagline', ids.get_encoding_software ())
295         set_if_exists ('encodingsoftware', ids.get_encoding_software ())
296         set_if_exists ('encodingdate', ids.get_encoding_date ())
297         set_if_exists ('encoder', ids.get_encoding_person ())
298         set_if_exists ('encodingdescription', ids.get_encoding_description ())
299
300         set_if_exists ('texidoc', ids.get_file_description ());
301
302         # Finally, apply the required compatibility modes
303         # Some applications created wrong MusicXML files, so we need to
304         # apply some compatibility mode, e.g. ignoring some features/tags
305         # in those files
306         software = ids.get_encoding_software_list ()
307
308         # Case 1: "Sibelius 5.1" with the "Dolet 3.4 for Sibelius" plugin
309         #         is missing all beam ends => ignore all beaming information
310         ignore_beaming_software = {
311             "Dolet 4 for Sibelius, Beta 2": "Dolet 4 for Sibelius, Beta 2",
312             "Dolet 3.5 for Sibelius": "Dolet 3.5 for Sibelius",
313             "Dolet 3.4 for Sibelius": "Dolet 3.4 for Sibelius",
314             "Dolet 3.3 for Sibelius": "Dolet 3.3 for Sibelius",
315             "Dolet 3.2 for Sibelius": "Dolet 3.2 for Sibelius",
316             "Dolet 3.1 for Sibelius": "Dolet 3.1 for Sibelius",
317             "Dolet for Sibelius 1.3": "Dolet for Sibelius 1.3",
318             "Noteworthy Composer": "Noteworthy Composer's nwc2xm[",
319         }
320         for s in software:
321             app_description = ignore_beaming_software.get (s, False);
322             if app_description:
323                 conversion_settings.ignore_beaming = True
324                 progress (_ ("Encountered file created by %s, containing wrong beaming information. All beaming information in the MusicXML file will be ignored") % app_description)
325
326     # TODO: Check for other unsupported features
327     return header
328
329 class PartGroupInfo:
330     def __init__ (self):
331         self.start = {}
332         self.end = {}
333     def is_empty (self):
334         return len (self.start) + len (self.end) == 0
335     def add_start (self, g):
336         self.start[getattr (g, 'number', "1")] = g
337     def add_end (self, g):
338         self.end[getattr (g, 'number', "1")] = g
339     def print_ly (self, printer):
340         error_message (_ ("Unprocessed PartGroupInfo %s encountered") % self)
341     def ly_expression (self):
342         error_message (_ ("Unprocessed PartGroupInfo %s encountered") % self)
343         return ''
344
345 def musicxml_step_to_lily (step):
346     if step:
347         return (ord (step) - ord ('A') + 7 - 2) % 7
348     else:
349         return None
350
351
352 def staff_attributes_to_string_tunings (mxl_attr):
353     details = mxl_attr.get_maybe_exist_named_child ('staff-details')
354     if not details:
355         return []
356     lines = 6
357     staff_lines = details.get_maybe_exist_named_child ('staff-lines')
358     if staff_lines:
359         lines = string.atoi (staff_lines.get_text ())
360
361     tunings = [musicexp.Pitch()]*lines
362     staff_tunings = details.get_named_children ('staff-tuning')
363     for i in staff_tunings:
364         p = musicexp.Pitch()
365         line = 0
366         try:
367             line = string.atoi (i.line) - 1
368         except ValueError:
369             pass
370         tunings[line] = p
371
372         step = i.get_named_child (u'tuning-step')
373         step = step.get_text ().strip ()
374         p.step = musicxml_step_to_lily (step)
375
376         octave = i.get_named_child (u'tuning-octave')
377         octave = octave.get_text ().strip ()
378         p.octave = int (octave) - 4
379
380         alter = i.get_named_child (u'tuning-alter')
381         if alter:
382             p.alteration = int (alter.get_text ().strip ())
383     # lilypond seems to use the opposite ordering than MusicXML...
384     tunings.reverse ()
385
386     return tunings
387
388
389 def staff_attributes_to_lily_staff (mxl_attr):
390     if not mxl_attr:
391         return musicexp.Staff ()
392
393     (staff_id, attributes) = mxl_attr.items ()[0]
394
395     # distinguish by clef:
396     # percussion (percussion and rhythmic), tab, and everything else
397     clef_sign = None
398     clef = attributes.get_maybe_exist_named_child ('clef')
399     if clef:
400         sign = clef.get_maybe_exist_named_child ('sign')
401         if sign:
402             clef_sign = {"percussion": "percussion", "TAB": "tab"}.get (sign.get_text (), None)
403
404     lines = 5
405     details = attributes.get_named_children ('staff-details')
406     for d in details:
407         staff_lines = d.get_maybe_exist_named_child ('staff-lines')
408         if staff_lines:
409             lines = string.atoi (staff_lines.get_text ())
410
411     # TODO: Handle other staff attributes like staff-space, etc.
412
413     staff = None
414     if clef_sign == "percussion" and lines == 1:
415         staff = musicexp.RhythmicStaff ()
416     elif clef_sign == "percussion":
417         staff = musicexp.DrumStaff ()
418         # staff.drum_style_table = ???
419     elif clef_sign == "tab":
420         staff = musicexp.TabStaff ()
421         staff.string_tunings = staff_attributes_to_string_tunings (attributes)
422         # staff.tablature_format = ???
423     else:
424         staff = musicexp.Staff ()
425         # TODO: Handle case with lines <> 5!
426         if (lines != 5):
427             staff.add_context_modification ("\\override StaffSymbol #'line-count = #%s" % lines)
428
429
430     return staff
431
432
433 def extract_score_structure (part_list, staffinfo):
434     score = musicexp.Score ()
435     structure = musicexp.StaffGroup (None)
436     score.set_contents (structure)
437
438     if not part_list:
439         return structure
440
441     def read_score_part (el):
442         if not isinstance (el, musicxml.Score_part):
443             return
444         # Depending on the attributes of the first measure, we create different
445         # types of staves (Staff, RhythmicStaff, DrumStaff, TabStaff, etc.)
446         staff = staff_attributes_to_lily_staff (staffinfo.get (el.id, None))
447         if not staff:
448             return None
449         staff.id = el.id
450         partname = el.get_maybe_exist_named_child ('part-name')
451         # Finale gives unnamed parts the name "MusicXML Part" automatically!
452         if partname and partname.get_text() != "MusicXML Part":
453             staff.instrument_name = partname.get_text ()
454         # part-name-display overrides part-name!
455         partname = el.get_maybe_exist_named_child ("part-name-display")
456         if partname:
457             staff.instrument_name = extract_display_text (partname)
458
459         partdisplay = el.get_maybe_exist_named_child ('part-abbreviation')
460         if partdisplay:
461             staff.short_instrument_name = partdisplay.get_text ()
462         # part-abbreviation-display overrides part-abbreviation!
463         partdisplay = el.get_maybe_exist_named_child ("part-abbreviation-display")
464         if partdisplay:
465             staff.short_instrument_name = extract_display_text (partdisplay)
466         # TODO: Read in the MIDI device / instrument
467
468         return staff
469
470     def read_score_group (el):
471         if not isinstance (el, musicxml.Part_group):
472             return
473         group = musicexp.StaffGroup ()
474         if hasattr (el, 'number'):
475             id = el.number
476             group.id = id
477             #currentgroups_dict[id] = group
478             #currentgroups.append (id)
479         if el.get_maybe_exist_named_child ('group-name'):
480             group.instrument_name = el.get_maybe_exist_named_child ('group-name').get_text ()
481         if el.get_maybe_exist_named_child ('group-abbreviation'):
482             group.short_instrument_name = el.get_maybe_exist_named_child ('group-abbreviation').get_text ()
483         if el.get_maybe_exist_named_child ('group-symbol'):
484             group.symbol = el.get_maybe_exist_named_child ('group-symbol').get_text ()
485         if el.get_maybe_exist_named_child ('group-barline'):
486             group.spanbar = el.get_maybe_exist_named_child ('group-barline').get_text ()
487         return group
488
489
490     parts_groups = part_list.get_all_children ()
491
492     # the start/end group tags are not necessarily ordered correctly and groups
493     # might even overlap, so we can't go through the children sequentially!
494
495     # 1) Replace all Score_part objects by their corresponding Staff objects,
496     #    also collect all group start/stop points into one PartGroupInfo object
497     staves = []
498     group_info = PartGroupInfo ()
499     for el in parts_groups:
500         if isinstance (el, musicxml.Score_part):
501             if not group_info.is_empty ():
502                 staves.append (group_info)
503                 group_info = PartGroupInfo ()
504             staff = read_score_part (el)
505             if staff:
506                 staves.append (staff)
507         elif isinstance (el, musicxml.Part_group):
508             if el.type == "start":
509                 group_info.add_start (el)
510             elif el.type == "stop":
511                 group_info.add_end (el)
512     if not group_info.is_empty ():
513         staves.append (group_info)
514
515     # 2) Now, detect the groups:
516     group_starts = []
517     pos = 0
518     while pos < len (staves):
519         el = staves[pos]
520         if isinstance (el, PartGroupInfo):
521             prev_start = 0
522             if len (group_starts) > 0:
523                 prev_start = group_starts[-1]
524             elif len (el.end) > 0: # no group to end here
525                 el.end = {}
526             if len (el.end) > 0: # closes an existing group
527                 ends = el.end.keys ()
528                 prev_started = staves[prev_start].start.keys ()
529                 grpid = None
530                 intersection = filter(lambda x:x in ends, prev_started)
531                 if len (intersection) > 0:
532                     grpid = intersection[0]
533                 else:
534                     # Close the last started group
535                     grpid = staves[prev_start].start.keys () [0]
536                     # Find the corresponding closing tag and remove it!
537                     j = pos + 1
538                     foundclosing = False
539                     while j < len (staves) and not foundclosing:
540                         if isinstance (staves[j], PartGroupInfo) and staves[j].end.has_key (grpid):
541                             foundclosing = True
542                             del staves[j].end[grpid]
543                             if staves[j].is_empty ():
544                                 del staves[j]
545                         j += 1
546                 grpobj = staves[prev_start].start[grpid]
547                 group = read_score_group (grpobj)
548                 # remove the id from both the start and end
549                 if el.end.has_key (grpid):
550                     del el.end[grpid]
551                 del staves[prev_start].start[grpid]
552                 if el.is_empty ():
553                     del staves[pos]
554                 # replace the staves with the whole group
555                 for j in staves[(prev_start + 1):pos]:
556                     group.append_staff (j)
557                 del staves[(prev_start + 1):pos]
558                 staves.insert (prev_start + 1, group)
559                 # reset pos so that we continue at the correct position
560                 pos = prev_start
561                 # remove an empty start group
562                 if staves[prev_start].is_empty ():
563                     del staves[prev_start]
564                     group_starts.remove (prev_start)
565                     pos -= 1
566             elif len (el.start) > 0: # starts new part groups
567                 group_starts.append (pos)
568         pos += 1
569
570     if len (staves) == 1:
571         return staves[0]
572     for i in staves:
573         structure.append_staff (i)
574     return score
575
576
577 def musicxml_duration_to_lily (mxl_note):
578     # if the note has no Type child, then that method returns None. In that case,
579     # use the <duration> tag instead. If that doesn't exist, either -> Error
580     dur = mxl_note.get_duration_info ()
581     if dur:
582         d = musicexp.Duration ()
583         d.duration_log = dur[0]
584         d.dots = dur[1]
585         # Grace notes by specification have duration 0, so no time modification
586         # factor is possible. It even messes up the output with *0/1
587         if not mxl_note.get_maybe_exist_typed_child (musicxml.Grace):
588             d.factor = mxl_note._duration / d.get_length ()
589         return d
590
591     else:
592         if mxl_note._duration > 0:
593             return rational_to_lily_duration (mxl_note._duration)
594         else:
595             mxl_note.message (_ ("Encountered note at %s without type and duration (=%s)") % (mxl_note.start, mxl_note._duration) )
596             return None
597
598
599 def rational_to_lily_duration (rational_len):
600     d = musicexp.Duration ()
601
602     rational_len.normalize_self ()
603     d_log = {1: 0, 2: 1, 4:2, 8:3, 16:4, 32:5, 64:6, 128:7, 256:8, 512:9}.get (rational_len.denominator (), -1)
604
605     # Duration of the form 1/2^n or 3/2^n can be converted to a simple lilypond duration
606     dots = {1: 0, 3: 1, 7: 2, 15: 3, 31: 4, 63: 5, 127: 6}.get (rational_len.numerator(), -1)
607     if ( d_log >= dots >= 0 ):
608         # account for the dots!
609         d.duration_log = d_log - dots
610         d.dots = dots
611     elif (d_log >= 0):
612         d.duration_log = d_log
613         d.factor = Rational (rational_len.numerator ())
614     else:
615         error_message (_ ("Encountered rational duration with denominator %s, "
616                        "unable to convert to lilypond duration") %
617                        rational_len.denominator ())
618         # TODO: Test the above error message
619         return None
620
621     return d
622
623 def musicxml_partial_to_lily (partial_len):
624     if partial_len > 0:
625         p = musicexp.Partial ()
626         p.partial = rational_to_lily_duration (partial_len)
627         return p
628     else:
629         return Null
630
631 # Detect repeats and alternative endings in the chord event list (music_list)
632 # and convert them to the corresponding musicexp objects, containing nested
633 # music
634 def group_repeats (music_list):
635     repeat_replaced = True
636     music_start = 0
637     i = 0
638     # Walk through the list of expressions, looking for repeat structure
639     # (repeat start/end, corresponding endings). If we find one, try to find the
640     # last event of the repeat, replace the whole structure and start over again.
641     # For nested repeats, as soon as we encounter another starting repeat bar,
642     # treat that one first, and start over for the outer repeat.
643     while repeat_replaced and i < 100:
644         i += 1
645         repeat_start = -1  # position of repeat start / end
646         repeat_end = -1 # position of repeat start / end
647         repeat_times = 0
648         ending_start = -1 # position of current ending start
649         endings = [] # list of already finished endings
650         pos = 0
651         last = len (music_list) - 1
652         repeat_replaced = False
653         final_marker = 0
654         while pos < len (music_list) and not repeat_replaced:
655             e = music_list[pos]
656             repeat_finished = False
657             if isinstance (e, RepeatMarker):
658                 if not repeat_times and e.times:
659                     repeat_times = e.times
660                 if e.direction == -1:
661                     if repeat_end >= 0:
662                         repeat_finished = True
663                     else:
664                         repeat_start = pos
665                         repeat_end = -1
666                         ending_start = -1
667                         endings = []
668                 elif e.direction == 1:
669                     if repeat_start < 0:
670                         repeat_start = 0
671                     if repeat_end < 0:
672                         repeat_end = pos
673                     final_marker = pos
674             elif isinstance (e, EndingMarker):
675                 if e.direction == -1:
676                     if repeat_start < 0:
677                         repeat_start = 0
678                     if repeat_end < 0:
679                         repeat_end = pos
680                     ending_start = pos
681                 elif e.direction == 1:
682                     if ending_start < 0:
683                         ending_start = 0
684                     endings.append ([ending_start, pos])
685                     ending_start = -1
686                     final_marker = pos
687             elif not isinstance (e, musicexp.BarLine):
688                 # As soon as we encounter an element when repeat start and end
689                 # is set and we are not inside an alternative ending,
690                 # this whole repeat structure is finished => replace it
691                 if repeat_start >= 0 and repeat_end > 0 and ending_start < 0:
692                     repeat_finished = True
693
694             # Finish off all repeats without explicit ending bar (e.g. when
695             # we convert only one page of a multi-page score with repeats)
696             if pos == last and repeat_start >= 0:
697                 repeat_finished = True
698                 final_marker = pos
699                 if repeat_end < 0:
700                     repeat_end = pos
701                 if ending_start >= 0:
702                     endings.append ([ending_start, pos])
703                     ending_start = -1
704
705             if repeat_finished:
706                 # We found the whole structure replace it!
707                 r = musicexp.RepeatedMusic ()
708                 if repeat_times <= 0:
709                     repeat_times = 2
710                 r.repeat_count = repeat_times
711                 # don't erase the first element for "implicit" repeats (i.e. no
712                 # starting repeat bars at the very beginning)
713                 start = repeat_start+1
714                 if repeat_start == music_start:
715                     start = music_start
716                 r.set_music (music_list[start:repeat_end])
717                 for (start, end) in endings:
718                     s = musicexp.SequentialMusic ()
719                     s.elements = music_list[start+1:end]
720                     r.add_ending (s)
721                 del music_list[repeat_start:final_marker+1]
722                 music_list.insert (repeat_start, r)
723                 repeat_replaced = True
724             pos += 1
725         # TODO: Implement repeats until the end without explicit ending bar
726     return music_list
727
728
729 # Extract the settings for tuplets from the <notations><tuplet> and the
730 # <time-modification> elements of the note:
731 def musicxml_tuplet_to_lily (tuplet_elt, time_modification):
732     tsm = musicexp.TimeScaledMusic ()
733     fraction = (1,1)
734     if time_modification:
735         fraction = time_modification.get_fraction ()
736     tsm.numerator = fraction[0]
737     tsm.denominator  = fraction[1]
738
739
740     normal_type = tuplet_elt.get_normal_type ()
741     if not normal_type and time_modification:
742         normal_type = time_modification.get_normal_type ()
743     if not normal_type and time_modification:
744         note = time_modification.get_parent ()
745         if note:
746             normal_type = note.get_duration_info ()
747     if normal_type:
748         normal_note = musicexp.Duration ()
749         (normal_note.duration_log, normal_note.dots) = normal_type
750         tsm.normal_type = normal_note
751
752     actual_type = tuplet_elt.get_actual_type ()
753     if actual_type:
754         actual_note = musicexp.Duration ()
755         (actual_note.duration_log, actual_note.dots) = actual_type
756         tsm.actual_type = actual_note
757
758     # Obtain non-default nrs of notes from the tuplet object!
759     tsm.display_numerator = tuplet_elt.get_normal_nr ()
760     tsm.display_denominator = tuplet_elt.get_actual_nr ()
761
762
763     if hasattr (tuplet_elt, 'bracket') and tuplet_elt.bracket == "no":
764         tsm.display_bracket = None
765     elif hasattr (tuplet_elt, 'line-shape') and getattr (tuplet_elt, 'line-shape') == "curved":
766         tsm.display_bracket = "curved"
767     else:
768         tsm.display_bracket = "bracket"
769
770     display_values = {"none": None, "actual": "actual", "both": "both"}
771     if hasattr (tuplet_elt, "show-number"):
772         tsm.display_number = display_values.get (getattr (tuplet_elt, "show-number"), "actual")
773
774     if hasattr (tuplet_elt, "show-type"):
775         tsm.display_type = display_values.get (getattr (tuplet_elt, "show-type"), None)
776
777     return tsm
778
779
780 def group_tuplets (music_list, events):
781
782
783     """Collect Musics from
784     MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
785     """
786
787
788     indices = []
789     brackets = {}
790
791     j = 0
792     for (ev_chord, tuplet_elt, time_modification) in events:
793         while (j < len (music_list)):
794             if music_list[j] == ev_chord:
795                 break
796             j += 1
797         nr = 0
798         if hasattr (tuplet_elt, 'number'):
799             nr = getattr (tuplet_elt, 'number')
800         if tuplet_elt.type == 'start':
801             tuplet_object = musicxml_tuplet_to_lily (tuplet_elt, time_modification)
802             tuplet_info = [j, None, tuplet_object]
803             indices.append (tuplet_info)
804             brackets[nr] = tuplet_info
805         elif tuplet_elt.type == 'stop':
806             bracket_info = brackets.get (nr, None)
807             if bracket_info:
808                 bracket_info[1] = j # Set the ending position to j
809                 del brackets[nr]
810
811     new_list = []
812     last = 0
813     for (i1, i2, tsm) in indices:
814         if i1 > i2:
815             continue
816
817         new_list.extend (music_list[last:i1])
818         seq = musicexp.SequentialMusic ()
819         last = i2 + 1
820         seq.elements = music_list[i1:last]
821
822         tsm.element = seq
823
824         new_list.append (tsm)
825         #TODO: Handle nested tuplets!!!!
826
827     new_list.extend (music_list[last:])
828     return new_list
829
830
831 def musicxml_clef_to_lily (attributes):
832     change = musicexp.ClefChange ()
833     (change.type, change.position, change.octave) = attributes.get_clef_information ()
834     return change
835
836 def musicxml_time_to_lily (attributes):
837     sig = attributes.get_time_signature ()
838     if not sig:
839         return None
840     change = musicexp.TimeSignatureChange()
841     change.fractions = sig
842     if (len(sig) != 2) or isinstance (sig[0], list):
843         needed_additional_definitions.append ("compound-time-signature")
844
845     time_elm = attributes.get_maybe_exist_named_child ('time')
846     if time_elm and hasattr (time_elm, 'symbol'):
847         change.style = { 'single-number': "'single-digit",
848                          'cut': None,
849                          'common': None,
850                          'normal': "'()"}.get (time_elm.symbol, "'()")
851     else:
852         change.style = "'()"
853
854     # TODO: Handle senza-misura measures
855     # TODO: Handle hidden time signatures (print-object="no")
856     # TODO: What shall we do if the symbol clashes with the sig? e.g. "cut"
857     #       with 3/8 or "single-number" with (2+3)/8 or 3/8+2/4?
858
859     return change
860
861 def musicxml_key_to_lily (attributes):
862     key_sig = attributes.get_key_signature ()
863     if not key_sig or not (isinstance (key_sig, list) or isinstance (key_sig, tuple)):
864         error_message (_ ("Unable to extract key signature!"))
865         return None
866
867     change = musicexp.KeySignatureChange()
868
869     if len (key_sig) == 2 and not isinstance (key_sig[0], list):
870         # standard key signature, (fifths, mode)
871         (fifths, mode) = key_sig
872         change.mode = mode
873
874         start_pitch  = musicexp.Pitch ()
875         start_pitch.octave = 0
876         try:
877             (n,a) = {
878                 'major'     : (0,0),
879                 'minor'     : (5,0),
880                 'ionian'    : (0,0),
881                 'dorian'    : (1,0),
882                 'phrygian'  : (2,0),
883                 'lydian'    : (3,0),
884                 'mixolydian': (4,0),
885                 'aeolian'   : (5,0),
886                 'locrian'   : (6,0),
887                 }[mode]
888             start_pitch.step = n
889             start_pitch.alteration = a
890         except  KeyError:
891             error_message (_ ("unknown mode %s, expecting 'major' or 'minor' "
892                 "or a church mode!") % mode)
893
894         fifth = musicexp.Pitch()
895         fifth.step = 4
896         if fifths < 0:
897             fifths *= -1
898             fifth.step *= -1
899             fifth.normalize ()
900         for x in range (fifths):
901             start_pitch = start_pitch.transposed (fifth)
902         change.tonic = start_pitch
903
904     else:
905         # Non-standard key signature of the form [[step,alter<,octave>],...]
906         # MusicXML contains C,D,E,F,G,A,B as steps, lily uses 0-7, so convert
907         alterations = []
908         for k in key_sig:
909             k[0] = musicxml_step_to_lily (k[0])
910             alterations.append (k)
911         change.non_standard_alterations = alterations
912     return change
913
914 def musicxml_transpose_to_lily (attributes):
915     transpose = attributes.get_transposition ()
916     if not transpose:
917         return None
918
919     shift = musicexp.Pitch ()
920     octave_change = transpose.get_maybe_exist_named_child ('octave-change')
921     if octave_change:
922         shift.octave = string.atoi (octave_change.get_text ())
923     chromatic_shift = string.atoi (transpose.get_named_child ('chromatic').get_text ())
924     chromatic_shift_normalized = chromatic_shift % 12;
925     (shift.step, shift.alteration) = [
926         (0,0), (0,1), (1,0), (2,-1), (2,0),
927         (3,0), (3,1), (4,0), (5,-1), (5,0),
928         (6,-1), (6,0)][chromatic_shift_normalized];
929
930     shift.octave += (chromatic_shift - chromatic_shift_normalized) / 12
931
932     diatonic = transpose.get_maybe_exist_named_child ('diatonic')
933     if diatonic:
934         diatonic_step = string.atoi (diatonic.get_text ()) % 7
935         if diatonic_step != shift.step:
936             # We got the alter incorrect!
937             old_semitones = shift.semitones ()
938             shift.step = diatonic_step
939             new_semitones = shift.semitones ()
940             shift.alteration += old_semitones - new_semitones
941
942     transposition = musicexp.Transposition ()
943     transposition.pitch = musicexp.Pitch ().transposed (shift)
944     return transposition
945
946 def musicxml_staff_details_to_lily (attributes):
947     details = attributes.get_maybe_exist_named_child ('staff-details')
948     if not details:
949         return None
950
951     ## TODO: Handle staff-type, staff-lines, staff-tuning, capo, staff-size
952     ret = []
953
954     stafflines = details.get_maybe_exist_named_child ('staff-lines')
955     if stafflines:
956         lines = string.atoi (stafflines.get_text ());
957         lines_event = musicexp.StaffLinesEvent (lines);
958         ret.append (lines_event);
959
960     return ret;
961
962
963 def musicxml_attributes_to_lily (attrs):
964     elts = []
965     attr_dispatch =  {
966         'clef': musicxml_clef_to_lily,
967         'time': musicxml_time_to_lily,
968         'key': musicxml_key_to_lily,
969         'transpose': musicxml_transpose_to_lily,
970         'staff-details': musicxml_staff_details_to_lily,
971     }
972     for (k, func) in attr_dispatch.items ():
973         children = attrs.get_named_children (k)
974         if children:
975             ev = func (attrs)
976             if isinstance (ev, list):
977               for e in ev:
978                 elts.append (e)
979             elif ev:
980                 elts.append (ev)
981
982     return elts
983
984 def extract_display_text (el):
985     child = el.get_maybe_exist_named_child ("display-text")
986     if child:
987         return child.get_text ()
988     else:
989         return False
990
991
992 def musicxml_print_to_lily (el):
993     # TODO: Implement other print attributes
994     #  <!ELEMENT print (page-layout?, system-layout?, staff-layout*,
995     #          measure-layout?, measure-numbering?, part-name-display?,
996     #          part-abbreviation-display?)>
997     #  <!ATTLIST print
998     #      staff-spacing %tenths; #IMPLIED
999     #      new-system %yes-no; #IMPLIED
1000     #      new-page %yes-no-number; #IMPLIED
1001     #      blank-page NMTOKEN #IMPLIED
1002     #      page-number CDATA #IMPLIED
1003     #  >
1004     elts = []
1005     if (hasattr (el, "new-system") and conversion_settings.convert_page_layout):
1006         val = getattr (el, "new-system")
1007         if (val == "yes"):
1008             elts.append (musicexp.Break ("break"))
1009     if (hasattr (el, "new-page") and conversion_settings.convert_page_layout):
1010         val = getattr (el, "new-page")
1011         if (val == "yes"):
1012             elts.append (musicexp.Break ("pageBreak"))
1013     child = el.get_maybe_exist_named_child ("part-name-display")
1014     if child:
1015         elts.append (musicexp.SetEvent ("Staff.instrumentName",
1016                                         "\"%s\"" % extract_display_text (child)))
1017     child = el.get_maybe_exist_named_child ("part-abbreviation-display")
1018     if child:
1019         elts.append (musicexp.SetEvent ("Staff.shortInstrumentName",
1020                                         "\"%s\"" % extract_display_text (child)))
1021     return elts
1022
1023
1024 class Marker (musicexp.Music):
1025     def __init__ (self):
1026         self.direction = 0
1027         self.event = None
1028     def print_ly (self, printer):
1029         ly.stderr_write (_ ("Encountered unprocessed marker %s\n") % self)
1030         pass
1031     def ly_expression (self):
1032         return ""
1033 class RepeatMarker (Marker):
1034     def __init__ (self):
1035         Marker.__init__ (self)
1036         self.times = 0
1037 class EndingMarker (Marker):
1038     pass
1039
1040 # Convert the <barline> element to musicxml.BarLine (for non-standard barlines)
1041 # and to RepeatMarker and EndingMarker objects for repeat and
1042 # alternatives start/stops
1043 def musicxml_barline_to_lily (barline):
1044     # retval contains all possible markers in the order:
1045     # 0..bw_ending, 1..bw_repeat, 2..barline, 3..fw_repeat, 4..fw_ending
1046     retval = {}
1047     bartype_element = barline.get_maybe_exist_named_child ("bar-style")
1048     repeat_element = barline.get_maybe_exist_named_child ("repeat")
1049     ending_element = barline.get_maybe_exist_named_child ("ending")
1050
1051     bartype = None
1052     if bartype_element:
1053         bartype = bartype_element.get_text ()
1054
1055     if repeat_element and hasattr (repeat_element, 'direction'):
1056         repeat = RepeatMarker ()
1057         repeat.direction = {"forward": -1, "backward": 1}.get (repeat_element.direction, 0)
1058
1059         if ( (repeat_element.direction == "forward" and bartype == "heavy-light") or
1060              (repeat_element.direction == "backward" and bartype == "light-heavy") ):
1061             bartype = None
1062         if hasattr (repeat_element, 'times'):
1063             try:
1064                 repeat.times = int (repeat_element.times)
1065             except ValueError:
1066                 repeat.times = 2
1067         repeat.event = barline
1068         if repeat.direction == -1:
1069             retval[3] = repeat
1070         else:
1071             retval[1] = repeat
1072
1073     if ending_element and hasattr (ending_element, 'type'):
1074         ending = EndingMarker ()
1075         ending.direction = {"start": -1, "stop": 1, "discontinue": 1}.get (ending_element.type, 0)
1076         ending.event = barline
1077         if ending.direction == -1:
1078             retval[4] = ending
1079         else:
1080             retval[0] = ending
1081
1082     if bartype:
1083         b = musicexp.BarLine ()
1084         b.type = bartype
1085         retval[2] = b
1086
1087     return retval.values ()
1088
1089 spanner_event_dict = {
1090     'beam' : musicexp.BeamEvent,
1091     'dashes' : musicexp.TextSpannerEvent,
1092     'bracket' : musicexp.BracketSpannerEvent,
1093     'glissando' : musicexp.GlissandoEvent,
1094     'octave-shift' : musicexp.OctaveShiftEvent,
1095     'pedal' : musicexp.PedalEvent,
1096     'slide' : musicexp.GlissandoEvent,
1097     'slur' : musicexp.SlurEvent,
1098     'wavy-line' : musicexp.TrillSpanEvent,
1099     'wedge' : musicexp.HairpinEvent
1100 }
1101 spanner_type_dict = {
1102     'start': -1,
1103     'begin': -1,
1104     'crescendo': -1,
1105     'decreschendo': -1,
1106     'diminuendo': -1,
1107     'continue': 0,
1108     'change': 0,
1109     'up': -1,
1110     'down': -1,
1111     'stop': 1,
1112     'end' : 1
1113 }
1114
1115 def musicxml_spanner_to_lily_event (mxl_event):
1116     ev = None
1117
1118     name = mxl_event.get_name()
1119     func = spanner_event_dict.get (name)
1120     if func:
1121         ev = func()
1122     else:
1123         error_message (_ ('unknown span event %s') % mxl_event)
1124
1125
1126     type = mxl_event.get_type ()
1127     span_direction = spanner_type_dict.get (type)
1128     # really check for None, because some types will be translated to 0, which
1129     # would otherwise also lead to the unknown span warning
1130     if span_direction != None:
1131         ev.span_direction = span_direction
1132     else:
1133         error_message (_ ('unknown span type %s for %s') % (type, name))
1134
1135     ev.set_span_type (type)
1136     ev.line_type = getattr (mxl_event, 'line-type', 'solid')
1137
1138     # assign the size, which is used for octave-shift, etc.
1139     ev.size = mxl_event.get_size ()
1140
1141     return ev
1142
1143 def musicxml_direction_to_indicator (direction):
1144     return { "above": 1, "upright": 1, "up": 1, "below": -1, "downright": -1, "down": -1, "inverted": -1 }.get (direction, 0)
1145
1146 def musicxml_fermata_to_lily_event (mxl_event):
1147     ev = musicexp.ArticulationEvent ()
1148     txt = mxl_event.get_text ()
1149     # The contents of the element defined the shape, possible are normal, angled and square
1150     ev.type = { "angled": "shortfermata", "square": "longfermata" }.get (txt, "fermata")
1151     if hasattr (mxl_event, 'type'):
1152       dir = musicxml_direction_to_indicator (mxl_event.type)
1153       if dir and options.convert_directions:
1154         ev.force_direction = dir
1155     return ev
1156
1157 def musicxml_arpeggiate_to_lily_event (mxl_event):
1158     ev = musicexp.ArpeggioEvent ()
1159     ev.direction = musicxml_direction_to_indicator (getattr (mxl_event, 'direction', None))
1160     return ev
1161
1162 def musicxml_nonarpeggiate_to_lily_event (mxl_event):
1163     ev = musicexp.ArpeggioEvent ()
1164     ev.non_arpeggiate = True
1165     ev.direction = musicxml_direction_to_indicator (getattr (mxl_event, 'direction', None))
1166     return ev
1167
1168 def musicxml_tremolo_to_lily_event (mxl_event):
1169     ev = musicexp.TremoloEvent ()
1170     txt = mxl_event.get_text ()
1171     if txt:
1172       ev.bars = txt
1173     else:
1174       ev.bars = "3"
1175     return ev
1176
1177 def musicxml_falloff_to_lily_event (mxl_event):
1178     ev = musicexp.BendEvent ()
1179     ev.alter = -4
1180     return ev
1181
1182 def musicxml_doit_to_lily_event (mxl_event):
1183     ev = musicexp.BendEvent ()
1184     ev.alter = 4
1185     return ev
1186
1187 def musicxml_bend_to_lily_event (mxl_event):
1188     ev = musicexp.BendEvent ()
1189     ev.alter = mxl_event.bend_alter ()
1190     return ev
1191
1192 def musicxml_caesura_to_lily_event (mxl_event):
1193     ev = musicexp.MarkupEvent ()
1194     # FIXME: default to straight or curved caesura?
1195     ev.contents = "\\musicglyph #\"scripts.caesura.straight\""
1196     ev.force_direction = 1
1197     return ev
1198
1199 def musicxml_fingering_event (mxl_event):
1200     ev = musicexp.ShortArticulationEvent ()
1201     ev.type = mxl_event.get_text ()
1202     return ev
1203
1204 def musicxml_string_event (mxl_event):
1205     ev = musicexp.NoDirectionArticulationEvent ()
1206     ev.type = mxl_event.get_text ()
1207     return ev
1208
1209 def musicxml_accidental_mark (mxl_event):
1210     ev = musicexp.MarkupEvent ()
1211     contents = { "sharp": "\\sharp",
1212       "natural": "\\natural",
1213       "flat": "\\flat",
1214       "double-sharp": "\\doublesharp",
1215       "sharp-sharp": "\\sharp\\sharp",
1216       "flat-flat": "\\flat\\flat",
1217       "flat-flat": "\\doubleflat",
1218       "natural-sharp": "\\natural\\sharp",
1219       "natural-flat": "\\natural\\flat",
1220       "quarter-flat": "\\semiflat",
1221       "quarter-sharp": "\\semisharp",
1222       "three-quarters-flat": "\\sesquiflat",
1223       "three-quarters-sharp": "\\sesquisharp",
1224     }.get (mxl_event.get_text ())
1225     if contents:
1226         ev.contents = contents
1227         return ev
1228     else:
1229         return None
1230
1231 # translate articulations, ornaments and other notations into ArticulationEvents
1232 # possible values:
1233 #   -) string  (ArticulationEvent with that name)
1234 #   -) function (function(mxl_event) needs to return a full ArticulationEvent-derived object
1235 #   -) (class, name)  (like string, only that a different class than ArticulationEvent is used)
1236 # TODO: Some translations are missing!
1237 articulations_dict = {
1238     "accent": (musicexp.ShortArticulationEvent, ">"), # or "accent"
1239     "accidental-mark": musicxml_accidental_mark,
1240     "bend": musicxml_bend_to_lily_event,
1241     "breath-mark": (musicexp.NoDirectionArticulationEvent, "breathe"),
1242     "caesura": musicxml_caesura_to_lily_event,
1243     #"delayed-turn": "?",
1244     "detached-legato": (musicexp.ShortArticulationEvent, "_"), # or "portato"
1245     "doit": musicxml_doit_to_lily_event,
1246     #"double-tongue": "?",
1247     "down-bow": "downbow",
1248     "falloff": musicxml_falloff_to_lily_event,
1249     "fingering": musicxml_fingering_event,
1250     #"fingernails": "?",
1251     #"fret": "?",
1252     #"hammer-on": "?",
1253     "harmonic": "flageolet",
1254     #"heel": "?",
1255     "inverted-mordent": "prall",
1256     "inverted-turn": "reverseturn",
1257     "mordent": "mordent",
1258     "open-string": "open",
1259     #"plop": "?",
1260     #"pluck": "?",
1261     #"pull-off": "?",
1262     #"schleifer": "?",
1263     #"scoop": "?",
1264     #"shake": "?",
1265     "snap-pizzicato": "snappizzicato",
1266     #"spiccato": "?",
1267     "staccatissimo": (musicexp.ShortArticulationEvent, "|"), # or "staccatissimo"
1268     "staccato": (musicexp.ShortArticulationEvent, "."), # or "staccato"
1269     "stopped": (musicexp.ShortArticulationEvent, "+"), # or "stopped"
1270     #"stress": "?",
1271     "string": musicxml_string_event,
1272     "strong-accent": (musicexp.ShortArticulationEvent, "^"), # or "marcato"
1273     #"tap": "?",
1274     "tenuto": (musicexp.ShortArticulationEvent, "-"), # or "tenuto"
1275     "thumb-position": "thumb",
1276     #"toe": "?",
1277     "turn": "turn",
1278     "tremolo": musicxml_tremolo_to_lily_event,
1279     "trill-mark": "trill",
1280     #"triple-tongue": "?",
1281     #"unstress": "?"
1282     "up-bow": "upbow",
1283     #"wavy-line": "?",
1284 }
1285 articulation_spanners = [ "wavy-line" ]
1286
1287 def musicxml_articulation_to_lily_event (mxl_event):
1288     # wavy-line elements are treated as trill spanners, not as articulation ornaments
1289     if mxl_event.get_name () in articulation_spanners:
1290         return musicxml_spanner_to_lily_event (mxl_event)
1291
1292     tmp_tp = articulations_dict.get (mxl_event.get_name ())
1293     if not tmp_tp:
1294         return
1295
1296     if isinstance (tmp_tp, str):
1297         ev = musicexp.ArticulationEvent ()
1298         ev.type = tmp_tp
1299     elif isinstance (tmp_tp, tuple):
1300         ev = tmp_tp[0] ()
1301         ev.type = tmp_tp[1]
1302     else:
1303         ev = tmp_tp (mxl_event)
1304
1305     # Some articulations use the type attribute, other the placement...
1306     dir = None
1307     if hasattr (mxl_event, 'type') and options.convert_directions:
1308         dir = musicxml_direction_to_indicator (mxl_event.type)
1309     if hasattr (mxl_event, 'placement') and options.convert_directions:
1310         dir = musicxml_direction_to_indicator (mxl_event.placement)
1311     if dir:
1312         ev.force_direction = dir
1313     return ev
1314
1315
1316
1317 def musicxml_dynamics_to_lily_event (dynentry):
1318     dynamics_available = (
1319         "ppppp", "pppp", "ppp", "pp", "p", "mp", "mf",
1320         "f", "ff", "fff", "ffff", "fp", "sf", "sff", "sp", "spp", "sfz", "rfz" )
1321     dynamicsname = dynentry.get_name ()
1322     if dynamicsname == "other-dynamics":
1323         dynamicsname = dynentry.get_text ()
1324     if not dynamicsname or dynamicsname=="#text":
1325         return
1326
1327     if not dynamicsname in dynamics_available:
1328         # Get rid of - in tag names (illegal in ly tags!)
1329         dynamicstext = dynamicsname
1330         dynamicsname = string.replace (dynamicsname, "-", "")
1331         additional_definitions[dynamicsname] = dynamicsname + \
1332               " = #(make-dynamic-script \"" + dynamicstext + "\")"
1333         needed_additional_definitions.append (dynamicsname)
1334     event = musicexp.DynamicsEvent ()
1335     event.type = dynamicsname
1336     return event
1337
1338 # Convert single-color two-byte strings to numbers 0.0 - 1.0
1339 def hexcolorval_to_nr (hex_val):
1340     try:
1341         v = int (hex_val, 16)
1342         if v == 255:
1343             v = 256
1344         return v / 256.
1345     except ValueError:
1346         return 0.
1347
1348 def hex_to_color (hex_val):
1349     res = re.match (r'#([0-9a-f][0-9a-f]|)([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])$', hex_val, re.IGNORECASE)
1350     if res:
1351         return map (lambda x: hexcolorval_to_nr (x), res.group (2,3,4))
1352     else:
1353         return None
1354
1355 def musicxml_words_to_lily_event (words):
1356     event = musicexp.TextEvent ()
1357     text = words.get_text ()
1358     text = re.sub ('^ *\n? *', '', text)
1359     text = re.sub (' *\n? *$', '', text)
1360     event.text = text
1361
1362     if hasattr (words, 'default-y') and options.convert_directions:
1363         offset = getattr (words, 'default-y')
1364         try:
1365             off = string.atoi (offset)
1366             if off > 0:
1367                 event.force_direction = 1
1368             else:
1369                 event.force_direction = -1
1370         except ValueError:
1371             event.force_direction = 0
1372
1373     if hasattr (words, 'font-weight'):
1374         font_weight = { "normal": '', "bold": '\\bold' }.get (getattr (words, 'font-weight'), '')
1375         if font_weight:
1376             event.markup += font_weight
1377
1378     if hasattr (words, 'font-size'):
1379         size = getattr (words, 'font-size')
1380         font_size = {
1381             "xx-small": '\\teeny',
1382             "x-small": '\\tiny',
1383             "small": '\\small',
1384             "medium": '',
1385             "large": '\\large',
1386             "x-large": '\\huge',
1387             "xx-large": '\\larger\\huge'
1388         }.get (size, '')
1389         if font_size:
1390             event.markup += font_size
1391
1392     if hasattr (words, 'color'):
1393         color = getattr (words, 'color')
1394         rgb = hex_to_color (color)
1395         if rgb:
1396             event.markup += "\\with-color #(rgb-color %s %s %s)" % (rgb[0], rgb[1], rgb[2])
1397
1398     if hasattr (words, 'font-style'):
1399         font_style = { "italic": '\\italic' }.get (getattr (words, 'font-style'), '')
1400         if font_style:
1401             event.markup += font_style
1402
1403     # TODO: How should I best convert the font-family attribute?
1404
1405     # TODO: How can I represent the underline, overline and line-through
1406     #       attributes in LilyPond? Values of these attributes indicate
1407     #       the number of lines
1408
1409     return event
1410
1411
1412 # convert accordion-registration to lilypond.
1413 # Since lilypond does not have any built-in commands, we need to create
1414 # the markup commands manually and define our own variables.
1415 # Idea was taken from: http://lsr.dsi.unimi.it/LSR/Item?id=194
1416 def musicxml_accordion_to_markup (mxl_event):
1417     commandname = "accReg"
1418     command = ""
1419
1420     high = mxl_event.get_maybe_exist_named_child ('accordion-high')
1421     if high:
1422         commandname += "H"
1423         command += """\\combine
1424           \\raise #2.5 \\musicglyph #\"accordion.dot\"
1425           """
1426     middle = mxl_event.get_maybe_exist_named_child ('accordion-middle')
1427     if middle:
1428         # By default, use one dot (when no or invalid content is given). The
1429         # MusicXML spec is quiet about this case...
1430         txt = 1
1431         try:
1432           txt = string.atoi (middle.get_text ())
1433         except ValueError:
1434             pass
1435         if txt == 3:
1436             commandname += "MMM"
1437             command += """\\combine
1438           \\raise #1.5 \\musicglyph #\"accordion.dot\"
1439           \\combine
1440           \\raise #1.5 \\translate #(cons 1 0) \\musicglyph #\"accordion.dot\"
1441           \\combine
1442           \\raise #1.5 \\translate #(cons -1 0) \\musicglyph #\"accordion.dot\"
1443           """
1444         elif txt == 2:
1445             commandname += "MM"
1446             command += """\\combine
1447           \\raise #1.5 \\translate #(cons 0.5 0) \\musicglyph #\"accordion.dot\"
1448           \\combine
1449           \\raise #1.5 \\translate #(cons -0.5 0) \\musicglyph #\"accordion.dot\"
1450           """
1451         elif not txt <= 0:
1452             commandname += "M"
1453             command += """\\combine
1454           \\raise #1.5 \\musicglyph #\"accordion.dot\"
1455           """
1456     low = mxl_event.get_maybe_exist_named_child ('accordion-low')
1457     if low:
1458         commandname += "L"
1459         command += """\\combine
1460           \\raise #0.5 \musicglyph #\"accordion.dot\"
1461           """
1462
1463     command += "\musicglyph #\"accordion.discant\""
1464     command = "\\markup { \\normalsize %s }" % command
1465     # Define the newly built command \accReg[H][MMM][L]
1466     additional_definitions[commandname] = "%s = %s" % (commandname, command)
1467     needed_additional_definitions.append (commandname)
1468     return "\\%s" % commandname
1469
1470 def musicxml_accordion_to_ly (mxl_event):
1471     txt = musicxml_accordion_to_markup (mxl_event)
1472     if txt:
1473         ev = musicexp.MarkEvent (txt)
1474         return ev
1475     return
1476
1477
1478 def musicxml_rehearsal_to_ly_mark (mxl_event):
1479     text = mxl_event.get_text ()
1480     if not text:
1481         return
1482     # default is boxed rehearsal marks!
1483     encl = "box"
1484     if hasattr (mxl_event, 'enclosure'):
1485         encl = {"none": None, "square": "box", "circle": "circle" }.get (mxl_event.enclosure, None)
1486     if encl:
1487         text = "\\%s { %s }" % (encl, text)
1488     ev = musicexp.MarkEvent ("\\markup { %s }" % text)
1489     return ev
1490
1491 def musicxml_harp_pedals_to_ly (mxl_event):
1492     count = 0
1493     result = "\\harp-pedal #\""
1494     for t in mxl_event.get_named_children ('pedal-tuning'):
1495       alter = t.get_named_child ('pedal-alter')
1496       if alter:
1497         val = int (alter.get_text ().strip ())
1498         result += {1: "v", 0: "-", -1: "^"}.get (val, "")
1499       count += 1
1500       if count == 3:
1501         result += "|"
1502     ev = musicexp.MarkupEvent ()
1503     ev.contents = result + "\""
1504     return ev
1505
1506 def musicxml_eyeglasses_to_ly (mxl_event):
1507     needed_additional_definitions.append ("eyeglasses")
1508     return musicexp.MarkEvent ("\\markup { \\eyeglasses }")
1509
1510 def next_non_hash_index (lst, pos):
1511     pos += 1
1512     while pos < len (lst) and isinstance (lst[pos], musicxml.Hash_text):
1513         pos += 1
1514     return pos
1515
1516 def musicxml_metronome_to_ly (mxl_event):
1517     children = mxl_event.get_all_children ()
1518     if not children:
1519         return
1520
1521     index = -1
1522     index = next_non_hash_index (children, index)
1523     if isinstance (children[index], musicxml.BeatUnit):
1524         # first form of metronome-mark, using unit and beats/min or other unit
1525         ev = musicexp.TempoMark ()
1526         if hasattr (mxl_event, 'parentheses'):
1527             ev.set_parentheses (mxl_event.parentheses == "yes")
1528
1529         d = musicexp.Duration ()
1530         d.duration_log = musicxml.musicxml_duration_to_log (children[index].get_text ())
1531         index = next_non_hash_index (children, index)
1532         if isinstance (children[index], musicxml.BeatUnitDot):
1533             d.dots = 1
1534             index = next_non_hash_index (children, index)
1535         ev.set_base_duration (d)
1536         if isinstance (children[index], musicxml.BeatUnit):
1537             # Form "note = newnote"
1538             newd = musicexp.Duration ()
1539             newd.duration_log = musicxml.musicxml_duration_to_log (children[index].get_text ())
1540             index = next_non_hash_index (children, index)
1541             if isinstance (children[index], musicxml.BeatUnitDot):
1542                 newd.dots = 1
1543                 index = next_non_hash_index (children, index)
1544             ev.set_new_duration (newd)
1545         elif isinstance (children[index], musicxml.PerMinute):
1546             # Form "note = bpm"
1547             try:
1548                 beats = int (children[index].get_text ())
1549                 ev.set_beats_per_minute (beats)
1550             except ValueError:
1551                 pass
1552         else:
1553             error_message (_ ("Unknown metronome mark, ignoring"))
1554             return
1555         return ev
1556     else:
1557         #TODO: Implement the other (more complex) way for tempo marks!
1558         error_message (_ ("Metronome marks with complex relations (<metronome-note> in MusicXML) are not yet implemented."))
1559         return
1560
1561 # translate directions into Events, possible values:
1562 #   -) string  (MarkEvent with that command)
1563 #   -) function (function(mxl_event) needs to return a full Event-derived object
1564 #   -) (class, name)  (like string, only that a different class than MarkEvent is used)
1565 directions_dict = {
1566     'accordion-registration' : musicxml_accordion_to_ly,
1567     'coda' : (musicexp.MusicGlyphMarkEvent, "coda"),
1568 #     'damp' : ???
1569 #     'damp-all' : ???
1570     'eyeglasses': musicxml_eyeglasses_to_ly,
1571     'harp-pedals' : musicxml_harp_pedals_to_ly,
1572 #     'image' : ???
1573     'metronome' : musicxml_metronome_to_ly,
1574     'rehearsal' : musicxml_rehearsal_to_ly_mark,
1575 #     'scordatura' : ???
1576     'segno' : (musicexp.MusicGlyphMarkEvent, "segno"),
1577     'words' : musicxml_words_to_lily_event,
1578 }
1579 directions_spanners = [ 'octave-shift', 'pedal', 'wedge', 'dashes', 'bracket' ]
1580
1581 def musicxml_direction_to_lily (n):
1582     # TODO: Handle the <staff> element!
1583     res = []
1584     # placement applies to all children!
1585     dir = None
1586     if hasattr (n, 'placement') and options.convert_directions:
1587         dir = musicxml_direction_to_indicator (n.placement)
1588     dirtype_children = []
1589     # TODO: The direction-type is used for grouping (e.g. dynamics with text),
1590     #       so we can't simply flatten them out!
1591     for dt in n.get_typed_children (musicxml.DirType):
1592         dirtype_children += dt.get_all_children ()
1593
1594     for entry in dirtype_children:
1595         # backets, dashes, octave shifts. pedal marks, hairpins etc. are spanners:
1596         if entry.get_name() in directions_spanners:
1597             event = musicxml_spanner_to_lily_event (entry)
1598             if event:
1599                 res.append (event)
1600             continue
1601
1602         # now treat all the "simple" ones, that can be translated using the dict
1603         ev = None
1604         tmp_tp = directions_dict.get (entry.get_name (), None)
1605         if isinstance (tmp_tp, str): # string means MarkEvent
1606             ev = musicexp.MarkEvent (tmp_tp)
1607         elif isinstance (tmp_tp, tuple): # tuple means (EventClass, "text")
1608             ev = tmp_tp[0] (tmp_tp[1])
1609         elif tmp_tp:
1610             ev = tmp_tp (entry)
1611         if ev:
1612             # TODO: set the correct direction! Unfortunately, \mark in ly does
1613             #       not seem to support directions!
1614             ev.force_direction = dir
1615             res.append (ev)
1616             continue
1617
1618         if entry.get_name () == "dynamics":
1619             for dynentry in entry.get_all_children ():
1620                 ev = musicxml_dynamics_to_lily_event (dynentry)
1621                 if ev:
1622                     res.append (ev)
1623
1624     return res
1625
1626 def musicxml_frame_to_lily_event (frame):
1627     ev = musicexp.FretEvent ()
1628     ev.strings = frame.get_strings ()
1629     ev.frets = frame.get_frets ()
1630     #offset = frame.get_first_fret () - 1
1631     barre = []
1632     for fn in frame.get_named_children ('frame-note'):
1633         fret = fn.get_fret ()
1634         if fret <= 0:
1635             fret = "o"
1636         el = [ fn.get_string (), fret ]
1637         fingering = fn.get_fingering ()
1638         if fingering >= 0:
1639             el.append (fingering)
1640         ev.elements.append (el)
1641         b = fn.get_barre ()
1642         if b == 'start':
1643             barre[0] = el[0] # start string
1644             barre[2] = el[1] # fret
1645         elif b == 'stop':
1646             barre[1] = el[0] # end string
1647     if barre:
1648         ev.barre = barre
1649     return ev
1650
1651 def musicxml_harmony_to_lily (n):
1652     res = []
1653     for f in n.get_named_children ('frame'):
1654         ev = musicxml_frame_to_lily_event (f)
1655         if ev:
1656             res.append (ev)
1657     return res
1658
1659
1660 notehead_styles_dict = {
1661     'slash': '\'slash',
1662     'triangle': '\'triangle',
1663     'diamond': '\'diamond',
1664     'square': '\'la', # TODO: Proper squared note head
1665     'cross': None, # TODO: + shaped note head
1666     'x': '\'cross',
1667     'circle-x': '\'xcircle',
1668     'inverted triangle': None, # TODO: Implement
1669     'arrow down': None, # TODO: Implement
1670     'arrow up': None, # TODO: Implement
1671     'slashed': None, # TODO: Implement
1672     'back slashed': None, # TODO: Implement
1673     'normal': None,
1674     'cluster': None, # TODO: Implement
1675     'none': '#f',
1676     'do': '\'do',
1677     're': '\'re',
1678     'mi': '\'mi',
1679     'fa': '\'fa',
1680     'so': None,
1681     'la': '\'la',
1682     'ti': '\'ti',
1683     }
1684
1685 def musicxml_notehead_to_lily (nh):
1686     styles = []
1687
1688     # Notehead style
1689     style = notehead_styles_dict.get (nh.get_text ().strip (), None)
1690     style_elm = musicexp.NotestyleEvent ()
1691     if style:
1692         style_elm.style = style
1693     if hasattr (nh, 'filled'):
1694         style_elm.filled = (getattr (nh, 'filled') == "yes")
1695     if style_elm.style or (style_elm.filled != None):
1696         styles.append (style_elm)
1697
1698     # parentheses
1699     if hasattr (nh, 'parentheses') and (nh.parentheses == "yes"):
1700         styles.append (musicexp.ParenthesizeEvent ())
1701
1702     return styles
1703
1704 def musicxml_chordpitch_to_lily (mxl_cpitch):
1705     r = musicexp.ChordPitch ()
1706     r.alteration = mxl_cpitch.get_alteration ()
1707     r.step = musicxml_step_to_lily (mxl_cpitch.get_step ())
1708     return r
1709
1710 chordkind_dict = {
1711     'major': '5',
1712     'minor': 'm5',
1713     'augmented': 'aug5',
1714     'diminished': 'dim5',
1715         # Sevenths:
1716     'dominant': '7',
1717     'dominant-seventh': '7',
1718     'major-seventh': 'maj7',
1719     'minor-seventh': 'm7',
1720     'diminished-seventh': 'dim7',
1721     'augmented-seventh': 'aug7',
1722     'half-diminished': 'dim5m7',
1723     'major-minor': 'maj7m5',
1724         # Sixths:
1725     'major-sixth': '6',
1726     'minor-sixth': 'm6',
1727         # Ninths:
1728     'dominant-ninth': '9',
1729     'major-ninth': 'maj9',
1730     'minor-ninth': 'm9',
1731         # 11ths (usually as the basis for alteration):
1732     'dominant-11th': '11',
1733     'major-11th': 'maj11',
1734     'minor-11th': 'm11',
1735         # 13ths (usually as the basis for alteration):
1736     'dominant-13th': '13.11',
1737     'major-13th': 'maj13.11',
1738     'minor-13th': 'm13',
1739         # Suspended:
1740     'suspended-second': 'sus2',
1741     'suspended-fourth': 'sus4',
1742         # Functional sixths:
1743     # TODO
1744     #'Neapolitan': '???',
1745     #'Italian': '???',
1746     #'French': '???',
1747     #'German': '???',
1748         # Other:
1749     #'pedal': '???',(pedal-point bass)
1750     'power': '5^3',
1751     #'Tristan': '???',
1752     'other': '1',
1753     'none': None,
1754 }
1755
1756 def musicxml_chordkind_to_lily (kind):
1757     res = chordkind_dict.get (kind, None)
1758     # Check for None, since a major chord is converted to ''
1759     if res == None:
1760         error_message (_ ("Unable to convert chord type %s to lilypond.") % kind)
1761     return res
1762
1763 def musicxml_harmony_to_lily_chordname (n):
1764     res = []
1765     root = n.get_maybe_exist_named_child ('root')
1766     if root:
1767         ev = musicexp.ChordNameEvent ()
1768         ev.root = musicxml_chordpitch_to_lily (root)
1769         kind = n.get_maybe_exist_named_child ('kind')
1770         if kind:
1771             ev.kind = musicxml_chordkind_to_lily (kind.get_text ())
1772             if not ev.kind:
1773                 return res
1774         bass = n.get_maybe_exist_named_child ('bass')
1775         if bass:
1776             ev.bass = musicxml_chordpitch_to_lily (bass)
1777         inversion = n.get_maybe_exist_named_child ('inversion')
1778         if inversion:
1779             # TODO: LilyPond does not support inversions, does it?
1780
1781             # Mail from Carl Sorensen on lilypond-devel, June 11, 2008:
1782             # 4. LilyPond supports the first inversion in the form of added
1783             # bass notes.  So the first inversion of C major would be c:/g.
1784             # To get the second inversion of C major, you would need to do
1785             # e:6-3-^5 or e:m6-^5.  However, both of these techniques
1786             # require you to know the chord and calculate either the fifth
1787             # pitch (for the first inversion) or the third pitch (for the
1788             # second inversion) so they may not be helpful for musicxml2ly.
1789             inversion_count = string.atoi (inversion.get_text ())
1790             if inversion_count == 1:
1791               # TODO: Calculate the bass note for the inversion...
1792               pass
1793             pass
1794         for deg in n.get_named_children ('degree'):
1795             d = musicexp.ChordModification ()
1796             d.type = deg.get_type ()
1797             d.step = deg.get_value ()
1798             d.alteration = deg.get_alter ()
1799             ev.add_modification (d)
1800         #TODO: convert the user-symbols attribute:
1801             #major: a triangle, like Unicode 25B3
1802             #minor: -, like Unicode 002D
1803             #augmented: +, like Unicode 002B
1804             #diminished: (degree), like Unicode 00B0
1805             #half-diminished: (o with slash), like Unicode 00F8
1806         if ev and ev.root:
1807             res.append (ev)
1808
1809     return res
1810
1811 def musicxml_figured_bass_note_to_lily (n):
1812     res = musicexp.FiguredBassNote ()
1813     suffix_dict = { 'sharp' : "+",
1814                     'flat' : "-",
1815                     'natural' : "!",
1816                     'double-sharp' : "++",
1817                     'flat-flat' : "--",
1818                     'sharp-sharp' : "++",
1819                     'slash' : "/" }
1820     prefix = n.get_maybe_exist_named_child ('prefix')
1821     if prefix:
1822         res.set_prefix (suffix_dict.get (prefix.get_text (), ""))
1823     fnumber = n.get_maybe_exist_named_child ('figure-number')
1824     if fnumber:
1825         res.set_number (fnumber.get_text ())
1826     suffix = n.get_maybe_exist_named_child ('suffix')
1827     if suffix:
1828         res.set_suffix (suffix_dict.get (suffix.get_text (), ""))
1829     if n.get_maybe_exist_named_child ('extend'):
1830         # TODO: Implement extender lines (unfortunately, in lilypond you have
1831         #       to use \set useBassFigureExtenders = ##t, which turns them on
1832         #       globally, while MusicXML has a property for each note...
1833         #       I'm not sure there is a proper way to implement this cleanly
1834         #n.extend
1835         pass
1836     return res
1837
1838
1839
1840 def musicxml_figured_bass_to_lily (n):
1841     if not isinstance (n, musicxml.FiguredBass):
1842         return
1843     res = musicexp.FiguredBassEvent ()
1844     for i in n.get_named_children ('figure'):
1845         note = musicxml_figured_bass_note_to_lily (i)
1846         if note:
1847             res.append (note)
1848     dur = n.get_maybe_exist_named_child ('duration')
1849     if dur:
1850         # apply the duration to res
1851         length = Rational(int(dur.get_text()), n._divisions)*Rational(1,4)
1852         res.set_real_duration (length)
1853         duration = rational_to_lily_duration (length)
1854         if duration:
1855             res.set_duration (duration)
1856     if hasattr (n, 'parentheses') and n.parentheses == "yes":
1857         res.set_parentheses (True)
1858     return res
1859
1860 instrument_drumtype_dict = {
1861     'Acoustic Snare Drum': 'acousticsnare',
1862     'Side Stick': 'sidestick',
1863     'Open Triangle': 'opentriangle',
1864     'Mute Triangle': 'mutetriangle',
1865     'Tambourine': 'tambourine',
1866     'Bass Drum': 'bassdrum',
1867 }
1868
1869 def musicxml_note_to_lily_main_event (n):
1870     pitch  = None
1871     duration = None
1872     event = None
1873
1874     mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
1875     if mxl_pitch:
1876         pitch = musicxml_pitch_to_lily (mxl_pitch)
1877         event = musicexp.NoteEvent ()
1878         event.pitch = pitch
1879
1880         acc = n.get_maybe_exist_named_child ('accidental')
1881         if acc:
1882             # let's not force accs everywhere.
1883             event.cautionary = acc.cautionary
1884             # TODO: Handle editorial accidentals
1885             # TODO: Handle the level-display setting for displaying brackets/parentheses
1886
1887     elif n.get_maybe_exist_typed_child (musicxml.Unpitched):
1888         # Unpitched elements have display-step and can also have
1889         # display-octave.
1890         unpitched = n.get_maybe_exist_typed_child (musicxml.Unpitched)
1891         event = musicexp.NoteEvent ()
1892         event.pitch = musicxml_unpitched_to_lily (unpitched)
1893
1894     elif n.get_maybe_exist_typed_child (musicxml.Rest):
1895         # rests can have display-octave and display-step, which are
1896         # treated like an ordinary note pitch
1897         rest = n.get_maybe_exist_typed_child (musicxml.Rest)
1898         event = musicexp.RestEvent ()
1899         if options.convert_rest_positions:
1900             pitch = musicxml_restdisplay_to_lily (rest)
1901             event.pitch = pitch
1902
1903     elif n.instrument_name:
1904         event = musicexp.NoteEvent ()
1905         drum_type = instrument_drumtype_dict.get (n.instrument_name)
1906         if drum_type:
1907             event.drum_type = drum_type
1908         else:
1909             n.message (_ ("drum %s type unknown, please add to instrument_drumtype_dict") % n.instrument_name)
1910             event.drum_type = 'acousticsnare'
1911
1912     else:
1913         n.message (_ ("cannot find suitable event"))
1914
1915     if event:
1916         event.duration = musicxml_duration_to_lily (n)
1917
1918     noteheads = n.get_named_children ('notehead')
1919     for nh in noteheads:
1920         styles = musicxml_notehead_to_lily (nh)
1921         for s in styles:
1922             event.add_associated_event (s)
1923
1924     return event
1925
1926 def musicxml_lyrics_to_text (lyrics):
1927     # TODO: Implement text styles for lyrics syllables
1928     continued = False
1929     extended = False
1930     text = ''
1931     for e in lyrics.get_all_children ():
1932         if isinstance (e, musicxml.Syllabic):
1933             continued = e.continued ()
1934         elif isinstance (e, musicxml.Text):
1935             # We need to convert soft hyphens to -, otherwise the ascii codec as well
1936             # as lilypond will barf on that character
1937             text += string.replace( e.get_text(), u'\xad', '-' )
1938         elif isinstance (e, musicxml.Elision):
1939             if text:
1940                 text += " "
1941             continued = False
1942             extended = False
1943         elif isinstance (e, musicxml.Extend):
1944             if text:
1945                 text += " "
1946             extended = True
1947
1948     if text == "-" and continued:
1949         return "--"
1950     elif text == "_" and extended:
1951         return "__"
1952     elif continued and text:
1953         return musicxml.escape_ly_output_string (text) + " --"
1954     elif continued:
1955         return "--"
1956     elif extended and text:
1957         return musicxml.escape_ly_output_string (text) + " __"
1958     elif extended:
1959         return "__"
1960     elif text:
1961         return musicxml.escape_ly_output_string (text)
1962     else:
1963         return ""
1964
1965 ## TODO
1966 class NegativeSkip:
1967     def __init__ (self, here, dest):
1968         self.here = here
1969         self.dest = dest
1970
1971 class LilyPondVoiceBuilder:
1972     def __init__ (self):
1973         self.elements = []
1974         self.pending_dynamics = []
1975         self.end_moment = Rational (0)
1976         self.begin_moment = Rational (0)
1977         self.pending_multibar = Rational (0)
1978         self.ignore_skips = False
1979         self.has_relevant_elements = False
1980         self.measure_length = Rational (4, 4)
1981
1982     def _insert_multibar (self):
1983         layout_information.set_context_item ('Score', 'skipBars = ##t')
1984         r = musicexp.MultiMeasureRest ()
1985         lenfrac = self.measure_length
1986         r.duration = rational_to_lily_duration (lenfrac)
1987         r.duration.factor *= self.pending_multibar / lenfrac
1988         self.elements.append (r)
1989         self.begin_moment = self.end_moment
1990         self.end_moment = self.begin_moment + self.pending_multibar
1991         self.pending_multibar = Rational (0)
1992
1993     def set_measure_length (self, mlen):
1994         if (mlen != self.measure_length) and self.pending_multibar:
1995             self._insert_multibar ()
1996         self.measure_length = mlen
1997
1998     def add_multibar_rest (self, duration):
1999         self.pending_multibar += duration
2000
2001     def set_duration (self, duration):
2002         self.end_moment = self.begin_moment + duration
2003     def current_duration (self):
2004         return self.end_moment - self.begin_moment
2005
2006     def add_music (self, music, duration, relevant = True):
2007         assert isinstance (music, musicexp.Music)
2008         if self.pending_multibar > Rational (0):
2009             self._insert_multibar ()
2010
2011         self.has_relevant_elements = self.has_relevant_elements or relevant
2012         self.elements.append (music)
2013         self.begin_moment = self.end_moment
2014         self.set_duration (duration)
2015
2016         # Insert all pending dynamics right after the note/rest:
2017         if isinstance (music, musicexp.ChordEvent) and self.pending_dynamics:
2018             for d in self.pending_dynamics:
2019                 music.append (d)
2020             self.pending_dynamics = []
2021
2022     # Insert some music command that does not affect the position in the measure
2023     def add_command (self, command, relevant = True):
2024         assert isinstance (command, musicexp.Music)
2025         if self.pending_multibar > Rational (0):
2026             self._insert_multibar ()
2027         self.has_relevant_elements = self.has_relevant_elements or relevant
2028         self.elements.append (command)
2029     def add_barline (self, barline, relevant = False):
2030         # Insert only if we don't have a barline already
2031         # TODO: Implement proper merging of default barline and custom bar line
2032         has_relevant = self.has_relevant_elements
2033         if (not (self.elements) or
2034             not (isinstance (self.elements[-1], musicexp.BarLine)) or
2035             (self.pending_multibar > Rational (0))):
2036             self.add_music (barline, Rational (0))
2037         self.has_relevant_elements = has_relevant or relevant
2038     def add_partial (self, command):
2039         self.ignore_skips = True
2040         # insert the partial, but restore relevant_elements (partial is not relevant)
2041         relevant = self.has_relevant_elements
2042         self.add_command (command)
2043         self.has_relevant_elements = relevant
2044
2045     def add_dynamics (self, dynamic):
2046         # store the dynamic item(s) until we encounter the next note/rest:
2047         self.pending_dynamics.append (dynamic)
2048
2049     def add_bar_check (self, number):
2050         # re/store has_relevant_elements, so that a barline alone does not
2051         # trigger output for figured bass, chord names
2052         b = musicexp.BarLine ()
2053         b.bar_number = number
2054         self.add_barline (b)
2055
2056     def jumpto (self, moment):
2057         current_end = self.end_moment + self.pending_multibar
2058         diff = moment - current_end
2059
2060         if diff < Rational (0):
2061             error_message (_ ('Negative skip %s (from position %s to %s)') %
2062                              (diff, current_end, moment))
2063             diff = Rational (0)
2064
2065         if diff > Rational (0) and not (self.ignore_skips and moment == 0):
2066             skip = musicexp.SkipEvent()
2067             duration_factor = 1
2068             duration_log = {1: 0, 2: 1, 4:2, 8:3, 16:4, 32:5, 64:6, 128:7, 256:8, 512:9}.get (diff.denominator (), -1)
2069             duration_dots = 0
2070             # TODO: Use the time signature for skips, too. Problem: The skip
2071             #       might not start at a measure boundary!
2072             if duration_log > 0: # denominator is a power of 2...
2073                 if diff.numerator () == 3:
2074                     duration_log -= 1
2075                     duration_dots = 1
2076                 else:
2077                     duration_factor = Rational (diff.numerator ())
2078             else:
2079                 # for skips of a whole or more, simply use s1*factor
2080                 duration_log = 0
2081                 duration_factor = diff
2082             skip.duration.duration_log = duration_log
2083             skip.duration.factor = duration_factor
2084             skip.duration.dots = duration_dots
2085
2086             evc = musicexp.ChordEvent ()
2087             evc.elements.append (skip)
2088             self.add_music (evc, diff, False)
2089
2090         if diff > Rational (0) and moment == 0:
2091             self.ignore_skips = False
2092
2093     def last_event_chord (self, starting_at):
2094
2095         value = None
2096
2097         # if the position matches, find the last ChordEvent, do not cross a bar line!
2098         at = len( self.elements ) - 1
2099         while (at >= 0 and
2100                not isinstance (self.elements[at], musicexp.ChordEvent) and
2101                not isinstance (self.elements[at], musicexp.BarLine)):
2102             at -= 1
2103
2104         if (self.elements
2105             and at >= 0
2106             and isinstance (self.elements[at], musicexp.ChordEvent)
2107             and self.begin_moment == starting_at):
2108             value = self.elements[at]
2109         else:
2110             self.jumpto (starting_at)
2111             value = None
2112         return value
2113
2114     def correct_negative_skip (self, goto):
2115         self.end_moment = goto
2116         self.begin_moment = goto
2117         evc = musicexp.ChordEvent ()
2118         self.elements.append (evc)
2119
2120
2121 class VoiceData:
2122     def __init__ (self):
2123         self.voicename = None
2124         self.voicedata = None
2125         self.ly_voice = None
2126         self.figured_bass = None
2127         self.chordnames = None
2128         self.lyrics_dict = {}
2129         self.lyrics_order = []
2130
2131 def measure_length_from_attributes (attr, current_measure_length):
2132     len = attr.get_measure_length ()
2133     if not len:
2134         len = current_measure_length
2135     return len
2136
2137 def musicxml_voice_to_lily_voice (voice):
2138     tuplet_events = []
2139     modes_found = {}
2140     lyrics = {}
2141     return_value = VoiceData ()
2142     return_value.voicedata = voice
2143
2144     # First pitch needed for relative mode (if selected in command-line options)
2145     first_pitch = None
2146
2147     # Needed for melismata detection (ignore lyrics on those notes!):
2148     inside_slur = False
2149     is_tied = False
2150     is_chord = False
2151     is_beamed = False
2152     ignore_lyrics = False
2153
2154     current_staff = None
2155
2156     pending_figured_bass = []
2157     pending_chordnames = []
2158
2159     # Make sure that the keys in the dict don't get reordered, since
2160     # we need the correct ordering of the lyrics stanzas! By default,
2161     # a dict will reorder its keys
2162     return_value.lyrics_order = voice.get_lyrics_numbers ()
2163     for k in return_value.lyrics_order:
2164         lyrics[k] = []
2165
2166     voice_builder = LilyPondVoiceBuilder ()
2167     figured_bass_builder = LilyPondVoiceBuilder ()
2168     chordnames_builder = LilyPondVoiceBuilder ()
2169     current_measure_length = Rational (4, 4)
2170     voice_builder.set_measure_length (current_measure_length)
2171
2172     for n in voice._elements:
2173         tie_started = False
2174         if n.get_name () == 'forward':
2175             continue
2176         staff = n.get_maybe_exist_named_child ('staff')
2177         if staff:
2178             staff = staff.get_text ()
2179             if current_staff and staff <> current_staff and not n.get_maybe_exist_named_child ('chord'):
2180                 voice_builder.add_command (musicexp.StaffChange (staff))
2181             current_staff = staff
2182
2183         if isinstance (n, musicxml.Partial) and n.partial > 0:
2184             a = musicxml_partial_to_lily (n.partial)
2185             if a:
2186                 voice_builder.add_partial (a)
2187                 figured_bass_builder.add_partial (a)
2188                 chordnames_builder.add_partial (a)
2189             continue
2190
2191         is_chord = n.get_maybe_exist_named_child ('chord')
2192         is_after_grace = (isinstance (n, musicxml.Note) and n.is_after_grace ());
2193         if not is_chord and not is_after_grace:
2194             try:
2195                 voice_builder.jumpto (n._when)
2196                 figured_bass_builder.jumpto (n._when)
2197                 chordnames_builder.jumpto (n._when)
2198             except NegativeSkip, neg:
2199                 voice_builder.correct_negative_skip (n._when)
2200                 figured_bass_builder.correct_negative_skip (n._when)
2201                 chordnames_builder.correct_negative_skip (n._when)
2202                 n.message (_ ("Negative skip found: from %s to %s, difference is %s") % (neg.here, neg.dest, neg.dest - neg.here))
2203
2204         if isinstance (n, musicxml.Barline):
2205             barlines = musicxml_barline_to_lily (n)
2206             for a in barlines:
2207                 if isinstance (a, musicexp.BarLine):
2208                     voice_builder.add_barline (a)
2209                     figured_bass_builder.add_barline (a, False)
2210                     chordnames_builder.add_barline (a, False)
2211                 elif isinstance (a, RepeatMarker) or isinstance (a, EndingMarker):
2212                     voice_builder.add_command (a)
2213                     figured_bass_builder.add_barline (a, False)
2214                     chordnames_builder.add_barline (a, False)
2215             continue
2216
2217
2218         if isinstance (n, musicxml.Print):
2219             for a in musicxml_print_to_lily (n):
2220                 voice_builder.add_command (a, False)
2221             continue
2222
2223         # Continue any multimeasure-rests before trying to add bar checks!
2224         # Don't handle new MM rests yet, because for them we want bar checks!
2225         rest = n.get_maybe_exist_typed_child (musicxml.Rest)
2226         if (rest and rest.is_whole_measure ()
2227                  and voice_builder.pending_multibar > Rational (0)):
2228             voice_builder.add_multibar_rest (n._duration)
2229             continue
2230
2231
2232         # print a bar check at the beginning of each measure!
2233         if n.is_first () and n._measure_position == Rational (0) and n != voice._elements[0]:
2234             try:
2235                 num = int (n.get_parent ().number)
2236             except ValueError:
2237                 num = 0
2238             if num > 0:
2239                 voice_builder.add_bar_check (num)
2240                 figured_bass_builder.add_bar_check (num)
2241                 chordnames_builder.add_bar_check (num)
2242
2243         # Start any new multimeasure rests
2244         if (rest and rest.is_whole_measure ()):
2245             voice_builder.add_multibar_rest (n._duration)
2246             continue
2247
2248
2249         if isinstance (n, musicxml.Direction):
2250             for a in musicxml_direction_to_lily (n):
2251                 if a.wait_for_note ():
2252                     voice_builder.add_dynamics (a)
2253                 else:
2254                     voice_builder.add_command (a)
2255             continue
2256
2257         if isinstance (n, musicxml.Harmony):
2258             for a in musicxml_harmony_to_lily (n):
2259                 if a.wait_for_note ():
2260                     voice_builder.add_dynamics (a)
2261                 else:
2262                     voice_builder.add_command (a)
2263             for a in musicxml_harmony_to_lily_chordname (n):
2264                 pending_chordnames.append (a)
2265             continue
2266
2267         if isinstance (n, musicxml.FiguredBass):
2268             a = musicxml_figured_bass_to_lily (n)
2269             if a:
2270                 pending_figured_bass.append (a)
2271             continue
2272
2273         if isinstance (n, musicxml.Attributes):
2274             for a in musicxml_attributes_to_lily (n):
2275                 voice_builder.add_command (a)
2276             measure_length = measure_length_from_attributes (n, current_measure_length)
2277             if current_measure_length != measure_length:
2278                 current_measure_length = measure_length
2279                 voice_builder.set_measure_length (current_measure_length)
2280             continue
2281
2282         if not n.__class__.__name__ == 'Note':
2283             n.message (_ ('unexpected %s; expected %s or %s or %s') % (n, 'Note', 'Attributes', 'Barline'))
2284             continue
2285
2286         main_event = musicxml_note_to_lily_main_event (n)
2287         if main_event and not first_pitch:
2288             first_pitch = main_event.pitch
2289         # ignore lyrics for notes inside a slur, tie, chord or beam
2290         ignore_lyrics = inside_slur or is_tied or is_chord or is_beamed
2291
2292         if main_event and hasattr (main_event, 'drum_type') and main_event.drum_type:
2293             modes_found['drummode'] = True
2294
2295         ev_chord = voice_builder.last_event_chord (n._when)
2296         if not ev_chord:
2297             ev_chord = musicexp.ChordEvent()
2298             voice_builder.add_music (ev_chord, n._duration)
2299
2300         # For grace notes:
2301         grace = n.get_maybe_exist_typed_child (musicxml.Grace)
2302         if n.is_grace ():
2303             is_after_grace = ev_chord.has_elements () or n.is_after_grace ();
2304             is_chord = n.get_maybe_exist_typed_child (musicxml.Chord)
2305
2306             grace_chord = None
2307
2308             # after-graces and other graces use different lists; Depending on
2309             # whether we have a chord or not, obtain either a new ChordEvent or
2310             # the previous one to create a chord
2311             if is_after_grace:
2312                 if ev_chord.after_grace_elements and n.get_maybe_exist_typed_child (musicxml.Chord):
2313                     grace_chord = ev_chord.after_grace_elements.get_last_event_chord ()
2314                 if not grace_chord:
2315                     grace_chord = musicexp.ChordEvent ()
2316                     ev_chord.append_after_grace (grace_chord)
2317             elif n.is_grace ():
2318                 if ev_chord.grace_elements and n.get_maybe_exist_typed_child (musicxml.Chord):
2319                     grace_chord = ev_chord.grace_elements.get_last_event_chord ()
2320                 if not grace_chord:
2321                     grace_chord = musicexp.ChordEvent ()
2322                     ev_chord.append_grace (grace_chord)
2323
2324             if hasattr (grace, 'slash') and not is_after_grace:
2325                 # TODO: use grace_type = "appoggiatura" for slurred grace notes
2326                 if grace.slash == "yes":
2327                     ev_chord.grace_type = "acciaccatura"
2328             # now that we have inserted the chord into the grace music, insert
2329             # everything into that chord instead of the ev_chord
2330             ev_chord = grace_chord
2331             ev_chord.append (main_event)
2332             ignore_lyrics = True
2333         else:
2334             ev_chord.append (main_event)
2335             # When a note/chord has grace notes (duration==0), the duration of the
2336             # event chord is not yet known, but the event chord was already added
2337             # with duration 0. The following correct this when we hit the real note!
2338             if voice_builder.current_duration () == 0 and n._duration > 0:
2339                 voice_builder.set_duration (n._duration)
2340
2341         # if we have a figured bass, set its voice builder to the correct position
2342         # and insert the pending figures
2343         if pending_figured_bass:
2344             try:
2345                 figured_bass_builder.jumpto (n._when)
2346             except NegativeSkip, neg:
2347                 pass
2348             for fb in pending_figured_bass:
2349                 # if a duration is given, use that, otherwise the one of the note
2350                 dur = fb.real_duration
2351                 if not dur:
2352                     dur = ev_chord.get_length ()
2353                 if not fb.duration:
2354                     fb.duration = ev_chord.get_duration ()
2355                 figured_bass_builder.add_music (fb, dur)
2356             pending_figured_bass = []
2357
2358         if pending_chordnames:
2359             try:
2360                 chordnames_builder.jumpto (n._when)
2361             except NegativeSkip, neg:
2362                 pass
2363             for cn in pending_chordnames:
2364                 # Assign the duration of the EventChord
2365                 cn.duration = ev_chord.get_duration ()
2366                 chordnames_builder.add_music (cn, ev_chord.get_length ())
2367             pending_chordnames = []
2368
2369         notations_children = n.get_typed_children (musicxml.Notations)
2370         tuplet_event = None
2371         span_events = []
2372
2373         # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
2374         # +tied | +slur | +tuplet | glissando | slide |
2375         #    ornaments | technical | articulations | dynamics |
2376         #    +fermata | arpeggiate | non-arpeggiate |
2377         #    accidental-mark | other-notation
2378         for notations in notations_children:
2379             for tuplet_event in notations.get_tuplets():
2380                 time_mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
2381                 tuplet_events.append ((ev_chord, tuplet_event, time_mod))
2382
2383             # First, close all open slurs, only then start any new slur
2384             # TODO: Record the number of the open slur to dtermine the correct
2385             #       closing slur!
2386             endslurs = [s for s in notations.get_named_children ('slur')
2387                 if s.get_type () in ('stop')]
2388             if endslurs and not inside_slur:
2389                 endslurs[0].message (_ ('Encountered closing slur, but no slur is open'))
2390             elif endslurs:
2391                 if len (endslurs) > 1:
2392                     endslurs[0].message (_ ('Cannot have two simultaneous (closing) slurs'))
2393                 # record the slur status for the next note in the loop
2394                 inside_slur = False
2395                 lily_ev = musicxml_spanner_to_lily_event (endslurs[0])
2396                 ev_chord.append (lily_ev)
2397
2398             startslurs = [s for s in notations.get_named_children ('slur')
2399                 if s.get_type () in ('start')]
2400             if startslurs and inside_slur:
2401                 startslurs[0].message (_ ('Cannot have a slur inside another slur'))
2402             elif startslurs:
2403                 if len (startslurs) > 1:
2404                     startslurs[0].message (_ ('Cannot have two simultaneous slurs'))
2405                 # record the slur status for the next note in the loop
2406                 inside_slur = True
2407                 lily_ev = musicxml_spanner_to_lily_event (startslurs[0])
2408                 ev_chord.append (lily_ev)
2409
2410
2411             if not grace:
2412                 mxl_tie = notations.get_tie ()
2413                 if mxl_tie and mxl_tie.type == 'start':
2414                     ev_chord.append (musicexp.TieEvent ())
2415                     is_tied = True
2416                     tie_started = True
2417                 else:
2418                     is_tied = False
2419
2420             fermatas = notations.get_named_children ('fermata')
2421             for a in fermatas:
2422                 ev = musicxml_fermata_to_lily_event (a)
2423                 if ev:
2424                     ev_chord.append (ev)
2425
2426             arpeggiate = notations.get_named_children ('arpeggiate')
2427             for a in arpeggiate:
2428                 ev = musicxml_arpeggiate_to_lily_event (a)
2429                 if ev:
2430                     ev_chord.append (ev)
2431
2432             arpeggiate = notations.get_named_children ('non-arpeggiate')
2433             for a in arpeggiate:
2434                 ev = musicxml_nonarpeggiate_to_lily_event (a)
2435                 if ev:
2436                     ev_chord.append (ev)
2437
2438             glissandos = notations.get_named_children ('glissando')
2439             glissandos += notations.get_named_children ('slide')
2440             for a in glissandos:
2441                 ev = musicxml_spanner_to_lily_event (a)
2442                 if ev:
2443                     ev_chord.append (ev)
2444
2445             # accidental-marks are direct children of <notation>!
2446             for a in notations.get_named_children ('accidental-mark'):
2447                 ev = musicxml_articulation_to_lily_event (a)
2448                 if ev:
2449                     ev_chord.append (ev)
2450
2451             # Articulations can contain the following child elements:
2452             #         accent | strong-accent | staccato | tenuto |
2453             #         detached-legato | staccatissimo | spiccato |
2454             #         scoop | plop | doit | falloff | breath-mark |
2455             #         caesura | stress | unstress
2456             # Technical can contain the following child elements:
2457             #         up-bow | down-bow | harmonic | open-string |
2458             #         thumb-position | fingering | pluck | double-tongue |
2459             #         triple-tongue | stopped | snap-pizzicato | fret |
2460             #         string | hammer-on | pull-off | bend | tap | heel |
2461             #         toe | fingernails | other-technical
2462             # Ornaments can contain the following child elements:
2463             #         trill-mark | turn | delayed-turn | inverted-turn |
2464             #         shake | wavy-line | mordent | inverted-mordent |
2465             #         schleifer | tremolo | other-ornament, accidental-mark
2466             ornaments = notations.get_named_children ('ornaments')
2467             ornaments += notations.get_named_children ('articulations')
2468             ornaments += notations.get_named_children ('technical')
2469
2470             for a in ornaments:
2471                 for ch in a.get_all_children ():
2472                     ev = musicxml_articulation_to_lily_event (ch)
2473                     if ev:
2474                         ev_chord.append (ev)
2475
2476             dynamics = notations.get_named_children ('dynamics')
2477             for a in dynamics:
2478                 for ch in a.get_all_children ():
2479                     ev = musicxml_dynamics_to_lily_event (ch)
2480                     if ev:
2481                         ev_chord.append (ev)
2482
2483
2484         mxl_beams = [b for b in n.get_named_children ('beam')
2485                      if (b.get_type () in ('begin', 'end')
2486                          and b.is_primary ())]
2487         if mxl_beams and not conversion_settings.ignore_beaming:
2488             beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
2489             if beam_ev:
2490                 ev_chord.append (beam_ev)
2491                 if beam_ev.span_direction == -1: # beam and thus melisma starts here
2492                     is_beamed = True
2493                 elif beam_ev.span_direction == 1: # beam and thus melisma ends here
2494                     is_beamed = False
2495
2496         # Extract the lyrics
2497         if not rest and not ignore_lyrics:
2498             note_lyrics_processed = []
2499             note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
2500             for l in note_lyrics_elements:
2501                 if l.get_number () < 0:
2502                     for k in lyrics.keys ():
2503                         lyrics[k].append (musicxml_lyrics_to_text (l))
2504                         note_lyrics_processed.append (k)
2505                 else:
2506                     lyrics[l.number].append(musicxml_lyrics_to_text (l))
2507                     note_lyrics_processed.append (l.number)
2508             for lnr in lyrics.keys ():
2509                 if not lnr in note_lyrics_processed:
2510                     lyrics[lnr].append ("\skip4")
2511
2512         # Assume that a <tie> element only lasts for one note.
2513         # This might not be correct MusicXML interpretation, but works for
2514         # most cases and fixes broken files, which have the end tag missing
2515         if is_tied and not tie_started:
2516             is_tied = False
2517
2518     ## force trailing mm rests to be written out.
2519     voice_builder.add_music (musicexp.ChordEvent (), Rational (0))
2520
2521     ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
2522     ly_voice = group_repeats (ly_voice)
2523
2524     seq_music = musicexp.SequentialMusic ()
2525
2526     if 'drummode' in modes_found.keys ():
2527         ## \key <pitch> barfs in drummode.
2528         ly_voice = [e for e in ly_voice
2529                     if not isinstance(e, musicexp.KeySignatureChange)]
2530
2531     seq_music.elements = ly_voice
2532     for k in lyrics.keys ():
2533         return_value.lyrics_dict[k] = musicexp.Lyrics ()
2534         return_value.lyrics_dict[k].lyrics_syllables = lyrics[k]
2535
2536
2537     if len (modes_found) > 1:
2538        error_message (_ ('cannot simultaneously have more than one mode: %s') % modes_found.keys ())
2539
2540     if options.relative:
2541         v = musicexp.RelativeMusic ()
2542         v.element = seq_music
2543         v.basepitch = first_pitch
2544         seq_music = v
2545
2546     return_value.ly_voice = seq_music
2547     for mode in modes_found.keys ():
2548         v = musicexp.ModeChangingMusicWrapper()
2549         v.element = seq_music
2550         v.mode = mode
2551         return_value.ly_voice = v
2552
2553     # create \figuremode { figured bass elements }
2554     if figured_bass_builder.has_relevant_elements:
2555         fbass_music = musicexp.SequentialMusic ()
2556         fbass_music.elements = group_repeats (figured_bass_builder.elements)
2557         v = musicexp.ModeChangingMusicWrapper()
2558         v.mode = 'figuremode'
2559         v.element = fbass_music
2560         return_value.figured_bass = v
2561
2562     # create \chordmode { chords }
2563     if chordnames_builder.has_relevant_elements:
2564         cname_music = musicexp.SequentialMusic ()
2565         cname_music.elements = group_repeats (chordnames_builder.elements)
2566         v = musicexp.ModeChangingMusicWrapper()
2567         v.mode = 'chordmode'
2568         v.element = cname_music
2569         return_value.chordnames = v
2570
2571     return return_value
2572
2573 def musicxml_id_to_lily (id):
2574     digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
2575               'Six', 'Seven', 'Eight', 'Nine', 'Ten']
2576
2577     for digit in digits:
2578         d = digits.index (digit)
2579         id = re.sub ('%d' % d, digit, id)
2580
2581     id = re.sub  ('[^a-zA-Z]', 'X', id)
2582     return id
2583
2584 def musicxml_pitch_to_lily (mxl_pitch):
2585     p = musicexp.Pitch ()
2586     p.alteration = mxl_pitch.get_alteration ()
2587     p.step = musicxml_step_to_lily (mxl_pitch.get_step ())
2588     p.octave = mxl_pitch.get_octave () - 4
2589     return p
2590
2591 def musicxml_unpitched_to_lily (mxl_unpitched):
2592     p = None
2593     step = mxl_unpitched.get_step ()
2594     if step:
2595         p = musicexp.Pitch ()
2596         p.step = musicxml_step_to_lily (step)
2597     octave = mxl_unpitched.get_octave ()
2598     if octave and p:
2599         p.octave = octave - 4
2600     return p
2601
2602 def musicxml_restdisplay_to_lily (mxl_rest):
2603     p = None
2604     step = mxl_rest.get_step ()
2605     if step:
2606         p = musicexp.Pitch ()
2607         p.step = musicxml_step_to_lily (step)
2608     octave = mxl_rest.get_octave ()
2609     if octave and p:
2610         p.octave = octave - 4
2611     return p
2612
2613 def voices_in_part (part):
2614     """Return a Name -> Voice dictionary for PART"""
2615     part.interpret ()
2616     part.extract_voices ()
2617     voices = part.get_voices ()
2618     part_info = part.get_staff_attributes ()
2619
2620     return (voices, part_info)
2621
2622 def voices_in_part_in_parts (parts):
2623     """return a Part -> Name -> Voice dictionary"""
2624     # don't crash if p doesn't have an id (that's invalid MusicXML,
2625     # but such files are out in the wild!
2626     dictionary = {}
2627     for p in parts:
2628         voices = voices_in_part (p)
2629         if (hasattr (p, "id")):
2630              dictionary[p.id] = voices
2631         else:
2632              # TODO: extract correct part id from other sources
2633              dictionary[None] = voices
2634     return dictionary;
2635
2636
2637 def get_all_voices (parts):
2638     all_voices = voices_in_part_in_parts (parts)
2639
2640     all_ly_voices = {}
2641     all_ly_staffinfo = {}
2642     for p, (name_voice, staff_info) in all_voices.items ():
2643
2644         part_ly_voices = {}
2645         for n, v in name_voice.items ():
2646             progress (_ ("Converting to LilyPond expressions..."))
2647             # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
2648             part_ly_voices[n] = musicxml_voice_to_lily_voice (v)
2649
2650         all_ly_voices[p] = part_ly_voices
2651         all_ly_staffinfo[p] = staff_info
2652
2653     return (all_ly_voices, all_ly_staffinfo)
2654
2655
2656 def option_parser ():
2657     p = ly.get_option_parser (usage = _ ("musicxml2ly [OPTION]... FILE.xml"),
2658                              description =
2659 _ ("""Convert MusicXML from FILE.xml to LilyPond input.
2660 If the given filename is -, musicxml2ly reads from the command line.
2661 """), add_help_option=False)
2662
2663     p.add_option("-h", "--help",
2664                  action="help",
2665                  help=_ ("show this help and exit"))
2666
2667     p.version = ('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
2668 +
2669 _ ("""Copyright (c) 2005--2011 by
2670     Han-Wen Nienhuys <hanwen@xs4all.nl>,
2671     Jan Nieuwenhuizen <janneke@gnu.org> and
2672     Reinhold Kainhofer <reinhold@kainhofer.com>
2673 """
2674 +
2675 """
2676 This program is free software.  It is covered by the GNU General Public
2677 License and you are welcome to change it and/or distribute copies of it
2678 under certain conditions.  Invoke as `%s --warranty' for more
2679 information.""") % 'lilypond')
2680
2681     p.add_option("--version",
2682                  action="version",
2683                  help=_ ("show version number and exit"))
2684
2685     p.add_option ('-v', '--verbose',
2686                   action = "store_true",
2687                   dest = 'verbose',
2688                   help = _ ("be verbose"))
2689
2690     p.add_option ('', '--lxml',
2691                   action = "store_true",
2692                   default = False,
2693                   dest = "use_lxml",
2694                   help = _ ("use lxml.etree; uses less memory and cpu time"))
2695
2696     p.add_option ('-z', '--compressed',
2697                   action = "store_true",
2698                   dest = 'compressed',
2699                   default = False,
2700                   help = _ ("input file is a zip-compressed MusicXML file"))
2701
2702     p.add_option ('-r', '--relative',
2703                   action = "store_true",
2704                   default = True,
2705                   dest = "relative",
2706                   help = _ ("convert pitches in relative mode (default)"))
2707
2708     p.add_option ('-a', '--absolute',
2709                   action = "store_false",
2710                   dest = "relative",
2711                   help = _ ("convert pitches in absolute mode"))
2712
2713     p.add_option ('-l', '--language',
2714                   metavar = _ ("LANG"),
2715                   action = "store",
2716                   help = _ ("use LANG for pitch names, e.g. 'deutsch' for note names in German"))
2717
2718     p.add_option ('--nd', '--no-articulation-directions',
2719                   action = "store_false",
2720                   default = True,
2721                   dest = "convert_directions",
2722                   help = _ ("do not convert directions (^, _ or -) for articulations, dynamics, etc."))
2723
2724     p.add_option ('--nrp', '--no-rest-positions',
2725                   action = "store_false",
2726                   default = True,
2727                   dest = "convert_rest_positions",
2728                   help = _ ("do not convert exact vertical positions of rests"))
2729
2730     p.add_option ('--npl', '--no-page-layout',
2731                   action = "store_false",
2732                   default = True,
2733                   dest = "convert_page_layout",
2734                   help = _ ("do not convert the exact page layout and breaks"))
2735
2736     p.add_option ('--no-beaming',
2737                   action = "store_false",
2738                   default = True,
2739                   dest = "convert_beaming",
2740                   help = _ ("do not convert beaming information, use lilypond's automatic beaming instead"))
2741
2742     p.add_option ('-o', '--output',
2743                   metavar = _ ("FILE"),
2744                   action = "store",
2745                   default = None,
2746                   type = 'string',
2747                   dest = 'output_name',
2748                   help = _ ("set output filename to FILE, stdout if -"))
2749     p.add_option_group ('',
2750                         description = (
2751             _ ("Report bugs via %s")
2752             % 'http://post.gmane.org/post.php'
2753             '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
2754     return p
2755
2756 def music_xml_voice_name_to_lily_name (part_id, name):
2757     str = "Part%sVoice%s" % (part_id, name)
2758     return musicxml_id_to_lily (str)
2759
2760 def music_xml_lyrics_name_to_lily_name (part_id, name, lyricsnr):
2761     str = "Part%sVoice%sLyrics%s" % (part_id, name, lyricsnr)
2762     return musicxml_id_to_lily (str)
2763
2764 def music_xml_figuredbass_name_to_lily_name (part_id, voicename):
2765     str = "Part%sVoice%sFiguredBass" % (part_id, voicename)
2766     return musicxml_id_to_lily (str)
2767
2768 def music_xml_chordnames_name_to_lily_name (part_id, voicename):
2769     str = "Part%sVoice%sChords" % (part_id, voicename)
2770     return musicxml_id_to_lily (str)
2771
2772 def print_voice_definitions (printer, part_list, voices):
2773     for part in part_list:
2774         part_id = part.id
2775         nv_dict = voices.get (part_id, {})
2776         for (name, voice) in nv_dict.items ():
2777             k = music_xml_voice_name_to_lily_name (part_id, name)
2778             printer.dump ('%s = ' % k)
2779             voice.ly_voice.print_ly (printer)
2780             printer.newline()
2781             if voice.chordnames:
2782                 cnname = music_xml_chordnames_name_to_lily_name (part_id, name)
2783                 printer.dump ('%s = ' % cnname )
2784                 voice.chordnames.print_ly (printer)
2785                 printer.newline()
2786             for l in voice.lyrics_order:
2787                 lname = music_xml_lyrics_name_to_lily_name (part_id, name, l)
2788                 printer.dump ('%s = ' % lname )
2789                 voice.lyrics_dict[l].print_ly (printer)
2790                 printer.newline()
2791             if voice.figured_bass:
2792                 fbname = music_xml_figuredbass_name_to_lily_name (part_id, name)
2793                 printer.dump ('%s = ' % fbname )
2794                 voice.figured_bass.print_ly (printer)
2795                 printer.newline()
2796
2797
2798 def uniq_list (l):
2799     return dict ([(elt,1) for elt in l]).keys ()
2800
2801 # format the information about the staff in the form
2802 #     [staffid,
2803 #         [
2804 #            [voiceid1, [lyricsid11, lyricsid12,...], figuredbassid1],
2805 #            [voiceid2, [lyricsid21, lyricsid22,...], figuredbassid2],
2806 #            ...
2807 #         ]
2808 #     ]
2809 # raw_voices is of the form [(voicename, lyricsids, havefiguredbass)*]
2810 def format_staff_info (part_id, staff_id, raw_voices):
2811     voices = []
2812     for (v, lyricsids, figured_bass, chordnames) in raw_voices:
2813         voice_name = music_xml_voice_name_to_lily_name (part_id, v)
2814         voice_lyrics = [music_xml_lyrics_name_to_lily_name (part_id, v, l)
2815                    for l in lyricsids]
2816         figured_bass_name = ''
2817         if figured_bass:
2818             figured_bass_name = music_xml_figuredbass_name_to_lily_name (part_id, v)
2819         chordnames_name = ''
2820         if chordnames:
2821             chordnames_name = music_xml_chordnames_name_to_lily_name (part_id, v)
2822         voices.append ([voice_name, voice_lyrics, figured_bass_name, chordnames_name])
2823     return [staff_id, voices]
2824
2825 def update_score_setup (score_structure, part_list, voices):
2826
2827     for part_definition in part_list:
2828         part_id = part_definition.id
2829         nv_dict = voices.get (part_id)
2830         if not nv_dict:
2831             error_message (_ ('unknown part in part-list: %s') % part_id)
2832             continue
2833
2834         staves = reduce (lambda x,y: x+ y,
2835                 [voice.voicedata._staves.keys ()
2836                  for voice in nv_dict.values ()],
2837                 [])
2838         staves_info = []
2839         if len (staves) > 1:
2840             staves_info = []
2841             staves = uniq_list (staves)
2842             staves.sort ()
2843             for s in staves:
2844                 thisstaff_raw_voices = [(voice_name, voice.lyrics_order, voice.figured_bass, voice.chordnames)
2845                     for (voice_name, voice) in nv_dict.items ()
2846                     if voice.voicedata._start_staff == s]
2847                 staves_info.append (format_staff_info (part_id, s, thisstaff_raw_voices))
2848         else:
2849             thisstaff_raw_voices = [(voice_name, voice.lyrics_order, voice.figured_bass, voice.chordnames)
2850                 for (voice_name, voice) in nv_dict.items ()]
2851             staves_info.append (format_staff_info (part_id, None, thisstaff_raw_voices))
2852         score_structure.set_part_information (part_id, staves_info)
2853
2854 # Set global values in the \layout block, like auto-beaming etc.
2855 def update_layout_information ():
2856     if not conversion_settings.ignore_beaming and layout_information:
2857         layout_information.set_context_item ('Score', 'autoBeaming = ##f')
2858
2859 def print_ly_preamble (printer, filename):
2860     printer.dump_version ()
2861     printer.print_verbatim ('%% automatically converted from %s\n' % filename)
2862
2863 def print_ly_additional_definitions (printer, filename):
2864     if needed_additional_definitions:
2865         printer.newline ()
2866         printer.print_verbatim ('%% additional definitions required by the score:')
2867         printer.newline ()
2868     for a in set(needed_additional_definitions):
2869         printer.print_verbatim (additional_definitions.get (a, ''))
2870         printer.newline ()
2871     printer.newline ()
2872
2873 # Read in the tree from the given I/O object (either file or string) and
2874 # demarshall it using the classes from the musicxml.py file
2875 def read_xml (io_object, use_lxml):
2876     if use_lxml:
2877         import lxml.etree
2878         tree = lxml.etree.parse (io_object)
2879         mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
2880         return mxl_tree
2881     else:
2882         from xml.dom import minidom, Node
2883         doc = minidom.parse(io_object)
2884         node = doc.documentElement
2885         return musicxml.minidom_demarshal_node (node)
2886     return None
2887
2888
2889 def read_musicxml (filename, compressed, use_lxml):
2890     raw_string = None
2891     if compressed:
2892         if filename == "-":
2893              progress (_ ("Input is compressed, extracting raw MusicXML data from stdin") )
2894              z = zipfile.ZipFile (sys.stdin)
2895         else:
2896             progress (_ ("Input file %s is compressed, extracting raw MusicXML data") % filename)
2897             z = zipfile.ZipFile (filename, "r")
2898         container_xml = z.read ("META-INF/container.xml")
2899         if not container_xml:
2900             return None
2901         container = read_xml (StringIO.StringIO (container_xml), use_lxml)
2902         if not container:
2903             return None
2904         rootfiles = container.get_maybe_exist_named_child ('rootfiles')
2905         if not rootfiles:
2906             return None
2907         rootfile_list = rootfiles.get_named_children ('rootfile')
2908         mxml_file = None
2909         if len (rootfile_list) > 0:
2910             mxml_file = getattr (rootfile_list[0], 'full-path', None)
2911         if mxml_file:
2912             raw_string = z.read (mxml_file)
2913
2914     if raw_string:
2915         io_object = StringIO.StringIO (raw_string)
2916     elif filename == "-":
2917         io_object = sys.stdin
2918     else:
2919         io_object = filename
2920
2921     return read_xml (io_object, use_lxml)
2922
2923
2924 def convert (filename, options):
2925     if filename == "-":
2926         progress (_ ("Reading MusicXML from Standard input ...") )
2927     else:
2928         progress (_ ("Reading MusicXML from %s ...") % filename)
2929
2930     tree = read_musicxml (filename, options.compressed, options.use_lxml)
2931     score_information = extract_score_information (tree)
2932     paper_information = extract_paper_information (tree)
2933
2934     parts = tree.get_typed_children (musicxml.Part)
2935     (voices, staff_info) = get_all_voices (parts)
2936
2937     score = None
2938     mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
2939     if mxl_pl:
2940         score = extract_score_structure (mxl_pl, staff_info)
2941         part_list = mxl_pl.get_named_children ("score-part")
2942
2943     # score information is contained in the <work>, <identification> or <movement-title> tags
2944     update_score_setup (score, part_list, voices)
2945     # After the conversion, update the list of settings for the \layout block
2946     update_layout_information ()
2947
2948     if not options.output_name:
2949         options.output_name = os.path.basename (filename)
2950         options.output_name = os.path.splitext (options.output_name)[0]
2951     elif re.match (".*\.ly", options.output_name):
2952         options.output_name = os.path.splitext (options.output_name)[0]
2953
2954
2955     #defs_ly_name = options.output_name + '-defs.ly'
2956     if (options.output_name == "-"):
2957       output_ly_name = 'Standard output'
2958     else:
2959       output_ly_name = options.output_name + '.ly'
2960
2961     progress (_ ("Output to `%s'") % output_ly_name)
2962     printer = musicexp.Output_printer()
2963     #progress (_ ("Output to `%s'") % defs_ly_name)
2964     if (options.output_name == "-"):
2965       printer.set_file (codecs.getwriter ("utf-8")(sys.stdout))
2966     else:
2967       printer.set_file (codecs.open (output_ly_name, 'wb', encoding='utf-8'))
2968     print_ly_preamble (printer, filename)
2969     print_ly_additional_definitions (printer, filename)
2970     if score_information:
2971         score_information.print_ly (printer)
2972     if paper_information and conversion_settings.convert_page_layout:
2973         paper_information.print_ly (printer)
2974     if layout_information:
2975         layout_information.print_ly (printer)
2976     print_voice_definitions (printer, part_list, voices)
2977
2978     printer.newline ()
2979     printer.dump ("% The score definition")
2980     printer.newline ()
2981     score.print_ly (printer)
2982     printer.newline ()
2983
2984     return voices
2985
2986 def get_existing_filename_with_extension (filename, ext):
2987     if os.path.exists (filename):
2988         return filename
2989     newfilename = filename + "." + ext
2990     if os.path.exists (newfilename):
2991         return newfilename;
2992     newfilename = filename + ext
2993     if os.path.exists (newfilename):
2994         return newfilename;
2995     return ''
2996
2997 def main ():
2998     opt_parser = option_parser()
2999
3000     global options
3001     (options, args) = opt_parser.parse_args ()
3002     if not args:
3003         opt_parser.print_usage()
3004         sys.exit (2)
3005
3006     if options.language:
3007         musicexp.set_pitch_language (options.language)
3008         needed_additional_definitions.append (options.language)
3009         additional_definitions[options.language] = "\\language \"%s\"\n" % options.language
3010     conversion_settings.ignore_beaming = not options.convert_beaming
3011     conversion_settings.convert_page_layout = options.convert_page_layout
3012
3013     # Allow the user to leave out the .xml or xml on the filename
3014     basefilename = args[0].decode('utf-8')
3015     if basefilename == "-": # Read from stdin
3016         filename = "-"
3017     else:
3018         filename = get_existing_filename_with_extension (basefilename, "xml")
3019         if not filename:
3020             filename = get_existing_filename_with_extension (basefilename, "mxl")
3021             options.compressed = True
3022     if filename and filename.endswith ("mxl"):
3023         options.compressed = True
3024
3025     if filename and (filename == "-" or os.path.exists (filename)):
3026         voices = convert (filename, options)
3027     else:
3028         progress (_ ("Unable to find input file %s") % basefilename)
3029
3030 if __name__ == '__main__':
3031     main()