9612e44e7f382b05fde510c1a832cc7a7518b1f5
[pspp] / src / ui / gui / widget-io.c
1 /* PSPPIRE - a graphical user interface for PSPP.
2    Copyright (C) 2007, 2009, 2011  Free Software Foundation
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include "widget-io.h"
20
21 #include <string.h>
22 #include <stdlib.h>
23 #include <gl/printf-parse.h>
24 #include <stdarg.h>
25 #include <gtk/gtk.h>
26
27 #include <gl/gettext.h>
28
29 #include "xalloc.h"
30
31
32 /* Returns a string generated from FMT and a list of GtkEntry widgets.
33    Each conversion in FMT will be replaced with the text from the
34    corresponding GtkEntry.  The normal printf semantics will be ignored.
35    Note that the GtkEntry widgets may be GtkSpinbuttons or any other widget
36    derived from GtkEntry.
37    The returned string should be freed when no longer required.
38  */
39 gchar *
40 widget_printf (const gchar *fmt, ...)
41 {
42   gint i;
43   char_directives d;
44   arguments a;
45   GString *output;
46   GtkWidget **widgets;
47   gchar *text;
48   va_list ap;
49   const char *s = fmt;
50
51   if (0 !=  printf_parse (fmt, &d, &a))
52     return NULL;
53
54   widgets = xcalloc (d.count, sizeof (*widgets));
55   va_start (ap, fmt);
56   for (i = 0 ; i < d.count ; ++i)
57     {
58       if (d.dir[i].conversion != '%')
59         widgets[i] = va_arg (ap, GtkWidget *);
60     }
61   va_end (ap);
62
63   if (a.arg != a.direct_alloc_arg)
64     free (a.arg);
65
66   output = g_string_sized_new (strlen (fmt));
67
68   for (i = 0 ; i < d.count ; ++i)
69     {
70       char_directive dir = d.dir[i];
71       GtkWidget *w ;
72       const gchar *entry_text;
73
74       if (dir.conversion == '%')
75         {
76           s++;
77           continue;
78         }
79
80       w = widgets [dir.arg_index];
81       entry_text = gtk_entry_get_text (GTK_ENTRY (w));
82
83       if (dir.dir_start > s)
84         g_string_append_len (output, s, dir.dir_start - s);
85
86       s = dir.dir_end;
87
88       g_string_append (output, entry_text);
89     }
90
91   free (widgets);
92   if (d.dir != d.direct_alloc_dir)
93     free (d.dir);
94
95   if (*s)
96     g_string_append_len (output, s, -1);
97
98   text = output->str;
99   g_string_free (output, FALSE);
100   return text;
101 }