source: functions.c @ 8ea0ffc

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