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