File: rxvttoolkit.C

package info (click to toggle)
rxvt-unicode 9.22-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 6,476 kB
  • ctags: 5,351
  • sloc: ansic: 44,050; cpp: 18,621; sh: 3,235; perl: 2,972; makefile: 584
file content (1281 lines) | stat: -rw-r--r-- 29,513 bytes parent folder | download | duplicates (2)
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
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
/*----------------------------------------------------------------------*
 * File:	rxvttoolkit.C
 *----------------------------------------------------------------------*
 *
 * All portions of code are copyright by their respective author/s.
 * Copyright (c) 2003-2011 Marc Lehmann <schmorp@schmorp.de>
 * Copyright (c) 2011      Emanuele Giaquinta <e.giaquinta@glauco.it>
 *
 * 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 3 of the License, 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; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *----------------------------------------------------------------------*/

#include "../config.h"
#include <rxvt.h>
#include <rxvttoolkit.h>

#include <stdlib.h>

#include <unistd.h>
#include <fcntl.h>

#include <sys/utsname.h>
#include <sys/socket.h>
#include <sys/un.h>

#if XFT
# include <X11/extensions/Xrender.h>
#endif

static const char *const xa_names[] =
{
  "TEXT",
  "COMPOUND_TEXT",
  "UTF8_STRING",
  "MULTIPLE",
  "TARGETS",
  "TIMESTAMP",
  "VT_SELECTION",
  "INCR",
  "WM_PROTOCOLS",
  "WM_DELETE_WINDOW",
  "CLIPBOARD",
  "AVERAGE_WIDTH",
  "WEIGHT_NAME",
  "SLANT",
  "CHARSET_REGISTRY",
  "CHARSET_ENCODING",
#if ENABLE_FRILLS
  "_MOTIF_WM_HINTS",
#endif
#if ENABLE_EWMH
  "_NET_WM_PID",
  "_NET_WM_NAME",
  "_NET_WM_ICON_NAME",
  "_NET_WM_PING",
  "_NET_WM_ICON",
#endif
#if USE_XIM
  "WM_LOCALE_NAME",
  "XIM_SERVERS",
#endif
#if HAVE_IMG || ENABLE_PERL
  "_XROOTPMAP_ID",
  "ESETROOT_PMAP_ID",
#endif
#if ENABLE_XEMBED
  "_XEMBED",
  "_XEMBED_INFO",
#endif
#if !ENABLE_MINIMAL
  "SCREEN_RESOURCES",
  "XDCCC_LINEAR_RGB_CORRECTION",
  "XDCCC_LINEAR_RGB_MATRICES",
  "WM_COLORMAP_WINDOWS",
  "WM_STATE",
  "cursor",
# if USE_XIM
  "TRANSPORT",
  "LOCALES",
  "_XIM_PROTOCOL",
  "_XIM_XCONNECT",
  "_XIM_MOREDATA",
# endif
#endif
};

/////////////////////////////////////////////////////////////////////////////

refcounted::refcounted (const char *id)
{
  this->id = strdup (id);
}

refcounted::~refcounted ()
{
  free (id);
}

template<class T>
T *refcache<T>::get (const char *id)
{
  for (T **i = this->begin (); i < this->end (); ++i)
    {
      if (!strcmp (id, (*i)->id))
        {
          ++(*i)->referenced;
          (*i)->ref_next ();
          return *i;
        }
    }

  T *obj = new T (id);

  if (obj && obj->ref_init ())
    {
      obj->referenced = 1;
      this->push_back (obj);
      return obj;
    }
  else
    {
      delete obj;
      return 0;
    }
}

template<class T>
void refcache<T>::put (T *obj)
{
  if (!obj)
    return;

  if (!--obj->referenced)
    {
      this->erase (find (this->begin (), this->end (), obj));
      delete obj;
    }
}

template<class T>
void refcache<T>::clear ()
{
  while (this->size ())
    put (*this->begin ());
}

/////////////////////////////////////////////////////////////////////////////

#if USE_XIM

static void
#if XIMCB_PROTO_BROKEN
im_destroy_cb (XIC unused1, XPointer client_data, XPointer unused3)
#else
im_destroy_cb (XIM unused1, XPointer client_data, XPointer unused3)
#endif
{
  rxvt_xim *xim = (rxvt_xim *)client_data;
  rxvt_display *display = xim->display;

  xim->xim = 0;

  display->xims.erase (find (display->xims.begin (), display->xims.end (), xim));
  display->im_change_cb ();
}

bool
rxvt_xim::ref_init ()
{
  display = GET_R->display; //HACK: TODO

  xim = XOpenIM (display->dpy, 0, 0, 0);

  if (!xim)
    return false;

  XIMCallback ximcallback;
  ximcallback.client_data = (XPointer)this;
  ximcallback.callback = im_destroy_cb;

  XSetIMValues (xim, XNDestroyCallback, &ximcallback, (char *)0);

  return true;
}

rxvt_xim::~rxvt_xim ()
{
  if (xim)
    XCloseIM (xim);
}

#endif

/////////////////////////////////////////////////////////////////////////////

#if XFT
rxvt_drawable::~rxvt_drawable ()
{
  if (xftdrawable)
    XftDrawDestroy (xftdrawable);
}

rxvt_drawable::operator XftDraw *()
{
  if (!xftdrawable)
    xftdrawable = XftDrawCreate (screen->dpy, drawable, screen->visual, screen->cmap);

  return xftdrawable;
}
#endif

/////////////////////////////////////////////////////////////////////////////

#if XFT

// not strictly necessary as it is only used with superclass of zero_initialised
rxvt_screen::rxvt_screen ()
: scratch_area (0)
{
}

rxvt_drawable &rxvt_screen::scratch_drawable (int w, int h)
{
  if (!scratch_area || w > scratch_w || h > scratch_h)
    {
      if (scratch_area)
        {
          XFreePixmap (dpy, scratch_area->drawable);
          delete scratch_area;
        }

      Pixmap pm = XCreatePixmap (dpy, RootWindowOfScreen (ScreenOfDisplay (dpy, display->screen)),
                                 scratch_w = w, scratch_h = h, depth);

      scratch_area = new rxvt_drawable (this, pm);
    }

  return *scratch_area;
}

#endif

void
rxvt_screen::set (rxvt_display *disp)
{
  display = disp;
  dpy     = disp->dpy;

  Screen *screen = ScreenOfDisplay (dpy, disp->screen);

  depth   = DefaultDepthOfScreen    (screen);
  visual  = DefaultVisualOfScreen   (screen);
  cmap    = DefaultColormapOfScreen (screen);
}

#if ENABLE_FRILLS

void
rxvt_screen::select_visual (int id)
{
  XVisualInfo vinfo;
  vinfo.visualid = id;
  int n;

  if (XVisualInfo *vi = XGetVisualInfo (dpy, VisualIDMask, &vinfo, &n))
    {
      depth  = vi->depth;
      visual = vi->visual;

      XFree (vi);

      cmap = XCreateColormap (dpy, display->root, visual, AllocNone);
    }
  else
    rxvt_warn ("no visual found for requested id 0x%02x, using default visual.\n", id);
}

void
rxvt_screen::select_depth (int bitdepth)
{
  XVisualInfo vinfo;

  if (XMatchVisualInfo (dpy, display->screen, bitdepth, TrueColor, &vinfo))
    select_visual (vinfo.visualid);
  else
    rxvt_warn ("no visual found for requested depth %d, using default visual.\n", bitdepth);
}

#endif

void
rxvt_screen::clear ()
{
#if XFT
  if (scratch_area)
    {
      XFreePixmap (dpy, scratch_area->drawable);
      delete scratch_area;
    }
#endif

  if (cmap != DefaultColormapOfScreen (ScreenOfDisplay (dpy, display->screen)))
    XFreeColormap (dpy, cmap);
}

/////////////////////////////////////////////////////////////////////////////

rxvt_display::rxvt_display (const char *id)
: refcounted (id)
, selection_owner (0)
, clipboard_owner (0)
{
  x_ev    .set<rxvt_display, &rxvt_display::x_cb    > (this);
  flush_ev.set<rxvt_display, &rxvt_display::flush_cb> (this);
}

XrmDatabase
rxvt_display::get_resources (bool refresh)
{
  char *homedir = getenv ("HOME");
  char fname[1024];

  /*
   * get resources using the X library function
   */
  char *displayResource, *xe;
  XrmDatabase rdb1, database = 0;

#if !XLIB_ILLEGAL_ACCESS
  /* work around a bug in XrmSetDatabase where it frees the db, see ref_next */
  database = XrmGetStringDatabase ("");
#endif

  // for ordering, see for example http://www.faqs.org/faqs/Xt-FAQ/ Subject: 20
  // as opposed to "standard practise", we always read in ~/.Xdefaults

  // 6. System wide per application default file.

  /* Add in $XAPPLRESDIR/Rxvt only; not bothering with XUSERFILESEARCHPATH */
  if (!(xe = getenv ("XAPPLRESDIR")))
    {
      // Debian-specific; see #348697 and Policy
      xe = "/etc/X11/app-defaults";
    }
  snprintf (fname, sizeof (fname), "%s/%s", xe, RESCLASS);

  if ((rdb1 = XrmGetFileDatabase (fname)))
    XrmMergeDatabases (rdb1, &database);

  // 5. User's per application default file.
  // none

  // 4. User's defaults file.
  if (homedir)
    {
      snprintf (fname, sizeof (fname), "%s/.Xdefaults", homedir);

      if ((rdb1 = XrmGetFileDatabase (fname)))
        XrmMergeDatabases (rdb1, &database);
    }

  /* Get any Xserver defaults */
  if (refresh)
    {
      // fucking xlib keeps a copy of the rm string
      Atom actual_type;
      int actual_format;
      unsigned long nitems, nremaining;
      char *val = 0;

#if XLIB_ILLEGAL_ACCESS
      if (dpy->xdefaults)
        XFree (dpy->xdefaults);
#endif

      if (XGetWindowProperty (dpy, RootWindow (dpy, 0), XA_RESOURCE_MANAGER,
                              0L, 100000000L, False,
                              XA_STRING, &actual_type, &actual_format,
                              &nitems, &nremaining,
                              (unsigned char **)&val) == Success
          && actual_type == XA_STRING
          && actual_format == 8)
        displayResource = val;
      else
        {
          displayResource = 0;

          if (val)
            XFree (val);
        }

#if XLIB_ILLEGAL_ACCESS
      dpy->xdefaults = displayResource;
#endif
    }
  else
    displayResource = XResourceManagerString (dpy);

  if (displayResource)
    {
      if ((rdb1 = XrmGetStringDatabase (displayResource)))
        XrmMergeDatabases (rdb1, &database);
    }

#if !XLIB_ILLEGAL_ACCESS
  if (refresh && displayResource)
    XFree (displayResource);
#endif

  /* Get screen specific resources */
  displayResource = XScreenResourceString (ScreenOfDisplay (dpy, screen));

  if (displayResource)
    {
      if ((rdb1 = XrmGetStringDatabase (displayResource)))
        /* Merge with screen-independent resources */
        XrmMergeDatabases (rdb1, &database);

      XFree (displayResource);
    }

  // 3. User's per host defaults file
  /* Add in XENVIRONMENT file */
  if ((xe = getenv ("XENVIRONMENT"))
      && (rdb1 = XrmGetFileDatabase (xe)))
    XrmMergeDatabases (rdb1, &database);
  else if (homedir)
    {
      struct utsname un;

      if (!uname (&un))
        {
          snprintf (fname, sizeof (fname), "%s/.Xdefaults-%s", homedir, un.nodename);

          if ((rdb1 = XrmGetFileDatabase (fname)))
            XrmMergeDatabases (rdb1, &database);
        }
    }

  return database;
}

bool rxvt_display::ref_init ()
{
#ifdef LOCAL_X_IS_UNIX
  if (id[0] == ':')
    {
      char *val = rxvt_temp_buf<char> (5 + strlen (id) + 1);

      strcpy (val, "unix/");
      strcat (val, id);

      dpy = XOpenDisplay (val);
    }
  else
#endif
    dpy = 0;

  if (!dpy)
    dpy = XOpenDisplay (id);

  if (!dpy)
    return false;

  screen = DefaultScreen     (dpy);
  root   = DefaultRootWindow (dpy);

  assert (ecb_array_length (xa_names) == NUM_XA);
  XInternAtoms (dpy, (char **)xa_names, NUM_XA, False, xa);

  XrmSetDatabase (dpy, get_resources (false));

#ifdef POINTER_BLANK
  XColor blackcolour;
  blackcolour.red   = 0;
  blackcolour.green = 0;
  blackcolour.blue  = 0;
  Font f = XLoadFont (dpy, "fixed");
  blank_cursor = XCreateGlyphCursor (dpy, f, f, ' ', ' ',
                                     &blackcolour, &blackcolour);
  XUnloadFont (dpy, f);
#endif

  flags = 0;
#if XRENDER
  int major, minor;
  if (XRenderQueryVersion (dpy, &major, &minor))
    if (major > 0 || (major == 0 && minor >= 11))
      {
        flags |= DISPLAY_HAS_RENDER;

        if (XFilters *filters = XRenderQueryFilters (dpy, root))
          {
            for (int i = 0; i < filters->nfilter; i++)
              if (!strcmp (filters->filter [i], FilterConvolution))
                flags |= DISPLAY_HAS_RENDER_CONV;

            XFree (filters);
          }
      }
#endif

  int fd = XConnectionNumber (dpy);

  // try to detect whether we have a local connection.
  // assume unix domain socket == local, everything else not
  // TODO: might want to check for inet/127.0.0.1
  is_local = 0;
  sockaddr_un sa;
  socklen_t sl = sizeof (sa);

  if (!getsockname (fd, (sockaddr *)&sa, &sl))
    is_local = sa.sun_family == AF_UNIX;

  flush_ev.start ();
  x_ev.start (fd, ev::READ);
  fcntl (fd, F_SETFD, FD_CLOEXEC);

  XSelectInput (dpy, root, PropertyChangeMask);

  flush ();

  return true;
}

void
rxvt_display::ref_next ()
{
  // TODO: somehow check whether the database files/resources changed
  // before affording re-loading/parsing
  XrmDestroyDatabase (XrmGetDatabase (dpy));
#if XLIB_ILLEGAL_ACCESS
  /* work around a bug in XrmSetDatabase where it frees the db */
  dpy->db = 0;
#endif
  XrmSetDatabase (dpy, get_resources (true));
}

rxvt_display::~rxvt_display ()
{
  if (!dpy)
    return;

#ifdef POINTER_BLANK
  XFreeCursor (dpy, blank_cursor);
#endif
  x_ev.stop ();
  flush_ev.stop ();
#if USE_XIM
  xims.clear ();
#endif
  XrmDestroyDatabase (XrmGetDatabase (dpy));
  XCloseDisplay (dpy);
}

#if USE_XIM
void rxvt_display::im_change_cb ()
{
  for (im_watcher **i = imw.begin (); i != imw.end (); ++i)
    (*i)->call ();
}

void rxvt_display::im_change_check ()
{
  // try to only call im_change_cb when a new input method
  // registers, as xlib crashes due to a race otherwise.
  Atom actual_type, *atoms;
  int actual_format;
  unsigned long nitems, bytes_after;

  if (XGetWindowProperty (dpy, root, xa[XA_XIM_SERVERS], 0L, 1000000L,
                          False, XA_ATOM, &actual_type, &actual_format,
                          &nitems, &bytes_after, (unsigned char **)&atoms)
      != Success)
    return;

  if (actual_type == XA_ATOM && actual_format == 32)
    for (int i = 0; i < nitems; i++)
      if (XGetSelectionOwner (dpy, atoms[i]))
        {
          im_change_cb ();
          break;
        }

  XFree (atoms);
}
#endif

void rxvt_display::x_cb (ev::io &w, int revents)
{
  flush_ev.start ();
}

void rxvt_display::flush_cb (ev::prepare &w, int revents)
{
  while (XEventsQueued (dpy, QueuedAfterFlush))
    do
      {
        XEvent xev;
        XNextEvent (dpy, &xev);

#if USE_XIM
        if (!XFilterEvent (&xev, None))
          {
            if (xev.type == PropertyNotify
                && xev.xany.window == root
                && xev.xproperty.atom == xa[XA_XIM_SERVERS])
              im_change_check ();
#endif
            if (xev.type == MappingNotify)
              XRefreshKeyboardMapping (&xev.xmapping);

            for (int i = xw.size (); i--; )
              {
                if (!xw[i])
                  xw.erase_unordered (i);
                else if (xw[i]->window == xev.xany.window)
                  xw[i]->call (xev);
              }
#if USE_XIM
          }
#endif
      }
    while (XEventsQueued (dpy, QueuedAlready));

  w.stop ();
}

void rxvt_display::reg (xevent_watcher *w)
{
  if (!w->active)
    {
      xw.push_back (w);
      w->active = xw.size ();
    }
}

void rxvt_display::unreg (xevent_watcher *w)
{
  if (w->active)
    {
      xw[w->active - 1] = 0;
      w->active = 0;
    }
}

void rxvt_display::set_selection_owner (rxvt_term *owner, bool clipboard)
{
  rxvt_term * &cur_owner = !clipboard ? selection_owner : clipboard_owner;

  if (cur_owner && cur_owner != owner)
    {
      rxvt_term *term = cur_owner;
      term->selection_clear (clipboard);
      term->flush ();
    }

  cur_owner = owner;
}

#if USE_XIM

void rxvt_display::reg (im_watcher *w)
{
  imw.push_back (w);
}

void rxvt_display::unreg (im_watcher *w)
{
  imw.erase (find (imw.begin (), imw.end (), w));
}

rxvt_xim *rxvt_display::get_xim (const char *locale, const char *modifiers)
{
  char *id;
  int l, m;

  l = strlen (locale);
  m = strlen (modifiers);

  if (!(id = rxvt_temp_buf<char> (l + m + 2)))
    return 0;

  memcpy (id, locale, l); id[l] = '\n';
  memcpy (id + l + 1, modifiers, m); id[l + m + 1] = 0;

  rxvt_xim *xim = xims.get (id);

  return xim;
}

void rxvt_display::put_xim (rxvt_xim *xim)
{
# if XLIB_IS_RACEFREE
  xims.put (xim);
# endif
}

#endif

Atom rxvt_display::atom (const char *name)
{
  return XInternAtom (dpy, name, False);
}

Pixmap
rxvt_display::get_pixmap_property (Atom property)
{
  Pixmap pixmap = None;

  int aformat;
  unsigned long nitems, bytes_after;
  Atom atype;
  unsigned char *prop;
  int result = XGetWindowProperty (dpy, root, property,
                                   0L, 1L, False, XA_PIXMAP, &atype, &aformat,
                                   &nitems, &bytes_after, &prop);
  if (result == Success)
    {
      if (atype == XA_PIXMAP)
        pixmap = *(Pixmap *)prop;
      XFree (prop);
    }

  return pixmap;
}

/////////////////////////////////////////////////////////////////////////////

template class refcache<rxvt_display>;
refcache<rxvt_display> displays;

/////////////////////////////////////////////////////////////////////////////
//

static unsigned int
insert_component (unsigned int value, unsigned int mask, unsigned int shift)
{
  return (value * (mask + 1) >> 16) << shift;
}

bool
rxvt_color::alloc (rxvt_screen *screen, const rgba &color)
{
  //TODO: only supports 24 bit
  unsigned int alpha = color.a >= 0xff00 ? 0xffff : color.a;

#if XFT
  XRenderPictFormat *format;

  // not needed by XftColorAlloc, but by the other paths (ours
  // and fallback), so just set all components here.
  c.color.red   = color.r;
  c.color.green = color.g;
  c.color.blue  = color.b;
  c.color.alpha = alpha;

  // FUCKING Xft gets it wrong, of course, so work around it.
  // Transparency users should eat shit and die, and then
  // XRenderQueryPictIndexValues themselves plenty.
  if ((screen->visual->c_class == TrueColor)
      && (format = XRenderFindVisualFormat (screen->dpy, screen->visual)))
    {
      // the fun lies in doing everything manually...

      // Xft wants premultiplied alpha, but abuses the alpha channel
      // as blend factor, and doesn't allow us to set the alpha channel
      c.color.red   = c.color.red   * alpha / 0xffff;
      c.color.green = c.color.green * alpha / 0xffff;
      c.color.blue  = c.color.blue  * alpha / 0xffff;

      c.pixel = insert_component (c.color.red  , format->direct.redMask  , format->direct.red  )
              | insert_component (c.color.green, format->direct.greenMask, format->direct.green)
              | insert_component (c.color.blue , format->direct.blueMask , format->direct.blue )
              | insert_component (alpha        , format->direct.alphaMask, format->direct.alpha);

      return true;
    }
  else
    {
      XRenderColor d;

      d.red   = color.r;
      d.green = color.g;
      d.blue  = color.b;
      d.alpha = alpha;

      // XftColorAlloc always returns 100% transparent pixels(!)
      if (XftColorAllocValue (screen->dpy, screen->visual, screen->cmap, &d, &c))
        return true;
    }
#else
  c.red   = color.r;
  c.green = color.g;
  c.blue  = color.b;

  if (screen->visual->c_class == TrueColor)
    {
      c.pixel = (color.r >> (16 - ecb_popcount32 (screen->visual->red_mask  )) << ecb_ctz32 (screen->visual->red_mask  ))
              | (color.g >> (16 - ecb_popcount32 (screen->visual->green_mask)) << ecb_ctz32 (screen->visual->green_mask))
              | (color.b >> (16 - ecb_popcount32 (screen->visual->blue_mask )) << ecb_ctz32 (screen->visual->blue_mask ));

      return true;
    }
  else if (XAllocColor (screen->dpy, screen->cmap, &c))
    return true;
#endif

  c.pixel = (color.r * 2 + color.g * 3 + color.b) >= 0x8000 * 6
          ? WhitePixelOfScreen (DefaultScreenOfDisplay (screen->dpy))
          : BlackPixelOfScreen (DefaultScreenOfDisplay (screen->dpy));

  return false;
}

bool
rxvt_color::set (rxvt_screen *screen, const char *name)
{
  rgba c;
  char eos;
  int skip = 0;

  c.a = rgba::MAX_CC;

  // parse the nonstandard "[alphapercent]" prefix
  if (1 <= sscanf (name, "[%hd]%n", &c.a, &skip))
    {
      c.a = lerp<int, int, int> (0, rgba::MAX_CC, c.a);
      name += skip;
    }

  // parse the non-standard "rgba:rrrr/gggg/bbbb/aaaa" format
  if (strlen (name) != 4+5*4 || 4 != sscanf (name, "rgba:%4hx/%4hx/%4hx/%4hx%c", &c.r, &c.g, &c.b, &c.a, &eos))
    {
      XColor xc;

      if (XParseColor (screen->dpy, screen->cmap, name, &xc))
        {
          c.r = xc.red;
          c.g = xc.green;
          c.b = xc.blue;
        }
      else
        {
          c.r = 0xffff;
          c.g = 0x6969;
          c.b = 0xb4b4;

          rxvt_warn ("unable to parse color '%s', using pink instead.\n", name);
        }
    }

  return set (screen, c);
}

bool
rxvt_color::set (rxvt_screen *screen, const rgba &color)
{
  bool got = alloc (screen, color);

#if !ENABLE_MINIMAL
  int cmap_size = screen->visual->map_entries;

  if (!got
      && screen->visual->c_class == PseudoColor
      && cmap_size < 4096)
    {
      XColor *colors = new XColor [screen->visual->map_entries];

      for (int i = 0; i < cmap_size; i++)
        colors [i].pixel = i;

      // many kilobytes transfer per colour, but pseudocolor isn't worth
      // many extra optimisations.
      XQueryColors (screen->dpy, screen->cmap, colors, cmap_size);

      while (cmap_size)
        {
          int diff = 0x7fffffffL;
          XColor *best = colors;

          for (int i = 0; i < cmap_size; i++)
            {
              // simple weighted rgb distance sucks, but keeps it simple
              int d = abs (color.r - colors [i].red  ) * 2
                    + abs (color.g - colors [i].green) * 3
                    + abs (color.b - colors [i].blue );

              if (d < diff)
                {
                  diff = d;
                  best = colors + i;
                }
            }

          //rxvt_warn ("could not allocate %04x %04x %04x, getting %04x %04x %04x instead (%d,%d)\n",
          //    color.r, color.g, color.b, best->red, best->green, best->blue, diff, best - colors);

          got = alloc (screen, rgba (best->red, best->green, best->blue));

          if (got)
            break;

          *best = colors [--cmap_size];
        }

      delete [] colors;
    }
#endif

  return got;
}

void
rxvt_color::get (rgba &color) const
{
#if XFT

  color.r = c.color.red;
  color.g = c.color.green;
  color.b = c.color.blue;
  color.a = c.color.alpha;

  if (IN_RANGE_INC (color.a, 0x0001, 0xfffe))
    {
      color.r = color.r * 0xffff / color.a;
      color.g = color.g * 0xffff / color.a;
      color.b = color.b * 0xffff / color.a;
    }

#else

  color.r = c.red;
  color.g = c.green;
  color.b = c.blue;
  color.a = rgba::MAX_CC;

#endif
}

void
rxvt_color::get (XColor &color) const
{
  rgba c;
  get (c);

  color.red   = c.r;
  color.green = c.g;
  color.blue  = c.b;
  color.pixel = (Pixel)*this;
}

void
rxvt_color::free (rxvt_screen *screen)
{
  if (screen->visual->c_class == TrueColor)
    return; // nothing to do

#if XFT
  XftColorFree (screen->dpy, screen->visual, screen->cmap, &c);
#else
  XFreeColors (screen->dpy, screen->cmap, &c.pixel, 1, AllPlanes);
#endif
}

void
rxvt_color::fade (rxvt_screen *screen, int percent, rxvt_color &result, const rgba &to)
{
  rgba c;
  get (c);

  result.set (
    screen,
    rgba (
      lerp (c.r, to.r, percent),
      lerp (c.g, to.g, percent),
      lerp (c.b, to.b, percent),
      lerp (c.a, to.a, percent)
    )
  );
}

rxvt_selection::rxvt_selection (rxvt_display *disp, int selnum, Time tm, Window win, Atom prop, rxvt_term *term)
: display (disp), request_time (tm), request_win (win), request_prop (prop), term (term)
{
  assert (selnum >= Sel_Primary && selnum <= Sel_Clipboard);

  timer_ev.set<rxvt_selection, &rxvt_selection::timer_cb> (this);
  timer_ev.repeat = 10.;
  x_ev.set<rxvt_selection, &rxvt_selection::x_cb> (this);

  incr_buf = 0;
  incr_buf_size = incr_buf_fill = 0;
  selection_wait = Sel_normal;
  selection_type = selnum;
  cb_sv = 0;
}

void
rxvt_selection::stop ()
{
  free (incr_buf);
  incr_buf = 0;
  timer_ev.stop ();
  x_ev.stop (display);
}

rxvt_selection::~rxvt_selection ()
{
  stop ();
}

void
rxvt_selection::run ()
{
  int selnum = selection_type;

#if ENABLE_FRILLS
  if (selnum == Sel_Primary && display->selection_owner)
    {
      /* internal selection */
      char *str = rxvt_wcstombs (display->selection_owner->selection.text, display->selection_owner->selection.len);
      finish (str, strlen (str));
      free (str);
      return;
    }
#endif

#if X_HAVE_UTF8_STRING
  selection_type = Sel_UTF8String;
  if (request (display->xa[XA_UTF8_STRING], selnum))
    return;
#else
  selection_type = Sel_CompoundText;
  if (request (display->xa[XA_COMPOUND_TEXT], selnum))
    return;
#endif

  // fallback to CUT_BUFFER0 if the requested property has no owner
  handle_selection (display->root, XA_CUT_BUFFER0, false);
}

void
rxvt_selection::finish (char *data, unsigned int len)
{
  if (!cb_sv)
    {
      if (data)
        term->paste (data, len);

      term->selection_req = 0;
      delete this;
    }
#if ENABLE_PERL
  else
    {
      stop (); // we do not really trust perl callbacks
      rxvt_perl.selection_finish (this, data, len);
    }
#endif
}

bool
rxvt_selection::request (Atom target, int selnum)
{
  Atom sel;

  selection_type |= selnum;

  if (selnum == Sel_Primary)
    sel = XA_PRIMARY;
  else if (selnum == Sel_Secondary)
    sel = XA_SECONDARY;
  else
    sel = display->xa[XA_CLIPBOARD];

  if (XGetSelectionOwner (display->dpy, sel) != None)
    {
      XConvertSelection (display->dpy, sel, target, request_prop,
                         request_win, request_time);
      x_ev.start (display, request_win);
      timer_ev.again ();
      return true;
    }

  return false;
}

void
rxvt_selection::handle_selection (Window win, Atom prop, bool delete_prop)
{
  Display *dpy = display->dpy;
  char *data = 0;
  unsigned int data_len = 0;
  unsigned long bytes_after;
  XTextProperty ct;

  // check for failed XConvertSelection
  if (prop == None)
    {
      bool error = true;
      int selnum = selection_type & Sel_whereMask;

      if (selection_type & Sel_CompoundText)
        {
          selection_type = 0;
          error = !request (XA_STRING, selnum);
        }

      if (selection_type & Sel_UTF8String)
        {
          selection_type = Sel_CompoundText;
          error = !request (display->xa[XA_COMPOUND_TEXT], selnum);
        }

      if (error)
        {
          ct.value = 0;
          goto bailout;
        }

      return;
    }

  // length == (2^31 - 1) / 4, as gdk
  if (XGetWindowProperty (dpy, win, prop,
                          0, 0x1fffffff,
                          delete_prop, AnyPropertyType,
                          &ct.encoding, &ct.format,
                          &ct.nitems, &bytes_after,
                          &ct.value) != Success)
    {
      ct.value = 0;
      goto bailout;
    }

  if (ct.encoding == None)
    goto bailout;

  if (ct.value == 0)
    goto bailout;

  if (ct.encoding == display->xa[XA_INCR])
    {
      // INCR selection, start handshake
      if (!delete_prop)
        XDeleteProperty (dpy, win, prop);

      selection_wait = Sel_incr;
      timer_ev.again ();

      goto bailout;
    }

  if (ct.nitems == 0)
    {
      if (selection_wait == Sel_incr)
        {
          XFree (ct.value);

          // finally complete, now paste the whole thing
          selection_wait = Sel_normal;
          ct.value = (unsigned char *)incr_buf;
          ct.nitems = incr_buf_fill;
          incr_buf = 0;
          timer_ev.stop ();
        }
      else
        {
          // avoid recursion
          if (win != display->root || prop != XA_CUT_BUFFER0)
            {
              XFree (ct.value);

               // fallback to CUT_BUFFER0 if the requested property
               // has an owner but is empty
              handle_selection (display->root, XA_CUT_BUFFER0, False);
              return;
            }

          goto bailout;
        }
    }
  else if (selection_wait == Sel_incr)
    {
      timer_ev.again ();

      while (incr_buf_fill + ct.nitems > incr_buf_size)
        {
          incr_buf_size = incr_buf_size ? incr_buf_size * 2 : 128*1024;
          incr_buf = (char *)rxvt_realloc (incr_buf, incr_buf_size);
        }

      memcpy (incr_buf + incr_buf_fill, ct.value, ct.nitems);
      incr_buf_fill += ct.nitems;

      goto bailout;
    }

  char **cl;
  int cr;

  // we honour the first item only

#if !ENABLE_MINIMAL
  // xlib is horribly broken with respect to UTF8_STRING, and nobody cares to fix it
  // so recode it manually
  if (ct.encoding == display->xa[XA_UTF8_STRING])
    {
      wchar_t *w = rxvt_utf8towcs ((const char *)ct.value, ct.nitems);
      data = rxvt_wcstombs (w);
      free (w);
    }
  else
#endif
  if (XmbTextPropertyToTextList (dpy, &ct, &cl, &cr) >= 0
      && cl)
    {
      data = strdup (cl[0]);
      XFreeStringList (cl);
    }
  else
    {
      // paste raw
      data = strdup ((const char *)ct.value);
    }

  data_len = strlen (data);

bailout:
  XFree (ct.value);

  if (selection_wait == Sel_normal)
    {
      finish (data, data_len);
      free (data);
    }
}

void
rxvt_selection::timer_cb (ev::timer &w, int revents)
{
  if (selection_wait == Sel_incr)
    rxvt_warn ("data loss: timeout on INCR selection paste, ignoring.\n");

  finish ();
}

void
rxvt_selection::x_cb (XEvent &xev)
{
  switch (xev.type)
    {
      case PropertyNotify:
        if (selection_wait == Sel_incr
            && xev.xproperty.atom == request_prop
            && xev.xproperty.state == PropertyNewValue)
          handle_selection (xev.xproperty.window, xev.xproperty.atom, true);
        break;

      case SelectionNotify:
        if (selection_wait == Sel_normal
            && xev.xselection.time == request_time)
          {
            timer_ev.stop ();
            handle_selection (xev.xselection.requestor, xev.xselection.property, true);
          }
        break;
    }
}