Add support for 'PCM' and 'Headphone' channels for OSS mixer.
[lxde/lxpanel.git] / plugins / volumealsa / volumealsa.c
1 /*
2 * Copyright (C) 2006-2008 Jim Huang <jserv.tw@gmail.com>
3 * 2006 Hong Jen Yee (PCMan) <pcman.tw@gmail.com>
4 *
5 * Copyright (C) 2008 Fred Chien <fred@lxde.org>
6 * 2008 Hong Jen Yee (PCMan) <pcman.tw@gmail.com>
7 * 2009-2010 Marty Jack <martyj19@comcast.net>
8 * 2010-2012 Julien Lavergne <julien.lavergne@gmail.com>
9 * 2012 Henry Gebhardt <hsggebhardt@gmail.com>
10 * 2014 Peter <ombalaxitabou@users.sf.net>
11 * 2014-2016 Andriy Grytsenko <andrej@rep.kiev.ua>
12 *
13 * This file is a part of LXPanel project.
14 *
15 * This program is free software; you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation; either version 2 of the License, or
18 * (at your option) any later version.
19 *
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * You should have received a copy of the GNU General Public License
26 * along with this program; if not, write to the Free Software Foundation,
27 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
28 */
29
30 #define _ISOC99_SOURCE /* lrint() */
31 #define _GNU_SOURCE /* exp10() */
32
33 #ifdef HAVE_CONFIG_H
34 #include <config.h>
35 #endif
36
37 #include <gtk/gtk.h>
38 #include <stdlib.h>
39 #include <fcntl.h>
40 #include <unistd.h>
41 #include <glib.h>
42 #include <glib/gi18n.h>
43 #include <gdk-pixbuf/gdk-pixbuf.h>
44 #ifdef DISABLE_ALSA
45 #include <sys/types.h>
46 #include <sys/stat.h>
47 #include <sys/ioctl.h>
48 #include <string.h>
49 #include <stdio.h>
50 #include <fcntl.h>
51 #include <errno.h>
52 #ifdef HAVE_SYS_SOUNDCARD_H
53 #include <sys/soundcard.h>
54 #elif defined(HAVE_LINUX_SOUNDCARD_H)
55 #include <linux/soundcard.h>
56 #else
57 #error "Not supported platform"
58 #endif
59 #ifndef SOUND_MIXER_PHONEOUT
60 # define SOUND_MIXER_PHONEOUT SOUND_MIXER_MONO
61 #endif
62 //TODO: support OSSv4
63 #else
64 #include <alsa/asoundlib.h>
65 #include <poll.h>
66 #endif
67 #include <math.h>
68 #include <libfm/fm-gtk.h>
69 #include "plugin.h"
70 #include "misc.h"
71
72 #define ICONS_VOLUME_HIGH "volume-high"
73 #define ICONS_VOLUME_MEDIUM "volume-medium"
74 #define ICONS_VOLUME_LOW "volume-low"
75 #define ICONS_MUTE "mute"
76
77 #ifdef __UCLIBC__
78 /* 10^x = 10^(log e^x) = (e^x)^log10 = e^(x * log 10) */
79 # define M_LN10 2.30258509299404568402 /* log_e 10 */
80 #define exp10(x) (exp((x) * log(10)))
81 #endif /* __UCLIBC__ */
82
83 #define MAX_LINEAR_DB_SCALE 24
84
85 #ifdef DISABLE_ALSA
86 typedef union
87 {
88 struct
89 {
90 unsigned char left;
91 unsigned char right;
92 };
93 int value;
94 } StereoVolume;
95 #endif
96
97 typedef struct {
98
99 /* Graphics. */
100 GtkWidget * plugin; /* Back pointer to the widget */
101 LXPanel * panel; /* Back pointer to panel */
102 config_setting_t * settings; /* Plugin settings */
103 GtkWidget * tray_icon; /* Displayed image */
104 GtkWidget * popup_window; /* Top level window for popup */
105 GtkWidget * volume_scale; /* Scale for volume */
106 GtkWidget * mute_check; /* Checkbox for mute state */
107 gboolean show_popup; /* Toggle to show and hide the popup on left click */
108 guint volume_scale_handler; /* Handler for vscale widget */
109 guint mute_check_handler; /* Handler for mute_check widget */
110
111 #ifdef DISABLE_ALSA
112 int mixer_fd; /* The mixer FD */
113 gdouble vol_before_mute; /* Save value when muted */
114
115 guint master_channel;
116 #else
117 /* ALSA interface. */
118 snd_mixer_t * mixer; /* The mixer */
119 snd_mixer_selem_id_t * sid; /* The element ID */
120 snd_mixer_elem_t * master_element; /* The Master element */
121 guint mixer_evt_idle; /* Timer to handle restarting poll */
122 guint restart_idle;
123 gint alsamixer_mapping;
124
125 /* unloading and error handling */
126 GIOChannel **channels; /* Channels that we listen to */
127 guint *watches; /* Watcher IDs for channels */
128 guint num_channels; /* Number of channels */
129
130 char *master_channel;
131 #endif
132
133 /* Icons */
134 const char* icon_panel;
135 const char* icon_fallback;
136
137 /* Clicks */
138 int mute_click;
139 GdkModifierType mute_click_mods;
140 int mixer_click;
141 GdkModifierType mixer_click_mods;
142 int slider_click;
143 GdkModifierType slider_click_mods;
144 } VolumeALSAPlugin;
145
146 #ifndef DISABLE_ALSA
147 static gboolean asound_restart(gpointer vol_gpointer);
148 #endif
149 static gboolean asound_initialize(VolumeALSAPlugin * vol);
150 static void asound_deinitialize(VolumeALSAPlugin * vol);
151 static void volumealsa_update_display(VolumeALSAPlugin * vol);
152 static void volumealsa_destructor(gpointer user_data);
153
154 /*** ALSA ***/
155
156 #ifndef DISABLE_ALSA
157 static gboolean asound_find_element(VolumeALSAPlugin * vol, const char ** ename, int n)
158 {
159 int i;
160
161 for (i = 0; i < n; i++)
162 {
163 for (vol->master_element = snd_mixer_first_elem(vol->mixer);
164 vol->master_element != NULL;
165 vol->master_element = snd_mixer_elem_next(vol->master_element))
166 {
167 snd_mixer_selem_get_id(vol->master_element, vol->sid);
168 if (snd_mixer_selem_is_active(vol->master_element) &&
169 strcmp(ename[i], snd_mixer_selem_id_get_name(vol->sid)) == 0)
170 return TRUE;
171 }
172 }
173 return FALSE;
174 }
175
176 /* NOTE by PCMan:
177 * This is magic! Since ALSA uses its own machanism to handle this part.
178 * After polling of mixer fds, it requires that we should call
179 * snd_mixer_handle_events to clear all pending mixer events.
180 * However, when using the glib IO channels approach, we don't have
181 * poll() and snd_mixer_poll_descriptors_revents(). Due to the design of
182 * glib, on_mixer_event() will be called for every fd whose status was
183 * changed. So, after each poll(), it's called for several times,
184 * not just once. Therefore, we cannot call snd_mixer_handle_events()
185 * directly in the event handler. Otherwise, it will get called for
186 * several times, which might clear unprocessed pending events in the queue.
187 * So, here we call it once in the event callback for the first fd.
188 * Then, we don't call it for the following fds. After all fds with changed
189 * status are handled, we remove this restriction in an idle handler.
190 * The next time the event callback is involked for the first fs, we can
191 * call snd_mixer_handle_events() again. Racing shouldn't happen here
192 * because the idle handler has the same priority as the io channel callback.
193 * So, io callbacks for future pending events should be in the next gmain
194 * iteration, and won't be affected.
195 */
196
197 static gboolean asound_reset_mixer_evt_idle(VolumeALSAPlugin * vol)
198 {
199 if (!g_source_is_destroyed(g_main_current_source()))
200 vol->mixer_evt_idle = 0;
201 return FALSE;
202 }
203
204 /* Handler for I/O event on ALSA channel. */
205 static gboolean asound_mixer_event(GIOChannel * channel, GIOCondition cond, gpointer vol_gpointer)
206 {
207 VolumeALSAPlugin * vol = (VolumeALSAPlugin *) vol_gpointer;
208 int res = 0;
209
210 if (g_source_is_destroyed(g_main_current_source()))
211 return FALSE;
212
213 if (vol->mixer_evt_idle == 0)
214 {
215 vol->mixer_evt_idle = g_idle_add_full(G_PRIORITY_DEFAULT, (GSourceFunc) asound_reset_mixer_evt_idle, vol, NULL);
216 res = snd_mixer_handle_events(vol->mixer);
217 }
218
219 if (cond & G_IO_IN)
220 {
221 /* the status of mixer is changed. update of display is needed. */
222 volumealsa_update_display(vol);
223 }
224
225 if ((cond & G_IO_HUP) || (res < 0))
226 {
227 /* This means there're some problems with alsa. */
228 g_warning("volumealsa: ALSA (or pulseaudio) had a problem: "
229 "volumealsa: snd_mixer_handle_events() = %d,"
230 " cond 0x%x (IN: 0x%x, HUP: 0x%x).", res, cond,
231 G_IO_IN, G_IO_HUP);
232 gtk_widget_set_tooltip_text(vol->plugin, "ALSA (or pulseaudio) had a problem."
233 " Please check the lxpanel logs.");
234
235 if (vol->restart_idle == 0)
236 vol->restart_idle = g_timeout_add_seconds(1, asound_restart, vol);
237
238 return FALSE;
239 }
240
241 return TRUE;
242 }
243
244 static gboolean asound_restart(gpointer vol_gpointer)
245 {
246 VolumeALSAPlugin * vol = vol_gpointer;
247
248 if (g_source_is_destroyed(g_main_current_source()))
249 return FALSE;
250
251 asound_deinitialize(vol);
252
253 if (!asound_initialize(vol)) {
254 g_warning("volumealsa: Re-initialization failed.");
255 return TRUE; // try again in a second
256 }
257
258 g_warning("volumealsa: Restarted ALSA interface...");
259
260 vol->restart_idle = 0;
261 return FALSE;
262 }
263 #endif
264
265 /* Initialize the ALSA interface. */
266 static gboolean asound_initialize(VolumeALSAPlugin * vol)
267 {
268 /* Access the "default" device. */
269 #ifdef DISABLE_ALSA
270 vol->mixer_fd = open ("/dev/mixer", O_RDWR, 0);
271 if (vol->mixer_fd < 0)
272 {
273 g_warning("cannot initialize OSS mixer: %s", strerror(errno));
274 return FALSE;
275 }
276
277 //FIXME: is there a way to watch volume with OSS?
278 #else
279 snd_mixer_selem_id_alloca(&vol->sid);
280 snd_mixer_open(&vol->mixer, 0);
281 snd_mixer_attach(vol->mixer, "default");
282 snd_mixer_selem_register(vol->mixer, NULL, NULL);
283 snd_mixer_load(vol->mixer);
284
285 if (vol->master_channel)
286 {
287 /* If user defined the channel then use it */
288 if (!asound_find_element(vol, (const char **)&vol->master_channel, 1))
289 return FALSE;
290 }
291 else
292 {
293 const char * def_channels[] = { "Master", "Front", "PCM", "LineOut" };
294 /* Find Master element, or Front element, or PCM element, or LineOut element.
295 * If one of these succeeds, master_element is valid. */
296 if (!asound_find_element(vol, def_channels, G_N_ELEMENTS(def_channels)))
297 return FALSE;
298 }
299
300 /* Set the playback volume range as we wish it. */
301 if ( ! vol->alsamixer_mapping)
302 snd_mixer_selem_set_playback_volume_range(vol->master_element, 0, 100);
303
304 /* Listen to events from ALSA. */
305 int n_fds = snd_mixer_poll_descriptors_count(vol->mixer);
306 struct pollfd * fds = g_new0(struct pollfd, n_fds);
307
308 vol->channels = g_new0(GIOChannel *, n_fds);
309 vol->watches = g_new0(guint, n_fds);
310 vol->num_channels = n_fds;
311
312 snd_mixer_poll_descriptors(vol->mixer, fds, n_fds);
313 int i;
314 for (i = 0; i < n_fds; ++i)
315 {
316 GIOChannel* channel = g_io_channel_unix_new(fds[i].fd);
317 vol->watches[i] = g_io_add_watch(channel, G_IO_IN | G_IO_HUP, asound_mixer_event, vol);
318 vol->channels[i] = channel;
319 }
320 g_free(fds);
321 #endif
322 return TRUE;
323 }
324
325 static void asound_deinitialize(VolumeALSAPlugin * vol)
326 {
327 #ifdef DISABLE_ALSA
328 if (vol->mixer_fd >= 0)
329 close(vol->mixer_fd);
330 vol->mixer_fd = -1;
331 #else
332 guint i;
333
334 if (vol->mixer_evt_idle != 0) {
335 g_source_remove(vol->mixer_evt_idle);
336 vol->mixer_evt_idle = 0;
337 }
338
339 for (i = 0; i < vol->num_channels; i++) {
340 g_source_remove(vol->watches[i]);
341 g_io_channel_shutdown(vol->channels[i], FALSE, NULL);
342 g_io_channel_unref(vol->channels[i]);
343 }
344 g_free(vol->channels);
345 g_free(vol->watches);
346 vol->channels = NULL;
347 vol->watches = NULL;
348 vol->num_channels = 0;
349
350 snd_mixer_close(vol->mixer);
351 vol->master_element = NULL;
352 /* FIXME: unalloc vol->sid */
353 #endif
354 }
355
356 /* Get the presence of the mute control from the sound system. */
357 static gboolean asound_has_mute(VolumeALSAPlugin * vol)
358 {
359 #ifdef DISABLE_ALSA
360 /* it's emulated with OSS */
361 return TRUE;
362 #else
363 return ((vol->master_element != NULL) ? snd_mixer_selem_has_playback_switch(vol->master_element) : FALSE);
364 #endif
365 }
366
367 /* Get the condition of the mute control from the sound system. */
368 static gboolean asound_is_muted(VolumeALSAPlugin * vol)
369 {
370 /* The switch is on if sound is not muted, and off if the sound is muted.
371 * Initialize so that the sound appears unmuted if the control does not exist. */
372 int value = 1;
373 #ifdef DISABLE_ALSA
374 StereoVolume levels;
375
376 ioctl(vol->mixer_fd, MIXER_READ(vol->master_channel), &levels.value);
377 value = (levels.left + levels.right) >> 1;
378 #else
379 if (vol->master_element != NULL)
380 snd_mixer_selem_get_playback_switch(vol->master_element, 0, &value);
381 #endif
382 return (value == 0);
383 }
384
385 #ifndef DISABLE_ALSA
386 static long lrint_dir(double x, int dir)
387 {
388 if (dir > 0)
389 return lrint(ceil(x));
390 else if (dir < 0)
391 return lrint(floor(x));
392 else
393 return lrint(x);
394 }
395
396 static inline gboolean use_linear_dB_scale(long dBmin, long dBmax)
397 {
398 return dBmax - dBmin <= MAX_LINEAR_DB_SCALE * 100;
399 }
400
401 static long get_normalized_volume(snd_mixer_elem_t *elem,
402 snd_mixer_selem_channel_id_t channel)
403 {
404 long min, max, value;
405 double normalized, min_norm;
406 int err;
407
408 err = snd_mixer_selem_get_playback_dB_range(elem, &min, &max);
409 if (err < 0 || min >= max) {
410 err = snd_mixer_selem_get_playback_volume_range(elem, &min, &max);
411 if (err < 0 || min == max)
412 return 0;
413
414 err = snd_mixer_selem_get_playback_volume(elem, channel, &value);
415 if (err < 0)
416 return 0;
417
418 return lrint(100.0 * (value - min) / (double)(max - min));
419 }
420
421 err = snd_mixer_selem_get_playback_dB(elem, channel, &value);
422 if (err < 0)
423 return 0;
424
425 if (use_linear_dB_scale(min, max))
426 return lrint(100.0 * (value - min) / (double)(max - min));
427
428 normalized = exp10((value - max) / 6000.0);
429 if (min != SND_CTL_TLV_DB_GAIN_MUTE) {
430 min_norm = exp10((min - max) / 6000.0);
431 normalized = (normalized - min_norm) / (1 - min_norm);
432 }
433
434 return lrint(100.0 * normalized);
435 }
436 #endif
437
438 /* Get the volume from the sound system.
439 * This implementation returns the average of the Front Left and Front Right channels. */
440 static int asound_get_volume(VolumeALSAPlugin * vol)
441 {
442 #ifdef DISABLE_ALSA
443 StereoVolume levels;
444
445 ioctl(vol->mixer_fd, MIXER_READ(vol->master_channel), &levels.value);
446 return (levels.left + levels.right) >> 1;
447 #else
448 long aleft = 0;
449 long aright = 0;
450
451 if (vol->master_element != NULL)
452 {
453 if ( ! vol->alsamixer_mapping)
454 {
455 snd_mixer_selem_get_playback_volume(vol->master_element, SND_MIXER_SCHN_FRONT_LEFT, &aleft);
456 snd_mixer_selem_get_playback_volume(vol->master_element, SND_MIXER_SCHN_FRONT_RIGHT, &aright);
457 }
458 else
459 {
460 aleft = get_normalized_volume(vol->master_element, SND_MIXER_SCHN_FRONT_LEFT);
461 aright = get_normalized_volume(vol->master_element, SND_MIXER_SCHN_FRONT_RIGHT);
462 }
463 }
464 return (aleft + aright) >> 1;
465 #endif
466 }
467
468 #ifndef DISABLE_ALSA
469 static int set_normalized_volume(snd_mixer_elem_t *elem,
470 snd_mixer_selem_channel_id_t channel,
471 int vol,
472 int dir)
473 {
474 long min, max, value;
475 double min_norm, volume;
476 int err;
477
478 volume = vol / 100.0;
479
480 err = snd_mixer_selem_get_playback_dB_range(elem, &min, &max);
481 if (err < 0 || min >= max) {
482 err = snd_mixer_selem_get_playback_volume_range(elem, &min, &max);
483 if (err < 0)
484 return err;
485
486 value = lrint_dir(volume * (max - min), dir) + min;
487 return snd_mixer_selem_set_playback_volume(elem, channel, value);
488 }
489
490 if (use_linear_dB_scale(min, max)) {
491 value = lrint_dir(volume * (max - min), dir) + min;
492 return snd_mixer_selem_set_playback_dB(elem, channel, value, dir);
493 }
494
495 if (min != SND_CTL_TLV_DB_GAIN_MUTE) {
496 min_norm = exp10((min - max) / 6000.0);
497 volume = volume * (1 - min_norm) + min_norm;
498 }
499 value = lrint_dir(6000.0 * log10(volume), dir) + max;
500
501 return snd_mixer_selem_set_playback_dB(elem, channel, value, dir);
502 }
503 #endif
504
505 /* Set the volume to the sound system.
506 * This implementation sets the Front Left and Front Right channels to the specified value. */
507 static void asound_set_volume(VolumeALSAPlugin * vol, int volume)
508 {
509 int dir = volume - asound_get_volume(vol);
510
511 /* Volume is set to the correct value already */
512 if (dir == 0)
513 return;
514
515 #ifdef DISABLE_ALSA
516 StereoVolume levels;
517
518 levels.left = levels.right = volume;
519 ioctl(vol->mixer_fd, MIXER_WRITE(vol->master_channel), &levels.value);
520 #else
521 if (vol->master_element != NULL)
522 {
523 if ( ! vol->alsamixer_mapping)
524 {
525 snd_mixer_selem_set_playback_volume(vol->master_element, SND_MIXER_SCHN_FRONT_LEFT, volume);
526 snd_mixer_selem_set_playback_volume(vol->master_element, SND_MIXER_SCHN_FRONT_RIGHT, volume);
527 }
528 else
529 {
530 set_normalized_volume(vol->master_element, SND_MIXER_SCHN_FRONT_LEFT, volume, dir);
531 set_normalized_volume(vol->master_element, SND_MIXER_SCHN_FRONT_RIGHT, volume, dir);
532 }
533 }
534 #endif
535 }
536
537 /*** Graphics ***/
538
539 static void volumealsa_lookup_current_icon(VolumeALSAPlugin * vol, gboolean mute, int level)
540 {
541 /* Change icon according to mute / volume */
542 const char* icon_panel="audio-volume-muted-panel";
543 const char* icon_fallback=ICONS_MUTE;
544 if (mute)
545 {
546 icon_panel = "audio-volume-muted-panel";
547 icon_fallback=ICONS_MUTE;
548 }
549 else if (level >= 66)
550 {
551 icon_panel = "audio-volume-high-panel";
552 icon_fallback=ICONS_VOLUME_HIGH;
553 }
554 else if (level >= 33)
555 {
556 icon_panel = "audio-volume-medium-panel";
557 icon_fallback=ICONS_VOLUME_MEDIUM;
558 }
559 else if (level > 0)
560 {
561 icon_panel = "audio-volume-low-panel";
562 icon_fallback=ICONS_VOLUME_LOW;
563 }
564
565 vol->icon_panel = icon_panel;
566 vol->icon_fallback = icon_fallback;
567 }
568
569 static void volumealsa_update_current_icon(VolumeALSAPlugin * vol, gboolean mute, int level)
570 {
571 /* Find suitable icon */
572 volumealsa_lookup_current_icon(vol, mute, level);
573
574 /* Change icon, fallback to default icon if theme doesn't exsit */
575 lxpanel_image_change_icon(vol->tray_icon, vol->icon_panel, vol->icon_fallback);
576
577 /* Display current level in tooltip. */
578 char * tooltip = g_strdup_printf("%s %d", _("Volume control"), level);
579 gtk_widget_set_tooltip_text(vol->plugin, tooltip);
580 g_free(tooltip);
581 }
582
583 /*
584 * Here we just update volume's vertical scale and mute check button.
585 * The rest will be updated by signal handelrs.
586 */
587 static void volumealsa_update_display(VolumeALSAPlugin * vol)
588 {
589 /* Mute. */
590 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(vol->mute_check), asound_is_muted(vol));
591 gtk_widget_set_sensitive(vol->mute_check, (asound_has_mute(vol)));
592
593 /* Volume. */
594 if (vol->volume_scale != NULL)
595 {
596 gtk_range_set_value(GTK_RANGE(vol->volume_scale), asound_get_volume(vol));
597 }
598 }
599
600 static void volume_run_mixer(VolumeALSAPlugin * vol)
601 {
602 char *path = NULL;
603 const gchar *command_line = NULL;
604 GAppInfoCreateFlags flags = G_APP_INFO_CREATE_NONE;
605
606 /* check if command line was configured */
607 config_setting_lookup_string(vol->settings, "MixerCommand", &command_line);
608
609 /* if command isn't set in settings then let guess it */
610 if (command_line == NULL && (path = g_find_program_in_path("pulseaudio")))
611 {
612 g_free(path);
613 /* Assume that when pulseaudio is installed, it's launching every time */
614 if ((path = g_find_program_in_path("gnome-sound-applet")))
615 {
616 command_line = "gnome-sound-applet";
617 }
618 else if ((path = g_find_program_in_path("pavucontrol")))
619 {
620 command_line = "pavucontrol";
621 }
622 }
623
624 /* Fallback to alsamixer when PA is not running, or when no PA utility is find */
625 if (command_line == NULL)
626 {
627 if ((path = g_find_program_in_path("gnome-alsamixer")))
628 {
629 command_line = "gnome-alsamixer";
630 }
631 else if ((path = g_find_program_in_path("alsamixergui")))
632 {
633 command_line = "alsamixergui";
634 }
635 else if ((path = g_find_program_in_path("alsamixer")))
636 {
637 command_line = "alsamixer";
638 flags = G_APP_INFO_CREATE_NEEDS_TERMINAL;
639 }
640 }
641 g_free(path);
642
643 if (command_line)
644 {
645 fm_launch_command_simple(NULL, NULL, flags, command_line, NULL);
646 }
647 else
648 {
649 fm_show_error(NULL, NULL,
650 _("Error, you need to install an application to configure"
651 " the sound (pavucontrol, alsamixer ...)"));
652 }
653 }
654
655 static void _check_click(VolumeALSAPlugin * vol, int button, GdkModifierType mod)
656 {
657 if (vol->slider_click == button && vol->slider_click_mods == mod)
658 {
659 /* Left-click. Show or hide the popup window. */
660 if (vol->show_popup)
661 {
662 gtk_widget_hide(vol->popup_window);
663 vol->show_popup = FALSE;
664 }
665 else
666 {
667 gtk_widget_show_all(vol->popup_window);
668 vol->show_popup = TRUE;
669 }
670 }
671 if (vol->mute_click == button && vol->mute_click_mods == mod)
672 {
673 /* Middle-click. Toggle the mute status. */
674 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(vol->mute_check), ! gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(vol->mute_check)));
675 }
676 if (vol->mixer_click == button && vol->mixer_click_mods == mod)
677 {
678 volume_run_mixer(vol);
679 }
680 }
681
682 /* Handler for "button-press-event" signal on main widget. */
683 static gboolean volumealsa_button_press_event(GtkWidget * widget, GdkEventButton * event, LXPanel * panel)
684 {
685 VolumeALSAPlugin * vol = lxpanel_plugin_get_data(widget);
686
687 if (event->button == 1)
688 {
689 _check_click(vol, 1,
690 event->state & gtk_accelerator_get_default_mod_mask());
691 }
692
693 return FALSE;
694 }
695
696 static gboolean volumealsa_button_release_event(GtkWidget * widget, GdkEventButton * event, VolumeALSAPlugin * vol)
697 {
698 if (event->button != 1)
699 {
700 _check_click(vol, event->button,
701 event->state & gtk_accelerator_get_default_mod_mask());
702 }
703 return FALSE;
704 }
705
706 /* Handler for "focus-out" signal on popup window. */
707 static gboolean volumealsa_popup_focus_out(GtkWidget * widget, GdkEvent * event, VolumeALSAPlugin * vol)
708 {
709 /* Hide the widget. */
710 gtk_widget_hide(vol->popup_window);
711 vol->show_popup = FALSE;
712 return FALSE;
713 }
714
715 /* Handler for "map" signal on popup window. */
716 static void volumealsa_popup_map(GtkWidget * widget, VolumeALSAPlugin * vol)
717 {
718 lxpanel_plugin_adjust_popup_position(widget, vol->plugin);
719 }
720
721 /* Handler for "value_changed" signal on popup window vertical scale. */
722 static void volumealsa_popup_scale_changed(GtkRange * range, VolumeALSAPlugin * vol)
723 {
724 int level = gtk_range_get_value(GTK_RANGE(vol->volume_scale));
725 gboolean mute = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(vol->mute_check));
726
727 /* Reflect the value of the control to the sound system. */
728 asound_set_volume(vol, level);
729
730 /*
731 * Redraw the controls.
732 * Scale and check button do not need to be updated, as these are always
733 * in sync with user's actions.
734 */
735 volumealsa_update_current_icon(vol, mute, level);
736 }
737
738 /* Handler for "scroll-event" signal on popup window vertical scale. */
739 static void volumealsa_popup_scale_scrolled(GtkScale * scale, GdkEventScroll * evt, VolumeALSAPlugin * vol)
740 {
741 /* Get the state of the vertical scale. */
742 gdouble val = gtk_range_get_value(GTK_RANGE(vol->volume_scale));
743
744 /* Dispatch on scroll direction to update the value. */
745 if ((evt->direction == GDK_SCROLL_UP) || (evt->direction == GDK_SCROLL_LEFT))
746 val += 2;
747 else
748 val -= 2;
749
750 /* Reset the state of the vertical scale. This provokes a "value_changed" event. */
751 gtk_range_set_value(GTK_RANGE(vol->volume_scale), CLAMP((int)val, 0, 100));
752 }
753
754 /* Handler for "toggled" signal on popup window mute checkbox. */
755 static void volumealsa_popup_mute_toggled(GtkWidget * widget, VolumeALSAPlugin * vol)
756 {
757 int level = gtk_range_get_value(GTK_RANGE(vol->volume_scale));
758 gboolean mute = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(vol->mute_check));
759
760 /* Reflect the mute toggle to the sound system. */
761 #ifdef DISABLE_ALSA
762 if (mute)
763 {
764 vol->vol_before_mute = level;
765 asound_set_volume(vol, 0);
766 }
767 else
768 {
769 asound_set_volume(vol, vol->vol_before_mute);
770 }
771 #else
772 if (vol->master_element != NULL)
773 {
774 int chn;
775 for (chn = 0; chn <= SND_MIXER_SCHN_LAST; chn++)
776 snd_mixer_selem_set_playback_switch(vol->master_element, chn, ((mute) ? 0 : 1));
777 }
778 #endif
779
780 /*
781 * Redraw the controls.
782 * Scale and check button do not need to be updated, as these are always
783 * in sync with user's actions.
784 */
785 volumealsa_update_current_icon(vol, mute, level);
786 }
787
788 /* Build the window that appears when the top level widget is clicked. */
789 static void volumealsa_build_popup_window(GtkWidget *p)
790 {
791 VolumeALSAPlugin * vol = lxpanel_plugin_get_data(p);
792
793 /* Create a new window. */
794 vol->popup_window = gtk_window_new(GTK_WINDOW_POPUP);
795 gtk_window_set_decorated(GTK_WINDOW(vol->popup_window), FALSE);
796 gtk_container_set_border_width(GTK_CONTAINER(vol->popup_window), 5);
797 gtk_window_set_default_size(GTK_WINDOW(vol->popup_window), 80, 140);
798 gtk_window_set_skip_taskbar_hint(GTK_WINDOW(vol->popup_window), TRUE);
799 gtk_window_set_skip_pager_hint(GTK_WINDOW(vol->popup_window), TRUE);
800 gtk_window_set_type_hint(GTK_WINDOW(vol->popup_window), GDK_WINDOW_TYPE_HINT_UTILITY);
801
802 /* Connect signals. */
803 g_signal_connect(G_OBJECT(vol->popup_window), "focus-out-event", G_CALLBACK(volumealsa_popup_focus_out), vol);
804 g_signal_connect(G_OBJECT(vol->popup_window), "map", G_CALLBACK(volumealsa_popup_map), vol);
805
806 /* Create a scrolled window as the child of the top level window. */
807 GtkWidget * scrolledwindow = gtk_scrolled_window_new(NULL, NULL);
808 gtk_container_set_border_width (GTK_CONTAINER(scrolledwindow), 0);
809 gtk_widget_show(scrolledwindow);
810 gtk_container_add(GTK_CONTAINER(vol->popup_window), scrolledwindow);
811 gtk_widget_set_can_focus(scrolledwindow, FALSE);
812 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW (scrolledwindow), GTK_POLICY_NEVER, GTK_POLICY_NEVER);
813 gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scrolledwindow), GTK_SHADOW_NONE);
814
815 /* Create a viewport as the child of the scrolled window. */
816 GtkWidget * viewport = gtk_viewport_new(NULL, NULL);
817 gtk_container_add(GTK_CONTAINER(scrolledwindow), viewport);
818 gtk_viewport_set_shadow_type(GTK_VIEWPORT(viewport), GTK_SHADOW_NONE);
819 gtk_widget_show(viewport);
820
821 /* Create a frame as the child of the viewport. */
822 GtkWidget * frame = gtk_frame_new(_("Volume"));
823 gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_IN);
824 gtk_container_add(GTK_CONTAINER(viewport), frame);
825
826 /* Create a vertical box as the child of the frame. */
827 GtkWidget * box = gtk_vbox_new(FALSE, 0);
828 gtk_container_add(GTK_CONTAINER(frame), box);
829
830 /* Create a vertical scale as the child of the vertical box. */
831 vol->volume_scale = gtk_vscale_new(GTK_ADJUSTMENT(gtk_adjustment_new(100, 0, 100, 0, 0, 0)));
832 gtk_scale_set_draw_value(GTK_SCALE(vol->volume_scale), FALSE);
833 gtk_range_set_inverted(GTK_RANGE(vol->volume_scale), TRUE);
834 gtk_box_pack_start(GTK_BOX(box), vol->volume_scale, TRUE, TRUE, 0);
835
836 /* Value-changed and scroll-event signals. */
837 vol->volume_scale_handler = g_signal_connect(vol->volume_scale, "value-changed", G_CALLBACK(volumealsa_popup_scale_changed), vol);
838 g_signal_connect(vol->volume_scale, "scroll-event", G_CALLBACK(volumealsa_popup_scale_scrolled), vol);
839
840 /* Create a check button as the child of the vertical box. */
841 vol->mute_check = gtk_check_button_new_with_label(_("Mute"));
842 gtk_box_pack_end(GTK_BOX(box), vol->mute_check, FALSE, FALSE, 0);
843 vol->mute_check_handler = g_signal_connect(vol->mute_check, "toggled", G_CALLBACK(volumealsa_popup_mute_toggled), vol);
844
845 /* Set background to default. */
846 gtk_widget_set_style(viewport, panel_get_defstyle(vol->panel));
847 }
848
849 /* Plugin constructor. */
850 static GtkWidget *volumealsa_constructor(LXPanel *panel, config_setting_t *settings)
851 {
852 /* Allocate and initialize plugin context and set into Plugin private data pointer. */
853 VolumeALSAPlugin * vol = g_new0(VolumeALSAPlugin, 1);
854 GtkWidget *p;
855 const char *tmp_str;
856
857 #ifndef DISABLE_ALSA
858 /* Read config necessary for proper initialization of ALSA. */
859 config_setting_lookup_int(settings, "UseAlsamixerVolumeMapping", &vol->alsamixer_mapping);
860 if (config_setting_lookup_string(settings, "MasterChannel", &tmp_str))
861 vol->master_channel = g_strdup(tmp_str);
862 #else
863 vol->master_channel = SOUND_MIXER_VOLUME;
864 if (config_setting_lookup_string(settings, "MasterChannel", &tmp_str))
865 {
866 if (strcmp(tmp_str, "PCM") == 0)
867 vol->master_channel = SOUND_MIXER_PCM;
868 else if (strcmp(tmp_str, "Headphone") == 0)
869 vol->master_channel = SOUND_MIXER_PHONEOUT;
870 }
871 #endif
872 if (config_setting_lookup_string(settings, "MuteButton", &tmp_str))
873 vol->mute_click = panel_config_click_parse(tmp_str, &vol->mute_click_mods);
874 else
875 vol->mute_click = 2; /* middle-click default */
876 if (config_setting_lookup_string(settings, "SliderButton", &tmp_str))
877 vol->slider_click = panel_config_click_parse(tmp_str, &vol->slider_click_mods);
878 else
879 vol->slider_click = 1; /* left-click default */
880 if (config_setting_lookup_string(settings, "MixerButton", &tmp_str))
881 vol->mixer_click = panel_config_click_parse(tmp_str, &vol->mixer_click_mods);
882
883 /* Initialize ALSA. If that fails, present nothing. */
884 if ( ! asound_initialize(vol))
885 {
886 volumealsa_destructor(vol);
887 return NULL;
888 }
889
890 /* Allocate top level widget and set into Plugin widget pointer. */
891 vol->panel = panel;
892 vol->plugin = p = gtk_event_box_new();
893 vol->settings = settings;
894 lxpanel_plugin_set_data(p, vol, volumealsa_destructor);
895 gtk_widget_set_tooltip_text(p, _("Volume control"));
896
897 /* Allocate icon as a child of top level. */
898 vol->tray_icon = lxpanel_image_new_for_icon(panel, "audio-volume-muted-panel",
899 -1, ICONS_MUTE);
900 gtk_container_add(GTK_CONTAINER(p), vol->tray_icon);
901
902 /* Initialize window to appear when icon clicked. */
903 volumealsa_build_popup_window(p);
904
905 /* Connect signals. */
906 g_signal_connect(G_OBJECT(p), "scroll-event", G_CALLBACK(volumealsa_popup_scale_scrolled), vol );
907 g_signal_connect(G_OBJECT(p), "button-release-event", G_CALLBACK(volumealsa_button_release_event), vol );
908
909 /* Update the display, show the widget, and return. */
910 volumealsa_update_display(vol);
911 volumealsa_update_current_icon(vol, asound_is_muted(vol), asound_get_volume(vol));
912 gtk_widget_show_all(p);
913 return p;
914 }
915
916 /* Plugin destructor. */
917 static void volumealsa_destructor(gpointer user_data)
918 {
919 VolumeALSAPlugin * vol = (VolumeALSAPlugin *) user_data;
920
921 asound_deinitialize(vol);
922
923 /* If the dialog box is open, dismiss it. */
924 if (vol->popup_window != NULL)
925 gtk_widget_destroy(vol->popup_window);
926
927 #ifndef DISABLE_ALSA
928 if (vol->restart_idle)
929 g_source_remove(vol->restart_idle);
930
931 g_free(vol->master_channel);
932 #endif
933
934 /* Deallocate all memory. */
935 g_free(vol);
936 }
937
938 /* Callback when the configuration dialog is to be shown. */
939
940 static GtkWidget *volumealsa_configure(LXPanel *panel, GtkWidget *p)
941 {
942 VolumeALSAPlugin * vol = lxpanel_plugin_get_data(p);
943
944 /* FIXME: configure settings! */
945 /* FIXME: support "needs terminal" for MixerCommand */
946 /* FIXME: selection for master channel! */
947 /* FIXME: selection for the device */
948 /* FIXME: configure buttons for each action (toggle volume/mixer/mute)! */
949 /* FIXME: allow bind multimedia keys to volume using libkeybinder */
950
951 volume_run_mixer(vol);
952
953 return NULL;
954 }
955
956 /* Callback when panel configuration changes. */
957 static void volumealsa_panel_configuration_changed(LXPanel *panel, GtkWidget *p)
958 {
959 /* Do a full redraw. */
960 volumealsa_update_display(lxpanel_plugin_get_data(p));
961 }
962
963 #ifndef DISABLE_ALSA
964 static LXPanelPluginInit _volumealsa_init = {
965 .name = N_("Volume Control"),
966 .description = N_("Display and control volume"),
967
968 .superseded = TRUE,
969 .new_instance = volumealsa_constructor,
970 .config = volumealsa_configure,
971 .reconfigure = volumealsa_panel_configuration_changed,
972 .button_press_event = volumealsa_button_press_event
973 };
974
975 static void volumealsa_init(void)
976 {
977 lxpanel_register_plugin_type("volumealsa", &_volumealsa_init);
978 }
979 #endif
980
981 FM_DEFINE_MODULE(lxpanel_gtk, volume)
982
983 /* Plugin descriptor. */
984 LXPanelPluginInit fm_module_init_lxpanel_gtk = {
985 .name = N_("Volume Control"),
986 .description = N_("Display and control volume"),
987 #ifndef DISABLE_ALSA
988 .init = volumealsa_init,
989 #endif
990
991 .new_instance = volumealsa_constructor,
992 .config = volumealsa_configure,
993 .reconfigure = volumealsa_panel_configuration_changed,
994 .button_press_event = volumealsa_button_press_event
995 };
996
997 /* vim: set sw=4 et sts=4 : */