]> git.donarmstrong.com Git - lilypond.git/blob - scripts/musicxml2ly.py
MusicXML: Add support for compressed MusicXML files (command-line option -z)
[lilypond.git] / scripts / musicxml2ly.py
1 #!@TARGET_PYTHON@
2
3 import optparse
4 import sys
5 import re
6 import os
7 import string
8 import codecs
9 import zipfile
10 import StringIO
11 from gettext import gettext as _
12
13 """
14 @relocate-preamble@
15 """
16
17 import lilylib as ly
18
19 import musicxml
20 import musicexp
21
22 from rational import Rational
23
24 # Store command-line options in a global variable, so we can access them everythwere
25 options = None
26
27 def progress (str):
28     sys.stderr.write (str + '\n')
29     sys.stderr.flush ()
30
31 def error_message (str):
32     sys.stderr.write (str + '\n')
33     sys.stderr.flush ()
34
35 needed_additional_definitions = []
36 additional_definitions = {
37   "snappizzicato": """#(define-markup-command (snappizzicato layout props) ()
38   (interpret-markup layout props
39     (markup #:stencil
40       (ly:stencil-translate-axis
41         (ly:stencil-add
42           (make-circle-stencil 0.7 0.1 #f)
43           (ly:make-stencil
44             (list 'draw-line 0.1 0 0.1 0 1)
45             '(-0.1 . 0.1) '(0.1 . 1)
46           )
47         )
48         0.7 X
49       )
50     )
51   )
52 )
53 """
54 }
55
56 def round_to_two_digits (val):
57     return round (val * 100) / 100
58
59 def extract_layout_information (tree):
60     paper = musicexp.Paper ()
61     defaults = tree.get_maybe_exist_named_child ('defaults')
62     if not defaults:
63         return None
64     tenths = -1
65     scaling = defaults.get_maybe_exist_named_child ('scaling')
66     if scaling:
67         mm = scaling.get_named_child ('millimeters')
68         mm = string.atof (mm.get_text ())
69         tn = scaling.get_maybe_exist_named_child ('tenths')
70         tn = string.atof (tn.get_text ())
71         tenths = mm / tn
72         paper.global_staff_size = mm * 72.27 / 25.4
73     # We need the scaling (i.e. the size of staff tenths for everything!
74     if tenths < 0:
75         return None
76
77     def from_tenths (txt):
78         return round_to_two_digits (string.atof (txt) * tenths / 10)
79     def set_paper_variable (varname, parent, element_name):
80         el = parent.get_maybe_exist_named_child (element_name)
81         if el: # Convert to cm from tenths
82             setattr (paper, varname, from_tenths (el.get_text ()))
83
84     pagelayout = defaults.get_maybe_exist_named_child ('page-layout')
85     if pagelayout:
86         # TODO: How can one have different margins for even and odd pages???
87         set_paper_variable ("page_height", pagelayout, 'page-height')
88         set_paper_variable ("page_width", pagelayout, 'page-width')
89
90         pmargins = pagelayout.get_named_children ('page-margins')
91         for pm in pmargins:
92             set_paper_variable ("left_margin", pm, 'left-margin')
93             set_paper_variable ("right_margin", pm, 'right-margin')
94             set_paper_variable ("bottom_margin", pm, 'bottom-margin')
95             set_paper_variable ("top_margin", pm, 'top-margin')
96
97     systemlayout = defaults.get_maybe_exist_named_child ('system-layout')
98     if systemlayout:
99         sl = systemlayout.get_maybe_exist_named_child ('system-margins')
100         if sl:
101             set_paper_variable ("system_left_margin", sl, 'left-margin')
102             set_paper_variable ("system_right_margin", sl, 'right-margin')
103         set_paper_variable ("system_distance", systemlayout, 'system-distance')
104         set_paper_variable ("top_system_distance", systemlayout, 'top-system-distance')
105
106     stafflayout = defaults.get_named_children ('staff-layout')
107     for sl in stafflayout:
108         nr = getattr (sl, 'number', 1)
109         dist = sl.get_named_child ('staff-distance')
110         #TODO: the staff distance needs to be set in the Staff context!!!
111
112     # TODO: Finish appearance?, music-font?, word-font?, lyric-font*, lyric-language*
113     appearance = defaults.get_named_child ('appearance')
114     if appearance:
115         lws = appearance.get_named_children ('line-width')
116         for lw in lws:
117             # Possible types are: beam, bracket, dashes,
118             #    enclosure, ending, extend, heavy barline, leger,
119             #    light barline, octave shift, pedal, slur middle, slur tip,
120             #    staff, stem, tie middle, tie tip, tuplet bracket, and wedge
121             tp = lw.type
122             w = from_tenths (lw.get_text  ())
123             # TODO: Do something with these values!
124         nss = appearance.get_named_children ('note-size')
125         for ns in nss:
126             # Possible types are: cue, grace and large
127             tp = ns.type
128             sz = from_tenths (ns.get_text ())
129             # TODO: Do something with these values!
130         # <other-appearance> elements have no specified meaning
131
132     rawmusicfont = defaults.get_named_child ('music-font')
133     if rawmusicfont:
134         # TODO: Convert the font
135         pass
136     rawwordfont = defaults.get_named_child ('word-font')
137     if rawwordfont:
138         # TODO: Convert the font
139         pass
140     rawlyricsfonts = defaults.get_named_children ('lyric-font')
141     for lyricsfont in rawlyricsfonts:
142         # TODO: Convert the font
143         pass
144
145     return paper
146
147
148
149 # score information is contained in the <work>, <identification> or <movement-title> tags
150 # extract those into a hash, indexed by proper lilypond header attributes
151 def extract_score_information (tree):
152     header = musicexp.Header ()
153     def set_if_exists (field, value):
154         if value:
155             header.set_field (field, musicxml.escape_ly_output_string (value))
156
157     work = tree.get_maybe_exist_named_child ('work')
158     if work:
159         set_if_exists ('title', work.get_work_title ())
160         set_if_exists ('worknumber', work.get_work_number ())
161         set_if_exists ('opus', work.get_opus ())
162     else:
163         movement_title = tree.get_maybe_exist_named_child ('movement-title')
164         if movement_title:
165             set_if_exists ('title', movement_title.get_text ())
166     
167     identifications = tree.get_named_children ('identification')
168     for ids in identifications:
169         set_if_exists ('copyright', ids.get_rights ())
170         set_if_exists ('composer', ids.get_composer ())
171         set_if_exists ('arranger', ids.get_arranger ())
172         set_if_exists ('editor', ids.get_editor ())
173         set_if_exists ('poet', ids.get_poet ())
174             
175         set_if_exists ('tagline', ids.get_encoding_software ())
176         set_if_exists ('encodingsoftware', ids.get_encoding_software ())
177         set_if_exists ('encodingdate', ids.get_encoding_date ())
178         set_if_exists ('encoder', ids.get_encoding_person ())
179         set_if_exists ('encodingdescription', ids.get_encoding_description ())
180
181     return header
182
183 class PartGroupInfo:
184     def __init__ (self):
185         self.start = {}
186         self.end = {}
187     def is_empty (self):
188         return len (self.start) + len (self.end) == 0
189     def add_start (self, g):
190         self.start[getattr (g, 'number', "1")] = g
191     def add_end (self, g):
192         self.end[getattr (g, 'number', "1")] = g
193     def print_ly (self, printer):
194         error_message ("Unprocessed PartGroupInfo %s encountered" % self)
195     def ly_expression (self):
196         error_message ("Unprocessed PartGroupInfo %s encountered" % self)
197         return ''
198
199
200 def staff_attributes_to_string_tunings (mxl_attr):
201     details = mxl_attr.get_maybe_exist_named_child ('staff-details')
202     if not details:
203         return []
204     lines = 6
205     staff_lines = details.get_maybe_exist_named_child ('staff-lines')
206     if staff_lines:
207         lines = string.atoi (staff_lines.get_text ())
208
209     tunings = [0]*lines
210     staff_tunings = details.get_named_children ('staff-tuning')
211     for i in staff_tunings:
212         p = musicexp.Pitch()
213         line = 0
214         try:
215             line = string.atoi (i.line) - 1
216         except ValueError:
217             pass
218         tunings[line] = p
219
220         step = i.get_named_child (u'tuning-step')
221         step = step.get_text ().strip ()
222         p.step = (ord (step) - ord ('A') + 7 - 2) % 7
223
224         octave = i.get_named_child (u'tuning-octave')
225         octave = octave.get_text ().strip ()
226         p.octave = int (octave) - 4
227
228         alter = i.get_named_child (u'tuning-alter')
229         if alter:
230             p.alteration = int (alter.get_text ().strip ())
231     # lilypond seems to use the opposite ordering than MusicXML...
232     tunings.reverse ()
233
234     return tunings
235
236
237 def staff_attributes_to_lily_staff (mxl_attr):
238     if not mxl_attr:
239         return musicexp.Staff ()
240
241     (staff_id, attributes) = mxl_attr.items ()[0]
242
243     # distinguish by clef:
244     # percussion (percussion and rhythmic), tab, and everything else
245     clef_sign = None
246     clef = attributes.get_maybe_exist_named_child ('clef')
247     if clef:
248         sign = clef.get_maybe_exist_named_child ('sign')
249         if sign:
250             clef_sign = {"percussion": "percussion", "TAB": "tab"}.get (sign.get_text (), None)
251
252     lines = 5
253     details = attributes.get_maybe_exist_named_child ('staff-details')
254     if details:
255         staff_lines = details.get_maybe_exist_named_child ('staff-lines')
256         if staff_lines:
257             lines = string.atoi (staff_lines.get_text ())
258
259     staff = None
260     if clef_sign == "percussion" and lines == 1:
261         staff = musicexp.RhythmicStaff ()
262     elif clef_sign == "percussion":
263         staff = musicexp.DrumStaff ()
264         # staff.drum_style_table = ???
265     elif clef_sign == "tab":
266         staff = musicexp.TabStaff ()
267         staff.string_tunings = staff_attributes_to_string_tunings (attributes)
268         # staff.tablature_format = ???
269     else:
270         # TODO: Handle case with lines <> 5!
271         staff = musicexp.Staff ()
272
273     return staff
274
275
276 def extract_score_layout (part_list, staffinfo):
277     layout = musicexp.StaffGroup (None)
278     if not part_list:
279         return layout
280
281     def read_score_part (el):
282         if not isinstance (el, musicxml.Score_part):
283             return
284         # Depending on the attributes of the first measure, we create different
285         # types of staves (Staff, RhythmicStaff, DrumStaff, TabStaff, etc.)
286         staff = staff_attributes_to_lily_staff (staffinfo.get (el.id, None))
287         if not staff:
288             return None
289         staff.id = el.id
290         partname = el.get_maybe_exist_named_child ('part-name')
291         # Finale gives unnamed parts the name "MusicXML Part" automatically!
292         if partname and partname.get_text() != "MusicXML Part":
293             staff.instrument_name = partname.get_text ()
294         if el.get_maybe_exist_named_child ('part-abbreviation'):
295             staff.short_instrument_name = el.get_maybe_exist_named_child ('part-abbreviation').get_text ()
296         # TODO: Read in the MIDI device / instrument
297         return staff
298
299     def read_score_group (el):
300         if not isinstance (el, musicxml.Part_group):
301             return
302         group = musicexp.StaffGroup ()
303         if hasattr (el, 'number'):
304             id = el.number
305             group.id = id
306             #currentgroups_dict[id] = group
307             #currentgroups.append (id)
308         if el.get_maybe_exist_named_child ('group-name'):
309             group.instrument_name = el.get_maybe_exist_named_child ('group-name').get_text ()
310         if el.get_maybe_exist_named_child ('group-abbreviation'):
311             group.short_instrument_name = el.get_maybe_exist_named_child ('group-abbreviation').get_text ()
312         if el.get_maybe_exist_named_child ('group-symbol'):
313             group.symbol = el.get_maybe_exist_named_child ('group-symbol').get_text ()
314         if el.get_maybe_exist_named_child ('group-barline'):
315             group.spanbar = el.get_maybe_exist_named_child ('group-barline').get_text ()
316         return group
317
318
319     parts_groups = part_list.get_all_children ()
320
321     # the start/end group tags are not necessarily ordered correctly and groups
322     # might even overlap, so we can't go through the children sequentially!
323
324     # 1) Replace all Score_part objects by their corresponding Staff objects,
325     #    also collect all group start/stop points into one PartGroupInfo object
326     staves = []
327     group_info = PartGroupInfo ()
328     for el in parts_groups:
329         if isinstance (el, musicxml.Score_part):
330             if not group_info.is_empty ():
331                 staves.append (group_info)
332                 group_info = PartGroupInfo ()
333             staff = read_score_part (el)
334             if staff:
335                 staves.append (staff)
336         elif isinstance (el, musicxml.Part_group):
337             if el.type == "start":
338                 group_info.add_start (el)
339             elif el.type == "stop":
340                 group_info.add_end (el)
341     if not group_info.is_empty ():
342         staves.append (group_info)
343
344     # 2) Now, detect the groups:
345     group_starts = []
346     pos = 0
347     while pos < len (staves):
348         el = staves[pos]
349         if isinstance (el, PartGroupInfo):
350             prev_start = 0
351             if len (group_starts) > 0:
352                 prev_start = group_starts[-1]
353             elif len (el.end) > 0: # no group to end here
354                 el.end = {}
355             if len (el.end) > 0: # closes an existing group
356                 ends = el.end.keys ()
357                 prev_started = staves[prev_start].start.keys ()
358                 grpid = None
359                 intersection = filter(lambda x:x in ends, prev_started)
360                 if len (intersection) > 0:
361                     grpid = intersection[0]
362                 else:
363                     # Close the last started group
364                     grpid = staves[prev_start].start.keys () [0]
365                     # Find the corresponding closing tag and remove it!
366                     j = pos + 1
367                     foundclosing = False
368                     while j < len (staves) and not foundclosing:
369                         if isinstance (staves[j], PartGroupInfo) and staves[j].end.has_key (grpid):
370                             foundclosing = True
371                             del staves[j].end[grpid]
372                             if staves[j].is_empty ():
373                                 del staves[j]
374                         j += 1
375                 grpobj = staves[prev_start].start[grpid]
376                 group = read_score_group (grpobj)
377                 # remove the id from both the start and end
378                 if el.end.has_key (grpid):
379                     del el.end[grpid]
380                 del staves[prev_start].start[grpid]
381                 if el.is_empty ():
382                     del staves[pos]
383                 # replace the staves with the whole group
384                 for j in staves[(prev_start + 1):pos]:
385                     if j.is_group:
386                         j.stafftype = "InnerStaffGroup"
387                     group.append_staff (j)
388                 del staves[(prev_start + 1):pos]
389                 staves.insert (prev_start + 1, group)
390                 # reset pos so that we continue at the correct position
391                 pos = prev_start
392                 # remove an empty start group
393                 if staves[prev_start].is_empty ():
394                     del staves[prev_start]
395                     group_starts.remove (prev_start)
396                     pos -= 1
397             elif len (el.start) > 0: # starts new part groups
398                 group_starts.append (pos)
399         pos += 1
400
401     if len (staves) == 1:
402         return staves[0]
403     for i in staves:
404         layout.append_staff (i)
405     return layout
406
407
408
409 def musicxml_duration_to_lily (mxl_note):
410     d = musicexp.Duration ()
411     # if the note has no Type child, then that method spits out a warning and 
412     # returns 0, i.e. a whole note
413     d.duration_log = mxl_note.get_duration_log ()
414
415     d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
416     # Grace notes by specification have duration 0, so no time modification 
417     # factor is possible. It even messes up the output with *0/1
418     if not mxl_note.get_maybe_exist_typed_child (musicxml.Grace):
419         d.factor = mxl_note._duration / d.get_length ()
420
421     return d
422
423 def rational_to_lily_duration (rational_len):
424     d = musicexp.Duration ()
425     d.duration_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)
426     d.factor = Rational (rational_len.numerator ())
427     if d.duration_log < 0:
428         error_message ("Encountered rational duration with denominator %s, "
429                        "unable to convert to lilypond duration" %
430                        rational_len.denominator ())
431         # TODO: Test the above error message
432         return None
433     else:
434         return d
435
436 def musicxml_partial_to_lily (partial_len):
437     if partial_len > 0:
438         p = musicexp.Partial ()
439         p.partial = rational_to_lily_duration (partial_len)
440         return p
441     else:
442         return Null
443
444 # Detect repeats and alternative endings in the chord event list (music_list)
445 # and convert them to the corresponding musicexp objects, containing nested
446 # music
447 def group_repeats (music_list):
448     repeat_replaced = True
449     music_start = 0
450     i = 0
451     # Walk through the list of expressions, looking for repeat structure
452     # (repeat start/end, corresponding endings). If we find one, try to find the
453     # last event of the repeat, replace the whole structure and start over again.
454     # For nested repeats, as soon as we encounter another starting repeat bar,
455     # treat that one first, and start over for the outer repeat.
456     while repeat_replaced and i < 100:
457         i += 1
458         repeat_start = -1  # position of repeat start / end
459         repeat_end = -1 # position of repeat start / end
460         repeat_times = 0
461         ending_start = -1 # position of current ending start
462         endings = [] # list of already finished endings
463         pos = 0
464         last = len (music_list) - 1
465         repeat_replaced = False
466         final_marker = 0
467         while pos < len (music_list) and not repeat_replaced:
468             e = music_list[pos]
469             repeat_finished = False
470             if isinstance (e, RepeatMarker):
471                 if not repeat_times and e.times:
472                     repeat_times = e.times
473                 if e.direction == -1:
474                     if repeat_end >= 0:
475                         repeat_finished = True
476                     else:
477                         repeat_start = pos
478                         repeat_end = -1
479                         ending_start = -1
480                         endings = []
481                 elif e.direction == 1:
482                     if repeat_start < 0:
483                         repeat_start = 0
484                     if repeat_end < 0:
485                         repeat_end = pos
486                     final_marker = pos
487             elif isinstance (e, EndingMarker):
488                 if e.direction == -1:
489                     if repeat_start < 0:
490                         repeat_start = 0
491                     if repeat_end < 0:
492                         repeat_end = pos
493                     ending_start = pos
494                 elif e.direction == 1:
495                     if ending_start < 0:
496                         ending_start = 0
497                     endings.append ([ending_start, pos])
498                     ending_start = -1
499                     final_marker = pos
500             elif not isinstance (e, musicexp.BarLine):
501                 # As soon as we encounter an element when repeat start and end
502                 # is set and we are not inside an alternative ending,
503                 # this whole repeat structure is finished => replace it
504                 if repeat_start >= 0 and repeat_end > 0 and ending_start < 0:
505                     repeat_finished = True
506
507             # Finish off all repeats without explicit ending bar (e.g. when
508             # we convert only one page of a multi-page score with repeats)
509             if pos == last and repeat_start >= 0:
510                 repeat_finished = True
511                 final_marker = pos
512                 if repeat_end < 0:
513                     repeat_end = pos
514                 if ending_start >= 0:
515                     endings.append ([ending_start, pos])
516                     ending_start = -1
517
518             if repeat_finished:
519                 # We found the whole structure replace it!
520                 r = musicexp.RepeatedMusic ()
521                 if repeat_times <= 0:
522                     repeat_times = 2
523                 r.repeat_count = repeat_times
524                 # don't erase the first element for "implicit" repeats (i.e. no
525                 # starting repeat bars at the very beginning)
526                 start = repeat_start+1
527                 if repeat_start == music_start:
528                     start = music_start
529                 r.set_music (music_list[start:repeat_end])
530                 for (start, end) in endings:
531                     s = musicexp.SequentialMusic ()
532                     s.elements = music_list[start+1:end]
533                     r.add_ending (s)
534                 del music_list[repeat_start:final_marker+1]
535                 music_list.insert (repeat_start, r)
536                 repeat_replaced = True
537             pos += 1
538         # TODO: Implement repeats until the end without explicit ending bar
539     return music_list
540
541
542
543 def group_tuplets (music_list, events):
544
545
546     """Collect Musics from
547     MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
548     """
549
550     
551     indices = []
552
553     j = 0
554     for (ev_chord, tuplet_elt, fraction) in events:
555         while (j < len (music_list)):
556             if music_list[j] == ev_chord:
557                 break
558             j += 1
559         if tuplet_elt.type == 'start':
560             indices.append ((j, None, fraction))
561         elif tuplet_elt.type == 'stop':
562             indices[-1] = (indices[-1][0], j, indices[-1][2])
563
564     new_list = []
565     last = 0
566     for (i1, i2, frac) in indices:
567         if i1 >= i2:
568             continue
569
570         new_list.extend (music_list[last:i1])
571         seq = musicexp.SequentialMusic ()
572         last = i2 + 1
573         seq.elements = music_list[i1:last]
574
575         tsm = musicexp.TimeScaledMusic ()
576         tsm.element = seq
577
578         tsm.numerator = frac[0]
579         tsm.denominator  = frac[1]
580
581         new_list.append (tsm)
582
583     new_list.extend (music_list[last:])
584     return new_list
585
586
587 def musicxml_clef_to_lily (attributes):
588     change = musicexp.ClefChange ()
589     (change.type, change.position, change.octave) = attributes.get_clef_information ()
590     return change
591     
592 def musicxml_time_to_lily (attributes):
593     (beats, type) = attributes.get_time_signature ()
594
595     change = musicexp.TimeSignatureChange()
596     change.fraction = (beats, type)
597     
598     return change
599
600 def musicxml_key_to_lily (attributes):
601     start_pitch  = musicexp.Pitch ()
602     (fifths, mode) = attributes.get_key_signature () 
603     try:
604         (n,a) = {
605             'major' : (0,0),
606             'minor' : (5,0),
607             }[mode]
608         start_pitch.step = n
609         start_pitch.alteration = a
610     except  KeyError:
611         error_message ('unknown mode %s' % mode)
612
613     fifth = musicexp.Pitch()
614     fifth.step = 4
615     if fifths < 0:
616         fifths *= -1
617         fifth.step *= -1
618         fifth.normalize ()
619     
620     for x in range (fifths):
621         start_pitch = start_pitch.transposed (fifth)
622
623     start_pitch.octave = 0
624
625     change = musicexp.KeySignatureChange()
626     change.mode = mode
627     change.tonic = start_pitch
628     return change
629     
630 def musicxml_attributes_to_lily (attrs):
631     elts = []
632     attr_dispatch =  {
633         'clef': musicxml_clef_to_lily,
634         'time': musicxml_time_to_lily,
635         'key': musicxml_key_to_lily
636     }
637     for (k, func) in attr_dispatch.items ():
638         children = attrs.get_named_children (k)
639         if children:
640             elts.append (func (attrs))
641     
642     return elts
643
644 class Marker (musicexp.Music):
645     def __init__ (self):
646         self.direction = 0
647         self.event = None
648     def print_ly (self, printer):
649         sys.stderr.write ("Encountered unprocessed marker %s\n" % self)
650         pass
651     def ly_expression (self):
652         return ""
653 class RepeatMarker (Marker):
654     def __init__ (self):
655         Marker.__init__ (self)
656         self.times = 0
657 class EndingMarker (Marker):
658     pass
659
660 # Convert the <barline> element to musicxml.BarLine (for non-standard barlines)
661 # and to RepeatMarker and EndingMarker objects for repeat and
662 # alternatives start/stops
663 def musicxml_barline_to_lily (barline):
664     # retval contains all possible markers in the order:
665     # 0..bw_ending, 1..bw_repeat, 2..barline, 3..fw_repeat, 4..fw_ending
666     retval = {}
667     bartype_element = barline.get_maybe_exist_named_child ("bar-style")
668     repeat_element = barline.get_maybe_exist_named_child ("repeat")
669     ending_element = barline.get_maybe_exist_named_child ("ending")
670
671     bartype = None
672     if bartype_element:
673         bartype = bartype_element.get_text ()
674
675     if repeat_element and hasattr (repeat_element, 'direction'):
676         repeat = RepeatMarker ()
677         repeat.direction = {"forward": -1, "backward": 1}.get (repeat_element.direction, 0)
678
679         if ( (repeat_element.direction == "forward" and bartype == "heavy-light") or
680              (repeat_element.direction == "backward" and bartype == "light-heavy") ):
681             bartype = None
682         if hasattr (repeat_element, 'times'):
683             try:
684                 repeat.times = int (repeat_element.times)
685             except ValueError:
686                 repeat.times = 2
687         repeat.event = barline
688         if repeat.direction == -1:
689             retval[3] = repeat
690         else:
691             retval[1] = repeat
692
693     if ending_element and hasattr (ending_element, 'type'):
694         ending = EndingMarker ()
695         ending.direction = {"start": -1, "stop": 1, "discontinue": 1}.get (ending_element.type, 0)
696         ending.event = barline
697         if ending.direction == -1:
698             retval[4] = ending
699         else:
700             retval[0] = ending
701
702     if bartype:
703         b = musicexp.BarLine ()
704         b.type = bartype
705         retval[2] = b
706
707     return retval.values ()
708
709 spanner_event_dict = {
710     'slur' : musicexp.SlurEvent,
711     'beam' : musicexp.BeamEvent,
712     'glissando' : musicexp.GlissandoEvent,
713     'pedal' : musicexp.PedalEvent,
714     'wavy-line' : musicexp.TrillSpanEvent,
715     'octave-shift' : musicexp.OctaveShiftEvent,
716     'wedge' : musicexp.HairpinEvent
717 }
718 spanner_type_dict = {
719     'start': -1,
720     'begin': -1,
721     'crescendo': -1,
722     'decreschendo': -1,
723     'diminuendo': -1,
724     'continue': 0,
725     'up': -1,
726     'down': -1,
727     'stop': 1,
728     'end' : 1
729 }
730
731 def musicxml_spanner_to_lily_event (mxl_event):
732     ev = None
733     
734     name = mxl_event.get_name()
735     func = spanner_event_dict.get (name)
736     if func:
737         ev = func()
738     else:
739         error_message ('unknown span event %s' % mxl_event)
740
741
742     type = mxl_event.get_type ()
743     span_direction = spanner_type_dict.get (type)
744     # really check for None, because some types will be translated to 0, which
745     # would otherwise also lead to the unknown span warning
746     if span_direction != None:
747         ev.span_direction = span_direction
748     else:
749         error_message ('unknown span type %s for %s' % (type, name))
750
751     ev.set_span_type (type)
752     ev.line_type = getattr (mxl_event, 'line-type', 'solid')
753
754     # assign the size, which is used for octave-shift, etc.
755     ev.size = mxl_event.get_size ()
756
757     return ev
758
759 def musicxml_direction_to_indicator (direction):
760     return { "above": 1, "upright": 1, "up":1, "below": -1, "downright": -1, "down": -1 }.get (direction, 0)
761
762 def musicxml_fermata_to_lily_event (mxl_event):
763     ev = musicexp.ArticulationEvent ()
764     ev.type = "fermata"
765     if hasattr (mxl_event, 'type'):
766       dir = musicxml_direction_to_indicator (mxl_event.type)
767       if dir and options.convert_directions:
768         ev.force_direction = dir
769     return ev
770
771
772 def musicxml_arpeggiate_to_lily_event (mxl_event):
773     ev = musicexp.ArpeggioEvent ()
774     ev.direction = musicxml_direction_to_indicator (getattr (mxl_event, 'direction', None))
775     return ev
776
777
778 def musicxml_tremolo_to_lily_event (mxl_event):
779     ev = musicexp.TremoloEvent ()
780     ev.bars = mxl_event.get_text ()
781     return ev
782
783 def musicxml_bend_to_lily_event (mxl_event):
784     ev = musicexp.BendEvent ()
785     ev.alter = mxl_event.bend_alter ()
786     return ev
787
788
789 def musicxml_fingering_event (mxl_event):
790     ev = musicexp.ShortArticulationEvent ()
791     ev.type = mxl_event.get_text ()
792     return ev
793
794 def musicxml_snappizzicato_event (mxl_event):
795     needed_additional_definitions.append ("snappizzicato")
796     ev = musicexp.MarkupEvent ()
797     ev.contents = "\\snappizzicato"
798     return ev
799
800 def musicxml_string_event (mxl_event):
801     ev = musicexp.NoDirectionArticulationEvent ()
802     ev.type = mxl_event.get_text ()
803     return ev
804
805 def musicxml_accidental_mark (mxl_event):
806     ev = musicexp.MarkupEvent ()
807     contents = { "sharp": "\\sharp",
808       "natural": "\\natural",
809       "flat": "\\flat",
810       "double-sharp": "\\doublesharp",
811       "sharp-sharp": "\\sharp\\sharp",
812       "flat-flat": "\\flat\\flat",
813       "flat-flat": "\\doubleflat",
814       "natural-sharp": "\\natural\\sharp",
815       "natural-flat": "\\natural\\flat",
816       "quarter-flat": "\\semiflat",
817       "quarter-sharp": "\\semisharp",
818       "three-quarters-flat": "\\sesquiflat",
819       "three-quarters-sharp": "\\sesquisharp",
820     }.get (mxl_event.get_text ())
821     if contents:
822         ev.contents = contents
823         return ev
824     else:
825         return None
826
827 # translate articulations, ornaments and other notations into ArticulationEvents
828 # possible values:
829 #   -) string  (ArticulationEvent with that name)
830 #   -) function (function(mxl_event) needs to return a full ArticulationEvent-derived object
831 #   -) (class, name)  (like string, only that a different class than ArticulationEvent is used)
832 # TODO: Some translations are missing!
833 articulations_dict = {
834     "accent": (musicexp.ShortArticulationEvent, ">"), # or "accent"
835     "accidental-mark": musicxml_accidental_mark,
836     "bend": musicxml_bend_to_lily_event,
837     "breath-mark": (musicexp.NoDirectionArticulationEvent, "breathe"),
838     #"caesura": "caesura",
839     #"delayed-turn": "?",
840     "detached-legato": (musicexp.ShortArticulationEvent, "_"), # or "portato"
841     #"doit": "",
842     #"double-tongue": "",
843     "down-bow": "downbow",
844     #"falloff": "",
845     "fingering": musicxml_fingering_event,
846     #"fingernails": "",
847     #"fret": "",
848     #"hammer-on": "",
849     "harmonic": "flageolet",
850     #"heel": "",
851     "inverted-mordent": "prall",
852     "inverted-turn": "reverseturn",
853     "mordent": "mordent",
854     "open-string": "open",
855     #"plop": "",
856     #"pluck": "",
857     #"pull-off": "",
858     #"schleifer": "?",
859     #"scoop": "",
860     #"shake": "?",
861     "snap-pizzicato": musicxml_snappizzicato_event,
862     #"spiccato": "",
863     "staccatissimo": (musicexp.ShortArticulationEvent, "|"), # or "staccatissimo"
864     "staccato": (musicexp.ShortArticulationEvent, "."), # or "staccato"
865     "stopped": (musicexp.ShortArticulationEvent, "+"), # or "stopped"
866     #"stress": "",
867     "string": musicxml_string_event,
868     "strong-accent": (musicexp.ShortArticulationEvent, "^"), # or "marcato"
869     #"tap": "",
870     "tenuto": (musicexp.ShortArticulationEvent, "-"), # or "tenuto"
871     #"thumb-position": "",
872     #"toe": "",
873     "turn": "turn",
874     "tremolo": musicxml_tremolo_to_lily_event,
875     "trill-mark": "trill",
876     #"triple-tongue": "",
877     #"unstress": ""
878     "up-bow": "upbow",
879     #"wavy-line": "?",
880 }
881 articulation_spanners = [ "wavy-line" ]
882
883 def musicxml_articulation_to_lily_event (mxl_event):
884     # wavy-line elements are treated as trill spanners, not as articulation ornaments
885     if mxl_event.get_name () in articulation_spanners:
886         return musicxml_spanner_to_lily_event (mxl_event)
887
888     tmp_tp = articulations_dict.get (mxl_event.get_name ())
889     if not tmp_tp:
890         return
891
892     if isinstance (tmp_tp, str):
893         ev = musicexp.ArticulationEvent ()
894         ev.type = tmp_tp
895     elif isinstance (tmp_tp, tuple):
896         ev = tmp_tp[0] ()
897         ev.type = tmp_tp[1]
898     else:
899         ev = tmp_tp (mxl_event)
900
901     # Some articulations use the type attribute, other the placement...
902     dir = None
903     if hasattr (mxl_event, 'type') and options.convert_directions:
904         dir = musicxml_direction_to_indicator (mxl_event.type)
905     if hasattr (mxl_event, 'placement') and options.convert_directions:
906         dir = musicxml_direction_to_indicator (mxl_event.placement)
907     if dir:
908         ev.force_direction = dir
909     return ev
910
911
912 def musicxml_dynamics_to_lily_event (dynentry):
913     dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
914         "f", "ff", "fff", "ffff", "fffff", "ffffff",
915         "mp", "mf", "sf", "sfp", "sfpp", "fp",
916         "rf", "rfz", "sfz", "sffz", "fz" )
917     if not dynentry.get_name() in dynamics_available:
918         return
919     event = musicexp.DynamicsEvent ()
920     event.type = dynentry.get_name ()
921     return event
922
923 # Convert single-color two-byte strings to numbers 0.0 - 1.0
924 def hexcolorval_to_nr (hex_val):
925     try:
926         v = int (hex_val, 16)
927         if v == 255:
928             v = 256
929         return v / 256.
930     except ValueError:
931         return 0.
932
933 def hex_to_color (hex_val):
934     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)
935     if res:
936         return map (lambda x: hexcolorval_to_nr (x), res.group (2,3,4))
937     else:
938         return None
939
940 def musicxml_words_to_lily_event (words):
941     event = musicexp.TextEvent ()
942     text = words.get_text ()
943     text = re.sub ('^ *\n? *', '', text)
944     text = re.sub (' *\n? *$', '', text)
945     event.text = text
946
947     if hasattr (words, 'default-y') and options.convert_directions:
948         offset = getattr (words, 'default-y')
949         try:
950             off = string.atoi (offset)
951             if off > 0:
952                 event.force_direction = 1
953             else:
954                 event.force_direction = -1
955         except ValueError:
956             event.force_direction = 0
957
958     if hasattr (words, 'font-weight'):
959         font_weight = { "normal": '', "bold": '\\bold' }.get (getattr (words, 'font-weight'), '')
960         if font_weight:
961             event.markup += font_weight
962
963     if hasattr (words, 'font-size'):
964         size = getattr (words, 'font-size')
965         font_size = {
966             "xx-small": '\\teeny',
967             "x-small": '\\tiny',
968             "small": '\\small',
969             "medium": '',
970             "large": '\\large',
971             "x-large": '\\huge',
972             "xx-large": '\\bigger\\huge'
973         }.get (size, '')
974         if font_size:
975             event.markup += font_size
976
977     if hasattr (words, 'color'):
978         color = getattr (words, 'color')
979         rgb = hex_to_color (color)
980         if rgb:
981             event.markup += "\\with-color #(rgb-color %s %s %s)" % (rgb[0], rgb[1], rgb[2])
982
983     if hasattr (words, 'font-style'):
984         font_style = { "italic": '\\italic' }.get (getattr (words, 'font-style'), '')
985         if font_style:
986             event.markup += font_style
987
988     # TODO: How should I best convert the font-family attribute?
989
990     # TODO: How can I represent the underline, overline and line-through
991     #       attributes in Lilypond? Values of these attributes indicate
992     #       the number of lines
993
994     return event
995
996
997 direction_spanners = [ 'octave-shift', 'pedal', 'wedge' ]
998
999 def musicxml_direction_to_lily (n):
1000     # TODO: Handle the <staff> element!
1001     res = []
1002     dirtype_children = []
1003     for dt in n.get_typed_children (musicxml.DirType):
1004         dirtype_children += dt.get_all_children ()
1005
1006     for entry in dirtype_children:
1007
1008         if entry.get_name () == "dynamics":
1009             for dynentry in entry.get_all_children ():
1010                 ev = musicxml_dynamics_to_lily_event (dynentry)
1011                 if ev:
1012                     res.append (ev)
1013
1014         if entry.get_name () == "words":
1015             ev = musicxml_words_to_lily_event (entry)
1016             if ev:
1017                 res.append (ev)
1018
1019         # octave shifts. pedal marks, hairpins etc. are spanners:
1020         if entry.get_name() in direction_spanners:
1021             event = musicxml_spanner_to_lily_event (entry)
1022             if event:
1023                 res.append (event)
1024
1025
1026     return res
1027
1028 def musicxml_frame_to_lily_event (frame):
1029     ev = musicexp.FretEvent ()
1030     ev.strings = frame.get_strings ()
1031     ev.frets = frame.get_frets ()
1032     #offset = frame.get_first_fret () - 1
1033     barre = []
1034     for fn in frame.get_named_children ('frame-note'):
1035         fret = fn.get_fret ()
1036         if fret <= 0:
1037             fret = "o"
1038         el = [ fn.get_string (), fret ]
1039         fingering = fn.get_fingering ()
1040         if fingering >= 0:
1041             el.append (fingering)
1042         ev.elements.append (el)
1043         b = fn.get_barre ()
1044         if b == 'start':
1045             barre[0] = el[0] # start string
1046             barre[2] = el[1] # fret
1047         elif b == 'stop':
1048             barre[1] = el[0] # end string
1049     if barre:
1050         ev.barre = barre
1051     return ev
1052
1053 def musicxml_harmony_to_lily (n):
1054     res = []
1055     for f in n.get_named_children ('frame'):
1056         ev = musicxml_frame_to_lily_event (f)
1057         if ev:
1058             res.append (ev)
1059
1060     return res
1061
1062 instrument_drumtype_dict = {
1063     'Acoustic Snare Drum': 'acousticsnare',
1064     'Side Stick': 'sidestick',
1065     'Open Triangle': 'opentriangle',
1066     'Mute Triangle': 'mutetriangle',
1067     'Tambourine': 'tambourine',
1068     'Bass Drum': 'bassdrum',
1069 }
1070
1071 def musicxml_note_to_lily_main_event (n):
1072     pitch  = None
1073     duration = None
1074         
1075     mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
1076     event = None
1077     if mxl_pitch:
1078         pitch = musicxml_pitch_to_lily (mxl_pitch)
1079         event = musicexp.NoteEvent()
1080         event.pitch = pitch
1081
1082         acc = n.get_maybe_exist_named_child ('accidental')
1083         if acc:
1084             # let's not force accs everywhere. 
1085             event.cautionary = acc.editorial
1086         
1087     elif n.get_maybe_exist_typed_child (musicxml.Rest):
1088         # rests can have display-octave and display-step, which are
1089         # treated like an ordinary note pitch
1090         rest = n.get_maybe_exist_typed_child (musicxml.Rest)
1091         event = musicexp.RestEvent()
1092         pitch = musicxml_restdisplay_to_lily (rest)
1093         event.pitch = pitch
1094     elif n.instrument_name:
1095         event = musicexp.NoteEvent ()
1096         drum_type = instrument_drumtype_dict.get (n.instrument_name)
1097         if drum_type:
1098             event.drum_type = drum_type
1099         else:
1100             n.message ("drum %s type unknown, please add to instrument_drumtype_dict" % n.instrument_name)
1101             event.drum_type = 'acousticsnare'
1102     
1103     if not event:
1104         n.message ("cannot find suitable event")
1105
1106     event.duration = musicxml_duration_to_lily (n)
1107     return event
1108
1109
1110 ## TODO
1111 class NegativeSkip:
1112     def __init__ (self, here, dest):
1113         self.here = here
1114         self.dest = dest
1115
1116 class LilyPondVoiceBuilder:
1117     def __init__ (self):
1118         self.elements = []
1119         self.pending_dynamics = []
1120         self.end_moment = Rational (0)
1121         self.begin_moment = Rational (0)
1122         self.pending_multibar = Rational (0)
1123         self.ignore_skips = False
1124
1125     def _insert_multibar (self):
1126         r = musicexp.MultiMeasureRest ()
1127         r.duration = musicexp.Duration()
1128         r.duration.duration_log = 0
1129         r.duration.factor = self.pending_multibar
1130         self.elements.append (r)
1131         self.begin_moment = self.end_moment
1132         self.end_moment = self.begin_moment + self.pending_multibar
1133         self.pending_multibar = Rational (0)
1134         
1135     def add_multibar_rest (self, duration):
1136         self.pending_multibar += duration
1137
1138     def set_duration (self, duration):
1139         self.end_moment = self.begin_moment + duration
1140     def current_duration (self):
1141         return self.end_moment - self.begin_moment
1142         
1143     def add_music (self, music, duration):
1144         assert isinstance (music, musicexp.Music)
1145         if self.pending_multibar > Rational (0):
1146             self._insert_multibar ()
1147
1148         self.elements.append (music)
1149         self.begin_moment = self.end_moment
1150         self.set_duration (duration)
1151         
1152         # Insert all pending dynamics right after the note/rest:
1153         if isinstance (music, musicexp.EventChord) and self.pending_dynamics:
1154             for d in self.pending_dynamics:
1155                 music.append (d)
1156             self.pending_dynamics = []
1157
1158     # Insert some music command that does not affect the position in the measure
1159     def add_command (self, command):
1160         assert isinstance (command, musicexp.Music)
1161         if self.pending_multibar > Rational (0):
1162             self._insert_multibar ()
1163         self.elements.append (command)
1164     def add_barline (self, barline):
1165         # TODO: Implement merging of default barline and custom bar line
1166         self.add_music (barline, Rational (0))
1167     def add_partial (self, command):
1168         self.ignore_skips = True
1169         self.add_command (command)
1170
1171     def add_dynamics (self, dynamic):
1172         # store the dynamic item(s) until we encounter the next note/rest:
1173         self.pending_dynamics.append (dynamic)
1174
1175     def add_bar_check (self, number):
1176         b = musicexp.BarLine ()
1177         b.bar_number = number
1178         self.add_barline (b)
1179
1180     def jumpto (self, moment):
1181         current_end = self.end_moment + self.pending_multibar
1182         diff = moment - current_end
1183         
1184         if diff < Rational (0):
1185             error_message ('Negative skip %s' % diff)
1186             diff = Rational (0)
1187
1188         if diff > Rational (0) and not (self.ignore_skips and moment == 0):
1189             skip = musicexp.SkipEvent()
1190             skip.duration.duration_log = 0
1191             skip.duration.factor = diff
1192
1193             evc = musicexp.EventChord ()
1194             evc.elements.append (skip)
1195             self.add_music (evc, diff)
1196
1197         if diff > Rational (0) and moment == 0:
1198             self.ignore_skips = False
1199
1200     def last_event_chord (self, starting_at):
1201
1202         value = None
1203
1204         # if the position matches, find the last EventChord, do not cross a bar line!
1205         at = len( self.elements ) - 1
1206         while (at >= 0 and
1207                not isinstance (self.elements[at], musicexp.EventChord) and
1208                not isinstance (self.elements[at], musicexp.BarLine)):
1209             at -= 1
1210
1211         if (self.elements
1212             and at >= 0
1213             and isinstance (self.elements[at], musicexp.EventChord)
1214             and self.begin_moment == starting_at):
1215             value = self.elements[at]
1216         else:
1217             self.jumpto (starting_at)
1218             value = None
1219         return value
1220         
1221     def correct_negative_skip (self, goto):
1222         self.end_moment = goto
1223         self.begin_moment = goto
1224         evc = musicexp.EventChord ()
1225         self.elements.append (evc)
1226
1227
1228 class VoiceData:
1229     def __init__ (self):
1230         self.voicedata = None
1231         self.ly_voice = None
1232         self.lyrics_dict = {}
1233         self.lyrics_order = []
1234
1235 def musicxml_voice_to_lily_voice (voice):
1236     tuplet_events = []
1237     modes_found = {}
1238     lyrics = {}
1239     return_value = VoiceData ()
1240     return_value.voicedata = voice
1241
1242     # Needed for melismata detection (ignore lyrics on those notes!):
1243     inside_slur = False
1244     is_tied = False
1245     is_chord = False
1246     ignore_lyrics = False
1247
1248     current_staff = None
1249
1250     # Make sure that the keys in the dict don't get reordered, since
1251     # we need the correct ordering of the lyrics stanzas! By default,
1252     # a dict will reorder its keys
1253     return_value.lyrics_order = voice.get_lyrics_numbers ()
1254     for k in return_value.lyrics_order:
1255         lyrics[k] = []
1256
1257     voice_builder = LilyPondVoiceBuilder()
1258
1259     for n in voice._elements:
1260         if n.get_name () == 'forward':
1261             continue
1262         staff = n.get_maybe_exist_named_child ('staff')
1263         if staff:
1264             staff = staff.get_text ()
1265             if current_staff and staff <> current_staff and not n.get_maybe_exist_named_child ('chord'):
1266                 voice_builder.add_command (musicexp.StaffChange (staff))
1267             current_staff = staff
1268
1269         if isinstance (n, musicxml.Partial) and n.partial > 0:
1270             a = musicxml_partial_to_lily (n.partial)
1271             if a:
1272                 voice_builder.add_partial (a)
1273             continue
1274
1275         if isinstance (n, musicxml.Direction):
1276             for a in musicxml_direction_to_lily (n):
1277                 if a.wait_for_note ():
1278                     voice_builder.add_dynamics (a)
1279                 else:
1280                     voice_builder.add_command (a)
1281             continue
1282
1283         if isinstance (n, musicxml.Harmony):
1284             for a in musicxml_harmony_to_lily (n):
1285                 if a.wait_for_note ():
1286                     voice_builder.add_dynamics (a)
1287                 else:
1288                     voice_builder.add_command (a)
1289             continue
1290
1291         is_chord = n.get_maybe_exist_named_child ('chord')
1292         if not is_chord:
1293             try:
1294                 voice_builder.jumpto (n._when)
1295             except NegativeSkip, neg:
1296                 voice_builder.correct_negative_skip (n._when)
1297                 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
1298             
1299         if isinstance (n, musicxml.Attributes):
1300             if n.is_first () and n._measure_position == Rational (0):
1301                 try:
1302                     number = int (n.get_parent ().number)
1303                 except ValueError:
1304                     number = 0
1305                 if number > 0:
1306                     voice_builder.add_bar_check (number)
1307
1308             for a in musicxml_attributes_to_lily (n):
1309                 voice_builder.add_command (a)
1310             continue
1311
1312         if isinstance (n, musicxml.Barline):
1313             barlines = musicxml_barline_to_lily (n)
1314             for a in barlines:
1315                 if isinstance (a, musicexp.BarLine):
1316                     voice_builder.add_barline (a)
1317                 elif isinstance (a, RepeatMarker) or isinstance (a, EndingMarker):
1318                     voice_builder.add_command (a)
1319             continue
1320
1321         if not n.__class__.__name__ == 'Note':
1322             error_message ('not a Note or Attributes? %s' % n)
1323             continue
1324
1325         rest = n.get_maybe_exist_typed_child (musicxml.Rest)
1326         if (rest
1327             and rest.is_whole_measure ()):
1328
1329             voice_builder.add_multibar_rest (n._duration)
1330             continue
1331
1332         if n.is_first () and n._measure_position == Rational (0):
1333             try: 
1334                 num = int (n.get_parent ().number)
1335             except ValueError:
1336                 num = 0
1337             if num > 0:
1338                 voice_builder.add_bar_check (num)
1339
1340         main_event = musicxml_note_to_lily_main_event (n)
1341         ignore_lyrics = inside_slur or is_tied or is_chord
1342
1343         if hasattr (main_event, 'drum_type') and main_event.drum_type:
1344             modes_found['drummode'] = True
1345
1346
1347         ev_chord = voice_builder.last_event_chord (n._when)
1348         if not ev_chord: 
1349             ev_chord = musicexp.EventChord()
1350             voice_builder.add_music (ev_chord, n._duration)
1351
1352         grace = n.get_maybe_exist_typed_child (musicxml.Grace)
1353         if grace:
1354             grace_chord = None
1355             if n.get_maybe_exist_typed_child (musicxml.Chord) and ev_chord.grace_elements:
1356                 grace_chord = ev_chord.grace_elements.get_last_event_chord ()
1357             if not grace_chord:
1358                 grace_chord = musicexp.EventChord ()
1359                 ev_chord.append_grace (grace_chord)
1360             if hasattr (grace, 'slash'):
1361                 # TODO: use grace_type = "appoggiatura" for slurred grace notes
1362                 if grace.slash == "yes":
1363                     ev_chord.grace_type = "acciaccatura"
1364                 elif grace.slash == "no":
1365                     ev_chord.grace_type = "grace"
1366             # now that we have inserted the chord into the grace music, insert
1367             # everything into that chord instead of the ev_chord
1368             ev_chord = grace_chord
1369             ev_chord.append (main_event)
1370             ignore_lyrics = True
1371         else:
1372             ev_chord.append (main_event)
1373             # When a note/chord has grace notes (duration==0), the duration of the
1374             # event chord is not yet known, but the event chord was already added
1375             # with duration 0. The following correct this when we hit the real note!
1376             if voice_builder.current_duration () == 0 and n._duration > 0:
1377                 voice_builder.set_duration (n._duration)
1378         
1379         notations_children = n.get_typed_children (musicxml.Notations)
1380         tuplet_event = None
1381         span_events = []
1382
1383         # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
1384         # +tied | +slur | +tuplet | glissando | slide | 
1385         #    ornaments | technical | articulations | dynamics |
1386         #    +fermata | arpeggiate | non-arpeggiate | 
1387         #    accidental-mark | other-notation
1388         for notations in notations_children:
1389             if notations.get_tuplet():
1390                 tuplet_event = notations.get_tuplet()
1391                 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
1392                 frac = (1,1)
1393                 if mod:
1394                     frac = mod.get_fraction ()
1395                 
1396                 tuplet_events.append ((ev_chord, tuplet_event, frac))
1397
1398             slurs = [s for s in notations.get_named_children ('slur')
1399                 if s.get_type () in ('start','stop')]
1400             if slurs:
1401                 if len (slurs) > 1:
1402                     error_message ('more than 1 slur?')
1403                 # record the slur status for the next note in the loop
1404                 if not grace:
1405                     if slurs[0].get_type () == 'start':
1406                         inside_slur = True
1407                     elif slurs[0].get_type () == 'stop':
1408                         inside_slur = False
1409                 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
1410                 ev_chord.append (lily_ev)
1411
1412             if not grace:
1413                 mxl_tie = notations.get_tie ()
1414                 if mxl_tie and mxl_tie.type == 'start':
1415                     ev_chord.append (musicexp.TieEvent ())
1416                     is_tied = True
1417                 else:
1418                     is_tied = False
1419
1420             fermatas = notations.get_named_children ('fermata')
1421             for a in fermatas:
1422                 ev = musicxml_fermata_to_lily_event (a)
1423                 if ev: 
1424                     ev_chord.append (ev)
1425
1426             arpeggiate = notations.get_named_children ('arpeggiate')
1427             for a in arpeggiate:
1428                 ev = musicxml_arpeggiate_to_lily_event (a)
1429                 if ev:
1430                     ev_chord.append (ev)
1431
1432             glissandos = notations.get_named_children ('glissando')
1433             for a in glissandos:
1434                 ev = musicxml_spanner_to_lily_event (a)
1435                 if ev:
1436                     ev_chord.append (ev)
1437                 
1438             # Articulations can contain the following child elements:
1439             #         accent | strong-accent | staccato | tenuto |
1440             #         detached-legato | staccatissimo | spiccato |
1441             #         scoop | plop | doit | falloff | breath-mark | 
1442             #         caesura | stress | unstress
1443             # Technical can contain the following child elements:
1444             #         up-bow | down-bow | harmonic | open-string |
1445             #         thumb-position | fingering | pluck | double-tongue |
1446             #         triple-tongue | stopped | snap-pizzicato | fret |
1447             #         string | hammer-on | pull-off | bend | tap | heel |
1448             #         toe | fingernails | other-technical
1449             # Ornaments can contain the following child elements:
1450             #         trill-mark | turn | delayed-turn | inverted-turn |
1451             #         shake | wavy-line | mordent | inverted-mordent | 
1452             #         schleifer | tremolo | other-ornament, accidental-mark
1453             ornaments = notations.get_named_children ('ornaments')
1454             for a in ornaments:
1455                 for ch in a.get_named_children ('tremolo'):
1456                     ev = musicxml_tremolo_to_lily_event (ch)
1457                     if ev: 
1458                         ev_chord.append (ev)
1459
1460             ornaments += notations.get_named_children ('articulations')
1461             ornaments += notations.get_named_children ('technical')
1462
1463             for a in ornaments:
1464                 for ch in a.get_all_children ():
1465                     ev = musicxml_articulation_to_lily_event (ch)
1466                     if ev: 
1467                         ev_chord.append (ev)
1468
1469             dynamics = notations.get_named_children ('dynamics')
1470             for a in dynamics:
1471                 for ch in a.get_all_children ():
1472                     ev = musicxml_dynamics_to_lily_event (ch)
1473                     if ev:
1474                         ev_chord.append (ev)
1475
1476         # Extract the lyrics
1477         if not rest and not ignore_lyrics:
1478             note_lyrics_processed = []
1479             note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
1480             for l in note_lyrics_elements:
1481                 if l.get_number () < 0:
1482                     for k in lyrics.keys ():
1483                         lyrics[k].append (l.lyric_to_text ())
1484                         note_lyrics_processed.append (k)
1485                 else:
1486                     lyrics[l.number].append(l.lyric_to_text ())
1487                     note_lyrics_processed.append (l.number)
1488             for lnr in lyrics.keys ():
1489                 if not lnr in note_lyrics_processed:
1490                     lyrics[lnr].append ("\skip4")
1491
1492
1493         mxl_beams = [b for b in n.get_named_children ('beam')
1494                      if (b.get_type () in ('begin', 'end')
1495                          and b.is_primary ())] 
1496         if mxl_beams:
1497             beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
1498             if beam_ev:
1499                 ev_chord.append (beam_ev)
1500             
1501         if tuplet_event:
1502             mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
1503             frac = (1,1)
1504             if mod:
1505                 frac = mod.get_fraction ()
1506                 
1507             tuplet_events.append ((ev_chord, tuplet_event, frac))
1508
1509     ## force trailing mm rests to be written out.   
1510     voice_builder.add_music (musicexp.EventChord (), Rational (0))
1511     
1512     ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
1513     ly_voice = group_repeats (ly_voice)
1514
1515     seq_music = musicexp.SequentialMusic ()
1516
1517     if 'drummode' in modes_found.keys ():
1518         ## \key <pitch> barfs in drummode.
1519         ly_voice = [e for e in ly_voice
1520                     if not isinstance(e, musicexp.KeySignatureChange)]
1521     
1522     seq_music.elements = ly_voice
1523     for k in lyrics.keys ():
1524         return_value.lyrics_dict[k] = musicexp.Lyrics ()
1525         return_value.lyrics_dict[k].lyrics_syllables = lyrics[k]
1526     
1527     
1528     if len (modes_found) > 1:
1529        error_message ('Too many modes found %s' % modes_found.keys ())
1530
1531     return_value.ly_voice = seq_music
1532     for mode in modes_found.keys ():
1533         v = musicexp.ModeChangingMusicWrapper()
1534         v.element = seq_music
1535         v.mode = mode
1536         return_value.ly_voice = v
1537     
1538     return return_value
1539
1540
1541 def musicxml_id_to_lily (id):
1542     digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
1543               'Six', 'Seven', 'Eight', 'Nine', 'Ten']
1544     
1545     for digit in digits:
1546         d = digits.index (digit)
1547         id = re.sub ('%d' % d, digit, id)
1548
1549     id = re.sub  ('[^a-zA-Z]', 'X', id)
1550     return id
1551
1552
1553 def musicxml_pitch_to_lily (mxl_pitch):
1554     p = musicexp.Pitch()
1555     p.alteration = mxl_pitch.get_alteration ()
1556     p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
1557     p.octave = mxl_pitch.get_octave () - 4
1558     return p
1559
1560 def musicxml_restdisplay_to_lily (mxl_rest):
1561     p = None
1562     step = mxl_rest.get_step ()
1563     if step:
1564         p = musicexp.Pitch()
1565         p.step = (ord (step) - ord ('A') + 7 - 2) % 7
1566     octave = mxl_rest.get_octave ()
1567     if octave and p:
1568         p.octave = octave - 4
1569     return p
1570
1571 def voices_in_part (part):
1572     """Return a Name -> Voice dictionary for PART"""
1573     part.interpret ()
1574     part.extract_voices ()
1575     voices = part.get_voices ()
1576     part_info = part.get_staff_attributes ()
1577
1578     return (voices, part_info)
1579
1580 def voices_in_part_in_parts (parts):
1581     """return a Part -> Name -> Voice dictionary"""
1582     return dict([(p.id, voices_in_part (p)) for p in parts])
1583
1584
1585 def get_all_voices (parts):
1586     all_voices = voices_in_part_in_parts (parts)
1587
1588     all_ly_voices = {}
1589     all_ly_staffinfo = {}
1590     for p, (name_voice, staff_info) in all_voices.items ():
1591
1592         part_ly_voices = {}
1593         for n, v in name_voice.items ():
1594             progress ("Converting to LilyPond expressions...")
1595             # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
1596             part_ly_voices[n] = musicxml_voice_to_lily_voice (v)
1597
1598         all_ly_voices[p] = part_ly_voices
1599         all_ly_staffinfo[p] = staff_info
1600
1601     return (all_ly_voices, all_ly_staffinfo)
1602
1603
1604 def option_parser ():
1605     p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
1606                              version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
1607                                       +
1608 _ ("""This program is free software.  It is covered by the GNU General Public
1609 License and you are welcome to change it and/or distribute copies of it
1610 under certain conditions.  Invoke as `%s --warranty' for more
1611 information.""") % 'lilypond'
1612 + """
1613 Copyright (c) 2005--2007 by
1614     Han-Wen Nienhuys <hanwen@xs4all.nl> and
1615     Jan Nieuwenhuizen <janneke@gnu.org>
1616 """),
1617                              description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
1618     p.add_option ('-v', '--verbose',
1619                   action="store_true",
1620                   dest='verbose',
1621                   help=_ ("be verbose"))
1622
1623     p.add_option ('', '--lxml',
1624                   action="store_true",
1625                   default=False,
1626                   dest="use_lxml",
1627                   help=_ ("Use lxml.etree; uses less memory and cpu time."))
1628
1629     p.add_option ('-z', '--compressed',
1630                   action = "store_true",
1631                   dest = 'compressed',
1632                   default = False,
1633                   help = _ ("Input file is a zip-compressed MusicXML file."))
1634
1635     p.add_option ('-l', '--language',
1636                   action = "store",
1637                   help = _ ("Use a different language file, e.g. 'deutsch' for deutsch.ly."))
1638
1639     p.add_option ('--no-articulation-directions', '--nd',
1640                   action = "store_false",
1641                   default = True,
1642                   dest = "convert_directions",
1643                   help = _ ("Do not convert directions (^, _ or -) for articulations."))
1644
1645     p.add_option ('-o', '--output',
1646                   metavar=_ ("FILE"),
1647                   action="store",
1648                   default=None,
1649                   type='string',
1650                   dest='output_name',
1651                   help=_ ("set output filename to FILE"))
1652     p.add_option_group ('bugs',
1653                         description=(_ ("Report bugs via")
1654                                      + ''' http://post.gmane.org/post.php'''
1655                                      '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
1656     return p
1657
1658 def music_xml_voice_name_to_lily_name (part_id, name):
1659     str = "Part%sVoice%s" % (part_id, name)
1660     return musicxml_id_to_lily (str) 
1661
1662 def music_xml_lyrics_name_to_lily_name (part_id, name, lyricsnr):
1663     str = "Part%sVoice%sLyrics%s" % (part_id, name, lyricsnr)
1664     return musicxml_id_to_lily (str) 
1665
1666 def print_voice_definitions (printer, part_list, voices):
1667     for part in part_list:
1668         part_id = part.id
1669         nv_dict = voices.get (part_id, {})
1670         for (name, voice) in nv_dict.items ():
1671             k = music_xml_voice_name_to_lily_name (part_id, name)
1672             printer.dump ('%s = ' % k)
1673             voice.ly_voice.print_ly (printer)
1674             printer.newline()
1675             for l in voice.lyrics_order:
1676                 lname = music_xml_lyrics_name_to_lily_name (part_id, name, l)
1677                 printer.dump ('%s = ' %lname )
1678                 voice.lyrics_dict[l].print_ly (printer)
1679                 printer.newline()
1680
1681
1682 def uniq_list (l):
1683     return dict ([(elt,1) for elt in l]).keys ()
1684
1685 # format the information about the staff in the form 
1686 #     [staffid,
1687 #         [
1688 #            [voiceid1, [lyricsid11, lyricsid12,...] ...],
1689 #            [voiceid2, [lyricsid21, lyricsid22,...] ...],
1690 #            ...
1691 #         ]
1692 #     ]
1693 # raw_voices is of the form [(voicename, lyricsids)*]
1694 def format_staff_info (part_id, staff_id, raw_voices):
1695     voices = []
1696     for (v, lyricsids) in raw_voices:
1697         voice_name = music_xml_voice_name_to_lily_name (part_id, v)
1698         voice_lyrics = [music_xml_lyrics_name_to_lily_name (part_id, v, l)
1699                    for l in lyricsids]
1700         voices.append ([voice_name, voice_lyrics])
1701     return [staff_id, voices]
1702
1703 def update_score_setup (score_structure, part_list, voices):
1704
1705     for part_definition in part_list:
1706         part_id = part_definition.id
1707         nv_dict = voices.get (part_id)
1708         if not nv_dict:
1709             error_message ('unknown part in part-list: %s' % part_id)
1710             continue
1711
1712         staves = reduce (lambda x,y: x+ y,
1713                 [voice.voicedata._staves.keys ()
1714                  for voice in nv_dict.values ()],
1715                 [])
1716         staves_info = []
1717         if len (staves) > 1:
1718             staves_info = []
1719             staves = uniq_list (staves)
1720             staves.sort ()
1721             for s in staves:
1722                 thisstaff_raw_voices = [(voice_name, voice.lyrics_order) 
1723                     for (voice_name, voice) in nv_dict.items ()
1724                     if voice.voicedata._start_staff == s]
1725                 staves_info.append (format_staff_info (part_id, s, thisstaff_raw_voices))
1726         else:
1727             thisstaff_raw_voices = [(voice_name, voice.lyrics_order) 
1728                 for (voice_name, voice) in nv_dict.items ()]
1729             staves_info.append (format_staff_info (part_id, None, thisstaff_raw_voices))
1730         score_structure.set_part_information (part_id, staves_info)
1731
1732 def print_ly_preamble (printer, filename):
1733     printer.dump_version ()
1734     printer.print_verbatim ('%% automatically converted from %s\n' % filename)
1735
1736 def print_ly_additional_definitions (printer, filename):
1737     if needed_additional_definitions:
1738         printer.newline ()
1739         printer.print_verbatim ('%% additional definitions required by the score:')
1740         printer.newline ()
1741     for a in set(needed_additional_definitions):
1742         printer.print_verbatim (additional_definitions.get (a, ''))
1743     printer.newline ()
1744
1745 # Read in the tree from the given I/O object (either file or string) and 
1746 # demarshall it using the classes from the musicxml.py file
1747 def read_xml (io_object, use_lxml):
1748     if use_lxml:
1749         import lxml.etree
1750         tree = lxml.etree.parse (io_object)
1751         mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
1752         return mxl_tree
1753     else:
1754         from xml.dom import minidom, Node
1755         doc = minidom.parse(io_object)
1756         node = doc.documentElement
1757         return musicxml.minidom_demarshal_node (node)
1758     return None
1759
1760
1761 def read_musicxml (filename, compressed, use_lxml):
1762     raw_string = None
1763     if compressed:
1764         progress ("Input file %s is compressed, extracting raw MusicXML data" % filename)
1765         z = zipfile.ZipFile (filename, "r")
1766         container_xml = z.read ("META-INF/container.xml")
1767         if not container_xml:
1768             return None
1769         container = read_xml (StringIO.StringIO (container_xml), use_lxml)
1770         if not container:
1771             return None
1772         rootfiles = container.get_maybe_exist_named_child ('rootfiles')
1773         if not rootfiles:
1774             return None
1775         rootfile_list = rootfiles.get_named_children ('rootfile')
1776         mxml_file = None
1777         if len (rootfile_list) > 0:
1778             mxml_file = getattr (rootfile_list[0], 'full-path', None)
1779         if mxml_file:
1780             raw_string = z.read (mxml_file)
1781
1782     io_object = filename
1783     if raw_string:
1784         io_object = StringIO.StringIO (raw_string)
1785
1786     return read_xml (io_object, use_lxml)
1787
1788
1789 def convert (filename, options):
1790     progress ("Reading MusicXML from %s ..." % filename)
1791     
1792     tree = read_musicxml (filename, options.compressed, options.use_lxml)
1793     parts = tree.get_typed_children (musicxml.Part)
1794     (voices, staff_info) = get_all_voices (parts)
1795
1796     score_structure = None
1797     mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
1798     if mxl_pl:
1799         score_structure = extract_score_layout (mxl_pl, staff_info)
1800         part_list = mxl_pl.get_named_children ("score-part")
1801
1802     # score information is contained in the <work>, <identification> or <movement-title> tags
1803     score_information = extract_score_information (tree)
1804     layout_information = extract_layout_information (tree)
1805     update_score_setup (score_structure, part_list, voices)
1806
1807     if not options.output_name:
1808         options.output_name = os.path.basename (filename) 
1809         options.output_name = os.path.splitext (options.output_name)[0]
1810     elif re.match (".*\.ly", options.output_name):
1811         options.output_name = os.path.splitext (options.output_name)[0]
1812
1813
1814     defs_ly_name = options.output_name + '-defs.ly'
1815     driver_ly_name = options.output_name + '.ly'
1816
1817     printer = musicexp.Output_printer()
1818     progress ("Output to `%s'" % defs_ly_name)
1819     printer.set_file (codecs.open (defs_ly_name, 'wb', encoding='utf-8'))
1820
1821     print_ly_preamble (printer, filename)
1822     print_ly_additional_definitions (printer, filename)
1823     if score_information:
1824         score_information.print_ly (printer)
1825     if layout_information:
1826         layout_information.print_ly (printer)
1827     print_voice_definitions (printer, part_list, voices)
1828     
1829     printer.close ()
1830     
1831     
1832     progress ("Output to `%s'" % driver_ly_name)
1833     printer = musicexp.Output_printer()
1834     printer.set_file (codecs.open (driver_ly_name, 'wb', encoding='utf-8'))
1835     print_ly_preamble (printer, filename)
1836     printer.dump (r'\include "%s"' % os.path.basename (defs_ly_name))
1837     score_structure.print_ly (printer)
1838     printer.newline ()
1839
1840     return voices
1841
1842 def get_existing_filename_with_extension (filename, ext):
1843     if os.path.exists (filename):
1844         return filename
1845     newfilename = filename + "." + ext
1846     if os.path.exists (newfilename):
1847         return newfilename;
1848     newfilename = filename + ext
1849     if os.path.exists (newfilename):
1850         return newfilename;
1851     return ''
1852
1853 def main ():
1854     opt_parser = option_parser()
1855
1856     global options
1857     (options, args) = opt_parser.parse_args ()
1858     if not args:
1859         opt_parser.print_usage()
1860         sys.exit (2)
1861
1862     if options.language:
1863         musicexp.set_pitch_language (options.language)
1864         needed_additional_definitions.append (options.language)
1865         additional_definitions[options.language] = "\\include \"%s.ly\"\n" % options.language
1866
1867     # Allow the user to leave out the .xml or xml on the filename
1868     filename = get_existing_filename_with_extension (args[0], "xml")
1869     if not filename:
1870         filename = get_existing_filename_with_extension (args[0], "mxl")
1871         options.compressed = True
1872     if filename and os.path.exists (filename):
1873         voices = convert (filename, options)
1874     else:
1875         progress ("Unable to find input file %s" % args[0])
1876
1877 if __name__ == '__main__':
1878     main()