-
Notifications
You must be signed in to change notification settings - Fork 43
/
gmusicbrowser.pl
executable file
·10417 lines (9755 loc) · 369 KB
/
gmusicbrowser.pl
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/env perl
# Copyright (C) 2005-2020 Quentin Sculo <squentin@free.fr>
#
# This file is part of Gmusicbrowser.
# Gmusicbrowser is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3, as
# published by the Free Software Foundation
#
# Gmusicbrowser 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, see <http://www.gnu.org/licenses/>.
use strict;
use warnings;
use utf8;
binmode STDERR,':utf8';
binmode STDOUT,':utf8';
package main;
use Gtk3 '-init';
use Glib qw/filename_from_unicode filename_to_unicode/;
{ no warnings 'once';
# maybe should be loaded automatically by "use Gtk3" ? send patch ?
# needed for Pango::Cairo::show_layout
Glib::Object::Introspection->setup( basename=>'PangoCairo', version=>'1.0', package=>'Pango::Cairo' );
*Cairo::Context::show_layout= *Pango::Cairo::show_layout{CODE};
# needed to get window xid, only needed for gstreamer visuals and for interaction with screensaver #FIXME make it optional
# seems to be needed for Gtk3::Gdk::drag_status too ?
Glib::Object::Introspection->setup( basename=>'GdkX11', version=>'3.0', package=>'Gtk3::Gdk' );
push @Gtk3::Gdk::X11Window::ISA, 'Gtk3::Gdk::Window';
*Gtk3::Gdk::X11DragContext::status= *Gtk3::Gdk::drag_status{CODE};
# make some cairo functions easier to use
*Cairo::Context::set_source_pixbuf= *Gtk3::Gdk::cairo_set_source_pixbuf{CODE};
*Cairo::Context::set_source_gdk_rgba= *Gtk3::Gdk::cairo_set_source_rgba{CODE};
*Cairo::Context::get_clip_rectangle= *Gtk3::Gdk::cairo_get_clip_rectangle{CODE};
*Cairo::Context::gdk_rectangle= *Gtk3::Gdk::cairo_rectangle{CODE};
*Cairo::Context::should_draw_window= *Gtk3::cairo_should_draw_window{CODE};
# make some Gtk3::render_* functions easier to use
*Gtk3::StyleContext::render_layout= *Gtk3::render_layout{CODE};
*Gtk3::StyleContext::render_focus= *Gtk3::render_focus{CODE};
*Gtk3::StyleContext::render_background= *Gtk3::render_background{CODE};
*Gtk3::StyleContext::render_frame= *Gtk3::render_frame{CODE};
*Gtk3::StyleContext::render_line= *Gtk3::render_line{CODE};
#convenience Gtk3::Widget method
*Gtk3::Widget::GET_ancestor= \&GET_ancestor;
}
our $WnckOK;
sub Load_Wnck
{ return $WnckOK ||= eval { Glib::Object::Introspection->setup( basename => 'Wnck', version => '3.0', package => 'Wnck', flatten_array_ref_return_for => [qw/Wnck::Screen::get_windows_stacked/] ); 1; };
}
{no warnings 'redefine';
# fix for binding not handling gdk_pixbuf_loader_write properly prior to Glib::Object::Introspection::VERSION 0.049
*Gtk3::Gdk::PixbufLoader::write= sub { return Glib::Object::Introspection->invoke( 'GdkPixbuf', 'PixbufLoader', 'write', $_[0], [unpack 'C*', $_[1]] ); }
if $Glib::Object::Introspection::VERSION<0.049;
sub Gtk3::ComboBox::get_active_iter
{ my ($ok,$iter)= Glib::Object::Introspection->invoke( 'Gtk', 'ComboBox', 'get_active_iter', $_[0]);
return $ok ? $iter : undef;
}
sub Gtk3::TextIter::get_tags
{ my $tags= Glib::Object::Introspection->invoke( 'Gtk', 'TextIter', 'get_tags', $_[0]);
return $tags ? @$tags : ();
}
sub Gtk3::Gdk::DragContext::list_targets
{ my $targets= Glib::Object::Introspection->invoke( 'Gdk', 'DragContext', 'list_targets', $_[0]);
return $targets ? @$targets : ();
}
sub Gtk3::FileChooserWidget::get_uris
{ my $uris= Glib::Object::Introspection->invoke( 'Gtk', 'FileChooser', 'get_uris', $_[0]);
return $uris ? @$uris : ();
}
{ no warnings 'once'; *Gtk3::FileChooserDialog::get_uris= \&Gtk3::FileChooserWidget::get_uris; }
# make 2nd & 3rd arguments optionals
sub Gtk3::TreeView::set_cursor
{ Glib::Object::Introspection->invoke( 'Gtk', 'TreeView', 'set_cursor', $_[0], $_[1], $_[2] || undef, $_[3] || 0);
}
#fix for curent Gtk3 bindings
sub Gtk3::Dialog::new
{ my ($class, $title, $parent, $flags, @rest) = @_;
my $dialog= Glib::Object::Introspection->invoke('Gtk', 'Dialog', 'new', $class);
$flags= Gtk3::DialogFlags->new($flags); #line missing from current Gtk3 binding reimplementation of Gtk3::Dialog::new, results in dialog always being modal and destroy-with-parent
defined $title and $dialog->set_title ($title);
defined $parent and $dialog->set_transient_for ($parent);
$flags & 'modal' and $dialog->set_modal (Glib::TRUE);
$flags & 'destroy-with-parent' and $dialog->set_destroy_with_parent (Glib::TRUE);
$dialog->add_buttons (@rest);
return $dialog;
}
# revert behavior of iter_next to perl-gtk2 one, easier to port old code with that, and much less risks of introducing bugs
sub Gtk3::TreeModel::iter_next
{ my ($model,$iter)= @_;
my $newiter= $iter->copy;
my $ok= Glib::Object::Introspection->invoke('Gtk', 'TreeModel', 'iter_next', $model,$newiter);
return $ok==1 ? $newiter : undef;
}
# Gtk3 bindings don't convert the size for Gtk3::Button::new_from_icon_name
sub Gtk3::Button::new_from_icon_name
{ my $i= Gtk3::Image->new_from_icon_name($_[1],$_[2]);
my $b= Gtk3::Button->new;
$b->set_image($i);
$b;
}
}
#icon sizes used in gtk2
our %IconSize= (menu=>16, 'small-toolbar'=>16, 'large-toolbar'=>24, dnd=>32, dialog=>48, button=>16);
use constant PANGO_WEIGHT_NORMAL => Glib::Object::Introspection->convert_sv_to_enum('Pango::Weight','normal');
use constant PANGO_WEIGHT_BOLD => Glib::Object::Introspection->convert_sv_to_enum('Pango::Weight','bold');
use constant PANGO_STYLE_NORMAL => Glib::Object::Introspection->convert_sv_to_enum('Pango::Style', 'normal');
use constant PANGO_STYLE_ITALIC => Glib::Object::Introspection->convert_sv_to_enum('Pango::Style', 'italic');
use POSIX qw/setlocale LC_NUMERIC LC_MESSAGES LC_TIME strftime mktime getcwd _exit/;
use Encode qw/_utf8_on _utf8_off/;
{no warnings 'redefine';
# alternate names for some functions that were, once upon a time, not provided by Glib
*filename_to_utf8displayname=\&Glib::filename_display_name if *Glib::filename_display_name{CODE};
*PangoEsc=\&Glib::Markup::escape_text if *Glib::Markup::escape_text{CODE};
if (eval($POSIX::VERSION)<1.18) #previously, date strings returned by strftime needed to be decoded by the locale encoding # maybe too old to care about these versions ?
{ my ($encoding)= setlocale(LC_TIME)=~m#\.([^@]+)#;
$encoding='cp'.$encoding if $^O eq 'MSWin32' && $encoding=~m/^\d+$/;
if (!Encode::resolve_alias($encoding)) {warn "Can't find dates encoding used for dates, (LC_TIME=".setlocale(LC_TIME)."), dates may have wrong encoding\n";$encoding=undef}
*strftime_utf8= sub { $encoding ? Encode::decode($encoding, &strftime) : &strftime; };
}
}
use List::Util qw/min max sum first/;
use File::Copy;
use Fcntl qw/O_NONBLOCK O_WRONLY O_RDWR SEEK_SET/;
use Scalar::Util qw/blessed weaken refaddr/;
use Unicode::Normalize 'NFKD'; #for accent-insensitive sort and search, only used via superlc()
use Carp;
$SIG{INT} = sub {&Carp::cluck; exit 2};
$SIG{CHLD}= 'IGNORE'; # to get rid of zombie child processes
#use constant SLASH => ($^O eq 'MSWin32')? '\\' : '/';
use constant SLASH => '/'; #gtk file chooser use '/' in win32 and perl accepts both '/' and '\'
# Find dir containing other files (*.pm & pix/) -> $DATADIR
use FindBin;
our $DATADIR;
BEGIN
{ my @dirs=( $FindBin::RealBin,
join (SLASH,$FindBin::RealBin,'..','share','gmusicbrowser') #FIXME remove, all perl files will be in $FindBin::RealBin, gmusicbrowser.pl symlinked to /usr/bin/gmusibrowser
);
($DATADIR)=grep -e $_.SLASH.'gmusicbrowser_layout.pm', @dirs;
die "Can't find folder containing data files, looked in @dirs\n" unless $DATADIR;
}
use lib $DATADIR;
use constant
{
TRUE => 1,
FALSE => 0,
VERSION => '1.109901',
VERSIONSTRING => '1.1.99.1',
PIXPATH => $DATADIR.SLASH.'pix'.SLASH,
PROGRAM_NAME => 'gmusicbrowser',
DRAG_STRING => 0, DRAG_USTRING => 1, DRAG_FILE => 2,
DRAG_ID => 3, DRAG_ARTIST => 4, DRAG_ALBUM => 5,
DRAG_FILTER => 6, DRAG_MARKUP => 7,
PI => 4 * atan2(1, 1), #needed for cairo rotation functions
KB => 1000, #1024 # bytes in a KB
WINDOW_PADDING => 18,
};
use constant MB => KB()**2;
sub _ ($) {$_[0]} #dummy translation functions
sub _p ($$) {_($_[1])}
sub __ { sprintf( ($_[2]>1 ? $_[1] : $_[0]), $_[2]); }
sub __p {shift;&__}
sub __np {shift;&__n}
sub __n { replace_fnumber( ($_[2]>1 ? $_[1] : $_[0]), $_[2]); }
sub __x { my ($s,%h)=@_; $s=~s/{(\w+)}/$h{$1}/g; $s; }
sub replace_fnumber { my $s=$_[0]; use locale; $s=~s/%d/format_number($_[1])/e; $s } #replace %d by the formated number, could use sprintf($_[0],$_[1]) instead but would require changing %d to %s
BEGIN
{no warnings 'redefine';
my $localedir=$DATADIR;
$localedir= $FindBin::RealBin.SLASH.'..'.SLASH.'share' unless -d $localedir.SLASH.'locale';
$localedir.=SLASH.'locale';
my $domain='gmusicbrowser';
eval {require Locale::Messages;};
if ($@)
{ eval {require Locale::gettext};
if ($@) { warn "neither Locale::Messages, nor Locale::gettext found -> no translations\n"; }
elsif ($Locale::gettext::VERSION<1.04) { warn "Needs at least version 1.04 of Locale::gettext, v$Locale::gettext::VERSION found -> no translations\n" }
else
{ warn "Locale::Messages not found, using Locale::gettext instead\n" if $::debug;
my $d= eval { Locale::gettext->domain($domain); };
if ($@) { warn "Locale::gettext error : $@\n -> no translations\n"; }
else
{ $d->dir($localedir);
*_=sub ($) { $d->get($_[0]); };
*__=sub { sprintf $d->nget(@_),$_[2]; };
*__n=sub { replace_fnumber($d->nget(@_),$_[2]); };
}
}
}
else
{ Locale::Messages::textdomain($domain);
Locale::Messages::bindtextdomain($domain=> $localedir);
Locale::Messages::bind_textdomain_codeset($domain=> 'utf-8');
Locale::Messages::bind_textdomain_filter($domain=> \&Locale::Messages::turn_utf_8_on);
*_ = \&Locale::Messages::gettext;
*_p = \&Locale::Messages::pgettext;
*__ =sub { sprintf Locale::Messages::ngettext(@_),$_[2]; };
*__p=sub { sprintf Locale::Messages::npgettext(@_),$_[3];};
*__n =sub { replace_fnumber( Locale::Messages::ngettext(@_),$_[2] );};
*__np=sub { replace_fnumber( Locale::Messages::npgettext(@_),$_[3]);};
}
}
my $thousandsep;
BEGIN { $thousandsep= POSIX::localeconv()->{thousands_sep} // ''; }
sub format_number
{ my ($d,$f)=@_;
use locale;
$d= $f ? sprintf($f,$d) : ''.($d+0); # ''.($d+0) to force stringification of the number with the locale
return $d unless $d=~s/^(-?\d{4,})//; # $d now contains the fractional part
return $d unless $thousandsep;
my $i=$1; # integer part
$i =~ s/(?<=\d)(?=(?:\d\d\d)+\b)/$thousandsep/g;
return $i.$d;
}
our $QSLASH; #quoted SLASH for use in regex
# %html_entities and decode_html() are only used if HTML::Entities is not found
my %html_entities=
( amp => '&', 'lt' => '<', 'gt' => '>', quot => '"', apos => "'",
raquo => '»', copy => '©', middot => '·',
acirc => 'â', eacute => 'é', egrave => 'è', ecirc => 'ê',
agrave=> 'à', ccedil => 'ç',
);
sub decode_html
{ my $s=shift;
$s=~s/&(?:#(\d+)|#x([0-9A-F]+)|([a-z]+));/$1 ? chr($1) : $2 ? chr(hex $2) : $html_entities{$3}||'?'/egi;
return $s;
}
BEGIN
{ no warnings 'redefine';
eval {require HTML::Entities};
*decode_html= \&HTML::Entities::decode_entities unless $@;
$QSLASH=quotemeta SLASH;
}
sub file_name_is_absolute
{ my $path=shift;
$^O eq 'MSWin32' ? $path=~m#^\w:$QSLASH#o : $path=~m#^$QSLASH#o;
}
sub rel2abs
{ my ($path,$base)=@_;
return $path if file_name_is_absolute($path);
$base||= POSIX::getcwd;
return catfile($base,$path);
}
sub catfile
{ my $path=join SLASH,@_;
$path=~s#$QSLASH{2,}#SLASH#goe;
return $path;
}
sub pathslash
{ #return catfile($_[0],'');
my $path=shift;
$path.=SLASH unless $path=~m/$QSLASH$/o;
return $path;
}
sub simplify_path
{ my ($path,$end_with_slash)=@_;
1 while $path=~s#$QSLASH+[^$QSLASH]+$QSLASH\.\.(?:$QSLASH+|$)#SLASH#oe;
return cleanpath($path,$end_with_slash);
}
sub cleanpath #remove repeated slashes, /./, and make sure it (does or doesn't) end with a slash
{ my ($path,$end_with_slash)=@_;
$path=~s#$QSLASH\.$QSLASH#SLASH#goe;
$path=~s#$QSLASH{2,}#SLASH#goe;
$path=~s#$QSLASH$##o;
$path.=SLASH if $end_with_slash || $path!~m#$QSLASH#o; # $end_with_slash or root folder
return $path;
}
sub splitpath
{ my $path=shift;
my $file= $path=~s#$QSLASH+([^$QSLASH]+)$##o ? $1 : '';
$path.=SLASH unless $path=~m#$QSLASH#o; #root folder
return $path,$file;
}
sub dirname
{ (&splitpath)[0];
}
sub parentdir
{ my $path=shift;
$path=~s#$QSLASH+$##o;
return $path=~m#$QSLASH#o ? dirname($path) : undef;
}
sub basename
{ my $file=shift;
return $file=~m#([^$QSLASH]+)$#o ? $1 : '';
}
sub barename #filename without extension
{ my $file=&basename;
my $ext= $file=~s#\.([^.]*)$##o ? $1 : '';
return wantarray ? ($file,$ext) : $file;
}
our %Alias_ext; #define alternate file extensions (ie: .ogg files treated as .oga files)
INIT
{ # needs to be in a INIT block because used in a INIT block in gmusicbrowser_tags.pm
%Alias_ext=
( mp2=>'mp3', ogg=> 'oga', m4b=>'m4a',
it=>'mod', s3m=>'mod', xm=>'mod', mtm=>'mod', dmf=>'mod', 669=>'mod',
);
}
our @ScanExt= qw/mp3 mp2 ogg oga flac mpc ape wv m4a m4b opus/;
our @ScanExtOther= qw/aac wav wma/;
our @ScanExtVideo= qw/mp4 mkv avi wmv flv webm mov mpg mpeg m4v ogv asf rmvb/;
our @ScanExtMod= qw/mod it s3m xm mtm dmf 669/;
our ($Verbose,$debug);
our %CmdLine;
our ($HomeDir,$SaveFile,$FIFOFile,$ImportFile,$DBus_id,$DBus_suffix);
our $TempDir;
sub find_gmbrc_file { my @f= map $_[0].$_, '','.gz','.xz'; return wantarray ? (grep { -e $_ } @f) : first { -e $_ } @f }
my $gmbrc_ext_re= qr/\.gz$|\.xz$/;
# Parse command line
BEGIN # in a BEGIN block so that commands for a running instance are sent sooner/faster
{ $DBus_id='org.gmusicbrowser'; $DBus_suffix='';
$CmdLine{id}='';
my $default_home= Glib::get_user_config_dir.SLASH.'gmusicbrowser';
if (!-d $default_home && -d (my $old= Glib::get_home_dir.SLASH.'.gmusicbrowser' ) )
{ warn "Using folder $old for configuration, you could move it to $default_home to conform to the XDG Base Directory Specification\n";
$default_home=$old;
}
my $help=PROGRAM_NAME.' v'.VERSIONSTRING." (c)2005-2020 Quentin Sculo
options :
-nocheck: don't check for updated/deleted songs on startup
-noscan : don't scan folders for songs on startup
-demo : don't save settings/tags on exit
-ro : prevent modifying/renaming/deleting song files
-rotags : prevent modifying tags of music files
-play : start playing on startup
-nogst : do not load any gstreamer librairies
-server : send playing song to connected icecast clent
-port N : listen for connection on port N in icecast server mode
-verbose: print some info, like the file being played
-debug : print lots of mostly useless informations, implies -verbose
-backtrace : print a backtrace for every warning
-id ID : append -ID to strings identifying the application (window roles, application name, DBus id) and to default gmbrc and fifo files.
-nodbus : do not provide DBus services
-dbus-id KEY : append .KEY to the DBus service id used by gmusicbrowser (org.gmusicbrowser)
-nofifo : do not create/use named pipe
-F FIFO, -fifo FILE : use FIFO as named pipe to receive commands (instead of 'gmusicbrowser.fifo' in default folder)
-C FILE, -cfg FILE : use FILE as configuration file (instead of 'gmbrc' in default folder),
if FILE is a folder, sets the default folder to FILE.
-l NAME, -layout NAME : Use layout NAME for player window
+plugin NAME : Enable plugin NAME
-plugin NAME : Disable plugin NAME
-noplugins : Disable all plugins
-searchpath FOLDER : Additional FOLDER to look for plugins and layouts
-use-gnome-session : Use gnome libraries to save tags/settings on session logout
-workspace N : move initial window to workspace N (requires libwnck and its introspection data)
-gzip : force not compressing gmbrc
+gzip : force compressing gmbrc with gzip
+xz : force compressing gmbrc with xz
-cmd CMD : add CMD to the list of commands to execute
-ifnotrunning MODE : change behavior when no running gmusicbrowser instance is found
MODE can be one of :
* normal (default) : launch a new instance and execute commands
* nocmd : launch a new instance but discard commands
* abort : do nothing
-nolaunch : same as : -ifnotrunning abort
Running instances of gmusicbrowser are detected via the fifo or via DBus.
To run more than one instance, use a unique fifo and a unique DBus-id, or deactivate them.
Options to change what is done with files/folders passed as arguments (done in running gmusicbrowser if there is one) :
-playlist : Set them as playlist (default)
-enqueue : Enqueue them
-addplaylist : Add them to the playlist
-insertplaylist : Insert them in the playlist after current song
-add : Add them to the library
-tagedit FOLDER_OR_FILE ... : Edittag mode
-listplugin : list the available plugins and exit
-listcmd : list the available fifo commands and exit
-listlayout : list the available layouts and exit
";
unshift @ARGV,'-tagedit' if $0=~m/tagedit/;
my (@files,$filescmd,@cmd,$ignore);
my $ifnotrunning='normal';
while (defined (my $arg=shift))
{ if ($arg eq '-c' || $arg eq '-nocheck') {$CmdLine{nocheck}=1}
elsif($arg eq '-s' || $arg eq '-noscan') {$CmdLine{noscan}=1}
elsif($arg eq '-demo') {$CmdLine{demo}=1}
elsif($arg eq '-play') {$CmdLine{play}=1}
elsif($arg eq '-hide') {$CmdLine{hide}=1}
elsif($arg eq '-server') {$CmdLine{server}=1}
elsif($arg eq '-nodbus') {$CmdLine{noDBus}=1}
elsif($arg eq '-nogst') {$CmdLine{nogst}=1}
elsif($arg eq '-ro') {$CmdLine{ro}=$CmdLine{rotags}=1}
elsif($arg eq '-rotags') {$CmdLine{rotags}=1}
elsif($arg eq '-port') {$CmdLine{port}=shift if $ARGV[0]}
elsif($arg eq '-verbose') {$Verbose=1}
elsif($arg eq '-debug') {$debug=$Verbose=4}
elsif($arg eq '-backtrace') { $SIG{ __WARN__ } = \&Carp::cluck; $SIG{ __DIE__ } = \&Carp::confess; }
elsif($arg eq '-nofifo') {$FIFOFile=''}
elsif($arg eq '-workspace') {$CmdLine{workspace}=shift if defined $ARGV[0]} #requires libwnck
elsif($arg eq '-C' || $arg eq '-cfg') {$CmdLine{savefile}=shift if $ARGV[0]}
elsif($arg eq '-F' || $arg eq '-fifo') {$FIFOFile=rel2abs(shift) if $ARGV[0]}
elsif($arg eq '-l' || $arg eq '-layout') {$CmdLine{layout}=shift if $ARGV[0]}
elsif($arg eq '-import') { $ImportFile=rel2abs(shift) if $ARGV[0]}
elsif($arg eq '-searchpath') { push @{ $CmdLine{searchpath} },shift if $ARGV[0]}
elsif($arg=~m/^([+-])plugin$/) { $CmdLine{plugins}{shift @ARGV}=($1 eq '+') if $ARGV[0]}
elsif($arg eq '-noplugins') { $CmdLine{noplugins}=1; delete $CmdLine{plugins}; }
elsif($arg=~m/^([+-])gzip$/) { $CmdLine{gzip}= $1 eq '+' ? 'gzip':''}
elsif($arg=~m/^([+-])xz$/) { $CmdLine{gzip}= $1 eq '+' ? 'xz':''}
elsif($arg eq '-geometry') { $CmdLine{geometry}=shift if $ARGV[0]; }
elsif($arg eq '-tagedit') { $CmdLine{tagedit}=1; $ignore=1; last; }
elsif($arg eq '-listplugin') { $CmdLine{pluginlist}=1; $ignore=1; last; }
elsif($arg eq '-listcmd') { $CmdLine{cmdlist}=1; $ignore=1; last; }
elsif($arg eq '-listlayout') { $CmdLine{layoutlist}=1; $ignore=1; last; }
elsif($arg eq '-cmd') { push @cmd, shift if $ARGV[0]; }
elsif($arg eq '-ifnotrunning') { $ifnotrunning=shift if $ARGV[0]; }
elsif($arg eq '-nolaunch') { $ifnotrunning='abort'; }
elsif($arg eq '-id') { if (my $id=shift) { if ($id=~m/^\w+$/) { $CmdLine{id}="-$id"; $DBus_suffix=".$id"; } else { warn "invalid id '$id', only letters, numbers and _ allowed\n" }; } }
elsif($arg eq '-dbus-id') { if (my $id=shift) { if ($id=~m/^\w+$/) { $DBus_suffix=".$id"; } else { warn "invalid dbus-id '$id', only letters, numbers and _ allowed\n" }; } }
elsif($arg eq '-add') { $filescmd='AddToLibrary'; }
elsif($arg eq '-playlist') { $filescmd='OpenFiles'; }
elsif($arg eq '-enqueue') { $filescmd='EnqueueFiles'; }
elsif($arg eq '-addplaylist') { $filescmd='AddFilesToPlaylist'; }
elsif($arg eq '-insertplaylist'){ $filescmd='InsertFilesInPlaylist'; }
elsif($arg eq '-use-gnome-session'){ $CmdLine{UseGnomeSession}=1; }
elsif($arg=~m#^http://# || -e $arg) { push @files,$arg }
else
{ warn "unknown option '$arg'\n" unless $arg=~/^--?h(elp)?$/;
print $help;
exit;
}
}
# determine $HomeDir $SaveFile $ImportFile and $FIFOFile
my $save= delete $CmdLine{savefile};
if (defined $save)
{ my $isdir= $save=~m#/$#; ## $save is considered a folder if ends with a "/"
$save= rel2abs($save);
if (-d $save || $isdir) { $HomeDir = $save; }
else { $SaveFile= $save; }
}
warn "using '$HomeDir' folder for saving/setting folder instead of '$default_home'\n" if $debug && $HomeDir;
$HomeDir= pathslash(cleanpath($HomeDir || $default_home)); # $HomeDir must end with a slash
if (!-d $HomeDir)
{ warn "Creating folder $HomeDir\n";
my $current='';
for my $dir (split /$QSLASH/o,$HomeDir)
{ $current.=SLASH.$dir;
next if -d $current;
die "Can't create folder $HomeDir : $!\n" unless mkdir $current;
}
}
my $id= $CmdLine{id};
# auto import from old v1.0 tags file if using default savefile, it doesn't exist and old tags file exists
if (!$SaveFile && !find_gmbrc_file($HomeDir.'gmbrc'.$id) && !$id && -e $HomeDir.'tags') { $ImportFile||=$HomeDir.'tags'; }
$SaveFile||= $HomeDir.'gmbrc'.$id;
$FIFOFile= $HomeDir."gmusicbrowser$id.fifo" if !defined $FIFOFile && $^O ne 'MSWin32';
unless ($ignore)
{ # filenames given in the command line
if (@files)
{ for my $f (@files)
{ unless ($f=~m#^http://#)
{ $f=rel2abs($f);
$f=~s/([^A-Za-z0-9])/sprintf('%%%02X', ord($1))/seg; #FIXME use url_escapeall, but not yet defined
}
}
$filescmd ||= 'OpenFiles';
my $cmd="$filescmd(@files)";
push @cmd, $cmd;
}
#check if there is an instance already running
my $running;
if ($FIFOFile && -p $FIFOFile)
{ my @c= @cmd ? @cmd : ('Show'); #fallback to "Show" command
my $ok=sysopen my$fifofh,$FIFOFile, O_NONBLOCK | O_WRONLY;
if ($ok)
{ print $fifofh "$_\n" and $running=1 for @c;
close $fifofh;
$running&&= "using '$FIFOFile'";
}
else {warn "Found orphaned fifo '$FIFOFile' : previous session wasn't closed properly\n"}
}
if (!$running && !$CmdLine{noDBus})
{ eval {require 'gmusicbrowser_dbus.pm'}
|| warn "Error loading gmusicbrowser_dbus.pm :\n$@ => controlling gmusicbrowser through DBus won't be possible.\n\n";
my $object= GMB::DBus::simple_call("$DBus_id$DBus_suffix org.gmusicbrowser/org/gmusicbrowser");
if ($object)
{ $object->RunCommand($_) for @cmd;
$running="using DBus id=$DBus_id$DBus_suffix";
}
}
if ($running)
{ warn "Found a running instance ($running)\n";
exit;
}
else
{ exit if $ifnotrunning eq 'abort';
@cmd=() if $ifnotrunning eq 'nocmd';
}
$CmdLine{runcmd}=\@cmd if @cmd;
}
}
# end of command line handling
our $HTTP_module;
our ($Play_package,%PlayPacks); my ($PlayNext_package,$Vol_package);
BEGIN{
require 'gmusicbrowser_songs.pm';
require 'gmusicbrowser_tags.pm';
require 'gmusicbrowser_layout.pm';
require 'gmusicbrowser_list.pm';
$HTTP_module= -e $DATADIR.SLASH.'simple_http_wget.pm' && (grep -x $_.SLASH.'wget', split /:/, $ENV{PATH}) ? 'simple_http_wget.pm' :
-e $DATADIR.SLASH.'simple_http_AE.pm' && (grep -f $_.SLASH.'AnyEvent'.SLASH.'HTTP.pm', @INC) ? 'simple_http_AE.pm' :
'simple_http.pm';
#warn "using $HTTP_module for http requests\n";
#require $HTTP_module;
# load gstreamer backend module
if (!$CmdLine{nogst})
{ eval { require 'gmusicbrowser_gstreamer-1.x.pm'; };
if (my $error=$@)
{ warn $error if $::debug;
$error=~s/\n.*//s; #only keep first line, others are noise
warn "\nCan't load gstreamer-1.x (via Glib::Object::Introspection) -> gstreamer output won't be available :\n $error\n\n";
}
}
# load non-gstreamer backend modules
for my $file (qw/gmusicbrowser_123.pm gmusicbrowser_mplayer.pm gmusicbrowser_mpv.pm gmusicbrowser_server.pm/)
{ eval { require $file } || warn $@; #each file sets $::PlayPacks{PACKAGENAME} to 1 for each of its included playback packages
}
$TempDir= Glib::get_tmp_dir.SLASH; _utf8_off($TempDir); #turn utf8 flag off to not auto-utf8-upgrade other filenames in the same strings
}
my $TrayIconAvailable;
BEGIN
{ if (*Gtk3::StatusIcon::set_has_tooltip{CODE}) { $TrayIconAvailable=1; }
else { warn "Gtk3::StatusIcon not found, probaly deprecated -> tray icon won't be available (need to implement replacements)\n" }
}
my $IconSearchPath= ( Gtk3::IconTheme::get_default()->get_search_path )[0];
our $Image_ext_re; # = qr/\.(?:jpe?g|png|gif|bmp)$/i;
BEGIN
{ my $re=join '|', sort map @{ $_->get_extensions }, Gtk3::Gdk::Pixbuf::get_formats();
$Image_ext_re=qr/\.(?:$re)$/i;
}
our $EmbImage_ext_re= join '|', sort grep $FileTag::FORMATS{$_}{image}, keys %FileTag::FORMATS;
$EmbImage_ext_re= qr/\.(?:$EmbImage_ext_re)/i; # warning: doesn't force end of string (with a "$") as sometimes needs to include/extract a :\w+ at the end, so need to use it with /$EmbImage_ext_re$/ or /$EmbImage_ext_re(:\w+)?$/
##########
#our $re_spaces_unlessinbrackets=qr/([^( ]+(?:\(.*?\))?)(?: +|$)/; #breaks "widget1(options with spaces) widget2" in "widget1(options with spaces)" and "widget2" #replaced by ExtractNameAndOptions
my ($browsercmd,$opendircmd);
#changes to %QActions must be followed by a call to Update_QueueActionList()
# changed : called from Queue or QueueAction changed
# action : called when queue is empty
# keep : do not clear mode once empty
# save : save mode when RememberQueue is on
# condition : do not show mode if return false
# order : used to sort modes
# autofill : indicate that this mode use the maxautofill value
# can_next : this mode can be use with $NextAction
our %QActions=
( '' => {order=>0, short=> _"normal", long=> _"Normal mode", can_next=>1, },
autofill=> {order=>10, icon=>'gtk-refresh', short=> _"autofill", long=> _"Auto-fill queue", changed=>\&QAutoFill, keep=>1,save=>1,autofill=>1, },
'wait' => {order=>20, icon=>'gmb-wait', short=> _"wait for more", long=> _"Wait for more when queue empty", action=>\&Stop, changed=>\&QWaitAutoPlay,keep=>1,save=>1, },
stop => {order=>30, icon=>'gtk-media-stop', short=> _"stop", long=> _"Stop when queue empty", action=>\&Stop,
can_next=>1, long_next=>_"Stop after this song", },
quit => {order=>40, icon=>'gtk-quit', short=> _"quit", long=> _"Quit when queue empty", action=>\&Quit,
can_next=>1, long_next=>_"Quit after this song"},
turnoff => {order=>50, icon=>'gmb-turnoff', short=> _"turn off", long=> _"Turn off computer when queue empty", action=>sub {Stop(); TurnOff();},
condition=> sub { $::Options{Shutdown_cmd} }, can_next=>1, long_next=>_"Turn off computer after this song"},
);
our @DRAGTYPES;
@DRAGTYPES[DRAG_FILE,DRAG_USTRING,DRAG_STRING,DRAG_MARKUP,DRAG_ID,DRAG_ARTIST,DRAG_ALBUM,DRAG_FILTER]=
( ['text/uri-list'],
['text/plain;charset=utf-8'],
['STRING'],
['markup'],
[SongID =>
{ DRAG_FILE, sub { Songs::Map('uri',\@_); },
DRAG_ARTIST, sub { @{Songs::UniqList('artist',\@_,1)}; },
DRAG_ALBUM, sub { @{Songs::UniqList('album',\@_,1)}; },
DRAG_USTRING, sub { (@_==1)? Songs::Display($_[0],'title') : __n("%d song","%d songs",scalar@_) },
#DRAG_STRING, undef, #will use DRAG_USTRING
DRAG_STRING, sub { Songs::Map('uri',\@_); },
DRAG_FILTER, sub {Filter->newadd(FALSE,map 'title:~:'.Songs::Get($_,'title'),@_)->{string}},
DRAG_MARKUP, sub { return ReplaceFieldsAndEsc($_[0],_"<b>%t</b>\n<small><small>by</small> %a\n<small>from</small> %l</small>") if @_==1;
my $nba=@{Songs::UniqList2('artist',\@_)};
my $artists= ($nba==1)? Songs::DisplayEsc($_[0],'artist') : __("%d artist","%d artists",$nba);
__x( _("{songs} by {artists}") . "\n<small>{length}</small>",
songs => __n("%d song","%d songs",scalar@_),
artists => $artists,
'length' => CalcListLength(\@_,'length')
)},
}],
[Artist => { DRAG_USTRING, sub { (@_<10)? join("\n",@{Songs::Gid_to_Display('artist',\@_)}) : __("%d artist","%d artists",scalar@_) },
#DRAG_STRING, undef, #will use DRAG_USTRING
DRAG_STRING, sub { my $l=Filter->newadd(FALSE,map Songs::MakeFilterFromGID('artists',$_),@_)->filter; SortList($l); Songs::Map('uri',$l); },
DRAG_FILE, sub { my $l=Filter->newadd(FALSE,map Songs::MakeFilterFromGID('artists',$_),@_)->filter; SortList($l); Songs::Map('uri',$l); },
DRAG_FILTER, sub { Filter->newadd(FALSE,map Songs::MakeFilterFromGID('artists',$_),@_)->{string} },
DRAG_ID, sub { my $l=Filter->newadd(FALSE,map Songs::MakeFilterFromGID('artists',$_),@_)->filter; SortList($l); @$l; },
}],
[Album => { DRAG_USTRING, sub { (@_<10)? join("\n",@{Songs::Gid_to_Display('album',\@_)}) : __("%d album","%d albums",scalar@_) },
#DRAG_STRING, undef, #will use DRAG_USTRING
DRAG_STRING, sub { my $l=Filter->newadd(FALSE,map Songs::MakeFilterFromGID('album',$_),@_)->filter; SortList($l); Songs::Map('uri',$l); },
DRAG_FILE, sub { my $l=Filter->newadd(FALSE,map Songs::MakeFilterFromGID('album',$_),@_)->filter; SortList($l); Songs::Map('uri',$l); },
DRAG_FILTER, sub { Filter->newadd(FALSE,map Songs::MakeFilterFromGID('album',$_),@_)->{string} },
DRAG_ID, sub { my $l=Filter->newadd(FALSE,map Songs::MakeFilterFromGID('album',$_),@_)->filter; SortList($l); @$l; },
}],
[Filter =>
{ DRAG_USTRING, sub {Filter->new($_[0])->explain},
#DRAG_STRING, undef, #will use DRAG_USTRING
DRAG_STRING, sub { my $l=Filter->new($_[0])->filter; SortList($l); Songs::Map('uri',$l); },
DRAG_ID, sub { my $l=Filter->new($_[0])->filter; SortList($l); @$l; },
DRAG_FILE, sub { my $l=Filter->new($_[0])->filter; SortList($l); Songs::Map('uri',$l); },
}
],
);
our %DRAGTYPES;
$DRAGTYPES{$DRAGTYPES[$_][0]}=$_ for DRAG_FILE,DRAG_USTRING,DRAG_STRING,DRAG_ID,DRAG_ARTIST,DRAG_ALBUM,DRAG_FILTER,DRAG_MARKUP;
our @submenuRemove=
( { label => sub {$_[0]{mode} eq 'Q' ? _"Remove from queue" : $_[0]{mode} eq 'A' ? _"Remove from playlist" : _"Remove from list"}, code => sub { $_[0]{self}->RemoveSelected; }, mode => 'BLQA', istrue=> 'allowremove', },
{ label => _"Remove from library", code => sub { SongsRemove($_[0]{IDs}); }, },
{ label => _"Remove from disk", code => sub { DeleteFiles($_[0]{IDs}); }, test => sub {!$CmdLine{ro}}, stockicon => 'gtk-delete' },
);
our @submenuQueue=
( { label => _"Prepend", code => sub { QueueInsert( @{ $_[0]{IDs} } ); }, },
{ label => _"Replace", code => sub { ReplaceQueue( @{ $_[0]{IDs} } ); }, },
{ label => _"Append", code => sub { Enqueue( @{ $_[0]{IDs} } ); }, },
);
#modes : S:Search, B:Browser, Q:Queue, L:List, P:Playing song in the player window, F:Filter Panels (submenu "x songs")
our @SongCMenu;
unshift @SongCMenu, #unshift instead of "=" because the replaygain submenu (and maybe more in the future) has already been added to @::SongCMenu
( { label => _"Song Properties", code => sub { DialogSongProp (@{ $_[0]{IDs} }); }, onlyone => 'IDs', stockicon => 'gtk-edit' },
{ label => _"Songs Properties", code => sub { DialogSongsProp(@{ $_[0]{IDs} }); }, onlymany=> 'IDs', stockicon => 'gtk-edit' },
{ label => _"Play Only Selected",code => sub { Select(song => 'first', play => 1, staticlist => $_[0]{IDs} ); },
onlymany => 'IDs', stockicon => 'gtk-media-play'},
{ label => _"Play Only Displayed",code => sub { Select(song => 'first', play => 1, staticlist => \@{$_[0]{listIDs}} ); },
test => sub { @{$_[0]{IDs}}<2 }, notmode => 'A', onlymany => 'listIDs', stockicon => 'gtk-media-play' },
{ label => _"Append to playlist",code => sub { ::DoActionForList('addplay',$_[0]{IDs}); },
notempty => 'IDs', test => sub { $::ListMode }, },
{ label => _"Enqueue Selected", code => sub { Enqueue(@{ $_[0]{IDs} }); }, submenu3=> \@submenuQueue,
notempty => 'IDs', notmode => 'QP', stockicon => 'gmb-queue' },
{ label => _"Enqueue Displayed", code => sub { Enqueue(@{ $_[0]{listIDs} }); },
empty => 'IDs', notempty=> 'listIDs', notmode => 'QP', stockicon => 'gmb-queue' },
{ label => _"Add to list", submenu => \&AddToListMenu, notempty => 'IDs' },
# edit submenu for label-type fields
{ label => sub { Songs::Field_Edit_string($_[0]{field}); }, notempty => 'IDs',
submenu=>sub { LabelEditMenu($_[0]{field},$_[0]{IDs}); },
foreach=>sub { 'field', Songs::FieldList(true=>'editsubmenu',type=>'flags'); }, },
# edit submenu for rating-type fields
{ label => sub { Songs::Field_Edit_string($_[0]{field}); }, notempty => 'IDs',
submenu=>sub { Stars::createmenu($_[0]{field},$_[0]{IDs}); },
foreach=>sub { 'field', Songs::FieldList(true=>'editsubmenu',type=>'rating'); }, },
{ label => _"Find songs with the same names", code => sub { SearchSame('title',$_[0]) }, mode => 'B', notempty => 'IDs' },
{ label => _"Find songs with same artists", code => sub { SearchSame('artists',$_[0])}, mode => 'B', notempty => 'IDs' },
{ label => _"Find songs in same albums", code => sub { SearchSame('album',$_[0]) }, mode => 'B', notempty => 'IDs' },
{ label => sub { __x(_"Find songs with the same {field}", field=>Songs::FieldName($_[0]{field})); },
code => sub { SearchSame($_[0]{field},$_[0]); },
foreach=>sub { 'field', Songs::FieldList(true=>'samemenu',); }, mode => 'B', notempty => 'IDs' },
{ label => _"Rename file", code => sub { DialogRename( @{ $_[0]{IDs} }); }, onlyone => 'IDs', test => sub {!$CmdLine{ro}}, },
{ label => _"Mass Rename", code => sub { DialogMassRename( @{ $_[0]{IDs} }); }, onlymany=> 'IDs', test => sub {!$CmdLine{ro}}, },
{ label => _"Copy", code => sub { CopyMoveFilesDialog($_[0]{IDs},TRUE); },
notempty => 'IDs', stockicon => 'gtk-copy', notmode => 'P' },
{ label => _"Move", code => sub { CopyMoveFilesDialog($_[0]{IDs},FALSE); },
notempty => 'IDs', notmode => 'P', test => sub {!$CmdLine{ro}}, },
#{ label => sub {'Remove from '.($_[0]{mode} eq 'Q' ? 'queue' : 'this list')}, code => sub { $_[0]{self}->RemoveSelected; }, stockicon => 'gtk-remove', notempty => 'IDs', mode => 'LQ' }, #FIXME
{ label => _"Remove", submenu => \@submenuRemove, stockicon => 'gtk-remove', notempty => 'IDs', notmode => 'P' },
{ label => _"Re-read tags", code => sub { ReReadTags(@{ $_[0]{IDs} }); },
notempty => 'IDs', notmode => 'P', stockicon => 'gtk-refresh' },
{ label => _"Same Title", submenu => sub { ChooseSongsTitle( $_[0]{IDs}[0] ); }, mode => 'P' },
{ label => _"Edit Lyrics", code => sub { EditLyrics( $_[0]{IDs}[0] ); }, mode => 'P' },
{ label => _"Lookup in google", code => sub { Google( $_[0]{IDs}[0] ); }, mode => 'P' },
{ label => _"Open containing folder", code => sub { openfolder( Songs::Get( $_[0]{IDs}[0], 'path') ); }, onlyone => 'IDs' },
{ label => _"Queue options", submenu => \@Layout::MenuQueue, mode => 'Q', }
);
our @cMenuAA=
( { label => _"Lock", code => sub { ToggleLock($_[0]{lockfield}); }, check => sub { $::TogLock && $::TogLock eq $_[0]{lockfield}}, mode => 'P',
test => sub { $_[0]{field} eq $_[0]{lockfield} || $_[0]{gid} == Songs::Get_gid($::SongID,$_[0]{lockfield}); },
},
{ label => _"Lookup in AMG", code => sub { AMGLookup( $_[0]{mainfield}, $_[0]{aaname} ); },
test => sub { $_[0]{mainfield} =~m/^album$|^artist$|^title$/; },
},
{ label => _"Filter", code => sub { Select(filter => Songs::MakeFilterFromGID($_[0]{field},$_[0]{gid})); }, stockicon => 'gmb-filter', mode => 'P' },
{ label => \&SongsSubMenuTitle, submenu => \&SongsSubMenu, },
{ label => sub {$_[0]{mode} eq 'P' ? _"Display Songs" : _"Filter"}, code => \&FilterOnAA,
test => sub { GetSonglist( $_[0]{self} ) }, },
{ label => _"Set Picture", code => sub { ChooseAAPicture($_[0]{ID},$_[0]{mainfield},$_[0]{gid}); },
stockicon => 'gmb-picture' },
);
our @TrayMenu=
( { label=> sub {$::TogPlay ? _"Pause" : _"Play"}, code => \&PlayPause, stockicon => sub { $::TogPlay ? 'gtk-media-pause' : 'gtk-media-play'; }, id=>'playpause' },
{ label=> _"Stop", code => \&Stop, stockicon => 'gtk-media-stop' },
{ label=> _"Next", code => \&NextSong, stockicon => 'gtk-media-next', id=>'next', },
{ label=> _"Recently played", submenu => sub { my $m=ChooseSongs([GetPrevSongs(8)]); }, stockicon => 'gtk-media-previous' },
{ label=> sub {$::TogLock && $::TogLock eq 'first_artist'? _"Unlock Artist" : _"Lock Artist"}, code => sub {ToggleLock('first_artist');} },
{ label=> sub {$::TogLock && $::TogLock eq 'album' ? _"Unlock Album" : _"Lock Album"}, code => sub {ToggleLock('album');} },
{ label=> _"Windows", code => \&PresentWindow, submenu_ordered_hash =>1,
submenu => sub { [map { $_->layout_name => $_ } grep $_->isa('Layout::Window'), Gtk3::Window::list_toplevels]; }, },
{ label=> sub { IsWindowVisible($::MainWindow) ? _"Hide": _"Show"}, code => sub { ShowHide(); }, id=>'showhide', },
{ label=> _"Fullscreen", code => \&ToggleFullscreenLayout, stockicon => 'gtk-fullscreen' },
{ label=> _"Settings", code => 'OpenPref', stockicon => 'gtk-preferences' },
{ label=> _"Quit", code => \&Quit, stockicon => 'gtk-quit' },
);
our %Artists_split=
( '\s*&\s*' => "&",
'\s*\\+\s*' => "+",
'\s*\\|\s*' => "|",
'\s*;\s*' => ";",
'\s*/\s*' => "/",
'\s*,\s+' => ", ",
',?\s+and\s+' => "and", #case-sensitive because the user might want to use "And" in artist names that should NOT be splitted
',?\s+And\s+' => "And",
'\s+featuring\s+' => "featuring",
'\s+feat\.\s+' => "feat.",
'\s+[Vv][Ss]\s+' => "VS",
);
our %Artists_from_title=
( '\(with\s+([^)]+)\)' => "(with X)",
'\(feat\.\s+([^)]+)\)' => "(feat. X)",
'\(featuring\s+([^)]+)\)' => "(featuring X)",
);
#a few inactive debug functions
sub red {}
sub blue {}
sub callstack {}
sub url_escapeall
{ my $s=$_[0];
_utf8_off($s); # or "use bytes" ?
$s=~s#([^A-Za-z0-9])#sprintf('%%%02X', ord($1))#seg;
return $s;
}
sub url_escape
{ my $s=$_[0];
_utf8_off($s);
$s=~s#([^/\$_.+!*'(),A-Za-z0-9-])#sprintf('%%%02X',ord($1))#seg;
return $s;
}
sub decode_url
{ my $s=$_[0];
return undef unless defined $s;
_utf8_off($s);
$s=~s#%([0-9A-F]{2})#chr(hex $1)#ieg;
return $s;
}
sub PangoEsc # escape special chars for pango ( & < > ) #replaced by Glib::Markup::escape_text if available
{ local $_=$_[0];
return '' unless defined;
s/&/&/g; s/</</g; s/>/>/g;
s/"/"/g; s/'/'/g; # doesn't seem to be needed
return $_;
}
sub MarkupFormat
{ my $format=shift;
sprintf $format, map PangoEsc($_), @_;
}
sub Gtk3::Label::new_with_format
{ my $class=shift;
my $label=Gtk3::Label->new;
$label->set_markup( MarkupFormat(@_) );
return $label;
}
sub Gtk3::Label::set_markup_with_format
{ my $label=shift;
$label->set_markup( MarkupFormat(@_) );
}
sub Gtk3::Entry::enable_autoexpand
{ my $entry=shift;
my $enabled;
my $check_length= sub
{ return unless $enabled;
my $l= $_[0]->get_width_chars;
$l=20 if $l<1;
return unless length($_[0]->get_text) > $l-2;
$_[0]->get_parent->child_set($_[0],$_=>1) for qw/expand fill/;
$enabled=0;
};
my $check_parent= sub
{ my $parent=$_[0]->get_parent;
$enabled= $parent && $parent->isa('Gtk3::Box') && $parent->get_orientation eq 'horizontal';
$check_length->($_[0]);
};
$entry->signal_connect(changed => $check_length);
$entry->signal_connect(parent_set => $check_parent);
$check_parent->($entry)
}
sub Gtk3::Dialog::add_button_custom
{ my ($dialog,$text,$response_id,%args)=@_;
my ($icon,$tip,$secondary)=@args{qw/icon tip secondary/};
my $button= Gtk3::Button->new;
$button->set_image( Gtk3::Image->new_from_stock($icon,'menu') ) if $icon;
$button->set_label($text);
$button->set_use_underline(1);
$button->set_tooltip_text($tip) if defined $tip;
$dialog->add_action_widget($button,$response_id);
if ($secondary)
{ my $bb= $button->get_parent;
if ($bb && $bb->isa('Gtk3::ButtonBox')) { $bb->set_child_secondary($button,1); } #move button to other side
}
return $button;
}
sub IncSuffix # increment a number suffix from a string
{ $_[0] =~ s/(?<=\D)(\d*)$/sprintf "%0".length($1)."d",($1||1)+1/e;
}
sub Ellipsize
{ my ($string,$max)=@_;
return length $string>$max+3 ? substr($string,0,$max)."\x{2026}" : $string;
}
sub Clamp
{ $_[0] > $_[2] ? $_[2] : $_[0] < $_[1] ? $_[1] : $_[0];
}
sub CleanupFileName
{ local $_=$_[0];
s#[[:cntrl:]/:><*?"\\^]##g;
s#^[- ]+##g;
$_=substr $_,0,255 if length>255;
s/[. ]+$//g;
return $_;
}
sub CleanupDirName
{ local $_=$_[0];
if ($^O eq 'MSWin32') { s#[[:cntrl:]/:><*?"^]##g; }
else { s#[[:cntrl:]:><*?"\\^]##g;}
s#^[- ]+##g;
$_=substr $_,0,255 if length>255;
s/[. ]+$//g;
return $_;
}
sub uniq
{ my %h;
map { $h{$_}++ == 0 ? $_ : () } @_;
}
sub sort_number_aware #sort (s1 s10 s2) into (s1 s2 s10)
{ my %h;
($h{$_} = superlc($_)) =~ s/(\d+)/"0"x(20-length($1)).$1/ge for @_; #format numbers with at least 20 digits, will fail for numbers with more than 20 digits, but probably not interesting anyway
return sort {$h{$a} cmp $h{$b}} @_;
}
sub superlc ##lowercase, normalize and remove accents/diacritics #not sure how good it is
{ #test if 8th bit set for any character, if not it's pure ascii and we can just return lc
use bytes; # test is much faster in bytes mode
return lc $_[0] unless $_[0]=~m/[\x80-\xff]/; # lc in bytes mode
no bytes;
my $s=NFKD($_[0]);
$s=~s/\pM//og; #remove Marks (see perlunicode)
#$s=Unicode::Normalize::compose($s); #almost never change anything and should not change comparison result anyway; so better leave it out as it's rather costly
return lc $s; # lc NOT in bytes mode
}
sub superlc_sort
{ return sort {superlc($a) cmp superlc($b)} @_;
}
sub sorted_keys #return keys of $hash sorted by $hash->{$_}{$sort_subkey} or by $hash->{$_} using superlc
{ my ($hash,$sort_subkey)=@_;
if (defined $sort_subkey)
{ return sort { superlc($hash->{$a}{$sort_subkey}) cmp superlc($hash->{$b}{$sort_subkey}) } keys %$hash;
}
else
{ return sort { superlc($hash->{$a}) cmp superlc($hash->{$b}) } keys %$hash;
}
}
sub WordIn #return true if 1st argument is a word contained in the 2nd argument (space-separated words)
{ return 1 if first {$_[0] eq $_} split / +/,$_[1];
return 0;
}
sub OneInCommon #true if at least one string common to both list
{ my ($l1,$l2)=@_;
($l1,$l2)=($l2,$l1) if @$l1>@$l2;
return 0 if @$l1==0;
if (@$l1==1) { my $s=$l1->[0]; return defined first {$_ eq $s} @$l2 }
my %h;
$h{$_}=undef for @$l1;
return 1 if defined first { exists $h{$_} } @$l2;
return 0;
}
sub ListInCommon
{ my ($l1,$l2)=@_;
my %l1; $l1{$_}=undef for @$l1;
grep exists $l1{$_}, @$l2;
}
sub ListNotIn
{ my ($l1,$l2)=@_;
my %l1; $l1{$_}=undef for @$l1;
grep !exists $l1{$_}, @$l2;
}
sub find_common_parent_folder
{ return unless @_;
my @folders= uniq(@_);
my $folder=$folders[0];
my $nb=@folders;
return $folder if $nb==1;
$folder=~s/$QSLASH+$//o;
until ($nb==grep m/^\Q$folder\E(?:$QSLASH|$)/, @folders)
{ $folder='' unless $folder=~m/$QSLASH/o; #for win32 drives
last unless $folder=~s/$QSLASH[^$QSLASH]+$//o;
}
$folder.=SLASH unless $folder=~m/$QSLASH/o;
return $folder;
}
sub ExtractNameAndOptions
{ local $_=$_[0]; #the passed string is modified unless wantarray
my $prefixre=$_[1];
my @res;
while ($_ ne '')
{ s#^\s*##;
my $prefix;
if ($prefixre)
{ $prefix=$1 if s/^$prefixre//;
}
m/[^(\s]*/g; #name in "name(options...)"
my $depth=0;
$depth=1 if m#\G\(#gc;
while ($depth)
{ m#\G(?:[^()]*[^()\\])?([()])?#gc; #search next ()
last unless $1; #end of string
# next if "\\" eq substr($_,pos()-2,1);#escaped () => ignore
if ($1 eq '(') {$depth++}
else {$depth--}
}
my $str=substr $_,0,pos,'';
$str=~s#\\([()])#$1#g; #unescape ()
$str=[$str,$prefix] if $prefixre;
$_[0]=$_ , return $str unless wantarray;
push @res, $str;
}
return @res;
}
sub ParseOptions
{ local $_=$_[0]; #warn "$_\n";
my %opt;
while (m#\G\s*([^= ]+)=\s*#gc)
{ my $key=$1;
if (m#\G(["'])#gc) #quotted
{ my $q= $1 ;
my $v;
if (m#\G((?:[^$q\\]|\\.)*)$q#gc)
{ $v=$1;
$v=~s#\\$q#$q#g;
}
else
{ print "Can't find end of quote in ".(substr $_,pos()-1)."\n";
}
$opt{$key}=$v;
m#\G[^,]*(?:,|$)#gc; #skip the rest
}
else
{ m#\G([^,]*?)\s*(?:,|$)#gc;
$opt{$key}=$1;
}
}
#warn " $_ => $opt{$_}\n" for sort keys %opt; warn "\n";