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