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