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