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