Fix window width calculation when $lua returns newlines
[monky] / src / conky.c
1 /* -*- mode: c; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: t -*-
2  *
3  * Conky, a system monitor, based on torsmo
4  *
5  * Any original torsmo code is licensed under the BSD license
6  *
7  * All code written since the fork of torsmo is licensed under the GPL
8  *
9  * Please see COPYING for details
10  *
11  * Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
12  * Copyright (c) 2005-2009 Brenden Matthews, Philip Kovacs, et. al.
13  *      (see AUTHORS)
14  * All rights reserved.
15  *
16  * This program is free software: you can redistribute it and/or modify
17  * it under the terms of the GNU General Public License as published by
18  * the Free Software Foundation, either version 3 of the License, or
19  * (at your option) any later version.
20  *
21  * This program is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24  * GNU General Public License for more details.
25  * You should have received a copy of the GNU General Public License
26  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
27  *
28  * vim: ts=4 sw=4 noet ai cindent syntax=c
29  *
30  */
31
32 #include "config.h"
33 #include "text_object.h"
34 #include "conky.h"
35 #include "common.h"
36 #include <stdarg.h>
37 #include <math.h>
38 #include <time.h>
39 #include <locale.h>
40 #include <signal.h>
41 #include <errno.h>
42 #include <limits.h>
43 #if HAVE_DIRENT_H
44 #include <dirent.h>
45 #endif
46 #include <sys/time.h>
47 #include <sys/param.h>
48 #ifdef HAVE_SYS_INOTIFY_H
49 #include <sys/inotify.h>
50 #endif /* HAVE_SYS_INOTIFY_H */
51 #ifdef X11
52 #include "x11.h"
53 #include <X11/Xutil.h>
54 #ifdef HAVE_XDAMAGE
55 #include <X11/extensions/Xdamage.h>
56 #endif
57 #ifdef IMLIB2
58 #include "imlib2.h"
59 #endif /* IMLIB2 */
60 #endif /* X11 */
61 #include <sys/types.h>
62 #include <sys/stat.h>
63 #include <netinet/in.h>
64 #include <netdb.h>
65 #include <fcntl.h>
66 #include <getopt.h>
67 #ifdef NCURSES
68 #include <ncurses.h>
69 #endif
70 #ifdef XOAP
71 #include <libxml/parser.h>
72 #endif /* XOAP */
73
74 /* local headers */
75 #include "core.h"
76 #include "algebra.h"
77 #include "build.h"
78 #include "colours.h"
79 #include "diskio.h"
80 #ifdef X11
81 #include "fonts.h"
82 #endif
83 #include "fs.h"
84 #include "logging.h"
85 #include "mixer.h"
86 #include "mail.h"
87 #include "mboxscan.h"
88 #include "specials.h"
89 #include "temphelper.h"
90 #include "template.h"
91 #include "tailhead.h"
92 #include "top.h"
93
94 /* check for OS and include appropriate headers */
95 #if defined(__linux__)
96 #include "linux.h"
97 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
98 #include "freebsd.h"
99 #elif defined(__OpenBSD__)
100 #include "openbsd.h"
101 #endif
102
103 #if defined(__FreeBSD_kernel__)
104 #include <bsd/bsd.h>
105 #endif
106
107 /* FIXME: apm_getinfo is unused here. maybe it's meant for common.c */
108 #if (defined(__FreeBSD__) || defined(__FreeBSD_kernel__) \
109                 || defined(__OpenBSD__)) && (defined(i386) || defined(__i386__))
110 int apm_getinfo(int fd, apm_info_t aip);
111 char *get_apm_adapter(void);
112 char *get_apm_battery_life(void);
113 char *get_apm_battery_time(void);
114 #endif
115
116 #ifdef CONFIG_OUTPUT
117 #include "defconfig.h"
118 #include "conf_cookie.h"
119 #endif
120
121 #ifndef S_ISSOCK
122 #define S_ISSOCK(x)   ((x & S_IFMT) == S_IFSOCK)
123 #endif
124
125 #define MAIL_FILE "$MAIL"
126 #define MAX_IF_BLOCK_DEPTH 5
127
128 //#define SIGNAL_BLOCKING
129 #undef SIGNAL_BLOCKING
130
131 /* debugging level, used by logging.h */
132 int global_debug_level = 0;
133
134 /* two strings for internal use */
135 static char *tmpstring1, *tmpstring2;
136
137 /* variables holding various config settings */
138 int short_units;
139 int format_human_readable;
140 int cpu_separate;
141 enum {
142         NO_SPACER = 0,
143         LEFT_SPACER,
144         RIGHT_SPACER
145 } use_spacer;
146 int top_cpu, top_mem, top_time;
147 #ifdef IOSTATS
148 int top_io;
149 #endif
150 #ifdef __linux__
151 int top_running;
152 #endif
153 static unsigned int top_name_width = 15;
154 int output_methods;
155 static int extra_newline;
156 enum x_initialiser_state x_initialised = NO;
157 static volatile int g_signal_pending;
158 /* Update interval */
159 double update_interval;
160 double update_interval_old;
161 double update_interval_bat;
162 void *global_cpu = NULL;
163 pid_t childpid = 0;
164
165 int argc_copy;
166 char** argv_copy;
167
168 /* prototypes for internally used functions */
169 static void signal_handler(int);
170 static void print_version(void) __attribute__((noreturn));
171 static void reload_config(void);
172 static void generate_text_internal(char *, int, struct text_object,
173                                    struct information *);
174
175 static void print_version(void)
176 {
177         printf(PACKAGE_NAME" "VERSION" compiled "BUILD_DATE" for "BUILD_ARCH"\n");
178
179         printf("\nCompiled in features:\n\n"
180                    "System config file: "SYSTEM_CONFIG_FILE"\n"
181                    "Package library path: "PACKAGE_LIBDIR"\n\n"
182 #ifdef X11
183                    " X11:\n"
184 # ifdef HAVE_XDAMAGE
185                    "  * Xdamage extension\n"
186 # endif /* HAVE_XDAMAGE */
187 # ifdef HAVE_XDBE
188                    "  * XDBE (double buffer extension)\n"
189 # endif /* HAVE_XDBE */
190 # ifdef XFT
191                    "  * Xft\n"
192 # endif /* XFT */
193 #endif /* X11 */
194                    "\n Music detection:\n"
195 #ifdef AUDACIOUS
196                    "  * Audacious\n"
197 #endif /* AUDACIOUS */
198 #ifdef BMPX
199                    "  * BMPx\n"
200 #endif /* BMPX */
201 #ifdef MPD
202                    "  * MPD\n"
203 #endif /* MPD */
204 #ifdef MOC
205                    "  * MOC\n"
206 #endif /* MOC */
207 #ifdef XMMS2
208                    "  * XMMS2\n"
209 #endif /* XMMS2 */
210                    "\n General:\n"
211 #ifdef HAVE_OPENMP
212                    "  * OpenMP\n"
213 #endif /* HAVE_OPENMP */
214 #ifdef MATH
215                    "  * math\n"
216 #endif /* Math */
217 #ifdef HDDTEMP
218                    "  * hddtemp\n"
219 #endif /* HDDTEMP */
220 #ifdef TCP_PORT_MONITOR
221                    "  * portmon\n"
222 #endif /* TCP_PORT_MONITOR */
223 #ifdef HAVE_CURL
224                    "  * Curl\n"
225 #endif /* HAVE_CURL */
226 #ifdef RSS
227                    "  * RSS\n"
228 #endif /* RSS */
229 #ifdef WEATHER
230                    "  * Weather (METAR)\n"
231 #ifdef XOAP
232                    "  * Weather (XOAP)\n"
233 #endif /* XOAP */
234 #endif /* WEATHER */
235 #ifdef HAVE_IWLIB
236                    "  * wireless\n"
237 #endif /* HAVE_IWLIB */
238 #ifdef IBM
239                    "  * support for IBM/Lenovo notebooks\n"
240 #endif /* IBM */
241 #ifdef NVIDIA
242                    "  * nvidia\n"
243 #endif /* NVIDIA */
244 #ifdef EVE
245                    "  * eve-online\n"
246 #endif /* EVE */
247 #ifdef CONFIG_OUTPUT
248                    "  * config-output\n"
249 #endif /* CONFIG_OUTPUT */
250 #ifdef IMLIB2
251                    "  * Imlib2\n"
252 #endif /* IMLIB2 */
253 #ifdef MIXER_IS_ALSA
254                    "  * ALSA mixer support\n"
255 #endif /* MIXER_IS_ALSA */
256 #ifdef APCUPSD
257                    "  * apcupsd\n"
258 #endif /* APCUPSD */
259 #ifdef IOSTATS
260                    "  * iostats\n"
261 #endif /* IOSTATS */
262 #ifdef HAVE_LUA
263                    "  * Lua\n"
264                    "\n  Lua bindings:\n"
265 #ifdef HAVE_LUA_CAIRO
266                    "   * Cairo\n"
267 #endif /* HAVE_LUA_CAIRO */
268 #ifdef HAVE_LUA_IMLIB2
269                    "   * Imlib2\n"
270 #endif /* IMLIB2 */
271 #endif /* HAVE_LUA */
272         );
273
274         exit(EXIT_SUCCESS);
275 }
276
277 static const char *suffixes[] = { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "" };
278
279
280 #ifdef X11
281
282 static void X11_create_window(void);
283 static void X11_initialisation(void);
284
285 struct _x11_stuff_s {
286         Region region;
287 #ifdef HAVE_XDAMAGE
288         Damage damage;
289         XserverRegion region2, part;
290         int event_base, error_base;
291 #endif
292 } x11_stuff;
293
294 /* text size */
295
296 static int text_start_x, text_start_y;  /* text start position in window */
297 static int text_width, text_height;
298
299 /* alignments */
300 enum alignment {
301         TOP_LEFT = 1,
302         TOP_RIGHT,
303         TOP_MIDDLE,
304         BOTTOM_LEFT,
305         BOTTOM_RIGHT,
306         BOTTOM_MIDDLE,
307         MIDDLE_LEFT,
308         MIDDLE_RIGHT,
309         NONE
310 };
311
312 /* display to connect to */
313 static char *disp = NULL;
314
315 #endif /* X11 */
316
317 /* struct that has all info to be shared between
318  * instances of the same text object */
319 struct information info;
320
321 /* path to config file */
322 char *current_config;
323
324 /* set to 1 if you want all text to be in uppercase */
325 static unsigned int stuff_in_uppercase;
326
327 /* Run how many times? */
328 static unsigned long total_run_times;
329
330 /* fork? */
331 static int fork_to_background;
332
333 static int cpu_avg_samples, net_avg_samples, diskio_avg_samples;
334
335 /* filenames for output */
336 char *overwrite_file = NULL; FILE *overwrite_fpointer = NULL;
337 char *append_file = NULL; FILE *append_fpointer = NULL;
338
339 #ifdef X11
340
341 static int show_graph_scale;
342 static int show_graph_range;
343
344 /* Position on the screen */
345 static int text_alignment;
346 static int gap_x, gap_y;
347
348 /* border */
349 static int draw_borders;
350 static int draw_graph_borders;
351 static int stippled_borders;
352
353 int get_stippled_borders(void)
354 {
355         return stippled_borders;
356 }
357
358 static int draw_shades, draw_outline;
359
360 long default_fg_color, default_bg_color, default_out_color;
361
362 /* create own window or draw stuff to root? */
363 static int set_transparent = 0;
364
365 #ifdef OWN_WINDOW
366 static int own_window = 0;
367 static int background_colour = 0;
368
369 /* fixed size/pos is set if wm/user changes them */
370 static int fixed_size = 0, fixed_pos = 0;
371 #endif
372
373 static int minimum_width, minimum_height;
374 static int maximum_width;
375
376 #endif /* X11 */
377
378 #ifdef __OpenBSD__
379 static int sensor_device;
380 #endif
381
382 long color0, color1, color2, color3, color4, color5, color6, color7, color8,
383          color9;
384
385 /* maximum size of config TEXT buffer, i.e. below TEXT line. */
386 unsigned int max_user_text;
387
388 /* maximum size of individual text buffers, ie $exec buffer size */
389 unsigned int text_buffer_size = DEFAULT_TEXT_BUFFER_SIZE;
390
391 /* UTF-8 */
392 int utf8_mode = 0;
393
394 /* no buffers in used memory? */
395 int no_buffers;
396
397 /* pad percentages to decimals? */
398 static int pad_percents = 0;
399
400 static char *global_text = 0;
401
402 char *get_global_text(void)
403 {
404         return global_text;
405 }
406
407 long global_text_lines;
408
409 static int total_updates;
410 static int updatereset;
411
412 void set_updatereset(int i)
413 {
414         updatereset = i;
415 }
416
417 int get_updatereset(void)
418 {
419         return updatereset;
420 }
421
422 int check_contains(char *f, char *s)
423 {
424         int ret = 0;
425         FILE *where = open_file(f, 0);
426
427         if (where) {
428                 char buf1[256];
429
430                 while (fgets(buf1, 256, where)) {
431                         if (strstr(buf1, s)) {
432                                 ret = 1;
433                                 break;
434                         }
435                 }
436                 fclose(where);
437         } else {
438                 NORM_ERR("Could not open the file");
439         }
440         return ret;
441 }
442
443 #define SECRIT_MULTILINE_CHAR '\x02'
444
445 #ifdef X11
446
447 static inline int calc_text_width(const char *s, int l)
448 {
449         if ((output_methods & TO_X) == 0) {
450                 return 0;
451         }
452 #ifdef XFT
453         if (use_xft) {
454                 XGlyphInfo gi;
455
456                 if (utf8_mode) {
457                         XftTextExtentsUtf8(display, fonts[selected_font].xftfont,
458                                 (const FcChar8 *) s, l, &gi);
459                 } else {
460                         XftTextExtents8(display, fonts[selected_font].xftfont,
461                                 (const FcChar8 *) s, l, &gi);
462                 }
463                 return gi.xOff;
464         } else
465 #endif
466         {
467                 return XTextWidth(fonts[selected_font].font, s, l);
468         }
469 }
470 #endif /* X11 */
471
472 /* formatted text to render on screen, generated in generate_text(),
473  * drawn in draw_stuff() */
474
475 static char *text_buffer;
476
477 /* quite boring functions */
478
479 static inline void for_each_line(char *b, int f(char *, int))
480 {
481         char *ps, *pe;
482         int special_index = 0; /* specials index */
483
484         for (ps = b, pe = b; *pe; pe++) {
485                 if (*pe == '\n') {
486                         *pe = '\0';
487                         special_index = f(ps, special_index);
488                         *pe = '\n';
489                         ps = pe + 1;
490                 }
491         }
492
493         if (ps < pe) {
494                 f(ps, special_index);
495         }
496 }
497
498 static void convert_escapes(char *buf)
499 {
500         char *p = buf, *s = buf;
501
502         while (*s) {
503                 if (*s == '\\') {
504                         s++;
505                         if (*s == 'n') {
506                                 *p++ = '\n';
507                         } else if (*s == '\\') {
508                                 *p++ = '\\';
509                         }
510                         s++;
511                 } else {
512                         *p++ = *s++;
513                 }
514         }
515         *p = '\0';
516 }
517
518 /* Prints anything normally printed with snprintf according to the current value
519  * of use_spacer.  Actually slightly more flexible than snprintf, as you can
520  * safely specify the destination buffer as one of your inputs.  */
521 int spaced_print(char *buf, int size, const char *format, int width, ...)
522 {
523         int len = 0;
524         va_list argp;
525         char *tempbuf;
526
527         if (size < 1) {
528                 return 0;
529         }
530         tempbuf = malloc(size * sizeof(char));
531
532         // Passes the varargs along to vsnprintf
533         va_start(argp, width);
534         vsnprintf(tempbuf, size, format, argp);
535         va_end(argp);
536
537         switch (use_spacer) {
538                 case NO_SPACER:
539                         len = snprintf(buf, size, "%s", tempbuf);
540                         break;
541                 case LEFT_SPACER:
542                         len = snprintf(buf, size, "%*s", width, tempbuf);
543                         break;
544                 case RIGHT_SPACER:
545                         len = snprintf(buf, size, "%-*s", width, tempbuf);
546                         break;
547         }
548         free(tempbuf);
549         return len;
550 }
551
552 /* print percentage values
553  *
554  * - i.e., unsigned values between 0 and 100
555  * - respect the value of pad_percents */
556 static int percent_print(char *buf, int size, unsigned value)
557 {
558         return spaced_print(buf, size, "%u", pad_percents, value);
559 }
560
561 /* converts from bytes to human readable format (K, M, G, T)
562  *
563  * The algorithm always divides by 1024, as unit-conversion of byte
564  * counts suggests. But for output length determination we need to
565  * compare with 1000 here, as we print in decimal form. */
566 static void human_readable(long long num, char *buf, int size)
567 {
568         const char **suffix = suffixes;
569         float fnum;
570         int precision;
571         int width;
572         const char *format;
573
574         /* Possibly just output as usual, for example for stdout usage */
575         if (!format_human_readable) {
576                 spaced_print(buf, size, "%d", 6, round_to_int(num));
577                 return;
578         }
579         if (short_units) {
580                 width = 5;
581                 format = "%.*f%.1s";
582         } else {
583                 width = 7;
584                 format = "%.*f%-3s";
585         }
586
587         if (llabs(num) < 1000LL) {
588                 spaced_print(buf, size, format, width, 0, (float)num, *suffix);
589                 return;
590         }
591
592         while (llabs(num / 1024) >= 1000LL && **(suffix + 2)) {
593                 num /= 1024;
594                 suffix++;
595         }
596
597         suffix++;
598         fnum = num / 1024.0;
599
600         /* fnum should now be < 1000, so looks like 'AAA.BBBBB'
601          *
602          * The goal is to always have a significance of 3, by
603          * adjusting the decimal part of the number. Sample output:
604          *  123MiB
605          * 23.4GiB
606          * 5.12B   
607          * so the point of alignment resides between number and unit. The
608          * upside of this is that there is minimal padding necessary, though
609          * there should be a way to make alignment take place at the decimal
610          * dot (then with fixed width decimal part). 
611          *
612          * Note the repdigits below: when given a precision value, printf()
613          * rounds the float to it, not just cuts off the remaining digits. So
614          * e.g. 99.95 with a precision of 1 gets 100.0, which again should be
615          * printed with a precision of 0. Yay. */
616
617         precision = 0;          /* print 100-999 without decimal part */
618         if (fnum < 99.95)
619                 precision = 1;  /* print 10-99 with one decimal place */
620         if (fnum < 9.995)
621                 precision = 2;  /* print 0-9 with two decimal places */
622
623         spaced_print(buf, size, format, width, precision, fnum, *suffix);
624 }
625
626 /* global object list root element */
627 static struct text_object global_root_object;
628
629 //our own implementation of popen, the difference : the value of 'childpid' will be filled with
630 //the pid of the running 'command'. This is useful if want to kill it when it hangs while reading
631 //or writing to it. We have to kill it because pclose will wait until the process dies by itself
632 FILE* pid_popen(const char *command, const char *mode, pid_t *child) {
633         int ends[2];
634         int parentend, childend;
635
636         //by running pipe after the strcmp's we make sure that we don't have to create a pipe
637         //and close the ends if mode is something illegal
638         if(strcmp(mode, "r") == 0) {
639                 if(pipe(ends) != 0) {
640                         return NULL;
641                 }
642                 parentend = ends[0];
643                 childend = ends[1];
644         } else if(strcmp(mode, "w") == 0) {
645                 if(pipe(ends) != 0) {
646                         return NULL;
647                 }
648                 parentend = ends[1];
649                 childend = ends[0];
650         } else {
651                 return NULL;
652         }
653         *child = fork();
654         if(*child == -1) {
655                 close(parentend);
656                 close(childend);
657                 return NULL;
658         } else if(*child > 0) {
659                 close(childend);
660                 waitpid(*child, NULL, 0);
661         } else {
662                 //don't read from both stdin and pipe or write to both stdout and pipe
663                 if(childend == ends[0]) {
664                         close(0);
665                 } else {
666                         close(1);
667                 }
668                 dup(childend);  //by dupping childend, the returned fd will have close-on-exec turned off
669                 execl("/bin/sh", "sh", "-c", command, (char *) NULL);
670                 _exit(EXIT_FAILURE); //child should die here, (normally execl will take care of this but it can fail) 
671         }
672         return fdopen(parentend, mode);
673 }
674
675 static inline void read_exec(const char *data, char *buf, const int size)
676 {
677         FILE *fp;
678
679         alarm(update_interval);
680         fp = pid_popen(data, "r", &childpid);
681         if(fp) {
682                 int length;
683
684                 length = fread(buf, 1, size, fp);
685                 pclose(fp);
686                 buf[length] = '\0';
687                 if (length > 0 && buf[length - 1] == '\n') {
688                         buf[length - 1] = '\0';
689                 }
690         } else {
691                 buf[0] = '\0';
692         }
693         alarm(0);
694 }
695
696 void do_read_exec(const char *data, char *buf, const int size)
697 {
698         read_exec(data, buf, size);
699 }
700
701 void *threaded_exec(void *) __attribute__((noreturn));
702
703 void *threaded_exec(void *arg)
704 {
705         char *buff, *p2;
706         struct text_object *obj = (struct text_object *)arg;
707
708         while (1) {
709                 buff = malloc(text_buffer_size);
710                 read_exec(obj->data.texeci.cmd, buff,
711                         text_buffer_size);
712                 p2 = buff;
713                 while (*p2) {
714                         if (*p2 == '\001') {
715                                 *p2 = ' ';
716                         }
717                         p2++;
718                 }
719                 timed_thread_lock(obj->data.texeci.p_timed_thread);
720                 strncpy(obj->data.texeci.buffer, buff, text_buffer_size);
721                 timed_thread_unlock(obj->data.texeci.p_timed_thread);
722                 free(buff);
723                 if (timed_thread_test(obj->data.texeci.p_timed_thread, 0)) {
724                         timed_thread_exit(obj->data.texeci.p_timed_thread);
725                 }
726         }
727         /* never reached */
728 }
729
730 static long current_text_color;
731
732 void set_current_text_color(long colour)
733 {
734         current_text_color = colour;
735 }
736
737 long get_current_text_color(void)
738 {
739         return current_text_color;
740 }
741
742 //adds newstring to to the tree unless you can already see it when travelling back.
743 //if it's possible to attach it then it returns a pointer to the leaf, else it returns NULL
744 struct conftree* conftree_add(struct conftree* previous, const char* newstring) {
745         struct conftree* node;
746         struct conftree* node2;
747
748         for(node = previous; node != NULL; node = node->back) {
749                 if(strcmp(node->string, newstring) == 0) {
750                         return NULL;
751                 }
752         }
753         node = malloc(sizeof(struct conftree));
754         if (previous != NULL) {
755                 if(previous->vert_next == NULL) {
756                         previous->vert_next = node;
757                 } else {
758                         for(node2 = previous->vert_next; node2->horz_next != NULL; node2 = node2->horz_next ) { }
759                         node2->horz_next = node;
760                 }
761         }
762         node->string = strdup(newstring);
763         node->horz_next = NULL;
764         node->vert_next = NULL;
765         node->back = previous;
766         return node;
767 }
768
769 void conftree_empty(struct conftree* tree) {
770         if(tree) {
771                 conftree_empty(tree->horz_next);
772                 conftree_empty(tree->vert_next);
773                 free(tree->string);
774                 free(tree);
775         }
776 }
777
778 struct conftree *currentconffile;
779
780 static void extract_variable_text(const char *p)
781 {
782         free_text_objects(&global_root_object, 0);
783         if (tmpstring1) {
784                 free(tmpstring1);
785                 tmpstring1 = 0;
786         }
787         if (tmpstring2) {
788                 free(tmpstring2);
789                 tmpstring2 = 0;
790         }
791         if (text_buffer) {
792                 free(text_buffer);
793                 text_buffer = 0;
794         }
795
796         extract_variable_text_internal(&global_root_object, p);
797 }
798
799 void parse_conky_vars(struct text_object *root, const char *txt, char *p, struct information *cur)
800 {
801         extract_variable_text_internal(root, txt);
802         generate_text_internal(p, max_user_text, *root, cur);
803 }
804
805 static inline struct mail_s *ensure_mail_thread(struct text_object *obj,
806                 void *thread(void *), const char *text)
807 {
808         if (obj->char_b && info.mail) {
809                 // this means we use info
810                 if (!info.mail->p_timed_thread) {
811                         info.mail->p_timed_thread =
812                                 timed_thread_create(thread,
813                                                 (void *) info.mail, info.mail->interval * 1000000);
814                         if (!info.mail->p_timed_thread) {
815                                 NORM_ERR("Error creating %s timed thread", text);
816                         }
817                         timed_thread_register(info.mail->p_timed_thread,
818                                         &info.mail->p_timed_thread);
819                         if (timed_thread_run(info.mail->p_timed_thread)) {
820                                 NORM_ERR("Error running %s timed thread", text);
821                         }
822                 }
823                 return info.mail;
824         } else if (obj->data.mail) {
825                 // this means we use obj
826                 if (!obj->data.mail->p_timed_thread) {
827                         obj->data.mail->p_timed_thread =
828                                 timed_thread_create(thread,
829                                                 (void *) obj->data.mail,
830                                                 obj->data.mail->interval * 1000000);
831                         if (!obj->data.mail->p_timed_thread) {
832                                 NORM_ERR("Error creating %s timed thread", text);
833                         }
834                         timed_thread_register(obj->data.mail->p_timed_thread,
835                                         &obj->data.mail->p_timed_thread);
836                         if (timed_thread_run(obj->data.mail->p_timed_thread)) {
837                                 NORM_ERR("Error running %s timed thread", text);
838                         }
839                 }
840                 return obj->data.mail;
841         } else if (!obj->a) {
842                 // something is wrong, warn once then stop
843                 NORM_ERR("There's a problem with your mail settings.  "
844                                 "Check that the global mail settings are properly defined"
845                                 " (line %li).", obj->line);
846                 obj->a++;
847         }
848         return NULL;
849 }
850
851 char *format_time(unsigned long timeval, const int width)
852 {
853         char buf[10];
854         unsigned long nt;       // narrow time, for speed on 32-bit
855         unsigned cc;            // centiseconds
856         unsigned nn;            // multi-purpose whatever
857
858         nt = timeval;
859         cc = nt % 100;          // centiseconds past second
860         nt /= 100;                      // total seconds
861         nn = nt % 60;           // seconds past the minute
862         nt /= 60;                       // total minutes
863         if (width >= snprintf(buf, sizeof buf, "%lu:%02u.%02u",
864                                 nt, nn, cc)) {
865                 return strndup(buf, text_buffer_size);
866         }
867         if (width >= snprintf(buf, sizeof buf, "%lu:%02u", nt, nn)) {
868                 return strndup(buf, text_buffer_size);
869         }
870         nn = nt % 60;           // minutes past the hour
871         nt /= 60;                       // total hours
872         if (width >= snprintf(buf, sizeof buf, "%lu,%02u", nt, nn)) {
873                 return strndup(buf, text_buffer_size);
874         }
875         nn = nt;                        // now also hours
876         if (width >= snprintf(buf, sizeof buf, "%uh", nn)) {
877                 return strndup(buf, text_buffer_size);
878         }
879         nn /= 24;                       // now days
880         if (width >= snprintf(buf, sizeof buf, "%ud", nn)) {
881                 return strndup(buf, text_buffer_size);
882         }
883         nn /= 7;                        // now weeks
884         if (width >= snprintf(buf, sizeof buf, "%uw", nn)) {
885                 return strndup(buf, text_buffer_size);
886         }
887         // well shoot, this outta' fit...
888         return strndup("<inf>", text_buffer_size);
889 }
890
891 //remove backspaced chars, example: "dog^H^H^Hcat" becomes "cat"
892 //string has to end with \0 and it's length should fit in a int
893 #define BACKSPACE 8
894 void remove_deleted_chars(char *string){
895         int i = 0;
896         while(string[i] != 0){
897                 if(string[i] == BACKSPACE){
898                         if(i != 0){
899                                 strcpy( &(string[i-1]), &(string[i+1]) );
900                                 i--;
901                         }else strcpy( &(string[i]), &(string[i+1]) ); //necessary for ^H's at the start of a string
902                 }else i++;
903         }
904 }
905
906 static inline void format_media_player_time(char *buf, const int size,
907                 int seconds)
908 {
909         int days, hours, minutes;
910
911         days = seconds / (24 * 60 * 60);
912         seconds %= (24 * 60 * 60);
913         hours = seconds / (60 * 60);
914         seconds %= (60 * 60);
915         minutes = seconds / 60;
916         seconds %= 60;
917
918         if (days > 0) {
919                 snprintf(buf, size, "%i days %i:%02i:%02i", days,
920                                 hours, minutes, seconds);
921         } else if (hours > 0) {
922                 snprintf(buf, size, "%i:%02i:%02i", hours, minutes,
923                                 seconds);
924         } else {
925                 snprintf(buf, size, "%i:%02i", minutes, seconds);
926         }
927 }
928
929 static inline double get_barnum(char *buf)
930 {
931         char *c = buf;
932         double barnum;
933
934         while (*c) {
935                 if (*c == '\001') {
936                         *c = ' ';
937                 }
938                 c++;
939         }
940
941         if (sscanf(buf, "%lf", &barnum) == 0) {
942                 NORM_ERR("reading exec value failed (perhaps it's not the "
943                                 "correct format?)");
944                 return -1;
945         }
946         if (barnum > 100.0 || barnum < 0.0) {
947                 NORM_ERR("your exec value is not between 0 and 100, "
948                                 "therefore it will be ignored");
949                 return -1;
950         }
951         return barnum;
952 }
953
954 /* substitutes all occurrences of '\n' with SECRIT_MULTILINE_CHAR, which allows
955  * multiline objects like $exec work with $align[rc] and friends
956  */
957 void substitute_newlines(char *p, long l)
958 {
959         char *s = p;
960         if (l < 0) return;
961         while (p && *p && p < s + l) {
962                 if (*p == '\n') {
963                         /* only substitute if it's not the last newline */
964                         *p = SECRIT_MULTILINE_CHAR;
965                 }
966                 p++;
967         }
968 }
969
970 static void generate_text_internal(char *p, int p_max_size,
971                 struct text_object root, struct information *cur)
972 {
973         struct text_object *obj;
974 #ifdef X11
975         int need_to_load_fonts = 0;
976 #endif /* X11 */
977
978         /* for the OBJ_top* handler */
979         struct process **needed = 0;
980
981 #ifdef HAVE_ICONV
982         char buff_in[p_max_size];
983         buff_in[0] = 0;
984         set_iconv_converting(0);
985 #endif /* HAVE_ICONV */
986
987         p[0] = 0;
988         obj = root.next;
989         while (obj && p_max_size > 0) {
990                 needed = 0; /* reset for top stuff */
991
992 /* IFBLOCK jumping algorithm
993  *
994  * This is easier as it looks like:
995  * - each IF checks it's condition
996  *   - on FALSE: call DO_JUMP
997  *   - on TRUE: don't care
998  * - each ELSE calls DO_JUMP unconditionally
999  * - each ENDIF is silently being ignored
1000  *
1001  * Why this works:
1002  * DO_JUMP overwrites the "obj" variable of the loop and sets it to the target
1003  * (i.e. the corresponding ELSE or ENDIF). After that, processing for the given
1004  * object can continue, free()ing stuff e.g., then the for-loop does the rest: as
1005  * regularly, "obj" is being updated to point to obj->next, so object parsing
1006  * continues right after the corresponding ELSE or ENDIF. This means that if we
1007  * find an ELSE, it's corresponding IF must not have jumped, so we need to jump
1008  * always. If we encounter an ENDIF, it's corresponding IF or ELSE has not
1009  * jumped, and there is nothing to do.
1010  */
1011 #define DO_JUMP { \
1012         DBGP2("jumping"); \
1013         obj = obj->data.ifblock.next; \
1014 }
1015
1016 #define OBJ(a) break; case OBJ_##a:
1017
1018                 switch (obj->type) {
1019                         default:
1020                                 NORM_ERR("not implemented obj type %d", obj->type);
1021                         OBJ(read_tcp) {
1022                                 int sock, received;
1023                                 struct sockaddr_in addr;
1024                                 struct hostent* he = gethostbyname(obj->data.read_tcp.host);
1025                                 if(he != NULL) {
1026                                         sock = socket(he->h_addrtype, SOCK_STREAM, 0);
1027                                         if(sock != -1) {
1028                                                 memset(&addr, 0, sizeof(addr));
1029                                                 addr.sin_family = AF_INET;
1030                                                 addr.sin_port = obj->data.read_tcp.port;
1031                                                 memcpy(&addr.sin_addr, he->h_addr, he->h_length);
1032                                                 if (connect(sock, (struct sockaddr*)&addr, sizeof(struct sockaddr)) == 0) {
1033                                                         fd_set readfds;
1034                                                         struct timeval tv;
1035                                                         FD_ZERO(&readfds);
1036                                                         FD_SET(sock, &readfds);
1037                                                         tv.tv_sec = 1;
1038                                                         tv.tv_usec = 0;
1039                                                         if(select(sock + 1, &readfds, NULL, NULL, &tv) > 0){
1040                                                                 received = recv(sock, p, p_max_size, 0);
1041                                                                 p[received] = 0;
1042                                                         }
1043                                                         close(sock);
1044                                                 } else {
1045                                                         NORM_ERR("read_tcp: Couldn't create a connection");
1046                                                 }
1047                                         }else{
1048                                                 NORM_ERR("read_tcp: Couldn't create a socket");
1049                                         }
1050                                 }else{
1051                                         NORM_ERR("read_tcp: Problem with resolving the hostname");
1052                                 }
1053                         }
1054 #ifndef __OpenBSD__
1055                         OBJ(acpitemp) {
1056                                 temp_print(p, p_max_size, get_acpi_temperature(obj->data.i), TEMP_CELSIUS);
1057                         }
1058 #endif /* !__OpenBSD__ */
1059                         OBJ(freq) {
1060                                 if (obj->a) {
1061                                         obj->a = get_freq(p, p_max_size, "%.0f", 1,
1062                                                         obj->data.cpu_index);
1063                                 }
1064                         }
1065                         OBJ(freq_g) {
1066                                 if (obj->a) {
1067 #ifndef __OpenBSD__
1068                                         obj->a = get_freq(p, p_max_size, "%'.2f", 1000,
1069                                                         obj->data.cpu_index);
1070 #else
1071                                         /* OpenBSD has no such flag (SUSv2) */
1072                                         obj->a = get_freq(p, p_max_size, "%.2f", 1000,
1073                                                         obj->data.cpu_index);
1074 #endif /* __OpenBSD */
1075                                 }
1076                         }
1077 #if defined(__linux__)
1078                         OBJ(voltage_mv) {
1079                                 if (obj->a) {
1080                                         obj->a = get_voltage(p, p_max_size, "%.0f", 1,
1081                                                         obj->data.cpu_index);
1082                                 }
1083                         }
1084                         OBJ(voltage_v) {
1085                                 if (obj->a) {
1086                                         obj->a = get_voltage(p, p_max_size, "%'.3f", 1000,
1087                                                         obj->data.cpu_index);
1088                                 }
1089                         }
1090
1091 #ifdef HAVE_IWLIB
1092                         OBJ(wireless_essid) {
1093                                 snprintf(p, p_max_size, "%s", obj->data.net->essid);
1094                         }
1095                         OBJ(wireless_mode) {
1096                                 snprintf(p, p_max_size, "%s", obj->data.net->mode);
1097                         }
1098                         OBJ(wireless_bitrate) {
1099                                 snprintf(p, p_max_size, "%s", obj->data.net->bitrate);
1100                         }
1101                         OBJ(wireless_ap) {
1102                                 snprintf(p, p_max_size, "%s", obj->data.net->ap);
1103                         }
1104                         OBJ(wireless_link_qual) {
1105                                 spaced_print(p, p_max_size, "%d", 4,
1106                                                 obj->data.net->link_qual);
1107                         }
1108                         OBJ(wireless_link_qual_max) {
1109                                 spaced_print(p, p_max_size, "%d", 4,
1110                                                 obj->data.net->link_qual_max);
1111                         }
1112                         OBJ(wireless_link_qual_perc) {
1113                                 if (obj->data.net->link_qual_max > 0) {
1114                                         spaced_print(p, p_max_size, "%.0f", 5,
1115                                                         (double) obj->data.net->link_qual /
1116                                                         obj->data.net->link_qual_max * 100);
1117                                 } else {
1118                                         spaced_print(p, p_max_size, "unk", 5);
1119                                 }
1120                         }
1121                         OBJ(wireless_link_bar) {
1122 #ifdef X11
1123                                 if(output_methods & TO_X) {
1124                                         new_bar(p, obj->a, obj->b, ((double) obj->data.net->link_qual /
1125                                                 obj->data.net->link_qual_max) * 255.0);
1126                                 }else{
1127 #endif /* X11 */
1128                                         if(!obj->a) obj->a = DEFAULT_BAR_WIDTH_NO_X;
1129                                         new_bar_in_shell(p, p_max_size, ((double) obj->data.net->link_qual /
1130                                                 obj->data.net->link_qual_max) * 100.0, obj->a);
1131 #ifdef X11
1132                                 }
1133 #endif /* X11 */
1134                         }
1135 #endif /* HAVE_IWLIB */
1136
1137 #endif /* __linux__ */
1138
1139 #ifndef __OpenBSD__
1140                         OBJ(adt746xcpu) {
1141                                 get_adt746x_cpu(p, p_max_size);
1142                         }
1143                         OBJ(adt746xfan) {
1144                                 get_adt746x_fan(p, p_max_size);
1145                         }
1146                         OBJ(acpifan) {
1147                                 get_acpi_fan(p, p_max_size);
1148                         }
1149                         OBJ(acpiacadapter) {
1150                                 get_acpi_ac_adapter(p, p_max_size);
1151                         }
1152                         OBJ(battery) {
1153                                 get_battery_stuff(p, p_max_size, obj->data.s, BATTERY_STATUS);
1154                         }
1155                         OBJ(battery_time) {
1156                                 get_battery_stuff(p, p_max_size, obj->data.s, BATTERY_TIME);
1157                         }
1158                         OBJ(battery_percent) {
1159                                 percent_print(p, p_max_size, get_battery_perct(obj->data.s));
1160                         }
1161                         OBJ(battery_bar) {
1162 #ifdef X11
1163                                 if(output_methods & TO_X) {
1164                                         new_bar(p, obj->a, obj->b, get_battery_perct_bar(obj->data.s));
1165                                 }else{
1166 #endif /* X11 */
1167                                         if(!obj->a) obj->a = DEFAULT_BAR_WIDTH_NO_X;
1168                                         new_bar_in_shell(p, p_max_size, get_battery_perct_bar(obj->data.s) / 2.55, obj->a);
1169 #ifdef X11
1170                                 }
1171 #endif /* X11 */
1172                         }
1173                         OBJ(battery_short) {
1174                                 get_battery_short_status(p, p_max_size, obj->data.s);
1175                         }
1176 #endif /* __OpenBSD__ */
1177
1178                         OBJ(buffers) {
1179                                 human_readable(cur->buffers * 1024, p, 255);
1180                         }
1181                         OBJ(cached) {
1182                                 human_readable(cur->cached * 1024, p, 255);
1183                         }
1184                         OBJ(cpu) {
1185                                 if (obj->data.cpu_index > info.cpu_count) {
1186                                         NORM_ERR("obj->data.cpu_index %i info.cpu_count %i",
1187                                                         obj->data.cpu_index, info.cpu_count);
1188                                         CRIT_ERR(NULL, NULL, "attempting to use more CPUs than you have!");
1189                                 }
1190                                 percent_print(p, p_max_size,
1191                                               round_to_int(cur->cpu_usage[obj->data.cpu_index] * 100.0));
1192                         }
1193 #ifdef X11
1194                         OBJ(cpugauge)
1195                                 new_gauge(p, obj->a, obj->b,
1196                                                 round_to_int(cur->cpu_usage[obj->data.cpu_index] * 255.0));
1197 #endif /* X11 */
1198                         OBJ(cpubar) {
1199 #ifdef X11
1200                                 if(output_methods & TO_X) {
1201                                         new_bar(p, obj->a, obj->b,
1202                                                 round_to_int(cur->cpu_usage[obj->data.cpu_index] * 255.0));
1203                                 }else{
1204 #endif /* X11 */
1205                                         if(!obj->a) obj->a = DEFAULT_BAR_WIDTH_NO_X;
1206                                         new_bar_in_shell(p, p_max_size, round_to_int(cur->cpu_usage[obj->data.cpu_index] * 100), obj->a);
1207 #ifdef X11
1208                                 }
1209 #endif /* X11 */
1210                         }
1211 #ifdef X11
1212                         OBJ(cpugraph) {
1213                                 new_graph(p, obj->a, obj->b, obj->c, obj->d,
1214                                                 round_to_int(cur->cpu_usage[obj->data.cpu_index] * 100),
1215                                                 100, 1, obj->char_a, obj->char_b);
1216                         }
1217                         OBJ(loadgraph) {
1218                                 new_graph(p, obj->a, obj->b, obj->c, obj->d, cur->loadavg[0],
1219                                                 obj->e, 1, obj->char_a, obj->char_b);
1220                         }
1221 #endif /* X11 */
1222                         OBJ(color) {
1223                                 new_fg(p, obj->data.l);
1224                         }
1225 #ifdef X11
1226                         OBJ(color0) {
1227                                 new_fg(p, color0);
1228                         }
1229                         OBJ(color1) {
1230                                 new_fg(p, color1);
1231                         }
1232                         OBJ(color2) {
1233                                 new_fg(p, color2);
1234                         }
1235                         OBJ(color3) {
1236                                 new_fg(p, color3);
1237                         }
1238                         OBJ(color4) {
1239                                 new_fg(p, color4);
1240                         }
1241                         OBJ(color5) {
1242                                 new_fg(p, color5);
1243                         }
1244                         OBJ(color6) {
1245                                 new_fg(p, color6);
1246                         }
1247                         OBJ(color7) {
1248                                 new_fg(p, color7);
1249                         }
1250                         OBJ(color8) {
1251                                 new_fg(p, color8);
1252                         }
1253                         OBJ(color9) {
1254                                 new_fg(p, color9);
1255                         }
1256 #endif /* X11 */
1257                         OBJ(conky_version) {
1258                                 snprintf(p, p_max_size, "%s", VERSION);
1259                         }
1260                         OBJ(conky_build_date) {
1261                                 snprintf(p, p_max_size, "%s", BUILD_DATE);
1262                         }
1263                         OBJ(conky_build_arch) {
1264                                 snprintf(p, p_max_size, "%s", BUILD_ARCH);
1265                         }
1266 #if defined(__linux__)
1267                         OBJ(disk_protect) {
1268                                 snprintf(p, p_max_size, "%s",
1269                                                 get_disk_protect_queue(obj->data.s));
1270                         }
1271                         OBJ(i8k_version) {
1272                                 snprintf(p, p_max_size, "%s", i8k.version);
1273                         }
1274                         OBJ(i8k_bios) {
1275                                 snprintf(p, p_max_size, "%s", i8k.bios);
1276                         }
1277                         OBJ(i8k_serial) {
1278                                 snprintf(p, p_max_size, "%s", i8k.serial);
1279                         }
1280                         OBJ(i8k_cpu_temp) {
1281                                 int cpu_temp;
1282
1283                                 sscanf(i8k.cpu_temp, "%d", &cpu_temp);
1284                                 temp_print(p, p_max_size, (double)cpu_temp, TEMP_CELSIUS);
1285                         }
1286                         OBJ(i8k_left_fan_status) {
1287                                 int left_fan_status;
1288
1289                                 sscanf(i8k.left_fan_status, "%d", &left_fan_status);
1290                                 if (left_fan_status == 0) {
1291                                         snprintf(p, p_max_size, "off");
1292                                 }
1293                                 if (left_fan_status == 1) {
1294                                         snprintf(p, p_max_size, "low");
1295                                 }
1296                                 if (left_fan_status == 2) {
1297                                         snprintf(p, p_max_size, "high");
1298                                 }
1299                         }
1300                         OBJ(i8k_right_fan_status) {
1301                                 int right_fan_status;
1302
1303                                 sscanf(i8k.right_fan_status, "%d", &right_fan_status);
1304                                 if (right_fan_status == 0) {
1305                                         snprintf(p, p_max_size, "off");
1306                                 }
1307                                 if (right_fan_status == 1) {
1308                                         snprintf(p, p_max_size, "low");
1309                                 }
1310                                 if (right_fan_status == 2) {
1311                                         snprintf(p, p_max_size, "high");
1312                                 }
1313                         }
1314                         OBJ(i8k_left_fan_rpm) {
1315                                 snprintf(p, p_max_size, "%s", i8k.left_fan_rpm);
1316                         }
1317                         OBJ(i8k_right_fan_rpm) {
1318                                 snprintf(p, p_max_size, "%s", i8k.right_fan_rpm);
1319                         }
1320                         OBJ(i8k_ac_status) {
1321                                 int ac_status;
1322
1323                                 sscanf(i8k.ac_status, "%d", &ac_status);
1324                                 if (ac_status == -1) {
1325                                         snprintf(p, p_max_size, "disabled (read i8k docs)");
1326                                 }
1327                                 if (ac_status == 0) {
1328                                         snprintf(p, p_max_size, "off");
1329                                 }
1330                                 if (ac_status == 1) {
1331                                         snprintf(p, p_max_size, "on");
1332                                 }
1333                         }
1334                         OBJ(i8k_buttons_status) {
1335                                 snprintf(p, p_max_size, "%s", i8k.buttons_status);
1336                         }
1337 #if defined(IBM)
1338                         OBJ(ibm_fan) {
1339                                 get_ibm_acpi_fan(p, p_max_size);
1340                         }
1341                         OBJ(ibm_temps) {
1342                                 get_ibm_acpi_temps();
1343                                 temp_print(p, p_max_size,
1344                                            ibm_acpi.temps[obj->data.sensor], TEMP_CELSIUS);
1345                         }
1346                         OBJ(ibm_volume) {
1347                                 get_ibm_acpi_volume(p, p_max_size);
1348                         }
1349                         OBJ(ibm_brightness) {
1350                                 get_ibm_acpi_brightness(p, p_max_size);
1351                         }
1352 #endif /* IBM */
1353                         /* information from sony_laptop kernel module
1354                          * /sys/devices/platform/sony-laptop */
1355                         OBJ(sony_fanspeed) {
1356                                 get_sony_fanspeed(p, p_max_size);
1357                         }
1358                         OBJ(if_gw) {
1359                                 if (!cur->gw_info.count) {
1360                                         DO_JUMP;
1361                                 }
1362                         }
1363                         OBJ(gw_iface) {
1364                                 snprintf(p, p_max_size, "%s", cur->gw_info.iface);
1365                         }
1366                         OBJ(gw_ip) {
1367                                 snprintf(p, p_max_size, "%s", cur->gw_info.ip);
1368                         }
1369                         OBJ(laptop_mode) {
1370                                 snprintf(p, p_max_size, "%d", get_laptop_mode());
1371                         }
1372                         OBJ(pb_battery) {
1373                                 get_powerbook_batt_info(p, p_max_size, obj->data.i);
1374                         }
1375 #endif /* __linux__ */
1376 #if (defined(__FreeBSD__) || defined(__linux__))
1377                         OBJ(if_up) {
1378                                 if ((obj->data.ifblock.s)
1379                                                 && (!interface_up(obj->data.ifblock.s))) {
1380                                         DO_JUMP;
1381                                 }
1382                         }
1383 #endif
1384 #ifdef __OpenBSD__
1385                         OBJ(obsd_sensors_temp) {
1386                                 obsd_sensors.device = sensor_device;
1387                                 update_obsd_sensors();
1388                                 temp_print(p, p_max_size,
1389                                            obsd_sensors.temp[obsd_sensors.device][obj->data.sensor],
1390                                            TEMP_CELSIUS);
1391                         }
1392                         OBJ(obsd_sensors_fan) {
1393                                 obsd_sensors.device = sensor_device;
1394                                 update_obsd_sensors();
1395                                 snprintf(p, p_max_size, "%d",
1396                                                 obsd_sensors.fan[obsd_sensors.device][obj->data.sensor]);
1397                         }
1398                         OBJ(obsd_sensors_volt) {
1399                                 obsd_sensors.device = sensor_device;
1400                                 update_obsd_sensors();
1401                                 snprintf(p, p_max_size, "%.2f",
1402                                                 obsd_sensors.volt[obsd_sensors.device][obj->data.sensor]);
1403                         }
1404                         OBJ(obsd_vendor) {
1405                                 get_obsd_vendor(p, p_max_size);
1406                         }
1407                         OBJ(obsd_product) {
1408                                 get_obsd_product(p, p_max_size);
1409                         }
1410 #endif /* __OpenBSD__ */
1411 #ifdef X11
1412                         OBJ(font) {
1413                                 new_font(p, obj->data.s);
1414                                 need_to_load_fonts = 1;
1415                         }
1416 #endif /* X11 */
1417                         /* TODO: move this correction from kB to kB/s elsewhere
1418                          * (or get rid of it??) */
1419                         OBJ(diskio) {
1420                                 human_readable((obj->data.diskio->current / update_interval) * 1024LL,
1421                                                 p, p_max_size);
1422                         }
1423                         OBJ(diskio_write) {
1424                                 human_readable((obj->data.diskio->current_write / update_interval) * 1024LL,
1425                                                 p, p_max_size);
1426                         }
1427                         OBJ(diskio_read) {
1428                                 human_readable((obj->data.diskio->current_read / update_interval) * 1024LL,
1429                                                 p, p_max_size);
1430                         }
1431 #ifdef X11
1432                         OBJ(diskiograph) {
1433                                 new_graph(p, obj->a, obj->b, obj->c, obj->d,
1434                                           obj->data.diskio->current, obj->e, 1, obj->char_a, obj->char_b);
1435                         }
1436                         OBJ(diskiograph_read) {
1437                                 new_graph(p, obj->a, obj->b, obj->c, obj->d,
1438                                           obj->data.diskio->current_read, obj->e, 1, obj->char_a, obj->char_b);
1439                         }
1440                         OBJ(diskiograph_write) {
1441                                 new_graph(p, obj->a, obj->b, obj->c, obj->d,
1442                                           obj->data.diskio->current_write, obj->e, 1, obj->char_a, obj->char_b);
1443                         }
1444 #endif /* X11 */
1445                         OBJ(downspeed) {
1446                                 human_readable(obj->data.net->recv_speed, p, 255);
1447                         }
1448                         OBJ(downspeedf) {
1449                                 spaced_print(p, p_max_size, "%.1f", 8,
1450                                                 obj->data.net->recv_speed / 1024.0);
1451                         }
1452 #ifdef X11
1453                         OBJ(downspeedgraph) {
1454                                 new_graph(p, obj->a, obj->b, obj->c, obj->d,
1455                                         obj->data.net->recv_speed / 1024.0, obj->e, 1, obj->char_a, obj->char_b);
1456                         }
1457 #endif /* X11 */
1458                         OBJ(else) {
1459                                 /* Since we see you, you're if has not jumped.
1460                                  * Do Ninja jump here: without leaving traces.
1461                                  * This is to prevent us from stale jumped flags.
1462                                  */
1463                                 obj = obj->data.ifblock.next;
1464                                 continue;
1465                         }
1466                         OBJ(endif) {
1467                                 /* harmless object, just ignore */
1468                         }
1469                         OBJ(addr) {
1470                                 if ((obj->data.net->addr.sa_data[2] & 255) == 0
1471                                                 && (obj->data.net->addr.sa_data[3] & 255) == 0
1472                                                 && (obj->data.net->addr.sa_data[4] & 255) == 0
1473                                                 && (obj->data.net->addr.sa_data[5] & 255) == 0) {
1474                                         snprintf(p, p_max_size, "No Address");
1475                                 } else {
1476                                         snprintf(p, p_max_size, "%u.%u.%u.%u",
1477                                                 obj->data.net->addr.sa_data[2] & 255,
1478                                                 obj->data.net->addr.sa_data[3] & 255,
1479                                                 obj->data.net->addr.sa_data[4] & 255,
1480                                                 obj->data.net->addr.sa_data[5] & 255);
1481                                 }
1482                         }
1483 #if defined(__linux__)
1484                         OBJ(addrs) {
1485                                 if (NULL != obj->data.net->addrs && strlen(obj->data.net->addrs) > 2) {
1486                                         obj->data.net->addrs[strlen(obj->data.net->addrs) - 2] = 0; /* remove ", " from end of string */
1487                                         strcpy(p, obj->data.net->addrs);
1488                                 } else {
1489                                         strcpy(p, "0.0.0.0");
1490                                 }
1491                         }
1492 #endif /* __linux__ */
1493 #if defined(IMLIB2) && defined(X11)
1494                         OBJ(image) {
1495                                 /* doesn't actually draw anything, just queues it omp.  the
1496                                  * image will get drawn after the X event loop */
1497                                 cimlib_add_image(obj->data.s);
1498                         }
1499 #endif /* IMLIB2 */
1500                         OBJ(eval) {
1501                                 evaluate(obj->data.s, p);
1502                         }
1503                         OBJ(exec) {
1504                                 read_exec(obj->data.s, p, text_buffer_size);
1505                                 remove_deleted_chars(p);
1506                         }
1507                         OBJ(execp) {
1508                                 struct information *tmp_info;
1509                                 struct text_object subroot;
1510
1511                                 read_exec(obj->data.s, p, text_buffer_size);
1512
1513                                 tmp_info = malloc(sizeof(struct information));
1514                                 memcpy(tmp_info, cur, sizeof(struct information));
1515                                 parse_conky_vars(&subroot, p, p, tmp_info);
1516
1517                                 free_text_objects(&subroot, 1);
1518                                 free(tmp_info);
1519                         }
1520 #ifdef X11
1521                         OBJ(execgauge) {
1522                                 double barnum;
1523
1524                                 read_exec(obj->data.s, p, text_buffer_size);
1525                                 barnum = get_barnum(p); /*using the same function*/
1526
1527                                 if (barnum >= 0.0) {
1528                                         barnum /= 100;
1529                                         new_gauge(p, obj->a, obj->b, round_to_int(barnum * 255.0));
1530                                 }
1531                         }
1532 #endif /* X11 */
1533                         OBJ(execbar) {
1534                                 double barnum;
1535
1536                                 read_exec(obj->data.s, p, text_buffer_size);
1537                                 barnum = get_barnum(p);
1538
1539                                 if (barnum >= 0.0) {
1540 #ifdef X11
1541                                         if(output_methods & TO_X) {
1542                                                 barnum /= 100;
1543                                                 new_bar(p, obj->a, obj->b, round_to_int(barnum * 255.0));
1544                                         }else{
1545 #endif /* X11 */
1546                                                 if(!obj->a) obj->a = DEFAULT_BAR_WIDTH_NO_X;
1547                                                 new_bar_in_shell(p, p_max_size, barnum, obj->a);
1548 #ifdef X11
1549                                         }
1550 #endif /* X11 */
1551                                 }
1552                         }
1553 #ifdef X11
1554                         OBJ(execgraph) {
1555                                 char showaslog = FALSE;
1556                                 char tempgrad = FALSE;
1557                                 double barnum;
1558                                 char *cmd = obj->data.s;
1559
1560                                 if (strstr(cmd, " "TEMPGRAD) && strlen(cmd) > strlen(" "TEMPGRAD)) {
1561                                         tempgrad = TRUE;
1562                                         cmd += strlen(" "TEMPGRAD);
1563                                 }
1564                                 if (strstr(cmd, " "LOGGRAPH) && strlen(cmd) > strlen(" "LOGGRAPH)) {
1565                                         showaslog = TRUE;
1566                                         cmd += strlen(" "LOGGRAPH);
1567                                 }
1568                                 read_exec(cmd, p, text_buffer_size);
1569                                 barnum = get_barnum(p);
1570
1571                                 if (barnum > 0) {
1572                                         new_graph(p, obj->a, obj->b, obj->c, obj->d, round_to_int(barnum),
1573                                                         100, 1, showaslog, tempgrad);
1574                                 }
1575                         }
1576 #endif /* X11 */
1577                         OBJ(execibar) {
1578                                 if (current_update_time - obj->data.execi.last_update
1579                                                 >= obj->data.execi.interval) {
1580                                         double barnum;
1581
1582                                         read_exec(obj->data.execi.cmd, p, text_buffer_size);
1583                                         barnum = get_barnum(p);
1584
1585                                         if (barnum >= 0.0) {
1586                                                 obj->f = barnum;
1587                                         }
1588                                         obj->data.execi.last_update = current_update_time;
1589                                 }
1590 #ifdef X11
1591                                 if(output_methods & TO_X) {
1592                                         new_bar(p, obj->a, obj->b, round_to_int(obj->f * 2.55));
1593                                 } else {
1594 #endif /* X11 */
1595                                         if(!obj->a) obj->a = DEFAULT_BAR_WIDTH_NO_X;
1596                                         new_bar_in_shell(p, p_max_size, round_to_int(obj->f), obj->a);
1597 #ifdef X11
1598                                 }
1599 #endif /* X11 */
1600                         }
1601 #ifdef X11
1602                         OBJ(execigraph) {
1603                                 if (current_update_time - obj->data.execi.last_update
1604                                                 >= obj->data.execi.interval) {
1605                                         double barnum;
1606                                         char showaslog = FALSE;
1607                                         char tempgrad = FALSE;
1608                                         char *cmd = obj->data.execi.cmd;
1609
1610                                         if (strstr(cmd, " "TEMPGRAD) && strlen(cmd) > strlen(" "TEMPGRAD)) {
1611                                                 tempgrad = TRUE;
1612                                                 cmd += strlen(" "TEMPGRAD);
1613                                         }
1614                                         if (strstr(cmd, " "LOGGRAPH) && strlen(cmd) > strlen(" "LOGGRAPH)) {
1615                                                 showaslog = TRUE;
1616                                                 cmd += strlen(" "LOGGRAPH);
1617                                         }
1618                                         obj->char_a = showaslog;
1619                                         obj->char_b = tempgrad;
1620                                         read_exec(cmd, p, text_buffer_size);
1621                                         barnum = get_barnum(p);
1622
1623                                         if (barnum >= 0.0) {
1624                                                 obj->f = barnum;
1625                                         }
1626                                         obj->data.execi.last_update = current_update_time;
1627                                 }
1628                                 new_graph(p, obj->a, obj->b, obj->c, obj->d, (int) (obj->f), 100, 1, obj->char_a, obj->char_b);
1629                         }
1630                         OBJ(execigauge) {
1631                                 if (current_update_time - obj->data.execi.last_update
1632                                                 >= obj->data.execi.interval) {
1633                                         double barnum;
1634
1635                                         read_exec(obj->data.execi.cmd, p, text_buffer_size);
1636                                         barnum = get_barnum(p);
1637
1638                                         if (barnum >= 0.0) {
1639                                                 obj->f = 255 * barnum / 100.0;
1640                                         }
1641                                         obj->data.execi.last_update = current_update_time;
1642                                 }
1643                                 new_gauge(p, obj->a, obj->b, round_to_int(obj->f));
1644                         }
1645 #endif /* X11 */
1646                         OBJ(execi) {
1647                                 if (current_update_time - obj->data.execi.last_update
1648                                                 >= obj->data.execi.interval
1649                                                 && obj->data.execi.interval != 0) {
1650                                         read_exec(obj->data.execi.cmd, obj->data.execi.buffer,
1651                                                 text_buffer_size);
1652                                         obj->data.execi.last_update = current_update_time;
1653                                 }
1654                                 snprintf(p, text_buffer_size, "%s", obj->data.execi.buffer);
1655                         }
1656                         OBJ(execpi) {
1657                                 struct text_object subroot;
1658                                 struct information *tmp_info =
1659                                         malloc(sizeof(struct information));
1660                                 memcpy(tmp_info, cur, sizeof(struct information));
1661
1662                                 if (current_update_time - obj->data.execi.last_update
1663                                                 < obj->data.execi.interval
1664                                                 || obj->data.execi.interval == 0) {
1665                                         parse_conky_vars(&subroot, obj->data.execi.buffer, p, tmp_info);
1666                                 } else {
1667                                         char *output = obj->data.execi.buffer;
1668                                         FILE *fp = pid_popen(obj->data.execi.cmd, "r", &childpid);
1669                                         int length = fread(output, 1, text_buffer_size, fp);
1670
1671                                         pclose(fp);
1672
1673                                         output[length] = '\0';
1674                                         if (length > 0 && output[length - 1] == '\n') {
1675                                                 output[length - 1] = '\0';
1676                                         }
1677
1678                                         parse_conky_vars(&subroot, obj->data.execi.buffer, p, tmp_info);
1679                                         obj->data.execi.last_update = current_update_time;
1680                                 }
1681                                 free_text_objects(&subroot, 1);
1682                                 free(tmp_info);
1683                         }
1684                         OBJ(texeci) {
1685                                 if (!obj->data.texeci.p_timed_thread) {
1686                                         obj->data.texeci.p_timed_thread =
1687                                                 timed_thread_create(&threaded_exec,
1688                                                 (void *) obj, obj->data.texeci.interval * 1000000);
1689                                         if (!obj->data.texeci.p_timed_thread) {
1690                                                 NORM_ERR("Error creating texeci timed thread");
1691                                         }
1692                                         /*
1693                                          * note that we don't register this thread with the
1694                                          * timed_thread list, because we destroy it manually
1695                                          */
1696                                         if (timed_thread_run(obj->data.texeci.p_timed_thread)) {
1697                                                 NORM_ERR("Error running texeci timed thread");
1698                                         }
1699                                 } else {
1700                                         timed_thread_lock(obj->data.texeci.p_timed_thread);
1701                                         snprintf(p, text_buffer_size, "%s", obj->data.texeci.buffer);
1702                                         timed_thread_unlock(obj->data.texeci.p_timed_thread);
1703                                 }
1704                         }
1705                         OBJ(imap_unseen) {
1706                                 struct mail_s *mail = ensure_mail_thread(obj, imap_thread, "imap");
1707
1708                                 if (mail && mail->p_timed_thread) {
1709                                         timed_thread_lock(mail->p_timed_thread);
1710                                         snprintf(p, p_max_size, "%lu", mail->unseen);
1711                                         timed_thread_unlock(mail->p_timed_thread);
1712                                 }
1713                         }
1714                         OBJ(imap_messages) {
1715                                 struct mail_s *mail = ensure_mail_thread(obj, imap_thread, "imap");
1716
1717                                 if (mail && mail->p_timed_thread) {
1718                                         timed_thread_lock(mail->p_timed_thread);
1719                                         snprintf(p, p_max_size, "%lu", mail->messages);
1720                                         timed_thread_unlock(mail->p_timed_thread);
1721                                 }
1722                         }
1723                         OBJ(pop3_unseen) {
1724                                 struct mail_s *mail = ensure_mail_thread(obj, pop3_thread, "pop3");
1725
1726                                 if (mail && mail->p_timed_thread) {
1727                                         timed_thread_lock(mail->p_timed_thread);
1728                                         snprintf(p, p_max_size, "%lu", mail->unseen);
1729                                         timed_thread_unlock(mail->p_timed_thread);
1730                                 }
1731                         }
1732                         OBJ(pop3_used) {
1733                                 struct mail_s *mail = ensure_mail_thread(obj, pop3_thread, "pop3");
1734
1735                                 if (mail && mail->p_timed_thread) {
1736                                         timed_thread_lock(mail->p_timed_thread);
1737                                         snprintf(p, p_max_size, "%.1f",
1738                                                 mail->used / 1024.0 / 1024.0);
1739                                         timed_thread_unlock(mail->p_timed_thread);
1740                                 }
1741                         }
1742                         OBJ(fs_bar) {
1743                                 if (obj->data.fs != NULL) {
1744                                         if (obj->data.fs->size == 0) {
1745 #ifdef X11
1746                                                 if(output_methods & TO_X) {
1747                                                         new_bar(p, obj->data.fsbar.w, obj->data.fsbar.h, 255);
1748                                                 }else{
1749 #endif /* X11 */
1750                                                         if(!obj->data.fsbar.w) obj->data.fsbar.w = DEFAULT_BAR_WIDTH_NO_X;
1751                                                         new_bar_in_shell(p, p_max_size, 100, obj->data.fsbar.w);
1752 #ifdef X11
1753                                                 }
1754 #endif /* X11 */
1755                                         } else {
1756 #ifdef X11
1757                                                 if(output_methods & TO_X) {
1758                                                         new_bar(p, obj->data.fsbar.w, obj->data.fsbar.h,
1759                                                                 (int) (255 - obj->data.fsbar.fs->avail * 255 /
1760                                                                 obj->data.fs->size));
1761                                                 }else{
1762 #endif /* X11 */
1763                                                         if(!obj->data.fsbar.w) obj->data.fsbar.w = DEFAULT_BAR_WIDTH_NO_X;
1764                                                         new_bar_in_shell(p, p_max_size,
1765                                                                 (int) (100 - obj->data.fsbar.fs->avail * 100 / obj->data.fs->size), obj->data.fsbar.w);
1766 #ifdef X11
1767                                                 }
1768 #endif /* X11 */
1769                                         }
1770                                 }
1771                         }
1772                         OBJ(fs_free) {
1773                                 if (obj->data.fs != NULL) {
1774                                         human_readable(obj->data.fs->avail, p, 255);
1775                                 }
1776                         }
1777                         OBJ(fs_free_perc) {
1778                                 if (obj->data.fs != NULL) {
1779                                         int val = 0;
1780
1781                                         if (obj->data.fs->size) {
1782                                                 val = obj->data.fs->avail * 100 / obj->data.fs->size;
1783                                         }
1784
1785                                         percent_print(p, p_max_size, val);
1786                                 }
1787                         }
1788                         OBJ(fs_size) {
1789                                 if (obj->data.fs != NULL) {
1790                                         human_readable(obj->data.fs->size, p, 255);
1791                                 }
1792                         }
1793                         OBJ(fs_type) {
1794                                 if (obj->data.fs != NULL)
1795                                         snprintf(p, p_max_size, "%s", obj->data.fs->type);
1796                         }
1797                         OBJ(fs_used) {
1798                                 if (obj->data.fs != NULL) {
1799                                         human_readable(obj->data.fs->size - obj->data.fs->free, p,
1800                                                         255);
1801                                 }
1802                         }
1803                         OBJ(fs_bar_free) {
1804                                 if (obj->data.fs != NULL) {
1805                                         if (obj->data.fs->size == 0) {
1806 #ifdef X11
1807                                                 if(output_methods & TO_X) {
1808                                                         new_bar(p, obj->data.fsbar.w, obj->data.fsbar.h, 255);
1809                                                 }else{
1810 #endif /* X11 */
1811                                                         if(!obj->data.fsbar.w) obj->data.fsbar.w = DEFAULT_BAR_WIDTH_NO_X;
1812                                                         new_bar_in_shell(p, p_max_size, 100, obj->data.fsbar.w);
1813 #ifdef X11
1814                                                 }
1815 #endif /* X11 */
1816                                         } else {
1817 #ifdef X11
1818                                                 if(output_methods & TO_X) {
1819                                                         new_bar(p, obj->data.fsbar.w, obj->data.fsbar.h,
1820                                                                 (int) (obj->data.fsbar.fs->avail * 255 /
1821                                                                 obj->data.fs->size));
1822                                                 }else{
1823 #endif /* X11 */
1824                                                         if(!obj->data.fsbar.w) obj->data.fsbar.w = DEFAULT_BAR_WIDTH_NO_X;
1825                                                         new_bar_in_shell(p, p_max_size,
1826                                                                 (int) (obj->data.fsbar.fs->avail * 100 / obj->data.fs->size), obj->data.fsbar.w);
1827 #ifdef X11
1828                                                 }
1829 #endif /* X11 */
1830                                         }
1831                                 }
1832                         }
1833                         OBJ(fs_used_perc) {
1834                                 if (obj->data.fs != NULL) {
1835                                         int val = 0;
1836
1837                                         if (obj->data.fs->size) {
1838                                                 val = obj->data.fs->free
1839                                                                 * 100 /
1840                                                         obj->data.fs->size;
1841                                         }
1842
1843                                         percent_print(p, p_max_size, 100 - val);
1844                                 }
1845                         }
1846                         OBJ(loadavg) {
1847                                 float *v = info.loadavg;
1848
1849                                 if (obj->data.loadavg[2]) {
1850                                         snprintf(p, p_max_size, "%.2f %.2f %.2f",
1851                                                 v[obj->data.loadavg[0] - 1],
1852                                                 v[obj->data.loadavg[1] - 1],
1853                                                 v[obj->data.loadavg[2] - 1]);
1854                                 } else if (obj->data.loadavg[1]) {
1855                                         snprintf(p, p_max_size, "%.2f %.2f",
1856                                                 v[obj->data.loadavg[0] - 1],
1857                                                 v[obj->data.loadavg[1] - 1]);
1858                                 } else if (obj->data.loadavg[0]) {
1859                                         snprintf(p, p_max_size, "%.2f",
1860                                                 v[obj->data.loadavg[0] - 1]);
1861                                 }
1862                         }
1863                         OBJ(goto) {
1864                                 new_goto(p, obj->data.i);
1865                         }
1866                         OBJ(tab) {
1867                                 new_tab(p, obj->data.pair.a, obj->data.pair.b);
1868                         }
1869 #ifdef X11
1870                         OBJ(hr) {
1871                                 new_hr(p, obj->data.i);
1872                         }
1873 #endif
1874                         OBJ(nameserver) {
1875                                 if (cur->nameserver_info.nscount > obj->data.i)
1876                                         snprintf(p, p_max_size, "%s",
1877                                                         cur->nameserver_info.ns_list[obj->data.i]);
1878                         }
1879 #ifdef EVE
1880                         OBJ(eve) {
1881                                 char *skill = eve(obj->data.eve.userid, obj->data.eve.apikey, obj->data.eve.charid);
1882                                 snprintf(p, p_max_size, "%s", skill);
1883                         }
1884 #endif
1885 #ifdef HAVE_CURL
1886                         OBJ(curl) {
1887                                 if (obj->data.curl.uri != NULL) {
1888                                         ccurl_process_info(p, p_max_size, obj->data.curl.uri, obj->data.curl.interval);
1889                                 } else {
1890                                         NORM_ERR("error processing Curl data");
1891                                 }
1892                         }
1893 #endif
1894 #ifdef RSS
1895                         OBJ(rss) {
1896                                 if (obj->data.rss.uri != NULL) {
1897                                         rss_process_info(p, p_max_size, obj->data.rss.uri, obj->data.rss.action, obj->data.rss.act_par, obj->data.rss.interval, obj->data.rss.nrspaces);
1898                                 } else {
1899                                         NORM_ERR("error processing RSS data");
1900                                 }
1901                         }
1902 #endif
1903 #ifdef WEATHER
1904                         OBJ(weather) {
1905                                 if (obj->data.weather.uri != NULL) {
1906                                         weather_process_info(p, p_max_size, obj->data.weather.uri, obj->data.weather.data_type, obj->data.weather.interval);
1907                                 } else {
1908                                         NORM_ERR("error processing weather data, check that you have a valid XOAP key if using XOAP.");
1909                                 }
1910                         }
1911 #endif
1912 #ifdef XOAP
1913                         OBJ(weather_forecast) {
1914                                 if (obj->data.weather_forecast.uri != NULL) {
1915                                         weather_forecast_process_info(p, p_max_size, obj->data.weather_forecast.uri, obj->data.weather_forecast.day, obj->data.weather_forecast.data_type, obj->data.weather_forecast.interval);
1916                                 } else {
1917                                         NORM_ERR("error processing weather forecast data, check that you have a valid XOAP key if using XOAP.");
1918                                 }
1919                         }
1920 #endif
1921 #ifdef HAVE_LUA
1922                         OBJ(lua) {
1923                                 char *str = llua_getstring(obj->data.s);
1924                                 if (str) {
1925                                         snprintf(p, p_max_size, "%s", str);
1926                                         free(str);
1927                                 }
1928                         }
1929                         OBJ(lua_parse) {
1930                                 char *str = llua_getstring(obj->data.s);
1931                                 if (str) {
1932                                         evaluate(str, p);
1933                                         free(str);
1934                                 }
1935                         }
1936                         OBJ(lua_bar) {
1937                                 double per;
1938                                 if (llua_getnumber(obj->data.s, &per)) {
1939 #ifdef X11
1940                                         if(output_methods & TO_X) {
1941                                                 new_bar(p, obj->a, obj->b, (per/100.0 * 255));
1942                                         } else {
1943 #endif /* X11 */
1944                                                 if(!obj->a) obj->a = DEFAULT_BAR_WIDTH_NO_X;
1945                                                 new_bar_in_shell(p, p_max_size, per, obj->a);
1946 #ifdef X11
1947                                         }
1948 #endif /* X11 */
1949                                 }
1950                         }
1951 #ifdef X11
1952                         OBJ(lua_graph) {
1953                                 double per;
1954                                 if (llua_getnumber(obj->data.s, &per)) {
1955                                         new_graph(p, obj->a, obj->b, obj->c, obj->d,
1956                                                         per, obj->e, 1, obj->char_a, obj->char_b);
1957                                 }
1958                         }
1959                         OBJ(lua_gauge) {
1960                                 double per;
1961                                 if (llua_getnumber(obj->data.s, &per)) {
1962                                         new_gauge(p, obj->a, obj->b, (per/100.0 * 255));
1963                                 }
1964                         }
1965 #endif /* X11 */
1966 #endif /* HAVE_LUA */
1967 #ifdef HDDTEMP
1968                         OBJ(hddtemp) {
1969                                 short val;
1970                                 char unit;
1971
1972                                 if (get_hddtemp_info(obj->data.s, &val, &unit)) {
1973                                         snprintf(p, p_max_size, "N/A");
1974                                 } else {
1975                                         temp_print(p, p_max_size, (double)val,
1976                                                         (unit == 'C' ? TEMP_CELSIUS : TEMP_FAHRENHEIT));
1977                                 }
1978                         }
1979 #endif
1980                         OBJ(offset) {
1981                                 new_offset(p, obj->data.i);
1982                         }
1983                         OBJ(voffset) {
1984                                 new_voffset(p, obj->data.i);
1985                         }
1986 #ifdef __linux__
1987                         OBJ(i2c) {
1988                                 double r;
1989
1990                                 r = get_sysfs_info(&obj->data.sysfs.fd, obj->data.sysfs.arg,
1991                                         obj->data.sysfs.devtype, obj->data.sysfs.type);
1992
1993                                 r = r * obj->data.sysfs.factor + obj->data.sysfs.offset;
1994
1995                                 if (!strncmp(obj->data.sysfs.type, "temp", 4)) {
1996                                         temp_print(p, p_max_size, r, TEMP_CELSIUS);
1997                                 } else if (r >= 100.0 || r == 0) {
1998                                         snprintf(p, p_max_size, "%d", (int) r);
1999                                 } else {
2000                                         snprintf(p, p_max_size, "%.1f", r);
2001                                 }
2002                         }
2003                         OBJ(platform) {
2004                                 double r;
2005
2006                                 r = get_sysfs_info(&obj->data.sysfs.fd, obj->data.sysfs.arg,
2007                                         obj->data.sysfs.devtype, obj->data.sysfs.type);
2008
2009                                 r = r * obj->data.sysfs.factor + obj->data.sysfs.offset;
2010
2011                                 if (!strncmp(obj->data.sysfs.type, "temp", 4)) {
2012                                         temp_print(p, p_max_size, r, TEMP_CELSIUS);
2013                                 } else if (r >= 100.0 || r == 0) {
2014                                         snprintf(p, p_max_size, "%d", (int) r);
2015                                 } else {
2016                                         snprintf(p, p_max_size, "%.1f", r);
2017                                 }
2018                         }
2019                         OBJ(hwmon) {
2020                                 double r;
2021
2022                                 r = get_sysfs_info(&obj->data.sysfs.fd, obj->data.sysfs.arg,
2023                                         obj->data.sysfs.devtype, obj->data.sysfs.type);
2024
2025                                 r = r * obj->data.sysfs.factor + obj->data.sysfs.offset;
2026
2027                                 if (!strncmp(obj->data.sysfs.type, "temp", 4)) {
2028                                         temp_print(p, p_max_size, r, TEMP_CELSIUS);
2029                                 } else if (r >= 100.0 || r == 0) {
2030                                         snprintf(p, p_max_size, "%d", (int) r);
2031                                 } else {
2032                                         snprintf(p, p_max_size, "%.1f", r);
2033                                 }
2034                         }
2035 #endif /* __linux__ */
2036                         OBJ(alignr) {
2037                                 new_alignr(p, obj->data.i);
2038                         }
2039                         OBJ(alignc) {
2040                                 new_alignc(p, obj->data.i);
2041                         }
2042                         OBJ(if_empty) {
2043                                 char buf[max_user_text];
2044                                 struct information *tmp_info =
2045                                         malloc(sizeof(struct information));
2046                                 memcpy(tmp_info, cur, sizeof(struct information));
2047                                 generate_text_internal(buf, max_user_text,
2048                                                        *obj->sub, tmp_info);
2049
2050                                 if (strlen(buf) != 0) {
2051                                         DO_JUMP;
2052                                 }
2053                                 free(tmp_info);
2054                         }
2055                         OBJ(if_match) {
2056                                 char expression[max_user_text];
2057                                 int val;
2058                                 struct information *tmp_info;
2059
2060                                 tmp_info = malloc(sizeof(struct information));
2061                                 memcpy(tmp_info, cur, sizeof(struct information));
2062                                 generate_text_internal(expression, max_user_text,
2063                                                        *obj->sub, tmp_info);
2064                                 DBGP("parsed arg into '%s'", expression);
2065
2066                                 val = compare(expression);
2067                                 if (val == -2) {
2068                                         NORM_ERR("compare failed for expression '%s'",
2069                                                         expression);
2070                                 } else if (!val) {
2071                                         DO_JUMP;
2072                                 }
2073                                 free(tmp_info);
2074                         }
2075                         OBJ(if_existing) {
2076                                 if (obj->data.ifblock.str
2077                                     && !check_contains(obj->data.ifblock.s,
2078                                                        obj->data.ifblock.str)) {
2079                                         DO_JUMP;
2080                                 } else if (obj->data.ifblock.s
2081                                            && access(obj->data.ifblock.s, F_OK)) {
2082                                         DO_JUMP;
2083                                 }
2084                         }
2085                         OBJ(if_mounted) {
2086                                 if ((obj->data.ifblock.s)
2087                                                 && (!check_mount(obj->data.ifblock.s))) {
2088                                         DO_JUMP;
2089                                 }
2090                         }
2091                         OBJ(if_running) {
2092 #ifdef __linux__
2093                                 if (!get_process_by_name(obj->data.ifblock.s)) {
2094 #else
2095                                 if ((obj->data.ifblock.s) && system(obj->data.ifblock.s)) {
2096 #endif
2097                                         DO_JUMP;
2098                                 }
2099                         }
2100 #if defined(__linux__)
2101                         OBJ(ioscheduler) {
2102                                 snprintf(p, p_max_size, "%s", get_ioscheduler(obj->data.s));
2103                         }
2104 #endif
2105                         OBJ(kernel) {
2106                                 snprintf(p, p_max_size, "%s", cur->uname_s.release);
2107                         }
2108                         OBJ(machine) {
2109                                 snprintf(p, p_max_size, "%s", cur->uname_s.machine);
2110                         }
2111
2112                         /* memory stuff */
2113                         OBJ(mem) {
2114                                 human_readable(cur->mem * 1024, p, 255);
2115                         }
2116                         OBJ(memeasyfree) {
2117                                 human_readable(cur->memeasyfree * 1024, p, 255);
2118                         }
2119                         OBJ(memfree) {
2120                                 human_readable(cur->memfree * 1024, p, 255);
2121                         }
2122                         OBJ(memmax) {
2123                                 human_readable(cur->memmax * 1024, p, 255);
2124                         }
2125                         OBJ(memperc) {
2126                                 if (cur->memmax)
2127                                         percent_print(p, p_max_size, cur->mem * 100 / cur->memmax);
2128                         }
2129 #ifdef X11
2130                         OBJ(memgauge){
2131                                 new_gauge(p, obj->data.pair.a, obj->data.pair.b,
2132                                         cur->memmax ? (cur->mem * 255) / (cur->memmax) : 0);
2133                         }
2134 #endif /* X11 */
2135                         OBJ(membar) {
2136 #ifdef X11
2137                                 if(output_methods & TO_X) {
2138                                         new_bar(p, obj->data.pair.a, obj->data.pair.b,
2139                                                 cur->memmax ? (cur->mem * 255) / (cur->memmax) : 0);
2140                                 }else{
2141 #endif /* X11 */
2142                                         if(!obj->data.pair.a) obj->data.pair.a = DEFAULT_BAR_WIDTH_NO_X;
2143                                         new_bar_in_shell(p, p_max_size, cur->memmax ? (cur->mem * 100) / (cur->memmax) : 0, obj->data.pair.a);
2144 #ifdef X11
2145                                 }
2146 #endif /* X11 */
2147                         }
2148 #ifdef X11
2149                         OBJ(memgraph) {
2150                                 new_graph(p, obj->a, obj->b, obj->c, obj->d,
2151                                         cur->memmax ? (cur->mem * 100.0) / (cur->memmax) : 0.0,
2152                                         100, 1, obj->char_a, obj->char_b);
2153                         }
2154 #endif /* X11 */
2155                         /* mixer stuff */
2156                         OBJ(mixer) {
2157                                 percent_print(p, p_max_size, mixer_get_avg(obj->data.l));
2158                         }
2159                         OBJ(mixerl) {
2160                                 percent_print(p, p_max_size, mixer_get_left(obj->data.l));
2161                         }
2162                         OBJ(mixerr) {
2163                                 percent_print(p, p_max_size, mixer_get_right(obj->data.l));
2164                         }
2165 #ifdef X11
2166                         OBJ(mixerbar) {
2167                                 new_bar(p, obj->data.mixerbar.w, obj->data.mixerbar.h,
2168                                         mixer_to_255(obj->data.mixerbar.l,mixer_get_avg(obj->data.mixerbar.l)));
2169                         }
2170                         OBJ(mixerlbar) {
2171                                 new_bar(p, obj->data.mixerbar.w, obj->data.mixerbar.h,
2172                                         mixer_to_255(obj->data.mixerbar.l,mixer_get_left(obj->data.mixerbar.l)));
2173                         }
2174                         OBJ(mixerrbar) {
2175                                 new_bar(p, obj->data.mixerbar.w, obj->data.mixerbar.h,
2176                                         mixer_to_255(obj->data.mixerbar.l,mixer_get_right(obj->data.mixerbar.l)));
2177                         }
2178 #endif /* X11 */
2179                         OBJ(if_mixer_mute) {
2180                                 if (!mixer_is_mute(obj->data.ifblock.i)) {
2181                                         DO_JUMP;
2182                                 }
2183                         }
2184 #ifdef X11
2185 #define NOT_IN_X "Not running in X"
2186                         OBJ(monitor) {
2187                                 if(x_initialised != YES) {
2188                                         strncpy(p, NOT_IN_X, p_max_size);
2189                                 }else{
2190                                         snprintf(p, p_max_size, "%d", cur->x11.monitor.current);
2191                                 }
2192                         }
2193                         OBJ(monitor_number) {
2194                                 if(x_initialised != YES) {
2195                                         strncpy(p, NOT_IN_X, p_max_size);
2196                                 }else{
2197                                         snprintf(p, p_max_size, "%d", cur->x11.monitor.number);
2198                                 }
2199                         }
2200                         OBJ(desktop) {
2201                                 if(x_initialised != YES) {
2202                                         strncpy(p, NOT_IN_X, p_max_size);
2203                                 }else{
2204                                         snprintf(p, p_max_size, "%d", cur->x11.desktop.current);
2205                                 }
2206                         }
2207                         OBJ(desktop_number) {
2208                                 if(x_initialised != YES) {
2209                                         strncpy(p, NOT_IN_X, p_max_size);
2210                                 }else{
2211                                         snprintf(p, p_max_size, "%d", cur->x11.desktop.number);
2212                                 }
2213                         }
2214                         OBJ(desktop_name) {
2215                                 if(x_initialised != YES) {
2216                                         strncpy(p, NOT_IN_X, p_max_size);
2217                                 }else if(cur->x11.desktop.name != NULL) {
2218                                         strncpy(p, cur->x11.desktop.name, p_max_size);
2219                                 }
2220                         }
2221 #endif /* X11 */
2222
2223                         /* mail stuff */
2224                         OBJ(mails) {
2225                                 update_mail_count(&obj->data.local_mail);
2226                                 snprintf(p, p_max_size, "%d", obj->data.local_mail.mail_count);
2227                         }
2228                         OBJ(new_mails) {
2229                                 update_mail_count(&obj->data.local_mail);
2230                                 snprintf(p, p_max_size, "%d",
2231                                         obj->data.local_mail.new_mail_count);
2232                         }
2233                         OBJ(seen_mails) {
2234                                 update_mail_count(&obj->data.local_mail);
2235                                 snprintf(p, p_max_size, "%d",
2236                                         obj->data.local_mail.seen_mail_count);
2237                         }
2238                         OBJ(unseen_mails) {
2239                                 update_mail_count(&obj->data.local_mail);
2240                                 snprintf(p, p_max_size, "%d",
2241                                         obj->data.local_mail.unseen_mail_count);
2242                         }
2243                         OBJ(flagged_mails) {
2244                                 update_mail_count(&obj->data.local_mail);
2245                                 snprintf(p, p_max_size, "%d",
2246                                         obj->data.local_mail.flagged_mail_count);
2247                         }
2248                         OBJ(unflagged_mails) {
2249                                 update_mail_count(&obj->data.local_mail);
2250                                 snprintf(p, p_max_size, "%d",
2251                                         obj->data.local_mail.unflagged_mail_count);
2252                         }
2253                         OBJ(forwarded_mails) {
2254                                 update_mail_count(&obj->data.local_mail);
2255                                 snprintf(p, p_max_size, "%d",
2256                                         obj->data.local_mail.forwarded_mail_count);
2257                         }
2258                         OBJ(unforwarded_mails) {
2259                                 update_mail_count(&obj->data.local_mail);
2260                                 snprintf(p, p_max_size, "%d",
2261                                         obj->data.local_mail.unforwarded_mail_count);
2262                         }
2263                         OBJ(replied_mails) {
2264                                 update_mail_count(&obj->data.local_mail);
2265                                 snprintf(p, p_max_size, "%d",
2266                                         obj->data.local_mail.replied_mail_count);
2267                         }
2268                         OBJ(unreplied_mails) {
2269                                 update_mail_count(&obj->data.local_mail);
2270                                 snprintf(p, p_max_size, "%d",
2271                                         obj->data.local_mail.unreplied_mail_count);
2272                         }
2273                         OBJ(draft_mails) {
2274                                 update_mail_count(&obj->data.local_mail);
2275                                 snprintf(p, p_max_size, "%d",
2276                                         obj->data.local_mail.draft_mail_count);
2277                         }
2278                         OBJ(trashed_mails) {
2279                                 update_mail_count(&obj->data.local_mail);
2280                                 snprintf(p, p_max_size, "%d",
2281                                         obj->data.local_mail.trashed_mail_count);
2282                         }
2283                         OBJ(mboxscan) {
2284                                 mbox_scan(obj->data.mboxscan.args, obj->data.mboxscan.output,
2285                                         text_buffer_size);
2286                                 snprintf(p, p_max_size, "%s", obj->data.mboxscan.output);
2287                         }
2288                         OBJ(nodename) {
2289                                 snprintf(p, p_max_size, "%s", cur->uname_s.nodename);
2290                         }
2291                         OBJ(outlinecolor) {
2292                                 new_outline(p, obj->data.l);
2293                         }
2294                         OBJ(processes) {
2295                                 spaced_print(p, p_max_size, "%hu", 4, cur->procs);
2296                         }
2297                         OBJ(running_processes) {
2298                                 spaced_print(p, p_max_size, "%hu", 4, cur->run_procs);
2299                         }
2300                         OBJ(text) {
2301                                 snprintf(p, p_max_size, "%s", obj->data.s);
2302                         }
2303 #ifdef X11
2304                         OBJ(shadecolor) {
2305                                 new_bg(p, obj->data.l);
2306                         }
2307                         OBJ(stippled_hr) {
2308                                 new_stippled_hr(p, obj->data.pair.a, obj->data.pair.b);
2309                         }
2310 #endif /* X11 */
2311                         OBJ(swap) {
2312                                 human_readable(cur->swap * 1024, p, 255);
2313                         }
2314                         OBJ(swapfree) {
2315                                 human_readable(cur->swapfree * 1024, p, 255);
2316                         }
2317                         OBJ(swapmax) {
2318                                 human_readable(cur->swapmax * 1024, p, 255);
2319                         }
2320                         OBJ(swapperc) {
2321                                 if (cur->swapmax == 0) {
2322                                         strncpy(p, "No swap", p_max_size);
2323                                 } else {
2324                                         percent_print(p, p_max_size, cur->swap * 100 / cur->swapmax);
2325                                 }
2326                         }
2327                         OBJ(swapbar) {
2328 #ifdef X11
2329                                 if(output_methods & TO_X) {
2330                                         new_bar(p, obj->data.pair.a, obj->data.pair.b,
2331                                                 cur->swapmax ? (cur->swap * 255) / (cur->swapmax) : 0);
2332                                 }else{
2333 #endif /* X11 */
2334                                         if(!obj->data.pair.a) obj->data.pair.a = DEFAULT_BAR_WIDTH_NO_X;
2335                                         new_bar_in_shell(p, p_max_size, cur->swapmax ? (cur->swap * 100) / (cur->swapmax) : 0, obj->data.pair.a);
2336 #ifdef X11
2337                                 }
2338 #endif /* X11 */
2339                         }
2340                         OBJ(sysname) {
2341                                 snprintf(p, p_max_size, "%s", cur->uname_s.sysname);
2342                         }
2343                         OBJ(time) {
2344                                 time_t t = time(NULL);
2345                                 struct tm *tm = localtime(&t);
2346
2347                                 setlocale(LC_TIME, "");
2348                                 strftime(p, p_max_size, obj->data.s, tm);
2349                         }
2350                         OBJ(utime) {
2351                                 time_t t = time(NULL);
2352                                 struct tm *tm = gmtime(&t);
2353
2354                                 strftime(p, p_max_size, obj->data.s, tm);
2355                         }
2356                         OBJ(tztime) {
2357                                 char *oldTZ = NULL;
2358                                 time_t t;
2359                                 struct tm *tm;
2360
2361                                 if (obj->data.tztime.tz) {
2362                                         oldTZ = getenv("TZ");
2363                                         setenv("TZ", obj->data.tztime.tz, 1);
2364                                         tzset();
2365                                 }
2366                                 t = time(NULL);
2367                                 tm = localtime(&t);
2368
2369                                 setlocale(LC_TIME, "");
2370                                 strftime(p, p_max_size, obj->data.tztime.fmt, tm);
2371                                 if (oldTZ) {
2372                                         setenv("TZ", oldTZ, 1);
2373                                         tzset();
2374                                 } else {
2375                                         unsetenv("TZ");
2376                                 }
2377                                 // Needless to free oldTZ since getenv gives ptr to static data
2378                         }
2379                         OBJ(totaldown) {
2380                                 human_readable(obj->data.net->recv, p, 255);
2381                         }
2382                         OBJ(totalup) {
2383                                 human_readable(obj->data.net->trans, p, 255);
2384                         }
2385                         OBJ(updates) {
2386                                 snprintf(p, p_max_size, "%d", total_updates);
2387                         }
2388                         OBJ(if_updatenr) {
2389                                 if(total_updates % updatereset != obj->data.ifblock.i - 1) {
2390                                         DO_JUMP;
2391                                 }
2392                         }
2393                         OBJ(upspeed) {
2394                                 human_readable(obj->data.net->trans_speed, p, 255);
2395                         }
2396                         OBJ(upspeedf) {
2397                                 spaced_print(p, p_max_size, "%.1f", 8,
2398                                         obj->data.net->trans_speed / 1024.0);
2399                         }
2400 #ifdef X11
2401                         OBJ(upspeedgraph) {
2402                                 new_graph(p, obj->a, obj->b, obj->c, obj->d,
2403                                         obj->data.net->trans_speed / 1024.0, obj->e, 1, obj->char_a, obj->char_b);
2404                         }
2405 #endif /* X11 */
2406                         OBJ(uptime_short) {
2407                                 format_seconds_short(p, p_max_size, (int) cur->uptime);
2408                         }
2409                         OBJ(uptime) {
2410                                 format_seconds(p, p_max_size, (int) cur->uptime);
2411                         }
2412                         OBJ(user_names) {
2413                                 snprintf(p, p_max_size, "%s", cur->users.names);
2414                         }
2415                         OBJ(user_terms) {
2416                                 snprintf(p, p_max_size, "%s", cur->users.terms);
2417                         }
2418                         OBJ(user_times) {
2419                                 snprintf(p, p_max_size, "%s", cur->users.times);
2420                         }
2421                         OBJ(user_number) {
2422                                 snprintf(p, p_max_size, "%d", cur->users.number);
2423                         }
2424 #if (defined(__FreeBSD__) || defined(__FreeBSD_kernel__) \
2425                 || defined(__OpenBSD__)) && (defined(i386) || defined(__i386__))
2426                         OBJ(apm_adapter) {
2427                                 char *msg;
2428
2429                                 msg = get_apm_adapter();
2430                                 snprintf(p, p_max_size, "%s", msg);
2431                                 free(msg);
2432                         }
2433                         OBJ(apm_battery_life) {
2434                                 char *msg;
2435
2436                                 msg = get_apm_battery_life();
2437                                 snprintf(p, p_max_size, "%s", msg);
2438                                 free(msg);
2439                         }
2440                         OBJ(apm_battery_time) {
2441                                 char *msg;
2442
2443                                 msg = get_apm_battery_time();
2444                                 snprintf(p, p_max_size, "%s", msg);
2445                                 free(msg);
2446                         }
2447 #endif /* __FreeBSD__ __OpenBSD__ */
2448
2449 #ifdef MPD
2450 #define mpd_printf(fmt, val) \
2451         snprintf(p, p_max_size, fmt, mpd_get_info()->val)
2452 #define mpd_sprintf(val) { \
2453         if (!obj->data.i || obj->data.i > p_max_size) \
2454                 mpd_printf("%s", val); \
2455         else \
2456                 snprintf(p, obj->data.i, "%s", mpd_get_info()->val); \
2457 }
2458                         OBJ(mpd_title)
2459                                 mpd_sprintf(title);
2460                         OBJ(mpd_artist)
2461                                 mpd_sprintf(artist);
2462                         OBJ(mpd_album)
2463                                 mpd_sprintf(album);
2464                         OBJ(mpd_random)
2465                                 mpd_printf("%s", random);
2466                         OBJ(mpd_repeat)
2467                                 mpd_printf("%s", repeat);
2468                         OBJ(mpd_track)
2469                                 mpd_sprintf(track);
2470                         OBJ(mpd_name)
2471                                 mpd_sprintf(name);
2472                         OBJ(mpd_file)
2473                                 mpd_sprintf(file);
2474                         OBJ(mpd_vol)
2475                                 mpd_printf("%d", volume);
2476                         OBJ(mpd_bitrate)
2477                                 mpd_printf("%d", bitrate);
2478                         OBJ(mpd_status)
2479                                 mpd_printf("%s", status);
2480                         OBJ(mpd_elapsed) {
2481                                 format_media_player_time(p, p_max_size, mpd_get_info()->elapsed);
2482                         }
2483                         OBJ(mpd_length) {
2484                                 format_media_player_time(p, p_max_size, mpd_get_info()->length);
2485                         }
2486                         OBJ(mpd_percent) {
2487                                 percent_print(p, p_max_size, (int)(mpd_get_info()->progress * 100));
2488                         }
2489                         OBJ(mpd_bar) {
2490 #ifdef X11
2491                                 if(output_methods & TO_X) {
2492                                         new_bar(p, obj->data.pair.a, obj->data.pair.b,
2493                                                 (int) (mpd_get_info()->progress * 255.0f));
2494                                 } else {
2495 #endif /* X11 */
2496                                         if(!obj->data.pair.a) obj->data.pair.a = DEFAULT_BAR_WIDTH_NO_X;
2497                                         new_bar_in_shell(p, p_max_size, (int) (mpd_get_info()->progress * 100.0f), obj->data.pair.a);
2498 #ifdef X11
2499                                 }
2500 #endif /* X11 */
2501                         }
2502                         OBJ(mpd_smart) {
2503                                 struct mpd_s *mpd = mpd_get_info();
2504                                 int len = obj->data.i;
2505                                 if (len == 0 || len > p_max_size)
2506                                         len = p_max_size;
2507
2508                                 memset(p, 0, p_max_size);
2509                                 if (mpd->artist && *mpd->artist &&
2510                                     mpd->title && *mpd->title) {
2511                                         snprintf(p, len, "%s - %s", mpd->artist,
2512                                                 mpd->title);
2513                                 } else if (mpd->title && *mpd->title) {
2514                                         snprintf(p, len, "%s", mpd->title);
2515                                 } else if (mpd->artist && *mpd->artist) {
2516                                         snprintf(p, len, "%s", mpd->artist);
2517                                 } else if (mpd->file && *mpd->file) {
2518                                         snprintf(p, len, "%s", mpd->file);
2519                                 } else {
2520                                         *p = 0;
2521                                 }
2522                         }
2523                         OBJ(if_mpd_playing) {
2524                                 if (!mpd_get_info()->is_playing) {
2525                                         DO_JUMP;
2526                                 }
2527                         }
2528 #undef mpd_sprintf
2529 #undef mpd_printf
2530 #endif
2531
2532 #ifdef MOC
2533 #define MOC_PRINT(t, a) \
2534         snprintf(p, p_max_size, "%s", (moc.t ? moc.t : a))
2535                         OBJ(moc_state) {
2536                                 MOC_PRINT(state, "??");
2537                         }
2538                         OBJ(moc_file) {
2539                                 MOC_PRINT(file, "no file");
2540                         }
2541                         OBJ(moc_title) {
2542                                 MOC_PRINT(title, "no title");
2543                         }
2544                         OBJ(moc_artist) {
2545                                 MOC_PRINT(artist, "no artist");
2546                         }
2547                         OBJ(moc_song) {
2548                                 MOC_PRINT(song, "no song");
2549                         }
2550                         OBJ(moc_album) {
2551                                 MOC_PRINT(album, "no album");
2552                         }
2553                         OBJ(moc_totaltime) {
2554                                 MOC_PRINT(totaltime, "0:00");
2555                         }
2556                         OBJ(moc_timeleft) {
2557                                 MOC_PRINT(timeleft, "0:00");
2558                         }
2559                         OBJ(moc_curtime) {
2560                                 MOC_PRINT(curtime, "0:00");
2561                         }
2562                         OBJ(moc_bitrate) {
2563                                 MOC_PRINT(bitrate, "0Kbps");
2564                         }
2565                         OBJ(moc_rate) {
2566                                 MOC_PRINT(rate, "0KHz");
2567                         }
2568 #undef MOC_PRINT
2569 #endif /* MOC */
2570 #ifdef XMMS2
2571                         OBJ(xmms2_artist) {
2572                                 snprintf(p, p_max_size, "%s", cur->xmms2.artist);
2573                         }
2574                         OBJ(xmms2_album) {
2575                                 snprintf(p, p_max_size, "%s", cur->xmms2.album);
2576                         }
2577                         OBJ(xmms2_title) {
2578                                 snprintf(p, p_max_size, "%s", cur->xmms2.title);
2579                         }
2580                         OBJ(xmms2_genre) {
2581                                 snprintf(p, p_max_size, "%s", cur->xmms2.genre);
2582                         }
2583                         OBJ(xmms2_comment) {
2584                                 snprintf(p, p_max_size, "%s", cur->xmms2.comment);
2585                         }
2586                         OBJ(xmms2_url) {
2587                                 snprintf(p, p_max_size, "%s", cur->xmms2.url);
2588                         }
2589                         OBJ(xmms2_status) {
2590                                 snprintf(p, p_max_size, "%s", cur->xmms2.status);
2591                         }
2592                         OBJ(xmms2_date) {
2593                                 snprintf(p, p_max_size, "%s", cur->xmms2.date);
2594                         }
2595                         OBJ(xmms2_tracknr) {
2596                                 if (cur->xmms2.tracknr != -1) {
2597                                         snprintf(p, p_max_size, "%i", cur->xmms2.tracknr);
2598                                 }
2599                         }
2600                         OBJ(xmms2_bitrate) {
2601                                 snprintf(p, p_max_size, "%i", cur->xmms2.bitrate);
2602                         }
2603                         OBJ(xmms2_id) {
2604                                 snprintf(p, p_max_size, "%u", cur->xmms2.id);
2605                         }
2606                         OBJ(xmms2_size) {
2607                                 snprintf(p, p_max_size, "%2.1f", cur->xmms2.size);
2608                         }
2609                         OBJ(xmms2_elapsed) {
2610                                 snprintf(p, p_max_size, "%02d:%02d", cur->xmms2.elapsed / 60000,
2611                                         (cur->xmms2.elapsed / 1000) % 60);
2612                         }
2613                         OBJ(xmms2_duration) {
2614                                 snprintf(p, p_max_size, "%02d:%02d",
2615                                         cur->xmms2.duration / 60000,
2616                                         (cur->xmms2.duration / 1000) % 60);
2617                         }
2618                         OBJ(xmms2_percent) {
2619                                 snprintf(p, p_max_size, "%2.0f", cur->xmms2.progress * 100);
2620                         }
2621 #ifdef X11
2622                         OBJ(xmms2_bar) {
2623                                 new_bar(p, obj->data.pair.a, obj->data.pair.b,
2624                                         (int) (cur->xmms2.progress * 255.0f));
2625                         }
2626 #endif /* X11 */
2627                         OBJ(xmms2_playlist) {
2628                                 snprintf(p, p_max_size, "%s", cur->xmms2.playlist);
2629                         }
2630                         OBJ(xmms2_timesplayed) {
2631                                 snprintf(p, p_max_size, "%i", cur->xmms2.timesplayed);
2632                         }
2633                         OBJ(xmms2_smart) {
2634                                 if (strlen(cur->xmms2.title) < 2
2635                                                 && strlen(cur->xmms2.title) < 2) {
2636                                         snprintf(p, p_max_size, "%s", cur->xmms2.url);
2637                                 } else {
2638                                         snprintf(p, p_max_size, "%s - %s", cur->xmms2.artist,
2639                                                 cur->xmms2.title);
2640                                 }
2641                         }
2642                         OBJ(if_xmms2_connected) {
2643                                 if (cur->xmms2.conn_state != 1) {
2644                                         DO_JUMP;
2645                                 }
2646                         }
2647 #endif /* XMMS */
2648 #ifdef AUDACIOUS
2649                         OBJ(audacious_status) {
2650                                 snprintf(p, p_max_size, "%s",
2651                                         cur->audacious.items[AUDACIOUS_STATUS]);
2652                         }
2653                         OBJ(audacious_title) {
2654                                 snprintf(p, cur->audacious.max_title_len > 0
2655                                         ? cur->audacious.max_title_len : p_max_size, "%s",
2656                                         cur->audacious.items[AUDACIOUS_TITLE]);
2657                         }
2658                         OBJ(audacious_length) {
2659                                 snprintf(p, p_max_size, "%s",
2660                                         cur->audacious.items[AUDACIOUS_LENGTH]);
2661                         }
2662                         OBJ(audacious_length_seconds) {
2663                                 snprintf(p, p_max_size, "%s",
2664                                         cur->audacious.items[AUDACIOUS_LENGTH_SECONDS]);
2665                         }
2666                         OBJ(audacious_position) {
2667                                 snprintf(p, p_max_size, "%s",
2668                                         cur->audacious.items[AUDACIOUS_POSITION]);
2669                         }
2670                         OBJ(audacious_position_seconds) {
2671                                 snprintf(p, p_max_size, "%s",
2672                                         cur->audacious.items[AUDACIOUS_POSITION_SECONDS]);
2673                         }
2674                         OBJ(audacious_bitrate) {
2675                                 snprintf(p, p_max_size, "%s",
2676                                         cur->audacious.items[AUDACIOUS_BITRATE]);
2677                         }
2678                         OBJ(audacious_frequency) {
2679                                 snprintf(p, p_max_size, "%s",
2680                                         cur->audacious.items[AUDACIOUS_FREQUENCY]);
2681                         }
2682                         OBJ(audacious_channels) {
2683                                 snprintf(p, p_max_size, "%s",
2684                                         cur->audacious.items[AUDACIOUS_CHANNELS]);
2685                         }
2686                         OBJ(audacious_filename) {
2687                                 snprintf(p, p_max_size, "%s",
2688                                         cur->audacious.items[AUDACIOUS_FILENAME]);
2689                         }
2690                         OBJ(audacious_playlist_length) {
2691                                 snprintf(p, p_max_size, "%s",
2692                                         cur->audacious.items[AUDACIOUS_PLAYLIST_LENGTH]);
2693                         }
2694                         OBJ(audacious_playlist_position) {
2695                                 snprintf(p, p_max_size, "%s",
2696                                         cur->audacious.items[AUDACIOUS_PLAYLIST_POSITION]);
2697                         }
2698                         OBJ(audacious_main_volume) {
2699                                 snprintf(p, p_max_size, "%s",
2700                                         cur->audacious.items[AUDACIOUS_MAIN_VOLUME]);
2701                         }
2702 #ifdef X11
2703                         OBJ(audacious_bar) {
2704                                 double progress;
2705
2706                                 progress =
2707                                         atof(cur->audacious.items[AUDACIOUS_POSITION_SECONDS]) /
2708                                         atof(cur->audacious.items[AUDACIOUS_LENGTH_SECONDS]);
2709                                 new_bar(p, obj->a, obj->b, (int) (progress * 255.0f));
2710                         }
2711 #endif /* X11 */
2712 #endif /* AUDACIOUS */
2713
2714 #ifdef BMPX
2715                         OBJ(bmpx_title) {
2716                                 snprintf(p, p_max_size, "%s", cur->bmpx.title);
2717                         }
2718                         OBJ(bmpx_artist) {
2719                                 snprintf(p, p_max_size, "%s", cur->bmpx.artist);
2720                         }
2721                         OBJ(bmpx_album) {
2722                                 snprintf(p, p_max_size, "%s", cur->bmpx.album);
2723                         }
2724                         OBJ(bmpx_uri) {
2725                                 snprintf(p, p_max_size, "%s", cur->bmpx.uri);
2726                         }
2727                         OBJ(bmpx_track) {
2728                                 snprintf(p, p_max_size, "%i", cur->bmpx.track);
2729                         }
2730                         OBJ(bmpx_bitrate) {
2731                                 snprintf(p, p_max_size, "%i", cur->bmpx.bitrate);
2732                         }
2733 #endif /* BMPX */
2734                         /* we have four different types of top (top, top_mem,
2735                          * top_time and top_io). To avoid having almost-same code four
2736                          * times, we have this special handler. */
2737                         break;
2738                         case OBJ_top:
2739                                 parse_top_args("top", obj->data.top.s, obj);
2740                                 if (!needed) needed = cur->cpu;
2741                         case OBJ_top_mem:
2742                                 parse_top_args("top_mem", obj->data.top.s, obj);
2743                                 if (!needed) needed = cur->memu;
2744                         case OBJ_top_time:
2745                                 parse_top_args("top_time", obj->data.top.s, obj);
2746                                 if (!needed) needed = cur->time;
2747 #ifdef IOSTATS
2748                         case OBJ_top_io:
2749                                 parse_top_args("top_io", obj->data.top.s, obj);
2750                                 if (!needed) needed = cur->io;
2751 #endif
2752
2753                                 if (needed[obj->data.top.num]) {
2754                                         char *timeval;
2755
2756                                         switch (obj->data.top.type) {
2757                                                 case TOP_NAME:
2758                                                         snprintf(p, top_name_width + 1, "%-*s", top_name_width,
2759                                                                         needed[obj->data.top.num]->name);
2760                                                         break;
2761                                                 case TOP_CPU:
2762                                                         snprintf(p, 7, "%6.2f",
2763                                                                         needed[obj->data.top.num]->amount);
2764                                                         break;
2765                                                 case TOP_PID:
2766                                                         snprintf(p, 6, "%5i",
2767                                                                         needed[obj->data.top.num]->pid);
2768                                                         break;
2769                                                 case TOP_MEM:
2770                                                         snprintf(p, 7, "%6.2f",
2771                                                                         needed[obj->data.top.num]->totalmem);
2772                                                         break;
2773                                                 case TOP_TIME:
2774                                                         timeval = format_time(
2775                                                                         needed[obj->data.top.num]->total_cpu_time, 9);
2776                                                         snprintf(p, 10, "%9s", timeval);
2777                                                         free(timeval);
2778                                                         break;
2779                                                 case TOP_MEM_RES:
2780                                                         human_readable(needed[obj->data.top.num]->rss,
2781                                                                         p, 255);
2782                                                         break;
2783                                                 case TOP_MEM_VSIZE:
2784                                                         human_readable(needed[obj->data.top.num]->vsize,
2785                                                                         p, 255);
2786                                                         break;
2787 #ifdef IOSTATS
2788                                                 case TOP_READ_BYTES:
2789                                                         human_readable(needed[obj->data.top.num]->read_bytes / update_interval,
2790                                                                         p, 255);
2791                                                         break;
2792                                                 case TOP_WRITE_BYTES:
2793                                                         human_readable(needed[obj->data.top.num]->write_bytes / update_interval,
2794                                                                         p, 255);
2795                                                         break;
2796                                                 case TOP_IO_PERC:
2797                                                         snprintf(p, 7, "%6.2f",
2798                                                                         needed[obj->data.top.num]->io_perc);
2799                                                         break;
2800 #endif
2801                                         }
2802                                 }
2803                         OBJ(tail) {
2804                                 print_tailhead("tail", obj, p, p_max_size);
2805                         }
2806                         OBJ(head) {
2807                                 print_tailhead("head", obj, p, p_max_size);
2808                         }
2809                         OBJ(lines) {
2810                                 FILE *fp = open_file(obj->data.s, &obj->a);
2811
2812                                 if(fp != NULL) {
2813 /* FIXME: use something more general (see also tail.c, head.c */
2814 #define BUFSZ 0x1000
2815                                         char buf[BUFSZ];
2816                                         int j, lines;
2817
2818                                         lines = 0;
2819                                         while(fgets(buf, BUFSZ, fp) != NULL){
2820                                                 for(j = 0; buf[j] != 0; j++) {
2821                                                         if(buf[j] == '\n') {
2822                                                                 lines++;
2823                                                         }
2824                                                 }
2825                                         }
2826                                         sprintf(p, "%d", lines);
2827                                         fclose(fp);
2828                                 } else {
2829                                         sprintf(p, "File Unreadable");
2830                                 }
2831                         }
2832
2833                         OBJ(words) {
2834                                 FILE *fp = open_file(obj->data.s, &obj->a);
2835
2836                                 if(fp != NULL) {
2837                                         char buf[BUFSZ];
2838                                         int j, words;
2839                                         char inword = FALSE;
2840
2841                                         words = 0;
2842                                         while(fgets(buf, BUFSZ, fp) != NULL){
2843                                                 for(j = 0; buf[j] != 0; j++) {
2844                                                         if(!isspace(buf[j])) {
2845                                                                 if(inword == FALSE) {
2846                                                                         words++;
2847                                                                         inword = TRUE;
2848                                                                 }
2849                                                         } else {
2850                                                                 inword = FALSE;
2851                                                         }
2852                                                 }
2853                                         }
2854                                         sprintf(p, "%d", words);
2855                                         fclose(fp);
2856                                 } else {
2857                                         sprintf(p, "File Unreadable");
2858                                 }
2859                         }
2860 #ifdef TCP_PORT_MONITOR
2861                         OBJ(tcp_portmon) {
2862                                 tcp_portmon_action(p, p_max_size,
2863                                                    &obj->data.tcp_port_monitor);
2864                         }
2865 #endif /* TCP_PORT_MONITOR */
2866
2867 #ifdef HAVE_ICONV
2868                         OBJ(iconv_start) {
2869                                 set_iconv_converting(1);
2870                                 set_iconv_selected(obj->a);
2871                         }
2872                         OBJ(iconv_stop) {
2873                                 set_iconv_converting(0);
2874                                 set_iconv_selected(0);
2875                         }
2876 #endif /* HAVE_ICONV */
2877
2878                         OBJ(entropy_avail) {
2879                                 snprintf(p, p_max_size, "%d", cur->entropy.entropy_avail);
2880                         }
2881                         OBJ(entropy_perc) {
2882                                 percent_print(p, p_max_size,
2883                                               cur->entropy.entropy_avail *
2884                                               100 / cur->entropy.poolsize);
2885                         }
2886                         OBJ(entropy_poolsize) {
2887                                 snprintf(p, p_max_size, "%d", cur->entropy.poolsize);
2888                         }
2889                         OBJ(entropy_bar) {
2890                                 double entropy_perc;
2891
2892                                 entropy_perc = (double) cur->entropy.entropy_avail /
2893                                         (double) cur->entropy.poolsize;
2894 #ifdef X11
2895                                 if(output_methods & TO_X) {
2896                                         new_bar(p, obj->a, obj->b, (int) (entropy_perc * 255.0f));
2897                                 } else {
2898 #endif /* X11 */
2899                                         if(!obj->a) obj->a = DEFAULT_BAR_WIDTH_NO_X;
2900                                         new_bar_in_shell(p, p_max_size, (int) (entropy_perc * 100.0f), obj->a);
2901 #ifdef X11
2902                                 }
2903 #endif /* X11 */
2904                         }
2905 #ifdef IBM
2906                         OBJ(smapi) {
2907                                 char *s;
2908                                 if(obj->data.s) {
2909                                         s = smapi_get_val(obj->data.s);
2910                                         snprintf(p, p_max_size, "%s", s);
2911                                         free(s);
2912                                 }
2913                         }
2914                         OBJ(if_smapi_bat_installed) {
2915                                 int idx;
2916                                 if(obj->data.ifblock.s && sscanf(obj->data.ifblock.s, "%i", &idx) == 1) {
2917                                         if(!smapi_bat_installed(idx)) {
2918                                                 DO_JUMP;
2919                                         }
2920                                 } else
2921                                         NORM_ERR("argument to if_smapi_bat_installed must be an integer");
2922                         }
2923                         OBJ(smapi_bat_perc) {
2924                                 int idx, val;
2925                                 if(obj->data.s && sscanf(obj->data.s, "%i", &idx) == 1) {
2926                                         val = smapi_bat_installed(idx) ?
2927                                                 smapi_get_bat_int(idx, "remaining_percent") : 0;
2928                                         percent_print(p, p_max_size, val);
2929                                 } else
2930                                         NORM_ERR("argument to smapi_bat_perc must be an integer");
2931                         }
2932                         OBJ(smapi_bat_temp) {
2933                                 int idx, val;
2934                                 if(obj->data.s && sscanf(obj->data.s, "%i", &idx) == 1) {
2935                                         val = smapi_bat_installed(idx) ?
2936                                                 smapi_get_bat_int(idx, "temperature") : 0;
2937                                         /* temperature is in milli degree celsius */
2938                                         temp_print(p, p_max_size, val / 1000, TEMP_CELSIUS);
2939                                 } else
2940                                         NORM_ERR("argument to smapi_bat_temp must be an integer");
2941                         }
2942                         OBJ(smapi_bat_power) {
2943                                 int idx, val;
2944                                 if(obj->data.s && sscanf(obj->data.s, "%i", &idx) == 1) {
2945                                         val = smapi_bat_installed(idx) ?
2946                                                 smapi_get_bat_int(idx, "power_now") : 0;
2947                                         /* power_now is in mW, set to W with one digit precision */
2948                                         snprintf(p, p_max_size, "%.1f", ((double)val / 1000));
2949                                 } else
2950                                         NORM_ERR("argument to smapi_bat_power must be an integer");
2951                         }
2952 #ifdef X11
2953                         OBJ(smapi_bat_bar) {
2954                                 if(obj->data.i >= 0 && smapi_bat_installed(obj->data.i))
2955                                         new_bar(p, obj->a, obj->b, (int)
2956                                                         (255 * smapi_get_bat_int(obj->data.i, "remaining_percent") / 100));
2957                                 else
2958                                         new_bar(p, obj->a, obj->b, 0);
2959                         }
2960 #endif /* X11 */
2961 #endif /* IBM */
2962                         OBJ(include) {
2963                                 if(obj->sub) {
2964                                         char buf[max_user_text];
2965
2966                                         generate_text_internal(buf, max_user_text, *obj->sub, cur);
2967                                         snprintf(p, p_max_size, "%s", buf);
2968                                 } else {
2969                                         p[0] = 0;
2970                                 }
2971                         }
2972                         OBJ(blink) {
2973                                 //blinking like this can look a bit ugly if the chars in the font don't have the same width
2974                                 char buf[max_user_text];
2975                                 unsigned int j;
2976
2977                                 generate_text_internal(buf, max_user_text, *obj->sub, cur);
2978                                 snprintf(p, p_max_size, "%s", buf);
2979                                 if(total_updates % 2) {
2980                                         for(j=0; p[j] != 0; j++) {
2981                                                 p[j] = ' ';
2982                                         }
2983                                 }
2984                         }
2985                         OBJ(to_bytes) {
2986                                 char buf[max_user_text];
2987                                 long long bytes;
2988                                 char unit[16];  // 16 because we can also have long names (like mega-bytes)
2989
2990                                 generate_text_internal(buf, max_user_text, *obj->sub, cur);
2991                                 if(sscanf(buf, "%lli%s", &bytes, unit) == 2 && strlen(unit) < 16){
2992                                         if(strncasecmp("b", unit, 1) == 0) snprintf(buf, max_user_text, "%lli", bytes);
2993                                         else if(strncasecmp("k", unit, 1) == 0) snprintf(buf, max_user_text, "%lli", bytes * 1024);
2994                                         else if(strncasecmp("m", unit, 1) == 0) snprintf(buf, max_user_text, "%lli", bytes * 1024 * 1024);
2995                                         else if(strncasecmp("g", unit, 1) == 0) snprintf(buf, max_user_text, "%lli", bytes * 1024 * 1024 * 1024);
2996                                         else if(strncasecmp("t", unit, 1) == 0) snprintf(buf, max_user_text, "%lli", bytes * 1024 * 1024 * 1024 * 1024);
2997                                 }
2998                                 snprintf(p, p_max_size, "%s", buf);
2999                         }
3000                         OBJ(scroll) {
3001                                 unsigned int j, colorchanges = 0, frontcolorchanges = 0, visibcolorchanges = 0, strend;
3002                                 char *pwithcolors;
3003                                 char buf[max_user_text];
3004                                 generate_text_internal(buf, max_user_text,
3005                                                        *obj->sub, cur);
3006                                 for(j = 0; buf[j] != 0; j++) {
3007                                         switch(buf[j]) {
3008                                         case '\n':      //place all the lines behind each other with LINESEPARATOR between them
3009 #define LINESEPARATOR '|'
3010                                                 buf[j]=LINESEPARATOR;
3011                                                 break;
3012                                         case SPECIAL_CHAR:
3013                                                 colorchanges++;
3014                                                 break;
3015                                         }
3016                                 }
3017                                 //no scrolling necessary if the length of the text to scroll is too short
3018                                 if (strlen(buf) - colorchanges <= obj->data.scroll.show) {
3019                                         snprintf(p, p_max_size, "%s", buf);
3020                                         break;
3021                                 }
3022                                 //make sure a colorchange at the front is not part of the string we are going to show
3023                                 while(*(buf + obj->data.scroll.start) == SPECIAL_CHAR) {
3024                                         obj->data.scroll.start++;
3025                                 }
3026                                 //place all chars that should be visible in p, including colorchanges
3027                                 for(j=0; j < obj->data.scroll.show + visibcolorchanges; j++) {
3028                                         p[j] = *(buf + obj->data.scroll.start + j);
3029                                         if(p[j] == SPECIAL_CHAR) {
3030                                                 visibcolorchanges++;
3031                                         }
3032                                         //if there is still room fill it with spaces
3033                                         if( ! p[j]) break;
3034                                 }
3035                                 for(; j < obj->data.scroll.show + visibcolorchanges; j++) {
3036                                         p[j] = ' ';
3037                                 }
3038                                 p[j] = 0;
3039                                 //count colorchanges in front of the visible part and place that many colorchanges in front of the visible part
3040                                 for(j = 0; j < obj->data.scroll.start; j++) {
3041                                         if(buf[j] == SPECIAL_CHAR) frontcolorchanges++;
3042                                 }
3043                                 pwithcolors=malloc(strlen(p) + 1 + colorchanges - visibcolorchanges);
3044                                 for(j = 0; j < frontcolorchanges; j++) {
3045                                         pwithcolors[j] = SPECIAL_CHAR;
3046                                 }
3047                                 pwithcolors[j] = 0;
3048                                 strcat(pwithcolors,p);
3049                                 strend = strlen(pwithcolors);
3050                                 //and place the colorchanges not in front or in the visible part behind the visible part
3051                                 for(j = 0; j < colorchanges - frontcolorchanges - visibcolorchanges; j++) {
3052                                         pwithcolors[strend + j] = SPECIAL_CHAR;
3053                                 }
3054                                 pwithcolors[strend + j] = 0;
3055                                 strcpy(p, pwithcolors);
3056                                 free(pwithcolors);
3057                                 //scroll
3058                                 obj->data.scroll.start += obj->data.scroll.step;
3059                                 if(buf[obj->data.scroll.start] == 0){
3060                                          obj->data.scroll.start = 0;
3061                                 }
3062 #ifdef X11
3063                                 //reset color when scroll is finished
3064                                 new_fg(p + strlen(p), obj->data.scroll.resetcolor);
3065 #endif
3066                         }
3067                         OBJ(combine) {
3068                                 char buf[2][max_user_text];
3069                                 int i, j;
3070                                 long longest=0;
3071                                 int nextstart;
3072                                 int nr_rows[2];
3073                                 struct llrows {
3074                                         char* row;
3075                                         struct llrows* next;
3076                                 };
3077                                 struct llrows *ll_rows[2], *current[2];
3078                                 struct text_object * objsub = obj->sub;
3079
3080                                 p[0]=0;
3081                                 for(i=0; i<2; i++) {
3082                                         nr_rows[i] = 1;
3083                                         nextstart = 0;
3084                                         ll_rows[i] = malloc(sizeof(struct llrows));
3085                                         current[i] = ll_rows[i];
3086                                         for(j=0; j<i; j++) objsub = objsub->sub;
3087                                         generate_text_internal(buf[i], max_user_text, *objsub, cur);
3088                                         for(j=0; buf[i][j] != 0; j++) {
3089                                                 if(buf[i][j] == '\t') buf[i][j] = ' ';
3090                                                 if(buf[i][j] == '\n') {
3091                                                         buf[i][j] = 0;
3092                                                         current[i]->row = strdup(buf[i]+nextstart);
3093                                                         if(i==0 && (long)strlen(current[i]->row) > longest) longest = (long)strlen(current[i]->row);
3094                                                         current[i]->next = malloc(sizeof(struct llrows));
3095                                                         current[i] = current[i]->next;
3096                                                         nextstart = j + 1;
3097                                                         nr_rows[i]++;
3098                                                 }
3099                                         }
3100                                         current[i]->row = strdup(buf[i]+nextstart);
3101                                         if(i==0 && (long)strlen(current[i]->row) > longest) longest = (long)strlen(current[i]->row);
3102                                         current[i]->next = NULL;
3103                                         current[i] = ll_rows[i];
3104                                 }
3105                                 for(j=0; j < (nr_rows[0] > nr_rows[1] ? nr_rows[0] : nr_rows[1] ); j++) {
3106                                         if(current[0]) {
3107                                                 strcat(p, current[0]->row);
3108                                                 i=strlen(current[0]->row);
3109                                         }else i = 0;
3110                                         while(i < longest) {
3111                                                 strcat(p, " ");
3112                                                 i++;
3113                                         }
3114                                         if(current[1]) {
3115                                                 strcat(p, obj->data.combine.seperation);
3116                                                 strcat(p, current[1]->row);
3117                                         }
3118                                         strcat(p, "\n");
3119                                         #ifdef HAVE_OPENMP
3120                                         #pragma omp parallel for schedule(dynamic,10)
3121                                         #endif /* HAVE_OPENMP */
3122                                         for(i=0; i<2; i++) if(current[i]) current[i]=current[i]->next;
3123                                 }
3124                                 #ifdef HAVE_OPENMP
3125                                 #pragma omp parallel for schedule(dynamic,10)
3126                                 #endif /* HAVE_OPENMP */
3127                                 for(i=0; i<2; i++) {
3128                                         while(ll_rows[i] != NULL) {
3129                                                 current[i]=ll_rows[i];
3130                                                 free(current[i]->row);
3131                                                 ll_rows[i]=current[i]->next;
3132                                                 free(current[i]);
3133                                         }
3134                                 }
3135                         }
3136 #ifdef NVIDIA
3137                         OBJ(nvidia) {
3138                                 int value = get_nvidia_value(obj->data.nvidia.type, display);
3139                                 if(value == -1)
3140                                         snprintf(p, p_max_size, "N/A");
3141                                 else if (obj->data.nvidia.type == NV_TEMP)
3142                                         temp_print(p, p_max_size, (double)value, TEMP_CELSIUS);
3143                                 else if (obj->data.nvidia.print_as_float &&
3144                                                 value > 0 && value < 100)
3145                                         snprintf(p, p_max_size, "%.1f", (float)value);
3146                                 else
3147                                         snprintf(p, p_max_size, "%d", value);
3148                         }
3149 #endif /* NVIDIA */
3150 #ifdef APCUPSD
3151                         OBJ(apcupsd) {
3152                                 /* This is just a meta-object to set host:port */
3153                         }
3154                         OBJ(apcupsd_name) {
3155                                 snprintf(p, p_max_size, "%s",
3156                                                  cur->apcupsd.items[APCUPSD_NAME]);
3157                         }
3158                         OBJ(apcupsd_model) {
3159                                 snprintf(p, p_max_size, "%s",
3160                                                  cur->apcupsd.items[APCUPSD_MODEL]);
3161                         }
3162                         OBJ(apcupsd_upsmode) {
3163                                 snprintf(p, p_max_size, "%s",
3164                                                  cur->apcupsd.items[APCUPSD_UPSMODE]);
3165                         }
3166                         OBJ(apcupsd_cable) {
3167                                 snprintf(p, p_max_size, "%s",
3168                                                  cur->apcupsd.items[APCUPSD_CABLE]);
3169                         }
3170                         OBJ(apcupsd_status) {
3171                                 snprintf(p, p_max_size, "%s",
3172                                                  cur->apcupsd.items[APCUPSD_STATUS]);
3173                         }
3174                         OBJ(apcupsd_linev) {
3175                                 snprintf(p, p_max_size, "%s",
3176                                                  cur->apcupsd.items[APCUPSD_LINEV]);
3177                         }
3178                         OBJ(apcupsd_load) {
3179                                 snprintf(p, p_max_size, "%s",
3180                                                  cur->apcupsd.items[APCUPSD_LOAD]);
3181                         }
3182                         OBJ(apcupsd_loadbar) {
3183                                 double progress;
3184 #ifdef X11
3185                                 if(output_methods & TO_X) {
3186                                         progress = atof(cur->apcupsd.items[APCUPSD_LOAD]) / 100.0 * 255.0;
3187                                         new_bar(p, obj->a, obj->b, (int) progress);
3188                                 } else {
3189 #endif /* X11 */
3190                                         progress = atof(cur->apcupsd.items[APCUPSD_LOAD]);
3191                                         if(!obj->a) obj->a = DEFAULT_BAR_WIDTH_NO_X;
3192                                         new_bar_in_shell(p, p_max_size, (int) progress, obj->a);
3193 #ifdef X11
3194                                 }
3195 #endif /* X11 */
3196                         }
3197 #ifdef X11
3198                         OBJ(apcupsd_loadgraph) {
3199                                 double progress;
3200                                 progress =      atof(cur->apcupsd.items[APCUPSD_LOAD]);
3201                                 new_graph(p, obj->a, obj->b, obj->c, obj->d,
3202                                                   (int)progress, 100, 1, obj->char_a, obj->char_b);
3203                         }
3204                         OBJ(apcupsd_loadgauge) {
3205                                 double progress;
3206                                 progress =      atof(cur->apcupsd.items[APCUPSD_LOAD]) / 100.0 * 255.0;
3207                                 new_gauge(p, obj->a, obj->b,
3208                                                   (int)progress);
3209                         }
3210 #endif /* X11 */
3211                         OBJ(apcupsd_charge) {
3212                                 snprintf(p, p_max_size, "%s",
3213                                                  cur->apcupsd.items[APCUPSD_CHARGE]);
3214                         }
3215                         OBJ(apcupsd_timeleft) {
3216                                 snprintf(p, p_max_size, "%s",
3217                                                  cur->apcupsd.items[APCUPSD_TIMELEFT]);
3218                         }
3219                         OBJ(apcupsd_temp) {
3220                                 snprintf(p, p_max_size, "%s",
3221                                                  cur->apcupsd.items[APCUPSD_TEMP]);
3222                         }
3223                         OBJ(apcupsd_lastxfer) {
3224                                 snprintf(p, p_max_size, "%s",
3225                                                  cur->apcupsd.items[APCUPSD_LASTXFER]);
3226                         }
3227 #endif /* APCUPSD */
3228                         break;
3229                 }
3230 #undef DO_JUMP
3231
3232
3233                 {
3234                         size_t a = strlen(p);
3235
3236 #ifdef HAVE_ICONV
3237                         iconv_convert(a, buff_in, p, p_max_size);
3238 #endif /* HAVE_ICONV */
3239                         if (obj->type != OBJ_text && obj->type != OBJ_execp && obj->type != OBJ_execpi
3240                                         && obj->type != OBJ_lua && obj->type != OBJ_lua_parse) {
3241                                 substitute_newlines(p, a - 2);
3242                         }
3243                         p += a;
3244                         p_max_size -= a;
3245                 }
3246                 obj = obj->next;
3247         }
3248 #ifdef X11
3249         /* load any new fonts we may have had */
3250         if (need_to_load_fonts) {
3251                 load_fonts();
3252         }
3253 #endif /* X11 */
3254 }
3255
3256 void evaluate(const char *text, char *buffer)
3257 {
3258         struct information *tmp_info;
3259         struct text_object subroot;
3260
3261         tmp_info = malloc(sizeof(struct information));
3262         memcpy(tmp_info, &info, sizeof(struct information));
3263         parse_conky_vars(&subroot, text, buffer, tmp_info);
3264         DBGP("evaluated '%s' to '%s'", text, buffer);
3265
3266         free_text_objects(&subroot, 1);
3267         free(tmp_info);
3268 }
3269
3270 double current_update_time, next_update_time, last_update_time;
3271
3272 static void generate_text(void)
3273 {
3274         struct information *cur = &info;
3275         char *p;
3276
3277         special_count = 0;
3278
3279         /* update info */
3280
3281         current_update_time = get_time();
3282
3283         update_stuff();
3284
3285         /* add things to the buffer */
3286
3287         /* generate text */
3288
3289         p = text_buffer;
3290
3291         generate_text_internal(p, max_user_text, global_root_object, cur);
3292
3293         if (stuff_in_uppercase) {
3294                 char *tmp_p;
3295
3296                 tmp_p = text_buffer;
3297                 while (*tmp_p) {
3298                         *tmp_p = toupper(*tmp_p);
3299                         tmp_p++;
3300                 }
3301         }
3302
3303         next_update_time += update_interval;
3304         if (next_update_time < get_time()) {
3305                 next_update_time = get_time() + update_interval;
3306         } else if (next_update_time > get_time() + update_interval) {
3307                 next_update_time = get_time() + update_interval;
3308         }
3309         last_update_time = current_update_time;
3310         total_updates++;
3311 }
3312
3313 void set_update_interval(double interval)
3314 {
3315         update_interval = interval;
3316         update_interval_old = interval;
3317 }
3318
3319 static inline int get_string_width(const char *s)
3320 {
3321 #ifdef X11
3322         if (output_methods & TO_X) {
3323                 return *s ? calc_text_width(s, strlen(s)) : 0;
3324         }
3325 #endif /* X11 */
3326         return strlen(s);
3327 }
3328
3329 #ifdef X11
3330 static int get_string_width_special(char *s, int special_index)
3331 {
3332         char *p, *final;
3333         int idx = 1;
3334         int width = 0;
3335         long i;
3336
3337         if ((output_methods & TO_X) == 0) {
3338                 return (s) ? strlen(s) : 0;
3339         }
3340
3341         if (!s) {
3342                 return 0;
3343         }
3344
3345         p = strndup(s, text_buffer_size);
3346         final = p;
3347
3348         while (*p) {
3349                 if (*p == SPECIAL_CHAR) {
3350                         /* shift everything over by 1 so that the special char
3351                          * doesn't mess up the size calculation */
3352                         for (i = 0; i < (long)strlen(p); i++) {
3353                                 *(p + i) = *(p + i + 1);
3354                         }
3355                         if (specials[special_index + idx].type == GRAPH
3356                                         || specials[special_index + idx].type == GAUGE
3357                                         || specials[special_index + idx].type == BAR) {
3358                                 width += specials[special_index + idx].width;
3359                         }
3360                         idx++;
3361                 } else if (*p == SECRIT_MULTILINE_CHAR) {
3362                         *p = 0;
3363                         break;
3364                 } else {
3365                         p++;
3366                 }
3367         }
3368         if (strlen(final) > 1) {
3369                 width += calc_text_width(final, strlen(final));
3370         }
3371         free(final);
3372         return width;
3373 }
3374
3375 static int text_size_updater(char *s, int special_index);
3376
3377 int last_font_height;
3378 static void update_text_area(void)
3379 {
3380         int x = 0, y = 0;
3381
3382         if ((output_methods & TO_X) == 0)
3383                 return;
3384         /* update text size if it isn't fixed */
3385 #ifdef OWN_WINDOW
3386         if (!fixed_size)
3387 #endif
3388         {
3389                 text_width = minimum_width;
3390                 text_height = 0;
3391                 last_font_height = font_height();
3392                 for_each_line(text_buffer, text_size_updater);
3393                 text_width += 1;
3394                 if (text_height < minimum_height) {
3395                         text_height = minimum_height;
3396                 }
3397                 if (text_width > maximum_width && maximum_width > 0) {
3398                         text_width = maximum_width;
3399                 }
3400         }
3401
3402         /* get text position on workarea */
3403         switch (text_alignment) {
3404                 case TOP_LEFT:
3405                         x = gap_x;
3406                         y = gap_y;
3407                         break;
3408
3409                 case TOP_RIGHT:
3410                         x = workarea[2] - text_width - gap_x;
3411                         y = gap_y;
3412                         break;
3413
3414                 case TOP_MIDDLE:
3415                         x = workarea[2] / 2 - text_width / 2 - gap_x;
3416                         y = gap_y;
3417                         break;
3418
3419                 default:
3420                 case BOTTOM_LEFT:
3421                         x = gap_x;
3422                         y = workarea[3] - text_height - gap_y;
3423                         break;
3424
3425                 case BOTTOM_RIGHT:
3426                         x = workarea[2] - text_width - gap_x;
3427                         y = workarea[3] - text_height - gap_y;
3428                         break;
3429
3430                 case BOTTOM_MIDDLE:
3431                         x = workarea[2] / 2 - text_width / 2 - gap_x;
3432                         y = workarea[3] - text_height - gap_y;
3433                         break;
3434
3435                 case MIDDLE_LEFT:
3436                         x = gap_x;
3437                         y = workarea[3] / 2 - text_height / 2 - gap_y;
3438                         break;
3439
3440                 case MIDDLE_RIGHT:
3441                         x = workarea[2] - text_width - gap_x;
3442                         y = workarea[3] / 2 - text_height / 2 - gap_y;
3443                         break;
3444
3445 #ifdef OWN_WINDOW
3446                 case NONE:      // Let the WM manage the window
3447                         x = window.x;
3448                         y = window.y;
3449
3450                         fixed_pos = 1;
3451                         fixed_size = 1;
3452                         break;
3453 #endif
3454         }
3455 #ifdef OWN_WINDOW
3456
3457         if (own_window && !fixed_pos) {
3458                 x += workarea[0];
3459                 y += workarea[1];
3460                 text_start_x = window.border_inner_margin + window.border_outer_margin + window.border_width;
3461                 text_start_y = window.border_inner_margin + window.border_outer_margin + window.border_width;
3462                 window.x = x - window.border_inner_margin - window.border_outer_margin - window.border_width;
3463                 window.y = y - window.border_inner_margin - window.border_outer_margin - window.border_width;
3464         } else
3465 #endif
3466         {
3467                 /* If window size doesn't match to workarea's size,
3468                  * then window probably includes panels (gnome).
3469                  * Blah, doesn't work on KDE. */
3470                 if (workarea[2] != window.width || workarea[3] != window.height) {
3471                         y += workarea[1];
3472                         x += workarea[0];
3473                 }
3474
3475                 text_start_x = x;
3476                 text_start_y = y;
3477         }
3478 #ifdef HAVE_LUA
3479         /* update lua window globals */
3480         llua_update_window_table(text_start_x, text_start_y, text_width, text_height);
3481 #endif /* HAVE_LUA */
3482 }
3483
3484 /* drawing stuff */
3485
3486 static int cur_x, cur_y;        /* current x and y for drawing */
3487 #endif
3488 //draw_mode also without X11 because we only need to print to stdout with FG
3489 static int draw_mode;           /* FG, BG or OUTLINE */
3490 #ifdef X11
3491 static long current_color;
3492
3493 static int text_size_updater(char *s, int special_index)
3494 {
3495         int w = 0;
3496         char *p;
3497
3498         if ((output_methods & TO_X) == 0)
3499                 return 0;
3500         /* get string widths and skip specials */
3501         p = s;
3502         while (*p) {
3503                 if (*p == SPECIAL_CHAR) {
3504                         *p = '\0';
3505                         w += get_string_width(s);
3506                         *p = SPECIAL_CHAR;
3507
3508                         if (specials[special_index].type == BAR
3509                                         || specials[special_index].type == GAUGE
3510                                         || specials[special_index].type == GRAPH) {
3511                                 w += specials[special_index].width;
3512                                 if (specials[special_index].height > last_font_height) {
3513                                         last_font_height = specials[special_index].height;
3514                                         last_font_height += font_height();
3515                                 }
3516                         } else if (specials[special_index].type == OFFSET) {
3517                                 if (specials[special_index].arg > 0) {
3518                                         w += specials[special_index].arg;
3519                                 }
3520                         } else if (specials[special_index].type == VOFFSET) {
3521                                 last_font_height += specials[special_index].arg;
3522                         } else if (specials[special_index].type == GOTO) {
3523                                 if (specials[special_index].arg > cur_x) {
3524                                         w = (int) specials[special_index].arg;
3525                                 }
3526                         } else if (specials[special_index].type == TAB) {
3527                                 int start = specials[special_index].arg;
3528                                 int step = specials[special_index].width;
3529
3530                                 if (!step || step < 0) {
3531                                         step = 10;
3532                                 }
3533                                 w += step - (cur_x - text_start_x - start) % step;
3534                         } else if (specials[special_index].type == FONT) {
3535                                 selected_font = specials[special_index].font_added;
3536                                 if (font_height() > last_font_height) {
3537                                         last_font_height = font_height();
3538                                 }
3539                         }
3540
3541                         special_index++;
3542                         s = p + 1;
3543                 } else if (*p == SECRIT_MULTILINE_CHAR) {
3544                         int lw;
3545                         *p = '\0';
3546                         lw = get_string_width(s);
3547                         *p = SECRIT_MULTILINE_CHAR;
3548                         s = p + 1;
3549                         w = lw > w ? lw : w;
3550                         text_height += last_font_height;
3551                 }
3552                 p++;
3553         }
3554         w += get_string_width(s);
3555         if (w > text_width) {
3556                 text_width = w;
3557         }
3558         if (text_width > maximum_width && maximum_width) {
3559                 text_width = maximum_width;
3560         }
3561
3562         text_height += last_font_height;
3563         last_font_height = font_height();
3564         return special_index;
3565 }
3566 #endif /* X11 */
3567
3568 static inline void set_foreground_color(long c)
3569 {
3570 #ifdef X11
3571         if (output_methods & TO_X) {
3572                 current_color = c;
3573                 XSetForeground(display, window.gc, c);
3574         }
3575 #endif /* X11 */
3576 #ifdef NCURSES
3577         if (output_methods & TO_NCURSES) {
3578                 attron(COLOR_PAIR(c));
3579         }
3580 #endif /* NCURSES */
3581         UNUSED(c);
3582         return;
3583 }
3584
3585 static void draw_string(const char *s)
3586 {
3587         int i, i2, pos, width_of_s;
3588         int max = 0;
3589         int added;
3590         char *s_with_newlines;
3591
3592         if (s[0] == '\0') {
3593                 return;
3594         }
3595
3596         width_of_s = get_string_width(s);
3597         s_with_newlines = strdup(s);
3598         for(i = 0; i < (int) strlen(s_with_newlines); i++) {
3599                 if(s_with_newlines[i] == SECRIT_MULTILINE_CHAR) {
3600                         s_with_newlines[i] = '\n';
3601                 }
3602         }
3603         if ((output_methods & TO_STDOUT) && draw_mode == FG) {
3604                 printf("%s\n", s_with_newlines);
3605                 if (extra_newline) fputc('\n', stdout);
3606                 fflush(stdout); /* output immediately, don't buffer */
3607         }
3608         if ((output_methods & TO_STDERR) && draw_mode == FG) {
3609                 fprintf(stderr, "%s\n", s_with_newlines);
3610                 fflush(stderr); /* output immediately, don't buffer */
3611         }
3612         if ((output_methods & OVERWRITE_FILE) && draw_mode == FG && overwrite_fpointer) {
3613                 fprintf(overwrite_fpointer, "%s\n", s_with_newlines);
3614         }
3615         if ((output_methods & APPEND_FILE) && draw_mode == FG && append_fpointer) {
3616                 fprintf(append_fpointer, "%s\n", s_with_newlines);
3617         }
3618 #ifdef NCURSES
3619         if ((output_methods & TO_NCURSES) && draw_mode == FG) {
3620                 printw("%s", s_with_newlines);
3621         }
3622 #endif
3623         free(s_with_newlines);
3624         memset(tmpstring1, 0, text_buffer_size);
3625         memset(tmpstring2, 0, text_buffer_size);
3626         strncpy(tmpstring1, s, text_buffer_size - 1);
3627         pos = 0;
3628         added = 0;
3629
3630 #ifdef X11
3631         if (output_methods & TO_X) {
3632                 max = ((text_width - width_of_s) / get_string_width(" "));
3633         }
3634 #endif /* X11 */
3635         /* This code looks for tabs in the text and coverts them to spaces.
3636          * The trick is getting the correct number of spaces, and not going
3637          * over the window's size without forcing the window larger. */
3638         for (i = 0; i < (int) text_buffer_size; i++) {
3639                 if (tmpstring1[i] == '\t') {
3640                         i2 = 0;
3641                         for (i2 = 0; i2 < (8 - (1 + pos) % 8) && added <= max; i2++) {
3642                                 /* guard against overrun */
3643                                 tmpstring2[MIN(pos + i2, (int)text_buffer_size - 1)] = ' ';
3644                                 added++;
3645                         }
3646                         pos += i2;
3647                 } else {
3648                         /* guard against overrun */
3649                         tmpstring2[MIN(pos, (int) text_buffer_size - 1)] = tmpstring1[i];
3650                         pos++;
3651                 }
3652         }
3653 #ifdef X11
3654         if (output_methods & TO_X) {
3655                 if (text_width == maximum_width) {
3656                         /* this means the text is probably pushing the limit,
3657                          * so we'll chop it */
3658                         while (cur_x + get_string_width(tmpstring2) - text_start_x
3659                                         > maximum_width && strlen(tmpstring2) > 0) {
3660                                 tmpstring2[strlen(tmpstring2) - 1] = '\0';
3661                         }
3662                 }
3663         }
3664 #endif /* X11 */
3665         s = tmpstring2;
3666 #ifdef X11
3667         if (output_methods & TO_X) {
3668 #ifdef XFT
3669                 if (use_xft) {
3670                         XColor c;
3671                         XftColor c2;
3672
3673                         c.pixel = current_color;
3674                         XQueryColor(display, DefaultColormap(display, screen), &c);
3675
3676                         c2.pixel = c.pixel;
3677                         c2.color.red = c.red;
3678                         c2.color.green = c.green;
3679                         c2.color.blue = c.blue;
3680                         c2.color.alpha = fonts[selected_font].font_alpha;
3681                         if (utf8_mode) {
3682                                 XftDrawStringUtf8(window.xftdraw, &c2, fonts[selected_font].xftfont,
3683                                         cur_x, cur_y, (const XftChar8 *) s, strlen(s));
3684                         } else {
3685                                 XftDrawString8(window.xftdraw, &c2, fonts[selected_font].xftfont,
3686                                         cur_x, cur_y, (const XftChar8 *) s, strlen(s));
3687                         }
3688                 } else
3689 #endif
3690                 {
3691                         XDrawString(display, window.drawable, window.gc, cur_x, cur_y, s,
3692                                 strlen(s));
3693                 }
3694                 cur_x += width_of_s;
3695         }
3696 #endif /* X11 */
3697         memcpy(tmpstring1, s, text_buffer_size);
3698 }
3699
3700 int draw_each_line_inner(char *s, int special_index, int last_special_applied)
3701 {
3702 #ifdef X11
3703         int font_h = font_height();
3704         int cur_y_add = 0;
3705 #endif /* X11 */
3706         char *recurse = 0;
3707         char *p = s;
3708         int last_special_needed = -1;
3709         int orig_special_index = special_index;
3710
3711 #ifdef X11
3712         cur_x = text_start_x;
3713         cur_y += font_ascent();
3714 #endif /* X11 */
3715
3716         while (*p) {
3717                 if (*p == SECRIT_MULTILINE_CHAR) {
3718                         /* special newline marker for multiline objects */
3719                         recurse = p + 1;
3720                         *p = '\0';
3721                         break;
3722                 }
3723                 if (*p == SPECIAL_CHAR || last_special_applied > -1) {
3724 #ifdef X11
3725                         int w = 0;
3726 #endif /* X11 */
3727
3728                         /* draw string before special, unless we're dealing multiline
3729                          * specials */
3730                         if (last_special_applied > -1) {
3731                                 special_index = last_special_applied;
3732                         } else {
3733                                 *p = '\0';
3734                                 draw_string(s);
3735                                 *p = SPECIAL_CHAR;
3736                                 s = p + 1;
3737                         }
3738                         /* draw special */
3739                         switch (specials[special_index].type) {
3740 #ifdef X11
3741                                 case HORIZONTAL_LINE:
3742                                 {
3743                                         int h = specials[special_index].height;
3744                                         int mid = font_ascent() / 2;
3745
3746                                         w = text_start_x + text_width - cur_x;
3747
3748                                         XSetLineAttributes(display, window.gc, h, LineSolid,
3749                                                 CapButt, JoinMiter);
3750                                         XDrawLine(display, window.drawable, window.gc, cur_x,
3751                                                 cur_y - mid / 2, cur_x + w, cur_y - mid / 2);
3752                                         break;
3753                                 }
3754
3755                                 case STIPPLED_HR:
3756                                 {
3757                                         int h = specials[special_index].height;
3758                                         int tmp_s = specials[special_index].arg;
3759                                         int mid = font_ascent() / 2;
3760                                         char ss[2] = { tmp_s, tmp_s };
3761
3762                                         w = text_start_x + text_width - cur_x - 1;
3763                                         XSetLineAttributes(display, window.gc, h, LineOnOffDash,
3764                                                 CapButt, JoinMiter);
3765                                         XSetDashes(display, window.gc, 0, ss, 2);
3766                                         XDrawLine(display, window.drawable, window.gc, cur_x,
3767                                                 cur_y - mid / 2, cur_x + w, cur_y - mid / 2);
3768                                         break;
3769                                 }
3770
3771                                 case BAR:
3772                                 {
3773                                         int h, bar_usage, by;
3774                                         if (cur_x - text_start_x > maximum_width
3775                                                         && maximum_width > 0) {
3776                                                 break;
3777                                         }
3778                                         h = specials[special_index].height;
3779                                         bar_usage = specials[special_index].arg;
3780                                         by = cur_y - (font_ascent() / 2) - 1;
3781
3782                                         if (h < font_h) {
3783                                                 by -= h / 2 - 1;
3784                                         }
3785                                         w = specials[special_index].width;
3786                                         if (w == 0) {
3787                                                 w = text_start_x + text_width - cur_x - 1;
3788                                         }
3789                                         if (w < 0) {
3790                                                 w = 0;
3791                                         }
3792
3793                                         XSetLineAttributes(display, window.gc, 1, LineSolid,
3794                                                 CapButt, JoinMiter);
3795
3796                                         XDrawRectangle(display, window.drawable, window.gc, cur_x,
3797                                                 by, w, h);
3798                                         XFillRectangle(display, window.drawable, window.gc, cur_x,
3799                                                 by, w * bar_usage / 255, h);
3800                                         if (h > cur_y_add
3801                                                         && h > font_h) {
3802                                                 cur_y_add = h;
3803                                         }
3804                                         break;
3805                                 }
3806
3807                                 case GAUGE: /* new GAUGE  */
3808                                 {
3809                                         int h, by = 0;
3810                                         unsigned long last_colour = current_color;
3811 #ifdef MATH
3812                                         float angle, px, py;
3813                                         int usage;
3814 #endif /* MATH */
3815
3816                                         if (cur_x - text_start_x > maximum_width
3817                                                         && maximum_width > 0) {
3818                                                 break;
3819                                         }
3820
3821                                         h = specials[special_index].height;
3822                                         by = cur_y - (font_ascent() / 2) - 1;
3823
3824                                         if (h < font_h) {
3825                                                 by -= h / 2 - 1;
3826                                         }
3827                                         w = specials[special_index].width;
3828                                         if (w == 0) {
3829                                                 w = text_start_x + text_width - cur_x - 1;
3830                                         }
3831                                         if (w < 0) {
3832                                                 w = 0;
3833                                         }
3834
3835                                         XSetLineAttributes(display, window.gc, 1, LineSolid,
3836                                                         CapButt, JoinMiter);
3837
3838                                         XDrawArc(display, window.drawable, window.gc,
3839                                                         cur_x, by, w, h * 2, 0, 180*64);
3840
3841 #ifdef MATH
3842                                         usage = specials[special_index].arg;
3843                                         angle = (M_PI)*(float)(usage)/255.;
3844                                         px = (float)(cur_x+(w/2.))-(float)(w/2.)*cos(angle);
3845                                         py = (float)(by+(h))-(float)(h)*sin(angle);
3846
3847                                         XDrawLine(display, window.drawable, window.gc,
3848                                                         cur_x + (w/2.), by+(h), (int)(px), (int)(py));
3849 #endif /* MATH */
3850
3851                                         if (h > cur_y_add
3852                                                         && h > font_h) {
3853                                                 cur_y_add = h;
3854                                         }
3855
3856                                         set_foreground_color(last_colour);
3857
3858                                         break;
3859
3860                                 }
3861
3862                                 case GRAPH:
3863                                 {
3864                                         int h, by, i = 0, j = 0;
3865                                         int colour_idx = 0;
3866                                         unsigned long last_colour = current_color;
3867                                         unsigned long *tmpcolour = 0;
3868                                         if (cur_x - text_start_x > maximum_width
3869                                                         && maximum_width > 0) {
3870                                                 break;
3871                                         }
3872                                         h = specials[special_index].height;
3873                                         by = cur_y - (font_ascent() / 2) - 1;
3874
3875                                         if (h < font_h) {
3876                                                 by -= h / 2 - 1;
3877                                         }
3878                                         w = specials[special_index].width;
3879                                         if (w == 0) {
3880                                                 w = text_start_x + text_width - cur_x - 1;
3881                                         }
3882                                         if (w < 0) {
3883                                                 w = 0;
3884                                         }
3885                                         if (draw_graph_borders) {
3886                                                 XSetLineAttributes(display, window.gc, 1, LineSolid,
3887                                                         CapButt, JoinMiter);
3888                                                 XDrawRectangle(display, window.drawable, window.gc,
3889                                                         cur_x, by, w, h);
3890                                         }
3891                                         XSetLineAttributes(display, window.gc, 1, LineSolid,
3892                                                 CapButt, JoinMiter);
3893
3894                                         if (specials[special_index].last_colour != 0
3895                                                         || specials[special_index].first_colour != 0) {
3896                                                 tmpcolour = do_gradient(w - 1, specials[special_index].last_colour, specials[special_index].first_colour);
3897                                         }
3898                                         colour_idx = 0;
3899                                         for (i = w - 2; i > -1; i--) {
3900                                                 if (specials[special_index].last_colour != 0
3901                                                                 || specials[special_index].first_colour != 0) {
3902                                                         if (specials[special_index].tempgrad) {
3903 #ifdef DEBUG_lol
3904                                                                 assert(
3905                                                                                 (int)((float)(w - 2) - specials[special_index].graph[j] *
3906                                                                                         (w - 2) / (float)specials[special_index].graph_scale)
3907                                                                                 < w - 1
3908                                                                           );
3909                                                                 assert(
3910                                                                                 (int)((float)(w - 2) - specials[special_index].graph[j] *
3911                                                                                         (w - 2) / (float)specials[special_index].graph_scale)
3912                                                                                 > -1
3913                                                                           );
3914                                                                 if (specials[special_index].graph[j] == specials[special_index].graph_scale) {
3915                                                                         assert(
3916                                                                                         (int)((float)(w - 2) - specials[special_index].graph[j] *
3917                                                                                                 (w - 2) / (float)specials[special_index].graph_scale)
3918                                                                                         == 0
3919                                                                                   );
3920                                                                 }
3921 #endif /* DEBUG_lol */
3922                                                                 XSetForeground(display, window.gc, tmpcolour[
3923                                                                                 (int)((float)(w - 2) - specials[special_index].graph[j] *
3924                                                                                         (w - 2) / (float)specials[special_index].graph_scale)
3925                                                                                 ]);
3926                                                         } else {
3927                                                                 XSetForeground(display, window.gc, tmpcolour[colour_idx++]);
3928                                                         }
3929                                                 }
3930                                                 /* this is mugfugly, but it works */
3931                                                 XDrawLine(display, window.drawable, window.gc,
3932                                                                 cur_x + i + 1, by + h, cur_x + i + 1,
3933                                                                 round_to_int((double)by + h - specials[special_index].graph[j] *
3934                                                                         (h - 1) / specials[special_index].graph_scale));
3935                                                 if ((w - i) / ((float) (w - 2) /
3936                                                                         (specials[special_index].graph_width)) > j
3937                                                                 && j < MAX_GRAPH_DEPTH - 3) {
3938                                                         j++;
3939                                                 }
3940                                         }
3941                                         if (tmpcolour) free(tmpcolour);
3942                                         if (h > cur_y_add
3943                                                         && h > font_h) {
3944                                                 cur_y_add = h;
3945                                         }
3946                                         /* if (draw_mode == BG) {
3947                                                 set_foreground_color(default_bg_color);
3948                                         } else if (draw_mode == OUTLINE) {
3949                                                 set_foreground_color(default_out_color);
3950                                         } else {
3951                                                 set_foreground_color(default_fg_color);
3952                                         } */
3953                                         if (show_graph_range) {
3954                                                 int tmp_x = cur_x;
3955                                                 int tmp_y = cur_y;
3956                                                 unsigned short int seconds = update_interval * w;
3957                                                 char *tmp_day_str;
3958                                                 char *tmp_hour_str;
3959                                                 char *tmp_min_str;
3960                                                 char *tmp_sec_str;
3961                                                 char *tmp_str;
3962                                                 unsigned short int timeunits;
3963                                                 if (seconds != 0) {
3964                                                         timeunits = seconds / 86400; seconds %= 86400;
3965                                                         if (timeunits > 0) {
3966                                                                 asprintf(&tmp_day_str, "%dd", timeunits);
3967                                                         } else {
3968                                                                 tmp_day_str = strdup("");
3969                                                         }
3970                                                         timeunits = seconds / 3600; seconds %= 3600;
3971                                                         if (timeunits > 0) {
3972                                                                 asprintf(&tmp_hour_str, "%dh", timeunits);
3973                                                         } else {
3974                                                                 tmp_hour_str = strdup("");
3975                                                         }
3976                                                         timeunits = seconds / 60; seconds %= 60;
3977                                                         if (timeunits > 0) {
3978                                                                 asprintf(&tmp_min_str, "%dm", timeunits);
3979                                                         } else {
3980                                                                 tmp_min_str = strdup("");
3981                                                         }
3982                                                         if (seconds > 0) {
3983                                                                 asprintf(&tmp_sec_str, "%ds", seconds);
3984                                                         } else {
3985                                                                 tmp_sec_str = strdup("");
3986                                                         }
3987                                                         asprintf(&tmp_str, "%s%s%s%s", tmp_day_str, tmp_hour_str, tmp_min_str, tmp_sec_str);
3988                                                         free(tmp_day_str); free(tmp_hour_str); free(tmp_min_str); free(tmp_sec_str);
3989                                                 } else {
3990                                                         asprintf(&tmp_str, "Range not possible"); // should never happen, but better safe then sorry
3991                                                 }
3992                                                 cur_x += (w / 2) - (font_ascent() * (strlen(tmp_str) / 2));
3993                                                 cur_y += font_h / 2;
3994                                                 draw_string(tmp_str);
3995                                                 free(tmp_str);
3996                                                 cur_x = tmp_x;
3997                                                 cur_y = tmp_y;
3998                                         }
3999 #ifdef MATH
4000                                         if (show_graph_scale && (specials[special_index].show_scale == 1)) {
4001                                                 int tmp_x = cur_x;
4002                                                 int tmp_y = cur_y;
4003                                                 char *tmp_str;
4004                                                 cur_x += font_ascent() / 2;
4005                                                 cur_y += font_h / 2;
4006                                                 tmp_str = (char *)
4007                                                         calloc(log10(floor(specials[special_index].graph_scale)) + 4,
4008                                                                         sizeof(char));
4009                                                 sprintf(tmp_str, "%.1f", specials[special_index].graph_scale);
4010                                                 draw_string(tmp_str);
4011                                                 free(tmp_str);
4012                                                 cur_x = tmp_x;
4013                                                 cur_y = tmp_y;
4014                                         }
4015 #endif
4016                                         set_foreground_color(last_colour);
4017                                         break;
4018                                 }
4019
4020                                 case FONT:
4021                                 {
4022                                         int old = font_ascent();
4023
4024                                         cur_y -= font_ascent();
4025                                         selected_font = specials[special_index].font_added;
4026                                         set_font();
4027                                         if (cur_y + font_ascent() < cur_y + old) {
4028                                                 cur_y += old;
4029                                         } else {
4030                                                 cur_y += font_ascent();
4031                                         }
4032                                         font_h = font_height();
4033                                         break;
4034                                 }
4035 #endif /* X11 */
4036                                 case FG:
4037                                         if (draw_mode == FG) {
4038                                                 set_foreground_color(specials[special_index].arg);
4039                                         }
4040                                         break;
4041
4042 #ifdef X11
4043                                 case BG:
4044                                         if (draw_mode == BG) {
4045                                                 set_foreground_color(specials[special_index].arg);
4046                                         }
4047                                         break;
4048
4049                                 case OUTLINE:
4050                                         if (draw_mode == OUTLINE) {
4051                                                 set_foreground_color(specials[special_index].arg);
4052                                         }
4053                                         break;
4054
4055                                 case OFFSET:
4056                                         w += specials[special_index].arg;
4057                                         last_special_needed = special_index;
4058                                         break;
4059
4060                                 case VOFFSET:
4061                                         cur_y += specials[special_index].arg;
4062                                         break;
4063
4064                                 case GOTO:
4065                                         if (specials[special_index].arg >= 0) {
4066                                                 cur_x = (int) specials[special_index].arg;
4067                                         }
4068                                         last_special_needed = special_index;
4069                                         break;
4070
4071                                 case TAB:
4072                                 {
4073                                         int start = specials[special_index].arg;
4074                                         int step = specials[special_index].width;
4075
4076                                         if (!step || step < 0) {
4077                                                 step = 10;
4078                                         }
4079                                         w = step - (cur_x - text_start_x - start) % step;
4080                                         last_special_needed = special_index;
4081                                         break;
4082                                 }
4083
4084                                 case ALIGNR:
4085                                 {
4086                                         /* TODO: add back in "+ window.border_inner_margin" to the end of
4087                                          * this line? */
4088                                         int pos_x = text_start_x + text_width -
4089                                                 get_string_width_special(s, special_index);
4090
4091                                         /* printf("pos_x %i text_start_x %i text_width %i cur_x %i "
4092                                                 "get_string_width(p) %i gap_x %i "
4093                                                 "specials[special_index].arg %i window.border_inner_margin %i "
4094                                                 "window.border_width %i\n", pos_x, text_start_x, text_width,
4095                                                 cur_x, get_string_width_special(s), gap_x,
4096                                                 specials[special_index].arg, window.border_inner_margin,
4097                                                 window.border_width); */
4098                                         if (pos_x > specials[special_index].arg && pos_x > cur_x) {
4099                                                 cur_x = pos_x - specials[special_index].arg;
4100                                         }
4101                                         last_special_needed = special_index;
4102                                         break;
4103                                 }
4104
4105                                 case ALIGNC:
4106                                 {
4107                                         int pos_x = (text_width) / 2 - get_string_width_special(s,
4108                                                         special_index) / 2 - (cur_x -
4109                                                                 text_start_x);
4110                                         /* int pos_x = text_start_x + text_width / 2 -
4111                                                 get_string_width_special(s) / 2; */
4112
4113                                         /* printf("pos_x %i text_start_x %i text_width %i cur_x %i "
4114                                                 "get_string_width(p) %i gap_x %i "
4115                                                 "specials[special_index].arg %i\n", pos_x, text_start_x,
4116                                                 text_width, cur_x, get_string_width(s), gap_x,
4117                                                 specials[special_index].arg); */
4118                                         if (pos_x > specials[special_index].arg) {
4119                                                 w = pos_x - specials[special_index].arg;
4120                                         }
4121                                         last_special_needed = special_index;
4122                                         break;
4123                                 }
4124 #endif /* X11 */
4125                         }
4126
4127 #ifdef X11
4128                         cur_x += w;
4129 #endif /* X11 */
4130
4131                         if (special_index != last_special_applied) {
4132                                 special_index++;
4133                         } else {
4134                                 special_index = orig_special_index;
4135                                 last_special_applied = -1;
4136                         }
4137                 }
4138                 p++;
4139         }
4140
4141 #ifdef X11
4142         cur_y += cur_y_add;
4143 #endif /* X11 */
4144         draw_string(s);
4145 #ifdef NCURSES
4146         if (output_methods & TO_NCURSES) {
4147                 printw("\n");
4148         }
4149 #endif /* NCURSES */
4150 #ifdef X11
4151         cur_y += font_descent();
4152 #endif /* X11 */
4153         if (recurse && *recurse) {
4154                 special_index = draw_each_line_inner(recurse, special_index, last_special_needed);
4155                 *(recurse - 1) = SECRIT_MULTILINE_CHAR;
4156         }
4157         return special_index;
4158 }
4159
4160 static int draw_line(char *s, int special_index)
4161 {
4162 #ifdef X11
4163         if (output_methods & TO_X) {
4164                 return draw_each_line_inner(s, special_index, -1);
4165         }
4166 #endif /* X11 */
4167 #ifdef NCURSES
4168         if (output_methods & TO_NCURSES) {
4169                 return draw_each_line_inner(s, special_index, -1);
4170         }
4171 #endif /* NCURSES */
4172         draw_string(s);
4173         UNUSED(special_index);
4174         return 0;
4175 }
4176
4177 static void draw_text(void)
4178 {
4179 #ifdef X11
4180 #ifdef HAVE_LUA
4181         llua_draw_pre_hook();
4182 #endif /* HAVE_LUA */
4183         if (output_methods & TO_X) {
4184                 cur_y = text_start_y;
4185
4186                 /* draw borders */
4187                 if (draw_borders && window.border_width > 0) {
4188                         if (stippled_borders) {
4189                                 char ss[2] = { stippled_borders, stippled_borders };
4190                                 XSetLineAttributes(display, window.gc, window.border_width, LineOnOffDash,
4191                                         CapButt, JoinMiter);
4192                                 XSetDashes(display, window.gc, 0, ss, 2);
4193                         } else {
4194                                 XSetLineAttributes(display, window.gc, window.border_width, LineSolid,
4195                                         CapButt, JoinMiter);
4196                         }
4197
4198                         XDrawRectangle(display, window.drawable, window.gc,
4199                                 text_start_x - window.border_inner_margin - window.border_width,
4200                                 text_start_y - window.border_inner_margin - window.border_width,
4201                                 text_width + window.border_inner_margin * 2 + window.border_width * 2,
4202                                 text_height + window.border_inner_margin * 2 + window.border_width * 2);
4203                 }
4204
4205                 /* draw text */
4206         }
4207         setup_fonts();
4208 #endif /* X11 */
4209 #ifdef NCURSES
4210         init_pair(COLOR_WHITE, COLOR_WHITE, COLOR_BLACK);
4211         attron(COLOR_PAIR(COLOR_WHITE));
4212 #endif /* NCURSES */
4213         for_each_line(text_buffer, draw_line);
4214 #if defined(HAVE_LUA) && defined(X11)
4215         llua_draw_post_hook();
4216 #endif /* HAVE_LUA */
4217 }
4218
4219 static void draw_stuff(void)
4220 {
4221 #ifdef IMLIB2
4222         cimlib_render(text_start_x, text_start_y, window.width, window.height);
4223 #endif /* IMLIB2 */
4224         if (overwrite_file) {
4225                 overwrite_fpointer = fopen(overwrite_file, "w");
4226                 if(!overwrite_fpointer)
4227                         NORM_ERR("Can't overwrite '%s' anymore", overwrite_file);
4228         }
4229         if (append_file) {
4230                 append_fpointer = fopen(append_file, "a");
4231                 if(!append_fpointer)
4232                         NORM_ERR("Can't append '%s' anymore", append_file);
4233         }
4234 #ifdef X11
4235         if (output_methods & TO_X) {
4236                 selected_font = 0;
4237                 if (draw_shades && !draw_outline) {
4238                         text_start_x++;
4239                         text_start_y++;
4240                         set_foreground_color(default_bg_color);
4241                         draw_mode = BG;
4242                         draw_text();
4243                         text_start_x--;
4244                         text_start_y--;
4245                 }
4246
4247                 if (draw_outline) {
4248                         int i, j;
4249                         selected_font = 0;
4250
4251                         for (i = -1; i < 2; i++) {
4252                                 for (j = -1; j < 2; j++) {
4253                                         if (i == 0 && j == 0) {
4254                                                 continue;
4255                                         }
4256                                         text_start_x += i;
4257                                         text_start_y += j;
4258                                         set_foreground_color(default_out_color);
4259                                         draw_mode = OUTLINE;
4260                                         draw_text();
4261                                         text_start_x -= i;
4262                                         text_start_y -= j;
4263                                 }
4264                         }
4265                 }
4266
4267                 set_foreground_color(default_fg_color);
4268         }
4269 #endif /* X11 */
4270         draw_mode = FG;
4271         draw_text();
4272 #ifdef X11
4273         xdbe_swap_buffers();
4274         if (output_methods & TO_X) {
4275 #ifdef HAVE_XDBE
4276 #endif
4277         }
4278 #endif /* X11 */
4279         if(overwrite_fpointer) {
4280                 fclose(overwrite_fpointer);
4281                 overwrite_fpointer = 0;
4282         }
4283         if(append_fpointer) {
4284                 fclose(append_fpointer);
4285                 append_fpointer = 0;
4286         }
4287 }
4288
4289 #ifdef X11
4290 static void clear_text(int exposures)
4291 {
4292 #ifdef HAVE_XDBE
4293         if (use_xdbe) {
4294                 /* The swap action is XdbeBackground, which clears */
4295                 return;
4296         } else
4297 #endif
4298         if (display && window.window) { // make sure these are !null
4299                 /* there is some extra space for borders and outlines */
4300                 XClearArea(display, window.window, text_start_x - window.border_inner_margin - window.border_outer_margin - window.border_width,
4301                         text_start_y - window.border_inner_margin - window.border_outer_margin - window.border_width,
4302                         text_width + window.border_inner_margin * 2 + window.border_outer_margin * 2 + window.border_width * 2,
4303                         text_height + window.border_inner_margin * 2 + window.border_outer_margin * 2 + window.border_width * 2, exposures ? True : 0);
4304         }
4305 }
4306 #endif /* X11 */
4307
4308 static int need_to_update;
4309
4310 /* update_text() generates new text and clears old text area */
4311 static void update_text(void)
4312 {
4313 #ifdef IMLIB2
4314         cimlib_cleanup();
4315 #endif /* IMLIB2 */
4316         generate_text();
4317 #ifdef X11
4318         if (output_methods & TO_X)
4319                 clear_text(1);
4320 #endif /* X11 */
4321         need_to_update = 1;
4322 #ifdef HAVE_LUA
4323         llua_update_info(&info, update_interval);
4324 #endif /* HAVE_LUA */
4325 }
4326
4327 #ifdef HAVE_SYS_INOTIFY_H
4328 int inotify_fd;
4329 #endif
4330
4331 static void main_loop(void)
4332 {
4333         int terminate = 0;
4334 #ifdef SIGNAL_BLOCKING
4335         sigset_t newmask, oldmask;
4336 #endif
4337         double t;
4338 #ifdef HAVE_SYS_INOTIFY_H
4339         int inotify_config_wd = -1;
4340 #define INOTIFY_EVENT_SIZE  (sizeof(struct inotify_event))
4341 #define INOTIFY_BUF_LEN     (20 * (INOTIFY_EVENT_SIZE + 16))
4342         char inotify_buff[INOTIFY_BUF_LEN];
4343 #endif /* HAVE_SYS_INOTIFY_H */
4344
4345
4346 #ifdef SIGNAL_BLOCKING
4347         sigemptyset(&newmask);
4348         sigaddset(&newmask, SIGINT);
4349         sigaddset(&newmask, SIGTERM);
4350         sigaddset(&newmask, SIGUSR1);
4351 #endif
4352
4353         last_update_time = 0.0;
4354         next_update_time = get_time();
4355         info.looped = 0;
4356         while (terminate == 0 && (total_run_times == 0 || info.looped < total_run_times)) {
4357                 if(update_interval_bat != NOBATTERY && update_interval_bat != update_interval_old) {
4358                         char buf[max_user_text];
4359
4360                         get_battery_short_status(buf, max_user_text, "BAT0");
4361                         if(buf[0] == 'D') {
4362                                 update_interval = update_interval_bat;
4363                         } else {
4364                                 update_interval = update_interval_old;
4365                         }
4366                 }
4367                 info.looped++;
4368
4369 #ifdef SIGNAL_BLOCKING
4370                 /* block signals.  we will inspect for pending signals later */
4371                 if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0) {
4372                         CRIT_ERR(NULL, NULL, "unable to sigprocmask()");
4373                 }
4374 #endif
4375
4376 #ifdef X11
4377                 if (output_methods & TO_X) {
4378                         XFlush(display);
4379
4380                         /* wait for X event or timeout */
4381
4382                         if (!XPending(display)) {
4383                                 fd_set fdsr;
4384                                 struct timeval tv;
4385                                 int s;
4386                                 t = next_update_time - get_time();
4387
4388                                 if (t < 0) {
4389                                         t = 0;
4390                                 } else if (t > update_interval) {
4391                                         t = update_interval;
4392                                 }
4393
4394                                 tv.tv_sec = (long) t;
4395                                 tv.tv_usec = (long) (t * 1000000) % 1000000;
4396                                 FD_ZERO(&fdsr);
4397                                 FD_SET(ConnectionNumber(display), &fdsr);
4398
4399                                 s = select(ConnectionNumber(display) + 1, &fdsr, 0, 0, &tv);
4400                                 if (s == -1) {
4401                                         if (errno != EINTR) {
4402                                                 NORM_ERR("can't select(): %s", strerror(errno));
4403                                         }
4404                                 } else {
4405                                         /* timeout */
4406                                         if (s == 0) {
4407                                                 update_text();
4408                                         }
4409                                 }
4410                         }
4411
4412                         if (need_to_update) {
4413 #ifdef OWN_WINDOW
4414                                 int wx = window.x, wy = window.y;
4415 #endif
4416
4417                                 need_to_update = 0;
4418                                 selected_font = 0;
4419                                 update_text_area();
4420 #ifdef OWN_WINDOW
4421                                 if (own_window) {
4422                                         int changed = 0;
4423
4424                                         /* resize window if it isn't right size */
4425                                         if (!fixed_size
4426                                                         && (text_width + window.border_inner_margin * 2 + window.border_outer_margin * 2 + window.border_width * 2 != window.width
4427                                                                 || text_height + window.border_inner_margin * 2 + window.border_outer_margin * 2 + window.border_width * 2 != window.height)) {
4428                                                 window.width = text_width + window.border_inner_margin * 2 + window.border_outer_margin * 2 + window.border_width * 2;
4429                                                 window.height = text_height + window.border_inner_margin * 2 + window.border_outer_margin * 2 + window.border_width * 2;
4430                                                 draw_stuff(); /* redraw everything in our newly sized window */
4431                                                 XResizeWindow(display, window.window, window.width,
4432                                                                 window.height); /* resize window */
4433                                                 set_transparent_background(window.window);
4434 #ifdef HAVE_XDBE
4435                                                 /* swap buffers */
4436                                                 xdbe_swap_buffers();
4437 #endif
4438
4439                                                 changed++;
4440 #ifdef HAVE_LUA
4441                                                 /* update lua window globals */
4442                                                 llua_update_window_table(text_start_x, text_start_y, text_width, text_height);
4443 #endif /* HAVE_LUA */
4444                                         }
4445
4446                                         /* move window if it isn't in right position */
4447                                         if (!fixed_pos && (window.x != wx || window.y != wy)) {
4448                                                 XMoveWindow(display, window.window, window.x, window.y);
4449                                                 changed++;
4450                                         }
4451
4452                                         /* update struts */
4453                                         if (changed && window.type == TYPE_PANEL) {
4454                                                 int sidenum = -1;
4455
4456                                                 fprintf(stderr, PACKAGE_NAME": defining struts\n");
4457                                                 fflush(stderr);
4458
4459                                                 switch (text_alignment) {
4460                                                         case TOP_LEFT:
4461                                                         case TOP_RIGHT:
4462                                                         case TOP_MIDDLE:
4463                                                                 {
4464                                                                         sidenum = 2;
4465                                                                         break;
4466                                                                 }
4467                                                         case BOTTOM_LEFT:
4468                                                         case BOTTOM_RIGHT:
4469                                                         case BOTTOM_MIDDLE:
4470                                                                 {
4471                                                                         sidenum = 3;
4472                                                                         break;
4473                                                                 }
4474                                                         case MIDDLE_LEFT:
4475                                                                 {
4476                                                                         sidenum = 0;
4477                                                                         break;
4478                                                                 }
4479                                                         case MIDDLE_RIGHT:
4480                                                                 {
4481                                                                         sidenum = 1;
4482                                                                         break;
4483                                                                 }
4484                                                 }
4485
4486                                                 set_struts(sidenum);
4487                                         }
4488                                 }
4489 #endif
4490
4491                                 clear_text(1);
4492
4493 #ifdef HAVE_XDBE
4494                                 if (use_xdbe) {
4495                                         XRectangle r;
4496
4497                                         r.x = text_start_x - window.border_inner_margin - window.border_outer_margin - window.border_width;
4498                                         r.y = text_start_y - window.border_inner_margin - window.border_outer_margin - window.border_width;
4499                                         r.width = text_width + window.border_inner_margin * 2 + window.border_outer_margin * 2 + window.border_width * 2;
4500                                         r.height = text_height + window.border_inner_margin * 2 + window.border_outer_margin * 2 + window.border_width * 2;
4501                                         XUnionRectWithRegion(&r, x11_stuff.region, x11_stuff.region);
4502                                 }
4503 #endif
4504                         }
4505
4506                         /* handle X events */
4507                         while (XPending(display)) {
4508                                 XEvent ev;
4509
4510                                 XNextEvent(display, &ev);
4511                                 switch (ev.type) {
4512                                         case Expose:
4513                                         {
4514                                                 XRectangle r;
4515                                                 r.x = ev.xexpose.x;
4516                                                 r.y = ev.xexpose.y;
4517                                                 r.width = ev.xexpose.width;
4518                                                 r.height = ev.xexpose.height;
4519                                                 XUnionRectWithRegion(&r, x11_stuff.region, x11_stuff.region);
4520                                                 break;
4521                                         }
4522
4523                                         case PropertyNotify:
4524                                         {
4525                                                 if ( ev.xproperty.state == PropertyNewValue ) {
4526                                                         get_x11_desktop_info( ev.xproperty.display, ev.xproperty.atom );
4527                                                 }
4528                                                 break;
4529                                         }
4530
4531 #ifdef OWN_WINDOW
4532                                         case ReparentNotify:
4533                                                 /* set background to ParentRelative for all parents */
4534                                                 if (own_window) {
4535                                                         set_transparent_background(window.window);
4536                                                 }
4537                                                 break;
4538
4539                                         case ConfigureNotify:
4540                                                 if (own_window) {
4541                                                         /* if window size isn't what expected, set fixed size */
4542                                                         if (ev.xconfigure.width != window.width
4543                                                                         || ev.xconfigure.height != window.height) {
4544                                                                 if (window.width != 0 && window.height != 0) {
4545                                                                         fixed_size = 1;
4546                                                                 }
4547
4548                                                                 /* clear old stuff before screwing up
4549                                                                  * size and pos */
4550                                                                 clear_text(1);
4551
4552                                                                 {
4553                                                                         XWindowAttributes attrs;
4554                                                                         if (XGetWindowAttributes(display,
4555                                                                                         window.window, &attrs)) {
4556                                                                                 window.width = attrs.width;
4557                                                                                 window.height = attrs.height;
4558                                                                         }
4559                                                                 }
4560
4561                                                                 text_width = window.width - window.border_inner_margin * 2 - window.border_outer_margin * 2 - window.border_width * 2;
4562                                                                 text_height = window.height - window.border_inner_margin * 2 - window.border_outer_margin * 2 - window.border_width * 2;
4563                                                                 if (text_width > maximum_width
4564                                                                                 && maximum_width > 0) {
4565                                                                         text_width = maximum_width;
4566                                                                 }
4567                                                         }
4568
4569                                                         /* if position isn't what expected, set fixed pos
4570                                                          * total_updates avoids setting fixed_pos when window
4571                                                          * is set to weird locations when started */
4572                                                         /* // this is broken
4573                                                         if (total_updates >= 2 && !fixed_pos
4574                                                                         && (window.x != ev.xconfigure.x
4575                                                                         || window.y != ev.xconfigure.y)
4576                                                                         && (ev.xconfigure.x != 0
4577                                                                         || ev.xconfigure.y != 0)) {
4578                                                                 fixed_pos = 1;
4579                                                         } */
4580                                                 }
4581                                                 break;
4582
4583                                         case ButtonPress:
4584                                                 if (own_window) {
4585                                                         /* if an ordinary window with decorations */
4586                                                         if ((window.type == TYPE_NORMAL &&
4587                                                                                 (!TEST_HINT(window.hints,
4588                                                                                                         HINT_UNDECORATED))) ||
4589                                                                         window.type == TYPE_DESKTOP) {
4590                                                                 /* allow conky to hold input focus. */
4591                                                                 break;
4592                                                         } else {
4593                                                                 /* forward the click to the desktop window */
4594                                                                 XUngrabPointer(display, ev.xbutton.time);
4595                                                                 ev.xbutton.window = window.desktop;
4596                                                                 ev.xbutton.x = ev.xbutton.x_root;
4597                                                                 ev.xbutton.y = ev.xbutton.y_root;
4598                                                                 XSendEvent(display, ev.xbutton.window, False,
4599                                                                         ButtonPressMask, &ev);
4600                                                                 XSetInputFocus(display, ev.xbutton.window,
4601                                                                         RevertToParent, ev.xbutton.time);
4602                                                         }
4603                                                 }
4604                                                 break;
4605
4606                                         case ButtonRelease:
4607                                                 if (own_window) {
4608                                                         /* if an ordinary window with decorations */
4609                                                         if ((window.type == TYPE_NORMAL)
4610                                                                         && (!TEST_HINT(window.hints,
4611                                                                         HINT_UNDECORATED))) {
4612                                                                 /* allow conky to hold input focus. */
4613                                                                 break;
4614                                                         } else {
4615                                                                 /* forward the release to the desktop window */
4616                                                                 ev.xbutton.window = window.desktop;
4617                                                                 ev.xbutton.x = ev.xbutton.x_root;
4618                                                                 ev.xbutton.y = ev.xbutton.y_root;
4619                                                                 XSendEvent(display, ev.xbutton.window, False,
4620                                                                         ButtonReleaseMask, &ev);
4621                                                         }
4622                                                 }
4623                                                 break;
4624
4625 #endif
4626
4627                                         default:
4628 #ifdef HAVE_XDAMAGE
4629                                                 if (ev.type == x11_stuff.event_base + XDamageNotify) {
4630                                                         XDamageNotifyEvent *dev = (XDamageNotifyEvent *) &ev;
4631
4632                                                         XFixesSetRegion(display, x11_stuff.part, &dev->area, 1);
4633                                                         XFixesUnionRegion(display, x11_stuff.region2, x11_stuff.region2, x11_stuff.part);
4634                                                 }
4635 #endif /* HAVE_XDAMAGE */
4636                                                 break;
4637                                 }
4638                         }
4639
4640 #ifdef HAVE_XDAMAGE
4641                         XDamageSubtract(display, x11_stuff.damage, x11_stuff.region2, None);
4642                         XFixesSetRegion(display, x11_stuff.region2, 0, 0);
4643 #endif /* HAVE_XDAMAGE */
4644
4645                         /* XDBE doesn't seem to provide a way to clear the back buffer
4646                          * without interfering with the front buffer, other than passing
4647                          * XdbeBackground to XdbeSwapBuffers. That means that if we're
4648                          * using XDBE, we need to redraw the text even if it wasn't part of
4649                          * the exposed area. OTOH, if we're not going to call draw_stuff at
4650                          * all, then no swap happens and we can safely do nothing. */
4651
4652                         if (!XEmptyRegion(x11_stuff.region)) {
4653 #ifdef HAVE_XDBE
4654                                 if (use_xdbe) {
4655                                         XRectangle r;
4656
4657                                         r.x = text_start_x - window.border_inner_margin - window.border_outer_margin - window.border_width;
4658                                         r.y = text_start_y - window.border_inner_margin - window.border_outer_margin - window.border_width;
4659                                         r.width = text_width + window.border_inner_margin * 2 + window.border_outer_margin * 2 + window.border_width * 2;
4660                                         r.height = text_height + window.border_inner_margin * 2 + window.border_outer_margin * 2 + window.border_width * 2;
4661                                         XUnionRectWithRegion(&r, x11_stuff.region, x11_stuff.region);
4662                                 }
4663 #endif
4664                                 XSetRegion(display, window.gc, x11_stuff.region);
4665 #ifdef XFT
4666                                 if (use_xft) {
4667                                         XftDrawSetClip(window.xftdraw, x11_stuff.region);
4668                                 }
4669 #endif
4670                                 draw_stuff();
4671                                 XDestroyRegion(x11_stuff.region);
4672                                 x11_stuff.region = XCreateRegion();
4673                         }
4674                 } else {
4675 #endif /* X11 */
4676                         t = (next_update_time - get_time()) * 1000000;
4677                         if(t > 0) usleep((useconds_t)t);
4678                         update_text();
4679                         draw_stuff();
4680 #ifdef NCURSES
4681                         if(output_methods & TO_NCURSES) {
4682                                 refresh();
4683                                 clear();
4684                         }
4685 #endif
4686 #ifdef X11
4687                 }
4688 #endif /* X11 */
4689
4690 #ifdef SIGNAL_BLOCKING
4691                 /* unblock signals of interest and let handler fly */
4692                 if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0) {
4693                         CRIT_ERR(NULL, NULL, "unable to sigprocmask()");
4694                 }
4695 #endif
4696
4697                 switch (g_signal_pending) {
4698                         case SIGHUP:
4699                         case SIGUSR1:
4700                                 NORM_ERR("received SIGHUP or SIGUSR1. reloading the config file.");
4701                                 reload_config();
4702                                 break;
4703                         case SIGINT:
4704                         case SIGTERM:
4705                                 NORM_ERR("received SIGINT or SIGTERM to terminate. bye!");
4706                                 terminate = 1;
4707 #ifdef X11
4708                                 if (output_methods & TO_X) {
4709                                         XDestroyRegion(x11_stuff.region);
4710                                         x11_stuff.region = NULL;
4711 #ifdef HAVE_XDAMAGE
4712                                         XDamageDestroy(display, x11_stuff.damage);
4713                                         XFixesDestroyRegion(display, x11_stuff.region2);
4714                                         XFixesDestroyRegion(display, x11_stuff.part);
4715 #endif /* HAVE_XDAMAGE */
4716                                         if (disp) {
4717                                                 free(disp);
4718                                         }
4719                                 }
4720 #endif /* X11 */
4721                                 if(overwrite_file) {
4722                                         free(overwrite_file);
4723                                         overwrite_file = 0;
4724                                 }
4725                                 if(append_file) {
4726                                         free(append_file);
4727                                         append_file = 0;
4728                                 }
4729                                 break;
4730                         default:
4731                                 /* Reaching here means someone set a signal
4732                                  * (SIGXXXX, signal_handler), but didn't write any code
4733                                  * to deal with it.
4734                                  * If you don't want to handle a signal, don't set a handler on
4735                                  * it in the first place. */
4736                                 if (g_signal_pending) {
4737                                         NORM_ERR("ignoring signal (%d)", g_signal_pending);
4738                                 }
4739                                 break;
4740                 }
4741 #ifdef HAVE_SYS_INOTIFY_H
4742                 if (inotify_fd != -1 && inotify_config_wd == -1 && current_config != 0) {
4743                         inotify_config_wd = inotify_add_watch(inotify_fd,
4744                                         current_config,
4745                                         IN_MODIFY);
4746                 }
4747                 if (inotify_fd != -1 && inotify_config_wd != -1 && current_config != 0) {
4748                         int len = 0, idx = 0;
4749                         fd_set descriptors;
4750                         struct timeval time_to_wait;
4751
4752                         FD_ZERO(&descriptors);
4753                         FD_SET(inotify_fd, &descriptors);
4754
4755                         time_to_wait.tv_sec = time_to_wait.tv_usec = 0;
4756
4757                         select(inotify_fd + 1, &descriptors, NULL, NULL, &time_to_wait);
4758                         if (FD_ISSET(inotify_fd, &descriptors)) {
4759                                 /* process inotify events */
4760                                 len = read(inotify_fd, inotify_buff, INOTIFY_BUF_LEN);
4761                                 while (len > 0 && idx < len) {
4762                                         struct inotify_event *ev = (struct inotify_event *) &inotify_buff[idx];
4763                                         if (ev->wd == inotify_config_wd && (ev->mask & IN_MODIFY || ev->mask & IN_IGNORED)) {
4764                                                 /* current_config should be reloaded */
4765                                                 NORM_ERR("'%s' modified, reloading...", current_config);
4766                                                 reload_config();
4767                                                 if (ev->mask & IN_IGNORED) {
4768                                                         /* for some reason we get IN_IGNORED here
4769                                                          * sometimes, so we need to re-add the watch */
4770                                                         inotify_config_wd = inotify_add_watch(inotify_fd,
4771                                                                         current_config,
4772                                                                         IN_MODIFY);
4773                                                 }
4774                                         }
4775 #ifdef HAVE_LUA
4776                                         else {
4777                                                 llua_inotify_query(ev->wd, ev->mask);
4778                                         }
4779 #endif /* HAVE_LUA */
4780                                         idx += INOTIFY_EVENT_SIZE + ev->len;
4781                                 }
4782                         }
4783                 }
4784 #endif /* HAVE_SYS_INOTIFY_H */
4785
4786 #ifdef HAVE_LUA
4787         llua_update_info(&info, update_interval);
4788 #endif /* HAVE_LUA */
4789                 g_signal_pending = 0;
4790         }
4791         clean_up(NULL, NULL);
4792
4793 #ifdef HAVE_SYS_INOTIFY_H
4794         if (inotify_fd != -1) {
4795                 inotify_rm_watch(inotify_fd, inotify_config_wd);
4796                 close(inotify_fd);
4797                 inotify_fd = inotify_config_wd = 0;
4798         }
4799 #endif /* HAVE_SYS_INOTIFY_H */
4800 }
4801
4802 #ifdef X11
4803 static void load_config_file_x11(const char *);
4804 #endif /* X11 */
4805 void initialisation(int argc, char** argv);
4806
4807         /* reload the config file */
4808 static void reload_config(void)
4809 {
4810         char *current_config_copy = strdup(current_config);
4811         clean_up(NULL, NULL);
4812         current_config = current_config_copy;
4813         initialisation(argc_copy, argv_copy);
4814 }
4815
4816 void clean_up(void *memtofree1, void* memtofree2)
4817 {
4818         int i;
4819
4820 #ifdef NCURSES
4821         if(output_methods & TO_NCURSES) {
4822                 endwin();
4823         }
4824 #endif
4825         conftree_empty(currentconffile);
4826         currentconffile = NULL;
4827         if(memtofree1) {
4828                 free(memtofree1);
4829         }
4830         if(memtofree2) {
4831                 free(memtofree2);
4832         }
4833         timed_thread_destroy_registered_threads();
4834
4835         if (info.cpu_usage) {
4836                 free(info.cpu_usage);
4837                 info.cpu_usage = NULL;
4838         }
4839 #ifdef X11
4840         if (x_initialised == YES) {
4841                 XClearArea(display, window.window, text_start_x - window.border_inner_margin - window.border_outer_margin - window.border_width,
4842                         text_start_y - window.border_inner_margin - window.border_outer_margin - window.border_width,
4843                         text_width + window.border_inner_margin * 2 + window.border_outer_margin * 2 + window.border_width * 2,
4844                         text_height + window.border_inner_margin * 2 + window.border_outer_margin * 2 + window.border_width * 2, 0);
4845                 destroy_window();
4846                 free_fonts();
4847                 if(x11_stuff.region) {
4848                         XDestroyRegion(x11_stuff.region);
4849                         x11_stuff.region = NULL;
4850                 }
4851                 XCloseDisplay(display);
4852                 display = NULL;
4853                 if(info.x11.desktop.all_names) {
4854                         free(info.x11.desktop.all_names);
4855                         info.x11.desktop.all_names = NULL;
4856                 }
4857                 if (info.x11.desktop.name) {
4858                         free(info.x11.desktop.name);
4859                         info.x11.desktop.name = NULL;
4860                 }
4861                 x_initialised = NO;
4862         }else{
4863                 free(fonts);    //in set_default_configurations a font is set but not loaded
4864                 font_count = -1;
4865         }
4866
4867 #endif /* X11 */
4868
4869         free_update_callbacks();
4870
4871         free_templates();
4872
4873         free_text_objects(&global_root_object, 0);
4874         if (tmpstring1) {
4875                 free(tmpstring1);
4876                 tmpstring1 = 0;
4877         }
4878         if (tmpstring2) {
4879                 free(tmpstring2);
4880                 tmpstring2 = 0;
4881         }
4882         if (text_buffer) {
4883                 free(text_buffer);
4884                 text_buffer = 0;
4885         }
4886
4887         if (global_text) {
4888                 free(global_text);
4889                 global_text = 0;
4890         }
4891
4892         free(current_config);
4893         current_config = 0;
4894
4895 #ifdef TCP_PORT_MONITOR
4896         tcp_portmon_clear();
4897 #endif
4898 #ifdef HAVE_CURL
4899         ccurl_free_info();
4900 #endif
4901 #ifdef RSS
4902         rss_free_info();
4903 #endif
4904 #ifdef WEATHER
4905         weather_free_info();
4906 #endif
4907 #ifdef HAVE_LUA
4908         llua_shutdown_hook();
4909         llua_close();
4910 #endif /* HAVE_LUA */
4911 #ifdef IMLIB2
4912         cimlib_deinit();
4913 #endif /* IMLIB2 */
4914 #ifdef XOAP
4915         xmlCleanupParser();
4916 #endif /* XOAP */
4917
4918         if (specials) {
4919                 for (i = 0; i < special_count; i++) {
4920                         if (specials[i].type == GRAPH) {
4921                                 free(specials[i].graph);
4922                         }
4923                 }
4924                 free(specials);
4925                 specials = NULL;
4926         }
4927
4928         clear_net_stats();
4929         clear_diskio_stats();
4930         if(global_cpu != NULL) {
4931                 free(global_cpu);
4932                 global_cpu = NULL;
4933         }
4934 }
4935
4936 static int string_to_bool(const char *s)
4937 {
4938         if (!s) {
4939                 // Assumes an option without a true/false means true
4940                 return 1;
4941         } else if (strcasecmp(s, "yes") == EQUAL) {
4942                 return 1;
4943         } else if (strcasecmp(s, "true") == EQUAL) {
4944                 return 1;
4945         } else if (strcasecmp(s, "1") == EQUAL) {
4946                 return 1;
4947         }
4948         return 0;
4949 }
4950
4951 #ifdef X11
4952 static enum alignment string_to_alignment(const char *s)
4953 {
4954         if (strcasecmp(s, "top_left") == EQUAL) {
4955                 return TOP_LEFT;
4956         } else if (strcasecmp(s, "top_right") == EQUAL) {
4957                 return TOP_RIGHT;
4958         } else if (strcasecmp(s, "top_middle") == EQUAL) {
4959                 return TOP_MIDDLE;
4960         } else if (strcasecmp(s, "bottom_left") == EQUAL) {
4961                 return BOTTOM_LEFT;
4962         } else if (strcasecmp(s, "bottom_right") == EQUAL) {
4963                 return BOTTOM_RIGHT;
4964         } else if (strcasecmp(s, "bottom_middle") == EQUAL) {
4965                 return BOTTOM_MIDDLE;
4966         } else if (strcasecmp(s, "middle_left") == EQUAL) {
4967                 return MIDDLE_LEFT;
4968         } else if (strcasecmp(s, "middle_right") == EQUAL) {
4969                 return MIDDLE_RIGHT;
4970         } else if (strcasecmp(s, "tl") == EQUAL) {
4971                 return TOP_LEFT;
4972         } else if (strcasecmp(s, "tr") == EQUAL) {
4973                 return TOP_RIGHT;
4974         } else if (strcasecmp(s, "tm") == EQUAL) {
4975                 return TOP_MIDDLE;
4976         } else if (strcasecmp(s, "bl") == EQUAL) {
4977                 return BOTTOM_LEFT;
4978         } else if (strcasecmp(s, "br") == EQUAL) {
4979                 return BOTTOM_RIGHT;
4980         } else if (strcasecmp(s, "bm") == EQUAL) {
4981                 return BOTTOM_MIDDLE;
4982         } else if (strcasecmp(s, "ml") == EQUAL) {
4983                 return MIDDLE_LEFT;
4984         } else if (strcasecmp(s, "mr") == EQUAL) {
4985                 return MIDDLE_RIGHT;
4986         } else if (strcasecmp(s, "none") == EQUAL) {
4987                 return NONE;
4988         }
4989         return TOP_LEFT;
4990 }
4991 #endif /* X11 */
4992
4993 #ifdef X11
4994 static void set_default_configurations_for_x(void)
4995 {
4996         default_fg_color = WhitePixel(display, screen);
4997         default_bg_color = BlackPixel(display, screen);
4998         default_out_color = BlackPixel(display, screen);
4999         color0 = default_fg_color;
5000         color1 = default_fg_color;
5001         color2 = default_fg_color;
5002         color3 = default_fg_color;
5003         color4 = default_fg_color;
5004         color5 = default_fg_color;
5005         color6 = default_fg_color;
5006         color7 = default_fg_color;
5007         color8 = default_fg_color;
5008         color9 = default_fg_color;
5009         current_text_color = default_fg_color;
5010 }
5011 #endif /* X11 */
5012
5013 static void set_default_configurations(void)
5014 {
5015 #ifdef MPD
5016         char *mpd_env_host;
5017         char *mpd_env_port;
5018 #endif
5019         update_uname();
5020         fork_to_background = 0;
5021         total_run_times = 0;
5022         info.cpu_avg_samples = 2;
5023         info.net_avg_samples = 2;
5024         info.diskio_avg_samples = 2;
5025         info.memmax = 0;
5026         top_cpu = 0;
5027         cpu_separate = 0;
5028         short_units = 0;
5029         format_human_readable = 1;
5030         top_mem = 0;
5031         top_time = 0;
5032 #ifdef IOSTATS
5033         top_io = 0;
5034 #endif
5035 #ifdef __linux__
5036         top_running = 0;
5037 #endif
5038 #ifdef MPD
5039         mpd_env_host = getenv("MPD_HOST");
5040         mpd_env_port = getenv("MPD_PORT");
5041
5042         if (!mpd_env_host || !strlen(mpd_env_host)) {
5043                 mpd_set_host("localhost");
5044         } else {
5045                 /* MPD_HOST environment variable is set */
5046                 char *mpd_hostpart = strchr(mpd_env_host, '@');
5047                 if (!mpd_hostpart) {
5048                         mpd_set_host(mpd_env_host);
5049                 } else {
5050                         /* MPD_HOST contains a password */
5051                         char mpd_password[mpd_hostpart - mpd_env_host + 1];
5052                         snprintf(mpd_password, mpd_hostpart - mpd_env_host + 1, "%s", mpd_env_host);
5053
5054                         if (!strlen(mpd_hostpart + 1)) {
5055                                 mpd_set_host("localhost");
5056                         } else {
5057                                 mpd_set_host(mpd_hostpart + 1);
5058                         }
5059
5060                         mpd_set_password(mpd_password, 1);
5061                 }
5062         }
5063
5064
5065         if (!mpd_env_port || mpd_set_port(mpd_env_port)) {
5066                 /* failed to set port from environment variable */
5067                 mpd_set_port("6600");
5068         }
5069 #endif
5070 #ifdef XMMS2
5071         info.xmms2.artist = NULL;
5072         info.xmms2.album = NULL;
5073         info.xmms2.title = NULL;
5074         info.xmms2.genre = NULL;
5075         info.xmms2.comment = NULL;
5076         info.xmms2.url = NULL;
5077         info.xmms2.status = NULL;
5078         info.xmms2.playlist = NULL;
5079 #endif
5080         use_spacer = NO_SPACER;
5081 #ifdef X11
5082         output_methods = TO_X;
5083 #else
5084         output_methods = TO_STDOUT;
5085 #endif
5086 #ifdef X11
5087         show_graph_scale = 0;
5088         show_graph_range = 0;
5089         draw_shades = 1;
5090         draw_borders = 0;
5091         draw_graph_borders = 1;
5092         draw_outline = 0;
5093         set_first_font("6x10");
5094         gap_x = 5;
5095         gap_y = 60;
5096         minimum_width = 5;
5097         minimum_height = 5;
5098         maximum_width = 0;
5099 #ifdef OWN_WINDOW
5100         own_window = 0;
5101         window.type = TYPE_NORMAL;
5102         window.hints = 0;
5103         strcpy(window.class_name, PACKAGE_NAME);
5104         sprintf(window.title, PACKAGE_NAME" (%s)", info.uname_s.nodename);
5105 #endif
5106         stippled_borders = 0;
5107         window.border_inner_margin = 3;
5108         window.border_outer_margin = 1;
5109         window.border_width = 1;
5110         text_alignment = BOTTOM_LEFT;
5111         info.x11.monitor.number = 1;
5112         info.x11.monitor.current = 0;
5113         info.x11.desktop.current = 1; 
5114         info.x11.desktop.number = 1;
5115         info.x11.desktop.nitems = 0;
5116         info.x11.desktop.all_names = NULL; 
5117         info.x11.desktop.name = NULL; 
5118 #endif /* X11 */
5119
5120         free_templates();
5121
5122         free(current_mail_spool);
5123         {
5124                 char buf[256];
5125
5126                 variable_substitute(MAIL_FILE, buf, 256);
5127                 if (buf[0] != '\0') {
5128                         current_mail_spool = strndup(buf, text_buffer_size);
5129                 }
5130         }
5131
5132         no_buffers = 1;
5133         set_update_interval(3);
5134         update_interval_bat = NOBATTERY;
5135         info.music_player_interval = 1.0;
5136         stuff_in_uppercase = 0;
5137         info.users.number = 1;
5138
5139 #ifdef TCP_PORT_MONITOR
5140         /* set default connection limit */
5141         tcp_portmon_set_max_connections(0);
5142 #endif
5143 }
5144
5145 /* returns 1 if you can overwrite or create the file at 'path' */
5146 static _Bool overwrite_works(const char *path)
5147 {
5148         FILE *filepointer;
5149
5150         if (!(filepointer = fopen(path, "w")))
5151                 return 0;
5152         fclose(filepointer);
5153         return 1;
5154 }
5155
5156 /* returns 1 if you can append or create the file at 'path' */
5157 static _Bool append_works(const char *path)
5158 {
5159         FILE *filepointer;
5160
5161         if (!(filepointer = fopen(path, "a")))
5162                 return 0;
5163         fclose(filepointer);
5164         return 1;
5165 }
5166
5167 #ifdef X11
5168 #ifdef DEBUG
5169 /* WARNING, this type not in Xlib spec */
5170 int x11_error_handler(Display *d, XErrorEvent *err)
5171         __attribute__((noreturn));
5172 int x11_error_handler(Display *d, XErrorEvent *err)
5173 {
5174         NORM_ERR("X Error: type %i Display %lx XID %li serial %lu error_code %i request_code %i minor_code %i other Display: %lx\n",
5175                         err->type,
5176                         (long unsigned)err->display,
5177                         (long)err->resourceid,
5178                         err->serial,
5179                         err->error_code,
5180                         err->request_code,
5181                         err->minor_code,
5182                         (long unsigned)d
5183                         );
5184         abort();
5185 }
5186
5187 int x11_ioerror_handler(Display *d)
5188         __attribute__((noreturn));
5189 int x11_ioerror_handler(Display *d)
5190 {
5191         NORM_ERR("X Error: Display %lx\n",
5192                         (long unsigned)d
5193                         );
5194         abort();
5195 }
5196 #endif /* DEBUG */
5197
5198 static void X11_initialisation(void)
5199 {
5200         if (x_initialised == YES) return;
5201         output_methods |= TO_X;
5202         init_X11(disp);
5203         set_default_configurations_for_x();
5204         x_initialised = YES;
5205 #ifdef DEBUG
5206         _Xdebug = 1;
5207         /* WARNING, this type not in Xlib spec */
5208         XSetErrorHandler(&x11_error_handler);
5209         XSetIOErrorHandler(&x11_ioerror_handler);
5210 #endif /* DEBUG */
5211 }
5212
5213 static char **xargv = 0;
5214 static int xargc = 0;
5215
5216 static void X11_create_window(void)
5217 {
5218         if (output_methods & TO_X) {
5219 #ifdef OWN_WINDOW
5220                 init_window(own_window, text_width + window.border_inner_margin * 2 + window.border_outer_margin * 2 + window.border_width * 2,
5221                                 text_height + window.border_inner_margin * 2 + window.border_outer_margin * 2 + window.border_width * 2, set_transparent, background_colour,
5222                                 xargv, xargc);
5223 #else /* OWN_WINDOW */
5224                 init_window(0, text_width + window.border_inner_margin * 2 + window.border_outer_margin * 2 + window.border_width * 2,
5225                                 text_height + window.border_inner_margin * 2 + window.border_outer_margin * 2 + window.border_width * 2, set_transparent, 0,
5226                                 xargv, xargc);
5227 #endif /* OWN_WINDOW */
5228
5229                 setup_fonts();
5230                 load_fonts();
5231                 update_text_area();     /* to position text/window on screen */
5232
5233 #ifdef OWN_WINDOW
5234                 if (own_window && !fixed_pos) {
5235                         XMoveWindow(display, window.window, window.x, window.y);
5236                 }
5237                 if (own_window) {
5238                         set_transparent_background(window.window);
5239                 }
5240 #endif
5241
5242                 create_gc();
5243
5244                 draw_stuff();
5245
5246                 x11_stuff.region = XCreateRegion();
5247 #ifdef HAVE_XDAMAGE
5248                 if (!XDamageQueryExtension(display, &x11_stuff.event_base, &x11_stuff.error_base)) {
5249                         NORM_ERR("Xdamage extension unavailable");
5250                 }
5251                 x11_stuff.damage = XDamageCreate(display, window.window, XDamageReportNonEmpty);
5252                 x11_stuff.region2 = XFixesCreateRegionFromWindow(display, window.window, 0);
5253                 x11_stuff.part = XFixesCreateRegionFromWindow(display, window.window, 0);
5254 #endif /* HAVE_XDAMAGE */
5255
5256                 selected_font = 0;
5257                 update_text_area();     /* to get initial size of the window */
5258         }
5259 #ifdef HAVE_LUA
5260         /* setup lua window globals */
5261         llua_setup_window_table(text_start_x, text_start_y, text_width, text_height);
5262 #endif /* HAVE_LUA */
5263 }
5264 #endif /* X11 */
5265
5266 #define CONF_ERR NORM_ERR("%s: %d: config file error", f, line)
5267 #define CONF_ERR2(a) NORM_ERR("%s: %d: config file error: %s", f, line, a)
5268 #define CONF2(a) if (strcasecmp(name, a) == 0)
5269 #define CONF(a) else CONF2(a)
5270 #define CONF3(a, b) else if (strcasecmp(name, a) == 0 \
5271                 || strcasecmp(name, b) == 0)
5272 #define CONF_CONTINUE 1
5273 #define CONF_BREAK 2
5274 #define CONF_BUFF_SIZE 512
5275
5276 static FILE *open_config_file(const char *f)
5277 {
5278 #ifdef CONFIG_OUTPUT
5279         if (!strcmp(f, "==builtin==")) {
5280                 return conf_cookie_open();
5281         } else
5282 #endif /* CONFIG_OUTPUT */
5283                 return fopen(f, "r");
5284 }
5285
5286 static int do_config_step(int *line, FILE *fp, char *buf, char **name, char **value)
5287 {
5288         char *p, *p2;
5289         (*line)++;
5290         if (fgets(buf, CONF_BUFF_SIZE, fp) == NULL) {
5291                 return CONF_BREAK;
5292         }
5293         remove_comments(buf);
5294
5295         p = buf;
5296
5297         /* skip spaces */
5298         while (*p && isspace((int) *p)) {
5299                 p++;
5300         }
5301         if (*p == '\0') {
5302                 return CONF_CONTINUE;   /* empty line */
5303         }
5304
5305         *name = p;
5306
5307         /* skip name */
5308         p2 = p;
5309         while (*p2 && !isspace((int) *p2)) {
5310                 p2++;
5311         }
5312         if (*p2 != '\0') {
5313                 *p2 = '\0';     /* break at name's end */
5314                 p2++;
5315         }
5316
5317         /* get value */
5318         if (*p2) {
5319                 p = p2;
5320                 while (*p && isspace((int) *p)) {
5321                         p++;
5322                 }
5323
5324                 *value = p;
5325
5326                 p2 = *value + strlen(*value);
5327                 while (isspace((int) *(p2 - 1))) {
5328                         *--p2 = '\0';
5329                 }
5330         } else {
5331                 *value = 0;
5332         }
5333         return 0;
5334 }
5335
5336 char load_config_file(const char *f)
5337 {
5338         int line = 0;
5339         FILE *fp;
5340
5341         fp = open_config_file(f);
5342         if (!fp) {
5343                 return FALSE;
5344         }
5345         DBGP("reading contents from config file '%s'", f);
5346
5347         while (!feof(fp)) {
5348                 char buff[CONF_BUFF_SIZE], *name, *value;
5349                 int ret = do_config_step(&line, fp, buff, &name, &value);
5350                 if (ret == CONF_BREAK) {
5351                         break;
5352                 } else if (ret == CONF_CONTINUE) {
5353                         continue;
5354                 }
5355
5356 #ifdef X11
5357                 CONF2("out_to_x") {
5358                         /* don't listen if X is already initialised or
5359                          * if we already know we don't want it */
5360                         if(x_initialised != YES) {
5361                                 if (string_to_bool(value)) {
5362                                         output_methods &= TO_X;
5363                                 } else {
5364                                         output_methods &= ~TO_X;
5365                                         x_initialised = NEVER;
5366                                 }
5367                         }
5368                 }
5369                 CONF("display") {
5370                         if (!value || x_initialised == YES) {
5371                                 CONF_ERR;
5372                         } else {
5373                                 if (disp)
5374                                         free(disp);
5375                                 disp = strdup(value);
5376                         }
5377                 }
5378                 CONF("alignment") {
5379 #ifdef OWN_WINDOW
5380                         if (window.type == TYPE_DOCK)
5381                                 ;
5382                         else
5383 #endif /*OWN_WINDOW */
5384                         if (value) {
5385                                 int a = string_to_alignment(value);
5386
5387                                 if (a <= 0) {
5388                                         CONF_ERR;
5389                                 } else {
5390                                         text_alignment = a;
5391                                 }
5392                         } else {
5393                                 CONF_ERR;
5394                         }
5395                 }
5396                 CONF("background") {
5397                         fork_to_background = string_to_bool(value);
5398                 }
5399 #else
5400                 CONF2("background") {
5401                         fork_to_background = string_to_bool(value);
5402                 }
5403 #endif /* X11 */
5404 #ifdef X11
5405                 CONF("show_graph_scale") {
5406                         show_graph_scale = string_to_bool(value);
5407                 }
5408                 CONF("show_graph_range") {
5409                         show_graph_range = string_to_bool(value);
5410                 }
5411                 CONF("border_inner_margin") {
5412                         if (value) {
5413                                 window.border_inner_margin = strtol(value, 0, 0);
5414                                 if (window.border_inner_margin < 0) window.border_inner_margin = 0;
5415                         } else {
5416                                 CONF_ERR;
5417                         }
5418                 }
5419                 CONF("border_outer_margin") {
5420                         if (value) {
5421                                 window.border_outer_margin = strtol(value, 0, 0);
5422                                 if (window.border_outer_margin < 0) window.border_outer_margin = 0;
5423                         } else {
5424                                 CONF_ERR;
5425                         }
5426                 }
5427                 CONF("border_width") {
5428                         if (value) {
5429                                 window.border_width = strtol(value, 0, 0);
5430                                 if (window.border_width < 0) window.border_width = 0;
5431                         } else {
5432                                 CONF_ERR;
5433                         }
5434                 }
5435 #endif /* X11 */
5436 #define TEMPLATE_CONF(n) \
5437                 CONF("template"#n) { \
5438                         if (set_template(n, value)) \
5439                                 CONF_ERR; \
5440                 }
5441                 TEMPLATE_CONF(0)
5442                 TEMPLATE_CONF(1)
5443                 TEMPLATE_CONF(2)
5444                 TEMPLATE_CONF(3)
5445                 TEMPLATE_CONF(4)
5446                 TEMPLATE_CONF(5)
5447                 TEMPLATE_CONF(6)
5448                 TEMPLATE_CONF(7)
5449                 TEMPLATE_CONF(8)
5450                 TEMPLATE_CONF(9)
5451                 CONF("imap") {
5452                         if (value) {
5453                                 info.mail = parse_mail_args(IMAP_TYPE, value);
5454                         } else {
5455                                 CONF_ERR;
5456                         }
5457                 }
5458                 CONF("pop3") {
5459                         if (value) {
5460                                 info.mail = parse_mail_args(POP3_TYPE, value);
5461                         } else {
5462                                 CONF_ERR;
5463                         }
5464                 }
5465                 CONF("default_bar_size") {
5466                         char err = 0;
5467                         if (value) {
5468                                 if (sscanf(value, "%d %d", &default_bar_width, &default_bar_height) != 2) {
5469                                         err = 1;
5470                                 }
5471                         } else {
5472                                 err = 1;
5473                         }
5474                         if (err) {
5475                                 CONF_ERR2("default_bar_size takes 2 integer arguments (ie. 'default_bar_size 0 6')")
5476                         }
5477                 }
5478 #ifdef X11
5479                 CONF("default_graph_size") {
5480                         char err = 0;
5481                         if (value) {
5482                                 if (sscanf(value, "%d %d", &default_graph_width, &default_graph_height) != 2) {
5483                                         err = 1;
5484                                 }
5485                         } else {
5486                                 err = 1;
5487                         }
5488                         if (err) {
5489                                 CONF_ERR2("default_graph_size takes 2 integer arguments (ie. 'default_graph_size 0 6')")
5490                         }
5491                 }
5492                 CONF("default_gauge_size") {
5493                         char err = 0;
5494                         if (value) {
5495                                 if (sscanf(value, "%d %d", &default_gauge_width, &default_gauge_height) != 2) {
5496                                         err = 1;
5497                                 }
5498                         } else {
5499                                 err = 1;
5500                         }
5501                         if (err) {
5502                                 CONF_ERR2("default_gauge_size takes 2 integer arguments (ie. 'default_gauge_size 0 6')")
5503                         }
5504                 }
5505 #endif
5506 #ifdef MPD
5507                 CONF("mpd_host") {
5508                         if (value) {
5509                                 mpd_set_host(value);
5510                         } else {
5511                                 CONF_ERR;
5512                         }
5513                 }
5514                 CONF("mpd_port") {
5515                         if (value && mpd_set_port(value)) {
5516                                 CONF_ERR;
5517                         }
5518                 }
5519                 CONF("mpd_password") {
5520                         if (value) {
5521                                 mpd_set_password(value, 0);
5522                         } else {
5523                                 CONF_ERR;
5524                         }
5525                 }
5526 #endif
5527                 CONF("music_player_interval") {
5528                         if (value) {
5529                                 info.music_player_interval = strtod(value, 0);
5530                         } else {
5531                                 CONF_ERR;
5532                         }
5533                 }
5534 #ifdef __OpenBSD__
5535                 CONF("sensor_device") {
5536                         if (value) {
5537                                 sensor_device = strtol(value, 0, 0);
5538                         } else {
5539                                 CONF_ERR;
5540                         }
5541                 }
5542 #endif
5543                 CONF("cpu_avg_samples") {
5544                         if (value) {
5545                                 cpu_avg_samples = strtol(value, 0, 0);
5546                                 if (cpu_avg_samples < 1 || cpu_avg_samples > 14) {
5547                                         CONF_ERR;
5548                                 } else {
5549                                         info.cpu_avg_samples = cpu_avg_samples;
5550                                 }
5551                         } else {
5552                                 CONF_ERR;
5553                         }
5554                 }
5555                 CONF("net_avg_samples") {
5556                         if (value) {
5557                                 net_avg_samples = strtol(value, 0, 0);
5558                                 if (net_avg_samples < 1 || net_avg_samples > 14) {
5559                                         CONF_ERR;
5560                                 } else {
5561                                         info.net_avg_samples = net_avg_samples;
5562                                 }
5563                         } else {
5564                                 CONF_ERR;
5565                         }
5566                 }
5567                 CONF("diskio_avg_samples") {
5568                         if (value) {
5569                                 diskio_avg_samples = strtol(value, 0, 0);
5570                                 if (diskio_avg_samples < 1 || diskio_avg_samples > 14) {
5571                                         CONF_ERR;
5572                                 } else {
5573                                         info.diskio_avg_samples = diskio_avg_samples;
5574                                 }
5575                         } else {
5576                                 CONF_ERR;
5577                         }
5578                 }
5579
5580 #ifdef HAVE_XDBE
5581                 CONF("double_buffer") {
5582                         use_xdbe = string_to_bool(value);
5583                 }
5584 #endif
5585 #ifdef X11
5586                 CONF("override_utf8_locale") {
5587                         utf8_mode = string_to_bool(value);
5588                 }
5589                 CONF("draw_borders") {
5590                         draw_borders = string_to_bool(value);
5591                 }
5592                 CONF("draw_graph_borders") {
5593                         draw_graph_borders = string_to_bool(value);
5594                 }
5595                 CONF("draw_shades") {
5596                         draw_shades = string_to_bool(value);
5597                 }
5598                 CONF("draw_outline") {
5599                         draw_outline = string_to_bool(value);
5600                 }
5601 #endif /* X11 */
5602                 CONF("out_to_console") {
5603                         if(string_to_bool(value)) {
5604                                 output_methods |= TO_STDOUT;
5605                         } else {
5606                                 output_methods &= ~TO_STDOUT;
5607                         }
5608                 }
5609                 CONF("extra_newline") {
5610                         extra_newline = string_to_bool(value);
5611                 }
5612                 CONF("out_to_stderr") {
5613                         if(string_to_bool(value))
5614                                 output_methods |= TO_STDERR;
5615                 }
5616 #ifdef NCURSES
5617                 CONF("out_to_ncurses") {
5618                         if(string_to_bool(value)) {
5619                                 initscr();
5620                                 start_color();
5621                                 output_methods |= TO_NCURSES;
5622                         }
5623                 }
5624 #endif
5625                 CONF("overwrite_file") {
5626                         if(overwrite_file) {
5627                                 free(overwrite_file);
5628                                 overwrite_file = 0;
5629                         }
5630                         if(overwrite_works(value)) {
5631                                 overwrite_file = strdup(value);
5632                                 output_methods |= OVERWRITE_FILE;
5633                         } else
5634                                 NORM_ERR("overwrite_file won't be able to create/overwrite '%s'", value);
5635                 }
5636                 CONF("append_file") {
5637                         if(append_file) {
5638                                 free(append_file);
5639                                 append_file = 0;
5640                         }
5641                         if(append_works(value)) {
5642                                 append_file = strdup(value);
5643                                 output_methods |= APPEND_FILE;
5644                         } else
5645                                 NORM_ERR("append_file won't be able to create/append '%s'", value);
5646                 }
5647                 CONF("use_spacer") {
5648                         if (value) {
5649                                 if (strcasecmp(value, "left") == EQUAL) {
5650                                         use_spacer = LEFT_SPACER;
5651                                 } else if (strcasecmp(value, "right") == EQUAL) {
5652                                         use_spacer = RIGHT_SPACER;
5653                                 } else if (strcasecmp(value, "none") == EQUAL) {
5654                                         use_spacer = NO_SPACER;
5655                                 } else {
5656                                         use_spacer = string_to_bool(value);
5657                                         NORM_ERR("use_spacer should have an argument of left, right, or"
5658                                                 " none.  '%s' seems to be some form of '%s', so"
5659                                                 " defaulting to %s.", value,
5660                                                 use_spacer ? "true" : "false",
5661                                                 use_spacer ? "right" : "none");
5662                                         if (use_spacer) {
5663                                                 use_spacer = RIGHT_SPACER;
5664                                         } else {
5665                                                 use_spacer = NO_SPACER;
5666                                         }
5667                                 }
5668                         } else {
5669                                 NORM_ERR("use_spacer should have an argument. Defaulting to right.");
5670                                 use_spacer = RIGHT_SPACER;
5671                         }
5672                 }
5673 #ifdef X11
5674 #ifdef XFT
5675                 CONF("use_xft") {
5676                         use_xft = string_to_bool(value);
5677                 }
5678                 CONF("font") {
5679                         if (value) {
5680                                 set_first_font(value);
5681                         }
5682                 }
5683                 CONF("xftalpha") {
5684                         if (value && font_count >= 0) {
5685                                 fonts[0].font_alpha = atof(value) * 65535.0;
5686                         }
5687                 }
5688                 CONF("xftfont") {
5689                         if (use_xft) {
5690 #else
5691                 CONF("use_xft") {
5692                         if (string_to_bool(value)) {
5693                                 NORM_ERR("Xft not enabled at compile time");
5694                         }
5695                 }
5696                 CONF("xftfont") {
5697                         /* xftfont silently ignored when no Xft */
5698                 }
5699                 CONF("xftalpha") {
5700                         /* xftalpha is silently ignored when no Xft */
5701                 }
5702                 CONF("font") {
5703 #endif
5704                         if (value) {
5705                                 set_first_font(value);
5706                         }
5707 #ifdef XFT
5708                         }
5709 #endif
5710                 }
5711                 CONF("gap_x") {
5712                         if (value) {
5713                                 gap_x = atoi(value);
5714                         } else {
5715                                 CONF_ERR;
5716                         }
5717                 }
5718                 CONF("gap_y") {
5719                         if (value) {
5720                                 gap_y = atoi(value);
5721                         } else {
5722                                 CONF_ERR;
5723                         }
5724                 }
5725 #endif /* X11 */
5726                 CONF("mail_spool") {
5727                         if (value) {
5728                                 char buffer[256];
5729
5730                                 variable_substitute(value, buffer, 256);
5731
5732                                 if (buffer[0] != '\0') {
5733                                         if (current_mail_spool) {
5734                                                 free(current_mail_spool);
5735                                         }
5736                                         current_mail_spool = strndup(buffer, text_buffer_size);
5737                                 }
5738                         } else {
5739                                 CONF_ERR;
5740                         }
5741                 }
5742 #ifdef X11
5743                 CONF("minimum_size") {
5744                         if (value) {
5745                                 if (sscanf(value, "%d %d", &minimum_width, &minimum_height)
5746                                                 != 2) {
5747                                         if (sscanf(value, "%d", &minimum_width) != 1) {
5748                                                 CONF_ERR;
5749                                         }
5750                                 }
5751                         } else {
5752                                 CONF_ERR;
5753                         }
5754                 }
5755                 CONF("maximum_width") {
5756                         if (value) {
5757                                 if (sscanf(value, "%d", &maximum_width) != 1) {
5758                                         CONF_ERR;
5759                                 }
5760                         } else {
5761                                 CONF_ERR;
5762                         }
5763                 }
5764 #endif /* X11 */
5765                 CONF("no_buffers") {
5766                         no_buffers = string_to_bool(value);
5767                 }
5768                 CONF("top_name_width") {
5769                         if (value) {
5770                                 if (sscanf(value, "%u", &top_name_width) != 1) {
5771                                         CONF_ERR;
5772                                 }
5773                         } else {
5774                                 CONF_ERR;
5775                         }
5776                         if (top_name_width >= max_user_text) {
5777                                 top_name_width = max_user_text - 1;
5778                         }
5779                 }
5780                 CONF("top_cpu_separate") {
5781                         cpu_separate = string_to_bool(value);
5782                 }
5783                 CONF("short_units") {
5784                         short_units = string_to_bool(value);
5785                 }
5786                 CONF("format_human_readable") {
5787                         format_human_readable = string_to_bool(value);
5788                 }
5789 #ifdef HDDTEMP
5790                 CONF("hddtemp_host") {
5791                         set_hddtemp_host(value);
5792                 }
5793                 CONF("hddtemp_port") {
5794                         set_hddtemp_port(value);
5795                 }
5796 #endif /* HDDTEMP */
5797                 CONF("pad_percents") {
5798                         pad_percents = atoi(value);
5799                 }
5800 #ifdef X11
5801 #ifdef OWN_WINDOW
5802                 CONF("own_window") {
5803                         if (value) {
5804                                 own_window = string_to_bool(value);
5805                         }
5806                 }
5807                 CONF("own_window_class") {
5808                         if (value) {
5809                                 memset(window.class_name, 0, sizeof(window.class_name));
5810                                 strncpy(window.class_name, value,
5811                                                 sizeof(window.class_name) - 1);
5812                         }
5813                 }
5814                 CONF("own_window_title") {
5815                         if (value) {
5816                                 memset(window.title, 0, sizeof(window.title));
5817                                 strncpy(window.title, value, sizeof(window.title) - 1);
5818                         }
5819                 }
5820                 CONF("own_window_transparent") {
5821                         if (value) {
5822                                 set_transparent = string_to_bool(value);
5823                         }
5824                 }
5825                 CONF("own_window_hints") {
5826                         if (value) {
5827                                 char *p_hint, *p_save;
5828                                 char delim[] = ", ";
5829
5830                                 /* tokenize the value into individual hints */
5831                                 if ((p_hint = strtok_r(value, delim, &p_save)) != NULL) {
5832                                         do {
5833                                                 /* fprintf(stderr, "hint [%s] parsed\n", p_hint); */
5834                                                 if (strncmp(p_hint, "undecorate", 10) == EQUAL) {
5835                                                         SET_HINT(window.hints, HINT_UNDECORATED);
5836                                                 } else if (strncmp(p_hint, "below", 5) == EQUAL) {
5837                                                         SET_HINT(window.hints, HINT_BELOW);
5838                                                 } else if (strncmp(p_hint, "above", 5) == EQUAL) {
5839                                                         SET_HINT(window.hints, HINT_ABOVE);
5840                                                 } else if (strncmp(p_hint, "sticky", 6) == EQUAL) {
5841                                                         SET_HINT(window.hints, HINT_STICKY);
5842                                                 } else if (strncmp(p_hint, "skip_taskbar", 12) == EQUAL) {
5843                                                         SET_HINT(window.hints, HINT_SKIP_TASKBAR);
5844                                                 } else if (strncmp(p_hint, "skip_pager", 10) == EQUAL) {
5845                                                         SET_HINT(window.hints, HINT_SKIP_PAGER);
5846                                                 } else {
5847                                                         CONF_ERR;
5848                                                 }
5849
5850                                                 p_hint = strtok_r(NULL, delim, &p_save);
5851                                         } while (p_hint != NULL);
5852                                 }
5853                         } else {
5854                                 CONF_ERR;
5855                         }
5856                 }
5857                 CONF("own_window_type") {
5858                         if (value) {
5859                                 if (strncmp(value, "normal", 6) == EQUAL) {
5860                                         window.type = TYPE_NORMAL;
5861                                 } else if (strncmp(value, "desktop", 7) == EQUAL) {
5862                                         window.type = TYPE_DESKTOP;
5863                                 } else if (strncmp(value, "dock", 4) == EQUAL) {
5864                                         window.type = TYPE_DOCK;
5865                                         text_alignment = TOP_LEFT;
5866                                 } else if (strncmp(value, "panel", 5) == EQUAL) {
5867                                         window.type = TYPE_PANEL;
5868                                 } else if (strncmp(value, "override", 8) == EQUAL) {
5869                                         window.type = TYPE_OVERRIDE;
5870                                 } else {
5871                                         CONF_ERR;
5872                                 }
5873                         } else {
5874                                 CONF_ERR;
5875                         }
5876                 }
5877 #endif
5878                 CONF("stippled_borders") {
5879                         if (value) {
5880                                 stippled_borders = strtol(value, 0, 0);
5881                         } else {
5882                                 stippled_borders = 4;
5883                         }
5884                 }
5885 #ifdef IMLIB2
5886                 CONF("imlib_cache_size") {
5887                         if (value) {
5888                                 cimlib_set_cache_size(atoi(value));
5889                         }
5890                 }
5891                 CONF("imlib_cache_flush_interval") {
5892                         if (value) {
5893                                 cimlib_set_cache_flush_interval(atoi(value));
5894                         }
5895                 }
5896 #endif /* IMLIB2 */
5897 #endif /* X11 */
5898                 CONF("update_interval_on_battery") {
5899                         if (value) {
5900                                 update_interval_bat = strtod(value, 0);
5901                         } else {
5902                                 CONF_ERR;
5903                         }
5904                 }
5905                 CONF("update_interval") {
5906                         if (value) {
5907                                 set_update_interval(strtod(value, 0));
5908                         } else {
5909                                 CONF_ERR;
5910                         }
5911                         if (info.music_player_interval == 0) {
5912                                 // default to update_interval
5913                                 info.music_player_interval = update_interval;
5914                         }
5915                 }
5916                 CONF("total_run_times") {
5917                         if (value) {
5918                                 total_run_times = strtod(value, 0);
5919                         } else {
5920                                 CONF_ERR;
5921                         }
5922                 }
5923                 CONF("uppercase") {
5924                         stuff_in_uppercase = string_to_bool(value);
5925                 }
5926                 CONF("max_specials") {
5927                         if (value) {
5928                                 max_specials = atoi(value);
5929                         } else {
5930                                 CONF_ERR;
5931                         }
5932                 }
5933                 CONF("max_user_text") {
5934                         if (value) {
5935                                 max_user_text = atoi(value);
5936                         } else {
5937                                 CONF_ERR;
5938                         }
5939                 }
5940                 CONF("text_buffer_size") {
5941                         if (value) {
5942                                 text_buffer_size = atoi(value);
5943                                 if (text_buffer_size < DEFAULT_TEXT_BUFFER_SIZE) {
5944                                         NORM_ERR("text_buffer_size must be >=%i bytes", DEFAULT_TEXT_BUFFER_SIZE);
5945                                         text_buffer_size = DEFAULT_TEXT_BUFFER_SIZE;
5946                                 }
5947                         } else {
5948                                 CONF_ERR;
5949                         }
5950                 }
5951                 CONF("text") {
5952 #ifdef X11
5953                         if (output_methods & TO_X) {
5954                                 X11_initialisation();
5955                         }
5956 #endif
5957
5958                         if (global_text) {
5959                                 free(global_text);
5960                                 global_text = 0;
5961                         }
5962
5963                         global_text = (char *) malloc(1);
5964                         global_text[0] = '\0';
5965
5966                         while (!feof(fp)) {
5967                                 unsigned int l = strlen(global_text);
5968                                 unsigned int bl;
5969                                 char buf[CONF_BUFF_SIZE];
5970
5971                                 if (fgets(buf, CONF_BUFF_SIZE, fp) == NULL) {
5972                                         break;
5973                                 }
5974
5975                                 /* Remove \\-\n. */
5976                                 bl = strlen(buf);
5977                                 if (bl >= 2 && buf[bl-2] == '\\' && buf[bl-1] == '\n') {
5978                                         buf[bl-2] = '\0';
5979                                         bl -= 2;
5980                                         if (bl == 0) {
5981                                                 continue;
5982                                         }
5983                                 }
5984
5985                                 /* Check for continuation of \\-\n. */
5986                                 if (l > 0 && buf[0] == '\n' && global_text[l-1] == '\\') {
5987                                         global_text[l-1] = '\0';
5988                                         continue;
5989                                 }
5990
5991                                 global_text = (char *) realloc(global_text, l + bl + 1);
5992                                 strcat(global_text, buf);
5993
5994                                 if (strlen(global_text) > max_user_text) {
5995                                         break;
5996                                 }
5997                         }
5998                         fclose(fp);
5999                         if (strlen(global_text) < 1) {
6000                                 CRIT_ERR(NULL, NULL, "no text supplied in configuration; exiting");
6001                         }
6002                         global_text_lines = line + 1;
6003                         return TRUE;
6004                 }
6005 #ifdef TCP_PORT_MONITOR
6006                 CONF("max_port_monitor_connections") {
6007                         int max;
6008                         if (!value || (sscanf(value, "%d", &max) != 1)) {
6009                                 /* an error. use default, warn and continue. */
6010                                 tcp_portmon_set_max_connections(0);
6011                                 CONF_ERR;
6012                         } else if (tcp_portmon_set_max_connections(max)) {
6013                                 /* max is < 0, default has been set*/
6014                                 CONF_ERR;
6015                         }
6016                 }
6017 #endif
6018                 CONF("if_up_strictness") {
6019                         if (!value) {
6020                                 NORM_ERR("incorrect if_up_strictness value, defaulting to 'up'");
6021                                 ifup_strictness = IFUP_UP;
6022                         } else if (strcasecmp(value, "up") == EQUAL) {
6023                                 ifup_strictness = IFUP_UP;
6024                         } else if (strcasecmp(value, "link") == EQUAL) {
6025                                 ifup_strictness = IFUP_LINK;
6026                         } else if (strcasecmp(value, "address") == EQUAL) {
6027                                 ifup_strictness = IFUP_ADDR;
6028                         } else {
6029                                 NORM_ERR("incorrect if_up_strictness value, defaulting to 'up'");
6030                                 ifup_strictness = IFUP_UP;
6031                         }
6032                 }
6033
6034                 CONF("temperature_unit") {
6035                         if (!value) {
6036                                 NORM_ERR("config option 'temperature_unit' needs an argument, either 'celsius' or 'fahrenheit'");
6037                         } else if (set_temp_output_unit(value)) {
6038                                 NORM_ERR("temperature_unit: incorrect argument");
6039                         }
6040                 }
6041
6042 #ifdef HAVE_LUA
6043                 CONF("lua_load") {
6044                         if (value) {
6045                                 char *ptr = strtok(value, " ");
6046                                 while (ptr) {
6047                                         llua_load(ptr);
6048                                         ptr = strtok(NULL, " ");
6049                                 }
6050                         } else {
6051                                 CONF_ERR;
6052                         }
6053                 }
6054 #ifdef X11
6055                 CONF("lua_draw_hook_pre") {
6056                         if (value) {
6057                                 llua_set_draw_pre_hook(value);
6058                         } else {
6059                                 CONF_ERR;
6060                         }
6061                 }
6062                 CONF("lua_draw_hook_post") {
6063                         if (value) {
6064                                 llua_set_draw_post_hook(value);
6065                         } else {
6066                                 CONF_ERR;
6067                         }
6068                 }
6069                 CONF("lua_startup_hook") {
6070                         if (value) {
6071                                 llua_set_startup_hook(value);
6072                         } else {
6073                                 CONF_ERR;
6074                         }
6075                 }
6076                 CONF("lua_shutdown_hook") {
6077                         if (value) {
6078                                 llua_set_shutdown_hook(value);
6079                         } else {
6080                                 CONF_ERR;
6081                         }
6082                 }
6083 #endif /* X11 */
6084 #endif /* HAVE_LUA */
6085
6086                 CONF("color0"){}
6087                 CONF("color1"){}
6088                 CONF("color2"){}
6089                 CONF("color3"){}
6090                 CONF("color4"){}
6091                 CONF("color5"){}
6092                 CONF("color6"){}
6093                 CONF("color7"){}
6094                 CONF("color8"){}
6095                 CONF("color9"){}
6096                 CONF("default_color"){}
6097                 CONF3("default_shade_color", "default_shadecolor"){}
6098                 CONF3("default_outline_color", "default_outlinecolor") {}
6099                 CONF("own_window_colour") {}
6100
6101                 else {
6102                         NORM_ERR("%s: %d: no such configuration: '%s'", f, line, name);
6103                 }
6104         }
6105
6106         fclose(fp);
6107
6108         if (info.music_player_interval == 0) {
6109                 // default to update_interval
6110                 info.music_player_interval = update_interval;
6111         }
6112         if (!global_text) { // didn't supply any text
6113                 CRIT_ERR(NULL, NULL, "missing text block in configuration; exiting");
6114         }
6115         return TRUE;
6116 }
6117
6118 #ifdef X11
6119 static void load_config_file_x11(const char *f)
6120 {
6121         int line = 0;
6122         FILE *fp;
6123
6124         fp = open_config_file(f);
6125         if (!fp) {
6126                 return;
6127         }
6128         DBGP("reading contents from config file '%s'", f);
6129
6130         while (!feof(fp)) {
6131                 char buff[CONF_BUFF_SIZE], *name, *value;
6132                 int ret = do_config_step(&line, fp, buff, &name, &value);
6133                 if (ret == CONF_BREAK) {
6134                         break;
6135                 } else if (ret == CONF_CONTINUE) {
6136                         continue;
6137                 }
6138
6139                 CONF2("color0") {
6140                         X11_initialisation();
6141                         if (x_initialised == YES) {
6142                                 if (value) {
6143                                         color0 = get_x11_color(value);
6144                                 } else {
6145                                         CONF_ERR;
6146                                 }
6147                         }
6148                 }
6149                 CONF("color1") {
6150                         X11_initialisation();
6151                         if (x_initialised == YES) {
6152                                 if (value) {
6153                                         color1 = get_x11_color(value);
6154                                 } else {
6155                                         CONF_ERR;
6156                                 }
6157                         }
6158                 }
6159                 CONF("color2") {
6160                         X11_initialisation();
6161                         if (x_initialised == YES) {
6162                                 if (value) {
6163                                         color2 = get_x11_color(value);
6164                                 } else {
6165                                         CONF_ERR;
6166                                 }
6167                         }
6168                 }
6169                 CONF("color3") {
6170                         X11_initialisation();
6171                         if (x_initialised == YES) {
6172                                 if (value) {
6173                                         color3 = get_x11_color(value);
6174                                 } else {
6175                                         CONF_ERR;
6176                                 }
6177                         }
6178                 }
6179                 CONF("color4") {
6180                         X11_initialisation();
6181                         if (x_initialised == YES) {
6182                                 if (value) {
6183                                         color4 = get_x11_color(value);
6184                                 } else {
6185                                         CONF_ERR;
6186                                 }
6187                         }
6188                 }
6189                 CONF("color5") {
6190                         X11_initialisation();
6191                         if (x_initialised == YES) {
6192                                 if (value) {
6193                                         color5 = get_x11_color(value);
6194                                 } else {
6195                                         CONF_ERR;
6196                                 }
6197                         }
6198                 }
6199                 CONF("color6") {
6200                         X11_initialisation();
6201                         if (x_initialised == YES) {
6202                                 if (value) {
6203                                         color6 = get_x11_color(value);
6204                                 } else {
6205                                         CONF_ERR;
6206                                 }
6207                         }
6208                 }
6209                 CONF("color7") {
6210                         X11_initialisation();
6211                         if (x_initialised == YES) {
6212                                 if (value) {
6213                                         color7 = get_x11_color(value);
6214                                 } else {
6215                                         CONF_ERR;
6216                                 }
6217                         }
6218                 }
6219                 CONF("color8") {
6220                         X11_initialisation();
6221                         if (x_initialised == YES) {
6222                                 if (value) {
6223                                         color8 = get_x11_color(value);
6224                                 } else {
6225                                         CONF_ERR;
6226                                 }
6227                         }
6228                 }
6229                 CONF("color9") {
6230                         X11_initialisation();
6231                         if (x_initialised == YES) {
6232                                 if (value) {
6233                                         color9 = get_x11_color(value);
6234                                 } else {
6235                                         CONF_ERR;
6236                                 }
6237                         }
6238                 }
6239                 CONF("default_color") {
6240                         X11_initialisation();
6241                         if (x_initialised == YES) {
6242                                 if (value) {
6243                                         default_fg_color = get_x11_color(value);
6244                                 } else {
6245                                         CONF_ERR;
6246                                 }
6247                         }
6248                 }
6249                 CONF3("default_shade_color", "default_shadecolor") {
6250                         X11_initialisation();
6251                         if (x_initialised == YES) {
6252                                 if (value) {
6253                                         default_bg_color = get_x11_color(value);
6254                                 } else {
6255                                         CONF_ERR;
6256                                 }
6257                         }
6258                 }
6259                 CONF3("default_outline_color", "default_outlinecolor") {
6260                         X11_initialisation();
6261                         if (x_initialised == YES) {
6262                                 if (value) {
6263                                         default_out_color = get_x11_color(value);
6264                                 } else {
6265                                         CONF_ERR;
6266                                 }
6267                         }
6268                 }
6269 #ifdef OWN_WINDOW
6270                 CONF("own_window_colour") {
6271                         X11_initialisation();
6272                         if (x_initialised == YES) {
6273                                 if (value) {
6274                                         background_colour = get_x11_color(value);
6275                                 } else {
6276                                         NORM_ERR("Invalid colour for own_window_colour (try omitting the "
6277                                                 "'#' for hex colours");
6278                                 }
6279                         }
6280                 }
6281 #endif
6282                 CONF("text") {
6283                         /* initialize X11 if nothing X11-related is mentioned before TEXT (and if X11 is the default outputmethod) */
6284                         if(output_methods & TO_X) {
6285                                 X11_initialisation();
6286                         }
6287                 }
6288 #undef CONF
6289 #undef CONF2
6290 #undef CONF3
6291 #undef CONF_ERR
6292 #undef CONF_ERR2
6293 #undef CONF_BREAK
6294 #undef CONF_CONTINUE
6295 #undef CONF_BUFF_SIZE
6296         }
6297
6298         fclose(fp);
6299
6300 }
6301 #endif /* X11 */
6302
6303 static void print_help(const char *prog_name) {
6304         printf("Usage: %s [OPTION]...\n"
6305                         PACKAGE_NAME" is a system monitor that renders text on desktop or to own transparent\n"
6306                         "window. Command line options will override configurations defined in config\n"
6307                         "file.\n"
6308                         "   -v, --version             version\n"
6309                         "   -q, --quiet               quiet mode\n"
6310                         "   -D, --debug               increase debugging output, ie. -DD for more debugging\n"
6311                         "   -c, --config=FILE         config file to load\n"
6312 #ifdef CONFIG_OUTPUT
6313                         "   -C, --print-config        print the builtin default config to stdout\n"
6314                         "                             e.g. 'conky -C > ~/.conkyrc' will create a new default config\n"
6315 #endif
6316                         "   -d, --daemonize           daemonize, fork to background\n"
6317                         "   -h, --help                help\n"
6318 #ifdef X11
6319                         "   -a, --alignment=ALIGNMENT text alignment on screen, {top,bottom,middle}_{left,right,middle}\n"
6320                         "   -f, --font=FONT           font to use\n"
6321                         "   -X, --display=DISPLAY     X11 display to use\n"
6322 #ifdef OWN_WINDOW
6323                         "   -o, --own-window          create own window to draw\n"
6324 #endif
6325 #ifdef HAVE_XDBE
6326                         "   -b, --double-buffer       double buffer (prevents flickering)\n"
6327 #endif
6328                         "   -w, --window-id=WIN_ID    window id to draw\n"
6329                         "   -x X                      x position\n"
6330                         "   -y Y                      y position\n"
6331 #endif /* X11 */
6332                         "   -t, --text=TEXT           text to render, remember single quotes, like -t '$uptime'\n"
6333                         "   -u, --interval=SECS       update interval\n"
6334                         "   -i COUNT                  number of times to update "PACKAGE_NAME" (and quit)\n",
6335                         prog_name
6336         );
6337 }
6338
6339 /* : means that character before that takes an argument */
6340 static const char *getopt_string = "vVqdDt:u:i:hc:"
6341 #ifdef X11
6342         "x:y:w:a:f:X:"
6343 #ifdef OWN_WINDOW
6344         "o"
6345 #endif
6346 #ifdef HAVE_XDBE
6347         "b"
6348 #endif
6349 #endif /* X11 */
6350 #ifdef CONFIG_OUTPUT
6351         "C"
6352 #endif
6353         ;
6354
6355 static const struct option longopts[] = {
6356         { "help", 0, NULL, 'h' },
6357         { "version", 0, NULL, 'V' },
6358         { "debug", 0, NULL, 'D' },
6359         { "config", 1, NULL, 'c' },
6360 #ifdef CONFIG_OUTPUT
6361         { "print-config", 0, NULL, 'C' },
6362 #endif
6363         { "daemonize", 0, NULL, 'd' },
6364 #ifdef X11
6365         { "alignment", 1, NULL, 'a' },
6366         { "font", 1, NULL, 'f' },
6367         { "display", 1, NULL, 'X' },
6368 #ifdef OWN_WINDOW
6369         { "own-window", 0, NULL, 'o' },
6370 #endif
6371 #ifdef HAVE_XDBE
6372         { "double-buffer", 0, NULL, 'b' },
6373 #endif
6374         { "window-id", 1, NULL, 'w' },
6375 #endif /* X11 */
6376         { "text", 1, NULL, 't' },
6377         { "interval", 0, NULL, 'u' },
6378         { 0, 0, 0, 0 }
6379 };
6380
6381 void initialisation(int argc, char **argv) {
6382         struct sigaction act, oact;
6383
6384         set_default_configurations();
6385         load_config_file(current_config);
6386         currentconffile = conftree_add(currentconffile, current_config);
6387
6388         /* init specials array */
6389         if ((specials = calloc(sizeof(struct special_t), max_specials)) == 0) {
6390                 NORM_ERR("failed to create specials array");
6391         }
6392
6393 #ifdef MAIL_FILE
6394         if (current_mail_spool == NULL) {
6395                 char buf[256];
6396
6397                 variable_substitute(MAIL_FILE, buf, 256);
6398
6399                 if (buf[0] != '\0') {
6400                         current_mail_spool = strndup(buf, text_buffer_size);
6401                 }
6402         }
6403 #endif
6404
6405         /* handle other command line arguments */
6406
6407 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__) \
6408                 || defined(__NetBSD__)
6409         optind = optreset = 1;
6410 #else
6411         optind = 0;
6412 #endif
6413
6414 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
6415         if ((kd = kvm_open("/dev/null", "/dev/null", "/dev/null", O_RDONLY,
6416                         "kvm_open")) == NULL) {
6417                 CRIT_ERR(NULL, NULL, "cannot read kvm");
6418         }
6419 #endif
6420
6421         while (1) {
6422                 int c = getopt_long(argc, argv, getopt_string, longopts, NULL);
6423
6424                 if (c == -1) {
6425                         break;
6426                 }
6427
6428                 switch (c) {
6429                         case 'd':
6430                                 fork_to_background = 1;
6431                                 break;
6432                         case 'D':
6433                                 global_debug_level++;
6434                                 break;
6435 #ifdef X11
6436                         case 'f':
6437                                 set_first_font(optarg);
6438                                 break;
6439                         case 'a':
6440                                 text_alignment = string_to_alignment(optarg);
6441                                 break;
6442
6443 #ifdef OWN_WINDOW
6444                         case 'o':
6445                                 own_window = 1;
6446                                 break;
6447 #endif
6448 #ifdef HAVE_XDBE
6449                         case 'b':
6450                                 use_xdbe = 1;
6451                                 break;
6452 #endif
6453 #endif /* X11 */
6454                         case 't':
6455                                 if (global_text) {
6456                                         free(global_text);
6457                                         global_text = 0;
6458                                 }
6459                                 global_text = strndup(optarg, max_user_text);
6460                                 convert_escapes(global_text);
6461                                 break;
6462
6463                         case 'u':
6464                                 update_interval = strtod(optarg, 0);
6465                                 update_interval_old = update_interval;
6466                                 if (info.music_player_interval == 0) {
6467                                         // default to update_interval
6468                                         info.music_player_interval = update_interval;
6469                                 }
6470                                 break;
6471
6472                         case 'i':
6473                                 total_run_times = strtod(optarg, 0);
6474                                 break;
6475 #ifdef X11
6476                         case 'x':
6477                                 gap_x = atoi(optarg);
6478                                 break;
6479
6480                         case 'y':
6481                                 gap_y = atoi(optarg);
6482                                 break;
6483 #endif /* X11 */
6484
6485                         case '?':
6486                                 exit(EXIT_FAILURE);
6487                 }
6488         }
6489
6490 #ifdef X11
6491         /* load font */
6492         if (output_methods & TO_X) {
6493                 load_config_file_x11(current_config);
6494         }
6495 #endif /* X11 */
6496
6497         /* generate text and get initial size */
6498         extract_variable_text(global_text);
6499         if (global_text) {
6500                 free(global_text);
6501                 global_text = 0;
6502         }
6503         global_text = NULL;
6504         /* fork */
6505         if (fork_to_background) {
6506                 int pid = fork();
6507
6508                 switch (pid) {
6509                         case -1:
6510                                 NORM_ERR(PACKAGE_NAME": couldn't fork() to background: %s",
6511                                         strerror(errno));
6512                                 break;
6513
6514                         case 0:
6515                                 /* child process */
6516                                 usleep(25000);
6517                                 fprintf(stderr, "\n");
6518                                 fflush(stderr);
6519                                 break;
6520
6521                         default:
6522                                 /* parent process */
6523                                 fprintf(stderr, PACKAGE_NAME": forked to background, pid is %d\n",
6524                                         pid);
6525                                 fflush(stderr);
6526                                 exit(EXIT_SUCCESS);
6527                 }
6528         }
6529
6530         text_buffer = malloc(max_user_text);
6531         memset(text_buffer, 0, max_user_text);
6532         tmpstring1 = malloc(text_buffer_size);
6533         memset(tmpstring1, 0, text_buffer_size);
6534         tmpstring2 = malloc(text_buffer_size);
6535         memset(tmpstring2, 0, text_buffer_size);
6536
6537 #ifdef X11
6538         xargc = argc;
6539         xargv = argv;
6540         X11_create_window();
6541 #endif /* X11 */
6542 #ifdef HAVE_LUA
6543         llua_setup_info(&info, update_interval);
6544 #endif /* HAVE_LUA */
6545 #ifdef XOAP
6546         xmlInitParser();
6547 #endif /* XOAP */
6548
6549         /* Set signal handlers */
6550         act.sa_handler = signal_handler;
6551         sigemptyset(&act.sa_mask);
6552         act.sa_flags = 0;
6553 #ifdef SA_RESTART
6554         act.sa_flags |= SA_RESTART;
6555 #endif
6556
6557         if (            sigaction(SIGINT,  &act, &oact) < 0
6558                         ||      sigaction(SIGALRM, &act, &oact) < 0
6559                         ||      sigaction(SIGUSR1, &act, &oact) < 0
6560                         ||      sigaction(SIGHUP,  &act, &oact) < 0
6561                         ||      sigaction(SIGTERM, &act, &oact) < 0) {
6562                 NORM_ERR("error setting signal handler: %s", strerror(errno));
6563         }
6564
6565 #ifdef HAVE_LUA
6566         llua_startup_hook();
6567 #endif /* HAVE_LUA */
6568 }
6569
6570 int main(int argc, char **argv)
6571 {
6572 #ifdef X11
6573         char *s, *temp;
6574         unsigned int x;
6575 #endif
6576
6577         argc_copy = argc;
6578         argv_copy = argv;
6579         g_signal_pending = 0;
6580         max_user_text = MAX_USER_TEXT_DEFAULT;
6581         current_config = 0;
6582         memset(&info, 0, sizeof(info));
6583         free_templates();
6584         clear_net_stats();
6585
6586 #ifdef TCP_PORT_MONITOR
6587         /* set default connection limit */
6588         tcp_portmon_set_max_connections(0);
6589 #endif
6590
6591         /* handle command line parameters that don't change configs */
6592 #ifdef X11
6593         if (((s = getenv("LC_ALL")) && *s) || ((s = getenv("LC_CTYPE")) && *s)
6594                         || ((s = getenv("LANG")) && *s)) {
6595                 temp = (char *) malloc((strlen(s) + 1) * sizeof(char));
6596                 if (temp == NULL) {
6597                         NORM_ERR("malloc failed");
6598                 }
6599                 for (x = 0; x < strlen(s); x++) {
6600                         temp[x] = tolower(s[x]);
6601                 }
6602                 temp[x] = 0;
6603                 if (strstr(temp, "utf-8") || strstr(temp, "utf8")) {
6604                         utf8_mode = 1;
6605                 }
6606
6607                 free(temp);
6608         }
6609         if (!setlocale(LC_CTYPE, "")) {
6610                 NORM_ERR("Can't set the specified locale!\nCheck LANG, LC_CTYPE, LC_ALL.");
6611         }
6612 #endif /* X11 */
6613         while (1) {
6614                 int c = getopt_long(argc, argv, getopt_string, longopts, NULL);
6615
6616                 if (c == -1) {
6617                         break;
6618                 }
6619
6620                 switch (c) {
6621                         case 'v':
6622                         case 'V':
6623                                 print_version();
6624                         case 'c':
6625                                 if (current_config) {
6626                                         free(current_config);
6627                                 }
6628                                 current_config = strndup(optarg, max_user_text);
6629                                 break;
6630                         case 'q':
6631                                 freopen("/dev/null", "w", stderr);
6632                                 break;
6633                         case 'h':
6634                                 print_help(argv[0]);
6635                                 return 0;
6636 #ifdef CONFIG_OUTPUT
6637                         case 'C':
6638                                 print_defconfig();
6639                                 return 0;
6640 #endif
6641 #ifdef X11
6642                         case 'w':
6643                                 window.window = strtol(optarg, 0, 0);
6644                                 break;
6645                         case 'X':
6646                                 if (disp)
6647                                         free(disp);
6648                                 disp = strdup(optarg);
6649                                 break;
6650 #endif /* X11 */
6651
6652                         case '?':
6653                                 exit(EXIT_FAILURE);
6654                 }
6655         }
6656
6657         /* check if specified config file is valid */
6658         if (current_config) {
6659                 struct stat sb;
6660                 if (stat(current_config, &sb) ||
6661                                 (!S_ISREG(sb.st_mode) && !S_ISLNK(sb.st_mode))) {
6662                         NORM_ERR("invalid configuration file '%s'\n", current_config);
6663                         free(current_config);
6664                         current_config = 0;
6665                 }
6666         }
6667
6668         /* load current_config, CONFIG_FILE or SYSTEM_CONFIG_FILE */
6669
6670         if (!current_config) {
6671                 /* load default config file */
6672                 char buf[DEFAULT_TEXT_BUFFER_SIZE];
6673                 FILE *fp;
6674
6675                 /* Try to use personal config file first */
6676                 to_real_path(buf, CONFIG_FILE);
6677                 if (buf[0] && (fp = fopen(buf, "r"))) {
6678                         current_config = strndup(buf, max_user_text);
6679                         fclose(fp);
6680                 }
6681
6682                 /* Try to use system config file if personal config not readable */
6683                 if (!current_config && (fp = fopen(SYSTEM_CONFIG_FILE, "r"))) {
6684                         current_config = strndup(SYSTEM_CONFIG_FILE, max_user_text);
6685                         fclose(fp);
6686                 }
6687
6688                 /* No readable config found */
6689                 if (!current_config) {
6690 #ifdef CONFIG_OUTPUT
6691                         current_config = strdup("==builtin==");
6692                         NORM_ERR("no readable personal or system-wide config file found,"
6693                                         " using builtin default");
6694 #else
6695                         CRIT_ERR(NULL, NULL, "no readable personal or system-wide config file found");
6696 #endif /* ! CONF_OUTPUT */
6697                 }
6698         }
6699
6700 #ifdef XOAP
6701         /* Load xoap keys, if existing */
6702         load_xoap_keys();
6703 #endif /* XOAP */
6704
6705 #ifdef HAVE_SYS_INOTIFY_H
6706         inotify_fd = inotify_init();
6707 #endif /* HAVE_SYS_INOTIFY_H */
6708
6709         initialisation(argc, argv);
6710
6711         main_loop();
6712
6713 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
6714         kvm_close(kd);
6715 #endif
6716
6717         return 0;
6718
6719 }
6720
6721 void alarm_handler(void) {
6722         if(childpid > 0) {
6723                 kill(childpid, SIGTERM);
6724         }
6725 }
6726
6727 static void signal_handler(int sig)
6728 {
6729         /* signal handler is light as a feather, as it should be.
6730          * we will poll g_signal_pending with each loop of conky
6731          * and do any signal processing there, NOT here (except 
6732          * SIGALRM because this is caused when conky is hanging) */
6733         if(sig == SIGALRM) {
6734                 alarm_handler();
6735         } else {
6736                 g_signal_pending = sig;
6737         }
6738 }