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