forked from jwdj/EasyABC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
easy_abc.py
8649 lines (7468 loc) · 387 KB
/
easy_abc.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
#!/usr/bin/python2.7
#
program_name = 'EasyABC 1.3.7.6 2016-11-12'
# Copyright (C) 2011-2014 Nils Liberg (mail: kotorinl at yahoo.co.uk)
# Copyright (C) 2015-2016 Seymour Shlien (mail: [email protected]), Jan Wybren de Jong (jw_de_jong at yahoo dot com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# V1.3.7.2
# - Note selection bug on OSX fixed
# - 'Add bar' type assist now has option automatic
#
# V1.3.7.1
# - Dutch translation
# - ABC assist improvements
#
# V1.3.7.0
# Incremental improvements and bug fixes.
#
# New V1.3.6.4
# - Recent files menu
# - Font from .svg file now rendered properly
# - Some fixes to accommodate 1.3.6.3 issues on the Mac.
# - On Windows the 'Input Processed Tune' window was not updated correctly (since 1.3.6.3)
# - Added an option to play a short introduction (count in) before the music is played.
# - Added volume controls for the guitar bass/chord accompaniment
# - Added to internals show output midi file (an advanced feature for debugging)
#
# New V1.3.6.3
# When the cursor moves outside the current page, the correct page is automatically chosen
# Unique filenames for midi and svg to prevent problems when multiple editor windows are used
# Preprocessing abc file and generating midi/svg split up
# Volume-settings still work even when the abc code contains %%MIDI program
# Music score can be zoomed in further
# MIDI file starts a little faster after pressing play on Windows OS
# Play button acts as pause button when tune is playing
# Fixed "Processed Abc Tune": no longer editable and uses fixed font now. Also resizing fixed.
# More text translatable
# Easier switching between different versions of executables by using dropdown button in File Settings tab
# Removed buttons 'Change abcm2ps path' and 'Restore abcm2ps path' because the default can be chosen in de File Settings tab
# Sometimes opening the messages window showed the 'processed tune' window
# Added beats/minute controlled to the toolbar
# Changed Internals->Messages to fixed font so Abcm2ps-messages with a ^ make sense
#
#
# New V1.3.6.2
# EasyAbc now supports the abcm2ps voicecolor command which has been
# introduced in version 8.5 and higher. There have been other changes
# which improve the performance of the svg rendering functions.
#
#
# New V1.3.6.1
# Added settings/cold restart
# Eliminated path_ps2pdf settings option
# Checked the values of some of the page settings (for abcm2ps)
# Rearranged settings in Abc Settings NoteBook
# New in V1.3.6
# Reworking the internals/Messages.
# To make the abc file settings more transparent, they now show the
# default settings if the executables are found. However
# if you make them blank, the next time easyabc starts, it will
# set them to the defaults provided the executabls exist.
# The voice/channel settings is now a separate page in the
# abc settings tabbed book.
# Eliminated hash code from cached abc,svg,midi temp files.
# Added tools/search which searches recursively all abc files
# in a folder for a tune containing a specific word in the title.
# A list of all tunes found is shown in a listbox and clicking
# anyone of those tunes will automatically load the file.
# Added option to set the gchord pattern in the Abc Settings
# Changed the call sequence to AbcToSvg so that it is more compact.
# Added abcm2ps page in abc settings. The page provides an
# option to include bar line numbering in the music output.
# Added a status bar which is used to report any problems that
# are detected when processing a tune.
# The popup Error Messages have been suppressed. The user needs
# to go to the Internals/messages menu item to view the problems.
# A progress bar appears for operations that take a long time
# -- for example exporting a large collection of tunes to midi
# files. The user has the option of cancelling in the middle.
# Upgraded the xml modules (abc2xml.py-??, xml2abc.py-?? and
# xml2abc_interface) to the latest versions developed by Wim Vree.
# Added to the Internals menu, Show settings status function.
# Added Settings/Cold restart/ an option to put EasyAbc in
# the state as if it is running for the first time. The settings.1.3.dat
# file will be recreated with the initial settings.
#
# New in V1.3.5_p09 patch.
# On startup the program checks that the abc settings are consistent.
# The path to ghostscript and /or ps2pdf can be specified by the
# user. If the path to ps2pdf is specified, that program will be
# used to create the pdf file from the PostScript file.
# The abc settings dialog box has been replaced with a tabbed
# notebook leaving more space for more user options to be introduced
# in future versions of this program.
# Upgraded to abc2xml_v61 and xml2abc_v52.
# If midiplayer is defined in abc settings, that player will be used.
# Added 'internals' to the top menu for viewing some of the
# internals of the program. Internals/messages displays the warnings
# and error messages returned by abc2midi and other applications.
# Internals/input processed tune displays the abc file actually
# given to abc2midi or other applications so that line numbers
# can be matched with the warnings.
#
#
# New in V1.3.5_p08 patch.
# The music panel representation now responds to moving the cursor using
# arrow keys in the edit panel.
# Fixed a problem in playing a tune (converting to MIDI) when the
# tune has non ascii characters. (reported by Chuck Boody)
# The F7 key will stop playing MIDI music.
# Included a new application abccore.py which runs separately
# from easy_abc.py. It was created by Seymour Shlien and is in
# still in development.
#
# New in V1.3.5_p07 patch
# Add option to be able to set different instrument for each midi voice (request from Chuck Boody)
# Add option to be able to set volume and balance for each midi voice (request from Chuck Boody)
# Add option to have default instrument for all voices (previous behaviour)
# Remove experimental mention concerning abc2xml (request from Chuck Boody)
# Fix the fact that on MacOS X guitar chord are always played if the are define in another voice than voice 1 (reported by Chuck Boody)
# Try to reduce glitch while looping playback if double-click on play button
#
# New in V1.3.5_p06 patch
# upgrade to version 54 of abc2xml
# upgrade to version 2014-02-05 of abcMIDI (abc2abc and abc2midi)
# upgrade to version 7.7.1 of abcm2ps
# fixed alarm regarding musicxml file when imported in Finale (reported by Chuck Boody) need to verify with other software
# fixed bug: Easy_abc manages svg files created with version 7.6.5 and later for width/height (reported by Frederic Aupepin)
# increase size of line for staff lines, bar lines, and note stems (patch from Seymour)
#
# New in V1.3.5_p05 patch
# upgrade to version 2013-03-26 of abcMIDI (abc2abc and abc2midi)
# upgrade to version 7.5.2 of abcm2ps
# upgrade to version 50 of xml2abc
#
# New in V1.3.5_p04 patch
# fixed bug: note selection from tune with abcm2ps version 7.2.0 and later (reported by Chuck Boody)
#
# New in V1.3.5_p03 patch
# add an export all to individual pdf files (request from Chuck Boody)
#
# New in V1.3.5_p02 patch
# add an export all for midi (request from Chuck Boody)
# fixed bug: syntax highlighting ']' in comments (reported by Frederic Aupepin)
#
# New in V1.3.5_p01 patch
# fixed bug: syntax highlighting with lyrics (reported by Chuck Boody)
#
# All other changes from V1.3 to V1.3.5 are described in changes.txt
# which comes with the source code.
# Table of Contents
# ---------------------------------
#Global:
# str2fractions(), calc_tune_id(), read_text_if_file_exists(),
# get_ghostscript_path(), upload_tune(), get_default_path_for_executable(),
# launch_file(), remove_non_note_fragments(), get_notes_from_abc(),
# copy_bar_symbols_from_first_voice(), process_MCM(), get_hash_code(),
# change_abc_tempo(), add_table_of_contents_to_postscript_file(),
# sort_abc_tunes(), process_abc_code(), AbcToPS, GetSvgFileList(),
# AbcToSvg(), AbcToAbc(), MidiToMftext(),
# AbcToPDF(), test_for_guitar_chords(), list_voices_in(),
# grab_time_signature(), drum_intro(), need_left_repeat(),
# make_abc_introduction(), AbcToMidi(), process_abc_for_midi(),
# add_abc2midi_options(), str2bool(), fix_boxmarks(),
# change_texts_into_chords(), NWCToXml(), frac_mod()
#class AbcTune()
# abc_code()
#class MidiTune()
# cleanup()
#class SvgTune()
# render_page(),clear_pages(),cleanup(),page_count()
#class MusicPrintout()
# HasPage(), GetPageInfo(), OnPrintPage()
#class MusicUpdateDoneEvent()
#class MusicUpdateThread()
# run(), ConvertAbcToSvg(), abort()
# frac_mod(), start_process()
#class MidiThread()
# run(), play_midi, clear_queue, queue_task
# abort, is_busy()
#class RecordThread()
# timedelta_microseconds(), beat_duration(), run(), quantize_swinged_16th(),
# quantize_triplet(), quantize(), abort()
#class IncipitsFrame()
# GrayUngray(), OnTwoColumns(), save_settings(), OnOk(), OnCancel()
#class MyNoteBook()
#class AbcFileSettingsFrame()
# OnBrowse(), OnChangePath(), change_path_for_control(), On_Chk_IncludeHeader()
# OnPath_midiplayer(), OnRestoreSettings()
# append_exe(), keep_existing_paths(), get_default_path()
#class MyChordPlayPage()
# OnPlayChords(), OnNodynamics(), OnNofermatas(), OnNograce(), OnBarfly()
# OnMidiIntro(), OnMidi_Program(), On_midi_chord_program(),
# On_midi_bass_program, SetGchordChoices(), OnGchordSelection(),
# OnBeatsPerMinute(), OnTranspose(), OnTuning(), OnChordVol(), OnBassVol()
#class MyVoicePage()
# OnProgramSelection(), OnSliderScroll(), OnResetDefault()
#class MyAbcm2psPage()
# OnAbcm2psClean(), OnAbcm2psDefaults(), OnAbcm2psBar()
# OnAbcm2pslyrics(), OnAbcm2psref(), OnAbcm2psend()
# OnPSScale(), OnPSleftmarg(), OnPSrightmarg(),
# OnPStopmarg(), OnPSbotmarg(), OnPSpagewidth(),
# OnPSpageheight(), OnFormat(), On_extra_params(),
# OnBrowse_format()
#class MyXmlPage()
# OnXmlPage(), OnXmlCompressed(), OnXmlUnfold(), OnXmlMidi()
# OnVolta(), OnMaxbars(), OnMaxchrs(), OnCreditval(), OnUnitval()
#class MidiSettingsFrame()
# OnOk(), OnCancel()
#class MidiOptionsFrame()
# OnOk(), OnCancel()
#class ErrorFrame()
# OnKeyDownEvent(), OnOk(), OnCancel()
#class ProgressFrame()
# SetPercent()
#class FlexibleListCtrl()
# GetListCtrl(), GetSortImages(), getColumnText(), GetSecondarySortValues()
#class MySearchFrame()
# On_browse_abcsearch(), On_start_search(), find_abc_files(),
# find_abc_string(),OnItemSelected()
#class MyHtmlFrame()
#class MyOpenPopupMenu()
#class MainFrame()
# OnPageSetup(),OnPrint(),OnPrintPreview(),GetAbcToPlay(),
# parse_desc(), get_num_extra_header_lines(),OnNoteSelectionChangeDesc(),
# transpose_selected_note(), OnResetView(), OnSettingsChanged(),
# OnToggleMusicPaneMaximize(), OnMouseWheel(), update_playback_rate()
# OnBpmSlider(), OnBpmSliderClick(), start_midi_out(),
# do_load_media_file(), OnMediaLoaded(),
# OnMediaStop(), OnMediaFinished(), OnToolRecord(),
# OnToolStop(), OnSeek(), OnZoomSlider(), OnPlayTimer(),
# OnRecordBpmSelected(), OnRecordMetreSelected(), flip_toolbar(),
# setup_toolbar(), OnRecordStop(), OnDoReMiModeChange(),
# generate_incipits_abc(), OnGenerateIncipits(), OnViewIncipits()
# OnSortTunes(), OnRenumberTunes(), OnSearchDirectories(),
# OnUploadTune(), OnGetFileNameForTune(), OnExportMidi(),
# OnExportAllMidi(), OnExportAllPDFFiles(), OnExportPDF()
# OnExportSVG(), OnExportMusicXML(), OnExportAllMusicXML(),
# OnExportHTML(), OnExportAllHTML(), createArchive(),
# OnExportAllEpub(), OnExportAllPDF(),
# OnMusicPaneDoubleClick(), OnMusicPaneKeyDown(), OnRightClickList(),
# OnInsertSymbol(), OnToolPlay(), OnToolPlayLoop(),
# OnToolRefresh(), OnToolAbcAssist(), UpdateAbcAssistSetting(),
# __onPaneClose(), OnToolAddTune(), OnToolDynamics(),
# OnToolOrnamentation(), OnToolDirections(), CanClose(),
# OnNew(), OnOpen(), OnImport(), get_encoding(),
# load_or_import(), load(), ask_save(), save(),
# save_as(), AbcToAbcCurrentTune(), OnHaveL(), OnDoubleL(),
# OnTranspose(), OnAlignBars(), create_symbols_popup_menu(),
# create_menu_bar(), create_menu(), append_menu_item()
# create_upload_context_menu(), setup_typing_assistance_menu(),
# setup_menus(), OnShowMessages(), ShowMessages(), OnShowAbcTune(),
# OnCloseFile(), OnSave(), OnSaveAs(), OnQuit(),
# do_command(), OnUndo(), OnRedo(), OnCut(), OnCopy(),
# OnPaste(), OnDelete(), OnSelectAll(), OnFind(),
# OnReplace, OnFindClose(), get_scintilla_find_flags(),
# OnFindReplace(), OnFindReplaceAll(), OnFindNextABC(),
# OnFindNext(), OnAbout(), OnEasyABCHelp(), OnABCStandard(),
# OnABCLearn(), OnAbcm2psHelp(), OnClearCache(), OnMidiSettings(),
# OnAbcSettings(), OnChangeFont(), OnViewFieldReference(),
# OnFieldReferenceItemDClick(), OnUseDefaultFont(),
# ScrollMusicPaneToMatchEditor(), OnMovedToDifferentLine(),
# AutoInsertXNum(), DoReMiToNote(), OnCharEvent(),
# FixNoteDurations(), AddTextWithUndo(), OnKeyDownEvent(),
# StartKeyboardInputMode(), OnEditorMouseRelease(),
# OnPosChanged(), OnModified(), AutomaticUpdate(),
# OnChangeText(), GrayUnGray(), OnUpdate(), OnClose(),
# DetermineMidiPlayRange(), PlayMidi(), GetTextPositionOfTune()
# OnTuneListClick(), SetErrorMessage(), OnPageSelected(),
# UpdateMusicPane(), OnMusicUpdateDone(), GetTextRangeOfTune()
# GetFileHeaderBlock(), GetSelectedTune(), GetTune(),
# OnTuneDoubleClicked(), OnTuneSelected(), UpdateTuneList()
# UpdateTuneListVisibility(), OnTimer(), GetTunes(),
# GetTuneAbc(), InitEditor(), OnDropFile(), update_statusbar_and_messages()
# handle_midi_conversion(), OnReducedMargins(), load_settings(),
# save_settings(), restore_settings()
#class MyFileDropTarget()
#class AboutFrame()
#class MyInfoFrame()
# ShowText(), update_text()
#class MyAbcFrame()
# ShowText(), update_text()
#class MyMidiTextTree
# LoadMidiData
#class MyApp()
# CheckCanDrawSharpFlat(), NewMainFrame(), UnRegisterFrame(),
# GetAllFrames(), MacOpenFile(), OnInit(),
# # for finding memory leaks uncomment following two lines
# import gc
# gc.set_debug(gc.DEBUG_LEAK)
#
# # for finding segmentation fault or bus error (pip install faulthandler)
# try:
# import faulthandler # pip install faulthandler
# faulthandler.enable()
# except ImportError:
# print('faulthandler not installed. Try: pip install faulthandler')
# pass
import sys
PY3 = sys.version_info.major > 2
abcm2ps_default_encoding = 'utf-8' ## 'latin-1'
import codecs
utf8_byte_order_mark = codecs.BOM_UTF8 # chr(0xef) + chr(0xbb) + chr(0xbf) #'\xef\xbb\xbf'
if PY3:
unichr = chr
xrange = range
def unicode(s):
return s
max_int = sys.maxsize
basestring = str
else:
max_int = sys.maxint
import os, os.path
import wx
if os.getenv('EASYABCDIR'):
cwd = os.getenv('EASYABCDIR')
else:
cwd = os.getcwd()
if os.path.isabs(sys.argv[0]):
cwd = os.path.dirname(sys.argv[0])
# 1.3.6.3 [JWDJ] 2015-04-27 On Windows replace forward slashes with backslashes
if wx.Platform == "__WXMSW__":
cwd = cwd.replace('/', '\\')
sys.path.append(cwd)
import re
import subprocess
import hashlib
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
try:
import pickle as pickle # py3
except ImportError:
import cPickle as pickle # py2
import threading
import shutil
import platform
import webbrowser
import time
import traceback
# import xml.etree.cElementTree as ET # 1.3.7.4 [JWdJ] 2016-06-30
import zipfile
from datetime import datetime
from collections import deque, namedtuple, defaultdict
from io import StringIO
from wx.lib.scrolledpanel import ScrolledPanel
import wx.html
import wx.stc as stc
import wx.lib.agw.aui as aui
import wx.lib.rcsizer as rcs
# import wx.lib.filebrowsebutton as filebrowse # 1.3.6.3 [JWdJ] 2015-04-22
import wx.media
import wx.lib.platebtn as platebtn
import wx.lib.mixins.listctrl as listmix
import wx.lib.agw.hypertreelist as htl
from wx.lib.embeddedimage import PyEmbeddedImage
# from wx.lib.expando import ExpandoTextCtrl, EVT_ETC_LAYOUT_NEEDED # 1.3.7.3 [JWdJ] 2016-04-09
from wx import GetTranslation as _
from wxhelper import *
##from xml2abc_nils import xml_to_abc
from xml2abc_interface import xml_to_abc, abc_to_xml
from midi2abc import midi_to_abc, Note, duration2abc
# from midi_meta_data import midi_to_meta_data # 1.3.6.3 [JWdJ] 2015-04-22
from generalmidi import general_midi_instruments
# from ps_parser import Abcm2psOutputParser # 1.3.6.3 [JWdJ] 2015-04-22
from abc_styler import ABCStyler
from abc_character_encoding import decode_abc, abc_text_to_unicode
# from abc_character_encoding import encode_abc # 1.3.7.3 [JWdJ] 2016-04-09
from abc_search import abc_matches_iter
from fractions import Fraction
from music_score_panel import MusicScorePanel
from svgrenderer import SvgRenderer
import itertools
from aligner import align_lines, extract_incipit, bar_sep, bar_sep_without_space, get_bar_length, bar_and_voice_overlay_sep
##from midi_processing import humanize_midi
if PY3:
from queue import Queue # 1.3.6.2 [JWdJ] 2015-02
else:
from Queue import Queue # 1.3.6.2 [JWdJ] 2015-02
if wx.Platform == "__WXMSW__":
import win32api
import win32process
try:
if wx.Platform == "__WXMAC__":
import pygame.midi as pypm
pypm.init()
else:
import pygame
import pygame.pypm as pypm
pypm.Initialize()
except ImportError:
try:
import pypm
except ImportError:
sys.stderr.write('Warning: pygame/pypm module not found. Recording midi will not work')
def str2fraction(s):
parts = [int(x.strip()) for x in s.split('/')]
return Fraction(parts[0], parts[1])
Tune = namedtuple('Tune', 'xnum title rythm offset_start offset_end abc header num_header_lines')
MidiNote = namedtuple('MidiNote', 'start stop indices page svg_row')
class AbortException(Exception): pass
class Abcm2psException(Exception): pass
class NWCConversionException(Exception): pass
from abc_tune import AbcTune
def ensure_file_name_does_not_exist(file_path):
if not os.path.exists(file_path):
return file_path
i = 0
file_exists = True
path, file_name = os.path.split(file_path)
name, extension = os.path.splitext(file_name)
while file_exists:
i += 1
file_path = os.path.abspath(os.path.join(path, "{0}({1}){2}".format(name, i, extension)))
file_exists = os.path.exists(file_path)
return file_path
def generate_temp_file_name(path, ending, replace_ending=None):
i = 0
file_exists = True
while file_exists:
file_name = os.path.abspath(os.path.join(path, "temp{0:02d}{1}".format(i, ending)))
file_exists = os.path.exists(file_name)
if not file_exists and replace_ending is not None:
f = os.path.abspath(os.path.join(path, "temp{0:02d}{1}".format(i, replace_ending)))
file_exists = os.path.exists(f)
i += 1
return file_name
# 1.3.6.3 [JWdJ] 2015-04-22
class MidiTune(object):
""" Container for abc2midi-generated .midi files """
def __init__(self, abc_tune, midi_file=None, error=None):
self.error = error
self.midi_file = midi_file
self.abc_tune = abc_tune
def cleanup(self):
if self.midi_file:
if os.path.isfile(self.midi_file):
os.remove(self.midi_file)
self.midi_file = None
# 1.3.6.2 [JWdJ]
class SvgTune(object):
""" Container for abcm2ps-generated .svg files """
def __init__(self, abc_tune, svg_files, error=None):
self.error = error
self.svg_files = svg_files
self.pages = {}
self.abc_tune = abc_tune
def render_page(self, page_index, renderer):
if 0 <= page_index < self.page_count:
page = self.pages.get(page_index, None)
if page is None:
page = renderer.svg_to_page(open(self.svg_files[page_index], 'rb').read())
page.index = page_index
self.pages[page_index] = page
else:
page = renderer.empty_page
return page
def cleanup(self):
for f in self.svg_files:
if os.path.isfile(f):
os.remove(f)
self.svg_files = ()
def is_equal(self, svg_tune):
if not isinstance(svg_tune, SvgTune):
return False
return self.abc_tune and self.abc_tune.is_equal(svg_tune.abc_tune)
@property
def page_count(self):
return len(self.svg_files)
@property
def first_note_line_index(self):
if self.abc_tune:
return self.abc_tune.first_note_line_index
return -1
@property
def tune_header_start_line_index(self):
if self.abc_tune:
return self.abc_tune.tune_header_start_line_index
return -1
@property
def x_number(self):
if self.abc_tune:
return self.abc_tune.x_number
return -1
# 1.3.6.3 [JWdJ] 2015-04-22
class AbcTunes(object):
""" A holder for created tunes. Takes care of proper cleanup. """
def __init__(self, cache_size=1):
self.__tunes = {}
self.cache_size = cache_size
self.cached_tune_ids = deque()
def get(self, tune_id):
tune = self.__tunes.get(tune_id, None)
return tune
def add(self, tune):
if tune.abc_tune and self.cache_size > 0:
tune_id = tune.abc_tune.tune_id
#if tune_id in self.__tunes:
# print 'tune already cached'
while len(self.cached_tune_ids) >= self.cache_size:
old_tune_id = self.cached_tune_ids.pop()
self.remove(old_tune_id)
self.__tunes[tune_id] = tune
self.cached_tune_ids.append(tune_id)
def cleanup(self):
for tune_id in list(self.__tunes):
self.remove(tune_id)
self.__tunes = {}
def remove(self, tune_id):
tune = self.__tunes[tune_id]
if tune is not None:
tune.cleanup()
del self.__tunes[tune_id]
#global variables
all_notes = "C,, D,, E,, F,, G,, A,, B,, C, D, E, F, G, A, B, C D E F G A B c d e f g a b c' d' e' f' g' a' b' c'' d'' e'' f'' g'' a'' b''".split()
doremi_prefixes = 'DRMFSLTdrmfslt' # 'd' corresponds to "do", 'r' to "re" and so on, DO vs. do is like C vs. c in ABC
doremi_suffixes = 'oeiaoaioOEIAOAIOlLhH'
execmessages = u''
visible_abc_code = u''
line_end_re = re.compile('\r\n|\r|\n')
tune_index_re = re.compile(r'^X:\s*(\d+)')
def text_to_lines(text):
return line_end_re.split(text)
# 1.3.6.3 [JWDJ] one function to determine font size
def get_normal_fontsize():
if wx.Platform == "__WXMSW__":
font_size = 10
else:
font_size = 14
return font_size
def frac_mod(fractional_number, modulo):
return fractional_number - modulo * int(fractional_number / modulo)
def start_process(cmd):
""" Starts a process
:param cmd: tuple containing executable and command line parameter
:return: nothing
"""
global execmessages # 1.3.6.4 [SS] 2015-05-27
# 1.3.6.4 [SS] 2015-05-01
if wx.Platform == "__WXMSW__":
creationflags = win32process.DETACHED_PROCESS
else:
creationflags = 0
# 1.3.6.4 [SS] 2015-05-27
#process = subprocess.Popen(cmd,shell=False,stdin=None,stdout=subprocess.PIPE,stderr=subprocess.PIPE,close_fds=True,creationflags=creationflags)
process = subprocess.Popen(cmd,shell=False,stdin=None,stdout=subprocess.PIPE,stderr=subprocess.PIPE,creationflags=creationflags)
stdout_value, stderr_value = process.communicate()
execmessages += '\n'+stderr_value + stdout_value
return
def get_output_from_process(cmd, input=None, creationflags=None, cwd=None, bufsize=0, encoding='utf-8', errors='strict', output_encoding=None):
stdin_pipe = None
if input is not None:
stdin_pipe = subprocess.PIPE
if isinstance(input, basestring):
input = input.encode(encoding, errors)
if creationflags is None:
if wx.Platform == "__WXMSW__":
creationflags = win32process.CREATE_NO_WINDOW
else:
creationflags = 0
process = subprocess.Popen(cmd, stdin=stdin_pipe, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=creationflags, cwd=cwd, bufsize=bufsize)
stdout_value, stderr_value = process.communicate(input)
returncode = process.returncode
if output_encoding is None:
output_encoding = encoding
stdout_value, stderr_value = stdout_value.decode(output_encoding, errors), stderr_value.decode(output_encoding, errors)
return stdout_value, stderr_value, returncode
def read_text_if_file_exists(filepath):
''' reads the contents of the given file if it exists, otherwise returns the empty string '''
if filepath and os.path.exists(filepath):
return open(filepath, 'rb').read()
else:
return ''
def show_in_browser(url):
handle = webbrowser.get()
handle.open(url)
def get_default_path_for_executable(name):
if wx.Platform == "__WXMSW__":
exe_name = '{0}.exe'.format(name)
else:
exe_name = name
path = os.path.join(cwd, 'bin', exe_name)
if wx.Platform == "__WXGTK__":
if not os.path.exists(path):
path = '/usr/local/bin/{0}'.format(name)
if not os.path.exists(path):
path = '/usr/bin/{0}'.format(name)
return path
# p09 2014-10-14 [SS]
def get_ghostscript_path():
''' Fetches the ghostscript path from the windows registry and returns it.
This function may not see the 64-bit ghostscript installations, especially
if Python was compiled as a 32-bit application.
'''
if PY3:
import winreg
else:
import _winreg as winreg
available_versions = []
for reg_key_name in [r"SOFTWARE\\GPL Ghostscript", r"SOFTWARE\\GNU Ghostscript"]:
try:
aReg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
aKey = winreg.OpenKey(aReg, reg_key_name)
for i in range(100):
try:
version = winreg.EnumKey(aKey,i)
bKey = winreg.OpenKey(aReg, reg_key_name + "\\%s" % version)
value, _ = winreg.QueryValueEx(bKey, 'GS_DLL')
winreg.CloseKey(bKey)
path = os.path.join(os.path.dirname(value), 'gswin32c.exe')
if os.path.exists(path):
available_versions.append((version, path))
path = os.path.join(os.path.dirname(value), 'gswin64c.exe')
if os.path.exists(path):
available_versions.append((version, path))
except EnvironmentError:
break
winreg.CloseKey(aKey)
except:
pass
if available_versions:
return sorted(available_versions)[-1][1] # path to the latest version
else:
return None
browser = None
def upload_tune(tune, author):
''' upload the tune to the site ABC WIKI site folkwiki.se (this UI option is only visible if the OS language is Swedish) '''
global browser
import mechanize
import tempfile
tune = tune.replace('\r\n', '\n')
text = '(:music:)\n%s\n(:musicend:)\n' % tune.strip()
if not browser:
browser = mechanize.Browser()
response = browser.open('http://www.folkwiki.se/Meta/Nyl%c3%a5t?n=Meta.Nyl%c3%a5t&base=Musik.Musik&action=newnumbered')
response = response.read()
import pdb; pdb.set_trace()
m = re.search(r"img src='(.*?action=captchaimage.*?)'", response)
if m:
captcha_url = m.group(1).encode('utf-8')
f = tempfile.NamedTemporaryFile(delete=False)
img_path = f.name
# print(captcha_url)
# print(img_path)
img_data = urlopen(captcha_url).read()
urlretrieve(urlunparse(parsed), outpath)
# print(img_data)
f.write(img_data)
f.close()
return ''
browser.select_form(nr=1)
browser['text'] = text.encode('utf-8')
browser['author'] = author.encode('utf-8')
response = browser.submit()
url = response.geturl()
url = url.split('?')[0] # remove the part after the first '?'
return url
def launch_file(filepath):
''' open the given document using its associated program '''
if wx.Platform == "__WXMSW__":
os.startfile(filepath)
elif wx.Platform == "__WXMAC__":
subprocess.call(('open', filepath))
elif os.name == 'posix':
subprocess.call(('xdg-open', filepath))
return True
def remove_non_note_fragments(abc, exclude_grace_notes=False):
''' remove parts of the ABC which is not notes or bar symbols by replacing them by spaces (in order to preserve offsets) '''
repl_by_spaces = lambda m: ' ' * len(m.group(0))
# replace non-note fragments of the text by replacing them by spaces (thereby preserving offsets), but keep also bar and repeat symbols
abc = abc.replace('\r', '\n')
abc = re.sub(r'(?s)%%beginps.+?%%endps', repl_by_spaces, abc) # remove embedded postscript
abc = re.sub(r'(?s)%%begintext.+?%%endtext', repl_by_spaces, abc) # remove text
abc = re.sub(r'(?m)%.*$', repl_by_spaces, abc) # remove comments
abc = re.sub(r'\[\w:.*?\]', repl_by_spaces, abc) # remove embedded fields
abc = re.sub(r'(?m)^\w:.*?$', repl_by_spaces, abc) # remove normal fields
abc = re.sub(r'\\"', repl_by_spaces, abc) # remove escaped quote characters
abc = re.sub(r'".*?"', repl_by_spaces, abc) # remove strings
abc = re.sub(r'!.+?!', repl_by_spaces, abc) # remove ornaments like eg. !pralltriller!
abc = re.sub(r'\+.+?\+', repl_by_spaces, abc) # remove ornaments like eg. +pralltriller+
if exclude_grace_notes:
abc = re.sub(r'\{.*?\}', repl_by_spaces, abc) # remove grace notes
return abc
def get_notes_from_abc(abc, exclude_grace_notes=False):
''' returns a list of (start-offset, end-offset, abc-note-text) tuples for ABC notes/rests '''
abc = remove_non_note_fragments(abc, exclude_grace_notes)
# find and return ABC notes (including the text ranges)
# 1.3.6.3 [JWDJ] 2015-3 made regex case sensitive again, because after typing Z and <space> a bar did not appear
return [(note.start(0), note.end(0), note.group(0)) for note in
re.finditer(r"([_=^]?[[A-Ga-gz](,+|'+)?\d{0,2}(/\d{1,2}|/+)?)[><-]?", abc)]
def copy_bar_symbols_from_first_voice(abc):
# normalize line endings (necessary for ^ in regexp) and extract the header and the two voices
abc = re.sub(r'\r\n|\r', '\n', abc)
m = re.match(r'(?sm)(.*?K:[^\n]+\s+)^V: *1(.*?)^V: *2\s*(.*)', abc)
header, V1, V2 = m.groups()
# replace strings and other parts with spaces and locate all bar symbols
V1_clean = remove_non_note_fragments(V1)
V2_clean = remove_non_note_fragments(V2)
bar_seps1 = bar_sep_without_space.findall(V1_clean)
bar_seps2 = bar_sep_without_space.findall(V2_clean)
# abort, if the number of par symbols in the first and second voice doesn't match.
if len(bar_seps1) != len(bar_seps2):
print('warning: number of bar separators does not match (cannot complete operation)')
return abc
offset = 0
for m in bar_sep_without_space.finditer(V2_clean):
bar_symbol = bar_seps1.pop(0)
bar_symbol = ' %s ' % bar_symbol.strip()
start, end = m.start(0)+offset, m.end(0)+offset
if bar_symbol != V2[start:end]:
V2 = V2[:start] + bar_symbol + V2[end:]
offset += len(bar_symbol) - (end-start)
abc = header + 'V:1' + V1 + 'V:2\nI:repbra 0\n' + V2.lstrip()
abc = abc.replace('\n', os.linesep)
return abc
def process_MCM(abc):
""" Processes sticky rhythm feature of mcmusiceditor http://www.mcmusiceditor.com/download/sticky-rhythm.pdf
:param abc: abc possibly containing sticky rhythm
:return: abc-compliant
"""
abc, n = re.subn(r'(?m)^(L:\s*mcm_default)', r'L:1/8', abc)
if n:
# erase non-note fragments of the text by replacing them by spaces (thereby preserving offsets)
repl_by_spaces = lambda m: ' ' * len(m.group(0))
s = abc.replace('\r', '\n')
s = re.sub(r'(?s)%%begin(ps|text).+?%%end(ps|text)', repl_by_spaces, s) # remove embedded text/postscript
s = re.sub(r'(?m)^\w:.*?$|%.*$', repl_by_spaces, s) # remove non-embedded fields and comments
s = re.sub(r'".*?"|!.+?!|\+\w+?\+|\[\w:.*?\]', repl_by_spaces, s) # remove strings, ornaments and embedded fields
fragments = []
last_fragment_end = 0
for m in re.finditer(r"(?P<note>([_=^]?[A-Ga-gxz](,+|'+)?))(?P<len>\d{0,2})(?P<dot>\.?)", s):
if m.group('len') == '':
length = 0
else:
length = Fraction(8, int(m.group('len')))
if m.group('dot'):
length = length * 3 / 2
start, end = m.start(0), m.end(0)
fragments.append((False, abc[last_fragment_end:start]))
fragments.append((True, m.group('note') + str(length)))
last_fragment_end = end
fragments.append((False, abc[last_fragment_end:]))
abc = ''.join((text for is_note, text in fragments))
return abc
def get_hash_code(*args):
hash = hashlib.md5()
for arg in args:
if type(arg) is unicode:
arg = arg.encode('utf-8', 'ignore')
hash.update(arg)
hash.update(program_name)
return hash.hexdigest()[:10]
def change_abc_tempo(abc_code, tempo_multiplier):
''' multiples all Q: fields in the abc code by the given multiplier and returns the modified abc code '''
def subfunc(m, multiplier):
try:
if '=' in m.group(0):
parts = m.group(0).split('=')
parts[1] = str(int( int(parts[1])*multiplier ))
return '='.join(parts)
q = int( int(m.group(1))*multiplier )
if '[' in m.group(0):
return '[Q: %d]' % q
else:
return 'Q: %d' % q
except:
return m.group(0)
abc_code, n1 = re.subn(r'(?m)^Q: *(.+)', lambda m, mul=tempo_multiplier: subfunc(m, mul), abc_code)
abc_code, n2 = re.subn(r'\[Q: *(.+)\]', lambda m, mul=tempo_multiplier: subfunc(m, mul), abc_code)
# if no Q: field that is not inline add a new Q: field after the X: line
# (it seems to be ignored by abcmidi if added earlier in the code)
if n1 == 0:
default_tempo = 120
extra_line = 'Q:%d' % int(default_tempo * tempo_multiplier)
lines = text_to_lines(abc_code)
for i in range(len(lines)):
if lines[i].startswith('X:'):
lines.insert(i+1, extra_line)
break
abc_code = os.linesep.join(lines)
return abc_code
def add_table_of_contents_to_postscript_file(filepath):
def to_ps_string(s): # handle unicode strings
if any(c for c in s if ord(c) > 127):
return '<FEFF%s>' % ''.join('%.4x' % ord(c) for c in s) # encode unicode
else:
return '(%s)' % s.replace('(', r'\(').replace(')', r'\)') # escape any parenthesis
lines = list(codecs.open(filepath, 'rU', 'utf-8'))
for line in lines:
if 'pdfmark' in line:
return # pdfmarks have already been added
new_lines = []
new_tune_state = False
tunes = []
for line in lines:
new_lines.append(line)
m = re.match(r'% --- (\d+) \((.*?)\) ---', line)
if m:
new_tune_state = True
tune_index, tune_title = m.group(1), m.group(2)
tunes.append((tune_index, tune_title))
if new_tune_state and (line.rstrip().endswith('showc') or
line.rstrip().endswith('showr') or
line.rstrip().endswith('show')):
ps_title = to_ps_string(decode_abc(tune_title))
new_lines.append('[ /Dest /NamedDest%s /View [ /XYZ null null null ] /DEST pdfmark' % tune_index)
new_lines.append('[ /Action /GoTo /Dest /NamedDest%s /Title %s /OUT pdfmark' % (tune_index, ps_title))
new_tune_state = False # now this tune has been handled, wait for next one....
codecs.open(filepath, 'wb', 'utf-8').write(os.linesep.join(new_lines))
def sort_abc_tunes(abc_code, sort_fields, keep_free_text=True):
lines = text_to_lines(abc_code)
tunes = []
file_header = []
preceeding_lines = []
Tune = namedtuple('Tune', 'lines header preceeding_lines')
cur_tune = None
inside_begin = ''
for line in lines:
if line.startswith('X:'):
tune = Tune([], {}, [])
if tunes:
tune.preceeding_lines.extend(preceeding_lines)
else:
file_header = preceeding_lines
preceeding_lines = []
cur_tune = tune
tunes.append(cur_tune)
if cur_tune:
cur_tune.lines.append(line)
if re.match('[a-zA-Z]:', line):
field = line[0]
text = line[2:].strip().lower()
if field == 'X':
try:
text = int(text)
except:
pass
if field in cur_tune.header:
cur_tune.header[field] += '\n' + text
else:
cur_tune.header[field] = text
elif not line.strip():
cur_tune = None
preceeding_lines = [line]
else:
preceeding_lines.append(line)
def get_sort_key_for_tune(tune, sort_fields):
return tuple([tune.header.get(f, '') for f in sort_fields])
tunes = [(get_sort_key_for_tune(t, sort_fields), t) for t in tunes]
tunes.sort()
##print '\n'.join([str(x[0]) for x in tunes])