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