Code

481683c847a8f490820a8b6b7991a3e045c45d21
[ncmpc.git] / src / hscroll.c
1 /* ncmpc (Ncurses MPD Client)
2  * (c) 2004-2009 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.
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.
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 "hscroll.h"
21 #include "charset.h"
23 #include <assert.h>
24 #include <string.h>
26 char *
27 strscroll(struct hscroll *hscroll, const char *str, const char *separator,
28           unsigned width)
29 {
30         gchar *tmp, *buf;
31         gsize len, size;
33         assert(hscroll != NULL);
34         assert(str != NULL);
35         assert(separator != NULL);
37         if (hscroll->offset == 0)
38                 return g_strdup(str);
40         /* create a buffer containing the string and the separator */
41         tmp = g_strconcat(str, separator, NULL);
42         len = utf8_width(tmp);
44         if (hscroll->offset >= len)
45                 hscroll->offset = 0;
47         /* create the new scrolled string */
48         size = width+1;
49         if (g_utf8_validate(tmp, -1, NULL) ) {
50                 size_t ulen;
51                 buf = g_malloc(size*6);// max length of utf8 char is 6
52                 g_utf8_strncpy(buf, g_utf8_offset_to_pointer(tmp, hscroll->offset), size);
53                 if( (ulen = g_utf8_strlen(buf, -1)) < width )
54                         g_utf8_strncpy(buf+strlen(buf), tmp, size - ulen - 1);
55         } else {
56                 buf = g_malloc(size);
57                 g_strlcpy(buf, tmp + hscroll->offset, size);
58                 if (strlen(buf) < (size_t)width)
59                         g_strlcat(buf, tmp, size);
60         }
62         g_free(tmp);
63         return buf;
64 }