source: util.c @ 396505be

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