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