-
Notifications
You must be signed in to change notification settings - Fork 4
/
xlbiff.c
1150 lines (993 loc) · 37.8 KB
/
xlbiff.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*\
|* xlbiff -- X Literate Biff
|*
|* DESCRIPTION:
|*
|* xlbiff is yet another biff utility. It lurks around, polling
|* a mail file until its size changes. When this happens, it pops
|* up a window containing a `scan' of the contents of the mailbox.
|* Xlbiff is modeled after xconsole; it remains invisible at non-
|* useful times, eg, when no mail is present. See README for details.
|*
|* Author: Eduardo Santiago, [email protected]
|* Created: 20 August 1991
|* Last Updated: 16 May 2017
|*
|* Copyright 1994, 2017 Eduardo Santiago
|* SPDX-License-Identifier: MIT
*/
#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <X11/Shell.h>
#include <X11/Xaw/Command.h>
#include <X11/Xatom.h> // for XA_ATOM
#include <X11/Xos.h>
#include <X11/extensions/Xrandr.h>
#include <unistd.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <time.h>
#include <pwd.h>
#include <errno.h>
/*
** This grody gunk stolen outright from mit/lib/Xaw/Mailbox.h
*/
#ifndef X_NOT_POSIX
#ifdef _POSIX_SOURCE
# include <sys/wait.h>
#else
#define _POSIX_SOURCE
# include <sys/wait.h>
#undef _POSIX_SOURCE
#endif
# define waitCode(w) WEXITSTATUS(w)
# define waitSig(w) WIFSIGNALED(w)
typedef int waitType;
# define INTWAITTYPE
#else /* ! X_NOT_POSIX */
#if defined(SYSV) || defined(SVR4)
# define waitCode(w) (((w) >> 8) & 0x7f)
# define waitSig(w) ((w) & 0xff)
typedef int waitType;
# define INTWAITTYPE
#else
# include <sys/wait.h>
# define waitCode(w) ((w).w_T.w_Retcode)
# define waitSig(w) ((w).w_T.w_Termsig)
typedef union wait waitType;
#endif /* SYSV else */
#endif /* ! X_NOT_POSIX else */
/*
** This defines the file we need to monitor. If not defined explicitly
** on the command line, we pick this default.
*/
#ifndef XLBIFF_MAILPATH
#define XLBIFF_MAILPATH "/var/mail/%s"
#endif
/*****************************************************************************\
** prototypes **
\*****************************************************************************/
char *doScan();
void Popdown(), Popup();
void realize_window();
void Usage();
extern char *getlogin();
void Shrink(Widget, XtPointer, XEvent*, Boolean*);
void handler(XtPointer, XtIntervalId*);
void initStaticData(int*, int*, int*);
void Exit(Widget, XEvent*, String*, Cardinal*);
void Mailer(Widget, XEvent*, String*, Cardinal*);
void lbiffUnrealize(), lbiffRealize(char*);
void getDimensions(char*, Dimension*, Dimension*);
void toggle_key_led(int);
void init_randr();
void ErrExit(Boolean, char*);
Bool CheckEvent(Display*, XEvent*, XPointer);
void debug(int level, char *format, ...);
waitType popen_nmh(char *cmd, int bufsize, char **buf_out, size_t *size_out);
/*****************************************************************************\
** globals **
\*****************************************************************************/
extern int errno;
Widget topLevel, textBox; /* my widgets */
XtAppContext app_context; /* application context */
Boolean visible; /* is window visible? */
Boolean hasdata; /* Something is to be displayed */
char *default_file; /* default filename */
char *progname; /* my program name */
struct timeval acknowledge_time = {0}; /* time window was acknowledged */
struct timeval popup_time = {0}; /* time window was popped up */
static Atom wm_delete_window; /* for handling WM_DELETE */
typedef struct {
int debug; /* level of debug logging */
char *file; /* file to monitor size of */
char *checkCmd; /* command to run for check */
char *cmd; /* command to run for output */
char *mailerCmd; /* command to read mail */
float update; /* update interval, in seconds */
float fade; /* popdown interval, in seconds */
int columns; /* number of columns across */
int rows; /* max# of lines in display */
int volume; /* bell volume, 0-100 percent */
Boolean bottom; /* Put window at window bottom */
Boolean resetSaver; /* reset screensaver on popup */
float refresh; /* seconds before reposting msg */
int led; /* led number to light up */
Boolean ledPopdown; /* turn off LED on popdown? */
char *sound; /* Sound file to use */
} AppData, *AppDataPtr;
AppData lbiff_data;
#define offset(field) XtOffset(AppDataPtr, field)
float default_update_secs = 15.0f;
float default_fade_secs = 0.0f;
float default_refresh_secs = 1800.0f;
static XtResource xlbiff_resources[] = {
{"debug", "Debug", XtRInt, sizeof(int),
offset(debug), XtRImmediate, (XtPointer)0},
{"file", "File", XtRString, sizeof(String),
offset(file), XtRString, NULL},
{"checkCommand", "CheckCommand", XtRString, sizeof(String),
offset(checkCmd), XtRString, NULL},
{"scanCommand", "ScanCommand", XtRString, sizeof(String),
offset(cmd), XtRString, "scan -file %s -width %d 2>&1"},
{"mailerCommand", "MailerCommand", XtRString, sizeof(String),
offset(mailerCmd), XtRString, NULL },
{"update", "Interval", XtRFloat, sizeof(float),
offset(update), XtRFloat, &default_update_secs},
{"fade", "Fade", XtRFloat, sizeof(float),
offset(fade), XtRFloat, &default_fade_secs},
{"columns", "Columns", XtRInt, sizeof(int),
offset(columns), XtRImmediate, (XtPointer)80},
{"rows", "Rows", XtRInt, sizeof(int),
offset(rows), XtRImmediate, (XtPointer)20},
{"sound", "Sound", XtRString, sizeof(String),
offset(sound), XtRString, ""},
{"volume", "Volume", XtRInt, sizeof(int),
offset(volume), XtRImmediate, (XtPointer)100},
{"bottom", "Bottom", XtRBoolean, sizeof(Boolean),
offset(bottom), XtRImmediate, False},
{"resetSaver", "ResetSaver", XtRBoolean, sizeof(Boolean),
offset(resetSaver), XtRImmediate, False},
{"refresh", "Refresh", XtRFloat, sizeof(float),
offset(refresh), XtRFloat, &default_refresh_secs},
{"led", "Led", XtRInt, sizeof(int),
offset(led), XtRImmediate, (XtPointer)0},
{"ledPopdown", "LedPopdown", XtRBoolean, sizeof(Boolean),
offset(ledPopdown), XtRImmediate, False}
};
static XrmOptionDescRec optionDescList[] = {
{"-bottom", ".bottom", XrmoptionNoArg, (XtPointer) "true"},
{"+bottom", ".bottom", XrmoptionNoArg, (XtPointer) "false"},
{"-debug", ".debug", XrmoptionSepArg, (XtPointer) NULL},
{"-file", ".file", XrmoptionSepArg, (XtPointer) NULL},
{"-rows", ".rows", XrmoptionSepArg, (XtPointer) NULL},
{"-columns", ".columns", XrmoptionSepArg, (XtPointer) NULL},
{"-update", ".update", XrmoptionSepArg, (XtPointer) NULL},
{"-fade", ".fade", XrmoptionSepArg, (XtPointer) NULL},
{"-volume", ".volume", XrmoptionSepArg, (XtPointer) NULL},
{"-resetSaver", ".resetSaver", XrmoptionNoArg, (XtPointer) "true"},
{"+resetSaver", ".resetSaver", XrmoptionNoArg, (XtPointer) "false"},
{"-refresh", ".refresh", XrmoptionSepArg, (XtPointer) NULL},
{"-led", ".led", XrmoptionSepArg, (XtPointer) NULL},
{"-ledPopdown", ".ledPopdown", XrmoptionNoArg, (XtPointer) "true"},
{"+ledPopdown", ".ledPopdown", XrmoptionNoArg, (XtPointer) "false"},
{"-sound", ".sound", XrmoptionSepArg, (XtPointer) NULL},
{"-scanCommand", ".scanCommand", XrmoptionSepArg, (XtPointer) NULL},
{"-mailerCommand",".mailerCommand",XrmoptionSepArg,(XtPointer) NULL},
{"-checkCommand",".checkCommand",XrmoptionSepArg, (XtPointer) NULL}
};
static char *fallback_resources[] = {
"*Font: -*-clean-bold-r-normal--13-130-75-75-c-80-iso646.1991-*",
"*Geometry: +0-0",
NULL
};
static XtActionsRec lbiff_actions[] = {
{"exit", Exit},
{"mailer", Mailer},
{"popdown", Popdown}
};
/*****************************************************************************\
** code **
\*****************************************************************************/
/**********\
|* main *|
\**********/
int main(int argc, char *argv[]) {
progname = argv[0];
XtSetLanguageProc(NULL, NULL, NULL);
topLevel = XtVaAppInitialize(&app_context,
"XLbiff",
optionDescList, XtNumber(optionDescList),
&argc, argv,
fallback_resources,
XtNallowShellResize, True,
NULL);
XtGetApplicationResources(topLevel, &lbiff_data,
xlbiff_resources, XtNumber(xlbiff_resources),
(ArgList)NULL, 0);
setvbuf(stdout, NULL, _IOLBF, 0); /* line buffer any debug messages */
/*
** Check command line arguments
*/
if (argc > 1) {
if (!strncmp(argv[1], "-version", strlen(argv[1]))) {
fprintf(stderr, "%s version %s\n", progname, VERSION);
exit(0);
} else if (!strncmp(argv[1], "-help", strlen(argv[1]))) {
Usage();
} else if (argv[1][0] != '-') {
lbiff_data.file = argv[1];
} else {
fprintf(stderr,
"%s: no such option \"%s\", type '%s -help' for help\n",
progname, argv[1], progname);
exit(1);
}
}
/*
** If no data file was explicitly given, make our best guess
*/
if (lbiff_data.file == NULL) {
char *username = getlogin();
if (username == NULL || username[0] == '\0') {
struct passwd *pwd = getpwuid(getuid());
if (pwd == NULL) {
fprintf(stderr, "%s: cannot get username\n", progname);
exit(1);
}
username = pwd->pw_name;
}
// -2 for the "%s" removed by formatting, +1 for the NUL.
size_t mailpath_file_size =
strlen(XLBIFF_MAILPATH) - 2 + strlen(username) + 1;
default_file = (char *)malloc(mailpath_file_size);
if (default_file == NULL)
ErrExit(True, "default_file malloc()");
snprintf(default_file, mailpath_file_size, XLBIFF_MAILPATH, username);
default_file[mailpath_file_size - 1] = '\0';
lbiff_data.file = default_file;
}
debug(1, "file= %s", lbiff_data.file);
if (lbiff_data.cmd == NULL || lbiff_data.cmd[0] == '\0') {
fprintf(stderr, "%s: empty scanCommand will not work\n", progname);
exit(1);
}
/*
** Fix DISPLAY environment variable, might be needed by subprocesses
*/
{
char *envstr =
(char *)malloc(strlen("DISPLAY=") + 1 +
strlen(XDisplayString(XtDisplay(topLevel))));
sprintf(envstr, "DISPLAY=%s", XDisplayString(XtDisplay(topLevel)));
putenv(envstr);
}
textBox = XtVaCreateManagedWidget("text",
commandWidgetClass,
topLevel,
NULL);
XtAddCallback(textBox, XtNcallback, Popdown, textBox);
XtAppAddActions(app_context, lbiff_actions, XtNumber(lbiff_actions));
XtAddEventHandler(topLevel, StructureNotifyMask, False,
(XtEventHandler)Shrink, (XtPointer)NULL);
XtOverrideTranslations(
topLevel, XtParseTranslationTable("<Message>WM_PROTOCOLS: exit()"));
wm_delete_window =
XInternAtom(XtDisplay(topLevel), "WM_DELETE_WINDOW", False);
toggle_key_led(False);
/*
** check to see if there's something to do, pop up window if necessary,
** and set up alarm to wake us up again every so often.
*/
handler(NULL, NULL);
/*
** main program loop -- mostly just loops forever waiting for events
**
** note that we will continually be interrupted by the timeout code
*/
XtAppMainLoop(app_context);
}
/***********\
|* Usage *| displays usage message
\***********/
void Usage() {
static char *help_message[] = {
"where options include:",
" -version display xlbiff version number",
" -display host:dpy X server to contact",
" -geometry +x+y x,y coords of window",
" -rows height height of window, in lines",
" -columns width width of window, in characters",
" -file file file to watch",
" -update seconds how often to check for mail",
" -fade seconds lifetime of unmodified window",
" -volume percentage how loud to ring the bell",
" -bg color background color",
" -fg color foreground color",
" -refresh seconds seconds before re-posting window",
" -led ledNum keyboard LED to light up",
" -ledPopdown turn off LED when popped down",
" -scanCommand command command to interpret and display",
" -checkCommand command command used to check for change",
" -mailerCommand command command used to read mail",
NULL};
char **s;
printf("usage:\t%s [-options ...] [file to watch]\n", progname);
for (s = help_message; *s; s++)
printf("%s\n", *s);
printf("\n");
exit(1);
}
// Returns true if the difference between newtime and oldtime is
// greater than interval_seconds.
int time_passed(struct timeval *newtime, struct timeval *oldtime,
float interval_seconds) {
float timediff_secs = newtime->tv_sec - oldtime->tv_sec +
(newtime->tv_usec - oldtime->tv_usec) * 1e-6;
return timediff_secs > interval_seconds;
}
/**********\
|* Exit *| called via callback, exits the program
\**********/
void Exit(Widget w, XEvent *event, String *params, Cardinal *num_params) {
debug(1, "++Exit()");
if (event->type == ClientMessage) {
if (event->xclient.data.l[0] != wm_delete_window) {
debug(1, "received client message that was not delete_window");
XBell(XtDisplay(w), 0);
return;
} else
debug(1, "exiting after receiving a wm_delete_window message");
}
toggle_key_led(False);
XCloseDisplay(XtDisplay(w));
exit(0);
}
/***************\
|* checksize *| checks mail file to see if new mail is present
|***************
|* This routine stat's the mail spool file and compares its size
|* with the previously obtained result. If the size has become
|* zero, it pops down the window. If nonzero, it calls a routine
|* to execute the scanCommand. If the result of this is non-null,
|* it pops up a window showing it (note that users of Berkeley
|* mail may have non-empty mail files with all old mail).
*/
void checksize() {
static int mailsize = 0;
struct stat mailstat;
int pop_window = False;
struct timeval tp;
debug(1, "++checksize()...");
/*
** If user has specified a command to use to check the file, invoke
** it with lbiff_data.file and "previous" as arguments, where "previous"
** is the output of the script the last time it was run (or zero,
** the first time we call it). This is useful as a way of keeping
** state for the checkCommand; in this manner it knows, if the
** spool file size is nonzero, whether it has grown since the last
** time we called it.
*/
if (lbiff_data.checkCmd != NULL && lbiff_data.checkCmd[0] != '\0') {
waitType status;
int outbuf_size = 80;
static char *outbuf;
static char *cmd_buf;
static int previous;
if (cmd_buf == NULL) {
cmd_buf = (char *)malloc(strlen(lbiff_data.checkCmd) +
strlen(lbiff_data.file) + 10);
if (cmd_buf == NULL)
ErrExit(True, "scan command buffer malloc()");
}
if (outbuf == NULL) {
outbuf = (char *)malloc(outbuf_size);
if (outbuf == NULL)
ErrExit(True, "check output buffer malloc()");
}
sprintf(cmd_buf, lbiff_data.checkCmd, lbiff_data.file, previous);
debug(1, "++checkCommand= %s", cmd_buf);
status = popen_nmh(cmd_buf, outbuf_size, &outbuf, NULL);
previous = atol(outbuf);
debug(1, "checkCommand returns %d", previous);
switch (waitCode(status)) {
case 0: /* 0: new data */
mailstat.st_size = mailsize + 1;
break;
case 2: /* 2: no data (clear) */
mailstat.st_size = 0;
break;
default: /* 1: same as before */
mailstat.st_size = mailsize;
}
} else { /* no checkCmd, just stat the mailfile and check size */
/*
** Do the stat to get the mail file size. If it fails for any reason,
** ignore the failure and assume the file is size 0. Failures I can
** think of are that should be ignored are:
**
** + nonexistent file. Some Berkeley-style mailers delete
** the spool file when they're done with it.
** + NFS stale filehandle. Yuk. This one happens if
** your mail spool file is on an NFS-mounted directory
** _and_ your update interval is too low _and_ you use
** a Berkeleyish mailer. Yuk.
**
** Doubtless there are errors we should complain about, but this
** would get too ugly.
*/
if (stat(lbiff_data.file, &mailstat) != 0) {
debug(1, "stat() failed, errno=%d. Assuming filesize=0!", errno);
mailstat.st_size = 0;
}
}
/*
** If it's changed size, take appropriate action.
*/
if (mailstat.st_size != mailsize) {
debug(1, "changed size: %d -> %d", mailsize, (int)mailstat.st_size);
mailsize = mailstat.st_size;
pop_window = True;
} else if (!visible && lbiff_data.refresh && mailsize != 0) {
/*
** If window has been popped down, check if it's time to refresh
*/
if (gettimeofday(&tp, NULL) != 0) {
ErrExit(True, "gettimeofday() in checksize()");
} else {
if (time_passed(&tp, &acknowledge_time, lbiff_data.refresh)) {
debug(1, "reposting window, repost time reached");
pop_window = True;
}
}
} else if (visible && (mailstat.st_size = mailsize)) {
/*
** window is visible--see if fade time has been reached, and
** if so, popdown window
** if fade is zero, do not pop down
*/
if (gettimeofday(&tp, NULL) != 0) {
ErrExit(True, "gettimeofday() in checksize()");
} else if (lbiff_data.fade > 0) {
if (time_passed(&tp, &popup_time, lbiff_data.fade)) {
debug(1, "fade time (%f) reached", lbiff_data.fade);
lbiffUnrealize();
}
}
}
if (pop_window) {
if (mailsize == 0) {
hasdata = False;
toggle_key_led(False);
lbiffUnrealize();
} else { /* something was added? */
char *s = doScan();
if (strlen(s) != 0) { /* is there anything new? */
if (hasdata) /* ESM && isvisible? ESM */
lbiffUnrealize(); /* pop down if it's up */
hasdata = True;
toggle_key_led(True);
lbiffRealize(s); /* pop back up */
}
}
} else {
debug(1, "no change (still %d)", mailsize);
}
}
/************\
|* Mailer *| called via callback, starts a mailer
\************/
void Mailer(Widget w, XEvent *event, String *params, Cardinal *num_params) {
int system_return;
debug(1, "++Mailer()");
Popdown();
if (lbiff_data.mailerCmd != NULL && lbiff_data.mailerCmd[0] != '\0') {
debug(1, "---mailerCmd = %s", lbiff_data.mailerCmd);
system_return = system(lbiff_data.mailerCmd);
if (system_return == 0) {
debug(1, "---mailerCmd completed successfully");
} else {
fprintf(stderr, "mailer command \"%s\" returned %d (%#x)\n",
lbiff_data.mailerCmd, system_return, system_return);
}
}
checksize();
Popup();
}
/*************\
|* handler *| Checks mail file and reschedules itself to do so again
\*************/
void handler(XtPointer closure, XtIntervalId *id) {
checksize();
long int update_msecs = lbiff_data.update * 1000.0f + 0.5f;
XtAppAddTimeOut(app_context, update_msecs, handler, NULL);
}
/************\
|* doScan *| invoke MH ``scan'' command to examine mail messages
|************
|* This routine looks at the mail file and parses the contents. It
|* does this by invoking scan(1) or some other user-defined function.
*/
char *doScan() {
static char *cmd_buf;
static char *buf = NULL;
static int bufsize;
static char scan_fail_msg[] = "\n---->>>> scanCommand failed <<<<<----\n";
size_t size;
waitType status;
debug(1, "++doScan()");
/*
** Initialise display buffer to #rows * #cols
** Initialise command string
*/
if (buf == NULL) {
/* +6 for a few multibyte characters, +1 for the newline */
bufsize = (lbiff_data.columns + 6 + 1) * lbiff_data.rows;
buf = (char *)malloc(bufsize + sizeof(scan_fail_msg) + 1);
if (buf == NULL)
ErrExit(True, "text buffer malloc()");
debug(1, "---size= %dx%d", lbiff_data.rows, lbiff_data.columns);
cmd_buf = (char *)malloc(strlen(lbiff_data.cmd) +
strlen(lbiff_data.file) + 10);
if (cmd_buf == NULL)
ErrExit(True, "command buffer malloc()");
sprintf(cmd_buf, lbiff_data.cmd,
lbiff_data.file, lbiff_data.columns, lbiff_data.rows);
debug(1, "---cmd= %s", cmd_buf);
}
/*
** Execute the command, read the results, then set the contents of window.
*/
status = popen_nmh(cmd_buf, bufsize, &buf, &size);
if (waitCode(status) != 0) {
strcpy(buf + size, scan_fail_msg);
size += strlen(scan_fail_msg);
}
buf[size] = '\0'; /* null-terminate it! */
debug(1, "scanned:%s", buf);
return buf;
}
/****************\
|* CheckEvent *|
\****************/
Bool CheckEvent(Display *d, XEvent *e, XPointer arg) {
if (e->type == MapNotify || e->type == UnmapNotify)
if (e->xmap.window == (Window)arg)
return True;
return False;
}
static XEvent lastEvent;
/* ARGSUSED */
/*
** Handler for map/unmap events. Copied from xconsole.
** When unmap and map events occur consecutively, eg when resetting a
** window manager, this makes sure that only the last such event takes place.
*/
/************\
|* Shrink *| get StructureNotify events, popdown if iconified
\************/
void Shrink(Widget w, XtPointer data, XEvent *e, Boolean *b) {
char *type_str;
switch (e->type) {
case UnmapNotify: type_str = "UnmapNotify"; break;
case MapNotify: type_str = "MapNotify"; break;
case ReparentNotify: type_str = "ReparentNotify"; break;
case ConfigureNotify: type_str = "ConfigureNotify"; break;
default: type_str = "event type";
}
debug(1, "++Shrink(%s %d)", type_str, e->type);
if (e->type != MapNotify && e->type != UnmapNotify) {
return;
}
int event_seen = 0;
Window win = e->xmap.window;
memcpy((char *)&lastEvent, (char *)e, sizeof(XEvent));
XSync(XtDisplay(w), False);
while (XCheckIfEvent(XtDisplay(w), &lastEvent, CheckEvent,
(XPointer)win)) {
event_seen = 1;
}
if (!event_seen) {
return;
}
if (lastEvent.type == UnmapNotify && visible) {
Popdown();
} else if (lastEvent.type == MapNotify && hasdata) {
Popup();
}
}
/*
** These here routines (Popdown/Popup) bring the main window up or down.
** They are pretty simple except for the issue with *bottom...
** If running with *bottom, things are more complicated. You can't
** just map/unmap(), because since the window has already been placed
** at the bottom (when realized) any lines that get added to it when
** more mail comes in will just drop off the edge of the screen.
** Thus when *bottom is true we need to realize() the window anew
** each time something changes in it.
*/
/*************\
|* Popdown *| kill window
\*************/
void Popdown() {
debug(1, "++Popdown()");
lbiffUnrealize();
}
void Popup() {
struct timeval tp;
debug(1, "++Popup() hasdata=%d visible=%d", hasdata, visible);
if (!hasdata || visible) {
return;
}
/*
** Remember when we were popped up so we can fade later
*/
if (gettimeofday(&tp, NULL) != 0)
ErrExit(True, "gettimeofday() in Popup()");
popup_time = tp;
if (lbiff_data.bottom) {
Arg args[1];
int n = 0;
XtSetArg(args[n], XtNy, -1); n++;
XtSetValues(topLevel, args, n);
}
realize_window();
XtPopup(topLevel, XtGrabNone);
XSync(XtDisplay(topLevel), False);
visible = True;
}
void realize_window() {
XtRealizeWidget(topLevel);
(void)XSetWMProtocols(XtDisplay(topLevel), XtWindow(topLevel),
&wm_delete_window, 1);
// Tell WM not to give us the focus when we pop up.
// May also cause WM to not decorate the window.
Atom wm_window_type_value = XInternAtom(
XtDisplay(topLevel), "_NET_WM_WINDOW_TYPE_NOTIFICATION", False);
XChangeProperty(
XtDisplay(topLevel), XtWindow(topLevel),
XInternAtom(XtDisplay(topLevel), "_NET_WM_WINDOW_TYPE", False),
XA_ATOM, 32, PropModeReplace,
(unsigned char *)&wm_window_type_value, 1);
}
/********************\
|* lbiffUnrealize *| kill window
\********************/
void lbiffUnrealize() {
debug(1, "++lbiffUnrealize()");
/*
** Remember when we were popped down so we can refresh later
*/
struct timeval tp;
if (gettimeofday(&tp, NULL) != 0)
ErrExit(True, "gettimeofday() in lbiffUnrealize()");
acknowledge_time = tp;
if (visible) {
debug(1, "calling XtUnrealizeWidget");
XtUnrealizeWidget(topLevel);
XSync(XtDisplay(topLevel), False);
}
if (lbiff_data.ledPopdown) /* Turn off LED if so requested */
toggle_key_led(False);
visible = False;
}
/******************\
|* lbiffRealize *| reformat window, set the text and bring window up
\******************/
void lbiffRealize(char *s) {
Arg args[4];
int n;
static int first_time = 1;
debug(1, "++lbiffRealize()");
/*
** Set the contents of the window
*/
n = 0;
XtSetArg(args[n], XtNlabel, s); n++;
XtSetValues(textBox, args, n);
/*
** If running with *bottom, we need to tell the widget what size it
** is before realize()ing it. This is so the WM can position it
** properly at the bottom of the screen.
*/
Dimension width, height;
getDimensions(s, &width, &height);
n = 0;
XtSetArg(args[n], XtNwidth, width); n++;
XtSetArg(args[n], XtNheight, height); n++;
XtSetValues(topLevel, args, n);
Popup();
if (first_time) {
/* first time through this code */
init_randr();
first_time = 0;
}
if (lbiff_data.sound[0] == '\0') {
/*
** No, the following is not a typo, nor is it redundant code.
** Apparently there is one X terminal that beeps whenever XBell()
** is called, even with volume zero.
*/
if (lbiff_data.volume > 0) {
XBell(XtDisplay(topLevel), lbiff_data.volume - 100);
debug(1, "---sound= %s", "XBell default");
}
} else {
static char *sound_buf;
int system_return;
/*
** Initialise sound string
*/
if (sound_buf == NULL) {
sound_buf = (char *)malloc(strlen(lbiff_data.sound) + 10);
if (sound_buf == NULL)
ErrExit(True, "sound_buf malloc()");
sprintf(sound_buf, lbiff_data.sound, lbiff_data.volume);
debug(1, "---sound= %s", sound_buf);
}
system_return = system(sound_buf);
if (system_return != 0) {
fprintf(stderr, "sound command \"%s\" returned %d (%#x)\n",
sound_buf, system_return, system_return);
}
}
if (lbiff_data.resetSaver)
XResetScreenSaver(XtDisplay(topLevel));
}
/*******************\
|* getDimensions *| get width x height of text string
\*******************/
void getDimensions(char *s, Dimension *width, Dimension *height) {
Dimension tmp_width;
int i, len = strlen(s);
static int fontWidth, fontHeight;
static int borderWidth = -1;
tmp_width = *width = *height = 1;
if (borderWidth == -1)
initStaticData(&borderWidth, &fontHeight, &fontWidth);
/*
** count rows and columns
*/
for (i = 0; i < len - 1; i++) {
if (s[i] == '\n') { /* new line: clear width */
++*height;
tmp_width = 0;
} else {
++tmp_width;
if (tmp_width > *width) /* monitor highest width */
*width = tmp_width;
}
}
if (*height > lbiff_data.rows) /* cut to fit max wid/hgt */
*height = lbiff_data.rows;
if (*width > lbiff_data.columns)
*width = lbiff_data.columns;
debug(1, "geom= %dx%d chars (%dx%d pixels)", *width, *height,
*width * fontWidth,
*height * fontHeight);
*width *= fontWidth; *width += 6; /* convert to pixels */
*height *= fontHeight; *height += 4; /* and add a little fudge */
}
/********************\
|* initStaticData *| initializes font size & borderWidth
\********************/
void initStaticData(int *bw, int *fontH, int *fontW) {
Arg args[2];
XFontStruct *fs = NULL;
int tmp = 0;
debug(1, "++initStaticData...");
XtSetArg(args[0], XtNfont, &fs);
XtSetArg(args[1], XtNborderWidth, &tmp);
XtGetValues(textBox, args, 2);
if (fs == NULL)
ErrExit(False, "unknown font");
*bw = tmp;
*fontW = fs->max_bounds.width;
*fontH = fs->max_bounds.ascent + fs->max_bounds.descent;
debug(1, "font= %dx%d, borderWidth= %d", *fontH, *fontW, *bw);
}
/********************\
|* toggle_key_led *| toggle a keyboard LED on and off
\********************/
void toggle_key_led(int flag) {
XKeyboardControl keyboard;
if (lbiff_data.led == 0) /* return if no led action desired */
return;
debug(1, "++toggle_key_led(%d,%s)", lbiff_data.led, flag ? "True" : "False");
if (flag)
keyboard.led_mode = LedModeOn;
else
keyboard.led_mode = LedModeOff;
keyboard.led = lbiff_data.led;
XChangeKeyboardControl(XtDisplay(topLevel), KBLed | KBLedMode, &keyboard);
}
/*************\
|* ErrExit *| print out error message, clean up and exit
|*************
|* ErrExit prints out a given error message to stderr. If <errno_valid>
|* is True, it calls strerror(errno) to get the descriptive text for the
|* indicated error. It then clears the LEDs and exits.
|*
|* It is the intention that someday this will bring up a popup window.
*/
void ErrExit(Boolean errno_valid, char *s) {
if (errno_valid)
fprintf(stderr, "%s: %s: %s\n", progname, s, strerror(errno));
else
fprintf(stderr, "%s: %s\n", progname, s);
toggle_key_led(False);
XCloseDisplay(XtDisplay(topLevel));
exit(1);
}
// Debug level 1 logs changes in the internal state of xlbiff
// Debug level 2 logs extra events that don't change state
// The formatted string is preceded by the current time and program name
// and followed by a newline
void debug(int level, char *format, ...) {
if (lbiff_data.debug >= level) {
struct timeval tp;
struct tm tm;
char timestr[9];
if (gettimeofday(&tp, NULL) == 0) {
localtime_r(&tp.tv_sec, &tm);
strftime(timestr, sizeof(timestr), "%H:%M:%S", &tm);
printf("%s.%03ld ", timestr, tp.tv_usec/1000L);
}
printf("%s ", progname);
va_list argp;
va_start(argp, format);
vprintf(format, argp);
va_end(argp);
printf("\n");
}
}
waitType popen_simple(char *cmd, int bufsize, char **buf_out,
size_t *size_out) {
FILE *p;
size_t read_size;
waitType status;
/*
** Execute the command and read the results.
** If there is data remaining in the pipe, read it in (and throw it away)
** so our exit status is correct (eg, not "Broken pipe").
*/
if ((p = popen(cmd, "r")) == NULL)
ErrExit(True, "popen");
read_size = fread(*buf_out, 1, bufsize, p);