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