forked from jwdj/EasyABC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tune_actions.py
1920 lines (1613 loc) · 79.2 KB
/
tune_actions.py
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import unicode_literals
import re
import os
import sys
PY3 = sys.version_info.major > 2
from collections import namedtuple
from wx import GetTranslation as _
from tune_elements import *
try:
from html import escape # py3
except ImportError:
from cgi import escape # py2
try:
from urllib.parse import urlparse, urlencode, urlunparse, parse_qsl, quote # py3
from urllib.request import urlopen, Request, urlretrieve
from urllib.error import HTTPError, URLError
except ImportError:
from urlparse import urlparse, urlunparse, parse_qsl # py2
from urllib import urlencode, urlretrieve, quote
from urllib2 import urlopen, Request, HTTPError, URLError
from fractions import Fraction
from aligner import get_bar_length
from generalmidi import general_midi_instruments
from abc_tune import AbcTune
from abc_character_encoding import unicode_text_to_abc
if PY3:
basestring = str
def unicode(value):
return value
UrlTuple = namedtuple('UrlTuple', 'url content')
# determine if application is a script file or frozen exe
if getattr(sys, 'frozen', False):
application_path = os.path.dirname(sys.executable)
elif __file__:
application_path = os.path.dirname(__file__)
def path2url(path):
#url_path = urlparse.urljoin('file:', urllib.pathname2url(path))
#url_path = re.sub(r'(/[A-Z]:/)/', r'\1', url_path) # replace double slash after drive letter with single slash
#return url_path
return path # wx.HtmlWindow can only handle regular path-name and not file:// notation
def html_enclose(tag, content, attributes=None):
if attributes is None:
return u'<{0}>{1}</{0}>'.format(tag, content)
else:
attr_text = u''
for attribute in attributes:
value = attributes[attribute]
if value is None:
attr_text += ' {0}'.format(attribute)
else:
attr_text += ' {0}="{1}"'.format(attribute, value)
return u'<{0}{1}>{2}</{0}>'.format(tag, attr_text, content)
def html_enclose_attr(tag, attributes, content):
return html_enclose(tag, content, attributes)
def url_tuple_to_href(value):
if type(value) == UrlTuple:
return html_enclose_attr('a', { 'href': value.url }, value.content)
return value
def html_enclose_item(tag, item, attributes=None):
item = url_tuple_to_href(item)
return html_enclose(tag, item, attributes)
def html_enclose_items(tag, items, attributes=None):
items = url_tuple_to_href(items)
#if isinstance(items, CodeDescription):
# items = (html_enclose('code', escape(items.code)), escape(items.description))
if isinstance(items, (list, tuple)):
result = u''
for item in items:
result += html_enclose_item(tag, item, attributes)
elif isinstance(items, dict):
result = u''
for item in items:
result += html_enclose_items(tag, items[item], attributes)
else:
result = html_enclose_item(tag, items, attributes)
return result
def html_table(rows, headers=None, cellpadding=0, row_has_td=False, indent=0, width=None):
result = u''
if headers:
result = html_enclose_items('th', headers)
for row in rows:
if not row_has_td:
row = html_enclose_items('td', row, { 'nowrap': None, 'align': 'left' })
if indent:
row = html_enclose('td', '', { 'width': indent}) + row
result += html_enclose('tr', row)
attributes = { 'cellpadding': cellpadding, 'cellspacing': 0, 'border': 0, 'align': 'left'}
if width is not None:
attributes['width'] = width
return html_enclose_attr('table', attributes, result)
def html_image(image_name, description):
image_path = u'{0}/img/{1}.png'.format(application_path, image_name)
image_html = ''
if os.path.exists(image_path):
image_html = u'<img src="{0}" border="0" alt="{1}">'.format(path2url(image_path), description or '')
return image_html
class AbcAction(object):
def __init__(self, name, display_name=None, group=None):
self.name = name
if display_name:
self.display_name = display_name
else:
self.display_name = name
self.group = group
def can_execute(self, context, params=None):
return False
def execute(self, context, params=None):
pass
def get_action_html(self, context):
if self.can_execute(context):
html = u'<br>' + html_enclose_attr('a', { 'href': self.name }, escape(self.display_name))
return html
return u''
def get_action_url(self, params=None):
if params is None:
return self.name
else:
for param in list(params):
value = params[param]
if isinstance(value, basestring):
params[param] = value.encode('utf-8') # urlencode only accepts ascii
return '{0}?{1}'.format(self.name, urlencode(params))
class ValueChangeAction(AbcAction):
def __init__(self, name, supported_values, matchgroup=None, display_name=None, valid_sections=None, use_inner_match=False):
super(ValueChangeAction, self).__init__(name, display_name=display_name)
self.supported_values = supported_values
self.matchgroup = matchgroup
self.use_inner_match = use_inner_match
self.valid_sections = valid_sections
self.relative_selection = None
self.show_non_common = False
def can_execute(self, context, params=None):
show_non_common = params.get('show_non_common')
if show_non_common is not None:
return True
value = params.get('value', '')
return not self.is_current_value(context, value)
def is_current_value(self, context, value):
current_value = None
if self.matchgroup:
match = self.get_match(context)
if match:
current_value = match.group(self.matchgroup)
elif self.use_inner_match:
current_value = context.inner_text
else:
current_value = context.match_text
return value == current_value
def get_match(self, context):
if self.use_inner_match:
return context.inner_match
else:
return context.current_match
def get_tune_scope(self):
if self.use_inner_match:
return TuneScope.InnerText
else:
return TuneScope.MatchText
def execute(self, context, params=None):
show_non_common = params.get('show_non_common')
if show_non_common is not None:
self.show_non_common = show_non_common == 'True'
context.invalidate()
else:
value = params.get('value', '')
value = value.encode('latin-1').decode('utf-8')
context.replace_match_text(value, self.matchgroup, tune_scope=self.get_tune_scope())
if self.relative_selection is not None:
context.set_relative_selection(self.relative_selection)
def is_action_allowed(self, context):
valid_sections = self.valid_sections
if valid_sections is None and context.current_element:
valid_sections = context.current_element.valid_sections
if valid_sections is not None:
if isinstance(valid_sections, list):
if not context.abc_section in valid_sections:
return False
else:
if context.abc_section != valid_sections:
return False
match = self.get_match(context)
if match is None:
return False
elif self.matchgroup is not None:
try:
start = match.start(self.matchgroup)
except IndexError:
start = -1
if start == -1:
return False # don't show action if matchgroup not present in match
return True
def get_action_html(self, context):
result = u''
if not self.is_action_allowed(context):
return result
rows = []
if self.display_name:
row = html_enclose('b', escape(self.display_name))
row = self.add_options(row)
rows.append(row)
row = self.get_values_html(context)
rows.append(row)
return html_table(rows)
def get_values(self, context):
return self.supported_values
def contains_only_common(self, values):
for value in values:
if isinstance(value, ValueDescription):
if not value.common:
return False
elif not isinstance(value, basestring) and hasattr(value, '__iter__'):
if not self.contains_only_common(value):
return False
return True
def add_options(self, row):
only_common = self.contains_only_common(self.supported_values)
if only_common:
return row
else:
action_url = self.get_action_url({'show_non_common': not self.show_non_common})
if self.show_non_common:
url_tuple = UrlTuple(action_url, html_image('arrow-up', _('Less options')))
else:
url_tuple = UrlTuple(action_url, html_image('arrow-down', _('More options')))
return html_table([[row + ' ', url_tuple_to_href(url_tuple)]])
@staticmethod
def enclose_action_url(action_url, value):
if action_url is not None:
return UrlTuple(action_url, value)
return value
def get_columns_for_value(self, context, value, show_value_column, fixed_font=True):
columns = []
if isinstance(value, ValueDescription):
if value.common or self.show_non_common:
desc = escape(value.description)
params = {'value': value.value}
can = self.can_execute(context, params)
action_url = None
if can:
action_url = self.get_action_url(params)
if show_value_column:
if value.show_value: #isinstance(value, (CodeDescription, CodeImageDescription)):
columns.append(html_enclose('code', escape(value.value)))
else:
columns.append(html_enclose('code', ''))
if isinstance(value, ActionValue):
action_html = value.get_action_html()
if action_html:
columns.append(action_html)
else:
if isinstance(value, ValueImageDescription):
image_html = html_image(value.image_name, desc)
columns.append(self.enclose_action_url(action_url, image_html))
if can:
columns.append(self.enclose_action_url(action_url, desc))
else:
columns.append(self.html_selected_item(context, value.value, desc))
elif isinstance(value, list):
for v in value:
columns += self.get_columns_for_value(context, v, show_value_column, fixed_font=fixed_font)
else:
params = {'value': value}
desc = escape(value)
if fixed_font:
desc = html_enclose('code', desc)
if self.can_execute(context, params):
t = UrlTuple(self.get_action_url(params), desc)
columns.append(t)
else:
columns.append(desc) # self.html_selected_item(context, value, desc)
return columns
def get_values_html(self, context):
rows = []
show_value_column = False
values = self.get_values(context)
for value in values:
if isinstance(value, ValueDescription):
if value.show_value:
show_value_column = True
break
for value in values:
if isinstance(value, list):
values = value
row = []
for v in values:
columns = self.get_columns_for_value(context, v, show_value_column)
row += columns
if row:
rows.append(html_table([row], cellpadding=2))
else:
columns = self.get_columns_for_value(context, value, show_value_column)
if columns:
rows.append(tuple(columns))
result = html_table(rows, cellpadding=2, indent=20)
if result is None:
result = ''
return result
@staticmethod
def html_selected_item(context, value, description):
# if self.is_current_value(context, value):
# return html_enclose('b', description) # to make selected item bold
return description
class InsertValueAction(ValueChangeAction):
def __init__(self, name, supported_values, valid_sections=None, display_name=None, matchgroup=None):
super(InsertValueAction, self).__init__(name, supported_values, valid_sections=valid_sections, display_name=display_name, matchgroup=matchgroup)
self.caret_after_matchgroup = False
def can_execute(self, context, params=None):
value = params.get('value')
if value is None:
return super(InsertValueAction, self).can_execute(context, params)
else:
return True
def execute(self, context, params=None):
value = params.get('value')
if value is None:
super(InsertValueAction, self).execute(context, params)
else:
if self.matchgroup:
text = context.get_matchgroup(self.matchgroup)
text += value
context.replace_match_text(text, self.matchgroup, caret_after_matchgroup=self.caret_after_matchgroup)
else:
context.insert_text(value)
if self.relative_selection is not None:
context.set_relative_selection(self.relative_selection)
# class RemoveValueAction(AbcAction):
# def __init__(self, matchgroups=None):
# super(RemoveValueAction, self).__init__('remove_match', display_name=_('Remove'))
# self.matchgroups = matchgroups
#
# def can_execute(self, context, params=None):
# matchgroup = params.get('matchgroup', '')
# if self.matchgroups is not None:
# return matchgroup in self.matchgroups and context.get_matchgroup(matchgroup)
# else:
# return True
#
# def execute(self, context, params=None):
# matchgroup = params.get('matchgroup', '')
# context.replace_match_text('', matchgroup)
class ConvertToAnnotationAction(AbcAction):
def __init__(self):
super(ConvertToAnnotationAction, self).__init__('convert_to_annotation', display_name=_('Convert to annotation'))
self.matchgroup = 'text'
def can_execute(self, context, params=None):
chord = context.get_matchgroup('chordnote')
return chord is None or chord[0].lower() not in 'abcdefg'
def execute(self, context, params=None):
annotation = '^' + context.get_matchgroup(self.matchgroup)
context.replace_match_text(annotation, matchgroup=self.matchgroup)
class DirectiveChangeAction(ValueChangeAction):
def __init__(self, directive_name, name, supported_values, valid_sections=None, display_name=None, matchgroup=None):
super(DirectiveChangeAction, self).__init__(name, supported_values, valid_sections=valid_sections, display_name=display_name, matchgroup=matchgroup)
self.directive_name = directive_name
class ActionValue(ValueDescription):
def __init__(self, action_name, description='', common=True):
super(ActionValue, self).__init__(action_name, description, common=common, show_value=False)
self.action_name = action_name
def get_action_html(self):
html = html_enclose_attr('a', { 'href': self.action_name }, escape(self.description))
return html
##################################################################################################
# CHANGE ACTIONS
##################################################################################################
class AccidentalChangeAction(ValueChangeAction):
accidentals = [
CodeDescription('', _('No accidental')),
CodeDescription('=', _('Natural')),
CodeDescription('^', _('Sharp')),
CodeDescription('_', _('Flat')),
CodeDescription('^^', _('Double sharp'), common=False),
CodeDescription('__', _('Double flat'), common=False),
CodeDescription('^/', _('Half sharp'), common=False),
CodeDescription('_/', _('Half flat'), common=False),
CodeDescription('^3/2', _('Sharp and a half'), common=False),
CodeDescription('_3/2', _('Flat and a half'), common=False)
]
def __init__(self):
super(AccidentalChangeAction, self).__init__('change_accidental', AccidentalChangeAction.accidentals, matchgroup='accidental', display_name=_('Change accidental'))
class MeterChangeAction(ValueChangeAction):
values = [
CodeDescription('C', _('Common time (4/4)')),
CodeDescription('C|', _('Cut time (2/2)')),
CodeDescription('2/4', _('2/4')),
CodeDescription('3/4', _('3/4')),
CodeDescription('4/4', _('4/4')),
CodeDescription('6/4', _('6/4')),
CodeDescription('6/8', _('6/8')),
CodeDescription('9/8', _('9/8')),
CodeDescription('12/8', _('12/8'))
]
def __init__(self):
super(MeterChangeAction, self).__init__('change_meter', MeterChangeAction.values, use_inner_match=True, display_name=_('Change meter'))
class UnitNoteLengthChangeAction(ValueChangeAction):
values = [
CodeDescription('1/2', _('half note')),
CodeDescription('1/4', _('quarter note')),
CodeDescription('1/8', _('eighth note')),
CodeDescription('1/16', _('sixteenth note'))
]
def __init__(self):
super(UnitNoteLengthChangeAction, self).__init__('change_unit_note_length', UnitNoteLengthChangeAction.values, use_inner_match=True, display_name=_('Change note length'))
class TempoNoteLengthChangeAction(ValueChangeAction):
values = [
CodeDescription('3/4', _('three quarter note'), common=False),
CodeDescription('1/2', _('half note')),
CodeDescription('3/8', _('three eighth note'), common=False),
CodeDescription('1/4', _('quarter note')),
CodeDescription('1/8', _('eighth note')),
CodeDescription('1/16', _('sixteenth note'))
]
def __init__(self):
super(TempoNoteLengthChangeAction, self).__init__('change_tempo_note1_length', TempoNoteLengthChangeAction.values, matchgroup='note1', use_inner_match=True, display_name=_('Change note length'))
class TempoNote2LengthChangeAction(ValueChangeAction):
def __init__(self):
super(TempoNote2LengthChangeAction, self).__init__('change_tempo_note2_length', TempoNoteLengthChangeAction.values, matchgroup='note2', use_inner_match=True, display_name=_('Change second note length'))
class TempoNotationChangeAction(ValueChangeAction):
values = [
ValueDescription('name', _('Only name')),
ValueDescription('speed', _('Only speed')),
ValueDescription('name+speed', _('Name & speed')),
]
def __init__(self):
super(TempoNotationChangeAction, self).__init__('change_tempo_notation', TempoNotationChangeAction.values, display_name=_('Change tempo notation'))
def execute(self, context, params=None):
value = params.get('value')
if value is None:
super(TempoNotationChangeAction, self).execute(context, params)
else:
replacements = []
if value in ['name', 'name+speed']:
if not context.get_matchgroup('pre_text'):
replacements.append(('pre_text', '"Allegro"'))
else:
replacements.append(('pre_text', ''))
if value in ['speed', 'name+speed']:
if not context.get_matchgroup('metronome'):
replacements.append(('metronome', ' 1/4=120'))
else:
replacements.append(('metronome', ''))
context.replace_matchgroups(replacements)
def is_current_value(self, context, value):
has_name = context.get_matchgroup('pre_text')
has_speed = context.get_matchgroup('metronome')
current_value = None
if has_name:
if has_speed:
current_value = 'name+speed'
else:
current_value = 'name'
elif has_speed:
current_value = 'speed'
return value == current_value
class TempoNameChangeAction(ValueChangeAction):
values = [
ValueDescription('Larghissimo' , _('Larghissimo'), common=False),
ValueDescription('Grave' , _('Grave'), common=False),
ValueDescription('Lento' , _('Lento')),
ValueDescription('Largo' , _('Largo')),
ValueDescription('Adagio' , _('Adagio')),
ValueDescription('Adagietto' , _('Adagietto'), common=False),
ValueDescription('Andante' , _('Andante')),
ValueDescription('Andantino' , _('Andantino'), common=False),
ValueDescription('Moderato' , _('Moderato')),
ValueDescription('Allegretto' , _('Allegretto'), common=False),
ValueDescription('Allegro' , _('Allegro')),
ValueDescription('Vivace' , _('Vivace')),
ValueDescription('Presto' , _('Presto')),
ValueDescription('Prestissimo' , _('Prestissimo'), common=False),
]
def __init__(self):
super(TempoNameChangeAction, self).__init__('change_tempo_name', TempoNameChangeAction.values, matchgroup='pre_name', use_inner_match=True, display_name=_('Change tempo name'))
class PitchAction(ValueChangeAction):
pitch_values = [
ValueDescription('noteup', _('Note up')),
ValueDescription('notedown', _('Note down')),
ValueDescription("'", _('Octave up')),
ValueDescription(",", _('Octave down'))
]
all_notes = 'CDEFGABcdefgab'
def __init__(self):
super(PitchAction, self).__init__('change_pitch', PitchAction.pitch_values, display_name=_('Change pitch'))
def can_execute(self, context, params=None):
value = params.get('value')
if value is None:
return super(PitchAction, self).can_execute(context, params)
else:
note = context.get_matchgroup('note')
octave = context.get_matchgroup('octave')
note_no = self.octave_abc_to_number(note, octave)
if value == "'" or value == 'noteup':
return note_no < 4*7
elif value == ',' or value == 'notedown':
return note_no > -4*7
return False
def execute(self, context, params=None):
value = params.get('value')
if value is None:
super(PitchAction, self).execute(context, params)
else:
value = params.get('value')
note = context.get_matchgroup('note')
octave = context.get_matchgroup('octave')
note_no = self.octave_abc_to_number(note, octave)
if value == 'noteup':
note_no += 1
elif value == 'notedown':
note_no -= 1
elif value == "'":
note_no += 7
elif value == ',':
note_no -= 7
offset = 0
if note_no >= 7:
offset = 7
note = PitchAction.all_notes[(note_no % 7) + offset]
octave_no = note_no // 7
if octave_no > 1:
octave = "'" * (octave_no-1)
elif octave_no < 0:
octave = "," * -octave_no
else:
octave = ''
context.replace_matchgroups([('note', note), ('octave', octave)])
@staticmethod
def octave_abc_to_number(note, abc_octave):
result = PitchAction.all_notes.index(note)
if abc_octave:
for ch in abc_octave:
if ch == "'":
result += 7
elif ch == ',':
result -= 7
return result
class DurationAction(ValueChangeAction):
denominator_re = re.compile('/(\d*)')
def __init__(self, name, values):
super(DurationAction, self).__init__(name, values, display_name=_('Change duration'))
self.max_length_denominator = 128
self.max_length_numerator = 16
self.fraction_allowed = True
@staticmethod
def length_to_fraction(length):
result = Fraction(1, 1)
if length:
parts = length.split('/', 1)
numerator_part = parts[0].strip()
denominator_part = ''
if len(parts) > 1:
denominator_part = '/'+parts[1].strip()
if numerator_part:
result = Fraction(int(numerator_part), 1)
for m in DurationAction.denominator_re.finditer(denominator_part):
divisor = m.groups()[0]
if divisor:
divisor = int(divisor)
else:
divisor = 2
result = result * Fraction(1, divisor)
return result
@staticmethod
def is_power2(num):
return ((num & (num - 1)) == 0) and num != 0
def can_execute(self, context, params=None):
value = params.get('value')
if value is None:
return super(DurationAction, self).can_execute(context, params)
elif not value:
return context.get_matchgroup('pair') or context.get_matchgroup('length')
elif value == '1':
return context.get_matchgroup('length')
elif value == '-':
return context.get_matchgroup('rest') is None # a rest can not have a tie, chord and note can
elif value in '<>':
return True # not value in context.get_matchgroup('pair', '')
elif value in ['z', 'Z']:
return True
else:
frac = self.length_to_fraction(context.get_matchgroup('length'))
if value == '/':
if self.fraction_allowed:
return frac.denominator < self.max_length_denominator
else:
return frac.numerator > 1 and frac.numerator % 2 == 0
elif value in ['2', '+']:
return frac.numerator < self.max_length_numerator
elif value == '3':
return self.is_power2(frac.numerator) and self.is_power2(frac.denominator)
elif value == '=':
return frac.numerator > 1
def execute(self, context, params=None):
value = params.get('value')
if value is None:
super(DurationAction, self).execute(context, params)
elif not value:
context.replace_matchgroups([('length', ''), ('pair', '')])
elif value == 'Z':
match = context.get_matchgroup('rest')
new_value = None
if match == 'z':
new_value = 'Z'
elif match == 'x':
new_value = 'X'
if new_value:
context.replace_matchgroups([('rest', new_value), ('length', ''), ('pair', '')])
elif value == 'z':
match = context.get_matchgroup('rest')
new_value = None
if match == 'Z':
new_value = 'z'
elif match == 'X':
new_value = 'x'
if new_value:
context.replace_matchgroups([('rest', new_value), ('length', '')])
elif value == '1':
context.replace_matchgroups([('length', '')])
elif value in '/23+=':
frac = self.length_to_fraction(context.get_matchgroup('length'))
if value == '/':
frac *= Fraction(1, 2)
elif value == '2':
frac *= Fraction(2, 1)
elif value == '3':
frac *= Fraction(3, 2)
elif value == '+':
frac += 1
elif value == '=':
frac -= 1
if frac.numerator == 1:
text = ''
else:
text = str(frac.numerator)
if frac.denominator != 1:
if frac.denominator == 2:
text += '/'
elif frac.denominator == 4:
text += '//'
else:
text += '/{0}'.format(frac.denominator)
context.replace_match_text(text, matchgroup='length')
elif value in '<>':
current_value = context.get_matchgroup('pair', '')
if current_value == value:
new_value = value * 2
else:
new_value = value
context.replace_match_text(new_value, matchgroup='pair')
#if len(current_value) < 2 or current_value[0] != new_value[0]:
# context.set_relative_selection(-1)
elif value == '-':
if context.get_matchgroup('tie') == value:
context.replace_match_text('', matchgroup='tie')
else:
context.replace_match_text(value, matchgroup='tie')
class MeasureRestDurationAction(DurationAction):
values = [
ValueDescription('1', _('One measure')),
ValueDescription('2', _('Double measures')),
ValueDescription('/', _('Half measures')),
ValueDescription('+', _('Increase measures')),
ValueDescription('=', _('Decrease measures')),
CodeDescription('z', _('Normal rest'))
]
def __init__(self):
super(MeasureRestDurationAction, self).__init__('change_measurerest_duration', MeasureRestDurationAction.values)
self.max_length_denominator = 1
self.max_length_numerator = 64
self.fraction_allowed = False
class NoteDurationAction(DurationAction):
values = [
CodeDescription('', _('Default length')),
CodeDescription('/', _('Halve note length')),
CodeDescription('2', _('Double note length')),
CodeDescription('3', _('Dotted note')),
CodeDescription('>', _('This note dotted, next note halved')),
CodeDescription('<', _('This note halved, next note dotted')),
CodeDescription('-', _('Tie / untie'))
]
def __init__(self):
super(NoteDurationAction, self).__init__('change_note_duration', NoteDurationAction.values)
class RestDurationAction(DurationAction):
values = [
CodeDescription('', _('Default length')),
CodeDescription('/', _('Halve note length')),
CodeDescription('2', _('Double note length')),
CodeDescription('3', _('Dotted note')),
CodeDescription('>', _('This note dotted, next note halved')),
CodeDescription('<', _('This note halved, next note dotted')),
CodeDescription('Z', _('Whole measure'))
]
def __init__(self):
super(RestDurationAction, self).__init__('change_rest_duration', RestDurationAction.values)
class ChangeAnnotationAction(ValueChangeAction):
values = [
ValueDescription('"<(\u266f)"', _('Optional sharp')),
ValueDescription('"<(\u266e)"', _('Optional natural')),
ValueDescription('"<(\u266d)"', _('Optional flat')),
ValueDescription('"^rit."', _('Ritenuto')),
]
def __init__(self):
super(ChangeAnnotationAction, self).__init__('change_annotation', ChangeAnnotationAction.values, matchgroup='annotation', display_name=_('Change annotation'))
self.caret_after_matchgroup = True
class AnnotationPositionAction(ValueChangeAction):
values = [
CodeDescription('^', _('Above')),
CodeDescription('_', _('Below')),
CodeDescription('<', _('Left')),
CodeDescription('>', _('Right')),
CodeDescription('@', _('Auto'))
]
def __init__(self):
super(AnnotationPositionAction, self).__init__('change_annotation_position', AnnotationPositionAction.values, 'pos', display_name=_('Position'))
class BarChangeAction(ValueChangeAction):
values = [
CodeDescription('|', _('Bar line')),
CodeDescription('||', _('Double bar line')),
CodeDescription('|]', _('Thin-thick double bar line')),
CodeDescription('.|', _('Dotted bar'), common=False),
CodeDescription('[|', _('Thick-thin double bar line'), common=False),
CodeDescription('|:', _('Start of repeated section')),
CodeDescription(':|', _('End of repeated section')),
CodeDescription('|1', _('First ending')),
CodeDescription(':|2', _('Second ending')),
CodeDescription('::', _('Both end and start of repetition'), common=False),
CodeDescription('&', _('Voice overlay'), common=False),
CodeDescription('[|]', _('Invisible bar'), common=False)
]
def __init__(self):
super(BarChangeAction, self).__init__('change_bar', BarChangeAction.values, display_name=_('Change bar'))
class RestVisibilityChangeAction(ValueChangeAction):
values = [
CodeDescription('z', _('Visible')),
CodeDescription('x', _('Hidden')),
]
def __init__(self):
super(RestVisibilityChangeAction, self).__init__('change_rest_visibility', RestVisibilityChangeAction.values, 'rest', display_name=_('Visibility'))
class MeasureRestVisibilityChangeAction(ValueChangeAction):
values = [
CodeDescription('Z', _('Visible')),
CodeDescription('X', _('Hidden')),
]
def __init__(self):
super(MeasureRestVisibilityChangeAction, self).__init__('change_measurerest_visibility', MeasureRestVisibilityChangeAction.values, 'rest', display_name=_('Visibility'))
class AppoggiaturaOrAcciaccaturaChangeAction(ValueChangeAction):
values = [
CodeDescription('', _('Appoggiatura')),
CodeDescription('/', _('Acciaccatura')),
]
def __init__(self):
super(AppoggiaturaOrAcciaccaturaChangeAction, self).__init__('change_appoggiatura_acciaccatura', AppoggiaturaOrAcciaccaturaChangeAction.values, 'acciaccatura', display_name=_('Appoggiatura/acciaccatura'))
class KeyChangeAction(ValueChangeAction):
_mode_to_num = {
'': -2,
'm': +1,
'loc': +3,
'phr': +2,
'min': +1,
'dor': 0,
'mix': -1,
'maj': -2,
'lyd': -3
}
@staticmethod
def abc_mode_to_number(mode, default=None):
if mode is None:
return default
mode = mode[:3].lower()
return KeyChangeAction._mode_to_num.get(mode, default)
class KeySignatureChangeAction(KeyChangeAction):
values = [
ValueDescription( 6, _('6 sharps'), common=False),
ValueDescription( 5, _('5 sharps'), common=False),
ValueDescription( 4, _('4 sharps')),
ValueDescription( 3, _('3 sharps')),
ValueDescription( 2, _('2 sharps')),
ValueDescription( 1, _('1 sharp')),
ValueDescription( 0, _('0 sharps/flats')),
ValueDescription(-1, _('1 flat')),
ValueDescription(-2, _('2 flats')),
ValueDescription(-3, _('3 flats')),
ValueDescription(-4, _('4 flats')),
ValueDescription(-5, _('5 flats'), common=False),
ValueDescription(-6, _('6 flats'), common=False),
ValueDescription('none', _('None'), common=False),
]
def __init__(self):
super(KeySignatureChangeAction, self).__init__('change_key_signature', KeySignatureChangeAction.values, matchgroup='tonic', use_inner_match=True, display_name=_('Key signature'))
def is_action_allowed(self, context):
return True
def can_execute(self, context, params=None):
value = params.get('value')
if value is None:
return super(KeySignatureChangeAction, self).can_execute(context, params)
if context.inner_match is None:
return True
tonic = context.get_matchgroup('tonic')
value = params.get('value')
if value == 'none':
return tonic != value
else:
value = int(value)
middle_idx = len(key_ladder) // 2
try:
tonic_idx = key_ladder.index(tonic)
except ValueError:
return True
mode = context.get_matchgroup('mode')
mode_idx = self.abc_mode_to_number(mode)
if mode_idx is None:
return False
if tonic_idx >= 0 and mode_idx is not None:
current_value = tonic_idx - middle_idx - mode_idx
return current_value != value
else:
return True
def execute(self, context, params=None):
value = params.get('value')
if value is None:
super(KeySignatureChangeAction, self).execute(context, params)
elif value == 'none':
context.replace_match_text(value, tune_scope=TuneScope.InnerText)
else:
value = int(value)
middle_idx = len(key_ladder) // 2
new_value = middle_idx + value
mode = context.get_matchgroup('mode')
mode_idx = self.abc_mode_to_number(mode)
if mode_idx is None:
new_value -= 2 # assume major scale
tonic = key_ladder[new_value]
context.replace_match_text(tonic, tune_scope=TuneScope.InnerText)
else:
new_value += mode_idx
tonic = key_ladder[new_value]
context.replace_match_text(tonic, matchgroup='tonic')
class KeyModeChangeAction(KeyChangeAction):
values = [
ValueDescription(-2, _('Major (Ionian)')),
ValueDescription(1, _('Minor (Aeolian)')),
ValueDescription(0, _('Dorian'), common=False),
ValueDescription(-1, _('Mixolydian'), common=False),
ValueDescription(2, _('Phrygian'), common=False),
ValueDescription(-3, _('Lydian'), common=False),
ValueDescription(3, _('Locrian'), common=False)
]
def __init__(self):
super(KeyModeChangeAction, self).__init__('change_key_mode', KeyModeChangeAction.values, 'mode', use_inner_match=True, display_name=_('Mode'))
def is_action_allowed(self, context):
if context.inner_match is None:
return False
tonic = context.get_matchgroup('tonic')
return tonic in key_ladder
def can_execute(self, context, params=None):
value = params.get('value')
if value is None:
return super(KeyModeChangeAction, self).can_execute(context, params)
else:
tonic = context.get_matchgroup('tonic')
if tonic in key_ladder:
value = int(params.get('value'))
mode = context.get_matchgroup(self.matchgroup)
current_value = self.abc_mode_to_number(mode)
return value != current_value
else:
return False
def execute(self, context, params=None):
value = params.get('value')
if value is None:
super(KeyModeChangeAction, self).execute(context, params)