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