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