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