source: util.c @ 84a4aca

release-1.10release-1.7release-1.8release-1.9
Last change on this file since 84a4aca was 05ca0d8, checked in by David Benjamin <davidben@mit.edu>, 14 years ago
Implement our own owl_signal_connect_object This is actually more code, but that's because of comments. It'll be MUCH less error-prone.
  • Property mode set to 100644
File size: 19.9 KB
RevLine 
[7d4fbcd]1#include "owl.h"
2#include <stdlib.h>
3#include <string.h>
[5145235]4#include <unistd.h>
[7d4fbcd]5#include <ctype.h>
[f36222f]6#include <pwd.h>
[435001d]7#include <sys/stat.h>
8#include <sys/types.h>
[7d4fbcd]9
[05ca0d8]10#include <glib-object.h>
11
[e19eb97]12void sepbar(const char *in)
[e4eebe8]13{
[7d4fbcd]14  WINDOW *sepwin;
[3eb599d]15  const owl_messagelist *ml;
[9e5c9f3]16  const owl_view *v;
[7d4fbcd]17  int x, y, i;
[e19eb97]18  const char *foo, *appendtosepbar;
[7d4fbcd]19
20  sepwin=owl_global_get_curs_sepwin(&g);
21  ml=owl_global_get_msglist(&g);
22  v=owl_global_get_current_view(&g);
23
24  werase(sepwin);
25  wattron(sepwin, A_REVERSE);
[c15bbfb]26  if (owl_global_is_fancylines(&g)) {
27    whline(sepwin, ACS_HLINE, owl_global_get_cols(&g));
28  } else {
29    whline(sepwin, '-', owl_global_get_cols(&g));
30  }
[7d4fbcd]31
[73624b4]32  if (owl_global_is_sepbar_disable(&g)) {
33    getyx(sepwin, y, x);
34    wmove(sepwin, y, owl_global_get_cols(&g)-1);
35    return;
36  }
37
[96c3265]38  wmove(sepwin, 0, 2);
[7d4fbcd]39
[96c3265]40  if (owl_messagelist_get_size(ml) == 0)
41    waddstr(sepwin, " (-/-) ");
42  else
43    wprintw(sepwin, " (%i/%i/%i) ", owl_global_get_curmsg(&g) + 1,
44            owl_view_get_size(v),
45            owl_messagelist_get_size(ml));
[7d4fbcd]46
47  foo=owl_view_get_filtname(v);
[96c3265]48  if (strcmp(foo, owl_global_get_view_home(&g)))
49      wattroff(sepwin, A_REVERSE);
50  wprintw(sepwin, " %s ", owl_view_get_filtname(v));
51  if (strcmp(foo, owl_global_get_view_home(&g)))
52      wattron(sepwin, A_REVERSE);
[7d4fbcd]53
54  if (owl_mainwin_is_curmsg_truncated(owl_global_get_mainwin(&g))) {
55    getyx(sepwin, y, x);
56    wmove(sepwin, y, x+2);
57    wattron(sepwin, A_BOLD);
58    waddstr(sepwin, " <truncated> ");
59    wattroff(sepwin, A_BOLD);
60  }
61
62  i=owl_mainwin_get_last_msg(owl_global_get_mainwin(&g));
63  if ((i != -1) &&
64      (i < owl_view_get_size(v)-1)) {
65    getyx(sepwin, y, x);
66    wmove(sepwin, y, x+2);
67    wattron(sepwin, A_BOLD);
68    waddstr(sepwin, " <more> ");
69    wattroff(sepwin, A_BOLD);
70  }
71
72  if (owl_global_get_rightshift(&g)>0) {
73    getyx(sepwin, y, x);
74    wmove(sepwin, y, x+2);
[96c3265]75    wprintw(sepwin, " right: %i ", owl_global_get_rightshift(&g));
[7d4fbcd]76  }
77
[4b660cc]78  if (owl_global_is_zaway(&g) || owl_global_is_aaway(&g)) {
[7d4fbcd]79    getyx(sepwin, y, x);
80    wmove(sepwin, y, x+2);
81    wattron(sepwin, A_BOLD);
82    wattroff(sepwin, A_REVERSE);
[4b660cc]83    if (owl_global_is_zaway(&g) && owl_global_is_aaway(&g)) {
84      waddstr(sepwin, " AWAY ");
85    } else if (owl_global_is_zaway(&g)) {
86      waddstr(sepwin, " Z-AWAY ");
87    } else if (owl_global_is_aaway(&g)) {
88      waddstr(sepwin, " A-AWAY ");
89    }
[7d4fbcd]90    wattron(sepwin, A_REVERSE);
91    wattroff(sepwin, A_BOLD);
92  }
93
94  if (owl_global_get_curmsg_vert_offset(&g)) {
95    getyx(sepwin, y, x);
96    wmove(sepwin, y, x+2);
97    wattron(sepwin, A_BOLD);
98    wattroff(sepwin, A_REVERSE);
99    waddstr(sepwin, " SCROLL ");
100    wattron(sepwin, A_REVERSE);
101    wattroff(sepwin, A_BOLD);
102  }
103 
104  if (in) {
105    getyx(sepwin, y, x);
106    wmove(sepwin, y, x+2);
107    waddstr(sepwin, in);
108  }
109
110  appendtosepbar = owl_global_get_appendtosepbar(&g);
111  if (appendtosepbar && *appendtosepbar) {
112    getyx(sepwin, y, x);
113    wmove(sepwin, y, x+2);
114    waddstr(sepwin, " ");
115    waddstr(sepwin, owl_global_get_appendtosepbar(&g));
116    waddstr(sepwin, " ");
117  }
118
119  getyx(sepwin, y, x);
120  wmove(sepwin, y, owl_global_get_cols(&g)-1);
121   
122  wattroff(sepwin, A_BOLD);
123  wattroff(sepwin, A_REVERSE);
[4e33cb2]124  owl_global_set_needrefresh(&g);
[7d4fbcd]125}
126
[e19eb97]127char **atokenize(const char *buffer, const char *sep, int *i)
[e4eebe8]128{
[7d4fbcd]129  /* each element of return must be freed by user */
130  char **args;
131  char *workbuff, *foo;
132  int done=0, first=1, count=0;
133
[46d940a]134  workbuff = owl_strdup(buffer);
[7d4fbcd]135
136  args=NULL;
137  while (!done) {
138    if (first) {
139      first=0;
[4d86e06]140      foo=strtok(workbuff, sep);
[7d4fbcd]141    } else {
[4d86e06]142      foo=strtok(NULL, sep);
[7d4fbcd]143    }
144    if (foo==NULL) {
145      done=1;
146    } else {
[4d86e06]147      args=owl_realloc(args, sizeof(char *) * (count+1));
[36486be]148      args[count] = owl_strdup(foo);
[7d4fbcd]149      count++;
150    }
151  }
152  *i=count;
153  owl_free(workbuff);
154  return(args);
155}
156
[e19eb97]157const char *skiptokens(const char *buff, int n) {
[e30ed92]158  /* skips n tokens and returns where that would be. */
159  char quote = 0;
[7d4fbcd]160  while (*buff && n>0) {
161      while (*buff == ' ') buff++;
[e30ed92]162      while (*buff && (quote || *buff != ' ')) {
163        if(quote) {
164          if(*buff == quote) quote = 0;
165        } else if(*buff == '"' || *buff == '\'') {
166          quote = *buff;
167        }
168        buff++;
[7d4fbcd]169      }
170      while (*buff == ' ') buff++;
171      n--;
172  }
173  return buff;
174}
175
[f36222f]176/* Return a "nice" version of the path.  Tilde expansion is done, and
177 * duplicate slashes are removed.  Caller must free the return.
178 */
[e19eb97]179char *owl_util_makepath(const char *in)
[f36222f]180{
181  int i, j, x;
182  char *out, user[MAXPATHLEN];
183  struct passwd *pw;
184
185  out=owl_malloc(MAXPATHLEN+1);
186  out[0]='\0';
187  j=strlen(in);
188  x=0;
189  for (i=0; i<j; i++) {
190    if (in[i]=='~') {
191      if ( (i==(j-1)) ||          /* last character */
192           (in[i+1]=='/') ) {     /* ~/ */
193        /* use my homedir */
194        pw=getpwuid(getuid());
195        if (!pw) {
196          out[x]=in[i];
197        } else {
198          out[x]='\0';
199          strcat(out, pw->pw_dir);
200          x+=strlen(pw->pw_dir);
201        }
202      } else {
203        /* another user homedir */
204        int a, b;
205        b=0;
206        for (a=i+1; i<j; a++) {
207          if (in[a]==' ' || in[a]=='/') {
208            break;
209          } else {
210            user[b]=in[a];
211            i++;
212            b++;
213          }
214        }
215        user[b]='\0';
216        pw=getpwnam(user);
217        if (!pw) {
[8766d44]218          out[x]=in[i];
[f36222f]219        } else {
220          out[x]='\0';
221          strcat(out, pw->pw_dir);
222          x+=strlen(pw->pw_dir);
223        }
224      }
225    } else if (in[i]=='/') {
226      /* check for a double / */
227      if (i<(j-1) && (in[i+1]=='/')) {
228        /* do nothing */
229      } else {
230        out[x]=in[i];
231        x++;
232      }
233    } else {
234      out[x]=in[i];
235      x++;
236    }
237  }
238  out[x]='\0';
239  return(out);
240}
241
[1672650]242void atokenize_delete(char **tok, int nels)
[e4eebe8]243{
[7d4fbcd]244  int i;
245  for (i=0; i<nels; i++) {
246    owl_free(tok[i]);
247  }
248  owl_free(tok);
249}
250
251
[40d22cf]252void owl_parse_delete(char **argv, int argc)
[e4eebe8]253{
[7d4fbcd]254  int i;
255
256  if (!argv) return;
257 
258  for (i=0; i<argc; i++) {
259    if (argv[i]) owl_free(argv[i]);
260  }
261  owl_free(argv);
262}
263
[e19eb97]264char **owl_parseline(const char *line, int *argc)
[e4eebe8]265{
[7d4fbcd]266  /* break a command line up into argv, argc.  The caller must free
267     the returned values.  If there is an error argc will be set to
268     -1, argv will be NULL and the caller does not need to free
269     anything */
270
271  char **argv;
272  int i, len, between=1;
273  char *curarg;
274  char quote;
275
276  argv=owl_malloc(sizeof(char *));
277  len=strlen(line);
278  curarg=owl_malloc(len+10);
279  strcpy(curarg, "");
280  quote='\0';
281  *argc=0;
282  for (i=0; i<len+1; i++) {
283    /* find the first real character */
284    if (between) {
285      if (line[i]==' ' || line[i]=='\t' || line[i]=='\0') {
286        continue;
287      } else {
288        between=0;
289        i--;
290        continue;
291      }
292    }
293
294    /* deal with a quote character */
295    if (line[i]=='"' || line[i]=="'"[0]) {
296      /* if this type of quote is open, close it */
297      if (quote==line[i]) {
298        quote='\0';
299        continue;
300      }
301
302      /* if no quoting is open then open with this */
303      if (quote=='\0') {
304        quote=line[i];
305        continue;
306      }
307
308      /* if another type of quote is open then treat this as a literal */
309      curarg[strlen(curarg)+1]='\0';
310      curarg[strlen(curarg)]=line[i];
311      continue;
312    }
313
314    /* if it's not a space or end of command, then use it */
315    if (line[i]!=' ' && line[i]!='\t' && line[i]!='\n' && line[i]!='\0') {
316      curarg[strlen(curarg)+1]='\0';
317      curarg[strlen(curarg)]=line[i];
318      continue;
319    }
320
321    /* otherwise, if we're not in quotes, add the whole argument */
322    if (quote=='\0') {
323      /* add the argument */
324      argv=owl_realloc(argv, sizeof(char *)*((*argc)+1));
[36486be]325      argv[*argc] = owl_strdup(curarg);
[7d4fbcd]326      *argc=*argc+1;
327      strcpy(curarg, "");
328      between=1;
329      continue;
330    }
331
332    /* if it is a space and we're in quotes, then use it */
333    curarg[strlen(curarg)+1]='\0';
334    curarg[strlen(curarg)]=line[i];
335  }
336
[d524c83]337  owl_free(curarg);
[95caa16]338
[7d4fbcd]339  /* check for unbalanced quotes */
340  if (quote!='\0') {
[40d22cf]341    owl_parse_delete(argv, *argc);
[7d4fbcd]342    *argc=-1;
343    return(NULL);
344  }
345
346  return(argv);
347}
348
[de03334]349/* caller must free the return */
[5b85d19]350char *owl_util_minutes_to_timestr(int in)
[de03334]351{
[f1e629d]352  int days, hours;
[de03334]353  long run;
354  char *out;
355
[5b85d19]356  run=in;
[de03334]357
[5b85d19]358  days=run/1440;
359  run-=days*1440;
360  hours=run/60;
361  run-=hours*60;
[de03334]362
363  if (days>0) {
[6eaf35b]364    out=owl_sprintf("%i d %2.2i:%2.2li", days, hours, run);
[de03334]365  } else {
[6eaf35b]366    out=owl_sprintf("    %2.2i:%2.2li", hours, run);
[de03334]367  }
368  return(out);
369}
370
[42abb10]371/* hooks for doing memory allocation et. al. in owl */
372
[e4eebe8]373void *owl_malloc(size_t size)
374{
[34509d5]375  return(g_malloc(size));
[7d4fbcd]376}
377
[e4eebe8]378void owl_free(void *ptr)
379{
[34509d5]380  g_free(ptr);
[7d4fbcd]381}
382
[e4eebe8]383char *owl_strdup(const char *s1)
384{
[34509d5]385  return(g_strdup(s1));
[7d4fbcd]386}
387
[e4eebe8]388void *owl_realloc(void *ptr, size_t size)
389{
[34509d5]390  return(g_realloc(ptr, size));
[7d4fbcd]391}
392
[e4eebe8]393/* allocates memory and returns the string or null.
394 * caller must free the string.
395 */
396char *owl_sprintf(const char *fmt, ...)
397{
[1c6c4d3]398  va_list ap;
[28ee32b]399  char *ret = NULL;
400  va_start(ap, fmt);
401  ret = g_strdup_vprintf(fmt, ap);
402  va_end(ap);
403  return ret;
[1c6c4d3]404}
405
[a3e61a2]406/* These are in order of their value in owl.h */
407static const struct {
408  int number;
409  const char *name;
410} color_map[] = {
411  {OWL_COLOR_INVALID, "invalid"},
412  {OWL_COLOR_DEFAULT, "default"},
413  {OWL_COLOR_BLACK, "black"},
414  {OWL_COLOR_RED, "red"},
415  {OWL_COLOR_GREEN, "green"},
416  {OWL_COLOR_YELLOW,"yellow"},
417  {OWL_COLOR_BLUE, "blue"},
418  {OWL_COLOR_MAGENTA, "magenta"},
419  {OWL_COLOR_CYAN, "cyan"},
420  {OWL_COLOR_WHITE, "white"},
421};
[28ee32b]422
[12c35df]423/* Return the owl color associated with the named color.  Return -1
424 * if the named color is not available
425 */
[e19eb97]426int owl_util_string_to_color(const char *color)
[e4eebe8]427{
[a3e61a2]428  int c, i;
[1b9d3cc]429  char *p;
[a3e61a2]430
431  for (i = 0; i < (sizeof(color_map)/sizeof(color_map[0])); i++)
432    if (strcasecmp(color, color_map[i].name) == 0)
433      return color_map[i].number;
434
[1b9d3cc]435  c = strtol(color, &p, 10);
436  if (p != color && c >= -1 && c < COLORS) {
[c2c5c77]437    return(c);
438  }
[601733d]439  return(OWL_COLOR_INVALID);
[7d4fbcd]440}
441
[e4eebe8]442/* Return a string name of the given owl color */
[e19eb97]443const char *owl_util_color_to_string(int color)
[e4eebe8]444{
[a3e61a2]445  if (color >= OWL_COLOR_INVALID && color <= OWL_COLOR_WHITE)
446    return color_map[color - OWL_COLOR_INVALID].name;
[7d4fbcd]447  return("Unknown color");
448}
[e1c4636]449
[e4eebe8]450/* Get the default tty name.  Caller must free the return */
[c79a047]451char *owl_util_get_default_tty(void)
[e4eebe8]452{
[e19eb97]453  const char *tmp;
[65b2173]454  char *out;
[61e79a9]455
456  if (getenv("DISPLAY")) {
457    out=owl_strdup(getenv("DISPLAY"));
[5145235]458  } else if ((tmp=ttyname(fileno(stdout)))!=NULL) {
459    out=owl_strdup(tmp);
[61e79a9]460    if (!strncmp(out, "/dev/", 5)) {
461      owl_free(out);
[5145235]462      out=owl_strdup(tmp+5);
[61e79a9]463    }
464  } else {
[5145235]465    out=owl_strdup("unknown");
[61e79a9]466  }
467  return(out);
468}
469
[e4eebe8]470/* strip leading and trailing new lines.  Caller must free the
471 * return.
472 */
[e19eb97]473char *owl_util_stripnewlines(const char *in)
[e4eebe8]474{
[7e3e00a]475 
476  char  *tmp, *ptr1, *ptr2, *out;
477
478  ptr1=tmp=owl_strdup(in);
479  while (ptr1[0]=='\n') {
480    ptr1++;
481  }
482  ptr2=ptr1+strlen(ptr1)-1;
[1bb1e67]483  while (ptr2>ptr1 && ptr2[0]=='\n') {
[7e3e00a]484    ptr2[0]='\0';
485    ptr2--;
486  }
487
488  out=owl_strdup(ptr1);
489  owl_free(tmp);
490  return(out);
491}
492
[946058b]493/* Delete all lines matching "line" from the named file.  If no such
494 * line is found the file is left intact.  If backup==1 then leave a
495 * backup file containing the original contents.  The match is
496 * case-insensitive.
[da60ba9]497 *
498 * Returns the number of lines removed
[38cf544c]499 */
[da60ba9]500int owl_util_file_deleteline(const char *filename, const char *line, int backup)
[38cf544c]501{
[946058b]502  char *backupfile, *newfile, *buf = NULL;
503  FILE *old, *new;
504  struct stat st;
[da60ba9]505  int numremoved = 0;
[38cf544c]506
[946058b]507  if ((old = fopen(filename, "r")) == NULL) {
508    owl_function_error("Cannot open %s (for reading): %s",
509                       filename, strerror(errno));
[da60ba9]510    return 0;
[38cf544c]511  }
[e6449bc]512
[946058b]513  if (fstat(fileno(old), &st) != 0) {
514    owl_function_error("Cannot stat %s: %s", filename, strerror(errno));
515    return 0;
[38cf544c]516  }
517
[946058b]518  newfile = owl_sprintf("%s.new", filename);
519  if ((new = fopen(newfile, "w")) == NULL) {
520    owl_function_error("Cannot open %s (for writing): %s",
521                       filename, strerror(errno));
522    free(newfile);
523    fclose(old);
524    return 0;
525  }
526
527  if (fchmod(fileno(new), st.st_mode & 0777) != 0) {
528    owl_function_error("Cannot set permissions on %s: %s",
529                       filename, strerror(errno));
530    unlink(newfile);
531    fclose(new);
532    free(newfile);
533    fclose(old);
534    return 0;
535  }
536
537  while (owl_getline_chomp(&buf, old))
538    if (strcasecmp(buf, line) != 0)
539      fprintf(new, "%s\n", buf);
540    else
[da60ba9]541      numremoved++;
[a61daae]542  owl_free(buf);
[38cf544c]543
[946058b]544  fclose(new);
545  fclose(old);
546
547  if (backup) {
548    backupfile = owl_sprintf("%s.backup", filename);
549    unlink(backupfile);
550    if (link(filename, backupfile) != 0) {
551      owl_function_error("Cannot link %s: %s", backupfile, strerror(errno));
552      owl_free(backupfile);
553      unlink(newfile);
554      owl_free(newfile);
555      return 0;
[6a50af2]556    }
[946058b]557    owl_free(backupfile);
[38cf544c]558  }
559
[946058b]560  if (rename(newfile, filename) != 0) {
561    owl_function_error("Cannot move %s to %s: %s",
562                       newfile, filename, strerror(errno));
563    numremoved = 0;
[38cf544c]564  }
565
[946058b]566  unlink(newfile);
567  owl_free(newfile);
[da60ba9]568
569  return numremoved;
[38cf544c]570}
571
[fe67f1f]572int owl_util_max(int a, int b)
573{
574  if (a>b) return(a);
575  return(b);
576}
577
578int owl_util_min(int a, int b)
579{
580  if (a<b) return(a);
581  return(b);
582}
583
[7a20e4c]584/* Return the base class or instance from a zephyr class, by removing
585   leading `un' or trailing `.d'.
[be5aa09]586   The caller is responsible for freeing the allocated string.
[7a20e4c]587*/
[e19eb97]588char * owl_util_baseclass(const char * class)
[7a20e4c]589{
[59916e8]590  char *start, *end;
591
[fa4562c]592  while(!strncmp(class, "un", 2)) {
593    class += 2;
[7a20e4c]594  }
[f166580]595
[fa4562c]596  start = owl_strdup(class);
[59916e8]597  end = start + strlen(start) - 1;
[04166e9]598  while(end > start && *end == 'd' && *(end-1) == '.') {
[7a20e4c]599    end -= 2;
600  }
601  *(end + 1) = 0;
[59916e8]602
[f166580]603  return start;
[7a20e4c]604}
605
[c79a047]606const char * owl_get_datadir(void)
[5376a95]607{
[e19eb97]608  const char * datadir = getenv("BARNOWL_DATA_DIR");
[5376a95]609  if(datadir != NULL)
[7bf51d5]610    return datadir;
[5376a95]611  return DATADIR;
612}
613
[9a7b4f2]614const char * owl_get_bindir(void)
615{
616  const char * bindir = getenv("BARNOWL_BIN_DIR");
617  if(bindir != NULL)
618    return bindir;
619  return BINDIR;
620}
621
[5376a95]622/* Strips format characters from a valid utf-8 string. Returns the
623   empty string if 'in' does not validate. */
[7f6a8a2]624char * owl_strip_format_chars(const char *in)
[5376a95]625{
626  char *r;
627  if (g_utf8_validate(in, -1, NULL)) {
[7f6a8a2]628    const char *s, *p;
[5376a95]629    r = owl_malloc(strlen(in)+1);
630    r[0] = '\0';
631    s = in;
632    p = strchr(s, OWL_FMTEXT_UC_STARTBYTE_UTF8);
633    while(p) {
634      /* If it's a format character, copy up to it, and skip all
635         immediately following format characters. */
[c1522ec]636      if (owl_fmtext_is_format_char(g_utf8_get_char(p))) {
[5376a95]637        strncat(r, s, p-s);
638        p = g_utf8_next_char(p);
[f119757]639        while (owl_fmtext_is_format_char(g_utf8_get_char(p))) {
[5376a95]640          p = g_utf8_next_char(p);
641        }
642        s = p;
643        p = strchr(s, OWL_FMTEXT_UC_STARTBYTE_UTF8);
644      }
645      else {
646        p = strchr(p+1, OWL_FMTEXT_UC_STARTBYTE_UTF8);
647      }
648    }
649    if (s) strcat(r,s);
650  }
651  else {
652    r = owl_strdup("");
653  }
654  return r;
655}
656
657/* If in is not UTF-8, convert from ISO-8859-1. We may want to allow
658 * the caller to specify an alternative in the future. We also strip
659 * out characters in Unicode Plane 16, as we use that plane internally
660 * for formatting.
661 */
[7f6a8a2]662char * owl_validate_or_convert(const char *in)
[5376a95]663{
[6201646]664  if (g_utf8_validate(in, -1, NULL)) {
[5376a95]665    return owl_strip_format_chars(in);
666  }
667  else {
[6201646]668    return g_convert(in, -1,
[5376a95]669                     "UTF-8", "ISO-8859-1",
670                     NULL, NULL, NULL);
671  }
[89f5338]672}
[4b17a6c]673/*
674 * Validate 'in' as UTF-8, and either return a copy of it, or an empty
675 * string if it is invalid utf-8.
[7b1d048]676 */
[7f6a8a2]677char * owl_validate_utf8(const char *in)
[7b1d048]678{
679  char *out;
680  if (g_utf8_validate(in, -1, NULL)) {
[4b17a6c]681    out = owl_strdup(in);
682  } else {
[7b1d048]683    out = owl_strdup("");
684  }
685  return out;
686}
[89f5338]687
[84027015]688/* This is based on _extract() and _isCJ() from perl's Text::WrapI18N */
689int owl_util_can_break_after(gunichar c)
690{
691 
692  if (c == ' ') return 1;
693  if (c >= 0x3000 && c <= 0x312f) {
694    /* CJK punctuations, Hiragana, Katakana, Bopomofo */
695    if (c == 0x300a || c == 0x300c || c == 0x300e ||
696        c == 0x3010 || c == 0x3014 || c == 0x3016 ||
697        c == 0x3018 || c == 0x301a)
698      return 0;
699    return 1;
700  }
701  if (c >= 0x31a0 && c <= 0x31bf) {return 1;}  /* Bopomofo */
702  if (c >= 0x31f0 && c <= 0x31ff) {return 1;}  /* Katakana extension */
703  if (c >= 0x3400 && c <= 0x9fff) {return 1;}  /* Han Ideogram */
704  if (c >= 0xf900 && c <= 0xfaff) {return 1;}  /* Han Ideogram */
705  if (c >= 0x20000 && c <= 0x2ffff) {return 1;}  /* Han Ideogram */
706  return 0;
707}
[eea72a13]708
709char *owl_escape_highbit(const char *str)
710{
711  GString *out = g_string_new("");
712  unsigned char c;
713  while((c = (*str++))) {
714    if(c == '\\') {
715      g_string_append(out, "\\\\");
716    } else if(c & 0x80) {
717      g_string_append_printf(out, "\\x%02x", (int)c);
718    } else {
719      g_string_append_c(out, c);
720    }
721  }
722  return g_string_free(out, 0);
723}
[6ace255]724
725/* innards of owl_getline{,_chomp} below */
726static int owl_getline_internal(char **s, FILE *fp, int newline)
727{
728  int size = 0;
729  int target = 0;
730  int count = 0;
731  int c;
732
733  while (1) {
734    c = getc(fp);
735    if ((target + 1) > size) {
736      size += BUFSIZ;
737      *s = owl_realloc(*s, size);
738    }
739    if (c == EOF)
740      break;
741    count++;
742    if (c != '\n' || newline)
743        (*s)[target++] = c;
744    if (c == '\n')
745      break;
746  }
747  (*s)[target] = 0;
748
749  return count;
750}
751
752/* Read a line from fp, allocating memory to hold it, returning the number of
753 * byte read.  *s should either be NULL or a pointer to memory allocated with
754 * owl_malloc; it will be owl_realloc'd as appropriate.  The caller must
755 * eventually free it.  (This is roughly the interface of getline in the gnu
756 * libc).
757 *
758 * The final newline will be included if it's there.
759 */
760int owl_getline(char **s, FILE *fp)
761{
762  return owl_getline_internal(s, fp, 1);
763}
764
765/* As above, but omitting the final newline */
766int owl_getline_chomp(char **s, FILE *fp)
767{
768  return owl_getline_internal(s, fp, 0);
769}
770
771/* Read the rest of the input available in fp into a string. */
772char *owl_slurp(FILE *fp)
773{
774  char *buf = NULL;
775  char *p;
776  int size = 0;
777  int count;
778
779  while (1) {
780    buf = owl_realloc(buf, size + BUFSIZ);
781    p = &buf[size];
782    size += BUFSIZ;
783
784    if ((count = fread(p, 1, BUFSIZ, fp)) < BUFSIZ)
785      break;
786  }
787  p[count] = 0;
788
789  return buf;
790}
[05ca0d8]791
792typedef struct { /*noproto*/
793  GObject  *sender;
794  gulong    signal_id;
795} SignalData;
796
797static void _closure_invalidated(gpointer data, GClosure *closure);
798
799/*
800 * GObject's g_signal_connect_object has a documented bug. This function is
801 * identical except it does not leak the signal handler.
802 */
803gulong owl_signal_connect_object(gpointer sender, const gchar *detailed_signal, GCallback c_handler, gpointer receiver, GConnectFlags connect_flags)
804{
805  g_return_val_if_fail (G_TYPE_CHECK_INSTANCE (sender), 0);
806  g_return_val_if_fail (detailed_signal != NULL, 0);
807  g_return_val_if_fail (c_handler != NULL, 0);
808
809  if (receiver) {
810    SignalData *sdata;
811    GClosure *closure;
812    gulong signal_id;
813
814    g_return_val_if_fail (G_IS_OBJECT (receiver), 0);
815
816    closure = ((connect_flags & G_CONNECT_SWAPPED) ? g_cclosure_new_object_swap : g_cclosure_new_object) (c_handler, receiver);
817    signal_id = g_signal_connect_closure (sender, detailed_signal, closure, connect_flags & G_CONNECT_AFTER);
818
819    /* Register the missing hooks */
820    sdata = g_slice_new0(SignalData);
821    sdata->sender = sender;
822    sdata->signal_id = signal_id;
823
824    g_closure_add_invalidate_notifier(closure, sdata, _closure_invalidated);
825
826    return signal_id;
827  } else {
828    return g_signal_connect_data(sender, detailed_signal, c_handler, NULL, NULL, connect_flags);
829  }
830}
831
832/*
833 * There are three ways the signal could come to an end:
834 *
835 * 1. The user explicitly disconnects it with the returned signal_id.
836 *    - In that case, the disconnection unref's the closure, causing it
837 *      to first be invalidated. The handler's already disconnected, so
838 *      we have no work to do.
839 * 2. The sender gets destroyed.
840 *    - GObject will disconnect each signal which then goes into the above
841 *      case. Our handler does no work.
842 * 3. The receiver gets destroyed.
843 *    - The GClosure was created by g_cclosure_new_object_{,swap} which gets
844 *      invalidated when the receiver is destroyed. We then follow through case 1
845 *      again, but *this* time, the handler has not been disconnected. We then
846 *      clean up ourselves.
847 *
848 * We can't actually hook into this process earlier with weakrefs as GObject
849 * will, on object dispose, first disconnect signals, then invalidate closures,
850 * and notify weakrefs last.
851 */
852static void _closure_invalidated(gpointer data, GClosure *closure)
853{
854  SignalData *sdata = data;
855  if (g_signal_handler_is_connected(sdata->sender, sdata->signal_id)) {
856    g_signal_handler_disconnect(sdata->sender, sdata->signal_id);
857  }
858  g_slice_free(SignalData, sdata);
859}
860
Note: See TracBrowser for help on using the repository browser.