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