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