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