source: functions.c @ 050d25e

release-1.5
Last change on this file since 050d25e was a96b109, checked in by Nelson Elhage <nelhage@mit.edu>, 11 years ago
Add owl_message_delete to fix leaks. Signed-off-by: Anders Kaseorg <andersk@mit.edu> Reviewed-by: Alejandro R. Sedeño <asedeno@mit.edu>
  • Property mode set to 100644
File size: 97.1 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_delete(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      owl_free(newbuff);
2023      return out;
2024    } else if (type==2) {
2025      owl_function_adminmsg(buff, out);
2026    } else {
2027      owl_function_popless_text(out);
2028    }
2029    owl_free(out);
2030  }
2031  owl_free(newbuff);
2032  return NULL;
2033}
2034
2035char *owl_function_perl(int argc, const char *const *argv, const char *buff, int type)
2036{
2037  /* if type == 1 display in a popup
2038   * if type == 2 display an admin messages
2039   * if type == 0 return output
2040   * else display in a popup
2041   */
2042  char *perlout;
2043
2044  if (argc<2) {
2045    owl_function_error("Wrong number of arguments to perl command");
2046    return NULL;
2047  }
2048
2049  /* consume first token (argv[0]) */
2050  buff = skiptokens(buff, 1);
2051
2052  perlout = owl_perlconfig_execute(buff);
2053  if (perlout) { 
2054    if (type==1) {
2055      owl_function_popless_text(perlout);
2056    } else if (type==2) {
2057      owl_function_adminmsg(buff, perlout);
2058    } else if (type==0) {
2059      return perlout;
2060    } else {
2061      owl_function_popless_text(perlout);
2062    }
2063    owl_free(perlout);
2064  }
2065  return NULL;
2066}
2067
2068/* Change the filter associated with the current view.
2069 * This also figures out which message in the new filter
2070 * should have the pointer.
2071 */
2072void owl_function_change_currentview_filter(const char *filtname)
2073{
2074  owl_view *v;
2075  owl_filter *f;
2076  int curid=-1, newpos, curmsg;
2077  const owl_message *curm=NULL;
2078
2079  v=owl_global_get_current_view(&g);
2080
2081  curmsg=owl_global_get_curmsg(&g);
2082  if (curmsg==-1) {
2083    owl_function_debugmsg("Hit the curmsg==-1 case in change_view");
2084  } else {
2085    curm=owl_view_get_element(v, curmsg);
2086    if (curm) {
2087      curid=owl_message_get_id(curm);
2088      owl_view_save_curmsgid(v, curid);
2089    }
2090  }
2091
2092  f=owl_global_get_filter(&g, filtname);
2093  if (!f) {
2094    owl_function_error("Unknown filter %s", filtname);
2095    return;
2096  }
2097
2098  owl_view_new_filter(v, f);
2099
2100  /* Figure out what to set the current message to.
2101   * - If the view we're leaving has messages in it, go to the closest message
2102   *   to the last message pointed to in that view.
2103   * - If the view we're leaving is empty, try to restore the position
2104   *   from the last time we were in the new view.  */
2105  if (curm) {
2106    newpos = owl_view_get_nearest_to_msgid(v, curid);
2107  } else {
2108    newpos = owl_view_get_nearest_to_saved(v);
2109  }
2110
2111  owl_global_set_curmsg(&g, newpos);
2112  owl_function_calculate_topmsg(OWL_DIRECTION_DOWNWARDS);
2113  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
2114  owl_global_set_direction_downwards(&g);
2115}
2116
2117/* Create a new filter, or replace an existing one
2118 * with a new definition.
2119 */
2120void owl_function_create_filter(int argc, const char *const *argv)
2121{
2122  owl_filter *f;
2123  const owl_view *v;
2124  int inuse = 0;
2125
2126  if (argc < 2) {
2127    owl_function_error("Wrong number of arguments to filter command");
2128    return;
2129  }
2130
2131  owl_function_debugmsg("owl_function_create_filter: starting to create filter named %s", argv[1]);
2132
2133  v=owl_global_get_current_view(&g);
2134
2135  /* don't touch the all filter */
2136  if (!strcmp(argv[1], "all")) {
2137    owl_function_error("You may not change the 'all' filter.");
2138    return;
2139  }
2140
2141  /* deal with the case of trying change the filter color */
2142  if (argc==4 && !strcmp(argv[2], "-c")) {
2143    f=owl_global_get_filter(&g, argv[1]);
2144    if (!f) {
2145      owl_function_error("The filter '%s' does not exist.", argv[1]);
2146      return;
2147    }
2148    if (owl_util_string_to_color(argv[3])==OWL_COLOR_INVALID) {
2149      owl_function_error("The color '%s' is not available.", argv[3]);
2150      return;
2151    }
2152    owl_filter_set_fgcolor(f, owl_util_string_to_color(argv[3]));
2153    owl_global_set_needrefresh(&g);
2154    owl_mainwin_redisplay(owl_global_get_mainwin(&g));
2155    return;
2156  }
2157  if (argc==4 && !strcmp(argv[2], "-b")) {
2158    f=owl_global_get_filter(&g, argv[1]);
2159    if (!f) {
2160      owl_function_error("The filter '%s' does not exist.", argv[1]);
2161      return;
2162    }
2163    if (owl_util_string_to_color(argv[3])==OWL_COLOR_INVALID) {
2164      owl_function_error("The color '%s' is not available.", argv[3]);
2165      return;
2166    }
2167    owl_filter_set_bgcolor(f, owl_util_string_to_color(argv[3]));
2168    owl_global_set_needrefresh(&g);
2169    owl_mainwin_redisplay(owl_global_get_mainwin(&g));
2170    return;
2171  }
2172
2173  /* create the filter and check for errors */
2174  f = owl_filter_new(argv[1], argc-2, argv+2);
2175  if (f == NULL) {
2176    owl_function_error("Invalid filter");
2177    return;
2178  }
2179
2180  /* if the named filter is in use by the current view, remember it */
2181  if (!strcmp(owl_view_get_filtname(v), argv[1])) {
2182    inuse=1;
2183  }
2184
2185  /* if the named filter already exists, nuke it */
2186  if (owl_global_get_filter(&g, argv[1])) {
2187    owl_global_remove_filter(&g, argv[1]);
2188  }
2189
2190  /* add the filter */
2191  owl_global_add_filter(&g, f);
2192
2193  /* if it was in use by the current view then update */
2194  if (inuse) {
2195    owl_function_change_currentview_filter(argv[1]);
2196  }
2197  owl_global_set_needrefresh(&g);
2198  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
2199}
2200
2201/* If 'filtername' does not start with 'not-' create a filter named
2202 * 'not-<filtername>' defined as "not filter <filtername>".  If the
2203 * filter 'not-<filtername>' already exists, do not overwrite it.  If
2204 * 'filtername' begins with 'not-' and a filter 'filtername' already
2205 * exists, then do nothing.  If the filter 'filtername' does not
2206 * exist, create it and define it as 'not filter <filtername>'
2207 *
2208 * Returns the name of the negated filter, which the caller must free.
2209 */
2210char *owl_function_create_negative_filter(const char *filtername)
2211{
2212  char *newname;
2213  const owl_filter *tmpfilt;
2214  const char *argv[5];
2215
2216  owl_function_debugmsg("owl_function_create_negative_filter");
2217 
2218  if (!strncmp(filtername, "not-", 4)) {
2219    newname=owl_strdup(filtername+4);
2220  } else {
2221    newname=owl_sprintf("not-%s", filtername);
2222  }
2223
2224  tmpfilt=owl_global_get_filter(&g, newname);
2225  if (!tmpfilt) {
2226    argv[0]="filter"; /* anything is fine here */
2227    argv[1]=newname;
2228    argv[2]="not";
2229    argv[3]="filter";
2230    argv[4]=filtername;
2231    owl_function_create_filter(5, argv);
2232  }
2233
2234  owl_function_debugmsg("owl_function_create_negative_filter: returning with %s", newname);
2235  return(newname);
2236}
2237
2238void owl_function_show_filters(void)
2239{
2240  const owl_filter *f;
2241  GList *fl;
2242  owl_fmtext fm;
2243
2244  owl_fmtext_init_null(&fm);
2245
2246  owl_fmtext_append_bold(&fm, "Filters:\n");
2247
2248  for (fl = g.filterlist; fl; fl = g_list_next(fl)) {
2249    f = fl->data;
2250    owl_fmtext_append_normal(&fm, "   ");
2251    if (owl_global_get_hascolors(&g)) {
2252      owl_fmtext_append_normal_color(&fm, owl_filter_get_name(f), owl_filter_get_fgcolor(f), owl_filter_get_bgcolor(f));
2253    } else {
2254      owl_fmtext_append_normal(&fm, owl_filter_get_name(f));
2255    }
2256    owl_fmtext_append_normal(&fm, "\n");
2257  }
2258  owl_function_popless_fmtext(&fm);
2259  owl_fmtext_free(&fm);
2260}
2261
2262void owl_function_show_filter(const char *name)
2263{
2264  const owl_filter *f;
2265  char *buff, *tmp;
2266
2267  f=owl_global_get_filter(&g, name);
2268  if (!f) {
2269    owl_function_error("There is no filter named %s", name);
2270    return;
2271  }
2272  tmp = owl_filter_print(f);
2273  buff = owl_sprintf("%s: %s", owl_filter_get_name(f), tmp);
2274  owl_function_popless_text(buff);
2275  owl_free(buff);
2276  owl_free(tmp);
2277}
2278
2279void owl_function_show_zpunts(void)
2280{
2281  const owl_filter *f;
2282  const owl_list *fl;
2283  char buff[5000];
2284  char *tmp;
2285  owl_fmtext fm;
2286  int i, j;
2287
2288  owl_fmtext_init_null(&fm);
2289
2290  fl=owl_global_get_puntlist(&g);
2291  j=owl_list_get_size(fl);
2292  owl_fmtext_append_bold(&fm, "Active zpunt filters:\n");
2293
2294  for (i=0; i<j; i++) {
2295    f=owl_list_get_element(fl, i);
2296    snprintf(buff, sizeof(buff), "[% 2d] ", i+1);
2297    owl_fmtext_append_normal(&fm, buff);
2298    tmp = owl_filter_print(f);
2299    owl_fmtext_append_normal(&fm, tmp);
2300    owl_free(tmp);
2301  }
2302  owl_function_popless_fmtext(&fm);
2303  owl_fmtext_free(&fm);
2304}
2305
2306/* Create a filter for a class, instance if one doesn't exist.  If
2307 * instance is NULL then catch all messgaes in the class.  Returns the
2308 * name of the filter, which the caller must free.
2309 */
2310char *owl_function_classinstfilt(const char *c, const char *i) 
2311{
2312  owl_filter *f;
2313  char *argbuff, *filtname;
2314  char *tmpclass, *tmpinstance = NULL;
2315  char *class, *instance = NULL;
2316
2317  class = owl_util_baseclass(c);
2318  if(i) {
2319    instance = owl_util_baseclass(i);
2320  }
2321
2322  /* name for the filter */
2323  if (!instance) {
2324    filtname = owl_sprintf("class-%s", class);
2325  } else {
2326    filtname = owl_sprintf("class-%s-instance-%s", class, instance);
2327  }
2328  /* downcase it */
2329  {
2330    char *temp = g_utf8_strdown(filtname, -1);
2331    if (temp) {
2332      owl_free(filtname);
2333      filtname = temp;
2334    }
2335  }
2336  /* turn spaces, single quotes, and double quotes into dots */
2337  owl_text_tr(filtname, ' ', '.');
2338  owl_text_tr(filtname, '\'', '.');
2339  owl_text_tr(filtname, '"', '.');
2340 
2341  /* if it already exists then go with it.  This lets users override */
2342  if (owl_global_get_filter(&g, filtname)) {
2343    return(filtname);
2344  }
2345
2346  /* create the new filter */
2347  tmpclass=owl_text_quote(class, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2348  owl_text_tr(tmpclass, ' ', '.');
2349  owl_text_tr(tmpclass, '\'', '.');
2350  owl_text_tr(tmpclass, '"', '.');
2351  if (instance) {
2352    tmpinstance=owl_text_quote(instance, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2353    owl_text_tr(tmpinstance, ' ', '.');
2354    owl_text_tr(tmpinstance, '\'', '.');
2355    owl_text_tr(tmpinstance, '"', '.');
2356  }
2357
2358  argbuff = owl_sprintf("class ^(un)*%s(\\.d)*$", tmpclass);
2359  if (tmpinstance) {
2360    char *tmp = argbuff;
2361    argbuff = owl_sprintf("%s and ( instance ^(un)*%s(\\.d)*$ )", tmp, tmpinstance);
2362    owl_free(tmp);
2363  }
2364  owl_free(tmpclass);
2365  if (tmpinstance) owl_free(tmpinstance);
2366
2367  f = owl_filter_new_fromstring(filtname, argbuff);
2368
2369  /* add it to the global list */
2370  owl_global_add_filter(&g, f);
2371
2372  owl_free(argbuff);
2373  owl_free(class);
2374  if (instance) {
2375    owl_free(instance);
2376  }
2377  return(filtname);
2378}
2379
2380/* Create a filter for personal zephyrs to or from the specified
2381 * zephyr user.  Includes login/logout notifications for the user.
2382 * The name of the filter will be 'user-<user>'.  If a filter already
2383 * exists with this name, no new filter will be created.  This allows
2384 * the configuration to override this function.  Returns the name of
2385 * the filter, which the caller must free.
2386 */
2387char *owl_function_zuserfilt(const char *user)
2388{
2389  owl_filter *f;
2390  char *argbuff, *longuser, *esclonguser, *shortuser, *filtname;
2391
2392  /* stick the local realm on if it's not there */
2393  longuser=long_zuser(user);
2394  shortuser=short_zuser(user);
2395
2396  /* name for the filter */
2397  filtname=owl_sprintf("user-%s", shortuser);
2398
2399  /* if it already exists then go with it.  This lets users override */
2400  if (owl_global_get_filter(&g, filtname)) {
2401    return(owl_strdup(filtname));
2402  }
2403
2404  /* create the new-internal filter */
2405  esclonguser = owl_text_quote(longuser, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2406
2407  argbuff=owl_sprintf("( type ^zephyr$ and filter personal and "
2408      "( ( direction ^in$ and sender ^%1$s$ ) or ( direction ^out$ and "
2409      "recipient ^%1$s$ ) ) ) or ( ( class ^login$ ) and ( sender ^%1$s$ ) )",
2410      esclonguser);
2411
2412  f = owl_filter_new_fromstring(filtname, argbuff);
2413
2414  /* add it to the global list */
2415  owl_global_add_filter(&g, f);
2416
2417  /* free stuff */
2418  owl_free(argbuff);
2419  owl_free(longuser);
2420  owl_free(esclonguser);
2421  owl_free(shortuser);
2422
2423  return(filtname);
2424}
2425
2426/* Create a filter for AIM IM messages to or from the specified
2427 * screenname.  The name of the filter will be 'aimuser-<user>'.  If a
2428 * filter already exists with this name, no new filter will be
2429 * created.  This allows the configuration to override this function.
2430 * Returns the name of the filter, which the caller must free.
2431 */
2432char *owl_function_aimuserfilt(const char *user)
2433{
2434  owl_filter *f;
2435  char *argbuff, *filtname;
2436  char *escuser;
2437
2438  /* name for the filter */
2439  filtname=owl_sprintf("aimuser-%s", user);
2440
2441  /* if it already exists then go with it.  This lets users override */
2442  if (owl_global_get_filter(&g, filtname)) {
2443    return(owl_strdup(filtname));
2444  }
2445
2446  /* create the new-internal filter */
2447  escuser = owl_text_quote(user, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2448
2449  argbuff = owl_sprintf(
2450      "( type ^aim$ and ( ( sender ^%1$s$ and recipient ^%2$s$ ) or "
2451      "( sender ^%2$s$ and recipient ^%1$s$ ) ) )",
2452      escuser, owl_global_get_aim_screenname_for_filters(&g));
2453
2454  f = owl_filter_new_fromstring(filtname, argbuff);
2455
2456  /* add it to the global list */
2457  owl_global_add_filter(&g, f);
2458
2459  /* free stuff */
2460  owl_free(argbuff);
2461  owl_free(escuser);
2462
2463  return(filtname);
2464}
2465
2466char *owl_function_typefilt(const char *type)
2467{
2468  owl_filter *f;
2469  char *argbuff, *filtname, *esctype;
2470
2471  /* name for the filter */
2472  filtname=owl_sprintf("type-%s", type);
2473
2474  /* if it already exists then go with it.  This lets users override */
2475  if (owl_global_get_filter(&g, filtname)) {
2476    return filtname;
2477  }
2478
2479  /* create the new-internal filter */
2480  f=owl_malloc(sizeof(owl_filter));
2481
2482  esctype = owl_text_quote(type, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2483
2484  argbuff = owl_sprintf("type ^%s$", esctype);
2485
2486  f = owl_filter_new_fromstring(filtname, argbuff);
2487
2488  /* add it to the global list */
2489  owl_global_add_filter(&g, f);
2490
2491  /* free stuff */
2492  owl_free(argbuff);
2493  owl_free(esctype);
2494
2495  return filtname;
2496}
2497
2498/* If flag is 1, marks for deletion.  If flag is 0,
2499 * unmarks for deletion. */
2500void owl_function_delete_curview_msgs(int flag)
2501{
2502  const owl_view *v;
2503  int i, j;
2504
2505  v=owl_global_get_current_view(&g);
2506  j=owl_view_get_size(v);
2507  for (i=0; i<j; i++) {
2508    if (flag == 1) {
2509      owl_message_mark_delete(owl_view_get_element(v, i));
2510    } else if (flag == 0) {
2511      owl_message_unmark_delete(owl_view_get_element(v, i));
2512    }
2513  }
2514
2515  owl_function_makemsg("%i messages marked for %sdeletion", j, flag?"":"un");
2516
2517  owl_mainwin_redisplay(owl_global_get_mainwin(&g)); 
2518}
2519
2520/* Create a filter based on the current message.  Returns the name of
2521 * a filter or null.  The caller must free this name.
2522 *
2523 * if the curmsg is a personal zephyr return a filter name
2524 *    to the zephyr conversation with that user.
2525 * If the curmsg is a zephyr class message, instance foo, recip *,
2526 *    return a filter name to the class, inst.
2527 * If the curmsg is a zephyr class message and type==0 then
2528 *    return a filter name for just the class.
2529 * If the curmsg is a zephyr class message and type==1 then
2530 *    return a filter name for the class and instance.
2531 * If the curmsg is a personal AIM message returna  filter
2532 *    name to the AIM conversation with that user
2533 */
2534char *owl_function_smartfilter(int type)
2535{
2536  const owl_view *v;
2537  const owl_message *m;
2538  char *zperson, *filtname=NULL;
2539  const char *argv[1];
2540 
2541  v=owl_global_get_current_view(&g);
2542  m=owl_view_get_element(v, owl_global_get_curmsg(&g));
2543
2544  if (!m || owl_view_get_size(v)==0) {
2545    owl_function_error("No message selected\n");
2546    return(NULL);
2547  }
2548
2549  /* very simple handling of admin messages for now */
2550  if (owl_message_is_type_admin(m)) {
2551    return(owl_function_typefilt("admin"));
2552  }
2553
2554  /* very simple handling of loopback messages for now */
2555  if (owl_message_is_type_loopback(m)) {
2556    return(owl_function_typefilt("loopback"));
2557  }
2558
2559  /* aim messages */
2560  if (owl_message_is_type_aim(m)) {
2561    if (owl_message_is_direction_in(m)) {
2562      filtname=owl_function_aimuserfilt(owl_message_get_sender(m));
2563    } else if (owl_message_is_direction_out(m)) {
2564      filtname=owl_function_aimuserfilt(owl_message_get_recipient(m));
2565    }
2566    return(filtname);
2567  }
2568
2569  /* narrow personal and login messages to the sender or recip as appropriate */
2570  if (owl_message_is_type_zephyr(m)) {
2571    if (owl_message_is_personal(m) || owl_message_is_loginout(m)) {
2572      if (owl_message_is_direction_in(m)) {
2573        zperson=short_zuser(owl_message_get_sender(m));
2574      } else {
2575        zperson=short_zuser(owl_message_get_recipient(m));
2576      }
2577      filtname=owl_function_zuserfilt(zperson);
2578      owl_free(zperson);
2579      return(filtname);
2580    }
2581
2582    /* narrow class MESSAGE, instance foo, recip * messages to class, inst */
2583    if (!strcasecmp(owl_message_get_class(m), "message")) {
2584      filtname=owl_function_classinstfilt(owl_message_get_class(m), owl_message_get_instance(m));
2585      return(filtname);
2586    }
2587
2588    /* otherwise narrow to the class */
2589    if (type==0) {
2590      filtname=owl_function_classinstfilt(owl_message_get_class(m), NULL);
2591    } else if (type==1) {
2592      filtname=owl_function_classinstfilt(owl_message_get_class(m), owl_message_get_instance(m));
2593    }
2594    return(filtname);
2595  }
2596
2597  /* pass it off to perl */
2598  if(type) {
2599    argv[0] = "-i";
2600  };
2601  return owl_perlconfig_message_call_method(m, "smartfilter", type ? 1 : 0, argv);
2602}
2603
2604void owl_function_smartzpunt(int type)
2605{
2606  /* Starts a zpunt command based on the current class,instance pair.
2607   * If type=0, uses just class.  If type=1, uses instance as well. */
2608  const owl_view *v;
2609  const owl_message *m;
2610  const char *cmdprefix, *mclass, *minst;
2611  char *cmd;
2612 
2613  v=owl_global_get_current_view(&g);
2614  m=owl_view_get_element(v, owl_global_get_curmsg(&g));
2615
2616  if (!m || owl_view_get_size(v)==0) {
2617    owl_function_error("No message selected\n");
2618    return;
2619  }
2620
2621  /* for now we skip admin messages. */
2622  if (owl_message_is_type_admin(m)
2623      || owl_message_is_loginout(m)
2624      || !owl_message_is_type_zephyr(m)) {
2625    owl_function_error("smartzpunt doesn't support this message type.");
2626    return;
2627  }
2628
2629  mclass = owl_message_get_class(m);
2630  minst = owl_message_get_instance(m);
2631  if (!mclass || !*mclass || *mclass==' '
2632      || (!strcasecmp(mclass, "message") && !strcasecmp(minst, "personal"))
2633      || (type && (!minst || !*minst|| *minst==' '))) {
2634    owl_function_error("smartzpunt can't safely do this for <%s,%s>",
2635                         mclass, minst);
2636  } else {
2637    cmdprefix = "start-command zpunt ";
2638    cmd = owl_malloc(strlen(cmdprefix)+strlen(mclass)+strlen(minst)+10);
2639    strcpy(cmd, cmdprefix);
2640    strcat(cmd, owl_getquoting(mclass));
2641    strcat(cmd, mclass);
2642    strcat(cmd, owl_getquoting(mclass));
2643    if (type) {
2644      strcat(cmd, " ");
2645      strcat(cmd, owl_getquoting(minst));
2646      strcat(cmd, minst);
2647      strcat(cmd, owl_getquoting(minst));
2648    } else {
2649      strcat(cmd, " *");
2650    }
2651    owl_function_command(cmd);
2652    owl_free(cmd);
2653  }
2654}
2655
2656/* Set the color of the current view's filter to
2657 * be 'color'
2658 */
2659void owl_function_color_current_filter(const char *fgcolor, const char *bgcolor)
2660{
2661  const char *name;
2662
2663  name=owl_view_get_filtname(owl_global_get_current_view(&g));
2664  owl_function_color_filter(name, fgcolor, bgcolor);
2665}
2666
2667/* Set the color of the filter 'filter' to be 'color'.  If the color
2668 * name does not exist, return -1, if the filter does not exist or is
2669 * the "all" filter, return -2.  Return 0 on success
2670 */
2671int owl_function_color_filter(const char *filtname, const char *fgcolor, const char *bgcolor)
2672{
2673  owl_filter *f;
2674
2675  f=owl_global_get_filter(&g, filtname);
2676  if (!f) {
2677    owl_function_error("Unknown filter");
2678    return(-2);
2679  }
2680
2681  /* don't touch the all filter */
2682  if (!strcmp(filtname, "all")) {
2683    owl_function_error("You may not change the 'all' filter.");
2684    return(-2);
2685  }
2686
2687  if (owl_util_string_to_color(fgcolor)==OWL_COLOR_INVALID) {
2688    owl_function_error("No color named '%s' avilable.", fgcolor);
2689    return(-1);
2690  }
2691
2692
2693  if (bgcolor != NULL) {
2694    if (owl_util_string_to_color(bgcolor)==OWL_COLOR_INVALID) {
2695      owl_function_error("No color named '%s' avilable.", bgcolor);
2696      return(-1);
2697    }
2698    owl_filter_set_bgcolor(f, owl_util_string_to_color(bgcolor));
2699  }
2700  owl_filter_set_fgcolor(f, owl_util_string_to_color(fgcolor));
2701 
2702  owl_global_set_needrefresh(&g);
2703  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
2704  return(0);
2705}
2706
2707void owl_function_show_colors(void)
2708{
2709  owl_fmtext fm;
2710  int i; 
2711 
2712  owl_fmtext_init_null(&fm);
2713  owl_fmtext_append_normal(&fm, "default: ");
2714  owl_fmtext_append_normal_color(&fm, "default\n", OWL_COLOR_DEFAULT, OWL_COLOR_DEFAULT);
2715
2716  owl_fmtext_append_normal(&fm,"red:      ");
2717  owl_fmtext_append_normal_color(&fm, "red\n", OWL_COLOR_RED, OWL_COLOR_DEFAULT);
2718
2719  owl_fmtext_append_normal(&fm,"green:    ");
2720  owl_fmtext_append_normal_color(&fm, "green\n", OWL_COLOR_GREEN, OWL_COLOR_DEFAULT);
2721
2722  owl_fmtext_append_normal(&fm,"yellow:   ");
2723  owl_fmtext_append_normal_color(&fm, "yellow\n", OWL_COLOR_YELLOW, OWL_COLOR_DEFAULT);
2724
2725  owl_fmtext_append_normal(&fm,"blue:     ");
2726  owl_fmtext_append_normal_color(&fm, "blue\n", OWL_COLOR_BLUE, OWL_COLOR_DEFAULT);
2727
2728  owl_fmtext_append_normal(&fm,"magenta:  ");
2729  owl_fmtext_append_normal_color(&fm, "magenta\n", OWL_COLOR_MAGENTA, OWL_COLOR_DEFAULT);
2730
2731  owl_fmtext_append_normal(&fm,"cyan:     ");
2732  owl_fmtext_append_normal_color(&fm, "cyan\n", OWL_COLOR_CYAN, OWL_COLOR_DEFAULT);
2733
2734  owl_fmtext_append_normal(&fm,"white:    ");
2735  owl_fmtext_append_normal_color(&fm, "white\n", OWL_COLOR_WHITE, OWL_COLOR_DEFAULT);
2736
2737  for(i = 8; i < COLORS; ++i) {
2738    char* str1 = owl_sprintf("%4i:     ",i);
2739    char* str2 = owl_sprintf("%i\n",i);
2740    owl_fmtext_append_normal(&fm,str1);
2741    owl_fmtext_append_normal_color(&fm, str2, i, OWL_COLOR_DEFAULT);
2742    owl_free(str1);
2743     owl_free(str2);
2744  }
2745 
2746  owl_function_popless_fmtext(&fm);
2747  owl_fmtext_free(&fm);
2748}
2749
2750/* add the given class, inst, recip to the punt list for filtering.
2751 *   if direction==0 then punt
2752 *   if direction==1 then unpunt
2753 */
2754void owl_function_zpunt(const char *class, const char *inst, const char *recip, int direction)
2755{
2756  char *puntexpr, *classexpr, *instexpr, *recipexpr;
2757  char *quoted;
2758
2759  if (!strcmp(class, "*")) {
2760    classexpr = owl_sprintf("class .*");
2761  } else {
2762    quoted=owl_text_quote(class, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2763    owl_text_tr(quoted, ' ', '.');
2764    owl_text_tr(quoted, '\'', '.');
2765    owl_text_tr(quoted, '"', '.');
2766    classexpr = owl_sprintf("class ^(un)*%s(\\.d)*$", quoted);
2767    owl_free(quoted);
2768  }
2769  if (!strcmp(inst, "*")) {
2770    instexpr = owl_sprintf(" and instance .*");
2771  } else {
2772    quoted=owl_text_quote(inst, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2773    owl_text_tr(quoted, ' ', '.');
2774    owl_text_tr(quoted, '\'', '.');
2775    owl_text_tr(quoted, '"', '.');
2776    instexpr = owl_sprintf(" and instance ^(un)*%s(\\.d)*$", quoted);
2777    owl_free(quoted);
2778  }
2779  if (!strcmp(recip, "*")) {
2780    recipexpr = owl_sprintf("");
2781  } else {
2782    if(!strcmp(recip, "%me%")) {
2783      recip = owl_zephyr_get_sender();
2784    }
2785    quoted=owl_text_quote(recip, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
2786    owl_text_tr(quoted, ' ', '.');
2787    owl_text_tr(quoted, '\'', '.');
2788    owl_text_tr(quoted, '"', '.');
2789    recipexpr = owl_sprintf(" and recipient ^%s$", quoted);
2790    owl_free(quoted);
2791  }
2792
2793  puntexpr = owl_sprintf("%s %s %s", classexpr, instexpr, recipexpr);
2794  owl_function_punt(puntexpr, direction);
2795  owl_free(puntexpr);
2796  owl_free(classexpr);
2797  owl_free(instexpr);
2798  owl_free(recipexpr);
2799}
2800
2801void owl_function_punt(const char *filter, int direction)
2802{
2803  owl_filter *f;
2804  owl_list *fl;
2805  int i, j;
2806  fl=owl_global_get_puntlist(&g);
2807
2808  /* first, create the filter */
2809  owl_function_debugmsg("About to filter %s", filter);
2810  f = owl_filter_new_fromstring("punt-filter", filter);
2811  if (f == NULL) {
2812    owl_function_error("Error creating filter for zpunt");
2813    return;
2814  }
2815
2816  /* Check for an identical filter */
2817  j=owl_list_get_size(fl);
2818  for (i=0; i<j; i++) {
2819    if (owl_filter_equiv(f, owl_list_get_element(fl, i))) {
2820      owl_function_debugmsg("found an equivalent punt filter");
2821      /* if we're punting, then just silently bow out on this duplicate */
2822      if (direction==0) {
2823        owl_filter_delete(f);
2824        return;
2825      }
2826
2827      /* if we're unpunting, then remove this filter from the puntlist */
2828      if (direction==1) {
2829        owl_filter_delete(owl_list_get_element(fl, i));
2830        owl_list_remove_element(fl, i);
2831        owl_filter_delete(f);
2832        return;
2833      }
2834    }
2835  }
2836
2837  owl_function_debugmsg("punting");
2838  /* If we're punting, add the filter to the global punt list */
2839  if (direction==0) {
2840    owl_list_append_element(fl, f);
2841  }
2842}
2843
2844void owl_function_activate_keymap(const char *keymap)
2845{
2846  if (!owl_keyhandler_activate(owl_global_get_keyhandler(&g), keymap)) {
2847    owl_function_error("Unable to activate keymap '%s'", keymap);
2848  }
2849}
2850
2851void owl_function_show_keymaps(void)
2852{
2853  owl_list l;
2854  owl_fmtext fm;
2855  const owl_keymap *km;
2856  const owl_keyhandler *kh;
2857  int i, numkm;
2858  const char *kmname;
2859
2860  kh = owl_global_get_keyhandler(&g);
2861  owl_fmtext_init_null(&fm);
2862  owl_fmtext_append_bold(&fm, "Keymaps:   ");
2863  owl_fmtext_append_normal(&fm, "(use 'show keymap <name>' for details)\n");
2864  owl_keyhandler_get_keymap_names(kh, &l);
2865  owl_fmtext_append_list(&fm, &l, "\n", owl_function_keymap_summary);
2866  owl_fmtext_append_normal(&fm, "\n");
2867
2868  numkm = owl_list_get_size(&l);
2869  for (i=0; i<numkm; i++) {
2870    kmname = owl_list_get_element(&l, i);
2871    km = owl_keyhandler_get_keymap(kh, kmname);
2872    owl_fmtext_append_bold(&fm, "\n\n----------------------------------------------------------------------------------------------------\n\n");
2873    owl_keymap_get_details(km, &fm);   
2874  }
2875  owl_fmtext_append_normal(&fm, "\n");
2876 
2877  owl_function_popless_fmtext(&fm);
2878  owl_keyhandler_keymap_namelist_free(&l);
2879  owl_fmtext_free(&fm);
2880}
2881
2882char *owl_function_keymap_summary(const char *name)
2883{
2884  const owl_keymap *km
2885    = owl_keyhandler_get_keymap(owl_global_get_keyhandler(&g), name);
2886  if (km) return owl_keymap_summary(km);
2887  else return(NULL);
2888}
2889
2890/* TODO: implement for real */
2891void owl_function_show_keymap(const char *name)
2892{
2893  owl_fmtext fm;
2894  const owl_keymap *km;
2895
2896  owl_fmtext_init_null(&fm);
2897  km = owl_keyhandler_get_keymap(owl_global_get_keyhandler(&g), name);
2898  if (km) {
2899    owl_keymap_get_details(km, &fm);
2900  } else {
2901    owl_fmtext_append_normal(&fm, "No such keymap...\n");
2902  } 
2903  owl_function_popless_fmtext(&fm);
2904  owl_fmtext_free(&fm);
2905}
2906
2907void owl_function_help_for_command(const char *cmdname)
2908{
2909  owl_fmtext fm;
2910
2911  owl_fmtext_init_null(&fm);
2912  owl_cmd_get_help(owl_global_get_cmddict(&g), cmdname, &fm);
2913  owl_function_popless_fmtext(&fm); 
2914  owl_fmtext_free(&fm);
2915}
2916
2917void owl_function_search_start(const char *string, int direction)
2918{
2919  /* direction is OWL_DIRECTION_DOWNWARDS or OWL_DIRECTION_UPWARDS or
2920   * OWL_DIRECTION_NONE */
2921  owl_regex re;
2922
2923  if (string && owl_regex_create_quoted(&re, string) == 0) {
2924    owl_global_set_search_re(&g, &re);
2925    owl_regex_free(&re);
2926  } else {
2927    owl_global_set_search_re(&g, NULL);
2928  }
2929
2930  if (direction == OWL_DIRECTION_NONE)
2931    owl_mainwin_redisplay(owl_global_get_mainwin(&g));
2932  else
2933    owl_function_search_helper(0, direction);
2934}
2935
2936void owl_function_search_continue(int direction)
2937{
2938  /* direction is OWL_DIRECTION_DOWNWARDS or OWL_DIRECTION_UPWARDS */
2939  owl_function_search_helper(1, direction);
2940}
2941
2942void owl_function_search_helper(int mode, int direction)
2943{
2944  /* move to a message that contains the string.  If direction is
2945   * OWL_DIRECTION_DOWNWARDS then search fowards, if direction is
2946   * OWL_DIRECTION_UPWARDS then search backwards.
2947   *
2948   * If mode==0 then it will stay on the current message if it
2949   * contains the string.
2950   */
2951
2952  const owl_view *v;
2953  int viewsize, i, curmsg, start;
2954  owl_message *m;
2955
2956  v=owl_global_get_current_view(&g);
2957  viewsize=owl_view_get_size(v);
2958  curmsg=owl_global_get_curmsg(&g);
2959 
2960  if (viewsize==0) {
2961    owl_function_error("No messages present");
2962    return;
2963  }
2964
2965  if (mode==0) {
2966    start=curmsg;
2967  } else if (direction==OWL_DIRECTION_DOWNWARDS) {
2968    start=curmsg+1;
2969  } else {
2970    start=curmsg-1;
2971  }
2972
2973  /* bounds check */
2974  if (start>=viewsize || start<0) {
2975    owl_function_error("No further matches found");
2976    return;
2977  }
2978
2979  for (i=start; i<viewsize && i>=0;) {
2980    m=owl_view_get_element(v, i);
2981    if (owl_message_search(m, owl_global_get_search_re(&g))) {
2982      owl_global_set_curmsg(&g, i);
2983      owl_function_calculate_topmsg(direction);
2984      owl_mainwin_redisplay(owl_global_get_mainwin(&g));
2985      if (direction==OWL_DIRECTION_DOWNWARDS) {
2986        owl_global_set_direction_downwards(&g);
2987      } else {
2988        owl_global_set_direction_upwards(&g);
2989      }
2990      return;
2991    }
2992    if (direction==OWL_DIRECTION_DOWNWARDS) {
2993      i++;
2994    } else {
2995      i--;
2996    }
2997    owl_function_mask_sigint(NULL);
2998    if(owl_global_is_interrupted(&g)) {
2999      owl_global_unset_interrupted(&g);
3000      owl_function_unmask_sigint(NULL);
3001      owl_function_makemsg("Search interrupted!");
3002      owl_mainwin_redisplay(owl_global_get_mainwin(&g));
3003      return;
3004    }
3005    owl_function_unmask_sigint(NULL);
3006  }
3007  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
3008  owl_function_error("No matches found");
3009}
3010
3011/* strips formatting from ztext and returns the unformatted text.
3012 * caller is responsible for freeing. */
3013char *owl_function_ztext_stylestrip(const char *zt)
3014{
3015  owl_fmtext fm;
3016  char *plaintext;
3017
3018  owl_fmtext_init_null(&fm);
3019  owl_fmtext_append_ztext(&fm, zt);
3020  plaintext = owl_fmtext_print_plain(&fm);
3021  owl_fmtext_free(&fm);
3022  return(plaintext);
3023}
3024
3025/* Popup a buddylisting.  If filename is NULL use the default .anyone */
3026void owl_function_buddylist(int aim, int zephyr, const char *filename)
3027{
3028  int i, j, idle;
3029  int interrupted = 0;
3030  owl_fmtext fm;
3031  const owl_buddylist *bl;
3032  const owl_buddy *b;
3033  char *timestr;
3034#ifdef HAVE_LIBZEPHYR
3035  int x;
3036  owl_list anyone;
3037  const char *user;
3038  char *tmp;
3039  ZLocations_t location[200];
3040  int numlocs, ret;
3041#endif
3042
3043  owl_fmtext_init_null(&fm);
3044
3045  /* AIM first */
3046  if (aim && owl_global_is_aimloggedin(&g)) {
3047    bl=owl_global_get_buddylist(&g);
3048
3049    owl_fmtext_append_bold(&fm, "AIM users logged in:\n");
3050    /* we're assuming AIM for now */
3051    j=owl_buddylist_get_size(bl);
3052    for (i=0; i<j; i++) {
3053      b=owl_buddylist_get_buddy_n(bl, i);
3054      idle=owl_buddy_get_idle_time(b);
3055      if (idle!=0) {
3056        timestr=owl_util_minutes_to_timestr(idle);
3057      } else {
3058        timestr=owl_strdup("");
3059      }
3060      owl_fmtext_appendf_normal(&fm, "  %-20.20s %-12.12s\n", owl_buddy_get_name(b), timestr);
3061      owl_free(timestr);
3062    }
3063  }
3064
3065#ifdef HAVE_LIBZEPHYR
3066  if (zephyr) {
3067    if(!owl_global_is_havezephyr(&g)) {
3068      owl_function_error("Zephyr currently not available.");
3069    } else {
3070      owl_fmtext_append_bold(&fm, "Zephyr users logged in:\n");
3071      owl_list_create(&anyone);
3072      ret=owl_zephyr_get_anyone_list(&anyone, filename);
3073      if (ret) {
3074        if (errno == ENOENT) {
3075          owl_fmtext_append_normal(&fm, " You have not added any zephyr buddies.  Use the\n");
3076          owl_fmtext_append_normal(&fm, " command ':addbuddy zephyr ");
3077          owl_fmtext_append_bold(  &fm, "<username>");
3078          owl_fmtext_append_normal(&fm, "'.\n");
3079        } else {
3080          owl_fmtext_append_normal(&fm, " Could not read zephyr buddies from the .anyone file.\n");
3081        }
3082      } else {
3083        j=owl_list_get_size(&anyone);
3084        for (i=0; i<j; i++) {
3085          user=owl_list_get_element(&anyone, i);
3086          ret=ZLocateUser(zstr(user), &numlocs, ZAUTH);
3087
3088          owl_function_mask_sigint(NULL);
3089          if(owl_global_is_interrupted(&g)) {
3090            interrupted = 1;
3091            owl_global_unset_interrupted(&g);
3092            owl_function_unmask_sigint(NULL);
3093            owl_function_makemsg("Interrupted!");
3094            break;
3095          }
3096
3097          owl_function_unmask_sigint(NULL);
3098
3099          if (ret!=ZERR_NONE) {
3100            owl_function_error("Error getting location for %s", user);
3101            continue;
3102          }
3103
3104          numlocs=200;
3105          ret=ZGetLocations(location, &numlocs);
3106          if (ret==0) {
3107            for (x=0; x<numlocs; x++) {
3108              tmp=short_zuser(user);
3109              owl_fmtext_appendf_normal(&fm, "  %-10.10s %-24.24s %-12.12s  %20.20s\n",
3110                                        tmp,
3111                                        location[x].host,
3112                                        location[x].tty,
3113                                        location[x].time);
3114              owl_free(tmp);
3115            }
3116            if (numlocs>=200) {
3117              owl_fmtext_append_normal(&fm, "  Too many locations found for this user, truncating.\n");
3118            }
3119          }
3120        }
3121      }
3122      owl_list_free_all(&anyone, owl_free);
3123    }
3124  }
3125#endif
3126
3127  if (aim && zephyr) {
3128    if (owl_perlconfig_is_function("BarnOwl::Hooks::_get_blist")) {
3129      char * perlblist = owl_perlconfig_execute("BarnOwl::Hooks::_get_blist()");
3130      if (perlblist) {
3131        owl_fmtext_append_ztext(&fm, perlblist);
3132        owl_free(perlblist);
3133      }
3134    }
3135  }
3136
3137  if(!interrupted) {
3138    owl_function_popless_fmtext(&fm);
3139  }
3140  owl_fmtext_free(&fm);
3141}
3142
3143/* Dump messages in the current view to the file 'filename'. */
3144void owl_function_dump(const char *filename) 
3145{
3146  int i, j;
3147  owl_message *m;
3148  const owl_view *v;
3149  FILE *file;
3150  char *plaintext;
3151
3152  v=owl_global_get_current_view(&g);
3153
3154  /* in the future make it ask yes/no */
3155  /*
3156  ret=stat(filename, &sbuf);
3157  if (!ret) {
3158    ret=owl_function_askyesno("File exists, continue? [Y/n]");
3159    if (!ret) return;
3160  }
3161  */
3162
3163  file=fopen(filename, "w");
3164  if (!file) {
3165    owl_function_error("Error opening file");
3166    return;
3167  }
3168
3169  j=owl_view_get_size(v);
3170  for (i=0; i<j; i++) {
3171    m=owl_view_get_element(v, i);
3172    plaintext = owl_strip_format_chars(owl_message_get_text(m));
3173    if (plaintext) {
3174      fputs(plaintext, file);
3175      owl_free(plaintext);
3176    }
3177  }
3178  fclose(file);
3179  owl_function_makemsg("Messages dumped to %s", filename);
3180}
3181
3182void owl_function_do_newmsgproc(void)
3183{
3184  if (owl_global_get_newmsgproc(&g) && strcmp(owl_global_get_newmsgproc(&g), "")) {
3185    /* if there's a process out there, we need to check on it */
3186    if (owl_global_get_newmsgproc_pid(&g)) {
3187      owl_function_debugmsg("Checking on newmsgproc pid==%i", owl_global_get_newmsgproc_pid(&g));
3188      owl_function_debugmsg("Waitpid return is %i", waitpid(owl_global_get_newmsgproc_pid(&g), NULL, WNOHANG));
3189      waitpid(owl_global_get_newmsgproc_pid(&g), NULL, WNOHANG);
3190      if (waitpid(owl_global_get_newmsgproc_pid(&g), NULL, WNOHANG)==-1) {
3191        /* it exited */
3192        owl_global_set_newmsgproc_pid(&g, 0);
3193        owl_function_debugmsg("newmsgproc exited");
3194      } else {
3195        owl_function_debugmsg("newmsgproc did not exit");
3196      }
3197    }
3198   
3199    /* if it exited, fork & exec a new one */
3200    if (owl_global_get_newmsgproc_pid(&g)==0) {
3201      pid_t i;
3202      int myargc;
3203      i=fork();
3204      if (i) {
3205        /* parent set the child's pid */
3206        owl_global_set_newmsgproc_pid(&g, i);
3207        owl_function_debugmsg("I'm the parent and I started a new newmsgproc with pid %i", i);
3208      } else {
3209        /* child exec's the program */
3210        char **parsed;
3211        parsed=owl_parseline(owl_global_get_newmsgproc(&g), &myargc);
3212        if (myargc < 0) {
3213          owl_function_debugmsg("Could not parse newmsgproc '%s': unbalanced quotes?", owl_global_get_newmsgproc(&g));
3214        }
3215        if (myargc <= 0) {
3216          _exit(127);
3217        }
3218        parsed=owl_realloc(parsed, sizeof(*parsed) * (myargc+1));
3219        parsed[myargc] = NULL;
3220       
3221        owl_function_debugmsg("About to exec \"%s\" with %d arguments", parsed[0], myargc);
3222       
3223        execvp(parsed[0], parsed);
3224       
3225       
3226        /* was there an error exec'ing? */
3227        owl_function_debugmsg("Cannot run newmsgproc '%s': cannot exec '%s': %s", 
3228                              owl_global_get_newmsgproc(&g), parsed[0], strerror(errno));
3229        _exit(127);
3230      }
3231    }
3232  }
3233}
3234
3235/* print the xterm escape sequence to raise the window */
3236void owl_function_xterm_raise(void)
3237{
3238  printf("\033[5t");
3239}
3240
3241/* print the xterm escape sequence to deiconify the window */
3242void owl_function_xterm_deiconify(void)
3243{
3244  printf("\033[1t");
3245}
3246
3247/* Add the specified command to the startup file.  Eventually this
3248 * should be clever, and rewriting settings that will obviosly
3249 * override earlier settings with 'set' 'bindkey' and 'alias'
3250 * commands.  For now though we just remove any line that would
3251 * duplicate this one and then append this line to the end of
3252 * startupfile.
3253 */
3254void owl_function_addstartup(const char *buff)
3255{
3256  FILE *file;
3257  const char *filename;
3258
3259  filename=owl_global_get_startupfile(&g);
3260
3261  /* delete earlier copies */
3262  owl_util_file_deleteline(filename, buff, 1);
3263
3264  file=fopen(filename, "a");
3265  if (!file) {
3266    owl_function_error("Error opening startupfile for new command");
3267    return;
3268  }
3269
3270  /* add this line */
3271  fprintf(file, "%s\n", buff);
3272
3273  fclose(file);
3274}
3275
3276/* Remove the specified command from the startup file. */
3277void owl_function_delstartup(const char *buff)
3278{
3279  const char *filename;
3280  filename=owl_global_get_startupfile(&g);
3281  owl_util_file_deleteline(filename, buff, 1);
3282}
3283
3284/* Execute owl commands from the given filename.  If the filename
3285 * is NULL, use the default owl startup commands file.
3286 */
3287void owl_function_source(const char *filename)
3288{
3289  char *path;
3290  FILE *file;
3291  char *s = NULL;
3292  int fail_silent = 0;
3293
3294  if (!filename) {
3295    fail_silent = 1;
3296    path = owl_strdup(owl_global_get_startupfile(&g));
3297  } else {
3298    path = owl_util_makepath(filename);
3299  }
3300  file = fopen(path, "r");
3301  owl_free(path);
3302  if (!file) {
3303    if (!fail_silent) {
3304      owl_function_error("Error opening file: %s", filename);
3305    }
3306    return;
3307  }
3308  while (owl_getline_chomp(&s, file)) {
3309    if (s[0] == '\0' || s[0] == '#')
3310      continue;
3311    owl_function_command(s);
3312  }
3313
3314  owl_free(s);
3315  fclose(file);
3316}
3317
3318void owl_function_change_style(owl_view *v, const char *stylename)
3319{
3320  const owl_style *s;
3321
3322  s=owl_global_get_style_by_name(&g, stylename);
3323  if (!s) {
3324    owl_function_error("No style named %s", stylename);
3325    return;
3326  }
3327  owl_view_set_style(v, s);
3328  owl_messagelist_invalidate_formats(owl_global_get_msglist(&g));
3329  owl_function_calculate_topmsg(OWL_DIRECTION_DOWNWARDS);
3330  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
3331}
3332
3333void owl_function_toggleoneline(void)
3334{
3335  owl_view *v;
3336  const owl_style *s;
3337
3338  v=owl_global_get_current_view(&g);
3339  s=owl_view_get_style(v);
3340
3341  if (!owl_style_matches_name(s, "oneline")) {
3342    owl_function_change_style(v, "oneline");
3343  } else {
3344    owl_function_change_style(v, owl_global_get_default_style(&g));
3345  }
3346
3347  owl_messagelist_invalidate_formats(owl_global_get_msglist(&g));
3348  owl_function_calculate_topmsg(OWL_DIRECTION_DOWNWARDS);
3349  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
3350}
3351
3352void owl_function_error(const char *fmt, ...)
3353{
3354  static int in_error = 0;
3355  va_list ap;
3356  char *buff;
3357  const char *nl;
3358
3359  if (++in_error > 2) {
3360    /* More than two nested errors, bail immediately. */
3361    in_error--;
3362    return;
3363  }
3364
3365  va_start(ap, fmt);
3366  buff = g_strdup_vprintf(fmt, ap);
3367  va_end(ap);
3368
3369  owl_function_debugmsg("ERROR: %s", buff);
3370  owl_function_log_err(buff);
3371
3372  nl = strchr(buff, '\n');
3373
3374  /*
3375    Showing admin messages triggers a lot of code. If we have a
3376    recursive error call, that's the most likely candidate, so
3377    suppress the call in that case, to try to avoid infinite looping.
3378  */
3379
3380  if(nl && *(nl + 1) && in_error == 1) {
3381    /* Multiline error */
3382    owl_function_adminmsg("ERROR", buff);
3383  } else {
3384    owl_function_makemsg("[Error] %s", buff);
3385  }
3386
3387  owl_free(buff);
3388
3389  in_error--;
3390}
3391
3392void owl_function_log_err(const char *string)
3393{
3394  char *date;
3395  time_t now;
3396  char *buff;
3397
3398  now=time(NULL);
3399  date=owl_strdup(ctime(&now));
3400  date[strlen(date)-1]='\0';
3401
3402  buff = owl_sprintf("%s %s", date, string);
3403
3404  owl_errqueue_append_err(owl_global_get_errqueue(&g), buff);
3405
3406  owl_free(buff);
3407  owl_free(date);
3408}
3409
3410void owl_function_showerrs(void)
3411{
3412  owl_fmtext fm;
3413
3414  owl_fmtext_init_null(&fm);
3415  owl_fmtext_append_normal(&fm, "Errors:\n\n");
3416  owl_errqueue_to_fmtext(owl_global_get_errqueue(&g), &fm);
3417  owl_function_popless_fmtext(&fm);
3418}
3419
3420void owl_function_makemsg(const char *fmt, ...)
3421{
3422  va_list ap;
3423  char buff[2048];
3424
3425  if (!owl_global_get_curs_msgwin(&g)) return;
3426
3427  va_start(ap, fmt);
3428  werase(owl_global_get_curs_msgwin(&g));
3429 
3430  vsnprintf(buff, 2048, fmt, ap);
3431  owl_function_debugmsg("makemsg: %s", buff);
3432  waddstr(owl_global_get_curs_msgwin(&g), buff); 
3433  wnoutrefresh(owl_global_get_curs_msgwin(&g));
3434  owl_global_set_needrefresh(&g);
3435  va_end(ap);
3436}
3437
3438/* get locations for everyone in .anyone.  If 'notify' is '1' then
3439 * send a pseudo login or logout message for everyone not in sync with
3440 * the global zephyr buddy list.  The list is updated regardless of
3441 * the status of 'notify'.
3442 */
3443void owl_function_zephyr_buddy_check(int notify)
3444{
3445#ifdef HAVE_LIBZEPHYR
3446  int i, j;
3447  owl_list anyone;
3448  owl_message *m;
3449  owl_zbuddylist *zbl;
3450  const char *user;
3451  ZLocations_t location[200];
3452  int numlocs, ret;
3453
3454  if (!owl_global_is_havezephyr(&g)) return;
3455
3456  zbl=owl_global_get_zephyr_buddylist(&g);
3457
3458  owl_list_create(&anyone);
3459  ret=owl_zephyr_get_anyone_list(&anyone, NULL);
3460
3461  j=owl_list_get_size(&anyone);
3462  for (i=0; i<j; i++) {
3463    user=owl_list_get_element(&anyone, i);
3464    ret=ZLocateUser(zstr(user), &numlocs, ZAUTH);
3465    if (ret!=ZERR_NONE) {
3466      owl_function_error("Error getting location for %s", user);
3467      continue;
3468    }
3469    numlocs=200;
3470    ret=ZGetLocations(location, &numlocs);
3471    if (ret==0) {
3472      if ((numlocs>0) && !owl_zbuddylist_contains_user(zbl, user)) {
3473        /* Send a PSEUDO LOGIN! */
3474        if (notify) {
3475          m=owl_malloc(sizeof(owl_message));
3476          owl_message_create_pseudo_zlogin(m, 0, user, location[0].host, location[0].time, location[0].tty);
3477          owl_global_messagequeue_addmsg(&g, m);
3478        }
3479        owl_zbuddylist_adduser(zbl, user);
3480        owl_function_debugmsg("owl_function_zephyr_buddy_check: login for %s ", user);
3481      } else if ((numlocs==0) && owl_zbuddylist_contains_user(zbl, user)) {
3482        /* I don't think this ever happens (if there are 0 locations we should get an error from
3483         * ZGetLocations)
3484         */
3485        owl_function_error("owl_function_zephyr_buddy_check: exceptional case logout for %s ",user);
3486      }
3487    } else if ((ret==ZERR_NOLOCATIONS) && owl_zbuddylist_contains_user(zbl, user)) {
3488      /* Send a PSEUDO LOGOUT! */
3489      if (notify) {
3490        m=owl_malloc(sizeof(owl_message));
3491        owl_message_create_pseudo_zlogin(m, 1, user, "", "", "");
3492        owl_global_messagequeue_addmsg(&g, m);
3493      }
3494      owl_zbuddylist_deluser(zbl, user);
3495      owl_function_debugmsg("owl_function_zephyr_buddy_check: logout for %s ",user);
3496    }
3497  }
3498
3499  owl_list_free_all(&anyone, owl_free);
3500#endif
3501}
3502
3503void owl_function_aimsearch_results(const char *email, owl_list *namelist)
3504{
3505  owl_fmtext fm;
3506  int i, j;
3507
3508  owl_fmtext_init_null(&fm);
3509  owl_fmtext_append_normal(&fm, "AIM screennames associated with ");
3510  owl_fmtext_append_normal(&fm, email);
3511  owl_fmtext_append_normal(&fm, ":\n");
3512
3513  j=owl_list_get_size(namelist);
3514  for (i=0; i<j; i++) {
3515    owl_fmtext_append_normal(&fm, "  ");
3516    owl_fmtext_append_normal(&fm, owl_list_get_element(namelist, i));
3517    owl_fmtext_append_normal(&fm, "\n");
3518  }
3519
3520  owl_function_popless_fmtext(&fm);
3521  owl_fmtext_free(&fm);
3522}
3523
3524int owl_function_get_color_count(void)
3525{
3526     return COLORS;
3527}
3528
3529void owl_function_mask_sigint(sigset_t *oldmask) {
3530  sigset_t intr;
3531
3532  sigemptyset(&intr);
3533  sigaddset(&intr, SIGINT);
3534  sigprocmask(SIG_BLOCK, &intr, oldmask);
3535}
3536
3537void owl_function_unmask_sigint(sigset_t *oldmask) {
3538  sigset_t intr;
3539
3540  sigemptyset(&intr);
3541  sigaddset(&intr, SIGINT);
3542  sigprocmask(SIG_UNBLOCK, &intr, oldmask);
3543}
3544
3545void _owl_function_mark_message(const owl_message *m)
3546{
3547  if (m) {
3548    owl_global_set_markedmsgid(&g, owl_message_get_id(m));
3549    owl_mainwin_redisplay(owl_global_get_mainwin(&g));
3550  }
3551}
3552
3553void owl_function_mark_message(void)
3554{
3555  const owl_message *m;
3556  const owl_view *v;
3557
3558  v=owl_global_get_current_view(&g);
3559
3560  /* bail if there's no current message */
3561  if (owl_view_get_size(v) < 1) {
3562    owl_function_error("No messages to mark");
3563    return;
3564  }
3565
3566  /* mark the message */
3567  m=owl_view_get_element(v, owl_global_get_curmsg(&g));
3568  _owl_function_mark_message(m);
3569  owl_function_makemsg("Mark set");
3570}
3571
3572void owl_function_swap_cur_marked(void)
3573{
3574  int marked_id;
3575  const owl_message *m;
3576  const owl_view *v;
3577
3578  marked_id=owl_global_get_markedmsgid(&g);
3579  if (marked_id == -1) {
3580    owl_function_error("Mark not set.");
3581    return;
3582  }
3583
3584  v=owl_global_get_current_view(&g);
3585  /* bail if there's no current message */
3586  if (owl_view_get_size(v) < 1) {
3587    return;
3588  }
3589
3590  m=owl_view_get_element(v, owl_global_get_curmsg(&g));
3591  _owl_function_mark_message(m);
3592  owl_global_set_curmsg(&g, owl_view_get_nearest_to_msgid(v, marked_id));
3593  owl_function_calculate_topmsg(OWL_DIRECTION_NONE);
3594  owl_mainwin_redisplay(owl_global_get_mainwin(&g));
3595  owl_global_set_direction_downwards(&g);
3596}
Note: See TracBrowser for help on using the repository browser.