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