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