File: tools.py

package info (click to toggle)
frescobaldi 1.1.4-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 4,240 kB
  • ctags: 2,434
  • sloc: python: 15,614; lisp: 28; sh: 25; makefile: 2
file content (565 lines) | stat: -rw-r--r-- 21,957 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
# This file is part of the Frescobaldi project, http://www.frescobaldi.org/
#
# Copyright (c) 2008, 2009, 2010 by Wilbert Berendsen
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
# See http://www.gnu.org/licenses/ for more information.

from __future__ import unicode_literals

"""
All kinds of tools needed to manipulate strings with LilyPond input.
"""

import ly.pitch
import ly.tokenize        


class Pitch(ly.pitch.Pitch):
    @classmethod
    def fromToken(cls, token, tokenizer):
        result = tokenizer.readStep(token)
        if result:
            p = cls()
            p.note, p.alter = result
            p.octave = ly.pitch.octaveToNum(token.octave)
            p.cautionary = token.cautionary
            if token.octcheck:
                p.octaveCheck = ly.pitch.octaveToNum(token.octcheck)
            return p
    

def relativeToAbsolute(text, start = 0, changes = None):
    """
    Convert \relative { }  music to absolute pitches.
    Returns a ChangeList instance that contains the changes.
    """
    tokenizer = ly.tokenize.MusicTokenizer()
    tokens = tokenizer.tokens(text)
    
    # Walk through not-selected text, to track the state and the 
    # current pitch language.
    if start:
        for token in tokens:
            if token.end >= start:
                break
    
    if changes is None:
        changes = ly.tokenize.ChangeList(text)
    
    def newPitch(token, pitch, lastPitch):
        """
        Writes a new pitch with all parts except the octave taken from the
        token. The octave is set using lastPitch.
        """
        pitch.absolute(lastPitch)
        changes.replaceToken(token,
            token.step + ly.pitch.octaveToString(pitch.octave) + token.cautionary)
        
    class gen(object):
        """
        Advanced generator of tokens, discarding whitespace and comments,
        and automatically detecting \relative blocks and places where a new
        LilyPond parsing context is started, like \score inside \markup.
        """
        def __iter__(self):
            return self
            
        def next(self):
            token = next(tokens)
            while isinstance(token, (tokenizer.Space, tokenizer.Comment)):
                token = next(tokens)
            if token == "\\relative":
                relative(token.pos)
                token = next(tokens)
            elif isinstance(token, tokenizer.MarkupScore):
                absolute()
                token = next(tokens)
            return token
    
    source = gen()
    
    def consume():
        """ Consume tokens till the level drops (we exit a construct). """
        depth = tokenizer.depth()
        for token in source:
            yield token
            if tokenizer.depth() < depth:
                return
    
    def absolute():
        """ Consume tokens while not doing anything. """
        for token in consume():
            pass
    
    def relative(start):
        """
        Called when a \\relative command is encountered.
        start is the position of the \\relative token, to remove it later.
        """
        # find the pitch after the \relative command
        lastPitch = None
        token = next(source)
        if isinstance(token, tokenizer.Pitch):
            lastPitch = Pitch.fromToken(token, tokenizer)
            token = next(source)
        if not lastPitch:
            lastPitch = Pitch.c1()
        
        # remove the \relative <pitch> tokens
        changes.remove(start, token.pos)
        
        # eat stuff like \new Staff == "bla" \new Voice \notes etc.
        while True:
            if token in ('\\new', '\\context'):
                next(source) # skip context type
                token = next(source)
                if token == '=':
                    next(source) # skip context name
                    token = next(source)
            elif isinstance(token, (tokenizer.ChordMode, tokenizer.NoteMode)):
                token = next(source)
            else:
                break
        
        # now convert the relative expression to absolute
        if isinstance(token, tokenizer.OpenDelimiter):
            # Handle full music expression { ... } or << ... >>
            for token in consume():
                # skip commands with pitches that do not count
                if token in ('\\key', '\\transposition'):
                    next(source)
                elif token == '\\transpose':
                    next(source)
                    next(source)
                elif token == '\\octaveCheck':
                    start = token.pos
                    token = next(source)
                    if isinstance(token, tokenizer.Pitch):
                        p = Pitch.fromToken(token, tokenizer)
                        if p:
                            lastPitch = p
                            changes.remove(start, token.end)
                elif isinstance(token, tokenizer.OpenChord):
                    # handle chord
                    chord = [lastPitch]
                    for token in source:
                        if isinstance(token, tokenizer.CloseChord):
                            lastPitch = chord[:2][-1] # same or first
                            break
                        elif isinstance(token, tokenizer.Pitch):
                            p = Pitch.fromToken(token, tokenizer)
                            if p:
                                newPitch(token, p, chord[-1])
                                chord.append(p)
                elif isinstance(token, tokenizer.Pitch):
                    p = Pitch.fromToken(token, tokenizer)
                    if p:
                        newPitch(token, p, lastPitch)
                        lastPitch = p
        elif isinstance(token, tokenizer.OpenChord):
            # Handle just one chord
            for token in source:
                if isinstance(token, tokenizer.CloseChord):
                    break
                elif isinstance(token, tokenizer.Pitch):
                    p = Pitch.fromToken(token, tokenizer)
                    if p:
                        newPitch(token, p, lastPitch)
                        lastPitch = p
        elif isinstance(token, tokenizer.Pitch):
            # Handle just one pitch
            p = Pitch.fromToken(token, tokenizer)
            if p:
                newPitch(token, p, lastPitch)
    
    # Do it!
    for token in source:
        pass
    return changes

def absoluteToRelative(text, start = 0, changes = None):
    """
    Converts the selected music expression or all toplevel expressions to \relative ones.
    """
    tokenizer = ly.tokenize.MusicTokenizer()
    tokens = tokenizer.tokens(text)
    
    # Walk through not-selected text, to track the state and the 
    # current pitch language.
    if start:
        for token in tokens:
            if token.end >= start:
                break
    
    if changes is None:
        changes = ly.tokenize.ChangeList(text)
    
    def newPitch(token, pitch):
        """
        Writes a new pitch with all parts except the octave taken from the
        token.
        """
        changes.replaceToken(token,
            token.step + ly.pitch.octaveToString(pitch.octave) + token.cautionary)
        
    class gen(object):
        """
        Advanced generator of tokens, discarding whitespace and comments,
        and automatically detecting \relative blocks and places where a new
        LilyPond parsing context is started, like \score inside \markup.
        """
        def __iter__(self):
            return self
            
        def next(self):
            token = next(tokens)
            while isinstance(token, (tokenizer.Space, tokenizer.Comment)):
                token = next(tokens)
            if token == "\\relative":
                relative()
                token = next(tokens)
            elif isinstance(token, tokenizer.ChordMode):
                absolute() # do not change chords
            elif isinstance(token, tokenizer.MarkupScore):
                absolute()
                token = next(tokens)
            return token
    
    source = gen()
    
    def consume():
        """ Consume tokens till the level drops (we exit a construct). """
        depth = tokenizer.depth()
        for token in source:
            yield token
            if tokenizer.depth() < depth:
                return
    
    def absolute():
        """ Consume tokens while not doing anything. """
        for token in consume():
            pass
    
    def relative():
        """ Consume the whole \relative expression without doing anything. """
        # skip pitch argument
        token = next(source)
        if isinstance(token, tokenizer.Pitch):
            token = next(source)
        if isinstance(token, tokenizer.OpenDelimiter):
            for token in consume():
                pass
        elif isinstance(token, tokenizer.OpenChord):
            while not isinstance(token, tokenizer.CloseChord):
                token = next(source)
    
    # Do it!
    startToken = None
    for token in source:
        if isinstance(token, tokenizer.OpenDelimiter):
            # Ok, parse current expression.
            startToken = token # before which to insert the \relative command
            lastPitch = None
            chord = None
            try:
                for token in consume():
                    # skip commands with pitches that do not count
                    if token in ('\\key', '\\transposition'):
                        next(source)
                    elif token == '\\transpose':
                        next(source)
                        next(source)
                    elif isinstance(token, tokenizer.OpenChord):
                        # Handle chord
                        chord = []
                    elif isinstance(token, tokenizer.CloseChord):
                        if chord:
                            lastPitch = chord[0]
                        chord = None
                    elif isinstance(token, tokenizer.Pitch):
                        # Handle pitch
                        p = Pitch.fromToken(token, tokenizer)
                        if p:
                            if lastPitch is None:
                                lastPitch = Pitch.c1()
                                lastPitch.octave = p.octave
                                if p.note > 3:
                                    lastPitch.octave += 1
                                changes.insert(startToken.pos,
                                    "\\relative {0} ".format(
                                        lastPitch.output(tokenizer.language)))
                            newPitch(token, p.relative(lastPitch))
                            lastPitch = p
                            # remember the first pitch of a chord
                            chord == [] and chord.append(p)
            except StopIteration:
                pass # because of the next(source) statements
    if startToken is None:  # no single expression converted?
        raise ly.NoMusicExpressionFound
    return changes

def languageAndKey(text):
    """
    Return language and key signature pitch (as Pitch) of text.
    """
    tokenizer = ly.tokenize.MusicTokenizer()
    tokens = iter(tokenizer.tokens(text))
    keyPitch = Pitch.c0()

    for token in tokens:
        if token == "\\key":
            for token in tokens:
                if not isinstance(token, (tokenizer.Space, tokenizer.Comment)):
                    break
            if isinstance(token, tokenizer.Pitch):
                p = Pitch.fromToken(token, tokenizer)
                if p:
                    keyPitch = p
                    keyPitch.octave = 0
    return tokenizer.language, keyPitch

def transpose(text, transposer, start = 0, changes = None):
    """
    Transpose all or selected pitches.
    Raises ly.QuarterToneAlterationNotAvailable if quarter tones are
    requested but not available in the current language.
    """
    tokenizer = ly.tokenize.MusicTokenizer()
    tokens = tokenizer.tokens(text)
    
    if changes is None:
        changes = ly.tokenize.ChangeList(text)
    
    class gen(object):
        """
        Advanced generator of tokens, discarding whitespace and comments,
        and automatically detecting \relative blocks and places where a new
        LilyPond parsing context is started, like \score inside \markup.
        
        It also handles transposition tasks that are the same in relative
        and absolute environments.
        """
        def __init__(self):
            self.inSelection = not start
            
        def __iter__(self):
            return self
            
        def next(self):
            while True:
                token = next(tokens)
                if isinstance(token, (tokenizer.Space, tokenizer.Comment)):
                    continue
                elif not self.inSelection and token.pos >= start:
                    self.inSelection = True
                # Handle stuff that's the same in relative and absolute here
                if token == "\\relative":
                    relative()
                elif isinstance(token, tokenizer.MarkupScore):
                    absolute(consume())
                elif isinstance(token, tokenizer.ChordMode):
                    chordmode()
                elif token == "\\transposition":
                    next(source) # skip pitch
                elif token == "\\transpose":
                    if self.inSelection:
                        for token in next(source), next(source):
                            if isinstance(token, tokenizer.Pitch):
                                transpose(token)
                    else:
                        next(source), next(source)
                elif token == "\\key":
                    token = next(source)
                    if self.inSelection and isinstance(token, tokenizer.Pitch):
                        transpose(token, 0)
                else:
                    return token
    
    source = gen()
    
    def consume():
        """ Consume tokens till the level drops (we exit a construct). """
        depth = tokenizer.depth()
        for token in source:
            yield token
            if tokenizer.depth() < depth:
                return
    
    def transpose(token, resetOctave = None):
        """ Transpose absolute pitch in token, must be tokenizer.Pitch """
        p = Pitch.fromToken(token, tokenizer)
        if p:
            transposer.transpose(p)
            if resetOctave is not None:
                p.octave = resetOctave
            changes.replaceToken(token, p.output(tokenizer.language))
    
    def relative():
        """ Called when \\relative is encountered. """
        def transposeRelative(token, lastPitch):
            """
            Make a new relative pitch from token, if possible.
            Return the last pitch used (absolute, untransposed).
            """
            p = Pitch.fromToken(token, tokenizer)
            if not p:
                return lastPitch
            # absolute pitch determined from untransposed pitch of lastPitch
            octaveCheck = p.octaveCheck is not None
            p.absolute(lastPitch)
            if source.inSelection:
                # we may change this pitch. Make it relative against the
                # transposed lastPitch.
                try:
                    last = lastPitch.transposed
                except AttributeError:
                    last = lastPitch
                # transpose a copy and store that in the transposed
                # attribute of lastPitch. Next time that is used for
                # making the next pitch relative correctly.
                copy = p.copy()
                transposer.transpose(copy)
                p.transposed = copy # store transposed copy in new lastPitch
                new = copy.relative(last)
                if octaveCheck:
                    new.octaveCheck = copy.octave
                if relPitchToken:
                    # we are allowed to change the pitch after the
                    # \relative command. lastPitch contains this pitch.
                    lastPitch.octave += new.octave
                    new.octave = 0
                    changes.replaceToken(relPitchToken[0], lastPitch.output(tokenizer.language))
                    del relPitchToken[:]
                changes.replaceToken(token, new.output(tokenizer.language))
            return p

        lastPitch = None
        relPitchToken = [] # we use a list so it can be changed from inside functions
        
        # find the pitch after the \relative command
        token = next(source)
        if isinstance(token, tokenizer.Pitch):
            lastPitch = Pitch.fromToken(token, tokenizer)
            if lastPitch and source.inSelection:
                relPitchToken.append(token)
            token = next(source)
        if not lastPitch:
            lastPitch = Pitch.c1()
        
        # eat stuff like \new Staff == "bla" \new Voice \notes etc.
        while True:
            if token in ('\\new', '\\context'):
                next(source) # skip context type
                token = next(source)
                if token == '=':
                    next(source) # skip context name
                    token = next(source)
            elif isinstance(token, tokenizer.NoteMode):
                token = next(source)
            else:
                break
        
        # now transpose the relative expression
        if isinstance(token, tokenizer.OpenDelimiter):
            # Handle full music expression { ... } or << ... >>
            for token in consume():
                if token == '\\octaveCheck':
                    token = next(source)
                    if isinstance(token, tokenizer.Pitch):
                        p = Pitch.fromToken(token, tokenizer)
                        if p:
                            if source.inSelection:
                                copy = p.copy()
                                transposer.transpose(copy)
                                p.transposed = copy
                                changes.replaceToken(token, copy.output(tokenizer.language))    
                            lastPitch = p
                            del relPitchToken[:]
                elif isinstance(token, tokenizer.OpenChord):
                    chord = [lastPitch]
                    for token in source:
                        if isinstance(token, tokenizer.CloseChord):
                            lastPitch = chord[:2][-1] # same or first
                            break
                        elif isinstance(token, tokenizer.Pitch):
                            chord.append(transposeRelative(token, chord[-1]))
                elif isinstance(token, tokenizer.Pitch):
                    lastPitch = transposeRelative(token, lastPitch)
        elif isinstance(token, tokenizer.OpenChord):
            # Handle just one chord
            for token in source:
                if isinstance(token, tokenizer.CloseChord):
                    break
                elif isinstance(token, tokenizer.Pitch):
                    lastPitch = transposeRelative(token, lastPitch)
        elif isinstance(token, tokenizer.Pitch):
            # Handle just one pitch
            transposeRelative(token, lastPitch)
        
    def chordmode():
        """ Called inside \\chordmode or \\chords. """
        for token in consume():
            if source.inSelection and isinstance(token, tokenizer.Pitch):
                transpose(token, 0)
            
    def absolute(tokens):
        """ Called when outside a possible \\relative environment. """
        for token in tokens:
            if source.inSelection and isinstance(token, tokenizer.Pitch):
                transpose(token)
    
    # Do it!
    absolute(source)
    return changes

def translate(text, lang, start = 0, changes = None):
    """
    Change the LilyPond pitch name language in our document to lang.
    Raises ly.QuarterToneAlterationNotAvailable if quarter tones are
    requested but not available in the target language.
    """
    tokenizer = ly.tokenize.Tokenizer()
    tokens = tokenizer.tokens(text)
    
    # Walk through not-selected text, to track the state and the 
    # current pitch language.
    if start:
        for token in tokens:
            if token.end >= start:
                break
    
    if changes is None:
        changes = ly.tokenize.ChangeList(text)

    writer = ly.pitch.pitchWriter[lang]
    reader = ly.pitch.pitchReader[tokenizer.language]
    
    # Now walk through the part that needs to be translated.
    includeCommandChanged = False
    for token in tokens:
        if isinstance(token, tokenizer.IncludeLanguageFile):
            reader = ly.pitch.pitchReader[tokenizer.language]
            changes.replaceToken(token, '"{0}.ly"'.format(lang))
            includeCommandChanged = True
        elif isinstance(token, tokenizer.PitchWord):
            result = reader(token)
            if result:
                note, alter = result
                # Write out the translated pitch.
                changes.replaceToken(token, writer(note, alter))
    return changes, includeCommandChanged