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