Code

screen_song: fix memory leak
[ncmpc.git] / src / screen_song.c
1 /* ncmpc (Ncurses MPD Client)
2  * (c) 2004-2017 The Music Player Daemon Project
3  * Project homepage: http://musicpd.org
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
20 #include "screen_song.h"
21 #include "screen_interface.h"
22 #include "screen_file.h"
23 #include "screen_lyrics.h"
24 #include "screen_find.h"
25 #include "i18n.h"
26 #include "screen.h"
27 #include "charset.h"
28 #include "time_format.h"
29 #include "mpdclient.h"
31 #include <mpd/client.h>
33 #include <glib/gprintf.h>
34 #include <assert.h>
35 #include <string.h>
37 enum {
38         LABEL_LENGTH = MPD_TAG_COUNT,
39         LABEL_PATH,
40         LABEL_BITRATE,
41         LABEL_FORMAT,
42         LABEL_POSITION,
43 };
45 static const char *const tag_labels[] = {
46         [MPD_TAG_ARTIST] = N_("Artist"),
47         [MPD_TAG_TITLE] = N_("Title"),
48         [MPD_TAG_ALBUM] = N_("Album"),
49         [LABEL_LENGTH] = N_("Length"),
50         [LABEL_POSITION] = N_("Position"),
51         [MPD_TAG_COMPOSER] = N_("Composer"),
52         [MPD_TAG_NAME] = N_("Name"),
53         [MPD_TAG_DISC] = N_("Disc"),
54         [MPD_TAG_TRACK] = N_("Track"),
55         [MPD_TAG_DATE] = N_("Date"),
56         [MPD_TAG_GENRE] = N_("Genre"),
57         [MPD_TAG_COMMENT] = N_("Comment"),
58         [LABEL_PATH] = N_("Path"),
59         [LABEL_BITRATE] = N_("Bitrate"),
60         [LABEL_FORMAT] = N_("Format"),
61 };
63 static unsigned max_tag_label_width;
65 enum stats_label {
66         STATS_ARTISTS,
67         STATS_ALBUMS,
68         STATS_SONGS,
69         STATS_UPTIME,
70         STATS_DBUPTIME,
71         STATS_PLAYTIME,
72         STATS_DBPLAYTIME,
73 };
75 static const char *const stats_labels[] = {
76         [STATS_ARTISTS] = N_("Number of artists"),
77         [STATS_ALBUMS] = N_("Number of albums"),
78         [STATS_SONGS] = N_("Number of songs"),
79         [STATS_UPTIME] = N_("Uptime"),
80         [STATS_DBUPTIME] = N_("Most recent db update"),
81         [STATS_PLAYTIME] = N_("Playtime"),
82         [STATS_DBPLAYTIME] = N_("DB playtime"),
83 };
85 static unsigned max_stats_label_width;
87 static struct list_window *lw;
89 static struct mpd_song *next_song;
91 static struct {
92         struct mpd_song *selected_song;
93         struct mpd_song *played_song;
94         GPtrArray *lines;
95 } current;
97 static void
98 screen_song_clear(void)
99 {
100         for (guint i = 0; i < current.lines->len; ++i)
101                 g_free(g_ptr_array_index(current.lines, i));
103         g_ptr_array_set_size(current.lines, 0);
105         if (current.selected_song != NULL) {
106                 mpd_song_free(current.selected_song);
107                 current.selected_song = NULL;
108         }
109         if (current.played_song != NULL) {
110                 mpd_song_free(current.played_song);
111                 current.played_song = NULL;
112         }
115 static const char *
116 screen_song_list_callback(unsigned idx, gcc_unused void *data)
118         assert(idx < current.lines->len);
120         return g_ptr_array_index(current.lines, idx);
124 static void
125 screen_song_init(WINDOW *w, unsigned cols, unsigned rows)
127         for (unsigned i = 0; i < G_N_ELEMENTS(tag_labels); ++i) {
128                 if (tag_labels[i] != NULL) {
129                         unsigned width = utf8_width(_(tag_labels[i]));
131                         if (width > max_tag_label_width)
132                                 max_tag_label_width = width;
133                 }
134         }
136         for (unsigned i = 0; i < G_N_ELEMENTS(stats_labels); ++i) {
137                 if (stats_labels[i] != NULL) {
138                         unsigned width = utf8_width(_(stats_labels[i]));
140                         if (width > max_stats_label_width)
141                                 max_stats_label_width = width;
142                 }
143         }
145         /* We will need at least 10 lines, so this saves 10 reallocations :) */
146         current.lines = g_ptr_array_sized_new(10);
147         lw = list_window_init(w, cols, rows);
148         lw->hide_cursor = true;
151 static void
152 screen_song_exit(void)
154         list_window_free(lw);
156         screen_song_clear();
158         g_ptr_array_free(current.lines, TRUE);
159         current.lines = NULL;
162 static void
163 screen_song_resize(unsigned cols, unsigned rows)
165         list_window_resize(lw, cols, rows);
168 static const char *
169 screen_song_title(gcc_unused char *str, gcc_unused size_t size)
171         return _("Song viewer");
174 static void
175 screen_song_paint(void)
177         list_window_paint(lw, screen_song_list_callback, NULL);
180 /* Appends a line with a fixed width for the label column
181  * Handles NULL strings gracefully */
182 static void
183 screen_song_append(const char *label, const char *value, unsigned label_col)
185         const unsigned label_width = locale_width(label) + 2;
187         assert(label != NULL);
188         assert(value != NULL);
189         assert(g_utf8_validate(value, -1, NULL));
191         /* +2 for ': ' */
192         label_col += 2;
193         const int value_col = lw->cols - label_col;
194         /* calculate the number of required linebreaks */
195         const gchar *value_iter = value;
196         const int label_size = strlen(label) + label_col;
198         while (*value_iter != 0) {
199                 char *entry = g_malloc(label_size), *entry_iter;
200                 if (value_iter == value) {
201                         entry_iter = entry + g_sprintf(entry, "%s: ", label);
202                         /* fill the label column with whitespaces */
203                         memset(entry_iter, ' ', label_col - label_width);
204                         entry_iter += label_col - label_width;
205                 }
206                 else {
207                         /* fill the label column with whitespaces */
208                         memset(entry, ' ', label_col);
209                         entry_iter = entry + label_col;
210                 }
211                 /* skip whitespaces */
212                 while (g_ascii_isspace(*value_iter)) ++value_iter;
214                 char *p = g_strdup(value_iter);
215                 unsigned width = utf8_cut_width(p, value_col);
216                 if (width == 0) {
217                         /* not enough room for anything - bail out */
218                         g_free(entry);
219                         g_free(p);
220                         break;
221                 }
223                 *entry_iter = 0;
225                 value_iter += strlen(p);
226                 p = replace_utf8_to_locale(p);
227                 char *q = g_strconcat(entry, p, NULL);
228                 g_free(entry);
229                 g_free(p);
231                 g_ptr_array_add(current.lines, q);
232         }
235 static void
236 screen_song_append_tag(const struct mpd_song *song, enum mpd_tag_type tag)
238         const char *label = _(tag_labels[tag]);
239         unsigned i = 0;
240         const char *value;
242         assert((unsigned)tag < G_N_ELEMENTS(tag_labels));
243         assert(label != NULL);
245         while ((value = mpd_song_get_tag(song, tag, i++)) != NULL)
246                 screen_song_append(label, value, max_tag_label_width);
249 static void
250 screen_song_add_song(const struct mpd_song *song)
252         assert(song != NULL);
254         char songpos[16];
255         g_snprintf(songpos, sizeof(songpos), "%d", mpd_song_get_pos(song) + 1);
256         screen_song_append(_(tag_labels[LABEL_POSITION]), songpos,
257                            max_tag_label_width);
259         screen_song_append_tag(song, MPD_TAG_ARTIST);
260         screen_song_append_tag(song, MPD_TAG_TITLE);
261         screen_song_append_tag(song, MPD_TAG_ALBUM);
263         /* create time string and add it */
264         if (mpd_song_get_duration(song) > 0) {
265                 char length[16];
266                 format_duration_short(length, sizeof(length),
267                                       mpd_song_get_duration(song));
269                 const char *value = length;
271                 char buffer[64];
273                 if (mpd_song_get_end(song) > 0) {
274                         char start[16], end[16];
275                         format_duration_short(start, sizeof(start),
276                                               mpd_song_get_start(song));
277                         format_duration_short(end, sizeof(end),
278                                               mpd_song_get_end(song));
280                         snprintf(buffer, sizeof(buffer), "%s [%s-%s]\n",
281                                  length, start, end);
282                         value = buffer;
283                 } else if (mpd_song_get_start(song) > 0) {
284                         char start[16];
285                         format_duration_short(start, sizeof(start),
286                                               mpd_song_get_start(song));
288                         snprintf(buffer, sizeof(buffer), "%s [%s-]\n",
289                                  length, start);
290                         value = buffer;
291                 }
293                 screen_song_append(_(tag_labels[LABEL_LENGTH]), value,
294                                    max_tag_label_width);
295         }
297         screen_song_append_tag(song, MPD_TAG_COMPOSER);
298         screen_song_append_tag(song, MPD_TAG_NAME);
299         screen_song_append_tag(song, MPD_TAG_DISC);
300         screen_song_append_tag(song, MPD_TAG_TRACK);
301         screen_song_append_tag(song, MPD_TAG_DATE);
302         screen_song_append_tag(song, MPD_TAG_GENRE);
303         screen_song_append_tag(song, MPD_TAG_COMMENT);
305         screen_song_append(_(tag_labels[LABEL_PATH]), mpd_song_get_uri(song),
306                            max_tag_label_width);
309 static void
310 screen_song_append_stats(enum stats_label label, const char *value)
312         screen_song_append(_(stats_labels[label]), value,
313                            max_stats_label_width);
316 static bool
317 screen_song_add_stats(struct mpd_connection *connection)
319         struct mpd_stats *mpd_stats = mpd_run_stats(connection);
320         if (mpd_stats == NULL)
321                 return false;
323         g_ptr_array_add(current.lines, g_strdup(_("MPD statistics")) );
325         char buf[64];
326         g_snprintf(buf, sizeof(buf), "%d",
327                    mpd_stats_get_number_of_artists(mpd_stats));
328         screen_song_append_stats(STATS_ARTISTS, buf);
329         g_snprintf(buf, sizeof(buf), "%d",
330                    mpd_stats_get_number_of_albums(mpd_stats));
331         screen_song_append_stats(STATS_ALBUMS, buf);
332         g_snprintf(buf, sizeof(buf), "%d",
333                    mpd_stats_get_number_of_songs(mpd_stats));
334         screen_song_append_stats(STATS_SONGS, buf);
336         format_duration_long(buf, sizeof(buf),
337                              mpd_stats_get_db_play_time(mpd_stats));
338         screen_song_append_stats(STATS_DBPLAYTIME, buf);
340         format_duration_long(buf, sizeof(buf),
341                              mpd_stats_get_play_time(mpd_stats));
342         screen_song_append_stats(STATS_PLAYTIME, buf);
344         format_duration_long(buf, sizeof(buf),
345                              mpd_stats_get_uptime(mpd_stats));
346         screen_song_append_stats(STATS_UPTIME, buf);
348         GDate *date = g_date_new();
349         g_date_set_time_t(date, mpd_stats_get_db_update_time(mpd_stats));
350         g_date_strftime(buf, sizeof(buf), "%x", date);
351         screen_song_append_stats(STATS_DBUPTIME, buf);
352         g_date_free(date);
354         mpd_stats_free(mpd_stats);
355         return true;
358 static void
359 audio_format_to_string(char *buffer, size_t size,
360                        const struct mpd_audio_format *format)
362 #if LIBMPDCLIENT_CHECK_VERSION(2,10,0)
363         if (format->bits == MPD_SAMPLE_FORMAT_FLOAT) {
364                 g_snprintf(buffer, size, "%u:f:%u",
365                            format->sample_rate,
366                            format->channels);
367                 return;
368         }
370         if (format->bits == MPD_SAMPLE_FORMAT_DSD) {
371                 if (format->sample_rate > 0 &&
372                     format->sample_rate % 44100 == 0) {
373                         /* use shortcuts such as "dsd64" which implies the
374                            sample rate */
375                         g_snprintf(buffer, size, "dsd%u:%u",
376                                    format->sample_rate * 8 / 44100,
377                                    format->channels);
378                         return;
379                 }
381                 g_snprintf(buffer, size, "%u:dsd:%u",
382                            format->sample_rate,
383                            format->channels);
384                 return;
385         }
386 #endif
388         g_snprintf(buffer, size, "%u:%u:%u",
389                    format->sample_rate, format->bits,
390                    format->channels);
393 static void
394 screen_song_update(struct mpdclient *c)
396         /* Clear all lines */
397         for (guint i = 0; i < current.lines->len; ++i)
398                 g_free(g_ptr_array_index(current.lines, i));
399         g_ptr_array_set_size(current.lines, 0);
401         /* If a song was selected before the song screen was opened */
402         if (next_song != NULL) {
403                 assert(current.selected_song == NULL);
404                 current.selected_song = next_song;
405                 next_song = NULL;
406         }
408         if (current.selected_song != NULL &&
409                         (c->song == NULL ||
410                          strcmp(mpd_song_get_uri(current.selected_song),
411                                 mpd_song_get_uri(c->song)) != 0 ||
412                          !mpdclient_is_playing(c))) {
413                 g_ptr_array_add(current.lines, g_strdup(_("Selected song")) );
414                 screen_song_add_song(current.selected_song);
415                 g_ptr_array_add(current.lines, g_strdup("\0"));
416         }
418         if (c->song != NULL && mpdclient_is_playing(c)) {
419                 if (current.played_song != NULL) {
420                         mpd_song_free(current.played_song);
421                 }
422                 current.played_song = mpd_song_dup(c->song);
423                 g_ptr_array_add(current.lines, g_strdup(_("Currently playing song")));
424                 screen_song_add_song(current.played_song);
426                 if (mpd_status_get_kbit_rate(c->status) > 0) {
427                         char buf[16];
428                         g_snprintf(buf, sizeof(buf), _("%d kbps"),
429                                    mpd_status_get_kbit_rate(c->status));
430                         screen_song_append(_(tag_labels[LABEL_BITRATE]), buf,
431                                            max_tag_label_width);
432                 }
434                 const struct mpd_audio_format *format =
435                         mpd_status_get_audio_format(c->status);
436                 if (format) {
437                         char buf[32];
438                         audio_format_to_string(buf, sizeof(buf), format);
439                         screen_song_append(_(tag_labels[LABEL_FORMAT]), buf,
440                                            max_tag_label_width);
441                 }
443                 g_ptr_array_add(current.lines, g_strdup("\0"));
444         }
446         /* Add some statistics about mpd */
447         struct mpd_connection *connection = mpdclient_get_connection(c);
448         if (connection != NULL && !screen_song_add_stats(connection))
449                 mpdclient_handle_error(c);
451         list_window_set_length(lw, current.lines->len);
452         screen_song_paint();
455 static bool
456 screen_song_cmd(struct mpdclient *c, command_t cmd)
458         if (list_window_scroll_cmd(lw, cmd)) {
459                 screen_song_paint();
460                 return true;
461         }
463         switch(cmd) {
464         case CMD_LOCATE:
465                 if (current.selected_song != NULL) {
466                         screen_file_goto_song(c, current.selected_song);
467                         return true;
468                 }
469                 if (current.played_song != NULL) {
470                         screen_file_goto_song(c, current.played_song);
471                         return true;
472                 }
474                 return false;
476 #ifdef ENABLE_LYRICS_SCREEN
477         case CMD_SCREEN_LYRICS:
478                 if (current.selected_song != NULL) {
479                         screen_lyrics_switch(c, current.selected_song, false);
480                         return true;
481                 }
482                 if (current.played_song != NULL) {
483                         screen_lyrics_switch(c, current.played_song, true);
484                         return true;
485                 }
486                 return false;
488 #endif
490         case CMD_SCREEN_SWAP:
491                 if (current.selected_song != NULL)
492                         screen_swap(c, current.selected_song);
493                 else
494                 // No need to check if this is null - we'd pass null anyway
495                         screen_swap(c, current.played_song);
496                 return true;
498         default:
499                 break;
500         }
502         if (screen_find(lw, cmd, screen_song_list_callback, NULL)) {
503                 /* center the row */
504                 list_window_center(lw, lw->selected);
505                 screen_song_paint();
506                 return true;
507         }
509         return false;
512 const struct screen_functions screen_song = {
513         .init = screen_song_init,
514         .exit = screen_song_exit,
515         .open = screen_song_update,
516         .close = screen_song_clear,
517         .resize = screen_song_resize,
518         .paint = screen_song_paint,
519         .update = screen_song_update,
520         .cmd = screen_song_cmd,
521         .get_title = screen_song_title,
522 };
524 void
525 screen_song_switch(struct mpdclient *c, const struct mpd_song *song)
527         assert(song != NULL);
528         assert(current.selected_song == NULL);
529         assert(current.played_song == NULL);
531         next_song = mpd_song_dup(song);
532         screen_switch(&screen_song, c);