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