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