source: functions.c @ 18fdd5f9

release-1.10release-1.5release-1.6release-1.7release-1.8release-1.9
Last change on this file since 18fdd5f9 was 23fddad, checked in by Karl Ramm <kcr@1ts.org>, 15 years ago
refactor & rename filter creation & storage management filter_init_fromstring -> filter_new_fromstring filter_init -> filter_new filter_free -> filter_delete Every time owl_filter_init and owl_filter_init_fromstring were called, there was a call to malloc right above them; Conversely, after every owl_filter_free there needed to be a call to owl_free (and sometimes there wasn't).
  • Property mode set to 100644
File size: 97.6 KB
Line 
1#include <stdio.h>
2#include <stdlib.h>
3#include <unistd.h>
4#include <signal.h>
5#include <netinet/in.h>
6#include <string.h>
7#include <time.h>
8#include <sys/types.h>
9#include <sys/stat.h>
10#include <sys/wait.h>
11#include <errno.h>
12#include <signal.h>
13#include "owl.h"
14
15char *owl_function_command(const char *cmdbuff)
16{
17  owl_function_debugmsg("executing command: %s", cmdbuff);
18  return owl_cmddict_execute(owl_global_get_cmddict(&g), 
19                             owl_global_get_context(&g), cmdbuff);
20}
21
22char *owl_function_command_argv(const char *const *argv, int argc)
23{
24  return owl_cmddict_execute_argv(owl_global_get_cmddict(&g),
25                                  owl_global_get_context(&g),
26                                  argv, argc);
27}
28
29void owl_function_command_norv(const char *cmdbuff)
30{
31  char *rv;
32  rv=owl_function_command(cmdbuff);
33  if (rv) owl_free(rv);
34}
35
36void owl_function_command_alias(const char *alias_from, const char *alias_to)
37{
38  owl_cmddict_add_alias(owl_global_get_cmddict(&g), alias_from, alias_to);
39}
40
41const owl_cmd *owl_function_get_cmd(const char *name)
42{
43  return owl_cmddict_find(owl_global_get_cmddict(&g), name);
44}
45
46void owl_function_show_commands(void)
47{
48  owl_list l;
49  owl_fmtext fm;
50
51  owl_fmtext_init_null(&fm);
52  owl_fmtext_append_bold(&fm, "Commands:  ");
53  owl_fmtext_append_normal(&fm, "(use 'show command <name>' for details)\n");
54  owl_cmddict_get_names(owl_global_get_cmddict(&g), &l);
55  owl_fmtext_append_list(&fm, &l, "\n", owl_function_cmd_describe);
56  owl_fmtext_append_normal(&fm, "\n");
57  owl_function_popless_fmtext(&fm);
58  owl_cmddict_namelist_free(&l);
59  owl_fmtext_free(&fm);
60}
61
62void owl_function_show_view(const char *viewname)
63{
64  const owl_view *v;
65  owl_fmtext fm;
66
67  /* we only have the one view right now */
68  v=owl_global_get_current_view(&g);
69  if (viewname && strcmp(viewname, owl_view_get_name(v))) {
70    owl_function_error("No view named '%s'", viewname);
71    return;
72  }
73
74  owl_fmtext_init_null(&fm);
75  owl_view_to_fmtext(v, &fm);
76  owl_function_popless_fmtext(&fm);
77  owl_fmtext_free(&fm);
78}
79
80void owl_function_show_styles(void) {
81  owl_list l;
82  owl_fmtext fm;
83
84  owl_fmtext_init_null(&fm);
85  owl_fmtext_append_bold(&fm, "Styles:\n");
86  owl_global_get_style_names(&g, &l);
87  owl_fmtext_append_list(&fm, &l, "\n", owl_function_style_describe);
88  owl_fmtext_append_normal(&fm, "\n");
89  owl_function_popless_fmtext(&fm);
90  owl_list_free_all(&l, owl_free);
91  owl_fmtext_free(&fm);
92}
93
94char *owl_function_style_describe(const char *name) {
95  const char *desc;
96  char *s;
97  const owl_style *style;
98  style = owl_global_get_style_by_name(&g, name);
99  if (style) {
100    desc = owl_style_get_description(style);
101  } else {
102    desc = "???";
103  }
104  s = owl_sprintf("%-20s - %s%s", name, 
105                  0==owl_style_validate(style)?"":"[INVALID] ",
106                  desc);
107  return s;
108}
109
110char *owl_function_cmd_describe(const char *name)
111{
112  const owl_cmd *cmd = owl_cmddict_find(owl_global_get_cmddict(&g), name);
113  if (cmd) return owl_cmd_describe(cmd);
114  else return(NULL);
115}
116
117void owl_function_show_command(const char *name)
118{
119  owl_function_help_for_command(name);
120}
121
122void owl_function_show_license(void)
123{
124  const char *text;
125
126  text=""
127    "barnowl version " OWL_VERSION_STRING "\n"
128    "Copyright (c) 2006-2009 The BarnOwl Developers. All rights reserved.\n"
129    "Copyright (c) 2004 James Kretchmar. All rights reserved.\n"
130    "\n"
131    "Redistribution and use in source and binary forms, with or without\n"
132    "modification, are permitted provided that the following conditions are\n"
133    "met:\n"
134    "\n"
135    "   * Redistributions of source code must retain the above copyright\n"
136    "     notice, this list of conditions and the following disclaimer.\n"
137    "\n"
138    "   * Redistributions in binary form must reproduce the above copyright\n"
139    "     notice, this list of conditions and the following disclaimer in\n"
140    "     the documentation and/or other materials provided with the\n"
141    "     distribution.\n"
142    "\n"
143    "   * Redistributions in any form must be accompanied by information on\n"
144    "     how to obtain complete source code for the Owl software and any\n"
145    "     accompanying software that uses the Owl software. The source code\n"
146    "     must either be included in the distribution or be available for no\n"
147    "     more than the cost of distribution plus a nominal fee, and must be\n"
148    "     freely redistributable under reasonable conditions. For an\n"
149    "     executable file, complete source code means the source code for\n"
150    "     all modules it contains. It does not include source code for\n"
151    "     modules or files that typically accompany the major components of\n"
152    "     the operating system on which the executable file runs.\n"
153    "\n"
154    "THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"
155    "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n"
156    "WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR\n"
157    "NON-INFRINGEMENT, ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE\n"
158    "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n"
159    "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n"
160    "SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n"
161    "BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n"
162    "WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n"
163    "OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n"
164    "IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n";
165  owl_function_popless_text(text);
166}
167
168void owl_function_show_quickstart(void)
169{
170    const char *message =
171    "Move between messages with the arrow keys, and press 'r' to reply.\n"
172    "For more info, press 'h' or visit http://barnowl.mit.edu/\n\n"
173#ifdef HAVE_LIBZEPHYR
174    "@b(Zephyr:)\n"
175    "To send a message to a user, type ':zwrite @b(username)'. You can also\n"
176    "press 'z' and then type the username. To subscribe to a class, type\n"
177    "':sub @b(class)', and then type ':zwrite -c @b(class)' to send.\n\n"
178#endif
179    "@b(AIM:)\n"
180    "Log in to AIM with ':aimlogin @b(screenname)'. Use ':aimwrite @b(screenname)',\n"
181    "or 'a' and then the screen name, to send someone a message.\n\n"
182    ;
183
184    if (owl_perlconfig_is_function("BarnOwl::Hooks::_get_quickstart")) {
185        char *perlquickstart = owl_perlconfig_execute("BarnOwl::Hooks::_get_quickstart()");
186        if (perlquickstart) {
187            char *result = owl_sprintf("%s%s", message, perlquickstart);
188            owl_function_adminmsg("BarnOwl Quickstart", result);
189            owl_free(result);
190            owl_free(perlquickstart);
191            return;
192        }
193    }
194    owl_function_adminmsg("BarnOwl Quickstart", message);
195}
196
197
198/* Create an admin message, append it to the global list of messages
199 * and redisplay if necessary.
200 */
201void owl_function_adminmsg(const char *header, const char *body)
202{
203  owl_message *m;
204
205  m=owl_malloc(sizeof(owl_message));
206  owl_message_create_admin(m, header, body);
207 
208  /* add it to the global list and current view */
209  owl_messagelist_append_element(owl_global_get_msglist(&g), m);
210  owl_view_consider_message(owl_global_get_current_view(&g), m);
211
212  /* do followlast if necessary */
213  if (owl_global_should_followlast(&g)) owl_function_lastmsg_noredisplay();
214
215  /* redisplay etc. */
216  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
217  if (owl_popwin_is_active(owl_global_get_popwin(&g))) {
218    owl_popwin_refresh(owl_global_get_popwin(&g));
219  }
220  wnoutrefresh(owl_global_get_curs_recwin(&g));
221  owl_global_set_needrefresh(&g);
222}
223
224/* Create an outgoing zephyr message and return a pointer to it.  Does
225 * not put it on the global queue, use owl_global_messagequeue_addmsg() for
226 * that.
227 */
228owl_message *owl_function_make_outgoing_zephyr(const char *body, const char *zwriteline, const char *zsig)
229{
230  owl_message *m;
231  owl_zwrite zw;
232
233  owl_zwrite_create_from_line(&zw, zwriteline);
234  owl_zwrite_set_zsig(&zw, zsig);
235
236  /* create the message */
237  m=owl_malloc(sizeof(owl_message));
238 
239  owl_message_create_from_zwrite(m, &zw, body);
240  owl_zwrite_free(&zw);
241
242  return(m);
243}
244
245/* Create an outgoing AIM message, returns a pointer to the created
246 * message or NULL if we're not logged into AIM (and thus unable to
247 * create the message).  Does not put it on the global queue.  Use
248 * owl_global_messagequeue_addmsg() for that .
249 */
250owl_message *owl_function_make_outgoing_aim(const char *body, const char *to)
251{
252  owl_message *m;
253
254  /* error if we're not logged into aim */
255  if (!owl_global_is_aimloggedin(&g)) return(NULL);
256 
257  m=owl_malloc(sizeof(owl_message));
258  owl_message_create_aim(m,
259                         owl_global_get_aim_screenname(&g),
260                         to,
261                         body,
262                         OWL_MESSAGE_DIRECTION_OUT,
263                         0);
264  return(m);
265}
266
267/* Create an outgoing loopback message and return a pointer to it.
268 * Does not append it to the global queue, use
269 * owl_global_messagequeue_addmsg() for that.
270 */
271owl_message *owl_function_make_outgoing_loopback(const char *body)
272{
273  owl_message *m;
274
275  /* create the message */
276  m=owl_malloc(sizeof(owl_message));
277  owl_message_create_loopback(m, body);
278  owl_message_set_direction_out(m);
279
280  return(m);
281}
282
283void owl_function_start_edit_win(const char *line, void (*callback)(owl_editwin *), void *data)
284{
285  owl_editwin *e;
286  char *s;
287
288  /* create and setup the editwin */
289  e = owl_global_get_typwin(&g);
290  owl_editwin_new_style(e, OWL_EDITWIN_STYLE_MULTILINE,
291                        owl_global_get_msg_history(&g));
292  owl_editwin_clear(e);
293  owl_editwin_set_dotsend(e);
294  s = owl_sprintf("----> %s\n", line);
295  owl_editwin_set_locktext(e, s);
296  owl_free(s);
297
298  /* make it active */
299  owl_global_set_typwin_active(&g);
300
301  owl_editwin_set_cbdata(owl_global_get_typwin(&g), data);
302  owl_global_set_buffercallback(&g, callback);
303}
304
305static void owl_function_write_setup(const char *line, const char *noun, void (*callback)(owl_editwin *))
306{
307
308  if (!owl_global_get_lockout_ctrld(&g))
309    owl_function_makemsg("Type your %s below.  "
310                         "End with ^D or a dot on a line by itself."
311                         "  ^C will quit.", noun);
312  else
313    owl_function_makemsg("Type your %s below.  "
314                         "End with a dot on a line by itself.  ^C will quit.",
315                         noun);
316
317  owl_function_start_edit_win(line, callback, NULL);
318  owl_global_set_buffercommand(&g, line);
319}
320
321void owl_function_zwrite_setup(const char *line)
322{
323  owl_zwrite z;
324  int ret;
325
326  /* check the arguments */
327  ret=owl_zwrite_create_from_line(&z, line);
328  if (ret) {
329    owl_function_error("Error in zwrite arguments");
330    owl_zwrite_free(&z);
331    return;
332  }
333
334  /* send a ping if necessary */
335  if (owl_global_is_txping(&g)) {
336    owl_zwrite_send_ping(&z);
337  }
338  owl_zwrite_free(&z);
339
340  owl_function_write_setup(line, "zephyr", &owl_callback_zwrite);
341}
342
343void owl_function_aimwrite_setup(const char *line)
344{
345  owl_function_write_setup(line, "message", &owl_callback_aimwrite);
346}
347
348void owl_function_loopwrite_setup(void)
349{
350  owl_editwin *e;
351
352  /* create and setup the editwin */
353  e=owl_global_get_typwin(&g);
354  owl_editwin_new_style(e, OWL_EDITWIN_STYLE_MULTILINE, owl_global_get_msg_history(&g));
355
356  if (!owl_global_get_lockout_ctrld(&g)) {
357    owl_function_makemsg("Type your message below.  End with ^D or a dot on a line by itself.  ^C will quit.");
358  } else {
359    owl_function_makemsg("Type your message below.  End with a dot on a line by itself.  ^C will quit.");
360  }
361
362  owl_editwin_clear(e);
363  owl_editwin_set_dotsend(e);
364  owl_editwin_set_locktext(e, "----> loopwrite\n");
365
366  /* make it active */
367  owl_global_set_typwin_active(&g);
368
369  owl_global_set_buffercommand(&g, "loopwrite");
370  owl_global_set_buffercallback(&g, &owl_callback_loopwrite);
371}
372
373void owl_callback_zwrite(owl_editwin *e) {
374  owl_function_zwrite(owl_editwin_get_command(e),
375                      owl_editwin_get_text(e));
376}
377
378/* send, log and display an outgoing zephyr.  If 'msg' is NULL
379 * the message is expected to be set from the zwrite line itself
380 */
381void owl_function_zwrite(const char *line, const char *msg)
382{
383  owl_zwrite z;
384  const char *mymsg;
385  owl_message *m;
386
387  if(!strncmp(line, "zcrypt", strlen("zcrypt"))) {
388    owl_function_zcrypt(line, msg);
389    return;
390  }
391
392  /* create the zwrite and send the message */
393  owl_zwrite_create_from_line(&z, line);
394  owl_zwrite_populate_zsig(&z);
395  if (msg) {
396    owl_zwrite_set_message(&z, msg);
397  }
398  owl_zwrite_send_message(&z);
399  owl_function_makemsg("Waiting for ack...");
400
401  /* If it's personal */
402  if (owl_zwrite_is_personal(&z)) {
403    /* create the outgoing message */
404    mymsg=owl_zwrite_get_message(&z);
405    m=owl_function_make_outgoing_zephyr(mymsg, line, owl_zwrite_get_zsig(&z));
406
407    if (m) {
408      owl_global_messagequeue_addmsg(&g, m);
409    } else {
410      owl_function_error("Could not create outgoing zephyr message");
411    }
412  }
413
414  /* free the zwrite */
415  owl_zwrite_free(&z);
416}
417
418/* send, log and display an outgoing zcrypt zephyr.  If 'msg' is NULL
419 * the message is expected to be set from the zwrite line itself
420 */
421void owl_function_zcrypt(const char *line, const char *msg)
422{
423  owl_zwrite z;
424  const char *mymsg;
425  char *cryptmsg;
426  owl_message *m;
427#ifdef OWL_ENABLE_ZCRYPT
428  int ret;
429#endif
430
431  /* create the zwrite and send the message */
432  owl_zwrite_create_from_line(&z, line);
433  owl_zwrite_populate_zsig(&z);
434  if (msg) {
435    owl_zwrite_set_message(&z, msg);
436  }
437
438  mymsg=owl_zwrite_get_message(&z);
439#ifdef OWL_ENABLE_ZCRYPT
440  /* Allocate enough space for the crypted message. For each byte of
441   * the message, the encoded cyphertext will have two bytes. Block
442   * size is 8 bytes of input, or 16 bytes of output, so make sure we
443   * have at least one block worth of space allocated. If the message
444   * is empty, no blocks are sent, but we still allocate one
445   * block. The additional 16 bytes also provide space for the null
446   * terminator, as we will never use all of it for cyphertext.
447   */
448  cryptmsg=owl_malloc((strlen(mymsg)*2)+16);
449  ret=owl_zcrypt_encrypt(cryptmsg, mymsg, owl_zwrite_get_class(&z), owl_zwrite_get_instance(&z));
450  if (ret) {
451    owl_function_error("Error in zcrypt, possibly no key found.  Message not sent.");
452    owl_function_beep();
453    owl_free(cryptmsg);
454    owl_zwrite_free(&z);
455    return;
456  }
457#else
458  cryptmsg=owl_strdup(mymsg);
459#endif
460
461  owl_zwrite_set_message(&z, cryptmsg);
462  owl_zwrite_set_opcode(&z, "crypt");
463   
464  owl_zwrite_send_message(&z);
465  owl_function_makemsg("Waiting for ack...");
466
467  /* If it's personal */
468  if (owl_zwrite_is_personal(&z)) {
469    /* create the outgoing message */
470    mymsg=owl_zwrite_get_message(&z);
471    m=owl_function_make_outgoing_zephyr(mymsg, line, owl_zwrite_get_zsig(&z));
472    if (m) {
473      owl_global_messagequeue_addmsg(&g, m);
474    } else {
475      owl_function_error("Could not create outgoing zephyr message");
476    }
477  }
478
479  /* free the zwrite */
480  owl_free(cryptmsg);
481  owl_zwrite_free(&z);
482}
483
484void owl_callback_aimwrite(owl_editwin *e) {
485  owl_function_aimwrite(owl_editwin_get_command(e),
486                        owl_editwin_get_text(e));
487}
488
489void owl_function_aimwrite(const char *line, const char *msg)
490{
491  int ret;
492  const char *to;
493  char *format_msg;
494  owl_message *m;
495
496  to = line + 9;
497
498  /* make a formatted copy of the message */
499  format_msg=owl_strdup(msg);
500  owl_text_wordunwrap(format_msg);
501 
502  /* send the message */
503  ret=owl_aim_send_im(to, format_msg);
504  if (!ret) {
505    owl_function_makemsg("AIM message sent.");
506  } else {
507    owl_function_error("Could not send AIM message.");
508  }
509
510  /* create the outgoing message */
511  m=owl_function_make_outgoing_aim(msg, to);
512
513  if (m) {
514    owl_global_messagequeue_addmsg(&g, m);
515  } else {
516    owl_function_error("Could not create outgoing AIM message");
517  }
518
519  owl_free(format_msg);
520}
521
522void owl_function_send_aimawymsg(const char *to, const char *msg)
523{
524  int ret;
525  char *format_msg;
526  owl_message *m;
527
528  /* make a formatted copy of the message */
529  format_msg=owl_strdup(msg);
530  owl_text_wordunwrap(format_msg);
531 
532  /* send the message */
533  ret=owl_aim_send_awaymsg(to, format_msg);
534  if (!ret) {
535    /* owl_function_makemsg("AIM message sent."); */
536  } else {
537    owl_function_error("Could not send AIM message.");
538  }
539
540  /* create the message */
541  m=owl_function_make_outgoing_aim(msg, to);
542  if (m) {
543    owl_global_messagequeue_addmsg(&g, m);
544  } else {
545    owl_function_error("Could not create AIM message");
546  }
547  owl_free(format_msg);
548}
549
550void owl_callback_loopwrite(owl_editwin *e) {
551  owl_function_loopwrite(owl_editwin_get_text(e));
552}
553
554void owl_function_loopwrite(const char *msg)
555{
556  owl_message *min, *mout;
557
558  /* create a message and put it on the message queue.  This simulates
559   * an incoming message */
560  min=owl_malloc(sizeof(owl_message));
561  mout=owl_function_make_outgoing_loopback(msg);
562
563  if (owl_global_is_displayoutgoing(&g)) {
564    owl_global_messagequeue_addmsg(&g, mout);
565  } else {
566    owl_message_free(mout);
567  }
568
569  owl_message_create_loopback(min, msg);
570  owl_message_set_direction_in(min);
571  owl_global_messagequeue_addmsg(&g, min);
572
573  /* fake a makemsg */
574  owl_function_makemsg("loopback message sent");
575}
576
577/* If filter is non-null, looks for the next message matching
578 * that filter.  If skip_deleted, skips any deleted messages.
579 * If last_if_none, will stop at the last message in the view
580 * if no matching messages are found.  */
581void owl_function_nextmsg_full(const char *filter, int skip_deleted, int last_if_none)
582{
583  int curmsg, i, viewsize, found;
584  const owl_view *v;
585  const owl_filter *f = NULL;
586  const owl_message *m;
587
588  v=owl_global_get_current_view(&g);
589
590  if (filter) {
591    f=owl_global_get_filter(&g, filter);
592    if (!f) {
593      owl_function_error("No %s filter defined", filter);
594      return;
595    }
596  }
597
598  curmsg=owl_global_get_curmsg(&g);
599  viewsize=owl_view_get_size(v);
600  found=0;
601
602  /* just check to make sure we're in bounds... */
603  if (curmsg>viewsize-1) curmsg=viewsize-1;
604  if (curmsg<0) curmsg=0;
605
606  for (i=curmsg+1; i<viewsize; i++) {
607    m=owl_view_get_element(v, i);
608    if (skip_deleted && owl_message_is_delete(m)) continue;
609    if (f && !owl_filter_message_match(f, m)) continue;
610    found = 1;
611    break;
612  }
613
614  if (i>owl_view_get_size(v)-1) i=owl_view_get_size(v)-1;
615  if (i<0) i=0;
616
617  if (!found) {
618    owl_function_makemsg("already at last%s message%s%s%s",
619                         skip_deleted?" non-deleted":"",
620                         filter?" in ":"", filter?filter:"",
621                         owl_mainwin_is_curmsg_truncated(owl_global_get_mainwin(&g)) ?
622                         ", press Enter to scroll" : "");
623    /* if (!skip_deleted) owl_function_beep(); */
624  }
625
626  if (last_if_none || found) {
627    owl_global_set_curmsg(&g, i);
628    owl_function_calculate_topmsg(OWL_DIRECTION_DOWNWARDS);
629    owl_mainwin_redisplay(owl_global_get_mainwin(&g));
630    owl_global_set_direction_downwards(&g);
631  }
632}
633
634void owl_function_prevmsg_full(const char *filter, int skip_deleted, int first_if_none)
635{
636  int curmsg, i, found;
637  const owl_view *v;
638  const owl_filter *f = NULL;
639  const owl_message *m;
640
641  v=owl_global_get_current_view(&g);
642
643  if (filter) {
644    f=owl_global_get_filter(&g, filter);
645    if (!f) {
646      owl_function_error("No %s filter defined", filter);
647      return;
648    }
649  }
650
651  curmsg=owl_global_get_curmsg(&g);
652  found=0;
653
654  /* just check to make sure we're in bounds... */
655  if (curmsg<0) curmsg=0;
656
657  for (i=curmsg-1; i>=0; i--) {
658    m=owl_view_get_element(v, i);
659    if (skip_deleted && owl_message_is_delete(m)) continue;
660    if (f && !owl_filter_message_match(f, m)) continue;
661    found = 1;
662    break;
663  }
664
665  if (i<0) i=0;
666
667  if (!found) {
668    owl_function_makemsg("already at first%s message%s%s",
669                         skip_deleted?" non-deleted":"",
670                         filter?" in ":"", filter?filter:"");
671    /* if (!skip_deleted) owl_function_beep(); */
672  }
673
674  if (first_if_none || found) {
675    owl_global_set_curmsg(&g, i);
676    owl_function_calculate_topmsg(OWL_DIRECTION_UPWARDS);
677    owl_mainwin_redisplay(owl_global_get_mainwin(&g));
678    owl_global_set_direction_upwards(&g);
679  }
680}
681
682void owl_function_nextmsg(void)
683{
684  owl_function_nextmsg_full(NULL, 0, 1);
685}
686
687void owl_function_prevmsg(void)
688{
689  owl_function_prevmsg_full(NULL, 0, 1);
690}
691
692void owl_function_nextmsg_notdeleted(void)
693{
694  owl_function_nextmsg_full(NULL, 1, 1);
695}
696
697void owl_function_prevmsg_notdeleted(void)
698{
699  owl_function_prevmsg_full(NULL, 1, 1);
700}
701
702/* if move_after is 1, moves after the delete */
703void owl_function_deletecur(int move_after)
704{
705  int curmsg;
706  owl_view *v;
707
708  v=owl_global_get_current_view(&g);
709
710  /* bail if there's no current message */
711  if (owl_view_get_size(v) < 1) {
712    owl_function_error("No current message to delete");
713    return;
714  }
715
716  /* mark the message for deletion */
717  curmsg=owl_global_get_curmsg(&g);
718  owl_view_delete_element(v, curmsg);
719
720  if (move_after) {
721    /* move the poiner in the appropriate direction
722     * to the next undeleted msg */
723    if (owl_global_get_direction(&g)==OWL_DIRECTION_UPWARDS) {
724      owl_function_prevmsg_notdeleted();
725    } else {
726      owl_function_nextmsg_notdeleted();
727    }
728  }
729}
730
731void owl_function_undeletecur(int move_after)
732{
733  int curmsg;
734  owl_view *v;
735
736  v=owl_global_get_current_view(&g);
737 
738  if (owl_view_get_size(v) < 1) {
739    owl_function_error("No current message to undelete");
740    return;
741  }
742  curmsg=owl_global_get_curmsg(&g);
743
744  owl_view_undelete_element(v, curmsg);
745
746  if (move_after) {
747    if (owl_global_get_direction(&g)==OWL_DIRECTION_UPWARDS) {
748      if (curmsg>0) {
749        owl_function_prevmsg();
750      } else {
751        owl_function_nextmsg();
752      }
753    } else {
754      owl_function_nextmsg();
755    }
756  }
757
758  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
759}
760
761void owl_function_expunge(void)
762{
763  int curmsg;
764  const owl_message *m;
765  owl_messagelist *ml;
766  owl_view *v;
767  int lastmsgid=0;
768
769  curmsg=owl_global_get_curmsg(&g);
770  v=owl_global_get_current_view(&g);
771  ml=owl_global_get_msglist(&g);
772
773  m=owl_view_get_element(v, curmsg);
774  if (m) lastmsgid = owl_message_get_id(m);
775
776  /* expunge the message list */
777  owl_messagelist_expunge(ml);
778
779  /* update all views (we only have one right now) */
780  owl_view_recalculate(v);
781
782  /* find where the new position should be
783     (as close as possible to where we last where) */
784  curmsg = owl_view_get_nearest_to_msgid(v, lastmsgid);
785  if (curmsg>owl_view_get_size(v)-1) curmsg = owl_view_get_size(v)-1;
786  if (curmsg<0) curmsg = 0;
787  owl_global_set_curmsg(&g, curmsg);
788  owl_function_calculate_topmsg(OWL_DIRECTION_NONE);
789  /* if there are no messages set the direction to down in case we
790     delete everything upwards */
791  owl_global_set_direction_downwards(&g);
792 
793  owl_function_makemsg("Messages expunged");
794  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
795}
796
797void owl_function_firstmsg(void)
798{
799  owl_global_set_curmsg(&g, 0);
800  owl_global_set_topmsg(&g, 0);
801  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
802  owl_global_set_direction_downwards(&g);
803}
804
805void owl_function_lastmsg_noredisplay(void)
806{
807  int oldcurmsg, curmsg;
808  const owl_view *v;
809
810  v=owl_global_get_current_view(&g);
811  oldcurmsg=owl_global_get_curmsg(&g);
812  curmsg=owl_view_get_size(v)-1; 
813  if (curmsg<0) curmsg=0;
814  owl_global_set_curmsg(&g, curmsg);
815  if (oldcurmsg < curmsg) {
816    owl_function_calculate_topmsg(OWL_DIRECTION_DOWNWARDS);
817  } else if (curmsg<owl_view_get_size(v)) {
818    /* If already at the end, blank the screen and move curmsg
819     * past the end of the messages. */
820    owl_global_set_topmsg(&g, curmsg+1);
821    owl_global_set_curmsg(&g, curmsg+1);
822  } 
823  /* owl_mainwin_redisplay(owl_global_get_mainwin(&g)); */
824  owl_global_set_direction_downwards(&g);
825}
826
827void owl_function_lastmsg(void)
828{
829  owl_function_lastmsg_noredisplay();
830  owl_mainwin_redisplay(owl_global_get_mainwin(&g)); 
831}
832
833void owl_function_shift_right(void)
834{
835  owl_global_set_rightshift(&g, owl_global_get_rightshift(&g)+10);
836  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
837  owl_global_set_needrefresh(&g);
838}
839
840void owl_function_shift_left(void)
841{
842  int shift;
843
844  shift=owl_global_get_rightshift(&g);
845  if (shift>=10) {
846    owl_global_set_rightshift(&g, shift-10);
847    owl_mainwin_redisplay(owl_global_get_mainwin(&g));
848    owl_global_set_needrefresh(&g);
849  } else {
850    owl_function_beep();
851    owl_function_makemsg("Already full left");
852  }
853}
854
855void owl_function_unsuball(void)
856{
857  unsuball();
858  owl_function_makemsg("Unsubscribed from all messages.");
859}
860
861
862/* Load zephyr subscriptions from the named 'file' and load zephyr's
863 * default subscriptions as well.  An error message is printed if
864 * 'file' can't be opened or if zephyr reports an error in
865 * subscribing.
866 *
867 * If 'file' is NULL, this look for the default filename
868 * $HOME/.zephyr.subs.  If the file can not be opened in this case
869 * only, no error message is printed.
870 */
871void owl_function_loadsubs(const char *file)
872{
873  int ret, ret2;
874  const char *foo;
875  char *path;
876
877  if (file==NULL) {
878    ret=owl_zephyr_loadsubs(NULL, 0);
879  } else {
880    path = owl_util_makepath(file);
881    ret=owl_zephyr_loadsubs(path, 1);
882    owl_free(path);
883  }
884
885  /* for backwards compatibility for now */
886  ret2=owl_zephyr_loaddefaultsubs();
887
888  if (!owl_context_is_interactive(owl_global_get_context(&g))) return;
889
890  foo=file?file:"file";
891  if (ret==0 && ret2==0) {
892    if (!file) {
893      owl_function_makemsg("Subscribed to messages.");
894    } else {
895      owl_function_makemsg("Subscribed to messages from %s", file);
896    }
897  } else if (ret==-1) {
898    owl_function_error("Could not read %s", foo);
899  } else {
900    owl_function_error("Error subscribing to messages");
901  }
902}
903
904void owl_function_loadloginsubs(const char *file)
905{
906  int ret;
907
908  ret=owl_zephyr_loadloginsubs(file);
909
910  if (!owl_context_is_interactive(owl_global_get_context(&g))) return;
911  if (ret==0) {
912  } else if (ret==-1) {
913    owl_function_error("Could not open file for login subscriptions.");
914  } else {
915    owl_function_error("Error subscribing to login messages from file.");
916  }
917}
918
919void owl_callback_aimlogin(owl_editwin *e) {
920  owl_function_aimlogin(owl_editwin_get_command(e),
921                        owl_editwin_get_text(e));
922}
923
924void owl_function_aimlogin(const char *user, const char *passwd) {
925  int ret;
926
927  /* clear the buddylist */
928  owl_buddylist_clear(owl_global_get_buddylist(&g));
929
930  /* try to login */
931  ret=owl_aim_login(user, passwd);
932  if (ret) owl_function_makemsg("Warning: login for %s failed.\n", user);
933}
934
935void owl_function_suspend(void)
936{
937  endwin();
938  printf("\n");
939  kill(getpid(), SIGSTOP);
940
941  /* resize to reinitialize all the windows when we come back */
942  owl_command_resize();
943}
944
945void owl_function_zaway_toggle(void)
946{
947  if (!owl_global_is_zaway(&g)) {
948    owl_global_set_zaway_msg(&g, owl_global_get_zaway_msg_default(&g));
949    owl_function_zaway_on();
950  } else {
951    owl_function_zaway_off();
952  }
953}
954
955void owl_function_zaway_on(void)
956{
957  owl_global_set_zaway_on(&g);
958  owl_function_makemsg("zaway set (%s)", owl_global_get_zaway_msg(&g));
959}
960
961void owl_function_zaway_off(void)
962{
963  owl_global_set_zaway_off(&g);
964  owl_function_makemsg("zaway off");
965}
966
967void owl_function_aaway_toggle(void)
968{
969  if (!owl_global_is_aaway(&g)) {
970    owl_global_set_aaway_msg(&g, owl_global_get_aaway_msg_default(&g));
971    owl_function_aaway_on();
972  } else {
973    owl_function_aaway_off();
974  }
975}
976
977void owl_function_aaway_on(void)
978{
979  owl_global_set_aaway_on(&g);
980  /* owl_aim_set_awaymsg(owl_global_get_zaway_msg(&g)); */
981  owl_function_makemsg("AIM away set (%s)", owl_global_get_aaway_msg(&g));
982}
983
984void owl_function_aaway_off(void)
985{
986  owl_global_set_aaway_off(&g);
987  /* owl_aim_set_awaymsg(""); */
988  owl_function_makemsg("AIM away off");
989}
990
991void owl_function_quit(void)
992{
993  char *ret;
994 
995  /* zlog out if we need to */
996  if (owl_global_is_havezephyr(&g) &&
997      owl_global_is_shutdownlogout(&g)) {
998    owl_zephyr_zlog_out();
999  }
1000
1001  /* execute the commands in shutdown */
1002  ret = owl_perlconfig_execute("BarnOwl::Hooks::_shutdown();");
1003  if (ret) owl_free(ret);
1004
1005  /* signal our child process, if any */
1006  if (owl_global_get_newmsgproc_pid(&g)) {
1007    kill(owl_global_get_newmsgproc_pid(&g), SIGHUP);
1008  }
1009
1010  /* Quit zephyr */
1011  owl_zephyr_shutdown();
1012 
1013  /* Quit AIM */
1014  if (owl_global_is_aimloggedin(&g)) {
1015    owl_aim_logout();
1016  }
1017
1018  /* done with curses */
1019  endwin();
1020
1021  /* restore terminal settings */
1022  tcsetattr(0, TCSAFLUSH, owl_global_get_startup_tio(&g));
1023
1024  owl_function_debugmsg("Quitting Owl");
1025  exit(0);
1026}
1027
1028void owl_function_calculate_topmsg(int direction)
1029{
1030  int recwinlines, topmsg, curmsg;
1031  const owl_view *v;
1032
1033  v=owl_global_get_current_view(&g);
1034  curmsg=owl_global_get_curmsg(&g);
1035  topmsg=owl_global_get_topmsg(&g);
1036  recwinlines=owl_global_get_recwin_lines(&g);
1037
1038  /*
1039  if (owl_view_get_size(v) < 1) {
1040    return;
1041  }
1042  */
1043
1044  switch (owl_global_get_scrollmode(&g)) {
1045  case OWL_SCROLLMODE_TOP:
1046    topmsg = owl_function_calculate_topmsg_top(direction, v, curmsg, topmsg, recwinlines);
1047    break;
1048  case OWL_SCROLLMODE_NEARTOP:
1049    topmsg = owl_function_calculate_topmsg_neartop(direction, v, curmsg, topmsg, recwinlines);
1050    break;
1051  case OWL_SCROLLMODE_CENTER:
1052    topmsg = owl_function_calculate_topmsg_center(direction, v, curmsg, topmsg, recwinlines);
1053    break;
1054  case OWL_SCROLLMODE_PAGED:
1055    topmsg = owl_function_calculate_topmsg_paged(direction, v, curmsg, topmsg, recwinlines, 0);
1056    break;
1057  case OWL_SCROLLMODE_PAGEDCENTER:
1058    topmsg = owl_function_calculate_topmsg_paged(direction, v, curmsg, topmsg, recwinlines, 1);
1059    break;
1060  case OWL_SCROLLMODE_NORMAL:
1061  default:
1062    topmsg = owl_function_calculate_topmsg_normal(direction, v, curmsg, topmsg, recwinlines);
1063  }
1064  owl_function_debugmsg("Calculated a topmsg of %i", topmsg);
1065  owl_global_set_topmsg(&g, topmsg);
1066}
1067
1068/* Returns what the new topmsg should be. 
1069 * Passed the last direction of movement,
1070 * the current view,
1071 * the current message number in the view,
1072 * the top message currently being displayed,
1073 * and the number of lines in the recwin.
1074 */
1075int owl_function_calculate_topmsg_top(int direction, const owl_view *v, int curmsg, int topmsg, int recwinlines)
1076{
1077  return(curmsg);
1078}
1079
1080int owl_function_calculate_topmsg_neartop(int direction, const owl_view *v, int curmsg, int topmsg, int recwinlines)
1081{
1082  if (curmsg>0 
1083      && (owl_message_get_numlines(owl_view_get_element(v, curmsg-1))
1084          <  recwinlines/2)) {
1085    return(curmsg-1);
1086  } else {
1087    return(curmsg);
1088  }
1089}
1090 
1091int owl_function_calculate_topmsg_center(int direction, const owl_view *v, int curmsg, int topmsg, int recwinlines)
1092{
1093  int i, last, lines;
1094
1095  last = curmsg;
1096  lines = 0;
1097  for (i=curmsg-1; i>=0; i--) {
1098    lines += owl_message_get_numlines(owl_view_get_element(v, i));
1099    if (lines > recwinlines/2) break;
1100    last = i;
1101  }
1102  return(last);
1103}
1104 
1105int owl_function_calculate_topmsg_paged(int direction, const owl_view *v, int curmsg, int topmsg, int recwinlines, int center_on_page)
1106{
1107  int i, last, lines, savey;
1108 
1109  /* If we're off the top of the screen, scroll up such that the
1110   * curmsg is near the botton of the screen. */
1111  if (curmsg < topmsg) {
1112    last = curmsg;
1113    lines = 0;
1114    for (i=curmsg; i>=0; i--) {
1115      lines += owl_message_get_numlines(owl_view_get_element(v, i));
1116      if (lines > recwinlines) break;
1117    last = i;
1118    }
1119    if (center_on_page) {
1120      return(owl_function_calculate_topmsg_center(direction, v, curmsg, 0, recwinlines));
1121    } else {
1122      return(last);
1123    }
1124  }
1125
1126  /* Find number of lines from top to bottom of curmsg (store in savey) */
1127  savey=0;
1128  for (i=topmsg; i<=curmsg; i++) {
1129    savey+=owl_message_get_numlines(owl_view_get_element(v, i));
1130  }
1131
1132  /* if we're off the bottom of the screen, scroll down */
1133  if (savey > recwinlines) {
1134    if (center_on_page) {
1135      return(owl_function_calculate_topmsg_center(direction, v, curmsg, 0, recwinlines));
1136    } else {
1137      return(curmsg);
1138    }
1139  }
1140
1141  /* else just stay as we are... */
1142  return(topmsg);
1143}
1144
1145int owl_function_calculate_topmsg_normal(int direction, const owl_view *v, int curmsg, int topmsg, int recwinlines)
1146{
1147  int savey, i, foo, y;
1148
1149  if (curmsg<0) return(topmsg);
1150   
1151  /* If we're off the top of the screen then center */
1152  if (curmsg<topmsg) {
1153    topmsg=owl_function_calculate_topmsg_center(direction, v, curmsg, 0, recwinlines);
1154  }
1155
1156  /* If curmsg is so far past topmsg that there are more messages than
1157     lines, skip the line counting that follows because we're
1158     certainly off screen.  */
1159  savey=curmsg-topmsg;
1160  if (savey <= recwinlines) {
1161    /* Find number of lines from top to bottom of curmsg (store in savey) */
1162    savey = 0;
1163    for (i=topmsg; i<=curmsg; i++) {
1164      savey+=owl_message_get_numlines(owl_view_get_element(v, i));
1165    }
1166  }
1167
1168  /* If we're off the bottom of the screen, set the topmsg to curmsg
1169   * and scroll upwards */
1170  if (savey > recwinlines) {
1171    topmsg=curmsg;
1172    savey=owl_message_get_numlines(owl_view_get_element(v, curmsg));
1173    direction=OWL_DIRECTION_UPWARDS;
1174  }
1175 
1176  /* If our bottom line is less than 1/4 down the screen then scroll up */
1177  if (direction == OWL_DIRECTION_UPWARDS || direction == OWL_DIRECTION_NONE) {
1178    if (savey < (recwinlines / 4)) {
1179      y=0;
1180      for (i=curmsg; i>=0; i--) {
1181        foo=owl_message_get_numlines(owl_view_get_element(v, i));
1182        /* will we run the curmsg off the screen? */
1183        if ((foo+y) >= recwinlines) {
1184          i++;
1185          if (i>curmsg) i=curmsg;
1186          break;
1187        }
1188        /* have saved 1/2 the screen space? */
1189        y+=foo;
1190        if (y > (recwinlines / 2)) break;
1191      }
1192      if (i<0) i=0;
1193      return(i);
1194    }
1195  }
1196
1197  if (direction == OWL_DIRECTION_DOWNWARDS || direction == OWL_DIRECTION_NONE) {
1198    /* If curmsg bottom line is more than 3/4 down the screen then scroll down */
1199    if (savey > ((recwinlines * 3)/4)) {
1200      y=0;
1201      /* count lines from the top until we can save 1/2 the screen size */
1202      for (i=topmsg; i<curmsg; i++) {
1203        y+=owl_message_get_numlines(owl_view_get_element(v, i));
1204        if (y > (recwinlines / 2)) break;
1205      }
1206      if (i==curmsg) {
1207        i--;
1208      }
1209      return(i+1);
1210    }
1211  }
1212
1213  return(topmsg);
1214}
1215
1216void owl_function_resize(void)
1217{
1218  owl_global_set_resize_pending(&g);
1219}
1220
1221void owl_function_run_buffercommand(void)
1222{
1223  owl_editwin_do_callback(owl_global_get_typwin(&g));
1224}
1225
1226void owl_function_debugmsg(const char *fmt, ...)
1227{
1228  FILE *file;
1229  time_t now;
1230  va_list ap;
1231  va_start(ap, fmt);
1232
1233  if (!owl_global_is_debug_fast(&g))
1234    return;
1235
1236  file = fopen(owl_global_get_debug_file(&g), "a");
1237  if (!file) /* XXX should report this */
1238    return;
1239
1240  now = time(NULL);
1241
1242  fprintf(file, "[%d -  %.24s - %lds]: ",
1243          (int) getpid(), ctime(&now), now - owl_global_get_starttime(&g));
1244  vfprintf(file, fmt, ap);
1245  putc('\n', file);
1246  fclose(file);
1247
1248  va_end(ap);
1249}
1250
1251void owl_function_beep(void)
1252{
1253  if (owl_global_is_bell(&g)) {
1254    beep();
1255    owl_global_set_needrefresh(&g); /* do we really need this? */
1256  }
1257}
1258
1259int owl_function_subscribe(const char *class, const char *inst, const char *recip)
1260{
1261  int ret;
1262
1263  ret=owl_zephyr_sub(class, inst, recip);
1264  if (ret) {
1265    owl_function_error("Error subscribing.");
1266  } else {
1267    owl_function_makemsg("Subscribed.");
1268  }
1269  return(ret);
1270}
1271
1272void owl_function_unsubscribe(const char *class, const char *inst, const char *recip)
1273{
1274  int ret;
1275
1276  ret=owl_zephyr_unsub(class, inst, recip);
1277  if (ret) {
1278    owl_function_error("Error subscribing.");
1279  } else {
1280    owl_function_makemsg("Unsubscribed.");
1281  }
1282}
1283
1284void owl_function_set_cursor(WINDOW *win)
1285{
1286  wnoutrefresh(win);
1287}
1288
1289void owl_function_full_redisplay(void)
1290{
1291  redrawwin(owl_global_get_curs_recwin(&g));
1292  redrawwin(owl_global_get_curs_sepwin(&g));
1293  /* Work around curses segfualts with windows off the screen */
1294  if (g.lines >= owl_global_get_typwin_lines(&g)+2)
1295      redrawwin(owl_global_get_curs_typwin(&g));
1296  if (g.lines >= 2)
1297      redrawwin(owl_global_get_curs_msgwin(&g));
1298
1299  wnoutrefresh(owl_global_get_curs_recwin(&g));
1300  wnoutrefresh(owl_global_get_curs_sepwin(&g));
1301  wnoutrefresh(owl_global_get_curs_typwin(&g));
1302  wnoutrefresh(owl_global_get_curs_msgwin(&g));
1303
1304  if (owl_popwin_is_active(owl_global_get_popwin(&g))) {
1305    owl_popwin_refresh(owl_global_get_popwin(&g));
1306  }
1307 
1308  sepbar("");
1309  owl_function_makemsg("");
1310
1311  owl_global_set_needrefresh(&g);
1312}
1313
1314void owl_function_popless_text(const char *text)
1315{
1316  owl_popwin *pw;
1317  owl_viewwin *v;
1318
1319  pw=owl_global_get_popwin(&g);
1320  v=owl_global_get_viewwin(&g);
1321
1322  owl_popwin_up(pw);
1323  owl_viewwin_init_text(v, owl_popwin_get_curswin(pw),
1324                        owl_popwin_get_lines(pw), owl_popwin_get_cols(pw),
1325                        text);
1326  owl_popwin_refresh(pw);
1327  owl_viewwin_redisplay(v, 0);
1328  owl_global_set_needrefresh(&g);
1329}
1330
1331void owl_function_popless_fmtext(const owl_fmtext *fm)
1332{
1333  owl_popwin *pw;
1334  owl_viewwin *v;
1335
1336  pw=owl_global_get_popwin(&g);
1337  v=owl_global_get_viewwin(&g);
1338
1339  owl_popwin_up(pw);
1340  owl_viewwin_init_fmtext(v, owl_popwin_get_curswin(pw),
1341                   owl_popwin_get_lines(pw), owl_popwin_get_cols(pw),
1342                   fm);
1343  owl_popwin_refresh(pw);
1344  owl_viewwin_redisplay(v, 0);
1345  owl_global_set_needrefresh(&g);
1346}
1347
1348void owl_function_popless_file(const char *filename)
1349{
1350  owl_fmtext fm;
1351  FILE *file;
1352  char *s = NULL;
1353
1354  file=fopen(filename, "r");
1355  if (!file) {
1356    owl_function_error("Could not open file: %s", filename);
1357    return;
1358  }
1359
1360  owl_fmtext_init_null(&fm);
1361  while (owl_getline(&s, file))
1362    owl_fmtext_append_normal(&fm, s);
1363  owl_free(s);
1364
1365  owl_function_popless_fmtext(&fm);
1366  owl_fmtext_free(&fm);
1367  fclose(file);
1368}
1369
1370void owl_function_about(void)
1371{
1372  owl_function_popless_text(
1373    "This is barnowl version " OWL_VERSION_STRING ".\n\n"
1374    "barnowl is a fork of the Owl zephyr client, written and\n"
1375    "maintained by Alejandro Sedeno and Nelson Elhage at the\n"
1376    "Massachusetts Institute of Technology. \n"
1377    "\n"
1378    "Owl was written by James Kretchmar. The first version, 0.5, was\n"
1379    "released in March 2002.\n"
1380    "\n"
1381    "The name 'owl' was chosen in reference to the owls in the\n"
1382    "Harry Potter novels, who are tasked with carrying messages\n"
1383    "between Witches and Wizards. The name 'barnowl' was chosen\n"
1384    "because we feel our owls should live closer to our ponies.\n"
1385    "\n"
1386    "Copyright (c) 2006-2009 The BarnOwl Developers. All rights reserved.\n"
1387    "Copyright (c) 2004 James Kretchmar. All rights reserved.\n"
1388    "Copyright 2002 Massachusetts Institute of Technology\n"
1389    "\n"
1390    "This program is free software. You can redistribute it and/or\n"
1391    "modify under the terms of the Sleepycat License. Use the \n"
1392    "':show license' command to display the full license\n"
1393  );
1394}
1395
1396void owl_function_info(void)
1397{
1398  const owl_message *m;
1399  owl_fmtext fm, attrfm;
1400  const owl_view *v;
1401#ifdef HAVE_LIBZEPHYR
1402  const ZNotice_t *n;
1403#endif
1404
1405  owl_fmtext_init_null(&fm);
1406 
1407  v=owl_global_get_current_view(&g);
1408  m=owl_view_get_element(v, owl_global_get_curmsg(&g));
1409  if (!m || owl_view_get_size(v)==0) {
1410    owl_function_error("No message selected\n");
1411    return;
1412  }
1413
1414  owl_fmtext_append_bold(&fm, "General Information:\n");
1415  owl_fmtext_appendf_normal(&fm, "  Msg Id    : %i\n", owl_message_get_id(m));
1416
1417  owl_fmtext_append_normal(&fm, "  Type      : ");
1418  owl_fmtext_append_bold(&fm, owl_message_get_type(m));
1419  owl_fmtext_append_normal(&fm, "\n");
1420
1421  if (owl_message_is_direction_in(m)) {
1422    owl_fmtext_append_normal(&fm, "  Direction : in\n");
1423  } else if (owl_message_is_direction_out(m)) {
1424    owl_fmtext_append_normal(&fm, "  Direction : out\n");
1425  } else if (owl_message_is_direction_none(m)) {
1426    owl_fmtext_append_normal(&fm, "  Direction : none\n");
1427  } else {
1428    owl_fmtext_append_normal(&fm, "  Direction : unknown\n");
1429  }
1430
1431  owl_fmtext_appendf_normal(&fm, "  Time      : %s\n", owl_message_get_timestr(m));
1432
1433  if (!owl_message_is_type_admin(m)) {
1434    owl_fmtext_appendf_normal(&fm, "  Sender    : %s\n", owl_message_get_sender(m));
1435    owl_fmtext_appendf_normal(&fm, "  Recipient : %s\n", owl_message_get_recipient(m));
1436  }
1437
1438  if (owl_message_is_type_zephyr(m)) {
1439    owl_fmtext_append_bold(&fm, "\nZephyr Specific Information:\n");
1440   
1441    owl_fmtext_appendf_normal(&fm, "  Class     : %s\n", owl_message_get_class(m));
1442    owl_fmtext_appendf_normal(&fm, "  Instance  : %s\n", owl_message_get_instance(m));
1443    owl_fmtext_appendf_normal(&fm, "  Opcode    : %s\n", owl_message_get_opcode(m));
1444#ifdef HAVE_LIBZEPHYR
1445    if (owl_message_is_direction_in(m)) {
1446      char *ptr, tmpbuff[1024];
1447      int i, j, fields, len;
1448
1449      n=owl_message_get_notice(m);
1450
1451      if (!owl_message_is_pseudo(m)) {
1452        owl_fmtext_append_normal(&fm, "  Kind      : ");
1453        if (n->z_kind==UNSAFE) {
1454          owl_fmtext_append_normal(&fm, "UNSAFE\n");
1455        } else if (n->z_kind==UNACKED) {
1456          owl_fmtext_append_normal(&fm, "UNACKED\n");
1457        } else if (n->z_kind==ACKED) {
1458          owl_fmtext_append_normal(&fm, "ACKED\n");
1459        } else if (n->z_kind==HMACK) {
1460          owl_fmtext_append_normal(&fm, "HMACK\n");
1461        } else if (n->z_kind==HMCTL) {
1462          owl_fmtext_append_normal(&fm, "HMCTL\n");
1463        } else if (n->z_kind==SERVACK) {
1464          owl_fmtext_append_normal(&fm, "SERVACK\n");
1465        } else if (n->z_kind==SERVNAK) {
1466          owl_fmtext_append_normal(&fm, "SERVNACK\n");
1467        } else if (n->z_kind==CLIENTACK) {
1468          owl_fmtext_append_normal(&fm, "CLIENTACK\n");
1469        } else if (n->z_kind==STAT) {
1470          owl_fmtext_append_normal(&fm, "STAT\n");
1471        } else {
1472          owl_fmtext_append_normal(&fm, "ILLEGAL VALUE\n");
1473        }
1474      }
1475      owl_fmtext_appendf_normal(&fm, "  Host      : %s\n", owl_message_get_hostname(m));
1476
1477      if (!owl_message_is_pseudo(m)) {
1478        owl_fmtext_append_normal(&fm, "\n");
1479        owl_fmtext_appendf_normal(&fm, "  Port      : %i\n", ntohs(n->z_port));
1480        owl_fmtext_appendf_normal(&fm, "  Auth      : %s\n", owl_zephyr_get_authstr(n));
1481
1482        /* FIXME make these more descriptive */
1483        owl_fmtext_appendf_normal(&fm, "  Checkd Ath: %i\n", n->z_checked_auth);
1484        owl_fmtext_appendf_normal(&fm, "  Multi notc: %s\n", n->z_multinotice);
1485        owl_fmtext_appendf_normal(&fm, "  Num other : %i\n", n->z_num_other_fields);
1486        owl_fmtext_appendf_normal(&fm, "  Msg Len   : %i\n", n->z_message_len);
1487
1488        fields=owl_zephyr_get_num_fields(n);
1489        owl_fmtext_appendf_normal(&fm, "  Fields    : %i\n", fields);
1490
1491        for (i=0; i<fields; i++) {
1492          ptr=owl_zephyr_get_field_as_utf8(n, i+1);
1493          len=strlen(ptr);
1494          if (len<30) {
1495            strncpy(tmpbuff, ptr, len);
1496            tmpbuff[len]='\0';
1497          } else {
1498            strncpy(tmpbuff, ptr, 30);
1499            tmpbuff[30]='\0';
1500            strcat(tmpbuff, "...");
1501          }
1502          owl_free(ptr);
1503
1504          for (j=0; j<strlen(tmpbuff); j++) {
1505            if (tmpbuff[j]=='\n') tmpbuff[j]='~';
1506            if (tmpbuff[j]=='\r') tmpbuff[j]='!';
1507          }
1508
1509          owl_fmtext_appendf_normal(&fm, "  Field %i   : %s\n", i+1, tmpbuff);
1510        }
1511        owl_fmtext_appendf_normal(&fm, "  Default Fm: %s\n", n->z_default_format);
1512      }
1513
1514    }
1515#endif
1516  }
1517
1518  owl_fmtext_append_bold(&fm, "\nOwl Message Attributes:\n");
1519  owl_message_attributes_tofmtext(m, &attrfm);
1520  owl_fmtext_append_fmtext(&fm, &attrfm);
1521 
1522  owl_function_popless_fmtext(&fm);
1523  owl_fmtext_free(&fm);
1524  owl_fmtext_free(&attrfm);
1525}
1526
1527/* print the current message in a popup window.
1528 * Use the 'default' style regardless of whatever
1529 * style the user may be using
1530 */
1531void owl_function_curmsg_to_popwin(void)
1532{
1533  const owl_view *v;
1534  const owl_message *m;
1535  const owl_style *s;
1536  owl_fmtext fm;
1537
1538  v=owl_global_get_current_view(&g);
1539  s=owl_global_get_style_by_name(&g, "default");
1540
1541  m=owl_view_get_element(v, owl_global_get_curmsg(&g));
1542
1543  if (!m || owl_view_get_size(v)==0) {
1544    owl_function_error("No current message");
1545    return;
1546  }
1547
1548  owl_fmtext_init_null(&fm);
1549  owl_style_get_formattext(s, &fm, m);
1550
1551  owl_function_popless_fmtext(&fm);
1552  owl_fmtext_free(&fm);
1553}
1554
1555void owl_function_page_curmsg(int step)
1556{
1557  /* scroll down or up within the current message IF the message is truncated */
1558
1559  int offset, curmsg, lines;
1560  const owl_view *v;
1561  owl_message *m;
1562
1563  offset=owl_global_get_curmsg_vert_offset(&g);
1564  v=owl_global_get_current_view(&g);
1565  curmsg=owl_global_get_curmsg(&g);
1566  m=owl_view_get_element(v, curmsg);
1567  if (!m || owl_view_get_size(v)==0) return;
1568  lines=owl_message_get_numlines(m);
1569
1570  if (offset==0) {
1571    /* Bail if the curmsg isn't the last one displayed */
1572    if (curmsg != owl_mainwin_get_last_msg(owl_global_get_mainwin(&g))) {
1573      owl_function_makemsg("The entire message is already displayed");
1574      return;
1575    }
1576   
1577    /* Bail if we're not truncated */
1578    if (!owl_mainwin_is_curmsg_truncated(owl_global_get_mainwin(&g))) {
1579      owl_function_makemsg("The entire message is already displayed");
1580      return;
1581    }
1582  }
1583 
1584 
1585  /* don't scroll past the last line */
1586  if (step>0) {
1587    if (offset+step > lines-1) {
1588      owl_global_set_curmsg_vert_offset(&g, lines-1);
1589    } else {
1590      owl_global_set_curmsg_vert_offset(&g, offset+step);
1591    }
1592  }
1593
1594  /* would we be before the beginning of the message? */
1595  if (step<0) {
1596    if (offset+step<0) {
1597      owl_global_set_curmsg_vert_offset(&g, 0);
1598    } else {
1599      owl_global_set_curmsg_vert_offset(&g, offset+step);
1600    }
1601  }
1602 
1603  /* redisplay */
1604  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
1605  owl_global_set_needrefresh(&g);
1606}
1607
1608void owl_function_resize_typwin(int newsize)
1609{
1610  owl_global_set_typwin_lines(&g, newsize);
1611  owl_function_resize();
1612}
1613
1614void owl_function_mainwin_pagedown(void)
1615{
1616  int i;
1617
1618  i=owl_mainwin_get_last_msg(owl_global_get_mainwin(&g));
1619  if (i<0) return;
1620  if (owl_mainwin_is_last_msg_truncated(owl_global_get_mainwin(&g))
1621      && (owl_global_get_curmsg(&g) < i)
1622      && (i>0)) {
1623    i--;
1624  }
1625  owl_global_set_curmsg(&g, i);
1626  owl_function_nextmsg();
1627}
1628
1629void owl_function_mainwin_pageup(void)
1630{
1631  owl_global_set_curmsg(&g, owl_global_get_topmsg(&g));
1632  owl_function_prevmsg();
1633}
1634
1635void owl_function_getsubs(void)
1636{
1637  char *buff;
1638
1639  buff=owl_zephyr_getsubs();
1640
1641  if (buff) {
1642    owl_function_popless_text(buff);
1643  } else {
1644    owl_function_popless_text("Error getting subscriptions");
1645  }
1646           
1647  owl_free(buff);
1648}
1649
1650void owl_function_printallvars(void)
1651{
1652  const char *name;
1653  char var[LINE];
1654  owl_list varnames;
1655  int i, numvarnames;
1656  GString *str   = g_string_new("");
1657
1658  g_string_append_printf(str, "%-20s = %s\n", "VARIABLE", "VALUE");
1659  g_string_append_printf(str, "%-20s   %s\n",  "--------", "-----");
1660  owl_variable_dict_get_names(owl_global_get_vardict(&g), &varnames);
1661  numvarnames = owl_list_get_size(&varnames);
1662  for (i=0; i<numvarnames; i++) {
1663    name = owl_list_get_element(&varnames, i);
1664    if (name && name[0]!='_') {
1665      g_string_append_printf(str, "\n%-20s = ", name);
1666      owl_variable_get_tostring(owl_global_get_vardict(&g), name, var, LINE);
1667      g_string_append(str, var);
1668    }
1669  }
1670  g_string_append(str, "\n");
1671  owl_variable_dict_namelist_free(&varnames);
1672
1673  owl_function_popless_text(str->str);
1674  g_string_free(str, TRUE);
1675}
1676
1677void owl_function_show_variables(void)
1678{
1679  owl_list varnames;
1680  owl_fmtext fm; 
1681  int i, numvarnames;
1682  const char *varname;
1683
1684  owl_fmtext_init_null(&fm);
1685  owl_fmtext_append_bold(&fm, 
1686      "Variables: (use 'show variable <name>' for details)\n");
1687  owl_variable_dict_get_names(owl_global_get_vardict(&g), &varnames);
1688  numvarnames = owl_list_get_size(&varnames);
1689  for (i=0; i<numvarnames; i++) {
1690    varname = owl_list_get_element(&varnames, i);
1691    if (varname && varname[0]!='_') {
1692      owl_variable_describe(owl_global_get_vardict(&g), varname, &fm);
1693    }
1694  }
1695  owl_variable_dict_namelist_free(&varnames);
1696  owl_function_popless_fmtext(&fm);
1697  owl_fmtext_free(&fm);
1698}
1699
1700void owl_function_show_variable(const char *name)
1701{
1702  owl_fmtext fm; 
1703
1704  owl_fmtext_init_null(&fm);
1705  owl_variable_get_help(owl_global_get_vardict(&g), name, &fm);
1706  owl_function_popless_fmtext(&fm);
1707  owl_fmtext_free(&fm); 
1708}
1709
1710/* note: this applies to global message list, not to view.
1711 * If flag is 1, deletes.  If flag is 0, undeletes. */
1712void owl_function_delete_by_id(int id, int flag)
1713{
1714  const owl_messagelist *ml;
1715  owl_message *m;
1716  ml = owl_global_get_msglist(&g);
1717  m = owl_messagelist_get_by_id(ml, id);
1718  if (m) {
1719    if (flag == 1) {
1720      owl_message_mark_delete(m);
1721    } else if (flag == 0) {
1722      owl_message_unmark_delete(m);
1723    }
1724    owl_mainwin_redisplay(owl_global_get_mainwin(&g));
1725    owl_global_set_needrefresh(&g);
1726  } else {
1727    owl_function_error("No message with id %d: unable to mark for (un)delete",id);
1728  }
1729}
1730
1731void owl_function_delete_automsgs(void)
1732{
1733  /* mark for deletion all messages in the current view that match the
1734   * 'trash' filter */
1735
1736  int i, j, count;
1737  owl_message *m;
1738  const owl_view *v;
1739  const owl_filter *f;
1740
1741  /* get the trash filter */
1742  f=owl_global_get_filter(&g, "trash");
1743  if (!f) {
1744    owl_function_error("No trash filter defined");
1745    return;
1746  }
1747
1748  v=owl_global_get_current_view(&g);
1749
1750  count=0;
1751  j=owl_view_get_size(v);
1752  for (i=0; i<j; i++) {
1753    m=owl_view_get_element(v, i);
1754    if (owl_filter_message_match(f, m)) {
1755      count++;
1756      owl_message_mark_delete(m);
1757    }
1758  }
1759  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
1760  owl_function_makemsg("%i messages marked for deletion", count);
1761  owl_global_set_needrefresh(&g);
1762}
1763
1764void owl_function_status(void)
1765{
1766  char buff[MAXPATHLEN+1];
1767  time_t start;
1768  int up, days, hours, minutes;
1769  owl_fmtext fm;
1770
1771  owl_fmtext_init_null(&fm);
1772
1773  start=owl_global_get_starttime(&g);
1774
1775  owl_fmtext_append_normal(&fm, "General Information:\n");
1776
1777  owl_fmtext_append_normal(&fm, "  Version: ");
1778  owl_fmtext_append_normal(&fm, OWL_VERSION_STRING);
1779  owl_fmtext_append_normal(&fm, "\n");
1780
1781  owl_fmtext_append_normal(&fm, "  Startup Arguments: ");
1782  owl_fmtext_append_normal(&fm, owl_global_get_startupargs(&g));
1783  owl_fmtext_append_normal(&fm, "\n");
1784
1785  owl_fmtext_append_normal(&fm, "  Current Directory: ");
1786  if(getcwd(buff, MAXPATHLEN) == NULL) {
1787    owl_fmtext_append_normal(&fm, "<Error in getcwd>");
1788  } else {
1789    owl_fmtext_append_normal(&fm, buff);
1790  }
1791  owl_fmtext_append_normal(&fm, "\n");
1792
1793  owl_fmtext_appendf_normal(&fm, "  Startup Time: %s", ctime(&start));
1794
1795  up=owl_global_get_runtime(&g);
1796  days=up/86400;
1797  up-=days*86400;
1798  hours=up/3600;
1799  up-=hours*3600;
1800  minutes=up/60;
1801  up-=minutes*60;
1802  owl_fmtext_appendf_normal(&fm, "  Run Time: %i days %2.2i:%2.2i:%2.2i\n", days, hours, minutes, up);
1803
1804  owl_fmtext_append_normal(&fm, "\nProtocol Options:\n");
1805  owl_fmtext_append_normal(&fm, "  Zephyr included    : ");
1806  if (owl_global_is_havezephyr(&g)) {
1807    owl_fmtext_append_normal(&fm, "yes\n");
1808  } else {
1809    owl_fmtext_append_normal(&fm, "no\n");
1810  }
1811  owl_fmtext_append_normal(&fm, "  AIM included       : yes\n");
1812  owl_fmtext_append_normal(&fm, "  Loopback included  : yes\n");
1813
1814
1815  owl_fmtext_append_normal(&fm, "\nBuild Options:\n");
1816  owl_fmtext_append_normal(&fm, "  Stderr redirection : ");
1817#if OWL_STDERR_REDIR
1818  owl_fmtext_append_normal(&fm, "yes\n");
1819#else
1820  owl_fmtext_append_normal(&fm, "no\n");
1821#endif
1822 
1823
1824  owl_fmtext_append_normal(&fm, "\nAIM Status:\n");
1825  owl_fmtext_append_normal(&fm, "  Logged in: ");
1826  if (owl_global_is_aimloggedin(&g)) {
1827    owl_fmtext_append_normal(&fm, owl_global_get_aim_screenname(&g));
1828    owl_fmtext_append_normal(&fm, "\n");
1829  } else {
1830    owl_fmtext_append_normal(&fm, "(not logged in)\n");
1831  }
1832
1833  owl_fmtext_append_normal(&fm, "  Processing events: ");
1834  if (owl_global_is_doaimevents(&g)) {
1835    owl_fmtext_append_normal(&fm, "yes\n");
1836  } else {
1837    owl_fmtext_append_normal(&fm, "no\n");
1838  }
1839
1840  owl_function_popless_fmtext(&fm);
1841  owl_fmtext_free(&fm);
1842}
1843
1844void owl_function_show_term(void)
1845{
1846  owl_fmtext fm;
1847
1848  owl_fmtext_init_null(&fm);
1849  owl_fmtext_appendf_normal(&fm, "Terminal Lines: %i\nTerminal Columns: %i\n",
1850          owl_global_get_lines(&g),
1851          owl_global_get_cols(&g));
1852
1853  if (owl_global_get_hascolors(&g)) {
1854    owl_fmtext_append_normal(&fm, "Color: Yes\n");
1855    owl_fmtext_appendf_normal(&fm, "Number of color pairs: %i\n", owl_global_get_colorpairs(&g));
1856    owl_fmtext_appendf_normal(&fm, "Can change colors: %s\n", can_change_color() ? "yes" : "no");
1857  } else {
1858    owl_fmtext_append_normal(&fm, "Color: No\n");
1859  }
1860
1861  owl_function_popless_fmtext(&fm);
1862  owl_fmtext_free(&fm);
1863}
1864
1865/* if type = 0 then normal reply.
1866 * if type = 1 then it's a reply to sender
1867 * if enter = 0 then allow the command to be edited
1868 * if enter = 1 then don't wait for editing
1869 */
1870void owl_function_reply(int type, int enter)
1871{
1872  char *buff=NULL;
1873  const owl_message *m;
1874  const owl_filter *f;
1875 
1876  if (owl_view_get_size(owl_global_get_current_view(&g))==0) {
1877    owl_function_error("No message selected");
1878  } else {
1879    char *cmd;
1880   
1881    m=owl_view_get_element(owl_global_get_current_view(&g), owl_global_get_curmsg(&g));
1882    if (!m) {
1883      owl_function_error("No message selected");
1884      return;
1885    }
1886
1887    /* first check if we catch the reply-lockout filter */
1888    f=owl_global_get_filter(&g, "reply-lockout");
1889    if (f) {
1890      if (owl_filter_message_match(f, m)) {
1891        owl_function_error("Sorry, replies to this message have been disabled by the reply-lockout filter");
1892        return;
1893      }
1894    }
1895
1896    /* then check if it's a question and just bring up the command prompt */
1897    if (owl_message_is_question(m)) {
1898      owl_function_start_command("");
1899      return;
1900    }
1901
1902    if((type == 0 &&
1903        (cmd=owl_perlconfig_message_call_method(m, "replycmd", 0, NULL))) ||
1904       (type == 1 &&
1905        (cmd=owl_perlconfig_message_call_method(m, "replysendercmd", 0, NULL)))) {
1906      buff = cmd;
1907    }
1908
1909    if(!buff) {
1910        owl_function_error("I don't know how to reply to that message.");
1911        return;
1912    }
1913
1914    if (enter) {
1915      owl_history *hist = owl_global_get_cmd_history(&g);
1916      owl_history_store(hist, buff);
1917      owl_history_reset(hist);
1918      owl_function_command_norv(buff);
1919    } else {
1920      owl_function_start_command(buff);
1921    }
1922    owl_free(buff);
1923  }
1924}
1925
1926void owl_function_zlocate(int argc, const char *const *argv, int auth)
1927{
1928  owl_fmtext fm;
1929  char *ptr;
1930  char *result;
1931  int i;
1932
1933  owl_fmtext_init_null(&fm);
1934
1935  for (i=0; i<argc; i++) {
1936    ptr = long_zuser(argv[i]);
1937    result = owl_zephyr_zlocate(ptr, auth);
1938    owl_fmtext_append_normal(&fm, result);
1939    owl_free(result);
1940    owl_free(ptr);
1941  }
1942
1943  owl_function_popless_fmtext(&fm);
1944  owl_fmtext_free(&fm);
1945}
1946
1947void owl_function_start_command(const char *line)
1948{
1949  owl_editwin *tw;
1950
1951  tw=owl_global_get_typwin(&g);
1952  owl_global_set_typwin_active(&g);
1953  owl_editwin_new_style(tw, OWL_EDITWIN_STYLE_ONELINE, 
1954                        owl_global_get_cmd_history(&g));
1955
1956  owl_editwin_set_locktext(tw, "command: ");
1957  owl_global_set_needrefresh(&g);
1958
1959  owl_editwin_insert_string(tw, line);
1960  owl_editwin_redisplay(tw, 0);
1961
1962  owl_context_set_editline(owl_global_get_context(&g), tw);
1963  owl_function_activate_keymap("editline");
1964}
1965
1966void owl_function_start_question(const char *line)
1967{
1968  owl_editwin *tw;
1969
1970  tw=owl_global_get_typwin(&g);
1971  owl_global_set_typwin_active(&g);
1972  owl_editwin_new_style(tw, OWL_EDITWIN_STYLE_ONELINE, owl_global_get_cmd_history(&g));
1973
1974  owl_editwin_set_locktext(tw, line);
1975  owl_global_set_needrefresh(&g);
1976
1977  owl_editwin_redisplay(tw, 0);
1978
1979  owl_context_set_editresponse(owl_global_get_context(&g), tw);
1980  owl_function_activate_keymap("editresponse");
1981}
1982
1983void owl_function_start_password(const char *line)
1984{
1985  owl_editwin *tw;
1986
1987  tw=owl_global_get_typwin(&g);
1988  owl_global_set_typwin_active(&g);
1989  owl_editwin_new_style(tw, OWL_EDITWIN_STYLE_ONELINE, owl_global_get_cmd_history(&g));
1990  owl_editwin_set_echochar(tw, '*');
1991
1992  owl_editwin_set_locktext(tw, line);
1993  owl_global_set_needrefresh(&g);
1994
1995  owl_editwin_redisplay(tw, 0);
1996
1997  owl_context_set_editresponse(owl_global_get_context(&g), tw);
1998  owl_function_activate_keymap("editresponse");
1999}
2000
2001char *owl_function_exec(int argc, const char *const *argv, const char *buff, int type)
2002{
2003  /* if type == 1 display in a popup
2004   * if type == 2 display an admin messages
2005   * if type == 0 return output
2006   * else display in a popup
2007   */
2008  const char *redirect = " 2>&1 < /dev/null";
2009  char *newbuff;
2010  char *out;
2011  FILE *p;
2012
2013#if OWL_STDERR_REDIR
2014  redirect = " < /dev/null";
2015#endif
2016
2017  if (argc<2) {
2018    owl_function_error("Wrong number of arguments to the exec command");
2019    return NULL;
2020  }
2021
2022  buff = skiptokens(buff, 1);
2023  newbuff = owl_sprintf("%s%s", buff, redirect);
2024
2025  if (type == 1) {
2026    owl_popexec_new(newbuff);
2027  } else {
2028    p = popen(newbuff, "r");
2029    out = owl_slurp(p);
2030    pclose(p);
2031   
2032    if (type==1) {
2033      owl_function_popless_text(out);
2034    } else if (type==0) {
2035      return out;
2036    } else if (type==2) {
2037      owl_function_adminmsg(buff, out);
2038    } else {
2039      owl_function_popless_text(out);
2040    }
2041    owl_free(out);
2042  }
2043  return NULL;
2044}
2045
2046char *owl_function_perl(int argc, const char *const *argv, const char *buff, int type)
2047{
2048  /* if type == 1 display in a popup
2049   * if type == 2 display an admin messages
2050   * if type == 0 return output
2051   * else display in a popup
2052   */
2053  char *perlout;
2054
2055  if (argc<2) {
2056    owl_function_error("Wrong number of arguments to perl command");
2057    return NULL;
2058  }
2059
2060  /* consume first token (argv[0]) */
2061  buff = skiptokens(buff, 1);
2062
2063  perlout = owl_perlconfig_execute(buff);
2064  if (perlout) { 
2065    if (type==1) {
2066      owl_function_popless_text(perlout);
2067    } else if (type==2) {
2068      owl_function_adminmsg(buff, perlout);
2069    } else if (type==0) {
2070      return perlout;
2071    } else {
2072      owl_function_popless_text(perlout);
2073    }
2074    owl_free(perlout);
2075  }
2076  return NULL;
2077}
2078
2079/* Change the filter associated with the current view.
2080 * This also figures out which message in the new filter
2081 * should have the pointer.
2082 */
2083void owl_function_change_currentview_filter(const char *filtname)
2084{
2085  owl_view *v;
2086  owl_filter *f;
2087  int curid=-1, newpos, curmsg;
2088  const owl_message *curm=NULL;
2089
2090  v=owl_global_get_current_view(&g);
2091
2092  curmsg=owl_global_get_curmsg(&g);
2093  if (curmsg==-1) {
2094    owl_function_debugmsg("Hit the curmsg==-1 case in change_view");
2095  } else {
2096    curm=owl_view_get_element(v, curmsg);
2097    if (curm) {
2098      curid=owl_message_get_id(curm);
2099      owl_view_save_curmsgid(v, curid);
2100    }
2101  }
2102
2103  f=owl_global_get_filter(&g, filtname);
2104  if (!f) {
2105    owl_function_error("Unknown filter %s", filtname);
2106    return;
2107  }
2108
2109  owl_view_new_filter(v, f);
2110
2111  /* Figure out what to set the current message to.
2112   * - If the view we're leaving has messages in it, go to the closest message
2113   *   to the last message pointed to in that view.
2114   * - If the view we're leaving is empty, try to restore the position
2115   *   from the last time we were in the new view.  */
2116  if (curm) {
2117    newpos = owl_view_get_nearest_to_msgid(v, curid);
2118  } else {
2119    newpos = owl_view_get_nearest_to_saved(v);
2120  }
2121
2122  owl_global_set_curmsg(&g, newpos);
2123  owl_function_calculate_topmsg(OWL_DIRECTION_DOWNWARDS);
2124  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
2125  owl_global_set_direction_downwards(&g);
2126}
2127
2128/* Create a new filter, or replace an existing one
2129 * with a new definition.
2130 */
2131void owl_function_create_filter(int argc, const char *const *argv)
2132{
2133  owl_filter *f;
2134  const owl_view *v;
2135  int inuse = 0;
2136
2137  if (argc < 2) {
2138    owl_function_error("Wrong number of arguments to filter command");
2139    return;
2140  }
2141
2142  owl_function_debugmsg("owl_function_create_filter: starting to create filter named %s", argv[1]);
2143
2144  v=owl_global_get_current_view(&g);
2145
2146  /* don't touch the all filter */
2147  if (!strcmp(argv[1], "all")) {
2148    owl_function_error("You may not change the 'all' filter.");
2149    return;
2150  }
2151
2152  /* deal with the case of trying change the filter color */
2153  if (argc==4 && !strcmp(argv[2], "-c")) {
2154    f=owl_global_get_filter(&g, argv[1]);
2155    if (!f) {
2156      owl_function_error("The filter '%s' does not exist.", argv[1]);
2157      return;
2158    }
2159    if (owl_util_string_to_color(argv[3])==OWL_COLOR_INVALID) {
2160      owl_function_error("The color '%s' is not available.", argv[3]);
2161      return;
2162    }
2163    owl_filter_set_fgcolor(f, owl_util_string_to_color(argv[3]));
2164    owl_global_set_needrefresh(&g);
2165    owl_mainwin_redisplay(owl_global_get_mainwin(&g));
2166    return;
2167  }
2168  if (argc==4 && !strcmp(argv[2], "-b")) {
2169    f=owl_global_get_filter(&g, argv[1]);
2170    if (!f) {
2171      owl_function_error("The filter '%s' does not exist.", argv[1]);
2172      return;
2173    }
2174    if (owl_util_string_to_color(argv[3])==OWL_COLOR_INVALID) {
2175      owl_function_error("The color '%s' is not available.", argv[3]);
2176      return;
2177    }
2178    owl_filter_set_bgcolor(f, owl_util_string_to_color(argv[3]));
2179    owl_global_set_needrefresh(&g);
2180    owl_mainwin_redisplay(owl_global_get_mainwin(&g));
2181    return;
2182  }
2183
2184  /* create the filter and check for errors */
2185  f = owl_filter_new(argv[1], argc-2, argv+2);
2186  if (f == NULL) {
2187    owl_function_error("Invalid filter");
2188    return;
2189  }
2190
2191  /* if the named filter is in use by the current view, remember it */
2192  if (!strcmp(owl_view_get_filtname(v), argv[1])) {
2193    inuse=1;
2194  }
2195
2196  /* if the named filter already exists, nuke it */
2197  if (owl_global_get_filter(&g, argv[1])) {
2198    owl_global_remove_filter(&g, argv[1]);
2199  }
2200
2201  /* add the filter */
2202  owl_global_add_filter(&g, f);
2203
2204  /* if it was in use by the current view then update */
2205  if (inuse) {
2206    owl_function_change_currentview_filter(argv[1]);
2207  }
2208  owl_global_set_needrefresh(&g);
2209  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
2210}
2211
2212/* If 'filtername' does not start with 'not-' create a filter named
2213 * 'not-<filtername>' defined as "not filter <filtername>".  If the
2214 * filter 'not-<filtername>' already exists, do not overwrite it.  If
2215 * 'filtername' begins with 'not-' and a filter 'filtername' already
2216 * exists, then do nothing.  If the filter 'filtername' does not
2217 * exist, create it and define it as 'not filter <filtername>'
2218 *
2219 * Returns the name of the negated filter, which the caller must free.
2220 */
2221char *owl_function_create_negative_filter(const char *filtername)
2222{
2223  char *newname;
2224  const owl_filter *tmpfilt;
2225  const char *argv[5];
2226
2227  owl_function_debugmsg("owl_function_create_negative_filter");
2228 
2229  if (!strncmp(filtername, "not-", 4)) {
2230    newname=owl_strdup(filtername+4);
2231  } else {
2232    newname=owl_sprintf("not-%s", filtername);
2233  }
2234
2235  tmpfilt=owl_global_get_filter(&g, newname);
2236  if (!tmpfilt) {
2237    argv[0]="filter"; /* anything is fine here */
2238    argv[1]=newname;
2239    argv[2]="not";
2240    argv[3]="filter";
2241    argv[4]=filtername;
2242    owl_function_create_filter(5, argv);
2243  }
2244
2245  owl_function_debugmsg("owl_function_create_negative_filter: returning with %s", newname);
2246  return(newname);
2247}
2248
2249void owl_function_show_filters(void)
2250{
2251  const owl_list *l;
2252  const owl_filter *f;
2253  int i, j;
2254  owl_fmtext fm;
2255
2256  owl_fmtext_init_null(&fm);
2257
2258  l=owl_global_get_filterlist(&g);
2259  j=owl_list_get_size(l);
2260
2261  owl_fmtext_append_bold(&fm, "Filters:\n");
2262
2263  for (i=0; i<j; i++) {
2264    f=owl_list_get_element(l, i);
2265    owl_fmtext_append_normal(&fm, "   ");
2266    if (owl_global_get_hascolors(&g)) {
2267      owl_fmtext_append_normal_color(&fm, owl_filter_get_name(f), owl_filter_get_fgcolor(f), owl_filter_get_bgcolor(f));
2268    } else {
2269      owl_fmtext_append_normal(&fm, owl_filter_get_name(f));
2270    }
2271    owl_fmtext_append_normal(&fm, "\n");
2272  }
2273  owl_function_popless_fmtext(&fm);
2274  owl_fmtext_free(&fm);
2275}
2276
2277void owl_function_show_filter(const char *name)
2278{
2279  const owl_filter *f;
2280  char *buff, *tmp;
2281
2282  f=owl_global_get_filter(&g, name);
2283  if (!f) {
2284    owl_function_error("There is no filter named %s", name);
2285    return;
2286  }
2287  tmp = owl_filter_print(f);
2288  buff = owl_sprintf("%s: %s", owl_filter_get_name(f), tmp);
2289  owl_function_popless_text(buff);
2290  owl_free(buff);
2291  owl_free(tmp);
2292}
2293
2294void owl_function_show_zpunts(void)
2295{
2296  const owl_filter *f;
2297  const owl_list *fl;
2298  char buff[5000];
2299  char *tmp;
2300  owl_fmtext fm;
2301  int i, j;
2302
2303  owl_fmtext_init_null(&fm);
2304
2305  fl=owl_global_get_puntlist(&g);
2306  j=owl_list_get_size(fl);
2307  owl_fmtext_append_bold(&fm, "Active zpunt filters:\n");
2308
2309  for (i=0; i<j; i++) {
2310    f=owl_list_get_element(fl, i);
2311    snprintf(buff, sizeof(buff), "[% 2d] ", i+1);
2312    owl_fmtext_append_normal(&fm, buff);
2313    tmp = owl_filter_print(f);
2314    owl_fmtext_append_normal(&fm, tmp);
2315    owl_free(tmp);
2316  }
2317  owl_function_popless_fmtext(&fm);
2318  owl_fmtext_free(&fm);
2319}
2320
2321/* Create a filter for a class, instance if one doesn't exist.  If
2322 * instance is NULL then catch all messgaes in the class.  Returns the
2323 * name of the filter, which the caller must free.
2324 */
2325char *owl_function_classinstfilt(const char *c, const char *i) 
2326{
2327  owl_filter *f;
2328  char *argbuff, *filtname;
2329  char *tmpclass, *tmpinstance = NULL;
2330  char *class, *instance = NULL;
2331
2332  class = owl_util_baseclass(c);
2333  if(i) {
2334    instance = owl_util_baseclass(i);
2335  }
2336
2337  /* name for the filter */
2338  if (!instance) {
2339    filtname = owl_sprintf("class-%s", class);
2340  } else {
2341    filtname = owl_sprintf("class-%s-instance-%s", class, instance);
2342  }
2343  /* downcase it */
2344  {
2345    char *temp = g_utf8_strdown(filtname, -1);
2346    if (temp) {
2347      owl_free(filtname);
2348      filtname = temp;
2349    }
2350  }
2351  /* turn spaces, single quotes, and double quotes into dots */
2352  owl_text_tr(filtname, ' ', '.');
2353  owl_text_tr(filtname, '\'', '.');
2354  owl_text_tr(filtname, '"', '.');
2355 
2356  /* if it already exists then go with it.  This lets users override */
2357  if (owl_global_get_filter(&g, filtname)) {
2358    return(filtname);
2359  }
2360
2361  /* create the new filter */
2362  tmpclass=owl_text_quote(class, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2363  owl_text_tr(tmpclass, ' ', '.');
2364  owl_text_tr(tmpclass, '\'', '.');
2365  owl_text_tr(tmpclass, '"', '.');
2366  if (instance) {
2367    tmpinstance=owl_text_quote(instance, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2368    owl_text_tr(tmpinstance, ' ', '.');
2369    owl_text_tr(tmpinstance, '\'', '.');
2370    owl_text_tr(tmpinstance, '"', '.');
2371  }
2372
2373  argbuff = owl_sprintf("class ^(un)*%s(\\.d)*$", tmpclass);
2374  if (tmpinstance) {
2375    char *tmp = argbuff;
2376    argbuff = owl_sprintf("%s and ( instance ^(un)*%s(\\.d)*$ )", tmp, tmpinstance);
2377    owl_free(tmp);
2378  }
2379  owl_free(tmpclass);
2380  if (tmpinstance) owl_free(tmpinstance);
2381
2382  f = owl_filter_new_fromstring(filtname, argbuff);
2383
2384  /* add it to the global list */
2385  owl_global_add_filter(&g, f);
2386
2387  owl_free(argbuff);
2388  owl_free(class);
2389  if (instance) {
2390    owl_free(instance);
2391  }
2392  return(filtname);
2393}
2394
2395/* Create a filter for personal zephyrs to or from the specified
2396 * zephyr user.  Includes login/logout notifications for the user.
2397 * The name of the filter will be 'user-<user>'.  If a filter already
2398 * exists with this name, no new filter will be created.  This allows
2399 * the configuration to override this function.  Returns the name of
2400 * the filter, which the caller must free.
2401 */
2402char *owl_function_zuserfilt(const char *user)
2403{
2404  owl_filter *f;
2405  char *argbuff, *longuser, *esclonguser, *shortuser, *filtname;
2406
2407  /* stick the local realm on if it's not there */
2408  longuser=long_zuser(user);
2409  shortuser=short_zuser(user);
2410
2411  /* name for the filter */
2412  filtname=owl_sprintf("user-%s", shortuser);
2413
2414  /* if it already exists then go with it.  This lets users override */
2415  if (owl_global_get_filter(&g, filtname)) {
2416    return(owl_strdup(filtname));
2417  }
2418
2419  /* create the new-internal filter */
2420  esclonguser = owl_text_quote(longuser, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2421
2422  argbuff=owl_sprintf("( type ^zephyr$ and filter personal and "
2423      "( ( direction ^in$ and sender ^%1$s$ ) or ( direction ^out$ and "
2424      "recipient ^%1$s$ ) ) ) or ( ( class ^login$ ) and ( sender ^%1$s$ ) )",
2425      esclonguser);
2426
2427  f = owl_filter_new_fromstring(filtname, argbuff);
2428
2429  /* add it to the global list */
2430  owl_global_add_filter(&g, f);
2431
2432  /* free stuff */
2433  owl_free(argbuff);
2434  owl_free(longuser);
2435  owl_free(esclonguser);
2436  owl_free(shortuser);
2437
2438  return(filtname);
2439}
2440
2441/* Create a filter for AIM IM messages to or from the specified
2442 * screenname.  The name of the filter will be 'aimuser-<user>'.  If a
2443 * filter already exists with this name, no new filter will be
2444 * created.  This allows the configuration to override this function.
2445 * Returns the name of the filter, which the caller must free.
2446 */
2447char *owl_function_aimuserfilt(const char *user)
2448{
2449  owl_filter *f;
2450  char *argbuff, *filtname;
2451  char *escuser;
2452
2453  /* name for the filter */
2454  filtname=owl_sprintf("aimuser-%s", user);
2455
2456  /* if it already exists then go with it.  This lets users override */
2457  if (owl_global_get_filter(&g, filtname)) {
2458    return(owl_strdup(filtname));
2459  }
2460
2461  /* create the new-internal filter */
2462  escuser = owl_text_quote(user, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2463
2464  argbuff = owl_sprintf(
2465      "( type ^aim$ and ( ( sender ^%1$s$ and recipient ^%2$s$ ) or "
2466      "( sender ^%2$s$ and recipient ^%1$s$ ) ) )",
2467      escuser, owl_global_get_aim_screenname_for_filters(&g));
2468
2469  f = owl_filter_new_fromstring(filtname, argbuff);
2470
2471  /* add it to the global list */
2472  owl_global_add_filter(&g, f);
2473
2474  /* free stuff */
2475  owl_free(argbuff);
2476  owl_free(escuser);
2477
2478  return(filtname);
2479}
2480
2481char *owl_function_typefilt(const char *type)
2482{
2483  owl_filter *f;
2484  char *argbuff, *filtname, *esctype;
2485
2486  /* name for the filter */
2487  filtname=owl_sprintf("type-%s", type);
2488
2489  /* if it already exists then go with it.  This lets users override */
2490  if (owl_global_get_filter(&g, filtname)) {
2491    return filtname;
2492  }
2493
2494  /* create the new-internal filter */
2495  f=owl_malloc(sizeof(owl_filter));
2496
2497  esctype = owl_text_quote(type, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2498
2499  argbuff = owl_sprintf("type ^%s$", esctype);
2500
2501  f = owl_filter_new_fromstring(filtname, argbuff);
2502
2503  /* add it to the global list */
2504  owl_global_add_filter(&g, f);
2505
2506  /* free stuff */
2507  owl_free(argbuff);
2508  owl_free(esctype);
2509
2510  return filtname;
2511}
2512
2513/* If flag is 1, marks for deletion.  If flag is 0,
2514 * unmarks for deletion. */
2515void owl_function_delete_curview_msgs(int flag)
2516{
2517  const owl_view *v;
2518  int i, j;
2519
2520  v=owl_global_get_current_view(&g);
2521  j=owl_view_get_size(v);
2522  for (i=0; i<j; i++) {
2523    if (flag == 1) {
2524      owl_message_mark_delete(owl_view_get_element(v, i));
2525    } else if (flag == 0) {
2526      owl_message_unmark_delete(owl_view_get_element(v, i));
2527    }
2528  }
2529
2530  owl_function_makemsg("%i messages marked for %sdeletion", j, flag?"":"un");
2531
2532  owl_mainwin_redisplay(owl_global_get_mainwin(&g)); 
2533}
2534
2535/* Create a filter based on the current message.  Returns the name of
2536 * a filter or null.  The caller must free this name.
2537 *
2538 * if the curmsg is a personal zephyr return a filter name
2539 *    to the zephyr conversation with that user.
2540 * If the curmsg is a zephyr class message, instance foo, recip *,
2541 *    return a filter name to the class, inst.
2542 * If the curmsg is a zephyr class message and type==0 then
2543 *    return a filter name for just the class.
2544 * If the curmsg is a zephyr class message and type==1 then
2545 *    return a filter name for the class and instance.
2546 * If the curmsg is a personal AIM message returna  filter
2547 *    name to the AIM conversation with that user
2548 */
2549char *owl_function_smartfilter(int type)
2550{
2551  const owl_view *v;
2552  const owl_message *m;
2553  char *zperson, *filtname=NULL;
2554  const char *argv[1];
2555 
2556  v=owl_global_get_current_view(&g);
2557  m=owl_view_get_element(v, owl_global_get_curmsg(&g));
2558
2559  if (!m || owl_view_get_size(v)==0) {
2560    owl_function_error("No message selected\n");
2561    return(NULL);
2562  }
2563
2564  /* very simple handling of admin messages for now */
2565  if (owl_message_is_type_admin(m)) {
2566    return(owl_function_typefilt("admin"));
2567  }
2568
2569  /* very simple handling of loopback messages for now */
2570  if (owl_message_is_type_loopback(m)) {
2571    return(owl_function_typefilt("loopback"));
2572  }
2573
2574  /* aim messages */
2575  if (owl_message_is_type_aim(m)) {
2576    if (owl_message_is_direction_in(m)) {
2577      filtname=owl_function_aimuserfilt(owl_message_get_sender(m));
2578    } else if (owl_message_is_direction_out(m)) {
2579      filtname=owl_function_aimuserfilt(owl_message_get_recipient(m));
2580    }
2581    return(filtname);
2582  }
2583
2584  /* narrow personal and login messages to the sender or recip as appropriate */
2585  if (owl_message_is_type_zephyr(m)) {
2586    if (owl_message_is_personal(m) || owl_message_is_loginout(m)) {
2587      if (owl_message_is_direction_in(m)) {
2588        zperson=short_zuser(owl_message_get_sender(m));
2589      } else {
2590        zperson=short_zuser(owl_message_get_recipient(m));
2591      }
2592      filtname=owl_function_zuserfilt(zperson);
2593      owl_free(zperson);
2594      return(filtname);
2595    }
2596
2597    /* narrow class MESSAGE, instance foo, recip * messages to class, inst */
2598    if (!strcasecmp(owl_message_get_class(m), "message")) {
2599      filtname=owl_function_classinstfilt(owl_message_get_class(m), owl_message_get_instance(m));
2600      return(filtname);
2601    }
2602
2603    /* otherwise narrow to the class */
2604    if (type==0) {
2605      filtname=owl_function_classinstfilt(owl_message_get_class(m), NULL);
2606    } else if (type==1) {
2607      filtname=owl_function_classinstfilt(owl_message_get_class(m), owl_message_get_instance(m));
2608    }
2609    return(filtname);
2610  }
2611
2612  /* pass it off to perl */
2613  if(type) {
2614    argv[0] = "-i";
2615  };
2616  return owl_perlconfig_message_call_method(m, "smartfilter", type ? 1 : 0, argv);
2617}
2618
2619void owl_function_smartzpunt(int type)
2620{
2621  /* Starts a zpunt command based on the current class,instance pair.
2622   * If type=0, uses just class.  If type=1, uses instance as well. */
2623  const owl_view *v;
2624  const owl_message *m;
2625  const char *cmdprefix, *mclass, *minst;
2626  char *cmd;
2627 
2628  v=owl_global_get_current_view(&g);
2629  m=owl_view_get_element(v, owl_global_get_curmsg(&g));
2630
2631  if (!m || owl_view_get_size(v)==0) {
2632    owl_function_error("No message selected\n");
2633    return;
2634  }
2635
2636  /* for now we skip admin messages. */
2637  if (owl_message_is_type_admin(m)
2638      || owl_message_is_loginout(m)
2639      || !owl_message_is_type_zephyr(m)) {
2640    owl_function_error("smartzpunt doesn't support this message type.");
2641    return;
2642  }
2643
2644  mclass = owl_message_get_class(m);
2645  minst = owl_message_get_instance(m);
2646  if (!mclass || !*mclass || *mclass==' '
2647      || (!strcasecmp(mclass, "message") && !strcasecmp(minst, "personal"))
2648      || (type && (!minst || !*minst|| *minst==' '))) {
2649    owl_function_error("smartzpunt can't safely do this for <%s,%s>",
2650                         mclass, minst);
2651  } else {
2652    cmdprefix = "start-command zpunt ";
2653    cmd = owl_malloc(strlen(cmdprefix)+strlen(mclass)+strlen(minst)+10);
2654    strcpy(cmd, cmdprefix);
2655    strcat(cmd, owl_getquoting(mclass));
2656    strcat(cmd, mclass);
2657    strcat(cmd, owl_getquoting(mclass));
2658    if (type) {
2659      strcat(cmd, " ");
2660      strcat(cmd, owl_getquoting(minst));
2661      strcat(cmd, minst);
2662      strcat(cmd, owl_getquoting(minst));
2663    } else {
2664      strcat(cmd, " *");
2665    }
2666    owl_function_command(cmd);
2667    owl_free(cmd);
2668  }
2669}
2670
2671/* Set the color of the current view's filter to
2672 * be 'color'
2673 */
2674void owl_function_color_current_filter(const char *fgcolor, const char *bgcolor)
2675{
2676  const char *name;
2677
2678  name=owl_view_get_filtname(owl_global_get_current_view(&g));
2679  owl_function_color_filter(name, fgcolor, bgcolor);
2680}
2681
2682/* Set the color of the filter 'filter' to be 'color'.  If the color
2683 * name does not exist, return -1, if the filter does not exist or is
2684 * the "all" filter, return -2.  Return 0 on success
2685 */
2686int owl_function_color_filter(const char *filtname, const char *fgcolor, const char *bgcolor)
2687{
2688  owl_filter *f;
2689
2690  f=owl_global_get_filter(&g, filtname);
2691  if (!f) {
2692    owl_function_error("Unknown filter");
2693    return(-2);
2694  }
2695
2696  /* don't touch the all filter */
2697  if (!strcmp(filtname, "all")) {
2698    owl_function_error("You may not change the 'all' filter.");
2699    return(-2);
2700  }
2701
2702  if (owl_util_string_to_color(fgcolor)==OWL_COLOR_INVALID) {
2703    owl_function_error("No color named '%s' avilable.", fgcolor);
2704    return(-1);
2705  }
2706
2707
2708  if (bgcolor != NULL) {
2709    if (owl_util_string_to_color(bgcolor)==OWL_COLOR_INVALID) {
2710      owl_function_error("No color named '%s' avilable.", bgcolor);
2711      return(-1);
2712    }
2713    owl_filter_set_bgcolor(f, owl_util_string_to_color(bgcolor));
2714  }
2715  owl_filter_set_fgcolor(f, owl_util_string_to_color(fgcolor));
2716 
2717  owl_global_set_needrefresh(&g);
2718  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
2719  return(0);
2720}
2721
2722void owl_function_show_colors(void)
2723{
2724  owl_fmtext fm;
2725  int i; 
2726 
2727  owl_fmtext_init_null(&fm);
2728  owl_fmtext_append_normal(&fm, "default: ");
2729  owl_fmtext_append_normal_color(&fm, "default\n", OWL_COLOR_DEFAULT, OWL_COLOR_DEFAULT);
2730
2731  owl_fmtext_append_normal(&fm,"red:      ");
2732  owl_fmtext_append_normal_color(&fm, "red\n", OWL_COLOR_RED, OWL_COLOR_DEFAULT);
2733
2734  owl_fmtext_append_normal(&fm,"green:    ");
2735  owl_fmtext_append_normal_color(&fm, "green\n", OWL_COLOR_GREEN, OWL_COLOR_DEFAULT);
2736
2737  owl_fmtext_append_normal(&fm,"yellow:   ");
2738  owl_fmtext_append_normal_color(&fm, "yellow\n", OWL_COLOR_YELLOW, OWL_COLOR_DEFAULT);
2739
2740  owl_fmtext_append_normal(&fm,"blue:     ");
2741  owl_fmtext_append_normal_color(&fm, "blue\n", OWL_COLOR_BLUE, OWL_COLOR_DEFAULT);
2742
2743  owl_fmtext_append_normal(&fm,"magenta:  ");
2744  owl_fmtext_append_normal_color(&fm, "magenta\n", OWL_COLOR_MAGENTA, OWL_COLOR_DEFAULT);
2745
2746  owl_fmtext_append_normal(&fm,"cyan:     ");
2747  owl_fmtext_append_normal_color(&fm, "cyan\n", OWL_COLOR_CYAN, OWL_COLOR_DEFAULT);
2748
2749  owl_fmtext_append_normal(&fm,"white:    ");
2750  owl_fmtext_append_normal_color(&fm, "white\n", OWL_COLOR_WHITE, OWL_COLOR_DEFAULT);
2751
2752  for(i = 8; i < COLORS; ++i) {
2753    char* str1 = owl_sprintf("%4i:     ",i);
2754    char* str2 = owl_sprintf("%i\n",i);
2755    owl_fmtext_append_normal(&fm,str1);
2756    owl_fmtext_append_normal_color(&fm, str2, i, OWL_COLOR_DEFAULT);
2757    owl_free(str1);
2758     owl_free(str2);
2759  }
2760 
2761  owl_function_popless_fmtext(&fm);
2762  owl_fmtext_free(&fm);
2763}
2764
2765/* add the given class, inst, recip to the punt list for filtering.
2766 *   if direction==0 then punt
2767 *   if direction==1 then unpunt
2768 */
2769void owl_function_zpunt(const char *class, const char *inst, const char *recip, int direction)
2770{
2771  char *puntexpr, *classexpr, *instexpr, *recipexpr;
2772  char *quoted;
2773
2774  if (!strcmp(class, "*")) {
2775    classexpr = owl_sprintf("class .*");
2776  } else {
2777    quoted=owl_text_quote(class, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2778    owl_text_tr(quoted, ' ', '.');
2779    owl_text_tr(quoted, '\'', '.');
2780    owl_text_tr(quoted, '"', '.');
2781    classexpr = owl_sprintf("class ^(un)*%s(\\.d)*$", quoted);
2782    owl_free(quoted);
2783  }
2784  if (!strcmp(inst, "*")) {
2785    instexpr = owl_sprintf(" and instance .*");
2786  } else {
2787    quoted=owl_text_quote(inst, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2788    owl_text_tr(quoted, ' ', '.');
2789    owl_text_tr(quoted, '\'', '.');
2790    owl_text_tr(quoted, '"', '.');
2791    instexpr = owl_sprintf(" and instance ^(un)*%s(\\.d)*$", quoted);
2792    owl_free(quoted);
2793  }
2794  if (!strcmp(recip, "*")) {
2795    recipexpr = owl_sprintf("");
2796  } else {
2797    if(!strcmp(recip, "%me%")) {
2798      recip = owl_zephyr_get_sender();
2799    }
2800    quoted=owl_text_quote(recip, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2801    owl_text_tr(quoted, ' ', '.');
2802    owl_text_tr(quoted, '\'', '.');
2803    owl_text_tr(quoted, '"', '.');
2804    recipexpr = owl_sprintf(" and recipient ^%s$", quoted);
2805    owl_free(quoted);
2806  }
2807
2808  puntexpr = owl_sprintf("%s %s %s", classexpr, instexpr, recipexpr);
2809  owl_function_punt(puntexpr, direction);
2810  owl_free(puntexpr);
2811  owl_free(classexpr);
2812  owl_free(instexpr);
2813  owl_free(recipexpr);
2814}
2815
2816void owl_function_punt(const char *filter, int direction)
2817{
2818  owl_filter *f;
2819  owl_list *fl;
2820  int i, j;
2821  fl=owl_global_get_puntlist(&g);
2822
2823  /* first, create the filter */
2824  owl_function_debugmsg("About to filter %s", filter);
2825  f = owl_filter_new_fromstring("punt-filter", filter);
2826  if (f == NULL) {
2827    owl_function_error("Error creating filter for zpunt");
2828    return;
2829  }
2830
2831  /* Check for an identical filter */
2832  j=owl_list_get_size(fl);
2833  for (i=0; i<j; i++) {
2834    if (owl_filter_equiv(f, owl_list_get_element(fl, i))) {
2835      owl_function_debugmsg("found an equivalent punt filter");
2836      /* if we're punting, then just silently bow out on this duplicate */
2837      if (direction==0) {
2838        owl_filter_delete(f);
2839        return;
2840      }
2841
2842      /* if we're unpunting, then remove this filter from the puntlist */
2843      if (direction==1) {
2844        owl_filter_delete(owl_list_get_element(fl, i));
2845        owl_list_remove_element(fl, i);
2846        owl_filter_delete(f);
2847        return;
2848      }
2849    }
2850  }
2851
2852  owl_function_debugmsg("punting");
2853  /* If we're punting, add the filter to the global punt list */
2854  if (direction==0) {
2855    owl_list_append_element(fl, f);
2856  }
2857}
2858
2859void owl_function_activate_keymap(const char *keymap)
2860{
2861  if (!owl_keyhandler_activate(owl_global_get_keyhandler(&g), keymap)) {
2862    owl_function_error("Unable to activate keymap '%s'", keymap);
2863  }
2864}
2865
2866void owl_function_show_keymaps(void)
2867{
2868  owl_list l;
2869  owl_fmtext fm;
2870  const owl_keymap *km;
2871  const owl_keyhandler *kh;
2872  int i, numkm;
2873  const char *kmname;
2874
2875  kh = owl_global_get_keyhandler(&g);
2876  owl_fmtext_init_null(&fm);
2877  owl_fmtext_append_bold(&fm, "Keymaps:   ");
2878  owl_fmtext_append_normal(&fm, "(use 'show keymap <name>' for details)\n");
2879  owl_keyhandler_get_keymap_names(kh, &l);
2880  owl_fmtext_append_list(&fm, &l, "\n", owl_function_keymap_summary);
2881  owl_fmtext_append_normal(&fm, "\n");
2882
2883  numkm = owl_list_get_size(&l);
2884  for (i=0; i<numkm; i++) {
2885    kmname = owl_list_get_element(&l, i);
2886    km = owl_keyhandler_get_keymap(kh, kmname);
2887    owl_fmtext_append_bold(&fm, "\n\n----------------------------------------------------------------------------------------------------\n\n");
2888    owl_keymap_get_details(km, &fm);   
2889  }
2890  owl_fmtext_append_normal(&fm, "\n");
2891 
2892  owl_function_popless_fmtext(&fm);
2893  owl_keyhandler_keymap_namelist_free(&l);
2894  owl_fmtext_free(&fm);
2895}
2896
2897char *owl_function_keymap_summary(const char *name)
2898{
2899  const owl_keymap *km
2900    = owl_keyhandler_get_keymap(owl_global_get_keyhandler(&g), name);
2901  if (km) return owl_keymap_summary(km);
2902  else return(NULL);
2903}
2904
2905/* TODO: implement for real */
2906void owl_function_show_keymap(const char *name)
2907{
2908  owl_fmtext fm;
2909  const owl_keymap *km;
2910
2911  owl_fmtext_init_null(&fm);
2912  km = owl_keyhandler_get_keymap(owl_global_get_keyhandler(&g), name);
2913  if (km) {
2914    owl_keymap_get_details(km, &fm);
2915  } else {
2916    owl_fmtext_append_normal(&fm, "No such keymap...\n");
2917  } 
2918  owl_function_popless_fmtext(&fm);
2919  owl_fmtext_free(&fm);
2920}
2921
2922void owl_function_help_for_command(const char *cmdname)
2923{
2924  owl_fmtext fm;
2925
2926  owl_fmtext_init_null(&fm);
2927  owl_cmd_get_help(owl_global_get_cmddict(&g), cmdname, &fm);
2928  owl_function_popless_fmtext(&fm); 
2929  owl_fmtext_free(&fm);
2930}
2931
2932void owl_function_search_start(const char *string, int direction)
2933{
2934  /* direction is OWL_DIRECTION_DOWNWARDS or OWL_DIRECTION_UPWARDS or
2935   * OWL_DIRECTION_NONE */
2936  owl_regex re;
2937
2938  if (string && owl_regex_create_quoted(&re, string) == 0) {
2939    owl_global_set_search_re(&g, &re);
2940    owl_regex_free(&re);
2941  } else {
2942    owl_global_set_search_re(&g, NULL);
2943  }
2944
2945  if (direction == OWL_DIRECTION_NONE)
2946    owl_mainwin_redisplay(owl_global_get_mainwin(&g));
2947  else
2948    owl_function_search_helper(0, direction);
2949}
2950
2951void owl_function_search_continue(int direction)
2952{
2953  /* direction is OWL_DIRECTION_DOWNWARDS or OWL_DIRECTION_UPWARDS */
2954  owl_function_search_helper(1, direction);
2955}
2956
2957void owl_function_search_helper(int mode, int direction)
2958{
2959  /* move to a message that contains the string.  If direction is
2960   * OWL_DIRECTION_DOWNWARDS then search fowards, if direction is
2961   * OWL_DIRECTION_UPWARDS then search backwards.
2962   *
2963   * If mode==0 then it will stay on the current message if it
2964   * contains the string.
2965   */
2966
2967  const owl_view *v;
2968  int viewsize, i, curmsg, start;
2969  owl_message *m;
2970
2971  v=owl_global_get_current_view(&g);
2972  viewsize=owl_view_get_size(v);
2973  curmsg=owl_global_get_curmsg(&g);
2974 
2975  if (viewsize==0) {
2976    owl_function_error("No messages present");
2977    return;
2978  }
2979
2980  if (mode==0) {
2981    start=curmsg;
2982  } else if (direction==OWL_DIRECTION_DOWNWARDS) {
2983    start=curmsg+1;
2984  } else {
2985    start=curmsg-1;
2986  }
2987
2988  /* bounds check */
2989  if (start>=viewsize || start<0) {
2990    owl_function_error("No further matches found");
2991    return;
2992  }
2993
2994  for (i=start; i<viewsize && i>=0;) {
2995    m=owl_view_get_element(v, i);
2996    if (owl_message_search(m, owl_global_get_search_re(&g))) {
2997      owl_global_set_curmsg(&g, i);
2998      owl_function_calculate_topmsg(direction);
2999      owl_mainwin_redisplay(owl_global_get_mainwin(&g));
3000      if (direction==OWL_DIRECTION_DOWNWARDS) {
3001        owl_global_set_direction_downwards(&g);
3002      } else {
3003        owl_global_set_direction_upwards(&g);
3004      }
3005      return;
3006    }
3007    if (direction==OWL_DIRECTION_DOWNWARDS) {
3008      i++;
3009    } else {
3010      i--;
3011    }
3012    owl_function_mask_sigint(NULL);
3013    if(owl_global_is_interrupted(&g)) {
3014      owl_global_unset_interrupted(&g);
3015      owl_function_unmask_sigint(NULL);
3016      owl_function_makemsg("Search interrupted!");
3017      owl_mainwin_redisplay(owl_global_get_mainwin(&g));
3018      return;
3019    }
3020    owl_function_unmask_sigint(NULL);
3021  }
3022  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
3023  owl_function_error("No matches found");
3024}
3025
3026/* strips formatting from ztext and returns the unformatted text.
3027 * caller is responsible for freeing. */
3028char *owl_function_ztext_stylestrip(const char *zt)
3029{
3030  owl_fmtext fm;
3031  char *plaintext;
3032
3033  owl_fmtext_init_null(&fm);
3034  owl_fmtext_append_ztext(&fm, zt);
3035  plaintext = owl_fmtext_print_plain(&fm);
3036  owl_fmtext_free(&fm);
3037  return(plaintext);
3038}
3039
3040/* Popup a buddylisting.  If filename is NULL use the default .anyone */
3041void owl_function_buddylist(int aim, int zephyr, const char *filename)
3042{
3043  int i, j, idle;
3044  int interrupted = 0;
3045  owl_fmtext fm;
3046  const owl_buddylist *bl;
3047  const owl_buddy *b;
3048  char *timestr;
3049#ifdef HAVE_LIBZEPHYR
3050  int x;
3051  owl_list anyone;
3052  const char *user;
3053  char *tmp;
3054  ZLocations_t location[200];
3055  int numlocs, ret;
3056#endif
3057
3058  owl_fmtext_init_null(&fm);
3059
3060  /* AIM first */
3061  if (aim && owl_global_is_aimloggedin(&g)) {
3062    bl=owl_global_get_buddylist(&g);
3063
3064    owl_fmtext_append_bold(&fm, "AIM users logged in:\n");
3065    /* we're assuming AIM for now */
3066    j=owl_buddylist_get_size(bl);
3067    for (i=0; i<j; i++) {
3068      b=owl_buddylist_get_buddy_n(bl, i);
3069      idle=owl_buddy_get_idle_time(b);
3070      if (idle!=0) {
3071        timestr=owl_util_minutes_to_timestr(idle);
3072      } else {
3073        timestr=owl_strdup("");
3074      }
3075      owl_fmtext_appendf_normal(&fm, "  %-20.20s %-12.12s\n", owl_buddy_get_name(b), timestr);
3076      owl_free(timestr);
3077    }
3078  }
3079
3080#ifdef HAVE_LIBZEPHYR
3081  if (zephyr) {
3082    if(!owl_global_is_havezephyr(&g)) {
3083      owl_function_error("Zephyr currently not available.");
3084    } else {
3085      owl_fmtext_append_bold(&fm, "Zephyr users logged in:\n");
3086      owl_list_create(&anyone);
3087      ret=owl_zephyr_get_anyone_list(&anyone, filename);
3088      if (ret) {
3089        if (errno == ENOENT) {
3090          owl_fmtext_append_normal(&fm, " You have not added any zephyr buddies.  Use the\n");
3091          owl_fmtext_append_normal(&fm, " command ':addbuddy zephyr ");
3092          owl_fmtext_append_bold(  &fm, "<username>");
3093          owl_fmtext_append_normal(&fm, "'.\n");
3094        } else {
3095          owl_fmtext_append_normal(&fm, " Could not read zephyr buddies from the .anyone file.\n");
3096        }
3097      } else {
3098        j=owl_list_get_size(&anyone);
3099        for (i=0; i<j; i++) {
3100          user=owl_list_get_element(&anyone, i);
3101          ret=ZLocateUser(zstr(user), &numlocs, ZAUTH);
3102
3103          owl_function_mask_sigint(NULL);
3104          if(owl_global_is_interrupted(&g)) {
3105            interrupted = 1;
3106            owl_global_unset_interrupted(&g);
3107            owl_function_unmask_sigint(NULL);
3108            owl_function_makemsg("Interrupted!");
3109            break;
3110          }
3111
3112          owl_function_unmask_sigint(NULL);
3113
3114          if (ret!=ZERR_NONE) {
3115            owl_function_error("Error getting location for %s", user);
3116            continue;
3117          }
3118
3119          numlocs=200;
3120          ret=ZGetLocations(location, &numlocs);
3121          if (ret==0) {
3122            for (x=0; x<numlocs; x++) {
3123              tmp=short_zuser(user);
3124              owl_fmtext_appendf_normal(&fm, "  %-10.10s %-24.24s %-12.12s  %20.20s\n",
3125                                        tmp,
3126                                        location[x].host,
3127                                        location[x].tty,
3128                                        location[x].time);
3129              owl_free(tmp);
3130            }
3131            if (numlocs>=200) {
3132              owl_fmtext_append_normal(&fm, "  Too many locations found for this user, truncating.\n");
3133            }
3134          }
3135        }
3136      }
3137      owl_list_free_all(&anyone, owl_free);
3138    }
3139  }
3140#endif
3141
3142  if(aim && zephyr) {
3143      if(owl_perlconfig_is_function("BarnOwl::Hooks::_get_blist")) {
3144          char * perlblist = owl_perlconfig_execute("BarnOwl::Hooks::_get_blist()");
3145          if(perlblist) {
3146              owl_fmtext_append_ztext(&fm, perlblist);
3147              owl_free(perlblist);
3148          }
3149      }
3150  }
3151
3152  if(!interrupted) {
3153    owl_function_popless_fmtext(&fm);
3154  }
3155  owl_fmtext_free(&fm);
3156}
3157
3158/* Dump messages in the current view to the file 'filename'. */
3159void owl_function_dump(const char *filename) 
3160{
3161  int i, j;
3162  owl_message *m;
3163  const owl_view *v;
3164  FILE *file;
3165  char *plaintext;
3166
3167  v=owl_global_get_current_view(&g);
3168
3169  /* in the future make it ask yes/no */
3170  /*
3171  ret=stat(filename, &sbuf);
3172  if (!ret) {
3173    ret=owl_function_askyesno("File exists, continue? [Y/n]");
3174    if (!ret) return;
3175  }
3176  */
3177
3178  file=fopen(filename, "w");
3179  if (!file) {
3180    owl_function_error("Error opening file");
3181    return;
3182  }
3183
3184  j=owl_view_get_size(v);
3185  for (i=0; i<j; i++) {
3186    m=owl_view_get_element(v, i);
3187    plaintext = owl_strip_format_chars(owl_message_get_text(m));
3188    if (plaintext) {
3189      fputs(plaintext, file);
3190      owl_free(plaintext);
3191    }
3192  }
3193  fclose(file);
3194  owl_function_makemsg("Messages dumped to %s", filename);
3195}
3196
3197void owl_function_do_newmsgproc(void)
3198{
3199  if (owl_global_get_newmsgproc(&g) && strcmp(owl_global_get_newmsgproc(&g), "")) {
3200    /* if there's a process out there, we need to check on it */
3201    if (owl_global_get_newmsgproc_pid(&g)) {
3202      owl_function_debugmsg("Checking on newmsgproc pid==%i", owl_global_get_newmsgproc_pid(&g));
3203      owl_function_debugmsg("Waitpid return is %i", waitpid(owl_global_get_newmsgproc_pid(&g), NULL, WNOHANG));
3204      waitpid(owl_global_get_newmsgproc_pid(&g), NULL, WNOHANG);
3205      if (waitpid(owl_global_get_newmsgproc_pid(&g), NULL, WNOHANG)==-1) {
3206        /* it exited */
3207        owl_global_set_newmsgproc_pid(&g, 0);
3208        owl_function_debugmsg("newmsgproc exited");
3209      } else {
3210        owl_function_debugmsg("newmsgproc did not exit");
3211      }
3212    }
3213   
3214    /* if it exited, fork & exec a new one */
3215    if (owl_global_get_newmsgproc_pid(&g)==0) {
3216      pid_t i;
3217      int myargc;
3218      i=fork();
3219      if (i) {
3220        /* parent set the child's pid */
3221        owl_global_set_newmsgproc_pid(&g, i);
3222        owl_function_debugmsg("I'm the parent and I started a new newmsgproc with pid %i", i);
3223      } else {
3224        /* child exec's the program */
3225        char **parsed;
3226        parsed=owl_parseline(owl_global_get_newmsgproc(&g), &myargc);
3227        if (myargc < 0) {
3228          owl_function_debugmsg("Could not parse newmsgproc '%s': unbalanced quotes?", owl_global_get_newmsgproc(&g));
3229        }
3230        if (myargc <= 0) {
3231          _exit(127);
3232        }
3233        parsed=owl_realloc(parsed, sizeof(*parsed) * (myargc+1));
3234        parsed[myargc] = NULL;
3235       
3236        owl_function_debugmsg("About to exec \"%s\" with %d arguments", parsed[0], myargc);
3237       
3238        execvp(parsed[0], parsed);
3239       
3240       
3241        /* was there an error exec'ing? */
3242        owl_function_debugmsg("Cannot run newmsgproc '%s': cannot exec '%s': %s", 
3243                              owl_global_get_newmsgproc(&g), parsed[0], strerror(errno));
3244        _exit(127);
3245      }
3246    }
3247  }
3248}
3249
3250/* print the xterm escape sequence to raise the window */
3251void owl_function_xterm_raise(void)
3252{
3253  printf("\033[5t");
3254}
3255
3256/* print the xterm escape sequence to deiconify the window */
3257void owl_function_xterm_deiconify(void)
3258{
3259  printf("\033[1t");
3260}
3261
3262/* Add the specified command to the startup file.  Eventually this
3263 * should be clever, and rewriting settings that will obviosly
3264 * override earlier settings with 'set' 'bindkey' and 'alias'
3265 * commands.  For now though we just remove any line that would
3266 * duplicate this one and then append this line to the end of
3267 * startupfile.
3268 */
3269void owl_function_addstartup(const char *buff)
3270{
3271  FILE *file;
3272  const char *filename;
3273
3274  filename=owl_global_get_startupfile(&g);
3275  file=fopen(filename, "a");
3276  if (!file) {
3277    owl_function_error("Error opening startupfile for new command");
3278    return;
3279  }
3280
3281  /* delete earlier copies */
3282  owl_util_file_deleteline(filename, buff, 1);
3283
3284  /* add this line */
3285  fprintf(file, "%s\n", buff);
3286
3287  fclose(file);
3288}
3289
3290/* Remove the specified command from the startup file. */
3291void owl_function_delstartup(const char *buff)
3292{
3293  const char *filename;
3294  filename=owl_global_get_startupfile(&g);
3295  owl_util_file_deleteline(filename, buff, 1);
3296}
3297
3298/* Execute owl commands from the given filename.  If the filename
3299 * is NULL, use the default owl startup commands file.
3300 */
3301void owl_function_source(const char *filename)
3302{
3303  char *path;
3304  FILE *file;
3305  char *s = NULL;
3306  int fail_silent = 0;
3307
3308  if (!filename) {
3309    fail_silent = 1;
3310    path = owl_strdup(owl_global_get_startupfile(&g));
3311  } else {
3312    path = owl_util_makepath(filename);
3313  }
3314  file = fopen(path, "r");
3315  owl_free(path);
3316  if (!file) {
3317    if (!fail_silent) {
3318      owl_function_error("Error opening file: %s", filename);
3319    }
3320    return;
3321  }
3322  while (owl_getline_chomp(&s, file)) {
3323    if (s[0] == '\0' || s[0] == '#')
3324      continue;
3325    owl_function_command(s);
3326  }
3327
3328  owl_free(s);
3329  fclose(file);
3330}
3331
3332void owl_function_change_style(owl_view *v, const char *stylename)
3333{
3334  const owl_style *s;
3335
3336  s=owl_global_get_style_by_name(&g, stylename);
3337  if (!s) {
3338    owl_function_error("No style named %s", stylename);
3339    return;
3340  }
3341  owl_view_set_style(v, s);
3342  owl_messagelist_invalidate_formats(owl_global_get_msglist(&g));
3343  owl_function_calculate_topmsg(OWL_DIRECTION_DOWNWARDS);
3344  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
3345}
3346
3347void owl_function_toggleoneline(void)
3348{
3349  owl_view *v;
3350  const owl_style *s;
3351
3352  v=owl_global_get_current_view(&g);
3353  s=owl_view_get_style(v);
3354
3355  if (!owl_style_matches_name(s, "oneline")) {
3356    owl_function_change_style(v, "oneline");
3357  } else {
3358    owl_function_change_style(v, owl_global_get_default_style(&g));
3359  }
3360
3361  owl_messagelist_invalidate_formats(owl_global_get_msglist(&g));
3362  owl_function_calculate_topmsg(OWL_DIRECTION_DOWNWARDS);
3363  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
3364}
3365
3366void owl_function_error(const char *fmt, ...)
3367{
3368  static int in_error = 0;
3369  va_list ap;
3370  char *buff;
3371  const char *nl;
3372
3373  if (++in_error > 2) {
3374    /* More than two nested errors, bail immediately. */
3375    in_error--;
3376    return;
3377  }
3378
3379  va_start(ap, fmt);
3380  buff = g_strdup_vprintf(fmt, ap);
3381  va_end(ap);
3382
3383  owl_function_debugmsg("ERROR: %s", buff);
3384  owl_function_log_err(buff);
3385
3386  nl = strchr(buff, '\n');
3387
3388  /*
3389    Showing admin messages triggers a lot of code. If we have a
3390    recursive error call, that's the most likely candidate, so
3391    suppress the call in that case, to try to avoid infinite looping.
3392  */
3393
3394  if(nl && *(nl + 1) && in_error == 1) {
3395    /* Multiline error */
3396    owl_function_adminmsg("ERROR", buff);
3397  } else {
3398    owl_function_makemsg("[Error] %s", buff);
3399  }
3400
3401  owl_free(buff);
3402
3403  in_error--;
3404}
3405
3406void owl_function_log_err(const char *string)
3407{
3408  char *date;
3409  time_t now;
3410  char *buff;
3411
3412  now=time(NULL);
3413  date=owl_strdup(ctime(&now));
3414  date[strlen(date)-1]='\0';
3415
3416  buff = owl_sprintf("%s %s", date, string);
3417
3418  owl_errqueue_append_err(owl_global_get_errqueue(&g), buff);
3419
3420  owl_free(buff);
3421  owl_free(date);
3422}
3423
3424void owl_function_showerrs(void)
3425{
3426  owl_fmtext fm;
3427
3428  owl_fmtext_init_null(&fm);
3429  owl_fmtext_append_normal(&fm, "Errors:\n\n");
3430  owl_errqueue_to_fmtext(owl_global_get_errqueue(&g), &fm);
3431  owl_function_popless_fmtext(&fm);
3432}
3433
3434void owl_function_makemsg(const char *fmt, ...)
3435{
3436  va_list ap;
3437  char buff[2048];
3438
3439  if (!owl_global_get_curs_msgwin(&g)) return;
3440
3441  va_start(ap, fmt);
3442  werase(owl_global_get_curs_msgwin(&g));
3443 
3444  vsnprintf(buff, 2048, fmt, ap);
3445  owl_function_debugmsg("makemsg: %s", buff);
3446  waddstr(owl_global_get_curs_msgwin(&g), buff); 
3447  wnoutrefresh(owl_global_get_curs_msgwin(&g));
3448  owl_global_set_needrefresh(&g);
3449  va_end(ap);
3450}
3451
3452/* get locations for everyone in .anyone.  If 'notify' is '1' then
3453 * send a pseudo login or logout message for everyone not in sync with
3454 * the global zephyr buddy list.  The list is updated regardless of
3455 * the status of 'notify'.
3456 */
3457void owl_function_zephyr_buddy_check(int notify)
3458{
3459#ifdef HAVE_LIBZEPHYR
3460  int i, j;
3461  owl_list anyone;
3462  owl_message *m;
3463  owl_zbuddylist *zbl;
3464  const char *user;
3465  ZLocations_t location[200];
3466  int numlocs, ret;
3467
3468  if (!owl_global_is_havezephyr(&g)) return;
3469
3470  zbl=owl_global_get_zephyr_buddylist(&g);
3471
3472  owl_list_create(&anyone);
3473  ret=owl_zephyr_get_anyone_list(&anyone, NULL);
3474
3475  j=owl_list_get_size(&anyone);
3476  for (i=0; i<j; i++) {
3477    user=owl_list_get_element(&anyone, i);
3478    ret=ZLocateUser(zstr(user), &numlocs, ZAUTH);
3479    if (ret!=ZERR_NONE) {
3480      owl_function_error("Error getting location for %s", user);
3481      continue;
3482    }
3483    numlocs=200;
3484    ret=ZGetLocations(location, &numlocs);
3485    if (ret==0) {
3486      if ((numlocs>0) && !owl_zbuddylist_contains_user(zbl, user)) {
3487        /* Send a PSEUDO LOGIN! */
3488        if (notify) {
3489          m=owl_malloc(sizeof(owl_message));
3490          owl_message_create_pseudo_zlogin(m, 0, user, location[0].host, location[0].time, location[0].tty);
3491          owl_global_messagequeue_addmsg(&g, m);
3492        }
3493        owl_zbuddylist_adduser(zbl, user);
3494        owl_function_debugmsg("owl_function_zephyr_buddy_check: login for %s ", user);
3495      } else if ((numlocs==0) && owl_zbuddylist_contains_user(zbl, user)) {
3496        /* I don't think this ever happens (if there are 0 locations we should get an error from
3497         * ZGetLocations)
3498         */
3499        owl_function_error("owl_function_zephyr_buddy_check: exceptional case logout for %s ",user);
3500      }
3501    } else if ((ret==ZERR_NOLOCATIONS) && owl_zbuddylist_contains_user(zbl, user)) {
3502      /* Send a PSEUDO LOGOUT! */
3503      if (notify) {
3504        m=owl_malloc(sizeof(owl_message));
3505        owl_message_create_pseudo_zlogin(m, 1, user, "", "", "");
3506        owl_global_messagequeue_addmsg(&g, m);
3507      }
3508      owl_zbuddylist_deluser(zbl, user);
3509      owl_function_debugmsg("owl_function_zephyr_buddy_check: logout for %s ",user);
3510    }
3511  }
3512
3513  owl_list_free_all(&anyone, owl_free);
3514#endif
3515}
3516
3517void owl_function_aimsearch_results(const char *email, owl_list *namelist)
3518{
3519  owl_fmtext fm;
3520  int i, j;
3521
3522  owl_fmtext_init_null(&fm);
3523  owl_fmtext_append_normal(&fm, "AIM screennames associated with ");
3524  owl_fmtext_append_normal(&fm, email);
3525  owl_fmtext_append_normal(&fm, ":\n");
3526
3527  j=owl_list_get_size(namelist);
3528  for (i=0; i<j; i++) {
3529    owl_fmtext_append_normal(&fm, "  ");
3530    owl_fmtext_append_normal(&fm, owl_list_get_element(namelist, i));
3531    owl_fmtext_append_normal(&fm, "\n");
3532  }
3533
3534  owl_function_popless_fmtext(&fm);
3535  owl_fmtext_free(&fm);
3536}
3537
3538int owl_function_get_color_count(void)
3539{
3540     return COLORS;
3541}
3542
3543void owl_function_mask_sigint(sigset_t *oldmask) {
3544  sigset_t intr;
3545
3546  sigemptyset(&intr);
3547  sigaddset(&intr, SIGINT);
3548  sigprocmask(SIG_BLOCK, &intr, oldmask);
3549}
3550
3551void owl_function_unmask_sigint(sigset_t *oldmask) {
3552  sigset_t intr;
3553
3554  sigemptyset(&intr);
3555  sigaddset(&intr, SIGINT);
3556  sigprocmask(SIG_UNBLOCK, &intr, oldmask);
3557}
3558
3559void _owl_function_mark_message(const owl_message *m)
3560{
3561  if (m)
3562    owl_global_set_markedmsgid(&g, owl_message_get_id(m));
3563}
3564
3565void owl_function_mark_message(void)
3566{
3567  const owl_message *m;
3568  const owl_view *v;
3569
3570  v=owl_global_get_current_view(&g);
3571
3572  /* bail if there's no current message */
3573  if (owl_view_get_size(v) < 1) {
3574    owl_function_error("No messages to mark");
3575    return;
3576  }
3577
3578  /* mark the message */
3579  m=owl_view_get_element(v, owl_global_get_curmsg(&g));
3580  _owl_function_mark_message(m);
3581  owl_function_makemsg("Mark set");
3582}
3583
3584void owl_function_swap_cur_marked(void)
3585{
3586  int marked_id;
3587  const owl_message *m;
3588  const owl_view *v;
3589
3590  marked_id=owl_global_get_markedmsgid(&g);
3591  if (marked_id == -1) {
3592    owl_function_error("Mark not set.");
3593    return;
3594  }
3595
3596  v=owl_global_get_current_view(&g);
3597  /* bail if there's no current message */
3598  if (owl_view_get_size(v) < 1) {
3599    return;
3600  }
3601
3602  m=owl_view_get_element(v, owl_global_get_curmsg(&g));
3603  _owl_function_mark_message(m);
3604  owl_global_set_curmsg(&g, owl_view_get_nearest_to_msgid(v, marked_id));
3605  owl_function_calculate_topmsg(OWL_DIRECTION_NONE);
3606  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
3607  owl_global_set_direction_downwards(&g);
3608}
Note: See TracBrowser for help on using the repository browser.