source: util.c @ 65c753e

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