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