source: util.c @ 4ebbfbc

release-1.10release-1.9
Last change on this file since 4ebbfbc was 4ebbfbc, checked in by Jason Gross <jgross@mit.edu>, 13 years ago
Show the time zone in :info; replace ctime with strftime This fixes trac-#146. The new function owl_util_time_to_timestr takes a const struct tm * instead of a const time_t because, although we pass around time_t for just about everything else, this lets the caller decide whether to use localtime or gmtime (UTC). Note: I'm not sure that "%c" (which is locale-dependent) will always include the time zone. If not, or if we want a bit more consistency, we can switch to something like "%a %b %d %H:%M:%S %Y %Z" (like "Fri Jul 22 15:39:45 2011 EDT") or "%a %b %d, %Y %h:%M:%S %p %Z" (like "Fri Jul 22, 2011 03:39:45 PM 2011 EDT") or something. On linerva, "%c" seems to be equivalent to "%a %d %b %Y %h:%M:%S %p %Z" (like "Fri 22 Jul 2011 03:39:45 PM EDT").
  • Property mode set to 100644
File size: 21.7 KB
Line 
1#include "owl.h"
2#include <stdlib.h>
3#include <string.h>
4#include <unistd.h>
5#include <ctype.h>
6#include <pwd.h>
7#include <sys/stat.h>
8#include <sys/types.h>
9#include <assert.h>
10#include <stdarg.h>
11#include <glib.h>
12#include <glib/gstdio.h>
13#include <glib-object.h>
14
15const char *skiptokens(const char *buff, int n) {
16  /* skips n tokens and returns where that would be. */
17  char quote = 0;
18  while (*buff && n>0) {
19      while (*buff == ' ') buff++;
20      while (*buff && (quote || *buff != ' ')) {
21        if(quote) {
22          if(*buff == quote) quote = 0;
23        } else if(*buff == '"' || *buff == '\'') {
24          quote = *buff;
25        }
26        buff++;
27      }
28      while (*buff == ' ') buff++;
29      n--;
30  }
31  return buff;
32}
33
34CALLER_OWN char *owl_util_homedir_for_user(const char *name)
35{
36  int err;
37  struct passwd pw_buf;
38  struct passwd *pw;
39
40  char *pw_strbuf, *ret;
41  long pw_strbuf_len = sysconf(_SC_GETPW_R_SIZE_MAX);
42  if (pw_strbuf_len < 0) {
43    /* If we really hate ourselves, we can be fancy and loop until we stop
44     * getting ERANGE. For now just pick a random number. */
45    owl_function_error("owl_util_homedir_for_user: Could not get _SC_GETPW_R_SIZE_MAX");
46    pw_strbuf_len = 16384;
47  }
48  pw_strbuf = g_new0(char, pw_strbuf_len);
49  err = getpwnam_r(name, &pw_buf, pw_strbuf, pw_strbuf_len, &pw);
50  if (err) {
51    owl_function_error("getpwuid_r: %s", strerror(err));
52    /* Fall through; pw will be NULL. */
53  }
54  ret = pw ? g_strdup(pw->pw_dir) : NULL;
55  g_free(pw_strbuf);
56  return ret;
57}
58
59/* Return a "nice" version of the path.  Tilde expansion is done, and
60 * duplicate slashes are removed.  Caller must free the return.
61 */
62CALLER_OWN char *owl_util_makepath(const char *in)
63{
64  char *out;
65  int i, j;
66  if (in[0] == '~') {
67    /* Attempt tilde-expansion of the first component. Get the
68       tilde-prefix, which goes up to the next slash. */
69    const char *end = strchr(in + 1, '/');
70    if (end == NULL)
71      end = in + strlen(in);
72
73    /* Patch together a new path. Replace the ~ and tilde-prefix with
74       the homedir, if available. */
75    if (end == in + 1) {
76      /* My home directory. Use the one in owl_global for consistency with
77       * owl_zephyr_dotfile. */
78      out = g_strconcat(owl_global_get_homedir(&g), end, NULL);
79    } else {
80      /* Someone else's home directory. */
81      char *user = g_strndup(in + 1, end - (in + 1));
82      char *home = owl_util_homedir_for_user(user);
83      if (home) {
84        out = g_strconcat(home, end, NULL);
85      } else {
86        out = g_strdup(in);
87      }
88      g_free(home);
89      g_free(user);
90    }
91  } else {
92    out = g_strdup(in);
93  }
94
95  /* And a quick pass to remove duplicate slashes. */
96  for (i = j = 0; out[i] != '\0'; i++) {
97    if (out[i] != '/' || i == 0 || out[i-1] != '/')
98      out[j++] = out[i];
99  }
100  out[j] = '\0';
101  return out;
102}
103
104void owl_ptr_array_free(GPtrArray *array, GDestroyNotify element_free_func)
105{
106  /* TODO: when we move to requiring glib 2.22+, use
107   * g_ptr_array_new_with_free_func instead. */
108  if (element_free_func)
109    g_ptr_array_foreach(array, (GFunc)element_free_func, NULL);
110  g_ptr_array_free(array, true);
111}
112
113/* Break a command line up into argv, argc.  The caller must free
114   the returned values with g_strfreev.  If there is an error argc will be set
115   to -1, argv will be NULL and the caller does not need to free anything. The
116   returned vector is NULL-terminated. */
117CALLER_OWN char **owl_parseline(const char *line, int *argc)
118{
119  GPtrArray *argv;
120  int i, len, between=1;
121  GString *curarg;
122  char quote;
123
124  argv = g_ptr_array_new();
125  len=strlen(line);
126  curarg = g_string_new("");
127  quote='\0';
128  if (argc) *argc=0;
129  for (i=0; i<len+1; i++) {
130    /* find the first real character */
131    if (between) {
132      if (line[i]==' ' || line[i]=='\t' || line[i]=='\0') {
133        continue;
134      } else {
135        between=0;
136        i--;
137        continue;
138      }
139    }
140
141    /* deal with a quote character */
142    if (line[i]=='"' || line[i]=="'"[0]) {
143      /* if this type of quote is open, close it */
144      if (quote==line[i]) {
145        quote='\0';
146        continue;
147      }
148
149      /* if no quoting is open then open with this */
150      if (quote=='\0') {
151        quote=line[i];
152        continue;
153      }
154
155      /* if another type of quote is open then treat this as a literal */
156      g_string_append_c(curarg, line[i]);
157      continue;
158    }
159
160    /* if it's not a space or end of command, then use it */
161    if (line[i]!=' ' && line[i]!='\t' && line[i]!='\n' && line[i]!='\0') {
162      g_string_append_c(curarg, line[i]);
163      continue;
164    }
165
166    /* otherwise, if we're not in quotes, add the whole argument */
167    if (quote=='\0') {
168      /* add the argument */
169      g_ptr_array_add(argv, g_string_free(curarg, false));
170      curarg = g_string_new("");
171      between=1;
172      continue;
173    }
174
175    /* if it is a space and we're in quotes, then use it */
176    g_string_append_c(curarg, line[i]);
177  }
178
179  if (argc) *argc = argv->len;
180  g_ptr_array_add(argv, NULL);
181  g_string_free(curarg, true);
182
183  /* check for unbalanced quotes */
184  if (quote!='\0') {
185    owl_ptr_array_free(argv, g_free);
186    if (argc) *argc = -1;
187    return(NULL);
188  }
189
190  return (char**)g_ptr_array_free(argv, false);
191}
192
193/* Appends a quoted version of arg suitable for placing in a
194 * command-line to a GString. Does not append a space. */
195void owl_string_append_quoted_arg(GString *buf, const char *arg)
196{
197  const char *argp;
198  if (arg[0] == '\0') {
199    /* Quote the empty string. */
200    g_string_append(buf, "''");
201  } else if (arg[strcspn(arg, "'\" \n\t")] == '\0') {
202    /* If there are no nasty characters, return as-is. */
203    g_string_append(buf, arg);
204  } else if (!strchr(arg, '\'')) {
205    /* Single-quote if possible. */
206    g_string_append_c(buf, '\'');
207    g_string_append(buf, arg);
208    g_string_append_c(buf, '\'');
209  } else {
210    /* Nasty case: double-quote, but change all internal "s to "'"'"
211     * so that they are single-quoted because we're too cool for
212     * backslashes.
213     */
214    g_string_append_c(buf, '"');
215    for (argp = arg; *argp; argp++) {
216      if (*argp == '"')
217        g_string_append(buf, "\"'\"'\"");
218      else
219        g_string_append_c(buf, *argp);
220    }
221    g_string_append_c(buf, '"');
222  }
223}
224
225/*
226 * Appends 'tmpl' to 'buf', replacing any instances of '%q' with arguments from
227 * the varargs provided, quoting them to be safe for placing in a BarnOwl
228 * command line.
229 */
230void owl_string_appendf_quoted(GString *buf, const char *tmpl, ...)
231{
232  va_list ap;
233  va_start(ap, tmpl);
234  owl_string_vappendf_quoted(buf, tmpl, ap);
235  va_end(ap);
236}
237
238void owl_string_vappendf_quoted(GString *buf, const char *tmpl, va_list ap)
239{
240  const char *p = tmpl, *last = tmpl;
241  while (true) {
242    p = strchr(p, '%');
243    if (p == NULL) break;
244    if (*(p+1) != 'q') {
245      p++;
246      if (*p) p++;
247      continue;
248    }
249    g_string_append_len(buf, last, p - last);
250    owl_string_append_quoted_arg(buf, va_arg(ap, char *));
251    p += 2; last = p;
252  }
253
254  g_string_append(buf, last);
255}
256
257CALLER_OWN char *owl_string_build_quoted(const char *tmpl, ...)
258{
259  GString *buf = g_string_new("");
260  va_list ap;
261  va_start(ap, tmpl);
262  owl_string_vappendf_quoted(buf, tmpl, ap);
263  va_end(ap);
264  return g_string_free(buf, false); 
265}
266
267/* Returns a quoted version of arg suitable for placing in a
268 * command-line. Result should be freed with g_free. */
269CALLER_OWN char *owl_arg_quote(const char *arg)
270{
271  GString *buf = g_string_new("");;
272  owl_string_append_quoted_arg(buf, arg);
273  return g_string_free(buf, false);
274}
275
276/* caller must free the return */
277CALLER_OWN char *owl_util_minutes_to_timestr(int in)
278{
279  int days, hours;
280  long run;
281  char *out;
282
283  run=in;
284
285  days=run/1440;
286  run-=days*1440;
287  hours=run/60;
288  run-=hours*60;
289
290  if (days>0) {
291    out=g_strdup_printf("%i d %2.2i:%2.2li", days, hours, run);
292  } else {
293    out=g_strdup_printf("    %2.2i:%2.2li", hours, run);
294  }
295  return(out);
296}
297
298CALLER_OWN char *owl_util_time_to_timestr(const struct tm *time)
299{
300  /* 32 chosen for first attempt because timestr will end up being
301   * something like "Www Mmm dd hh:mm:ss AM yyyy UTC\0" */ 
302  size_t timestr_size = 16;
303  char *timestr = NULL;
304  do {
305    timestr_size *= 2;
306    timestr = g_renew(char, timestr, timestr_size);
307  } while (strftime(timestr, timestr_size, "%c", time) == 0);
308  return timestr;
309}
310
311/* These are in order of their value in owl.h */
312static const struct {
313  int number;
314  const char *name;
315} color_map[] = {
316  {OWL_COLOR_INVALID, "invalid"},
317  {OWL_COLOR_DEFAULT, "default"},
318  {OWL_COLOR_BLACK, "black"},
319  {OWL_COLOR_RED, "red"},
320  {OWL_COLOR_GREEN, "green"},
321  {OWL_COLOR_YELLOW,"yellow"},
322  {OWL_COLOR_BLUE, "blue"},
323  {OWL_COLOR_MAGENTA, "magenta"},
324  {OWL_COLOR_CYAN, "cyan"},
325  {OWL_COLOR_WHITE, "white"},
326};
327
328/* Return the owl color associated with the named color.  Return -1
329 * if the named color is not available
330 */
331int owl_util_string_to_color(const char *color)
332{
333  int c, i;
334  char *p;
335
336  for (i = 0; i < (sizeof(color_map)/sizeof(color_map[0])); i++)
337    if (strcasecmp(color, color_map[i].name) == 0)
338      return color_map[i].number;
339
340  c = strtol(color, &p, 10);
341  if (p != color && c >= -1 && c < COLORS) {
342    return(c);
343  }
344  return(OWL_COLOR_INVALID);
345}
346
347/* Return a string name of the given owl color */
348const char *owl_util_color_to_string(int color)
349{
350  if (color >= OWL_COLOR_INVALID && color <= OWL_COLOR_WHITE)
351    return color_map[color - OWL_COLOR_INVALID].name;
352  return("Unknown color");
353}
354
355/* Get the default tty name.  Caller must free the return */
356CALLER_OWN char *owl_util_get_default_tty(void)
357{
358  const char *tmp;
359  char *out;
360
361  if (getenv("DISPLAY")) {
362    out=g_strdup(getenv("DISPLAY"));
363  } else if ((tmp=ttyname(fileno(stdout)))!=NULL) {
364    out=g_strdup(tmp);
365    if (!strncmp(out, "/dev/", 5)) {
366      g_free(out);
367      out=g_strdup(tmp+5);
368    }
369  } else {
370    out=g_strdup("unknown");
371  }
372  return(out);
373}
374
375/* strip leading and trailing new lines.  Caller must free the
376 * return.
377 */
378CALLER_OWN char *owl_util_stripnewlines(const char *in)
379{
380 
381  char  *tmp, *ptr1, *ptr2, *out;
382
383  ptr1=tmp=g_strdup(in);
384  while (ptr1[0]=='\n') {
385    ptr1++;
386  }
387  ptr2=ptr1+strlen(ptr1)-1;
388  while (ptr2>ptr1 && ptr2[0]=='\n') {
389    ptr2[0]='\0';
390    ptr2--;
391  }
392
393  out=g_strdup(ptr1);
394  g_free(tmp);
395  return(out);
396}
397
398
399/* If filename is a link, recursively resolve symlinks.  Otherwise, return the filename
400 * unchanged.  On error, call owl_function_error and return NULL.
401 *
402 * This function assumes that filename eventually resolves to an acutal file.
403 * If you want to check this, you should stat() the file first.
404 *
405 * The caller of this function is responsible for freeing the return value.
406 *
407 * Error conditions are the same as g_file_read_link.
408 */
409CALLER_OWN gchar *owl_util_recursive_resolve_link(const char *filename)
410{
411  gchar *last_path = g_strdup(filename);
412  GError *err = NULL;
413
414  while (g_file_test(last_path, G_FILE_TEST_IS_SYMLINK)) {
415    gchar *link_path = g_file_read_link(last_path, &err);
416    if (link_path == NULL) {
417      owl_function_error("Cannot resolve symlink %s: %s",
418                         last_path, err->message);
419      g_error_free(err);
420      g_free(last_path);
421      return NULL;
422    }
423
424    /* Deal with obnoxious relative paths. If we really care, all this
425     * is racy. Whatever. */
426    if (!g_path_is_absolute(link_path)) {
427      char *last_dir = g_path_get_dirname(last_path);
428      char *tmp = g_build_filename(last_dir, link_path, NULL);
429      g_free(last_dir);
430      g_free(link_path);
431      link_path = tmp;
432    }
433
434    g_free(last_path);
435    last_path = link_path;
436  }
437  return last_path;
438}
439
440/* Delete all lines matching "line" from the named file.  If no such
441 * line is found the file is left intact.  If backup==1 then leave a
442 * backup file containing the original contents.  The match is
443 * case-insensitive.
444 *
445 * Returns the number of lines removed on success.  Returns -1 on failure.
446 */
447int owl_util_file_deleteline(const char *filename, const char *line, int backup)
448{
449  char *backupfile, *newfile, *buf = NULL;
450  gchar *actual_filename; /* gchar; we need to g_free it */
451  FILE *old, *new;
452  struct stat st;
453  int numremoved = 0;
454
455  if ((old = fopen(filename, "r")) == NULL) {
456    owl_function_error("Cannot open %s (for reading): %s",
457                       filename, strerror(errno));
458    return -1;
459  }
460
461  if (fstat(fileno(old), &st) != 0) {
462    owl_function_error("Cannot stat %s: %s", filename, strerror(errno));
463    return -1;
464  }
465
466  /* resolve symlinks, because link() fails on symlinks, at least on AFS */
467  actual_filename = owl_util_recursive_resolve_link(filename);
468  if (actual_filename == NULL)
469    return -1; /* resolving the symlink failed, but we already logged this error */
470
471  newfile = g_strdup_printf("%s.new", actual_filename);
472  if ((new = fopen(newfile, "w")) == NULL) {
473    owl_function_error("Cannot open %s (for writing): %s",
474                       actual_filename, strerror(errno));
475    g_free(newfile);
476    fclose(old);
477    g_free(actual_filename);
478    return -1;
479  }
480
481  if (fchmod(fileno(new), st.st_mode & 0777) != 0) {
482    owl_function_error("Cannot set permissions on %s: %s",
483                       actual_filename, strerror(errno));
484    unlink(newfile);
485    fclose(new);
486    g_free(newfile);
487    fclose(old);
488    g_free(actual_filename);
489    return -1;
490  }
491
492  while (owl_getline_chomp(&buf, old))
493    if (strcasecmp(buf, line) != 0)
494      fprintf(new, "%s\n", buf);
495    else
496      numremoved++;
497  g_free(buf);
498
499  fclose(new);
500  fclose(old);
501
502  if (backup) {
503    backupfile = g_strdup_printf("%s.backup", actual_filename);
504    unlink(backupfile);
505    if (link(actual_filename, backupfile) != 0) {
506      owl_function_error("Cannot link %s: %s", backupfile, strerror(errno));
507      g_free(backupfile);
508      unlink(newfile);
509      g_free(newfile);
510      return -1;
511    }
512    g_free(backupfile);
513  }
514
515  if (rename(newfile, actual_filename) != 0) {
516    owl_function_error("Cannot move %s to %s: %s",
517                       newfile, actual_filename, strerror(errno));
518    numremoved = -1;
519  }
520
521  unlink(newfile);
522  g_free(newfile);
523
524  g_free(actual_filename);
525
526  return numremoved;
527}
528
529/* Return the base class or instance from a zephyr class, by removing
530   leading `un' or trailing `.d'.
531   The caller is responsible for freeing the allocated string.
532*/
533CALLER_OWN char *owl_util_baseclass(const char *class)
534{
535  char *start, *end;
536
537  while(!strncmp(class, "un", 2)) {
538    class += 2;
539  }
540
541  start = g_strdup(class);
542  end = start + strlen(start) - 1;
543  while(end > start && *end == 'd' && *(end-1) == '.') {
544    end -= 2;
545  }
546  *(end + 1) = 0;
547
548  return start;
549}
550
551const char * owl_get_datadir(void)
552{
553  const char * datadir = getenv("BARNOWL_DATA_DIR");
554  if(datadir != NULL)
555    return datadir;
556  return DATADIR;
557}
558
559const char * owl_get_bindir(void)
560{
561  const char * bindir = getenv("BARNOWL_BIN_DIR");
562  if(bindir != NULL)
563    return bindir;
564  return BINDIR;
565}
566
567/* Strips format characters from a valid utf-8 string. Returns the
568   empty string if 'in' does not validate.  Caller must free the return. */
569CALLER_OWN char *owl_strip_format_chars(const char *in)
570{
571  char *r;
572  if (g_utf8_validate(in, -1, NULL)) {
573    const char *s, *p;
574    r = g_new(char, strlen(in)+1);
575    r[0] = '\0';
576    s = in;
577    p = strchr(s, OWL_FMTEXT_UC_STARTBYTE_UTF8);
578    while(p) {
579      /* If it's a format character, copy up to it, and skip all
580         immediately following format characters. */
581      if (owl_fmtext_is_format_char(g_utf8_get_char(p))) {
582        strncat(r, s, p-s);
583        p = g_utf8_next_char(p);
584        while (owl_fmtext_is_format_char(g_utf8_get_char(p))) {
585          p = g_utf8_next_char(p);
586        }
587        s = p;
588        p = strchr(s, OWL_FMTEXT_UC_STARTBYTE_UTF8);
589      }
590      else {
591        p = strchr(p+1, OWL_FMTEXT_UC_STARTBYTE_UTF8);
592      }
593    }
594    if (s) strcat(r,s);
595  }
596  else {
597    r = g_strdup("");
598  }
599  return r;
600}
601
602/* If in is not UTF-8, convert from ISO-8859-1. We may want to allow
603 * the caller to specify an alternative in the future. We also strip
604 * out characters in Unicode Plane 16, as we use that plane internally
605 * for formatting.
606 * Caller must free the return.
607 */
608CALLER_OWN char *owl_validate_or_convert(const char *in)
609{
610  if (g_utf8_validate(in, -1, NULL)) {
611    return owl_strip_format_chars(in);
612  }
613  else {
614    return g_convert(in, -1,
615                     "UTF-8", "ISO-8859-1",
616                     NULL, NULL, NULL);
617  }
618}
619/*
620 * Validate 'in' as UTF-8, and either return a copy of it, or an empty
621 * string if it is invalid utf-8.
622 * Caller must free the return.
623 */
624CALLER_OWN char *owl_validate_utf8(const char *in)
625{
626  char *out;
627  if (g_utf8_validate(in, -1, NULL)) {
628    out = g_strdup(in);
629  } else {
630    out = g_strdup("");
631  }
632  return out;
633}
634
635/* This is based on _extract() and _isCJ() from perl's Text::WrapI18N */
636int owl_util_can_break_after(gunichar c)
637{
638 
639  if (c == ' ') return 1;
640  if (c >= 0x3000 && c <= 0x312f) {
641    /* CJK punctuations, Hiragana, Katakana, Bopomofo */
642    if (c == 0x300a || c == 0x300c || c == 0x300e ||
643        c == 0x3010 || c == 0x3014 || c == 0x3016 ||
644        c == 0x3018 || c == 0x301a)
645      return 0;
646    return 1;
647  }
648  if (c >= 0x31a0 && c <= 0x31bf) {return 1;}  /* Bopomofo */
649  if (c >= 0x31f0 && c <= 0x31ff) {return 1;}  /* Katakana extension */
650  if (c >= 0x3400 && c <= 0x9fff) {return 1;}  /* Han Ideogram */
651  if (c >= 0xf900 && c <= 0xfaff) {return 1;}  /* Han Ideogram */
652  if (c >= 0x20000 && c <= 0x2ffff) {return 1;}  /* Han Ideogram */
653  return 0;
654}
655
656/* caller must free the return */
657CALLER_OWN char *owl_escape_highbit(const char *str)
658{
659  GString *out = g_string_new("");
660  unsigned char c;
661  while((c = (*str++))) {
662    if(c == '\\') {
663      g_string_append(out, "\\\\");
664    } else if(c & 0x80) {
665      g_string_append_printf(out, "\\x%02x", (int)c);
666    } else {
667      g_string_append_c(out, c);
668    }
669  }
670  return g_string_free(out, 0);
671}
672
673/* innards of owl_getline{,_chomp} below */
674static int owl_getline_internal(char **s, FILE *fp, int newline)
675{
676  int size = 0;
677  int target = 0;
678  int count = 0;
679  int c;
680
681  while (1) {
682    c = getc(fp);
683    if ((target + 1) > size) {
684      size += BUFSIZ;
685      *s = g_renew(char, *s, size);
686    }
687    if (c == EOF)
688      break;
689    count++;
690    if (c != '\n' || newline)
691        (*s)[target++] = c;
692    if (c == '\n')
693      break;
694  }
695  (*s)[target] = 0;
696
697  return count;
698}
699
700/* Read a line from fp, allocating memory to hold it, returning the number of
701 * byte read.  *s should either be NULL or a pointer to memory allocated with
702 * g_malloc; it will be g_renew'd as appropriate.  The caller must
703 * eventually free it.  (This is roughly the interface of getline in the gnu
704 * libc).
705 *
706 * The final newline will be included if it's there.
707 */
708int owl_getline(char **s, FILE *fp)
709{
710  return owl_getline_internal(s, fp, 1);
711}
712
713/* As above, but omitting the final newline */
714int owl_getline_chomp(char **s, FILE *fp)
715{
716  return owl_getline_internal(s, fp, 0);
717}
718
719/* Read the rest of the input available in fp into a string. */
720CALLER_OWN char *owl_slurp(FILE *fp)
721{
722  char *buf = NULL;
723  char *p;
724  int size = 0;
725  int count;
726
727  while (1) {
728    buf = g_renew(char, buf, size + BUFSIZ);
729    p = &buf[size];
730    size += BUFSIZ;
731
732    if ((count = fread(p, 1, BUFSIZ, fp)) < BUFSIZ)
733      break;
734  }
735  p[count] = 0;
736
737  return buf;
738}
739
740int owl_util_get_colorpairs(void) {
741#ifndef NCURSES_EXT_COLORS
742  /* Without ext-color support (an ABI change), ncurses only supports 256
743   * different color pairs. However, it gives us a larger number even if your
744   * ncurses is compiled without ext-color. */
745  return MIN(COLOR_PAIRS, 256);
746#else
747  return COLOR_PAIRS;
748#endif
749}
750
751gulong owl_dirty_window_on_signal(owl_window *w, gpointer sender, const gchar *detailed_signal)
752{
753  return owl_signal_connect_object(sender, detailed_signal, G_CALLBACK(owl_window_dirty), w, G_CONNECT_SWAPPED);
754}
755
756typedef struct { /*noproto*/
757  GObject  *sender;
758  gulong    signal_id;
759} SignalData;
760
761static void _closure_invalidated(gpointer data, GClosure *closure);
762
763/*
764 * GObject's g_signal_connect_object has a documented bug. This function is
765 * identical except it does not leak the signal handler.
766 */
767gulong owl_signal_connect_object(gpointer sender, const gchar *detailed_signal, GCallback c_handler, gpointer receiver, GConnectFlags connect_flags)
768{
769  g_return_val_if_fail (G_TYPE_CHECK_INSTANCE (sender), 0);
770  g_return_val_if_fail (detailed_signal != NULL, 0);
771  g_return_val_if_fail (c_handler != NULL, 0);
772
773  if (receiver) {
774    SignalData *sdata;
775    GClosure *closure;
776    gulong signal_id;
777
778    g_return_val_if_fail (G_IS_OBJECT (receiver), 0);
779
780    closure = ((connect_flags & G_CONNECT_SWAPPED) ? g_cclosure_new_object_swap : g_cclosure_new_object) (c_handler, receiver);
781    signal_id = g_signal_connect_closure (sender, detailed_signal, closure, connect_flags & G_CONNECT_AFTER);
782
783    /* Register the missing hooks */
784    sdata = g_slice_new0(SignalData);
785    sdata->sender = sender;
786    sdata->signal_id = signal_id;
787
788    g_closure_add_invalidate_notifier(closure, sdata, _closure_invalidated);
789
790    return signal_id;
791  } else {
792    return g_signal_connect_data(sender, detailed_signal, c_handler, NULL, NULL, connect_flags);
793  }
794}
795
796/*
797 * There are three ways the signal could come to an end:
798 *
799 * 1. The user explicitly disconnects it with the returned signal_id.
800 *    - In that case, the disconnection unref's the closure, causing it
801 *      to first be invalidated. The handler's already disconnected, so
802 *      we have no work to do.
803 * 2. The sender gets destroyed.
804 *    - GObject will disconnect each signal which then goes into the above
805 *      case. Our handler does no work.
806 * 3. The receiver gets destroyed.
807 *    - The GClosure was created by g_cclosure_new_object_{,swap} which gets
808 *      invalidated when the receiver is destroyed. We then follow through case 1
809 *      again, but *this* time, the handler has not been disconnected. We then
810 *      clean up ourselves.
811 *
812 * We can't actually hook into this process earlier with weakrefs as GObject
813 * will, on object dispose, first disconnect signals, then invalidate closures,
814 * and notify weakrefs last.
815 */
816static void _closure_invalidated(gpointer data, GClosure *closure)
817{
818  SignalData *sdata = data;
819  if (g_signal_handler_is_connected(sdata->sender, sdata->signal_id)) {
820    g_signal_handler_disconnect(sdata->sender, sdata->signal_id);
821  }
822  g_slice_free(SignalData, sdata);
823}
824
Note: See TracBrowser for help on using the repository browser.