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