rewrite template engine completely
[monky] / src / conky.c
1 /* Conky, a system monitor, based on torsmo
2  *
3  * Any original torsmo code is licensed under the BSD license
4  *
5  * All code written since the fork of torsmo is licensed under the GPL
6  *
7  * Please see COPYING for details
8  *
9  * Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
10  * Copyright (c) 2005-2008 Brenden Matthews, Philip Kovacs, et. al.
11  *      (see AUTHORS)
12  * All rights reserved.
13  *
14  * This program is free software: you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation, either version 3 of the License, or
17  * (at your option) any later version.
18  *
19  * This program is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  * You should have received a copy of the GNU General Public License
24  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
25  *
26  */
27
28 #include "conky.h"
29 #include <stdarg.h>
30 #include <math.h>
31 #include <ctype.h>
32 #include <time.h>
33 #include <locale.h>
34 #include <signal.h>
35 #include <unistd.h>
36 #include <errno.h>
37 #include <termios.h>
38 #include <limits.h>
39 #if HAVE_DIRENT_H
40 #include <dirent.h>
41 #endif
42 #include <sys/time.h>
43 #ifdef X11
44 #include <X11/Xutil.h>
45 #ifdef HAVE_XDAMAGE
46 #include <X11/extensions/Xdamage.h>
47 #endif
48 #ifdef IMLIB2
49 #include <Imlib2.h>
50 #endif /* IMLIB2 */
51 #endif /* X11 */
52 #include <sys/types.h>
53 #include <sys/stat.h>
54 #include <netinet/in.h>
55 #include <netdb.h>
56 #include <fcntl.h>
57 #include <getopt.h>
58
59 #ifdef HAVE_ICONV
60 #include <iconv.h>
61 #endif
62
63 #include "build.h"
64
65 #include "temphelper.h"
66
67 #ifndef S_ISSOCK
68 #define S_ISSOCK(x)   ((x & S_IFMT) == S_IFSOCK)
69 #endif
70
71 #define MAIL_FILE "$MAIL"
72 #define MAX_IF_BLOCK_DEPTH 5
73 #define MAX_TAIL_LINES 100
74
75 //#define SIGNAL_BLOCKING
76 #undef SIGNAL_BLOCKING
77
78 /* debugging level */
79 int global_debug_level = 0;
80
81 static void print_version(void) __attribute__((noreturn));
82
83 static void print_version(void)
84 {
85         printf(PACKAGE_NAME" "VERSION" compiled "BUILD_DATE" for "BUILD_ARCH"\n");
86
87         printf("\nCompiled in features:\n\n"
88                    "System config file: "SYSTEM_CONFIG_FILE"\n\n"
89 #ifdef X11
90                    " X11:\n"
91 # ifdef HAVE_XDAMAGE
92                    "  * Xdamage extension\n"
93 # endif /* HAVE_XDAMAGE */
94 # ifdef HAVE_XDBE
95                    "  * Xdbe extension (double buffer)\n"
96 # endif /* HAVE_XDBE */
97 # ifdef XFT
98                    "  * xft\n"
99 # endif /* XFT */
100 #endif /* X11 */
101                    "\n Music detection:\n"
102 #ifdef AUDACIOUS
103                    "  * audacious\n"
104 #endif /* AUDACIOUS */
105 #ifdef BMPX
106                    "  * bmpx\n"
107 #endif /* BMPX */
108 #ifdef MPD
109                    "  * mpd\n"
110 #endif /* MPD */
111 #ifdef MOC
112        "  * moc\n"
113 #endif /* MOC */
114 #ifdef XMMS2
115                    "  * xmms2\n"
116 #endif /* XMMS2 */
117                    "\n General features:\n"
118 #ifdef MATH
119                    "  * math\n"
120 #endif /* Math */
121 #ifdef HDDTEMP
122                    "  * hddtemp\n"
123 #endif /* HDDTEMP */
124 #ifdef TCP_PORT_MONITOR
125                    "  * portmon\n"
126 #endif /* TCP_PORT_MONITOR */
127 #ifdef RSS
128                    "  * rss\n"
129 #endif /* RSS */
130 #ifdef EVE
131                    "  * eve\n"
132 #endif /* EVE */
133 #ifdef HAVE_IWLIB
134                    "  * wireless\n"
135 #endif /* HAVE_IWLIB */
136 #ifdef SMAPI
137         "  * smapi\n"
138 #endif /* SMAPI */
139 #ifdef NVIDIA
140         "  * nvidia\n"
141 #endif
142         );
143
144         exit(0);
145 }
146
147 static const char *suffixes[] = { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "" };
148
149
150 #ifdef X11
151
152 /* text size */
153
154 static int text_start_x, text_start_y;  /* text start position in window */
155 static int text_width, text_height;
156
157 /* alignments */
158 enum alignment {
159         TOP_LEFT = 1,
160         TOP_RIGHT,
161         TOP_MIDDLE,
162         BOTTOM_LEFT,
163         BOTTOM_RIGHT,
164         BOTTOM_MIDDLE,
165         MIDDLE_LEFT,
166         MIDDLE_RIGHT,
167         NONE
168 };
169
170 /* for fonts */
171 struct font_list {
172
173         char name[DEFAULT_TEXT_BUFFER_SIZE];
174         int num;
175         XFontStruct *font;
176
177 #ifdef XFT
178         XftFont *xftfont;
179         int font_alpha;
180 #endif
181 };
182
183 static int selected_font = 0;
184 static int font_count = -1;
185 struct font_list *fonts = NULL;
186
187 #ifdef XFT
188
189 #define font_height() (use_xft ? (fonts[selected_font].xftfont->ascent + \
190         fonts[selected_font].xftfont->descent) \
191         : (fonts[selected_font].font->max_bounds.ascent + \
192         fonts[selected_font].font->max_bounds.descent))
193 #define font_ascent() (use_xft ? fonts[selected_font].xftfont->ascent \
194         : fonts[selected_font].font->max_bounds.ascent)
195 #define font_descent() (use_xft ? fonts[selected_font].xftfont->descent \
196         : fonts[selected_font].font->max_bounds.descent)
197
198 #else
199
200 #define font_height() (fonts[selected_font].font->max_bounds.ascent + \
201         fonts[selected_font].font->max_bounds.descent)
202 #define font_ascent() fonts[selected_font].font->max_bounds.ascent
203 #define font_descent() fonts[selected_font].font->max_bounds.descent
204
205 #endif
206
207 #define MAX_FONTS 64 // hmm, no particular reason, just makes sense.
208
209 static void set_font(void);
210
211 int addfont(const char *data_in)
212 {
213         if (font_count > MAX_FONTS) {
214                 CRIT_ERR("you don't need that many fonts, sorry.");
215         }
216         font_count++;
217         if (font_count == 0) {
218                 if (fonts != NULL) {
219                         free(fonts);
220                 }
221                 if ((fonts = (struct font_list *) malloc(sizeof(struct font_list)))
222                                 == NULL) {
223                         CRIT_ERR("malloc");
224                 }
225                 memset(fonts, 0, sizeof(struct font_list));
226         }
227         fonts = realloc(fonts, (sizeof(struct font_list) * (font_count + 1)));
228         memset(&fonts[font_count], 0, sizeof(struct font_list));
229         if (fonts == NULL) {
230                 CRIT_ERR("realloc in addfont");
231         }
232         // must account for null terminator
233         if (strlen(data_in) < DEFAULT_TEXT_BUFFER_SIZE) {
234                 strncpy(fonts[font_count].name, data_in, DEFAULT_TEXT_BUFFER_SIZE);
235 #ifdef XFT
236                 fonts[font_count].font_alpha = 0xffff;
237 #endif
238         } else {
239                 CRIT_ERR("Oops...looks like something overflowed in addfont().");
240         }
241         return font_count;
242 }
243
244 void set_first_font(const char *data_in)
245 {
246         if (font_count < 0) {
247                 if ((fonts = (struct font_list *) malloc(sizeof(struct font_list)))
248                                 == NULL) {
249                         CRIT_ERR("malloc");
250                 }
251                 memset(fonts, 0, sizeof(struct font_list));
252                 font_count++;
253         }
254         if (strlen(data_in) > 1) {
255                 strncpy(fonts[0].name, data_in, DEFAULT_TEXT_BUFFER_SIZE);
256 #ifdef XFT
257                 fonts[0].font_alpha = 0xffff;
258 #endif
259         }
260 }
261
262 void free_fonts(void)
263 {
264         int i;
265
266         for (i = 0; i <= font_count; i++) {
267 #ifdef XFT
268                 if (use_xft) {
269                         XftFontClose(display, fonts[i].xftfont);
270                         fonts[i].xftfont = 0;
271                 } else
272 #endif
273                 {
274                         XFreeFont(display, fonts[i].font);
275                         fonts[i].font = 0;
276                 }
277         }
278         free(fonts);
279         fonts = 0;
280         font_count = -1;
281         selected_font = 0;
282 }
283
284 static void load_fonts(void)
285 {
286         int i;
287
288         for (i = 0; i <= font_count; i++) {
289 #ifdef XFT
290                 /* load Xft font */
291                 if (use_xft && fonts[i].xftfont) {
292                         continue;
293                 } else if (use_xft) {
294                         /* if (fonts[i].xftfont != NULL && selected_font == 0) {
295                                 XftFontClose(display, fonts[i].xftfont);
296                         } */
297                         fonts[i].xftfont = XftFontOpenName(display, screen,
298                                         fonts[i].name);
299                         if (fonts[i].xftfont != NULL) {
300                                 continue;
301                         }
302
303                         ERR("can't load Xft font '%s'", fonts[i].name);
304                         if ((fonts[i].xftfont = XftFontOpenName(display, screen,
305                                         "courier-12")) != NULL) {
306                                 continue;
307                         }
308
309                         ERR("can't load Xft font '%s'", "courier-12");
310
311                         if ((fonts[i].font = XLoadQueryFont(display, "fixed")) == NULL) {
312                                 CRIT_ERR("can't load font '%s'", "fixed");
313                         }
314                         use_xft = 0;
315
316                         continue;
317                 }
318 #endif
319                 /* load normal font */
320                 /* if (fonts[i].font != NULL) {
321                         XFreeFont(display, fonts[i].font);
322                 } */
323
324                 if (fonts[i].font || (fonts[i].font = XLoadQueryFont(display, fonts[i].name)) == NULL) {
325                         ERR("can't load font '%s'", fonts[i].name);
326                         if ((fonts[i].font = XLoadQueryFont(display, "fixed")) == NULL) {
327                                 CRIT_ERR("can't load font '%s'", "fixed");
328                                 printf("loaded fixed?\n");
329                         }
330                 }
331         }
332 }
333
334 #endif /* X11 */
335
336 /* default config file */
337 static char *current_config;
338
339 /* set to 1 if you want all text to be in uppercase */
340 static unsigned int stuff_in_upper_case;
341
342 /* Run how many times? */
343 static unsigned long total_run_times;
344
345 /* fork? */
346 static int fork_to_background;
347
348 static int cpu_avg_samples, net_avg_samples;
349
350 #ifdef X11
351
352 static int show_graph_scale;
353 static int show_graph_range;
354
355 /* Position on the screen */
356 static int text_alignment;
357 static int gap_x, gap_y;
358
359 /* border */
360 static int draw_borders;
361 static int draw_graph_borders;
362 static int stippled_borders;
363
364 static int draw_shades, draw_outline;
365
366 static int border_margin, border_width;
367
368 static long default_fg_color, default_bg_color, default_out_color;
369
370 /* create own window or draw stuff to root? */
371 static int set_transparent = 0;
372
373 #ifdef OWN_WINDOW
374 static int own_window = 0;
375 static int background_colour = 0;
376
377 /* fixed size/pos is set if wm/user changes them */
378 static int fixed_size = 0, fixed_pos = 0;
379 #endif
380
381 static int minimum_width, minimum_height;
382 static int maximum_width;
383
384 #endif /* X11 */
385
386 #ifdef __OpenBSD__
387 static int sensor_device;
388 #endif
389
390 static long color0, color1, color2, color3, color4, color5, color6, color7,
391         color8, color9;
392
393 static char *template[10];
394
395 /* maximum number of special things, e.g. fonts, offsets, aligns, etc. */
396 static unsigned int max_specials = MAX_SPECIALS_DEFAULT;
397
398 /* maximum size of config TEXT buffer, i.e. below TEXT line. */
399 static unsigned int max_user_text = MAX_USER_TEXT_DEFAULT;
400
401 /* maximum size of individual text buffers, ie $exec buffer size */
402 unsigned int text_buffer_size = DEFAULT_TEXT_BUFFER_SIZE;
403
404 #ifdef HAVE_ICONV
405 #define CODEPAGE_LENGTH 20
406 long iconv_selected;
407 long iconv_count = 0;
408 char iconv_converting;
409 static iconv_t **iconv_cd = 0;
410
411 int register_iconv(iconv_t *new_iconv)
412 {
413         iconv_cd = realloc(iconv_cd, sizeof(iconv_t *) * (iconv_count + 1));
414         if (!iconv_cd) {
415                 CRIT_ERR("Out of memory");
416         }
417         iconv_cd[iconv_count] = malloc(sizeof(iconv_t));
418         if (!iconv_cd[iconv_count]) {
419                 CRIT_ERR("Out of memory");
420         }
421         memcpy(iconv_cd[iconv_count], new_iconv, sizeof(iconv_t));
422         iconv_count++;
423         return iconv_count;
424 }
425
426 void free_iconv(void)
427 {
428         if (iconv_cd) {
429                 long i;
430
431                 for (i = 0; i < iconv_count; i++) {
432                         if (iconv_cd[i]) {
433                                 iconv_close(*iconv_cd[i]);
434                                 free(iconv_cd[i]);
435                         }
436                 }
437                 free(iconv_cd);
438         }
439         iconv_cd = 0;
440 }
441
442 #endif
443
444 /* UTF-8 */
445 int utf8_mode = 0;
446
447 /* no buffers in used memory? */
448 int no_buffers;
449
450 /* pad percentages to decimals? */
451 static int pad_percents = 0;
452
453 #ifdef TCP_PORT_MONITOR
454 tcp_port_monitor_args_t tcp_port_monitor_args;
455 #endif
456
457 static char *global_text = 0;
458 long global_text_lines;
459
460 static int total_updates;
461
462 /* if-blocks */
463 static int blockdepth = 0;
464 static int if_jumped = 0;
465 static int blockstart[MAX_IF_BLOCK_DEPTH];
466
467 int check_contains(char *f, char *s)
468 {
469         int ret = 0;
470         FILE *where = fopen(f, "r");
471
472         if (where) {
473                 char buf1[256], buf2[256];
474
475                 while (fgets(buf1, 256, where)) {
476                         sscanf(buf1, "%255s", buf2);
477                         if (strstr(buf2, s)) {
478                                 ret = 1;
479                                 break;
480                         }
481                 }
482                 fclose(where);
483         } else {
484                 ERR("Could not open the file");
485         }
486         return ret;
487 }
488
489 #ifdef X11
490 static inline int calc_text_width(const char *s, int l)
491 {
492 #ifdef XFT
493         if (use_xft) {
494                 XGlyphInfo gi;
495
496                 if (utf8_mode) {
497                         XftTextExtentsUtf8(display, fonts[selected_font].xftfont,
498                                 (const FcChar8 *) s, l, &gi);
499                 } else {
500                         XftTextExtents8(display, fonts[selected_font].xftfont,
501                                 (const FcChar8 *) s, l, &gi);
502                 }
503                 return gi.xOff;
504         } else
505 #endif
506         {
507                 return XTextWidth(fonts[selected_font].font, s, l);
508         }
509 }
510 #endif /* X11 */
511
512 /* formatted text to render on screen, generated in generate_text(),
513  * drawn in draw_stuff() */
514
515 static char *text_buffer;
516
517 /* special stuff in text_buffer */
518
519 #define SPECIAL_CHAR '\x01'
520
521 enum special_types {
522         HORIZONTAL_LINE,
523         STIPPLED_HR,
524         BAR,
525         FG,
526         BG,
527         OUTLINE,
528         ALIGNR,
529         ALIGNC,
530         GRAPH,
531         OFFSET,
532         VOFFSET,
533         FONT,
534         GOTO,
535         TAB,
536 };
537
538 struct special_t {
539         int type;
540         short height;
541         short width;
542         long arg;
543         double *graph;
544         double graph_scale;
545         short show_scale;
546         int graph_width;
547         int scaled;
548         unsigned long first_colour;     // for graph gradient
549         unsigned long last_colour;
550         short font_added;
551 };
552
553 /* create specials array on heap instead of stack with introduction of
554  * max_specials */
555 static struct special_t *specials = NULL;
556
557 static unsigned int special_count;
558
559 #ifdef X11
560 static unsigned int special_index;      /* used when drawing */
561 #endif /* X11 */
562
563 /* why 256? cause an array of more then 256 doubles seems excessive,
564  * and who needs that kind of precision anyway? */
565 #define MAX_GRAPH_DEPTH 256
566
567 static struct special_t *new_special(char *buf, enum special_types t)
568 {
569         if (special_count >= max_specials) {
570                 CRIT_ERR("too many special things in text");
571         }
572
573         buf[0] = SPECIAL_CHAR;
574         buf[1] = '\0';
575         specials[special_count].type = t;
576         return &specials[special_count++];
577 }
578
579 long fwd_fcharfind(FILE *fp, char val, unsigned int step)
580 {
581 #define BUFSZ 0x1000
582         long ret = -1;
583         unsigned int count = 0;
584         static char buf[BUFSZ];
585         long orig_pos = ftell(fp);
586         long buf_pos = -1;
587         long buf_size = BUFSZ;
588         char *cur_found = NULL;
589
590         while (count < step) {
591                 if (cur_found == NULL) {
592                         buf_size = fread(buf, 1, buf_size, fp);
593                         buf_pos = 0;
594                 }
595                 cur_found = memchr(buf + buf_pos, val, buf_size - buf_pos);
596                 if (cur_found != NULL) {
597                         buf_pos = cur_found - buf + 1;
598                         count++;
599                 } else {
600                         if (feof(fp)) {
601                                 break;
602                         }
603                 }
604         }
605         if (count == step) {
606                 ret = ftell(fp) - buf_size + buf_pos - 1;
607         }
608         fseek(fp, orig_pos, SEEK_SET);
609         return ret;
610 }
611
612 #ifndef HAVE_MEMRCHR
613 void *memrchr(const void *buffer, char c, size_t n)
614 {
615         const unsigned char *p = buffer;
616
617         for (p += n; n; n--) {
618                 if (*--p == c) {
619                         return (void *) p;
620                 }
621         }
622         return NULL;
623 }
624 #endif
625
626 long rev_fcharfind(FILE *fp, char val, unsigned int step)
627 {
628 #define BUFSZ 0x1000
629         long ret = -1;
630         unsigned int count = 0;
631         static char buf[BUFSZ];
632         long orig_pos = ftell(fp);
633         long buf_pos = -1;
634         long file_pos = orig_pos;
635         long buf_size = BUFSZ;
636         char *cur_found;
637
638         while (count < step) {
639                 if (buf_pos <= 0) {
640                         if (file_pos > BUFSZ) {
641                                 fseek(fp, file_pos - BUFSZ, SEEK_SET);
642                         } else {
643                                 buf_size = file_pos;
644                                 fseek(fp, 0, SEEK_SET);
645                         }
646                         file_pos = ftell(fp);
647                         buf_pos = fread(buf, 1, buf_size, fp);
648                 }
649                 cur_found = memrchr(buf, val, (size_t) buf_pos);
650                 if (cur_found != NULL) {
651                         buf_pos = cur_found - buf;
652                         count++;
653                 } else {
654                         buf_pos = -1;
655                         if (file_pos == 0) {
656                                 break;
657                         }
658                 }
659         }
660         fseek(fp, orig_pos, SEEK_SET);
661         if (count == step) {
662                 ret = file_pos + buf_pos;
663         }
664         return ret;
665 }
666
667 static void new_bar(char *buf, int w, int h, int usage)
668 {
669         struct special_t *s = new_special(buf, BAR);
670
671         s->arg = (usage > 255) ? 255 : ((usage < 0) ? 0 : usage);
672         s->width = w;
673         s->height = h;
674 }
675
676 static const char *scan_bar(const char *args, int *w, int *h)
677 {
678         /* zero width means all space that is available */
679         *w = 0;
680         *h = 6;
681         /* bar's argument is either height or height,width */
682         if (args) {
683                 int n = 0;
684
685                 if (sscanf(args, "%d,%d %n", h, w, &n) <= 1) {
686                         sscanf(args, "%d %n", h, &n);
687                 }
688                 args += n;
689         }
690
691         return args;
692 }
693
694 static char *scan_font(const char *args)
695 {
696         if (args && *args) {
697                 return strndup(args, DEFAULT_TEXT_BUFFER_SIZE);
698         }
699
700         return NULL;
701 }
702
703 #ifdef X11
704 static void new_font(char *buf, char *args)
705 {
706         if (args) {
707                 struct special_t *s = new_special(buf, FONT);
708
709                 if (s->font_added > font_count || !s->font_added || (strncmp(args, fonts[s->font_added].name, DEFAULT_TEXT_BUFFER_SIZE) != EQUAL) ) {
710                         int tmp = selected_font;
711
712                         selected_font = s->font_added = addfont(args);
713                         load_fonts();
714                         selected_font = tmp;
715                 }
716         } else {
717                 struct special_t *s = new_special(buf, FONT);
718                 int tmp = selected_font;
719
720                 selected_font = s->font_added = 0;
721                 selected_font = tmp;
722         }
723 }
724 #endif
725 void graph_append(struct special_t *graph, double f, char showaslog)
726 {
727         int i;
728
729         if (showaslog) {
730 #ifdef MATH
731                 f = log10(f + 1);
732 #endif
733         }
734         
735         if (!graph->scaled && f > graph->graph_scale) {
736                 f = graph->graph_scale;
737         }
738
739 /* Already happens in new_graph
740         if (graph->scaled) {
741                 graph->graph_scale = 1;
742         }
743 */
744         graph->graph[0] = f;    /* add new data */
745         /* shift all the data by 1 */
746         for (i = graph->graph_width - 1; i > 0; i--) {
747                 graph->graph[i] = graph->graph[i - 1];
748                 if (graph->scaled && graph->graph[i] > graph->graph_scale) {
749                         /* check if we need to update the scale */
750                         graph->graph_scale = graph->graph[i];
751                 }
752         }
753 }
754
755 short colour_depth = 0;
756 void set_up_gradient(void);
757
758 /* precalculated: 31/255, and 63/255 */
759 #define CONST_8_TO_5_BITS 0.12156862745098
760 #define CONST_8_TO_6_BITS 0.247058823529412
761
762 /* adjust color values depending on color depth */
763 static unsigned int adjust_colors(unsigned int color)
764 {
765         double r, g, b;
766
767         if (colour_depth == 0) {
768                 set_up_gradient();
769         }
770         if (colour_depth == 16) {
771                 r = (color & 0xff0000) >> 16;
772                 g = (color & 0xff00) >> 8;
773                 b =  color & 0xff;
774                 color  = (int) (r * CONST_8_TO_5_BITS) << 11;
775                 color |= (int) (g * CONST_8_TO_6_BITS) << 5;
776                 color |= (int) (b * CONST_8_TO_5_BITS);
777         }
778         return color;
779 }
780
781 static void new_graph(char *buf, int w, int h, unsigned int first_colour,
782                 unsigned int second_colour, double i, int scale, int append, char showaslog)
783 {
784         struct special_t *s = new_special(buf, GRAPH);
785
786         s->width = w;
787         if (s->graph == NULL) {
788                 if (s->width > 0 && s->width < MAX_GRAPH_DEPTH) {
789                         // subtract 2 for the box
790                         s->graph_width = s->width /* - 2 */;
791                 } else {
792                         s->graph_width = MAX_GRAPH_DEPTH - 2;
793                 }
794                 s->graph = malloc(s->graph_width * sizeof(double));
795                 memset(s->graph, 0, s->graph_width * sizeof(double));
796                 s->graph_scale = 100;
797         }
798         s->height = h;
799         s->first_colour = adjust_colors(first_colour);
800         s->last_colour = adjust_colors(second_colour);
801         if (scale != 0) {
802                 s->scaled = 0;
803                 s->graph_scale = scale;
804                 s->show_scale = 0;
805         } else {
806                 s->scaled = 1;
807                 s->graph_scale = 1;
808                 s->show_scale = 1;
809         }
810         /* if (s->width) {
811                 s->graph_width = s->width - 2;  // subtract 2 for rectangle around
812         } */
813         if (showaslog) {
814 #ifdef MATH
815                 s->graph_scale = log10(s->graph_scale + 1);
816 #endif
817         }
818         if (append) {
819                 graph_append(s, i, showaslog);
820         }
821 }
822
823 //don't use spaces in LOGGRAPH or NORMGRAPH if you change them
824 #define LOGGRAPH "log"
825 #define NORMGRAPH "normal"
826
827 static char *scan_graph(const char *args, int *w, int *h,
828                 unsigned int *first_colour, unsigned int *last_colour,
829                 unsigned int *scale, char *showaslog)
830 {
831         const char *nographtype;
832         char buf[64];
833         buf[0] = 0;
834
835         /* zero width means all space that is available */
836         *w = 0;
837         *h = 25;
838         *first_colour = 0;
839         *last_colour = 0;
840         *scale = 0;
841         if (args) {
842                 //set showaslog and place the rest of the args in nographtype
843                 if(strcasecmp(args, LOGGRAPH) == EQUAL) {
844                         *showaslog = TRUE;
845                         return NULL;
846                 }else if(strcasecmp(args, NORMGRAPH) == EQUAL) {
847                         *showaslog = FALSE;
848                         return NULL;
849                 }else if(strncasecmp(args, LOGGRAPH" ", strlen(LOGGRAPH) + 1 ) == EQUAL) {
850                         *showaslog = TRUE;
851                         nographtype = &args[strlen(LOGGRAPH) + 1];
852                 }else if(strncasecmp(args, NORMGRAPH" ", strlen(NORMGRAPH) + 1 ) == EQUAL) {
853                         *showaslog = FALSE;
854                         nographtype = &args[strlen(NORMGRAPH) + 1];
855                 }else{
856                         *showaslog = FALSE;
857                         nographtype = args;
858                 }
859                 //check the rest of the args
860                 if (sscanf(nographtype, "%d,%d %x %x %u", h, w, first_colour, last_colour, scale) == 5) {
861                         return NULL;
862                 }
863                 *scale = 0;
864                 if (sscanf(nographtype, "%d,%d %x %x", h, w, first_colour, last_colour) == 4) {
865                         return NULL;
866                 }
867                 if (sscanf(nographtype, "%63s %d,%d %x %x %u", buf, h, w, first_colour, last_colour, scale) == 6) {
868                         return strndup(buf, text_buffer_size);
869                 }
870                 *scale = 0;
871                 if (sscanf(nographtype, "%63s %d,%d %x %x", buf, h, w, first_colour, last_colour) == 5) {
872                         return strndup(buf, text_buffer_size);
873                 }
874                 buf[0] = '\0';
875                 *h = 25;
876                 *w = 0;
877                 if (sscanf(nographtype, "%x %x %u", first_colour, last_colour, scale) == 3) {
878                         return NULL;
879                 }
880                 *scale = 0;
881                 if (sscanf(nographtype, "%x %x", first_colour, last_colour) == 2) {
882                         return NULL;
883                 }
884                 if (sscanf(nographtype, "%63s %x %x %u", buf, first_colour, last_colour, scale) == 4) {
885                         return strndup(buf, text_buffer_size);
886                 }
887                 *scale = 0;
888                 if (sscanf(nographtype, "%63s %x %x", buf, first_colour, last_colour) == 3) {
889                         return strndup(buf, text_buffer_size);
890                 }
891                 buf[0] = '\0';
892                 *first_colour = 0;
893                 *last_colour = 0;
894                 if (sscanf(nographtype, "%d,%d %u", h, w, scale) == 3) {
895                         return NULL;
896                 }
897                 *scale = 0;
898                 if (sscanf(nographtype, "%d,%d", h, w) == 2) {
899                         return NULL;
900                 }
901                 if (sscanf(nographtype, "%63s %d,%d %u", buf, h, w, scale) < 4) {
902                         *scale = 0;
903                         //TODO: check the return value and throw an error?
904                         sscanf(nographtype, "%63s %d,%d", buf, h, w);
905                 }
906
907                 return strndup(buf, text_buffer_size);
908         }
909
910         if (buf[0] == '\0') {
911                 return NULL;
912         } else {
913                 return strndup(buf, text_buffer_size);
914         }
915 }
916
917 static inline void new_hr(char *buf, int a)
918 {
919         new_special(buf, HORIZONTAL_LINE)->height = a;
920 }
921
922 static inline void new_stippled_hr(char *buf, int a, int b)
923 {
924         struct special_t *s = new_special(buf, STIPPLED_HR);
925
926         s->height = b;
927         s->arg = a;
928 }
929
930 static inline void new_fg(char *buf, long c)
931 {
932         new_special(buf, FG)->arg = c;
933 }
934
935 static inline void new_bg(char *buf, long c)
936 {
937         new_special(buf, BG)->arg = c;
938 }
939
940 static inline void new_outline(char *buf, long c)
941 {
942         new_special(buf, OUTLINE)->arg = c;
943 }
944
945 static inline void new_offset(char *buf, long c)
946 {
947         new_special(buf, OFFSET)->arg = c;
948 }
949
950 static inline void new_voffset(char *buf, long c)
951 {
952         new_special(buf, VOFFSET)->arg = c;
953 }
954
955 static inline void new_alignr(char *buf, long c)
956 {
957         new_special(buf, ALIGNR)->arg = c;
958 }
959
960 // A postive offset pushes the text further left
961 static inline void new_alignc(char *buf, long c)
962 {
963         new_special(buf, ALIGNC)->arg = c;
964 }
965
966 static inline void new_goto(char *buf, long c)
967 {
968         new_special(buf, GOTO)->arg = c;
969 }
970
971 static inline void new_tab(char *buf, int a, int b)
972 {
973         struct special_t *s = new_special(buf, TAB);
974
975         s->width = a;
976         s->arg = b;
977 }
978
979 /* quite boring functions */
980
981 static inline void for_each_line(char *b, void f(char *))
982 {
983         char *ps, *pe;
984
985         for (ps = b, pe = b; *pe; pe++) {
986                 if (*pe == '\n') {
987                         *pe = '\0';
988                         f(ps);
989                         *pe = '\n';
990                         ps = pe + 1;
991                 }
992         }
993
994         if (ps < pe) {
995                 f(ps);
996         }
997 }
998
999 static void convert_escapes(char *buf)
1000 {
1001         char *p = buf, *s = buf;
1002
1003         while (*s) {
1004                 if (*s == '\\') {
1005                         s++;
1006                         if (*s == 'n') {
1007                                 *p++ = '\n';
1008                         } else if (*s == '\\') {
1009                                 *p++ = '\\';
1010                         }
1011                         s++;
1012                 } else {
1013                         *p++ = *s++;
1014                 }
1015         }
1016         *p = '\0';
1017 }
1018
1019 /* Prints anything normally printed with snprintf according to the current value
1020  * of use_spacer.  Actually slightly more flexible than snprintf, as you can
1021  * safely specify the destination buffer as one of your inputs.  */
1022 static int spaced_print(char *, int, const char *, int, const char *, ...)
1023                 __attribute__((format(printf, 3, 6)));
1024
1025 static int spaced_print(char *buf, int size, const char *format, int width,
1026                 const char *func_name, ...) {
1027         int len;
1028         va_list argp;
1029         char *tempbuf;
1030
1031         if (size < 1) {
1032                 return 0;
1033         }
1034         tempbuf = malloc(size * sizeof(char));
1035
1036         // Passes the varargs along to vsnprintf
1037         va_start(argp, func_name);
1038         vsnprintf(tempbuf, size, format, argp);
1039         va_end(argp);
1040
1041         switch (use_spacer) {
1042                 case NO_SPACER:
1043                         len = snprintf(buf, size, "%s", tempbuf);
1044                         break;
1045                 case LEFT_SPACER:
1046                         len = snprintf(buf, size, "%*s", width - 1, tempbuf);
1047                         break;
1048                 case RIGHT_SPACER:
1049                         len = snprintf(buf, size, "%-*s", width - 1, tempbuf);
1050                         break;
1051                 default:
1052                         CRIT_ERR("%s encountered invalid use_spacer value (%d)", func_name,
1053                                 use_spacer);
1054         }
1055
1056         free(tempbuf);
1057
1058         return len;
1059 }
1060
1061 /* converts from bytes to human readable format (k, M, G, T) */
1062 static void human_readable(long long num, char *buf, int size, const char *func_name)
1063 {
1064         const char **suffix = suffixes;
1065         float fnum;
1066         int precision, len;
1067         static const int WIDTH = 10, SHORT_WIDTH = 8;
1068
1069         if (num < 1024LL && num > -1024LL) {
1070                 if (short_units) {
1071                         spaced_print(buf, size, "%lld%c", SHORT_WIDTH, func_name, num,
1072                                 **suffix);
1073                 } else {
1074                         spaced_print(buf, size, "%lld%s", WIDTH, func_name, num, *suffix);
1075                 }
1076                 return;
1077         }
1078
1079         while ((num / 1024 >= 1000LL || num / 1024 <= -1024LL) && **(suffix + 2)) {
1080                 num /= 1024;
1081                 suffix++;
1082         }
1083
1084         suffix++;
1085         fnum = num / 1024.0;
1086
1087         precision = 3;
1088         do {
1089                 precision--;
1090                 if (precision < 0) {
1091                         break;
1092                 }
1093                 if (short_units) {
1094                         len = spaced_print(buf, size, "%.*f%c", SHORT_WIDTH, func_name,
1095                                 precision, fnum, **suffix);
1096                 } else {
1097                         len = spaced_print(buf, size, "%.*f%s", WIDTH, func_name, precision,
1098                                 fnum, *suffix);
1099                 }
1100         } while (len >= (short_units ? SHORT_WIDTH : WIDTH) || len >= size);
1101 }
1102
1103 /* text handling */
1104
1105 enum text_object_type {
1106         OBJ_addr,
1107 #if defined(__linux__)
1108     OBJ_addrs,
1109 #endif /* __linux__ */
1110 #ifndef __OpenBSD__
1111         OBJ_acpiacadapter,
1112         OBJ_adt746xcpu,
1113         OBJ_adt746xfan,
1114         OBJ_acpifan,
1115         OBJ_acpitemp,
1116         OBJ_battery,
1117         OBJ_battery_time,
1118         OBJ_battery_percent,
1119         OBJ_battery_bar,
1120 #endif /* !__OpenBSD__ */
1121         OBJ_buffers,
1122         OBJ_cached,
1123         OBJ_color,
1124         OBJ_color0,
1125         OBJ_color1,
1126         OBJ_color2,
1127         OBJ_color3,
1128         OBJ_color4,
1129         OBJ_color5,
1130         OBJ_color6,
1131         OBJ_color7,
1132         OBJ_color8,
1133         OBJ_color9,
1134         OBJ_conky_version,
1135         OBJ_conky_build_date,
1136         OBJ_conky_build_arch,
1137         OBJ_font,
1138         OBJ_cpu,
1139         OBJ_cpubar,
1140         OBJ_cpugraph,
1141         OBJ_loadgraph,
1142         OBJ_diskio,
1143         OBJ_diskio_read,
1144         OBJ_diskio_write,
1145         OBJ_diskiograph,
1146         OBJ_diskiograph_read,
1147         OBJ_diskiograph_write,
1148         OBJ_downspeed,
1149         OBJ_downspeedf,
1150         OBJ_downspeedgraph,
1151         OBJ_else,
1152         OBJ_endif,
1153         OBJ_image,
1154         OBJ_exec,
1155         OBJ_execi,
1156         OBJ_texeci,
1157         OBJ_execbar,
1158         OBJ_execgraph,
1159         OBJ_execibar,
1160         OBJ_execigraph,
1161         OBJ_execp,
1162         OBJ_execpi,
1163         OBJ_freq,
1164         OBJ_freq_g,
1165         OBJ_fs_bar,
1166         OBJ_fs_bar_free,
1167         OBJ_fs_free,
1168         OBJ_fs_free_perc,
1169         OBJ_fs_size,
1170         OBJ_fs_type,
1171         OBJ_fs_used,
1172         OBJ_fs_used_perc,
1173         OBJ_goto,
1174         OBJ_tab,
1175         OBJ_hr,
1176         OBJ_offset,
1177         OBJ_voffset,
1178         OBJ_alignr,
1179         OBJ_alignc,
1180         OBJ_i2c,
1181         OBJ_platform,
1182         OBJ_hwmon,
1183 #if defined(__linux__)
1184         OBJ_disk_protect,
1185         OBJ_i8k_version,
1186         OBJ_i8k_bios,
1187         OBJ_i8k_serial,
1188         OBJ_i8k_cpu_temp,
1189         OBJ_i8k_left_fan_status,
1190         OBJ_i8k_right_fan_status,
1191         OBJ_i8k_left_fan_rpm,
1192         OBJ_i8k_right_fan_rpm,
1193         OBJ_i8k_ac_status,
1194         OBJ_i8k_buttons_status,
1195         OBJ_ibm_fan,
1196         OBJ_ibm_temps,
1197         OBJ_ibm_volume,
1198         OBJ_ibm_brightness,
1199         OBJ_if_up,
1200         OBJ_if_gw,
1201         OBJ_ioscheduler,
1202         OBJ_gw_iface,
1203         OBJ_gw_ip,
1204         OBJ_laptop_mode,
1205         OBJ_pb_battery,
1206         OBJ_voltage_mv,
1207         OBJ_voltage_v,
1208         OBJ_wireless_essid,
1209         OBJ_wireless_mode,
1210         OBJ_wireless_bitrate,
1211         OBJ_wireless_ap,
1212         OBJ_wireless_link_qual,
1213         OBJ_wireless_link_qual_max,
1214         OBJ_wireless_link_qual_perc,
1215         OBJ_wireless_link_bar,
1216 #endif /* __linux__ */
1217         OBJ_if_empty,
1218         OBJ_if_existing,
1219         OBJ_if_mounted,
1220         OBJ_if_running,
1221         OBJ_top,
1222         OBJ_top_mem,
1223         OBJ_tail,
1224         OBJ_head,
1225         OBJ_lines,
1226         OBJ_words,
1227         OBJ_kernel,
1228         OBJ_loadavg,
1229         OBJ_machine,
1230         OBJ_mails,
1231         OBJ_mboxscan,
1232         OBJ_mem,
1233         OBJ_memeasyfree,
1234         OBJ_memfree,
1235         OBJ_membar,
1236         OBJ_memgraph,
1237         OBJ_memmax,
1238         OBJ_memperc,
1239         OBJ_mem_res,
1240         OBJ_mem_vsize,
1241         OBJ_mixer,
1242         OBJ_mixerl,
1243         OBJ_mixerr,
1244         OBJ_mixerbar,
1245         OBJ_mixerlbar,
1246         OBJ_mixerrbar,
1247 #ifdef X11
1248         OBJ_monitor,
1249         OBJ_monitor_number,
1250 #endif
1251         OBJ_nameserver,
1252         OBJ_new_mails,
1253         OBJ_nodename,
1254         OBJ_nvidia,
1255         OBJ_pre_exec,
1256         OBJ_processes,
1257         OBJ_running_processes,
1258         OBJ_shadecolor,
1259         OBJ_outlinecolor,
1260         OBJ_stippled_hr,
1261         OBJ_swap,
1262         OBJ_swapbar,
1263         OBJ_swapmax,
1264         OBJ_swapperc,
1265         OBJ_sysname,
1266         OBJ_temp1,      /* i2c is used instead in these */
1267         OBJ_temp2,
1268         OBJ_text,
1269         OBJ_time,
1270         OBJ_utime,
1271         OBJ_tztime,
1272         OBJ_totaldown,
1273         OBJ_totalup,
1274         OBJ_updates,
1275         OBJ_upspeed,
1276         OBJ_upspeedf,
1277         OBJ_upspeedgraph,
1278         OBJ_uptime,
1279         OBJ_uptime_short,
1280         OBJ_user_names,
1281         OBJ_user_terms,
1282         OBJ_user_times,
1283         OBJ_user_number,
1284         OBJ_imap,
1285         OBJ_imap_messages,
1286         OBJ_imap_unseen,
1287         OBJ_pop3,
1288         OBJ_pop3_unseen,
1289         OBJ_pop3_used,
1290 #if (defined(__FreeBSD__) || defined(__FreeBSD_kernel__) \
1291                 || defined(__OpenBSD__)) && (defined(i386) || defined(__i386__))
1292         OBJ_apm_adapter,
1293         OBJ_apm_battery_time,
1294         OBJ_apm_battery_life,
1295 #endif /* __FreeBSD__ __OpenBSD__ */
1296 #ifdef __OpenBSD__
1297         OBJ_obsd_sensors_temp,
1298         OBJ_obsd_sensors_fan,
1299         OBJ_obsd_sensors_volt,
1300         OBJ_obsd_vendor,
1301         OBJ_obsd_product,
1302 #endif /* __OpenBSD__ */
1303 #ifdef MPD
1304         OBJ_mpd_title,
1305         OBJ_mpd_artist,
1306         OBJ_mpd_album,
1307         OBJ_mpd_random,
1308         OBJ_mpd_repeat,
1309         OBJ_mpd_vol,
1310         OBJ_mpd_bitrate,
1311         OBJ_mpd_status,
1312         OBJ_mpd_host,
1313         OBJ_mpd_port,
1314         OBJ_mpd_password,
1315         OBJ_mpd_bar,
1316         OBJ_mpd_elapsed,
1317         OBJ_mpd_length,
1318         OBJ_mpd_track,
1319         OBJ_mpd_name,
1320         OBJ_mpd_file,
1321         OBJ_mpd_percent,
1322         OBJ_mpd_smart,
1323         OBJ_if_mpd_playing,
1324 #endif
1325 #ifdef MOC
1326   OBJ_moc_state,
1327   OBJ_moc_file,
1328   OBJ_moc_title,
1329   OBJ_moc_artist,
1330   OBJ_moc_song,
1331   OBJ_moc_album,
1332   OBJ_moc_totaltime,
1333   OBJ_moc_timeleft,
1334   OBJ_moc_curtime,
1335   OBJ_moc_bitrate,
1336   OBJ_moc_rate,
1337 #endif
1338         OBJ_music_player_interval,
1339 #ifdef XMMS2
1340         OBJ_xmms2_artist,
1341         OBJ_xmms2_album,
1342         OBJ_xmms2_title,
1343         OBJ_xmms2_genre,
1344         OBJ_xmms2_comment,
1345         OBJ_xmms2_url,
1346         OBJ_xmms2_date,
1347         OBJ_xmms2_tracknr,
1348         OBJ_xmms2_bitrate,
1349         OBJ_xmms2_id,
1350         OBJ_xmms2_duration,
1351         OBJ_xmms2_elapsed,
1352         OBJ_xmms2_size,
1353         OBJ_xmms2_percent,
1354         OBJ_xmms2_status,
1355         OBJ_xmms2_bar,
1356         OBJ_xmms2_smart,
1357         OBJ_xmms2_playlist,
1358         OBJ_xmms2_timesplayed,
1359         OBJ_if_xmms2_connected,
1360 #endif
1361 #ifdef AUDACIOUS
1362         OBJ_audacious_status,
1363         OBJ_audacious_title,
1364         OBJ_audacious_length,
1365         OBJ_audacious_length_seconds,
1366         OBJ_audacious_position,
1367         OBJ_audacious_position_seconds,
1368         OBJ_audacious_bitrate,
1369         OBJ_audacious_frequency,
1370         OBJ_audacious_channels,
1371         OBJ_audacious_filename,
1372         OBJ_audacious_playlist_length,
1373         OBJ_audacious_playlist_position,
1374         OBJ_audacious_main_volume,
1375         OBJ_audacious_bar,
1376 #endif
1377 #ifdef BMPX
1378         OBJ_bmpx_title,
1379         OBJ_bmpx_artist,
1380         OBJ_bmpx_album,
1381         OBJ_bmpx_track,
1382         OBJ_bmpx_uri,
1383         OBJ_bmpx_bitrate,
1384 #endif
1385 #ifdef EVE
1386         OBJ_eve,
1387 #endif
1388 #ifdef RSS
1389         OBJ_rss,
1390 #endif
1391 #ifdef TCP_PORT_MONITOR
1392         OBJ_tcp_portmon,
1393 #endif
1394 #ifdef HAVE_ICONV
1395         OBJ_iconv_start,
1396         OBJ_iconv_stop,
1397 #endif
1398 #ifdef HDDTEMP
1399         OBJ_hddtemp,
1400 #endif
1401 #ifdef SMAPI
1402         OBJ_smapi,
1403         OBJ_smapi_bat_bar,
1404         OBJ_smapi_bat_perc,
1405         OBJ_smapi_bat_temp,
1406         OBJ_smapi_bat_power,
1407         OBJ_if_smapi_bat_installed,
1408 #endif
1409         OBJ_scroll,
1410         OBJ_entropy_avail,
1411         OBJ_entropy_poolsize,
1412         OBJ_entropy_bar
1413 };
1414
1415 struct text_object {
1416         union {
1417                 char *s;                /* some string */
1418                 int i;                  /* some integer */
1419                 long l;                 /* some other integer */
1420                 unsigned int sensor;
1421                 struct net_stat *net;
1422                 struct fs_stat *fs;
1423                 struct diskio_stat *diskio;
1424                 unsigned char loadavg[3];
1425                 unsigned int cpu_index;
1426                 struct mail_s *mail;
1427
1428                 struct {
1429                         char *args;
1430                         char *output;
1431                 } mboxscan;
1432
1433                 struct {
1434                         char *tz;       /* timezone variable */
1435                         char *fmt;      /* time display formatting */
1436                 } tztime;
1437
1438                 struct {
1439                         struct fs_stat *fs;
1440                         int w, h;
1441                 } fsbar;                /* 3 */
1442
1443                 struct {
1444                         int l;
1445                         int w, h;
1446                 } mixerbar;             /* 3 */
1447
1448                 struct {
1449                         int fd;
1450                         int arg;
1451                         char devtype[256];
1452                         char type[64];
1453                 } sysfs;                /* 2 */
1454
1455                 struct {
1456                         int pos;
1457                         char *s;
1458                         char *str;
1459                 } ifblock;
1460
1461                 struct {
1462                         int num;
1463                         int type;
1464                 } top;
1465
1466                 struct {
1467                         int wantedlines;
1468                         int readlines;
1469                         char *logfile;
1470                         double last_update;
1471                         float interval;
1472                         char *buffer;
1473                         /* If not -1, a file descriptor to read from when
1474                          * logfile is a FIFO. */
1475                         int fd;
1476                 } tail;
1477
1478                 struct {
1479                         double last_update;
1480                         float interval;
1481                         char *cmd;
1482                         char *buffer;
1483                         double data;
1484                 } execi;                /* 5 */
1485
1486                 struct {
1487                         float interval;
1488                         char *cmd;
1489                         char *buffer;
1490                         double data;
1491                         timed_thread *p_timed_thread;
1492                 } texeci;
1493
1494                 struct {
1495                         int a, b;
1496                 } pair;                 /* 2 */
1497 #ifdef TCP_PORT_MONITOR
1498                 struct {
1499                         /* starting port to monitor */
1500                         in_port_t port_range_begin;
1501                         /* ending port to monitor */
1502                         in_port_t port_range_end;
1503                         /* enum from libtcp-portmon.h, e.g. COUNT, etc. */
1504                         int item;
1505                         /* 0 to n-1 connections. */
1506                         int connection_index;
1507                 } tcp_port_monitor;
1508 #endif
1509 #ifdef HDDTEMP
1510                 struct {
1511                         char *addr;
1512                         int port;
1513                         char *dev;
1514                         double update_time;
1515                         char *temp;
1516                 } hddtemp;              /* 2 */
1517 #endif
1518 #ifdef EVE
1519                 struct {
1520                         char *apikey;
1521                         char *charid;
1522                         char *userid;
1523                 } eve;
1524 #endif
1525 #ifdef RSS
1526                 struct {
1527                         char *uri;
1528                         char *action;
1529                         int act_par;
1530                         int delay;
1531                 } rss;
1532 #endif
1533                 struct {
1534                         char *text;
1535                         unsigned int show;
1536                         unsigned int step;
1537                         unsigned int start;
1538                 } scroll;
1539                 
1540                 struct local_mail_s local_mail;
1541 #ifdef NVIDIA
1542                 struct nvidia_s nvidia;
1543 #endif /* NVIDIA */
1544
1545         } data;
1546         int type;
1547         int a, b;
1548         long line;
1549         unsigned int c, d, e;
1550         float f;
1551         char showaslog;
1552         char global_mode;
1553 };
1554
1555 struct text_object_list {
1556         unsigned int text_object_count;
1557         struct text_object *text_objects;
1558 };
1559
1560 static struct text_object_list *global_text_object_list;
1561
1562 static void generate_text_internal(char *p, int p_max_size,
1563         struct text_object_list *text_object_list,
1564         struct information *cur);
1565
1566 #define MAXDATASIZE 1000
1567 #define POP3 1
1568 #define IMAP 2
1569
1570 struct mail_s *parse_mail_args(char type, const char *arg)
1571 {
1572         struct mail_s *mail;
1573         char *tmp;
1574
1575         mail = malloc(sizeof(struct mail_s));
1576         memset(mail, 0, sizeof(struct mail_s));
1577
1578         if (sscanf(arg, "%128s %128s %128s", mail->host, mail->user, mail->pass)
1579                         != 3) {
1580                 if (type == POP3) {
1581                         ERR("Scanning IMAP args failed");
1582                 } else if (type == IMAP) {
1583                         ERR("Scanning POP3 args failed");
1584                 }
1585         }
1586         // see if password needs prompting
1587         if (mail->pass[0] == '*' && mail->pass[1] == '\0') {
1588                 int fp = fileno(stdin);
1589                 struct termios term;
1590
1591                 tcgetattr(fp, &term);
1592                 term.c_lflag &= ~ECHO;
1593                 tcsetattr(fp, TCSANOW, &term);
1594                 printf("Enter mailbox password (%s@%s): ", mail->user, mail->host);
1595                 scanf("%128s", mail->pass);
1596                 printf("\n");
1597                 term.c_lflag |= ECHO;
1598                 tcsetattr(fp, TCSANOW, &term);
1599         }
1600         // now we check for optional args
1601         tmp = strstr(arg, "-r ");
1602         if (tmp) {
1603                 tmp += 3;
1604                 sscanf(tmp, "%u", &mail->retries);
1605         } else {
1606                 mail->retries = 5;      // 5 retries after failure
1607         }
1608         tmp = strstr(arg, "-i ");
1609         if (tmp) {
1610                 tmp += 3;
1611                 sscanf(tmp, "%f", &mail->interval);
1612         } else {
1613                 mail->interval = 300;   // 5 minutes
1614         }
1615         tmp = strstr(arg, "-p ");
1616         if (tmp) {
1617                 tmp += 3;
1618                 sscanf(tmp, "%lu", &mail->port);
1619         } else {
1620                 if (type == POP3) {
1621                         mail->port = 110;       // default pop3 port
1622                 } else if (type == IMAP) {
1623                         mail->port = 143;       // default imap port
1624                 }
1625         }
1626         if (type == IMAP) {
1627                 tmp = strstr(arg, "-f ");
1628                 if (tmp) {
1629                         tmp += 3;
1630                         sscanf(tmp, "%s", mail->folder);
1631                 } else {
1632                         strncpy(mail->folder, "INBOX", 128);    // default imap inbox
1633                 }
1634         }
1635         tmp = strstr(arg, "-e ");
1636         if (tmp) {
1637                 int len = 1024;
1638                 tmp += 3;
1639
1640                 if (tmp[0] == '\'') {
1641                         len = strstr(tmp + 1, "'") - tmp - 1;
1642                         if (len > 1024) {
1643                                 len = 1024;
1644                         }
1645                 }
1646                 strncpy(mail->command, tmp + 1, len);
1647         } else {
1648                 mail->command[0] = '\0';
1649         }
1650         mail->p_timed_thread = NULL;
1651         return mail;
1652 }
1653
1654 int imap_command(int sockfd, const char *command, char *response, const char *verify)
1655 {
1656         struct timeval timeout;
1657         fd_set fdset;
1658         int res, numbytes = 0;
1659         if (send(sockfd, command, strlen(command), 0) == -1) {
1660                 perror("send");
1661                 return -1;
1662         }
1663         timeout.tv_sec = 60;    // 60 second timeout i guess
1664         timeout.tv_usec = 0;
1665         FD_ZERO(&fdset);
1666         FD_SET(sockfd, &fdset);
1667         res = select(sockfd + 1, &fdset, NULL, NULL, &timeout);
1668         if (res > 0) {
1669                 if ((numbytes = recv(sockfd, response, MAXDATASIZE - 1, 0)) == -1) {
1670                         perror("recv");
1671                         return -1;
1672                 }
1673         }
1674         DBGP2("imap_command() received: %s", response);
1675         response[numbytes] = '\0';
1676         if (strstr(response, verify) == NULL) {
1677                 return -1;
1678         }
1679         return 0;
1680 }
1681
1682 int imap_check_status(char *recvbuf, struct mail_s *mail)
1683 {
1684         char *reply;
1685         reply = strstr(recvbuf, " (MESSAGES ");
1686         if (!reply || strlen(reply) < 2) {
1687                 return -1;
1688         }
1689         reply += 2;
1690         *strchr(reply, ')') = '\0';
1691         if (reply == NULL) {
1692                 ERR("Error parsing IMAP response: %s", recvbuf);
1693                 return -1;
1694         } else {
1695                 timed_thread_lock(mail->p_timed_thread);
1696                 sscanf(reply, "MESSAGES %lu UNSEEN %lu", &mail->messages,
1697                                 &mail->unseen);
1698                 timed_thread_unlock(mail->p_timed_thread);
1699         }
1700         return 0;
1701 }
1702
1703 void imap_unseen_command(struct mail_s *mail, unsigned long old_unseen, unsigned long old_messages)
1704 {
1705         if (strlen(mail->command) > 1 && (mail->unseen > old_unseen
1706                                 || (mail->messages > old_messages && mail->unseen > 0))) {
1707                 // new mail goodie
1708                 if (system(mail->command) == -1) {
1709                         perror("system()");
1710                 }
1711         }
1712 }
1713
1714 void *imap_thread(void *arg)
1715 {
1716         int sockfd, numbytes;
1717         char recvbuf[MAXDATASIZE];
1718         char sendbuf[MAXDATASIZE];
1719         unsigned int fail = 0;
1720         unsigned long old_unseen = ULONG_MAX;
1721         unsigned long old_messages = ULONG_MAX;
1722         struct stat stat_buf;
1723         struct hostent he, *he_res = 0;
1724         int he_errno;
1725         char hostbuff[2048];
1726         struct sockaddr_in their_addr;  // connector's address information
1727         struct mail_s *mail = (struct mail_s *)arg;
1728         int has_idle = 0;
1729         int threadfd = timed_thread_readfd(mail->p_timed_thread);
1730
1731 #ifdef HAVE_GETHOSTBYNAME_R
1732         if (gethostbyname_r(mail->host, &he, hostbuff, sizeof(hostbuff), &he_res, &he_errno)) { // get the host info
1733                 ERR("IMAP gethostbyname_r: %s", hstrerror(h_errno));
1734                 exit(1);
1735         }
1736 #else /* HAVE_GETHOSTBYNAME_R */
1737         if ((he_res = gethostbyname(mail->host)) == NULL) {     // get the host info
1738                 herror("gethostbyname");
1739                 exit(1);
1740         }
1741 #endif /* HAVE_GETHOSTBYNAME_R */
1742         while (fail < mail->retries) {
1743                 struct timeval timeout;
1744                 int res;
1745                 fd_set fdset;
1746
1747                 if (fail > 0) {
1748                         ERR("Trying IMAP connection again for %s@%s (try %u/%u)",
1749                                         mail->user, mail->host, fail + 1, mail->retries);
1750                 }
1751                 do {
1752                         if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
1753                                 perror("socket");
1754                                 fail++;
1755                                 break;
1756                         }
1757
1758                         // host byte order
1759                         their_addr.sin_family = AF_INET;
1760                         // short, network byte order
1761                         their_addr.sin_port = htons(mail->port);
1762                         their_addr.sin_addr = *((struct in_addr *) he_res->h_addr);
1763                         // zero the rest of the struct
1764                         memset(&(their_addr.sin_zero), '\0', 8);
1765
1766                         if (connect(sockfd, (struct sockaddr *) &their_addr,
1767                                                 sizeof(struct sockaddr)) == -1) {
1768                                 perror("connect");
1769                                 fail++;
1770                                 break;
1771                         }
1772
1773                         timeout.tv_sec = 60;    // 60 second timeout i guess
1774                         timeout.tv_usec = 0;
1775                         FD_ZERO(&fdset);
1776                         FD_SET(sockfd, &fdset);
1777                         res = select(sockfd + 1, &fdset, NULL, NULL, &timeout);
1778                         if (res > 0) {
1779                                 if ((numbytes = recv(sockfd, recvbuf, MAXDATASIZE - 1, 0)) == -1) {
1780                                         perror("recv");
1781                                         fail++;
1782                                         break;
1783                                 }
1784                         } else {
1785                                 ERR("IMAP connection failed: timeout");
1786                                 fail++;
1787                                 break;
1788                         }
1789                         recvbuf[numbytes] = '\0';
1790                         DBGP2("imap_thread() received: %s", recvbuf);
1791                         if (strstr(recvbuf, "* OK") != recvbuf) {
1792                                 ERR("IMAP connection failed, probably not an IMAP server");
1793                                 fail++;
1794                                 break;
1795                         }
1796                         strncpy(sendbuf, "a1 login ", MAXDATASIZE);
1797                         strncat(sendbuf, mail->user, MAXDATASIZE - strlen(sendbuf) - 1);
1798                         strncat(sendbuf, " ", MAXDATASIZE - strlen(sendbuf) - 1);
1799                         strncat(sendbuf, mail->pass, MAXDATASIZE - strlen(sendbuf) - 1);
1800                         strncat(sendbuf, "\r\n", MAXDATASIZE - strlen(sendbuf) - 1);
1801                         if (imap_command(sockfd, sendbuf, recvbuf, "a1 OK")) {
1802                                 fail++;
1803                                 break;
1804                         }
1805                         if (strstr(recvbuf, " IDLE ") != NULL) {
1806                                 has_idle = 1;
1807                         }
1808
1809                         strncpy(sendbuf, "a2 STATUS ", MAXDATASIZE);
1810                         strncat(sendbuf, mail->folder, MAXDATASIZE - strlen(sendbuf) - 1);
1811                         strncat(sendbuf, " (MESSAGES UNSEEN)\r\n",
1812                                         MAXDATASIZE - strlen(sendbuf) - 1);
1813                         if (imap_command(sockfd, sendbuf, recvbuf, "a2 OK")) {
1814                                 fail++;
1815                                 break;
1816                         }
1817
1818                         if (imap_check_status(recvbuf, mail)) {
1819                                 fail++;
1820                                 break;
1821                         }
1822                         imap_unseen_command(mail, old_unseen, old_messages);
1823                         fail = 0;
1824                         old_unseen = mail->unseen;
1825                         old_messages = mail->messages;
1826
1827                         if (has_idle) {
1828                                 strncpy(sendbuf, "a4 SELECT ", MAXDATASIZE);
1829                                 strncat(sendbuf, mail->folder, MAXDATASIZE - strlen(sendbuf) - 1);
1830                                 strncat(sendbuf, "\r\n", MAXDATASIZE - strlen(sendbuf) - 1);
1831                                 if (imap_command(sockfd, sendbuf, recvbuf, "a4 OK")) {
1832                                         fail++;
1833                                         break;
1834                                 }
1835
1836                                 strncpy(sendbuf, "a5 IDLE\r\n", MAXDATASIZE);
1837                                 if (imap_command(sockfd, sendbuf, recvbuf, "+ idling")) {
1838                                         fail++;
1839                                         break;
1840                                 }
1841                                 recvbuf[0] = '\0';
1842
1843                                 while (1) {
1844                                         /*
1845                                          * RFC 2177 says we have to re-idle every 29 minutes.
1846                                          * We'll do it every 20 minutes to be safe.
1847                                          */
1848                                         timeout.tv_sec = 1200;
1849                                         timeout.tv_usec = 0;
1850                                         FD_ZERO(&fdset);
1851                                         FD_SET(sockfd, &fdset);
1852                                         FD_SET(threadfd, &fdset);
1853                                         res = select(MAX(sockfd + 1, threadfd + 1), &fdset, NULL, NULL, NULL);
1854                                         if (timed_thread_test(mail->p_timed_thread, 1) || (res == -1 && errno == EINTR) || FD_ISSET(threadfd, &fdset)) {
1855                                                 if ((fstat(sockfd, &stat_buf) == 0) && S_ISSOCK(stat_buf.st_mode)) {
1856                                                         /* if a valid socket, close it */
1857                                                         close(sockfd);
1858                                                 }
1859                                                 timed_thread_exit(mail->p_timed_thread);
1860                                         } else if (res > 0) {
1861                                                 if ((numbytes = recv(sockfd, recvbuf, MAXDATASIZE - 1, 0)) == -1) {
1862                                                         perror("recv idling");
1863                                                         fail++;
1864                                                         break;
1865                                                 }
1866                                         } else {
1867                                                 break;
1868                                         }
1869                                         recvbuf[numbytes] = '\0';
1870                                         DBGP2("imap_thread() received: %s", recvbuf);
1871                                         if (strlen(recvbuf) > 2) {
1872                                                 unsigned long messages, recent;
1873                                                 char *buf = recvbuf;
1874                                                 buf = strstr(buf, "EXISTS");
1875                                                 while (buf && strlen(buf) > 1 && strstr(buf + 1, "EXISTS")) {
1876                                                         buf = strstr(buf + 1, "EXISTS");
1877                                                 }
1878                                                 if (buf) {
1879                                                         // back up until we reach '*'
1880                                                         while (buf >= recvbuf && buf[0] != '*') {
1881                                                                 buf--;
1882                                                         }
1883                                                         if (sscanf(buf, "* %lu EXISTS\r\n", &messages) == 1) {
1884                                                                 timed_thread_lock(mail->p_timed_thread);
1885                                                                 mail->messages = messages;
1886                                                                 timed_thread_unlock(mail->p_timed_thread);
1887                                                         }
1888                                                 }
1889                                                 buf = recvbuf;
1890                                                 buf = strstr(buf, "RECENT");
1891                                                 while (buf && strlen(buf) > 1 && strstr(buf + 1, "RECENT")) {
1892                                                         buf = strstr(buf + 1, "RECENT");
1893                                                 }
1894                                                 if (buf) {
1895                                                         // back up until we reach '*'
1896                                                         while (buf >= recvbuf && buf[0] != '*') {
1897                                                                 buf--;
1898                                                         }
1899                                                         if (sscanf(buf, "* %lu RECENT\r\n", &recent) != 1) {
1900                                                                 recent = 0;
1901                                                         }
1902                                                 }
1903                                                 /*
1904                                                  * check if we got a FETCH from server, recent was
1905                                                  * something other than 0, or we had a timeout
1906                                                  */
1907                                                 buf = recvbuf;
1908                                                 if (recent > 0 || (buf && strstr(buf, " FETCH ")) || timeout.tv_sec == 0) {
1909                                                         // re-check messages and unseen
1910                                                         if (imap_command(sockfd, "DONE\r\n", recvbuf, "a5 OK")) {
1911                                                                 fail++;
1912                                                                 break;
1913                                                         }
1914                                                         strncpy(sendbuf, "a2 STATUS ", MAXDATASIZE);
1915                                                         strncat(sendbuf, mail->folder, MAXDATASIZE - strlen(sendbuf) - 1);
1916                                                         strncat(sendbuf, " (MESSAGES UNSEEN)\r\n",
1917                                                                         MAXDATASIZE - strlen(sendbuf) - 1);
1918                                                         if (imap_command(sockfd, sendbuf, recvbuf, "a2 OK")) {
1919                                                                 fail++;
1920                                                                 break;
1921                                                         }
1922                                                         if (imap_check_status(recvbuf, mail)) {
1923                                                                 fail++;
1924                                                                 break;
1925                                                         }
1926                                                         strncpy(sendbuf, "a5 IDLE\r\n", MAXDATASIZE);
1927                                                         if (imap_command(sockfd, sendbuf, recvbuf, "+ idling")) {
1928                                                                 fail++;
1929                                                                 break;
1930                                                         }
1931                                                 }
1932                                                 /*
1933                                                  * check if we got a BYE from server
1934                                                  */
1935                                                 buf = recvbuf;
1936                                                 if (buf && strstr(buf, "* BYE")) {
1937                                                         // need to re-connect
1938                                                         break;
1939                                                 }
1940                                         }
1941                                         imap_unseen_command(mail, old_unseen, old_messages);
1942                                         fail = 0;
1943                                         old_unseen = mail->unseen;
1944                                         old_messages = mail->messages;
1945                                 }
1946                         } else {
1947                                 strncpy(sendbuf, "a3 logout\r\n", MAXDATASIZE);
1948                                 if (send(sockfd, sendbuf, strlen(sendbuf), 0) == -1) {
1949                                         perror("send a3");
1950                                         fail++;
1951                                         break;
1952                                 }
1953                                 timeout.tv_sec = 60;    // 60 second timeout i guess
1954                                 timeout.tv_usec = 0;
1955                                 FD_ZERO(&fdset);
1956                                 FD_SET(sockfd, &fdset);
1957                                 res = select(sockfd + 1, &fdset, NULL, NULL, &timeout);
1958                                 if (res > 0) {
1959                                         if ((numbytes = recv(sockfd, recvbuf, MAXDATASIZE - 1, 0)) == -1) {
1960                                                 perror("recv a3");
1961                                                 fail++;
1962                                                 break;
1963                                         }
1964                                 }
1965                                 recvbuf[numbytes] = '\0';
1966                                 DBGP2("imap_thread() received: %s", recvbuf);
1967                                 if (strstr(recvbuf, "a3 OK") == NULL) {
1968                                         ERR("IMAP logout failed: %s", recvbuf);
1969                                         fail++;
1970                                         break;
1971                                 }
1972                         }
1973                 } while (0);
1974                 if ((fstat(sockfd, &stat_buf) == 0) && S_ISSOCK(stat_buf.st_mode)) {
1975                         /* if a valid socket, close it */
1976                         close(sockfd);
1977                 }
1978                 if (timed_thread_test(mail->p_timed_thread, 0)) {
1979                         timed_thread_exit(mail->p_timed_thread);
1980                 }
1981         }
1982         mail->unseen = 0;
1983         mail->messages = 0;
1984         return 0;
1985 }
1986
1987 int pop3_command(int sockfd, const char *command, char *response, const char *verify)
1988 {
1989         struct timeval timeout;
1990         fd_set fdset;
1991         int res, numbytes = 0;
1992         if (send(sockfd, command, strlen(command), 0) == -1) {
1993                 perror("send");
1994                 return -1;
1995         }
1996         timeout.tv_sec = 60;    // 60 second timeout i guess
1997         timeout.tv_usec = 0;
1998         FD_ZERO(&fdset);
1999         FD_SET(sockfd, &fdset);
2000         res = select(sockfd + 1, &fdset, NULL, NULL, &timeout);
2001         if (res > 0) {
2002                 if ((numbytes = recv(sockfd, response, MAXDATASIZE - 1, 0)) == -1) {
2003                         perror("recv");
2004                         return -1;
2005                 }
2006         }
2007         DBGP2("pop3_command() received: %s", response);
2008         response[numbytes] = '\0';
2009         if (strstr(response, verify) == NULL) {
2010                 return -1;
2011         }
2012         return 0;
2013 }
2014
2015 void *pop3_thread(void *arg)
2016 {
2017         int sockfd, numbytes;
2018         char recvbuf[MAXDATASIZE];
2019         char sendbuf[MAXDATASIZE];
2020         char *reply;
2021         unsigned int fail = 0;
2022         unsigned long old_unseen = ULONG_MAX;
2023         struct stat stat_buf;
2024         struct hostent he, *he_res = 0;
2025         int he_errno;
2026         char hostbuff[2048];
2027         struct sockaddr_in their_addr;  // connector's address information
2028         struct mail_s *mail = (struct mail_s *)arg;
2029
2030 #ifdef HAVE_GETHOSTBYNAME_R
2031         if (gethostbyname_r(mail->host, &he, hostbuff, sizeof(hostbuff), &he_res, &he_errno)) { // get the host info
2032                 ERR("POP3 gethostbyname_r: %s", hstrerror(h_errno));
2033                 exit(1);
2034         }
2035 #else /* HAVE_GETHOSTBYNAME_R */
2036         if ((he_res = gethostbyname(mail->host)) == NULL) {     // get the host info
2037                 herror("gethostbyname");
2038                 exit(1);
2039         }
2040 #endif /* HAVE_GETHOSTBYNAME_R */
2041         while (fail < mail->retries) {
2042                 struct timeval timeout;
2043                 int res;
2044                 fd_set fdset;
2045
2046                 if (fail > 0) {
2047                         ERR("Trying POP3 connection again for %s@%s (try %u/%u)",
2048                                         mail->user, mail->host, fail + 1, mail->retries);
2049                 }
2050                 do {
2051                         if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
2052                                 perror("socket");
2053                                 fail++;
2054                                 break;
2055                         }
2056
2057                         // host byte order
2058                         their_addr.sin_family = AF_INET;
2059                         // short, network byte order
2060                         their_addr.sin_port = htons(mail->port);
2061                         their_addr.sin_addr = *((struct in_addr *) he_res->h_addr);
2062                         // zero the rest of the struct
2063                         memset(&(their_addr.sin_zero), '\0', 8);
2064
2065                         if (connect(sockfd, (struct sockaddr *) &their_addr,
2066                                                 sizeof(struct sockaddr)) == -1) {
2067                                 perror("connect");
2068                                 fail++;
2069                                 break;
2070                         }
2071
2072                         timeout.tv_sec = 60;    // 60 second timeout i guess
2073                         timeout.tv_usec = 0;
2074                         FD_ZERO(&fdset);
2075                         FD_SET(sockfd, &fdset);
2076                         res = select(sockfd + 1, &fdset, NULL, NULL, &timeout);
2077                         if (res > 0) {
2078                                 if ((numbytes = recv(sockfd, recvbuf, MAXDATASIZE - 1, 0)) == -1) {
2079                                         perror("recv");
2080                                         fail++;
2081                                         break;
2082                                 }
2083                         } else {
2084                                 ERR("POP3 connection failed: timeout\n");
2085                                 fail++;
2086                                 break;
2087                         }
2088                         DBGP2("pop3_thread received: %s", recvbuf);
2089                         recvbuf[numbytes] = '\0';
2090                         if (strstr(recvbuf, "+OK ") != recvbuf) {
2091                                 ERR("POP3 connection failed, probably not a POP3 server");
2092                                 fail++;
2093                                 break;
2094                         }
2095                         strncpy(sendbuf, "USER ", MAXDATASIZE);
2096                         strncat(sendbuf, mail->user, MAXDATASIZE - strlen(sendbuf) - 1);
2097                         strncat(sendbuf, "\r\n", MAXDATASIZE - strlen(sendbuf) - 1);
2098                         if (pop3_command(sockfd, sendbuf, recvbuf, "+OK ")) {
2099                                 fail++;
2100                                 break;
2101                         }
2102
2103                         strncpy(sendbuf, "PASS ", MAXDATASIZE);
2104                         strncat(sendbuf, mail->pass, MAXDATASIZE - strlen(sendbuf) - 1);
2105                         strncat(sendbuf, "\r\n", MAXDATASIZE - strlen(sendbuf) - 1);
2106                         if (pop3_command(sockfd, sendbuf, recvbuf, "+OK ")) {
2107                                 ERR("POP3 server login failed: %s", recvbuf);
2108                                 fail++;
2109                                 break;
2110                         }
2111
2112                         strncpy(sendbuf, "STAT\r\n", MAXDATASIZE);
2113                         if (pop3_command(sockfd, sendbuf, recvbuf, "+OK ")) {
2114                                 perror("send STAT");
2115                                 fail++;
2116                                 break;
2117                         }
2118
2119                         // now we get the data
2120                         reply = recvbuf + 4;
2121                         if (reply == NULL) {
2122                                 ERR("Error parsing POP3 response: %s", recvbuf);
2123                                 fail++;
2124                                 break;
2125                         } else {
2126                                 timed_thread_lock(mail->p_timed_thread);
2127                                 sscanf(reply, "%lu %lu", &mail->unseen, &mail->used);
2128                                 timed_thread_unlock(mail->p_timed_thread);
2129                         }
2130                         
2131                         strncpy(sendbuf, "QUIT\r\n", MAXDATASIZE);
2132                         if (pop3_command(sockfd, sendbuf, recvbuf, "+OK")) {
2133                                 ERR("POP3 logout failed: %s", recvbuf);
2134                                 fail++;
2135                                 break;
2136                         }
2137                         
2138                         if (strlen(mail->command) > 1 && mail->unseen > old_unseen) {
2139                                 // new mail goodie
2140                                 if (system(mail->command) == -1) {
2141                                         perror("system()");
2142                                 }
2143                         }
2144                         fail = 0;
2145                         old_unseen = mail->unseen;
2146                 } while (0);
2147                 if ((fstat(sockfd, &stat_buf) == 0) && S_ISSOCK(stat_buf.st_mode)) {
2148                         /* if a valid socket, close it */
2149                         close(sockfd);
2150                 }
2151                 if (timed_thread_test(mail->p_timed_thread, 0)) {
2152                         timed_thread_exit(mail->p_timed_thread);
2153                 }
2154         }
2155         mail->unseen = 0;
2156         mail->used = 0;
2157         return 0;
2158 }
2159
2160 static inline void read_exec(const char *data, char *buf, const int size)
2161 {
2162         FILE *fp = popen(data, "r");
2163         int length = fread(buf, 1, size, fp);
2164
2165         pclose(fp);
2166         buf[length] = '\0';
2167         if (length > 0 && buf[length - 1] == '\n') {
2168                 buf[length - 1] = '\0';
2169         }
2170 }
2171
2172 void *threaded_exec(void *) __attribute__((noreturn));
2173
2174 void *threaded_exec(void *arg)
2175 {
2176         char *p2;
2177         struct text_object *obj = (struct text_object *)arg;
2178
2179         while (1) {
2180                 p2 = obj->data.texeci.buffer;
2181                 timed_thread_lock(obj->data.texeci.p_timed_thread);
2182                 read_exec(obj->data.texeci.cmd, obj->data.texeci.buffer,
2183                         text_buffer_size);
2184                 while (*p2) {
2185                         if (*p2 == '\001') {
2186                                 *p2 = ' ';
2187                         }
2188                         p2++;
2189                 }
2190                 timed_thread_unlock(obj->data.texeci.p_timed_thread);
2191                 if (timed_thread_test(obj->data.texeci.p_timed_thread, 0)) {
2192                         timed_thread_exit(obj->data.texeci.p_timed_thread);
2193                 }
2194         }
2195         /* never reached */
2196 }
2197
2198 static struct text_object *new_text_object_internal(void)
2199 {
2200         struct text_object *obj = malloc(sizeof(struct text_object));
2201         memset(obj, 0, sizeof(struct text_object));
2202         return obj;
2203 }
2204
2205 /*
2206  * call with full == 0 when freeing after 'internal' evaluation of objects
2207  */
2208 static void free_text_objects(struct text_object_list *text_object_list, char full)
2209 {
2210         unsigned int i;
2211         struct text_object *obj;
2212
2213         if (text_object_list == NULL) {
2214                 return;
2215         }
2216
2217         for (i = 0; i < text_object_list->text_object_count; i++) {
2218                 obj = &text_object_list->text_objects[i];
2219                 switch (obj->type) {
2220 #ifndef __OpenBSD__
2221                         case OBJ_acpitemp:
2222                                 close(obj->data.i);
2223                                 break;
2224                         case OBJ_i2c:
2225                         case OBJ_platform:
2226                         case OBJ_hwmon:
2227                                 close(obj->data.sysfs.fd);
2228                                 break;
2229 #endif /* !__OpenBSD__ */
2230                         case OBJ_time:
2231                         case OBJ_utime:
2232                                 free(obj->data.s);
2233                                 break;
2234                         case OBJ_tztime:
2235                                 free(obj->data.tztime.tz);
2236                                 free(obj->data.tztime.fmt);
2237                                 break;
2238                         case OBJ_mboxscan:
2239                                 free(obj->data.mboxscan.args);
2240                                 free(obj->data.mboxscan.output);
2241                                 break;
2242                         case OBJ_mails:
2243                         case OBJ_new_mails:
2244                                 free(obj->data.local_mail.box);
2245                                 break;
2246                         case OBJ_imap:
2247                                 free(info.mail);
2248                                 break;
2249                         case OBJ_imap_unseen:
2250                                 if (!obj->global_mode) {
2251                                         free(obj->data.mail);
2252                                 }
2253                                 break;
2254                         case OBJ_imap_messages:
2255                                 if (!obj->global_mode) {
2256                                         free(obj->data.mail);
2257                                 }
2258                                 break;
2259                         case OBJ_pop3:
2260                                 free(info.mail);
2261                                 break;
2262                         case OBJ_pop3_unseen:
2263                                 if (!obj->global_mode) {
2264                                         free(obj->data.mail);
2265                                 }
2266                                 break;
2267                         case OBJ_pop3_used:
2268                                 if (!obj->global_mode) {
2269                                         free(obj->data.mail);
2270                                 }
2271                                 break;
2272                         case OBJ_if_empty:
2273                         case OBJ_if_existing:
2274                         case OBJ_if_mounted:
2275                         case OBJ_if_running:
2276                                 free(obj->data.ifblock.s);
2277                                 free(obj->data.ifblock.str);
2278                                 break;
2279                         case OBJ_tail:
2280                                 free(obj->data.tail.logfile);
2281                                 free(obj->data.tail.buffer);
2282                                 break;
2283                         case OBJ_text:
2284                         case OBJ_font:
2285                         case OBJ_image:
2286                         case OBJ_exec:
2287                         case OBJ_execbar:
2288                         case OBJ_execgraph:
2289                         case OBJ_execp:
2290                                 free(obj->data.s);
2291                                 break;
2292 #ifdef HAVE_ICONV
2293                         case OBJ_iconv_start:
2294                                 free_iconv();
2295                                 break;
2296 #endif
2297 #ifdef __LINUX__
2298                         case OBJ_disk_protect:
2299                                 free(objs[i].data.s);
2300                                 break;
2301                         case OBJ_if_up:
2302                                 free(objs[i].data.ifblock.s);
2303                                 free(objs[i].data.ifblock.str);
2304                                 break;
2305                         case OBJ_if_gw:
2306                                 free(objs[i].data.ifblock.s);
2307                                 free(objs[i].data.ifblock.str);
2308                         case OBJ_gw_iface:
2309                         case OBJ_gw_ip:
2310                                 if (info.gw_info.iface) {
2311                                         free(info.gw_info.iface);
2312                                         info.gw_info.iface = 0;
2313                                 }
2314                                 if (info.gw_info.ip) {
2315                                         free(info.gw_info.ip);
2316                                         info.gw_info.ip = 0;
2317                                 }
2318                                 break;
2319                         case OBJ_ioscheduler:
2320                                 if(objs[i].data.s)
2321                                         free(objs[i].data.s);
2322                                 break;
2323 #endif
2324 #ifdef XMMS2
2325                         case OBJ_xmms2_artist:
2326                                 if (info.xmms2.artist) {
2327                                         free(info.xmms2.artist);
2328                                         info.xmms2.artist = 0;
2329                                 }
2330                                 break;
2331                         case OBJ_xmms2_album:
2332                                 if (info.xmms2.album) {
2333                                         free(info.xmms2.album);
2334                                         info.xmms2.album = 0;
2335                                 }
2336                                 break;
2337                         case OBJ_xmms2_title:
2338                                 if (info.xmms2.title) {
2339                                         free(info.xmms2.title);
2340                                         info.xmms2.title = 0;
2341                                 }
2342                                 break;
2343                         case OBJ_xmms2_genre:
2344                                 if (info.xmms2.genre) {
2345                                         free(info.xmms2.genre);
2346                                         info.xmms2.genre = 0;
2347                                 }
2348                                 break;
2349                         case OBJ_xmms2_comment:
2350                                 if (info.xmms2.comment) {
2351                                         free(info.xmms2.comment);
2352                                         info.xmms2.comment = 0;
2353                                 }
2354                                 break;
2355                         case OBJ_xmms2_url:
2356                                 if (info.xmms2.url) {
2357                                         free(info.xmms2.url);
2358                                         info.xmms2.url = 0;
2359                                 }
2360                                 break;
2361                         case OBJ_xmms2_date:
2362                                 if (info.xmms2.date) {
2363                                         free(info.xmms2.date);
2364                                         info.xmms2.date = 0;
2365                                 }
2366                                 break;
2367                         case OBJ_xmms2_status:
2368                                 if (info.xmms2.status) {
2369                                         free(info.xmms2.status);
2370                                         info.xmms2.status = 0;
2371                                 }
2372                                 break;
2373                         case OBJ_xmms2_playlist:
2374                                 if (info.xmms2.playlist) {
2375                                         free(info.xmms2.playlist);
2376                                         info.xmms2.playlist = 0;
2377                                 }
2378                                 break;
2379                         case OBJ_xmms2_smart:
2380                                 if (info.xmms2.artist) {
2381                                         free(info.xmms2.artist);
2382                                         info.xmms2.artist = 0;
2383                                 }
2384                                 if (info.xmms2.title) {
2385                                         free(info.xmms2.title);
2386                                         info.xmms2.title = 0;
2387                                 }
2388                                 if (info.xmms2.url) {
2389                                         free(info.xmms2.url);
2390                                         info.xmms2.url = 0;
2391                                 }
2392                                 break;
2393 #endif
2394 #ifdef BMPX
2395                         case OBJ_bmpx_title:
2396                         case OBJ_bmpx_artist:
2397                         case OBJ_bmpx_album:
2398                         case OBJ_bmpx_track:
2399                         case OBJ_bmpx_uri:
2400                         case OBJ_bmpx_bitrate:
2401                                 break;
2402 #endif
2403 #ifdef EVE
2404                         case OBJ_eve:
2405                                 break;
2406 #endif
2407 #ifdef RSS
2408                         case OBJ_rss:
2409                                 free(obj->data.rss.uri);
2410                                 free(obj->data.rss.action);
2411                                 break;
2412 #endif
2413                         case OBJ_pre_exec:
2414                                 break;
2415 #ifndef __OpenBSD__
2416                         case OBJ_battery:
2417                                 free(obj->data.s);
2418                                 break;
2419                         case OBJ_battery_time:
2420                                 free(obj->data.s);
2421                                 break;
2422 #endif /* !__OpenBSD__ */
2423                         case OBJ_execpi:
2424                         case OBJ_execi:
2425                         case OBJ_execibar:
2426                         case OBJ_execigraph:
2427                                 free(obj->data.execi.cmd);
2428                                 free(obj->data.execi.buffer);
2429                                 break;
2430                         case OBJ_texeci:
2431                                 free(obj->data.texeci.cmd);
2432                                 free(obj->data.texeci.buffer);
2433                                 break;
2434                         case OBJ_nameserver:
2435                                 free_dns_data();
2436                                 break;
2437                         case OBJ_top:
2438                         case OBJ_top_mem:
2439                                 if (info.first_process) {
2440                                         free_all_processes();
2441                                         info.first_process = NULL;
2442                                 }
2443                                 break;
2444 #ifdef HDDTEMP
2445                         case OBJ_hddtemp:
2446                                 free(obj->data.hddtemp.dev);
2447                                 free(obj->data.hddtemp.addr);
2448                                 if (obj->data.hddtemp.temp)
2449                                         free(obj->data.hddtemp.temp);
2450                                 break;
2451 #endif
2452                         case OBJ_entropy_avail:
2453                         case OBJ_entropy_poolsize:
2454                         case OBJ_entropy_bar:
2455                                 break;
2456                         case OBJ_user_names:
2457                                 if (info.users.names) {
2458                                         free(info.users.names);
2459                                         info.users.names = 0;
2460                                 }
2461                                 break;
2462                         case OBJ_user_terms:
2463                                 if (info.users.terms) {
2464                                         free(info.users.terms);
2465                                         info.users.terms = 0;
2466                                 }
2467                                 break;
2468                         case OBJ_user_times:
2469                                 if (info.users.times) {
2470                                         free(info.users.times);
2471                                         info.users.times = 0;
2472                                 }
2473                                 break;
2474 #ifdef SMAPI
2475                         case OBJ_smapi:
2476                         case OBJ_smapi_bat_perc:
2477                         case OBJ_smapi_bat_temp:
2478                         case OBJ_smapi_bat_power:
2479                                 free(obj->data.s);
2480                                 break;
2481                         case OBJ_if_smapi_bat_installed:
2482                                 free(obj->data.ifblock.s);
2483                                 free(obj->data.ifblock.str);
2484                                 break;
2485 #endif
2486 #ifdef NVIDIA
2487                         case OBJ_nvidia:
2488                                 break;
2489 #endif
2490 #ifdef MPD
2491                         case OBJ_mpd_title:
2492                         case OBJ_mpd_artist:
2493                         case OBJ_mpd_album:
2494                         case OBJ_mpd_random:
2495                         case OBJ_mpd_repeat:
2496                         case OBJ_mpd_vol:
2497                         case OBJ_mpd_bitrate:
2498                         case OBJ_mpd_status:
2499                         case OBJ_mpd_host:
2500                         case OBJ_mpd_port:
2501                         case OBJ_mpd_password:
2502                         case OBJ_mpd_bar:
2503                         case OBJ_mpd_elapsed:
2504                         case OBJ_mpd_length:
2505                         case OBJ_mpd_track:
2506                         case OBJ_mpd_name:
2507                         case OBJ_mpd_file:
2508                         case OBJ_mpd_percent:
2509                         case OBJ_mpd_smart:
2510                         case OBJ_if_mpd_playing:
2511                                 if (full) {
2512                                         free_mpd_vars(&info.mpd);
2513                                 }
2514                                 break;
2515 #endif
2516 #ifdef MOC
2517     case OBJ_moc_state:
2518     case OBJ_moc_file:
2519     case OBJ_moc_title:
2520     case OBJ_moc_artist: 
2521     case OBJ_moc_song: 
2522     case OBJ_moc_album:
2523     case OBJ_moc_totaltime:
2524     case OBJ_moc_timeleft:
2525     case OBJ_moc_curtime:
2526     case OBJ_moc_bitrate:
2527     case OBJ_moc_rate:
2528       free_moc(&info.moc);
2529       break;
2530 #endif
2531                         case OBJ_scroll:
2532                                 free(obj->data.scroll.text);
2533                                 break;
2534                 }
2535         }
2536         if (full) {} // disable warning when MPD !defined
2537         free(text_object_list->text_objects);
2538         text_object_list->text_objects = NULL;
2539         text_object_list->text_object_count = 0;
2540 }
2541
2542 void scan_mixer_bar(const char *arg, int *a, int *w, int *h)
2543 {
2544         char buf1[64];
2545         int n;
2546
2547         if (arg && sscanf(arg, "%63s %n", buf1, &n) >= 1) {
2548                 *a = mixer_init(buf1);
2549                 scan_bar(arg + n, w, h);
2550         } else {
2551                 *a = mixer_init(NULL);
2552                 scan_bar(arg, w, h);
2553         }
2554 }
2555
2556 /* strip a leading /dev/ if any */
2557 #define DEV_NAME(x) x != NULL && strlen(x) > 5 && strncmp(x, "/dev/", 5) == 0 \
2558         ? x + 5 : x
2559
2560 /* construct_text_object() creates a new text_object */
2561 static struct text_object *construct_text_object(const char *s,
2562                 const char *arg, unsigned int object_count,
2563                 struct text_object *text_objects, long line, char allow_threaded)
2564 {
2565         // struct text_object *obj = new_text_object();
2566         struct text_object *obj = new_text_object_internal();
2567
2568         obj->line = line;
2569
2570 #define OBJ(a, n) if (strcmp(s, #a) == 0) { \
2571         obj->type = OBJ_##a; need_mask |= (1 << n); {
2572 #define OBJ_THREAD(a, n) if (strcmp(s, #a) == 0 && allow_threaded) { \
2573         obj->type = OBJ_##a; need_mask |= (1 << n); {
2574 #define END } } else
2575
2576 #ifdef X11
2577         if (s[0] == '#') {
2578                 obj->type = OBJ_color;
2579                 obj->data.l = get_x11_color(s);
2580         } else
2581 #endif /* X11 */
2582 #ifdef __OpenBSD__
2583         OBJ(freq, INFO_FREQ)
2584 #else
2585         OBJ(acpitemp, 0)
2586                 obj->data.i = open_acpi_temperature(arg);
2587         END OBJ(acpiacadapter, 0)
2588         END OBJ(freq, INFO_FREQ)
2589 #endif /* !__OpenBSD__ */
2590                 get_cpu_count();
2591                 if (!arg || !isdigit(arg[0]) || strlen(arg) >= 2 || atoi(&arg[0]) == 0
2592                                 || (unsigned int) atoi(&arg[0]) > info.cpu_count) {
2593                         obj->data.cpu_index = 1;
2594                         /* ERR("freq: Invalid CPU number or you don't have that many CPUs! "
2595                                 "Displaying the clock for CPU 1."); */
2596                 } else {
2597                         obj->data.cpu_index = atoi(&arg[0]);
2598                 }
2599                 obj->a = 1;
2600         END OBJ(freq_g, INFO_FREQ)
2601                 get_cpu_count();
2602                 if (!arg || !isdigit(arg[0]) || strlen(arg) >= 2 || atoi(&arg[0]) == 0
2603                                 || (unsigned int) atoi(&arg[0]) > info.cpu_count) {
2604                         obj->data.cpu_index = 1;
2605                         /* ERR("freq_g: Invalid CPU number or you don't have that many "
2606                                 "CPUs! Displaying the clock for CPU 1."); */
2607                 } else {
2608                         obj->data.cpu_index = atoi(&arg[0]);
2609                 }
2610                 obj->a = 1;
2611 #if defined(__linux__)
2612         END OBJ(voltage_mv, 0)
2613                 get_cpu_count();
2614                 if (!arg || !isdigit(arg[0]) || strlen(arg) >= 2 || atoi(&arg[0]) == 0
2615                                 || (unsigned int) atoi(&arg[0]) > info.cpu_count) {
2616                         obj->data.cpu_index = 1;
2617                         /* ERR("voltage_mv: Invalid CPU number or you don't have that many "
2618                                 "CPUs! Displaying voltage for CPU 1."); */
2619                 } else {
2620                         obj->data.cpu_index = atoi(&arg[0]);
2621                 }
2622                 obj->a = 1;
2623         END OBJ(voltage_v, 0)
2624                 get_cpu_count();
2625                 if (!arg || !isdigit(arg[0]) || strlen(arg) >= 2 || atoi(&arg[0]) == 0
2626                                 || (unsigned int) atoi(&arg[0]) > info.cpu_count) {
2627                         obj->data.cpu_index = 1;
2628                         /* ERR("voltage_v: Invalid CPU number or you don't have that many "
2629                                 "CPUs! Displaying voltage for CPU 1."); */
2630                 } else {
2631                         obj->data.cpu_index = atoi(&arg[0]);
2632                 }
2633                 obj->a = 1;
2634
2635 #ifdef HAVE_IWLIB
2636         END OBJ(wireless_essid, INFO_NET)
2637                 if (arg) {
2638                         obj->data.net = get_net_stat(arg);
2639                 } else {
2640                         CRIT_ERR("wireless_essid: needs an argument");
2641                 }
2642         END OBJ(wireless_mode, INFO_NET)
2643                 if (arg) {
2644                         obj->data.net = get_net_stat(arg);
2645                 } else {
2646                         CRIT_ERR("wireless_mode: needs an argument");
2647                 }
2648         END OBJ(wireless_bitrate, INFO_NET)
2649                 if (arg) {
2650                         obj->data.net = get_net_stat(arg);
2651                 } else {
2652                         CRIT_ERR("wireless_bitrate: needs an argument");
2653                 }
2654         END OBJ(wireless_ap, INFO_NET)
2655                 if (arg) {
2656                         obj->data.net = get_net_stat(arg);
2657                 } else {
2658                         CRIT_ERR("wireless_ap: needs an argument");
2659                 }
2660         END OBJ(wireless_link_qual, INFO_NET)
2661                 if (arg) {
2662                         obj->data.net = get_net_stat(arg);
2663                 } else {
2664                         CRIT_ERR("wireless_link_qual: needs an argument");
2665                 }
2666         END OBJ(wireless_link_qual_max, INFO_NET)
2667                 if (arg) {
2668                         obj->data.net = get_net_stat(arg);
2669                 } else {
2670                         CRIT_ERR("wireless_link_qual_max: needs an argument");
2671                 }
2672         END OBJ(wireless_link_qual_perc, INFO_NET)
2673                 if (arg) {
2674                         obj->data.net = get_net_stat(arg);
2675                 } else {
2676                         CRIT_ERR("wireless_link_qual_perc: needs an argument");
2677                 }
2678         END OBJ(wireless_link_bar, INFO_NET)
2679                 if (arg) {
2680                         arg = scan_bar(arg, &obj->a, &obj->b);
2681                         obj->data.net = get_net_stat(arg);
2682                 } else {
2683                         CRIT_ERR("wireless_link_bar: needs an argument");
2684                 }
2685 #endif /* HAVE_IWLIB */
2686
2687 #endif /* __linux__ */
2688
2689 #ifndef __OpenBSD__
2690         END OBJ(acpifan, 0)
2691         END OBJ(battery, 0)
2692                 char bat[64];
2693
2694                 if (arg) {
2695                         sscanf(arg, "%63s", bat);
2696                 } else {
2697                         strcpy(bat, "BAT0");
2698                 }
2699                 obj->data.s = strndup(bat, text_buffer_size);
2700         END OBJ(battery_time, 0)
2701                 char bat[64];
2702
2703                 if (arg) {
2704                         sscanf(arg, "%63s", bat);
2705                 } else {
2706                         strcpy(bat, "BAT0");
2707                 }
2708                 obj->data.s = strndup(bat, text_buffer_size);
2709         END OBJ(battery_percent, 0)
2710                 char bat[64];
2711
2712                 if (arg) {
2713                         sscanf(arg, "%63s", bat);
2714                 } else {
2715                         strcpy(bat, "BAT0");
2716                 }
2717                 obj->data.s = strndup(bat, text_buffer_size);
2718         END OBJ(battery_bar, 0)
2719                 char bat[64];
2720                 obj->b = 6;
2721                 if (arg) {
2722                         arg = scan_bar(arg, &obj->a, &obj->b);
2723                         sscanf(arg, "%63s", bat);
2724                 } else {
2725                         strcpy(bat, "BAT0");
2726                 }
2727                 obj->data.s = strndup(bat, text_buffer_size);
2728 #endif /* !__OpenBSD__ */
2729
2730 #if defined(__linux__)
2731         END OBJ(disk_protect, 0)
2732                 if (arg)
2733                         obj->data.s = strndup(DEV_NAME(arg), text_buffer_size);
2734                 else
2735                         CRIT_ERR("disk_protect needs an argument");
2736         END OBJ(i8k_version, INFO_I8K)
2737         END OBJ(i8k_bios, INFO_I8K)
2738         END OBJ(i8k_serial, INFO_I8K)
2739         END OBJ(i8k_cpu_temp, INFO_I8K)
2740         END OBJ(i8k_left_fan_status, INFO_I8K)
2741         END OBJ(i8k_right_fan_status, INFO_I8K)
2742         END OBJ(i8k_left_fan_rpm, INFO_I8K)
2743         END OBJ(i8k_right_fan_rpm, INFO_I8K)
2744         END OBJ(i8k_ac_status, INFO_I8K)
2745         END OBJ(i8k_buttons_status, INFO_I8K)
2746         END OBJ(ibm_fan, 0)
2747         END OBJ(ibm_temps, 0)
2748                 if (!arg) {
2749                         CRIT_ERR("ibm_temps: needs an argument");
2750                 }
2751                 if (!isdigit(arg[0]) || strlen(arg) >= 2 || atoi(&arg[0]) >= 8) {
2752                         obj->data.sensor = 0;
2753                         ERR("Invalid temperature sensor! Sensor number must be 0 to 7. "
2754                                 "Using 0 (CPU temp sensor).");
2755                 }
2756                 obj->data.sensor = atoi(&arg[0]);
2757         END OBJ(ibm_volume, 0)
2758         END OBJ(ibm_brightness, 0)
2759         END OBJ(if_up, 0)
2760                 if (blockdepth >= MAX_IF_BLOCK_DEPTH) {
2761                         CRIT_ERR("MAX_IF_BLOCK_DEPTH exceeded");
2762                 }
2763                 if (!arg) {
2764                         ERR("if_up needs an argument");
2765                         obj->data.ifblock.s = 0;
2766                 } else
2767                         obj->data.ifblock.s = strndup(arg, text_buffer_size);
2768                 blockstart[blockdepth] = object_count;
2769                 obj->data.ifblock.pos = object_count + 2;
2770                 blockdepth++;
2771         END OBJ(if_gw, 0)
2772                 if (blockdepth >= MAX_IF_BLOCK_DEPTH) {
2773                         CRIT_ERR("MAX_IF_BLOCK_DEPTH exceeded");
2774                 }
2775                 blockstart[blockdepth] = object_count;
2776                 obj->data.ifblock.pos = object_count + 2;
2777                 blockdepth++;
2778         END OBJ(ioscheduler, 0)
2779                 if (!arg) {
2780                         CRIT_ERR("get_ioscheduler needs an argument (e.g. hda)");
2781                         obj->data.s = 0;
2782                 } else
2783                         obj->data.s = strndup(DEV_NAME(arg), text_buffer_size);
2784         END OBJ(laptop_mode, 0)
2785         END OBJ(pb_battery, 0)
2786                 if (arg && strcmp(arg, "status") == EQUAL) {
2787                         obj->data.i = PB_BATT_STATUS;
2788                 } else if (arg && strcmp(arg, "percent") == EQUAL) {
2789                         obj->data.i = PB_BATT_PERCENT;
2790                 } else if (arg && strcmp(arg, "time") == EQUAL) {
2791                         obj->data.i = PB_BATT_TIME;
2792                 } else {
2793                         ERR("pb_battery: needs one argument: status, percent or time");
2794                         free(obj);
2795                         return NULL;
2796                 }
2797
2798 #endif /* __linux__ */
2799 #if defined(__OpenBSD__)
2800         END OBJ(obsd_sensors_temp, 0)
2801                 if (!arg) {
2802                         CRIT_ERR("obsd_sensors_temp: needs an argument");
2803                 }
2804                 if (!isdigit(arg[0]) || atoi(&arg[0]) < 0
2805                                 || atoi(&arg[0]) > OBSD_MAX_SENSORS - 1) {
2806                         obj->data.sensor = 0;
2807                         ERR("Invalid temperature sensor number!");
2808                 }
2809                 obj->data.sensor = atoi(&arg[0]);
2810         END OBJ(obsd_sensors_fan, 0)
2811                 if (!arg) {
2812                         CRIT_ERR("obsd_sensors_fan: needs 2 arguments (device and sensor "
2813                                 "number)");
2814                 }
2815                 if (!isdigit(arg[0]) || atoi(&arg[0]) < 0
2816                                 || atoi(&arg[0]) > OBSD_MAX_SENSORS - 1) {
2817                         obj->data.sensor = 0;
2818                         ERR("Invalid fan sensor number!");
2819                 }
2820                 obj->data.sensor = atoi(&arg[0]);
2821         END OBJ(obsd_sensors_volt, 0)
2822                 if (!arg) {
2823                         CRIT_ERR("obsd_sensors_volt: needs 2 arguments (device and sensor "
2824                                 "number)");
2825                 }
2826                 if (!isdigit(arg[0]) || atoi(&arg[0]) < 0
2827                                 || atoi(&arg[0]) > OBSD_MAX_SENSORS - 1) {
2828                         obj->data.sensor = 0;
2829                         ERR("Invalid voltage sensor number!");
2830                 }
2831                 obj->data.sensor = atoi(&arg[0]);
2832         END OBJ(obsd_vendor, 0)
2833         END OBJ(obsd_product, 0)
2834 #endif /* __OpenBSD__ */
2835         END OBJ(buffers, INFO_BUFFERS)
2836         END OBJ(cached, INFO_BUFFERS)
2837         END OBJ(cpu, INFO_CPU)
2838                 if (arg) {
2839                         if (strncmp(arg, "cpu", 3) == EQUAL && isdigit(arg[3])) {
2840                                 obj->data.cpu_index = atoi(&arg[3]);
2841                                 arg += 4;
2842                         } else {
2843                                 obj->data.cpu_index = 0;
2844                         }
2845                         DBGP2("Adding $cpu for CPU %d", obj->data.cpu_index);
2846                 } else {
2847                         obj->data.cpu_index = 0;
2848                 }
2849         END OBJ(cpubar, INFO_CPU)
2850                 if (arg) {
2851                         if (strncmp(arg, "cpu", 3) == EQUAL && isdigit(arg[3])) {
2852                                 obj->data.cpu_index = atoi(&arg[3]);
2853                                 arg += 4;
2854                         } else {
2855                                 obj->data.cpu_index = 0;
2856                         }
2857                         scan_bar(arg, &obj->a, &obj->b);
2858                 } else {
2859                         scan_bar(arg, &obj->a, &obj->b);
2860                         obj->data.cpu_index = 0;
2861                 }
2862                 DBGP2("Adding $cpubar for CPU %d", obj->data.cpu_index);
2863         END OBJ(cpugraph, INFO_CPU)
2864                 char *buf = scan_graph(arg, &obj->a, &obj->b, &obj->c, &obj->d,
2865                         &obj->e, &obj->showaslog);
2866
2867                 if (buf) {
2868                         if (strncmp(buf, "cpu", 3) == EQUAL && isdigit(buf[3])) {
2869                                 obj->data.cpu_index = atoi(&buf[3]);
2870                         } else {
2871                                 obj->data.cpu_index = 0;
2872                         }
2873                         free(buf);
2874                 }
2875                 DBGP2("Adding $cpugraph for CPU %d", obj->data.cpu_index);
2876         END OBJ(loadgraph, INFO_LOADAVG)
2877                 char *buf = scan_graph(arg, &obj->a, &obj->b, &obj->c, &obj->d,
2878                                 &obj->e, &obj->showaslog);
2879                 if (buf) {
2880                         int a = 1, r = 3;
2881                         if (arg) {
2882                                 r = sscanf(arg, "%d", &a);
2883                         }
2884                         obj->data.loadavg[0] = (r >= 1) ? (unsigned char) a : 0;
2885                         free(buf);
2886                 }
2887 #if defined(__linux__)
2888         END OBJ(diskio, INFO_DISKIO)
2889                 if (arg) {
2890                         obj->data.diskio = prepare_diskio_stat(DEV_NAME(arg));
2891                 } else {
2892                         obj->data.diskio = NULL;
2893                 }
2894         END OBJ(diskio_read, INFO_DISKIO)
2895                 if (arg) {
2896                         obj->data.diskio = prepare_diskio_stat(DEV_NAME(arg));
2897                 } else {
2898                         obj->data.diskio = NULL;
2899                 }
2900         END OBJ(diskio_write, INFO_DISKIO)
2901                 if (arg) {
2902                         obj->data.diskio = prepare_diskio_stat(DEV_NAME(arg));
2903                 } else {
2904                         obj->data.diskio = NULL;
2905                 }
2906         END OBJ(diskiograph, INFO_DISKIO)
2907                 char *buf = scan_graph(DEV_NAME(arg), &obj->a, &obj->b, &obj->c, &obj->d,
2908                         &obj->e, &obj->showaslog);
2909
2910                 if (buf) {
2911                         obj->data.diskio = prepare_diskio_stat(buf);
2912                         free(buf);
2913                 } else {
2914                         obj->data.diskio = NULL;
2915                 }
2916         END OBJ(diskiograph_read, INFO_DISKIO)
2917                 char *buf = scan_graph(DEV_NAME(arg), &obj->a, &obj->b, &obj->c, &obj->d,
2918                         &obj->e, &obj->showaslog);
2919
2920                 if (buf) {
2921                         obj->data.diskio = prepare_diskio_stat(buf);
2922                         free(buf);
2923                 } else {
2924                         obj->data.diskio = NULL;
2925                 }
2926         END OBJ(diskiograph_write, INFO_DISKIO)
2927                 char *buf = scan_graph(DEV_NAME(arg), &obj->a, &obj->b, &obj->c, &obj->d,
2928                         &obj->e, &obj->showaslog);
2929
2930                 if (buf) {
2931                         obj->data.diskio = prepare_diskio_stat(buf);
2932                         free(buf);
2933                 } else {
2934                         obj->data.diskio = NULL;
2935                 }
2936 #endif
2937         END OBJ(color, 0)
2938 #ifdef X11
2939                 obj->data.l = arg ? get_x11_color(arg) : default_fg_color;
2940 #endif /* X11 */
2941         END OBJ(color0, 0)
2942                 obj->data.l = color0;
2943         END OBJ(color1, 0)
2944                 obj->data.l = color1;
2945         END OBJ(color2, 0)
2946                 obj->data.l = color2;
2947         END OBJ(color3, 0)
2948                 obj->data.l = color3;
2949         END OBJ(color4, 0)
2950                 obj->data.l = color4;
2951         END OBJ(color5, 0)
2952                 obj->data.l = color5;
2953         END OBJ(color6, 0)
2954                 obj->data.l = color6;
2955         END OBJ(color7, 0)
2956                 obj->data.l = color7;
2957         END OBJ(color8, 0)
2958                 obj->data.l = color8;
2959         END OBJ(color9, 0)
2960                 obj->data.l = color9;
2961         END OBJ(font, 0)
2962                 obj->data.s = scan_font(arg);
2963         END OBJ(conky_version, 0)
2964         END OBJ(conky_build_date, 0)
2965         END OBJ(conky_build_arch, 0)
2966         END OBJ(downspeed, INFO_NET)
2967                 if (arg) {
2968                         obj->data.net = get_net_stat(arg);
2969                 } else {
2970                         CRIT_ERR("downspeed needs argument");
2971                 }
2972         END OBJ(downspeedf, INFO_NET)
2973                 if (arg) {
2974                         obj->data.net = get_net_stat(arg);
2975                 } else {
2976                         CRIT_ERR("downspeedf needs argument");
2977                 }
2978         END OBJ(downspeedgraph, INFO_NET)
2979                 char *buf = scan_graph(arg, &obj->a, &obj->b, &obj->c, &obj->d,
2980                         &obj->e, &obj->showaslog);
2981
2982                 // default to DEFAULTNETDEV
2983                 buf = strndup(buf ? buf : "DEFAULTNETDEV", text_buffer_size);
2984                 obj->data.net = get_net_stat(buf);
2985                 free(buf);
2986         END OBJ(else, 0)
2987                 if (blockdepth) {
2988                         (text_objects[blockstart[blockdepth - 1]]).data.ifblock.pos =
2989                                 object_count;
2990                         blockstart[blockdepth - 1] = object_count;
2991                         obj->data.ifblock.pos = object_count + 2;
2992                 } else {
2993                         ERR("$else: no matching $if_*");
2994                 }
2995         END OBJ(endif, 0)
2996                 if (blockdepth) {
2997                         blockdepth--;
2998                         text_objects[blockstart[blockdepth]].data.ifblock.pos =
2999                                 object_count;
3000                 } else {
3001                         ERR("$endif: no matching $if_*");
3002                 }
3003         END OBJ(image, 0)
3004                 obj->data.s = strndup(arg ? arg : "", text_buffer_size);
3005 #ifdef HAVE_POPEN
3006         END OBJ(exec, 0)
3007                 obj->data.s = strndup(arg ? arg : "", text_buffer_size);
3008         END OBJ(execp, 0)
3009                 obj->data.s = strndup(arg ? arg : "", text_buffer_size);
3010         END OBJ(execbar, 0)
3011                 obj->data.s = strndup(arg ? arg : "", text_buffer_size);
3012         END OBJ(execgraph, 0)
3013                 obj->data.s = strndup(arg ? arg : "", text_buffer_size);
3014         END OBJ(execibar, 0)
3015                 int n;
3016
3017                 if (!arg || sscanf(arg, "%f %n", &obj->data.execi.interval, &n) <= 0) {
3018                         char buf[256];
3019
3020                         ERR("${execibar <interval> command}");
3021                         obj->type = OBJ_text;
3022                         snprintf(buf, 256, "${%s}", s);
3023                         obj->data.s = strndup(buf, text_buffer_size);
3024                 } else {
3025                         obj->data.execi.cmd = strndup(arg + n, text_buffer_size);
3026                 }
3027         END OBJ(execigraph, 0)
3028                 int n;
3029
3030                 if (!arg || sscanf(arg, "%f %n", &obj->data.execi.interval, &n) <= 0) {
3031                         char buf[256];
3032
3033                         ERR("${execigraph <interval> command}");
3034                         obj->type = OBJ_text;
3035                         snprintf(buf, 256, "${%s}", s);
3036                         obj->data.s = strndup(buf, text_buffer_size);
3037                 } else {
3038                         obj->data.execi.cmd = strndup(arg + n, text_buffer_size);
3039                 }
3040         END OBJ(execi, 0)
3041                 int n;
3042
3043                 if (!arg || sscanf(arg, "%f %n", &obj->data.execi.interval, &n) <= 0) {
3044                         char buf[256];
3045
3046                         ERR("${execi <interval> command}");
3047                         obj->type = OBJ_text;
3048                         snprintf(buf, 256, "${%s}", s);
3049                         obj->data.s = strndup(buf, text_buffer_size);
3050                 } else {
3051                         obj->data.execi.cmd = strndup(arg + n, text_buffer_size);
3052                         obj->data.execi.buffer = malloc(text_buffer_size);
3053                 }
3054         END OBJ(execpi, 0)
3055                 int n;
3056
3057                 if (!arg || sscanf(arg, "%f %n", &obj->data.execi.interval, &n) <= 0) {
3058                         char buf[256];
3059
3060                         ERR("${execi <interval> command}");
3061                         obj->type = OBJ_text;
3062                         snprintf(buf, 256, "${%s}", s);
3063                         obj->data.s = strndup(buf, text_buffer_size);
3064                 } else {
3065                         obj->data.execi.cmd = strndup(arg + n, text_buffer_size);
3066                         obj->data.execi.buffer = malloc(text_buffer_size);
3067                 }
3068         END OBJ_THREAD(texeci, 0)
3069                         int n;
3070
3071                         if (!arg || sscanf(arg, "%f %n", &obj->data.texeci.interval, &n) <= 0) {
3072                                 char buf[256];
3073
3074                                 ERR("${texeci <interval> command}");
3075                                 obj->type = OBJ_text;
3076                                 snprintf(buf, 256, "${%s}", s);
3077                                 obj->data.s = strndup(buf, text_buffer_size);
3078                         } else {
3079                                 obj->data.texeci.cmd = strndup(arg + n, text_buffer_size);
3080                                 obj->data.texeci.buffer = malloc(text_buffer_size);
3081                         }
3082                         obj->data.texeci.p_timed_thread = NULL;
3083         END     OBJ(pre_exec, 0)
3084                 obj->type = OBJ_text;
3085         if (arg) {
3086                 char buf[2048];
3087
3088                 read_exec(arg, buf, sizeof(buf));
3089                 obj->data.s = strndup(buf, text_buffer_size);
3090         } else {
3091                 obj->data.s = strndup("", text_buffer_size);
3092         }
3093 #endif
3094         END OBJ(fs_bar, INFO_FS)
3095                 arg = scan_bar(arg, &obj->data.fsbar.w, &obj->data.fsbar.h);
3096         if (arg) {
3097                         while (isspace(*arg)) {
3098                                 arg++;
3099                         }
3100                         if (*arg == '\0') {
3101                                 arg = "/";
3102                         }
3103                 } else {
3104                         arg = "/";
3105                 }
3106                 obj->data.fsbar.fs = prepare_fs_stat(arg);
3107         END OBJ(fs_bar_free, INFO_FS)
3108                 arg = scan_bar(arg, &obj->data.fsbar.w, &obj->data.fsbar.h);
3109                 if (arg) {
3110                         while (isspace(*arg)) {
3111                                 arg++;
3112                         }
3113                         if (*arg == '\0') {
3114                                 arg = "/";
3115                         }
3116                 } else {
3117                         arg = "/";
3118                 }
3119
3120                 obj->data.fsbar.fs = prepare_fs_stat(arg);
3121         END OBJ(fs_free, INFO_FS)
3122                 if (!arg) {
3123                         arg = "/";
3124                 }
3125                 obj->data.fs = prepare_fs_stat(arg);
3126         END OBJ(fs_used_perc, INFO_FS)
3127                 if (!arg) {
3128                         arg = "/";
3129                 }
3130                 obj->data.fs = prepare_fs_stat(arg);
3131         END OBJ(fs_free_perc, INFO_FS)
3132                 if (!arg) {
3133                         arg = "/";
3134                 }
3135                 obj->data.fs = prepare_fs_stat(arg);
3136         END OBJ(fs_size, INFO_FS)
3137                 if (!arg) {
3138                         arg = "/";
3139                 }
3140                 obj->data.fs = prepare_fs_stat(arg);
3141         END OBJ(fs_type, INFO_FS)
3142                 if (!arg) {
3143                         arg = "/";
3144                 }
3145                 obj->data.fs = prepare_fs_stat(arg);
3146         END OBJ(fs_used, INFO_FS)
3147                 if (!arg) {
3148                         arg = "/";
3149                 }
3150                 obj->data.fs = prepare_fs_stat(arg);
3151         END OBJ(hr, 0)
3152                 obj->data.i = arg ? atoi(arg) : 1;
3153         END OBJ(nameserver, INFO_DNS)
3154                 obj->data.i = arg ? atoi(arg) : 0;
3155         END OBJ(offset, 0)
3156                 obj->data.i = arg ? atoi(arg) : 1;
3157         END OBJ(voffset, 0)
3158                 obj->data.i = arg ? atoi(arg) : 1;
3159         END OBJ(goto, 0)
3160
3161                 if (!arg) {
3162                         ERR("goto needs arguments");
3163                         obj->type = OBJ_text;
3164                         obj->data.s = strndup("${goto}", text_buffer_size);
3165                         return NULL;
3166                 }
3167
3168                 obj->data.i = atoi(arg);
3169
3170         END OBJ(tab, 0)
3171                 int a = 10, b = 0;
3172
3173                 if (arg) {
3174                         if (sscanf(arg, "%d %d", &a, &b) != 2) {
3175                                 sscanf(arg, "%d", &b);
3176                         }
3177                 }
3178                 if (a <= 0) {
3179                         a = 1;
3180                 }
3181                 obj->data.pair.a = a;
3182                 obj->data.pair.b = b;
3183
3184 #ifndef __OpenBSD__
3185         END OBJ(i2c, INFO_SYSFS)
3186                 char buf1[64], buf2[64];
3187                 int n;
3188
3189                 if (!arg) {
3190                         ERR("i2c needs arguments");
3191                         obj->type = OBJ_text;
3192                         // obj->data.s = strndup("${i2c}", text_buffer_size);
3193                         return NULL;
3194                 }
3195
3196                 if (sscanf(arg, "%63s %63s %d", buf1, buf2, &n) != 3) {
3197                         /* if scanf couldn't read three values, read type and num and use
3198                          * default device */
3199                         sscanf(arg, "%63s %d", buf2, &n);
3200                         obj->data.sysfs.fd = open_i2c_sensor(0, buf2, n,
3201                                 &obj->data.sysfs.arg, obj->data.sysfs.devtype);
3202                         strncpy(obj->data.sysfs.type, buf2, 63);
3203                 } else {
3204                         obj->data.sysfs.fd = open_i2c_sensor(buf1, buf2, n,
3205                                 &obj->data.sysfs.arg, obj->data.sysfs.devtype);
3206                         strncpy(obj->data.sysfs.type, buf2, 63);
3207                 }
3208
3209         END OBJ(platform, INFO_SYSFS)
3210                 char buf1[64], buf2[64];
3211                 int n;
3212
3213                 if (!arg) {
3214                         ERR("platform needs arguments");
3215                         obj->type = OBJ_text;
3216                         return NULL;
3217                 }
3218
3219                 if (sscanf(arg, "%63s %63s %d", buf1, buf2, &n) != 3) {
3220                         /* if scanf couldn't read three values, read type and num and use
3221                          * default device */
3222                         sscanf(arg, "%63s %d", buf2, &n);
3223                         obj->data.sysfs.fd = open_platform_sensor(0, buf2, n,
3224                                 &obj->data.sysfs.arg, obj->data.sysfs.devtype);
3225                         strncpy(obj->data.sysfs.type, buf2, 63);
3226                 } else {
3227                         obj->data.sysfs.fd = open_platform_sensor(buf1, buf2, n,
3228                                 &obj->data.sysfs.arg, obj->data.sysfs.devtype);
3229                         strncpy(obj->data.sysfs.type, buf2, 63);
3230                 }
3231
3232         END OBJ(hwmon, INFO_SYSFS)
3233                 char buf1[64], buf2[64];
3234                 int n;
3235
3236                 if (!arg) {
3237                         ERR("hwmon needs argumanets");
3238                         obj->type = OBJ_text;
3239                         return NULL;
3240                 }
3241
3242                 if (sscanf(arg, "%63s %63s %d", buf1, buf2, &n) != 3) {
3243                         /* if scanf couldn't read three values, read type and num and use
3244                          * default device */
3245                         sscanf(arg, "%63s %d", buf2, &n);
3246                         obj->data.sysfs.fd = open_hwmon_sensor(0, buf2, n,
3247                                 &obj->data.sysfs.arg, obj->data.sysfs.devtype);
3248                         strncpy(obj->data.sysfs.type, buf2, 63);
3249                 } else {
3250                         obj->data.sysfs.fd = open_hwmon_sensor(buf1, buf2, n,
3251                                 &obj->data.sysfs.arg, obj->data.sysfs.devtype);
3252                         strncpy(obj->data.sysfs.type, buf2, 63);
3253                 }
3254 #endif /* !__OpenBSD__ */
3255
3256         END OBJ(top, INFO_TOP)
3257                 char buf[64];
3258                 int n;
3259
3260                 if (!arg) {
3261                         ERR("top needs arguments");
3262                         obj->type = OBJ_text;
3263                         // obj->data.s = strndup("${top}", text_buffer_size);
3264                         return NULL;
3265                 }
3266                 if (sscanf(arg, "%63s %i", buf, &n) == 2) {
3267                         if (strcmp(buf, "name") == EQUAL) {
3268                                 obj->data.top.type = TOP_NAME;
3269                         } else if (strcmp(buf, "cpu") == EQUAL) {
3270                                 obj->data.top.type = TOP_CPU;
3271                         } else if (strcmp(buf, "pid") == EQUAL) {
3272                                 obj->data.top.type = TOP_PID;
3273                         } else if (strcmp(buf, "mem") == EQUAL) {
3274                                 obj->data.top.type = TOP_MEM;
3275                         } else if (strcmp(buf, "time") == EQUAL) {
3276                                 obj->data.top.type = TOP_TIME;
3277                         } else if (strcmp(buf, "mem_res") == EQUAL) {
3278                                 obj->data.top.type = TOP_MEM_RES;
3279                         } else if (strcmp(buf, "mem_vsize") == EQUAL) {
3280                                 obj->data.top.type = TOP_MEM_VSIZE;
3281                         } else {
3282                                 ERR("invalid arg for top");
3283                                 return NULL;
3284                         }
3285                         if (n < 1 || n > 10) {
3286                                 CRIT_ERR("invalid arg for top");
3287                                 return NULL;
3288                         } else {
3289                                 obj->data.top.num = n - 1;
3290                                 top_cpu = 1;
3291                         }
3292                 } else {
3293                         ERR("invalid args given for top");
3294                         return NULL;
3295                 }
3296         END OBJ(top_mem, INFO_TOP)
3297                 char buf[64];
3298                 int n;
3299
3300                 if (!arg) {
3301                         ERR("top_mem needs arguments");
3302                         obj->type = OBJ_text;
3303                         obj->data.s = strndup("${top_mem}", text_buffer_size);
3304                         return NULL;
3305                 }
3306                 if (sscanf(arg, "%63s %i", buf, &n) == 2) {
3307                         if (strcmp(buf, "name") == EQUAL) {
3308                                 obj->data.top.type = TOP_NAME;
3309                         } else if (strcmp(buf, "cpu") == EQUAL) {
3310                                 obj->data.top.type = TOP_CPU;
3311                         } else if (strcmp(buf, "pid") == EQUAL) {
3312                                 obj->data.top.type = TOP_PID;
3313                         } else if (strcmp(buf, "mem") == EQUAL) {
3314                                 obj->data.top.type = TOP_MEM;
3315                         } else if (strcmp(buf, "time") == EQUAL) {
3316                                 obj->data.top.type = TOP_TIME;
3317                         } else if (strcmp(buf, "mem_res") == EQUAL) {
3318                                 obj->data.top.type = TOP_MEM_RES;
3319                         } else if (strcmp(buf, "mem_vsize") == EQUAL) {
3320                                 obj->data.top.type = TOP_MEM_VSIZE;
3321                         } else {
3322                                 ERR("invalid arg for top");
3323                                 return NULL;
3324                         }
3325                         if (n < 1 || n > 10) {
3326                                         CRIT_ERR("invalid arg for top");
3327                                 return NULL;
3328                         } else {
3329                                 obj->data.top.num = n - 1;
3330                                 top_mem = 1;
3331                         }
3332                 } else {
3333                         ERR("invalid args given for top");
3334                         return NULL;
3335                 }
3336         END OBJ(addr, INFO_NET)
3337                 if (arg) {
3338                         obj->data.net = get_net_stat(arg);
3339                 } else {
3340                         CRIT_ERR("addr needs argument");
3341                 }
3342 #if defined(__linux__)
3343         END OBJ(addrs, INFO_NET)
3344                 if (arg) {
3345                         obj->data.net = get_net_stat(arg);
3346                 } else {
3347                         CRIT_ERR("addrs needs argument");
3348                 }
3349 #endif /* __linux__ */
3350         END OBJ(tail, 0)
3351                 char buf[64];
3352                 int n1, n2;
3353                 struct stat st;
3354
3355                 if (!arg) {
3356                         ERR("tail needs arguments");
3357                         obj->type = OBJ_text;
3358                         obj->data.s = strndup("${tail}", text_buffer_size);
3359                         return NULL;
3360                 }
3361                 if (sscanf(arg, "%63s %i %i", buf, &n1, &n2) == 2) {
3362                         if (n1 < 1 || n1 > MAX_TAIL_LINES) {
3363                                 CRIT_ERR("invalid arg for tail, number of lines must be "
3364                                                 "between 1 and %i", MAX_TAIL_LINES);
3365                                 return NULL;
3366                         } else {
3367                                 FILE *fp = NULL;
3368                                 int fd;
3369
3370                                 obj->data.tail.fd = -1;
3371
3372                                 if (stat(buf, &st) == 0) {
3373                                         if (S_ISFIFO(st.st_mode)) {
3374                                                 fd = open(buf, O_RDONLY | O_NONBLOCK);
3375
3376                                                 if (fd == -1) {
3377                                                         CRIT_ERR("tail logfile does not exist, or you do "
3378                                                                 "not have correct permissions");
3379                                                 }
3380
3381                                                 obj->data.tail.fd = fd;
3382                                         } else {
3383                                                 fp = fopen(buf, "r");
3384                                         }
3385                                 }
3386
3387                                 if (fp || obj->data.tail.fd != -1) {
3388                                         obj->data.tail.logfile = malloc(text_buffer_size);
3389                                         strcpy(obj->data.tail.logfile, buf);
3390                                         obj->data.tail.wantedlines = n1;
3391                                         obj->data.tail.interval = update_interval * 2;
3392
3393                                         if (obj->data.tail.fd == -1) {
3394                                                 fclose(fp);
3395                                         }
3396                                 } else {
3397                                         // fclose(fp);
3398                                         CRIT_ERR("tail logfile does not exist, or you do not have "
3399                                                 "correct permissions");
3400                                 }
3401                         }
3402                 } else if (sscanf(arg, "%63s %i %i", buf, &n1, &n2) == 3) {
3403                         if (n1 < 1 || n1 > MAX_TAIL_LINES) {
3404                                 CRIT_ERR("invalid arg for tail, number of lines must be "
3405                                         "between 1 and %i", MAX_TAIL_LINES);
3406                                 return NULL;
3407                         } else if (n2 < 1 || n2 < update_interval) {
3408                                 CRIT_ERR("invalid arg for tail, interval must be greater than "
3409                                         "0 and "PACKAGE_NAME"'s interval");
3410                                 return NULL;
3411                         } else {
3412                                 FILE *fp = 0;
3413                                 int fd;
3414
3415                                 obj->data.tail.fd = -1;
3416
3417                                 if (stat(buf, &st) == 0) {
3418                                         if (S_ISFIFO(st.st_mode)) {
3419                                                 fd = open(buf, O_RDONLY | O_NONBLOCK);
3420
3421                                                 if (fd == -1) {
3422                                                         CRIT_ERR("tail logfile does not exist, or you do "
3423                                                                 "not have correct permissions");
3424                                                 }
3425
3426                                                 obj->data.tail.fd = fd;
3427                                         } else {
3428                                                 fp = fopen(buf, "r");
3429                                         }
3430                                 }
3431
3432                                 if (fp || obj->data.tail.fd != -1) {
3433                                         obj->data.tail.logfile = malloc(text_buffer_size);
3434                                         strcpy(obj->data.tail.logfile, buf);
3435                                         obj->data.tail.wantedlines = n1;
3436                                         obj->data.tail.interval = n2;
3437
3438                                         if (obj->data.tail.fd == -1) {
3439                                                 fclose(fp);
3440                                         }
3441                                 } else {
3442                                         // fclose(fp);
3443                                         CRIT_ERR("tail logfile does not exist, or you do not have "
3444                                                 "correct permissions");
3445                                 }
3446                         }
3447                 } else {
3448                         ERR("invalid args given for tail");
3449                         return NULL;
3450                 }
3451                 /* asumming all else worked */
3452                 obj->data.tail.buffer = malloc(text_buffer_size * 20);
3453         END OBJ(head, 0)
3454                 char buf[64];
3455                 int n1, n2;
3456
3457                 if (!arg) {
3458                         ERR("head needs arguments");
3459                         obj->type = OBJ_text;
3460                         obj->data.s = strndup("${head}", text_buffer_size);
3461                         return NULL;
3462                 }
3463                 if (sscanf(arg, "%63s %i %i", buf, &n1, &n2) == 2) {
3464                         if (n1 < 1 || n1 > MAX_TAIL_LINES) {
3465                                 CRIT_ERR("invalid arg for head, number of lines must be "
3466                                         "between 1 and %i", MAX_TAIL_LINES);
3467                                 return NULL;
3468                         } else {
3469                                 FILE *fp;
3470
3471                                 fp = fopen(buf, "r");
3472                                 if (fp != NULL) {
3473                                         obj->data.tail.logfile = malloc(text_buffer_size);
3474                                         strcpy(obj->data.tail.logfile, buf);
3475                                         obj->data.tail.wantedlines = n1;
3476                                         obj->data.tail.interval = update_interval * 2;
3477                                         fclose(fp);
3478                                 } else {
3479                                         // fclose(fp);
3480                                         CRIT_ERR("head logfile does not exist, or you do not have "
3481                                                 "correct permissions");
3482                                 }
3483                         }
3484                 } else if (sscanf(arg, "%63s %i %i", buf, &n1, &n2) == 3) {
3485                         if (n1 < 1 || n1 > MAX_TAIL_LINES) {
3486                                 CRIT_ERR("invalid arg for head, number of lines must be "
3487                                         "between 1 and %i", MAX_TAIL_LINES);
3488                                 return NULL;
3489                         } else if (n2 < 1 || n2 < update_interval) {
3490                                 CRIT_ERR("invalid arg for head, interval must be greater than "
3491                                         "0 and "PACKAGE_NAME"'s interval");
3492                                 return NULL;
3493                         } else {
3494                                 FILE *fp;
3495
3496                                 fp = fopen(buf, "r");
3497                                 if (fp != NULL) {
3498                                         obj->data.tail.logfile = malloc(text_buffer_size);
3499                                         strcpy(obj->data.tail.logfile, buf);
3500                                         obj->data.tail.wantedlines = n1;
3501                                         obj->data.tail.interval = n2;
3502                                         fclose(fp);
3503                                 } else {
3504                                         // fclose(fp);
3505                                         CRIT_ERR("head logfile does not exist, or you do not have "
3506                                                 "correct permissions");
3507                                 }
3508                         }
3509                 } else {
3510                         ERR("invalid args given for head");
3511                         return NULL;
3512                 }
3513                 /* asumming all else worked */
3514                 obj->data.tail.buffer = malloc(text_buffer_size * 20);
3515         END OBJ(lines, 0)
3516                 if (arg) {
3517                         obj->data.s = strdup(arg);
3518                 }else{
3519                         CRIT_ERR("lines needs a argument");
3520                 }
3521         END OBJ(words, 0)
3522                 if (arg) {
3523                         obj->data.s = strdup(arg);
3524                 }else{
3525                         CRIT_ERR("words needs a argument");
3526                 }
3527         END OBJ(loadavg, INFO_LOADAVG)
3528                 int a = 1, b = 2, c = 3, r = 3;
3529
3530                 if (arg) {
3531                         r = sscanf(arg, "%d %d %d", &a, &b, &c);
3532                         if (r >= 3 && (c < 1 || c > 3)) {
3533                                 r--;
3534                         }
3535                         if (r >= 2 && (b < 1 || b > 3)) {
3536                                 r--, b = c;
3537                         }
3538                         if (r >= 1 && (a < 1 || a > 3)) {
3539                                 r--, a = b, b = c;
3540                         }
3541                 }
3542                 obj->data.loadavg[0] = (r >= 1) ? (unsigned char) a : 0;
3543                 obj->data.loadavg[1] = (r >= 2) ? (unsigned char) b : 0;
3544                 obj->data.loadavg[2] = (r >= 3) ? (unsigned char) c : 0;
3545         END OBJ(if_empty, 0)
3546                 if (blockdepth >= MAX_IF_BLOCK_DEPTH) {
3547                         CRIT_ERR("MAX_IF_BLOCK_DEPTH exceeded");
3548                 }
3549                 if (!arg) {
3550                         ERR("if_empty needs an argument");
3551                         obj->data.ifblock.s = 0;
3552                 } else {
3553                         obj->data.ifblock.s = strndup(arg, text_buffer_size);
3554                 }
3555                 blockstart[blockdepth] = object_count;
3556                 obj->data.ifblock.pos = object_count + 2;
3557                 blockdepth++;
3558         END OBJ(if_existing, 0)
3559                 if (blockdepth >= MAX_IF_BLOCK_DEPTH) {
3560                         CRIT_ERR("MAX_IF_BLOCK_DEPTH exceeded");
3561                 }
3562                 if (!arg) {
3563                         ERR("if_existing needs an argument or two");
3564                         obj->data.ifblock.s = NULL;
3565                         obj->data.ifblock.str = NULL;
3566                 } else {
3567                         char buf1[256], buf2[256];
3568                         int r = sscanf(arg, "%255s %255[^\n]", buf1, buf2);
3569
3570                         if (r == 1) {
3571                                 obj->data.ifblock.s = strndup(buf1, text_buffer_size);
3572                                 obj->data.ifblock.str = NULL;
3573                         } else {
3574                                 obj->data.ifblock.s = strndup(buf1, text_buffer_size);
3575                                 obj->data.ifblock.str = strndup(buf2, text_buffer_size);
3576                         }
3577                 }
3578                 blockstart[blockdepth] = object_count;
3579                 obj->data.ifblock.pos = object_count + 2;
3580                 blockdepth++;
3581         END OBJ(if_mounted, 0)
3582                 if (blockdepth >= MAX_IF_BLOCK_DEPTH) {
3583                         CRIT_ERR("MAX_IF_BLOCK_DEPTH exceeded");
3584                 }
3585                 if (!arg) {
3586                         ERR("if_mounted needs an argument");
3587                         obj->data.ifblock.s = 0;
3588                 } else {
3589                         obj->data.ifblock.s = strndup(arg, text_buffer_size);
3590                 }
3591                 blockstart[blockdepth] = object_count;
3592                 obj->data.ifblock.pos = object_count + 2;
3593                 blockdepth++;
3594         END OBJ(if_running, 0)
3595                 if (blockdepth >= MAX_IF_BLOCK_DEPTH) {
3596                         CRIT_ERR("MAX_IF_BLOCK_DEPTH exceeded");
3597                 }
3598                 if (arg) {
3599                         char buf[256];
3600
3601                         snprintf(buf, 256, "pidof %s >/dev/null", arg);
3602                         obj->data.ifblock.s = strndup(buf, text_buffer_size);
3603                 } else {
3604                         ERR("if_running needs an argument");
3605                         obj->data.ifblock.s = 0;
3606                 }
3607                 blockstart[blockdepth] = object_count;
3608                 obj->data.ifblock.pos = object_count + 2;
3609                 blockdepth++;
3610         END OBJ(kernel, 0)
3611         END OBJ(machine, 0)
3612         END OBJ(mails, 0)
3613                 float n1;
3614                 char box[256], dst[256];
3615
3616                 if (!arg) {
3617                         n1 = 9.5;
3618                         /* Kapil: Changed from MAIL_FILE to
3619                            current_mail_spool since the latter
3620                            is a copy of the former if undefined
3621                            but the latter should take precedence
3622                            if defined */
3623                         strncpy(box, current_mail_spool, sizeof(box));
3624                 } else {
3625                         if (sscanf(arg, "%s %f", box, &n1) != 2) {
3626                                 n1 = 9.5;
3627                                 strncpy(box, arg, sizeof(box));
3628                         }
3629                 }
3630
3631                 variable_substitute(box, dst, sizeof(dst));
3632                 obj->data.local_mail.box = strndup(dst, text_buffer_size);
3633                 obj->data.local_mail.interval = n1;
3634         END OBJ(mboxscan, 0)
3635                 obj->data.mboxscan.args = (char *) malloc(text_buffer_size);
3636                 obj->data.mboxscan.output = (char *) malloc(text_buffer_size);
3637                 /* if '1' (in mboxscan.c) then there was SIGUSR1, hmm */
3638                 obj->data.mboxscan.output[0] = 1;
3639                 strncpy(obj->data.mboxscan.args, arg, text_buffer_size);
3640         END OBJ(mem, INFO_MEM)
3641         END OBJ(memeasyfree, INFO_MEM)
3642         END OBJ(memfree, INFO_MEM)
3643         END OBJ(memmax, INFO_MEM)
3644         END OBJ(memperc, INFO_MEM)
3645         END OBJ(membar, INFO_MEM)
3646                 scan_bar(arg, &obj->data.pair.a, &obj->data.pair.b);
3647         END OBJ(memgraph, INFO_MEM)
3648                 char *buf = scan_graph(arg, &obj->a, &obj->b, &obj->c, &obj->d,
3649                         &obj->e, &obj->showaslog);
3650
3651                 if (buf) {
3652                         free(buf);
3653                 }
3654         END OBJ(mixer, INFO_MIXER)
3655                 obj->data.l = mixer_init(arg);
3656         END OBJ(mixerl, INFO_MIXER)
3657                 obj->data.l = mixer_init(arg);
3658         END OBJ(mixerr, INFO_MIXER)
3659                 obj->data.l = mixer_init(arg);
3660         END OBJ(mixerbar, INFO_MIXER)
3661                 scan_mixer_bar(arg, &obj->data.mixerbar.l, &obj->data.mixerbar.w,
3662                         &obj->data.mixerbar.h);
3663         END OBJ(mixerlbar, INFO_MIXER)
3664                 scan_mixer_bar(arg, &obj->data.mixerbar.l, &obj->data.mixerbar.w,
3665                         &obj->data.mixerbar.h);
3666         END OBJ(mixerrbar, INFO_MIXER)
3667                 scan_mixer_bar(arg, &obj->data.mixerbar.l, &obj->data.mixerbar.w,
3668                         &obj->data.mixerbar.h);
3669 #ifdef X11
3670         END OBJ(monitor, INFO_X11)
3671         END OBJ(monitor_number, INFO_X11)
3672 #endif
3673         END OBJ(new_mails, 0)
3674                 float n1;
3675                 char box[256], dst[256];
3676
3677                 if (!arg) {
3678                         n1 = 9.5;
3679                         /* Kapil: Changed from MAIL_FILE to
3680                            current_mail_spool since the latter
3681                            is a copy of the former if undefined
3682                            but the latter should take precedence
3683                            if defined */
3684                         strncpy(box, current_mail_spool, sizeof(box));
3685                 } else {
3686                         if (sscanf(arg, "%s %f", box, &n1) != 2) {
3687                                 n1 = 9.5;
3688                                 strncpy(box, arg, sizeof(box));
3689                         }
3690                 }
3691
3692                 variable_substitute(box, dst, sizeof(dst));
3693                 obj->data.local_mail.box = strndup(dst, text_buffer_size);
3694                 obj->data.local_mail.interval = n1;
3695         END OBJ(nodename, 0)
3696         END OBJ(processes, INFO_PROCS)
3697         END OBJ(running_processes, INFO_RUN_PROCS)
3698         END OBJ(shadecolor, 0)
3699 #ifdef X11
3700                 obj->data.l = arg ? get_x11_color(arg) : default_bg_color;
3701 #endif /* X11 */
3702         END OBJ(outlinecolor, 0)
3703 #ifdef X11
3704                 obj->data.l = arg ? get_x11_color(arg) : default_out_color;
3705 #endif /* X11 */
3706         END OBJ(stippled_hr, 0)
3707 #ifdef X11
3708                 int a = stippled_borders, b = 1;
3709
3710                 if (arg) {
3711                         if (sscanf(arg, "%d %d", &a, &b) != 2) {
3712                                 sscanf(arg, "%d", &b);
3713                         }
3714                 }
3715                 if (a <= 0) {
3716                         a = 1;
3717                 }
3718                 obj->data.pair.a = a;
3719                 obj->data.pair.b = b;
3720 #endif /* X11 */
3721         END OBJ(swap, INFO_MEM)
3722         END OBJ(swapmax, INFO_MEM)
3723         END OBJ(swapperc, INFO_MEM)
3724         END OBJ(swapbar, INFO_MEM)
3725                 scan_bar(arg, &obj->data.pair.a, &obj->data.pair.b);
3726         END OBJ(sysname, 0)
3727 #ifndef __OpenBSD__
3728         END OBJ(temp1, INFO_SYSFS)
3729                 obj->type = OBJ_i2c;
3730                 obj->data.sysfs.fd = open_i2c_sensor(0, "temp", 1,
3731                         &obj->data.sysfs.arg, obj->data.sysfs.devtype);
3732         END OBJ(temp2, INFO_SYSFS)
3733                 obj->type = OBJ_i2c;
3734                 obj->data.sysfs.fd = open_i2c_sensor(0, "temp", 2,
3735                         &obj->data.sysfs.arg, obj->data.sysfs.devtype);
3736 #endif
3737         END OBJ(time, 0)
3738                 obj->data.s = strndup(arg ? arg : "%F %T", text_buffer_size);
3739         END OBJ(utime, 0)
3740                 obj->data.s = strndup(arg ? arg : "%F %T", text_buffer_size);
3741         END OBJ(tztime, 0)
3742                 char buf1[256], buf2[256], *fmt, *tz;
3743
3744                 fmt = tz = NULL;
3745                 if (arg) {
3746                         int nArgs = sscanf(arg, "%255s %255[^\n]", buf1, buf2);
3747
3748                         switch (nArgs) {
3749                                 case 2:
3750                                         tz = buf1;
3751                                 case 1:
3752                                         fmt = buf2;
3753                         }
3754                 }
3755
3756                 obj->data.tztime.fmt = strndup(fmt ? fmt : "%F %T", text_buffer_size);
3757                 obj->data.tztime.tz = tz ? strndup(tz, text_buffer_size) : NULL;
3758 #ifdef HAVE_ICONV
3759         END OBJ(iconv_start, 0)
3760                 if (iconv_converting) {
3761                         CRIT_ERR("You must stop your last iconv conversion before "
3762                                 "starting another");
3763                 }
3764                 if (arg) {
3765                         char iconv_from[CODEPAGE_LENGTH];
3766                         char iconv_to[CODEPAGE_LENGTH];
3767
3768                         if (sscanf(arg, "%s %s", iconv_from, iconv_to) != 2) {
3769                                 CRIT_ERR("Invalid arguments for iconv_start");
3770                         } else {
3771                                 iconv_t new_iconv;
3772
3773                                 new_iconv = iconv_open(iconv_to, iconv_from);
3774                                 if (new_iconv == (iconv_t) (-1)) {
3775                                         ERR("Can't convert from %s to %s.", iconv_from, iconv_to);
3776                                 } else {
3777                                         obj->a = register_iconv(&new_iconv);
3778                                         iconv_converting = 1;
3779                                 }
3780                         }
3781                 } else {
3782                         CRIT_ERR("Iconv requires arguments");
3783                 }
3784         END OBJ(iconv_stop, 0)
3785                 iconv_converting = 0;
3786
3787 #endif
3788         END OBJ(totaldown, INFO_NET)
3789                 if (arg) {
3790                         obj->data.net = get_net_stat(arg);
3791                 } else {
3792                         CRIT_ERR("totaldown needs argument");
3793                 }
3794         END OBJ(totalup, INFO_NET)
3795                 obj->data.net = get_net_stat(arg);
3796                 if (arg) {
3797                         obj->data.net = get_net_stat(arg);
3798                 } else {
3799                         CRIT_ERR("totalup needs argument");
3800                 }
3801         END OBJ(updates, 0)
3802         END OBJ(alignr, 0)
3803                 obj->data.i = arg ? atoi(arg) : 0;
3804         END OBJ(alignc, 0)
3805                 obj->data.i = arg ? atoi(arg) : 0;
3806         END OBJ(upspeed, INFO_NET)
3807                 if (arg) {
3808                         obj->data.net = get_net_stat(arg);
3809                 } else {
3810                         CRIT_ERR("upspeed needs argument");
3811                 }
3812         END OBJ(upspeedf, INFO_NET)
3813                 if (arg) {
3814                         obj->data.net = get_net_stat(arg);
3815                 } else {
3816                         CRIT_ERR("upspeedf needs argument");
3817                 }
3818
3819         END OBJ(upspeedgraph, INFO_NET)
3820                 char *buf = scan_graph(arg, &obj->a, &obj->b, &obj->c, &obj->d,
3821                         &obj->e, &obj->showaslog);
3822
3823                 // default to DEFAULTNETDEV
3824                 buf = strndup(buf ? buf : "DEFAULTNETDEV", text_buffer_size);
3825                 obj->data.net = get_net_stat(buf);
3826                 free(buf);
3827         END OBJ(uptime_short, INFO_UPTIME)
3828         END OBJ(uptime, INFO_UPTIME)
3829         END OBJ(user_names, INFO_USERS)
3830         END OBJ(user_times, INFO_USERS)
3831         END OBJ(user_terms, INFO_USERS)
3832         END OBJ(user_number, INFO_USERS)
3833 #if defined(__linux__)
3834         END OBJ(gw_iface, INFO_GW)
3835         END OBJ(gw_ip, INFO_GW)
3836         END OBJ(if_gw, INFO_GW)
3837 #endif /* !__linux__ */
3838 #ifndef __OpenBSD__
3839         END OBJ(adt746xcpu, 0)
3840         END OBJ(adt746xfan, 0)
3841 #endif /* !__OpenBSD__ */
3842 #if (defined(__FreeBSD__) || defined(__FreeBSD_kernel__) \
3843                 || defined(__OpenBSD__)) && (defined(i386) || defined(__i386__))
3844         END OBJ(apm_adapter, 0)
3845         END OBJ(apm_battery_life, 0)
3846         END OBJ(apm_battery_time, 0)
3847 #endif /* __FreeBSD__ */
3848         END OBJ_THREAD(imap_unseen, 0)
3849                 if (arg) {
3850                         // proccss
3851                         obj->data.mail = parse_mail_args(IMAP, arg);
3852                         obj->global_mode = 0;
3853                 } else {
3854                         obj->global_mode = 1;
3855                 }
3856         END OBJ_THREAD(imap_messages, 0)
3857                 if (arg) {
3858                         // proccss
3859                         obj->data.mail = parse_mail_args(IMAP, arg);
3860                         obj->global_mode = 0;
3861                 } else {
3862                         obj->global_mode = 1;
3863                 }
3864         END OBJ_THREAD(pop3_unseen, 0)
3865                 if (arg) {
3866                         // proccss
3867                         obj->data.mail = parse_mail_args(POP3, arg);
3868                         obj->global_mode = 0;
3869                 } else {
3870                         obj->global_mode = 1;
3871                 }
3872         END OBJ_THREAD(pop3_used, 0)
3873                 if (arg) {
3874                         // proccss
3875                         obj->data.mail = parse_mail_args(POP3, arg);
3876                         obj->global_mode = 0;
3877                 } else {
3878                         obj->global_mode = 1;
3879                 }
3880 #ifdef SMAPI
3881         END OBJ(smapi, 0)
3882                 if (arg)
3883                         obj->data.s = strndup(arg, text_buffer_size);
3884                 else
3885                         ERR("smapi needs an argument");
3886         END OBJ(if_smapi_bat_installed, 0)
3887                 if (blockdepth >= MAX_IF_BLOCK_DEPTH) {
3888                         CRIT_ERR("MAX_IF_BLOCK_DEPTH exceeded");
3889                 }
3890                 if (!arg) {
3891                         ERR("if_smapi_bat_installed needs an argument");
3892                         obj->data.ifblock.s = 0;
3893                 } else
3894                         obj->data.ifblock.s = strndup(arg, text_buffer_size);
3895                 blockstart[blockdepth] = object_count;
3896                 obj->data.ifblock.pos = object_count + 2;
3897                 blockdepth++;
3898         END OBJ(smapi_bat_perc, 0)
3899                 if (arg)
3900                         obj->data.s = strndup(arg, text_buffer_size);
3901                 else
3902                         ERR("smapi_bat_perc needs an argument");
3903         END OBJ(smapi_bat_temp, 0)
3904                 if (arg)
3905                         obj->data.s = strndup(arg, text_buffer_size);
3906                 else
3907                         ERR("smapi_bat_temp needs an argument");
3908         END OBJ(smapi_bat_power, 0)
3909                 if (arg)
3910                         obj->data.s = strndup(arg, text_buffer_size);
3911                 else
3912                         ERR("smapi_bat_power needs an argument");
3913         END OBJ(smapi_bat_bar, 0)
3914                 if(arg) {
3915                         int cnt;
3916                         if(sscanf(arg, "%i %n", &obj->data.i, &cnt) <= 0) {
3917                                 ERR("first argument to smapi_bat_bar must be an integer value");
3918                                 obj->data.i = -1;
3919                         } else {
3920                                 obj->b = 4;
3921                                 arg = scan_bar(arg + cnt, &obj->a, &obj->b);
3922                         }
3923                 } else
3924                         ERR("if_smapi_bat_bar needs an argument");
3925 #endif /* SMAPI */
3926 #ifdef MPD
3927         END OBJ_THREAD(mpd_artist, INFO_MPD)
3928         END OBJ_THREAD(mpd_title, INFO_MPD)
3929                 if (arg) {
3930                         sscanf(arg, "%d", &obj->data.i);
3931                         if (obj->data.i > 0) {
3932                                 obj->data.i++;
3933                         } else {
3934                                 CRIT_ERR("mpd_title: invalid length argument");
3935                         }
3936                 } else {
3937                         obj->data.i = 0;
3938                 }
3939         END OBJ_THREAD(mpd_random, INFO_MPD)
3940         END OBJ_THREAD(mpd_repeat, INFO_MPD)
3941         END OBJ_THREAD(mpd_elapsed, INFO_MPD)
3942         END OBJ_THREAD(mpd_length, INFO_MPD)
3943         END OBJ_THREAD(mpd_track, INFO_MPD)
3944         END OBJ_THREAD(mpd_name, INFO_MPD)
3945         END OBJ_THREAD(mpd_file, INFO_MPD)
3946         END OBJ_THREAD(mpd_percent, INFO_MPD)
3947         END OBJ_THREAD(mpd_album, INFO_MPD)
3948         END OBJ_THREAD(mpd_vol, INFO_MPD)
3949         END OBJ_THREAD(mpd_bitrate, INFO_MPD)
3950         END OBJ_THREAD(mpd_status, INFO_MPD)
3951         END OBJ_THREAD(mpd_bar, INFO_MPD)
3952                 scan_bar(arg, &obj->data.pair.a, &obj->data.pair.b);
3953         END OBJ_THREAD(mpd_smart, INFO_MPD)
3954                 if (arg) {
3955                         sscanf(arg, "%d", &obj->data.i);
3956                         if (obj->data.i > 0) {
3957                                 obj->data.i++;
3958                         } else {
3959                                 CRIT_ERR("mpd_smart: invalid length argument");
3960                         }
3961                 } else {
3962                         obj->data.i = 0;
3963                 }
3964         END OBJ_THREAD(if_mpd_playing, INFO_MPD)
3965                 if (blockdepth >= MAX_IF_BLOCK_DEPTH) {
3966                         CRIT_ERR("MAX_IF_BLOCK_DEPTH exceeded");
3967                 }
3968                 blockstart[blockdepth] = object_count;
3969                 obj->data.ifblock.pos = object_count + 2;
3970                 blockdepth++;
3971 #endif /* MPD */
3972 #ifdef MOC
3973   END OBJ_THREAD(moc_state, INFO_MOC)
3974   END OBJ_THREAD(moc_file, INFO_MOC)
3975   END OBJ_THREAD(moc_title, INFO_MOC)
3976   END OBJ_THREAD(moc_artist, INFO_MOC)
3977   END OBJ_THREAD(moc_song, INFO_MOC)
3978   END OBJ_THREAD(moc_album, INFO_MOC)
3979   END OBJ_THREAD(moc_totaltime, INFO_MOC)
3980   END OBJ_THREAD(moc_timeleft, INFO_MOC)
3981   END OBJ_THREAD(moc_curtime, INFO_MOC)
3982   END OBJ_THREAD(moc_bitrate, INFO_MOC)
3983   END OBJ_THREAD(moc_rate, INFO_MOC)
3984 #endif /* MOC */
3985 #ifdef XMMS2
3986         END OBJ(xmms2_artist, INFO_XMMS2)
3987         END OBJ(xmms2_album, INFO_XMMS2)
3988         END OBJ(xmms2_title, INFO_XMMS2)
3989         END OBJ(xmms2_genre, INFO_XMMS2)
3990         END OBJ(xmms2_comment, INFO_XMMS2)
3991         END OBJ(xmms2_url, INFO_XMMS2)
3992         END OBJ(xmms2_tracknr, INFO_XMMS2)
3993         END OBJ(xmms2_bitrate, INFO_XMMS2)
3994         END OBJ(xmms2_date, INFO_XMMS2)
3995         END OBJ(xmms2_id, INFO_XMMS2)
3996         END OBJ(xmms2_duration, INFO_XMMS2)
3997         END OBJ(xmms2_elapsed, INFO_XMMS2)
3998         END OBJ(xmms2_size, INFO_XMMS2)
3999         END OBJ(xmms2_status, INFO_XMMS2)
4000         END OBJ(xmms2_percent, INFO_XMMS2)
4001         END OBJ(xmms2_bar, INFO_XMMS2)
4002                 scan_bar(arg, &obj->data.pair.a, &obj->data.pair.b);
4003         END OBJ(xmms2_smart, INFO_XMMS2)
4004         END OBJ(xmms2_playlist, INFO_XMMS2)
4005         END OBJ(xmms2_timesplayed, INFO_XMMS2)
4006         END OBJ(if_xmms2_connected, INFO_XMMS2)
4007                 if (blockdepth >= MAX_IF_BLOCK_DEPTH) {
4008                         CRIT_ERR("MAX_IF_BLOCK_DEPTH exceeded");
4009                 }
4010                 blockstart[blockdepth] = object_count;
4011                 obj->data.ifblock.pos = object_count + 2;
4012                 blockdepth++;
4013 #endif
4014 #ifdef AUDACIOUS
4015         END OBJ(audacious_status, INFO_AUDACIOUS)
4016         END OBJ(audacious_title, INFO_AUDACIOUS)
4017                 if (arg) {
4018                         sscanf(arg, "%d", &info.audacious.max_title_len);
4019                         if (info.audacious.max_title_len > 0) {
4020                                 info.audacious.max_title_len++;
4021                         } else {
4022                                 CRIT_ERR("audacious_title: invalid length argument");
4023                         }
4024                 }
4025         END OBJ(audacious_length, INFO_AUDACIOUS)
4026         END OBJ(audacious_length_seconds, INFO_AUDACIOUS)
4027         END OBJ(audacious_position, INFO_AUDACIOUS)
4028         END OBJ(audacious_position_seconds, INFO_AUDACIOUS)
4029         END OBJ(audacious_bitrate, INFO_AUDACIOUS)
4030         END OBJ(audacious_frequency, INFO_AUDACIOUS)
4031         END OBJ(audacious_channels, INFO_AUDACIOUS)
4032         END OBJ(audacious_filename, INFO_AUDACIOUS)
4033         END OBJ(audacious_playlist_length, INFO_AUDACIOUS)
4034         END OBJ(audacious_playlist_position, INFO_AUDACIOUS)
4035         END OBJ(audacious_main_volume, INFO_AUDACIOUS)
4036         END OBJ(audacious_bar, INFO_AUDACIOUS)
4037                 scan_bar(arg, &obj->a, &obj->b);
4038 #endif
4039 #ifdef BMPX
4040         END OBJ(bmpx_title, INFO_BMPX)
4041                 memset(&(info.bmpx), 0, sizeof(struct bmpx_s));
4042         END OBJ(bmpx_artist, INFO_BMPX)
4043                 memset(&(info.bmpx), 0, sizeof(struct bmpx_s));
4044         END OBJ(bmpx_album, INFO_BMPX)
4045                 memset(&(info.bmpx), 0, sizeof(struct bmpx_s));
4046         END OBJ(bmpx_track, INFO_BMPX)
4047                 memset(&(info.bmpx), 0, sizeof(struct bmpx_s));
4048         END OBJ(bmpx_uri, INFO_BMPX)
4049                 memset(&(info.bmpx), 0, sizeof(struct bmpx_s));
4050         END OBJ(bmpx_bitrate, INFO_BMPX)
4051                 memset(&(info.bmpx), 0, sizeof(struct bmpx_s));
4052 #endif
4053 #ifdef EVE
4054         END OBJ(eve, 0)
4055                 if(arg) {
4056                         int argc;
4057                         char *userid = (char *) malloc(20 * sizeof(char));
4058                         char *apikey = (char *) malloc(64 * sizeof(char));
4059                         char *charid = (char *) malloc(20 * sizeof(char));
4060
4061                         argc = sscanf(arg, "%20s %64s %20s", userid, apikey, charid);
4062                         obj->data.eve.charid = charid;
4063                         obj->data.eve.userid = userid;
4064                         obj->data.eve.apikey = apikey;
4065
4066                         init_eve();
4067                 } else {
4068                         CRIT_ERR("eve needs arguments: <userid> <apikey> <characterid>");
4069                 }
4070 #endif
4071 #ifdef RSS
4072         END OBJ(rss, 0)
4073                 if (arg) {
4074                         int argc, delay, act_par;
4075                         char *uri = (char *) malloc(128 * sizeof(char));
4076                         char *action = (char *) malloc(64 * sizeof(char));
4077
4078                         argc = sscanf(arg, "%127s %d %63s %d", uri, &delay, action,
4079                                         &act_par);
4080                         obj->data.rss.uri = uri;
4081                         obj->data.rss.delay = delay;
4082                         obj->data.rss.action = action;
4083                         obj->data.rss.act_par = act_par;
4084
4085                         init_rss_info();
4086                 } else {
4087                         CRIT_ERR("rss needs arguments: <uri> <delay in minutes> <action> "
4088                                         "[act_par]");
4089                 }
4090 #endif
4091 #ifdef HDDTEMP
4092         END OBJ(hddtemp, 0)
4093                 if (scan_hddtemp(arg, &obj->data.hddtemp.dev,
4094                                  &obj->data.hddtemp.addr, &obj->data.hddtemp.port)) {
4095                         ERR("hddtemp needs arguments");
4096                         obj->type = OBJ_text;
4097                         obj->data.s = strndup("${hddtemp}", text_buffer_size);
4098                         obj->data.hddtemp.update_time = 0;
4099                 } else
4100                         obj->data.hddtemp.temp = NULL;
4101 #endif
4102 #ifdef TCP_PORT_MONITOR
4103         END OBJ(tcp_portmon, INFO_TCP_PORT_MONITOR)
4104                 int argc, port_begin, port_end, item, connection_index;
4105                 char itembuf[32];
4106
4107                 memset(itembuf, 0, sizeof(itembuf));
4108                 connection_index = 0;
4109                 /* massive argument checking */
4110                 if (!arg) {
4111                         CRIT_ERR("tcp_portmon: needs arguments");
4112                 }
4113                 argc = sscanf(arg, "%d %d %31s %d", &port_begin, &port_end, itembuf,
4114                                 &connection_index);
4115                 if ((argc != 3) && (argc != 4)) {
4116                         CRIT_ERR("tcp_portmon: requires 3 or 4 arguments");
4117                 }
4118                 if ((port_begin < 1) || (port_begin > 65535) || (port_end < 1)
4119                                 || (port_end > 65535)) {
4120                         CRIT_ERR("tcp_portmon: port values must be from 1 to 65535");
4121                 }
4122                 if (port_begin > port_end) {
4123                         CRIT_ERR("tcp_portmon: starting port must be <= ending port");
4124                 }
4125                 if (strncmp(itembuf, "count", 31) == EQUAL) {
4126                         item = COUNT;
4127                 } else if (strncmp(itembuf, "rip", 31) == EQUAL) {
4128                         item = REMOTEIP;
4129                 } else if (strncmp(itembuf, "rhost", 31) == EQUAL) {
4130                         item = REMOTEHOST;
4131                 } else if (strncmp(itembuf, "rport", 31) == EQUAL) {
4132                         item = REMOTEPORT;
4133                 } else if (strncmp(itembuf, "rservice", 31) == EQUAL) {
4134                         item = REMOTESERVICE;
4135                 } else if (strncmp(itembuf, "lip", 31) == EQUAL) {
4136                         item = LOCALIP;
4137                 } else if (strncmp(itembuf, "lhost", 31) == EQUAL) {
4138                         item = LOCALHOST;
4139                 } else if (strncmp(itembuf, "lport", 31) == EQUAL) {
4140                         item = LOCALPORT;
4141                 } else if (strncmp(itembuf, "lservice", 31) == EQUAL) {
4142                         item = LOCALSERVICE;
4143                 } else {
4144                         CRIT_ERR("tcp_portmon: invalid item specified");
4145                 }
4146                 if ((argc == 3) && (item != COUNT)) {
4147                         CRIT_ERR("tcp_portmon: 3 argument form valid only for \"count\" "
4148                                         "item");
4149                 }
4150                 if ((argc == 4) && (connection_index < 0)) {
4151                         CRIT_ERR("tcp_portmon: connection index must be non-negative");
4152                 }
4153                 /* ok, args looks good. save the text object data */
4154                 obj->data.tcp_port_monitor.port_range_begin = (in_port_t) port_begin;
4155                 obj->data.tcp_port_monitor.port_range_end = (in_port_t) port_end;
4156                 obj->data.tcp_port_monitor.item = item;
4157                 obj->data.tcp_port_monitor.connection_index = connection_index;
4158
4159                 /* if the port monitor collection hasn't been created,
4160                  * we must create it */
4161                 if (!info.p_tcp_port_monitor_collection) {
4162                         info.p_tcp_port_monitor_collection =
4163                                 create_tcp_port_monitor_collection();
4164                         if (!info.p_tcp_port_monitor_collection) {
4165                                 CRIT_ERR("tcp_portmon: unable to create port monitor "
4166                                                 "collection");
4167                         }
4168                 }
4169
4170                 /* if a port monitor for this port does not exist,
4171                  * create one and add it to the collection */
4172                 if (find_tcp_port_monitor(info.p_tcp_port_monitor_collection,
4173                                         port_begin, port_end) == NULL) {
4174                         tcp_port_monitor_t *p_monitor = create_tcp_port_monitor(port_begin,
4175                                         port_end, &tcp_port_monitor_args);
4176
4177                         if (!p_monitor) {
4178                                 CRIT_ERR("tcp_portmon: unable to create port monitor");
4179                         }
4180                         /* add the newly created monitor to the collection */
4181                         if (insert_tcp_port_monitor_into_collection(
4182                                                 info.p_tcp_port_monitor_collection, p_monitor) != 0) {
4183                                 CRIT_ERR("tcp_portmon: unable to add port monitor to "
4184                                                 "collection");
4185                         }
4186                 }
4187 #endif
4188         END OBJ(entropy_avail, INFO_ENTROPY)
4189                 END OBJ(entropy_poolsize, INFO_ENTROPY)
4190                 END OBJ(entropy_bar, INFO_ENTROPY)
4191                 scan_bar(arg, &obj->a, &obj->b);
4192         END OBJ(scroll, 0)
4193                 int n1, n2;
4194
4195                 obj->data.scroll.step = 1;
4196                 if (arg && sscanf(arg, "%u %n", &obj->data.scroll.show, &n1) > 0) {
4197                         if (sscanf(arg + n1, "%u %n", &obj->data.scroll.step, &n2) > 0)
4198                                 n1 += n2;
4199                         obj->data.scroll.text = strndup(arg + n1, text_buffer_size);
4200                         obj->data.scroll.start = 0;
4201                 } else {
4202                         CRIT_ERR("scroll needs arguments: <length> [<step>] <text>");
4203                 }
4204 #ifdef NVIDIA
4205         END OBJ(nvidia, 0)
4206                 if (!arg) {
4207                         CRIT_ERR("nvidia needs an argument\n");
4208                 } else if (set_nvidia_type(&obj->data.nvidia, arg)) {
4209                         CRIT_ERR("nvidia: invalid argument"
4210                                  " specified: '%s'\n", arg);
4211                 }
4212 #endif /* NVIDIA */
4213         END {
4214                 char buf[256];
4215
4216                 ERR("unknown variable %s", s);
4217                 obj->type = OBJ_text;
4218                 snprintf(buf, 256, "${%s}", s);
4219                 obj->data.s = strndup(buf, text_buffer_size);
4220         }
4221 #undef OBJ
4222
4223         return obj;
4224 }
4225
4226 static struct text_object *create_plain_text(const char *s)
4227 {
4228         struct text_object *obj;
4229
4230         if (s == NULL || *s == '\0') {
4231                 return NULL;
4232         }
4233
4234         obj = new_text_object_internal();
4235
4236         obj->type = OBJ_text;
4237         obj->data.s = strndup(s, text_buffer_size);
4238         return obj;
4239 }
4240
4241 /* backslash_escape - do the actual substitution task for template objects
4242  *
4243  * The field templates is used for substituting the \N occurences. Set it to
4244  * NULL to leave them as they are.
4245  */
4246 static char *backslash_escape(const char *src, char **templates, unsigned int template_count)
4247 {
4248         char *src_dup;
4249         const char *p;
4250         unsigned int dup_idx = 0, dup_len;
4251
4252         dup_len = strlen(src);
4253         src_dup = malloc(dup_len * sizeof(char));
4254
4255         p = src;
4256         while (*p) {
4257                 switch (*p) {
4258                 case '\\':
4259                         if (!*(p + 1))
4260                                 break;
4261                         if (*(p + 1) == '\\') {
4262                                 src_dup[dup_idx++] = '\\';
4263                                 p++;
4264                         } else if (*(p + 1) == ' ') {
4265                                 src_dup[dup_idx++] = ' ';
4266                                 p++;
4267                         } else if (*(p + 1) == 'n') {
4268                                 src_dup[dup_idx++] = '\n';
4269                                 p++;
4270                         } else if (templates) {
4271                                 unsigned int tmpl_num;
4272                                 int digits;
4273                                 if ((sscanf(p + 1, "%u%n", &tmpl_num, &digits) <= 0) ||
4274                                     (tmpl_num > template_count))
4275                                         break;
4276                                 dup_len += strlen(templates[tmpl_num - 1]);
4277                                 src_dup = realloc(src_dup, dup_len * sizeof(char));
4278                                 sprintf(src_dup + dup_idx, "%s", templates[tmpl_num - 1]);
4279                                 dup_idx += strlen(templates[tmpl_num - 1]);
4280                                 p += digits;
4281                         }
4282                         break;
4283                 default:
4284                         src_dup[dup_idx++] = *p;
4285                         break;
4286                 }
4287                 p++;
4288         }
4289         src_dup[dup_idx] = '\0';
4290         src_dup = realloc(src_dup, (strlen(src_dup) + 1) * sizeof(char));
4291         return src_dup;
4292 }
4293
4294 /* handle_template_object - core logic of the template object
4295  *
4296  * use config variables like this:
4297  * template1 = "$\1\2"
4298  * template2 = "\1: ${fs_bar 4,100 \2} ${fs_used \2} / ${fs_size \2}"
4299  *
4300  * and use them like this:
4301  * ${template1 node name}
4302  * ${template2 root /}
4303  * ${template2 cdrom /mnt/cdrom}
4304  */
4305 static char *handle_template(const char *tmpl, const char *args)
4306 {
4307         char *args_dup, *p, *p_old;
4308         char **argsp = NULL;
4309         unsigned int argcnt = 0, template_idx, i;
4310         char *eval_text;
4311
4312         if ((sscanf(tmpl, "template%u", &template_idx) != 1) ||
4313             (template_idx > 9))
4314                 return NULL;
4315
4316         args_dup = strdup(args);
4317         p = args_dup;
4318         while (*p) {
4319                 while (*p && (*p == ' ' && *(p - 1) != '\\'))
4320                         p++;
4321                 if (*(p - 1) == '\\')
4322                         p--;
4323                 p_old = p;
4324                 while (*p && (*p != ' ' || *(p - 1) == '\\'))
4325                         p++;
4326                 if (*p) {
4327                         (*p) = '\0';
4328                         p++;
4329                 }
4330                 argsp = realloc(argsp, ++argcnt * sizeof(char *));
4331                 argsp[argcnt - 1] = p_old;
4332         }
4333         for (i = 0; i < argcnt; i++) {
4334                 char *tmp;
4335                 tmp = backslash_escape(argsp[i], NULL, 0);
4336                 DBGP2("%s: substituted arg '%s' to '%s'", tmpl, argsp[i], tmp);
4337                 argsp[i] = tmp;
4338         }
4339
4340         eval_text = backslash_escape(template[template_idx], argsp, argcnt);
4341         DBGP("substituted %s, output is '%s'", tmpl, eval_text);
4342         free(args_dup);
4343         for (i = 0; i < argcnt; i++)
4344                 free(argsp[i]);
4345         free(argsp);
4346         return eval_text;
4347 }
4348
4349 static char *find_and_replace_templates(const char *inbuf)
4350 {
4351         char *outbuf, *indup, *p, *o, *templ, *args, *tmpl_out;
4352         int stack, outlen;
4353
4354         outlen = strlen(inbuf) + 1;
4355         o = outbuf = calloc(outlen, sizeof(char));
4356         memset(outbuf, 0, outlen * sizeof(char));
4357
4358         p = indup = strdup(inbuf);
4359         while (*p) {
4360                 while (*p && *p != '$')
4361                         *(o++) = *(p++);
4362
4363                 if (!(*p))
4364                         break;
4365
4366                 if (strncmp(p, "$template", 9) && strncmp(p, "${template", 10)) {
4367                         *(o++) = *(p++);
4368                         continue;
4369                 }
4370
4371                 if (*(p + 1) == '{') {
4372                         templ = p + 2;
4373                         while (*p != ' ')
4374                                 p++;
4375                         *(p++) = '\0';
4376                         args = p;
4377                         stack = 1;
4378                         while (stack > 0) {
4379                                 p++;
4380                                 if (*p == '{')
4381                                         stack++;
4382                                 else if (*p == '}')
4383                                         stack--;
4384                         }
4385                         *(p++) = '\0';
4386                 } else {
4387                         templ = p + 1;
4388                         while (*p != ' ')
4389                                 p++;
4390                         *(p++) = '\0';
4391                         args = NULL;
4392                 }
4393                 tmpl_out = handle_template(templ, args);
4394                 if (tmpl_out) {
4395                         outlen += strlen(tmpl_out);
4396                         outbuf = realloc(outbuf, outlen * sizeof(char));
4397                         strcat (outbuf, tmpl_out);
4398                         free(tmpl_out);
4399                         o = outbuf + strlen(outbuf);
4400                 } else {
4401                         ERR("failed to handle template '%s' with args '%s'", templ, args);
4402                 }
4403         }
4404         *o = '\0';
4405         outbuf = realloc(outbuf, (strlen(outbuf) + 1) * sizeof(char));
4406         free(indup);
4407         return outbuf;
4408 }
4409
4410 static int text_contains_templates(const char *text)
4411 {
4412         if (strcasestr(text, "${template") != NULL)
4413                 return 1;
4414         if (strcasestr(text, "$template") != NULL)
4415                 return 1;
4416         return 0;
4417 }
4418
4419 static struct text_object_list *extract_variable_text_internal(const char *const_p, char allow_threaded)
4420 {
4421         struct text_object_list *retval;
4422         struct text_object *obj;
4423         char *p, *s, *orig_p;
4424         long line;
4425
4426         p = strndup(const_p, max_user_text - 1);
4427         while (text_contains_templates(p)) {
4428                 char *tmp;
4429                 tmp = find_and_replace_templates(p);
4430                 free(p);
4431                 p = tmp;
4432         }
4433         s = orig_p = p;
4434
4435         if (strcmp(p, const_p)) {
4436                 DBGP("replaced all templates in text: input is\n'%s'\noutput is\n'%s'", const_p, p);
4437         } else {
4438                 DBGP("no templates to replace");
4439         }
4440
4441         retval = malloc(sizeof(struct text_object_list));
4442         memset(retval, 0, sizeof(struct text_object_list));
4443         retval->text_object_count = 0;
4444
4445         line = global_text_lines;
4446
4447         while (*p) {
4448                 if (*p == '\n') {
4449                         line++;
4450                 }
4451                 if (*p == '$') {
4452                         *p = '\0';
4453                         obj = create_plain_text(s);
4454                         if (obj != NULL) {
4455                                 // allocate memory for the object
4456                                 retval->text_objects = realloc(retval->text_objects,
4457                                                 sizeof(struct text_object) *
4458                                                 (retval->text_object_count + 1));
4459                                 // assign the new object to the end of the list.
4460                                 memcpy(&retval->text_objects[retval->text_object_count++], obj,
4461                                                 sizeof(struct text_object));
4462                                 free(obj);
4463                         }
4464                         *p = '$';
4465                         p++;
4466                         s = p;
4467
4468                         if (*p != '$') {
4469                                 char buf[256];
4470                                 const char *var;
4471                                 unsigned int len;
4472
4473                                 /* variable is either $foo or ${foo} */
4474                                 if (*p == '{') {
4475                                         unsigned int brl = 1, brr = 0;
4476
4477                                         p++;
4478                                         s = p;
4479                                         while (*p && brl != brr) {
4480                                                 if (*p == '{') {
4481                                                         brl++;
4482                                                 }
4483                                                 if (*p == '}') {
4484                                                         brr++;
4485                                                 }
4486                                                 p++;
4487                                         }
4488                                         p--;
4489                                 } else {
4490                                         s = p;
4491                                         if (*p == '#') {
4492                                                 p++;
4493                                         }
4494                                         while (*p && (isalnum((int) *p) || *p == '_')) {
4495                                                 p++;
4496                                         }
4497                                 }
4498
4499                                 /* copy variable to buffer */
4500                                 len = (p - s > 255) ? 255 : (p - s);
4501                                 strncpy(buf, s, len);
4502                                 buf[len] = '\0';
4503
4504                                 if (*p == '}') {
4505                                         p++;
4506                                 }
4507                                 s = p;
4508
4509                                 var = getenv(buf);
4510
4511                                 /* if variable wasn't found in environment, use some special */
4512                                 if (!var) {
4513                                         char *tmp_p;
4514                                         char *arg = 0;
4515
4516                                         /* split arg */
4517                                         if (strchr(buf, ' ')) {
4518                                                 arg = strchr(buf, ' ');
4519                                                 *arg = '\0';
4520                                                 arg++;
4521                                                 while (isspace((int) *arg)) {
4522                                                         arg++;
4523                                                 }
4524                                                 if (!*arg) {
4525                                                         arg = 0;
4526                                                 }
4527                                         }
4528
4529                                         /* lowercase variable name */
4530                                         tmp_p = buf;
4531                                         while (*tmp_p) {
4532                                                 *tmp_p = tolower(*tmp_p);
4533                                                 tmp_p++;
4534                                         }
4535
4536                                         obj = construct_text_object(buf, arg,
4537                                                         retval->text_object_count, retval->text_objects, line, allow_threaded);
4538                                         if (obj != NULL) {
4539                                                 // allocate memory for the object
4540                                                 retval->text_objects = realloc(retval->text_objects,
4541                                                                 sizeof(struct text_object) *
4542                                                                 (retval->text_object_count + 1));
4543                                                 // assign the new object to the end of the list.
4544                                                 memcpy(
4545                                                                 &retval->text_objects[retval->text_object_count++],
4546                                                                 obj, sizeof(struct text_object));
4547                                                 free(obj);
4548                                         }
4549                                 }
4550                                 continue;
4551                         } else {
4552                                 obj = create_plain_text("$");
4553                                 if (obj != NULL) {
4554                                         // allocate memory for the object
4555                                         retval->text_objects = realloc(retval->text_objects,
4556                                                         sizeof(struct text_object) *
4557                                                         (retval->text_object_count + 1));
4558                                         // assign the new object to the end of the list.
4559                                         memcpy(&retval->text_objects[retval->text_object_count++],
4560                                                         obj, sizeof(struct text_object));
4561                                         free(obj);
4562                                 }
4563                         }
4564                 }
4565                 p++;
4566         }
4567         obj = create_plain_text(s);
4568         if (obj != NULL) {
4569                 // allocate memory for the object
4570                 retval->text_objects = realloc(retval->text_objects,
4571                                 sizeof(struct text_object) * (retval->text_object_count + 1));
4572                 // assign the new object to the end of the list.
4573                 memcpy(&retval->text_objects[retval->text_object_count++], obj,
4574                                 sizeof(struct text_object));
4575                 free(obj);
4576         }
4577
4578         if (blockdepth) {
4579                 ERR("one or more $endif's are missing");
4580         }
4581
4582         free(orig_p);
4583         return retval;
4584 }
4585
4586 static void extract_variable_text(const char *p)
4587 {
4588         free_text_objects(global_text_object_list, 1);
4589         free(global_text_object_list);
4590         if (tmpstring1) {
4591                 free(tmpstring1);
4592                 tmpstring1 = 0;
4593         }
4594         if (tmpstring2) {
4595                 free(tmpstring2);
4596                 tmpstring2 = 0;
4597         }
4598         if (text_buffer) {
4599                 free(text_buffer);
4600                 text_buffer = 0;
4601         }
4602
4603         global_text_object_list = extract_variable_text_internal(p, 1);
4604 }
4605
4606 struct text_object_list *parse_conky_vars(char *txt, char *p, struct information *cur)
4607 {
4608         struct text_object_list *object_list =
4609                 extract_variable_text_internal(txt, 0);
4610
4611         generate_text_internal(p, max_user_text, object_list, cur);
4612         return object_list;
4613 }
4614
4615 /* Allows reading from a FIFO (i.e., /dev/xconsole).
4616  * The file descriptor is set to non-blocking which makes this possible.
4617  *
4618  * FIXME: Since lseek cannot seek a file descriptor long lines will break. */
4619 static void tail_pipe(struct text_object *obj, char *dst, size_t dst_size)
4620 {
4621 #define TAIL_PIPE_BUFSIZE       4096
4622         int lines = 0;
4623         int line_len = 0;
4624         int last_line = 0;
4625         int fd = obj->data.tail.fd;
4626
4627         while (1) {
4628                 char buf[TAIL_PIPE_BUFSIZE];
4629                 ssize_t len = read(fd, buf, sizeof(buf));
4630                 int i;
4631
4632                 if (len == -1) {
4633                         if (errno != EAGAIN) {
4634                                 strcpy(obj->data.tail.buffer, "Logfile Read Error");
4635                                 snprintf(dst, dst_size, "Logfile Read Error");
4636                         }
4637
4638                         break;
4639                 } else if (len == 0) {
4640                         strcpy(obj->data.tail.buffer, "Logfile Empty");
4641                         snprintf(dst, dst_size, "Logfile Empty");
4642                         break;
4643                 }
4644
4645                 for (line_len = 0, i = 0; i < len; i++) {
4646                         int pos = 0;
4647                         char *p;
4648
4649                         if (buf[i] == '\n') {
4650                                 lines++;
4651
4652                                 if (obj->data.tail.readlines > 0) {
4653                                         int n;
4654                                         int olines = 0;
4655                                         int first_line = 0;
4656
4657                                         for (n = 0; obj->data.tail.buffer[n]; n++) {
4658                                                 if (obj->data.tail.buffer[n] == '\n') {
4659                                                         if (!first_line) {
4660                                                                 first_line = n + 1;
4661                                                         }
4662
4663                                                         if (++olines < obj->data.tail.wantedlines) {
4664                                                                 pos = n + 1;
4665                                                                 continue;
4666                                                         }
4667
4668                                                         n++;
4669                                                         p = obj->data.tail.buffer + first_line;
4670                                                         pos = n - first_line;
4671                                                         memmove(obj->data.tail.buffer,
4672                                                                         obj->data.tail.buffer + first_line, strlen(p));
4673                                                         obj->data.tail.buffer[pos] = 0;
4674                                                         break;
4675                                                 }
4676                                         }
4677                                 }
4678
4679                                 p = buf + last_line;
4680                                 line_len++;
4681                                 memcpy(&(obj->data.tail.buffer[pos]), p, line_len);
4682                                 obj->data.tail.buffer[pos + line_len] = 0;
4683                                 last_line = i + 1;
4684                                 line_len = 0;
4685                                 obj->data.tail.readlines = lines;
4686                                 continue;
4687                         }
4688
4689                         line_len++;
4690                 }
4691         }
4692
4693         snprintf(dst, dst_size, "%s", obj->data.tail.buffer);
4694 }
4695
4696 static inline struct mail_s *ensure_mail_thread(struct text_object *obj,
4697                 void *thread(void *), const char *text)
4698 {
4699         if (obj->global_mode && info.mail) {
4700                 // this means we use info
4701                 if (!info.mail->p_timed_thread) {
4702                         info.mail->p_timed_thread =
4703                                 timed_thread_create(thread,
4704                                                 (void *) info.mail, info.mail->interval * 1000000);
4705                         if (!info.mail->p_timed_thread) {
4706                                 ERR("Error creating %s timed thread", text);
4707                         }
4708                         timed_thread_register(info.mail->p_timed_thread,
4709                                         &info.mail->p_timed_thread);
4710                         if (timed_thread_run(info.mail->p_timed_thread)) {
4711                                 ERR("Error running %s timed thread", text);
4712                         }
4713                 }
4714                 return info.mail;
4715         } else if (obj->data.mail) {
4716                 // this means we use obj
4717                 if (!obj->data.mail->p_timed_thread) {
4718                         obj->data.mail->p_timed_thread =
4719                                 timed_thread_create(thread,
4720                                                 (void *) obj->data.mail,
4721                                                 obj->data.mail->interval * 1000000);
4722                         if (!obj->data.mail->p_timed_thread) {
4723                                 ERR("Error creating %s timed thread", text);
4724                         }
4725                         timed_thread_register(obj->data.mail->p_timed_thread,
4726                                         &obj->data.mail->p_timed_thread);
4727                         if (timed_thread_run(obj->data.mail->p_timed_thread)) {
4728                                 ERR("Error running %s timed thread", text);
4729                         }
4730                 }
4731                 return obj->data.mail;
4732         } else if (!obj->a) {
4733                 // something is wrong, warn once then stop
4734                 ERR("Theres a problem with your %s_unseen settings.  "
4735                                 "Check that the global %s settings are defined "
4736                                 "properly (line %li).", global_text, global_text, obj->line);
4737                 obj->a++;
4738         }
4739         return NULL;
4740 }
4741
4742 char *format_time(unsigned long timeval, const int width)
4743 {
4744         char buf[10];
4745         unsigned long nt;       // narrow time, for speed on 32-bit
4746         unsigned cc;            // centiseconds
4747         unsigned nn;            // multi-purpose whatever
4748
4749         nt = timeval;
4750         cc = nt % 100;          // centiseconds past second
4751         nt /= 100;                      // total seconds
4752         nn = nt % 60;           // seconds past the minute
4753         nt /= 60;                       // total minutes
4754         if (width >= snprintf(buf, sizeof buf, "%lu:%02u.%02u",
4755                                 nt, nn, cc)) {
4756                 return strndup(buf, text_buffer_size);
4757         }
4758         if (width >= snprintf(buf, sizeof buf, "%lu:%02u", nt, nn)) {
4759                 return strndup(buf, text_buffer_size);
4760         }
4761         nn = nt % 60;           // minutes past the hour
4762         nt /= 60;                       // total hours
4763         if (width >= snprintf(buf, sizeof buf, "%lu,%02u", nt, nn)) {
4764                 return strndup(buf, text_buffer_size);
4765         }
4766         nn = nt;                        // now also hours
4767         if (width >= snprintf(buf, sizeof buf, "%uh", nn)) {
4768                 return strndup(buf, text_buffer_size);
4769         }
4770         nn /= 24;                       // now days
4771         if (width >= snprintf(buf, sizeof buf, "%ud", nn)) {
4772                 return strndup(buf, text_buffer_size);
4773         }
4774         nn /= 7;                        // now weeks
4775         if (width >= snprintf(buf, sizeof buf, "%uw", nn)) {
4776                 return strndup(buf, text_buffer_size);
4777         }
4778         // well shoot, this outta' fit...
4779         return strndup("<inf>", text_buffer_size);
4780 }
4781
4782 //remove backspaced chars, example: "dog^H^H^Hcat" becomes "cat"
4783 //string has to end with \0 and it's length should fit in a int
4784 #define BACKSPACE 8
4785 void remove_deleted_chars(char *string){
4786         int i = 0;
4787         while(string[i] != 0){
4788                 if(string[i] == BACKSPACE){
4789                         if(i != 0){
4790                                 strcpy( &(string[i-1]), &(string[i+1]) );
4791                                 i--;
4792                         }else strcpy( &(string[i]), &(string[i+1]) ); //necessary for ^H's at the start of a string
4793                 }else i++;
4794         }
4795 }
4796
4797 static inline void format_media_player_time(char *buf, const int size,
4798                 int seconds)
4799 {
4800         int days, hours, minutes;
4801
4802         days = seconds / (24 * 60 * 60);
4803         seconds %= (24 * 60 * 60);
4804         hours = seconds / (60 * 60);
4805         seconds %= (60 * 60);
4806         minutes = seconds / 60;
4807         seconds %= 60;
4808
4809         if (days > 0) {
4810                 snprintf(buf, size, "%i days %i:%02i:%02i", days,
4811                                 hours, minutes, seconds);
4812         } else if (hours > 0) {
4813                 snprintf(buf, size, "%i:%02i:%02i", hours, minutes,
4814                                 seconds);
4815         } else {
4816                 snprintf(buf, size, "%i:%02i", minutes, seconds);
4817         }
4818 }
4819
4820 static inline double get_barnum(char *buf)
4821 {
4822         char *c = buf;
4823         double barnum;
4824
4825         while (*c) {
4826                 if (*c == '\001') {
4827                         *c = ' ';
4828                 }
4829                 c++;
4830         }
4831
4832         if (sscanf(buf, "%lf", &barnum) == 0) {
4833                 ERR("reading execbar value failed (perhaps it's not the "
4834                                 "correct format?)");
4835                 return -1;
4836         }
4837         if (barnum > 100.0 || barnum < 0.0) {
4838                 ERR("your execbar value is not between 0 and 100, "
4839                                 "therefore it will be ignored");
4840                 return -1;
4841         }
4842         return barnum;
4843 }
4844
4845 static void generate_text_internal(char *p, int p_max_size,
4846                 struct text_object_list *text_object_list,
4847                 struct information *cur)
4848 {
4849         unsigned int i;
4850
4851 #ifdef HAVE_ICONV
4852         char buff_in[p_max_size];
4853         buff_in[0] = 0;
4854         iconv_converting = 0;
4855 #endif
4856
4857         p[0] = 0;
4858         for (i = 0; i < text_object_list->text_object_count; i++) {
4859                 struct text_object *obj = &(text_object_list->text_objects[i]);
4860
4861                 if (p_max_size < 1) {
4862                         break;
4863                 };
4864
4865 #define OBJ(a) break; case OBJ_##a:
4866
4867                 switch (obj->type) {
4868                         default:
4869                                 ERR("not implemented obj type %d", obj->type);
4870 #ifndef __OpenBSD__
4871                         OBJ(acpitemp) {
4872                                 temp_print(p, p_max_size, get_acpi_temperature(obj->data.i), TEMP_CELSIUS);
4873                         }
4874 #endif /* !__OpenBSD__ */
4875                         OBJ(freq) {
4876                                 if (obj->a) {
4877                                         obj->a = get_freq(p, p_max_size, "%.0f", 1,
4878                                                         obj->data.cpu_index);
4879                                 }
4880                         }
4881                         OBJ(freq_g) {
4882                                 if (obj->a) {
4883 #ifndef __OpenBSD__
4884                                         obj->a = get_freq(p, p_max_size, "%'.2f", 1000,
4885                                                         obj->data.cpu_index);
4886 #else
4887                                         /* OpenBSD has no such flag (SUSv2) */
4888                                         obj->a = get_freq(p, p_max_size, "%.2f", 1000,
4889                                                         obj->data.cpu_index);
4890 #endif
4891                                 }
4892                         }
4893 #if defined(__linux__)
4894                         OBJ(voltage_mv) {
4895                                 if (obj->a) {
4896                                         obj->a = get_voltage(p, p_max_size, "%.0f", 1,
4897                                                         obj->data.cpu_index);
4898                                 }
4899                         }
4900                         OBJ(voltage_v) {
4901                                 if (obj->a) {
4902                                         obj->a = get_voltage(p, p_max_size, "%'.3f", 1000,
4903                                                         obj->data.cpu_index);
4904                                 }
4905                         }
4906
4907 #ifdef HAVE_IWLIB
4908                         OBJ(wireless_essid) {
4909                                 snprintf(p, p_max_size, "%s", obj->data.net->essid);
4910                         }
4911                         OBJ(wireless_mode) {
4912                                 snprintf(p, p_max_size, "%s", obj->data.net->mode);
4913                         }
4914                         OBJ(wireless_bitrate) {
4915                                 snprintf(p, p_max_size, "%s", obj->data.net->bitrate);
4916                         }
4917                         OBJ(wireless_ap) {
4918                                 snprintf(p, p_max_size, "%s", obj->data.net->ap);
4919                         }
4920                         OBJ(wireless_link_qual) {
4921                                 spaced_print(p, p_max_size, "%d", 4, "wireless_link_qual",
4922                                                 obj->data.net->link_qual);
4923                         }
4924                         OBJ(wireless_link_qual_max) {
4925                                 spaced_print(p, p_max_size, "%d", 4,
4926                                                 "wireless_link_qual_max", obj->data.net->link_qual_max);
4927                         }
4928                         OBJ(wireless_link_qual_perc) {
4929                                 if (obj->data.net->link_qual_max > 0) {
4930                                         spaced_print(p, p_max_size, "%.0f", 5,
4931                                                         "wireless_link_qual_perc",
4932                                                         (double) obj->data.net->link_qual /
4933                                                         obj->data.net->link_qual_max * 100);
4934                                 } else {
4935                                         spaced_print(p, p_max_size, "unk", 5,
4936                                                         "wireless_link_qual_perc");
4937                                 }
4938                         }
4939                         OBJ(wireless_link_bar) {
4940                                 new_bar(p, obj->a, obj->b, ((double) obj->data.net->link_qual /
4941                                                         obj->data.net->link_qual_max) * 255.0);
4942                         }
4943 #endif /* HAVE_IWLIB */
4944
4945 #endif /* __linux__ */
4946
4947 #ifndef __OpenBSD__
4948                         OBJ(adt746xcpu) {
4949                                 get_adt746x_cpu(p, p_max_size);
4950                         }
4951                         OBJ(adt746xfan) {
4952                                 get_adt746x_fan(p, p_max_size);
4953                         }
4954                         OBJ(acpifan) {
4955                                 get_acpi_fan(p, p_max_size);
4956                         }
4957                         OBJ(acpiacadapter) {
4958                                 get_acpi_ac_adapter(p, p_max_size);
4959                         }
4960                         OBJ(battery) {
4961                                 get_battery_stuff(p, p_max_size, obj->data.s, BATTERY_STATUS);
4962                         }
4963                         OBJ(battery_time) {
4964                                 get_battery_stuff(p, p_max_size, obj->data.s, BATTERY_TIME);
4965                         }
4966                         OBJ(battery_percent) {
4967                                 spaced_print(p, p_max_size, "%*d", 4, "battery_percent",
4968                                                 pad_percents, get_battery_perct(obj->data.s));
4969                         }
4970                         OBJ(battery_bar) {
4971                                 new_bar(p, obj->a, obj->b, get_battery_perct_bar(obj->data.s));
4972                         }
4973 #endif /* __OpenBSD__ */
4974
4975                         OBJ(buffers) {
4976                                 human_readable(cur->buffers * 1024, p, 255, "buffers");
4977                         }
4978                         OBJ(cached) {
4979                                 human_readable(cur->cached * 1024, p, 255, "buffers");
4980                         }
4981                         OBJ(cpu) {
4982                                 if (obj->data.cpu_index > info.cpu_count) {
4983                                         printf("obj->data.cpu_index %i info.cpu_count %i",
4984                                                         obj->data.cpu_index, info.cpu_count);
4985                                         CRIT_ERR("attempting to use more CPUs than you have!");
4986                                 }
4987                                 spaced_print(p, p_max_size, "%*d", 4, "cpu", pad_percents,
4988                                                 round_to_int(cur->cpu_usage[obj->data.cpu_index] * 100.0));
4989                         }
4990                         OBJ(cpubar) {
4991                                 new_bar(p, obj->a, obj->b,
4992                                                 round_to_int(cur->cpu_usage[obj->data.cpu_index] * 255.0));
4993                         }
4994                         OBJ(cpugraph) {
4995                                 new_graph(p, obj->a, obj->b, obj->c, obj->d, (unsigned int)
4996                                                 round_to_int(cur->cpu_usage[obj->data.cpu_index] * 100),
4997                                                 100, 1, obj->showaslog);
4998                         }
4999                         OBJ(loadgraph) {
5000                                 new_graph(p, obj->a, obj->b, obj->c, obj->d, cur->loadavg[0],
5001                                                 obj->e, 1, obj->showaslog);
5002                         }
5003                         OBJ(color) {
5004                                 new_fg(p, obj->data.l);
5005                         }
5006                         OBJ(color0) {
5007                                 new_fg(p, color0);
5008                         }
5009                         OBJ(color1) {
5010                                 new_fg(p, color1);
5011                         }
5012                         OBJ(color2) {
5013                                 new_fg(p, color2);
5014                         }
5015                         OBJ(color3) {
5016                                 new_fg(p, color3);
5017                         }
5018                         OBJ(color4) {
5019                                 new_fg(p, color4);
5020                         }
5021                         OBJ(color5) {
5022                                 new_fg(p, color5);
5023                         }
5024                         OBJ(color6) {
5025                                 new_fg(p, color6);
5026                         }
5027                         OBJ(color7) {
5028                                 new_fg(p, color7);
5029                         }
5030                         OBJ(color8) {
5031                                 new_fg(p, color8);
5032                         }
5033                         OBJ(color9) {
5034                                 new_fg(p, color9);
5035                         }
5036                         OBJ(conky_version) {
5037                                 snprintf(p, p_max_size, "%s", VERSION);
5038                         }
5039                         OBJ(conky_build_date) {
5040                                 snprintf(p, p_max_size, "%s", BUILD_DATE);
5041                         }
5042                         OBJ(conky_build_arch) {
5043                                 snprintf(p, p_max_size, "%s", BUILD_ARCH);
5044                         }
5045 #if defined(__linux__)
5046                         OBJ(disk_protect) {
5047                                 snprintf(p, p_max_size, "%s",
5048                                                 get_disk_protect_queue(obj->data.s));
5049                         }
5050                         OBJ(i8k_version) {
5051                                 snprintf(p, p_max_size, "%s", i8k.version);
5052                         }
5053                         OBJ(i8k_bios) {
5054                                 snprintf(p, p_max_size, "%s", i8k.bios);
5055                         }
5056                         OBJ(i8k_serial) {
5057                                 snprintf(p, p_max_size, "%s", i8k.serial);
5058                         }
5059                         OBJ(i8k_cpu_temp) {
5060                                 int cpu_temp;
5061
5062                                 sscanf(i8k.cpu_temp, "%d", &cpu_temp);
5063                                 temp_print(p, p_max_size, (double)cpu_temp, TEMP_CELSIUS);
5064                         }
5065                         OBJ(i8k_left_fan_status) {
5066                                 int left_fan_status;
5067
5068                                 sscanf(i8k.left_fan_status, "%d", &left_fan_status);
5069                                 if (left_fan_status == 0) {
5070                                         snprintf(p, p_max_size, "off");
5071                                 }
5072                                 if (left_fan_status == 1) {
5073                                         snprintf(p, p_max_size, "low");
5074                                 }
5075                                 if (left_fan_status == 2) {
5076                                         snprintf(p, p_max_size, "high");
5077                                 }
5078                         }
5079                         OBJ(i8k_right_fan_status) {
5080                                 int right_fan_status;
5081
5082                                 sscanf(i8k.right_fan_status, "%d", &right_fan_status);
5083                                 if (right_fan_status == 0) {
5084                                         snprintf(p, p_max_size, "off");
5085                                 }
5086                                 if (right_fan_status == 1) {
5087                                         snprintf(p, p_max_size, "low");
5088                                 }
5089                                 if (right_fan_status == 2) {
5090                                         snprintf(p, p_max_size, "high");
5091                                 }
5092                         }
5093                         OBJ(i8k_left_fan_rpm) {
5094                                 snprintf(p, p_max_size, "%s", i8k.left_fan_rpm);
5095                         }
5096                         OBJ(i8k_right_fan_rpm) {
5097                                 snprintf(p, p_max_size, "%s", i8k.right_fan_rpm);
5098                         }
5099                         OBJ(i8k_ac_status) {
5100                                 int ac_status;
5101
5102                                 sscanf(i8k.ac_status, "%d", &ac_status);
5103                                 if (ac_status == -1) {
5104                                         snprintf(p, p_max_size, "disabled (read i8k docs)");
5105                                 }
5106                                 if (ac_status == 0) {
5107                                         snprintf(p, p_max_size, "off");
5108                                 }
5109                                 if (ac_status == 1) {
5110                                         snprintf(p, p_max_size, "on");
5111                                 }
5112                         }
5113                         OBJ(i8k_buttons_status) {
5114                                 snprintf(p, p_max_size, "%s", i8k.buttons_status);
5115                         }
5116                         OBJ(ibm_fan) {
5117                                 get_ibm_acpi_fan(p, p_max_size);
5118                         }
5119                         OBJ(ibm_temps) {
5120                                 get_ibm_acpi_temps();
5121                                 temp_print(p, p_max_size,
5122                                            ibm_acpi.temps[obj->data.sensor], TEMP_CELSIUS);
5123                         }
5124                         OBJ(ibm_volume) {
5125                                 get_ibm_acpi_volume(p, p_max_size);
5126                         }
5127                         OBJ(ibm_brightness) {
5128                                 get_ibm_acpi_brightness(p, p_max_size);
5129                         }
5130                         OBJ(if_up) {
5131                                 if ((obj->data.ifblock.s)
5132                                                 && (!interface_up(obj->data.ifblock.s))) {
5133                                         i = obj->data.ifblock.pos;
5134                                         if_jumped = 1;
5135                                 } else {
5136                                         if_jumped = 0;
5137                                 }
5138                         }
5139                         OBJ(if_gw) {
5140                                 if (!cur->gw_info.count) {
5141                                         i = obj->data.ifblock.pos;
5142                                         if_jumped = 1;
5143                                 } else {
5144                                         if_jumped = 0;
5145                                 }
5146                         }
5147                         OBJ(gw_iface) {
5148                                 snprintf(p, p_max_size, "%s", cur->gw_info.iface);
5149                         }
5150                         OBJ(gw_ip) {
5151                                 snprintf(p, p_max_size, "%s", cur->gw_info.ip);
5152                         }
5153                         OBJ(laptop_mode) {
5154                                 snprintf(p, p_max_size, "%d", get_laptop_mode());
5155                         }
5156                         OBJ(pb_battery) {
5157                                 get_powerbook_batt_info(p, p_max_size, obj->data.i);
5158                         }
5159 #endif /* __linux__ */
5160
5161 #ifdef __OpenBSD__
5162                         OBJ(obsd_sensors_temp) {
5163                                 obsd_sensors.device = sensor_device;
5164                                 update_obsd_sensors();
5165                                 temp_print(p, p_max_size,
5166                                            obsd_sensors.temp[obsd_sensors.device][obj->data.sensor],
5167                                            TEMP_CELSIUS);
5168                         }
5169                         OBJ(obsd_sensors_fan) {
5170                                 obsd_sensors.device = sensor_device;
5171                                 update_obsd_sensors();
5172                                 snprintf(p, p_max_size, "%d",
5173                                                 obsd_sensors.fan[obsd_sensors.device][obj->data.sensor]);
5174                         }
5175                         OBJ(obsd_sensors_volt) {
5176                                 obsd_sensors.device = sensor_device;
5177                                 update_obsd_sensors();
5178                                 snprintf(p, p_max_size, "%.2f",
5179                                                 obsd_sensors.volt[obsd_sensors.device][obj->data.sensor]);
5180                         }
5181                         OBJ(obsd_vendor) {
5182                                 get_obsd_vendor(p, p_max_size);
5183                         }
5184                         OBJ(obsd_product) {
5185                                 get_obsd_product(p, p_max_size);
5186                         }
5187 #endif /* __OpenBSD__ */
5188
5189 #ifdef X11
5190                         OBJ(font) {
5191                                 new_font(p, obj->data.s);
5192                         }
5193 #endif
5194                         /* TODO: move this correction from kB to kB/s elsewhere
5195                          * (or get rid of it??) */
5196                         OBJ(diskio) {
5197                                 if (obj->data.diskio) {
5198                                         human_readable(
5199                                                         (obj->data.diskio->current / update_interval) * 1024LL,
5200                                                         p, p_max_size, "diskio");
5201                                 } else {
5202                                         human_readable(info.diskio_value * 1024LL, p, p_max_size,
5203                                                         "diskio");
5204                                 }
5205                         }
5206                         OBJ(diskio_write) {
5207                                 if (obj->data.diskio) {
5208                                         human_readable((obj->data.diskio->current_write / update_interval) * 1024LL, p, p_max_size,
5209                                                         "diskio_write");
5210                                 } else {
5211                                         human_readable(info.diskio_write_value * 1024LL, p, p_max_size,
5212                                                         "diskio_write");
5213                                 }
5214                         }
5215                         OBJ(diskio_read) {
5216                                 if (obj->data.diskio) {
5217                                         human_readable((obj->data.diskio->current_read / update_interval) * 1024LL, p, p_max_size,
5218                                                         "diskio_read");
5219                                 } else {
5220                                         human_readable(info.diskio_read_value * 1024LL, p, p_max_size,
5221                                                         "diskio_read");
5222                                 }
5223                         }
5224                         OBJ(diskiograph) {
5225                                 if (obj->data.diskio) {
5226                                         new_graph(p, obj->a, obj->b, obj->c, obj->d,
5227                                                         obj->data.diskio->current, obj->e, 1, obj->showaslog);
5228                                 } else {
5229                                         new_graph(p, obj->a, obj->b, obj->c, obj->d, info.diskio_value,
5230                                                         obj->e, 1, obj->showaslog);
5231                                 }
5232                         }
5233                         OBJ(diskiograph_read) {
5234                                 if (obj->data.diskio) {
5235                                         new_graph(p, obj->a, obj->b, obj->c, obj->d,
5236                                                         obj->data.diskio->current_read, obj->e, 1, obj->showaslog);
5237                                 } else {
5238                                         new_graph(p, obj->a, obj->b, obj->c, obj->d,
5239                                                         info.diskio_read_value, obj->e, 1, obj->showaslog);
5240                                 }
5241                         }
5242                         OBJ(diskiograph_write) {
5243                                 if (obj->data.diskio) {
5244                                         new_graph(p, obj->a, obj->b, obj->c, obj->d,
5245                                                         obj->data.diskio->current_write, obj->e, 1, obj->showaslog);
5246                                 } else {
5247                                         new_graph(p, obj->a, obj->b, obj->c, obj->d,
5248                                                         info.diskio_write_value, obj->e, 1, obj->showaslog);
5249                                 }
5250                         }
5251                         OBJ(downspeed) {
5252                                 spaced_print(p, p_max_size, "%d", 6, "downspeed",
5253                                                 round_to_int(obj->data.net->recv_speed / 1024));
5254                         }
5255                         OBJ(downspeedf) {
5256                                 spaced_print(p, p_max_size, "%.1f", 8, "downspeedf",
5257                                                 obj->data.net->recv_speed / 1024.0);
5258                         }
5259                         OBJ(downspeedgraph) {
5260                         new_graph(p, obj->a, obj->b, obj->c, obj->d,
5261                                 obj->data.net->recv_speed / 1024.0, obj->e, 1, obj->showaslog);
5262                         }
5263                         OBJ(else) {
5264                                 if (!if_jumped) {
5265                                         i = obj->data.ifblock.pos - 1;
5266                                 } else {
5267                                         if_jumped = 0;
5268                                 }
5269                         }
5270                         OBJ(endif) {
5271                                 if_jumped = 0;
5272                         }
5273 #ifdef HAVE_POPEN
5274                         OBJ(addr) {
5275                                 if ((obj->data.net->addr.sa_data[2] & 255) == 0
5276                                                 && (obj->data.net->addr.sa_data[3] & 255) == 0
5277                                                 && (obj->data.net->addr.sa_data[4] & 255) == 0
5278                                                 && (obj->data.net->addr.sa_data[5] & 255) == 0) {
5279                                         snprintf(p, p_max_size, "No Address");
5280                                 } else {
5281                                         snprintf(p, p_max_size, "%u.%u.%u.%u",
5282                                                 obj->data.net->addr.sa_data[2] & 255,
5283                                                 obj->data.net->addr.sa_data[3] & 255,
5284                                                 obj->data.net->addr.sa_data[4] & 255,
5285                                                 obj->data.net->addr.sa_data[5] & 255);
5286                                 }
5287                         }
5288 #if defined(__linux__)
5289                         OBJ(addrs) {
5290                                 if(NULL != obj->data.net->addrs && strlen(obj->data.net->addrs) > 2)
5291                                 {
5292                                         obj->data.net->addrs[strlen(obj->data.net->addrs) - 2] = 0; /* remove ", " from end of string */
5293                                         strcpy(p, obj->data.net->addrs);
5294                                 }
5295                                 else
5296                                         strcpy(p, "0.0.0.0");
5297            }
5298 #endif /* __linux__ */
5299
5300 #if defined(IMLIB2) && defined(X11)
5301                         OBJ(image) {
5302                                 if (obj->a < 1) {
5303                                         obj->a++;
5304                                 } else {
5305                                         Imlib_Image image, buffer;
5306
5307                                         image = imlib_load_image(obj->data.s);
5308                                         imlib_context_set_image(image);
5309                                         if (image) {
5310                                                 int w, h;
5311
5312                                                 w = imlib_image_get_width();
5313                                                 h = imlib_image_get_height();
5314                                                 buffer = imlib_create_image(w, h);
5315                                                 imlib_context_set_display(display);
5316                                                 imlib_context_set_drawable(window.drawable);
5317                                                 imlib_context_set_colormap(DefaultColormap(display,
5318                                                         screen));
5319                                                 imlib_context_set_visual(DefaultVisual(display,
5320                                                         screen));
5321                                                 imlib_context_set_image(buffer);
5322                                                 imlib_blend_image_onto_image(image, 0, 0, 0, w, h,
5323                                                         text_start_x, text_start_y, w, h);
5324                                                 imlib_render_image_on_drawable(text_start_x,
5325                                                         text_start_y);
5326                                                 imlib_free_image();
5327                                                 imlib_context_set_image(image);
5328                                                 imlib_free_image();
5329                                         }
5330                                 }
5331                         }
5332 #endif /* IMLIB2 */
5333
5334                         OBJ(exec) {
5335                                 read_exec(obj->data.s, p, text_buffer_size);
5336                                 remove_deleted_chars(p);
5337                         }
5338                         OBJ(execp) {
5339                                 struct information *tmp_info;
5340                                 struct text_object_list *text_objects;
5341
5342                                 read_exec(obj->data.s, p, text_buffer_size);
5343
5344                                 tmp_info = malloc(sizeof(struct information));
5345                                 memcpy(tmp_info, cur, sizeof(struct information));
5346                                 text_objects = parse_conky_vars(p, p, tmp_info);
5347
5348                                 free_text_objects(text_objects, 0);
5349                                 free(text_objects);
5350                                 free(tmp_info);
5351                         }
5352                         OBJ(execbar) {
5353                                 double barnum;
5354
5355                                 read_exec(obj->data.s, p, text_buffer_size);
5356                                 barnum = get_barnum(p);
5357
5358                                 if (barnum >= 0.0) {
5359                                         barnum /= 100;
5360                                         new_bar(p, 0, 4, round_to_int(barnum * 255.0));
5361                                 }
5362                         }
5363                         OBJ(execgraph) {
5364                                 char showaslog = FALSE;
5365                                 double barnum;
5366
5367                                 if(strncasecmp(obj->data.s, LOGGRAPH" ", strlen(LOGGRAPH" ")) == EQUAL) {
5368                                         showaslog = TRUE;
5369                                         read_exec(obj->data.s + strlen(LOGGRAPH" ") * sizeof(char), p, text_buffer_size);
5370                                 } else if(strncasecmp(obj->data.s, NORMGRAPH" ", strlen(NORMGRAPH" ")) == EQUAL) {
5371                                         read_exec(obj->data.s + strlen(NORMGRAPH" ") * sizeof(char), p, text_buffer_size);
5372                                 } else {
5373                                         read_exec(obj->data.s, p, text_buffer_size);
5374                                 }
5375                                 barnum = get_barnum(p);
5376
5377                                 if (barnum >= 0.0) {
5378                                         new_graph(p, 0, 25, obj->c, obj->d, round_to_int(barnum),
5379                                                 100, 1, showaslog);
5380                                 }
5381                         }
5382                         OBJ(execibar) {
5383                                 if (current_update_time - obj->data.execi.last_update
5384                                                 >= obj->data.execi.interval) {
5385                                         double barnum;
5386
5387                                         read_exec(obj->data.execi.cmd, p, text_buffer_size);
5388                                         barnum = get_barnum(p);
5389
5390                                         if (barnum >= 0.0) {
5391                                                 obj->f = 255 * barnum / 100.0;
5392                                         }
5393                                         obj->data.execi.last_update = current_update_time;
5394                                 }
5395                                 new_bar(p, 0, 4, round_to_int(obj->f));
5396                         }
5397                         OBJ(execigraph) {
5398                                 if (current_update_time - obj->data.execi.last_update
5399                                                 >= obj->data.execi.interval) {
5400                                         double barnum;
5401
5402                                         read_exec(obj->data.execi.cmd, p, text_buffer_size);
5403                                         barnum = get_barnum(p);
5404
5405                                         if (barnum >= 0.0) {
5406                                                 obj->f = barnum;
5407                                         }
5408                                         obj->data.execi.last_update = current_update_time;
5409                                 }
5410                                 new_graph(p, 0, 25, obj->c, obj->d, (int) (obj->f), 100, 1, FALSE);
5411                         }
5412                         OBJ(execi) {
5413                                 if (current_update_time - obj->data.execi.last_update
5414                                                 >= obj->data.execi.interval
5415                                                 && obj->data.execi.interval != 0) {
5416                                         read_exec(obj->data.execi.cmd, obj->data.execi.buffer,
5417                                                 text_buffer_size);
5418                                         obj->data.execi.last_update = current_update_time;
5419                                 }
5420                                 snprintf(p, text_buffer_size, "%s", obj->data.execi.buffer);
5421                         }
5422                         OBJ(execpi) {
5423                                 struct text_object_list *text_objects = 0;
5424                                 struct information *tmp_info =
5425                                         malloc(sizeof(struct information));
5426                                 memcpy(tmp_info, cur, sizeof(struct information));
5427
5428                                 if (current_update_time - obj->data.execi.last_update
5429                                                 < obj->data.execi.interval
5430                                                 || obj->data.execi.interval == 0) {
5431                                         text_objects = parse_conky_vars(obj->data.execi.buffer, p, tmp_info);
5432                                 } else {
5433                                         char *output = obj->data.execi.buffer;
5434                                         FILE *fp = popen(obj->data.execi.cmd, "r");
5435                                         int length = fread(output, 1, text_buffer_size, fp);
5436
5437                                         pclose(fp);
5438
5439                                         output[length] = '\0';
5440                                         if (length > 0 && output[length - 1] == '\n') {
5441                                                 output[length - 1] = '\0';
5442                                         }
5443
5444                                         text_objects = parse_conky_vars(obj->data.execi.buffer, p, tmp_info);
5445                                         obj->data.execi.last_update = current_update_time;
5446                                 }
5447                                 free_text_objects(text_objects, 0);
5448                                 free(text_objects);
5449                                 free(tmp_info);
5450                         }
5451                         OBJ(texeci) {
5452                                 if (!obj->data.texeci.p_timed_thread) {
5453                                         obj->data.texeci.p_timed_thread =
5454                                                 timed_thread_create(&threaded_exec,
5455                                                 (void *) obj, obj->data.texeci.interval * 1000000);
5456                                         if (!obj->data.texeci.p_timed_thread) {
5457                                                 ERR("Error creating texeci timed thread");
5458                                         }
5459                                         timed_thread_register(obj->data.texeci.p_timed_thread,
5460                                                 &obj->data.texeci.p_timed_thread);
5461                                         if (timed_thread_run(obj->data.texeci.p_timed_thread)) {
5462                                                 ERR("Error running texeci timed thread");
5463                                         }
5464                                 }
5465                                 timed_thread_lock(obj->data.texeci.p_timed_thread);
5466                                 snprintf(p, text_buffer_size, "%s", obj->data.texeci.buffer);
5467                                 timed_thread_unlock(obj->data.texeci.p_timed_thread);
5468                         }
5469 #endif /* HAVE_POPEN */
5470                         OBJ(imap_unseen) {
5471                                 struct mail_s *mail = ensure_mail_thread(obj, imap_thread, "imap");
5472
5473                                 if (mail && mail->p_timed_thread) {
5474                                         timed_thread_lock(mail->p_timed_thread);
5475                                         snprintf(p, p_max_size, "%lu", mail->unseen);
5476                                         timed_thread_unlock(mail->p_timed_thread);
5477                                 }
5478                         }
5479                         OBJ(imap_messages) {
5480                                 struct mail_s *mail = ensure_mail_thread(obj, imap_thread, "imap");
5481
5482                                 if (mail && mail->p_timed_thread) {
5483                                         timed_thread_lock(mail->p_timed_thread);
5484                                         snprintf(p, p_max_size, "%lu", mail->messages);
5485                                         timed_thread_unlock(mail->p_timed_thread);
5486                                 }
5487                         }
5488                         OBJ(pop3_unseen) {
5489                                 struct mail_s *mail = ensure_mail_thread(obj, pop3_thread, "pop3");
5490
5491                                 if (mail && mail->p_timed_thread) {
5492                                         timed_thread_lock(mail->p_timed_thread);
5493                                         snprintf(p, p_max_size, "%lu", mail->unseen);
5494                                         timed_thread_unlock(mail->p_timed_thread);
5495                                 }
5496                         }
5497                         OBJ(pop3_used) {
5498                                 struct mail_s *mail = ensure_mail_thread(obj, pop3_thread, "pop3");
5499
5500                                 if (mail && mail->p_timed_thread) {
5501                                         timed_thread_lock(mail->p_timed_thread);
5502                                         snprintf(p, p_max_size, "%.1f",
5503                                                 mail->used / 1024.0 / 1024.0);
5504                                         timed_thread_unlock(mail->p_timed_thread);
5505                                 }
5506                         }
5507                         OBJ(fs_bar) {
5508                                 if (obj->data.fs != NULL) {
5509                                         if (obj->data.fs->size == 0) {
5510                                                 new_bar(p, obj->data.fsbar.w, obj->data.fsbar.h, 255);
5511                                         } else {
5512                                                 new_bar(p, obj->data.fsbar.w, obj->data.fsbar.h,
5513                                                         (int) (255 - obj->data.fsbar.fs->avail * 255 /
5514                                                         obj->data.fs->size));
5515                                         }
5516                                 }
5517                         }
5518                         OBJ(fs_free) {
5519                                 if (obj->data.fs != NULL) {
5520                                         human_readable(obj->data.fs->avail, p, 255, "fs_free");
5521                                 }
5522                         }
5523                         OBJ(fs_free_perc) {
5524                                 if (obj->data.fs != NULL) {
5525                                         if (obj->data.fs->size) {
5526                                                 spaced_print(p, p_max_size, "%*d", 4, "fs_free_perc",
5527                                                                 pad_percents, (int) ((obj->data.fs->avail * 100) /
5528                                                                         obj->data.fs->size));
5529                                         } else {
5530                                                 snprintf(p, p_max_size, "0");
5531                                         }
5532                                 }
5533                         }
5534                         OBJ(fs_size) {
5535                                 if (obj->data.fs != NULL) {
5536                                         human_readable(obj->data.fs->size, p, 255, "fs_size");
5537                                 }
5538                         }
5539                         OBJ(fs_type) {
5540                                 if (obj->data.fs != NULL)
5541                                         snprintf(p, p_max_size, "%s", obj->data.fs->type);
5542                         }
5543                         OBJ(fs_used) {
5544                                 if (obj->data.fs != NULL) {
5545                                         human_readable(obj->data.fs->size - (obj->data.fs->free
5546                                                 ? obj->data.fs->free : obj->data.fs->avail), p, 255,
5547                                                 "fs_used");
5548                                 }
5549                         }
5550                         OBJ(fs_bar_free) {
5551                                 if (obj->data.fs != NULL) {
5552                                         if (obj->data.fs->size == 0) {
5553                                                 new_bar(p, obj->data.fsbar.w, obj->data.fsbar.h, 255);
5554                                         } else {
5555                                                 new_bar(p, obj->data.fsbar.w, obj->data.fsbar.h,
5556                                                         (int) (obj->data.fsbar.fs->avail * 255 /
5557                                                         obj->data.fs->size));
5558                                         }
5559                                 }
5560                         }
5561                         OBJ(fs_used_perc) {
5562                                 if (obj->data.fs != NULL) {
5563                                         if (obj->data.fs->size) {
5564                                                 spaced_print(p, 4, "%*d", 4, "fs_used_perc",
5565                                                                 pad_percents, 100 - ((int) ((obj->data.fs->avail * 100) /
5566                                                                                 obj->data.fs->size)));
5567                                         } else {
5568                                                 snprintf(p, p_max_size, "0");
5569                                         }
5570                                 }
5571                         }
5572                         OBJ(loadavg) {
5573                                 float *v = info.loadavg;
5574
5575                                 if (obj->data.loadavg[2]) {
5576                                         snprintf(p, p_max_size, "%.2f %.2f %.2f",
5577                                                 v[obj->data.loadavg[0] - 1],
5578                                                 v[obj->data.loadavg[1] - 1],
5579                                                 v[obj->data.loadavg[2] - 1]);
5580                                 } else if (obj->data.loadavg[1]) {
5581                                         snprintf(p, p_max_size, "%.2f %.2f",
5582                                                 v[obj->data.loadavg[0] - 1],
5583                                                 v[obj->data.loadavg[1] - 1]);
5584                                 } else if (obj->data.loadavg[0]) {
5585                                         snprintf(p, p_max_size, "%.2f",
5586                                                 v[obj->data.loadavg[0] - 1]);
5587                                 }
5588                         }
5589                         OBJ(goto) {
5590                                 new_goto(p, obj->data.i);
5591                         }
5592                         OBJ(tab) {
5593                                 new_tab(p, obj->data.pair.a, obj->data.pair.b);
5594                         }
5595                         OBJ(hr) {
5596                                 new_hr(p, obj->data.i);
5597                         }
5598                         OBJ(nameserver) {
5599                                 if (cur->nameserver_info.nscount > obj->data.i)
5600                                         snprintf(p, p_max_size, "%s",
5601                                                         cur->nameserver_info.ns_list[obj->data.i]);
5602                         }
5603 #ifdef EVE
5604                         OBJ(eve) {
5605                                 char *skill = eve(obj->data.eve.userid, obj->data.eve.apikey, obj->data.eve.charid);
5606                                 snprintf(p, p_max_size, "%s", skill);
5607                         }
5608 #endif
5609 #ifdef RSS
5610                         OBJ(rss) {
5611                                 PRSS *data = get_rss_info(obj->data.rss.uri,
5612                                         obj->data.rss.delay);
5613                                 char *str;
5614
5615                                 if (data == NULL) {
5616                                         snprintf(p, p_max_size, "prss: Error reading RSS data\n");
5617                                 } else {
5618                                         if (strcmp(obj->data.rss.action, "feed_title") == EQUAL) {
5619                                                 str = data->title;
5620                                                 // remove trailing new line if one exists
5621                                                 if (str[strlen(str) - 1] == '\n') {
5622                                                         str[strlen(str) - 1] = 0;
5623                                                 }
5624                                                 snprintf(p, p_max_size, "%s", str);
5625                                         } else if (strcmp(obj->data.rss.action, "item_title") == EQUAL) {
5626                                                 if (obj->data.rss.act_par < data->item_count) {
5627                                                         str = data->items[obj->data.rss.act_par].title;
5628                                                         // remove trailing new line if one exists
5629                                                         if (str[strlen(str) - 1] == '\n') {
5630                                                                 str[strlen(str) - 1] = 0;
5631                                                         }
5632                                                         snprintf(p, p_max_size, "%s", str);
5633                                                 }
5634                                         } else if (strcmp(obj->data.rss.action, "item_desc") == EQUAL) {
5635                                                 if (obj->data.rss.act_par < data->item_count) {
5636                                                         str =
5637                                                                 data->items[obj->data.rss.act_par].description;
5638                                                         // remove trailing new line if one exists
5639                                                         if (str[strlen(str) - 1] == '\n') {
5640                                                                 str[strlen(str) - 1] = 0;
5641                                                         }
5642                                                         snprintf(p, p_max_size, "%s", str);
5643                                                 }
5644                                         } else if (strcmp(obj->data.rss.action, "item_titles") == EQUAL) {
5645                                                 if (data->item_count > 0) {
5646                                                         int itmp;
5647                                                         int show;
5648
5649                                                         p[0] = 0;
5650
5651                                                         if (obj->data.rss.act_par > data->item_count) {
5652                                                                 show = data->item_count;
5653                                                         } else {
5654                                                                 show = obj->data.rss.act_par;
5655                                                         }
5656                                                         for (itmp = 0; itmp < show; itmp++) {
5657                                                                 PRSS_Item *item = &data->items[itmp];
5658
5659                                                                 str = item->title;
5660                                                                 if (str) {
5661                                                                         // don't add new line before first item
5662                                                                         if (itmp > 0) {
5663                                                                                 strncat(p, "\n", p_max_size);
5664                                                                         }
5665                                                                         /* remove trailing new line if one exists,
5666                                                                          * we have our own */
5667                                                                         if (str[strlen(str) - 1] == '\n') {
5668                                                                                 str[strlen(str) - 1] = 0;
5669                                                                         }
5670                                                                         strncat(p, str, p_max_size);
5671                                                                 }
5672                                                         }
5673                                                 }
5674                                         }
5675                                 }
5676                         }
5677 #endif
5678 #ifdef HDDTEMP
5679                         OBJ(hddtemp) {
5680                                 char *endptr, unit;
5681                                 long val;
5682                                 if (obj->data.hddtemp.update_time < current_update_time - 30) {
5683                                         if (obj->data.hddtemp.temp)
5684                                                 free(obj->data.hddtemp.temp);
5685                                         obj->data.hddtemp.temp = get_hddtemp_info(obj->data.hddtemp.dev,
5686                                                         obj->data.hddtemp.addr, obj->data.hddtemp.port);
5687                                         obj->data.hddtemp.update_time = current_update_time;
5688                                 }
5689                                 if (!obj->data.hddtemp.temp) {
5690                                         snprintf(p, p_max_size, "N/A");
5691                                 } else {
5692                                         val = strtol(obj->data.hddtemp.temp + 1, &endptr, 10);
5693                                         unit = obj->data.hddtemp.temp[0];
5694
5695                                         if (*endptr != '\0')
5696                                                 snprintf(p, p_max_size, "N/A");
5697                                         else if (unit == 'C')
5698                                                 temp_print(p, p_max_size, (double)val, TEMP_CELSIUS);
5699                                         else if (unit == 'F')
5700                                                 temp_print(p, p_max_size, (double)val, TEMP_FAHRENHEIT);
5701                                         else
5702                                                 snprintf(p, p_max_size, "N/A");
5703                                 }
5704                         }
5705 #endif
5706                         OBJ(offset) {
5707                                 new_offset(p, obj->data.i);
5708                         }
5709                         OBJ(voffset) {
5710                                 new_voffset(p, obj->data.i);
5711                         }
5712 #ifndef __OpenBSD__
5713                         OBJ(i2c) {
5714                                 double r;
5715
5716                                 r = get_sysfs_info(&obj->data.sysfs.fd, obj->data.sysfs.arg,
5717                                         obj->data.sysfs.devtype, obj->data.sysfs.type);
5718
5719                                 if (!strncmp(obj->data.sysfs.type, "temp", 4)) {
5720                                         temp_print(p, p_max_size, r, TEMP_CELSIUS);
5721                                 } else if (r >= 100.0 || r == 0) {
5722                                         snprintf(p, p_max_size, "%d", (int) r);
5723                                 } else {
5724                                         snprintf(p, p_max_size, "%.1f", r);
5725                                 }
5726                         }
5727                         OBJ(platform) {
5728                                 double r;
5729
5730                                 r = get_sysfs_info(&obj->data.sysfs.fd, obj->data.sysfs.arg,
5731                                         obj->data.sysfs.devtype, obj->data.sysfs.type);
5732
5733                                 if (!strncmp(obj->data.sysfs.type, "temp", 4)) {
5734                                         temp_print(p, p_max_size, r, TEMP_CELSIUS);
5735                                 } else if (r >= 100.0 || r == 0) {
5736                                         snprintf(p, p_max_size, "%d", (int) r);
5737                                 } else {
5738                                         snprintf(p, p_max_size, "%.1f", r);
5739                                 }
5740                         }
5741                         OBJ(hwmon) {
5742                                 double r;
5743
5744                                 r = get_sysfs_info(&obj->data.sysfs.fd, obj->data.sysfs.arg,
5745                                         obj->data.sysfs.devtype, obj->data.sysfs.type);
5746
5747                                 if (!strncmp(obj->data.sysfs.type, "temp", 4)) {
5748                                         temp_print(p, p_max_size, r, TEMP_CELSIUS);
5749                                 } else if (r >= 100.0 || r == 0) {
5750                                         snprintf(p, p_max_size, "%d", (int) r);
5751                                 } else {
5752                                         snprintf(p, p_max_size, "%.1f", r);
5753                                 }
5754                         }
5755 #endif /* !__OpenBSD__ */
5756                         OBJ(alignr) {
5757                                 new_alignr(p, obj->data.i);
5758                         }
5759                         OBJ(alignc) {
5760                                 new_alignc(p, obj->data.i);
5761                         }
5762                         OBJ(if_empty) {
5763                                 struct text_object_list *text_objects;
5764                                 struct information *tmp_info =
5765                                         malloc(sizeof(struct information));
5766                                 memcpy(tmp_info, cur, sizeof(struct information));
5767                                 text_objects = parse_conky_vars(obj->data.ifblock.s, p, tmp_info);
5768
5769                                 if (strlen(p) != 0) {
5770                                         i = obj->data.ifblock.pos;
5771                                         if_jumped = 1;
5772                                 } else {
5773                                         if_jumped = 0;
5774                                 }
5775                                 p[0] = '\0';
5776                                 free_text_objects(text_objects, 0);
5777                                 free(text_objects);
5778                                 free(tmp_info);
5779                         }
5780                         OBJ(if_existing) {
5781                                 struct stat tmp;
5782
5783                                 if ((obj->data.ifblock.s)
5784                                                 && (stat(obj->data.ifblock.s, &tmp) == -1)) {
5785                                         i = obj->data.ifblock.pos;
5786                                         if_jumped = 1;
5787                                 } else {
5788                                         if (obj->data.ifblock.str) {
5789                                                 if (!check_contains(obj->data.ifblock.s,
5790                                                                 obj->data.ifblock.str)) {
5791                                                         i = obj->data.ifblock.pos;
5792                                                         if_jumped = 1;
5793                                                 } else {
5794                                                         if_jumped = 0;
5795                                                 }
5796                                         } else {
5797                                                 if_jumped = 0;
5798                                         }
5799                                 }
5800                         }
5801                         OBJ(if_mounted) {
5802                                 if ((obj->data.ifblock.s)
5803                                                 && (!check_mount(obj->data.ifblock.s))) {
5804                                         i = obj->data.ifblock.pos;
5805                                         if_jumped = 1;
5806                                 } else {
5807                                         if_jumped = 0;
5808                                 }
5809                         }
5810                         OBJ(if_running) {
5811                                 if ((obj->data.ifblock.s) && system(obj->data.ifblock.s)) {
5812                                         i = obj->data.ifblock.pos;
5813                                         if_jumped = 1;
5814                                 } else {
5815                                         if_jumped = 0;
5816                                 }
5817                         }
5818 #if defined(__linux__)
5819                         OBJ(ioscheduler) {
5820                                 snprintf(p, p_max_size, "%s", get_ioscheduler(obj->data.s));
5821                         }
5822 #endif
5823                         OBJ(kernel) {
5824                                 snprintf(p, p_max_size, "%s", cur->uname_s.release);
5825                         }
5826                         OBJ(machine) {
5827                                 snprintf(p, p_max_size, "%s", cur->uname_s.machine);
5828                         }
5829
5830                         /* memory stuff */
5831                         OBJ(mem) {
5832                                 human_readable(cur->mem * 1024, p, 255, "mem");
5833                         }
5834                         OBJ(memeasyfree) {
5835                                 human_readable(cur->memeasyfree * 1024, p, 255, "memeasyfree");
5836                         }
5837                         OBJ(memfree) {
5838                                 human_readable(cur->memfree * 1024, p, 255, "memfree");
5839                         }
5840                         OBJ(memmax) {
5841                                 human_readable(cur->memmax * 1024, p, 255, "memmax");
5842                         }
5843                         OBJ(memperc) {
5844                                 if (cur->memmax) {
5845                                         spaced_print(p, p_max_size, "%*llu", 4, "memperc",
5846                                                 pad_percents, cur->mem * 100 / cur->memmax);
5847                                 }
5848                         }
5849                         OBJ(membar) {
5850                                 new_bar(p, obj->data.pair.a, obj->data.pair.b,
5851                                         cur->memmax ? (cur->mem * 255) / (cur->memmax) : 0);
5852                         }
5853                         OBJ(memgraph) {
5854                                 new_graph(p, obj->a, obj->b, obj->c, obj->d,
5855                                         cur->memmax ? (cur->mem * 100.0) / (cur->memmax) : 0.0,
5856                                         100, 1, obj->showaslog);
5857                         }
5858
5859                         /* mixer stuff */
5860                         OBJ(mixer) {
5861                                 snprintf(p, p_max_size, "%d", mixer_get_avg(obj->data.l));
5862                         }
5863                         OBJ(mixerl) {
5864                                 snprintf(p, p_max_size, "%d", mixer_get_left(obj->data.l));
5865                         }
5866                         OBJ(mixerr) {
5867                                 snprintf(p, p_max_size, "%d", mixer_get_right(obj->data.l));
5868                         }
5869                         OBJ(mixerbar) {
5870                                 new_bar(p, obj->data.mixerbar.w, obj->data.mixerbar.h,
5871                                         mixer_get_avg(obj->data.mixerbar.l) * 255 / 100);
5872                         }
5873                         OBJ(mixerlbar) {
5874                                 new_bar(p, obj->data.mixerbar.w, obj->data.mixerbar.h,
5875                                         mixer_get_left(obj->data.mixerbar.l) * 255 / 100);
5876                         }
5877                         OBJ(mixerrbar) {
5878                                 new_bar(p, obj->data.mixerbar.w, obj->data.mixerbar.h,
5879                                         mixer_get_right(obj->data.mixerbar.l) * 255 / 100);
5880                         }
5881 #ifdef X11
5882                         OBJ(monitor) {
5883                                 snprintf(p, p_max_size, "%d", cur->x11.monitor.current);
5884                         }
5885                         OBJ(monitor_number) {
5886                                 snprintf(p, p_max_size, "%d", cur->x11.monitor.number);
5887                         }
5888 #endif
5889
5890                         /* mail stuff */
5891                         OBJ(mails) {
5892                                 update_mail_count(&obj->data.local_mail);
5893                                 snprintf(p, p_max_size, "%d", obj->data.local_mail.mail_count);
5894                         }
5895                         OBJ(mboxscan) {
5896                                 mbox_scan(obj->data.mboxscan.args, obj->data.mboxscan.output,
5897                                         text_buffer_size);
5898                                 snprintf(p, p_max_size, "%s", obj->data.mboxscan.output);
5899                         }
5900                         OBJ(new_mails) {
5901                                 update_mail_count(&obj->data.local_mail);
5902                                 snprintf(p, p_max_size, "%d",
5903                                         obj->data.local_mail.new_mail_count);
5904                         }
5905                         OBJ(nodename) {
5906                                 snprintf(p, p_max_size, "%s", cur->uname_s.nodename);
5907                         }
5908                         OBJ(outlinecolor) {
5909                                 new_outline(p, obj->data.l);
5910                         }
5911                         OBJ(processes) {
5912                                 spaced_print(p, p_max_size, "%hu", 5, "processes", cur->procs);
5913                         }
5914                         OBJ(running_processes) {
5915                                 spaced_print(p, p_max_size, "%hu", 3, "running_processes", cur->run_procs);
5916                         }
5917                         OBJ(text) {
5918                                 snprintf(p, p_max_size, "%s", obj->data.s);
5919                         }
5920                         OBJ(shadecolor) {
5921                                 new_bg(p, obj->data.l);
5922                         }
5923                         OBJ(stippled_hr) {
5924                                 new_stippled_hr(p, obj->data.pair.a, obj->data.pair.b);
5925                         }
5926                         OBJ(swap) {
5927                                 human_readable(cur->swap * 1024, p, 255, "swap");
5928                         }
5929                         OBJ(swapmax) {
5930                                 human_readable(cur->swapmax * 1024, p, 255, "swapmax");
5931                         }
5932                         OBJ(swapperc) {
5933                                 if (cur->swapmax == 0) {
5934                                         strncpy(p, "No swap", p_max_size);
5935                                 } else {
5936                                         spaced_print(p, p_max_size, "%*llu", 4, "swapperc",
5937                                                 pad_percents, cur->swap * 100 / cur->swapmax);
5938                                 }
5939                         }
5940                         OBJ(swapbar) {
5941                                 new_bar(p, obj->data.pair.a, obj->data.pair.b,
5942                                         cur->swapmax ? (cur->swap * 255) / (cur->swapmax) : 0);
5943                         }
5944                         OBJ(sysname) {
5945                                 snprintf(p, p_max_size, "%s", cur->uname_s.sysname);
5946                         }
5947                         OBJ(time) {
5948                                 time_t t = time(NULL);
5949                                 struct tm *tm = localtime(&t);
5950
5951                                 setlocale(LC_TIME, "");
5952                                 strftime(p, p_max_size, obj->data.s, tm);
5953                         }
5954                         OBJ(utime) {
5955                                 time_t t = time(NULL);
5956                                 struct tm *tm = gmtime(&t);
5957
5958                                 strftime(p, p_max_size, obj->data.s, tm);
5959                         }
5960                         OBJ(tztime) {
5961                                 char *oldTZ = NULL;
5962                                 time_t t;
5963                                 struct tm *tm;
5964
5965                                 if (obj->data.tztime.tz) {
5966                                         oldTZ = getenv("TZ");
5967                                         setenv("TZ", obj->data.tztime.tz, 1);
5968                                         tzset();
5969                                 }
5970                                 t = time(NULL);
5971                                 tm = localtime(&t);
5972
5973                                 setlocale(LC_TIME, "");
5974                                 strftime(p, p_max_size, obj->data.tztime.fmt, tm);
5975                                 if (oldTZ) {
5976                                         setenv("TZ", oldTZ, 1);
5977                                         tzset();
5978                                 } else {
5979                                         unsetenv("TZ");
5980                                 }
5981                                 // Needless to free oldTZ since getenv gives ptr to static data
5982                         }
5983                         OBJ(totaldown) {
5984                                 human_readable(obj->data.net->recv, p, 255, "totaldown");
5985                         }
5986                         OBJ(totalup) {
5987                                 human_readable(obj->data.net->trans, p, 255, "totalup");
5988                         }
5989                         OBJ(updates) {
5990                                 snprintf(p, p_max_size, "%d", total_updates);
5991                         }
5992                         OBJ(upspeed) {
5993                                 spaced_print(p, p_max_size, "%d", 6, "upspeed",
5994                                         round_to_int(obj->data.net->trans_speed / 1024));
5995                         }
5996                         OBJ(upspeedf) {
5997                                 spaced_print(p, p_max_size, "%.1f", 8, "upspeedf",
5998                                         obj->data.net->trans_speed / 1024.0);
5999                         }
6000                         OBJ(upspeedgraph) {
6001                                 new_graph(p, obj->a, obj->b, obj->c, obj->d,
6002                                         obj->data.net->trans_speed / 1024.0, obj->e, 1, obj->showaslog);
6003                         }
6004                         OBJ(uptime_short) {
6005                                 format_seconds_short(p, p_max_size, (int) cur->uptime);
6006                         }
6007                         OBJ(uptime) {
6008                                 format_seconds(p, p_max_size, (int) cur->uptime);
6009                         }
6010                         OBJ(user_names) {
6011                                 snprintf(p, p_max_size, "%s", cur->users.names);
6012                         }
6013                         OBJ(user_terms) {
6014                                 snprintf(p, p_max_size, "%s", cur->users.terms);
6015                         }
6016                         OBJ(user_times) {
6017                                 snprintf(p, p_max_size, "%s", cur->users.times);
6018                         }
6019                         OBJ(user_number) {
6020                                 snprintf(p, p_max_size, "%d", cur->users.number);
6021                         }
6022 #if (defined(__FreeBSD__) || defined(__FreeBSD_kernel__) \
6023                 || defined(__OpenBSD__)) && (defined(i386) || defined(__i386__))
6024                         OBJ(apm_adapter) {
6025                                 char *msg;
6026
6027                                 msg = get_apm_adapter();
6028                                 snprintf(p, p_max_size, "%s", msg);
6029                                 free(msg);
6030                         }
6031                         OBJ(apm_battery_life) {
6032                                 char *msg;
6033
6034                                 msg = get_apm_battery_life();
6035                                 snprintf(p, p_max_size, "%s", msg);
6036                                 free(msg);
6037                         }
6038                         OBJ(apm_battery_time) {
6039                                 char *msg;
6040
6041                                 msg = get_apm_battery_time();
6042                                 snprintf(p, p_max_size, "%s", msg);
6043                                 free(msg);
6044                         }
6045 #endif /* __FreeBSD__ __OpenBSD__ */
6046
6047 #ifdef MPD
6048                         OBJ(mpd_title) {
6049                                 int len = obj->data.i;
6050                                 if (len == 0 || len > p_max_size)
6051                                         len = p_max_size;
6052                                 snprintf(p, len, "%s", cur->mpd.title);
6053                         }
6054                         OBJ(mpd_artist) {
6055                                 snprintf(p, p_max_size, "%s", cur->mpd.artist);
6056                         }
6057                         OBJ(mpd_album) {
6058                                 snprintf(p, p_max_size, "%s", cur->mpd.album);
6059                         }
6060                         OBJ(mpd_random) {
6061                                 snprintf(p, p_max_size, "%s", cur->mpd.random);
6062                         }
6063                         OBJ(mpd_repeat) {
6064                                 snprintf(p, p_max_size, "%s", cur->mpd.repeat);
6065                         }
6066                         OBJ(mpd_track) {
6067                                 snprintf(p, p_max_size, "%s", cur->mpd.track);
6068                         }
6069                         OBJ(mpd_name) {
6070                                 snprintf(p, p_max_size, "%s", cur->mpd.name);
6071                         }
6072                         OBJ(mpd_file) {
6073                                 snprintf(p, p_max_size, "%s", cur->mpd.file);
6074                         }
6075                         OBJ(mpd_vol) {
6076                                 snprintf(p, p_max_size, "%i", cur->mpd.volume);
6077                         }
6078                         OBJ(mpd_bitrate) {
6079                                 snprintf(p, p_max_size, "%i", cur->mpd.bitrate);
6080                         }
6081                         OBJ(mpd_status) {
6082                                 snprintf(p, p_max_size, "%s", cur->mpd.status);
6083                         }
6084                         OBJ(mpd_elapsed) {
6085                                 format_media_player_time(p, p_max_size, cur->mpd.elapsed);
6086                         }
6087                         OBJ(mpd_length) {
6088                                 format_media_player_time(p, p_max_size, cur->mpd.length);
6089                         }
6090                         OBJ(mpd_percent) {
6091                                 spaced_print(p, p_max_size, "%*d", 4, "mpd_percent",
6092                                                 pad_percents, (int) (cur->mpd.progress * 100));
6093                         }
6094                         OBJ(mpd_bar) {
6095                                 new_bar(p, obj->data.pair.a, obj->data.pair.b,
6096                                         (int) (cur->mpd.progress * 255.0f));
6097                         }
6098                         OBJ(mpd_smart) {
6099                                 int len = obj->data.i;
6100                                 if (len == 0 || len > p_max_size)
6101                                         len = p_max_size;
6102
6103                                 memset(p, 0, p_max_size);
6104                                 if (cur->mpd.artist && *cur->mpd.artist && cur->mpd.title
6105                                                 && *cur->mpd.title) {
6106                                         snprintf(p, len, "%s - %s", cur->mpd.artist,
6107                                                 cur->mpd.title);
6108                                 } else if (cur->mpd.title && *cur->mpd.title) {
6109                                         snprintf(p, len, "%s", cur->mpd.title);
6110                                 } else if (cur->mpd.artist && *cur->mpd.artist) {
6111                                         snprintf(p, len, "%s", cur->mpd.artist);
6112                                 } else if (cur->mpd.file && *cur->mpd.file) {
6113                                         snprintf(p, len, "%s", cur->mpd.file);
6114                                 } else {
6115                                         *p = 0;
6116                                 }
6117                         }
6118                         OBJ(if_mpd_playing) {
6119                                 if (cur->mpd.is_playing) {
6120                                         if_jumped = 0;
6121                                 } else {
6122                                         i = obj->data.ifblock.pos;
6123                                         if_jumped = 1;
6124                                 }
6125                         }
6126 #endif
6127
6128 #ifdef MOC
6129                         OBJ(moc_state) {
6130                                 snprintf(p, p_max_size, "%s", (cur->moc.state ? cur->moc.state : "??"));
6131                         }
6132                         OBJ(moc_file) {
6133                                 snprintf(p, p_max_size, "%s", (cur->moc.file ? cur->moc.file : "no file"));
6134                         }
6135                         OBJ(moc_title) {
6136                                 snprintf(p, p_max_size, "%s", (cur->moc.title ? cur->moc.title : "no title"));
6137                         }
6138                         OBJ(moc_artist) {
6139                                 snprintf(p, p_max_size, "%s", (cur->moc.artist ? cur->moc.artist : "no artist"));
6140                         }
6141                         OBJ(moc_song) {
6142                                 snprintf(p, p_max_size, "%s", (cur->moc.song ? cur->moc.song : "no song"));
6143                         }
6144                         OBJ(moc_album) {
6145                                 snprintf(p, p_max_size, "%s", (cur->moc.album ? cur->moc.album : "no album"));
6146                         }
6147                         OBJ(moc_totaltime) {
6148                                 snprintf(p, p_max_size, "%s", (cur->moc.totaltime ? cur->moc.totaltime : "0:00"));
6149                         }
6150                         OBJ(moc_timeleft) {
6151                                 snprintf(p, p_max_size, "%s", (cur->moc.timeleft ? cur->moc.timeleft : "0:00"));
6152                         }
6153                         OBJ(moc_curtime) {
6154                                 snprintf(p, p_max_size, "%s", (cur->moc.curtime ? cur->moc.curtime : "0:00"));
6155                         }
6156                         OBJ(moc_bitrate) {
6157                                 snprintf(p, p_max_size, "%s", (cur->moc.bitrate ? cur->moc.bitrate : "0Kbps"));
6158                         }
6159                         OBJ(moc_rate) {
6160         snprintf(p, p_max_size, "%s", (cur->moc.rate ? cur->moc.rate : "0KHz"));
6161                         }
6162 #endif /* MOC */
6163 #ifdef XMMS2
6164                         OBJ(xmms2_artist) {
6165                                 snprintf(p, p_max_size, "%s", cur->xmms2.artist);
6166                         }
6167                         OBJ(xmms2_album) {
6168                                 snprintf(p, p_max_size, "%s", cur->xmms2.album);
6169                         }
6170                         OBJ(xmms2_title) {
6171                                 snprintf(p, p_max_size, "%s", cur->xmms2.title);
6172                         }
6173                         OBJ(xmms2_genre) {
6174                                 snprintf(p, p_max_size, "%s", cur->xmms2.genre);
6175                         }
6176                         OBJ(xmms2_comment) {
6177                                 snprintf(p, p_max_size, "%s", cur->xmms2.comment);
6178                         }
6179                         OBJ(xmms2_url) {
6180                                 snprintf(p, p_max_size, "%s", cur->xmms2.url);
6181                         }
6182                         OBJ(xmms2_status) {
6183                                 snprintf(p, p_max_size, "%s", cur->xmms2.status);
6184                         }
6185                         OBJ(xmms2_date) {
6186                                 snprintf(p, p_max_size, "%s", cur->xmms2.date);
6187                         }
6188                         OBJ(xmms2_tracknr) {
6189                                 if (cur->xmms2.tracknr != -1) {
6190                                         snprintf(p, p_max_size, "%i", cur->xmms2.tracknr);
6191                                 }
6192                         }
6193                         OBJ(xmms2_bitrate) {
6194                                 snprintf(p, p_max_size, "%i", cur->xmms2.bitrate);
6195                         }
6196                         OBJ(xmms2_id) {
6197                                 snprintf(p, p_max_size, "%u", cur->xmms2.id);
6198                         }
6199                         OBJ(xmms2_size) {
6200                                 snprintf(p, p_max_size, "%2.1f", cur->xmms2.size);
6201                         }
6202                         OBJ(xmms2_elapsed) {
6203                                 snprintf(p, p_max_size, "%02d:%02d", cur->xmms2.elapsed / 60000,
6204                                         (cur->xmms2.elapsed / 1000) % 60);
6205                         }
6206                         OBJ(xmms2_duration) {
6207                                 snprintf(p, p_max_size, "%02d:%02d",
6208                                         cur->xmms2.duration / 60000,
6209                                         (cur->xmms2.duration / 1000) % 60);
6210                         }
6211                         OBJ(xmms2_percent) {
6212                                 snprintf(p, p_max_size, "%2.0f", cur->xmms2.progress * 100);
6213                         }
6214                         OBJ(xmms2_bar) {
6215                                 new_bar(p, obj->data.pair.a, obj->data.pair.b,
6216                                         (int) (cur->xmms2.progress * 255.0f));
6217                         }
6218                         OBJ(xmms2_playlist) {
6219                                 snprintf(p, p_max_size, "%s", cur->xmms2.playlist);
6220                         }
6221                         OBJ(xmms2_timesplayed) {
6222                                 snprintf(p, p_max_size, "%i", cur->xmms2.timesplayed);
6223                         }
6224                         OBJ(xmms2_smart) {
6225                                 if (strlen(cur->xmms2.title) < 2
6226                                                 && strlen(cur->xmms2.title) < 2) {
6227                                         snprintf(p, p_max_size, "%s", cur->xmms2.url);
6228                                 } else {
6229                                         snprintf(p, p_max_size, "%s - %s", cur->xmms2.artist,
6230                                                 cur->xmms2.title);
6231                                 }
6232                         }
6233                         OBJ(if_xmms2_connected) {
6234                                 if (cur->xmms2_conn_state == 1) {
6235                                         if_jumped = 0;
6236                                 } else {
6237                                         i = obj->data.ifblock.pos;
6238                                         if_jumped = 1;
6239                                 }
6240                         }
6241 #endif
6242 #ifdef AUDACIOUS
6243                         OBJ(audacious_status) {
6244                                 snprintf(p, p_max_size, "%s",
6245                                         cur->audacious.items[AUDACIOUS_STATUS]);
6246                         }
6247                         OBJ(audacious_title) {
6248                                 snprintf(p, cur->audacious.max_title_len > 0
6249                                         ? cur->audacious.max_title_len : p_max_size, "%s",
6250                                         cur->audacious.items[AUDACIOUS_TITLE]);
6251                         }
6252                         OBJ(audacious_length) {
6253                                 snprintf(p, p_max_size, "%s",
6254                                         cur->audacious.items[AUDACIOUS_LENGTH]);
6255                         }
6256                         OBJ(audacious_length_seconds) {
6257                                 snprintf(p, p_max_size, "%s",
6258                                         cur->audacious.items[AUDACIOUS_LENGTH_SECONDS]);
6259                         }
6260                         OBJ(audacious_position) {
6261                                 snprintf(p, p_max_size, "%s",
6262                                         cur->audacious.items[AUDACIOUS_POSITION]);
6263                         }
6264                         OBJ(audacious_position_seconds) {
6265                                 snprintf(p, p_max_size, "%s",
6266                                         cur->audacious.items[AUDACIOUS_POSITION_SECONDS]);
6267                         }
6268                         OBJ(audacious_bitrate) {
6269                                 snprintf(p, p_max_size, "%s",
6270                                         cur->audacious.items[AUDACIOUS_BITRATE]);
6271                         }
6272                         OBJ(audacious_frequency) {
6273                                 snprintf(p, p_max_size, "%s",
6274                                         cur->audacious.items[AUDACIOUS_FREQUENCY]);
6275                         }
6276                         OBJ(audacious_channels) {
6277                                 snprintf(p, p_max_size, "%s",
6278                                         cur->audacious.items[AUDACIOUS_CHANNELS]);
6279                         }
6280                         OBJ(audacious_filename) {
6281                                 snprintf(p, p_max_size, "%s",
6282                                         cur->audacious.items[AUDACIOUS_FILENAME]);
6283                         }
6284                         OBJ(audacious_playlist_length) {
6285                                 snprintf(p, p_max_size, "%s",
6286                                         cur->audacious.items[AUDACIOUS_PLAYLIST_LENGTH]);
6287                         }
6288                         OBJ(audacious_playlist_position) {
6289                                 snprintf(p, p_max_size, "%s",
6290                                         cur->audacious.items[AUDACIOUS_PLAYLIST_POSITION]);
6291                         }
6292                         OBJ(audacious_main_volume) {
6293                                 snprintf(p, p_max_size, "%s",
6294                                         cur->audacious.items[AUDACIOUS_MAIN_VOLUME]);
6295                         }
6296                         OBJ(audacious_bar) {
6297                                 double progress;
6298
6299                                 progress =
6300                                         atof(cur->audacious.items[AUDACIOUS_POSITION_SECONDS]) /
6301                                         atof(cur->audacious.items[AUDACIOUS_LENGTH_SECONDS]);
6302                                 new_bar(p, obj->a, obj->b, (int) (progress * 255.0f));
6303                         }
6304 #endif
6305
6306 #ifdef BMPX
6307                         OBJ(bmpx_title) {
6308                                 snprintf(p, p_max_size, "%s", cur->bmpx.title);
6309                         }
6310                         OBJ(bmpx_artist) {
6311                                 snprintf(p, p_max_size, "%s", cur->bmpx.artist);
6312                         }
6313                         OBJ(bmpx_album) {
6314                                 snprintf(p, p_max_size, "%s", cur->bmpx.album);
6315                         }
6316                         OBJ(bmpx_uri) {
6317                                 snprintf(p, p_max_size, "%s", cur->bmpx.uri);
6318                         }
6319                         OBJ(bmpx_track) {
6320                                 snprintf(p, p_max_size, "%i", cur->bmpx.track);
6321                         }
6322                         OBJ(bmpx_bitrate) {
6323                                 snprintf(p, p_max_size, "%i", cur->bmpx.bitrate);
6324                         }
6325 #endif
6326                         OBJ(top) {
6327                                 if (obj->data.top.num >= 0 && obj->data.top.num < 10) {
6328                                         char *timeval;
6329
6330                                         switch (obj->data.top.type) {
6331                                                 case TOP_NAME:
6332                                                         snprintf(p, 16, "%-15s",
6333                                                                 cur->cpu[obj->data.top.num]->name);
6334                                                         break;
6335                                                 case TOP_CPU:
6336                                                         snprintf(p, 7, "%6.2f",
6337                                                                 cur->cpu[obj->data.top.num]->amount);
6338                                                         break;
6339                                                 case TOP_PID:
6340                                                         snprintf(p, 6, "%5i",
6341                                                                 cur->cpu[obj->data.top.num]->pid);
6342                                                         break;
6343                                                 case TOP_MEM:
6344                                                         snprintf(p, 7, "%6.2f",
6345                                                                 cur->cpu[obj->data.top.num]->totalmem);
6346                                                         break;
6347                                                 case TOP_TIME:
6348                                                         timeval = format_time(
6349                                                                 cur->cpu[obj->data.top.num]->total_cpu_time, 9);
6350                                                         snprintf(p, 10, "%9s", timeval);
6351                                                         free(timeval);
6352                                                         break;
6353                                                 case TOP_MEM_RES:
6354                                                         human_readable(cur->cpu[obj->data.top.num]->rss,
6355                                                                         p, 255, "top_rss");
6356                                                         break;
6357                                                 case TOP_MEM_VSIZE:
6358                                                         human_readable(cur->cpu[obj->data.top.num]->vsize,
6359                                                                         p, 255, "top_rss");
6360                                                         break;
6361                                                 default:
6362                                                         ERR("Unhandled top data type: %d\n",
6363                                                                 obj->data.top.type);
6364                                         }
6365                                 } else {
6366                                         ERR("Top index < 0 or > 10: %d\n", obj->data.top.num);
6367                                 }
6368                         }
6369                         OBJ(top_mem) {
6370                                 if (obj->data.top.num >= 0 && obj->data.top.num < 10) {
6371                                         char *timeval;
6372
6373                                         switch (obj->data.top.type) {
6374                                                 case TOP_NAME:
6375                                                         snprintf(p, 16, "%-15s",
6376                                                                 cur->memu[obj->data.top.num]->name);
6377                                                         break;
6378                                                 case TOP_CPU:
6379                                                         snprintf(p, 7, "%6.2f",
6380                                                                 cur->memu[obj->data.top.num]->amount);
6381                                                         break;
6382                                                 case TOP_PID:
6383                                                         snprintf(p, 6, "%5i",
6384                                                                 cur->memu[obj->data.top.num]->pid);
6385                                                         break;
6386                                                 case TOP_MEM:
6387                                                         snprintf(p, 7, "%6.2f",
6388                                                                 cur->memu[obj->data.top.num]->totalmem);
6389                                                         break;
6390                                                 case TOP_TIME:
6391                                                         timeval = format_time(
6392                                                                 cur->memu[obj->data.top.num]->total_cpu_time,
6393                                                                 9);
6394                                                         snprintf(p, 10, "%9s", timeval);
6395                                                         free(timeval);
6396                                                         break;
6397                                                 case TOP_MEM_RES:
6398                                                         human_readable(cur->cpu[obj->data.top.num]->rss,
6399                                                                         p, 255, "top_rss");
6400                                                         break;
6401                                                 case TOP_MEM_VSIZE:
6402                                                         human_readable(cur->cpu[obj->data.top.num]->vsize,
6403                                                                         p, 255, "top_rss");
6404                                                         break;
6405                                                 default:
6406                                                         ERR("Unhandled top data type: %d\n",
6407                                                                 obj->data.top.type);
6408                                         }
6409                                 } else {
6410                                         ERR("Top index < 0 or > 10: %d\n", obj->data.top.num);
6411                                 }
6412                         }
6413                         OBJ(tail) {
6414                                 if (current_update_time - obj->data.tail.last_update
6415                                                 < obj->data.tail.interval) {
6416                                         snprintf(p, p_max_size, "%s", obj->data.tail.buffer);
6417                                 } else {
6418                                         FILE *fp;
6419                                         long nl = 0, bsize;
6420                                         int iter;
6421
6422                                         obj->data.tail.last_update = current_update_time;
6423
6424                                         if (obj->data.tail.fd != -1) {
6425                                                 tail_pipe(obj, p, p_max_size);
6426                                                 goto head;
6427                                         }
6428
6429                                         fp = fopen(obj->data.tail.logfile, "rt");
6430
6431                                         if (fp == NULL) {
6432                                                 /* Send one message, but do not consistently spam
6433                                                  * on missing logfiles. */
6434                                                 if (obj->data.tail.readlines != 0) {
6435                                                         ERR("tail logfile failed to open");
6436                                                         strcpy(obj->data.tail.buffer, "Logfile Missing");
6437                                                 }
6438                                                 obj->data.tail.readlines = 0;
6439                                                 snprintf(p, p_max_size, "Logfile Missing");
6440                                         } else {
6441                                                 obj->data.tail.readlines = 0;
6442                                                 /* -1 instead of 0 to avoid counting a trailing
6443                                                  * newline */
6444                                                 fseek(fp, -1, SEEK_END);
6445                                                 bsize = ftell(fp) + 1;
6446                                                 for (iter = obj->data.tail.wantedlines; iter > 0;
6447                                                                 iter--) {
6448                                                         nl = rev_fcharfind(fp, '\n', iter);
6449                                                         if (nl >= 0) {
6450                                                                 break;
6451                                                         }
6452                                                 }
6453                                                 obj->data.tail.readlines = iter;
6454                                                 if (obj->data.tail.readlines
6455                                                                 < obj->data.tail.wantedlines) {
6456                                                         fseek(fp, 0, SEEK_SET);
6457                                                 } else {
6458                                                         fseek(fp, nl + 1, SEEK_SET);
6459                                                         bsize -= ftell(fp);
6460                                                 }
6461                                                 /* Make sure bsize is at least 1 byte smaller than the
6462                                                  * buffer max size. */
6463                                                 if (bsize > (long) ((text_buffer_size * 20) - 1)) {
6464                                                         fseek(fp, bsize - text_buffer_size * 20 - 1,
6465                                                                 SEEK_CUR);
6466                                                         bsize = text_buffer_size * 20 - 1;
6467                                                 }
6468                                                 bsize = fread(obj->data.tail.buffer, 1, bsize, fp);
6469                                                 fclose(fp);
6470                                                 if (bsize > 0) {
6471                                                         /* Clean up trailing newline, make sure the
6472                                                          * buffer is null terminated. */
6473                                                         if (obj->data.tail.buffer[bsize - 1] == '\n') {
6474                                                                 obj->data.tail.buffer[bsize - 1] = '\0';
6475                                                         } else {
6476                                                                 obj->data.tail.buffer[bsize] = '\0';
6477                                                         }
6478                                                         snprintf(p, p_max_size, "%s",
6479                                                                 obj->data.tail.buffer);
6480                                                 } else {
6481                                                         strcpy(obj->data.tail.buffer, "Logfile Empty");
6482                                                         snprintf(p, p_max_size, "Logfile Empty");
6483                                                 }       /* bsize > 0 */
6484                                         }               /* fp == NULL */
6485                                 }                       /* if cur_upd_time >= */
6486                                 // parse_conky_vars(obj->data.tail.buffer, p, cur);
6487                         }
6488 head:
6489                         OBJ(head) {
6490                                 if (current_update_time - obj->data.tail.last_update
6491                                                 < obj->data.tail.interval) {
6492                                         snprintf(p, p_max_size, "%s", obj->data.tail.buffer);
6493                                 } else {
6494                                         FILE *fp;
6495                                         long nl = 0;
6496                                         int iter;
6497
6498                                         obj->data.tail.last_update = current_update_time;
6499
6500                                         fp = fopen(obj->data.tail.logfile, "rt");
6501                                         if (fp == NULL) {
6502                                                 /* Send one message, but do not consistently spam
6503                                                  * on missing logfiles. */
6504                                                 if (obj->data.tail.readlines != 0) {
6505                                                         ERR("head logfile failed to open");
6506                                                         strcpy(obj->data.tail.buffer, "Logfile Missing");
6507                                                 }
6508                                                 obj->data.tail.readlines = 0;
6509                                                 snprintf(p, p_max_size, "Logfile Missing");
6510                                         } else {
6511                                                 obj->data.tail.readlines = 0;
6512                                                 for (iter = obj->data.tail.wantedlines; iter > 0;
6513                                                                 iter--) {
6514                                                         nl = fwd_fcharfind(fp, '\n', iter);
6515                                                         if (nl >= 0) {
6516                                                                 break;
6517                                                         }
6518                                                 }
6519                                                 obj->data.tail.readlines = iter;
6520                                                 /* Make sure nl is at least 1 byte smaller than the
6521                                                  * buffer max size. */
6522                                                 if (nl > (long) ((text_buffer_size * 20) - 1)) {
6523                                                         nl = text_buffer_size * 20 - 1;
6524                                                 }
6525                                                 nl = fread(obj->data.tail.buffer, 1, nl, fp);
6526                                                 fclose(fp);
6527                                                 if (nl > 0) {
6528                                                         /* Clean up trailing newline, make sure the buffer
6529                                                          * is null terminated. */
6530                                                         if (obj->data.tail.buffer[nl - 1] == '\n') {
6531                                                                 obj->data.tail.buffer[nl - 1] = '\0';
6532                                                         } else {
6533                                                                 obj->data.tail.buffer[nl] = '\0';
6534                                                         }
6535                                                         snprintf(p, p_max_size, "%s",
6536                                                                 obj->data.tail.buffer);
6537                                                 } else {
6538                                                         strcpy(obj->data.tail.buffer, "Logfile Empty");
6539                                                         snprintf(p, p_max_size, "Logfile Empty");
6540                                                 }       /* nl > 0 */
6541                                         }               /* if fp == null */
6542                                 }                       /* cur_upd_time >= */
6543                                 // parse_conky_vars(obj->data.tail.buffer, p, cur);
6544                         }
6545
6546                         OBJ(lines) {
6547                                 FILE *fp = fopen(obj->data.s,"r");
6548
6549                                 if(fp != NULL) {
6550                                         char buf[BUFSZ];
6551                                         int j, lines;
6552
6553                                         lines = 0;
6554                                         while(fgets(buf, BUFSZ, fp) != NULL){
6555                                                 for(j = 0; buf[j] != 0; j++) {
6556                                                         if(buf[j] == '\n') {
6557                                                                 lines++;
6558                                                         }
6559                                                 }
6560                                         }
6561                                         sprintf(p, "%d", lines);
6562                                         fclose(fp);
6563                                 } else {
6564                                         sprintf(p, "File Unreadable");
6565                                 }
6566                         }
6567
6568                         OBJ(words) {
6569                                 FILE *fp = fopen(obj->data.s,"r");
6570
6571                                 if(fp != NULL) {
6572                                         char buf[BUFSZ];
6573                                         int j, words;
6574                                         char inword = FALSE;
6575
6576                                         words = 0;
6577                                         while(fgets(buf, BUFSZ, fp) != NULL){
6578                                                 for(j = 0; buf[j] != 0; j++) {
6579                                                         if(!isspace(buf[j])) {
6580                                                                 if(inword == FALSE) {
6581                                                                         words++;
6582                                                                         inword = TRUE;
6583                                                                 }
6584                                                         } else {
6585                                                                 inword = FALSE;
6586                                                         }
6587                                                 }
6588                                         }
6589                                         sprintf(p, "%d", words);
6590                                         fclose(fp);
6591                                 } else {
6592                                         sprintf(p, "File Unreadable");
6593                                 }
6594                         }
6595 #ifdef TCP_PORT_MONITOR
6596                         OBJ(tcp_portmon) {
6597                                 /* grab a pointer to this port monitor */
6598                                 tcp_port_monitor_t *p_monitor =
6599                                         find_tcp_port_monitor(info.p_tcp_port_monitor_collection,
6600                                         obj->data.tcp_port_monitor.port_range_begin,
6601                                         obj->data.tcp_port_monitor.port_range_end);
6602
6603                                 if (!p_monitor) {
6604                                         snprintf(p, p_max_size, "monitor not found");
6605                                         break;
6606                                 }
6607
6608                                 /* now grab the text of interest */
6609                                 if (peek_tcp_port_monitor(p_monitor,
6610                                                 obj->data.tcp_port_monitor.item,
6611                                                 obj->data.tcp_port_monitor.connection_index, p,
6612                                                 p_max_size) != 0) {
6613                                         snprintf(p, p_max_size, "monitor peek error");
6614                                         break;
6615                                 }
6616                         }
6617 #endif
6618
6619 #ifdef HAVE_ICONV
6620                         OBJ(iconv_start) {
6621                                 iconv_converting = 1;
6622                                 iconv_selected = obj->a;
6623                         }
6624                         OBJ(iconv_stop) {
6625                                 iconv_converting = 0;
6626                                 iconv_selected = 0;
6627                         }
6628 #endif
6629
6630                         OBJ(entropy_avail) {
6631                                 snprintf(p, p_max_size, "%d", cur->entropy.entropy_avail);
6632                         }
6633                         OBJ(entropy_poolsize) {
6634                                 snprintf(p, p_max_size, "%d", cur->entropy.poolsize);
6635                         }
6636                         OBJ(entropy_bar) {
6637                                 double entropy_perc;
6638
6639                                 entropy_perc = (double) cur->entropy.entropy_avail /
6640                                         (double) cur->entropy.poolsize;
6641                                 new_bar(p, obj->a, obj->b, (int) (entropy_perc * 255.0f));
6642                         }
6643 #ifdef SMAPI
6644                         OBJ(smapi) {
6645                                 char *s;
6646                                 if(obj->data.s) {
6647                                         s = smapi_get_val(obj->data.s);
6648                                         snprintf(p, p_max_size, "%s", s);
6649                                         free(s);
6650                                 }
6651                         }
6652                         OBJ(if_smapi_bat_installed) {
6653                                 int idx;
6654                                 if(obj->data.ifblock.s && sscanf(obj->data.ifblock.s, "%i", &idx) == 1) {
6655                                         if(!smapi_bat_installed(idx)) {
6656                                                 i = obj->data.ifblock.pos;
6657                                                 if_jumped = 1;
6658                                         } else
6659                                                 if_jumped = 0;
6660                                 } else
6661                                         ERR("argument to if_smapi_bat_installed must be an integer");
6662                         }
6663                         OBJ(smapi_bat_perc) {
6664                                 int idx, val;
6665                                 if(obj->data.s && sscanf(obj->data.s, "%i", &idx) == 1) {
6666                                         val = smapi_bat_installed(idx) ?
6667                                                 smapi_get_bat_int(idx, "remaining_percent") : 0;
6668                                         spaced_print(p, p_max_size, "%*d", 4, "smapi_bat_perc", pad_percents, val);
6669                                 } else
6670                                         ERR("argument to smapi_bat_perc must be an integer");
6671                         }
6672                         OBJ(smapi_bat_temp) {
6673                                 int idx, val;
6674                                 if(obj->data.s && sscanf(obj->data.s, "%i", &idx) == 1) {
6675                                         val = smapi_bat_installed(idx) ?
6676                                                 smapi_get_bat_int(idx, "temperature") : 0;
6677                                         /* temperature is in milli degree celsius */
6678                                         temp_print(p, p_max_size, val / 1000, TEMP_CELSIUS);
6679                                 } else
6680                                         ERR("argument to smapi_bat_temp must be an integer");
6681                         }
6682                         OBJ(smapi_bat_power) {
6683                                 int idx, val;
6684                                 if(obj->data.s && sscanf(obj->data.s, "%i", &idx) == 1) {
6685                                         val = smapi_bat_installed(idx) ?
6686                                                 smapi_get_bat_int(idx, "power_now") : 0;
6687                                         /* power_now is in mW, set to W with one digit precision */
6688                                         snprintf(p, p_max_size, "%.1f", ((double)val / 1000));
6689                                 } else
6690                                         ERR("argument to smapi_bat_power must be an integer");
6691                         }
6692                         OBJ(smapi_bat_bar) {
6693                                 if(obj->data.i >= 0 && smapi_bat_installed(obj->data.i))
6694                                         new_bar(p, obj->a, obj->b, (int)
6695                                                         (255 * smapi_get_bat_int(obj->data.i, "remaining_percent") / 100));
6696                                 else
6697                                         new_bar(p, obj->a, obj->b, 0);
6698                         }
6699 #endif /* SMAPI */
6700                         OBJ(scroll) {
6701                                 unsigned int j;
6702                                 char *tmp;
6703                                 parse_conky_vars(obj->data.scroll.text, p, cur);
6704                                 
6705                                 if (strlen(p) <= obj->data.scroll.show) {
6706                                         break;
6707                                 }
6708 #define LINESEPARATOR '|'
6709                                 //place all the lines behind each other with LINESEPARATOR between them
6710                                 for(j = 0; p[j] != 0; j++) {
6711                                         if(p[j]=='\n') {
6712                                                 p[j]=LINESEPARATOR;
6713                                         }
6714                                 }
6715                                 //scroll the output obj->data.scroll.start places by copying that many chars from
6716                                 //the front of the string to tmp, scrolling the rest to the front and placing tmp
6717                                 //at the back of the string
6718                                 tmp = calloc(obj->data.scroll.start + 1, sizeof(char));
6719                                 strncpy(tmp, p, obj->data.scroll.start); tmp[obj->data.scroll.start] = 0;
6720                                 for(j = obj->data.scroll.start; p[j] != 0; j++){
6721                                         p[j - obj->data.scroll.start] = p[j];
6722                                 }
6723                                 strcpy(&p[j - obj->data.scroll.start], tmp);
6724                                 free(tmp);
6725                                 //only show the requested number of chars
6726                                 if(obj->data.scroll.show < j) {
6727                                         p[obj->data.scroll.show] = 0;
6728                                 }
6729                                 //next time, scroll a place more or reset scrolling if we are at the end
6730                                 obj->data.scroll.start += obj->data.scroll.step;
6731                                 if(obj->data.scroll.start >= j){
6732                                          obj->data.scroll.start = 0;
6733                                 }
6734                         }
6735 #ifdef NVIDIA
6736                         OBJ(nvidia) {
6737                                 int value = get_nvidia_value(obj->data.nvidia.type, display);
6738                                 if(value == -1)
6739                                         snprintf(p, p_max_size, "N/A");
6740                                 else if (obj->data.nvidia.type == NV_TEMP)
6741                                         temp_print(p, p_max_size, (double)value, TEMP_CELSIUS);
6742                                 else if (obj->data.nvidia.print_as_float &&
6743                                                 value > 0 && value < 100)
6744                                         snprintf(p, p_max_size, "%.1f", (float)value);
6745                                 else
6746                                         snprintf(p, p_max_size, "%d", value);
6747                         }
6748 #endif /* NVIDIA */
6749
6750                         break;
6751                 }
6752
6753                 {
6754                         unsigned int a = strlen(p);
6755
6756 #ifdef HAVE_ICONV
6757                         if (a > 0 && iconv_converting && iconv_selected > 0
6758                                         && (iconv_cd[iconv_selected - 1] != (iconv_t) (-1))) {
6759                                 int bytes;
6760                                 size_t dummy1, dummy2;
6761                                 char *ptr = buff_in;
6762                                 char *outptr = p;
6763
6764                                 dummy1 = dummy2 = a;
6765
6766                                 strncpy(buff_in, p, p_max_size);
6767
6768                                 iconv(*iconv_cd[iconv_selected - 1], NULL, NULL, NULL, NULL);
6769                                 while (dummy1 > 0) {
6770                                         bytes = iconv(*iconv_cd[iconv_selected - 1], &ptr, &dummy1,
6771                                                         &outptr, &dummy2);
6772                                         if (bytes == -1) {
6773                                                 ERR("Iconv codeset conversion failed");
6774                                                 break;
6775                                         }
6776                                 }
6777
6778                                 /* It is nessecary when we are converting from multibyte to
6779                                  * singlebyte codepage */
6780                                 a = outptr - p;
6781                         }
6782 #endif /* HAVE_ICONV */
6783                         p += a;
6784                         p_max_size -= a;
6785                 }
6786         }
6787 }
6788
6789 double current_update_time, next_update_time, last_update_time;
6790
6791 static void generate_text(void)
6792 {
6793         struct information *cur = &info;
6794         char *p;
6795
6796         special_count = 0;
6797
6798         /* update info */
6799
6800         current_update_time = get_time();
6801
6802         update_stuff();
6803         /* fix diskio rates to b/s (use update_interval */
6804         info.diskio_read_value /= update_interval;
6805         info.diskio_write_value /= update_interval;
6806         info.diskio_value /= update_interval;
6807
6808         /* add things to the buffer */
6809
6810         /* generate text */
6811
6812         p = text_buffer;
6813
6814         generate_text_internal(p, max_user_text, global_text_object_list, cur);
6815
6816         if (stuff_in_upper_case) {
6817                 char *tmp_p;
6818
6819                 tmp_p = text_buffer;
6820                 while (*tmp_p) {
6821                         *tmp_p = toupper(*tmp_p);
6822                         tmp_p++;
6823                 }
6824         }
6825
6826         next_update_time += update_interval;
6827         if (next_update_time < get_time()) {
6828                 next_update_time = get_time() + update_interval;
6829         } else if (next_update_time > get_time() + update_interval) {
6830                 next_update_time = get_time() + update_interval;
6831         }
6832         last_update_time = current_update_time;
6833         total_updates++;
6834         // free(p);
6835 }
6836
6837 #ifdef X11
6838 static void set_font(void)
6839 {
6840 #ifdef XFT
6841         if (use_xft) {
6842                 if (window.xftdraw != NULL) {
6843                         XftDrawDestroy(window.xftdraw);
6844                 }
6845                 window.xftdraw = XftDrawCreate(display, window.drawable,
6846                         DefaultVisual(display, screen), DefaultColormap(display, screen));
6847         } else
6848 #endif
6849         {
6850                 XSetFont(display, window.gc, fonts[selected_font].font->fid);
6851         }
6852 }
6853
6854 #endif /* X11 */
6855
6856 static inline int get_string_width(const char *s)
6857 {
6858 #ifdef X11
6859         return *s ? calc_text_width(s, strlen(s)) : 0;
6860 #else
6861         return strlen(s);
6862 #endif /* X11 */
6863 }
6864
6865 static inline int get_string_width_special(char *s)
6866 {
6867 #ifdef X11
6868         char *p, *final;
6869         int idx = 1;
6870         int width = 0;
6871         unsigned int i;
6872
6873         if (!s) {
6874                 return 0;
6875         }
6876
6877         p = strndup(s, text_buffer_size);
6878         final = p;
6879
6880         while (*p) {
6881                 if (*p == SPECIAL_CHAR) {
6882                         /* shift everything over by 1 so that the special char
6883                          * doesn't mess up the size calculation */
6884                         for (i = 0; i < strlen(p); i++) {
6885                                 *(p + i) = *(p + i + 1);
6886                         }
6887                         if (specials[special_index + idx].type == GRAPH
6888                                         || specials[special_index + idx].type == BAR) {
6889                                 width += specials[special_index + idx].width;
6890                         }
6891                         idx++;
6892                 } else {
6893                         p++;
6894                 }
6895         }
6896         if (strlen(final) > 1) {
6897                 width += calc_text_width(final, strlen(final));
6898         }
6899         free(final);
6900         return width;
6901 #else
6902         return (s) ? strlen(s) : 0;
6903 #endif /* X11 */
6904 }
6905
6906 #ifdef X11
6907 static void text_size_updater(char *s);
6908
6909 int last_font_height;
6910 static void update_text_area(void)
6911 {
6912         int x, y;
6913
6914         /* update text size if it isn't fixed */
6915 #ifdef OWN_WINDOW
6916         if (!fixed_size)
6917 #endif
6918         {
6919                 text_width = minimum_width;
6920                 text_height = 0;
6921                 special_index = 0;
6922                 last_font_height = font_height();
6923                 for_each_line(text_buffer, text_size_updater);
6924                 text_width += 1;
6925                 if (text_height < minimum_height) {
6926                         text_height = minimum_height;
6927                 }
6928                 if (text_width > maximum_width && maximum_width > 0) {
6929                         text_width = maximum_width;
6930                 }
6931         }
6932
6933         /* get text position on workarea */
6934         switch (text_alignment) {
6935                 case TOP_LEFT:
6936                         x = gap_x;
6937                         y = gap_y;
6938                         break;
6939
6940                 case TOP_RIGHT:
6941                         x = workarea[2] - text_width - gap_x;
6942                         y = gap_y;
6943                         break;
6944
6945                 case TOP_MIDDLE:
6946                         x = workarea[2] / 2 - text_width / 2 - gap_x;
6947                         y = gap_y;
6948                         break;
6949
6950                 default:
6951                 case BOTTOM_LEFT:
6952                         x = gap_x;
6953                         y = workarea[3] - text_height - gap_y;
6954                         break;
6955
6956                 case BOTTOM_RIGHT:
6957                         x = workarea[2] - text_width - gap_x;
6958                         y = workarea[3] - text_height - gap_y;
6959                         break;
6960
6961                 case BOTTOM_MIDDLE:
6962                         x = workarea[2] / 2 - text_width / 2 - gap_x;
6963                         y = workarea[3] - text_height - gap_y;
6964                         break;
6965
6966                 case MIDDLE_LEFT:
6967                         x = gap_x;
6968                         y = workarea[3] / 2 - text_height / 2 - gap_y;
6969                         break;
6970
6971                 case MIDDLE_RIGHT:
6972                         x = workarea[2] - text_width - gap_x;
6973                         y = workarea[3] / 2 - text_height / 2 - gap_y;
6974                         break;
6975
6976 #ifdef OWN_WINDOW
6977                 case NONE:      // Let the WM manage the window
6978                         x = window.x;
6979                         y = window.y;
6980
6981                         fixed_pos = 1;
6982                         fixed_size = 1;
6983                         break;
6984 #endif
6985         }
6986 #ifdef OWN_WINDOW
6987
6988         if (own_window && !fixed_pos) {
6989                 x += workarea[0];
6990                 y += workarea[1];
6991                 text_start_x = border_margin + 1;
6992                 text_start_y = border_margin + 1;
6993                 window.x = x - border_margin - 1;
6994                 window.y = y - border_margin - 1;
6995         } else
6996 #endif
6997         {
6998                 /* If window size doesn't match to workarea's size,
6999                  * then window probably includes panels (gnome).
7000                  * Blah, doesn't work on KDE. */
7001                 if (workarea[2] != window.width || workarea[3] != window.height) {
7002                         y += workarea[1];
7003                         x += workarea[0];
7004                 }
7005
7006                 text_start_x = x;
7007                 text_start_y = y;
7008         }
7009 }
7010
7011 /* drawing stuff */
7012
7013 static int cur_x, cur_y;        /* current x and y for drawing */
7014 #endif
7015 //draw_mode also without X11 because we only need to print to stdout with FG
7016 static int draw_mode;           /* FG, BG or OUTLINE */
7017 #ifdef X11
7018 static long current_color;
7019
7020 #ifdef X11
7021 static void text_size_updater(char *s)
7022 {
7023         int w = 0;
7024         char *p;
7025
7026         /* get string widths and skip specials */
7027         p = s;
7028         while (*p) {
7029                 if (*p == SPECIAL_CHAR) {
7030                         *p = '\0';
7031                         w += get_string_width(s);
7032                         *p = SPECIAL_CHAR;
7033
7034                         if (specials[special_index].type == BAR
7035                                         || specials[special_index].type == GRAPH) {
7036                                 w += specials[special_index].width;
7037                                 if (specials[special_index].height > last_font_height) {
7038                                         last_font_height = specials[special_index].height;
7039                                         last_font_height += font_ascent();
7040                                 }
7041                         } else if (specials[special_index].type == OFFSET) {
7042                                 if (specials[special_index].arg > 0) {
7043                                         w += specials[special_index].arg;
7044                                 }
7045                         } else if (specials[special_index].type == VOFFSET) {
7046                                 last_font_height += specials[special_index].arg;
7047                         } else if (specials[special_index].type == GOTO) {
7048                                 if (specials[special_index].arg > cur_x) {
7049                                         w = (int) specials[special_index].arg;
7050                                 }
7051                         } else if (specials[special_index].type == TAB) {
7052                                 int start = specials[special_index].arg;
7053                                 int step = specials[special_index].width;
7054
7055                                 if (!step || step < 0) {
7056                                         step = 10;
7057                                 }
7058                                 w += step - (cur_x - text_start_x - start) % step;
7059                         } else if (specials[special_index].type == FONT) {
7060                                 selected_font = specials[special_index].font_added;
7061                                 if (font_height() > last_font_height) {
7062                                         last_font_height = font_height();
7063                                 }
7064                         }
7065
7066                         special_index++;
7067                         s = p + 1;
7068                 }
7069                 p++;
7070         }
7071         w += get_string_width(s);
7072         if (w > text_width) {
7073                 text_width = w;
7074         }
7075         if (text_width > maximum_width && maximum_width) {
7076                 text_width = maximum_width;
7077         }
7078
7079         text_height += last_font_height;
7080         last_font_height = font_height();
7081 }
7082 #endif /* X11 */
7083
7084 static inline void set_foreground_color(long c)
7085 {
7086         current_color = c;
7087         XSetForeground(display, window.gc, c);
7088 }
7089 #endif /* X11 */
7090
7091 static void draw_string(const char *s)
7092 {
7093         int i, i2, pos, width_of_s;
7094         int max = 0;
7095         int added;
7096
7097         if (s[0] == '\0') {
7098                 return;
7099         }
7100
7101         width_of_s = get_string_width(s);
7102         if ((output_methods & TO_STDOUT) && draw_mode == FG) {
7103                 printf("%s\n", s);
7104                 fflush(stdout); /* output immediately, don't buffer */
7105         }
7106         memset(tmpstring1, 0, text_buffer_size);
7107         memset(tmpstring2, 0, text_buffer_size);
7108         strncpy(tmpstring1, s, text_buffer_size - 1);
7109         pos = 0;
7110         added = 0;
7111
7112 #ifdef X11
7113         max = ((text_width - width_of_s) / get_string_width(" "));
7114 #endif /* X11 */
7115         /* This code looks for tabs in the text and coverts them to spaces.
7116          * The trick is getting the correct number of spaces, and not going
7117          * over the window's size without forcing the window larger. */
7118         for (i = 0; i < (int) text_buffer_size; i++) {
7119                 if (tmpstring1[i] == '\t') {
7120                         i2 = 0;
7121                         for (i2 = 0; i2 < (8 - (1 + pos) % 8) && added <= max; i2++) {
7122                                 /* guard against overrun */
7123                                 tmpstring2[MIN(pos + i2, (int)text_buffer_size - 1)] = ' ';
7124                                 added++;
7125                         }
7126                         pos += i2;
7127                 } else {
7128                         /* guard against overrun */
7129                         tmpstring2[MIN(pos, (int) text_buffer_size - 1)] = tmpstring1[i];
7130                         pos++;
7131                 }
7132         }
7133 #ifdef X11
7134         if (text_width == maximum_width) {
7135                 /* this means the text is probably pushing the limit,
7136                  * so we'll chop it */
7137                 while (cur_x + get_string_width(tmpstring2) - text_start_x
7138                                 > maximum_width && strlen(tmpstring2) > 0) {
7139                         tmpstring2[strlen(tmpstring2) - 1] = '\0';
7140                 }
7141         }
7142 #endif /* X11 */
7143         s = tmpstring2;
7144 #ifdef X11
7145 #ifdef XFT
7146         if (use_xft) {
7147                 XColor c;
7148                 XftColor c2;
7149
7150                 c.pixel = current_color;
7151                 XQueryColor(display, DefaultColormap(display, screen), &c);
7152
7153                 c2.pixel = c.pixel;
7154                 c2.color.red = c.red;
7155                 c2.color.green = c.green;
7156                 c2.color.blue = c.blue;
7157                 c2.color.alpha = fonts[selected_font].font_alpha;
7158                 if (utf8_mode) {
7159                         XftDrawStringUtf8(window.xftdraw, &c2, fonts[selected_font].xftfont,
7160                                 cur_x, cur_y, (const XftChar8 *) s, strlen(s));
7161                 } else {
7162                         XftDrawString8(window.xftdraw, &c2, fonts[selected_font].xftfont,
7163                                 cur_x, cur_y, (const XftChar8 *) s, strlen(s));
7164                 }
7165         } else
7166 #endif
7167         {
7168                 XDrawString(display, window.drawable, window.gc, cur_x, cur_y, s,
7169                         strlen(s));
7170         }
7171         cur_x += width_of_s;
7172 #endif /* X11 */
7173         memcpy(tmpstring1, s, text_buffer_size);
7174 }
7175
7176 long redmask, greenmask, bluemask;
7177
7178 void set_up_gradient(void)
7179 {
7180         int i;
7181 #ifdef X11
7182         colour_depth = DisplayPlanes(display, screen);
7183 #else
7184         colour_depth = 16;
7185 #endif /* X11 */
7186         if (colour_depth != 24 && colour_depth != 16) {
7187                 ERR("using non-standard colour depth, gradients may look like a "
7188                         "lolly-pop");
7189         }
7190
7191         redmask = 0;
7192         greenmask = 0;
7193         bluemask = 0;
7194         for (i = (colour_depth / 3) - 1; i >= 0; i--) {
7195                 redmask |= 1 << i;
7196                 greenmask |= 1 << i;
7197                 bluemask |= 1 << i;
7198         }
7199         if (colour_depth % 3 == 1) {
7200                 greenmask |= 1 << (colour_depth / 3);
7201         }
7202         redmask = redmask << (2 * colour_depth / 3 + colour_depth % 3);
7203         greenmask = greenmask << (colour_depth / 3);
7204 }
7205
7206 /* this function returns the next colour between two colours for a gradient */
7207 unsigned long do_gradient(unsigned long first_colour,
7208                 unsigned long last_colour)
7209 {
7210         int tmp_color = 0;
7211         int red1, green1, blue1;                                // first colour
7212         int red2, green2, blue2;                                // second colour
7213         int red3 = 0, green3 = 0, blue3 = 0;    // difference
7214         short redshift = (2 * colour_depth / 3 + colour_depth % 3);
7215         short greenshift = (colour_depth / 3);
7216
7217         red1 = (first_colour & redmask) >> redshift;
7218         green1 = (first_colour & greenmask) >> greenshift;
7219         blue1 = first_colour & bluemask;
7220         red2 = (last_colour & redmask) >> redshift;
7221         green2 = (last_colour & greenmask) >> greenshift;
7222         blue2 = last_colour & bluemask;
7223         if (red1 > red2) {
7224                 red3 = -1;
7225         }
7226         if (red1 < red2) {
7227                 red3 = 1;
7228         }
7229         if (green1 > green2) {
7230                 green3 = -1;
7231         }
7232         if (green1 < green2) {
7233                 green3 = 1;
7234         }
7235         if (blue1 > blue2) {
7236                 blue3 = -1;
7237         }
7238         if (blue1 < blue2) {
7239                 blue3 = 1;
7240         }
7241         red1 += red3;
7242         green1 += green3;
7243         blue1 += blue3;
7244         if (red1 < 0) {
7245                 red1 = 0;
7246         }
7247         if (green1 < 0) {
7248                 green1 = 0;
7249         }
7250         if (blue1 < 0) {
7251                 blue1 = 0;
7252         }
7253         if (red1 > bluemask) {
7254                 red1 = bluemask;
7255         }
7256         if (green1 > bluemask) {
7257                 green1 = bluemask;
7258         }
7259         if (blue1 > bluemask) {
7260                 blue1 = bluemask;
7261         }
7262         tmp_color = (red1 << redshift) | (green1 << greenshift) | blue1;
7263         return tmp_color;
7264 }
7265
7266 /* this function returns the max diff for a gradient */
7267 unsigned long gradient_max(unsigned long first_colour,
7268                 unsigned long last_colour)
7269 {
7270         int red1, green1, blue1;                                // first colour
7271         int red2, green2, blue2;                                // second colour
7272         int red3 = 0, green3 = 0, blue3 = 0;                    // difference
7273         long redshift, greenshift;
7274         int max;
7275
7276         if (colour_depth == 0) {
7277                 set_up_gradient();
7278         }
7279         redshift = (2 * colour_depth / 3 + colour_depth % 3);
7280         greenshift = (colour_depth / 3);
7281
7282         red1 = (first_colour & redmask) >> redshift;
7283         green1 = (first_colour & greenmask) >> greenshift;
7284         blue1 = first_colour & bluemask;
7285         red2 = (last_colour & redmask) >> redshift;
7286         green2 = (last_colour & greenmask) >> greenshift;
7287         blue2 = last_colour & bluemask;
7288         red3 = abs(red1 - red2);
7289         green3 = abs(green1 - green2);
7290         blue3 = abs(blue1 - blue2);
7291         max = red3;
7292
7293         if (green3 > max) {
7294                 max = green3;
7295         }
7296         if (blue3 > max) {
7297                 max = blue3;
7298         }
7299         return max;
7300 }
7301
7302 static void draw_line(char *s)
7303 {
7304 #ifdef X11
7305         char *p;
7306         int cur_y_add = 0;
7307         short font_h;
7308         char *tmp_str;
7309
7310         cur_x = text_start_x;
7311         cur_y += font_ascent();
7312         font_h = font_height();
7313
7314         /* find specials and draw stuff */
7315         p = s;
7316         while (*p) {
7317                 if (*p == SPECIAL_CHAR) {
7318                         int w = 0;
7319
7320                         /* draw string before special */
7321                         *p = '\0';
7322                         draw_string(s);
7323                         *p = SPECIAL_CHAR;
7324                         s = p + 1;
7325
7326                         /* draw special */
7327                         switch (specials[special_index].type) {
7328                                 case HORIZONTAL_LINE:
7329                                 {
7330                                         int h = specials[special_index].height;
7331                                         int mid = font_ascent() / 2;
7332
7333                                         w = text_start_x + text_width - cur_x;
7334
7335                                         XSetLineAttributes(display, window.gc, h, LineSolid,
7336                                                 CapButt, JoinMiter);
7337                                         XDrawLine(display, window.drawable, window.gc, cur_x,
7338                                                 cur_y - mid / 2, cur_x + w, cur_y - mid / 2);
7339                                         break;
7340                                 }
7341
7342                                 case STIPPLED_HR:
7343                                 {
7344                                         int h = specials[special_index].height;
7345                                         int tmp_s = specials[special_index].arg;
7346                                         int mid = font_ascent() / 2;
7347                                         char ss[2] = { tmp_s, tmp_s };
7348
7349                                         w = text_start_x + text_width - cur_x - 1;
7350                                         XSetLineAttributes(display, window.gc, h, LineOnOffDash,
7351                                                 CapButt, JoinMiter);
7352                                         XSetDashes(display, window.gc, 0, ss, 2);
7353                                         XDrawLine(display, window.drawable, window.gc, cur_x,
7354                                                 cur_y - mid / 2, cur_x + w, cur_y - mid / 2);
7355                                         break;
7356                                 }
7357
7358                                 case BAR:
7359                                 {
7360                                         int h, bar_usage, by;
7361                                         if (cur_x - text_start_x > maximum_width
7362                                                         && maximum_width > 0) {
7363                                                 break;
7364                                         }
7365                                         h = specials[special_index].height;
7366                                         bar_usage = specials[special_index].arg;
7367                                         by = cur_y - (font_ascent() / 2) - 1;
7368
7369                                         if (h < font_height()) {
7370                                                 by -= h / 2 - 1;
7371                                         }
7372                                         w = specials[special_index].width;
7373                                         if (w == 0) {
7374                                                 w = text_start_x + text_width - cur_x - 1;
7375                                         }
7376                                         if (w < 0) {
7377                                                 w = 0;
7378                                         }
7379
7380                                         XSetLineAttributes(display, window.gc, 1, LineSolid,
7381                                                 CapButt, JoinMiter);
7382
7383                                         XDrawRectangle(display, window.drawable, window.gc, cur_x,
7384                                                 by, w, h);
7385                                         XFillRectangle(display, window.drawable, window.gc, cur_x,
7386                                                 by, w * bar_usage / 255, h);
7387                                         if (specials[special_index].height > cur_y_add
7388                                                         && specials[special_index].height > font_h) {
7389                                                 cur_y_add = specials[special_index].height;
7390                                         }
7391                                         break;
7392                                 }
7393
7394                                 case GRAPH:
7395                                 {
7396                                         int h, by, i, j = 0;
7397                                         int gradient_size = 0;
7398                                         float gradient_factor = 0;
7399                                         float gradient_update = 0;
7400                                         unsigned long last_colour = current_color;
7401                                         unsigned long tmpcolour = current_color;
7402                                         if (cur_x - text_start_x > maximum_width
7403                                                         && maximum_width > 0) {
7404                                                 break;
7405                                         }
7406                                         h = specials[special_index].height;
7407                                         by = cur_y - (font_ascent() / 2) - 1;
7408
7409                                         if (h < font_height()) {
7410                                                 by -= h / 2 - 1;
7411                                         }
7412                                         w = specials[special_index].width;
7413                                         if (w == 0) {
7414                                                 w = text_start_x + text_width - cur_x - 1;
7415                                         }
7416                                         if (w < 0) {
7417                                                 w = 0;
7418                                         }
7419                                         if (draw_graph_borders) {
7420                                                 XSetLineAttributes(display, window.gc, 1, LineSolid,
7421                                                         CapButt, JoinMiter);
7422                                                 XDrawRectangle(display, window.drawable, window.gc,
7423                                                         cur_x, by, w, h);
7424                                         }
7425                                         XSetLineAttributes(display, window.gc, 1, LineSolid,
7426                                                 CapButt, JoinMiter);
7427
7428                                         if (specials[special_index].last_colour != 0
7429                                                         || specials[special_index].first_colour != 0) {
7430                                                 tmpcolour = specials[special_index].last_colour;
7431                                                 gradient_size =
7432                                                         gradient_max(specials[special_index].last_colour,
7433                                                         specials[special_index].first_colour);
7434                                                 gradient_factor = (float) gradient_size / (w - 2);
7435                                         }
7436                                         for (i = w - 2; i > -1; i--) {
7437                                                 if (specials[special_index].last_colour != 0
7438                                                                 || specials[special_index].first_colour != 0) {
7439                                                         XSetForeground(display, window.gc, tmpcolour);
7440                                                         gradient_update += gradient_factor;
7441                                                         while (gradient_update > 0) {
7442                                                                 tmpcolour = do_gradient(tmpcolour,
7443                                                                         specials[special_index].first_colour);
7444                                                                 gradient_update--;
7445                                                         }
7446                                                 }
7447                                                 if ((w - i) / ((float) (w - 2) /
7448                                                                 (specials[special_index].graph_width)) > j
7449                                                                 && j < MAX_GRAPH_DEPTH - 3) {
7450                                                         j++;
7451                                                 }
7452                                                 /* this is mugfugly, but it works */
7453                                                 XDrawLine(display, window.drawable, window.gc,
7454                                                         cur_x + i + 1, by + h, cur_x + i + 1,
7455                                                         by + h - specials[special_index].graph[j] *
7456                                                         (h - 1) / specials[special_index].graph_scale);
7457                                         }
7458                                         if (specials[special_index].height > cur_y_add
7459                                                         && specials[special_index].height > font_h) {
7460                                                 cur_y_add = specials[special_index].height;
7461                                         }
7462                                         /* if (draw_mode == BG) {
7463                                                 set_foreground_color(default_bg_color);
7464                                         } else if (draw_mode == OUTLINE) {
7465                                                 set_foreground_color(default_out_color);
7466                                         } else {
7467                                                 set_foreground_color(default_fg_color);
7468                                         } */
7469                                         if (show_graph_range) {
7470                                                 int tmp_x = cur_x;
7471                                                 int tmp_y = cur_y;
7472                                                 unsigned short int seconds = update_interval * w;
7473                                                 char *tmp_day_str;
7474                                                 char *tmp_hour_str;
7475                                                 char *tmp_min_str;
7476                                                 char *tmp_sec_str;
7477                                                 unsigned short int timeunits;
7478                                                 if(seconds!=0){
7479                                                         timeunits = seconds / 86400; seconds %= 86400;
7480                                                         if( timeunits > 0 ) {
7481                                                                 asprintf(&tmp_day_str, "%dd", timeunits);
7482                                                         }else{
7483                                                                 tmp_day_str = strdup("");
7484                                                         }
7485                                                         timeunits = seconds / 3600; seconds %= 3600;
7486                                                         if( timeunits > 0 ) {
7487                                                                 asprintf(&tmp_hour_str, "%dh", timeunits);
7488                                                         }else{
7489                                                                 tmp_hour_str = strdup("");
7490                                                         }
7491                                                         timeunits = seconds / 60; seconds %= 60;
7492                                                         if(timeunits > 0) {
7493                                                                 asprintf(&tmp_min_str, "%dm", timeunits);
7494                                                         }else{
7495                                                                 tmp_min_str = strdup("");
7496                                                         }
7497                                                         if(seconds > 0) {
7498                                                                 asprintf(&tmp_sec_str, "%ds", seconds);
7499                                                         }else{
7500                                                                 tmp_sec_str = strdup("");
7501                                                         }
7502                                                         asprintf(&tmp_str, "%s%s%s%s", tmp_day_str, tmp_hour_str, tmp_min_str, tmp_sec_str);
7503                                                         free(tmp_day_str); free(tmp_hour_str); free(tmp_min_str); free(tmp_sec_str);
7504                                                 }else{
7505                                                         asprintf(&tmp_str, "Range not possible"); //should never happen, but better safe then sorry
7506                                                 }
7507                                                 cur_x += (w / 2) - (font_ascent() * (strlen(tmp_str) / 2));
7508                                                 cur_y += font_height() / 2;
7509                                                 draw_string(tmp_str);
7510                                                 free(tmp_str);
7511                                                 cur_x = tmp_x;
7512                                                 cur_y = tmp_y;
7513                                         }
7514 #ifdef MATH
7515                                         if (show_graph_scale && (specials[special_index].show_scale == 1)) {
7516                                                 int tmp_x = cur_x;
7517                                                 int tmp_y = cur_y;
7518                                                 cur_x += font_ascent() / 2;
7519                                                 cur_y += font_height() / 2;
7520                                                 tmp_str = (char *)
7521                                                         calloc(log10(floor(specials[special_index].graph_scale)) + 4,
7522                                                                         sizeof(char));
7523                                                 sprintf(tmp_str, "%.1f", specials[special_index].graph_scale);
7524                                                 draw_string(tmp_str);
7525                                                 free(tmp_str);
7526                                                 cur_x = tmp_x;
7527                                                 cur_y = tmp_y;
7528                                         }
7529 #endif
7530                                         set_foreground_color(last_colour);
7531                                         break;
7532                                 }
7533
7534                                 case FONT:
7535                                 {
7536                                         int old = font_ascent();
7537
7538                                         cur_y -= font_ascent();
7539                                         selected_font = specials[special_index].font_added;
7540                                         if (cur_y + font_ascent() < cur_y + old) {
7541                                                 cur_y += old;
7542                                         } else {
7543                                                 cur_y += font_ascent();
7544                                         }
7545                                         set_font();
7546                                         break;
7547                                 }
7548                                 case FG:
7549                                         if (draw_mode == FG) {
7550                                                 set_foreground_color(specials[special_index].arg);
7551                                         }
7552                                         break;
7553
7554                                 case BG:
7555                                         if (draw_mode == BG) {
7556                                                 set_foreground_color(specials[special_index].arg);
7557                                         }
7558                                         break;
7559
7560                                 case OUTLINE:
7561                                         if (draw_mode == OUTLINE) {
7562                                                 set_foreground_color(specials[special_index].arg);
7563                                         }
7564                                         break;
7565
7566                                 case OFFSET:
7567                                         w += specials[special_index].arg;
7568                                         break;
7569
7570                                 case VOFFSET:
7571                                         cur_y += specials[special_index].arg;
7572                                         break;
7573
7574                                 case GOTO:
7575                                         if (specials[special_index].arg >= 0) {
7576                                                 cur_x = (int) specials[special_index].arg;
7577                                         }
7578                                         break;
7579
7580                                 case TAB:
7581                                 {
7582                                         int start = specials[special_index].arg;
7583                                         int step = specials[special_index].width;
7584
7585                                         if (!step || step < 0) {
7586                                                 step = 10;
7587                                         }
7588                                         w = step - (cur_x - text_start_x - start) % step;
7589                                         break;
7590                                 }
7591
7592                                 case ALIGNR:
7593                                 {
7594                                         /* TODO: add back in "+ border_margin" to the end of
7595                                          * this line? */
7596                                         int pos_x = text_start_x + text_width -
7597                                                 get_string_width_special(s);
7598
7599                                         /* printf("pos_x %i text_start_x %i text_width %i cur_x %i "
7600                                                 "get_string_width(p) %i gap_x %i "
7601                                                 "specials[special_index].arg %i border_margin %i "
7602                                                 "border_width %i\n", pos_x, text_start_x, text_width,
7603                                                 cur_x, get_string_width_special(s), gap_x,
7604                                                 specials[special_index].arg, border_margin,
7605                                                 border_width); */
7606                                         if (pos_x > specials[special_index].arg && pos_x > cur_x) {
7607                                                 cur_x = pos_x - specials[special_index].arg;
7608                                         }
7609                                         break;
7610                                 }
7611
7612                                 case ALIGNC:
7613                                 {
7614                                         int pos_x = (text_width) / 2 - get_string_width_special(s) /
7615                                                 2 - (cur_x - text_start_x);
7616                                         /* int pos_x = text_start_x + text_width / 2 -
7617                                                 get_string_width_special(s) / 2; */
7618
7619                                         /* printf("pos_x %i text_start_x %i text_width %i cur_x %i "
7620                                                 "get_string_width(p) %i gap_x %i "
7621                                                 "specials[special_index].arg %i\n", pos_x, text_start_x,
7622                                                 text_width, cur_x, get_string_width(s), gap_x,
7623                                                 specials[special_index].arg); */
7624                                         if (pos_x > specials[special_index].arg) {
7625                                                 w = pos_x - specials[special_index].arg;
7626                                         }
7627                                         break;
7628                                 }
7629                         }
7630
7631                         cur_x += w;
7632
7633                         special_index++;
7634                 }
7635
7636                 p++;
7637         }
7638 #else
7639         draw_string(s);
7640 #endif
7641 #ifdef X11
7642         if (cur_y_add > 0) {
7643                 cur_y += cur_y_add;
7644                 cur_y -= font_descent();
7645         }
7646
7647         draw_string(s);
7648
7649         cur_y += font_descent();
7650 #endif /* X11 */
7651 }
7652
7653 static void draw_text(void)
7654 {
7655 #ifdef X11
7656         cur_y = text_start_y;
7657
7658         /* draw borders */
7659         if (draw_borders && border_width > 0) {
7660                 unsigned int b = (border_width + 1) / 2;
7661
7662                 if (stippled_borders) {
7663                         char ss[2] = { stippled_borders, stippled_borders };
7664                         XSetLineAttributes(display, window.gc, border_width, LineOnOffDash,
7665                                 CapButt, JoinMiter);
7666                         XSetDashes(display, window.gc, 0, ss, 2);
7667                 } else {
7668                         XSetLineAttributes(display, window.gc, border_width, LineSolid,
7669                                 CapButt, JoinMiter);
7670                 }
7671
7672                 XDrawRectangle(display, window.drawable, window.gc,
7673                         text_start_x - border_margin + b, text_start_y - border_margin + b,
7674                         text_width + border_margin * 2 - 1 - b * 2,
7675                         text_height + border_margin * 2 - 1 - b * 2);
7676         }
7677
7678         /* draw text */
7679         special_index = 0;
7680 #endif /* X11 */
7681         for_each_line(text_buffer, draw_line);
7682 }
7683
7684 static void draw_stuff(void)
7685 {
7686 #ifdef X11
7687         selected_font = 0;
7688         if (draw_shades && !draw_outline) {
7689                 text_start_x++;
7690                 text_start_y++;
7691                 set_foreground_color(default_bg_color);
7692                 draw_mode = BG;
7693                 draw_text();
7694                 text_start_x--;
7695                 text_start_y--;
7696         }
7697
7698         if (draw_outline) {
7699                 int i, j;
7700                 selected_font = 0;
7701
7702                 for (i = -1; i < 2; i++) {
7703                         for (j = -1; j < 2; j++) {
7704                                 if (i == 0 && j == 0) {
7705                                         continue;
7706                                 }
7707                                 text_start_x += i;
7708                                 text_start_y += j;
7709                                 set_foreground_color(default_out_color);
7710                                 draw_mode = OUTLINE;
7711                                 draw_text();
7712                                 text_start_x -= i;
7713                                 text_start_y -= j;
7714                         }
7715                 }
7716         }
7717
7718         set_foreground_color(default_fg_color);
7719 #endif /* X11 */
7720         draw_mode = FG;
7721         draw_text();
7722 #ifdef X11
7723 #ifdef HAVE_XDBE
7724         if (use_xdbe) {
7725                 XdbeSwapInfo swap;
7726
7727                 swap.swap_window = window.window;
7728                 swap.swap_action = XdbeBackground;
7729                 XdbeSwapBuffers(display, &swap, 1);
7730         }
7731 #endif
7732 #endif /* X11 */
7733 }
7734
7735 #ifdef X11
7736 static void clear_text(int exposures)
7737 {
7738 #ifdef HAVE_XDBE
7739         if (use_xdbe) {
7740                 /* The swap action is XdbeBackground, which clears */
7741                 return;
7742         } else
7743 #endif
7744         {
7745                 /* there is some extra space for borders and outlines */
7746                 XClearArea(display, window.window, text_start_x - border_margin - 1,
7747                         text_start_y - border_margin - 1,
7748                         text_width + border_margin * 2 + 2,
7749                         text_height + border_margin * 2 + 2, exposures ? True : 0);
7750         }
7751 }
7752 #endif /* X11 */
7753
7754 static int need_to_update;
7755
7756 /* update_text() generates new text and clears old text area */
7757 static void update_text(void)
7758 {
7759         generate_text();
7760 #ifdef X11
7761         clear_text(1);
7762 #endif /* X11 */
7763         need_to_update = 1;
7764 }
7765
7766 static void main_loop(void)
7767 {
7768 #ifdef SIGNAL_BLOCKING
7769         sigset_t newmask, oldmask;
7770 #endif
7771         double t;
7772 #ifdef X11
7773         Region region = XCreateRegion();
7774
7775 #ifdef HAVE_XDAMAGE
7776         Damage damage;
7777         XserverRegion region2, part;
7778         int event_base, error_base;
7779
7780         if (!XDamageQueryExtension(display, &event_base, &error_base)) {
7781                 ERR("Xdamage extension unavailable");
7782         }
7783         damage = XDamageCreate(display, window.window, XDamageReportNonEmpty);
7784         region2 = XFixesCreateRegionFromWindow(display, window.window, 0);
7785         part = XFixesCreateRegionFromWindow(display, window.window, 0);
7786 #endif /* HAVE_XDAMAGE */
7787 #endif /* X11 */
7788
7789 #ifdef SIGNAL_BLOCKING
7790         sigemptyset(&newmask);
7791         sigaddset(&newmask, SIGINT);
7792         sigaddset(&newmask, SIGTERM);
7793         sigaddset(&newmask, SIGUSR1);
7794 #endif
7795
7796         next_update_time = last_update_time = get_time();
7797         info.looped = 0;
7798         while (total_run_times == 0 || info.looped < total_run_times) {
7799                 info.looped++;
7800
7801 #ifdef SIGNAL_BLOCKING
7802                 /* block signals.  we will inspect for pending signals later */
7803                 if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0) {
7804                         CRIT_ERR("unable to sigprocmask()");
7805                 }
7806 #endif
7807
7808 #ifdef X11
7809                 XFlush(display);
7810
7811                 /* wait for X event or timeout */
7812
7813                 if (!XPending(display)) {
7814                         fd_set fdsr;
7815                         struct timeval tv;
7816                         int s;
7817                         t = next_update_time - get_time();
7818
7819                         if (t < 0) {
7820                                 t = 0;
7821                         } else if (t > update_interval) {
7822                                 t = update_interval;
7823                         }
7824
7825                         tv.tv_sec = (long) t;
7826                         tv.tv_usec = (long) (t * 1000000) % 1000000;
7827                         FD_ZERO(&fdsr);
7828                         FD_SET(ConnectionNumber(display), &fdsr);
7829
7830                         s = select(ConnectionNumber(display) + 1, &fdsr, 0, 0, &tv);
7831                         if (s == -1) {
7832                                 if (errno != EINTR) {
7833                                         ERR("can't select(): %s", strerror(errno));
7834                                 }
7835                         } else {
7836                                 /* timeout */
7837                                 if (s == 0) {
7838 #else
7839                 t = (next_update_time - get_time()) * 1000000;
7840                 usleep((useconds_t)t);
7841 #endif /* X11 */
7842                                         update_text();
7843 #ifdef X11
7844                                 }
7845                         }
7846                 }
7847
7848                 if (need_to_update) {
7849 #ifdef OWN_WINDOW
7850                         int wx = window.x, wy = window.y;
7851 #endif
7852
7853                         need_to_update = 0;
7854                         selected_font = 0;
7855                         update_text_area();
7856 #ifdef OWN_WINDOW
7857                         if (own_window) {
7858                                 /* resize window if it isn't right size */
7859                                 if (!fixed_size
7860                                                 && (text_width + border_margin * 2 + 1 != window.width
7861                                                 || text_height + border_margin * 2 + 1 != window.height)) {
7862                                         window.width = text_width + border_margin * 2 + 1;
7863                                         window.height = text_height + border_margin * 2 + 1;
7864                                         XResizeWindow(display, window.window, window.width,
7865                                                 window.height);
7866                                         if (own_window) {
7867                                                 set_transparent_background(window.window);
7868                                         }
7869                                 }
7870
7871                                 /* move window if it isn't in right position */
7872                                 if (!fixed_pos && (window.x != wx || window.y != wy)) {
7873                                         XMoveWindow(display, window.window, window.x, window.y);
7874                                 }
7875                         }
7876 #endif
7877
7878                         clear_text(1);
7879
7880 #ifdef HAVE_XDBE
7881                         if (use_xdbe) {
7882                                 XRectangle r;
7883
7884                                 r.x = text_start_x - border_margin;
7885                                 r.y = text_start_y - border_margin;
7886                                 r.width = text_width + border_margin * 2;
7887                                 r.height = text_height + border_margin * 2;
7888                                 XUnionRectWithRegion(&r, region, region);
7889                         }
7890 #endif
7891                 }
7892
7893                 /* handle X events */
7894                 while (XPending(display)) {
7895                         XEvent ev;
7896
7897                         XNextEvent(display, &ev);
7898                         switch (ev.type) {
7899                                 case Expose:
7900                                 {
7901                                         XRectangle r;
7902
7903                                         r.x = ev.xexpose.x;
7904                                         r.y = ev.xexpose.y;
7905                                         r.width = ev.xexpose.width;
7906                                         r.height = ev.xexpose.height;
7907                                         XUnionRectWithRegion(&r, region, region);
7908                                         break;
7909                                 }
7910
7911 #ifdef OWN_WINDOW
7912                                 case ReparentNotify:
7913                                         /* set background to ParentRelative for all parents */
7914                                         if (own_window) {
7915                                                 set_transparent_background(window.window);
7916                                         }
7917                                         break;
7918
7919                                 case ConfigureNotify:
7920                                         if (own_window) {
7921                                                 /* if window size isn't what expected, set fixed size */
7922                                                 if (ev.xconfigure.width != window.width
7923                                                                 || ev.xconfigure.height != window.height) {
7924                                                         if (window.width != 0 && window.height != 0) {
7925                                                                 fixed_size = 1;
7926                                                         }
7927
7928                                                         /* clear old stuff before screwing up
7929                                                          * size and pos */
7930                                                         clear_text(1);
7931
7932                                                         {
7933                                                                 XWindowAttributes attrs;
7934
7935                                                                 if (XGetWindowAttributes(display,
7936                                                                                 window.window, &attrs)) {
7937                                                                         window.width = attrs.width;
7938                                                                         window.height = attrs.height;
7939                                                                 }
7940                                                         }
7941
7942                                                         text_width = window.width - border_margin * 2 - 1;
7943                                                         text_height = window.height - border_margin * 2 - 1;
7944                                                         if (text_width > maximum_width
7945                                                                         && maximum_width > 0) {
7946                                                                 text_width = maximum_width;
7947                                                         }
7948                                                 }
7949
7950                                                 /* if position isn't what expected, set fixed pos
7951                                                  * total_updates avoids setting fixed_pos when window
7952                                                  * is set to weird locations when started */
7953                                                 /* // this is broken
7954                                                 if (total_updates >= 2 && !fixed_pos
7955                                                                 && (window.x != ev.xconfigure.x
7956                                                                 || window.y != ev.xconfigure.y)
7957                                                                 && (ev.xconfigure.x != 0
7958                                                                 || ev.xconfigure.y != 0)) {
7959                                                         fixed_pos = 1;
7960                                                 } */
7961                                                 set_font();
7962                                         }
7963                                         break;
7964
7965                                 case ButtonPress:
7966                                         if (own_window) {
7967                                                 /* if an ordinary window with decorations */
7968                                                 if ((window.type == TYPE_NORMAL)
7969                                                                 && (!TEST_HINT(window.hints,
7970                                                                 HINT_UNDECORATED))) {
7971                                                         /* allow conky to hold input focus. */
7972                                                         break;
7973                                                 } else {
7974                                                         /* forward the click to the desktop window */
7975                                                         XUngrabPointer(display, ev.xbutton.time);
7976                                                         ev.xbutton.window = window.desktop;
7977                                                         XSendEvent(display, ev.xbutton.window, False,
7978                                                                 ButtonPressMask, &ev);
7979                                                         XSetInputFocus(display, ev.xbutton.window,
7980                                                                 RevertToParent, ev.xbutton.time);
7981                                                 }
7982                                         }
7983                                         break;
7984
7985                                 case ButtonRelease:
7986                                         if (own_window) {
7987                                                 /* if an ordinary window with decorations */
7988                                                 if ((window.type == TYPE_NORMAL)
7989                                                                 && (!TEST_HINT(window.hints,
7990                                                                 HINT_UNDECORATED))) {
7991                                                         /* allow conky to hold input focus. */
7992                                                         break;
7993                                                 } else {
7994                                                         /* forward the release to the desktop window */
7995                                                         ev.xbutton.window = window.desktop;
7996                                                         XSendEvent(display, ev.xbutton.window, False,
7997                                                                 ButtonReleaseMask, &ev);
7998                                                 }
7999                                         }
8000                                         break;
8001
8002 #endif
8003
8004                                 default:
8005 #ifdef HAVE_XDAMAGE
8006                                         if (ev.type == event_base + XDamageNotify) {
8007                                                 XDamageNotifyEvent *dev = (XDamageNotifyEvent *) &ev;
8008
8009                                                 XFixesSetRegion(display, part, &dev->area, 1);
8010                                                 XFixesUnionRegion(display, region2, region2, part);
8011                                         }
8012 #endif /* HAVE_XDAMAGE */
8013                                         break;
8014                         }
8015                 }
8016
8017 #ifdef HAVE_XDAMAGE
8018                 XDamageSubtract(display, damage, region2, None);
8019                 XFixesSetRegion(display, region2, 0, 0);
8020 #endif /* HAVE_XDAMAGE */
8021
8022                 /* XDBE doesn't seem to provide a way to clear the back buffer without
8023                  * interfering with the front buffer, other than passing XdbeBackground
8024                  * to XdbeSwapBuffers. That means that if we're using XDBE, we need to
8025                  * redraw the text even if it wasn't part of the exposed area. OTOH,
8026                  * if we're not going to call draw_stuff at all, then no swap happens
8027                  * and we can safely do nothing. */
8028
8029                 if (!XEmptyRegion(region)) {
8030 #ifdef HAVE_XDBE
8031                         if (use_xdbe) {
8032                                 XRectangle r;
8033
8034                                 r.x = text_start_x - border_margin;
8035                                 r.y = text_start_y - border_margin;
8036                                 r.width = text_width + border_margin * 2;
8037                                 r.height = text_height + border_margin * 2;
8038                                 XUnionRectWithRegion(&r, region, region);
8039                         }
8040 #endif
8041                         XSetRegion(display, window.gc, region);
8042 #ifdef XFT
8043                         if (use_xft) {
8044                                 XftDrawSetClip(window.xftdraw, region);
8045                         }
8046 #endif
8047 #endif /* X11 */
8048                         draw_stuff();
8049 #ifdef X11
8050                         XDestroyRegion(region);
8051                         region = XCreateRegion();
8052                 }
8053 #endif /* X11 */
8054
8055 #ifdef SIGNAL_BLOCKING
8056                 /* unblock signals of interest and let handler fly */
8057                 if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0) {
8058                         CRIT_ERR("unable to sigprocmask()");
8059                 }
8060 #endif
8061
8062                 switch (g_signal_pending) {
8063                         case SIGHUP:
8064                         case SIGUSR1:
8065                                 ERR("received SIGHUP or SIGUSR1. reloading the config file.");
8066                                 reload_config();
8067                                 break;
8068                         case SIGINT:
8069                         case SIGTERM:
8070                                 ERR("received SIGINT or SIGTERM to terminate. bye!");
8071                                 clean_up();
8072 #ifdef X11
8073                                 XDestroyRegion(region);
8074                                 region = NULL;
8075 #ifdef HAVE_XDAMAGE
8076                                 XDamageDestroy(display, damage);
8077                                 XFixesDestroyRegion(display, region2);
8078                                 XFixesDestroyRegion(display, part);
8079 #endif /* HAVE_XDAMAGE */
8080 #endif /* X11 */
8081                                 return; /* return from main_loop */
8082                                 /* break; */
8083                         default:
8084                                 /* Reaching here means someone set a signal
8085                                  * (SIGXXXX, signal_handler), but didn't write any code
8086                                  * to deal with it.
8087                                  * If you don't want to handle a signal, don't set a handler on
8088                                  * it in the first place. */
8089                                 if (g_signal_pending) {
8090                                         ERR("ignoring signal (%d)", g_signal_pending);
8091                                 }
8092                                 break;
8093                 }
8094                 g_signal_pending = 0;
8095         }
8096
8097 #if defined(X11) && defined(HAVE_XDAMAGE)
8098         XDamageDestroy(display, damage);
8099         XFixesDestroyRegion(display, region2);
8100         XFixesDestroyRegion(display, part);
8101         XDestroyRegion(region);
8102         region = NULL;
8103 #endif /* X11 && HAVE_XDAMAGE */
8104 }
8105
8106 static void load_config_file(const char *);
8107
8108 /* reload the config file */
8109 void reload_config(void)
8110 {
8111         timed_thread_destroy_registered_threads();
8112
8113         if (info.cpu_usage) {
8114                 free(info.cpu_usage);
8115                 info.cpu_usage = NULL;
8116         }
8117
8118         if (info.mail) {
8119                 free(info.mail);
8120         }
8121
8122 #ifdef MPD
8123         if (info.mpd.title) {
8124                 free(info.mpd.title);
8125                 info.mpd.title = NULL;
8126         }
8127         if (info.mpd.artist) {
8128                 free(info.mpd.artist);
8129                 info.mpd.artist = NULL;
8130         }
8131         if (info.mpd.album) {
8132                 free(info.mpd.album);
8133                 info.mpd.album = NULL;
8134         }
8135         if (info.mpd.random) {
8136                 free(info.mpd.random);
8137                 info.mpd.random = NULL;
8138         }
8139         if (info.mpd.repeat) {
8140                 free(info.mpd.repeat);
8141                 info.mpd.repeat = NULL;
8142         }
8143         if (info.mpd.track) {
8144                 free(info.mpd.track);
8145                 info.mpd.track = NULL;
8146         }
8147         if (info.mpd.name) {
8148                 free(info.mpd.name);
8149                 info.mpd.name = NULL;
8150         }
8151         if (info.mpd.file) {
8152                 free(info.mpd.file);
8153                 info.mpd.file = NULL;
8154         }
8155         if (info.mpd.status) {
8156                 free(info.mpd.status);
8157                 info.mpd.status = NULL;
8158         }
8159 #endif
8160
8161 #ifdef MOC
8162   free_moc(&info.moc);
8163 #endif
8164   
8165 #ifdef X11
8166         free_fonts();
8167 #endif /* X11 */
8168
8169 #ifdef TCP_PORT_MONITOR
8170         destroy_tcp_port_monitor_collection(info.p_tcp_port_monitor_collection);
8171 #endif
8172
8173         if (current_config) {
8174                 clear_fs_stats();
8175                 load_config_file(current_config);
8176
8177                 /* re-init specials array */
8178                 if ((specials = realloc((void *) specials,
8179                                 sizeof(struct special_t) * max_specials)) == 0) {
8180                         ERR("failed to realloc specials array");
8181                 }
8182
8183 #ifdef X11
8184                 load_fonts();
8185                 set_font();
8186                 // clear the window first
8187                 XClearWindow(display, RootWindow(display, screen));
8188
8189 #endif /* X11 */
8190 #ifdef TCP_PORT_MONITOR
8191                 info.p_tcp_port_monitor_collection = NULL;
8192 #endif
8193                 extract_variable_text(global_text);
8194                 free(global_text);
8195                 global_text = NULL;
8196                 if (tmpstring1) {
8197                         free(tmpstring1);
8198                 }
8199                 tmpstring1 = malloc(text_buffer_size);
8200                 memset(tmpstring1, 0, text_buffer_size);
8201                 if (tmpstring2) {
8202                         free(tmpstring2);
8203                 }
8204                 tmpstring2 = malloc(text_buffer_size);
8205                 memset(tmpstring2, 0, text_buffer_size);
8206                 if (text_buffer) {
8207                         free(text_buffer);
8208                 }
8209                 text_buffer = malloc(max_user_text);
8210                 memset(text_buffer, 0, max_user_text);
8211                 update_text();
8212         }
8213 }
8214
8215 void clean_up(void)
8216 {
8217         timed_thread_destroy_registered_threads();
8218
8219         if (info.cpu_usage) {
8220                 free(info.cpu_usage);
8221                 info.cpu_usage = NULL;
8222         }
8223 #ifdef X11
8224 #ifdef HAVE_XDBE
8225         if (use_xdbe) {
8226                 XdbeDeallocateBackBufferName(display, window.back_buffer);
8227         }
8228 #endif
8229 #ifdef OWN_WINDOW
8230         if (own_window) {
8231                 XDestroyWindow(display, window.window);
8232                 XClearWindow(display, RootWindow(display, screen));
8233                 XFlush(display);
8234         } else
8235 #endif
8236         {
8237                 XClearWindow(display, RootWindow(display, screen));
8238                 clear_text(1);
8239                 XFlush(display);
8240         }
8241
8242         XFreeGC(display, window.gc);
8243         free_fonts();
8244 #endif /* X11 */
8245
8246         free_text_objects(global_text_object_list, 1);
8247         free(global_text_object_list);
8248         global_text_object_list = NULL;
8249         if (tmpstring1) {
8250                 free(tmpstring1);
8251                 tmpstring1 = 0;
8252         }
8253         if (tmpstring2) {
8254                 free(tmpstring2);
8255                 tmpstring2 = 0;
8256         }
8257         if (text_buffer) {
8258                 free(text_buffer);
8259                 text_buffer = 0;
8260         }
8261
8262         if (global_text) {
8263                 free(global_text);
8264                 global_text = 0;
8265         }
8266
8267         free(current_config);
8268
8269 #ifdef TCP_PORT_MONITOR
8270         destroy_tcp_port_monitor_collection(info.p_tcp_port_monitor_collection);
8271         info.p_tcp_port_monitor_collection = NULL;
8272 #endif
8273 #ifdef RSS
8274         free_rss_info();
8275 #endif
8276
8277         if (specials) {
8278                 unsigned int i;
8279
8280                 for (i = 0; i < special_count; i++) {
8281                         if (specials[i].type == GRAPH) {
8282                                 free(specials[i].graph);
8283                         }
8284                 }
8285                 free(specials);
8286                 specials = NULL;
8287         }
8288
8289         clear_diskio_stats();
8290 }
8291
8292 static int string_to_bool(const char *s)
8293 {
8294         if (!s) {
8295                 // Assumes an option without a true/false means true
8296                 return 1;
8297         } else if (strcasecmp(s, "yes") == EQUAL) {
8298                 return 1;
8299         } else if (strcasecmp(s, "true") == EQUAL) {
8300                 return 1;
8301         } else if (strcasecmp(s, "1") == EQUAL) {
8302                 return 1;
8303         }
8304         return 0;
8305 }
8306
8307 #ifdef X11
8308 static enum alignment string_to_alignment(const char *s)
8309 {
8310         if (strcasecmp(s, "top_left") == EQUAL) {
8311                 return TOP_LEFT;
8312         } else if (strcasecmp(s, "top_right") == EQUAL) {
8313                 return TOP_RIGHT;
8314         } else if (strcasecmp(s, "top_middle") == EQUAL) {
8315                 return TOP_MIDDLE;
8316         } else if (strcasecmp(s, "bottom_left") == EQUAL) {
8317                 return BOTTOM_LEFT;
8318         } else if (strcasecmp(s, "bottom_right") == EQUAL) {
8319                 return BOTTOM_RIGHT;
8320         } else if (strcasecmp(s, "bottom_middle") == EQUAL) {
8321                 return BOTTOM_MIDDLE;
8322         } else if (strcasecmp(s, "middle_left") == EQUAL) {
8323                 return MIDDLE_LEFT;
8324         } else if (strcasecmp(s, "middle_right") == EQUAL) {
8325                 return MIDDLE_RIGHT;
8326         } else if (strcasecmp(s, "tl") == EQUAL) {
8327                 return TOP_LEFT;
8328         } else if (strcasecmp(s, "tr") == EQUAL) {
8329                 return TOP_RIGHT;
8330         } else if (strcasecmp(s, "tm") == EQUAL) {
8331                 return TOP_MIDDLE;
8332         } else if (strcasecmp(s, "bl") == EQUAL) {
8333                 return BOTTOM_LEFT;
8334         } else if (strcasecmp(s, "br") == EQUAL) {
8335                 return BOTTOM_RIGHT;
8336         } else if (strcasecmp(s, "bm") == EQUAL) {
8337                 return BOTTOM_MIDDLE;
8338         } else if (strcasecmp(s, "ml") == EQUAL) {
8339                 return MIDDLE_LEFT;
8340         } else if (strcasecmp(s, "mr") == EQUAL) {
8341                 return MIDDLE_RIGHT;
8342         } else if (strcasecmp(s, "none") == EQUAL) {
8343                 return NONE;
8344         }
8345         return TOP_LEFT;
8346 }
8347 #endif /* X11 */
8348
8349 static void set_default_configurations(void)
8350 {
8351         fork_to_background = 0;
8352         total_run_times = 0;
8353         info.cpu_avg_samples = 2;
8354         info.net_avg_samples = 2;
8355         info.memmax = 0;
8356         top_cpu = 0;
8357         cpu_separate = 0;
8358         short_units = 0;
8359         top_mem = 0;
8360 #ifdef MPD
8361         strcpy(info.mpd.host, "localhost");
8362         info.mpd.port = 6600;
8363         info.mpd.status = NULL;
8364         info.mpd.artist = NULL;
8365         info.mpd.album = NULL;
8366         info.mpd.title = NULL;
8367         info.mpd.random = NULL;
8368         info.mpd.track = NULL;
8369         info.mpd.name = NULL;
8370         info.mpd.file = NULL;
8371 #endif
8372 #ifdef MOC
8373   init_moc(&info.moc);
8374 #endif
8375 #ifdef XMMS2
8376         info.xmms2.artist = NULL;
8377         info.xmms2.album = NULL;
8378         info.xmms2.title = NULL;
8379         info.xmms2.genre = NULL;
8380         info.xmms2.comment = NULL;
8381         info.xmms2.url = NULL;
8382         info.xmms2.status = NULL;
8383         info.xmms2.playlist = NULL;
8384 #endif
8385         use_spacer = NO_SPACER;
8386 #ifdef X11
8387         output_methods = TO_X;
8388 #else
8389         output_methods = TO_STDOUT;
8390 #endif
8391 #ifdef X11
8392         show_graph_scale = 0;
8393         show_graph_range = 0;
8394         default_fg_color = WhitePixel(display, screen);
8395         default_bg_color = BlackPixel(display, screen);
8396         default_out_color = BlackPixel(display, screen);
8397         color0 = default_fg_color;
8398         color1 = default_fg_color;
8399         color2 = default_fg_color;
8400         color3 = default_fg_color;
8401         color4 = default_fg_color;
8402         color5 = default_fg_color;
8403         color6 = default_fg_color;
8404         color7 = default_fg_color;
8405         color8 = default_fg_color;
8406         color9 = default_fg_color;
8407         template[0] = strdup("");
8408         template[1] = strdup("");
8409         template[2] = strdup("");
8410         template[3] = strdup("");
8411         template[4] = strdup("");
8412         template[5] = strdup("");
8413         template[6] = strdup("");
8414         template[7] = strdup("");
8415         template[8] = strdup("");
8416         template[9] = strdup("");
8417         draw_shades = 1;
8418         draw_borders = 0;
8419         draw_graph_borders = 1;
8420         draw_outline = 0;
8421         set_first_font("6x10");
8422         gap_x = 5;
8423         gap_y = 60;
8424         minimum_width = 5;
8425         minimum_height = 5;
8426         maximum_width = 0;
8427 #ifdef OWN_WINDOW
8428         own_window = 0;
8429         window.type = TYPE_NORMAL;
8430         window.hints = 0;
8431         strcpy(window.class_name, PACKAGE_NAME);
8432         update_uname();
8433         sprintf(window.title, PACKAGE_NAME" (%s)", info.uname_s.nodename);
8434 #endif
8435         stippled_borders = 0;
8436         border_margin = 3;
8437         border_width = 1;
8438         text_alignment = BOTTOM_LEFT;
8439         info.x11.monitor.number = 1;
8440         info.x11.monitor.current = 0;
8441 #endif /* X11 */
8442
8443         free(current_mail_spool);
8444         {
8445                 char buf[256];
8446
8447                 variable_substitute(MAIL_FILE, buf, 256);
8448                 if (buf[0] != '\0') {
8449                         current_mail_spool = strndup(buf, text_buffer_size);
8450                 }
8451         }
8452
8453         no_buffers = 1;
8454         update_interval = 3.0;
8455         info.music_player_interval = 1.0;
8456         stuff_in_upper_case = 0;
8457         info.users.number = 1;
8458
8459 #ifdef TCP_PORT_MONITOR
8460         tcp_port_monitor_args.max_port_monitor_connections =
8461                 MAX_PORT_MONITOR_CONNECTIONS_DEFAULT;
8462 #endif
8463 }
8464
8465 static void load_config_file(const char *f)
8466 {
8467 #define CONF_ERR ERR("%s: %d: config file error", f, line)
8468         int line = 0;
8469         FILE *fp;
8470
8471         set_default_configurations();
8472         fp = fopen(f, "r");
8473         if (!fp) {
8474                 return;
8475         }
8476
8477         while (!feof(fp)) {
8478                 char buf[256], *p, *p2, *name, *value;
8479
8480                 line++;
8481                 if (fgets(buf, 256, fp) == NULL) {
8482                         break;
8483                 }
8484
8485                 p = buf;
8486
8487                 /* break at comment */
8488                 p2 = strchr(p, '#');
8489                 if (p2) {
8490                         *p2 = '\0';
8491                 }
8492
8493                 /* skip spaces */
8494                 while (*p && isspace((int) *p)) {
8495                         p++;
8496                 }
8497                 if (*p == '\0') {
8498                         continue;       /* empty line */
8499                 }
8500
8501                 name = p;
8502
8503                 /* skip name */
8504                 p2 = p;
8505                 while (*p2 && !isspace((int) *p2)) {
8506                         p2++;
8507                 }
8508                 if (*p2 != '\0') {
8509                         *p2 = '\0';     /* break at name's end */
8510                         p2++;
8511                 }
8512
8513                 /* get value */
8514                 if (*p2) {
8515                         p = p2;
8516                         while (*p && isspace((int) *p)) {
8517                                 p++;
8518                         }
8519
8520                         value = p;
8521
8522                         p2 = value + strlen(value);
8523                         while (isspace((int) *(p2 - 1))) {
8524                                 *--p2 = '\0';
8525                         }
8526                 } else {
8527                         value = 0;
8528                 }
8529
8530 #define CONF2(a) if (strcasecmp(name, a) == 0)
8531 #define CONF(a) else CONF2(a)
8532 #define CONF3(a, b) else if (strcasecmp(name, a) == 0 \
8533                 || strcasecmp(name, b) == 0)
8534
8535 #ifdef X11
8536                 CONF2("alignment") {
8537                         if (window.type == TYPE_DOCK)
8538                                 ;
8539                         else if (value) {
8540                                 int a = string_to_alignment(value);
8541
8542                                 if (a <= 0) {
8543                                         CONF_ERR;
8544                                 } else {
8545                                         text_alignment = a;
8546                                 }
8547                         } else {
8548                                 CONF_ERR;
8549                         }
8550                 }
8551                 CONF("background") {
8552                         fork_to_background = string_to_bool(value);
8553                 }
8554 #else
8555                 CONF2("background") {
8556                         fork_to_background = string_to_bool(value);
8557                 }
8558 #endif /* X11 */
8559 #ifdef X11
8560                 CONF("show_graph_scale") {
8561                         show_graph_scale = string_to_bool(value);
8562                 }
8563                 CONF("show_graph_range") {
8564                         show_graph_range = string_to_bool(value);
8565                 }
8566                 CONF("border_margin") {
8567                         if (value) {
8568                                 border_margin = strtol(value, 0, 0);
8569                         } else {
8570                                 CONF_ERR;
8571                         }
8572                 }
8573                 CONF("border_width") {
8574                         if (value) {
8575                                 border_width = strtol(value, 0, 0);
8576                         } else {
8577                                 CONF_ERR;
8578                         }
8579                 }
8580                 CONF("color0") {
8581                         if (value) {
8582                                 color0 = get_x11_color(value);
8583                         } else {
8584                                 CONF_ERR;
8585                         }
8586                 }
8587                 CONF("color1") {
8588                         if (value) {
8589                                 color1 = get_x11_color(value);
8590                         } else {
8591                                 CONF_ERR;
8592                         }
8593                 }
8594                 CONF("color2") {
8595                         if (value) {
8596                                 color2 = get_x11_color(value);
8597                         } else {
8598                                 CONF_ERR;
8599                         }
8600                 }
8601                 CONF("color3") {
8602                         if (value) {
8603                                 color3 = get_x11_color(value);
8604                         } else {
8605                                 CONF_ERR;
8606                         }
8607                 }
8608                 CONF("color4") {
8609                         if (value) {
8610                                 color4 = get_x11_color(value);
8611                         } else {
8612                                 CONF_ERR;
8613                         }
8614                 }
8615                 CONF("color5") {
8616                         if (value) {
8617                                 color5 = get_x11_color(value);
8618                         } else {
8619                                 CONF_ERR;
8620                         }
8621                 }
8622                 CONF("color6") {
8623                         if (value) {
8624                                 color6 = get_x11_color(value);
8625                         } else {
8626                                 CONF_ERR;
8627                         }
8628                 }
8629                 CONF("color7") {
8630                         if (value) {
8631                                 color7 = get_x11_color(value);
8632                         } else {
8633                                 CONF_ERR;
8634                         }
8635                 }
8636                 CONF("color8") {
8637                         if (value) {
8638                                 color8 = get_x11_color(value);
8639                         } else {
8640                                 CONF_ERR;
8641                         }
8642                 }
8643                 CONF("color9") {
8644                         if (value) {
8645                                 color9 = get_x11_color(value);
8646                         } else {
8647                                 CONF_ERR;
8648                         }
8649                 }
8650 #define TEMPLATE_CONF(n) \
8651                 CONF("template"#n) { \
8652                         if (value) { \
8653                                 free(template[n]); \
8654                                 template[n] = strdup(value); \
8655                         } else { \
8656                                 CONF_ERR; \
8657                         } \
8658                 }
8659                 TEMPLATE_CONF(0)
8660                 TEMPLATE_CONF(1)
8661                 TEMPLATE_CONF(2)
8662                 TEMPLATE_CONF(3)
8663                 TEMPLATE_CONF(4)
8664                 TEMPLATE_CONF(5)
8665                 TEMPLATE_CONF(6)
8666                 TEMPLATE_CONF(7)
8667                 TEMPLATE_CONF(8)
8668                 TEMPLATE_CONF(9)
8669                 CONF("default_color") {
8670                         if (value) {
8671                                 default_fg_color = get_x11_color(value);
8672                         } else {
8673                                 CONF_ERR;
8674                         }
8675                 }
8676                 CONF3("default_shade_color", "default_shadecolor") {
8677                         if (value) {
8678                                 default_bg_color = get_x11_color(value);
8679                         } else {
8680                                 CONF_ERR;
8681                         }
8682                 }
8683                 CONF3("default_outline_color", "default_outlinecolor") {
8684                         if (value) {
8685                                 default_out_color = get_x11_color(value);
8686                         } else {
8687                                 CONF_ERR;
8688                         }
8689                 }
8690 #endif /* X11 */
8691                 CONF("imap") {
8692                         if (value) {
8693                                 info.mail = parse_mail_args(IMAP, value);
8694                         } else {
8695                                 CONF_ERR;
8696                         }
8697                 }
8698                 CONF("pop3") {
8699                         if (value) {
8700                                 info.mail = parse_mail_args(POP3, value);
8701                         } else {
8702                                 CONF_ERR;
8703                         }
8704                 }
8705 #ifdef MPD
8706                 CONF("mpd_host") {
8707                         if (value) {
8708                                 strncpy(info.mpd.host, value, 127);
8709                         } else {
8710                                 CONF_ERR;
8711                         }
8712                 }
8713                 CONF("mpd_port") {
8714                         if (value) {
8715                                 info.mpd.port = strtol(value, 0, 0);
8716                                 if (info.mpd.port < 1 || info.mpd.port > 0xffff) {
8717                                         CONF_ERR;
8718                                 }
8719                         }
8720                 }
8721                 CONF("mpd_password") {
8722                         if (value) {
8723                                 strncpy(info.mpd.password, value, 127);
8724                         } else {
8725                                 CONF_ERR;
8726                         }
8727                 }
8728 #endif
8729                 CONF("music_player_interval") {
8730                         if (value) {
8731                                 info.music_player_interval = strtod(value, 0);
8732                         } else {
8733                                 CONF_ERR;
8734                         }
8735                 }
8736 #ifdef __OpenBSD__
8737                 CONF("sensor_device") {
8738                         if (value) {
8739                                 sensor_device = strtol(value, 0, 0);
8740                         } else {
8741                                 CONF_ERR;
8742                         }
8743                 }
8744 #endif
8745                 CONF("cpu_avg_samples") {
8746                         if (value) {
8747                                 cpu_avg_samples = strtol(value, 0, 0);
8748                                 if (cpu_avg_samples < 1 || cpu_avg_samples > 14) {
8749                                         CONF_ERR;
8750                                 } else {
8751                                         info.cpu_avg_samples = cpu_avg_samples;
8752                                 }
8753                         } else {
8754                                 CONF_ERR;
8755                         }
8756                 }
8757                 CONF("net_avg_samples") {
8758                         if (value) {
8759                                 net_avg_samples = strtol(value, 0, 0);
8760                                 if (net_avg_samples < 1 || net_avg_samples > 14) {
8761                                         CONF_ERR;
8762                                 } else {
8763                                         info.net_avg_samples = net_avg_samples;
8764                                 }
8765                         } else {
8766                                 CONF_ERR;
8767                         }
8768                 }
8769
8770 #ifdef HAVE_XDBE
8771                 CONF("double_buffer") {
8772                         use_xdbe = string_to_bool(value);
8773                 }
8774 #endif
8775 #ifdef X11
8776                 CONF("override_utf8_locale") {
8777                         utf8_mode = string_to_bool(value);
8778                 }
8779                 CONF("draw_borders") {
8780                         draw_borders = string_to_bool(value);
8781                 }
8782                 CONF("draw_graph_borders") {
8783                         draw_graph_borders = string_to_bool(value);
8784                 }
8785                 CONF("draw_shades") {
8786                         draw_shades = string_to_bool(value);
8787                 }
8788                 CONF("draw_outline") {
8789                         draw_outline = string_to_bool(value);
8790                 }
8791 #endif /* X11 */
8792                 CONF("out_to_console") {
8793                         if(string_to_bool(value)) output_methods |= TO_STDOUT;
8794                 }
8795                 CONF("use_spacer") {
8796                         if (value) {
8797                                 if (strcasecmp(value, "left") == EQUAL) {
8798                                         use_spacer = LEFT_SPACER;
8799                                 } else if (strcasecmp(value, "right") == EQUAL) {
8800                                         use_spacer = RIGHT_SPACER;
8801                                 } else if (strcasecmp(value, "none") == EQUAL) {
8802                                         use_spacer = NO_SPACER;
8803                                 } else {
8804                                         use_spacer = string_to_bool(value);
8805                                         ERR("use_spacer should have an argument of left, right, or"
8806                                                 " none.  '%s' seems to be some form of '%s', so"
8807                                                 " defaulting to %s.", value,
8808                                                 use_spacer ? "true" : "false",
8809                                                 use_spacer ? "right" : "none");
8810                                         if (use_spacer) {
8811                                                 use_spacer = RIGHT_SPACER;
8812                                         } else {
8813                                                 use_spacer = NO_SPACER;
8814                                         }
8815                                 }
8816                         } else {
8817                                 ERR("use_spacer should have an argument. Defaulting to right.");
8818                                 use_spacer = RIGHT_SPACER;
8819                         }
8820                 }
8821 #ifdef X11
8822 #ifdef XFT
8823                 CONF("use_xft") {
8824                         use_xft = string_to_bool(value);
8825                 }
8826                 CONF("font") {
8827                         if (value) {
8828                                 set_first_font(value);
8829                         } else {
8830                                 CONF_ERR;
8831                         }
8832                 }
8833                 CONF("xftalpha") {
8834                         if (value && font_count >= 0) {
8835                                 fonts[0].font_alpha = atof(value) * 65535.0;
8836                         } else {
8837                                 CONF_ERR;
8838                         }
8839                 }
8840                 CONF("xftfont") {
8841                         if (use_xft) {
8842 #else
8843                 CONF("use_xft") {
8844                         if (string_to_bool(value)) {
8845                                 ERR("Xft not enabled");
8846                         }
8847                 }
8848                 CONF("xftfont") {
8849                         /* xftfont silently ignored when no Xft */
8850                 }
8851                 CONF("xftalpha") {
8852                         /* xftalpha is silently ignored when no Xft */
8853                 }
8854                 CONF("font") {
8855 #endif
8856                                 if (value) {
8857                                         set_first_font(value);
8858                                 } else {
8859                                         CONF_ERR;
8860                                 }
8861 #ifdef XFT
8862                         }
8863 #endif
8864                 }
8865                 CONF("gap_x") {
8866                         if (value) {
8867                                 gap_x = atoi(value);
8868                         } else {
8869                                 CONF_ERR;
8870                         }
8871                 }
8872                 CONF("gap_y") {
8873                         if (value) {
8874                                 gap_y = atoi(value);
8875                         } else {
8876                                 CONF_ERR;
8877                         }
8878                 }
8879 #endif /* X11 */
8880                 CONF("mail_spool") {
8881                         if (value) {
8882                                 char buffer[256];
8883
8884                                 variable_substitute(value, buffer, 256);
8885
8886                                 if (buffer[0] != '\0') {
8887                                         if (current_mail_spool) {
8888                                                 free(current_mail_spool);
8889                                         }
8890                                         current_mail_spool = strndup(buffer, text_buffer_size);
8891                                 }
8892                         } else {
8893                                 CONF_ERR;
8894                         }
8895                 }
8896 #ifdef X11
8897                 CONF("minimum_size") {
8898                         if (value) {
8899                                 if (sscanf(value, "%d %d", &minimum_width, &minimum_height)
8900                                                 != 2) {
8901                                         if (sscanf(value, "%d", &minimum_width) != 1) {
8902                                                 CONF_ERR;
8903                                         }
8904                                 }
8905                         } else {
8906                                 CONF_ERR;
8907                         }
8908                 }
8909                 CONF("maximum_width") {
8910                         if (value) {
8911                                 if (sscanf(value, "%d", &maximum_width) != 1) {
8912                                         CONF_ERR;
8913                                 }
8914                         } else {
8915                                 CONF_ERR;
8916                         }
8917                 }
8918 #endif /* X11 */
8919                 CONF("no_buffers") {
8920                         no_buffers = string_to_bool(value);
8921                 }
8922                 CONF("top_cpu_separate") {
8923                         cpu_separate = string_to_bool(value);
8924                 }
8925                 CONF("short_units") {
8926                         short_units = string_to_bool(value);
8927                 }
8928                 CONF("pad_percents") {
8929                         pad_percents = atoi(value);
8930                 }
8931 #ifdef X11
8932 #ifdef OWN_WINDOW
8933                 CONF("own_window") {
8934                         if (value) {
8935                                 own_window = string_to_bool(value);
8936                         } else {
8937                                 CONF_ERR;
8938                         }
8939                 }
8940                 CONF("own_window_class") {
8941                         if (value) {
8942                                 memset(window.class_name, 0, sizeof(window.class_name));
8943                                 strncpy(window.class_name, value,
8944                                         sizeof(window.class_name) - 1);
8945                         } else {
8946                                 CONF_ERR;
8947                         }
8948                 }
8949                 CONF("own_window_title") {
8950                         if (value) {
8951                                 memset(window.title, 0, sizeof(window.title));
8952                                 strncpy(window.title, value, sizeof(window.title) - 1);
8953                         } else {
8954                                 CONF_ERR;
8955                         }
8956                 }
8957                 CONF("own_window_transparent") {
8958                         if (value) {
8959                                 set_transparent = string_to_bool(value);
8960                         } else {
8961                                 CONF_ERR;
8962                         }
8963                 }
8964                 CONF("own_window_colour") {
8965                         if (value) {
8966                                 background_colour = get_x11_color(value);
8967                         } else {
8968                                 ERR("Invalid colour for own_window_colour (try omitting the "
8969                                         "'#' for hex colours");
8970                         }
8971                 }
8972                 CONF("own_window_hints") {
8973                         if (value) {
8974                                 char *p_hint, *p_save;
8975                                 char delim[] = ", ";
8976
8977                                 /* tokenize the value into individual hints */
8978                                 if ((p_hint = strtok_r(value, delim, &p_save)) != NULL) {
8979                                         do {
8980                                                 /* fprintf(stderr, "hint [%s] parsed\n", p_hint); */
8981                                                 if (strncmp(p_hint, "undecorate", 10) == EQUAL) {
8982                                                         SET_HINT(window.hints, HINT_UNDECORATED);
8983                                                 } else if (strncmp(p_hint, "below", 5) == EQUAL) {
8984                                                         SET_HINT(window.hints, HINT_BELOW);
8985                                                 } else if (strncmp(p_hint, "above", 5) == EQUAL) {
8986                                                         SET_HINT(window.hints, HINT_ABOVE);
8987                                                 } else if (strncmp(p_hint, "sticky", 6) == EQUAL) {
8988                                                         SET_HINT(window.hints, HINT_STICKY);
8989                                                 } else if (strncmp(p_hint, "skip_taskbar", 12) == EQUAL) {
8990                                                         SET_HINT(window.hints, HINT_SKIP_TASKBAR);
8991                                                 } else if (strncmp(p_hint, "skip_pager", 10) == EQUAL) {
8992                                                         SET_HINT(window.hints, HINT_SKIP_PAGER);
8993                                                 } else {
8994                                                         CONF_ERR;
8995                                                 }
8996
8997                                                 p_hint = strtok_r(NULL, delim, &p_save);
8998                                         } while (p_hint != NULL);
8999                                 }
9000                         } else {
9001                                 CONF_ERR;
9002                         }
9003                 }
9004                 CONF("own_window_type") {
9005                         if (value) {
9006                                 if (strncmp(value, "normal", 6) == EQUAL) {
9007                                         window.type = TYPE_NORMAL;
9008                                 } else if (strncmp(value, "desktop", 7) == EQUAL) {
9009                                         window.type = TYPE_DESKTOP;
9010                                 } else if (strncmp(value, "dock", 7) == EQUAL) {
9011                                         window.type = TYPE_DOCK;
9012                                         text_alignment = TOP_LEFT;
9013                                 } else if (strncmp(value, "override", 8) == EQUAL) {
9014                                         window.type = TYPE_OVERRIDE;
9015                                 } else {
9016                                         CONF_ERR;
9017                                 }
9018                         } else {
9019                                 CONF_ERR;
9020                         }
9021                 }
9022 #endif
9023                 CONF("stippled_borders") {
9024                         if (value) {
9025                                 stippled_borders = strtol(value, 0, 0);
9026                         } else {
9027                                 stippled_borders = 4;
9028                         }
9029                 }
9030 #endif /* X11 */
9031                 CONF("temp1") {
9032                         ERR("temp1 configuration is obsolete, use ${i2c <i2c device here> "
9033                                 "temp 1}");
9034                 }
9035                 CONF("temp2") {
9036                         ERR("temp2 configuration is obsolete, use ${i2c <i2c device here> "
9037                                 "temp 2}");
9038                 }
9039                 CONF("update_interval") {
9040                         if (value) {
9041                                 update_interval = strtod(value, 0);
9042                         } else {
9043                                 CONF_ERR;
9044                         }
9045                         if (info.music_player_interval == 0) {
9046                                 // default to update_interval
9047                                 info.music_player_interval = update_interval;
9048                         }
9049                 }
9050                 CONF("total_run_times") {
9051                         if (value) {
9052                                 total_run_times = strtod(value, 0);
9053                         } else {
9054                                 CONF_ERR;
9055                         }
9056                 }
9057                 CONF("uppercase") {
9058                         stuff_in_upper_case = string_to_bool(value);
9059                 }
9060                 CONF("max_specials") {
9061                         if (value) {
9062                                 max_specials = atoi(value);
9063                         } else {
9064                                 CONF_ERR;
9065                         }
9066                 }
9067                 CONF("max_user_text") {
9068                         if (value) {
9069                                 max_user_text = atoi(value);
9070                         } else {
9071                                 CONF_ERR;
9072                         }
9073                 }
9074                 CONF("text_buffer_size") {
9075                         if (value) {
9076                                 text_buffer_size = atoi(value);
9077                                 if (text_buffer_size < DEFAULT_TEXT_BUFFER_SIZE) {
9078                                         ERR("text_buffer_size must be >=%i bytes", DEFAULT_TEXT_BUFFER_SIZE);
9079                                         text_buffer_size = DEFAULT_TEXT_BUFFER_SIZE;
9080                                 }
9081                         } else {
9082                                 CONF_ERR;
9083                         }
9084                 }
9085                 CONF("text") {
9086                         if (global_text) {
9087                                 free(global_text);
9088                                 global_text = 0;
9089                         }
9090
9091                         global_text = (char *) malloc(1);
9092                         global_text[0] = '\0';
9093
9094                         while (!feof(fp)) {
9095                                 unsigned int l = strlen(global_text);
9096
9097                                 if (fgets(buf, 256, fp) == NULL) {
9098                                         break;
9099                                 }
9100                                 global_text = (char *) realloc(global_text, l + strlen(buf) + 1);
9101                                 strcat(global_text, buf);
9102
9103                                 if (strlen(global_text) > max_user_text) {
9104                                         break;
9105                                 }
9106                         }
9107                         fclose(fp);
9108                         if (strlen(global_text) < 1) {
9109                                 CRIT_ERR("no text supplied in configuration; exiting");
9110                         }
9111                         global_text_lines = line + 1;
9112                         return;
9113                 }
9114 #ifdef TCP_PORT_MONITOR
9115                 CONF("max_port_monitor_connections") {
9116                         if (!value || (sscanf(value, "%d",
9117                                         &tcp_port_monitor_args.max_port_monitor_connections) != 1)
9118                                         || tcp_port_monitor_args.max_port_monitor_connections < 0) {
9119                                 /* an error. use default, warn and continue. */
9120                                 tcp_port_monitor_args.max_port_monitor_connections =
9121                                         MAX_PORT_MONITOR_CONNECTIONS_DEFAULT;
9122                                 CONF_ERR;
9123                         } else if (tcp_port_monitor_args.max_port_monitor_connections
9124                                         == 0) {
9125                                 /* no error, just use default */
9126                                 tcp_port_monitor_args.max_port_monitor_connections =
9127                                         MAX_PORT_MONITOR_CONNECTIONS_DEFAULT;
9128                         }
9129                         /* else tcp_port_monitor_args.max_port_monitor_connections > 0
9130                          * as per config */
9131                 }
9132 #endif
9133                 CONF("if_up_strictness") {
9134                         if (!value) {
9135                                 ERR("incorrect if_up_strictness value, defaulting to 'up'");
9136                                 ifup_strictness = IFUP_UP;
9137                         } else if (strcasecmp(value, "up") == EQUAL) {
9138                                 ifup_strictness = IFUP_UP;
9139                         } else if (strcasecmp(value, "link") == EQUAL) {
9140                                 ifup_strictness = IFUP_LINK;
9141                         } else if (strcasecmp(value, "address") == EQUAL) {
9142                                 ifup_strictness = IFUP_ADDR;
9143                         } else {
9144                                 ERR("incorrect if_up_strictness value, defaulting to 'up'");
9145                                 ifup_strictness = IFUP_UP;
9146                         }
9147                 }
9148
9149                 CONF("temperature_unit") {
9150                         if (!value) {
9151                                 ERR("config option 'temperature_unit' needs an argument");
9152                         } else if (set_temp_output_unit(value)) {
9153                                 ERR("temperature_unit: incorrect argument");
9154                         }
9155                 }
9156
9157                 else {
9158                         ERR("%s: %d: no such configuration: '%s'", f, line, name);
9159                 }
9160
9161 #undef CONF
9162 #undef CONF2
9163         }
9164
9165         fclose(fp);
9166
9167 #undef CONF_ERR
9168
9169         if (info.music_player_interval == 0) {
9170                 // default to update_interval
9171                 info.music_player_interval = update_interval;
9172         }
9173         if (!global_text) { // didn't supply any text
9174                 CRIT_ERR("missing text block in configuration; exiting");
9175         }
9176 }
9177
9178 static void print_help(const char *prog_name) {
9179         printf("Usage: %s [OPTION]...\n"
9180                         PACKAGE_NAME" is a system monitor that renders text on desktop or to own transparent\n"
9181                         "window. Command line options will override configurations defined in config\n"
9182                         "file.\n"
9183                         "   -v, --version             version\n"
9184                         "   -q, --quiet               quiet mode\n"
9185                         "   -D, --debug               increase debugging output\n"
9186                         "   -c, --config=FILE         config file to load\n"
9187                         "   -d, --daemonize           daemonize, fork to background\n"
9188                         "   -h, --help                help\n"
9189 #ifdef X11
9190                         "   -a, --alignment=ALIGNMENT text alignment on screen, {top,bottom,middle}_{left,right,middle}\n"
9191                         "   -f, --font=FONT           font to use\n"
9192 #ifdef OWN_WINDOW
9193                         "   -o, --own-window          create own window to draw\n"
9194 #endif
9195 #ifdef HAVE_XDBE
9196                         "   -b, --double-buffer       double buffer (prevents flickering)\n"
9197 #endif
9198                         "   -w, --window-id=WIN_ID    window id to draw\n"
9199                         "   -x X                      x position\n"
9200                         "   -y Y                      y position\n"
9201 #endif /* X11 */
9202                         "   -t, --text=TEXT           text to render, remember single quotes, like -t '$uptime'\n"
9203                         "   -u, --interval=SECS       update interval\n"
9204                         "   -i COUNT                  number of times to update "PACKAGE_NAME" (and quit)\n",
9205                         prog_name
9206         );
9207 }
9208
9209 /* : means that character before that takes an argument */
9210 static const char *getopt_string = "vVqdDt:u:i:hc:"
9211 #ifdef X11
9212         "x:y:w:a:f:"
9213 #ifdef OWN_WINDOW
9214         "o"
9215 #endif
9216 #ifdef HAVE_XDBE
9217         "b"
9218 #endif
9219 #endif /* X11 */
9220         ;
9221
9222 static const struct option longopts[] = {
9223         { "help", 0, NULL, 'h' },
9224         { "version", 0, NULL, 'V' },
9225         { "debug", 0, NULL, 'D' },
9226         { "config", 1, NULL, 'c' },
9227         { "daemonize", 0, NULL, 'd' },
9228 #ifdef X11
9229         { "alignment", 1, NULL, 'a' },
9230         { "font", 1, NULL, 'f' },
9231 #ifdef OWN_WINDOW
9232         { "own-window", 0, NULL, 'o' },
9233 #endif
9234 #ifdef HAVE_XDBE
9235         { "double-buffer", 0, NULL, 'b' },
9236 #endif
9237         { "window-id", 1, NULL, 'w' },
9238 #endif /* X11 */
9239         { "text", 1, NULL, 't' },
9240         { "interval", 0, NULL, 'u' },
9241         { 0, 0, 0, 0 }
9242 };
9243
9244 int main(int argc, char **argv)
9245 {
9246 #ifdef X11
9247         char *s, *temp;
9248         unsigned int x;
9249 #endif
9250         struct sigaction act, oact;
9251
9252         g_signal_pending = 0;
9253         memset(&info, 0, sizeof(info));
9254         clear_net_stats();
9255
9256 #ifdef TCP_PORT_MONITOR
9257         tcp_port_monitor_args.max_port_monitor_connections =
9258                 MAX_PORT_MONITOR_CONNECTIONS_DEFAULT;
9259 #endif
9260
9261         /* handle command line parameters that don't change configs */
9262 #ifdef X11
9263         if (((s = getenv("LC_ALL")) && *s) || ((s = getenv("LC_CTYPE")) && *s)
9264                         || ((s = getenv("LANG")) && *s)) {
9265                 temp = (char *) malloc((strlen(s) + 1) * sizeof(char));
9266                 if (temp == NULL) {
9267                         ERR("malloc failed");
9268                 }
9269                 for (x = 0; x < strlen(s); x++) {
9270                         temp[x] = tolower(s[x]);
9271                 }
9272                 temp[x] = 0;
9273                 if (strstr(temp, "utf-8") || strstr(temp, "utf8")) {
9274                         utf8_mode = 1;
9275                 }
9276
9277                 free(temp);
9278         }
9279         if (!setlocale(LC_CTYPE, "")) {
9280                 ERR("Can't set the specified locale!\nCheck LANG, LC_CTYPE, LC_ALL.");
9281         }
9282 #endif /* X11 */
9283         while (1) {
9284                 int c = getopt_long(argc, argv, getopt_string, longopts, NULL);
9285
9286                 if (c == -1) {
9287                         break;
9288                 }
9289
9290                 switch (c) {
9291                         case 'v':
9292                         case 'V':
9293                                 print_version();
9294                         case 'c':
9295                                 if (current_config) {
9296                                         free(current_config);
9297                                 }
9298                                 current_config = strndup(optarg, max_user_text);
9299                                 break;
9300                         case 'q':
9301                                 freopen("/dev/null", "w", stderr);
9302                                 break;
9303                         case 'h':
9304                                 print_help(argv[0]);
9305                                 return 0;
9306 #ifdef X11
9307                         case 'w':
9308                                 window.window = strtol(optarg, 0, 0);
9309                                 break;
9310 #endif /* X11 */
9311
9312                         case '?':
9313                                 exit(EXIT_FAILURE);
9314                 }
9315         }
9316 #ifdef X11
9317         /* initalize X BEFORE we load config.
9318          * (we need to so that 'screen' is set) */
9319         init_X11();
9320 #endif /* X11 */
9321
9322         /* check if specified config file is valid */
9323         if (current_config) {
9324                 struct stat sb;
9325                 if (stat(current_config, &sb) ||
9326                                 (!S_ISREG(sb.st_mode) && !S_ISLNK(sb.st_mode))) {
9327                         ERR("invalid configuration file '%s'\n", current_config);
9328                         free(current_config);
9329                         current_config = 0;
9330                 }
9331         }
9332
9333         /* load current_config, CONFIG_FILE or SYSTEM_CONFIG_FILE */
9334
9335         if (!current_config) {
9336                 /* load default config file */
9337                 char buf[256];
9338                 FILE *fp;
9339
9340                 /* Try to use personal config file first */
9341                 variable_substitute(CONFIG_FILE, buf, sizeof(buf));
9342                 if (buf[0] && (fp = fopen(buf, "r"))) {
9343                         current_config = strndup(buf, max_user_text);
9344                         fclose(fp);
9345                 }
9346
9347                 /* Try to use system config file if personal config not readable */
9348                 if (!current_config && (fp = fopen(SYSTEM_CONFIG_FILE, "r"))) {
9349                         current_config = strndup(SYSTEM_CONFIG_FILE, max_user_text);
9350                         fclose(fp);
9351                 }
9352
9353                 /* No readable config found */
9354                 if (!current_config) {
9355                         CRIT_ERR("no readable personal or system-wide config file found");
9356                 }
9357         }
9358
9359         load_config_file(current_config);
9360
9361         /* init specials array */
9362         if ((specials = calloc(sizeof(struct special_t), max_specials)) == 0) {
9363                 ERR("failed to create specials array");
9364         }
9365
9366 #ifdef MAIL_FILE
9367         if (current_mail_spool == NULL) {
9368                 char buf[256];
9369
9370                 variable_substitute(MAIL_FILE, buf, 256);
9371
9372                 if (buf[0] != '\0') {
9373                         current_mail_spool = strndup(buf, text_buffer_size);
9374                 }
9375         }
9376 #endif
9377
9378         /* handle other command line arguments */
9379
9380 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__) \
9381                 || defined(__NetBSD__)
9382         optind = optreset = 1;
9383 #else
9384         optind = 0;
9385 #endif
9386
9387 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
9388         if ((kd = kvm_open("/dev/null", "/dev/null", "/dev/null", O_RDONLY,
9389                         "kvm_open")) == NULL) {
9390                 CRIT_ERR("cannot read kvm");
9391         }
9392 #endif
9393
9394         while (1) {
9395                 int c = getopt_long(argc, argv, getopt_string, longopts, NULL);
9396
9397                 if (c == -1) {
9398                         break;
9399                 }
9400
9401                 switch (c) {
9402                         case 'd':
9403                                 fork_to_background = 1;
9404                                 break;
9405                         case 'D':
9406                                 global_debug_level++;
9407                                 break;
9408 #ifdef X11
9409                         case 'f':
9410                                 set_first_font(optarg);
9411                                 break;
9412                         case 'a':
9413                                 text_alignment = string_to_alignment(optarg);
9414                                 break;
9415
9416 #ifdef OWN_WINDOW
9417                         case 'o':
9418                                 own_window = 1;
9419                                 break;
9420 #endif
9421 #ifdef HAVE_XDBE
9422                         case 'b':
9423                                 use_xdbe = 1;
9424                                 break;
9425 #endif
9426 #endif /* X11 */
9427                         case 't':
9428                                 if (global_text) {
9429                                         free(global_text);
9430                                         global_text = 0;
9431                                 }
9432                                 global_text = strndup(optarg, max_user_text);
9433                                 convert_escapes(global_text);
9434                                 break;
9435
9436                         case 'u':
9437                                 update_interval = strtod(optarg, 0);
9438                                 if (info.music_player_interval == 0) {
9439                                         // default to update_interval
9440                                         info.music_player_interval = update_interval;
9441                                 }
9442                                 break;
9443
9444                         case 'i':
9445                                 total_run_times = strtod(optarg, 0);
9446                                 break;
9447 #ifdef X11
9448                         case 'x':
9449                                 gap_x = atoi(optarg);
9450                                 break;
9451
9452                         case 'y':
9453                                 gap_y = atoi(optarg);
9454                                 break;
9455 #endif /* X11 */
9456
9457                         case '?':
9458                                 exit(EXIT_FAILURE);
9459                 }
9460         }
9461
9462 #ifdef X11
9463         /* load font */
9464         load_fonts();
9465 #endif /* X11 */
9466
9467         /* generate text and get initial size */
9468         extract_variable_text(global_text);
9469         if (global_text) {
9470                 free(global_text);
9471                 global_text = 0;
9472         }
9473         global_text = NULL;
9474         /* fork */
9475         if (fork_to_background) {
9476                 int pid = fork();
9477
9478                 switch (pid) {
9479                         case -1:
9480                                 ERR(PACKAGE_NAME": couldn't fork() to background: %s",
9481                                         strerror(errno));
9482                                 break;
9483
9484                         case 0:
9485                                 /* child process */
9486                                 usleep(25000);
9487                                 fprintf(stderr, "\n");
9488                                 fflush(stderr);
9489                                 break;
9490
9491                         default:
9492                                 /* parent process */
9493                                 fprintf(stderr, PACKAGE_NAME": forked to background, pid is %d\n",
9494                                         pid);
9495                                 fflush(stderr);
9496                                 return 0;
9497                 }
9498         }
9499
9500         text_buffer = malloc(max_user_text);
9501         memset(text_buffer, 0, max_user_text);
9502         tmpstring1 = malloc(text_buffer_size);
9503         memset(tmpstring1, 0, text_buffer_size);
9504         tmpstring2 = malloc(text_buffer_size);
9505         memset(tmpstring2, 0, text_buffer_size);
9506
9507 #ifdef X11
9508         selected_font = 0;
9509         update_text_area();     /* to get initial size of the window */
9510
9511 #ifdef OWN_WINDOW
9512         init_window(own_window, text_width + border_margin * 2 + 1,
9513                 text_height + border_margin * 2 + 1, set_transparent, background_colour,
9514                 argv, argc);
9515 #else /* OWN_WINDOW */
9516         init_window(0, text_width + border_margin * 2 + 1,
9517                 text_height + border_margin * 2 + 1, set_transparent, 0,
9518                 argv, argc);
9519 #endif /* OWN_WINDOW */
9520
9521         selected_font = 0;
9522         update_text_area();     /* to position text/window on screen */
9523
9524 #ifdef OWN_WINDOW
9525         if (own_window && !fixed_pos) {
9526                 XMoveWindow(display, window.window, window.x, window.y);
9527         }
9528         if (own_window) {
9529                 set_transparent_background(window.window);
9530         }
9531 #endif
9532
9533         create_gc();
9534
9535         set_font();
9536         draw_stuff();
9537 #endif /* X11 */
9538
9539         /* Set signal handlers */
9540         act.sa_handler = signal_handler;
9541         sigemptyset(&act.sa_mask);
9542         act.sa_flags = 0;
9543 #ifdef SA_RESTART
9544         act.sa_flags |= SA_RESTART;
9545 #endif
9546
9547         if (            sigaction(SIGINT,  &act, &oact) < 0
9548                         ||      sigaction(SIGUSR1, &act, &oact) < 0
9549                         ||      sigaction(SIGHUP,  &act, &oact) < 0
9550                         ||      sigaction(SIGTERM, &act, &oact) < 0) {
9551                 ERR("error setting signal handler: %s", strerror(errno));
9552         }
9553
9554         main_loop();
9555
9556 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
9557         kvm_close(kd);
9558 #endif
9559
9560         return 0;
9561 }
9562
9563 void signal_handler(int sig)
9564 {
9565         /* signal handler is light as a feather, as it should be.
9566          * we will poll g_signal_pending with each loop of conky
9567          * and do any signal processing there, NOT here. */
9568         g_signal_pending = sig;
9569 }