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