]> code.delx.au - gnu-emacs/blob - lisp/mpc.el
* lisp/mpc.el (mpc-songs-refresh): Don't side-effect `active'
[gnu-emacs] / lisp / mpc.el
1 ;;; mpc.el --- A client for the Music Player Daemon -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2006-2015 Free Software Foundation, Inc.
4
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Keywords: multimedia
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; This is an Emacs front end to the Music Player Daemon.
26
27 ;; It mostly provides a browser inspired from Rhythmbox for your music
28 ;; collection and also allows you to play the music you select. The basic
29 ;; interface is somewhat unusual in that it does not focus on the
30 ;; playlist as much as on the browser.
31 ;; I play albums rather than songs and thus don't have much need for
32 ;; playlists, and it shows. Playlist support exists, but is still limited.
33
34 ;; Bugs:
35
36 ;; - when reaching end/start of song while ffwd/rewind, it may get wedged,
37 ;; signal an error, ... or when mpc-next/prev is called while ffwd/rewind.
38 ;; - MPD errors are not reported to the user.
39
40 ;; Todo:
41
42 ;; - add bindings/buttons/menuentries for the various commands.
43 ;; - mpc-undo
44 ;; - visual feedback for drag'n'drop
45 ;; - display/set `repeat' and `random' state (and maybe also `crossfade').
46 ;; - allow multiple *mpc* sessions in the same Emacs to control different mpds.
47 ;; - fetch album covers and lyrics from the web?
48 ;; - improve MPC-Status: better volume control, add a way to show/hide the
49 ;; rest, plus add the buttons currently in the toolbar.
50 ;; - improve mpc-songs-mode's header-line column-headings so they can be
51 ;; dragged to resize.
52 ;; - allow selecting several entries by drag-mouse.
53 ;; - poll less often
54 ;; - use the `idle' command
55 ;; - do the time-ticking locally (and sync every once in a while)
56 ;; - look at the end of play time to make sure we notice the end
57 ;; as soon as possible
58 ;; - better volume widget.
59 ;; - add synthesized tags.
60 ;; e.g. pseudo-artist = artist + composer + performer.
61 ;; e.g. pseudo-performer = performer or artist
62 ;; e.g. rewrite artist "Foo bar & baz" to "Foo bar".
63 ;; e.g. filename regexp -> compilation flag
64 ;; - window/buffer management.
65 ;; - menubar, tooltips, ...
66 ;; - add mpc-describe-song, mpc-describe-album, ...
67 ;; - add import/export commands (especially export to an MP3 player).
68 ;; - add a real notion of album (as opposed to just album-name):
69 ;; if all songs with same album-name have same artist -> it's an album
70 ;; else it's either several albums or a compilation album (or both),
71 ;; in which case we could use heuristics or user provided info:
72 ;; - if the user followed the 1-album = 1-dir idea, then we can group songs
73 ;; by their directory to create albums.
74 ;; - if a `compilation' flag is available, and if <=1 of the songs have it
75 ;; set, then we can group songs by their artist to create albums.
76 ;; - if two songs have the same track-nb and disk-nb, they're not in the
77 ;; same album. So from the set of songs with identical album names, we
78 ;; can get a lower bound on the number of albums involved, and then see
79 ;; which of those may be non-compilations, etc...
80 ;; - use a special directory name for compilations.
81 ;; - ask the web ;-)
82
83 ;;; Code:
84
85 ;; Prefixes used in this code:
86 ;; mpc-proc : management of connection (in/out formatting, ...)
87 ;; mpc-status : auto-updated status info
88 ;; mpc-volume : stuff handling the volume widget
89 ;; mpc-cmd : mpdlib abstraction
90
91 ;; UI-commands : mpc-
92 ;; internal : mpc--
93
94 (eval-when-compile (require 'cl-lib))
95
96 (defgroup mpc ()
97 "Client for the Music Player Daemon (mpd)."
98 :prefix "mpc-"
99 :group 'multimedia
100 :group 'applications)
101
102 (defcustom mpc-browser-tags '(Genre Artist|Composer|Performer
103 Album|Playlist)
104 "Tags for which a browser buffer should be created by default."
105 ;; FIXME: provide a list of tags, for completion.
106 :type '(repeat symbol))
107
108 ;;; Misc utils ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
109
110 (defun mpc-assq-all (key alist)
111 (let ((res ()) val)
112 (dolist (elem alist)
113 (if (and (eq (car elem) key)
114 (not (member (setq val (cdr elem)) res)))
115 (push val res)))
116 (nreverse res)))
117
118 (defun mpc-union (&rest lists)
119 (let ((res (nreverse (pop lists))))
120 (dolist (list lists)
121 (let ((seen res)) ;Don't remove duplicates within each list.
122 (dolist (elem list)
123 (unless (member elem seen) (push elem res)))))
124 (nreverse res)))
125
126 (defun mpc-intersection (l1 l2 &optional selectfun)
127 "Return L1 after removing all elements not found in L2.
128 If SELECTFUN is non-nil, elements aren't compared directly, but instead
129 they are passed through SELECTFUN before comparison."
130 (let ((res ()))
131 (if selectfun (setq l2 (mapcar selectfun l2)))
132 (dolist (elem l1)
133 (when (member (if selectfun (funcall selectfun elem) elem) l2)
134 (push elem res)))
135 (nreverse res)))
136
137 (defun mpc-event-set-point (event)
138 (condition-case nil (posn-set-point (event-end event))
139 (error (condition-case nil (mouse-set-point event)
140 (error nil)))))
141
142 (defun mpc-compare-strings (str1 str2 &optional ignore-case)
143 "Compare strings STR1 and STR2.
144 Contrary to `compare-strings', this tries to get numbers sorted
145 numerically rather than lexicographically."
146 (let ((res (compare-strings str1 nil nil str2 nil nil ignore-case)))
147 (if (not (integerp res)) res
148 (let ((index (1- (abs res))))
149 (if (or (>= index (length str1)) (>= index (length str2)))
150 res
151 (let ((digit1 (memq (aref str1 index)
152 '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9)))
153 (digit2 (memq (aref str2 index)
154 '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9))))
155 (if digit1
156 (if digit2
157 (let ((num1 (progn (string-match "[0-9]+" str1 index)
158 (match-string 0 str1)))
159 (num2 (progn (string-match "[0-9]+" str2 index)
160 (match-string 0 str2))))
161 (cond
162 ;; Here we presume that leading zeroes are only used
163 ;; for same-length numbers. So we'll incorrectly
164 ;; consider that "000" comes after "01", but I don't
165 ;; think it matters.
166 ((< (length num1) (length num2)) (- (abs res)))
167 ((> (length num1) (length num2)) (abs res))
168 ((< (string-to-number num1) (string-to-number num2))
169 (- (abs res)))
170 (t (abs res))))
171 ;; "1a" comes before "10", but "0" comes before "a".
172 (if (and (not (zerop index))
173 (memq (aref str1 (1- index))
174 '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9)))
175 (abs res)
176 (- (abs res))))
177 (if digit2
178 ;; "1a" comes before "10", but "0" comes before "a".
179 (if (and (not (zerop index))
180 (memq (aref str1 (1- index))
181 '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9)))
182 (- (abs res))
183 (abs res))
184 res))))))))
185
186 (define-obsolete-function-alias 'mpc-string-prefix-p 'string-prefix-p "24.3")
187
188 ;; This can speed up mpc--song-search significantly. The table may grow
189 ;; very large, tho. It's only bounded by the fact that it gets flushed
190 ;; whenever the connection is established; which seems to work OK thanks
191 ;; to the fact that MPD tends to disconnect fairly often, although our
192 ;; constant polling often prevents disconnection.
193 (defvar mpc--find-memoize (make-hash-table :test 'equal)) ;; :weakness t
194 (defvar-local mpc-tag nil)
195
196 ;;; Support for the actual connection and MPD command execution ;;;;;;;;;;;;
197
198 (defcustom mpc-host
199 (concat (or (getenv "MPD_HOST") "localhost")
200 (if (getenv "MPD_PORT") (concat ":" (getenv "MPD_PORT"))))
201 "Host (and port) where the Music Player Daemon is running. The
202 format is \"HOST\", \"HOST:PORT\", \"PASSWORD@HOST\" or
203 \"PASSWORD@HOST:PORT\" where PASSWORD defaults to no password, PORT
204 defaults to 6600 and HOST defaults to localhost."
205 :type 'string)
206
207 (defvar mpc-proc nil)
208
209 (defconst mpc--proc-end-re "^\\(?:OK\\(?: MPD .*\\)?\\|ACK \\(.*\\)\\)\n")
210
211 (define-error 'mpc-proc-error "MPD error")
212
213 (defun mpc--debug (format &rest args)
214 (if (get-buffer "*MPC-debug*")
215 (with-current-buffer "*MPC-debug*"
216 (goto-char (point-max))
217 (insert-before-markers ;So it scrolls.
218 (replace-regexp-in-string "\n" "\n "
219 (apply #'format-message format args))
220 "\n"))))
221
222 (defun mpc--proc-filter (proc string)
223 (mpc--debug "Receive \"%s\"" string)
224 (with-current-buffer (process-buffer proc)
225 (if (process-get proc 'ready)
226 (if nil ;; (string-match "\\`\\(OK\n\\)+\\'" string)
227 ;; I haven't figured out yet why I get those extraneous OKs,
228 ;; so I'll just ignore them for now.
229 nil
230 (delete-process proc)
231 (set-process-buffer proc nil)
232 (pop-to-buffer (clone-buffer))
233 (error "MPD output while idle!?"))
234 (save-excursion
235 (let ((start (or (marker-position (process-mark proc)) (point-min))))
236 (goto-char start)
237 (insert string)
238 (move-marker (process-mark proc) (point))
239 (beginning-of-line)
240 (when (and (< start (point))
241 (re-search-backward mpc--proc-end-re start t))
242 (process-put proc 'ready t)
243 (unless (eq (match-end 0) (point-max))
244 (error "Unexpected trailing text"))
245 (let ((error-text (match-string 1)))
246 (delete-region (point) (point-max))
247 (let ((callback (process-get proc 'callback)))
248 (process-put proc 'callback nil)
249 (if error-text
250 (process-put proc 'mpc-proc-error error-text))
251 (funcall callback)))))))))
252
253 (defun mpc--proc-connect (host)
254 (let ((port 6600)
255 local
256 pass)
257
258 (when (string-match "\\`\\(?:\\(.*\\)@\\)?\\(.*?\\)\\(?::\\(.*\\)\\)?\\'"
259 host)
260 (let ((v (match-string 1 host)))
261 (when (and (stringp v) (not (string= "" v)))
262 (setq pass v)))
263 (let ((v (match-string 3 host)))
264 (setq host (match-string 2 host))
265 (when (and (stringp v) (not (string= "" v)))
266 (setq port
267 (if (string-match "[^[:digit:]]" v)
268 (string-to-number v)
269 v)))))
270 (when (file-name-absolute-p host)
271 ;; Expand file name because `file-name-absolute-p'
272 ;; considers paths beginning with "~" as absolute
273 (setq host (expand-file-name host))
274 (setq local t))
275
276 (mpc--debug "Connecting to %s:%s..." host port)
277 (with-current-buffer (get-buffer-create (format " *mpc-%s:%s*" host port))
278 ;; (pop-to-buffer (current-buffer))
279 (let (proc)
280 (while (and (setq proc (get-buffer-process (current-buffer)))
281 (progn ;; (debug)
282 (delete-process proc)))))
283 (erase-buffer)
284 (let* ((coding-system-for-read 'utf-8-unix)
285 (coding-system-for-write 'utf-8-unix)
286 (proc (condition-case err
287 (make-network-process :name "MPC" :buffer (current-buffer)
288 :host (unless local host)
289 :service (if local host port)
290 :family (if local 'local))
291 (error (user-error (error-message-string err))))))
292 (when (processp mpc-proc)
293 ;; Inherit the properties of the previous connection.
294 (let ((plist (process-plist mpc-proc)))
295 (while plist (process-put proc (pop plist) (pop plist)))))
296 (mpc-proc-buffer proc 'mpd-commands (current-buffer))
297 (process-put proc 'callback 'ignore)
298 (process-put proc 'ready nil)
299 (clrhash mpc--find-memoize)
300 (set-process-filter proc 'mpc--proc-filter)
301 (set-process-sentinel proc 'ignore)
302 (set-process-query-on-exit-flag proc nil)
303 ;; This may be called within a process filter ;-(
304 (with-local-quit (mpc-proc-sync proc))
305 (setq mpc-proc proc)
306 (when pass
307 (mpc-proc-cmd (list "password" pass) nil))))))
308
309 (defun mpc--proc-quote-string (s)
310 (if (numberp s) (number-to-string s)
311 (setq s (replace-regexp-in-string "[\"\\]" "\\\\\\&" s))
312 (if (string-match " " s) (concat "\"" s "\"") s)))
313
314 (defconst mpc--proc-alist-to-alists-starters '(file directory))
315
316 (defun mpc--proc-alist-to-alists (alist)
317 (cl-assert (or (null alist)
318 (memq (caar alist) mpc--proc-alist-to-alists-starters)))
319 (let ((starter (caar alist))
320 (alists ())
321 tmp)
322 (dolist (pair alist)
323 (when (eq (car pair) starter)
324 (if tmp (push (nreverse tmp) alists))
325 (setq tmp ()))
326 (push pair tmp))
327 (if tmp (push (nreverse tmp) alists))
328 (nreverse alists)))
329
330 (defun mpc-proc (&optional restart)
331 (unless (and mpc-proc
332 (buffer-live-p (process-buffer mpc-proc))
333 (not (and restart
334 (memq (process-status mpc-proc) '(closed)))))
335 (mpc--proc-connect mpc-host))
336 mpc-proc)
337
338 (defun mpc-proc-check (proc)
339 (let ((error-text (process-get proc 'mpc-proc-error)))
340 (when error-text
341 (process-put proc 'mpc-proc-error nil)
342 (signal 'mpc-proc-error error-text))))
343
344 (defun mpc-proc-sync (&optional proc)
345 "Wait for MPC process until it is idle again.
346 Return the buffer in which the process is/was running."
347 (unless proc (setq proc (mpc-proc)))
348 (unwind-protect
349 (progn
350 (while (and (not (process-get proc 'ready))
351 (accept-process-output proc)))
352 (mpc-proc-check proc)
353 (if (process-get proc 'ready) (process-buffer proc)
354 (error "No response from MPD")))
355 (unless (process-get proc 'ready)
356 ;; (debug)
357 (message "Killing hung process")
358 (delete-process proc))))
359
360 (defun mpc-proc-cmd (cmd &optional callback)
361 "Send command CMD to the MPD server.
362 If CALLBACK is nil, wait for the command to finish before returning,
363 otherwise return immediately and call CALLBACK with no argument
364 when the command terminates.
365 CMD can be a string which is passed as-is to MPD or a list of strings
366 which will be concatenated with proper quoting before passing them to MPD."
367 (let ((proc (mpc-proc 'restart)))
368 (if (and callback (not (process-get proc 'ready)))
369 (let ((old (process-get proc 'callback)))
370 (process-put proc 'callback
371 (lambda ()
372 (funcall old)
373 (mpc-proc-cmd cmd callback))))
374 ;; Wait for any pending async command to terminate.
375 (mpc-proc-sync proc)
376 (process-put proc 'ready nil)
377 (with-current-buffer (process-buffer proc)
378 (erase-buffer)
379 (mpc--debug "Send \"%s\"" cmd)
380 (process-send-string
381 proc (concat (if (stringp cmd) cmd
382 (mapconcat 'mpc--proc-quote-string cmd " "))
383 "\n")))
384 (if callback
385 ;; (let ((buf (current-buffer)))
386 (process-put proc 'callback
387 callback
388 ;; (lambda ()
389 ;; (funcall callback
390 ;; (prog1 (current-buffer)
391 ;; (set-buffer buf)))))
392 )
393 ;; If `callback' is nil, we're executing synchronously.
394 (process-put proc 'callback 'ignore)
395 ;; This returns the process's buffer.
396 (mpc-proc-sync proc)))))
397
398 ;; This function doesn't exist in Emacs-21.
399 ;; (put 'mpc-proc-cmd-list 'byte-optimizer 'byte-optimize-pure-func)
400 (defun mpc-proc-cmd-list (cmds)
401 (concat "command_list_begin\n"
402 (mapconcat (lambda (cmd)
403 (if (stringp cmd) cmd
404 (mapconcat 'mpc--proc-quote-string cmd " ")))
405 cmds
406 "\n")
407 "\ncommand_list_end"))
408
409 (defun mpc-proc-cmd-list-ok ()
410 ;; To implement this, we'll need to tweak the process filter since we'd
411 ;; then sometimes get "trailing" text after "OK\n".
412 (error "Not implemented yet"))
413
414 (defun mpc-proc-buf-to-alist (&optional buf)
415 (with-current-buffer (or buf (current-buffer))
416 (let ((res ()))
417 (goto-char (point-min))
418 (while (re-search-forward "^\\([^:]+\\): \\(.*\\)\n" nil t)
419 (push (cons (intern (match-string 1)) (match-string 2)) res))
420 (nreverse res))))
421
422 (defun mpc-proc-buf-to-alists (buf)
423 (mpc--proc-alist-to-alists (mpc-proc-buf-to-alist buf)))
424
425 (defun mpc-proc-cmd-to-alist (cmd &optional callback)
426 (if callback
427 (let ((buf (current-buffer)))
428 (mpc-proc-cmd cmd (lambda ()
429 (funcall callback (prog1 (mpc-proc-buf-to-alist
430 (current-buffer))
431 (set-buffer buf))))))
432 ;; (let ((res nil))
433 ;; (mpc-proc-cmd-to-alist cmd (lambda (alist) (setq res alist)))
434 ;; (mpc-proc-sync)
435 ;; res)
436 (mpc-proc-buf-to-alist (mpc-proc-cmd cmd))))
437
438 (defun mpc-proc-tag-string-to-sym (tag)
439 (intern (capitalize tag)))
440
441 (defun mpc-proc-buffer (proc use &optional buffer)
442 (let* ((bufs (process-get proc 'buffers))
443 (buf (cdr (assoc use bufs))))
444 (cond
445 ((and buffer (buffer-live-p buf) (not (eq buffer buf)))
446 (error "Duplicate MPC buffer for %s" use))
447 (buffer
448 (if buf
449 (setcdr (assoc use bufs) buffer)
450 (process-put proc 'buffers (cons (cons use buffer) bufs))))
451 (t buf))))
452
453 ;;; Support for regularly updated current status information ;;;;;;;;;;;;;;;
454
455 ;; Exported elements:
456 ;; `mpc-status' holds the uptodate data.
457 ;; `mpc-status-callbacks' holds the registered callback functions.
458 ;; `mpc-status-refresh' forces a refresh of the data.
459 ;; `mpc-status-stop' stops the automatic updating.
460
461 (defvar mpc-status nil)
462 (defvar mpc-status-callbacks
463 '((state . mpc--status-timers-refresh)
464 ;; (song . mpc--queue-refresh)
465 ;; (state . mpc--queue-refresh) ;To detect the end of the last song.
466 (state . mpc--faster-toggle-refresh) ;Only ffwd/rewind while play/pause.
467 (volume . mpc-volume-refresh)
468 (file . mpc-songpointer-refresh)
469 ;; The song pointer may need updating even if the file doesn't change,
470 ;; if the same song appears multiple times in a row.
471 (song . mpc-songpointer-refresh)
472 (updating_db . mpc-updated-db)
473 (updating_db . mpc--status-timers-refresh)
474 (t . mpc-current-refresh))
475 "Alist associating properties to the functions that care about them.
476 Each entry has the form (PROP . FUN) where PROP can be t to mean
477 to call FUN for any change whatsoever.")
478
479 (defun mpc--status-callback ()
480 (let ((old-status mpc-status))
481 ;; Update the alist.
482 (setq mpc-status (mpc-proc-buf-to-alist))
483 (cl-assert mpc-status)
484 (unless (equal old-status mpc-status)
485 ;; Run the relevant refresher functions.
486 (dolist (pair mpc-status-callbacks)
487 (when (or (eq t (car pair))
488 (not (equal (cdr (assq (car pair) old-status))
489 (cdr (assq (car pair) mpc-status)))))
490 (funcall (cdr pair)))))))
491
492 (defvar mpc--status-timer nil)
493 (defun mpc--status-timer-start ()
494 (add-hook 'pre-command-hook 'mpc--status-timer-stop)
495 (unless mpc--status-timer
496 (setq mpc--status-timer (run-with-timer 1 1 'mpc--status-timer-run))))
497 (defun mpc--status-timer-stop ()
498 (when mpc--status-timer
499 (cancel-timer mpc--status-timer)
500 (setq mpc--status-timer nil)))
501 (defun mpc--status-timer-run ()
502 (with-demoted-errors "MPC: %S"
503 (when (process-get (mpc-proc) 'ready)
504 (let* ((buf (mpc-proc-buffer (mpc-proc) 'status))
505 (win (get-buffer-window buf t)))
506 (if (not win)
507 (mpc--status-timer-stop)
508 (with-local-quit (mpc-status-refresh)))))))
509
510 (defvar mpc--status-idle-timer nil)
511 (defun mpc--status-idle-timer-start ()
512 (when mpc--status-idle-timer
513 ;; Turn it off even if we'll start it again, in case it changes the delay.
514 (cancel-timer mpc--status-idle-timer))
515 (setq mpc--status-idle-timer
516 (run-with-idle-timer 1 t 'mpc--status-idle-timer-run))
517 ;; Typically, the idle timer is started from the mpc--status-callback,
518 ;; which is run asynchronously while we're already idle (we typically
519 ;; just started idling), so the timer itself will only be run the next
520 ;; time we idle :-(
521 ;; To work around that, we immediately start the repeat timer.
522 (mpc--status-timer-start))
523 (defun mpc--status-idle-timer-stop (&optional really)
524 (when mpc--status-idle-timer
525 ;; Turn it off even if we'll start it again, in case it changes the delay.
526 (cancel-timer mpc--status-idle-timer))
527 (setq mpc--status-idle-timer
528 (unless really
529 ;; We don't completely stop the timer, so that if some other MPD
530 ;; client starts playback, we may get a chance to notice it.
531 (run-with-idle-timer 10 t 'mpc--status-idle-timer-run))))
532 (defun mpc--status-idle-timer-run ()
533 (mpc--status-timer-start)
534 (mpc--status-timer-run))
535
536 (defun mpc--status-timers-refresh ()
537 "Start/stop the timers according to whether a song is playing."
538 (if (or (member (cdr (assq 'state mpc-status)) '("play"))
539 (cdr (assq 'updating_db mpc-status)))
540 (mpc--status-idle-timer-start)
541 (mpc--status-idle-timer-stop)
542 (mpc--status-timer-stop)))
543
544 (defun mpc-status-refresh (&optional callback)
545 "Refresh `mpc-status'."
546 (let ((cb callback))
547 (mpc-proc-cmd (mpc-proc-cmd-list '("status" "currentsong"))
548 (lambda ()
549 (mpc--status-callback)
550 (if cb (funcall cb))))))
551
552 (defun mpc-status-stop ()
553 "Stop the autorefresh of `mpc-status'.
554 This is normally used only when quitting MPC.
555 Any call to `mpc-status-refresh' may cause it to be restarted."
556 (setq mpc-status nil)
557 (mpc--status-idle-timer-stop 'really)
558 (mpc--status-timer-stop))
559
560 ;;; A thin layer above the raw protocol commands ;;;;;;;;;;;;;;;;;;;;;;;;;;;
561
562 ;; (defvar mpc-queue nil)
563 ;; (defvar mpc-queue-back nil)
564
565 ;; (defun mpc--queue-head ()
566 ;; (if (stringp (car mpc-queue)) (car mpc-queue) (cadar mpc-queue)))
567 ;; (defun mpc--queue-pop ()
568 ;; (when mpc-queue ;Can be nil if out of sync.
569 ;; (let ((song (car mpc-queue)))
570 ;; (cl-assert song)
571 ;; (push (if (and (consp song) (cddr song))
572 ;; ;; The queue's first element is itself a list of
573 ;; ;; songs, where the first element isn't itself a song
574 ;; ;; but a description of the list.
575 ;; (prog1 (cadr song) (setcdr song (cddr song)))
576 ;; (prog1 (if (consp song) (cadr song) song)
577 ;; (setq mpc-queue (cdr mpc-queue))))
578 ;; mpc-queue-back)
579 ;; (cl-assert (stringp (car mpc-queue-back))))))
580
581 ;; (defun mpc--queue-refresh ()
582 ;; ;; Maintain the queue.
583 ;; (mpc--debug "mpc--queue-refresh")
584 ;; (let ((pos (cdr (or (assq 'Pos mpc-status) (assq 'song mpc-status)))))
585 ;; (cond
586 ;; ((null pos)
587 ;; (mpc-cmd-clear 'ignore))
588 ;; ((or (not (member pos '("0" nil)))
589 ;; ;; There's only one song in the playlist and we've stopped.
590 ;; ;; Maybe it's because of some external client that set the
591 ;; ;; playlist like that and/or manually stopped the playback, but
592 ;; ;; it's more likely that we've simply reached the end of
593 ;; ;; the song. So remove it.
594 ;; (and (equal (assq 'state mpc-status) "stop")
595 ;; (equal (assq 'playlistlength mpc-status) "1")
596 ;; (setq pos "1")))
597 ;; ;; We're not playing the first song in the queue/playlist any
598 ;; ;; more, so update the queue.
599 ;; (dotimes (i (string-to-number pos)) (mpc--queue-pop))
600 ;; (mpc-proc-cmd (mpc-proc-cmd-list
601 ;; (make-list (string-to-number pos) "delete 0"))
602 ;; 'ignore)
603 ;; (if (not (equal (cdr (assq 'file mpc-status))
604 ;; (mpc--queue-head)))
605 ;; (message "MPC's queue is out of sync"))))))
606
607 (defvar mpc--find-memoize-union-tags nil)
608
609 (defun mpc-cmd-flush (tag value)
610 (puthash (cons tag value) nil mpc--find-memoize)
611 (dolist (uniontag mpc--find-memoize-union-tags)
612 (if (member (symbol-name tag) (split-string (symbol-name uniontag) "|"))
613 (puthash (cons uniontag value) nil mpc--find-memoize))))
614
615
616 (defun mpc-cmd-special-tag-p (tag)
617 (or (memq tag '(Playlist Search Directory))
618 (string-match "|" (symbol-name tag))))
619
620 (defun mpc-cmd-find (tag value)
621 "Return a list of all songs whose tag TAG has value VALUE.
622 The songs are returned as alists."
623 (or (gethash (cons tag value) mpc--find-memoize)
624 (puthash (cons tag value)
625 (cond
626 ((eq tag 'Playlist)
627 ;; Special case for pseudo-tag playlist.
628 (let ((l (condition-case nil
629 (mpc-proc-buf-to-alists
630 (mpc-proc-cmd (list "listplaylistinfo" value)))
631 (mpc-proc-error
632 ;; "[50@0] {listplaylistinfo} No such playlist"
633 nil)))
634 (i 0))
635 (mapcar (lambda (s)
636 (prog1 (cons (cons 'Pos (number-to-string i)) s)
637 (cl-incf i)))
638 l)))
639 ((eq tag 'Search)
640 (mpc-proc-buf-to-alists
641 (mpc-proc-cmd (list "search" "any" value))))
642 ((eq tag 'Directory)
643 (let ((pairs
644 (mpc-proc-buf-to-alist
645 (mpc-proc-cmd (list "listallinfo" value)))))
646 (mpc--proc-alist-to-alists
647 ;; Strip away the `directory' entries.
648 (delq nil (mapcar (lambda (pair)
649 (if (eq (car pair) 'directory)
650 nil pair))
651 pairs)))))
652 ((string-match "|" (symbol-name tag))
653 (add-to-list 'mpc--find-memoize-union-tags tag)
654 (let ((tag1 (intern (substring (symbol-name tag)
655 0 (match-beginning 0))))
656 (tag2 (intern (substring (symbol-name tag)
657 (match-end 0)))))
658 (mpc-union (mpc-cmd-find tag1 value)
659 (mpc-cmd-find tag2 value))))
660 (t
661 (condition-case nil
662 (mpc-proc-buf-to-alists
663 (mpc-proc-cmd (list "find" (symbol-name tag) value)))
664 (mpc-proc-error
665 ;; If `tag' is not one of the expected tags, MPD burps
666 ;; about not having the relevant table. FIXME: check
667 ;; the kind of error.
668 (error "Unknown tag %s" tag)
669 (let ((res ()))
670 (setq value (cons tag value))
671 (dolist (song (mpc-proc-buf-to-alists
672 (mpc-proc-cmd "listallinfo")))
673 (if (member value song) (push song res)))
674 res)))))
675 mpc--find-memoize)))
676
677 (defun mpc-cmd-list (tag &optional other-tag value)
678 ;; FIXME: we could also provide a `mpc-cmd-list' alternative which
679 ;; doesn't take an "other-tag value" constraint but a "song-list" instead.
680 ;; That might be more efficient in some cases.
681 (cond
682 ((eq tag 'Playlist)
683 (let ((pls (mpc-assq-all 'playlist (mpc-proc-cmd-to-alist "lsinfo"))))
684 (when other-tag
685 (dolist (pl (prog1 pls (setq pls nil)))
686 (let ((plsongs (mpc-cmd-find 'Playlist pl)))
687 (if (not (mpc-cmd-special-tag-p other-tag))
688 (when (member (cons other-tag value)
689 (apply 'append plsongs))
690 (push pl pls))
691 ;; Problem N°2: we compute the intersection whereas all
692 ;; we care about is whether it's empty. So we could
693 ;; speed this up significantly.
694 ;; We only compare file names, because the full song-entries
695 ;; are slightly different (the ones in plsongs include
696 ;; position and id info specific to the playlist), and it's
697 ;; good enough because this is only used with "search", which
698 ;; doesn't pay attention to playlists and URLs anyway.
699 (let* ((osongs (mpc-cmd-find other-tag value))
700 (ofiles (mpc-assq-all 'file (apply 'append osongs)))
701 (plfiles (mpc-assq-all 'file (apply 'append plsongs))))
702 (when (mpc-intersection plfiles ofiles)
703 (push pl pls)))))))
704 pls))
705
706 ((eq tag 'Directory)
707 (if (null other-tag)
708 (apply 'nconc
709 (mpc-assq-all 'directory
710 (mpc-proc-buf-to-alist
711 (mpc-proc-cmd "lsinfo")))
712 (mapcar (lambda (dir)
713 (let ((shortdir
714 (if (get-text-property 0 'display dir)
715 (concat " "
716 (get-text-property 0 'display dir))
717 " ↪ "))
718 (subdirs
719 (mpc-assq-all 'directory
720 (mpc-proc-buf-to-alist
721 (mpc-proc-cmd (list "lsinfo" dir))))))
722 (dolist (subdir subdirs)
723 (put-text-property 0 (1+ (length dir))
724 'display shortdir
725 subdir))
726 subdirs))
727 (process-get (mpc-proc) 'Directory)))
728 ;; If there's an other-tag, then just extract the dir info from the
729 ;; list of other-tag's songs.
730 (let* ((other-songs (mpc-cmd-find other-tag value))
731 (files (mpc-assq-all 'file (apply 'append other-songs)))
732 (dirs '()))
733 (dolist (file files)
734 (let ((dir (file-name-directory file)))
735 (if (and dir (setq dir (directory-file-name dir))
736 (not (equal dir (car dirs))))
737 (push dir dirs))))
738 ;; Dirs might have duplicates still.
739 (setq dirs (delete-dups dirs))
740 (let ((newdirs dirs))
741 (while newdirs
742 (let ((dir (file-name-directory (pop newdirs))))
743 (when (and dir (setq dir (directory-file-name dir))
744 (not (member dir dirs)))
745 (push dir newdirs)
746 (push dir dirs)))))
747 dirs)))
748
749 ;; The UI should not provide access to such a thing anyway currently.
750 ;; But I could imagine adding in the future a browser for the "search"
751 ;; tag, which would provide things like previous searches. Not sure how
752 ;; useful that would be tho.
753 ((eq tag 'Search) (error "Not supported"))
754
755 ((string-match "|" (symbol-name tag))
756 (let ((tag1 (intern (substring (symbol-name tag)
757 0 (match-beginning 0))))
758 (tag2 (intern (substring (symbol-name tag)
759 (match-end 0)))))
760 (mpc-union (mpc-cmd-list tag1 other-tag value)
761 (mpc-cmd-list tag2 other-tag value))))
762
763 ((null other-tag)
764 (condition-case nil
765 (mapcar 'cdr (mpc-proc-cmd-to-alist (list "list" (symbol-name tag))))
766 (mpc-proc-error
767 ;; If `tag' is not one of the expected tags, MPD burps about not
768 ;; having the relevant table.
769 ;; FIXME: check the kind of error.
770 (error "MPD does not know this tag %s" tag)
771 (mpc-assq-all tag (mpc-proc-cmd-to-alist "listallinfo")))))
772 (t
773 (condition-case nil
774 (if (mpc-cmd-special-tag-p other-tag)
775 (signal 'mpc-proc-error "Not implemented")
776 (mapcar 'cdr
777 (mpc-proc-cmd-to-alist
778 (list "list" (symbol-name tag)
779 (symbol-name other-tag) value))))
780 (mpc-proc-error
781 ;; DAMN!! the 3-arg form of `list' is new in 0.12 !!
782 ;; FIXME: check the kind of error.
783 (let ((other-songs (mpc-cmd-find other-tag value)))
784 (mpc-assq-all tag
785 ;; Don't use `nconc' now that mpc-cmd-find may
786 ;; return a memoized result.
787 (apply 'append other-songs))))))))
788
789 (defun mpc-cmd-stop (&optional callback)
790 (mpc-proc-cmd "stop" callback))
791
792 (defun mpc-cmd-clear (&optional callback)
793 (mpc-proc-cmd "clear" callback)
794 ;; (setq mpc-queue-back nil mpc-queue nil)
795 )
796
797 (defun mpc-cmd-pause (&optional arg callback)
798 "Pause or resume playback of the queue of songs."
799 (let ((cb callback))
800 (mpc-proc-cmd (list "pause" arg)
801 (lambda () (mpc-status-refresh) (if cb (funcall cb))))
802 (unless callback (mpc-proc-sync))))
803
804 (defun mpc-cmd-status ()
805 (mpc-proc-cmd-to-alist "status"))
806
807 (defun mpc-cmd-play ()
808 (mpc-proc-cmd "play")
809 (mpc-status-refresh))
810
811 (defun mpc-cmd-add (files &optional playlist)
812 "Add the songs FILES to PLAYLIST.
813 If PLAYLIST is t or nil or missing, use the main playlist."
814 (mpc-proc-cmd (mpc-proc-cmd-list
815 (mapcar (lambda (file)
816 (if (stringp playlist)
817 (list "playlistadd" playlist file)
818 (list "add" file)))
819 files)))
820 (if (stringp playlist)
821 (mpc-cmd-flush 'Playlist playlist)))
822
823 (defun mpc-cmd-delete (song-poss &optional playlist)
824 "Delete the songs at positions SONG-POSS from PLAYLIST.
825 If PLAYLIST is t or nil or missing, use the main playlist."
826 (mpc-proc-cmd (mpc-proc-cmd-list
827 (mapcar (lambda (song-pos)
828 (if (stringp playlist)
829 (list "playlistdelete" playlist song-pos)
830 (list "delete" song-pos)))
831 ;; Sort them from last to first, so the renumbering
832 ;; caused by the earlier deletions don't affect
833 ;; later ones.
834 (sort song-poss '>))))
835 (if (stringp playlist)
836 (puthash (cons 'Playlist playlist) nil mpc--find-memoize)))
837
838
839 (defun mpc-cmd-move (song-poss dest-pos &optional playlist)
840 (let ((i 0))
841 (mpc-proc-cmd
842 (mpc-proc-cmd-list
843 (mapcar (lambda (song-pos)
844 (if (>= song-pos dest-pos)
845 ;; positions past dest-pos have been
846 ;; shifted by i.
847 (setq song-pos (+ song-pos i)))
848 (prog1 (if (stringp playlist)
849 (list "playlistmove" playlist song-pos dest-pos)
850 (list "move" song-pos dest-pos))
851 (if (< song-pos dest-pos)
852 ;; This move has shifted dest-pos by 1.
853 (cl-decf dest-pos))
854 (cl-incf i)))
855 ;; Sort them from last to first, so the renumbering
856 ;; caused by the earlier deletions affect
857 ;; later ones a bit less.
858 (sort song-poss '>))))
859 (if (stringp playlist)
860 (puthash (cons 'Playlist playlist) nil mpc--find-memoize))))
861
862 (defun mpc-cmd-update (&optional arg callback)
863 (let ((cb callback))
864 (mpc-proc-cmd (if arg (list "update" arg) "update")
865 (lambda () (mpc-status-refresh) (if cb (funcall cb))))
866 (unless callback (mpc-proc-sync))))
867
868 (defun mpc-cmd-tagtypes ()
869 (mapcar 'cdr (mpc-proc-cmd-to-alist "tagtypes")))
870
871 ;; This was never integrated into MPD.
872 ;; (defun mpc-cmd-download (file)
873 ;; (with-current-buffer (generate-new-buffer " *mpc download*")
874 ;; (set-buffer-multibyte nil)
875 ;; (let* ((proc (mpc-proc))
876 ;; (stdbuf (process-buffer proc))
877 ;; (markpos (marker-position (process-mark proc)))
878 ;; (stdcoding (process-coding-system proc)))
879 ;; (unwind-protect
880 ;; (progn
881 ;; (set-process-buffer proc (current-buffer))
882 ;; (set-process-coding-system proc 'binary (cdr stdcoding))
883 ;; (set-marker (process-mark proc) (point))
884 ;; (mpc-proc-cmd (list "download" file)))
885 ;; (set-process-buffer proc stdbuf)
886 ;; (set-marker (process-mark proc) markpos stdbuf)
887 ;; (set-process-coding-system proc (car stdcoding) (cdr stdcoding)))
888 ;; ;; The command has completed, let's decode.
889 ;; (goto-char (point-max))
890 ;; (delete-char -1) ;Delete final newline.
891 ;; (while (re-search-backward "^>" nil t)
892 ;; (delete-char 1))
893 ;; (current-buffer))))
894
895 ;;; Misc ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
896
897 (defcustom mpc-mpd-music-directory nil
898 "Location of MPD's music directory."
899 :type '(choice (const nil) directory))
900
901 (defcustom mpc-data-directory
902 (locate-user-emacs-file "mpc" ".mpc")
903 "Directory where MPC.el stores auxiliary data."
904 :type 'directory)
905
906 (defun mpc-data-directory ()
907 (unless (file-directory-p mpc-data-directory)
908 (make-directory mpc-data-directory))
909 mpc-data-directory)
910
911 (defun mpc-file-local-copy (file)
912 ;; Try to set mpc-mpd-music-directory.
913 (when (and (null mpc-mpd-music-directory)
914 (or (string-match "\\`localhost" mpc-host)
915 (file-name-absolute-p mpc-host)))
916 (let ((files `(,(let ((xdg (getenv "XDG_CONFIG_HOME")))
917 (concat (if (and xdg (file-name-absolute-p xdg))
918 xdg "~/.config")
919 "/mpd/mpd.conf"))
920 "~/.mpdconf" "~/.mpd/mpd.conf" "/etc/mpd.conf"))
921 file)
922 (while (and files (not file))
923 (if (file-exists-p (car files)) (setq file (car files)))
924 (setq files (cdr files)))
925 (with-temp-buffer
926 (ignore-errors (insert-file-contents file))
927 (goto-char (point-min))
928 (if (re-search-forward "^music_directory[ ]+\"\\([^\"]+\\)\"")
929 (setq mpc-mpd-music-directory
930 (match-string 1))))))
931 ;; Use mpc-mpd-music-directory if applicable, or else try to use the
932 ;; `download' command, although it's never been accepted in `mpd' :-(
933 (if (and mpc-mpd-music-directory
934 (file-exists-p (expand-file-name file mpc-mpd-music-directory)))
935 (expand-file-name file mpc-mpd-music-directory)
936 ;; (let ((aux (expand-file-name (replace-regexp-in-string "[/]" "|" file)
937 ;; (mpc-data-directory))))
938 ;; (unless (file-exists-p aux)
939 ;; (condition-case err
940 ;; (with-local-quit
941 ;; (with-current-buffer (mpc-cmd-download file)
942 ;; (write-region (point-min) (point-max) aux)
943 ;; (kill-buffer (current-buffer))))
944 ;; (mpc-proc-error (message "Download error: %s" err) (setq aux nil))))
945 ;; aux)
946 ))
947
948 ;;; Formatter ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
949
950 (defun mpc-secs-to-time (secs)
951 ;; We could use `format-seconds', but it doesn't seem worth the trouble
952 ;; because we'd still need to check (>= secs (* 60 100)) since the special
953 ;; %z only allows us to drop the large units for small values but
954 ;; not to drop the small units for large values.
955 (if (stringp secs) (setq secs (string-to-number secs)))
956 (if (>= secs (* 60 100)) ;More than 100 minutes.
957 (format "%dh%02d" ;"%d:%02d:%02d"
958 (/ secs 3600) (% (/ secs 60) 60)) ;; (% secs 60)
959 (format "%d:%02d" (/ secs 60) (% secs 60))))
960
961 (defvar mpc-tempfiles nil)
962 (defconst mpc-tempfiles-reftable (make-hash-table :weakness 'key))
963
964 (defun mpc-tempfiles-clean ()
965 (let ((live ()))
966 (maphash (lambda (_k v) (push v live)) mpc-tempfiles-reftable)
967 (dolist (f mpc-tempfiles)
968 (unless (member f live) (ignore-errors (delete-file f))))
969 (setq mpc-tempfiles live)))
970
971 (defun mpc-tempfiles-add (key file)
972 (mpc-tempfiles-clean)
973 (puthash key file mpc-tempfiles-reftable)
974 (push file mpc-tempfiles))
975
976 (defun mpc-format (format-spec info &optional hscroll)
977 "Format the INFO according to FORMAT-SPEC, inserting the result at point."
978 (let* ((pos 0)
979 (start (point))
980 (col (if hscroll (- hscroll) 0))
981 (insert (lambda (str)
982 (cond
983 ((>= col 0) (insert str))
984 (t (insert (substring str (min (length str) (- col))))))))
985 (pred nil))
986 (while (string-match "%\\(?:%\\|\\(-\\)?\\([0-9]+\\)?{\\([[:alpha:]][[:alnum:]]*\\)\\(?:-\\([^}]+\\)\\)?}\\)" format-spec pos)
987 (let ((pre-text (substring format-spec pos (match-beginning 0))))
988 (funcall insert pre-text)
989 (setq col (+ col (string-width pre-text))))
990 (setq pos (match-end 0))
991 (if (null (match-end 3))
992 (progn
993 (funcall insert "%")
994 (setq col (+ col 1)))
995 (let* ((size (match-string 2 format-spec))
996 (tag (intern (match-string 3 format-spec)))
997 (post (match-string 4 format-spec))
998 (right-align (match-end 1))
999 (text
1000 (if (eq info 'self) (symbol-name tag)
1001 (pcase tag
1002 ((or `Time `Duration)
1003 (let ((time (cdr (or (assq 'time info) (assq 'Time info)))))
1004 (setq pred (list nil)) ;Just assume it's never eq.
1005 (when time
1006 (mpc-secs-to-time (if (and (eq tag 'Duration)
1007 (string-match ":" time))
1008 (substring time (match-end 0))
1009 time)))))
1010 (`Cover
1011 (let* ((dir (file-name-directory
1012 (mpc-file-local-copy (cdr (assq 'file info)))))
1013 (covers '(".folder.png" "cover.jpg" "folder.jpg"))
1014 (cover (cl-loop for file in (directory-files dir)
1015 if (member (downcase file) covers)
1016 return (concat dir file)))
1017 (file (with-demoted-errors "MPC: %s"
1018 (mpc-file-local-copy cover)))
1019 image)
1020 ;; (debug)
1021 (push `(equal ',dir (file-name-directory (cdr (assq 'file info)))) pred)
1022 (if (null file)
1023 ;; Make sure we return something on which we can
1024 ;; place the `mpc-pred' property, as
1025 ;; a negative-cache. We could also use
1026 ;; a default cover.
1027 (progn (setq size nil) " ")
1028 (if (null size) (setq image (create-image file))
1029 (let ((tempfile (make-temp-file "mpc" nil ".jpg")))
1030 (call-process "convert" nil nil nil
1031 "-scale" size file tempfile)
1032 (setq image (create-image tempfile))
1033 (mpc-tempfiles-add image tempfile)))
1034 (setq size nil)
1035 (propertize dir 'display image))))
1036 (_ (let ((val (cdr (assq tag info))))
1037 ;; For Streaming URLs, there's no other info
1038 ;; than the URL in `file'. Pretend it's in `Title'.
1039 (when (and (null val) (eq tag 'Title))
1040 (setq val (cdr (assq 'file info))))
1041 (push `(equal ',val (cdr (assq ',tag info))) pred)
1042 (cond
1043 ((not (and (eq tag 'Date) (stringp val))) val)
1044 ;; For "date", only keep the year!
1045 ((string-match "[0-9]\\{4\\}" val)
1046 (match-string 0 val))
1047 (t val)))))))
1048 (space (when size
1049 (setq size (string-to-number size))
1050 (propertize " " 'display
1051 (list 'space :align-to (+ col size)))))
1052 (textwidth (if text (string-width text) 0))
1053 (postwidth (if post (string-width post) 0)))
1054 (when text
1055 (let ((display
1056 (if (and size
1057 (> (+ postwidth textwidth) size))
1058 (propertize
1059 (truncate-string-to-width text size nil nil "…")
1060 'help-echo text)
1061 text)))
1062 (when (memq tag '(Artist Album Composer)) ;FIXME: wrong list.
1063 (setq display
1064 (propertize display
1065 'mouse-face 'highlight
1066 'follow-link t
1067 'keymap `(keymap
1068 (mouse-2
1069 . (lambda ()
1070 (interactive)
1071 (mpc-constraints-push 'noerror)
1072 (mpc-constraints-restore
1073 ',(list (list tag text)))))))))
1074 (funcall insert
1075 (concat (when size
1076 (propertize " " 'display
1077 (list 'space :align-to
1078 (+ col
1079 (if (and size right-align)
1080 (- size postwidth textwidth)
1081 0)))))
1082 display post))))
1083 (if (null size) (setq col (+ col textwidth postwidth))
1084 (insert space)
1085 (setq col (+ col size))))))
1086 (put-text-property start (point) 'mpc-pred
1087 `(lambda (info) (and ,@(nreverse pred))))))
1088
1089 ;;; The actual UI code ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1090
1091 (defvar mpc-mode-map
1092 (let ((map (make-keymap)))
1093 (suppress-keymap map)
1094 ;; (define-key map "\e" 'mpc-stop)
1095 (define-key map "q" 'mpc-quit)
1096 (define-key map "\r" 'mpc-select)
1097 (define-key map [(shift return)] 'mpc-select-toggle)
1098 (define-key map [mouse-2] 'mpc-select)
1099 (define-key map [S-mouse-2] 'mpc-select-extend)
1100 (define-key map [C-mouse-2] 'mpc-select-toggle)
1101 (define-key map [drag-mouse-2] 'mpc-drag-n-drop)
1102 ;; We use `always' because a binding to t is like a binding to nil.
1103 (define-key map [follow-link] :always)
1104 ;; But follow-link doesn't apply blindly to header-line and
1105 ;; mode-line clicks.
1106 (define-key map [header-line follow-link] 'ignore)
1107 (define-key map [mode-line follow-link] 'ignore)
1108 ;; Doesn't work because the first click changes the buffer, so the second
1109 ;; is applied elsewhere :-(
1110 ;; (define-key map [(double mouse-2)] 'mpc-play-at-point)
1111 (define-key map "p" 'mpc-pause)
1112 map))
1113
1114 (easy-menu-define mpc-mode-menu mpc-mode-map
1115 "Menu for MPC.el."
1116 '("MPC.el"
1117 ["Add new browser" mpc-tagbrowser]
1118 ["Update DB" mpc-update]
1119 ["Quit" mpc-quit]))
1120
1121 (defvar mpc-tool-bar-map
1122 (let ((map (make-sparse-keymap)))
1123 (tool-bar-local-item "mpc/prev" 'mpc-prev 'prev map
1124 :enable '(not (equal (cdr (assq 'state mpc-status)) "stop"))
1125 :label "Prev" :vert-only t)
1126 ;; FIXME: how can we bind it to the down-event?
1127 (tool-bar-local-item "mpc/rewind" 'mpc-rewind 'rewind map
1128 :enable '(not (equal (cdr (assq 'state mpc-status)) "stop"))
1129 :label "Rew" :vert-only t
1130 :button '(:toggle . (and mpc--faster-toggle-timer
1131 (not mpc--faster-toggle-forward))))
1132 ;; We could use a single toggle command for pause/play, with 2 different
1133 ;; icons depending on whether or not it's selected, but then it'd have
1134 ;; to be a toggle-button, thus displayed depressed in one of the
1135 ;; two states :-(
1136 (tool-bar-local-item "mpc/pause" 'mpc-pause 'pause map
1137 :label "Pause" :vert-only t
1138 :visible '(equal (cdr (assq 'state mpc-status)) "play")
1139 :help "Pause/play")
1140 (tool-bar-local-item "mpc/play" 'mpc-play 'play map
1141 :label "Play" :vert-only t
1142 :visible '(not (equal (cdr (assq 'state mpc-status)) "play"))
1143 :help "Play/pause")
1144 ;; FIXME: how can we bind it to the down-event?
1145 (tool-bar-local-item "mpc/ffwd" 'mpc-ffwd 'ffwd map
1146 :enable '(not (equal (cdr (assq 'state mpc-status)) "stop"))
1147 :label "Ffwd" :vert-only t
1148 :button '(:toggle . (and mpc--faster-toggle-timer
1149 mpc--faster-toggle-forward)))
1150 (tool-bar-local-item "mpc/next" 'mpc-next 'next map
1151 :label "Next" :vert-only t
1152 :enable '(not (equal (cdr (assq 'state mpc-status)) "stop")))
1153 (tool-bar-local-item "mpc/stop" 'mpc-stop 'stop map
1154 :label "Stop" :vert-only t)
1155 (tool-bar-local-item "mpc/add" 'mpc-playlist-add 'add map
1156 :label "Add" :vert-only t
1157 :help "Append to the playlist")
1158 map))
1159
1160 (define-derived-mode mpc-mode fundamental-mode "MPC"
1161 "Major mode for the features common to all buffers of MPC."
1162 (buffer-disable-undo)
1163 (setq buffer-read-only t)
1164 (if (boundp 'tool-bar-map) ; not if --without-x
1165 (setq-local tool-bar-map mpc-tool-bar-map))
1166 (setq-local truncate-lines t))
1167
1168 ;;; The mpc-status-mode buffer ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1169
1170 (define-derived-mode mpc-status-mode mpc-mode "MPC-Status"
1171 "Major mode to display MPC status info."
1172 (setq-local mode-line-format
1173 '("%e" mode-line-frame-identification
1174 mode-line-buffer-identification))
1175 (setq-local window-area-factor 3)
1176 (setq-local header-line-format '("MPC " mpc-volume)))
1177
1178 (defvar mpc-status-buffer-format
1179 '("%-5{Time} / %{Duration} %2{Disc--}%4{Track}" "%{Title}" "%{Album}" "%{Artist}" "%128{Cover}"))
1180
1181 (defun mpc-status-buffer-refresh ()
1182 (let ((buf (mpc-proc-buffer (mpc-proc) 'status)))
1183 (when (buffer-live-p buf)
1184 (with-current-buffer buf
1185 (save-excursion
1186 (goto-char (point-min))
1187 (when (assq 'file mpc-status)
1188 (let ((inhibit-read-only t))
1189 (dolist (spec mpc-status-buffer-format)
1190 (let ((pred (get-text-property (point) 'mpc-pred)))
1191 (if (and pred (funcall pred mpc-status))
1192 (forward-line)
1193 (delete-region (point) (line-beginning-position 2))
1194 (ignore-errors (mpc-format spec mpc-status))
1195 (insert "\n"))))
1196 (unless (eobp) (delete-region (point) (point-max))))))))))
1197
1198 (defun mpc-status-buffer-show ()
1199 (interactive)
1200 (let* ((proc (mpc-proc))
1201 (buf (mpc-proc-buffer proc 'status))
1202 (songs-buf (mpc-proc-buffer proc 'songs))
1203 (songs-win (if songs-buf (get-buffer-window songs-buf 0))))
1204 (unless (buffer-live-p buf)
1205 (setq buf (get-buffer-create "*MPC-Status*"))
1206 (with-current-buffer buf
1207 (mpc-status-mode))
1208 (mpc-proc-buffer proc 'status buf))
1209 (if (null songs-win) (pop-to-buffer buf)
1210 (let ((_win (split-window songs-win 20 t)))
1211 (set-window-dedicated-p songs-win nil)
1212 (set-window-buffer songs-win buf)
1213 (set-window-dedicated-p songs-win 'soft)))))
1214
1215 ;;; Selection management;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1216
1217 (defvar mpc-separator-ol nil)
1218
1219 (defvar-local mpc-select nil)
1220
1221 (defmacro mpc-select-save (&rest body)
1222 "Execute BODY and restore the selection afterwards."
1223 (declare (indent 0) (debug t))
1224 `(let ((selection (mpc-select-get-selection))
1225 (position (cons (buffer-substring-no-properties
1226 (line-beginning-position) (line-end-position))
1227 (current-column))))
1228 ,@body
1229 (mpc-select-restore selection)
1230 (goto-char (point-min))
1231 (if (re-search-forward
1232 (concat "^" (regexp-quote (car position)) "$")
1233 (if (overlayp mpc-separator-ol)
1234 (overlay-end mpc-separator-ol))
1235 t)
1236 (move-to-column (cdr position)))
1237 (let ((win (get-buffer-window (current-buffer) 0)))
1238 (if win (set-window-point win (point))))))
1239
1240 (defun mpc-select-get-selection ()
1241 (mapcar (lambda (ol)
1242 (buffer-substring-no-properties
1243 (overlay-start ol) (1- (overlay-end ol))))
1244 mpc-select))
1245
1246 (defun mpc-select-restore (selection)
1247 ;; Restore the selection. I.e. move the overlays back to their
1248 ;; corresponding location. Actually which overlay is used for what
1249 ;; doesn't matter.
1250 (mapc 'delete-overlay mpc-select)
1251 (setq mpc-select nil)
1252 (dolist (elem selection)
1253 ;; After an update, some elements may have disappeared.
1254 (goto-char (point-min))
1255 (when (re-search-forward
1256 (concat "^" (regexp-quote elem) "$") nil t)
1257 (mpc-select-make-overlay)))
1258 (when mpc-tag (mpc-tagbrowser-all-select))
1259 (beginning-of-line))
1260
1261 (defun mpc-select-make-overlay ()
1262 (cl-assert (not (get-char-property (point) 'mpc-select)))
1263 (let ((ol (make-overlay
1264 (line-beginning-position) (line-beginning-position 2))))
1265 (overlay-put ol 'mpc-select t)
1266 (overlay-put ol 'face 'highlight)
1267 (overlay-put ol 'evaporate t)
1268 (push ol mpc-select)))
1269
1270 (defun mpc-select (&optional event)
1271 "Select the tag value at point."
1272 (interactive (list last-nonmenu-event))
1273 (mpc-event-set-point event)
1274 (if (and (bolp) (eobp)) (forward-line -1))
1275 (mapc 'delete-overlay mpc-select)
1276 (setq mpc-select nil)
1277 (if (mpc-tagbrowser-all-p)
1278 nil
1279 (mpc-select-make-overlay))
1280 (when mpc-tag
1281 (mpc-tagbrowser-all-select)
1282 (mpc-selection-refresh)))
1283
1284 (defun mpc-select-toggle (&optional event)
1285 "Toggle the selection of the tag value at point."
1286 (interactive (list last-nonmenu-event))
1287 (mpc-event-set-point event)
1288 (save-excursion
1289 (cond
1290 ;; The line is already selected: deselect it.
1291 ((get-char-property (point) 'mpc-select)
1292 (let ((ols nil))
1293 (dolist (ol mpc-select)
1294 (if (and (<= (overlay-start ol) (point))
1295 (> (overlay-end ol) (point)))
1296 (delete-overlay ol)
1297 (push ol ols)))
1298 (cl-assert (= (1+ (length ols)) (length mpc-select)))
1299 (setq mpc-select ols)))
1300 ;; We're trying to select *ALL* additionally to others.
1301 ((mpc-tagbrowser-all-p) nil)
1302 ;; Select the current line.
1303 (t (mpc-select-make-overlay))))
1304 (when mpc-tag
1305 (mpc-tagbrowser-all-select)
1306 (mpc-selection-refresh)))
1307
1308 (defun mpc-select-extend (&optional event)
1309 "Extend the selection up to point."
1310 (interactive (list last-nonmenu-event))
1311 (mpc-event-set-point event)
1312 (if (null mpc-select)
1313 ;; If nothing's selected yet, fallback to selecting the elem at point.
1314 (mpc-select event)
1315 (save-excursion
1316 (cond
1317 ;; The line is already in a selected area; truncate the area.
1318 ((get-char-property (point) 'mpc-select)
1319 (let ((before 0)
1320 (after 0)
1321 (mid (line-beginning-position))
1322 start end)
1323 (while (and (zerop (forward-line 1))
1324 (get-char-property (point) 'mpc-select))
1325 (setq end (1+ (point)))
1326 (cl-incf after))
1327 (goto-char mid)
1328 (while (and (zerop (forward-line -1))
1329 (get-char-property (point) 'mpc-select))
1330 (setq start (point))
1331 (cl-incf before))
1332 (if (and (= after 0) (= before 0))
1333 ;; Shortening an already minimum-size region: do nothing.
1334 nil
1335 (if (> after before)
1336 (setq end mid)
1337 (setq start (1+ mid)))
1338 (let ((ols '()))
1339 (dolist (ol mpc-select)
1340 (if (and (>= (overlay-start ol) start)
1341 (< (overlay-start ol) end))
1342 (delete-overlay ol)
1343 (push ol ols)))
1344 (setq mpc-select (nreverse ols))))))
1345 ;; Extending a prior area. Look for the closest selection.
1346 (t
1347 (when (mpc-tagbrowser-all-p)
1348 (forward-line 1))
1349 (let ((before 0)
1350 (count 0)
1351 (dir 1)
1352 (start (line-beginning-position)))
1353 (while (and (zerop (forward-line 1))
1354 (not (get-char-property (point) 'mpc-select)))
1355 (cl-incf count))
1356 (unless (get-char-property (point) 'mpc-select)
1357 (setq count nil))
1358 (goto-char start)
1359 (while (and (zerop (forward-line -1))
1360 (not (get-char-property (point) 'mpc-select)))
1361 (cl-incf before))
1362 (unless (get-char-property (point) 'mpc-select)
1363 (setq before nil))
1364 (when (and before (or (null count) (< before count)))
1365 (setq count before)
1366 (setq dir -1))
1367 (goto-char start)
1368 (dotimes (_i (1+ (or count 0)))
1369 (mpc-select-make-overlay)
1370 (forward-line dir))))))
1371 (when mpc-tag
1372 (mpc-tagbrowser-all-select)
1373 (mpc-selection-refresh))))
1374
1375 ;;; Constraint sets ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1376
1377 (defvar mpc--song-search nil)
1378
1379 (defun mpc-constraints-get-current (&optional avoid-buf)
1380 "Return currently selected set of constraints.
1381 If AVOID-BUF is non-nil, it specifies a buffer which should be ignored
1382 when constructing the set of constraints."
1383 (let ((constraints (if mpc--song-search `((Search ,mpc--song-search))))
1384 tag select)
1385 (dolist (buf (process-get (mpc-proc) 'buffers))
1386 (setq buf (cdr buf))
1387 (when (and (setq tag (buffer-local-value 'mpc-tag buf))
1388 (not (eq buf avoid-buf))
1389 (setq select
1390 (with-current-buffer buf (mpc-select-get-selection))))
1391 (push (cons tag select) constraints)))
1392 constraints))
1393
1394 (defun mpc-constraints-tag-lookup (buffer-tag constraints)
1395 (let (res)
1396 (dolist (constraint constraints)
1397 (when (or (eq (car constraint) buffer-tag)
1398 (and (string-match "|" (symbol-name buffer-tag))
1399 (member (symbol-name (car constraint))
1400 (split-string (symbol-name buffer-tag) "|"))))
1401 (setq res (cdr constraint))))
1402 res))
1403
1404 (defun mpc-constraints-restore (constraints)
1405 (let ((search (assq 'Search constraints)))
1406 (setq mpc--song-search (cadr search))
1407 (when search (setq constraints (delq search constraints))))
1408 (dolist (buf (process-get (mpc-proc) 'buffers))
1409 (setq buf (cdr buf))
1410 (when (buffer-live-p buf)
1411 (let* ((tag (buffer-local-value 'mpc-tag buf))
1412 (constraint (mpc-constraints-tag-lookup tag constraints)))
1413 (when tag
1414 (with-current-buffer buf
1415 (mpc-select-restore constraint))))))
1416 (mpc-selection-refresh))
1417
1418 ;; I don't get the ring.el code. I think it doesn't do what I need, but
1419 ;; then I don't understand when what it does would be useful.
1420 (defun mpc-ring-make (size) (cons 0 (cons 0 (make-vector size nil))))
1421 (defun mpc-ring-push (ring val)
1422 (aset (cddr ring) (car ring) val)
1423 (setcar (cdr ring) (max (cadr ring) (1+ (car ring))))
1424 (setcar ring (mod (1+ (car ring)) (length (cddr ring)))))
1425 (defun mpc-ring-pop (ring)
1426 (setcar ring (mod (1- (car ring)) (cadr ring)))
1427 (aref (cddr ring) (car ring)))
1428
1429 (defvar mpc-constraints-ring (mpc-ring-make 10))
1430
1431 (defun mpc-constraints-push (&optional noerror)
1432 "Push the current selection on the ring for later."
1433 (interactive)
1434 (let ((constraints (mpc-constraints-get-current)))
1435 (if (null constraints)
1436 (unless noerror (error "No selection to push"))
1437 (mpc-ring-push mpc-constraints-ring constraints))))
1438
1439 (defun mpc-constraints-pop ()
1440 "Recall the most recently pushed selection."
1441 (interactive)
1442 (let ((constraints (mpc-ring-pop mpc-constraints-ring)))
1443 (if (null constraints)
1444 (error "No selection to return to")
1445 (mpc-constraints-restore constraints))))
1446
1447 ;;; The TagBrowser mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1448
1449 (defconst mpc-tagbrowser-all-name (propertize "*ALL*" 'face 'italic))
1450 (defvar-local mpc-tagbrowser-all-ol nil)
1451 (defvar-local mpc-tag-name nil)
1452 (defun mpc-tagbrowser-all-p ()
1453 (and (eq (point-min) (line-beginning-position))
1454 (equal mpc-tagbrowser-all-name
1455 (buffer-substring (point-min) (line-end-position)))))
1456
1457 (define-derived-mode mpc-tagbrowser-mode mpc-mode '("MPC-" mpc-tag-name)
1458 (setq-local mode-line-process '("" mpc-tag-name))
1459 (setq-local mode-line-format nil)
1460 (setq-local header-line-format '("" mpc-tag-name)) ;; "s"
1461 (setq-local buffer-undo-list t)
1462 )
1463
1464 (defun mpc-tagbrowser-refresh ()
1465 (mpc-select-save
1466 (widen)
1467 (goto-char (point-min))
1468 (cl-assert (looking-at (regexp-quote mpc-tagbrowser-all-name)))
1469 (forward-line 1)
1470 (let ((inhibit-read-only t))
1471 (delete-region (point) (point-max))
1472 (dolist (val (mpc-cmd-list mpc-tag)) (insert val "\n")))
1473 (set-buffer-modified-p nil))
1474 (mpc-reorder))
1475
1476 (defun mpc-updated-db ()
1477 ;; FIXME: This is not asynchronous, but is run from a process filter.
1478 (unless (assq 'updating_db mpc-status)
1479 (clrhash mpc--find-memoize)
1480 (dolist (buf (process-get (mpc-proc) 'buffers))
1481 (setq buf (cdr buf))
1482 (when (buffer-local-value 'mpc-tag buf)
1483 (with-current-buffer buf (with-local-quit (mpc-tagbrowser-refresh)))))
1484 (with-local-quit (mpc-songs-refresh))))
1485
1486 (defun mpc-tagbrowser-tag-name (tag)
1487 (cond
1488 ((string-match "|" (symbol-name tag))
1489 (let ((tag1 (intern (substring (symbol-name tag)
1490 0 (match-beginning 0))))
1491 (tag2 (intern (substring (symbol-name tag)
1492 (match-end 0)))))
1493 (concat (mpc-tagbrowser-tag-name tag1)
1494 " | "
1495 (mpc-tagbrowser-tag-name tag2))))
1496 ((string-match "y\\'" (symbol-name tag))
1497 (concat (substring (symbol-name tag) 0 -1) "ies"))
1498 (t (concat (symbol-name tag) "s"))))
1499
1500 (defun mpc-tagbrowser-buf (tag)
1501 (let ((buf (mpc-proc-buffer (mpc-proc) tag)))
1502 (if (buffer-live-p buf) buf
1503 (setq buf (get-buffer-create (format "*MPC %ss*" tag)))
1504 (mpc-proc-buffer (mpc-proc) tag buf)
1505 (with-current-buffer buf
1506 (let ((inhibit-read-only t))
1507 (erase-buffer)
1508 (if (member tag '(Directory))
1509 (mpc-tagbrowser-dir-mode)
1510 (mpc-tagbrowser-mode))
1511 (insert mpc-tagbrowser-all-name "\n"))
1512 (forward-line -1)
1513 (setq mpc-tag tag)
1514 (setq mpc-tag-name (mpc-tagbrowser-tag-name tag))
1515 (mpc-tagbrowser-all-select)
1516 (mpc-tagbrowser-refresh)
1517 buf))))
1518
1519 (defvar tag-browser-tagtypes
1520 (lazy-completion-table tag-browser-tagtypes
1521 (lambda ()
1522 (append '("Playlist" "Directory")
1523 (mpc-cmd-tagtypes)))))
1524
1525 (defun mpc-tagbrowser (tag)
1526 "Create a new browser for TAG."
1527 (interactive
1528 (list
1529 (let ((completion-ignore-case t))
1530 (intern
1531 (completing-read "Tag: " tag-browser-tagtypes nil 'require-match)))))
1532 (let* ((newbuf (mpc-tagbrowser-buf tag))
1533 (win (get-buffer-window newbuf 0)))
1534 (if win (select-window win)
1535 (if (with-current-buffer (window-buffer)
1536 (derived-mode-p 'mpc-tagbrowser-mode))
1537 (setq win (selected-window))
1538 ;; Find a tagbrowser-mode buffer.
1539 (let ((buffers (process-get (mpc-proc) 'buffers))
1540 buffer)
1541 (while
1542 (and buffers
1543 (not (and (buffer-live-p (setq buffer (cdr (pop buffers))))
1544 (with-current-buffer buffer
1545 (derived-mode-p 'mpc-tagbrowser-mode))
1546 (setq win (get-buffer-window buffer 0))))))))
1547 (if (not win)
1548 (pop-to-buffer newbuf)
1549 (setq win (split-window win nil 'horiz))
1550 (set-window-buffer win newbuf)
1551 (set-window-dedicated-p win 'soft)
1552 (select-window win)
1553 (balance-windows-area)))))
1554
1555 (defun mpc-tagbrowser-all-select ()
1556 "Select the special *ALL* entry if no other is selected."
1557 (if mpc-select
1558 (delete-overlay mpc-tagbrowser-all-ol)
1559 (save-excursion
1560 (goto-char (point-min))
1561 (if mpc-tagbrowser-all-ol
1562 (move-overlay mpc-tagbrowser-all-ol
1563 (point) (line-beginning-position 2))
1564 (let ((ol (make-overlay (point) (line-beginning-position 2))))
1565 (overlay-put ol 'face 'highlight)
1566 (overlay-put ol 'evaporate t)
1567 (setq-local mpc-tagbrowser-all-ol ol))))))
1568
1569 ;; (defvar mpc-constraints nil)
1570 (defun mpc-separator (active)
1571 ;; Place a separator mark.
1572 (unless mpc-separator-ol
1573 (setq-local mpc-separator-ol
1574 (make-overlay (point) (point)))
1575 (overlay-put mpc-separator-ol 'after-string
1576 (propertize "\n"
1577 'face '(:height 0.05 :inverse-video t))))
1578 (goto-char (point-min))
1579 (forward-line 1)
1580 (while
1581 (and (member (buffer-substring-no-properties
1582 (line-beginning-position) (line-end-position))
1583 active)
1584 (zerop (forward-line 1))))
1585 (if (or (eobp) (null active))
1586 (delete-overlay mpc-separator-ol)
1587 (move-overlay mpc-separator-ol (1- (point)) (point))))
1588
1589 (defun mpc-sort (active)
1590 ;; Sort the active elements at the front.
1591 (let ((inhibit-read-only t))
1592 (goto-char (point-min))
1593 (if (mpc-tagbrowser-all-p) (forward-line 1))
1594 (condition-case nil
1595 (sort-subr nil 'forward-line 'end-of-line
1596 nil nil
1597 (lambda (s1 s2)
1598 (setq s1 (buffer-substring-no-properties
1599 (car s1) (cdr s1)))
1600 (setq s2 (buffer-substring-no-properties
1601 (car s2) (cdr s2)))
1602 (cond
1603 ((member s1 active)
1604 (if (member s2 active)
1605 (let ((cmp (mpc-compare-strings s1 s2 t)))
1606 (and (numberp cmp) (< cmp 0)))
1607 t))
1608 ((member s2 active) nil)
1609 (t (let ((cmp (mpc-compare-strings s1 s2 t)))
1610 (and (numberp cmp) (< cmp 0)))))))
1611 ;; The comparison predicate arg is new in Emacs-22.
1612 (wrong-number-of-arguments
1613 (sort-subr nil 'forward-line 'end-of-line
1614 (lambda ()
1615 (let ((name (buffer-substring-no-properties
1616 (point) (line-end-position))))
1617 (cond
1618 ((member name active) (concat "1" name))
1619 (t (concat "2" "name"))))))))))
1620
1621 (defvar mpc--changed-selection)
1622
1623 (defun mpc-reorder (&optional nodeactivate)
1624 "Reorder entries based on the currently active selections.
1625 I.e. split the current browser buffer into a first part containing the
1626 entries included in the selection, then a separator, and then the entries
1627 not included in the selection.
1628 Return non-nil if a selection was deactivated."
1629 (mpc-select-save
1630 (let ((constraints (mpc-constraints-get-current (current-buffer)))
1631 (active 'all))
1632 ;; (unless (equal constraints mpc-constraints)
1633 ;; (setq-local mpc-constraints constraints)
1634 (dolist (cst constraints)
1635 (let ((vals (apply 'mpc-union
1636 (mapcar (lambda (val)
1637 (mpc-cmd-list mpc-tag (car cst) val))
1638 (cdr cst)))))
1639 (setq active
1640 (if (listp active) (mpc-intersection active vals) vals))))
1641
1642 (when (listp active)
1643 ;; Remove the selections if they are all in conflict with
1644 ;; other constraints.
1645 (let ((deactivate t))
1646 (dolist (sel selection)
1647 (when (member sel active) (setq deactivate nil)))
1648 (when deactivate
1649 ;; Variable declared/used by `mpc-select-save'.
1650 (when selection
1651 (setq mpc--changed-selection t))
1652 (unless nodeactivate
1653 (setq selection nil)
1654 (mapc 'delete-overlay mpc-select)
1655 (setq mpc-select nil)
1656 (mpc-tagbrowser-all-select))))
1657
1658 ;; Don't bother splitting the "active" elements to the first part if
1659 ;; they're the same as the selection.
1660 (when (equal (sort (copy-sequence active) #'string-lessp)
1661 (sort (copy-sequence selection) #'string-lessp))
1662 (setq active 'all)))
1663
1664 ;; FIXME: This `mpc-sort' takes a lot of time. Maybe we should
1665 ;; be more clever and presume the buffer is mostly sorted already.
1666 (mpc-sort (if (listp active) active))
1667 (mpc-separator (if (listp active) active)))))
1668
1669 (defun mpc-selection-refresh ()
1670 (let ((mpc--changed-selection t))
1671 (while mpc--changed-selection
1672 (setq mpc--changed-selection nil)
1673 (dolist (buf (process-get (mpc-proc) 'buffers))
1674 (setq buf (cdr buf))
1675 (when (and (buffer-local-value 'mpc-tag buf)
1676 (not (eq buf (current-buffer))))
1677 (with-current-buffer buf (mpc-reorder)))))
1678 ;; FIXME: reorder the current buffer last and prevent deactivation,
1679 ;; since whatever selection we made here is the most recent one
1680 ;; and should hence take precedence.
1681 (when mpc-tag (mpc-reorder 'nodeactivate))
1682 ;; FIXME: comment?
1683 (if (and mpc--song-search mpc--changed-selection)
1684 (progn
1685 (setq mpc--song-search nil)
1686 (mpc-selection-refresh))
1687 (mpc-songs-refresh))))
1688
1689 ;;; Hierarchical tagbrowser ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1690 ;; Todo:
1691 ;; - Add a button on each dir to open/close it (?)
1692 ;; - add the parent dir on the previous line, grayed-out, if it's not
1693 ;; present (because we're in the non-selected part and the parent is
1694 ;; in the selected part).
1695
1696 (defvar mpc-tagbrowser-dir-mode-map
1697 (let ((map (make-sparse-keymap)))
1698 (set-keymap-parent map mpc-tagbrowser-mode-map)
1699 (define-key map [?\M-\C-m] 'mpc-tagbrowser-dir-toggle)
1700 map))
1701
1702 ;; (defvar mpc-tagbrowser-dir-keywords
1703 ;; '(mpc-tagbrowser-dir-hide-prefix))
1704
1705 (define-derived-mode mpc-tagbrowser-dir-mode mpc-tagbrowser-mode '("MPC-" mpc-tag-name)
1706 ;; (setq-local font-lock-defaults
1707 ;; '(mpc-tagbrowser-dir-keywords t))
1708 )
1709
1710 ;; (defun mpc-tagbrowser-dir-hide-prefix (limit)
1711 ;; (while
1712 ;; (let ((prev (buffer-substring (line-beginning-position 0)
1713 ;; (line-end-position 0))))
1714 ;; (
1715
1716 (defun mpc-tagbrowser-dir-toggle (event)
1717 "Open or close the element at point."
1718 (interactive (list last-nonmenu-event))
1719 (mpc-event-set-point event)
1720 (let ((name (buffer-substring (line-beginning-position)
1721 (line-end-position)))
1722 (prop (intern mpc-tag))
1723 (proc (mpc-proc)))
1724 (if (not (member name (process-get proc prop)))
1725 (process-put proc prop
1726 (cons name (process-get proc prop)))
1727 (let ((new (delete name (process-get proc prop))))
1728 (setq name (concat name "/"))
1729 (process-put proc prop
1730 (delq nil
1731 (mapcar (lambda (x)
1732 (if (string-prefix-p name x)
1733 nil x))
1734 new)))))
1735 (mpc-tagbrowser-refresh)))
1736
1737
1738 ;;; Playlist management ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1739
1740 (defvar-local mpc-songs-playlist nil
1741 "Name of the currently selected playlist, if any.
1742 A value of t means the main playlist.")
1743
1744 (defun mpc-playlist-create (name)
1745 "Save current playlist under name NAME."
1746 (interactive "sPlaylist name: ")
1747 (mpc-proc-cmd (list "save" name))
1748 (let ((buf (mpc-proc-buffer (mpc-proc) 'Playlist)))
1749 (when (buffer-live-p buf)
1750 (with-current-buffer buf (mpc-tagbrowser-refresh)))))
1751
1752 (defun mpc-playlist-destroy (name)
1753 "Delete playlist named NAME."
1754 (interactive
1755 (list (completing-read "Delete playlist: " (mpc-cmd-list 'Playlist)
1756 nil 'require-match)))
1757 (mpc-proc-cmd (list "rm" name))
1758 (let ((buf (mpc-proc-buffer (mpc-proc) 'Playlist)))
1759 (when (buffer-live-p buf)
1760 (with-current-buffer buf (mpc-tagbrowser-refresh)))))
1761
1762 (defun mpc-playlist-rename (oldname newname)
1763 "Rename playlist OLDNAME to NEWNAME."
1764 (interactive
1765 (let* ((oldname (if (and (eq mpc-tag 'Playlist) (null current-prefix-arg))
1766 (buffer-substring (line-beginning-position)
1767 (line-end-position))
1768 (completing-read "Rename playlist: "
1769 (mpc-cmd-list 'Playlist)
1770 nil 'require-match)))
1771 (newname (read-string (format-message "Rename `%s' to: " oldname))))
1772 (if (zerop (length newname))
1773 (error "Aborted")
1774 (list oldname newname))))
1775 (mpc-proc-cmd (list "rename" oldname newname))
1776 (let ((buf (mpc-proc-buffer (mpc-proc) 'Playlist)))
1777 (if (buffer-live-p buf)
1778 (with-current-buffer buf (mpc-tagbrowser-refresh)))))
1779
1780 (defun mpc-playlist ()
1781 "Show the current playlist."
1782 (interactive)
1783 (mpc-constraints-push 'noerror)
1784 (mpc-constraints-restore '()))
1785
1786 (defun mpc-playlist-add ()
1787 "Add the selection to the playlist."
1788 (interactive)
1789 (let ((songs (mapcar #'car (mpc-songs-selection))))
1790 (mpc-cmd-add songs)
1791 (message "Appended %d songs" (length songs))
1792 ;; Return the songs added. Used in `mpc-play'.
1793 songs))
1794
1795 (defun mpc-playlist-delete ()
1796 "Remove the selected songs from the playlist."
1797 (interactive)
1798 (unless mpc-songs-playlist
1799 (error "The selected songs aren't part of a playlist"))
1800 (let ((song-poss (mapcar #'cdr (mpc-songs-selection))))
1801 (mpc-cmd-delete song-poss mpc-songs-playlist)
1802 (mpc-songs-refresh)
1803 (message "Deleted %d songs" (length song-poss))))
1804
1805 ;;; Volume management ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1806
1807 (defvar mpc-volume-map
1808 (let ((map (make-sparse-keymap)))
1809 ;; Bind the up-events rather than the down-event, so the
1810 ;; `message' isn't canceled by the subsequent up-event binding.
1811 (define-key map [down-mouse-1] 'ignore)
1812 (define-key map [mouse-1] 'mpc-volume-mouse-set)
1813 (define-key map [header-line mouse-1] 'mpc-volume-mouse-set)
1814 (define-key map [header-line down-mouse-1] 'ignore)
1815 (define-key map [mode-line mouse-1] 'mpc-volume-mouse-set)
1816 (define-key map [mode-line down-mouse-1] 'ignore)
1817 map))
1818
1819 (defvar mpc-volume nil) (put 'mpc-volume 'risky-local-variable t)
1820
1821 (defun mpc-volume-refresh ()
1822 ;; Maintain the volume.
1823 (setq mpc-volume
1824 (mpc-volume-widget
1825 (string-to-number (cdr (assq 'volume mpc-status)))))
1826 (let ((status-buf (mpc-proc-buffer (mpc-proc) 'status)))
1827 (when status-buf (with-current-buffer status-buf (force-mode-line-update)))))
1828
1829 (defvar mpc-volume-step 5)
1830
1831 (defun mpc-volume-mouse-set (&optional event)
1832 "Change volume setting."
1833 (interactive (list last-nonmenu-event))
1834 (let* ((posn (event-start event))
1835 (diff
1836 (if (memq (if (stringp (car-safe (posn-object posn)))
1837 (aref (car (posn-object posn)) (cdr (posn-object posn)))
1838 (with-current-buffer (window-buffer (posn-window posn))
1839 (char-after (posn-point posn))))
1840 '(?◁ ?<))
1841 (- mpc-volume-step) mpc-volume-step))
1842 (curvol (string-to-number (cdr (assq 'volume mpc-status))))
1843 (newvol (max 0 (min 100 (+ curvol diff)))))
1844 (if (= newvol curvol)
1845 (progn
1846 (message "MPD volume already at %s%%" newvol)
1847 (ding))
1848 (mpc-proc-cmd (list "setvol" newvol) 'mpc-status-refresh)
1849 (message "Set MPD volume to %s%%" newvol))))
1850
1851 (defun mpc-volume-widget (vol &optional size)
1852 (unless size (setq size 12.5))
1853 (let ((scaledvol (* (/ vol 100.0) size)))
1854 ;; (message "Volume sizes: %s - %s" (/ vol fact) (/ (- 100 vol) fact))
1855 (list (propertize "<" ;; "◁"
1856 ;; 'face 'default
1857 'keymap mpc-volume-map
1858 'face '(:box (:line-width -2 :style pressed-button))
1859 'mouse-face '(:box (:line-width -2 :style released-button)))
1860 " "
1861 (propertize "a"
1862 'display (list 'space :width scaledvol)
1863 'face '(:inverse-video t
1864 :box (:line-width -2 :style released-button)))
1865 (propertize "a"
1866 'display (list 'space :width (- size scaledvol))
1867 'face '(:box (:line-width -2 :style released-button)))
1868 " "
1869 (propertize ">" ;; "▷"
1870 ;; 'face 'default
1871 'keymap mpc-volume-map
1872 'face '(:box (:line-width -2 :style pressed-button))
1873 'mouse-face '(:box (:line-width -2 :style released-button))))))
1874
1875 ;;; MPC songs mode ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1876
1877 (defvar mpc-current-song nil) (put 'mpc-current-song 'risky-local-variable t)
1878 (defvar mpc-current-updating nil) (put 'mpc-current-updating 'risky-local-variable t)
1879 (defvar mpc-songs-format-description nil) (put 'mpc-songs-format-description 'risky-local-variable t)
1880
1881 (defvar mpc-previous-window-config nil)
1882
1883 (defvar mpc-songs-mode-map
1884 (let ((map (make-sparse-keymap)))
1885 (set-keymap-parent map mpc-mode-map)
1886 (define-key map [remap mpc-select] 'mpc-songs-jump-to)
1887 map))
1888
1889 (defvar mpc-songpointer-set-visible nil)
1890
1891 (defvar mpc-songs-hashcons (make-hash-table :test 'equal :weakness t)
1892 "Make song file name objects unique via hash consing.
1893 This is used so that they can be compared with `eq', which is needed for
1894 `text-property-any'.")
1895 (defun mpc-songs-hashcons (name)
1896 (or (gethash name mpc-songs-hashcons) (puthash name name mpc-songs-hashcons)))
1897 (defcustom mpc-songs-format "%2{Disc--}%3{Track} %-5{Time} %25{Title} %20{Album} %20{Artist} %5{Date}"
1898 "Format used to display each song in the list of songs."
1899 :type 'string)
1900
1901 (defvar mpc-songs-totaltime)
1902
1903 (defun mpc-songs-refresh ()
1904 (let ((buf (mpc-proc-buffer (mpc-proc) 'songs)))
1905 (when (buffer-live-p buf)
1906 (with-current-buffer buf
1907 (let ((constraints (mpc-constraints-get-current (current-buffer)))
1908 (dontsort nil)
1909 (inhibit-read-only t)
1910 (totaltime 0)
1911 (curline (cons (count-lines (point-min)
1912 (line-beginning-position))
1913 (buffer-substring (line-beginning-position)
1914 (line-end-position))))
1915 active)
1916 (setq mpc-songs-playlist nil)
1917 (if (null constraints)
1918 ;; When there are no constraints, rather than show the list of
1919 ;; all songs (which could take a while to download and
1920 ;; format), we show the current playlist.
1921 ;; FIXME: it would be good to be able to show the complete
1922 ;; list, but that would probably require us to format it
1923 ;; on-the-fly to make it bearable.
1924 (setq dontsort t
1925 mpc-songs-playlist t
1926 active (mpc-proc-buf-to-alists
1927 (mpc-proc-cmd "playlistinfo")))
1928 (dolist (cst constraints)
1929 (if (and (eq (car cst) 'Playlist)
1930 (= 1 (length (cdr cst))))
1931 (setq mpc-songs-playlist (cadr cst)))
1932 ;; We don't do anything really special here for playlists,
1933 ;; because it's unclear what's a correct "union" of playlists.
1934 (let ((vals (apply 'mpc-union
1935 (mapcar (lambda (val)
1936 (mpc-cmd-find (car cst) val))
1937 (cdr cst)))))
1938 (setq active (cond
1939 ((null active)
1940 (if (eq (car cst) 'Playlist)
1941 (setq dontsort t))
1942 vals)
1943 ((or dontsort
1944 ;; Try to preserve ordering and
1945 ;; repetitions from playlists.
1946 (not (eq (car cst) 'Playlist)))
1947 (mpc-intersection active vals
1948 (lambda (x) (assq 'file x))))
1949 (t
1950 (setq dontsort t)
1951 (mpc-intersection vals active
1952 (lambda (x)
1953 (assq 'file x)))))))))
1954 (mpc-select-save
1955 (erase-buffer)
1956 ;; Sorting songs is surprisingly difficult: when comparing two
1957 ;; songs with the same album name but different artist name, you
1958 ;; have to know whether these are two different albums (with the
1959 ;; same name) or a single album (typically a compilation).
1960 ;; I punt on it and just use file-name sorting, which does the
1961 ;; right thing if your library is properly arranged.
1962 (dolist (song (if dontsort active
1963 (sort (copy-sequence active)
1964 (lambda (song1 song2)
1965 (let ((cmp (mpc-compare-strings
1966 (cdr (assq 'file song1))
1967 (cdr (assq 'file song2)))))
1968 (and (integerp cmp) (< cmp 0)))))))
1969 (cl-incf totaltime (string-to-number (or (cdr (assq 'Time song)) "0")))
1970 (mpc-format mpc-songs-format song)
1971 (delete-char (- (skip-chars-backward " "))) ;Remove trailing space.
1972 (insert "\n")
1973 (put-text-property
1974 (line-beginning-position 0) (line-beginning-position)
1975 'mpc-file (mpc-songs-hashcons (cdr (assq 'file song))))
1976 (let ((pos (assq 'Pos song)))
1977 (if pos
1978 (put-text-property
1979 (line-beginning-position 0) (line-beginning-position)
1980 'mpc-file-pos (string-to-number (cdr pos)))))
1981 ))
1982 (goto-char (point-min))
1983 (forward-line (car curline))
1984 (if (or (search-forward (cdr curline) nil t)
1985 (search-backward (cdr curline) nil t))
1986 (beginning-of-line)
1987 (goto-char (point-min)))
1988 (setq-local mpc-songs-totaltime
1989 (unless (zerop totaltime)
1990 (list " " (mpc-secs-to-time totaltime))))
1991 ))))
1992 (let ((mpc-songpointer-set-visible t))
1993 (mpc-songpointer-refresh)))
1994
1995 (defun mpc-songs-search (string)
1996 "Filter songs to those who include STRING in their metadata."
1997 (interactive "sSearch for: ")
1998 (setq mpc--song-search
1999 (if (zerop (length string)) nil string))
2000 (let ((mpc--changed-selection t))
2001 (while mpc--changed-selection
2002 (setq mpc--changed-selection nil)
2003 (dolist (buf (process-get (mpc-proc) 'buffers))
2004 (setq buf (cdr buf))
2005 (when (buffer-local-value 'mpc-tag buf)
2006 (with-current-buffer buf (mpc-reorder))))
2007 (mpc-songs-refresh))))
2008
2009 (defun mpc-songs-kill-search ()
2010 "Turn off the current search restriction."
2011 (interactive)
2012 (mpc-songs-search nil))
2013
2014 (defun mpc-songs-selection ()
2015 "Return the list of songs currently selected."
2016 (let ((buf (mpc-proc-buffer (mpc-proc) 'songs)))
2017 (when (buffer-live-p buf)
2018 (with-current-buffer buf
2019 (save-excursion
2020 (let ((files ()))
2021 (if mpc-select
2022 (dolist (ol mpc-select)
2023 (push (cons
2024 (get-text-property (overlay-start ol) 'mpc-file)
2025 (get-text-property (overlay-start ol) 'mpc-file-pos))
2026 files))
2027 (goto-char (point-min))
2028 (while (not (eobp))
2029 (push (cons
2030 (get-text-property (point) 'mpc-file)
2031 (get-text-property (point) 'mpc-file-pos))
2032 files)
2033 (forward-line 1)))
2034 (nreverse files)))))))
2035
2036 (defun mpc-songs-jump-to (song-file &optional posn)
2037 "Jump to song SONG-FILE; interactively, this is the song at point."
2038 (interactive
2039 (let* ((event last-nonmenu-event)
2040 (posn (event-end event)))
2041 (with-selected-window (posn-window posn)
2042 (goto-char (posn-point posn))
2043 (list (get-text-property (point) 'mpc-file)
2044 posn))))
2045 (let* ((plbuf (mpc-proc-cmd "playlist"))
2046 (re (if song-file
2047 ;; Newer MPCs apparently include "file: " in the buffer.
2048 (concat "^\\([0-9]+\\):\\(?:file: \\)?"
2049 (regexp-quote song-file) "$")))
2050 (sn (with-current-buffer plbuf
2051 (goto-char (point-min))
2052 (when (and re (re-search-forward re nil t))
2053 (match-string 1)))))
2054 (cond
2055 ((null re) (posn-set-point posn))
2056 ((null sn) (user-error "This song is not in the playlist"))
2057 ((null (with-current-buffer plbuf (re-search-forward re nil t)))
2058 ;; song-file only appears once in the playlist: no ambiguity,
2059 ;; we're good to go!
2060 (mpc-proc-cmd (list "play" sn)))
2061 (t
2062 ;; The song appears multiple times in the playlist. If the current
2063 ;; buffer holds not only the destination song but also the current
2064 ;; song, then we will move in the playlist to the same relative
2065 ;; position as in the buffer. Otherwise, we will simply choose the
2066 ;; song occurrence closest to the current song.
2067 (with-selected-window (posn-window posn)
2068 (let* ((cur (and (markerp overlay-arrow-position)
2069 (marker-position overlay-arrow-position)))
2070 (dest (save-excursion
2071 (goto-char (posn-point posn))
2072 (line-beginning-position)))
2073 (lines (when cur (* (if (< cur dest) 1 -1)
2074 (count-lines cur dest)))))
2075 (with-current-buffer plbuf
2076 (goto-char (point-min))
2077 ;; Start the search from the current song.
2078 (forward-line (string-to-number
2079 (or (cdr (assq 'song mpc-status)) "0")))
2080 ;; If the current song is also displayed in the buffer,
2081 ;; then try to move to the same relative position.
2082 (if lines (forward-line lines))
2083 ;; Now search the closest occurrence.
2084 (let* ((next (save-excursion
2085 (when (re-search-forward re nil t)
2086 (cons (point) (match-string 1)))))
2087 (prev (save-excursion
2088 (when (re-search-backward re nil t)
2089 (cons (point) (match-string 1)))))
2090 (sn (cdr (if (and next prev)
2091 (if (< (- (car next) (point))
2092 (- (point) (car prev)))
2093 next prev)
2094 (or next prev)))))
2095 (cl-assert sn)
2096 (mpc-proc-cmd (concat "play " sn))))))))))
2097
2098 (define-derived-mode mpc-songs-mode mpc-mode "MPC-song"
2099 (setq mpc-songs-format-description
2100 (with-temp-buffer (mpc-format mpc-songs-format 'self) (buffer-string)))
2101 (setq-local header-line-format
2102 ;; '("MPC " mpc-volume " " mpc-current-song)
2103 (list (propertize " " 'display '(space :align-to 0))
2104 ;; 'mpc-songs-format-description
2105 '(:eval
2106 (let ((hscroll (window-hscroll)))
2107 (with-temp-buffer
2108 (mpc-format mpc-songs-format 'self hscroll)
2109 ;; That would be simpler than the hscroll handling in
2110 ;; mpc-format, but currently move-to-column does not
2111 ;; recognize :space display properties.
2112 ;; (move-to-column hscroll)
2113 ;; (delete-region (point-min) (point))
2114 (buffer-string))))))
2115 (setq-local
2116 mode-line-format
2117 '("%e" mode-line-frame-identification mode-line-buffer-identification
2118 #(" " 0 3
2119 (help-echo "mouse-1: Select (drag to resize)\nmouse-2: Make current window occupy the whole frame\nmouse-3: Remove current window from display"))
2120 mode-line-position
2121 #(" " 0 2
2122 (help-echo "mouse-1: Select (drag to resize)\nmouse-2: Make current window occupy the whole frame\nmouse-3: Remove current window from display"))
2123 mpc-songs-totaltime
2124 mpc-current-updating
2125 #(" " 0 2
2126 (help-echo "mouse-1: Select (drag to resize)\nmouse-2: Make current window occupy the whole frame\nmouse-3: Remove current window from display"))
2127 (mpc--song-search
2128 (:propertize
2129 ("Search=\"" mpc--song-search "\"")
2130 help-echo "mouse-2: kill this search"
2131 follow-link t
2132 mouse-face mode-line-highlight
2133 keymap (keymap (mode-line keymap
2134 (mouse-2 . mpc-songs-kill-search))))
2135 (:propertize "NoSearch"
2136 help-echo "mouse-2: set a search restriction"
2137 follow-link t
2138 mouse-face mode-line-highlight
2139 keymap (keymap (mode-line keymap (mouse-2 . mpc-songs-search)))))))
2140
2141 ;; (setq-local mode-line-process
2142 ;; '("" ;; mpc-volume " "
2143 ;; mpc-songs-totaltime
2144 ;; mpc-current-updating))
2145 )
2146
2147 (defun mpc-songpointer-set (pos)
2148 (let* ((win (get-buffer-window (current-buffer) t))
2149 (visible (when win
2150 (or mpc-songpointer-set-visible
2151 (and (markerp overlay-arrow-position)
2152 (eq (marker-buffer overlay-arrow-position)
2153 (current-buffer))
2154 (<= (window-start win) overlay-arrow-position)
2155 (< overlay-arrow-position (window-end win)))))))
2156 (unless (local-variable-p 'overlay-arrow-position)
2157 (setq-local overlay-arrow-position (make-marker)))
2158 (move-marker overlay-arrow-position pos)
2159 ;; If the arrow was visible, try to keep it that way.
2160 (if (and visible pos
2161 (or (> (window-start win) pos) (>= pos (window-end win t))))
2162 (set-window-point win pos))))
2163
2164 (defun mpc-songpointer-refresh ()
2165 (let ((buf (mpc-proc-buffer (mpc-proc) 'songs)))
2166 (when (buffer-live-p buf)
2167 (with-current-buffer buf
2168 (let* ((pos (text-property-any
2169 (point-min) (point-max)
2170 'mpc-file (mpc-songs-hashcons
2171 (cdr (assq 'file mpc-status)))))
2172 (other (when pos
2173 (save-excursion
2174 (goto-char pos)
2175 (text-property-any
2176 (line-beginning-position 2) (point-max)
2177 'mpc-file (mpc-songs-hashcons
2178 (cdr (assq 'file mpc-status))))))))
2179 (if other
2180 ;; The song appears multiple times in the buffer.
2181 ;; We need to be careful to choose the right occurrence.
2182 (mpc-proc-cmd "playlist" 'mpc-songpointer-refresh-hairy)
2183 (mpc-songpointer-set pos)))))))
2184
2185 (defun mpc-songpointer-context (size plbuf)
2186 (with-current-buffer plbuf
2187 (goto-char (point-min))
2188 (forward-line (string-to-number (or (cdr (assq 'song mpc-status)) "0")))
2189 (let ((context-before '())
2190 (context-after '()))
2191 (save-excursion
2192 (dotimes (_i size)
2193 (when (re-search-backward "^[0-9]+:\\(.*\\)" nil t)
2194 (push (mpc-songs-hashcons (match-string 1)) context-before))))
2195 ;; Skip the actual current song.
2196 (forward-line 1)
2197 (dotimes (_i size)
2198 (when (re-search-forward "^[0-9]+:\\(.*\\)" nil t)
2199 (push (mpc-songs-hashcons (match-string 1)) context-after)))
2200 ;; If there isn't `size' context, then return nil.
2201 (unless (and (< (length context-before) size)
2202 (< (length context-after) size))
2203 (cons (nreverse context-before) (nreverse context-after))))))
2204
2205 (defun mpc-songpointer-score (context pos)
2206 (let ((count 0))
2207 (goto-char pos)
2208 (dolist (song (car context))
2209 (and (zerop (forward-line -1))
2210 (eq (get-text-property (point) 'mpc-file) song)
2211 (cl-incf count)))
2212 (goto-char pos)
2213 (dolist (song (cdr context))
2214 (and (zerop (forward-line 1))
2215 (eq (get-text-property (point) 'mpc-file) song)
2216 (cl-incf count)))
2217 count))
2218
2219 (defun mpc-songpointer-refresh-hairy ()
2220 ;; Based on the complete playlist, we should figure out where in the
2221 ;; song buffer is the currently playing song.
2222 (let ((plbuf (current-buffer))
2223 (buf (mpc-proc-buffer (mpc-proc) 'songs)))
2224 (when (buffer-live-p buf)
2225 (with-current-buffer buf
2226 (let* ((context-size 0)
2227 (context '(() . ()))
2228 (pos (text-property-any
2229 (point-min) (point-max)
2230 'mpc-file (mpc-songs-hashcons
2231 (cdr (assq 'file mpc-status)))))
2232 (score 0)
2233 (other pos))
2234 (while
2235 (setq other
2236 (save-excursion
2237 (goto-char other)
2238 (text-property-any
2239 (line-beginning-position 2) (point-max)
2240 'mpc-file (mpc-songs-hashcons
2241 (cdr (assq 'file mpc-status))))))
2242 ;; There is an `other' contestant.
2243 (let ((other-score (mpc-songpointer-score context other)))
2244 (cond
2245 ;; `other' is worse: try the next one.
2246 ((< other-score score) nil)
2247 ;; `other' is better: remember it and then search further.
2248 ((> other-score score)
2249 (setq pos other)
2250 (setq score other-score))
2251 ;; Both are equal and increasing the context size won't help.
2252 ;; Arbitrarily choose one of the two and keep looking
2253 ;; for a better match.
2254 ((< score context-size) nil)
2255 (t
2256 ;; Score is equal and increasing context might help: try it.
2257 (cl-incf context-size)
2258 (let ((new-context
2259 (mpc-songpointer-context context-size plbuf)))
2260 (if (null new-context)
2261 ;; There isn't more context: choose one arbitrarily
2262 ;; and keep looking for a better match elsewhere.
2263 (cl-decf context-size)
2264 (setq context new-context)
2265 (setq score (mpc-songpointer-score context pos))
2266 (save-excursion
2267 (goto-char other)
2268 ;; Go back one line so we find `other' again.
2269 (setq other (line-beginning-position 0)))))))))
2270 (mpc-songpointer-set pos))))))
2271
2272 (defun mpc-current-refresh ()
2273 ;; Maintain the current data.
2274 (mpc-status-buffer-refresh)
2275 (setq mpc-current-updating
2276 (if (assq 'updating_db mpc-status) " Updating-DB"))
2277 (ignore-errors
2278 (setq mpc-current-song
2279 (when (assq 'file mpc-status)
2280 (concat " "
2281 (mpc-secs-to-time (cdr (assq 'time mpc-status)))
2282 " "
2283 (cdr (assq 'Title mpc-status))
2284 " ("
2285 (cdr (assq 'Artist mpc-status))
2286 " / "
2287 (cdr (assq 'Album mpc-status))
2288 ")"))))
2289 (force-mode-line-update t))
2290
2291 (defun mpc-songs-buf ()
2292 (let ((buf (mpc-proc-buffer (mpc-proc) 'songs)))
2293 (if (buffer-live-p buf) buf
2294 (with-current-buffer (setq buf (get-buffer-create "*MPC-Songs*"))
2295 (mpc-proc-buffer (mpc-proc) 'songs buf)
2296 (mpc-songs-mode)
2297 buf))))
2298
2299 (defun mpc-update ()
2300 "Tell MPD to refresh its database."
2301 (interactive)
2302 (mpc-cmd-update))
2303
2304 (defun mpc-quit ()
2305 "Quit Music Player Daemon."
2306 (interactive)
2307 (let* ((proc mpc-proc)
2308 (bufs (mapcar 'cdr (if proc (process-get proc 'buffers))))
2309 (wins (mapcar (lambda (buf) (get-buffer-window buf 0)) bufs))
2310 (song-buf (mpc-songs-buf))
2311 frames)
2312 ;; Collect all the frames where MPC buffers appear.
2313 (dolist (win wins)
2314 (when (and win (not (memq (window-frame win) frames)))
2315 (push (window-frame win) frames)))
2316 (if (and frames song-buf
2317 (with-current-buffer song-buf mpc-previous-window-config))
2318 (progn
2319 (select-frame (car frames))
2320 (set-window-configuration
2321 (with-current-buffer song-buf mpc-previous-window-config)))
2322 ;; Now delete the ones that show nothing else than MPC buffers.
2323 (dolist (frame frames)
2324 (let ((delete t))
2325 (dolist (win (window-list frame))
2326 (unless (memq (window-buffer win) bufs) (setq delete nil)))
2327 (if delete (ignore-errors (delete-frame frame))))))
2328 ;; Then kill the buffers.
2329 (mapc 'kill-buffer bufs)
2330 (mpc-status-stop)
2331 (if proc (delete-process proc))))
2332
2333 (defun mpc-stop ()
2334 "Stop playing the current queue of songs."
2335 (interactive)
2336 (mpc-cmd-stop)
2337 (mpc-cmd-clear)
2338 (mpc-status-refresh))
2339
2340 (defun mpc-pause ()
2341 "Pause playing."
2342 (interactive)
2343 (mpc-cmd-pause "1"))
2344
2345 (defun mpc-resume ()
2346 "Resume playing."
2347 (interactive)
2348 (mpc-cmd-pause "0"))
2349
2350 (defun mpc-play ()
2351 "Start playing whatever is selected."
2352 (interactive)
2353 (if (member (cdr (assq 'state (mpc-cmd-status))) '("pause"))
2354 (mpc-resume)
2355 ;; When playing the playlist ends, the playlist isn't cleared, but the
2356 ;; user probably doesn't want to re-listen to it before getting to
2357 ;; listen to what he just selected.
2358 ;; (if (member (cdr (assq 'state (mpc-cmd-status))) '("stop"))
2359 ;; (mpc-cmd-clear))
2360 ;; Actually, we don't use mpc-play to append to the playlist any more,
2361 ;; so we can just always empty the playlist.
2362 (mpc-cmd-clear)
2363 (if (mpc-playlist-add)
2364 (if (member (cdr (assq 'state (mpc-cmd-status))) '("stop"))
2365 (mpc-cmd-play))
2366 (user-error "Don't know what to play"))))
2367
2368 (defun mpc-next ()
2369 "Jump to the next song in the queue."
2370 (interactive)
2371 (mpc-proc-cmd "next")
2372 (mpc-status-refresh))
2373
2374 (defun mpc-prev ()
2375 "Jump to the beginning of the current song, or to the previous song."
2376 (interactive)
2377 (let ((time (cdr (assq 'time mpc-status))))
2378 ;; Here we rely on the fact that string-to-number silently ignores
2379 ;; everything after a non-digit char.
2380 (cond
2381 ;; Go back to the beginning of current song.
2382 ((and time (> (string-to-number time) 0))
2383 (mpc-proc-cmd (list "seekid" (cdr (assq 'songid mpc-status)) 0)))
2384 ;; We're at the beginning of the first song of the playlist.
2385 ;; Fetch the previous one from `mpc-queue-back'.
2386 ;; ((and (zerop (string-to-number (cdr (assq 'song mpc-status))))
2387 ;; mpc-queue-back)
2388 ;; ;; Because we use cmd-list rather than cmd-play, the queue is not
2389 ;; ;; automatically updated.
2390 ;; (let ((prev (pop mpc-queue-back)))
2391 ;; (push prev mpc-queue)
2392 ;; (mpc-proc-cmd
2393 ;; (mpc-proc-cmd-list
2394 ;; (list (list "add" prev)
2395 ;; (list "move" (cdr (assq 'playlistlength mpc-status)) "0")
2396 ;; "previous")))))
2397 ;; We're at the beginning of a song, but not the first one.
2398 (t (mpc-proc-cmd "previous")))
2399 (mpc-status-refresh)))
2400
2401 (defvar mpc-last-seek-time '(0 . 0))
2402
2403 (defun mpc--faster (event speedup step)
2404 "Fast forward."
2405 (interactive (list last-nonmenu-event))
2406 (let ((repeat-delay (/ (abs (float step)) speedup)))
2407 (if (not (memq 'down (event-modifiers event)))
2408 (let* ((currenttime (float-time))
2409 (last-time (- currenttime (car mpc-last-seek-time))))
2410 (if (< last-time (* 0.9 repeat-delay))
2411 nil ;; Throttle
2412 (let* ((status (if (< last-time 1.0)
2413 mpc-status (mpc-cmd-status)))
2414 (songid (cdr (assq 'songid status)))
2415 (time (if songid
2416 (if (< last-time 1.0)
2417 (cdr mpc-last-seek-time)
2418 (string-to-number
2419 (cdr (assq 'time status)))))))
2420 (setq mpc-last-seek-time
2421 (cons currenttime (setq time (+ time step))))
2422 (mpc-proc-cmd (list "seekid" songid time)
2423 'mpc-status-refresh))))
2424 (let ((status (mpc-cmd-status)))
2425 (let* ((songid (cdr (assq 'songid status)))
2426 (time (if songid (string-to-number
2427 (cdr (assq 'time status))))))
2428 (let ((timer (run-with-timer
2429 t repeat-delay
2430 (lambda ()
2431 (mpc-proc-cmd (list "seekid" songid
2432 (setq time (+ time step)))
2433 'mpc-status-refresh)))))
2434 (while (mouse-movement-p
2435 (event-basic-type (setq event (read-event)))))
2436 (cancel-timer timer)))))))
2437
2438 (defvar mpc--faster-toggle-timer nil)
2439 (defun mpc--faster-stop ()
2440 (when mpc--faster-toggle-timer
2441 (cancel-timer mpc--faster-toggle-timer)
2442 (setq mpc--faster-toggle-timer nil)))
2443
2444 (defun mpc--faster-toggle-refresh ()
2445 (if (equal (cdr (assq 'state mpc-status)) "stop")
2446 (mpc--faster-stop)))
2447
2448 (defun mpc--songduration ()
2449 (string-to-number
2450 (let ((s (cdr (assq 'time mpc-status))))
2451 (if (not (string-match ":" s))
2452 (error "Unexpected time format %S" s)
2453 (substring s (match-end 0))))))
2454
2455 (defvar mpc--faster-toggle-forward nil)
2456 (defvar mpc--faster-acceleration 0.5)
2457 (defun mpc--faster-toggle (speedup step)
2458 (setq speedup (float speedup))
2459 (if mpc--faster-toggle-timer
2460 (mpc--faster-stop)
2461 (mpc-status-refresh) (mpc-proc-sync)
2462 (let* (songid ;The ID of the currently ffwd/rewinding song.
2463 songduration ;The duration of that song.
2464 songtime ;The time of the song last time we ran.
2465 oldtime ;The time of day last time we ran.
2466 prevsongid) ;The song we're in the process leaving.
2467 (let ((fun
2468 (lambda ()
2469 (let ((newsongid (cdr (assq 'songid mpc-status))))
2470
2471 (if (and (equal prevsongid newsongid)
2472 (not (equal prevsongid songid)))
2473 ;; We left prevsongid and came back to it. Pretend it
2474 ;; didn't happen.
2475 (setq newsongid songid))
2476
2477 (cond
2478 ((null newsongid) (mpc--faster-stop))
2479 ((not (equal songid newsongid))
2480 ;; We jumped to another song: reset.
2481 (setq songid newsongid)
2482 (setq songtime (string-to-number
2483 (cdr (assq 'time mpc-status))))
2484 (setq songduration (mpc--songduration))
2485 (setq oldtime (float-time)))
2486 ((and (>= songtime songduration) mpc--faster-toggle-forward)
2487 ;; Skip to the beginning of the next song.
2488 (if (not (equal (cdr (assq 'state mpc-status)) "play"))
2489 (mpc-proc-cmd "next" 'mpc-status-refresh)
2490 ;; If we're playing, this is done automatically, so we
2491 ;; don't need to do anything, or rather we *shouldn't*
2492 ;; do anything otherwise there's a race condition where
2493 ;; we could skip straight to the next next song.
2494 nil))
2495 ((and (<= songtime 0) (not mpc--faster-toggle-forward))
2496 ;; Skip to the end of the previous song.
2497 (setq prevsongid songid)
2498 (mpc-proc-cmd "previous"
2499 (lambda ()
2500 (mpc-status-refresh
2501 (lambda ()
2502 (setq songid (cdr (assq 'songid mpc-status)))
2503 (setq songtime (setq songduration (mpc--songduration)))
2504 (setq oldtime (float-time))
2505 (mpc-proc-cmd (list "seekid" songid songtime)))))))
2506 (t
2507 (setq speedup (+ speedup mpc--faster-acceleration))
2508 (let ((newstep
2509 (truncate (* speedup (- (float-time) oldtime)))))
2510 (if (<= newstep 1) (setq newstep 1))
2511 (setq oldtime (+ oldtime (/ newstep speedup)))
2512 (if (not mpc--faster-toggle-forward)
2513 (setq newstep (- newstep)))
2514 (setq songtime (min songduration (+ songtime newstep)))
2515 (unless (>= songtime songduration)
2516 (condition-case nil
2517 (mpc-proc-cmd
2518 (list "seekid" songid songtime)
2519 'mpc-status-refresh)
2520 (mpc-proc-error (mpc-status-refresh)))))))))))
2521 (setq mpc--faster-toggle-forward (> step 0))
2522 (funcall fun) ;Initialize values.
2523 (setq mpc--faster-toggle-timer
2524 (run-with-timer t 0.3 fun))))))
2525
2526
2527
2528 (defvar mpc-faster-speedup 8)
2529
2530 (defun mpc-ffwd (_event)
2531 "Fast forward."
2532 (interactive (list last-nonmenu-event))
2533 ;; (mpc--faster event 4.0 1)
2534 (mpc--faster-toggle mpc-faster-speedup 1))
2535
2536 (defun mpc-rewind (_event)
2537 "Fast rewind."
2538 (interactive (list last-nonmenu-event))
2539 ;; (mpc--faster event 4.0 -1)
2540 (mpc--faster-toggle mpc-faster-speedup -1))
2541
2542
2543 (defun mpc-play-at-point (&optional event)
2544 (interactive (list last-nonmenu-event))
2545 (mpc-select event)
2546 (mpc-play))
2547
2548 ;; (defun mpc-play-tagval ()
2549 ;; "Play all the songs of the tag at point."
2550 ;; (interactive)
2551 ;; (let* ((val (buffer-substring (line-beginning-position) (line-end-position)))
2552 ;; (songs (mapcar 'cdar
2553 ;; (mpc-proc-buf-to-alists
2554 ;; (mpc-proc-cmd (list "find" mpc-tag val))))))
2555 ;; (mpc-cmd-add songs)
2556 ;; (if (member (cdr (assq 'state (mpc-cmd-status))) '("stop"))
2557 ;; (mpc-cmd-play))))
2558
2559 ;;; Drag'n'drop support ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2560 ;; Todo:
2561 ;; the main thing to do here, is to provide visual feedback during the drag:
2562 ;; - change the mouse-cursor.
2563 ;; - highlight/select the source and the current destination.
2564
2565 (defun mpc-drag-n-drop (event)
2566 "DWIM for a drag EVENT."
2567 (interactive "e")
2568 (let* ((start (event-start event))
2569 (end (event-end event))
2570 (start-buf (window-buffer (posn-window start)))
2571 (end-buf (window-buffer (posn-window end)))
2572 (songs
2573 (with-current-buffer start-buf
2574 (goto-char (posn-point start))
2575 (if (get-text-property (point) 'mpc-select)
2576 ;; FIXME: actually we should only consider the constraints
2577 ;; corresponding to the selection in this particular buffer.
2578 (mpc-songs-selection)
2579 (cond
2580 ((and (derived-mode-p 'mpc-songs-mode)
2581 (get-text-property (point) 'mpc-file))
2582 (list (cons (get-text-property (point) 'mpc-file)
2583 (get-text-property (point) 'mpc-file-pos))))
2584 ((and mpc-tag (not (mpc-tagbrowser-all-p)))
2585 (mapcar (lambda (song)
2586 (list (cdr (assq 'file song))))
2587 (mpc-cmd-find
2588 mpc-tag
2589 (buffer-substring (line-beginning-position)
2590 (line-end-position)))))
2591 (t
2592 (error "Unsupported starting position for drag'n'drop gesture")))))))
2593 (with-current-buffer end-buf
2594 (goto-char (posn-point end))
2595 (cond
2596 ((eq mpc-tag 'Playlist)
2597 ;; Adding elements to a named playlist.
2598 (let ((playlist (if (or (mpc-tagbrowser-all-p)
2599 (and (bolp) (eolp)))
2600 (error "Not a playlist")
2601 (buffer-substring (line-beginning-position)
2602 (line-end-position)))))
2603 (mpc-cmd-add (mapcar 'car songs) playlist)
2604 (message "Added %d songs to %s" (length songs) playlist)
2605 (if (member playlist
2606 (cdr (assq 'Playlist (mpc-constraints-get-current))))
2607 (mpc-songs-refresh))))
2608 ((derived-mode-p 'mpc-songs-mode)
2609 (cond
2610 ((null mpc-songs-playlist)
2611 (error "The songs shown do not belong to a playlist"))
2612 ((eq start-buf end-buf)
2613 ;; Moving songs within the shown playlist.
2614 (let ((dest-pos (get-text-property (point) 'mpc-file-pos)))
2615 (mpc-cmd-move (mapcar 'cdr songs) dest-pos mpc-songs-playlist)
2616 (message "Moved %d songs" (length songs))))
2617 (t
2618 ;; Adding songs to the shown playlist.
2619 (let ((dest-pos (get-text-property (point) 'mpc-file-pos))
2620 (pl (if (stringp mpc-songs-playlist)
2621 (mpc-cmd-find 'Playlist mpc-songs-playlist)
2622 (mpc-proc-cmd-to-alist "playlist"))))
2623 ;; MPD's protocol does not let us add songs at a particular
2624 ;; position in a playlist, so we first have to add them to the
2625 ;; end, and then move them to their final destination.
2626 (mpc-cmd-add (mapcar 'car songs) mpc-songs-playlist)
2627 (mpc-cmd-move (let ((poss '()))
2628 (dotimes (i (length songs))
2629 (push (+ i (length pl)) poss))
2630 (nreverse poss))
2631 dest-pos mpc-songs-playlist)
2632 (message "Added %d songs" (length songs)))))
2633 (mpc-songs-refresh))
2634 (t
2635 (error "Unsupported drag'n'drop gesture"))))))
2636
2637 ;;; Toplevel ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2638
2639 (defcustom mpc-frame-alist '((name . "MPC") (tool-bar-lines . 1)
2640 (font . "Sans"))
2641 "Alist of frame parameters for the MPC frame."
2642 :type 'alist)
2643
2644 ;;;###autoload
2645 (defun mpc ()
2646 "Main entry point for MPC."
2647 (interactive
2648 (progn
2649 (if current-prefix-arg
2650 ;; FIXME: We should provide some completion here, especially for the
2651 ;; case where the user specifies a local socket/file name.
2652 (setq mpc-host (read-string "MPD host and port: " nil nil mpc-host)))
2653 nil))
2654 (let* ((song-buf (mpc-songs-buf))
2655 (song-win (get-buffer-window song-buf 0)))
2656 (if song-win
2657 (select-window song-win)
2658 (if (or (window-dedicated-p) (window-minibuffer-p))
2659 (ignore-errors (select-frame (make-frame mpc-frame-alist)))
2660 (with-current-buffer song-buf
2661 (setq-local mpc-previous-window-config
2662 (current-window-configuration))))
2663 (let* ((win1 (selected-window))
2664 (win2 (split-window))
2665 (tags mpc-browser-tags))
2666 (unless tags (error "Need at least one entry in `mpc-browser-tags'"))
2667 (set-window-buffer win2 song-buf)
2668 (set-window-dedicated-p win2 'soft)
2669 (mpc-status-buffer-show)
2670 (while
2671 (progn
2672 (set-window-buffer win1 (mpc-tagbrowser-buf (pop tags)))
2673 (set-window-dedicated-p win1 'soft)
2674 tags)
2675 (setq win1 (split-window win1 nil 'horiz)))))
2676 (balance-windows-area))
2677 (mpc-songs-refresh)
2678 (mpc-status-refresh))
2679
2680 (provide 'mpc)
2681
2682 ;;; mpc.el ends here