-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathlibmpdel.el
More file actions
1384 lines (1141 loc) · 48.9 KB
/
libmpdel.el
File metadata and controls
1384 lines (1141 loc) · 48.9 KB
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
;;; libmpdel.el --- Communication with an MPD server -*- lexical-binding: t; -*-
;; Copyright (C) 2017-2025 Damien Cassou
;; Author: Damien Cassou <damien@cassou.me>
;; Keywords: multimedia
;; URL: https://github.com/mpdel/libmpdel
;; Package-Requires: ((emacs "25.1"))
;; Version: 2.1.0
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 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 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 <https://www.gnu.org/licenses/>.
;;; Commentary:
;; The package libmpdel is an Emacs library client to communicate with
;; Music Player Daemon (MPD), a flexible, powerful, server-side
;; application for playing music. For a user interface, please check
;; the mpdel project instead (which depends on this one).
;;; Code:
(require 'time-stamp)
(require 'tq)
(require 'cl-lib)
(require 'subr-x)
(require 'seq)
;;; Customization
(defgroup libmpdel nil
"Communication with an MPD server."
:group 'comm)
(defcustom libmpdel-hostname "localhost"
"MPD server location to connect to. Also see `libmpdel-port'.
If this string starts with a slash, it means connect to a local
Unix socket with such absolute filename. Please see the MPD
server documentation for server configuration info.
The advantage of such a setup is that file and/or directory
permission modes can be used to enforce access control,
without the need for a password."
:type 'string)
(defcustom libmpdel-port 6600
"MPD server port to connect to. Also see `libmpdel-hostname'."
:type 'integer)
(defcustom libmpdel-family 'ipv4
"MPD address family when connecting via TCP connections.
For more information see `libmpdel-hostname'."
:type '(choice (const :tag "IPv4" ipv4)
(const :tag "IPv6" ipv6)))
(defcustom libmpdel-profiles (list (list "Local server" libmpdel-hostname libmpdel-port libmpdel-family))
"List of (NAME HOST PORT . FAMILY) when using several MPD servers."
:type '(repeat (list
:tag "Profile"
:value ("Local server" "localhost" 6600)
(string :tag "name")
(string :tag "host")
(integer :tag "port")
(choice (const :tag "IPv4" ipv4)
(const :tag "IPv6" ipv6)))))
(defcustom libmpdel-music-directory "~/Music"
"MPD `music_directory' variable's value.
This is used to map MPD's music files to the file-system."
:type 'directory)
(defcustom libmpdel-current-playlist-changed-hook nil
"Functions to call when the current playlist is modified."
:type 'hook
:group 'libmpdel)
(defcustom libmpdel-stored-playlist-changed-hook nil
"Functions to call when a stored playlist is modified."
:type 'hook
:group 'libmpdel)
(defcustom libmpdel-player-changed-hook nil
"Functions to call when the player status changes.
This includes starting, stopping and seeking music."
:type 'hook
:group 'libmpdel)
(defcustom libmpdel-current-song-changed-hook nil
"Functions to call when the current song changes.
See `libmpdel-current-song-id'."
:type 'hook
:group 'libmpdel)
;;; Global private variables
(defvar libmpdel--connection nil
"Current connection to the MPD server.
The logs of this connection are accessible in the `*mpd*' buffer.")
(defconst libmpdel--response-regexp
(rx line-start
(or
(and "OK" (? " MPD " (one-or-more not-newline)))
(and "ACK ["
(one-or-more (any digit)) "@" (one-or-more (any digit))
"] " (one-or-more not-newline)))
"\n")
"Regexp matching the responses sent by the MPD server.")
(defconst libmpdel--msgfield-regexp
(rx line-start
(group (+? (not (any ?:))))
": "
(group (* not-newline))
line-end)
"Regexp matching a line consisting of a key and a value.
The key is stored in group 1 and the value in group 2.")
(defvar libmpdel--msghandlers nil
"Current commands sent to the server.
Each element in the list is of the form (COMMAND HANDLER BUFFER).
COMMAND is the query sent to the server. Even though this
information is not necessary, it is useful to better understand
the log.
HANDLER is a function executed when the answers to COMMAND comes
back. The function must accept one parameter (usually named
MESSAGE) that will contain the answer.
BUFFER is a buffer that was active when COMMAND was sent. This
buffer is made active again while executing HANDLER.
An invariant of this MPD client is that there is always an IDLE
command sent to the server (and its corresponding handler in this
variable). This means our client is always registered to
notifications in the server. When we want to send a command to
the server (for example to change the current song), we always
have to (1) cancel the IDLE first (with a \"noidle\"
command), (2) send the command we want, and (3) send the IDLE
command again. Canceling the current \"idle\" command is done
in `mpdel-send-command'. Sending \"idle\" again is done in the
handler for \"idle\" that will be triggered when the empty answer
for the canceled \"idle\" arrives.
Because MPD answers in the order the commands are sent, we know
that the first handler is the one to execute when we receive a
message from the server.")
;;; Data structures
(cl-defstruct (libmpdel-artist
(:constructor libmpdel--artist-create)
(:conc-name libmpdel--artist-))
(name nil :read-only t))
(cl-defstruct (libmpdel-album
(:constructor libmpdel--album-create)
(:conc-name libmpdel--album-))
(name nil :read-only t)
(date nil :read-only t)
(artists nil :read-only t))
(cl-defstruct (libmpdel-song
(:constructor libmpdel--song-create)
(:conc-name libmpdel--song-))
(name nil :read-only t)
(track nil :read-only t)
(file nil :read-only t)
(album nil :read-only t)
(performers nil :read-only t)
(genres nil :read-only t)
(artists nil :read-only t)
(disc nil :read-only t)
(date nil :read-only t)
(id nil :read-only t)
(pos nil :read-only t))
(cl-defstruct (libmpdel-stored-playlist
(:constructor libmpdel--stored-playlist-create)
(:conc-name libmpdel--stored-playlist-))
(name nil :read-only t))
(cl-defstruct (libmpdel-genre
(:constructor libmpdel--genre-create)
(:conc-name libmpdel--genre-))
(name nil :read-only t))
(cl-defstruct (libmpdel-search-criteria
(:constructor libmpdel-search-criteria-create)
(:conc-name libmpdel--search-criteria-))
(type nil :read-only t)
(what nil :read-only t))
(cl-defstruct (libmpdel-filter
(:constructor libmpdel-filter-create)
(:conc-name libmpdel--filter-))
(text nil :read-only t))
(defun libmpdel-artist-name (entity)
"Return artist name of ENTITY."
(libmpdel--artist-name (libmpdel-artist entity)))
(defun libmpdel-artists-name (entity)
"Return semicolon separated string of artists names of ENTITY."
(string-join (mapcar #'libmpdel--artist-name
(libmpdel-artists entity))
"; "))
(cl-defgeneric libmpdel-artist (entity)
"Return artist of ENTITY."
(or (car (libmpdel-artists entity))
libmpdel--unknown-artist))
(cl-defmethod libmpdel-artists ((artist libmpdel-artist))
"Return singleton list containing ARTIST."
(list artist))
(cl-defmethod libmpdel-artists ((album libmpdel-album))
"Return the ALBUM's artist."
(libmpdel--album-artists album))
(cl-defmethod libmpdel-artists ((song libmpdel-song))
"Return the SONG's artists."
(libmpdel--song-artists song))
(defun libmpdel-album-name (entity)
"Return album name of ENTITY."
(libmpdel--album-name (libmpdel-album entity)))
(cl-defgeneric libmpdel-album (entity)
"Return album of ENTITY.")
(cl-defmethod libmpdel-album ((album libmpdel-album))
"Return ALBUM."
album)
(cl-defmethod libmpdel-album ((song libmpdel-song))
"Return SONG's album."
(libmpdel--song-album song))
(cl-defmethod libmpdel-performers ((song libmpdel-song))
"Return SONG's performers."
(libmpdel--song-performers song))
(cl-defmethod libmpdel-genres ((song libmpdel-song))
"Return SONG's genres."
(libmpdel--song-genres song))
(cl-defmethod libmpdel-genres ((genre libmpdel-genre))
"Return singleton list GENRE."
(list genre))
(cl-defgeneric libmpdel-entity-name (entity)
"Return the name of ENTITY.")
(cl-defmethod libmpdel-entity-name ((artist libmpdel-artist))
"Return ARTIST's name."
(libmpdel--artist-name artist))
(cl-defmethod libmpdel-entity-name ((album libmpdel-album))
"Return ALBUM's name."
(libmpdel--album-name album))
(cl-defmethod libmpdel-entity-name ((genre libmpdel-genre))
"Return GENRE's name."
(libmpdel--genre-name genre))
(cl-defmethod libmpdel-entity-name ((song libmpdel-song))
"Return SONG's name.
If the SONG's name is nil, return the filename instead."
(or (libmpdel--song-name song)
(libmpdel--song-file song)))
(cl-defmethod libmpdel-entity-name ((_entity (eql stored-playlists)))
"Return a string describing the `stored-playlists' entity."
"Stored playlists")
(cl-defmethod libmpdel-entity-name ((_entity (eql artists)))
"Return a string describing the `artists' entity."
"All artists")
(cl-defmethod libmpdel-entity-name ((_entity (eql albums)))
"Return a string describing the `albums' entity."
"All albums")
(cl-defmethod libmpdel-entity-name ((_entity (eql genres)))
"Return a string describing the `genres' entity."
"All genres")
(cl-defmethod libmpdel-entity-name ((_entity (eql current-playlist)))
"Return a string describing the `current-playlist' entity."
"Current playlist")
(cl-defmethod libmpdel-entity-name ((stored-playlist libmpdel-stored-playlist))
"Return name of STORED-PLAYLIST."
(libmpdel--stored-playlist-name stored-playlist))
(cl-defmethod libmpdel-entity-name ((search-criteria libmpdel-search-criteria))
"Return a string representing SEARCH-CRITERIA."
(format "search %s: \"%s\""
(libmpdel--search-criteria-type search-criteria)
(libmpdel--search-criteria-what search-criteria)))
(cl-defmethod libmpdel-entity-name ((filter libmpdel-filter))
"Return a string representing FILTER."
(format "filter %s" (libmpdel--filter-text filter)))
(cl-defgeneric libmpdel-entity-parent (_entity)
"Return parent of ENTITY, nil if none."
nil)
(cl-defmethod libmpdel-entity-parent ((song libmpdel-song))
"Return SONG's album."
(libmpdel-album song))
(cl-defmethod libmpdel-entity-parent ((album libmpdel-album))
"Return ALBUM's artist."
(libmpdel-artist album))
(cl-defmethod libmpdel-entity-parent ((_genre libmpdel-genre))
"Return the `genres' entity."
'genres)
(cl-defmethod libmpdel-entity-parent ((_artist libmpdel-artist))
"Return the `artists' entity."
'artists)
(cl-defmethod libmpdel-entity-parent ((_stored-playlist libmpdel-stored-playlist))
"Return the `stored-playlists' entity."
'stored-playlists)
(cl-defgeneric libmpdel-entity-id (entity)
"Return an identifier string for ENTITY."
entity)
(cl-defmethod libmpdel-entity-id ((song libmpdel-song))
"Return the SONG's filename."
;; Override of default implementation to ignore changing ids and
;; position.
(libmpdel--song-file song))
(defun libmpdel-song-file (song)
"Return the filename of SONG."
(libmpdel--song-file song))
(defun libmpdel-song-track (song)
"Return the track number of SONG within its album."
(or (libmpdel--song-track song) ""))
(cl-defgeneric libmpdel-entity-date (entity)
"Return the date of ENTITY.")
(cl-defmethod libmpdel-entity-date ((album libmpdel-album))
"Return ALBUM's date."
(libmpdel--album-date album))
(cl-defmethod libmpdel-entity-date ((song libmpdel-song))
"Return SONG's date."
(libmpdel--song-date song))
(defun libmpdel-song-disc (song)
"Return the disc number of SONG within its album."
(or (libmpdel--song-disc song) ""))
(defun libmpdel-song-id (song)
"Return SONG id within the current playlist, nil if none."
(libmpdel--song-id song))
(defun libmpdel-song-position (song)
"Return position of SONG in playlist, nil if not in playlist."
(let ((pos (libmpdel--song-pos song)))
(when (and (stringp pos) (not (string= pos "")))
(string-to-number pos))))
(defun libmpdel--artists-create (artist-names)
"Return a list of artists whose names are ARTIST-NAMES."
(mapcar (lambda (name)
(libmpdel--artist-create :name name))
artist-names))
(defun libmpdel--genres-create (genre-names)
"Return a list of genres whose names are GENRE-NAMES."
(mapcar (lambda (name)
(libmpdel--genre-create :name name))
genre-names))
(defun libmpdel--create-song-from-data (song-data)
"Return a song from SONG-DATA, a server's response."
(libmpdel--song-create
:name (cdr (assq 'Title song-data))
:track (cdr (assq 'Track song-data))
:file (cdr (assq 'file song-data))
:performers (libmpdel--artists-create (libmpdel-entries song-data 'Performer))
:genres (libmpdel--genres-create (libmpdel-entries song-data 'Genre))
:artists (libmpdel--artists-create (libmpdel-entries song-data 'Artist))
:album (libmpdel--create-album-from-data song-data)
:date (cdr (assq 'Date song-data))
:disc (cdr (assq 'Disc song-data))
:id (cdr (assq 'Id song-data))
:pos (cdr (assq 'Pos song-data))))
(defun libmpdel--create-songs-from-data (data)
"Return a list of songs from DATA, a server's response."
(mapcar #'libmpdel--create-song-from-data (libmpdel-group-data data)))
(defun libmpdel--create-album-from-data (song-data)
"Return an album from SONG-DATA, a server's response."
(libmpdel--album-create
:name (cdr (assq 'Album song-data))
:date (cdr (assq 'Date song-data))
:artists (libmpdel--artists-create (libmpdel-entries song-data 'AlbumArtist))))
(defun libmpdel--create-albums-from-data (data)
"Return a list of albums from DATA, a server's response."
(mapcar #'libmpdel--create-album-from-data (libmpdel-group-data data)))
(defun libmpdel-current-playlist-p (entity)
"Return non-nil if ENTITY is the current playlist."
(eq entity 'current-playlist))
;;; Helper functions
(defun libmpdel--process ()
"Return the process communicating with the MPD server."
(tq-process libmpdel--connection))
(defun libmpdel--process-buffer ()
"Return the buffer associated with the connection process."
(process-buffer (libmpdel--process)))
(defsubst libmpdel--connection-address-local-p ()
"Return non-nil if the MPD server address is a local family address."
(eq ?/ (aref libmpdel-hostname 0)))
(defsubst libmpdel--open-stream ()
"Open and return connection to the MPD process."
(if (not (libmpdel--connection-address-local-p))
(make-network-process
:name "mpd"
:buffer "*mpd*"
:host libmpdel-hostname
:service libmpdel-port
:family libmpdel-family
:type nil)
(make-network-process
:name "mpd" :buffer "*mpd*"
:family 'local :service libmpdel-hostname)))
(defun libmpdel--connect ()
"Create a new connection with the MPD server."
;; The *mpd* buffer will contain all the communication logs
(when (libmpdel-connected-p)
(user-error "A connection is already opened"))
(with-current-buffer (get-buffer-create "*mpd*")
(setq-local buffer-read-only t)
(let ((inhibit-read-only t))
(erase-buffer)))
(setq libmpdel--connection (tq-create (libmpdel--open-stream)))
(set-process-coding-system (libmpdel--process) 'utf-8-unix 'utf-8-unix)
(set-process-query-on-exit-flag (libmpdel--process) nil)
;; Take care of the initial welcome message from server that we
;; don't ask for:
(setq libmpdel--msghandlers '(("welcome" libmpdel--msghandler-ignore nil)))
(tq-queue-add libmpdel--connection nil libmpdel--response-regexp nil #'libmpdel--message-filter)
(libmpdel-refresh-status)
;; As an invariant of the MPD client, there is always an "idle"
;; command sent to the server. This acts like a registration to the
;; server's notifications. See `libmpdel--msghandlers' for more
;; information.
(libmpdel--raw-send-command-with-handler "idle" #'libmpdel--msghandler-idle))
;;;###autoload
(defun libmpdel-connect-profile (profile)
"Connect to MPD server defined in PROFILE.
Interactively, let the user choose PROFILE from `libmpdel-profiles'.
If a connection already exists, terminate it first."
(interactive (list (libmpdel--select-profile)))
(let* ((libmpdel-hostname (cl-second profile))
(libmpdel-port (cl-third profile))
(libmpdel-family (cl-fourth profile)))
(when (libmpdel-connected-p)
(libmpdel-disconnect))
(libmpdel--connect)))
(defun libmpdel--raw-send-command (command)
"Send COMMAND, a string, to the server and log that."
(libmpdel--log command "->")
(tq-enqueue
libmpdel--connection
(format "%s\n" command)
libmpdel--response-regexp
nil
#'libmpdel--message-filter))
(defun libmpdel--raw-send-command-with-handler (command &optional handler)
"Send COMMAND to MPD server and set HANDLER for the response.
If HANDLER is nil, response will be ignored.
If command is a string, send that. Otherwise, it must be a list
that will be passed to `format' before being sent."
(let ((command (if (listp command)
(apply #'format command)
command)))
(setq libmpdel--msghandlers
(append libmpdel--msghandlers
`((,command
,(or handler #'libmpdel--msghandler-ignore)
,(current-buffer)))))
(libmpdel--raw-send-command command)))
(defun libmpdel--message-filter (_ message)
"Take care of the MESSAGE sent by the server.
The first parameter is ignored. MESSAGE contains a string
representing the answer from the server."
;; Because errors in handlers are not raised by Emacs, we log them.
(condition-case-unless-debug error
(progn
;; because answers arrive in the same order we sent the
;; commands, we are sure that the first handler is the one to
;; use.
(cl-destructuring-bind (command handler buffer) (pop libmpdel--msghandlers)
(libmpdel--log (format "\"%s\" (as answer to \"%s\")" message command)
"<-")
;; if answer is a ACK, then there was a problem. We log it as such.
(if (string= (substring message 0 3) "ACK")
(libmpdel--log "ACK message" "ko")
(with-current-buffer (if (buffer-live-p buffer) buffer (current-buffer))
(funcall handler (libmpdel--extract-data message))))))
(error (libmpdel--log error "ko"))))
(defun libmpdel--log (string type-string)
"Add STRING at end of *mpd* buffer.
TYPE-STRING is a two-letter string classifying the kind of
message to log."
(with-current-buffer (libmpdel--process-buffer)
(let ((inhibit-read-only t)
(moving (= (point) (process-mark (libmpdel--process)))))
(save-excursion
;; Insert the text, advancing the process marker.
(goto-char (process-mark (libmpdel--process)))
(insert "-------------------------\n")
(insert (format "%s [%s] %s\n" type-string (time-stamp-string) string))
(set-marker (process-mark (libmpdel--process)) (point)))
(if moving (goto-char (process-mark (libmpdel--process)))))))
(defun libmpdel--msghandler-idle (data)
"Handler for the response DATA to the \"idle\" command.
This handler is responsible for sending another \"idle\"
command."
;; Because "idle" only informs about what changed (e.g., "the
;; playback state changed") without telling the new state (e.g.,
;; "the player is now stopped"), we have to ask for the details:
(when data
(libmpdel-refresh-status))
;; Each time an "idle" is finished, we start a new one:
(libmpdel--raw-send-command-with-handler "idle" #'libmpdel--msghandler-idle)
(mapc (lambda (changed-subsystem)
(cl-case (intern (cdr changed-subsystem))
;; At this point, libmpdel has only been informed that
;; something changed (e.g., "the current playlist has been
;; changed"). We don't have the details (e.g., "the
;; current playlist contains these songs"). As a result,
;; hook functions will have to fetch the details by
;; themselves if they need to. On the contrary, for hook
;; functions requiring libmpdel to have new data, use
;; `libmpdel--msghandler-status'.
(playlist (run-hooks 'libmpdel-current-playlist-changed-hook))
(stored_playlist (run-hooks 'libmpdel-stored-playlist-changed-hook))))
data))
(defun libmpdel--msghandler-status (data)
"Handler for the response DATA to the \"status\" command."
(dolist (status-pair data)
(let ((status-key (car status-pair))
(status-value (cdr status-pair)))
(cl-case status-key
(state (libmpdel--set-play-state status-value))
(songid (libmpdel--set-current-song status-value))
(playlistlength (libmpdel--set-playlist-length status-value))
(volume (libmpdel--set-volume status-value))
(random (libmpdel--set-random status-value))
(repeat (libmpdel--set-repeat status-value))
(single (libmpdel--set-single status-value)))))
;; When no song is being played, 'songid is not in DATA. If that's
;; the case, we have to set current song to nil:
(unless (cl-member 'songid data :key #'car)
(libmpdel--set-current-song nil)))
(defun libmpdel--msghandler-ignore (_)
"No handler was associated to last response."
;; nothing to do
nil)
(defun libmpdel--extract-data (message)
"Return MESSAGE."
(save-match-data
(with-temp-buffer
(insert message)
(let ((end-of-message (line-beginning-position))
(data nil))
(goto-char (point-min))
(while (re-search-forward libmpdel--msgfield-regexp end-of-message t)
(push (cons (intern (match-string 1)) (match-string 2)) data))
(reverse data)))))
(defun libmpdel--string<-ignore-case (str1 str2)
"Compare the contents of STR1 and STR2, ignoring case."
(let ((comp (compare-strings str1 nil nil str2 nil nil t)))
(or (eq comp t) (< comp 0))))
(defmacro libmpdel--define-state (name value-desc &rest set-body)
"Generate code to set and get state for NAME.
Name is a symbol (e.g., `volume' or `play-state') naming the
state to generate code for.
VALUE-DESC is a string describing the kind of value accepted for
this state.
SET-BODY is a list of forms to put in the generated setter
function. During execution of SET-BODY, a variable NEW-VALUE is
bound containing the value to set."
(declare (indent 1))
`(progn
(defvar ,(intern (format "libmpdel--%s" name)) nil
,(format "Current %s of MPD server.\n%s" name value-desc))
(defun ,(intern (format "libmpdel--set-%s" name)) (new-value)
,(format "Save NEW-VALUE as current %s.\n%s" name value-desc)
,@set-body)
(defun ,(intern (format "libmpdel-%s" name)) ()
,(format "Return current value of %s.\n%s" name value-desc)
,(intern (format "libmpdel--%s" name)))))
(libmpdel--define-state play-state
"Value is `play', `pause' or `stop'."
(let ((new-state (intern new-value))
(old-state libmpdel--play-state))
(unless (equal old-state new-state)
(setq libmpdel--play-state new-state)
(run-hooks 'libmpdel-player-changed-hook))))
(defun libmpdel-playing-p ()
"Return non-nil if player is playing, nil otherwise."
(eq 'play (libmpdel-play-state)))
(defun libmpdel-paused-p ()
"Return non-nil if player is paused, nil otherwise."
(eq 'pause (libmpdel-play-state)))
(defun libmpdel-stopped-p ()
"Return non-nil if player is stopped, nil otherwise."
(eq 'stop (libmpdel-play-state)))
(libmpdel--define-state current-song
"An entity representing currently played song."
(when (libmpdel--new-current-song-p new-value)
(libmpdel-send-command
"currentsong"
(lambda (data)
(setq libmpdel--current-song (and data (libmpdel--create-song-from-data data)))
(run-hooks 'libmpdel-current-song-changed-hook)))))
(defun libmpdel--new-current-song-p (song-id)
"Return non-nil if SONG-ID differs from `libmpdel--current-song'."
(let ((current-song-id (and libmpdel--current-song (libmpdel-song-id libmpdel--current-song))))
(not (equal song-id current-song-id))))
(libmpdel--define-state playlist-length
"Number of songs in current playlist."
(setq libmpdel--playlist-length (string-to-number new-value)))
(libmpdel--define-state volume
"Value is a string representing a number between 0 and 100."
(setq libmpdel--volume new-value))
(libmpdel--define-state random
"Boolean indicating if songs are played randomly or in order."
(setq libmpdel--random (string= new-value "1")))
(libmpdel--define-state repeat
"Boolean indicating if current playlist or song is repeated after it ends."
(setq libmpdel--repeat (string= new-value "1")))
(libmpdel--define-state single
"Symbol indicating if current song is repeated `forever', only `once' or `never'."
(setq libmpdel--single
(cond
((string= new-value "oneshot") 'once)
((string= new-value "1") 'forever)
(t 'never))))
(defun libmpdel-get-state (state handler)
"Run HANDLER, a function, passing the value for STATE as argument.
STATE is one of the following symbols: \\=`playlist-length',
\\=`volume', \\=`random', \\=`repeat' or \\=`single'.
If the server's status is available, HANDLER is called
synchronously. Otherwise, HANDLER is called asynchronously when
the response for status information comes back."
(let* ((fstate (intern (format "libmpdel-%s" state)))
(call-handler (lambda () (funcall handler (funcall fstate)))))
(if (and (funcall fstate) (libmpdel-connected-p))
(funcall call-handler)
(libmpdel-refresh-status call-handler))))
(defun libmpdel-time-to-string (time)
"Return a string representing TIME, a number in a string."
(if (not time)
"0"
(let* ((time (string-to-number time))
(seconds (mod time 60))
(minutes (/ (- time seconds) 60)))
(format "%02d:%02d" (truncate minutes) (truncate seconds)))))
(cl-defun libmpdel-completing-read (prompt entities &key category)
"PROMPT user to select one entity among ENTITIES.
Return the selected entity.
Transform each entity to a string with `libmpdel-entity-name'.
The user is allowed to exit by typing a string not matching any
entity. In this case, the user must confirm and the typed string
is returned.
CATEGORY may be used to specify the type of object being listed.
This is used by some packages to show additional information
about each candidate or to provide contextual menus.
The string representation of each element of ENTITIES include the
`libmpdel-entity' text property whose value is the entity
represented by the string. This is useful for the tools working
directly on the completion candidates (such as embark)."
(let* ((map (make-hash-table :test 'equal :size (length entities)))
(entity-strings (mapcar (lambda (entity) (propertize
(funcall #'libmpdel-entity-name entity)
'libmpdel-entity entity))
entities)))
(cl-loop for entity in entities
for entity-string in entity-strings
do (puthash entity-string entity map))
(let ((entity-string (completing-read prompt
(lambda (string predicate action)
(if (eq action 'metadata)
(list 'metadata (when category (cons 'category category)))
(complete-with-action
action entity-strings string predicate)))
nil 'confirm)))
(gethash entity-string map entity-string))))
(defun libmpdel-completing-read-entity (function prompt entity &rest rest)
"Call FUNCTION after prompting for an element of ENTITY.
Pass PROMPT and the elements of ENTITY to
`libmpdel-completing-read'."
(libmpdel-list
entity
(lambda (entities)
(funcall function
(apply #'libmpdel-completing-read prompt entities rest)))))
(defun libmpdel-funcall-on-stored-playlist (function)
"Pass a stored playlist as parameter to FUNCTION.
The user is asked to choose for a stored playlist first.
The user is allowed to enter a name for a non-existing stored
playlist. In this case, the user must confirm and the stored
playlist is created before being passed as parameter to
FUNCTION."
(libmpdel-completing-read-entity
(lambda (stored-playlist)
(let ((stored-playlist (if (stringp stored-playlist)
(libmpdel--stored-playlist-create :name stored-playlist)
stored-playlist)))
(funcall function stored-playlist)))
"Stored playlist: "
'stored-playlists))
(defun libmpdel-current-playlist-add (entity)
"Add ENTITY to the current playlist.
ENTITY can also be a list of entities to add."
(libmpdel-playlist-add entity 'current-playlist))
(defun libmpdel-current-playlist-replace (entity)
"Replace current playlist with ENTITY.
ENTITY can also be a list of entities to replace with."
(libmpdel-playlist-replace entity 'current-playlist))
(defun libmpdel-stored-playlist-add (entity)
"Add ENTITY to a stored playlist.
The user is asked to choose for a stored playlist first.
ENTITY can also be a list of entities to add."
(libmpdel-funcall-on-stored-playlist
(apply-partially #'libmpdel-playlist-add entity)))
(defun libmpdel-stored-playlist-replace (entity)
"Replace a stored playlist with ENTITY.
The user is asked to choose for a stored playlist first.
ENTITY can also be a list of entities to replace with."
(libmpdel-funcall-on-stored-playlist
(apply-partially #'libmpdel-playlist-replace entity)))
(defun libmpdel-current-playlist-insert (entity)
"Insert ENTITY after currently-played song and play it.
ENTITY can also be a list of entities in which case all entities
are added and the first one is played."
(libmpdel-list-songs
entity
(lambda (songs)
(libmpdel-send-commands
(mapcar (lambda (song) (format "addid %S" (libmpdel-song-file song))) songs)
(lambda (data)
(let ((song-ids (mapcar (lambda (song-data) (cdr song-data)) data))
;; Add after current song if possible:
(target-index (if (libmpdel-current-song) "-1" "0")))
(libmpdel-send-commands
;; The reverse is important to get the songs in the same
;; order as in the selection:
(mapcar
(lambda (song-id) (format "moveid %s %s" song-id target-index))
(reverse song-ids))
(lambda (_) (libmpdel-send-command `("playid %s" ,(car song-ids)))))))))))
(defun libmpdel-async-mapcar (list mapfn callback)
"Apply MAPFN to each element of LIST and pass result to CALLBACK.
MAPFN is a function taking 2 arguments: the element to map and a
callback to call when the mapping is done."
(if (not list)
(funcall callback nil)
(funcall ; transform the first element
mapfn
(car list)
(lambda (first-mapped)
(libmpdel-async-mapcar ; transform the rest
(cdr list)
mapfn
(lambda (latter-elements)
(funcall callback
(cons first-mapped
latter-elements))))))))
(defun libmpdel-async-mapcan (list mapfn callback)
"Apply MAPFN to each element of LIST.
Concatenate the results and pass that to CALLBACK.
MAPFN is a function taking 2 arguments: the element to map and a
callback to call when the mapping is done."
(libmpdel-async-mapcar
list
mapfn
(lambda (groups)
(funcall
callback
(apply #'cl-concatenate 'list groups)))))
(defun libmpdel--get-profile-from-name (name)
"Return an element of `libmpdel-profiles' matching NAME."
(cl-find name libmpdel-profiles :test #'string= :key #'car))
(defun libmpdel--select-profile ()
"Ask the user to select a profile among `libmpdel-profiles' and return it."
(unless (consp libmpdel-profiles)
(user-error "Add profiles to `libmpdel-profiles'"))
(if (= 1 (length libmpdel-profiles))
(progn
(message "Only 1 profile defined in `libmpdel-profiles'")
(car libmpdel-profiles))
(let* ((profile-names (mapcar #'car libmpdel-profiles))
(profile-name (completing-read "Choose an MPD profile"
profile-names nil t)))
(libmpdel--get-profile-from-name profile-name))))
;;; Public functions
(defun libmpdel-connected-p ()
"Return non-nil if there is a connection to MPD server."
(and libmpdel--connection
(process-live-p (libmpdel--process))))
(defun libmpdel-ensure-connection ()
"Make sure there is an active connection to the MPD server."
(unless (libmpdel-connected-p)
(libmpdel--connect)))
(defun libmpdel-disconnect ()
"Close connection to the MPD server."
(when (not (libmpdel-connected-p))
(user-error "There is no connection to MPD"))
(tq-close libmpdel--connection)
(setq libmpdel--connection nil))
(defun libmpdel-send-command (command &optional handler)
"Send COMMAND to server and register HANDLER for the answer.
If HANDLER is nil, ignore response."
(libmpdel-ensure-connection)
;; if current command is IDLE, we have to cancel it. See
;; `mpdel-msghandlers' for more information.
(when (eql (elt (car (last libmpdel--msghandlers)) 1) #'libmpdel--msghandler-idle)
(libmpdel--raw-send-command "noidle"))
(libmpdel--raw-send-command-with-handler command handler))
(defun libmpdel-send-commands (commands &optional handler)
"Send several COMMANDS at once and execute HANDLER once with result."
(libmpdel-send-command
(with-temp-buffer
(insert "command_list_begin\n")
(mapc (lambda (command) (insert command "\n")) commands)
(insert "command_list_end")
(buffer-substring-no-properties (point-min) (point-max)))
handler))
(defun libmpdel-entries (data key)
"Collect DATA entries matching KEY."
(mapcar #'cdr (cl-remove-if-not (apply-partially #'eq key) data :key #'car)))
(defun libmpdel-sorted-entries (data key)
"Sort and collect DATA entries matching KEY."
(sort (libmpdel-entries data key) #'libmpdel--string<-ignore-case))
(defun libmpdel-group-data (data)
"Find repeating fields in DATA and group them."
(when data
(let ((first-key (caar data))
result group)
(mapc (lambda (key-value)
(when (and
(eq (car key-value) first-key)
group)
(push (reverse group) result)
(setq group nil))
(push key-value group))
data)
(push (reverse group) result)
(reverse result))))
(cl-defgeneric libmpdel-dired (entity)
"Open `dired' on ENTITY.")
(eval-when-compile
(declare-function dired-jump "dired-x"))
(cl-defmethod libmpdel-dired ((song libmpdel-song))
"Open `dired' on SONG."
(require 'dired-x)
(dired-jump t (expand-file-name (libmpdel-song-file song) libmpdel-music-directory)))
(defun libmpdel-equal (entity1 entity2)
"Return non-nil if ENTITY1 and ENTITY2 represent the same entity."
(equal (libmpdel-entity-id entity1) (libmpdel-entity-id entity2)))
;;; Helper queries
(cl-defgeneric libmpdel-entity-to-criteria (entity)
"Return search query matching all songs from ENTITY.")
(cl-defmethod libmpdel-entity-to-criteria ((query string))
"Return QUERY."
query)
(cl-defmethod libmpdel-entity-to-criteria ((artist libmpdel-artist))
"Return search query matching all songs from ARTIST."
(format "artist %S" (libmpdel-entity-name artist)))
(cl-defmethod libmpdel-entity-to-criteria ((album libmpdel-album))
"Return search query matching all songs from ALBUM."
(format "%s album %S"
(string-join
(mapcar (lambda (artist)
(format "albumartist %S" (libmpdel-entity-name artist)))
(libmpdel-artists album))
" ")