summaryrefslogtreecommitdiff
path: root/src/globals.c
blob: 5f4350dd1394b5c397213ea08cd33376834afb6d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
/* Copyright (C) 2000, 2001, 2002, 2003, 2004 Shawn Betts <sabetts@vcn.bc.ca>
 *
 * This file is part of ratpoison.
 *
 * ratpoison is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * ratpoison is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this software; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307 USA
 */

#include "ratpoison.h"

#include <sys/types.h>
#include <sys/wait.h>

#include <ctype.h>
#include <errno.h>
#if defined (HAVE_PWD_H) && defined (HAVE_GETPWUID)
# include <pwd.h>
#endif
#include <signal.h>
#include <unistd.h>

/* Several systems seem not to have WAIT_ANY defined, so define it if
   it isn't. */
#ifndef WAIT_ANY
# define WAIT_ANY -1
#endif

/* Some systems don't define the close-on-exec flag in fcntl.h */
#ifndef FD_CLOEXEC
# define FD_CLOEXEC 1
#endif

int alarm_signalled = 0;
int kill_signalled = 0;
int hup_signalled = 0;
int chld_signalled = 0;
int rat_x;
int rat_y;
int rat_visible = 1;            /* rat is visible by default */

char *rp_exec_newwm = NULL;

int rp_font_ascent, rp_font_descent, rp_font_width;

Atom wm_name;
Atom wm_state;
Atom wm_change_state;
Atom wm_protocols;
Atom wm_delete;
Atom wm_take_focus;
Atom wm_colormaps;

Atom rp_command;
Atom rp_command_request;
Atom rp_command_result;
Atom rp_selection;

/* TEXT atoms */
Atom xa_string;
Atom xa_compound_text;
Atom xa_utf8_string;

/* netwm atoms */
Atom _net_wm_pid;
Atom _net_supported;
Atom _net_wm_window_type;
Atom _net_wm_window_type_dialog;
Atom _net_wm_name;

LIST_HEAD (rp_screens);
rp_screen *rp_current_screen;
rp_global_screen rp_glob_screen;

Display *dpy;

int rp_have_xrandr;

rp_group *rp_current_group;
LIST_HEAD (rp_groups);
LIST_HEAD (rp_children);
struct rp_defaults defaults;

int ignore_badwindow = 0;

char **myargv;

struct rp_key prefix_key;

struct modifier_info rp_modifier_info;

/* rudeness levels */
int rp_honour_transient_raise = 1;
int rp_honour_normal_raise = 1;
int rp_honour_transient_map = 1;
int rp_honour_normal_map = 1;

char *rp_error_msg = NULL;

/* Global frame numset */
struct numset *rp_frame_numset;

/* The X11 selection globals */
rp_xselection selection;

static void
x_export_selection (void)
{
  rp_screen *screen;

  list_first(screen, &rp_screens, node);
  if (!screen)
    return;

  /* Hang the selections off screen 0's key window. */
  XSetSelectionOwner (dpy, XA_PRIMARY, screen->key_window, CurrentTime);
  if (XGetSelectionOwner (dpy, XA_PRIMARY) != screen->key_window)
    PRINT_ERROR(("can't get primary selection"));
  XChangeProperty(dpy, screen->root, XA_CUT_BUFFER0, xa_string, 8,
                  PropModeReplace, (unsigned char*)selection.text, selection.len);
}

void
set_nselection (char *txt, int len)
{
  int i;

  /* Update the selection structure */
  free (selection.text);

  /* Copy the string by hand. */
  selection.text = xmalloc (len + 1);
  selection.len = len + 1;
  for (i=0; i<len; i++)
    selection.text[i] = txt[i];
  selection.text[len] = 0;

  x_export_selection();
}

void
set_selection (char *txt)
{
  /* Update the selection structure */
  free (selection.text);
  selection.text = xstrdup (txt);
  selection.len = strlen (txt);

  x_export_selection();
}

static char *
get_cut_buffer (void)
{
  int nbytes;
  char *data;

  PRINT_DEBUG (("trying the cut buffer\n"));

  data = XFetchBytes (dpy, &nbytes);

  if (data)
    {
      struct sbuf *s = sbuf_new (0);
      sbuf_nconcat (s, data, nbytes);
      XFree (data);
      return sbuf_free_struct (s);
    }
  else
    return NULL;
}

/* Lifted the code from rxvt. */
static char *
get_primary_selection(void)
{
  long            nread;
  unsigned long   bytes_after;
  XTextProperty   ct;
  struct sbuf *s = sbuf_new(0);

  for (nread = 0, bytes_after = 1; bytes_after > 0; nread += ct.nitems) {
    if ((XGetWindowProperty (dpy, rp_current_screen->input_window, rp_selection, (nread / 4), 4096,
                             True, AnyPropertyType, &ct.encoding,
                             &ct.format, &ct.nitems, &bytes_after,
                             &ct.value) != Success)) {
      XFree(ct.value);
      sbuf_free(s);
      return NULL;
    }
    if (ct.value == NULL)
      continue;
    /* Accumulate the data. FIXME: ct.value may not be NULL
       terminated. */
    sbuf_nconcat (s, (const char*)ct.value, ct.nitems);
    XFree(ct.value);
  }
  return sbuf_free_struct (s);
}

char *
get_selection (void)
{
  Atom property;
  XEvent ev;
  rp_screen *s = rp_current_screen;
  int loops = 1000;

  /* Just insert our text, if we own the selection. */
  if (selection.text)
    {
      return xstrdup (selection.text);
    }
  else
    {
      /* be a good icccm citizen */
      XDeleteProperty (dpy, s->input_window, rp_selection);
      /* TODO: we shouldn't use CurrentTime here, use the time of the XKeyEvent, should we fake it? */
      XConvertSelection (dpy, XA_PRIMARY, xa_string, rp_selection, s->input_window, CurrentTime);

      /* This seems like a hack. */
      while (!XCheckTypedWindowEvent (dpy, s->input_window, SelectionNotify, &ev))
        {
          if (loops == 0)
            {
              PRINT_ERROR (("selection request timed out\n"));
              return NULL;
            }
          usleep (10000);
          loops--;
        }

      PRINT_DEBUG (("SelectionNotify event\n"));

      property = ev.xselection.property;

      if (property != None)
        return get_primary_selection ();
      else
        return get_cut_buffer ();
    }
}

/* The hook dictionary globals. */

LIST_HEAD (rp_key_hook);
LIST_HEAD (rp_switch_win_hook);
LIST_HEAD (rp_switch_frame_hook);
LIST_HEAD (rp_switch_group_hook);
LIST_HEAD (rp_switch_screen_hook);
LIST_HEAD (rp_quit_hook);
LIST_HEAD (rp_restart_hook);
LIST_HEAD (rp_delete_window_hook);
LIST_HEAD (rp_new_window_hook);
LIST_HEAD (rp_title_changed_hook);

struct rp_hook_db_entry rp_hook_db[]=
  {{"key",              &rp_key_hook},
   {"switchwin",        &rp_switch_win_hook},
   {"switchframe",      &rp_switch_frame_hook},
   {"switchgroup",      &rp_switch_group_hook},
   {"switchscreen",      &rp_switch_screen_hook},
   {"deletewindow",     &rp_delete_window_hook},
   {"quit",             &rp_quit_hook},
   {"restart",          &rp_restart_hook},
   {"newwindow",	&rp_new_window_hook},
   {"titlechanged",	&rp_title_changed_hook},
   {NULL, NULL}};

void
set_rp_window_focus (rp_window *win)
{
  PRINT_DEBUG (("Giving focus to '%s'\n", window_name (win)));
  XSetInputFocus (dpy, win->w,
                  RevertToPointerRoot, CurrentTime);
}

void
set_window_focus (Window window)
{
  PRINT_DEBUG (("Giving focus to %ld\n", window));
  XSetInputFocus (dpy, window,
                  RevertToPointerRoot, CurrentTime);
}


/* Wrapper font functions to support Xft */

void
rp_draw_string (rp_screen *s, Drawable d, int style, int x, int y,
		char *string, int length)
{
  if (length < 0)
    length = strlen (string);

#ifdef USE_XFT_FONT
  if (s->xft_font)
    {
      XftDraw *draw;
      draw = XftDrawCreate (dpy, d, DefaultVisual (dpy, s->screen_num),
                            DefaultColormap (dpy, s->screen_num));
      if (!draw)
	{
	  PRINT_ERROR (("Failed to allocate XftDraw object\n"));
	  return;
	}

      if (utf8_locale)
	{
	  XftDrawStringUtf8 (draw, style == STYLE_NORMAL ? &s->xft_fg_color :
			     &s->xft_bg_color, s->xft_font, x, y,
			     (FcChar8*) string, length);
	}
      else
	{
	  XftDrawString8 (draw, style == STYLE_NORMAL ? &s->xft_fg_color :
			  &s->xft_bg_color, s->xft_font, x, y,
			  (FcChar8*) string, length);
     	}
      XftDrawDestroy (draw);
    }
  else
    PRINT_ERROR (("No Xft font available.\n"));
#else
  XmbDrawString (dpy, d, defaults.font, style == STYLE_NORMAL ? s->normal_gc :
		 s->inverse_gc, x, y, string, length);
#endif
}

int
rp_text_width (rp_screen *s, char *string, int count)
{
  (void) s; /* avoid "unused" warning */
  if (count < 0)
    count = strlen (string);

#ifdef USE_XFT_FONT
  if (s->xft_font)
    {
      XGlyphInfo extents;
      if (utf8_locale)
        XftTextExtentsUtf8 (dpy, s->xft_font, (FcChar8*) string, count, &extents);
      else
        XftTextExtents8 (dpy, s->xft_font, (FcChar8*) string, count, &extents);
      return extents.xOff;
    }
  PRINT_ERROR (("No Xft font available.\n"));
  return 0;
#else
  return XmbTextEscapement (defaults.font, string, count);
#endif
}

void
fatal (const char *msg)
{
  fprintf (stderr, "ratpoison: %s", msg);
  abort ();
}

void *
xmalloc (size_t size)
{
  void *value;

  value = malloc (size);
  if (value == NULL)
    fatal ("Virtual memory exhausted");
  return value;
}

void *
xrealloc (void *ptr, size_t size)
{
  void *value;

  value = realloc (ptr, size);
  if (value == NULL)
    fatal ("Virtual memory exhausted");
  return value;
}

char *
xstrdup (const char *s)
{
  char *value;
  value = strdup (s);
  if (value == NULL)
    fatal ("Virtual memory exhausted");
  return value;
}

/* Return a new string based on fmt. */
char *
xvsprintf (char *fmt, va_list ap)
{
  int size, nchars;
  char *buffer;
  va_list ap_copy;

  /* A reasonable starting value. */
  size = strlen (fmt) + 1;
  buffer = xmalloc (size);

  while (1)
    {
#if defined(va_copy)
      va_copy (ap_copy, ap);
#elif defined(__va_copy)
      __va_copy (ap_copy, ap);
#else
      /* If there is no copy macro then this MAY work. On some systems
         this could fail because va_list is a pointer so assigning one
         to the other as below wouldn't make a copy of the data, but
         just the pointer to the data. */
      ap_copy = ap;
#endif
      nchars = vsnprintf (buffer, size, fmt, ap_copy);
#if defined(va_copy) || defined(__va_copy)
      va_end (ap_copy);
#endif

      if (nchars > -1 && nchars < size)
        return buffer;
      else if (nchars > -1)
        size = nchars + 1;
      /* c99 says -1 is an error other than truncation,
       * which thus will not go away with a larger buffer.
       * To support older system but not making errors fatal
       * (ratpoison will abort when trying to get too much memory otherwise),
       * try to increase a bit but not too much: */
      else if (size < MAX_LEGACY_SNPRINTF_SIZE)
        size *= 2;
      else
	{
	  free(buffer);
	  break;
	}

      /* Resize the buffer and try again. */
      buffer = xrealloc (buffer, size);
    }

  return xstrdup("<FAILURE>");
}

/* Return a new string based on fmt. */
char *
xsprintf (char *fmt, ...)
{
  char *buffer;
  va_list ap;

  va_start (ap, fmt);
  buffer = xvsprintf (fmt, ap);
  va_end (ap);

  return buffer;
}

/* strtok but do it for whitespace and be locale compliant. */
char *
strtok_ws (char *s)
{
  char *nonws;
  static char *last = NULL;

  if (s != NULL)
    last = s;
  else if (last == NULL)
    {
      PRINT_ERROR (("strtok_ws() called but not initalized, this is a *BUG*\n"));
      abort();
    }

  /* skip to first non-whitespace char. */
  while (*last && isspace ((unsigned char)*last))
    last++;

  /* If we reached the end of the string here then there is no more
     data. */
  if (*last == '\0')
    return NULL;

  /* Now skip to the end of the data. */
  nonws = last;
  while (*last && !isspace ((unsigned char)*last))
    last++;
  if (*last)
    {
      *last = '\0';
      last++;
    }
  return nonws;
}

/* A case insensitive strncmp. */
int
str_comp (char *s1, char *s2, size_t len)
{
  size_t i;

  for (i = 0; i < len; i++)
    if (toupper ((unsigned char)s1[i]) != toupper ((unsigned char)s2[i]))
      return 0;

  return 1;
}

/* Check for child processes that have quit but haven't been
   acknowledged yet. Update their structure. */
void
check_child_procs (void)
{
  rp_child_info *cur;
  int pid, status;
  while (1)
    {
      pid = waitpid (WAIT_ANY, &status, WNOHANG);
      if (pid <= 0)
        break;

      PRINT_DEBUG(("Child status: %d\n", WEXITSTATUS (status)));

      /* Find the child and update its structure. */
      list_for_each_entry (cur, &rp_children, node)
        {
          if (cur->pid == pid)
            {
              cur->terminated = 1;
              cur->status = WEXITSTATUS (status);
              break;
            }
        }

      chld_signalled = 1;
    }
}

void
chld_handler (int signum UNUSED)
{
  int serrno;

  serrno = errno;
  check_child_procs();
  errno = serrno;
}

void
set_sig_handler (int sig, void (*action)(int))
{
  struct sigaction act;

  memset (&act, 0, sizeof (act));
  act.sa_handler = action;
  sigemptyset (&act.sa_mask);
  if (sigaction (sig, &act, NULL))
    {
      PRINT_ERROR (("Error setting signal handler: %s\n",
                    strerror (errno)));
    }
}

void
set_close_on_exec (int fd)
{
  int flags = fcntl (fd, F_GETFD);
  if (flags >= 0)
    fcntl (fd, F_SETFD, flags | FD_CLOEXEC);
}

void
read_rc_file (FILE *file)
{
  char *line;
  size_t linesize = 256;

  line = xmalloc (linesize);

  while (getline (&line, &linesize, file) != -1)
    {
      line[strcspn (line, "\n")] = '\0';

      PRINT_DEBUG (("rcfile line: %s\n", line));

      if (*line != '\0' && *line != '#')
        {
          cmdret *result;
          result = command (0, line);

          /* Gobble the result. */
          if (result)
            cmdret_free (result);
        }
    }

  free (line);
}

const char *
get_homedir (void)
{
  char *homedir;

  homedir = getenv ("HOME");
  if (homedir != NULL && homedir[0] == '\0')
    homedir = NULL;

#if defined (HAVE_PWD_H) && defined (HAVE_GETPWUID)
  if (homedir == NULL)
    {
      struct passwd *pw;

      pw = getpwuid (getuid ());
      if (pw != NULL)
        homedir = pw->pw_dir;

      if (homedir != NULL && homedir[0] == '\0')
        homedir = NULL;
    }
#endif

  return homedir;
}

void
clean_up (void)
{
  rp_screen *cur;
  struct list_head *iter, *tmp;

  history_save ();

  free_keymaps ();
  free_aliases ();
  free_user_commands ();
  free_bar ();
  free_window_stuff ();
  free_groups ();

  list_for_each_safe_entry (cur, iter, tmp, &rp_screens, node)
    {
      list_del (&cur->node);
      screen_free (cur);
      free (cur);
    }

  screen_free_final ();

  /* Delete the undo histories */
  clear_frame_undos ();

  /* Free the global frame numset shared by all screens. */
  numset_free (rp_frame_numset);

#ifndef USE_XFT_FONT
  XFreeFontSet (dpy, defaults.font);
#endif
  free (defaults.window_fmt);

  XSetInputFocus (dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
  XCloseDisplay (dpy);
}