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