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