source: functions.c @ 503d72e

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