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