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