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