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