source: functions.c @ 4ebbfbc

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