File: wmnetselect.c

package info (click to toggle)
wmnetselect 0.85-6
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 488 kB
  • ctags: 91
  • sloc: ansic: 865; sh: 330; makefile: 54
file content (1233 lines) | stat: -rw-r--r-- 37,218 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
/* wmnetselect - Window Maker Mozilla Selection dock app
   wmnetselect version 0.85    Last Modification:  8 Aug 2000
   
   Code canabalized from asclock/wmclock/wmmail.
   Thanks to respective authors of those apps, Beat Christen,
   Per Liden, Bryan Chan, and others I may have missed for
   making their code available.
   
   All errors herein are made by Patrick Hill (apathos@bham.net)
   This particular incarnation Copyright (c) 2000 Patrick Hill
   
 * 	This program is free software; you can redistribute it and/or modify
 * 	it under the terms of the GNU General Public License as published by
 * 	the Free Software Foundation; either version 2, or (at your option)
 * 	any later version.
 *
 * 	This program is distributed in the hope that it will be useful,
 * 	but WITHOUT ANY WARRANTY; without even the implied warranty of
 * 	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * 	GNU General Public License for more details.
 *
 * 	You should have received a copy of the GNU General Public License
 * 	along with this program (see the file COPYING); if not, write to the
 * 	Free Software Foundation, Inc., 59 Temple Place - Suite 330, 
 *      Boston, MA  02111-1307, USA
 *
 *
 */

#include <stdlib.h>

#include <stdio.h>
#include <string.h>
#include <X11/Xlib.h>
#include <X11/xpm.h>
#include <X11/extensions/shape.h>
#include <time.h>
#include <X11/Xatom.h>

#include <X11/Xproto.h>
#include <X11/Xmu/WinUtil.h>	/* for XmuClientWindow() */
#include <sys/types.h>
#include <unistd.h>

#define MOZILLA_VERSION_PROP	"_MOZILLA_VERSION"
#define MOZILLA_LOCK_PROP	"_MOZILLA_LOCK"
#define MOZILLA_COMMAND_PROP	"_MOZILLA_COMMAND"
#define MOZILLA_RESPONSE_PROP	"_MOZILLA_RESPONSE"
#define MOZILLA_URL_PROP	"_MOZILLA_URL"
#define DEFAULT_TIMEOUT 10000

static Window MozWin = None;

#include "xpm/moz.xpm"
#include "xpm/moz2.xpm"

#define VERSION 0.85
#define DEBUG 0

/* default executable is mozilla, may be overridden by command line parameter */
#define EXECUTABLE "mozilla"
#define LEFT_BUTTON          1         /* left mousebutton id */
#define MIDDLE_BUTTON        2         /* middle mousebutton id */
#define RIGHT_BUTTON         3         /* right mousebutton id */
#define DOUBLE_CLICK_TIME    250       /* double click latency (ms)  */
#define MW_EVENTS   (ExposureMask | ButtonPressMask | StructureNotifyMask)
#define FALSE 0
#define NEWLINE_CHAR "\n"

Display *dpy;
Window Root;
int screen;
int x_fd;
int d_depth;
XSizeHints mysizehints;
XWMHints mywmhints;
Pixel back_pix, fore_pix;
GC NormalGC;
Window iconwin, win;
char *ProgName;
char *Geometry;
char Execute[100];
char *ERR_colorcells = "not enough free color cells\n";
long Length = (65536 / sizeof(long));

typedef struct _XpmIcon {
    Pixmap pixmap;
    Pixmap mask;
    XpmAttributes attributes;
}        XpmIcon;

typedef struct query_target {
  char * name;
  char * pre;
  char * post;
} query_target_type ;
int Where;

int Raise;   /* Raise window? */

XpmIcon nets, negt;
XpmIcon visible;

/* prototypes */

void GetXPM(void);
static void CreatePixmap(Display *dpy, Window Root, char **data, XpmIcon* icon);
Pixel GetColor(char *name);
void RedrawWindow( XpmIcon *v);
void InsertTime();
int ProcessSelection (char *selection, Display *dpy, int NewWin, int dontask,
    int noproto, int quiet, int button);
int Selection2Bookmark (char *prefix, char *select, Window win);
int URLSelection (char *prefix, char *select, Window win, int NewWin, int raise);
int Search4Selection (char *select, Window win, int NewWin, int raise, int where);
int query_target_at (char *name);
int killchar(char *str, char *killchar);
void strim(char * str);
void transform(char * str);
char *encode (char *url, int button);
char *protocol (char *select, int noproto);
static void InitAtoms (Display *dpy);
static Window FindMozWin(Display *dpy);
static int SendCommand (Display *dpy, Window win, const char *command);

/*****************************************************************************/

static char *help_message[] = {
    "where options include:",
    " -a <Y|n>                Ask for URL if there is no X selection.",
    "                         Defaults to y",
    " -e <program>            Executable to start on left button double-click.",
    "                         Defaults to mozilla",
    " -i <Y|n>                Infer the protocol if the selection has none.",
    "                         Defaults to y",
	" -n                      Open new windows for right/middle click by default",
	" -t                      Open new tabs for right/middle click by default.",
	"                         Ignored if the \"-n\" flag is used.",
    " -p <[+|-]X[+|-]Y>       X/Y Position of wmnetselect.",
    "                         Defaults to +0+0",
    " -q <y|N>                Quiet:  disable audible error indication.",
    "                         Defaults to n",
    " -r <Y|n>                Raise (deiconify) the <program> window.",
    "                         Defaults to y",
    " -s <y|N>                Start <program> when wmnetselect is started.",
    "                         Defaults to n",
    " -w <search engine>      Which search engine to use on right button click:",
    "                         google, altavista, yahoo, excite, hotbot, lycos,",
    "                         northernlight, alltheweb, or raging",
    "                         Defaults to google",
    NULL
};

static query_target_type query_targets[] = {
  { "google",
    "http://www.google.com/search?q=",
    "&num=30"
  },
  { "altavista",
    "http://www.altavista.com/cgi-bin/query?pg=q&text=yes&what=web&fnt=d&q=",
    ""
  },
  { "excite",
    "http://search.excite.com/search.gw?search=",
    "&start=0&showSummary=true&perPage=30"
  },
  { "hotbot",
    "http://hotbot.lycos.com/?MT=",
    "",
  },
  { "lycos",
    "http://www.lycos.com/srch/?query=",
    "",
  },
  { "northernlight",
    "http://www.northernlight.com/nlquery.fcg?qr=",
    "&cb=0&us=025"
  },
  { "alltheweb",
    "http://alltheweb.com/cgi-bin/asearch?type=all&query=",
    ""
  },
  { "yahoo",
    "http://ink.yahoo.com/bin/query?p=",
    ""
  },
  { "raging",
    "http://ragingsearch.altavista.com/cgi-bin/query?q=",
    "&nbq=50"
  },
};

static int qt_num = sizeof(query_targets) / sizeof(query_target_type);

void usage() {
    char **cpp;

    fprintf(stderr,"\n%s version %4.2f\n\n",
            ProgName, VERSION);
    fprintf(stderr,"usage:  %s [-options ...] \n", ProgName);
    for (cpp = help_message; *cpp; cpp++) {
        fprintf(stderr, "%s\n", *cpp);
    }
    fprintf(stderr,"\n");
    exit(1);
}

int query_target_at (char *name) {
    int i;
    for (i=0; i < qt_num; i++) {
        if (!strcmp(query_targets[i].name,name))
	    return i;
    }
    fprintf (stderr, "Unknown search engine (%s). Defaulting to (%s).\n",
		name, query_targets[0].name);
    return 0;
}

int main(int argc,char *argv[]) {
    static Time last_left_mouse_click = -1;
    int i;
    unsigned int borderwidth ;
    char *display_name = NULL;
    char *wname = "wmnetselect";
    XGCValues gcv;
    unsigned long gcm;
    XEvent event;
    XTextProperty name;
    XClassHint classHint;
    Pixmap pixmask;

    unsigned long nitems, bytes_after;
    Atom type, property, target;
    int format;
    unsigned char *selection;
    Bool exists;

    int NewWin, cnt, defnew, delay, dontask, onstart, noproto, quiet;
    int ret = 25;
    
    cnt = defnew = dontask = onstart = noproto = quiet = 0;
    Raise = 0;
    
    ProgName = argv[0];
    Geometry = "";

    /* Default program to execute is #define EXECUTABLE  */
    strcpy (Execute, EXECUTABLE);

    /* Parse command line options */
    for (i=1; i<argc; i++) {
        char *arg = argv[i];

        if (arg[0] == '-') {
            switch (arg[1]) {
            case 'a':
                if (++i >= argc) usage();
                if (tolower(*argv[i]) == 'n')
	                dontask=1;	/* if no selection, ask */
                continue;
            case 'd':
                if (++i >= argc) usage();
		display_name = argv[i];
                continue;
            case 'e':
                if (++i >= argc) usage();
                strcpy(&Execute[0], argv[i]);
                continue;
            case 'i':
            	if (++i >= argc) usage();
                if (tolower(*argv[i]) == 'n')
                	noproto=1;	/* don't infer protocol */
                continue;
			case 'n':
				defnew = 1;
				continue;
			case 't':
				if (defnew == 0)
					defnew = 2;
				continue;
            case 'p':
                if (++i >= argc) usage();
                Geometry = argv[i];
                continue;
            case 'q':
            	if (++i >= argc) usage();
                if (tolower(*argv[i]) == 'y')
                	quiet=1;	/* no XBells */
                continue;
            case 'r':
            	if (++i >= argc) usage();
                if (tolower(*argv[i]) == 'n')
                	Raise=1;	/* don't raise window */
                continue;
            case 's':
            	if (++i >= argc) usage();
                if (tolower(*argv[i]) == 'y')
	                onstart=1;	/* start it at startup */
                continue;
	    case 'w':
		if (++i >= argc) usage();
		Where = query_target_at(argv[i]); 
		continue;
	    case 'v':
		fprintf (stderr,"\n%s version %4.2f\n\n",
            		ProgName, VERSION);
		exit(0);
		continue;	/* for consistency only */
            default:
                usage();
            }
        }
    }

    /* Open the display */
    if (!(dpy = XOpenDisplay(display_name))) {
        fprintf(stderr,"%s: can't open display %s\n",
                ProgName, XDisplayName(display_name));
        exit (1);
    }
    screen = DefaultScreen(dpy);
    Root = RootWindow(dpy, screen);
    d_depth = DefaultDepth(dpy, screen);
    x_fd = XConnectionNumber(dpy);

    GetXPM();

    /* Create a window to hold the banner */
    mysizehints.flags= USSize|USPosition;
    mysizehints.x = 0;
    mysizehints.y = 0;

    back_pix = GetColor("white");
    fore_pix = GetColor("black");

    XWMGeometry(dpy, screen, Geometry, NULL, (borderwidth =1), &mysizehints,
                &mysizehints.x,&mysizehints.y,&mysizehints.width,&mysizehints.height, &i);

    mysizehints.width = nets.attributes.width;
    mysizehints.height= nets.attributes.height;

    win = XCreateSimpleWindow(dpy,Root,mysizehints.x,mysizehints.y,
                              mysizehints.width,mysizehints.height,
                              borderwidth,fore_pix,back_pix);

    iconwin = XCreateSimpleWindow(dpy,win,mysizehints.x,mysizehints.y,
                                  mysizehints.width,mysizehints.height,
                                  borderwidth,fore_pix,back_pix);

    XSetWMNormalHints(dpy, win, &mysizehints);
    classHint.res_name =  "wmnetselect";
    classHint.res_class = "WMNetselect";
    XSetClassHint(dpy, win, &classHint);

    XSelectInput(dpy,win,MW_EVENTS);
    XSelectInput(dpy,iconwin,MW_EVENTS);

    if (XStringListToTextProperty(&wname, 1, &name) == 0) {
        fprintf(stderr, "%s: can't allocate window name\n", ProgName);
        exit(-1);
    }
    XSetWMName(dpy, win, &name);

    /* Create a GC for drawing */
    gcm = GCForeground|GCBackground|GCGraphicsExposures;
    gcv.foreground = fore_pix;
    gcv.background = back_pix;
    gcv.graphics_exposures = FALSE;
    NormalGC = XCreateGC(dpy, Root, gcm, &gcv);

    mywmhints.initial_state = WithdrawnState;
    mywmhints.icon_window = iconwin;
    mywmhints.icon_x = mysizehints.x;
    mywmhints.icon_y = mysizehints.y;
    mywmhints.window_group = win;
    mywmhints.flags = StateHint | IconWindowHint | IconPositionHint
                      | WindowGroupHint;
    XSetWMHints(dpy, win, &mywmhints);

    XSetCommand(dpy, win, argv, argc);
    XMapWindow(dpy,win);

    if (onstart) {
        strcat(&Execute[0], "&");
        system(Execute);
        /* take the ampersand back out */
        Execute[strlen(Execute)-1]='\0';
    }

    InitAtoms (dpy);

    RedrawWindow(&visible);
    while(1) {
        /* read a packet */
        while (XPending(dpy)) {
            XNextEvent(dpy,&event);
            switch(event.type) {
            case Expose:
                if(event.xexpose.count == 0 )
                    RedrawWindow(&visible);
                break;
            case ButtonPress:
                if (event.xbutton.button == LEFT_BUTTON) {
                    if (last_left_mouse_click > 0 && (event.xbutton.time
		            - last_left_mouse_click) <= DOUBLE_CLICK_TIME) {
                        last_left_mouse_click = -1;
                        XCopyArea(dpy, negt.pixmap, visible.pixmap,NormalGC,
                                  0,0,mysizehints.width,mysizehints.height,0,0);

                        delay=1;
                        RedrawWindow(&visible);

                        strcat(&Execute[0], "&");
                        system(Execute);

                        /* take the ampersand back out */
                        Execute[strlen(Execute)-1]='\0';
                   }
                    last_left_mouse_click = event.xbutton.time;
                    if ((event.xbutton.state & ControlMask) != 0 ) {
                        NewWin = 0;
						property = XInternAtom(dpy, "TEXT_STRING", exists = False);
                        target = XInternAtom(dpy, "STRING", exists = True);
                        XConvertSelection(dpy, XA_PRIMARY, target, property, win, CurrentTime);
					}
                }

                if (event.xbutton.button == MIDDLE_BUTTON ||
					event.xbutton.button == RIGHT_BUTTON) {

                    /* Open a new window when ctrl-[Middle|Right]Button pressed */
                    if ((event.xbutton.state & ControlMask) != 0)
                        NewWin = 1;
                    else
                        NewWin = 0;

					if (defnew == 1) {
						NewWin = !NewWin;
					} else if(defnew == 2) {
						NewWin = (NewWin == 1) ? 0 : 2;
					}

                    /* create an atom for data property to be put into */
                    property = XInternAtom(dpy, "TEXT_STRING", exists = False);

                    /* target type atom must have been created by owner */
                    target = XInternAtom(dpy, "STRING", exists = True);

                    /* now send out a request for the data */
                    XConvertSelection(dpy, XA_PRIMARY, target, property, win, CurrentTime);
                }
                break;
            case SelectionNotify:
                if (event.xselection.property == property) {
                    ret = XGetWindowProperty(dpy, win, property, 0L, Length,
                                             True, target, &type, &format,
                                             &nitems, &bytes_after, &selection);

                    if (NULL != selection) {
                        XCopyArea(dpy, negt.pixmap, visible.pixmap,NormalGC,
                                  0,0,mysizehints.width,mysizehints.height,0,0);
                        delay = 1;
                        RedrawWindow(&visible);
                        ProcessSelection (selection, dpy, NewWin, dontask,
			    noproto, quiet, event.xbutton.button);
                    }

                } else {
                    if (event.xselection.property == None) {
                        /* printf ("Nothing higlighted.\n");  */
                        ProcessSelection (NULL, dpy, 0, dontask, 0, quiet, event.xbutton.button);
                    }
                }
                break;
            case DestroyNotify:
                XCloseDisplay(dpy);
                exit(0);
            default:
                break;
            }
        }
        XFlush(dpy);
#ifdef SYSV
        poll((struct poll *) 0, (size_t) 0, 50);
#else
        usleep(50000L);			/* 5/100 sec */
#endif
        /* Delay ~2 seconds before redrawing default pixmap  */
        if (delay) cnt++;
        if (cnt > 40) {
            cnt = 0;
            delay=0;
            XCopyArea(dpy, nets.pixmap, visible.pixmap,NormalGC,
                      0,0,mysizehints.width,mysizehints.height,0,0);
            RedrawWindow(&visible);
        }
    }
    return 0;
}

/****************************************************************************/

void nocolor(char *a, char *b) {
    fprintf(stderr,"%s: can't %s %s\n", ProgName, a,b);
}

/****************************************************************************/

void GetXPM(void) {
    XWindowAttributes attributes;

    /* for the colormap */
    XGetWindowAttributes(dpy,Root,&attributes);

    CreatePixmap(dpy, Root, netscape, &nets);
    CreatePixmap(dpy, Root, negative, &negt);
    CreatePixmap(dpy, Root, netscape, &visible);
}

/****************************************************************************/

static void CreatePixmap(Display *dpy, Window Root, char **data, XpmIcon* icon) {
    int ret;

    icon->attributes.valuemask |= (XpmReturnPixels | XpmReturnExtensions
				   | XpmExactColors | XpmCloseness);
    icon->attributes.exactColors=False;
    icon->attributes.closeness=65636;
    ret = XpmCreatePixmapFromData(dpy, Root, data, &(icon->pixmap),
                                  &(icon->mask), &(icon->attributes));
    if(ret != XpmSuccess) {
        fprintf(stderr, ERR_colorcells);
        exit(1);
    }
}

/****************************************************************************/
/* Removes expose events for a specific window from the queue */

int flush_expose(Window win) {
    XEvent dummy;
    int i=0;

    while (XCheckTypedWindowEvent (dpy, win, Expose, &dummy))i++;
    return i;
}

/****************************************************************************/
/* Draws the icon window */

void RedrawWindow(XpmIcon *v) {
    flush_expose (iconwin);
    XCopyArea(dpy,v->pixmap,iconwin,NormalGC,
              0,0,v->attributes.width, v->attributes.height,0,0);
    flush_expose (win);
    XCopyArea(dpy,v->pixmap,win,NormalGC,
              0,0,v->attributes.width, v->attributes.height,0,0);

}

/****************************************************************************/

Pixel GetColor(char *name) {
    XColor color;
    XWindowAttributes attributes;

    XGetWindowAttributes(dpy,Root,&attributes);
    color.pixel = 0;
    if (!XParseColor (dpy, attributes.colormap, name, &color)) {
        nocolor("parse",name);
    } else if(!XAllocColor (dpy, attributes.colormap, &color)) {
        nocolor("alloc",name);
    }
    return color.pixel;
}

/****************************************************************************/

/*
 * Process the X selection:
 *   trim whitespace
 *   encode URL per RFC1738
 *   transform Slashdot, etc.
 *   Add protocol, if there is none
 *   Get existing Mozilla window id, 
 *     or start Mozilla if there isn't one.
 *   Send "processed" selection to Mozilla via SendCommand().
 */
 
int ProcessSelection (char *selection, Display *dpy, int NewWin, int dontask,
        int noproto, int quiet, int button) {
    char *prefix, *select;
    int err, raise;
    Window win;

    strim (selection);

    /* If we're using the middle button, we're trying to process
     * a URL. If so, then we have no need for spaces in the middle
     * of the URL. Squashing these spaces allows us to process URLs
     * that are broken across one or more lines.
     */
    if ( button != RIGHT_BUTTON ) {
        killchar(selection, " ");
        killchar(selection, NEWLINE_CHAR);
    }

    select = encode (selection, button);
    if (select == NULL) {
        fprintf (stderr, "Could not allocate memory\n");
        return -1;
    }

    /* transform keywords like slashdot, windowmaker, etc. */
    transform (select);
    
    raise = Raise;
    /* This block determines how to handle Null selections.  */
    if (strlen (select) == 0) {
        if (dontask) {
            if (!quiet) XBell(dpy, 10);
            if (select) free (select);
            return 0;
        } else {
	    NewWin = 0;
	    noproto = 1;
	    raise = 0;  /* Always raise if selection is NULL */
 	}
    }
    prefix = protocol (select, noproto);
    
    switch (button) {
    case LEFT_BUTTON:
        err = Selection2Bookmark (prefix, select, FindMozWin(dpy));
        break;
    case MIDDLE_BUTTON:
        err = URLSelection (prefix, select, FindMozWin(dpy), NewWin, raise);
        break;
    case RIGHT_BUTTON:
        err = Search4Selection (select, FindMozWin(dpy), NewWin, raise, Where);
        break;
    }
    if (select) free (select);
    return err;
}

/*
 * Create Bookmark using selection.  If Mozilla is not started,
 * start it, then create bookmark.
 */
 
int Selection2Bookmark (char *prefix, char *select, Window win) {
    char *netcommand;
    int error;

    if (win == None) {
        /* No Mozilla window, start one.  */
	/* prefix + & + "" + spaces + 2>/dev/null = 24 */
        netcommand = (char *)malloc(sizeof(char) * (strlen(Execute)
	    + strlen(select) + 25));
        if (netcommand == NULL) {
             fprintf (stderr, "Could not allocate memory\n");
            return -1;
        }
        sprintf (netcommand, "%s \"%s%s\" 2>/dev/null &", Execute,
                 prefix, select);
        error = system (netcommand);
    } else {
    
	netcommand = (char *) malloc(sizeof(char) * (strlen(select) + 30));
	if (netcommand == NULL) {
            fprintf (stderr, "Could not allocate memory\n");
            return -1;
	}
	sprintf (netcommand, "AddBookmark(%s%s,noraise)", prefix, select);

	error = SendCommand(dpy, win, netcommand);
    }
    if (netcommand) free (netcommand);
    return error;
}

int URLSelection (char *prefix, char *select, Window win, int NewWin, int raise) {
    char *netcommand = NULL, *NewWinString = "";
    int error;
    
    if (win == None) {
        /* No Mozilla window: start one.  */
	/* prefix + & + "" + spaces + 2>/dev/null = 24 */
        netcommand = (char *)malloc(sizeof(char) * (strlen(Execute)
	    + strlen(select) + 25));
        if (netcommand == NULL) {
            fprintf (stderr, "Could not allocate memory\n");
            return -1;
        }
        sprintf (netcommand, "%s \"%s%s\" 2>/dev/null &", Execute,
                 prefix, select);
        error = system (netcommand);
    } else /* win != None */ {
        /* netcommand = (char *) malloc(sizeof(char) * (strlen(select) + 27));
	*/
        netcommand = (char *) malloc(sizeof(char) * (strlen(select) + 35));
        if (netcommand == NULL) {
            fprintf (stderr, "Could not allocate memory\n");
            return -1;
        }
        if(NewWin == 1) NewWinString = ",new-window";
		else if(NewWin == 2) NewWinString = ",new-tab";
		sprintf (netcommand, "openURL(%s%s%s%s)",
                 prefix, select, NewWinString,
		 raise ? ",noraise" : "");

        error = SendCommand(dpy, win, netcommand);
    }
    /* printf ("\nerr = <%d>, netcommand=<%s> ",error, netcommand); */
    if (netcommand) 
		free (netcommand);
    return error;
}

/*
 * Send selection to the search engine as a query.
 */
 
int Search4Selection (char *select, Window win, int NewWin, int raise, int where) {
    query_target_type target = query_targets[where];
    char *netcommand = NULL, *NewWinString = "";
    int error;
    
    if (win == None) {
        /* No Mozilla window, start one.  */
        /* 2>/dev/null + spaces + & + "" = 17 */
        netcommand = (char *)
	   malloc (sizeof(char) * (strlen(Execute)
	    + strlen(target.pre) + strlen(select) + strlen(target.post) + 18));
        if (netcommand == NULL) {
            fprintf (stderr, "Could not allocate memory\n");
            return -1;
        }
        sprintf (netcommand, "%s \"%s%s%s\" 2>/dev/null &", Execute,
                 target.pre, select, target.post);
        error = system (netcommand);
    } else /* win != None */ {
        /* strlen ("openURL(,new-window)") = 20 */
        netcommand = (char *)
	   malloc(sizeof(char) * (
	      strlen(target.pre) + strlen(select) + strlen(target.post) + 28));
        if (netcommand == NULL) {
            fprintf (stderr, "Could not allocate memory\n");
            return -1;
        }
		if(NewWin == 1) NewWinString = ",new-window";
		else if(NewWin == 2) NewWinString = ",new-tab";
        sprintf (netcommand, "openURL(%s%s%s%s%s)",
                 target.pre, select, target.post, NewWinString,
		 raise ? ",noraise" : "");

        error = SendCommand(dpy, win, netcommand);
    }
    if (netcommand) free (netcommand);
    return error;
}

/* killchar()
 *  
 *  Arguments: pointer to a character string
 *  Purpose  : Removes newlines from the string.
 *  Returns  : number of newlines removed
 *  [Contributed by bigdan@kreft.net]
 */

int killchar(char *str, char *killchar) {
    char *newstr;
    char *next_chunk;
    int killed = 0;         // Number of newlines removed
    
    /* Just leave if there aren't any newlines to mess with. */
    if (NULL == str || strchr(str, *killchar) == (char *) NULL ) {
        return(0);
    }
    
    /* Allocate memory for buffer. */
    newstr = (char *) malloc(sizeof(char) * strlen(str));
    
    /* Get the chunk before the first newline and append it to newstr.  */
    next_chunk = strtok(str, killchar);
    strcpy(newstr, next_chunk);
    
    /* Get and append all remaining chunks delimited by newlines.  */
    while ( (next_chunk = strtok(NULL, killchar)) != (char *)NULL ) {
        strncat(newstr, next_chunk, strlen(next_chunk));
        ++killed;
    }

    strncpy(str, newstr, strlen(newstr)+1);
    free(newstr);
    
    return(killed);
}

/* Trim whitespace from both ends of str */

void strim(char *str) {
    int beg, end;

    if (str != NULL && *str != '\0') {
        end = strlen(str);
        for (; end > 0 && isspace(str[end-1]); end--);

        str[end] = '\0';
        for (beg = 0; beg < end && isspace(str[beg]); beg++);

        if (beg > 0)
            memmove(str, &str[beg], end-beg+1);
    }
}

/* Transform windowmaker to windowmaker.org, etc.  */
/* encode() malloc'ed extra memory for select to add ".org" or ".net"  */

void transform (char *str) {
    if (strcasecmp (str, "windowmaker") == 0)
        strcat (str, ".org");
    else if (strcasecmp (str, "slashdot") == 0)
        strcat (str, ".org");
    else if (strcasecmp (str, "freshmeat") == 0)
        strcat (str, ".net");

/*   need to add www.prefix to these:
    else if (strcasecmp (str, "gnu") == 0)
        strcat (str, ".org");
    else if (strcasecmp (str, "gnome") == 0)
        strcat (str, ".org");
    else if (strcasecmp (str, "kde") == 0)
        strcat (str, ".org");
*/
}

/*
 * Validating URLs:  If the selection is to be interpreted as a URL,
 * then, encode extra chars with "%HH", where H is a Hex digit and
 * extra chars are "!", "*", "'", "(", ")", ","
 *
 *     encode chars per RFC1738
 */

char *encode (char *url, int button) {
    char *ncoded, esc[3], *uns;
    int i, j, len;
    static char *unsafe = "!*'(),{};|\\^~[]`";
    static char *punctuation = "#?&+$%\":<>/.=!*'(),{};|\\^~[]`";
    
    if (NULL == url || (len = strlen(url)) == 0) {
        ncoded = (char *) malloc(sizeof(char) );
	*ncoded = '\0';
	return (ncoded);
    }
    if (button == RIGHT_BUTTON)
    	uns = punctuation;
    else
        uns = unsafe;
    i=j=0;

    /* allocate extra chars for ".org" or ".net"   */
    ncoded = (char *) malloc(sizeof(char) * len * 3);
    if (ncoded == NULL) {
        fprintf (stderr, "Could not allocate memory\n");
        return NULL;
    }

    while (1) {
	if (strchr (uns, url[j])) {
	           sprintf (esc, "%2x", url[j]);
        /*   if ((ncoded = (char *) realloc(ncoded, sizeof(char) * (len + 4)))
                        == NULL)
                return NULL;
	*/
            ncoded[i++]='%';
            ncoded[i++]=esc[0];
            ncoded[i++]=toupper(esc[1]);
	}
	 else if (isspace (url[j]))
	     ncoded[i++] = '+';
	 else
	     ncoded[i++] = url[j];

        if (url[++j] == '\0')
            break;
    }
    ncoded[i] = '\0';
    return (ncoded);
}

/*
 * Heuristic to supply the URL protocol: mailto, ftp;//, or http://
 */

char *protocol (char *url, int noproto) {
     static char ptcol[8];
     char *ptr;
    
    if (noproto || strstr(url, ":/"))
    	return (strcpy(ptcol,""));

    /* Are the first 4 chars "ftp." ?  */
    ptr = url;
    if (strstr(url, "ftp.") == ptr)
         return (strcpy (ptcol,"ftp://"));

    /* contains a '@' but no '/'  */
    if (!strchr(url, '/') && strchr(url, '@'))
         return (strcpy (ptcol, "mailto:"));

    /* first character is a '/', then it must be a file */
    if (*url == '/')
         return (strcpy (ptcol, "file:"));

    return (strcpy (ptcol, "http://"));
}

/********************* nsremote **********************************
  
  Mozilla remote control mechanism:
  See the reference implementation of the Mozilla remote control
  protocol (written by ex-Mozillan Jamie Zawinski jwz@jwz.org) at:
     http://home.netscape.com/newsref/std/remote.c
 
********************** nsremote **********************************/

static Atom XA_MOZILLA_VERSION  = 0;
static Atom XA_MOZILLA_LOCK     = 0;
static Atom XA_MOZILLA_COMMAND  = 0;
static Atom XA_MOZILLA_RESPONSE = 0;

static void InitAtoms (Display *dpy) {
    if (!XA_MOZILLA_VERSION)
        XA_MOZILLA_VERSION = XInternAtom (dpy, MOZILLA_VERSION_PROP, False);
    if (!XA_MOZILLA_LOCK)
        XA_MOZILLA_LOCK = XInternAtom (dpy, MOZILLA_LOCK_PROP, False);
    if (!XA_MOZILLA_COMMAND)
        XA_MOZILLA_COMMAND = XInternAtom (dpy, MOZILLA_COMMAND_PROP, False);
    if (!XA_MOZILLA_RESPONSE)
        XA_MOZILLA_RESPONSE = XInternAtom (dpy, MOZILLA_RESPONSE_PROP, False);
}

/*
 * See if the given window is a Mozilla window by looking for the
 * XA_MOZILLA_VERSION property
 */

static int
Check4Moz(Display *dpy, Window win) {
    Atom type;
    int format;
    unsigned long nitems, bytes_after;
    unsigned char *version = NULL;
    int status = XGetWindowProperty(dpy, win, XA_MOZILLA_VERSION, 0,
                                    Length, False, XA_STRING, &type,
                                    &format, &nitems, &bytes_after, &version);

    if (status != Success || !version) {
        if (version)
            XFree(version);
        return 0;
    }
    XFree(version);
    return 1;
}

/*
 * Find a Mozilla window.  If none available, return None.
 */

static Window
GetWindow(Display *dpy) {
    int i;
    Window root = RootWindowOfScreen (DefaultScreenOfDisplay (dpy));
    Window root2, parent, *kids;
    unsigned int nkids;
    Window result = None;

    if (! XQueryTree(dpy, root, &root2, &parent, &kids, &nkids)) {
        return None;
    }
    if (root != root2) {
        return None;
    }
    if (parent != None) {
        return None;
    }
    if (! (kids && nkids)) {
        return None;
    }

    for (i = 0; i < nkids; i++) {
        Window w = XmuClientWindow(dpy, kids[i]);
        if (Check4Moz(dpy, w)) {
            result = w;
            break;
        }
    }
    return result;
}

/* 
 * Trap error, but ignore it.
 */

int ErrorHandler (Display *dpy, XErrorEvent *event) {
    return 0;
}

/* 
 * Returns the saved window id Mozilla.  If no window id set,
 *  call GetWindow to attempt to find one.
 */

static Window
FindMozWin(Display *dpy) {
    Window win = None;

    XSetErrorHandler (ErrorHandler);
    if (win != None) {
        if (! Check4Moz(dpy, win)) {
            return None;
        }
    }
    if (MozWin != None && win == None) {
        if (Check4Moz(dpy, MozWin)) {
            win = MozWin;
        } else {
            MozWin = None;
        }
    }
    if (win == None) {
        if ((win = GetWindow(dpy)) == None) {
            return None;
        }
        MozWin = win;
    }
    return win;
}

/*
 * Participate in the Mozilla locking protocol so commands don't collide
 */

static int
GetLock(Display *dpy, Window win) {
    char lock_data[255];
    Bool locked = False;

    sprintf(lock_data, "pid%d@", getpid());
    if (gethostname(lock_data + strlen(lock_data), 100) == -1) {
        fprintf (stderr, "gethostname() error\n");
        return 0;
    }

    do {
        int result;
        Atom type;
        int format;
        unsigned long nitems, bytes_after;
        unsigned char *data = NULL;

        /*
         * Grab the server so nobody else can do anything
         */

        XGrabServer(dpy);

        /*
         * Check for Mozilla Lock
         */
        result = XGetWindowProperty(dpy, win, XA_MOZILLA_LOCK, 0,
                                    Length, False, XA_STRING, &type,
                                    &format, &nitems, &bytes_after, &data);

        if (result != Success || type == None) {
            /*
             * It's not locked now, lock it
             */
            XChangeProperty(dpy, win, XA_MOZILLA_LOCK, XA_STRING,
                            8, PropModeReplace,
                            (unsigned char *) lock_data,
                            strlen(lock_data));
            locked = True;
        }
        /*
         * Release the server grab
         */

        XUngrabServer(dpy);
        XSync(dpy, False);

        if (!locked) {
           /*
            * There was already a lock in place.  Wait for
            * a PropertyDelete event.
            */

            while (1) {
                XEvent event;
                XNextEvent (dpy, &event);
                if (event.xany.type == DestroyNotify
			&& event.xdestroywindow.window == win) {
                    /* 
		     * fprintf (stderr, "window 0x%x unexpectedly
                     * destroyed.\n", win);
		     */
                    return -1;
                } else if (event.xany.type == PropertyNotify
			&& event.xproperty.state == PropertyDelete
			&& event.xproperty.window == win
			&& event.xproperty.atom == XA_MOZILLA_LOCK) {
                    break;
                }
            }
        }
        if (data)
            XFree(data);
    } while (! locked);

    return locked == True ? 1 : 0;
}

static void
ReleaseLock(Display *dpy, Window win) {
    Atom type;
    int format;
    unsigned long nitems, bytes_after;
    unsigned char *data;

    XGetWindowProperty(dpy, win, XA_MOZILLA_LOCK, 0,
                       Length, True /* delete */,
                       XA_STRING, &type, &format,
                       &nitems, &bytes_after, &data);
    if (data)
        XFree(data);
}

/*
 * Send a command to the Mozilla window we found previously
 */

static int SendCommand (Display *dpy, Window win, const char *command) {
    int result, counter = 0;
    Bool done = False;
    Atom type;
    int format;
    unsigned long nitems, bytes_after;
    unsigned char *data = 0;

    /*
    * Select for PropertyChange events on the Mozilla window
    */

    XSelectInput(dpy, win, (PropertyChangeMask | StructureNotifyMask));

    if (GetLock(dpy, win) == 0) {
        XSelectInput(dpy, win, 0);
        return 1;
    }

    /*
     * We've got a successful lock, so send the command to Mozilla
     */

    /*  
     * fprintf (stderr, "(writing " MOZILLA_COMMAND_PROP " \"%s\" to 0x%x)\n",
     *  command, (unsigned int) win);
     */

    XChangeProperty(dpy, win, XA_MOZILLA_COMMAND,
                    XA_STRING, 8, PropModeReplace,
                    (unsigned char *) command, strlen(command));

    while (!done) {
        XEvent event;
        XNextEvent (dpy, &event);
        if (event.xany.type == DestroyNotify &&
                    event.xdestroywindow.window == win) {
            /*
	     * fprintf (stderr, "window 0x%x was destroyed.\n",
             * (unsigned int) win);
	     */
            return -1;
        } else if (event.xany.type == PropertyNotify &&
                    event.xproperty.state == PropertyNewValue &&
                    event.xproperty.window == win &&
                    event.xproperty.atom == XA_MOZILLA_RESPONSE) {

            result = XGetWindowProperty(dpy, win,
                                        XA_MOZILLA_RESPONSE, 0,
                                        Length, True /* delete */,
                                        XA_STRING, &type, &format,
                                        &nitems, &bytes_after, &data);

            if (result != Success) {
                /* 
		 * fprintf (stderr, "Failed to read response from Mozilla\n");
		 */
                ReleaseLock(dpy, win);
                XSelectInput(dpy, win, 0);
                return 1;
            }
            if (DEBUG && result == Success && data && *data) {
                fprintf (stderr, "(server sent " MOZILLA_RESPONSE_PROP
                         " \"%s\" to 0x%x.)\n", data, (unsigned int) win);
            }
	    
	    /* 
	     * counter gets us out if we are stuck waiting for a lock.
	     */
            if (!data || (++counter > 9)) {
                /* 
		 * printf ("No data returned from Mozilla\n");
		 */
                ReleaseLock(dpy, win);
                XSelectInput(dpy, win, 0);
                return 1;
            }
            if (data) {
                XFree (data);
                done=True;
            }
            ReleaseLock(dpy, win);
            XSelectInput(dpy, win, 0);
        }
    }
    return 0;
}