Fix broken cpu usage stuff (due to a previous commit).
[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  * $Id$ */
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         int dup_idx = 0, dup_len;
4251
4252         dup_len = strlen(src);
4253         if (templates) {
4254                 unsigned int i;
4255                 for (i = 0; i < template_count; i++)
4256                         dup_len += strlen(templates[i]);
4257         }
4258
4259         src_dup = malloc(dup_len * sizeof(char));
4260         p = src;
4261         while (*p) {
4262                 switch (*p) {
4263                 case '\\':
4264                         if (!*(p + 1))
4265                                 break;
4266                         if (*(p + 1) == '\\') {
4267                                 src_dup[dup_idx++] = '\\';
4268                                 p++;
4269                         } else if (*(p + 1) == ' ') {
4270                                 src_dup[dup_idx++] = ' ';
4271                                 p++;
4272                         } else if (*(p + 1) == 'n') {
4273                                 src_dup[dup_idx++] = '\n';
4274                                 p++;
4275                         } else if (templates) {
4276                                 unsigned int tmpl_num;
4277                                 int digits;
4278                                 if ((sscanf(p + 1, "%u%n", &tmpl_num, &digits) <= 0) ||
4279                                     (tmpl_num > template_count))
4280                                         break;
4281                                 sprintf(src_dup + dup_idx, "%s", templates[tmpl_num - 1]);
4282                                 dup_idx += strlen(templates[tmpl_num - 1]);
4283                                 p += digits;
4284                         }
4285                         break;
4286                 default:
4287                         src_dup[dup_idx++] = *p;
4288                         break;
4289                 }
4290                 p++;
4291         }
4292         src_dup[dup_idx] = '\0';
4293         src_dup = realloc(src_dup, (strlen(src_dup) + 1) * sizeof(char));
4294         return src_dup;
4295 }
4296 static struct text_object_list *extract_variable_text_internal(const char *, char);
4297
4298 /* handle_template_object - core logic of the template object
4299  *
4300  * use config variables like this:
4301  * template1 = "$\1\2"
4302  * template2 = "\1: ${fs_bar 4,100 \2} ${fs_used \2} / ${fs_size \2}"
4303  *
4304  * and use them like this:
4305  * ${template1 node name}
4306  * ${template2 root /}
4307  * ${template2 cdrom /mnt/cdrom}
4308  */
4309 static int handle_template_object(struct text_object_list **list,
4310                 char allow_threaded, const char *tmpl, const char *args)
4311 {
4312         char *args_dup, *template_dup, *p, *p_old;
4313         char **argsp = NULL;
4314         unsigned int argcnt = 0, template_idx, i;
4315         char *eval_text;
4316         struct text_object_list *eval_list;
4317
4318         if ((sscanf(tmpl, "template%u", &template_idx) != 1) ||
4319             (template_idx > 9))
4320                 return 1;
4321
4322         args_dup = strdup(args);
4323         p = args_dup;
4324         while (*p) {
4325                 while (*p && (*p == ' ' && *(p - 1) != '\\'))
4326                         p++;
4327                 if (*(p - 1) == '\\')
4328                         p--;
4329                 p_old = p;
4330                 while (*p && (*p != ' ' || *(p - 1) == '\\'))
4331                         p++;
4332                 if (*p) {
4333                         (*p) = '\0';
4334                         p++;
4335                 }
4336                 argsp = realloc(argsp, ++argcnt * sizeof(char *));
4337                 argsp[argcnt - 1] = p_old;
4338         }
4339         for (i = 0; i < argcnt; i++) {
4340                 char *tmp;
4341                 tmp = backslash_escape(argsp[i], NULL, 0);
4342                 DBGP2("%s: substituted arg '%s' to '%s'", tmpl, argsp[i], tmp);
4343                 sprintf(argsp[i], "%s", tmp);
4344                 free(tmp);
4345         }
4346
4347         p = template_dup = strdup(template[template_idx]);
4348
4349         eval_text = backslash_escape(template[template_idx], argsp, argcnt);
4350         DBGP("substituted %s, output is '%s'", tmpl, eval_text);
4351
4352         eval_list = extract_variable_text_internal(eval_text, allow_threaded);
4353         if (eval_list) {
4354                 (*list)->text_objects = realloc((*list)->text_objects,
4355                                 sizeof(struct text_object) *
4356                                 ((*list)->text_object_count +
4357                                  eval_list->text_object_count));
4358                 memcpy((*list)->text_objects + (*list)->text_object_count,
4359                                 eval_list->text_objects,
4360                                 sizeof(struct text_object) *
4361                                 eval_list->text_object_count);
4362                 (*list)->text_object_count += eval_list->text_object_count;
4363                 free(eval_list->text_objects);
4364                 free(eval_list);
4365         }
4366         free(args_dup);
4367         free(template_dup);
4368         free(eval_text);
4369         free(argsp);
4370         return 0;
4371 }
4372
4373 static struct text_object_list *extract_variable_text_internal(const char *const_p, char allow_threaded)
4374 {
4375         struct text_object_list *retval;
4376         struct text_object *obj;
4377         char *p, *s, *orig_p;
4378         long line;
4379
4380         p = strndup(const_p, max_user_text);
4381         s = orig_p = p;
4382
4383         retval = malloc(sizeof(struct text_object_list));
4384         memset(retval, 0, sizeof(struct text_object_list));
4385         retval->text_object_count = 0;
4386
4387         line = global_text_lines;
4388
4389         while (*p) {
4390                 if (*p == '\n') {
4391                         line++;
4392                 }
4393                 if (*p == '$') {
4394                         *p = '\0';
4395                         obj = create_plain_text(s);
4396                         if (obj != NULL) {
4397                                 // allocate memory for the object
4398                                 retval->text_objects = realloc(retval->text_objects,
4399                                                 sizeof(struct text_object) *
4400                                                 (retval->text_object_count + 1));
4401                                 // assign the new object to the end of the list.
4402                                 memcpy(&retval->text_objects[retval->text_object_count++], obj,
4403                                                 sizeof(struct text_object));
4404                                 free(obj);
4405                         }
4406                         *p = '$';
4407                         p++;
4408                         s = p;
4409
4410                         if (*p != '$') {
4411                                 char buf[256];
4412                                 const char *var;
4413                                 unsigned int len;
4414
4415                                 /* variable is either $foo or ${foo} */
4416                                 if (*p == '{') {
4417                                         unsigned int brl = 1, brr = 0;
4418
4419                                         p++;
4420                                         s = p;
4421                                         while (*p && brl != brr) {
4422                                                 if (*p == '{') {
4423                                                         brl++;
4424                                                 }
4425                                                 if (*p == '}') {
4426                                                         brr++;
4427                                                 }
4428                                                 p++;
4429                                         }
4430                                         p--;
4431                                 } else {
4432                                         s = p;
4433                                         if (*p == '#') {
4434                                                 p++;
4435                                         }
4436                                         while (*p && (isalnum((int) *p) || *p == '_')) {
4437                                                 p++;
4438                                         }
4439                                 }
4440
4441                                 /* copy variable to buffer */
4442                                 len = (p - s > 255) ? 255 : (p - s);
4443                                 strncpy(buf, s, len);
4444                                 buf[len] = '\0';
4445
4446                                 if (*p == '}') {
4447                                         p++;
4448                                 }
4449                                 s = p;
4450
4451                                 var = getenv(buf);
4452
4453                                 /* if variable wasn't found in environment, use some special */
4454                                 if (!var) {
4455                                         char *tmp_p;
4456                                         char *arg = 0;
4457
4458                                         /* split arg */
4459                                         if (strchr(buf, ' ')) {
4460                                                 arg = strchr(buf, ' ');
4461                                                 *arg = '\0';
4462                                                 arg++;
4463                                                 while (isspace((int) *arg)) {
4464                                                         arg++;
4465                                                 }
4466                                                 if (!*arg) {
4467                                                         arg = 0;
4468                                                 }
4469                                         }
4470
4471                                         /* lowercase variable name */
4472                                         tmp_p = buf;
4473                                         while (*tmp_p) {
4474                                                 *tmp_p = tolower(*tmp_p);
4475                                                 tmp_p++;
4476                                         }
4477
4478                                         if (!strncmp(buf, "template", 8)) {
4479                                                 if (handle_template_object(&retval, allow_threaded, buf, arg))
4480                                                         printf("Error: handling template '%s' failed for args '%s'\n", buf, arg);
4481                                         } else {
4482                                                 // create new object
4483                                                 obj = construct_text_object(buf, arg,
4484                                                                 retval->text_object_count, retval->text_objects, line, allow_threaded);
4485                                                 if (obj != NULL) {
4486                                                         // allocate memory for the object
4487                                                         retval->text_objects = realloc(retval->text_objects,
4488                                                                         sizeof(struct text_object) *
4489                                                                         (retval->text_object_count + 1));
4490                                                         // assign the new object to the end of the list.
4491                                                         memcpy(
4492                                                                         &retval->text_objects[retval->text_object_count++],
4493                                                                         obj, sizeof(struct text_object));
4494                                                         free(obj);
4495                                                 }
4496                                         }
4497                                 }
4498                                 continue;
4499                         } else {
4500                                 obj = create_plain_text("$");
4501                                 if (obj != NULL) {
4502                                         // allocate memory for the object
4503                                         retval->text_objects = realloc(retval->text_objects,
4504                                                         sizeof(struct text_object) *
4505                                                         (retval->text_object_count + 1));
4506                                         // assign the new object to the end of the list.
4507                                         memcpy(&retval->text_objects[retval->text_object_count++],
4508                                                         obj, sizeof(struct text_object));
4509                                         free(obj);
4510                                 }
4511                         }
4512                 }
4513                 p++;
4514         }
4515         obj = create_plain_text(s);
4516         if (obj != NULL) {
4517                 // allocate memory for the object
4518                 retval->text_objects = realloc(retval->text_objects,
4519                                 sizeof(struct text_object) * (retval->text_object_count + 1));
4520                 // assign the new object to the end of the list.
4521                 memcpy(&retval->text_objects[retval->text_object_count++], obj,
4522                                 sizeof(struct text_object));
4523                 free(obj);
4524         }
4525
4526         if (blockdepth) {
4527                 ERR("one or more $endif's are missing");
4528         }
4529
4530         free(orig_p);
4531         return retval;
4532 }
4533
4534 static void extract_variable_text(const char *p)
4535 {
4536         free_text_objects(global_text_object_list, 1);
4537         free(global_text_object_list);
4538         if (tmpstring1) {
4539                 free(tmpstring1);
4540                 tmpstring1 = 0;
4541         }
4542         if (tmpstring2) {
4543                 free(tmpstring2);
4544                 tmpstring2 = 0;
4545         }
4546         if (text_buffer) {
4547                 free(text_buffer);
4548                 text_buffer = 0;
4549         }
4550
4551         global_text_object_list = extract_variable_text_internal(p, 1);
4552 }
4553
4554 struct text_object_list *parse_conky_vars(char *txt, char *p, struct information *cur)
4555 {
4556         struct text_object_list *object_list =
4557                 extract_variable_text_internal(txt, 0);
4558
4559         generate_text_internal(p, max_user_text, object_list, cur);
4560         return object_list;
4561 }
4562
4563 /* Allows reading from a FIFO (i.e., /dev/xconsole).
4564  * The file descriptor is set to non-blocking which makes this possible.
4565  *
4566  * FIXME: Since lseek cannot seek a file descriptor long lines will break. */
4567 static void tail_pipe(struct text_object *obj, char *dst, size_t dst_size)
4568 {
4569 #define TAIL_PIPE_BUFSIZE       4096
4570         int lines = 0;
4571         int line_len = 0;
4572         int last_line = 0;
4573         int fd = obj->data.tail.fd;
4574
4575         while (1) {
4576                 char buf[TAIL_PIPE_BUFSIZE];
4577                 ssize_t len = read(fd, buf, sizeof(buf));
4578                 int i;
4579
4580                 if (len == -1) {
4581                         if (errno != EAGAIN) {
4582                                 strcpy(obj->data.tail.buffer, "Logfile Read Error");
4583                                 snprintf(dst, dst_size, "Logfile Read Error");
4584                         }
4585
4586                         break;
4587                 } else if (len == 0) {
4588                         strcpy(obj->data.tail.buffer, "Logfile Empty");
4589                         snprintf(dst, dst_size, "Logfile Empty");
4590                         break;
4591                 }
4592
4593                 for (line_len = 0, i = 0; i < len; i++) {
4594                         int pos = 0;
4595                         char *p;
4596
4597                         if (buf[i] == '\n') {
4598                                 lines++;
4599
4600                                 if (obj->data.tail.readlines > 0) {
4601                                         int n;
4602                                         int olines = 0;
4603                                         int first_line = 0;
4604
4605                                         for (n = 0; obj->data.tail.buffer[n]; n++) {
4606                                                 if (obj->data.tail.buffer[n] == '\n') {
4607                                                         if (!first_line) {
4608                                                                 first_line = n + 1;
4609                                                         }
4610
4611                                                         if (++olines < obj->data.tail.wantedlines) {
4612                                                                 pos = n + 1;
4613                                                                 continue;
4614                                                         }
4615
4616                                                         n++;
4617                                                         p = obj->data.tail.buffer + first_line;
4618                                                         pos = n - first_line;
4619                                                         memmove(obj->data.tail.buffer,
4620                                                                         obj->data.tail.buffer + first_line, strlen(p));
4621                                                         obj->data.tail.buffer[pos] = 0;
4622                                                         break;
4623                                                 }
4624                                         }
4625                                 }
4626
4627                                 p = buf + last_line;
4628                                 line_len++;
4629                                 memcpy(&(obj->data.tail.buffer[pos]), p, line_len);
4630                                 obj->data.tail.buffer[pos + line_len] = 0;
4631                                 last_line = i + 1;
4632                                 line_len = 0;
4633                                 obj->data.tail.readlines = lines;
4634                                 continue;
4635                         }
4636
4637                         line_len++;
4638                 }
4639         }
4640
4641         snprintf(dst, dst_size, "%s", obj->data.tail.buffer);
4642 }
4643
4644 static inline struct mail_s *ensure_mail_thread(struct text_object *obj,
4645                 void *thread(void *), const char *text)
4646 {
4647         if (obj->global_mode && info.mail) {
4648                 // this means we use info
4649                 if (!info.mail->p_timed_thread) {
4650                         info.mail->p_timed_thread =
4651                                 timed_thread_create(thread,
4652                                                 (void *) info.mail, info.mail->interval * 1000000);
4653                         if (!info.mail->p_timed_thread) {
4654                                 ERR("Error creating %s timed thread", text);
4655                         }
4656                         timed_thread_register(info.mail->p_timed_thread,
4657                                         &info.mail->p_timed_thread);
4658                         if (timed_thread_run(info.mail->p_timed_thread)) {
4659                                 ERR("Error running %s timed thread", text);
4660                         }
4661                 }
4662                 return info.mail;
4663         } else if (obj->data.mail) {
4664                 // this means we use obj
4665                 if (!obj->data.mail->p_timed_thread) {
4666                         obj->data.mail->p_timed_thread =
4667                                 timed_thread_create(thread,
4668                                                 (void *) obj->data.mail,
4669                                                 obj->data.mail->interval * 1000000);
4670                         if (!obj->data.mail->p_timed_thread) {
4671                                 ERR("Error creating %s timed thread", text);
4672                         }
4673                         timed_thread_register(obj->data.mail->p_timed_thread,
4674                                         &obj->data.mail->p_timed_thread);
4675                         if (timed_thread_run(obj->data.mail->p_timed_thread)) {
4676                                 ERR("Error running %s timed thread", text);
4677                         }
4678                 }
4679                 return obj->data.mail;
4680         } else if (!obj->a) {
4681                 // something is wrong, warn once then stop
4682                 ERR("Theres a problem with your %s_unseen settings.  "
4683                                 "Check that the global %s settings are defined "
4684                                 "properly (line %li).", global_text, global_text, obj->line);
4685                 obj->a++;
4686         }
4687         return NULL;
4688 }
4689
4690 char *format_time(unsigned long timeval, const int width)
4691 {
4692         char buf[10];
4693         unsigned long nt;       // narrow time, for speed on 32-bit
4694         unsigned cc;            // centiseconds
4695         unsigned nn;            // multi-purpose whatever
4696
4697         nt = timeval;
4698         cc = nt % 100;          // centiseconds past second
4699         nt /= 100;                      // total seconds
4700         nn = nt % 60;           // seconds past the minute
4701         nt /= 60;                       // total minutes
4702         if (width >= snprintf(buf, sizeof buf, "%lu:%02u.%02u",
4703                                 nt, nn, cc)) {
4704                 return strndup(buf, text_buffer_size);
4705         }
4706         if (width >= snprintf(buf, sizeof buf, "%lu:%02u", nt, nn)) {
4707                 return strndup(buf, text_buffer_size);
4708         }
4709         nn = nt % 60;           // minutes past the hour
4710         nt /= 60;                       // total hours
4711         if (width >= snprintf(buf, sizeof buf, "%lu,%02u", nt, nn)) {
4712                 return strndup(buf, text_buffer_size);
4713         }
4714         nn = nt;                        // now also hours
4715         if (width >= snprintf(buf, sizeof buf, "%uh", nn)) {
4716                 return strndup(buf, text_buffer_size);
4717         }
4718         nn /= 24;                       // now days
4719         if (width >= snprintf(buf, sizeof buf, "%ud", nn)) {
4720                 return strndup(buf, text_buffer_size);
4721         }
4722         nn /= 7;                        // now weeks
4723         if (width >= snprintf(buf, sizeof buf, "%uw", nn)) {
4724                 return strndup(buf, text_buffer_size);
4725         }
4726         // well shoot, this outta' fit...
4727         return strndup("<inf>", text_buffer_size);
4728 }
4729
4730 //remove backspaced chars, example: "dog^H^H^Hcat" becomes "cat"
4731 //string has to end with \0 and it's length should fit in a int
4732 #define BACKSPACE 8
4733 void remove_deleted_chars(char *string){
4734         int i = 0;
4735         while(string[i] != 0){
4736                 if(string[i] == BACKSPACE){
4737                         if(i != 0){
4738                                 strcpy( &(string[i-1]), &(string[i+1]) );
4739                                 i--;
4740                         }else strcpy( &(string[i]), &(string[i+1]) ); //necessary for ^H's at the start of a string
4741                 }else i++;
4742         }
4743 }
4744
4745 static inline void format_media_player_time(char *buf, const int size,
4746                 int seconds)
4747 {
4748         int days, hours, minutes;
4749
4750         days = seconds / (24 * 60 * 60);
4751         seconds %= (24 * 60 * 60);
4752         hours = seconds / (60 * 60);
4753         seconds %= (60 * 60);
4754         minutes = seconds / 60;
4755         seconds %= 60;
4756
4757         if (days > 0) {
4758                 snprintf(buf, size, "%i days %i:%02i:%02i", days,
4759                                 hours, minutes, seconds);
4760         } else if (hours > 0) {
4761                 snprintf(buf, size, "%i:%02i:%02i", hours, minutes,
4762                                 seconds);
4763         } else {
4764                 snprintf(buf, size, "%i:%02i", minutes, seconds);
4765         }
4766 }
4767
4768 static inline double get_barnum(char *buf)
4769 {
4770         char *c = buf;
4771         double barnum;
4772
4773         while (*c) {
4774                 if (*c == '\001') {
4775                         *c = ' ';
4776                 }
4777                 c++;
4778         }
4779
4780         if (sscanf(buf, "%lf", &barnum) == 0) {
4781                 ERR("reading execbar value failed (perhaps it's not the "
4782                                 "correct format?)");
4783                 return -1;
4784         }
4785         if (barnum > 100.0 || barnum < 0.0) {
4786                 ERR("your execbar value is not between 0 and 100, "
4787                                 "therefore it will be ignored");
4788                 return -1;
4789         }
4790         return barnum;
4791 }
4792
4793 static void generate_text_internal(char *p, int p_max_size,
4794                 struct text_object_list *text_object_list,
4795                 struct information *cur)
4796 {
4797         unsigned int i;
4798
4799 #ifdef HAVE_ICONV
4800         char buff_in[p_max_size];
4801         buff_in[0] = 0;
4802         iconv_converting = 0;
4803 #endif
4804
4805         p[0] = 0;
4806         for (i = 0; i < text_object_list->text_object_count; i++) {
4807                 struct text_object *obj = &(text_object_list->text_objects[i]);
4808
4809                 if (p_max_size < 1) {
4810                         break;
4811                 };
4812
4813 #define OBJ(a) break; case OBJ_##a:
4814
4815                 switch (obj->type) {
4816                         default:
4817                                 ERR("not implemented obj type %d", obj->type);
4818 #ifndef __OpenBSD__
4819                         OBJ(acpitemp) {
4820                                 temp_print(p, p_max_size, get_acpi_temperature(obj->data.i), TEMP_CELSIUS);
4821                         }
4822 #endif /* !__OpenBSD__ */
4823                         OBJ(freq) {
4824                                 if (obj->a) {
4825                                         obj->a = get_freq(p, p_max_size, "%.0f", 1,
4826                                                         obj->data.cpu_index);
4827                                 }
4828                         }
4829                         OBJ(freq_g) {
4830                                 if (obj->a) {
4831 #ifndef __OpenBSD__
4832                                         obj->a = get_freq(p, p_max_size, "%'.2f", 1000,
4833                                                         obj->data.cpu_index);
4834 #else
4835                                         /* OpenBSD has no such flag (SUSv2) */
4836                                         obj->a = get_freq(p, p_max_size, "%.2f", 1000,
4837                                                         obj->data.cpu_index);
4838 #endif
4839                                 }
4840                         }
4841 #if defined(__linux__)
4842                         OBJ(voltage_mv) {
4843                                 if (obj->a) {
4844                                         obj->a = get_voltage(p, p_max_size, "%.0f", 1,
4845                                                         obj->data.cpu_index);
4846                                 }
4847                         }
4848                         OBJ(voltage_v) {
4849                                 if (obj->a) {
4850                                         obj->a = get_voltage(p, p_max_size, "%'.3f", 1000,
4851                                                         obj->data.cpu_index);
4852                                 }
4853                         }
4854
4855 #ifdef HAVE_IWLIB
4856                         OBJ(wireless_essid) {
4857                                 snprintf(p, p_max_size, "%s", obj->data.net->essid);
4858                         }
4859                         OBJ(wireless_mode) {
4860                                 snprintf(p, p_max_size, "%s", obj->data.net->mode);
4861                         }
4862                         OBJ(wireless_bitrate) {
4863                                 snprintf(p, p_max_size, "%s", obj->data.net->bitrate);
4864                         }
4865                         OBJ(wireless_ap) {
4866                                 snprintf(p, p_max_size, "%s", obj->data.net->ap);
4867                         }
4868                         OBJ(wireless_link_qual) {
4869                                 spaced_print(p, p_max_size, "%d", 4, "wireless_link_qual",
4870                                                 obj->data.net->link_qual);
4871                         }
4872                         OBJ(wireless_link_qual_max) {
4873                                 spaced_print(p, p_max_size, "%d", 4,
4874                                                 "wireless_link_qual_max", obj->data.net->link_qual_max);
4875                         }
4876                         OBJ(wireless_link_qual_perc) {
4877                                 if (obj->data.net->link_qual_max > 0) {
4878                                         spaced_print(p, p_max_size, "%.0f", 5,
4879                                                         "wireless_link_qual_perc",
4880                                                         (double) obj->data.net->link_qual /
4881                                                         obj->data.net->link_qual_max * 100);
4882                                 } else {
4883                                         spaced_print(p, p_max_size, "unk", 5,
4884                                                         "wireless_link_qual_perc");
4885                                 }
4886                         }
4887                         OBJ(wireless_link_bar) {
4888                                 new_bar(p, obj->a, obj->b, ((double) obj->data.net->link_qual /
4889                                                         obj->data.net->link_qual_max) * 255.0);
4890                         }
4891 #endif /* HAVE_IWLIB */
4892
4893 #endif /* __linux__ */
4894
4895 #ifndef __OpenBSD__
4896                         OBJ(adt746xcpu) {
4897                                 get_adt746x_cpu(p, p_max_size);
4898                         }
4899                         OBJ(adt746xfan) {
4900                                 get_adt746x_fan(p, p_max_size);
4901                         }
4902                         OBJ(acpifan) {
4903                                 get_acpi_fan(p, p_max_size);
4904                         }
4905                         OBJ(acpiacadapter) {
4906                                 get_acpi_ac_adapter(p, p_max_size);
4907                         }
4908                         OBJ(battery) {
4909                                 get_battery_stuff(p, p_max_size, obj->data.s, BATTERY_STATUS);
4910                         }
4911                         OBJ(battery_time) {
4912                                 get_battery_stuff(p, p_max_size, obj->data.s, BATTERY_TIME);
4913                         }
4914                         OBJ(battery_percent) {
4915                                 spaced_print(p, p_max_size, "%*d", 4, "battery_percent",
4916                                                 pad_percents, get_battery_perct(obj->data.s));
4917                         }
4918                         OBJ(battery_bar) {
4919                                 new_bar(p, obj->a, obj->b, get_battery_perct_bar(obj->data.s));
4920                         }
4921 #endif /* __OpenBSD__ */
4922
4923                         OBJ(buffers) {
4924                                 human_readable(cur->buffers * 1024, p, 255, "buffers");
4925                         }
4926                         OBJ(cached) {
4927                                 human_readable(cur->cached * 1024, p, 255, "buffers");
4928                         }
4929                         OBJ(cpu) {
4930                                 if (obj->data.cpu_index > info.cpu_count) {
4931                                         printf("obj->data.cpu_index %i info.cpu_count %i",
4932                                                         obj->data.cpu_index, info.cpu_count);
4933                                         CRIT_ERR("attempting to use more CPUs than you have!");
4934                                 }
4935                                 spaced_print(p, p_max_size, "%*d", 4, "cpu", pad_percents,
4936                                                 round_to_int(cur->cpu_usage[obj->data.cpu_index] * 100.0));
4937                         }
4938                         OBJ(cpubar) {
4939                                 new_bar(p, obj->a, obj->b,
4940                                                 round_to_int(cur->cpu_usage[obj->data.cpu_index] * 255.0));
4941                         }
4942                         OBJ(cpugraph) {
4943                                 new_graph(p, obj->a, obj->b, obj->c, obj->d, (unsigned int)
4944                                                 round_to_int(cur->cpu_usage[obj->data.cpu_index] * 100),
4945                                                 100, 1, obj->showaslog);
4946                         }
4947                         OBJ(loadgraph) {
4948                                 new_graph(p, obj->a, obj->b, obj->c, obj->d, cur->loadavg[0],
4949                                                 obj->e, 1, obj->showaslog);
4950                         }
4951                         OBJ(color) {
4952                                 new_fg(p, obj->data.l);
4953                         }
4954                         OBJ(color0) {
4955                                 new_fg(p, color0);
4956                         }
4957                         OBJ(color1) {
4958                                 new_fg(p, color1);
4959                         }
4960                         OBJ(color2) {
4961                                 new_fg(p, color2);
4962                         }
4963                         OBJ(color3) {
4964                                 new_fg(p, color3);
4965                         }
4966                         OBJ(color4) {
4967                                 new_fg(p, color4);
4968                         }
4969                         OBJ(color5) {
4970                                 new_fg(p, color5);
4971                         }
4972                         OBJ(color6) {
4973                                 new_fg(p, color6);
4974                         }
4975                         OBJ(color7) {
4976                                 new_fg(p, color7);
4977                         }
4978                         OBJ(color8) {
4979                                 new_fg(p, color8);
4980                         }
4981                         OBJ(color9) {
4982                                 new_fg(p, color9);
4983                         }
4984                         OBJ(conky_version) {
4985                                 snprintf(p, p_max_size, "%s", VERSION);
4986                         }
4987                         OBJ(conky_build_date) {
4988                                 snprintf(p, p_max_size, "%s", BUILD_DATE);
4989                         }
4990                         OBJ(conky_build_arch) {
4991                                 snprintf(p, p_max_size, "%s", BUILD_ARCH);
4992                         }
4993 #if defined(__linux__)
4994                         OBJ(disk_protect) {
4995                                 snprintf(p, p_max_size, "%s",
4996                                                 get_disk_protect_queue(obj->data.s));
4997                         }
4998                         OBJ(i8k_version) {
4999                                 snprintf(p, p_max_size, "%s", i8k.version);
5000                         }
5001                         OBJ(i8k_bios) {
5002                                 snprintf(p, p_max_size, "%s", i8k.bios);
5003                         }
5004                         OBJ(i8k_serial) {
5005                                 snprintf(p, p_max_size, "%s", i8k.serial);
5006                         }
5007                         OBJ(i8k_cpu_temp) {
5008                                 int cpu_temp;
5009
5010                                 sscanf(i8k.cpu_temp, "%d", &cpu_temp);
5011                                 temp_print(p, p_max_size, (double)cpu_temp, TEMP_CELSIUS);
5012                         }
5013                         OBJ(i8k_left_fan_status) {
5014                                 int left_fan_status;
5015
5016                                 sscanf(i8k.left_fan_status, "%d", &left_fan_status);
5017                                 if (left_fan_status == 0) {
5018                                         snprintf(p, p_max_size, "off");
5019                                 }
5020                                 if (left_fan_status == 1) {
5021                                         snprintf(p, p_max_size, "low");
5022                                 }
5023                                 if (left_fan_status == 2) {
5024                                         snprintf(p, p_max_size, "high");
5025                                 }
5026                         }
5027                         OBJ(i8k_right_fan_status) {
5028                                 int right_fan_status;
5029
5030                                 sscanf(i8k.right_fan_status, "%d", &right_fan_status);
5031                                 if (right_fan_status == 0) {
5032                                         snprintf(p, p_max_size, "off");
5033                                 }
5034                                 if (right_fan_status == 1) {
5035                                         snprintf(p, p_max_size, "low");
5036                                 }
5037                                 if (right_fan_status == 2) {
5038                                         snprintf(p, p_max_size, "high");
5039                                 }
5040                         }
5041                         OBJ(i8k_left_fan_rpm) {
5042                                 snprintf(p, p_max_size, "%s", i8k.left_fan_rpm);
5043                         }
5044                         OBJ(i8k_right_fan_rpm) {
5045                                 snprintf(p, p_max_size, "%s", i8k.right_fan_rpm);
5046                         }
5047                         OBJ(i8k_ac_status) {
5048                                 int ac_status;
5049
5050                                 sscanf(i8k.ac_status, "%d", &ac_status);
5051                                 if (ac_status == -1) {
5052                                         snprintf(p, p_max_size, "disabled (read i8k docs)");
5053                                 }
5054                                 if (ac_status == 0) {
5055                                         snprintf(p, p_max_size, "off");
5056                                 }
5057                                 if (ac_status == 1) {
5058                                         snprintf(p, p_max_size, "on");
5059                                 }
5060                         }
5061                         OBJ(i8k_buttons_status) {
5062                                 snprintf(p, p_max_size, "%s", i8k.buttons_status);
5063                         }
5064                         OBJ(ibm_fan) {
5065                                 get_ibm_acpi_fan(p, p_max_size);
5066                         }
5067                         OBJ(ibm_temps) {
5068                                 get_ibm_acpi_temps();
5069                                 temp_print(p, p_max_size,
5070                                            ibm_acpi.temps[obj->data.sensor], TEMP_CELSIUS);
5071                         }
5072                         OBJ(ibm_volume) {
5073                                 get_ibm_acpi_volume(p, p_max_size);
5074                         }
5075                         OBJ(ibm_brightness) {
5076                                 get_ibm_acpi_brightness(p, p_max_size);
5077                         }
5078                         OBJ(if_up) {
5079                                 if ((obj->data.ifblock.s)
5080                                                 && (!interface_up(obj->data.ifblock.s))) {
5081                                         i = obj->data.ifblock.pos;
5082                                         if_jumped = 1;
5083                                 } else {
5084                                         if_jumped = 0;
5085                                 }
5086                         }
5087                         OBJ(if_gw) {
5088                                 if (!cur->gw_info.count) {
5089                                         i = obj->data.ifblock.pos;
5090                                         if_jumped = 1;
5091                                 } else {
5092                                         if_jumped = 0;
5093                                 }
5094                         }
5095                         OBJ(gw_iface) {
5096                                 snprintf(p, p_max_size, "%s", cur->gw_info.iface);
5097                         }
5098                         OBJ(gw_ip) {
5099                                 snprintf(p, p_max_size, "%s", cur->gw_info.ip);
5100                         }
5101                         OBJ(laptop_mode) {
5102                                 snprintf(p, p_max_size, "%d", get_laptop_mode());
5103                         }
5104                         OBJ(pb_battery) {
5105                                 get_powerbook_batt_info(p, p_max_size, obj->data.i);
5106                         }
5107 #endif /* __linux__ */
5108
5109 #ifdef __OpenBSD__
5110                         OBJ(obsd_sensors_temp) {
5111                                 obsd_sensors.device = sensor_device;
5112                                 update_obsd_sensors();
5113                                 temp_print(p, p_max_size,
5114                                            obsd_sensors.temp[obsd_sensors.device][obj->data.sensor],
5115                                            TEMP_CELSIUS);
5116                         }
5117                         OBJ(obsd_sensors_fan) {
5118                                 obsd_sensors.device = sensor_device;
5119                                 update_obsd_sensors();
5120                                 snprintf(p, p_max_size, "%d",
5121                                                 obsd_sensors.fan[obsd_sensors.device][obj->data.sensor]);
5122                         }
5123                         OBJ(obsd_sensors_volt) {
5124                                 obsd_sensors.device = sensor_device;
5125                                 update_obsd_sensors();
5126                                 snprintf(p, p_max_size, "%.2f",
5127                                                 obsd_sensors.volt[obsd_sensors.device][obj->data.sensor]);
5128                         }
5129                         OBJ(obsd_vendor) {
5130                                 get_obsd_vendor(p, p_max_size);
5131                         }
5132                         OBJ(obsd_product) {
5133                                 get_obsd_product(p, p_max_size);
5134                         }
5135 #endif /* __OpenBSD__ */
5136
5137 #ifdef X11
5138                         OBJ(font) {
5139                                 new_font(p, obj->data.s);
5140                         }
5141 #endif
5142                         /* TODO: move this correction from kB to kB/s elsewhere
5143                          * (or get rid of it??) */
5144                         OBJ(diskio) {
5145                                 if (obj->data.diskio) {
5146                                         human_readable(
5147                                                         (obj->data.diskio->current / update_interval) * 1024LL,
5148                                                         p, p_max_size, "diskio");
5149                                 } else {
5150                                         human_readable(info.diskio_value * 1024LL, p, p_max_size,
5151                                                         "diskio");
5152                                 }
5153                         }
5154                         OBJ(diskio_write) {
5155                                 if (obj->data.diskio) {
5156                                         human_readable((obj->data.diskio->current_write / update_interval) * 1024LL, p, p_max_size,
5157                                                         "diskio_write");
5158                                 } else {
5159                                         human_readable(info.diskio_write_value * 1024LL, p, p_max_size,
5160                                                         "diskio_write");
5161                                 }
5162                         }
5163                         OBJ(diskio_read) {
5164                                 if (obj->data.diskio) {
5165                                         human_readable((obj->data.diskio->current_read / update_interval) * 1024LL, p, p_max_size,
5166                                                         "diskio_read");
5167                                 } else {
5168                                         human_readable(info.diskio_read_value * 1024LL, p, p_max_size,
5169                                                         "diskio_read");
5170                                 }
5171                         }
5172                         OBJ(diskiograph) {
5173                                 if (obj->data.diskio) {
5174                                         new_graph(p, obj->a, obj->b, obj->c, obj->d,
5175                                                         obj->data.diskio->current, obj->e, 1, obj->showaslog);
5176                                 } else {
5177                                         new_graph(p, obj->a, obj->b, obj->c, obj->d, info.diskio_value,
5178                                                         obj->e, 1, obj->showaslog);
5179                                 }
5180                         }
5181                         OBJ(diskiograph_read) {
5182                                 if (obj->data.diskio) {
5183                                         new_graph(p, obj->a, obj->b, obj->c, obj->d,
5184                                                         obj->data.diskio->current_read, obj->e, 1, obj->showaslog);
5185                                 } else {
5186                                         new_graph(p, obj->a, obj->b, obj->c, obj->d,
5187                                                         info.diskio_read_value, obj->e, 1, obj->showaslog);
5188                                 }
5189                         }
5190                         OBJ(diskiograph_write) {
5191                                 if (obj->data.diskio) {
5192                                         new_graph(p, obj->a, obj->b, obj->c, obj->d,
5193                                                         obj->data.diskio->current_write, obj->e, 1, obj->showaslog);
5194                                 } else {
5195                                         new_graph(p, obj->a, obj->b, obj->c, obj->d,
5196                                                         info.diskio_write_value, obj->e, 1, obj->showaslog);
5197                                 }
5198                         }
5199                         OBJ(downspeed) {
5200                                 spaced_print(p, p_max_size, "%d", 6, "downspeed",
5201                                                 round_to_int(obj->data.net->recv_speed / 1024));
5202                         }
5203                         OBJ(downspeedf) {
5204                                 spaced_print(p, p_max_size, "%.1f", 8, "downspeedf",
5205                                                 obj->data.net->recv_speed / 1024.0);
5206                         }
5207                         OBJ(downspeedgraph) {
5208                         new_graph(p, obj->a, obj->b, obj->c, obj->d,
5209                                 obj->data.net->recv_speed / 1024.0, obj->e, 1, obj->showaslog);
5210                         }
5211                         OBJ(else) {
5212                                 if (!if_jumped) {
5213                                         i = obj->data.ifblock.pos - 1;
5214                                 } else {
5215                                         if_jumped = 0;
5216                                 }
5217                         }
5218                         OBJ(endif) {
5219                                 if_jumped = 0;
5220                         }
5221 #ifdef HAVE_POPEN
5222                         OBJ(addr) {
5223                                 if ((obj->data.net->addr.sa_data[2] & 255) == 0
5224                                                 && (obj->data.net->addr.sa_data[3] & 255) == 0
5225                                                 && (obj->data.net->addr.sa_data[4] & 255) == 0
5226                                                 && (obj->data.net->addr.sa_data[5] & 255) == 0) {
5227                                         snprintf(p, p_max_size, "No Address");
5228                                 } else {
5229                                         snprintf(p, p_max_size, "%u.%u.%u.%u",
5230                                                 obj->data.net->addr.sa_data[2] & 255,
5231                                                 obj->data.net->addr.sa_data[3] & 255,
5232                                                 obj->data.net->addr.sa_data[4] & 255,
5233                                                 obj->data.net->addr.sa_data[5] & 255);
5234                                 }
5235                         }
5236 #if defined(__linux__)
5237                         OBJ(addrs) {
5238                                 if(NULL != obj->data.net->addrs && strlen(obj->data.net->addrs) > 2)
5239                                 {
5240                                         obj->data.net->addrs[strlen(obj->data.net->addrs) - 2] = 0; /* remove ", " from end of string */
5241                                         strcpy(p, obj->data.net->addrs);
5242                                 }
5243                                 else
5244                                         strcpy(p, "0.0.0.0");
5245            }
5246 #endif /* __linux__ */
5247
5248 #if defined(IMLIB2) && defined(X11)
5249                         OBJ(image) {
5250                                 if (obj->a < 1) {
5251                                         obj->a++;
5252                                 } else {
5253                                         Imlib_Image image, buffer;
5254
5255                                         image = imlib_load_image(obj->data.s);
5256                                         imlib_context_set_image(image);
5257                                         if (image) {
5258                                                 int w, h;
5259
5260                                                 w = imlib_image_get_width();
5261                                                 h = imlib_image_get_height();
5262                                                 buffer = imlib_create_image(w, h);
5263                                                 imlib_context_set_display(display);
5264                                                 imlib_context_set_drawable(window.drawable);
5265                                                 imlib_context_set_colormap(DefaultColormap(display,
5266                                                         screen));
5267                                                 imlib_context_set_visual(DefaultVisual(display,
5268                                                         screen));
5269                                                 imlib_context_set_image(buffer);
5270                                                 imlib_blend_image_onto_image(image, 0, 0, 0, w, h,
5271                                                         text_start_x, text_start_y, w, h);
5272                                                 imlib_render_image_on_drawable(text_start_x,
5273                                                         text_start_y);
5274                                                 imlib_free_image();
5275                                                 imlib_context_set_image(image);
5276                                                 imlib_free_image();
5277                                         }
5278                                 }
5279                         }
5280 #endif /* IMLIB2 */
5281
5282                         OBJ(exec) {
5283                                 read_exec(obj->data.s, p, text_buffer_size);
5284                                 remove_deleted_chars(p);
5285                         }
5286                         OBJ(execp) {
5287                                 struct information *tmp_info;
5288                                 struct text_object_list *text_objects;
5289
5290                                 read_exec(obj->data.s, p, text_buffer_size);
5291
5292                                 tmp_info = malloc(sizeof(struct information));
5293                                 memcpy(tmp_info, cur, sizeof(struct information));
5294                                 text_objects = parse_conky_vars(p, p, tmp_info);
5295
5296                                 free_text_objects(text_objects, 0);
5297                                 free(text_objects);
5298                                 free(tmp_info);
5299                         }
5300                         OBJ(execbar) {
5301                                 double barnum;
5302
5303                                 read_exec(obj->data.s, p, text_buffer_size);
5304                                 barnum = get_barnum(p);
5305
5306                                 if (barnum >= 0.0) {
5307                                         barnum /= 100;
5308                                         new_bar(p, 0, 4, round_to_int(barnum * 255.0));
5309                                 }
5310                         }
5311                         OBJ(execgraph) {
5312                                 char showaslog = FALSE;
5313                                 double barnum;
5314
5315                                 if(strncasecmp(obj->data.s, LOGGRAPH" ", strlen(LOGGRAPH" ")) == EQUAL) {
5316                                         showaslog = TRUE;
5317                                         read_exec(obj->data.s + strlen(LOGGRAPH" ") * sizeof(char), p, text_buffer_size);
5318                                 } else if(strncasecmp(obj->data.s, NORMGRAPH" ", strlen(NORMGRAPH" ")) == EQUAL) {
5319                                         read_exec(obj->data.s + strlen(NORMGRAPH" ") * sizeof(char), p, text_buffer_size);
5320                                 } else {
5321                                         read_exec(obj->data.s, p, text_buffer_size);
5322                                 }
5323                                 barnum = get_barnum(p);
5324
5325                                 if (barnum >= 0.0) {
5326                                         new_graph(p, 0, 25, obj->c, obj->d, round_to_int(barnum),
5327                                                 100, 1, showaslog);
5328                                 }
5329                         }
5330                         OBJ(execibar) {
5331                                 if (current_update_time - obj->data.execi.last_update
5332                                                 >= obj->data.execi.interval) {
5333                                         double barnum;
5334
5335                                         read_exec(obj->data.execi.cmd, p, text_buffer_size);
5336                                         barnum = get_barnum(p);
5337
5338                                         if (barnum >= 0.0) {
5339                                                 obj->f = 255 * barnum / 100.0;
5340                                         }
5341                                         obj->data.execi.last_update = current_update_time;
5342                                 }
5343                                 new_bar(p, 0, 4, round_to_int(obj->f));
5344                         }
5345                         OBJ(execigraph) {
5346                                 if (current_update_time - obj->data.execi.last_update
5347                                                 >= obj->data.execi.interval) {
5348                                         double barnum;
5349
5350                                         read_exec(obj->data.execi.cmd, p, text_buffer_size);
5351                                         barnum = get_barnum(p);
5352
5353                                         if (barnum >= 0.0) {
5354                                                 obj->f = barnum;
5355                                         }
5356                                         obj->data.execi.last_update = current_update_time;
5357                                 }
5358                                 new_graph(p, 0, 25, obj->c, obj->d, (int) (obj->f), 100, 1, FALSE);
5359                         }
5360                         OBJ(execi) {
5361                                 if (current_update_time - obj->data.execi.last_update
5362                                                 >= obj->data.execi.interval
5363                                                 && obj->data.execi.interval != 0) {
5364                                         read_exec(obj->data.execi.cmd, obj->data.execi.buffer,
5365                                                 text_buffer_size);
5366                                         obj->data.execi.last_update = current_update_time;
5367                                 }
5368                                 snprintf(p, text_buffer_size, "%s", obj->data.execi.buffer);
5369                         }
5370                         OBJ(execpi) {
5371                                 struct text_object_list *text_objects = 0;
5372                                 struct information *tmp_info =
5373                                         malloc(sizeof(struct information));
5374                                 memcpy(tmp_info, cur, sizeof(struct information));
5375
5376                                 if (current_update_time - obj->data.execi.last_update
5377                                                 < obj->data.execi.interval
5378                                                 || obj->data.execi.interval == 0) {
5379                                         text_objects = parse_conky_vars(obj->data.execi.buffer, p, tmp_info);
5380                                 } else {
5381                                         char *output = obj->data.execi.buffer;
5382                                         FILE *fp = popen(obj->data.execi.cmd, "r");
5383                                         int length = fread(output, 1, text_buffer_size, fp);
5384
5385                                         pclose(fp);
5386
5387                                         output[length] = '\0';
5388                                         if (length > 0 && output[length - 1] == '\n') {
5389                                                 output[length - 1] = '\0';
5390                                         }
5391
5392                                         text_objects = parse_conky_vars(obj->data.execi.buffer, p, tmp_info);
5393                                         obj->data.execi.last_update = current_update_time;
5394                                 }
5395                                 free_text_objects(text_objects, 0);
5396                                 free(text_objects);
5397                                 free(tmp_info);
5398                         }
5399                         OBJ(texeci) {
5400                                 if (!obj->data.texeci.p_timed_thread) {
5401                                         obj->data.texeci.p_timed_thread =
5402                                                 timed_thread_create(&threaded_exec,
5403                                                 (void *) obj, obj->data.texeci.interval * 1000000);
5404                                         if (!obj->data.texeci.p_timed_thread) {
5405                                                 ERR("Error creating texeci timed thread");
5406                                         }
5407                                         timed_thread_register(obj->data.texeci.p_timed_thread,
5408                                                 &obj->data.texeci.p_timed_thread);
5409                                         if (timed_thread_run(obj->data.texeci.p_timed_thread)) {
5410                                                 ERR("Error running texeci timed thread");
5411                                         }
5412                                 }
5413                                 timed_thread_lock(obj->data.texeci.p_timed_thread);
5414                                 snprintf(p, text_buffer_size, "%s", obj->data.texeci.buffer);
5415                                 timed_thread_unlock(obj->data.texeci.p_timed_thread);
5416                         }
5417 #endif /* HAVE_POPEN */
5418                         OBJ(imap_unseen) {
5419                                 struct mail_s *mail = ensure_mail_thread(obj, imap_thread, "imap");
5420
5421                                 if (mail && mail->p_timed_thread) {
5422                                         timed_thread_lock(mail->p_timed_thread);
5423                                         snprintf(p, p_max_size, "%lu", mail->unseen);
5424                                         timed_thread_unlock(mail->p_timed_thread);
5425                                 }
5426                         }
5427                         OBJ(imap_messages) {
5428                                 struct mail_s *mail = ensure_mail_thread(obj, imap_thread, "imap");
5429
5430                                 if (mail && mail->p_timed_thread) {
5431                                         timed_thread_lock(mail->p_timed_thread);
5432                                         snprintf(p, p_max_size, "%lu", mail->messages);
5433                                         timed_thread_unlock(mail->p_timed_thread);
5434                                 }
5435                         }
5436                         OBJ(pop3_unseen) {
5437                                 struct mail_s *mail = ensure_mail_thread(obj, pop3_thread, "pop3");
5438
5439                                 if (mail && mail->p_timed_thread) {
5440                                         timed_thread_lock(mail->p_timed_thread);
5441                                         snprintf(p, p_max_size, "%lu", mail->unseen);
5442                                         timed_thread_unlock(mail->p_timed_thread);
5443                                 }
5444                         }
5445                         OBJ(pop3_used) {
5446                                 struct mail_s *mail = ensure_mail_thread(obj, pop3_thread, "pop3");
5447
5448                                 if (mail && mail->p_timed_thread) {
5449                                         timed_thread_lock(mail->p_timed_thread);
5450                                         snprintf(p, p_max_size, "%.1f",
5451                                                 mail->used / 1024.0 / 1024.0);
5452                                         timed_thread_unlock(mail->p_timed_thread);
5453                                 }
5454                         }
5455                         OBJ(fs_bar) {
5456                                 if (obj->data.fs != NULL) {
5457                                         if (obj->data.fs->size == 0) {
5458                                                 new_bar(p, obj->data.fsbar.w, obj->data.fsbar.h, 255);
5459                                         } else {
5460                                                 new_bar(p, obj->data.fsbar.w, obj->data.fsbar.h,
5461                                                         (int) (255 - obj->data.fsbar.fs->avail * 255 /
5462                                                         obj->data.fs->size));
5463                                         }
5464                                 }
5465                         }
5466                         OBJ(fs_free) {
5467                                 if (obj->data.fs != NULL) {
5468                                         human_readable(obj->data.fs->avail, p, 255, "fs_free");
5469                                 }
5470                         }
5471                         OBJ(fs_free_perc) {
5472                                 if (obj->data.fs != NULL) {
5473                                         if (obj->data.fs->size) {
5474                                                 spaced_print(p, p_max_size, "%*d", 4, "fs_free_perc",
5475                                                                 pad_percents, (int) ((obj->data.fs->avail * 100) /
5476                                                                         obj->data.fs->size));
5477                                         } else {
5478                                                 snprintf(p, p_max_size, "0");
5479                                         }
5480                                 }
5481                         }
5482                         OBJ(fs_size) {
5483                                 if (obj->data.fs != NULL) {
5484                                         human_readable(obj->data.fs->size, p, 255, "fs_size");
5485                                 }
5486                         }
5487                         OBJ(fs_type) {
5488                                 if (obj->data.fs != NULL)
5489                                         snprintf(p, p_max_size, "%s", obj->data.fs->type);
5490                         }
5491                         OBJ(fs_used) {
5492                                 if (obj->data.fs != NULL) {
5493                                         human_readable(obj->data.fs->size - (obj->data.fs->free
5494                                                 ? obj->data.fs->free : obj->data.fs->avail), p, 255,
5495                                                 "fs_used");
5496                                 }
5497                         }
5498                         OBJ(fs_bar_free) {
5499                                 if (obj->data.fs != NULL) {
5500                                         if (obj->data.fs->size == 0) {
5501                                                 new_bar(p, obj->data.fsbar.w, obj->data.fsbar.h, 255);
5502                                         } else {
5503                                                 new_bar(p, obj->data.fsbar.w, obj->data.fsbar.h,
5504                                                         (int) (obj->data.fsbar.fs->avail * 255 /
5505                                                         obj->data.fs->size));
5506                                         }
5507                                 }
5508                         }
5509                         OBJ(fs_used_perc) {
5510                                 if (obj->data.fs != NULL) {
5511                                         if (obj->data.fs->size) {
5512                                                 spaced_print(p, 4, "%*d", 4, "fs_used_perc",
5513                                                                 pad_percents, 100 - ((int) ((obj->data.fs->avail * 100) /
5514                                                                                 obj->data.fs->size)));
5515                                         } else {
5516                                                 snprintf(p, p_max_size, "0");
5517                                         }
5518                                 }
5519                         }
5520                         OBJ(loadavg) {
5521                                 float *v = info.loadavg;
5522
5523                                 if (obj->data.loadavg[2]) {
5524                                         snprintf(p, p_max_size, "%.2f %.2f %.2f",
5525                                                 v[obj->data.loadavg[0] - 1],
5526                                                 v[obj->data.loadavg[1] - 1],
5527                                                 v[obj->data.loadavg[2] - 1]);
5528                                 } else if (obj->data.loadavg[1]) {
5529                                         snprintf(p, p_max_size, "%.2f %.2f",
5530                                                 v[obj->data.loadavg[0] - 1],
5531                                                 v[obj->data.loadavg[1] - 1]);
5532                                 } else if (obj->data.loadavg[0]) {
5533                                         snprintf(p, p_max_size, "%.2f",
5534                                                 v[obj->data.loadavg[0] - 1]);
5535                                 }
5536                         }
5537                         OBJ(goto) {
5538                                 new_goto(p, obj->data.i);
5539                         }
5540                         OBJ(tab) {
5541                                 new_tab(p, obj->data.pair.a, obj->data.pair.b);
5542                         }
5543                         OBJ(hr) {
5544                                 new_hr(p, obj->data.i);
5545                         }
5546                         OBJ(nameserver) {
5547                                 if (cur->nameserver_info.nscount > obj->data.i)
5548                                         snprintf(p, p_max_size, "%s",
5549                                                         cur->nameserver_info.ns_list[obj->data.i]);
5550                         }
5551 #ifdef EVE
5552                         OBJ(eve) {
5553                                 char *skill = eve(obj->data.eve.userid, obj->data.eve.apikey, obj->data.eve.charid);
5554                                 snprintf(p, p_max_size, "%s", skill);
5555                         }
5556 #endif
5557 #ifdef RSS
5558                         OBJ(rss) {
5559                                 PRSS *data = get_rss_info(obj->data.rss.uri,
5560                                         obj->data.rss.delay);
5561                                 char *str;
5562
5563                                 if (data == NULL) {
5564                                         snprintf(p, p_max_size, "prss: Error reading RSS data\n");
5565                                 } else {
5566                                         if (strcmp(obj->data.rss.action, "feed_title") == EQUAL) {
5567                                                 str = data->title;
5568                                                 // remove trailing new line if one exists
5569                                                 if (str[strlen(str) - 1] == '\n') {
5570                                                         str[strlen(str) - 1] = 0;
5571                                                 }
5572                                                 snprintf(p, p_max_size, "%s", str);
5573                                         } else if (strcmp(obj->data.rss.action, "item_title") == EQUAL) {
5574                                                 if (obj->data.rss.act_par < data->item_count) {
5575                                                         str = data->items[obj->data.rss.act_par].title;
5576                                                         // remove trailing new line if one exists
5577                                                         if (str[strlen(str) - 1] == '\n') {
5578                                                                 str[strlen(str) - 1] = 0;
5579                                                         }
5580                                                         snprintf(p, p_max_size, "%s", str);
5581                                                 }
5582                                         } else if (strcmp(obj->data.rss.action, "item_desc") == EQUAL) {
5583                                                 if (obj->data.rss.act_par < data->item_count) {
5584                                                         str =
5585                                                                 data->items[obj->data.rss.act_par].description;
5586                                                         // remove trailing new line if one exists
5587                                                         if (str[strlen(str) - 1] == '\n') {
5588                                                                 str[strlen(str) - 1] = 0;
5589                                                         }
5590                                                         snprintf(p, p_max_size, "%s", str);
5591                                                 }
5592                                         } else if (strcmp(obj->data.rss.action, "item_titles") == EQUAL) {
5593                                                 if (data->item_count > 0) {
5594                                                         int itmp;
5595                                                         int show;
5596
5597                                                         p[0] = 0;
5598
5599                                                         if (obj->data.rss.act_par > data->item_count) {
5600                                                                 show = data->item_count;
5601                                                         } else {
5602                                                                 show = obj->data.rss.act_par;
5603                                                         }
5604                                                         for (itmp = 0; itmp < show; itmp++) {
5605                                                                 PRSS_Item *item = &data->items[itmp];
5606
5607                                                                 str = item->title;
5608                                                                 if (str) {
5609                                                                         // don't add new line before first item
5610                                                                         if (itmp > 0) {
5611                                                                                 strncat(p, "\n", p_max_size);
5612                                                                         }
5613                                                                         /* remove trailing new line if one exists,
5614                                                                          * we have our own */
5615                                                                         if (str[strlen(str) - 1] == '\n') {
5616                                                                                 str[strlen(str) - 1] = 0;
5617                                                                         }
5618                                                                         strncat(p, str, p_max_size);
5619                                                                 }
5620                                                         }
5621                                                 }
5622                                         }
5623                                 }
5624                         }
5625 #endif
5626 #ifdef HDDTEMP
5627                         OBJ(hddtemp) {
5628                                 char *endptr, unit;
5629                                 long val;
5630                                 if (obj->data.hddtemp.update_time < current_update_time - 30) {
5631                                         if (obj->data.hddtemp.temp)
5632                                                 free(obj->data.hddtemp.temp);
5633                                         obj->data.hddtemp.temp = get_hddtemp_info(obj->data.hddtemp.dev,
5634                                                         obj->data.hddtemp.addr, obj->data.hddtemp.port);
5635                                         obj->data.hddtemp.update_time = current_update_time;
5636                                 }
5637                                 if (!obj->data.hddtemp.temp) {
5638                                         snprintf(p, p_max_size, "N/A");
5639                                 } else {
5640                                         val = strtol(obj->data.hddtemp.temp + 1, &endptr, 10);
5641                                         unit = obj->data.hddtemp.temp[0];
5642
5643                                         if (*endptr != '\0')
5644                                                 snprintf(p, p_max_size, "N/A");
5645                                         else if (unit == 'C')
5646                                                 temp_print(p, p_max_size, (double)val, TEMP_CELSIUS);
5647                                         else if (unit == 'F')
5648                                                 temp_print(p, p_max_size, (double)val, TEMP_FAHRENHEIT);
5649                                         else
5650                                                 snprintf(p, p_max_size, "N/A");
5651                                 }
5652                         }
5653 #endif
5654                         OBJ(offset) {
5655                                 new_offset(p, obj->data.i);
5656                         }
5657                         OBJ(voffset) {
5658                                 new_voffset(p, obj->data.i);
5659                         }
5660 #ifndef __OpenBSD__
5661                         OBJ(i2c) {
5662                                 double r;
5663
5664                                 r = get_sysfs_info(&obj->data.sysfs.fd, obj->data.sysfs.arg,
5665                                         obj->data.sysfs.devtype, obj->data.sysfs.type);
5666
5667                                 if (!strncmp(obj->data.sysfs.type, "temp", 4)) {
5668                                         temp_print(p, p_max_size, r, TEMP_CELSIUS);
5669                                 } else if (r >= 100.0 || r == 0) {
5670                                         snprintf(p, p_max_size, "%d", (int) r);
5671                                 } else {
5672                                         snprintf(p, p_max_size, "%.1f", r);
5673                                 }
5674                         }
5675                         OBJ(platform) {
5676                                 double r;
5677
5678                                 r = get_sysfs_info(&obj->data.sysfs.fd, obj->data.sysfs.arg,
5679                                         obj->data.sysfs.devtype, obj->data.sysfs.type);
5680
5681                                 if (!strncmp(obj->data.sysfs.type, "temp", 4)) {
5682                                         temp_print(p, p_max_size, r, TEMP_CELSIUS);
5683                                 } else if (r >= 100.0 || r == 0) {
5684                                         snprintf(p, p_max_size, "%d", (int) r);
5685                                 } else {
5686                                         snprintf(p, p_max_size, "%.1f", r);
5687                                 }
5688                         }
5689                         OBJ(hwmon) {
5690                                 double r;
5691
5692                                 r = get_sysfs_info(&obj->data.sysfs.fd, obj->data.sysfs.arg,
5693                                         obj->data.sysfs.devtype, obj->data.sysfs.type);
5694
5695                                 if (!strncmp(obj->data.sysfs.type, "temp", 4)) {
5696                                         temp_print(p, p_max_size, r, TEMP_CELSIUS);
5697                                 } else if (r >= 100.0 || r == 0) {
5698                                         snprintf(p, p_max_size, "%d", (int) r);
5699                                 } else {
5700                                         snprintf(p, p_max_size, "%.1f", r);
5701                                 }
5702                         }
5703 #endif /* !__OpenBSD__ */
5704                         OBJ(alignr) {
5705                                 new_alignr(p, obj->data.i);
5706                         }
5707                         OBJ(alignc) {
5708                                 new_alignc(p, obj->data.i);
5709                         }
5710                         OBJ(if_empty) {
5711                                 struct text_object_list *text_objects;
5712                                 struct information *tmp_info =
5713                                         malloc(sizeof(struct information));
5714                                 memcpy(tmp_info, cur, sizeof(struct information));
5715                                 text_objects = parse_conky_vars(obj->data.ifblock.s, p, tmp_info);
5716
5717                                 if (strlen(p) != 0) {
5718                                         i = obj->data.ifblock.pos;
5719                                         if_jumped = 1;
5720                                 } else {
5721                                         if_jumped = 0;
5722                                 }
5723                                 p[0] = '\0';
5724                                 free_text_objects(text_objects, 0);
5725                                 free(text_objects);
5726                                 free(tmp_info);
5727                         }
5728                         OBJ(if_existing) {
5729                                 struct stat tmp;
5730
5731                                 if ((obj->data.ifblock.s)
5732                                                 && (stat(obj->data.ifblock.s, &tmp) == -1)) {
5733                                         i = obj->data.ifblock.pos;
5734                                         if_jumped = 1;
5735                                 } else {
5736                                         if (obj->data.ifblock.str) {
5737                                                 if (!check_contains(obj->data.ifblock.s,
5738                                                                 obj->data.ifblock.str)) {
5739                                                         i = obj->data.ifblock.pos;
5740                                                         if_jumped = 1;
5741                                                 } else {
5742                                                         if_jumped = 0;
5743                                                 }
5744                                         } else {
5745                                                 if_jumped = 0;
5746                                         }
5747                                 }
5748                         }
5749                         OBJ(if_mounted) {
5750                                 if ((obj->data.ifblock.s)
5751                                                 && (!check_mount(obj->data.ifblock.s))) {
5752                                         i = obj->data.ifblock.pos;
5753                                         if_jumped = 1;
5754                                 } else {
5755                                         if_jumped = 0;
5756                                 }
5757                         }
5758                         OBJ(if_running) {
5759                                 if ((obj->data.ifblock.s) && system(obj->data.ifblock.s)) {
5760                                         i = obj->data.ifblock.pos;
5761                                         if_jumped = 1;
5762                                 } else {
5763                                         if_jumped = 0;
5764                                 }
5765                         }
5766 #if defined(__linux__)
5767                         OBJ(ioscheduler) {
5768                                 snprintf(p, p_max_size, "%s", get_ioscheduler(obj->data.s));
5769                         }
5770 #endif
5771                         OBJ(kernel) {
5772                                 snprintf(p, p_max_size, "%s", cur->uname_s.release);
5773                         }
5774                         OBJ(machine) {
5775                                 snprintf(p, p_max_size, "%s", cur->uname_s.machine);
5776                         }
5777
5778                         /* memory stuff */
5779                         OBJ(mem) {
5780                                 human_readable(cur->mem * 1024, p, 255, "mem");
5781                         }
5782                         OBJ(memeasyfree) {
5783                                 human_readable(cur->memeasyfree * 1024, p, 255, "memeasyfree");
5784                         }
5785                         OBJ(memfree) {
5786                                 human_readable(cur->memfree * 1024, p, 255, "memfree");
5787                         }
5788                         OBJ(memmax) {
5789                                 human_readable(cur->memmax * 1024, p, 255, "memmax");
5790                         }
5791                         OBJ(memperc) {
5792                                 if (cur->memmax) {
5793                                         spaced_print(p, p_max_size, "%*llu", 4, "memperc",
5794                                                 pad_percents, cur->mem * 100 / cur->memmax);
5795                                 }
5796                         }
5797                         OBJ(membar) {
5798                                 new_bar(p, obj->data.pair.a, obj->data.pair.b,
5799                                         cur->memmax ? (cur->mem * 255) / (cur->memmax) : 0);
5800                         }
5801                         OBJ(memgraph) {
5802                                 new_graph(p, obj->a, obj->b, obj->c, obj->d,
5803                                         cur->memmax ? (cur->mem * 100.0) / (cur->memmax) : 0.0,
5804                                         100, 1, obj->showaslog);
5805                         }
5806
5807                         /* mixer stuff */
5808                         OBJ(mixer) {
5809                                 snprintf(p, p_max_size, "%d", mixer_get_avg(obj->data.l));
5810                         }
5811                         OBJ(mixerl) {
5812                                 snprintf(p, p_max_size, "%d", mixer_get_left(obj->data.l));
5813                         }
5814                         OBJ(mixerr) {
5815                                 snprintf(p, p_max_size, "%d", mixer_get_right(obj->data.l));
5816                         }
5817                         OBJ(mixerbar) {
5818                                 new_bar(p, obj->data.mixerbar.w, obj->data.mixerbar.h,
5819                                         mixer_get_avg(obj->data.mixerbar.l) * 255 / 100);
5820                         }
5821                         OBJ(mixerlbar) {
5822                                 new_bar(p, obj->data.mixerbar.w, obj->data.mixerbar.h,
5823                                         mixer_get_left(obj->data.mixerbar.l) * 255 / 100);
5824                         }
5825                         OBJ(mixerrbar) {
5826                                 new_bar(p, obj->data.mixerbar.w, obj->data.mixerbar.h,
5827                                         mixer_get_right(obj->data.mixerbar.l) * 255 / 100);
5828                         }
5829 #ifdef X11
5830                         OBJ(monitor) {
5831                                 snprintf(p, p_max_size, "%d", cur->x11.monitor.current);
5832                         }
5833                         OBJ(monitor_number) {
5834                                 snprintf(p, p_max_size, "%d", cur->x11.monitor.number);
5835                         }
5836 #endif
5837
5838                         /* mail stuff */
5839                         OBJ(mails) {
5840                                 update_mail_count(&obj->data.local_mail);
5841                                 snprintf(p, p_max_size, "%d", obj->data.local_mail.mail_count);
5842                         }
5843                         OBJ(mboxscan) {
5844                                 mbox_scan(obj->data.mboxscan.args, obj->data.mboxscan.output,
5845                                         text_buffer_size);
5846                                 snprintf(p, p_max_size, "%s", obj->data.mboxscan.output);
5847                         }
5848                         OBJ(new_mails) {
5849                                 update_mail_count(&obj->data.local_mail);
5850                                 snprintf(p, p_max_size, "%d",
5851                                         obj->data.local_mail.new_mail_count);
5852                         }
5853                         OBJ(nodename) {
5854                                 snprintf(p, p_max_size, "%s", cur->uname_s.nodename);
5855                         }
5856                         OBJ(outlinecolor) {
5857                                 new_outline(p, obj->data.l);
5858                         }
5859                         OBJ(processes) {
5860                                 spaced_print(p, p_max_size, "%hu", 5, "processes", cur->procs);
5861                         }
5862                         OBJ(running_processes) {
5863                                 spaced_print(p, p_max_size, "%hu", 3, "running_processes", cur->run_procs);
5864                         }
5865                         OBJ(text) {
5866                                 snprintf(p, p_max_size, "%s", obj->data.s);
5867                         }
5868                         OBJ(shadecolor) {
5869                                 new_bg(p, obj->data.l);
5870                         }
5871                         OBJ(stippled_hr) {
5872                                 new_stippled_hr(p, obj->data.pair.a, obj->data.pair.b);
5873                         }
5874                         OBJ(swap) {
5875                                 human_readable(cur->swap * 1024, p, 255, "swap");
5876                         }
5877                         OBJ(swapmax) {
5878                                 human_readable(cur->swapmax * 1024, p, 255, "swapmax");
5879                         }
5880                         OBJ(swapperc) {
5881                                 if (cur->swapmax == 0) {
5882                                         strncpy(p, "No swap", p_max_size);
5883                                 } else {
5884                                         spaced_print(p, p_max_size, "%*llu", 4, "swapperc",
5885                                                 pad_percents, cur->swap * 100 / cur->swapmax);
5886                                 }
5887                         }
5888                         OBJ(swapbar) {
5889                                 new_bar(p, obj->data.pair.a, obj->data.pair.b,
5890                                         cur->swapmax ? (cur->swap * 255) / (cur->swapmax) : 0);
5891                         }
5892                         OBJ(sysname) {
5893                                 snprintf(p, p_max_size, "%s", cur->uname_s.sysname);
5894                         }
5895                         OBJ(time) {
5896                                 time_t t = time(NULL);
5897                                 struct tm *tm = localtime(&t);
5898
5899                                 setlocale(LC_TIME, "");
5900                                 strftime(p, p_max_size, obj->data.s, tm);
5901                         }
5902                         OBJ(utime) {
5903                                 time_t t = time(NULL);
5904                                 struct tm *tm = gmtime(&t);
5905
5906                                 strftime(p, p_max_size, obj->data.s, tm);
5907                         }
5908                         OBJ(tztime) {
5909                                 char *oldTZ = NULL;
5910                                 time_t t;
5911                                 struct tm *tm;
5912
5913                                 if (obj->data.tztime.tz) {
5914                                         oldTZ = getenv("TZ");
5915                                         setenv("TZ", obj->data.tztime.tz, 1);
5916                                         tzset();
5917                                 }
5918                                 t = time(NULL);
5919                                 tm = localtime(&t);
5920
5921                                 setlocale(LC_TIME, "");
5922                                 strftime(p, p_max_size, obj->data.tztime.fmt, tm);
5923                                 if (oldTZ) {
5924                                         setenv("TZ", oldTZ, 1);
5925                                         tzset();
5926                                 } else {
5927                                         unsetenv("TZ");
5928                                 }
5929                                 // Needless to free oldTZ since getenv gives ptr to static data
5930                         }
5931                         OBJ(totaldown) {
5932                                 human_readable(obj->data.net->recv, p, 255, "totaldown");
5933                         }
5934                         OBJ(totalup) {
5935                                 human_readable(obj->data.net->trans, p, 255, "totalup");
5936                         }
5937                         OBJ(updates) {
5938                                 snprintf(p, p_max_size, "%d", total_updates);
5939                         }
5940                         OBJ(upspeed) {
5941                                 spaced_print(p, p_max_size, "%d", 6, "upspeed",
5942                                         round_to_int(obj->data.net->trans_speed / 1024));
5943                         }
5944                         OBJ(upspeedf) {
5945                                 spaced_print(p, p_max_size, "%.1f", 8, "upspeedf",
5946                                         obj->data.net->trans_speed / 1024.0);
5947                         }
5948                         OBJ(upspeedgraph) {
5949                                 new_graph(p, obj->a, obj->b, obj->c, obj->d,
5950                                         obj->data.net->trans_speed / 1024.0, obj->e, 1, obj->showaslog);
5951                         }
5952                         OBJ(uptime_short) {
5953                                 format_seconds_short(p, p_max_size, (int) cur->uptime);
5954                         }
5955                         OBJ(uptime) {
5956                                 format_seconds(p, p_max_size, (int) cur->uptime);
5957                         }
5958                         OBJ(user_names) {
5959                                 snprintf(p, p_max_size, "%s", cur->users.names);
5960                         }
5961                         OBJ(user_terms) {
5962                                 snprintf(p, p_max_size, "%s", cur->users.terms);
5963                         }
5964                         OBJ(user_times) {
5965                                 snprintf(p, p_max_size, "%s", cur->users.times);
5966                         }
5967                         OBJ(user_number) {
5968                                 snprintf(p, p_max_size, "%d", cur->users.number);
5969                         }
5970 #if (defined(__FreeBSD__) || defined(__FreeBSD_kernel__) \
5971                 || defined(__OpenBSD__)) && (defined(i386) || defined(__i386__))
5972                         OBJ(apm_adapter) {
5973                                 char *msg;
5974
5975                                 msg = get_apm_adapter();
5976                                 snprintf(p, p_max_size, "%s", msg);
5977                                 free(msg);
5978                         }
5979                         OBJ(apm_battery_life) {
5980                                 char *msg;
5981
5982                                 msg = get_apm_battery_life();
5983                                 snprintf(p, p_max_size, "%s", msg);
5984                                 free(msg);
5985                         }
5986                         OBJ(apm_battery_time) {
5987                                 char *msg;
5988
5989                                 msg = get_apm_battery_time();
5990                                 snprintf(p, p_max_size, "%s", msg);
5991                                 free(msg);
5992                         }
5993 #endif /* __FreeBSD__ __OpenBSD__ */
5994
5995 #ifdef MPD
5996                         OBJ(mpd_title) {
5997                                 int len = obj->data.i;
5998                                 if (len == 0 || len > p_max_size)
5999                                         len = p_max_size;
6000                                 snprintf(p, len, "%s", cur->mpd.title);
6001                         }
6002                         OBJ(mpd_artist) {
6003                                 snprintf(p, p_max_size, "%s", cur->mpd.artist);
6004                         }
6005                         OBJ(mpd_album) {
6006                                 snprintf(p, p_max_size, "%s", cur->mpd.album);
6007                         }
6008                         OBJ(mpd_random) {
6009                                 snprintf(p, p_max_size, "%s", cur->mpd.random);
6010                         }
6011                         OBJ(mpd_repeat) {
6012                                 snprintf(p, p_max_size, "%s", cur->mpd.repeat);
6013                         }
6014                         OBJ(mpd_track) {
6015                                 snprintf(p, p_max_size, "%s", cur->mpd.track);
6016                         }
6017                         OBJ(mpd_name) {
6018                                 snprintf(p, p_max_size, "%s", cur->mpd.name);
6019                         }
6020                         OBJ(mpd_file) {
6021                                 snprintf(p, p_max_size, "%s", cur->mpd.file);
6022                         }
6023                         OBJ(mpd_vol) {
6024                                 snprintf(p, p_max_size, "%i", cur->mpd.volume);
6025                         }
6026                         OBJ(mpd_bitrate) {
6027                                 snprintf(p, p_max_size, "%i", cur->mpd.bitrate);
6028                         }
6029                         OBJ(mpd_status) {
6030                                 snprintf(p, p_max_size, "%s", cur->mpd.status);
6031                         }
6032                         OBJ(mpd_elapsed) {
6033                                 format_media_player_time(p, p_max_size, cur->mpd.elapsed);
6034                         }
6035                         OBJ(mpd_length) {
6036                                 format_media_player_time(p, p_max_size, cur->mpd.length);
6037                         }
6038                         OBJ(mpd_percent) {
6039                                 spaced_print(p, p_max_size, "%*d", 4, "mpd_percent",
6040                                                 pad_percents, (int) (cur->mpd.progress * 100));
6041                         }
6042                         OBJ(mpd_bar) {
6043                                 new_bar(p, obj->data.pair.a, obj->data.pair.b,
6044                                         (int) (cur->mpd.progress * 255.0f));
6045                         }
6046                         OBJ(mpd_smart) {
6047                                 int len = obj->data.i;
6048                                 if (len == 0 || len > p_max_size)
6049                                         len = p_max_size;
6050
6051                                 memset(p, 0, p_max_size);
6052                                 if (cur->mpd.artist && *cur->mpd.artist && cur->mpd.title
6053                                                 && *cur->mpd.title) {
6054                                         snprintf(p, len, "%s - %s", cur->mpd.artist,
6055                                                 cur->mpd.title);
6056                                 } else if (cur->mpd.title && *cur->mpd.title) {
6057                                         snprintf(p, len, "%s", cur->mpd.title);
6058                                 } else if (cur->mpd.artist && *cur->mpd.artist) {
6059                                         snprintf(p, len, "%s", cur->mpd.artist);
6060                                 } else if (cur->mpd.file && *cur->mpd.file) {
6061                                         snprintf(p, len, "%s", cur->mpd.file);
6062                                 } else {
6063                                         *p = 0;
6064                                 }
6065                         }
6066                         OBJ(if_mpd_playing) {
6067                                 if (cur->mpd.is_playing) {
6068                                         if_jumped = 0;
6069                                 } else {
6070                                         i = obj->data.ifblock.pos;
6071                                         if_jumped = 1;
6072                                 }
6073                         }
6074 #endif
6075
6076 #ifdef MOC
6077                         OBJ(moc_state) {
6078                                 snprintf(p, p_max_size, "%s", (cur->moc.state ? cur->moc.state : "??"));
6079                         }
6080                         OBJ(moc_file) {
6081                                 snprintf(p, p_max_size, "%s", (cur->moc.file ? cur->moc.file : "no file"));
6082                         }
6083                         OBJ(moc_title) {
6084                                 snprintf(p, p_max_size, "%s", (cur->moc.title ? cur->moc.title : "no title"));
6085                         }
6086                         OBJ(moc_artist) {
6087                                 snprintf(p, p_max_size, "%s", (cur->moc.artist ? cur->moc.artist : "no artist"));
6088                         }
6089                         OBJ(moc_song) {
6090                                 snprintf(p, p_max_size, "%s", (cur->moc.song ? cur->moc.song : "no song"));
6091                         }
6092                         OBJ(moc_album) {
6093                                 snprintf(p, p_max_size, "%s", (cur->moc.album ? cur->moc.album : "no album"));
6094                         }
6095                         OBJ(moc_totaltime) {
6096                                 snprintf(p, p_max_size, "%s", (cur->moc.totaltime ? cur->moc.totaltime : "0:00"));
6097                         }
6098                         OBJ(moc_timeleft) {
6099                                 snprintf(p, p_max_size, "%s", (cur->moc.timeleft ? cur->moc.timeleft : "0:00"));
6100                         }
6101                         OBJ(moc_curtime) {
6102                                 snprintf(p, p_max_size, "%s", (cur->moc.curtime ? cur->moc.curtime : "0:00"));
6103                         }
6104                         OBJ(moc_bitrate) {
6105                                 snprintf(p, p_max_size, "%s", (cur->moc.bitrate ? cur->moc.bitrate : "0Kbps"));
6106                         }
6107                         OBJ(moc_rate) {
6108         snprintf(p, p_max_size, "%s", (cur->moc.rate ? cur->moc.rate : "0KHz"));
6109                         }
6110 #endif /* MOC */
6111 #ifdef XMMS2
6112                         OBJ(xmms2_artist) {
6113                                 snprintf(p, p_max_size, "%s", cur->xmms2.artist);
6114                         }
6115                         OBJ(xmms2_album) {
6116                                 snprintf(p, p_max_size, "%s", cur->xmms2.album);
6117                         }
6118                         OBJ(xmms2_title) {
6119                                 snprintf(p, p_max_size, "%s", cur->xmms2.title);
6120                         }
6121                         OBJ(xmms2_genre) {
6122                                 snprintf(p, p_max_size, "%s", cur->xmms2.genre);
6123                         }
6124                         OBJ(xmms2_comment) {
6125                                 snprintf(p, p_max_size, "%s", cur->xmms2.comment);
6126                         }
6127                         OBJ(xmms2_url) {
6128                                 snprintf(p, p_max_size, "%s", cur->xmms2.url);
6129                         }
6130                         OBJ(xmms2_status) {
6131                                 snprintf(p, p_max_size, "%s", cur->xmms2.status);
6132                         }
6133                         OBJ(xmms2_date) {
6134                                 snprintf(p, p_max_size, "%s", cur->xmms2.date);
6135                         }
6136                         OBJ(xmms2_tracknr) {
6137                                 if (cur->xmms2.tracknr != -1) {
6138                                         snprintf(p, p_max_size, "%i", cur->xmms2.tracknr);
6139                                 }
6140                         }
6141                         OBJ(xmms2_bitrate) {
6142                                 snprintf(p, p_max_size, "%i", cur->xmms2.bitrate);
6143                         }
6144                         OBJ(xmms2_id) {
6145                                 snprintf(p, p_max_size, "%u", cur->xmms2.id);
6146                         }
6147                         OBJ(xmms2_size) {
6148                                 snprintf(p, p_max_size, "%2.1f", cur->xmms2.size);
6149                         }
6150                         OBJ(xmms2_elapsed) {
6151                                 snprintf(p, p_max_size, "%02d:%02d", cur->xmms2.elapsed / 60000,
6152                                         (cur->xmms2.elapsed / 1000) % 60);
6153                         }
6154                         OBJ(xmms2_duration) {
6155                                 snprintf(p, p_max_size, "%02d:%02d",
6156                                         cur->xmms2.duration / 60000,
6157                                         (cur->xmms2.duration / 1000) % 60);
6158                         }
6159                         OBJ(xmms2_percent) {
6160                                 snprintf(p, p_max_size, "%2.0f", cur->xmms2.progress * 100);
6161                         }
6162                         OBJ(xmms2_bar) {
6163                                 new_bar(p, obj->data.pair.a, obj->data.pair.b,
6164                                         (int) (cur->xmms2.progress * 255.0f));
6165                         }
6166                         OBJ(xmms2_playlist) {
6167                                 snprintf(p, p_max_size, "%s", cur->xmms2.playlist);
6168                         }
6169                         OBJ(xmms2_timesplayed) {
6170                                 snprintf(p, p_max_size, "%i", cur->xmms2.timesplayed);
6171                         }
6172                         OBJ(xmms2_smart) {
6173                                 if (strlen(cur->xmms2.title) < 2
6174                                                 && strlen(cur->xmms2.title) < 2) {
6175                                         snprintf(p, p_max_size, "%s", cur->xmms2.url);
6176                                 } else {
6177                                         snprintf(p, p_max_size, "%s - %s", cur->xmms2.artist,
6178                                                 cur->xmms2.title);
6179                                 }
6180                         }
6181                         OBJ(if_xmms2_connected) {
6182                                 if (cur->xmms2_conn_state == 1) {
6183                                         if_jumped = 0;
6184                                 } else {
6185                                         i = obj->data.ifblock.pos;
6186                                         if_jumped = 1;
6187                                 }
6188                         }
6189 #endif
6190 #ifdef AUDACIOUS
6191                         OBJ(audacious_status) {
6192                                 snprintf(p, p_max_size, "%s",
6193                                         cur->audacious.items[AUDACIOUS_STATUS]);
6194                         }
6195                         OBJ(audacious_title) {
6196                                 snprintf(p, cur->audacious.max_title_len > 0
6197                                         ? cur->audacious.max_title_len : p_max_size, "%s",
6198                                         cur->audacious.items[AUDACIOUS_TITLE]);
6199                         }
6200                         OBJ(audacious_length) {
6201                                 snprintf(p, p_max_size, "%s",
6202                                         cur->audacious.items[AUDACIOUS_LENGTH]);
6203                         }
6204                         OBJ(audacious_length_seconds) {
6205                                 snprintf(p, p_max_size, "%s",
6206                                         cur->audacious.items[AUDACIOUS_LENGTH_SECONDS]);
6207                         }
6208                         OBJ(audacious_position) {
6209                                 snprintf(p, p_max_size, "%s",
6210                                         cur->audacious.items[AUDACIOUS_POSITION]);
6211                         }
6212                         OBJ(audacious_position_seconds) {
6213                                 snprintf(p, p_max_size, "%s",
6214                                         cur->audacious.items[AUDACIOUS_POSITION_SECONDS]);
6215                         }
6216                         OBJ(audacious_bitrate) {
6217                                 snprintf(p, p_max_size, "%s",
6218                                         cur->audacious.items[AUDACIOUS_BITRATE]);
6219                         }
6220                         OBJ(audacious_frequency) {
6221                                 snprintf(p, p_max_size, "%s",
6222                                         cur->audacious.items[AUDACIOUS_FREQUENCY]);
6223                         }
6224                         OBJ(audacious_channels) {
6225                                 snprintf(p, p_max_size, "%s",
6226                                         cur->audacious.items[AUDACIOUS_CHANNELS]);
6227                         }
6228                         OBJ(audacious_filename) {
6229                                 snprintf(p, p_max_size, "%s",
6230                                         cur->audacious.items[AUDACIOUS_FILENAME]);
6231                         }
6232                         OBJ(audacious_playlist_length) {
6233                                 snprintf(p, p_max_size, "%s",
6234                                         cur->audacious.items[AUDACIOUS_PLAYLIST_LENGTH]);
6235                         }
6236                         OBJ(audacious_playlist_position) {
6237                                 snprintf(p, p_max_size, "%s",
6238                                         cur->audacious.items[AUDACIOUS_PLAYLIST_POSITION]);
6239                         }
6240                         OBJ(audacious_main_volume) {
6241                                 snprintf(p, p_max_size, "%s",
6242                                         cur->audacious.items[AUDACIOUS_MAIN_VOLUME]);
6243                         }
6244                         OBJ(audacious_bar) {
6245                                 double progress;
6246
6247                                 progress =
6248                                         atof(cur->audacious.items[AUDACIOUS_POSITION_SECONDS]) /
6249                                         atof(cur->audacious.items[AUDACIOUS_LENGTH_SECONDS]);
6250                                 new_bar(p, obj->a, obj->b, (int) (progress * 255.0f));
6251                         }
6252 #endif
6253
6254 #ifdef BMPX
6255                         OBJ(bmpx_title) {
6256                                 snprintf(p, p_max_size, "%s", cur->bmpx.title);
6257                         }
6258                         OBJ(bmpx_artist) {
6259                                 snprintf(p, p_max_size, "%s", cur->bmpx.artist);
6260                         }
6261                         OBJ(bmpx_album) {
6262                                 snprintf(p, p_max_size, "%s", cur->bmpx.album);
6263                         }
6264                         OBJ(bmpx_uri) {
6265                                 snprintf(p, p_max_size, "%s", cur->bmpx.uri);
6266                         }
6267                         OBJ(bmpx_track) {
6268                                 snprintf(p, p_max_size, "%i", cur->bmpx.track);
6269                         }
6270                         OBJ(bmpx_bitrate) {
6271                                 snprintf(p, p_max_size, "%i", cur->bmpx.bitrate);
6272                         }
6273 #endif
6274                         OBJ(top) {
6275                                 if (obj->data.top.num >= 0 && obj->data.top.num < 10) {
6276                                         char *timeval;
6277
6278                                         switch (obj->data.top.type) {
6279                                                 case TOP_NAME:
6280                                                         snprintf(p, 16, "%-15s",
6281                                                                 cur->cpu[obj->data.top.num]->name);
6282                                                         break;
6283                                                 case TOP_CPU:
6284                                                         snprintf(p, 7, "%6.2f",
6285                                                                 cur->cpu[obj->data.top.num]->amount);
6286                                                         break;
6287                                                 case TOP_PID:
6288                                                         snprintf(p, 6, "%5i",
6289                                                                 cur->cpu[obj->data.top.num]->pid);
6290                                                         break;
6291                                                 case TOP_MEM:
6292                                                         snprintf(p, 7, "%6.2f",
6293                                                                 cur->cpu[obj->data.top.num]->totalmem);
6294                                                         break;
6295                                                 case TOP_TIME:
6296                                                         timeval = format_time(
6297                                                                 cur->cpu[obj->data.top.num]->total_cpu_time, 9);
6298                                                         snprintf(p, 10, "%9s", timeval);
6299                                                         free(timeval);
6300                                                         break;
6301                                                 case TOP_MEM_RES:
6302                                                         human_readable(cur->cpu[obj->data.top.num]->rss,
6303                                                                         p, 255, "top_rss");
6304                                                         break;
6305                                                 case TOP_MEM_VSIZE:
6306                                                         human_readable(cur->cpu[obj->data.top.num]->vsize,
6307                                                                         p, 255, "top_rss");
6308                                                         break;
6309                                                 default:
6310                                                         ERR("Unhandled top data type: %d\n",
6311                                                                 obj->data.top.type);
6312                                         }
6313                                 } else {
6314                                         ERR("Top index < 0 or > 10: %d\n", obj->data.top.num);
6315                                 }
6316                         }
6317                         OBJ(top_mem) {
6318                                 if (obj->data.top.num >= 0 && obj->data.top.num < 10) {
6319                                         char *timeval;
6320
6321                                         switch (obj->data.top.type) {
6322                                                 case TOP_NAME:
6323                                                         snprintf(p, 16, "%-15s",
6324                                                                 cur->memu[obj->data.top.num]->name);
6325                                                         break;
6326                                                 case TOP_CPU:
6327                                                         snprintf(p, 7, "%6.2f",
6328                                                                 cur->memu[obj->data.top.num]->amount);
6329                                                         break;
6330                                                 case TOP_PID:
6331                                                         snprintf(p, 6, "%5i",
6332                                                                 cur->memu[obj->data.top.num]->pid);
6333                                                         break;
6334                                                 case TOP_MEM:
6335                                                         snprintf(p, 7, "%6.2f",
6336                                                                 cur->memu[obj->data.top.num]->totalmem);
6337                                                         break;
6338                                                 case TOP_TIME:
6339                                                         timeval = format_time(
6340                                                                 cur->memu[obj->data.top.num]->total_cpu_time,
6341                                                                 9);
6342                                                         snprintf(p, 10, "%9s", timeval);
6343                                                         free(timeval);
6344                                                         break;
6345                                                 case TOP_MEM_RES:
6346                                                         human_readable(cur->cpu[obj->data.top.num]->rss,
6347                                                                         p, 255, "top_rss");
6348                                                         break;
6349                                                 case TOP_MEM_VSIZE:
6350                                                         human_readable(cur->cpu[obj->data.top.num]->vsize,
6351                                                                         p, 255, "top_rss");
6352                                                         break;
6353                                                 default:
6354                                                         ERR("Unhandled top data type: %d\n",
6355                                                                 obj->data.top.type);
6356                                         }
6357                                 } else {
6358                                         ERR("Top index < 0 or > 10: %d\n", obj->data.top.num);
6359                                 }
6360                         }
6361                         OBJ(tail) {
6362                                 if (current_update_time - obj->data.tail.last_update
6363                                                 < obj->data.tail.interval) {
6364                                         snprintf(p, p_max_size, "%s", obj->data.tail.buffer);
6365                                 } else {
6366                                         FILE *fp;
6367                                         long nl = 0, bsize;
6368                                         int iter;
6369
6370                                         obj->data.tail.last_update = current_update_time;
6371
6372                                         if (obj->data.tail.fd != -1) {
6373                                                 tail_pipe(obj, p, p_max_size);
6374                                                 goto head;
6375                                         }
6376
6377                                         fp = fopen(obj->data.tail.logfile, "rt");
6378
6379                                         if (fp == NULL) {
6380                                                 /* Send one message, but do not consistently spam
6381                                                  * on missing logfiles. */
6382                                                 if (obj->data.tail.readlines != 0) {
6383                                                         ERR("tail logfile failed to open");
6384                                                         strcpy(obj->data.tail.buffer, "Logfile Missing");
6385                                                 }
6386                                                 obj->data.tail.readlines = 0;
6387                                                 snprintf(p, p_max_size, "Logfile Missing");
6388                                         } else {
6389                                                 obj->data.tail.readlines = 0;
6390                                                 /* -1 instead of 0 to avoid counting a trailing
6391                                                  * newline */
6392                                                 fseek(fp, -1, SEEK_END);
6393                                                 bsize = ftell(fp) + 1;
6394                                                 for (iter = obj->data.tail.wantedlines; iter > 0;
6395                                                                 iter--) {
6396                                                         nl = rev_fcharfind(fp, '\n', iter);
6397                                                         if (nl >= 0) {
6398                                                                 break;
6399                                                         }
6400                                                 }
6401                                                 obj->data.tail.readlines = iter;
6402                                                 if (obj->data.tail.readlines
6403                                                                 < obj->data.tail.wantedlines) {
6404                                                         fseek(fp, 0, SEEK_SET);
6405                                                 } else {
6406                                                         fseek(fp, nl + 1, SEEK_SET);
6407                                                         bsize -= ftell(fp);
6408                                                 }
6409                                                 /* Make sure bsize is at least 1 byte smaller than the
6410                                                  * buffer max size. */
6411                                                 if (bsize > (long) ((text_buffer_size * 20) - 1)) {
6412                                                         fseek(fp, bsize - text_buffer_size * 20 - 1,
6413                                                                 SEEK_CUR);
6414                                                         bsize = text_buffer_size * 20 - 1;
6415                                                 }
6416                                                 bsize = fread(obj->data.tail.buffer, 1, bsize, fp);
6417                                                 fclose(fp);
6418                                                 if (bsize > 0) {
6419                                                         /* Clean up trailing newline, make sure the
6420                                                          * buffer is null terminated. */
6421                                                         if (obj->data.tail.buffer[bsize - 1] == '\n') {
6422                                                                 obj->data.tail.buffer[bsize - 1] = '\0';
6423                                                         } else {
6424                                                                 obj->data.tail.buffer[bsize] = '\0';
6425                                                         }
6426                                                         snprintf(p, p_max_size, "%s",
6427                                                                 obj->data.tail.buffer);
6428                                                 } else {
6429                                                         strcpy(obj->data.tail.buffer, "Logfile Empty");
6430                                                         snprintf(p, p_max_size, "Logfile Empty");
6431                                                 }       /* bsize > 0 */
6432                                         }               /* fp == NULL */
6433                                 }                       /* if cur_upd_time >= */
6434                                 // parse_conky_vars(obj->data.tail.buffer, p, cur);
6435                         }
6436 head:
6437                         OBJ(head) {
6438                                 if (current_update_time - obj->data.tail.last_update
6439                                                 < obj->data.tail.interval) {
6440                                         snprintf(p, p_max_size, "%s", obj->data.tail.buffer);
6441                                 } else {
6442                                         FILE *fp;
6443                                         long nl = 0;
6444                                         int iter;
6445
6446                                         obj->data.tail.last_update = current_update_time;
6447
6448                                         fp = fopen(obj->data.tail.logfile, "rt");
6449                                         if (fp == NULL) {
6450                                                 /* Send one message, but do not consistently spam
6451                                                  * on missing logfiles. */
6452                                                 if (obj->data.tail.readlines != 0) {
6453                                                         ERR("head logfile failed to open");
6454                                                         strcpy(obj->data.tail.buffer, "Logfile Missing");
6455                                                 }
6456                                                 obj->data.tail.readlines = 0;
6457                                                 snprintf(p, p_max_size, "Logfile Missing");
6458                                         } else {
6459                                                 obj->data.tail.readlines = 0;
6460                                                 for (iter = obj->data.tail.wantedlines; iter > 0;
6461                                                                 iter--) {
6462                                                         nl = fwd_fcharfind(fp, '\n', iter);
6463                                                         if (nl >= 0) {
6464                                                                 break;
6465                                                         }
6466                                                 }
6467                                                 obj->data.tail.readlines = iter;
6468                                                 /* Make sure nl is at least 1 byte smaller than the
6469                                                  * buffer max size. */
6470                                                 if (nl > (long) ((text_buffer_size * 20) - 1)) {
6471                                                         nl = text_buffer_size * 20 - 1;
6472                                                 }
6473                                                 nl = fread(obj->data.tail.buffer, 1, nl, fp);
6474                                                 fclose(fp);
6475                                                 if (nl > 0) {
6476                                                         /* Clean up trailing newline, make sure the buffer
6477                                                          * is null terminated. */
6478                                                         if (obj->data.tail.buffer[nl - 1] == '\n') {
6479                                                                 obj->data.tail.buffer[nl - 1] = '\0';
6480                                                         } else {
6481                                                                 obj->data.tail.buffer[nl] = '\0';
6482                                                         }
6483                                                         snprintf(p, p_max_size, "%s",
6484                                                                 obj->data.tail.buffer);
6485                                                 } else {
6486                                                         strcpy(obj->data.tail.buffer, "Logfile Empty");
6487                                                         snprintf(p, p_max_size, "Logfile Empty");
6488                                                 }       /* nl > 0 */
6489                                         }               /* if fp == null */
6490                                 }                       /* cur_upd_time >= */
6491                                 // parse_conky_vars(obj->data.tail.buffer, p, cur);
6492                         }
6493
6494                         OBJ(lines) {
6495                                 FILE *fp = fopen(obj->data.s,"r");
6496
6497                                 if(fp != NULL) {
6498                                         char buf[BUFSZ];
6499                                         int j, lines;
6500
6501                                         lines = 0;
6502                                         while(fgets(buf, BUFSZ, fp) != NULL){
6503                                                 for(j = 0; buf[j] != 0; j++) {
6504                                                         if(buf[j] == '\n') {
6505                                                                 lines++;
6506                                                         }
6507                                                 }
6508                                         }
6509                                         sprintf(p, "%d", lines);
6510                                         fclose(fp);
6511                                 } else {
6512                                         sprintf(p, "File Unreadable");
6513                                 }
6514                         }
6515
6516                         OBJ(words) {
6517                                 FILE *fp = fopen(obj->data.s,"r");
6518
6519                                 if(fp != NULL) {
6520                                         char buf[BUFSZ];
6521                                         int j, words;
6522                                         char inword = FALSE;
6523
6524                                         words = 0;
6525                                         while(fgets(buf, BUFSZ, fp) != NULL){
6526                                                 for(j = 0; buf[j] != 0; j++) {
6527                                                         if(!isspace(buf[j])) {
6528                                                                 if(inword == FALSE) {
6529                                                                         words++;
6530                                                                         inword = TRUE;
6531                                                                 }
6532                                                         } else {
6533                                                                 inword = FALSE;
6534                                                         }
6535                                                 }
6536                                         }
6537                                         sprintf(p, "%d", words);
6538                                         fclose(fp);
6539                                 } else {
6540                                         sprintf(p, "File Unreadable");
6541                                 }
6542                         }
6543 #ifdef TCP_PORT_MONITOR
6544                         OBJ(tcp_portmon) {
6545                                 /* grab a pointer to this port monitor */
6546                                 tcp_port_monitor_t *p_monitor =
6547                                         find_tcp_port_monitor(info.p_tcp_port_monitor_collection,
6548                                         obj->data.tcp_port_monitor.port_range_begin,
6549                                         obj->data.tcp_port_monitor.port_range_end);
6550
6551                                 if (!p_monitor) {
6552                                         snprintf(p, p_max_size, "monitor not found");
6553                                         break;
6554                                 }
6555
6556                                 /* now grab the text of interest */
6557                                 if (peek_tcp_port_monitor(p_monitor,
6558                                                 obj->data.tcp_port_monitor.item,
6559                                                 obj->data.tcp_port_monitor.connection_index, p,
6560                                                 p_max_size) != 0) {
6561                                         snprintf(p, p_max_size, "monitor peek error");
6562                                         break;
6563                                 }
6564                         }
6565 #endif
6566
6567 #ifdef HAVE_ICONV
6568                         OBJ(iconv_start) {
6569                                 iconv_converting = 1;
6570                                 iconv_selected = obj->a;
6571                         }
6572                         OBJ(iconv_stop) {
6573                                 iconv_converting = 0;
6574                                 iconv_selected = 0;
6575                         }
6576 #endif
6577
6578                         OBJ(entropy_avail) {
6579                                 snprintf(p, p_max_size, "%d", cur->entropy.entropy_avail);
6580                         }
6581                         OBJ(entropy_poolsize) {
6582                                 snprintf(p, p_max_size, "%d", cur->entropy.poolsize);
6583                         }
6584                         OBJ(entropy_bar) {
6585                                 double entropy_perc;
6586
6587                                 entropy_perc = (double) cur->entropy.entropy_avail /
6588                                         (double) cur->entropy.poolsize;
6589                                 new_bar(p, obj->a, obj->b, (int) (entropy_perc * 255.0f));
6590                         }
6591 #ifdef SMAPI
6592                         OBJ(smapi) {
6593                                 char *s;
6594                                 if(obj->data.s) {
6595                                         s = smapi_get_val(obj->data.s);
6596                                         snprintf(p, p_max_size, "%s", s);
6597                                         free(s);
6598                                 }
6599                         }
6600                         OBJ(if_smapi_bat_installed) {
6601                                 int idx;
6602                                 if(obj->data.ifblock.s && sscanf(obj->data.ifblock.s, "%i", &idx) == 1) {
6603                                         if(!smapi_bat_installed(idx)) {
6604                                                 i = obj->data.ifblock.pos;
6605                                                 if_jumped = 1;
6606                                         } else
6607                                                 if_jumped = 0;
6608                                 } else
6609                                         ERR("argument to if_smapi_bat_installed must be an integer");
6610                         }
6611                         OBJ(smapi_bat_perc) {
6612                                 int idx, val;
6613                                 if(obj->data.s && sscanf(obj->data.s, "%i", &idx) == 1) {
6614                                         val = smapi_bat_installed(idx) ?
6615                                                 smapi_get_bat_int(idx, "remaining_percent") : 0;
6616                                         spaced_print(p, p_max_size, "%*d", 4, "smapi_bat_perc", pad_percents, val);
6617                                 } else
6618                                         ERR("argument to smapi_bat_perc must be an integer");
6619                         }
6620                         OBJ(smapi_bat_temp) {
6621                                 int idx, val;
6622                                 if(obj->data.s && sscanf(obj->data.s, "%i", &idx) == 1) {
6623                                         val = smapi_bat_installed(idx) ?
6624                                                 smapi_get_bat_int(idx, "temperature") : 0;
6625                                         /* temperature is in milli degree celsius */
6626                                         temp_print(p, p_max_size, val / 1000, TEMP_CELSIUS);
6627                                 } else
6628                                         ERR("argument to smapi_bat_temp must be an integer");
6629                         }
6630                         OBJ(smapi_bat_power) {
6631                                 int idx, val;
6632                                 if(obj->data.s && sscanf(obj->data.s, "%i", &idx) == 1) {
6633                                         val = smapi_bat_installed(idx) ?
6634                                                 smapi_get_bat_int(idx, "power_now") : 0;
6635                                         /* power_now is in mW, set to W with one digit precision */
6636                                         snprintf(p, p_max_size, "%.1f", ((double)val / 1000));
6637                                 } else
6638                                         ERR("argument to smapi_bat_power must be an integer");
6639                         }
6640                         OBJ(smapi_bat_bar) {
6641                                 if(obj->data.i >= 0 && smapi_bat_installed(obj->data.i))
6642                                         new_bar(p, obj->a, obj->b, (int)
6643                                                         (255 * smapi_get_bat_int(obj->data.i, "remaining_percent") / 100));
6644                                 else
6645                                         new_bar(p, obj->a, obj->b, 0);
6646                         }
6647 #endif /* SMAPI */
6648                         OBJ(scroll) {
6649                                 unsigned int j;
6650                                 char *tmp;
6651                                 parse_conky_vars(obj->data.scroll.text, p, cur);
6652                                 
6653                                 if (strlen(p) <= obj->data.scroll.show) {
6654                                         break;
6655                                 }
6656 #define LINESEPARATOR '|'
6657                                 //place all the lines behind each other with LINESEPARATOR between them
6658                                 for(j = 0; p[j] != 0; j++) {
6659                                         if(p[j]=='\n') {
6660                                                 p[j]=LINESEPARATOR;
6661                                         }
6662                                 }
6663                                 //scroll the output obj->data.scroll.start places by copying that many chars from
6664                                 //the front of the string to tmp, scrolling the rest to the front and placing tmp
6665                                 //at the back of the string
6666                                 tmp = calloc(obj->data.scroll.start + 1, sizeof(char));
6667                                 strncpy(tmp, p, obj->data.scroll.start); tmp[obj->data.scroll.start] = 0;
6668                                 for(j = obj->data.scroll.start; p[j] != 0; j++){
6669                                         p[j - obj->data.scroll.start] = p[j];
6670                                 }
6671                                 strcpy(&p[j - obj->data.scroll.start], tmp);
6672                                 free(tmp);
6673                                 //only show the requested number of chars
6674                                 if(obj->data.scroll.show < j) {
6675                                         p[obj->data.scroll.show] = 0;
6676                                 }
6677                                 //next time, scroll a place more or reset scrolling if we are at the end
6678                                 obj->data.scroll.start += obj->data.scroll.step;
6679                                 if(obj->data.scroll.start >= j){
6680                                          obj->data.scroll.start = 0;
6681                                 }
6682                         }
6683 #ifdef NVIDIA
6684                         OBJ(nvidia) {
6685                                 int value = get_nvidia_value(obj->data.nvidia.type, display);
6686                                 if(value == -1)
6687                                         snprintf(p, p_max_size, "N/A");
6688                                 else if (obj->data.nvidia.type == NV_TEMP)
6689                                         temp_print(p, p_max_size, (double)value, TEMP_CELSIUS);
6690                                 else if (obj->data.nvidia.print_as_float &&
6691                                                 value > 0 && value < 100)
6692                                         snprintf(p, p_max_size, "%.1f", (float)value);
6693                                 else
6694                                         snprintf(p, p_max_size, "%d", value);
6695                         }
6696 #endif /* NVIDIA */
6697
6698                         break;
6699                 }
6700
6701                 {
6702                         unsigned int a = strlen(p);
6703
6704 #ifdef HAVE_ICONV
6705                         if (a > 0 && iconv_converting && iconv_selected > 0
6706                                         && (iconv_cd[iconv_selected - 1] != (iconv_t) (-1))) {
6707                                 int bytes;
6708                                 size_t dummy1, dummy2;
6709                                 char *ptr = buff_in;
6710                                 char *outptr = p;
6711
6712                                 dummy1 = dummy2 = a;
6713
6714                                 strncpy(buff_in, p, p_max_size);
6715
6716                                 iconv(*iconv_cd[iconv_selected - 1], NULL, NULL, NULL, NULL);
6717                                 while (dummy1 > 0) {
6718                                         bytes = iconv(*iconv_cd[iconv_selected - 1], &ptr, &dummy1,
6719                                                         &outptr, &dummy2);
6720                                         if (bytes == -1) {
6721                                                 ERR("Iconv codeset conversion failed");
6722                                                 break;
6723                                         }
6724                                 }
6725
6726                                 /* It is nessecary when we are converting from multibyte to
6727                                  * singlebyte codepage */
6728                                 a = outptr - p;
6729                         }
6730 #endif /* HAVE_ICONV */
6731                         p += a;
6732                         p_max_size -= a;
6733                 }
6734         }
6735 }
6736
6737 double current_update_time, next_update_time, last_update_time;
6738
6739 static void generate_text(void)
6740 {
6741         struct information *cur = &info;
6742         char *p;
6743
6744         special_count = 0;
6745
6746         /* update info */
6747
6748         current_update_time = get_time();
6749
6750         update_stuff();
6751         /* fix diskio rates to b/s (use update_interval */
6752         info.diskio_read_value /= update_interval;
6753         info.diskio_write_value /= update_interval;
6754         info.diskio_value /= update_interval;
6755
6756         /* add things to the buffer */
6757
6758         /* generate text */
6759
6760         p = text_buffer;
6761
6762         generate_text_internal(p, max_user_text, global_text_object_list, cur);
6763
6764         if (stuff_in_upper_case) {
6765                 char *tmp_p;
6766
6767                 tmp_p = text_buffer;
6768                 while (*tmp_p) {
6769                         *tmp_p = toupper(*tmp_p);
6770                         tmp_p++;
6771                 }
6772         }
6773
6774         next_update_time += update_interval;
6775         if (next_update_time < get_time()) {
6776                 next_update_time = get_time() + update_interval;
6777         } else if (next_update_time > get_time() + update_interval) {
6778                 next_update_time = get_time() + update_interval;
6779         }
6780         last_update_time = current_update_time;
6781         total_updates++;
6782         // free(p);
6783 }
6784
6785 #ifdef X11
6786 static void set_font(void)
6787 {
6788 #ifdef XFT
6789         if (use_xft) {
6790                 if (window.xftdraw != NULL) {
6791                         XftDrawDestroy(window.xftdraw);
6792                 }
6793                 window.xftdraw = XftDrawCreate(display, window.drawable,
6794                         DefaultVisual(display, screen), DefaultColormap(display, screen));
6795         } else
6796 #endif
6797         {
6798                 XSetFont(display, window.gc, fonts[selected_font].font->fid);
6799         }
6800 }
6801
6802 #endif /* X11 */
6803
6804 static inline int get_string_width(const char *s)
6805 {
6806 #ifdef X11
6807         return *s ? calc_text_width(s, strlen(s)) : 0;
6808 #else
6809         return strlen(s);
6810 #endif /* X11 */
6811 }
6812
6813 static inline int get_string_width_special(char *s)
6814 {
6815 #ifdef X11
6816         char *p, *final;
6817         int idx = 1;
6818         int width = 0;
6819         unsigned int i;
6820
6821         if (!s) {
6822                 return 0;
6823         }
6824
6825         p = strndup(s, text_buffer_size);
6826         final = p;
6827
6828         while (*p) {
6829                 if (*p == SPECIAL_CHAR) {
6830                         /* shift everything over by 1 so that the special char
6831                          * doesn't mess up the size calculation */
6832                         for (i = 0; i < strlen(p); i++) {
6833                                 *(p + i) = *(p + i + 1);
6834                         }
6835                         if (specials[special_index + idx].type == GRAPH
6836                                         || specials[special_index + idx].type == BAR) {
6837                                 width += specials[special_index + idx].width;
6838                         }
6839                         idx++;
6840                 } else {
6841                         p++;
6842                 }
6843         }
6844         if (strlen(final) > 1) {
6845                 width += calc_text_width(final, strlen(final));
6846         }
6847         free(final);
6848         return width;
6849 #else
6850         return (s) ? strlen(s) : 0;
6851 #endif /* X11 */
6852 }
6853
6854 #ifdef X11
6855 static void text_size_updater(char *s);
6856
6857 int last_font_height;
6858 static void update_text_area(void)
6859 {
6860         int x, y;
6861
6862         /* update text size if it isn't fixed */
6863 #ifdef OWN_WINDOW
6864         if (!fixed_size)
6865 #endif
6866         {
6867                 text_width = minimum_width;
6868                 text_height = 0;
6869                 special_index = 0;
6870                 last_font_height = font_height();
6871                 for_each_line(text_buffer, text_size_updater);
6872                 text_width += 1;
6873                 if (text_height < minimum_height) {
6874                         text_height = minimum_height;
6875                 }
6876                 if (text_width > maximum_width && maximum_width > 0) {
6877                         text_width = maximum_width;
6878                 }
6879         }
6880
6881         /* get text position on workarea */
6882         switch (text_alignment) {
6883                 case TOP_LEFT:
6884                         x = gap_x;
6885                         y = gap_y;
6886                         break;
6887
6888                 case TOP_RIGHT:
6889                         x = workarea[2] - text_width - gap_x;
6890                         y = gap_y;
6891                         break;
6892
6893                 case TOP_MIDDLE:
6894                         x = workarea[2] / 2 - text_width / 2 - gap_x;
6895                         y = gap_y;
6896                         break;
6897
6898                 default:
6899                 case BOTTOM_LEFT:
6900                         x = gap_x;
6901                         y = workarea[3] - text_height - gap_y;
6902                         break;
6903
6904                 case BOTTOM_RIGHT:
6905                         x = workarea[2] - text_width - gap_x;
6906                         y = workarea[3] - text_height - gap_y;
6907                         break;
6908
6909                 case BOTTOM_MIDDLE:
6910                         x = workarea[2] / 2 - text_width / 2 - gap_x;
6911                         y = workarea[3] - text_height - gap_y;
6912                         break;
6913
6914                 case MIDDLE_LEFT:
6915                         x = gap_x;
6916                         y = workarea[3] / 2 - text_height / 2 - gap_y;
6917                         break;
6918
6919                 case MIDDLE_RIGHT:
6920                         x = workarea[2] - text_width - gap_x;
6921                         y = workarea[3] / 2 - text_height / 2 - gap_y;
6922                         break;
6923
6924 #ifdef OWN_WINDOW
6925                 case NONE:      // Let the WM manage the window
6926                         x = window.x;
6927                         y = window.y;
6928
6929                         fixed_pos = 1;
6930                         fixed_size = 1;
6931                         break;
6932 #endif
6933         }
6934 #ifdef OWN_WINDOW
6935
6936         if (own_window && !fixed_pos) {
6937                 x += workarea[0];
6938                 y += workarea[1];
6939                 text_start_x = border_margin + 1;
6940                 text_start_y = border_margin + 1;
6941                 window.x = x - border_margin - 1;
6942                 window.y = y - border_margin - 1;
6943         } else
6944 #endif
6945         {
6946                 /* If window size doesn't match to workarea's size,
6947                  * then window probably includes panels (gnome).
6948                  * Blah, doesn't work on KDE. */
6949                 if (workarea[2] != window.width || workarea[3] != window.height) {
6950                         y += workarea[1];
6951                         x += workarea[0];
6952                 }
6953
6954                 text_start_x = x;
6955                 text_start_y = y;
6956         }
6957 }
6958
6959 /* drawing stuff */
6960
6961 static int cur_x, cur_y;        /* current x and y for drawing */
6962 #endif
6963 //draw_mode also without X11 because we only need to print to stdout with FG
6964 static int draw_mode;           /* FG, BG or OUTLINE */
6965 #ifdef X11
6966 static long current_color;
6967
6968 #ifdef X11
6969 static void text_size_updater(char *s)
6970 {
6971         int w = 0;
6972         char *p;
6973
6974         /* get string widths and skip specials */
6975         p = s;
6976         while (*p) {
6977                 if (*p == SPECIAL_CHAR) {
6978                         *p = '\0';
6979                         w += get_string_width(s);
6980                         *p = SPECIAL_CHAR;
6981
6982                         if (specials[special_index].type == BAR
6983                                         || specials[special_index].type == GRAPH) {
6984                                 w += specials[special_index].width;
6985                                 if (specials[special_index].height > last_font_height) {
6986                                         last_font_height = specials[special_index].height;
6987                                         last_font_height += font_ascent();
6988                                 }
6989                         } else if (specials[special_index].type == OFFSET) {
6990                                 if (specials[special_index].arg > 0) {
6991                                         w += specials[special_index].arg;
6992                                 }
6993                         } else if (specials[special_index].type == VOFFSET) {
6994                                 last_font_height += specials[special_index].arg;
6995                         } else if (specials[special_index].type == GOTO) {
6996                                 if (specials[special_index].arg > cur_x) {
6997                                         w = (int) specials[special_index].arg;
6998                                 }
6999                         } else if (specials[special_index].type == TAB) {
7000                                 int start = specials[special_index].arg;
7001                                 int step = specials[special_index].width;
7002
7003                                 if (!step || step < 0) {
7004                                         step = 10;
7005                                 }
7006                                 w += step - (cur_x - text_start_x - start) % step;
7007                         } else if (specials[special_index].type == FONT) {
7008                                 selected_font = specials[special_index].font_added;
7009                                 if (font_height() > last_font_height) {
7010                                         last_font_height = font_height();
7011                                 }
7012                         }
7013
7014                         special_index++;
7015                         s = p + 1;
7016                 }
7017                 p++;
7018         }
7019         w += get_string_width(s);
7020         if (w > text_width) {
7021                 text_width = w;
7022         }
7023         if (text_width > maximum_width && maximum_width) {
7024                 text_width = maximum_width;
7025         }
7026
7027         text_height += last_font_height;
7028         last_font_height = font_height();
7029 }
7030 #endif /* X11 */
7031
7032 static inline void set_foreground_color(long c)
7033 {
7034         current_color = c;
7035         XSetForeground(display, window.gc, c);
7036 }
7037 #endif /* X11 */
7038
7039 static void draw_string(const char *s)
7040 {
7041         int i, i2, pos, width_of_s;
7042         int max = 0;
7043         int added;
7044
7045         if (s[0] == '\0') {
7046                 return;
7047         }
7048
7049         width_of_s = get_string_width(s);
7050         if ((output_methods & TO_STDOUT) && draw_mode == FG) {
7051                 printf("%s\n", s);
7052                 fflush(stdout); /* output immediately, don't buffer */
7053         }
7054         memset(tmpstring1, 0, text_buffer_size);
7055         memset(tmpstring2, 0, text_buffer_size);
7056         strncpy(tmpstring1, s, text_buffer_size - 1);
7057         pos = 0;
7058         added = 0;
7059
7060 #ifdef X11
7061         max = ((text_width - width_of_s) / get_string_width(" "));
7062 #endif /* X11 */
7063         /* This code looks for tabs in the text and coverts them to spaces.
7064          * The trick is getting the correct number of spaces, and not going
7065          * over the window's size without forcing the window larger. */
7066         for (i = 0; i < (int) text_buffer_size; i++) {
7067                 if (tmpstring1[i] == '\t') {
7068                         i2 = 0;
7069                         for (i2 = 0; i2 < (8 - (1 + pos) % 8) && added <= max; i2++) {
7070                                 /* guard against overrun */
7071                                 tmpstring2[MIN(pos + i2, (int)text_buffer_size - 1)] = ' ';
7072                                 added++;
7073                         }
7074                         pos += i2;
7075                 } else {
7076                         /* guard against overrun */
7077                         tmpstring2[MIN(pos, (int) text_buffer_size - 1)] = tmpstring1[i];
7078                         pos++;
7079                 }
7080         }
7081 #ifdef X11
7082         if (text_width == maximum_width) {
7083                 /* this means the text is probably pushing the limit,
7084                  * so we'll chop it */
7085                 while (cur_x + get_string_width(tmpstring2) - text_start_x
7086                                 > maximum_width && strlen(tmpstring2) > 0) {
7087                         tmpstring2[strlen(tmpstring2) - 1] = '\0';
7088                 }
7089         }
7090 #endif /* X11 */
7091         s = tmpstring2;
7092 #ifdef X11
7093 #ifdef XFT
7094         if (use_xft) {
7095                 XColor c;
7096                 XftColor c2;
7097
7098                 c.pixel = current_color;
7099                 XQueryColor(display, DefaultColormap(display, screen), &c);
7100
7101                 c2.pixel = c.pixel;
7102                 c2.color.red = c.red;
7103                 c2.color.green = c.green;
7104                 c2.color.blue = c.blue;
7105                 c2.color.alpha = fonts[selected_font].font_alpha;
7106                 if (utf8_mode) {
7107                         XftDrawStringUtf8(window.xftdraw, &c2, fonts[selected_font].xftfont,
7108                                 cur_x, cur_y, (const XftChar8 *) s, strlen(s));
7109                 } else {
7110                         XftDrawString8(window.xftdraw, &c2, fonts[selected_font].xftfont,
7111                                 cur_x, cur_y, (const XftChar8 *) s, strlen(s));
7112                 }
7113         } else
7114 #endif
7115         {
7116                 XDrawString(display, window.drawable, window.gc, cur_x, cur_y, s,
7117                         strlen(s));
7118         }
7119         cur_x += width_of_s;
7120 #endif /* X11 */
7121         memcpy(tmpstring1, s, text_buffer_size);
7122 }
7123
7124 long redmask, greenmask, bluemask;
7125
7126 void set_up_gradient(void)
7127 {
7128         int i;
7129 #ifdef X11
7130         colour_depth = DisplayPlanes(display, screen);
7131 #else
7132         colour_depth = 16;
7133 #endif /* X11 */
7134         if (colour_depth != 24 && colour_depth != 16) {
7135                 ERR("using non-standard colour depth, gradients may look like a "
7136                         "lolly-pop");
7137         }
7138
7139         redmask = 0;
7140         greenmask = 0;
7141         bluemask = 0;
7142         for (i = (colour_depth / 3) - 1; i >= 0; i--) {
7143                 redmask |= 1 << i;
7144                 greenmask |= 1 << i;
7145                 bluemask |= 1 << i;
7146         }
7147         if (colour_depth % 3 == 1) {
7148                 greenmask |= 1 << (colour_depth / 3);
7149         }
7150         redmask = redmask << (2 * colour_depth / 3 + colour_depth % 3);
7151         greenmask = greenmask << (colour_depth / 3);
7152 }
7153
7154 /* this function returns the next colour between two colours for a gradient */
7155 unsigned long do_gradient(unsigned long first_colour,
7156                 unsigned long last_colour)
7157 {
7158         int tmp_color = 0;
7159         int red1, green1, blue1;                                // first colour
7160         int red2, green2, blue2;                                // second colour
7161         int red3 = 0, green3 = 0, blue3 = 0;    // difference
7162         short redshift = (2 * colour_depth / 3 + colour_depth % 3);
7163         short greenshift = (colour_depth / 3);
7164
7165         red1 = (first_colour & redmask) >> redshift;
7166         green1 = (first_colour & greenmask) >> greenshift;
7167         blue1 = first_colour & bluemask;
7168         red2 = (last_colour & redmask) >> redshift;
7169         green2 = (last_colour & greenmask) >> greenshift;
7170         blue2 = last_colour & bluemask;
7171         if (red1 > red2) {
7172                 red3 = -1;
7173         }
7174         if (red1 < red2) {
7175                 red3 = 1;
7176         }
7177         if (green1 > green2) {
7178                 green3 = -1;
7179         }
7180         if (green1 < green2) {
7181                 green3 = 1;
7182         }
7183         if (blue1 > blue2) {
7184                 blue3 = -1;
7185         }
7186         if (blue1 < blue2) {
7187                 blue3 = 1;
7188         }
7189         red1 += red3;
7190         green1 += green3;
7191         blue1 += blue3;
7192         if (red1 < 0) {
7193                 red1 = 0;
7194         }
7195         if (green1 < 0) {
7196                 green1 = 0;
7197         }
7198         if (blue1 < 0) {
7199                 blue1 = 0;
7200         }
7201         if (red1 > bluemask) {
7202                 red1 = bluemask;
7203         }
7204         if (green1 > bluemask) {
7205                 green1 = bluemask;
7206         }
7207         if (blue1 > bluemask) {
7208                 blue1 = bluemask;
7209         }
7210         tmp_color = (red1 << redshift) | (green1 << greenshift) | blue1;
7211         return tmp_color;
7212 }
7213
7214 /* this function returns the max diff for a gradient */
7215 unsigned long gradient_max(unsigned long first_colour,
7216                 unsigned long last_colour)
7217 {
7218         int red1, green1, blue1;                                // first colour
7219         int red2, green2, blue2;                                // second colour
7220         int red3 = 0, green3 = 0, blue3 = 0;                    // difference
7221         long redshift, greenshift;
7222         int max;
7223
7224         if (colour_depth == 0) {
7225                 set_up_gradient();
7226         }
7227         redshift = (2 * colour_depth / 3 + colour_depth % 3);
7228         greenshift = (colour_depth / 3);
7229
7230         red1 = (first_colour & redmask) >> redshift;
7231         green1 = (first_colour & greenmask) >> greenshift;
7232         blue1 = first_colour & bluemask;
7233         red2 = (last_colour & redmask) >> redshift;
7234         green2 = (last_colour & greenmask) >> greenshift;
7235         blue2 = last_colour & bluemask;
7236         red3 = abs(red1 - red2);
7237         green3 = abs(green1 - green2);
7238         blue3 = abs(blue1 - blue2);
7239         max = red3;
7240
7241         if (green3 > max) {
7242                 max = green3;
7243         }
7244         if (blue3 > max) {
7245                 max = blue3;
7246         }
7247         return max;
7248 }
7249
7250 static void draw_line(char *s)
7251 {
7252 #ifdef X11
7253         char *p;
7254         int cur_y_add = 0;
7255         short font_h;
7256         char *tmp_str;
7257
7258         cur_x = text_start_x;
7259         cur_y += font_ascent();
7260         font_h = font_height();
7261
7262         /* find specials and draw stuff */
7263         p = s;
7264         while (*p) {
7265                 if (*p == SPECIAL_CHAR) {
7266                         int w = 0;
7267
7268                         /* draw string before special */
7269                         *p = '\0';
7270                         draw_string(s);
7271                         *p = SPECIAL_CHAR;
7272                         s = p + 1;
7273
7274                         /* draw special */
7275                         switch (specials[special_index].type) {
7276                                 case HORIZONTAL_LINE:
7277                                 {
7278                                         int h = specials[special_index].height;
7279                                         int mid = font_ascent() / 2;
7280
7281                                         w = text_start_x + text_width - cur_x;
7282
7283                                         XSetLineAttributes(display, window.gc, h, LineSolid,
7284                                                 CapButt, JoinMiter);
7285                                         XDrawLine(display, window.drawable, window.gc, cur_x,
7286                                                 cur_y - mid / 2, cur_x + w, cur_y - mid / 2);
7287                                         break;
7288                                 }
7289
7290                                 case STIPPLED_HR:
7291                                 {
7292                                         int h = specials[special_index].height;
7293                                         int tmp_s = specials[special_index].arg;
7294                                         int mid = font_ascent() / 2;
7295                                         char ss[2] = { tmp_s, tmp_s };
7296
7297                                         w = text_start_x + text_width - cur_x - 1;
7298                                         XSetLineAttributes(display, window.gc, h, LineOnOffDash,
7299                                                 CapButt, JoinMiter);
7300                                         XSetDashes(display, window.gc, 0, ss, 2);
7301                                         XDrawLine(display, window.drawable, window.gc, cur_x,
7302                                                 cur_y - mid / 2, cur_x + w, cur_y - mid / 2);
7303                                         break;
7304                                 }
7305
7306                                 case BAR:
7307                                 {
7308                                         int h, bar_usage, by;
7309                                         if (cur_x - text_start_x > maximum_width
7310                                                         && maximum_width > 0) {
7311                                                 break;
7312                                         }
7313                                         h = specials[special_index].height;
7314                                         bar_usage = specials[special_index].arg;
7315                                         by = cur_y - (font_ascent() / 2) - 1;
7316
7317                                         if (h < font_height()) {
7318                                                 by -= h / 2 - 1;
7319                                         }
7320                                         w = specials[special_index].width;
7321                                         if (w == 0) {
7322                                                 w = text_start_x + text_width - cur_x - 1;
7323                                         }
7324                                         if (w < 0) {
7325                                                 w = 0;
7326                                         }
7327
7328                                         XSetLineAttributes(display, window.gc, 1, LineSolid,
7329                                                 CapButt, JoinMiter);
7330
7331                                         XDrawRectangle(display, window.drawable, window.gc, cur_x,
7332                                                 by, w, h);
7333                                         XFillRectangle(display, window.drawable, window.gc, cur_x,
7334                                                 by, w * bar_usage / 255, h);
7335                                         if (specials[special_index].height > cur_y_add
7336                                                         && specials[special_index].height > font_h) {
7337                                                 cur_y_add = specials[special_index].height;
7338                                         }
7339                                         break;
7340                                 }
7341
7342                                 case GRAPH:
7343                                 {
7344                                         int h, by, i, j = 0;
7345                                         int gradient_size = 0;
7346                                         float gradient_factor = 0;
7347                                         float gradient_update = 0;
7348                                         unsigned long last_colour = current_color;
7349                                         unsigned long tmpcolour = current_color;
7350                                         if (cur_x - text_start_x > maximum_width
7351                                                         && maximum_width > 0) {
7352                                                 break;
7353                                         }
7354                                         h = specials[special_index].height;
7355                                         by = cur_y - (font_ascent() / 2) - 1;
7356
7357                                         if (h < font_height()) {
7358                                                 by -= h / 2 - 1;
7359                                         }
7360                                         w = specials[special_index].width;
7361                                         if (w == 0) {
7362                                                 w = text_start_x + text_width - cur_x - 1;
7363                                         }
7364                                         if (w < 0) {
7365                                                 w = 0;
7366                                         }
7367                                         if (draw_graph_borders) {
7368                                                 XSetLineAttributes(display, window.gc, 1, LineSolid,
7369                                                         CapButt, JoinMiter);
7370                                                 XDrawRectangle(display, window.drawable, window.gc,
7371                                                         cur_x, by, w, h);
7372                                         }
7373                                         XSetLineAttributes(display, window.gc, 1, LineSolid,
7374                                                 CapButt, JoinMiter);
7375
7376                                         if (specials[special_index].last_colour != 0
7377                                                         || specials[special_index].first_colour != 0) {
7378                                                 tmpcolour = specials[special_index].last_colour;
7379                                                 gradient_size =
7380                                                         gradient_max(specials[special_index].last_colour,
7381                                                         specials[special_index].first_colour);
7382                                                 gradient_factor = (float) gradient_size / (w - 2);
7383                                         }
7384                                         for (i = w - 2; i > -1; i--) {
7385                                                 if (specials[special_index].last_colour != 0
7386                                                                 || specials[special_index].first_colour != 0) {
7387                                                         XSetForeground(display, window.gc, tmpcolour);
7388                                                         gradient_update += gradient_factor;
7389                                                         while (gradient_update > 0) {
7390                                                                 tmpcolour = do_gradient(tmpcolour,
7391                                                                         specials[special_index].first_colour);
7392                                                                 gradient_update--;
7393                                                         }
7394                                                 }
7395                                                 if ((w - i) / ((float) (w - 2) /
7396                                                                 (specials[special_index].graph_width)) > j
7397                                                                 && j < MAX_GRAPH_DEPTH - 3) {
7398                                                         j++;
7399                                                 }
7400                                                 /* this is mugfugly, but it works */
7401                                                 XDrawLine(display, window.drawable, window.gc,
7402                                                         cur_x + i + 1, by + h, cur_x + i + 1,
7403                                                         by + h - specials[special_index].graph[j] *
7404                                                         (h - 1) / specials[special_index].graph_scale);
7405                                         }
7406                                         if (specials[special_index].height > cur_y_add
7407                                                         && specials[special_index].height > font_h) {
7408                                                 cur_y_add = specials[special_index].height;
7409                                         }
7410                                         /* if (draw_mode == BG) {
7411                                                 set_foreground_color(default_bg_color);
7412                                         } else if (draw_mode == OUTLINE) {
7413                                                 set_foreground_color(default_out_color);
7414                                         } else {
7415                                                 set_foreground_color(default_fg_color);
7416                                         } */
7417                                         if (show_graph_range) {
7418                                                 int tmp_x = cur_x;
7419                                                 int tmp_y = cur_y;
7420                                                 unsigned short int seconds = update_interval * w;
7421                                                 char *tmp_day_str;
7422                                                 char *tmp_hour_str;
7423                                                 char *tmp_min_str;
7424                                                 char *tmp_sec_str;
7425                                                 unsigned short int timeunits;
7426                                                 if(seconds!=0){
7427                                                         timeunits = seconds / 86400; seconds %= 86400;
7428                                                         if( timeunits > 0 ) {
7429                                                                 asprintf(&tmp_day_str, "%dd", timeunits);
7430                                                         }else{
7431                                                                 tmp_day_str = strdup("");
7432                                                         }
7433                                                         timeunits = seconds / 3600; seconds %= 3600;
7434                                                         if( timeunits > 0 ) {
7435                                                                 asprintf(&tmp_hour_str, "%dh", timeunits);
7436                                                         }else{
7437                                                                 tmp_hour_str = strdup("");
7438                                                         }
7439                                                         timeunits = seconds / 60; seconds %= 60;
7440                                                         if(timeunits > 0) {
7441                                                                 asprintf(&tmp_min_str, "%dm", timeunits);
7442                                                         }else{
7443                                                                 tmp_min_str = strdup("");
7444                                                         }
7445                                                         if(seconds > 0) {
7446                                                                 asprintf(&tmp_sec_str, "%ds", seconds);
7447                                                         }else{
7448                                                                 tmp_sec_str = strdup("");
7449                                                         }
7450                                                         asprintf(&tmp_str, "%s%s%s%s", tmp_day_str, tmp_hour_str, tmp_min_str, tmp_sec_str);
7451                                                         free(tmp_day_str); free(tmp_hour_str); free(tmp_min_str); free(tmp_sec_str);
7452                                                 }else{
7453                                                         asprintf(&tmp_str, "Range not possible"); //should never happen, but better safe then sorry
7454                                                 }
7455                                                 cur_x += (w / 2) - (font_ascent() * (strlen(tmp_str) / 2));
7456                                                 cur_y += font_height() / 2;
7457                                                 draw_string(tmp_str);
7458                                                 free(tmp_str);
7459                                                 cur_x = tmp_x;
7460                                                 cur_y = tmp_y;
7461                                         }
7462 #ifdef MATH
7463                                         if (show_graph_scale && (specials[special_index].show_scale == 1)) {
7464                                                 int tmp_x = cur_x;
7465                                                 int tmp_y = cur_y;
7466                                                 cur_x += font_ascent() / 2;
7467                                                 cur_y += font_height() / 2;
7468                                                 tmp_str = (char *)
7469                                                         calloc(log10(floor(specials[special_index].graph_scale)) + 4,
7470                                                                         sizeof(char));
7471                                                 sprintf(tmp_str, "%.1f", specials[special_index].graph_scale);
7472                                                 draw_string(tmp_str);
7473                                                 free(tmp_str);
7474                                                 cur_x = tmp_x;
7475                                                 cur_y = tmp_y;
7476                                         }
7477 #endif
7478                                         set_foreground_color(last_colour);
7479                                         break;
7480                                 }
7481
7482                                 case FONT:
7483                                 {
7484                                         int old = font_ascent();
7485
7486                                         cur_y -= font_ascent();
7487                                         selected_font = specials[special_index].font_added;
7488                                         if (cur_y + font_ascent() < cur_y + old) {
7489                                                 cur_y += old;
7490                                         } else {
7491                                                 cur_y += font_ascent();
7492                                         }
7493                                         set_font();
7494                                         break;
7495                                 }
7496                                 case FG:
7497                                         if (draw_mode == FG) {
7498                                                 set_foreground_color(specials[special_index].arg);
7499                                         }
7500                                         break;
7501
7502                                 case BG:
7503                                         if (draw_mode == BG) {
7504                                                 set_foreground_color(specials[special_index].arg);
7505                                         }
7506                                         break;
7507
7508                                 case OUTLINE:
7509                                         if (draw_mode == OUTLINE) {
7510                                                 set_foreground_color(specials[special_index].arg);
7511                                         }
7512                                         break;
7513
7514                                 case OFFSET:
7515                                         w += specials[special_index].arg;
7516                                         break;
7517
7518                                 case VOFFSET:
7519                                         cur_y += specials[special_index].arg;
7520                                         break;
7521
7522                                 case GOTO:
7523                                         if (specials[special_index].arg >= 0) {
7524                                                 cur_x = (int) specials[special_index].arg;
7525                                         }
7526                                         break;
7527
7528                                 case TAB:
7529                                 {
7530                                         int start = specials[special_index].arg;
7531                                         int step = specials[special_index].width;
7532
7533                                         if (!step || step < 0) {
7534                                                 step = 10;
7535                                         }
7536                                         w = step - (cur_x - text_start_x - start) % step;
7537                                         break;
7538                                 }
7539
7540                                 case ALIGNR:
7541                                 {
7542                                         /* TODO: add back in "+ border_margin" to the end of
7543                                          * this line? */
7544                                         int pos_x = text_start_x + text_width -
7545                                                 get_string_width_special(s);
7546
7547                                         /* printf("pos_x %i text_start_x %i text_width %i cur_x %i "
7548                                                 "get_string_width(p) %i gap_x %i "
7549                                                 "specials[special_index].arg %i border_margin %i "
7550                                                 "border_width %i\n", pos_x, text_start_x, text_width,
7551                                                 cur_x, get_string_width_special(s), gap_x,
7552                                                 specials[special_index].arg, border_margin,
7553                                                 border_width); */
7554                                         if (pos_x > specials[special_index].arg && pos_x > cur_x) {
7555                                                 cur_x = pos_x - specials[special_index].arg;
7556                                         }
7557                                         break;
7558                                 }
7559
7560                                 case ALIGNC:
7561                                 {
7562                                         int pos_x = (text_width) / 2 - get_string_width_special(s) /
7563                                                 2 - (cur_x - text_start_x);
7564                                         /* int pos_x = text_start_x + text_width / 2 -
7565                                                 get_string_width_special(s) / 2; */
7566
7567                                         /* printf("pos_x %i text_start_x %i text_width %i cur_x %i "
7568                                                 "get_string_width(p) %i gap_x %i "
7569                                                 "specials[special_index].arg %i\n", pos_x, text_start_x,
7570                                                 text_width, cur_x, get_string_width(s), gap_x,
7571                                                 specials[special_index].arg); */
7572                                         if (pos_x > specials[special_index].arg) {
7573                                                 w = pos_x - specials[special_index].arg;
7574                                         }
7575                                         break;
7576                                 }
7577                         }
7578
7579                         cur_x += w;
7580
7581                         special_index++;
7582                 }
7583
7584                 p++;
7585         }
7586 #else
7587         draw_string(s);
7588 #endif
7589 #ifdef X11
7590         if (cur_y_add > 0) {
7591                 cur_y += cur_y_add;
7592                 cur_y -= font_descent();
7593         }
7594
7595         draw_string(s);
7596
7597         cur_y += font_descent();
7598 #endif /* X11 */
7599 }
7600
7601 static void draw_text(void)
7602 {
7603 #ifdef X11
7604         cur_y = text_start_y;
7605
7606         /* draw borders */
7607         if (draw_borders && border_width > 0) {
7608                 unsigned int b = (border_width + 1) / 2;
7609
7610                 if (stippled_borders) {
7611                         char ss[2] = { stippled_borders, stippled_borders };
7612                         XSetLineAttributes(display, window.gc, border_width, LineOnOffDash,
7613                                 CapButt, JoinMiter);
7614                         XSetDashes(display, window.gc, 0, ss, 2);
7615                 } else {
7616                         XSetLineAttributes(display, window.gc, border_width, LineSolid,
7617                                 CapButt, JoinMiter);
7618                 }
7619
7620                 XDrawRectangle(display, window.drawable, window.gc,
7621                         text_start_x - border_margin + b, text_start_y - border_margin + b,
7622                         text_width + border_margin * 2 - 1 - b * 2,
7623                         text_height + border_margin * 2 - 1 - b * 2);
7624         }
7625
7626         /* draw text */
7627         special_index = 0;
7628 #endif /* X11 */
7629         for_each_line(text_buffer, draw_line);
7630 }
7631
7632 static void draw_stuff(void)
7633 {
7634 #ifdef X11
7635         selected_font = 0;
7636         if (draw_shades && !draw_outline) {
7637                 text_start_x++;
7638                 text_start_y++;
7639                 set_foreground_color(default_bg_color);
7640                 draw_mode = BG;
7641                 draw_text();
7642                 text_start_x--;
7643                 text_start_y--;
7644         }
7645
7646         if (draw_outline) {
7647                 int i, j;
7648                 selected_font = 0;
7649
7650                 for (i = -1; i < 2; i++) {
7651                         for (j = -1; j < 2; j++) {
7652                                 if (i == 0 && j == 0) {
7653                                         continue;
7654                                 }
7655                                 text_start_x += i;
7656                                 text_start_y += j;
7657                                 set_foreground_color(default_out_color);
7658                                 draw_mode = OUTLINE;
7659                                 draw_text();
7660                                 text_start_x -= i;
7661                                 text_start_y -= j;
7662                         }
7663                 }
7664         }
7665
7666         set_foreground_color(default_fg_color);
7667 #endif /* X11 */
7668         draw_mode = FG;
7669         draw_text();
7670 #ifdef X11
7671 #ifdef HAVE_XDBE
7672         if (use_xdbe) {
7673                 XdbeSwapInfo swap;
7674
7675                 swap.swap_window = window.window;
7676                 swap.swap_action = XdbeBackground;
7677                 XdbeSwapBuffers(display, &swap, 1);
7678         }
7679 #endif
7680 #endif /* X11 */
7681 }
7682
7683 #ifdef X11
7684 static void clear_text(int exposures)
7685 {
7686 #ifdef HAVE_XDBE
7687         if (use_xdbe) {
7688                 /* The swap action is XdbeBackground, which clears */
7689                 return;
7690         } else
7691 #endif
7692         {
7693                 /* there is some extra space for borders and outlines */
7694                 XClearArea(display, window.window, text_start_x - border_margin - 1,
7695                         text_start_y - border_margin - 1,
7696                         text_width + border_margin * 2 + 2,
7697                         text_height + border_margin * 2 + 2, exposures ? True : 0);
7698         }
7699 }
7700 #endif /* X11 */
7701
7702 static int need_to_update;
7703
7704 /* update_text() generates new text and clears old text area */
7705 static void update_text(void)
7706 {
7707         generate_text();
7708 #ifdef X11
7709         clear_text(1);
7710 #endif /* X11 */
7711         need_to_update = 1;
7712 }
7713
7714 static void main_loop(void)
7715 {
7716 #ifdef SIGNAL_BLOCKING
7717         sigset_t newmask, oldmask;
7718 #endif
7719         double t;
7720 #ifdef X11
7721         Region region = XCreateRegion();
7722
7723 #ifdef HAVE_XDAMAGE
7724         Damage damage;
7725         XserverRegion region2, part;
7726         int event_base, error_base;
7727
7728         if (!XDamageQueryExtension(display, &event_base, &error_base)) {
7729                 ERR("Xdamage extension unavailable");
7730         }
7731         damage = XDamageCreate(display, window.window, XDamageReportNonEmpty);
7732         region2 = XFixesCreateRegionFromWindow(display, window.window, 0);
7733         part = XFixesCreateRegionFromWindow(display, window.window, 0);
7734 #endif /* HAVE_XDAMAGE */
7735 #endif /* X11 */
7736
7737 #ifdef SIGNAL_BLOCKING
7738         sigemptyset(&newmask);
7739         sigaddset(&newmask, SIGINT);
7740         sigaddset(&newmask, SIGTERM);
7741         sigaddset(&newmask, SIGUSR1);
7742 #endif
7743
7744         next_update_time = last_update_time = get_time();
7745         info.looped = 0;
7746         while (total_run_times == 0 || info.looped < total_run_times) {
7747                 info.looped++;
7748
7749 #ifdef SIGNAL_BLOCKING
7750                 /* block signals.  we will inspect for pending signals later */
7751                 if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0) {
7752                         CRIT_ERR("unable to sigprocmask()");
7753                 }
7754 #endif
7755
7756 #ifdef X11
7757                 XFlush(display);
7758
7759                 /* wait for X event or timeout */
7760
7761                 if (!XPending(display)) {
7762                         fd_set fdsr;
7763                         struct timeval tv;
7764                         int s;
7765                         t = next_update_time - get_time();
7766
7767                         if (t < 0) {
7768                                 t = 0;
7769                         } else if (t > update_interval) {
7770                                 t = update_interval;
7771                         }
7772
7773                         tv.tv_sec = (long) t;
7774                         tv.tv_usec = (long) (t * 1000000) % 1000000;
7775                         FD_ZERO(&fdsr);
7776                         FD_SET(ConnectionNumber(display), &fdsr);
7777
7778                         s = select(ConnectionNumber(display) + 1, &fdsr, 0, 0, &tv);
7779                         if (s == -1) {
7780                                 if (errno != EINTR) {
7781                                         ERR("can't select(): %s", strerror(errno));
7782                                 }
7783                         } else {
7784                                 /* timeout */
7785                                 if (s == 0) {
7786 #else
7787                 t = (next_update_time - get_time()) * 1000000;
7788                 usleep((useconds_t)t);
7789 #endif /* X11 */
7790                                         update_text();
7791 #ifdef X11
7792                                 }
7793                         }
7794                 }
7795
7796                 if (need_to_update) {
7797 #ifdef OWN_WINDOW
7798                         int wx = window.x, wy = window.y;
7799 #endif
7800
7801                         need_to_update = 0;
7802                         selected_font = 0;
7803                         update_text_area();
7804 #ifdef OWN_WINDOW
7805                         if (own_window) {
7806                                 /* resize window if it isn't right size */
7807                                 if (!fixed_size
7808                                                 && (text_width + border_margin * 2 + 1 != window.width
7809                                                 || text_height + border_margin * 2 + 1 != window.height)) {
7810                                         window.width = text_width + border_margin * 2 + 1;
7811                                         window.height = text_height + border_margin * 2 + 1;
7812                                         XResizeWindow(display, window.window, window.width,
7813                                                 window.height);
7814                                         if (own_window) {
7815                                                 set_transparent_background(window.window);
7816                                         }
7817                                 }
7818
7819                                 /* move window if it isn't in right position */
7820                                 if (!fixed_pos && (window.x != wx || window.y != wy)) {
7821                                         XMoveWindow(display, window.window, window.x, window.y);
7822                                 }
7823                         }
7824 #endif
7825
7826                         clear_text(1);
7827
7828 #ifdef HAVE_XDBE
7829                         if (use_xdbe) {
7830                                 XRectangle r;
7831
7832                                 r.x = text_start_x - border_margin;
7833                                 r.y = text_start_y - border_margin;
7834                                 r.width = text_width + border_margin * 2;
7835                                 r.height = text_height + border_margin * 2;
7836                                 XUnionRectWithRegion(&r, region, region);
7837                         }
7838 #endif
7839                 }
7840
7841                 /* handle X events */
7842                 while (XPending(display)) {
7843                         XEvent ev;
7844
7845                         XNextEvent(display, &ev);
7846                         switch (ev.type) {
7847                                 case Expose:
7848                                 {
7849                                         XRectangle r;
7850
7851                                         r.x = ev.xexpose.x;
7852                                         r.y = ev.xexpose.y;
7853                                         r.width = ev.xexpose.width;
7854                                         r.height = ev.xexpose.height;
7855                                         XUnionRectWithRegion(&r, region, region);
7856                                         break;
7857                                 }
7858
7859 #ifdef OWN_WINDOW
7860                                 case ReparentNotify:
7861                                         /* set background to ParentRelative for all parents */
7862                                         if (own_window) {
7863                                                 set_transparent_background(window.window);
7864                                         }
7865                                         break;
7866
7867                                 case ConfigureNotify:
7868                                         if (own_window) {
7869                                                 /* if window size isn't what expected, set fixed size */
7870                                                 if (ev.xconfigure.width != window.width
7871                                                                 || ev.xconfigure.height != window.height) {
7872                                                         if (window.width != 0 && window.height != 0) {
7873                                                                 fixed_size = 1;
7874                                                         }
7875
7876                                                         /* clear old stuff before screwing up
7877                                                          * size and pos */
7878                                                         clear_text(1);
7879
7880                                                         {
7881                                                                 XWindowAttributes attrs;
7882
7883                                                                 if (XGetWindowAttributes(display,
7884                                                                                 window.window, &attrs)) {
7885                                                                         window.width = attrs.width;
7886                                                                         window.height = attrs.height;
7887                                                                 }
7888                                                         }
7889
7890                                                         text_width = window.width - border_margin * 2 - 1;
7891                                                         text_height = window.height - border_margin * 2 - 1;
7892                                                         if (text_width > maximum_width
7893                                                                         && maximum_width > 0) {
7894                                                                 text_width = maximum_width;
7895                                                         }
7896                                                 }
7897
7898                                                 /* if position isn't what expected, set fixed pos
7899                                                  * total_updates avoids setting fixed_pos when window
7900                                                  * is set to weird locations when started */
7901                                                 /* // this is broken
7902                                                 if (total_updates >= 2 && !fixed_pos
7903                                                                 && (window.x != ev.xconfigure.x
7904                                                                 || window.y != ev.xconfigure.y)
7905                                                                 && (ev.xconfigure.x != 0
7906                                                                 || ev.xconfigure.y != 0)) {
7907                                                         fixed_pos = 1;
7908                                                 } */
7909                                                 set_font();
7910                                         }
7911                                         break;
7912
7913                                 case ButtonPress:
7914                                         if (own_window) {
7915                                                 /* if an ordinary window with decorations */
7916                                                 if ((window.type == TYPE_NORMAL)
7917                                                                 && (!TEST_HINT(window.hints,
7918                                                                 HINT_UNDECORATED))) {
7919                                                         /* allow conky to hold input focus. */
7920                                                         break;
7921                                                 } else {
7922                                                         /* forward the click to the desktop window */
7923                                                         XUngrabPointer(display, ev.xbutton.time);
7924                                                         ev.xbutton.window = window.desktop;
7925                                                         XSendEvent(display, ev.xbutton.window, False,
7926                                                                 ButtonPressMask, &ev);
7927                                                         XSetInputFocus(display, ev.xbutton.window,
7928                                                                 RevertToParent, ev.xbutton.time);
7929                                                 }
7930                                         }
7931                                         break;
7932
7933                                 case ButtonRelease:
7934                                         if (own_window) {
7935                                                 /* if an ordinary window with decorations */
7936                                                 if ((window.type == TYPE_NORMAL)
7937                                                                 && (!TEST_HINT(window.hints,
7938                                                                 HINT_UNDECORATED))) {
7939                                                         /* allow conky to hold input focus. */
7940                                                         break;
7941                                                 } else {
7942                                                         /* forward the release to the desktop window */
7943                                                         ev.xbutton.window = window.desktop;
7944                                                         XSendEvent(display, ev.xbutton.window, False,
7945                                                                 ButtonReleaseMask, &ev);
7946                                                 }
7947                                         }
7948                                         break;
7949
7950 #endif
7951
7952                                 default:
7953 #ifdef HAVE_XDAMAGE
7954                                         if (ev.type == event_base + XDamageNotify) {
7955                                                 XDamageNotifyEvent *dev = (XDamageNotifyEvent *) &ev;
7956
7957                                                 XFixesSetRegion(display, part, &dev->area, 1);
7958                                                 XFixesUnionRegion(display, region2, region2, part);
7959                                         }
7960 #endif /* HAVE_XDAMAGE */
7961                                         break;
7962                         }
7963                 }
7964
7965 #ifdef HAVE_XDAMAGE
7966                 XDamageSubtract(display, damage, region2, None);
7967                 XFixesSetRegion(display, region2, 0, 0);
7968 #endif /* HAVE_XDAMAGE */
7969
7970                 /* XDBE doesn't seem to provide a way to clear the back buffer without
7971                  * interfering with the front buffer, other than passing XdbeBackground
7972                  * to XdbeSwapBuffers. That means that if we're using XDBE, we need to
7973                  * redraw the text even if it wasn't part of the exposed area. OTOH,
7974                  * if we're not going to call draw_stuff at all, then no swap happens
7975                  * and we can safely do nothing. */
7976
7977                 if (!XEmptyRegion(region)) {
7978 #ifdef HAVE_XDBE
7979                         if (use_xdbe) {
7980                                 XRectangle r;
7981
7982                                 r.x = text_start_x - border_margin;
7983                                 r.y = text_start_y - border_margin;
7984                                 r.width = text_width + border_margin * 2;
7985                                 r.height = text_height + border_margin * 2;
7986                                 XUnionRectWithRegion(&r, region, region);
7987                         }
7988 #endif
7989                         XSetRegion(display, window.gc, region);
7990 #ifdef XFT
7991                         if (use_xft) {
7992                                 XftDrawSetClip(window.xftdraw, region);
7993                         }
7994 #endif
7995 #endif /* X11 */
7996                         draw_stuff();
7997 #ifdef X11
7998                         XDestroyRegion(region);
7999                         region = XCreateRegion();
8000                 }
8001 #endif /* X11 */
8002
8003 #ifdef SIGNAL_BLOCKING
8004                 /* unblock signals of interest and let handler fly */
8005                 if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0) {
8006                         CRIT_ERR("unable to sigprocmask()");
8007                 }
8008 #endif
8009
8010                 switch (g_signal_pending) {
8011                         case SIGHUP:
8012                         case SIGUSR1:
8013                                 ERR("received SIGHUP or SIGUSR1. reloading the config file.");
8014                                 reload_config();
8015                                 break;
8016                         case SIGINT:
8017                         case SIGTERM:
8018                                 ERR("received SIGINT or SIGTERM to terminate. bye!");
8019                                 clean_up();
8020 #ifdef X11
8021                                 XDestroyRegion(region);
8022                                 region = NULL;
8023 #ifdef HAVE_XDAMAGE
8024                                 XDamageDestroy(display, damage);
8025                                 XFixesDestroyRegion(display, region2);
8026                                 XFixesDestroyRegion(display, part);
8027 #endif /* HAVE_XDAMAGE */
8028 #endif /* X11 */
8029                                 return; /* return from main_loop */
8030                                 /* break; */
8031                         default:
8032                                 /* Reaching here means someone set a signal
8033                                  * (SIGXXXX, signal_handler), but didn't write any code
8034                                  * to deal with it.
8035                                  * If you don't want to handle a signal, don't set a handler on
8036                                  * it in the first place. */
8037                                 if (g_signal_pending) {
8038                                         ERR("ignoring signal (%d)", g_signal_pending);
8039                                 }
8040                                 break;
8041                 }
8042                 g_signal_pending = 0;
8043         }
8044
8045 #if defined(X11) && defined(HAVE_XDAMAGE)
8046         XDamageDestroy(display, damage);
8047         XFixesDestroyRegion(display, region2);
8048         XFixesDestroyRegion(display, part);
8049         XDestroyRegion(region);
8050         region = NULL;
8051 #endif /* X11 && HAVE_XDAMAGE */
8052 }
8053
8054 static void load_config_file(const char *);
8055
8056 /* reload the config file */
8057 void reload_config(void)
8058 {
8059         timed_thread_destroy_registered_threads();
8060
8061         if (info.cpu_usage) {
8062                 free(info.cpu_usage);
8063                 info.cpu_usage = NULL;
8064         }
8065
8066         if (info.mail) {
8067                 free(info.mail);
8068         }
8069
8070 #ifdef MPD
8071         if (info.mpd.title) {
8072                 free(info.mpd.title);
8073                 info.mpd.title = NULL;
8074         }
8075         if (info.mpd.artist) {
8076                 free(info.mpd.artist);
8077                 info.mpd.artist = NULL;
8078         }
8079         if (info.mpd.album) {
8080                 free(info.mpd.album);
8081                 info.mpd.album = NULL;
8082         }
8083         if (info.mpd.random) {
8084                 free(info.mpd.random);
8085                 info.mpd.random = NULL;
8086         }
8087         if (info.mpd.repeat) {
8088                 free(info.mpd.repeat);
8089                 info.mpd.repeat = NULL;
8090         }
8091         if (info.mpd.track) {
8092                 free(info.mpd.track);
8093                 info.mpd.track = NULL;
8094         }
8095         if (info.mpd.name) {
8096                 free(info.mpd.name);
8097                 info.mpd.name = NULL;
8098         }
8099         if (info.mpd.file) {
8100                 free(info.mpd.file);
8101                 info.mpd.file = NULL;
8102         }
8103         if (info.mpd.status) {
8104                 free(info.mpd.status);
8105                 info.mpd.status = NULL;
8106         }
8107 #endif
8108
8109 #ifdef MOC
8110   free_moc(&info.moc);
8111 #endif
8112   
8113 #ifdef X11
8114         free_fonts();
8115 #endif /* X11 */
8116
8117 #ifdef TCP_PORT_MONITOR
8118         destroy_tcp_port_monitor_collection(info.p_tcp_port_monitor_collection);
8119 #endif
8120
8121         if (current_config) {
8122                 clear_fs_stats();
8123                 load_config_file(current_config);
8124
8125                 /* re-init specials array */
8126                 if ((specials = realloc((void *) specials,
8127                                 sizeof(struct special_t) * max_specials)) == 0) {
8128                         ERR("failed to realloc specials array");
8129                 }
8130
8131 #ifdef X11
8132                 load_fonts();
8133                 set_font();
8134                 // clear the window first
8135                 XClearWindow(display, RootWindow(display, screen));
8136
8137 #endif /* X11 */
8138 #ifdef TCP_PORT_MONITOR
8139                 info.p_tcp_port_monitor_collection = NULL;
8140 #endif
8141                 extract_variable_text(global_text);
8142                 free(global_text);
8143                 global_text = NULL;
8144                 if (tmpstring1) {
8145                         free(tmpstring1);
8146                 }
8147                 tmpstring1 = malloc(text_buffer_size);
8148                 memset(tmpstring1, 0, text_buffer_size);
8149                 if (tmpstring2) {
8150                         free(tmpstring2);
8151                 }
8152                 tmpstring2 = malloc(text_buffer_size);
8153                 memset(tmpstring2, 0, text_buffer_size);
8154                 if (text_buffer) {
8155                         free(text_buffer);
8156                 }
8157                 text_buffer = malloc(max_user_text);
8158                 memset(text_buffer, 0, max_user_text);
8159                 update_text();
8160         }
8161 }
8162
8163 void clean_up(void)
8164 {
8165         timed_thread_destroy_registered_threads();
8166
8167         if (info.cpu_usage) {
8168                 free(info.cpu_usage);
8169                 info.cpu_usage = NULL;
8170         }
8171 #ifdef X11
8172 #ifdef HAVE_XDBE
8173         if (use_xdbe) {
8174                 XdbeDeallocateBackBufferName(display, window.back_buffer);
8175         }
8176 #endif
8177 #ifdef OWN_WINDOW
8178         if (own_window) {
8179                 XDestroyWindow(display, window.window);
8180                 XClearWindow(display, RootWindow(display, screen));
8181                 XFlush(display);
8182         } else
8183 #endif
8184         {
8185                 XClearWindow(display, RootWindow(display, screen));
8186                 clear_text(1);
8187                 XFlush(display);
8188         }
8189
8190         XFreeGC(display, window.gc);
8191         free_fonts();
8192 #endif /* X11 */
8193
8194         free_text_objects(global_text_object_list, 1);
8195         free(global_text_object_list);
8196         global_text_object_list = NULL;
8197         if (tmpstring1) {
8198                 free(tmpstring1);
8199                 tmpstring1 = 0;
8200         }
8201         if (tmpstring2) {
8202                 free(tmpstring2);
8203                 tmpstring2 = 0;
8204         }
8205         if (text_buffer) {
8206                 free(text_buffer);
8207                 text_buffer = 0;
8208         }
8209
8210         if (global_text) {
8211                 free(global_text);
8212                 global_text = 0;
8213         }
8214
8215         free(current_config);
8216
8217 #ifdef TCP_PORT_MONITOR
8218         destroy_tcp_port_monitor_collection(info.p_tcp_port_monitor_collection);
8219         info.p_tcp_port_monitor_collection = NULL;
8220 #endif
8221 #ifdef RSS
8222         free_rss_info();
8223 #endif
8224
8225         if (specials) {
8226                 unsigned int i;
8227
8228                 for (i = 0; i < special_count; i++) {
8229                         if (specials[i].type == GRAPH) {
8230                                 free(specials[i].graph);
8231                         }
8232                 }
8233                 free(specials);
8234                 specials = NULL;
8235         }
8236
8237         clear_diskio_stats();
8238 }
8239
8240 static int string_to_bool(const char *s)
8241 {
8242         if (!s) {
8243                 // Assumes an option without a true/false means true
8244                 return 1;
8245         } else if (strcasecmp(s, "yes") == EQUAL) {
8246                 return 1;
8247         } else if (strcasecmp(s, "true") == EQUAL) {
8248                 return 1;
8249         } else if (strcasecmp(s, "1") == EQUAL) {
8250                 return 1;
8251         }
8252         return 0;
8253 }
8254
8255 #ifdef X11
8256 static enum alignment string_to_alignment(const char *s)
8257 {
8258         if (strcasecmp(s, "top_left") == EQUAL) {
8259                 return TOP_LEFT;
8260         } else if (strcasecmp(s, "top_right") == EQUAL) {
8261                 return TOP_RIGHT;
8262         } else if (strcasecmp(s, "top_middle") == EQUAL) {
8263                 return TOP_MIDDLE;
8264         } else if (strcasecmp(s, "bottom_left") == EQUAL) {
8265                 return BOTTOM_LEFT;
8266         } else if (strcasecmp(s, "bottom_right") == EQUAL) {
8267                 return BOTTOM_RIGHT;
8268         } else if (strcasecmp(s, "bottom_middle") == EQUAL) {
8269                 return BOTTOM_MIDDLE;
8270         } else if (strcasecmp(s, "middle_left") == EQUAL) {
8271                 return MIDDLE_LEFT;
8272         } else if (strcasecmp(s, "middle_right") == EQUAL) {
8273                 return MIDDLE_RIGHT;
8274         } else if (strcasecmp(s, "tl") == EQUAL) {
8275                 return TOP_LEFT;
8276         } else if (strcasecmp(s, "tr") == EQUAL) {
8277                 return TOP_RIGHT;
8278         } else if (strcasecmp(s, "tm") == EQUAL) {
8279                 return TOP_MIDDLE;
8280         } else if (strcasecmp(s, "bl") == EQUAL) {
8281                 return BOTTOM_LEFT;
8282         } else if (strcasecmp(s, "br") == EQUAL) {
8283                 return BOTTOM_RIGHT;
8284         } else if (strcasecmp(s, "bm") == EQUAL) {
8285                 return BOTTOM_MIDDLE;
8286         } else if (strcasecmp(s, "ml") == EQUAL) {
8287                 return MIDDLE_LEFT;
8288         } else if (strcasecmp(s, "mr") == EQUAL) {
8289                 return MIDDLE_RIGHT;
8290         } else if (strcasecmp(s, "none") == EQUAL) {
8291                 return NONE;
8292         }
8293         return TOP_LEFT;
8294 }
8295 #endif /* X11 */
8296
8297 static void set_default_configurations(void)
8298 {
8299         fork_to_background = 0;
8300         total_run_times = 0;
8301         info.cpu_avg_samples = 2;
8302         info.net_avg_samples = 2;
8303         info.memmax = 0;
8304         top_cpu = 0;
8305         cpu_separate = 0;
8306         short_units = 0;
8307         top_mem = 0;
8308 #ifdef MPD
8309         strcpy(info.mpd.host, "localhost");
8310         info.mpd.port = 6600;
8311         info.mpd.status = NULL;
8312         info.mpd.artist = NULL;
8313         info.mpd.album = NULL;
8314         info.mpd.title = NULL;
8315         info.mpd.random = NULL;
8316         info.mpd.track = NULL;
8317         info.mpd.name = NULL;
8318         info.mpd.file = NULL;
8319 #endif
8320 #ifdef MOC
8321   init_moc(&info.moc);
8322 #endif
8323 #ifdef XMMS2
8324         info.xmms2.artist = NULL;
8325         info.xmms2.album = NULL;
8326         info.xmms2.title = NULL;
8327         info.xmms2.genre = NULL;
8328         info.xmms2.comment = NULL;
8329         info.xmms2.url = NULL;
8330         info.xmms2.status = NULL;
8331         info.xmms2.playlist = NULL;
8332 #endif
8333         use_spacer = NO_SPACER;
8334 #ifdef X11
8335         output_methods = TO_X;
8336 #else
8337         output_methods = TO_STDOUT;
8338 #endif
8339 #ifdef X11
8340         show_graph_scale = 0;
8341         show_graph_range = 0;
8342         default_fg_color = WhitePixel(display, screen);
8343         default_bg_color = BlackPixel(display, screen);
8344         default_out_color = BlackPixel(display, screen);
8345         color0 = default_fg_color;
8346         color1 = default_fg_color;
8347         color2 = default_fg_color;
8348         color3 = default_fg_color;
8349         color4 = default_fg_color;
8350         color5 = default_fg_color;
8351         color6 = default_fg_color;
8352         color7 = default_fg_color;
8353         color8 = default_fg_color;
8354         color9 = default_fg_color;
8355         template[0] = strdup("");
8356         template[1] = strdup("");
8357         template[2] = strdup("");
8358         template[3] = strdup("");
8359         template[4] = strdup("");
8360         template[5] = strdup("");
8361         template[6] = strdup("");
8362         template[7] = strdup("");
8363         template[8] = strdup("");
8364         template[9] = strdup("");
8365         draw_shades = 1;
8366         draw_borders = 0;
8367         draw_graph_borders = 1;
8368         draw_outline = 0;
8369         set_first_font("6x10");
8370         gap_x = 5;
8371         gap_y = 60;
8372         minimum_width = 5;
8373         minimum_height = 5;
8374         maximum_width = 0;
8375 #ifdef OWN_WINDOW
8376         own_window = 0;
8377         window.type = TYPE_NORMAL;
8378         window.hints = 0;
8379         strcpy(window.class_name, PACKAGE_NAME);
8380         update_uname();
8381         sprintf(window.title, PACKAGE_NAME" (%s)", info.uname_s.nodename);
8382 #endif
8383         stippled_borders = 0;
8384         border_margin = 3;
8385         border_width = 1;
8386         text_alignment = BOTTOM_LEFT;
8387         info.x11.monitor.number = 1;
8388         info.x11.monitor.current = 0;
8389 #endif /* X11 */
8390
8391         free(current_mail_spool);
8392         {
8393                 char buf[256];
8394
8395                 variable_substitute(MAIL_FILE, buf, 256);
8396                 if (buf[0] != '\0') {
8397                         current_mail_spool = strndup(buf, text_buffer_size);
8398                 }
8399         }
8400
8401         no_buffers = 1;
8402         update_interval = 3.0;
8403         info.music_player_interval = 1.0;
8404         stuff_in_upper_case = 0;
8405         info.users.number = 1;
8406
8407 #ifdef TCP_PORT_MONITOR
8408         tcp_port_monitor_args.max_port_monitor_connections =
8409                 MAX_PORT_MONITOR_CONNECTIONS_DEFAULT;
8410 #endif
8411 }
8412
8413 static void load_config_file(const char *f)
8414 {
8415 #define CONF_ERR ERR("%s: %d: config file error", f, line)
8416         int line = 0;
8417         FILE *fp;
8418
8419         set_default_configurations();
8420         fp = fopen(f, "r");
8421         if (!fp) {
8422                 return;
8423         }
8424
8425         while (!feof(fp)) {
8426                 char buf[256], *p, *p2, *name, *value;
8427
8428                 line++;
8429                 if (fgets(buf, 256, fp) == NULL) {
8430                         break;
8431                 }
8432
8433                 p = buf;
8434
8435                 /* break at comment */
8436                 p2 = strchr(p, '#');
8437                 if (p2) {
8438                         *p2 = '\0';
8439                 }
8440
8441                 /* skip spaces */
8442                 while (*p && isspace((int) *p)) {
8443                         p++;
8444                 }
8445                 if (*p == '\0') {
8446                         continue;       /* empty line */
8447                 }
8448
8449                 name = p;
8450
8451                 /* skip name */
8452                 p2 = p;
8453                 while (*p2 && !isspace((int) *p2)) {
8454                         p2++;
8455                 }
8456                 if (*p2 != '\0') {
8457                         *p2 = '\0';     /* break at name's end */
8458                         p2++;
8459                 }
8460
8461                 /* get value */
8462                 if (*p2) {
8463                         p = p2;
8464                         while (*p && isspace((int) *p)) {
8465                                 p++;
8466                         }
8467
8468                         value = p;
8469
8470                         p2 = value + strlen(value);
8471                         while (isspace((int) *(p2 - 1))) {
8472                                 *--p2 = '\0';
8473                         }
8474                 } else {
8475                         value = 0;
8476                 }
8477
8478 #define CONF2(a) if (strcasecmp(name, a) == 0)
8479 #define CONF(a) else CONF2(a)
8480 #define CONF3(a, b) else if (strcasecmp(name, a) == 0 \
8481                 || strcasecmp(name, b) == 0)
8482
8483 #ifdef X11
8484                 CONF2("alignment") {
8485                         if (window.type == TYPE_DOCK)
8486                                 ;
8487                         else if (value) {
8488                                 int a = string_to_alignment(value);
8489
8490                                 if (a <= 0) {
8491                                         CONF_ERR;
8492                                 } else {
8493                                         text_alignment = a;
8494                                 }
8495                         } else {
8496                                 CONF_ERR;
8497                         }
8498                 }
8499                 CONF("background") {
8500                         fork_to_background = string_to_bool(value);
8501                 }
8502 #else
8503                 CONF2("background") {
8504                         fork_to_background = string_to_bool(value);
8505                 }
8506 #endif /* X11 */
8507 #ifdef X11
8508                 CONF("show_graph_scale") {
8509                         show_graph_scale = string_to_bool(value);
8510                 }
8511                 CONF("show_graph_range") {
8512                         show_graph_range = string_to_bool(value);
8513                 }
8514                 CONF("border_margin") {
8515                         if (value) {
8516                                 border_margin = strtol(value, 0, 0);
8517                         } else {
8518                                 CONF_ERR;
8519                         }
8520                 }
8521                 CONF("border_width") {
8522                         if (value) {
8523                                 border_width = strtol(value, 0, 0);
8524                         } else {
8525                                 CONF_ERR;
8526                         }
8527                 }
8528                 CONF("color0") {
8529                         if (value) {
8530                                 color0 = get_x11_color(value);
8531                         } else {
8532                                 CONF_ERR;
8533                         }
8534                 }
8535                 CONF("color1") {
8536                         if (value) {
8537                                 color1 = get_x11_color(value);
8538                         } else {
8539                                 CONF_ERR;
8540                         }
8541                 }
8542                 CONF("color2") {
8543                         if (value) {
8544                                 color2 = get_x11_color(value);
8545                         } else {
8546                                 CONF_ERR;
8547                         }
8548                 }
8549                 CONF("color3") {
8550                         if (value) {
8551                                 color3 = get_x11_color(value);
8552                         } else {
8553                                 CONF_ERR;
8554                         }
8555                 }
8556                 CONF("color4") {
8557                         if (value) {
8558                                 color4 = get_x11_color(value);
8559                         } else {
8560                                 CONF_ERR;
8561                         }
8562                 }
8563                 CONF("color5") {
8564                         if (value) {
8565                                 color5 = get_x11_color(value);
8566                         } else {
8567                                 CONF_ERR;
8568                         }
8569                 }
8570                 CONF("color6") {
8571                         if (value) {
8572                                 color6 = get_x11_color(value);
8573                         } else {
8574                                 CONF_ERR;
8575                         }
8576                 }
8577                 CONF("color7") {
8578                         if (value) {
8579                                 color7 = get_x11_color(value);
8580                         } else {
8581                                 CONF_ERR;
8582                         }
8583                 }
8584                 CONF("color8") {
8585                         if (value) {
8586                                 color8 = get_x11_color(value);
8587                         } else {
8588                                 CONF_ERR;
8589                         }
8590                 }
8591                 CONF("color9") {
8592                         if (value) {
8593                                 color9 = get_x11_color(value);
8594                         } else {
8595                                 CONF_ERR;
8596                         }
8597                 }
8598 #define TEMPLATE_CONF(n) \
8599                 CONF("template"#n) { \
8600                         if (value) { \
8601                                 free(template[n]); \
8602                                 template[n] = strdup(value); \
8603                         } else { \
8604                                 CONF_ERR; \
8605                         } \
8606                 }
8607                 TEMPLATE_CONF(0)
8608                 TEMPLATE_CONF(1)
8609                 TEMPLATE_CONF(2)
8610                 TEMPLATE_CONF(3)
8611                 TEMPLATE_CONF(4)
8612                 TEMPLATE_CONF(5)
8613                 TEMPLATE_CONF(6)
8614                 TEMPLATE_CONF(7)
8615                 TEMPLATE_CONF(8)
8616                 TEMPLATE_CONF(9)
8617                 CONF("default_color") {
8618                         if (value) {
8619                                 default_fg_color = get_x11_color(value);
8620                         } else {
8621                                 CONF_ERR;
8622                         }
8623                 }
8624                 CONF3("default_shade_color", "default_shadecolor") {
8625                         if (value) {
8626                                 default_bg_color = get_x11_color(value);
8627                         } else {
8628                                 CONF_ERR;
8629                         }
8630                 }
8631                 CONF3("default_outline_color", "default_outlinecolor") {
8632                         if (value) {
8633                                 default_out_color = get_x11_color(value);
8634                         } else {
8635                                 CONF_ERR;
8636                         }
8637                 }
8638 #endif /* X11 */
8639                 CONF("imap") {
8640                         if (value) {
8641                                 info.mail = parse_mail_args(IMAP, value);
8642                         } else {
8643                                 CONF_ERR;
8644                         }
8645                 }
8646                 CONF("pop3") {
8647                         if (value) {
8648                                 info.mail = parse_mail_args(POP3, value);
8649                         } else {
8650                                 CONF_ERR;
8651                         }
8652                 }
8653 #ifdef MPD
8654                 CONF("mpd_host") {
8655                         if (value) {
8656                                 strncpy(info.mpd.host, value, 127);
8657                         } else {
8658                                 CONF_ERR;
8659                         }
8660                 }
8661                 CONF("mpd_port") {
8662                         if (value) {
8663                                 info.mpd.port = strtol(value, 0, 0);
8664                                 if (info.mpd.port < 1 || info.mpd.port > 0xffff) {
8665                                         CONF_ERR;
8666                                 }
8667                         }
8668                 }
8669                 CONF("mpd_password") {
8670                         if (value) {
8671                                 strncpy(info.mpd.password, value, 127);
8672                         } else {
8673                                 CONF_ERR;
8674                         }
8675                 }
8676 #endif
8677                 CONF("music_player_interval") {
8678                         if (value) {
8679                                 info.music_player_interval = strtod(value, 0);
8680                         } else {
8681                                 CONF_ERR;
8682                         }
8683                 }
8684 #ifdef __OpenBSD__
8685                 CONF("sensor_device") {
8686                         if (value) {
8687                                 sensor_device = strtol(value, 0, 0);
8688                         } else {
8689                                 CONF_ERR;
8690                         }
8691                 }
8692 #endif
8693                 CONF("cpu_avg_samples") {
8694                         if (value) {
8695                                 cpu_avg_samples = strtol(value, 0, 0);
8696                                 if (cpu_avg_samples < 1 || cpu_avg_samples > 14) {
8697                                         CONF_ERR;
8698                                 } else {
8699                                         info.cpu_avg_samples = cpu_avg_samples;
8700                                 }
8701                         } else {
8702                                 CONF_ERR;
8703                         }
8704                 }
8705                 CONF("net_avg_samples") {
8706                         if (value) {
8707                                 net_avg_samples = strtol(value, 0, 0);
8708                                 if (net_avg_samples < 1 || net_avg_samples > 14) {
8709                                         CONF_ERR;
8710                                 } else {
8711                                         info.net_avg_samples = net_avg_samples;
8712                                 }
8713                         } else {
8714                                 CONF_ERR;
8715                         }
8716                 }
8717
8718 #ifdef HAVE_XDBE
8719                 CONF("double_buffer") {
8720                         use_xdbe = string_to_bool(value);
8721                 }
8722 #endif
8723 #ifdef X11
8724                 CONF("override_utf8_locale") {
8725                         utf8_mode = string_to_bool(value);
8726                 }
8727                 CONF("draw_borders") {
8728                         draw_borders = string_to_bool(value);
8729                 }
8730                 CONF("draw_graph_borders") {
8731                         draw_graph_borders = string_to_bool(value);
8732                 }
8733                 CONF("draw_shades") {
8734                         draw_shades = string_to_bool(value);
8735                 }
8736                 CONF("draw_outline") {
8737                         draw_outline = string_to_bool(value);
8738                 }
8739 #endif /* X11 */
8740                 CONF("out_to_console") {
8741                         if(string_to_bool(value)) output_methods |= TO_STDOUT;
8742                 }
8743                 CONF("use_spacer") {
8744                         if (value) {
8745                                 if (strcasecmp(value, "left") == EQUAL) {
8746                                         use_spacer = LEFT_SPACER;
8747                                 } else if (strcasecmp(value, "right") == EQUAL) {
8748                                         use_spacer = RIGHT_SPACER;
8749                                 } else if (strcasecmp(value, "none") == EQUAL) {
8750                                         use_spacer = NO_SPACER;
8751                                 } else {
8752                                         use_spacer = string_to_bool(value);
8753                                         ERR("use_spacer should have an argument of left, right, or"
8754                                                 " none.  '%s' seems to be some form of '%s', so"
8755                                                 " defaulting to %s.", value,
8756                                                 use_spacer ? "true" : "false",
8757                                                 use_spacer ? "right" : "none");
8758                                         if (use_spacer) {
8759                                                 use_spacer = RIGHT_SPACER;
8760                                         } else {
8761                                                 use_spacer = NO_SPACER;
8762                                         }
8763                                 }
8764                         } else {
8765                                 ERR("use_spacer should have an argument. Defaulting to right.");
8766                                 use_spacer = RIGHT_SPACER;
8767                         }
8768                 }
8769 #ifdef X11
8770 #ifdef XFT
8771                 CONF("use_xft") {
8772                         use_xft = string_to_bool(value);
8773                 }
8774                 CONF("font") {
8775                         if (value) {
8776                                 set_first_font(value);
8777                         } else {
8778                                 CONF_ERR;
8779                         }
8780                 }
8781                 CONF("xftalpha") {
8782                         if (value && font_count >= 0) {
8783                                 fonts[0].font_alpha = atof(value) * 65535.0;
8784                         } else {
8785                                 CONF_ERR;
8786                         }
8787                 }
8788                 CONF("xftfont") {
8789                         if (use_xft) {
8790 #else
8791                 CONF("use_xft") {
8792                         if (string_to_bool(value)) {
8793                                 ERR("Xft not enabled");
8794                         }
8795                 }
8796                 CONF("xftfont") {
8797                         /* xftfont silently ignored when no Xft */
8798                 }
8799                 CONF("xftalpha") {
8800                         /* xftalpha is silently ignored when no Xft */
8801                 }
8802                 CONF("font") {
8803 #endif
8804                                 if (value) {
8805                                         set_first_font(value);
8806                                 } else {
8807                                         CONF_ERR;
8808                                 }
8809 #ifdef XFT
8810                         }
8811 #endif
8812                 }
8813                 CONF("gap_x") {
8814                         if (value) {
8815                                 gap_x = atoi(value);
8816                         } else {
8817                                 CONF_ERR;
8818                         }
8819                 }
8820                 CONF("gap_y") {
8821                         if (value) {
8822                                 gap_y = atoi(value);
8823                         } else {
8824                                 CONF_ERR;
8825                         }
8826                 }
8827 #endif /* X11 */
8828                 CONF("mail_spool") {
8829                         if (value) {
8830                                 char buffer[256];
8831
8832                                 variable_substitute(value, buffer, 256);
8833
8834                                 if (buffer[0] != '\0') {
8835                                         if (current_mail_spool) {
8836                                                 free(current_mail_spool);
8837                                         }
8838                                         current_mail_spool = strndup(buffer, text_buffer_size);
8839                                 }
8840                         } else {
8841                                 CONF_ERR;
8842                         }
8843                 }
8844 #ifdef X11
8845                 CONF("minimum_size") {
8846                         if (value) {
8847                                 if (sscanf(value, "%d %d", &minimum_width, &minimum_height)
8848                                                 != 2) {
8849                                         if (sscanf(value, "%d", &minimum_width) != 1) {
8850                                                 CONF_ERR;
8851                                         }
8852                                 }
8853                         } else {
8854                                 CONF_ERR;
8855                         }
8856                 }
8857                 CONF("maximum_width") {
8858                         if (value) {
8859                                 if (sscanf(value, "%d", &maximum_width) != 1) {
8860                                         CONF_ERR;
8861                                 }
8862                         } else {
8863                                 CONF_ERR;
8864                         }
8865                 }
8866 #endif /* X11 */
8867                 CONF("no_buffers") {
8868                         no_buffers = string_to_bool(value);
8869                 }
8870                 CONF("top_cpu_separate") {
8871                         cpu_separate = string_to_bool(value);
8872                 }
8873                 CONF("short_units") {
8874                         short_units = string_to_bool(value);
8875                 }
8876                 CONF("pad_percents") {
8877                         pad_percents = atoi(value);
8878                 }
8879 #ifdef X11
8880 #ifdef OWN_WINDOW
8881                 CONF("own_window") {
8882                         if (value) {
8883                                 own_window = string_to_bool(value);
8884                         } else {
8885                                 CONF_ERR;
8886                         }
8887                 }
8888                 CONF("own_window_class") {
8889                         if (value) {
8890                                 memset(window.class_name, 0, sizeof(window.class_name));
8891                                 strncpy(window.class_name, value,
8892                                         sizeof(window.class_name) - 1);
8893                         } else {
8894                                 CONF_ERR;
8895                         }
8896                 }
8897                 CONF("own_window_title") {
8898                         if (value) {
8899                                 memset(window.title, 0, sizeof(window.title));
8900                                 strncpy(window.title, value, sizeof(window.title) - 1);
8901                         } else {
8902                                 CONF_ERR;
8903                         }
8904                 }
8905                 CONF("own_window_transparent") {
8906                         if (value) {
8907                                 set_transparent = string_to_bool(value);
8908                         } else {
8909                                 CONF_ERR;
8910                         }
8911                 }
8912                 CONF("own_window_colour") {
8913                         if (value) {
8914                                 background_colour = get_x11_color(value);
8915                         } else {
8916                                 ERR("Invalid colour for own_window_colour (try omitting the "
8917                                         "'#' for hex colours");
8918                         }
8919                 }
8920                 CONF("own_window_hints") {
8921                         if (value) {
8922                                 char *p_hint, *p_save;
8923                                 char delim[] = ", ";
8924
8925                                 /* tokenize the value into individual hints */
8926                                 if ((p_hint = strtok_r(value, delim, &p_save)) != NULL) {
8927                                         do {
8928                                                 /* fprintf(stderr, "hint [%s] parsed\n", p_hint); */
8929                                                 if (strncmp(p_hint, "undecorate", 10) == EQUAL) {
8930                                                         SET_HINT(window.hints, HINT_UNDECORATED);
8931                                                 } else if (strncmp(p_hint, "below", 5) == EQUAL) {
8932                                                         SET_HINT(window.hints, HINT_BELOW);
8933                                                 } else if (strncmp(p_hint, "above", 5) == EQUAL) {
8934                                                         SET_HINT(window.hints, HINT_ABOVE);
8935                                                 } else if (strncmp(p_hint, "sticky", 6) == EQUAL) {
8936                                                         SET_HINT(window.hints, HINT_STICKY);
8937                                                 } else if (strncmp(p_hint, "skip_taskbar", 12) == EQUAL) {
8938                                                         SET_HINT(window.hints, HINT_SKIP_TASKBAR);
8939                                                 } else if (strncmp(p_hint, "skip_pager", 10) == EQUAL) {
8940                                                         SET_HINT(window.hints, HINT_SKIP_PAGER);
8941                                                 } else {
8942                                                         CONF_ERR;
8943                                                 }
8944
8945                                                 p_hint = strtok_r(NULL, delim, &p_save);
8946                                         } while (p_hint != NULL);
8947                                 }
8948                         } else {
8949                                 CONF_ERR;
8950                         }
8951                 }
8952                 CONF("own_window_type") {
8953                         if (value) {
8954                                 if (strncmp(value, "normal", 6) == EQUAL) {
8955                                         window.type = TYPE_NORMAL;
8956                                 } else if (strncmp(value, "desktop", 7) == EQUAL) {
8957                                         window.type = TYPE_DESKTOP;
8958                                 } else if (strncmp(value, "dock", 7) == EQUAL) {
8959                                         window.type = TYPE_DOCK;
8960                                         text_alignment = TOP_LEFT;
8961                                 } else if (strncmp(value, "override", 8) == EQUAL) {
8962                                         window.type = TYPE_OVERRIDE;
8963                                 } else {
8964                                         CONF_ERR;
8965                                 }
8966                         } else {
8967                                 CONF_ERR;
8968                         }
8969                 }
8970 #endif
8971                 CONF("stippled_borders") {
8972                         if (value) {
8973                                 stippled_borders = strtol(value, 0, 0);
8974                         } else {
8975                                 stippled_borders = 4;
8976                         }
8977                 }
8978 #endif /* X11 */
8979                 CONF("temp1") {
8980                         ERR("temp1 configuration is obsolete, use ${i2c <i2c device here> "
8981                                 "temp 1}");
8982                 }
8983                 CONF("temp2") {
8984                         ERR("temp2 configuration is obsolete, use ${i2c <i2c device here> "
8985                                 "temp 2}");
8986                 }
8987                 CONF("update_interval") {
8988                         if (value) {
8989                                 update_interval = strtod(value, 0);
8990                         } else {
8991                                 CONF_ERR;
8992                         }
8993                         if (info.music_player_interval == 0) {
8994                                 // default to update_interval
8995                                 info.music_player_interval = update_interval;
8996                         }
8997                 }
8998                 CONF("total_run_times") {
8999                         if (value) {
9000                                 total_run_times = strtod(value, 0);
9001                         } else {
9002                                 CONF_ERR;
9003                         }
9004                 }
9005                 CONF("uppercase") {
9006                         stuff_in_upper_case = string_to_bool(value);
9007                 }
9008                 CONF("max_specials") {
9009                         if (value) {
9010                                 max_specials = atoi(value);
9011                         } else {
9012                                 CONF_ERR;
9013                         }
9014                 }
9015                 CONF("max_user_text") {
9016                         if (value) {
9017                                 max_user_text = atoi(value);
9018                         } else {
9019                                 CONF_ERR;
9020                         }
9021                 }
9022                 CONF("text_buffer_size") {
9023                         if (value) {
9024                                 text_buffer_size = atoi(value);
9025                                 if (text_buffer_size < DEFAULT_TEXT_BUFFER_SIZE) {
9026                                         ERR("text_buffer_size must be >=%i bytes", DEFAULT_TEXT_BUFFER_SIZE);
9027                                         text_buffer_size = DEFAULT_TEXT_BUFFER_SIZE;
9028                                 }
9029                         } else {
9030                                 CONF_ERR;
9031                         }
9032                 }
9033                 CONF("text") {
9034                         if (global_text) {
9035                                 free(global_text);
9036                                 global_text = 0;
9037                         }
9038
9039                         global_text = (char *) malloc(1);
9040                         global_text[0] = '\0';
9041
9042                         while (!feof(fp)) {
9043                                 unsigned int l = strlen(global_text);
9044
9045                                 if (fgets(buf, 256, fp) == NULL) {
9046                                         break;
9047                                 }
9048                                 global_text = (char *) realloc(global_text, l + strlen(buf) + 1);
9049                                 strcat(global_text, buf);
9050
9051                                 if (strlen(global_text) > max_user_text) {
9052                                         break;
9053                                 }
9054                         }
9055                         fclose(fp);
9056                         if (strlen(global_text) < 1) {
9057                                 CRIT_ERR("no text supplied in configuration; exiting");
9058                         }
9059                         global_text_lines = line + 1;
9060                         return;
9061                 }
9062 #ifdef TCP_PORT_MONITOR
9063                 CONF("max_port_monitor_connections") {
9064                         if (!value || (sscanf(value, "%d",
9065                                         &tcp_port_monitor_args.max_port_monitor_connections) != 1)
9066                                         || tcp_port_monitor_args.max_port_monitor_connections < 0) {
9067                                 /* an error. use default, warn and continue. */
9068                                 tcp_port_monitor_args.max_port_monitor_connections =
9069                                         MAX_PORT_MONITOR_CONNECTIONS_DEFAULT;
9070                                 CONF_ERR;
9071                         } else if (tcp_port_monitor_args.max_port_monitor_connections
9072                                         == 0) {
9073                                 /* no error, just use default */
9074                                 tcp_port_monitor_args.max_port_monitor_connections =
9075                                         MAX_PORT_MONITOR_CONNECTIONS_DEFAULT;
9076                         }
9077                         /* else tcp_port_monitor_args.max_port_monitor_connections > 0
9078                          * as per config */
9079                 }
9080 #endif
9081                 CONF("if_up_strictness") {
9082                         if (!value) {
9083                                 ERR("incorrect if_up_strictness value, defaulting to 'up'");
9084                                 ifup_strictness = IFUP_UP;
9085                         } else if (strcasecmp(value, "up") == EQUAL) {
9086                                 ifup_strictness = IFUP_UP;
9087                         } else if (strcasecmp(value, "link") == EQUAL) {
9088                                 ifup_strictness = IFUP_LINK;
9089                         } else if (strcasecmp(value, "address") == EQUAL) {
9090                                 ifup_strictness = IFUP_ADDR;
9091                         } else {
9092                                 ERR("incorrect if_up_strictness value, defaulting to 'up'");
9093                                 ifup_strictness = IFUP_UP;
9094                         }
9095                 }
9096
9097                 CONF("temperature_unit") {
9098                         if (!value) {
9099                                 ERR("config option 'temperature_unit' needs an argument");
9100                         } else if (set_temp_output_unit(value)) {
9101                                 ERR("temperature_unit: incorrect argument");
9102                         }
9103                 }
9104
9105                 else {
9106                         ERR("%s: %d: no such configuration: '%s'", f, line, name);
9107                 }
9108
9109 #undef CONF
9110 #undef CONF2
9111         }
9112
9113         fclose(fp);
9114
9115 #undef CONF_ERR
9116
9117         if (info.music_player_interval == 0) {
9118                 // default to update_interval
9119                 info.music_player_interval = update_interval;
9120         }
9121         if (!global_text) { // didn't supply any text
9122                 CRIT_ERR("missing text block in configuration; exiting");
9123         }
9124 }
9125
9126 static void print_help(const char *prog_name) {
9127         printf("Usage: %s [OPTION]...\n"
9128                         PACKAGE_NAME" is a system monitor that renders text on desktop or to own transparent\n"
9129                         "window. Command line options will override configurations defined in config\n"
9130                         "file.\n"
9131                         "   -v, --version             version\n"
9132                         "   -q, --quiet               quiet mode\n"
9133                         "   -D, --debug               increase debugging output\n"
9134                         "   -c, --config=FILE         config file to load\n"
9135                         "   -d, --daemonize           daemonize, fork to background\n"
9136                         "   -h, --help                help\n"
9137 #ifdef X11
9138                         "   -a, --alignment=ALIGNMENT text alignment on screen, {top,bottom,middle}_{left,right,middle}\n"
9139                         "   -f, --font=FONT           font to use\n"
9140 #ifdef OWN_WINDOW
9141                         "   -o, --own-window          create own window to draw\n"
9142 #endif
9143 #ifdef HAVE_XDBE
9144                         "   -b, --double-buffer       double buffer (prevents flickering)\n"
9145 #endif
9146                         "   -w, --window-id=WIN_ID    window id to draw\n"
9147                         "   -x X                      x position\n"
9148                         "   -y Y                      y position\n"
9149 #endif /* X11 */
9150                         "   -t, --text=TEXT           text to render, remember single quotes, like -t '$uptime'\n"
9151                         "   -u, --interval=SECS       update interval\n"
9152                         "   -i COUNT                  number of times to update "PACKAGE_NAME" (and quit)\n",
9153                         prog_name
9154         );
9155 }
9156
9157 /* : means that character before that takes an argument */
9158 static const char *getopt_string = "vVqdDt:u:i:hc:"
9159 #ifdef X11
9160         "x:y:w:a:f:"
9161 #ifdef OWN_WINDOW
9162         "o"
9163 #endif
9164 #ifdef HAVE_XDBE
9165         "b"
9166 #endif
9167 #endif /* X11 */
9168         ;
9169
9170 static const struct option longopts[] = {
9171         { "help", 0, NULL, 'h' },
9172         { "version", 0, NULL, 'V' },
9173         { "debug", 0, NULL, 'D' },
9174         { "config", 1, NULL, 'c' },
9175         { "daemonize", 0, NULL, 'd' },
9176 #ifdef X11
9177         { "alignment", 1, NULL, 'a' },
9178         { "font", 1, NULL, 'f' },
9179 #ifdef OWN_WINDOW
9180         { "own-window", 0, NULL, 'o' },
9181 #endif
9182 #ifdef HAVE_XDBE
9183         { "double-buffer", 0, NULL, 'b' },
9184 #endif
9185         { "window-id", 1, NULL, 'w' },
9186 #endif /* X11 */
9187         { "text", 1, NULL, 't' },
9188         { "interval", 0, NULL, 'u' },
9189         { 0, 0, 0, 0 }
9190 };
9191
9192 int main(int argc, char **argv)
9193 {
9194 #ifdef X11
9195         char *s, *temp;
9196         unsigned int x;
9197 #endif
9198         struct sigaction act, oact;
9199
9200         g_signal_pending = 0;
9201         memset(&info, 0, sizeof(info));
9202         clear_net_stats();
9203
9204 #ifdef TCP_PORT_MONITOR
9205         tcp_port_monitor_args.max_port_monitor_connections =
9206                 MAX_PORT_MONITOR_CONNECTIONS_DEFAULT;
9207 #endif
9208
9209         /* handle command line parameters that don't change configs */
9210 #ifdef X11
9211         if (((s = getenv("LC_ALL")) && *s) || ((s = getenv("LC_CTYPE")) && *s)
9212                         || ((s = getenv("LANG")) && *s)) {
9213                 temp = (char *) malloc((strlen(s) + 1) * sizeof(char));
9214                 if (temp == NULL) {
9215                         ERR("malloc failed");
9216                 }
9217                 for (x = 0; x < strlen(s); x++) {
9218                         temp[x] = tolower(s[x]);
9219                 }
9220                 temp[x] = 0;
9221                 if (strstr(temp, "utf-8") || strstr(temp, "utf8")) {
9222                         utf8_mode = 1;
9223                 }
9224
9225                 free(temp);
9226         }
9227         if (!setlocale(LC_CTYPE, "")) {
9228                 ERR("Can't set the specified locale!\nCheck LANG, LC_CTYPE, LC_ALL.");
9229         }
9230 #endif /* X11 */
9231         while (1) {
9232                 int c = getopt_long(argc, argv, getopt_string, longopts, NULL);
9233
9234                 if (c == -1) {
9235                         break;
9236                 }
9237
9238                 switch (c) {
9239                         case 'v':
9240                         case 'V':
9241                                 print_version();
9242                         case 'c':
9243                                 if (current_config) {
9244                                         free(current_config);
9245                                 }
9246                                 current_config = strndup(optarg, max_user_text);
9247                                 break;
9248                         case 'q':
9249                                 freopen("/dev/null", "w", stderr);
9250                                 break;
9251                         case 'h':
9252                                 print_help(argv[0]);
9253                                 return 0;
9254 #ifdef X11
9255                         case 'w':
9256                                 window.window = strtol(optarg, 0, 0);
9257                                 break;
9258 #endif /* X11 */
9259
9260                         case '?':
9261                                 exit(EXIT_FAILURE);
9262                 }
9263         }
9264 #ifdef X11
9265         /* initalize X BEFORE we load config.
9266          * (we need to so that 'screen' is set) */
9267         init_X11();
9268 #endif /* X11 */
9269
9270         /* check if specified config file is valid */
9271         if (current_config) {
9272                 struct stat sb;
9273                 if (stat(current_config, &sb) ||
9274                                 (!S_ISREG(sb.st_mode) && !S_ISLNK(sb.st_mode))) {
9275                         ERR("invalid configuration file '%s'\n", current_config);
9276                         free(current_config);
9277                         current_config = 0;
9278                 }
9279         }
9280
9281         /* load current_config, CONFIG_FILE or SYSTEM_CONFIG_FILE */
9282
9283         if (!current_config) {
9284                 /* load default config file */
9285                 char buf[256];
9286                 FILE *fp;
9287
9288                 /* Try to use personal config file first */
9289                 variable_substitute(CONFIG_FILE, buf, sizeof(buf));
9290                 if (buf[0] && (fp = fopen(buf, "r"))) {
9291                         current_config = strndup(buf, max_user_text);
9292                         fclose(fp);
9293                 }
9294
9295                 /* Try to use system config file if personal config not readable */
9296                 if (!current_config && (fp = fopen(SYSTEM_CONFIG_FILE, "r"))) {
9297                         current_config = strndup(SYSTEM_CONFIG_FILE, max_user_text);
9298                         fclose(fp);
9299                 }
9300
9301                 /* No readable config found */
9302                 if (!current_config) {
9303                         CRIT_ERR("no readable personal or system-wide config file found");
9304                 }
9305         }
9306
9307         load_config_file(current_config);
9308
9309         /* init specials array */
9310         if ((specials = calloc(sizeof(struct special_t), max_specials)) == 0) {
9311                 ERR("failed to create specials array");
9312         }
9313
9314 #ifdef MAIL_FILE
9315         if (current_mail_spool == NULL) {
9316                 char buf[256];
9317
9318                 variable_substitute(MAIL_FILE, buf, 256);
9319
9320                 if (buf[0] != '\0') {
9321                         current_mail_spool = strndup(buf, text_buffer_size);
9322                 }
9323         }
9324 #endif
9325
9326         /* handle other command line arguments */
9327
9328 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__) \
9329                 || defined(__NetBSD__)
9330         optind = optreset = 1;
9331 #else
9332         optind = 0;
9333 #endif
9334
9335 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
9336         if ((kd = kvm_open("/dev/null", "/dev/null", "/dev/null", O_RDONLY,
9337                         "kvm_open")) == NULL) {
9338                 CRIT_ERR("cannot read kvm");
9339         }
9340 #endif
9341
9342         while (1) {
9343                 int c = getopt_long(argc, argv, getopt_string, longopts, NULL);
9344
9345                 if (c == -1) {
9346                         break;
9347                 }
9348
9349                 switch (c) {
9350                         case 'd':
9351                                 fork_to_background = 1;
9352                                 break;
9353                         case 'D':
9354                                 global_debug_level++;
9355                                 break;
9356 #ifdef X11
9357                         case 'f':
9358                                 set_first_font(optarg);
9359                                 break;
9360                         case 'a':
9361                                 text_alignment = string_to_alignment(optarg);
9362                                 break;
9363
9364 #ifdef OWN_WINDOW
9365                         case 'o':
9366                                 own_window = 1;
9367                                 break;
9368 #endif
9369 #ifdef HAVE_XDBE
9370                         case 'b':
9371                                 use_xdbe = 1;
9372                                 break;
9373 #endif
9374 #endif /* X11 */
9375                         case 't':
9376                                 if (global_text) {
9377                                         free(global_text);
9378                                         global_text = 0;
9379                                 }
9380                                 global_text = strndup(optarg, max_user_text);
9381                                 convert_escapes(global_text);
9382                                 break;
9383
9384                         case 'u':
9385                                 update_interval = strtod(optarg, 0);
9386                                 if (info.music_player_interval == 0) {
9387                                         // default to update_interval
9388                                         info.music_player_interval = update_interval;
9389                                 }
9390                                 break;
9391
9392                         case 'i':
9393                                 total_run_times = strtod(optarg, 0);
9394                                 break;
9395 #ifdef X11
9396                         case 'x':
9397                                 gap_x = atoi(optarg);
9398                                 break;
9399
9400                         case 'y':
9401                                 gap_y = atoi(optarg);
9402                                 break;
9403 #endif /* X11 */
9404
9405                         case '?':
9406                                 exit(EXIT_FAILURE);
9407                 }
9408         }
9409
9410 #ifdef X11
9411         /* load font */
9412         load_fonts();
9413 #endif /* X11 */
9414
9415         /* generate text and get initial size */
9416         extract_variable_text(global_text);
9417         if (global_text) {
9418                 free(global_text);
9419                 global_text = 0;
9420         }
9421         global_text = NULL;
9422         /* fork */
9423         if (fork_to_background) {
9424                 int pid = fork();
9425
9426                 switch (pid) {
9427                         case -1:
9428                                 ERR(PACKAGE_NAME": couldn't fork() to background: %s",
9429                                         strerror(errno));
9430                                 break;
9431
9432                         case 0:
9433                                 /* child process */
9434                                 usleep(25000);
9435                                 fprintf(stderr, "\n");
9436                                 fflush(stderr);
9437                                 break;
9438
9439                         default:
9440                                 /* parent process */
9441                                 fprintf(stderr, PACKAGE_NAME": forked to background, pid is %d\n",
9442                                         pid);
9443                                 fflush(stderr);
9444                                 return 0;
9445                 }
9446         }
9447
9448         text_buffer = malloc(max_user_text);
9449         memset(text_buffer, 0, max_user_text);
9450         tmpstring1 = malloc(text_buffer_size);
9451         memset(tmpstring1, 0, text_buffer_size);
9452         tmpstring2 = malloc(text_buffer_size);
9453         memset(tmpstring2, 0, text_buffer_size);
9454
9455 #ifdef X11
9456         selected_font = 0;
9457         update_text_area();     /* to get initial size of the window */
9458
9459 #ifdef OWN_WINDOW
9460         init_window(own_window, text_width + border_margin * 2 + 1,
9461                 text_height + border_margin * 2 + 1, set_transparent, background_colour,
9462                 argv, argc);
9463 #else /* OWN_WINDOW */
9464         init_window(0, text_width + border_margin * 2 + 1,
9465                 text_height + border_margin * 2 + 1, set_transparent, 0,
9466                 argv, argc);
9467 #endif /* OWN_WINDOW */
9468
9469         selected_font = 0;
9470         update_text_area();     /* to position text/window on screen */
9471
9472 #ifdef OWN_WINDOW
9473         if (own_window && !fixed_pos) {
9474                 XMoveWindow(display, window.window, window.x, window.y);
9475         }
9476         if (own_window) {
9477                 set_transparent_background(window.window);
9478         }
9479 #endif
9480
9481         create_gc();
9482
9483         set_font();
9484         draw_stuff();
9485 #endif /* X11 */
9486
9487         /* Set signal handlers */
9488         act.sa_handler = signal_handler;
9489         sigemptyset(&act.sa_mask);
9490         act.sa_flags = 0;
9491 #ifdef SA_RESTART
9492         act.sa_flags |= SA_RESTART;
9493 #endif
9494
9495         if (            sigaction(SIGINT,  &act, &oact) < 0
9496                         ||      sigaction(SIGUSR1, &act, &oact) < 0
9497                         ||      sigaction(SIGHUP,  &act, &oact) < 0
9498                         ||      sigaction(SIGTERM, &act, &oact) < 0) {
9499                 ERR("error setting signal handler: %s", strerror(errno));
9500         }
9501
9502         main_loop();
9503
9504 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
9505         kvm_close(kd);
9506 #endif
9507
9508         return 0;
9509 }
9510
9511 void signal_handler(int sig)
9512 {
9513         /* signal handler is light as a feather, as it should be.
9514          * we will poll g_signal_pending with each loop of conky
9515          * and do any signal processing there, NOT here. */
9516         g_signal_pending = sig;
9517 }