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