source: util.c @ 6f14b20

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