aboutsummaryrefslogtreecommitdiff
path: root/nx-X11/programs/Xserver/hw/nxagent/NXdispatch.c
blob: 6573ac0b95575cc50a15afbff48235753f99bdcc (plain)
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
/**************************************************************************/
/*                                                                        */
/* Copyright (c) 2001, 2011 NoMachine (http://www.nomachine.com)          */
/* Copyright (c) 2008-2014 Oleksandr Shneyder <o.shneyder@phoca-gmbh.de>  */
/* Copyright (c) 2011-2016 Mike Gabriel <mike.gabriel@das-netzwerkteam.de>*/
/* Copyright (c) 2014-2016 Mihai Moldovan <ionic@ionic.de>                */
/* Copyright (c) 2014-2016 Ulrich Sibiller <uli42@gmx.de>                 */
/* Copyright (c) 2015-2016 Qindel Group (http://www.qindel.com)           */
/*                                                                        */
/* NXAGENT, NX protocol compression and NX extensions to this software    */
/* are copyright of the aforementioned persons and companies.             */
/*                                                                        */
/* Redistribution and use of the present software is allowed according    */
/* to terms specified in the file LICENSE which comes in the source       */
/* distribution.                                                          */
/*                                                                        */
/* All rights reserved.                                                   */
/*                                                                        */
/* NOTE: This software has received contributions from various other      */
/* contributors, only the core maintainers and supporters are listed as   */
/* copyright holders. Please contact us, if you feel you should be listed */
/* as copyright holder, as well.                                          */
/*                                                                        */
/**************************************************************************/

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

Copyright 1987, 1989, 1998  The Open Group

Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of The Open Group shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from The Open Group.


Copyright 1987, 1989 by Digital Equipment Corporation, Maynard, Massachusetts.

                        All Rights Reserved

Permission to use, copy, modify, and distribute this software and its 
documentation for any purpose and without fee is hereby granted, 
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in 
supporting documentation, and that the name of Digital not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.  

DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.

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

/* The panoramix components contained the following notice */
/*****************************************************************

Copyright (c) 1991, 1997 Digital Equipment Corporation, Maynard, Massachusetts.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software.

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
DIGITAL EQUIPMENT CORPORATION BE LIABLE FOR ANY CLAIM, DAMAGES, INCLUDING,
BUT NOT LIMITED TO CONSEQUENTIAL OR INCIDENTAL DAMAGES, OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of Digital Equipment Corporation
shall not be used in advertising or otherwise to promote the sale, use or other
dealings in this Software without prior written authorization from Digital
Equipment Corporation.

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


#ifdef __sun
#define False 0
#define True 1
#endif

#include <X11/fonts/fontstruct.h>

#define GC XlibGC
#include <nx-X11/Xlib.h>
#undef GC

#include "../../dix/dispatch.c"

#include "windowstr.h"

#include "Atoms.h"
#include "Splash.h"
#include "Xdmcp.h"
#include "Client.h"
#include "Clipboard.h"
#include "Reconnect.h"
#include "Millis.h"
#include "Font.h"
#include <nx/Shadow.h>
#include "Handlers.h"
#include "Keyboard.h"
#include "Init.h"
#include "Utils.h"

const int nxagentMaxFontNames = 10000;

/*
 * This allows the agent to exit if no
 * client is connected within a timeout.
 */

int nxagentClients = 0;

void nxagentWaitDisplay(void);

void nxagentListRemoteFonts(const char *, int);

#include "Xatom.h"

/*
 * Set here the required log level.
 */

#define PANIC
#define WARNING
#undef  TEST
#undef  WATCH

/*
 * Log begin and end of the important handlers.
 */

#undef  BLOCKS

#ifdef WATCH
#include "unistd.h"
#endif

#include "Literals.h"

#ifdef VIEWPORT_FRAME

extern WindowPtr nxagentViewportFrameLeft;
extern WindowPtr nxagentViewportFrameRight;
extern WindowPtr nxagentViewportFrameAbove;
extern WindowPtr nxagentViewportFrameBelow;

#define IsViewportFrame(pWin) ((pWin) == nxagentViewportFrameLeft || \
                                   (pWin) == nxagentViewportFrameRight || \
                                       (pWin) == nxagentViewportFrameAbove || \
                                           (pWin) == nxagentViewportFrameBelow)

#else

#define IsViewportFrame(pWin) (0)

#endif /* #ifdef VIEWPORT_FRAME */

extern int nxagentMaxAllowedResets;

extern int nxagentFindClientResource(int, RESTYPE, void *);

#ifdef NXAGENT_CLIPBOARD
extern int nxagentPrimarySelection;
extern int nxagentClipboardSelection;
extern int nxagentMaxSelections;
#endif

extern int nxOpenFont(ClientPtr, XID, Mask, unsigned, char*);


/*
 * This used to be a dix variable used only by XPRINT, so xorg dropped it.
 */
ClientPtr nxagentRequestingClient;

void
InitSelections(void)
{
    xorg_InitSelections();

#ifdef NXAGENT_CLIPBOARD
    {
      Selection *newsels;
      newsels = (Selection *)malloc(nxagentMaxSelections * sizeof(Selection));
      if (!newsels)
        return;
      NumCurrentSelections += nxagentMaxSelections;
      CurrentSelections = newsels;

      CurrentSelections[nxagentPrimarySelection].selection = XA_PRIMARY;
      CurrentSelections[nxagentPrimarySelection].lastTimeChanged = ClientTimeToServerTime(0);
      CurrentSelections[nxagentPrimarySelection].window = screenInfo.screens[0]->root->drawable.id;
      CurrentSelections[nxagentPrimarySelection].pWin = NULL;
      CurrentSelections[nxagentPrimarySelection].client = NullClient;

      CurrentSelections[nxagentClipboardSelection].selection = MakeAtom("CLIPBOARD", 9, 1);
      CurrentSelections[nxagentClipboardSelection].lastTimeChanged = ClientTimeToServerTime(0);
      CurrentSelections[nxagentClipboardSelection].window = screenInfo.screens[0]->root->drawable.id;
      CurrentSelections[nxagentClipboardSelection].pWin = NULL;
      CurrentSelections[nxagentClipboardSelection].client = NullClient;
    }
#endif
}

#define MAJOROP ((xReq *)client->requestBuffer)->reqType

void
Dispatch(void)
{
    register int        *clientReady;     /* array of request ready clients */
    register int	result;
    register ClientPtr	client;
    register int	nready;
    register HWEventQueuePtr* icheck = checkForInput;
    long			start_tick;

    nextFreeClientID = 1;
    InitSelections();
    nClients = 0;

#ifdef NXAGENT_SERVER
    /*
     * The agent initialization was successfully
     * completed. We can now handle our clients.
     */

    #ifdef XKB

    nxagentInitXkbWrapper();

    nxagentTuneXkbWrapper();

    #endif

    #ifdef NXAGENT_ONSTART

    /*
     * Set NX_WM property (used by NX client to identify the agent's
     * window) three seconds since the first client connects.
     */

    unsigned int nxagentWMtimeout = GetTimeInMillis() + 3000;

    #endif

#endif /* NXAGENT_SERVER */
    clientReady = (int *) malloc(sizeof(int) * MaxClients);
    if (!clientReady)
	return;

#ifdef NXAGENT_SERVER
    #ifdef WATCH

    fprintf(stderr, "Dispatch: Watchpoint 12.\n");

/*
Reply   Total	Cached	Bits In			Bits Out		Bits/Reply	  Ratio
------- -----	------	-------			--------		----------	  -----
#3      1		352 bits (0 KB) ->	236 bits (0 KB) ->	352/1 -> 236/1	= 1.492:1
#14     1		256 bits (0 KB) ->	101 bits (0 KB) ->	256/1 -> 101/1	= 2.535:1
#16     1		256 bits (0 KB) ->	26 bits (0 KB) ->	256/1 -> 26/1	= 9.846:1
#20     2	2	12256 bits (1 KB) ->	56 bits (0 KB) ->	6128/1 -> 28/1	= 218.857:1
#43     1		256 bits (0 KB) ->	45 bits (0 KB) ->	256/1 -> 45/1	= 5.689:1
#47     2	2	42304 bits (5 KB) ->	49 bits (0 KB) ->	21152/1 -> 24/1	= 863.347:1
#98     1		256 bits (0 KB) ->	34 bits (0 KB) ->	256/1 -> 34/1	= 7.529:1
*/

    sleep(30);

    #endif

    #ifdef TEST
    fprintf(stderr, "Dispatch: Value of dispatchException is [%x].\n",
                dispatchException);

    fprintf(stderr, "Dispatch: Value of dispatchExceptionAtReset is [%x].\n",
                dispatchExceptionAtReset);
    #endif

    if (!(dispatchException & DE_TERMINATE))
        dispatchException = 0;

    /* Init TimeoutTimer if requested */
    nxagentSetTimeoutTimer(0);
#endif /* NXAGENT_SERVER */

    while (!dispatchException)
    {
        if (*icheck[0] != *icheck[1])
	{
	    ProcessInputEvents();
	    FlushIfCriticalOutputPending();
	}

#ifdef NXAGENT_SERVER
        /*
         * Ensure we remove the splash after the timeout.
         * Initializing clientReady[0] to -1 will tell
         * WaitForSomething() to yield control after the
         * timeout set in clientReady[1].
         */

        clientReady[0] = 0;

        if (nxagentHaveSplashWindow() || (nxagentOption(Xdmcp) && nxagentXdmcpUp == 0))
        {
          #ifdef TEST
          fprintf(stderr, "******Dispatch: Requesting a timeout of [%d] Ms.\n",
                      NXAGENT_WAKEUP);
          #endif

          clientReady[0] = -1;
          clientReady[1] = NXAGENT_WAKEUP;
        }

        if (serverGeneration > nxagentMaxAllowedResets &&
                nxagentSessionState == SESSION_STARTING &&
                    (!nxagentOption(Xdmcp) || nxagentXdmcpUp == 1))
        {
          #ifdef NX_DEBUG_INPUT
          fprintf(stderr, "Session: Session started at '%s' timestamp [%u].\n",
                      GetTimeAsString(), GetTimeInMillis());
          #else
          fprintf(stderr, "Session: Session started at '%s'.\n",
                      GetTimeAsString());
          #endif

          nxagentSessionState = SESSION_UP;
          saveAgentState("RUNNING");
        }

        #ifdef BLOCKS
        fprintf(stderr, "[End dispatch]\n");
        #endif
#endif /* NXAGENT_SERVER */

	nready = WaitForSomething(clientReady);

#ifdef NXAGENT_SERVER
        #ifdef BLOCKS
        fprintf(stderr, "[Begin dispatch]\n");
        #endif

        #ifdef TEST
        fprintf(stderr, "******Dispatch: Running with [%d] clients ready.\n",
                    nready);
        #endif
        
        #ifdef NXAGENT_ONSTART

	/*
	 * If the timeout is expired set the selection informing the
	 * NX client that the agent is ready.
	 */

	if (nxagentWMtimeout < GetTimeInMillis())
	{
	  nxagentRemoveSplashWindow();
	}

        nxagentClients = nClients;

        #endif
#endif /* NXAGENT_SERVER */

	if (nready)
	{
	    clientReady[0] = SmartScheduleClient (clientReady, nready);
	    nready = 1;
	}
       /***************** 
	*  Handle events in round robin fashion, doing input between 
	*  each round 
	*****************/

	while (!dispatchException && (--nready >= 0))
	{
	    client = clients[clientReady[nready]];
	    if (! client)
	    {
		/* KillClient can cause this to happen */
		continue;
	    }
	    /* GrabServer activation can cause this to be true */
	    if (grabState == GrabKickout)
	    {
		grabState = GrabActive;
		break;
	    }
	    isItTimeToYield = FALSE;
 
#ifdef NXAGENT_SERVER
	    nxagentRequestingClient = client;
#endif
	    start_tick = SmartScheduleTime;
	    while (!isItTimeToYield)
	    {
	        if (*icheck[0] != *icheck[1])
		{
		    ProcessInputEvents();
		    FlushIfCriticalOutputPending();
		}
		if ((SmartScheduleTime - start_tick) >= SmartScheduleSlice)
		{
		    /* Penalize clients which consume ticks */
		    if (client->smart_priority > SMART_MIN_PRIORITY)
			client->smart_priority--;
		    break;
		}
		/* now, finally, deal with client requests */

		/* Update currentTime so request time checks, such as for input
		 * device grabs, are calculated correctly */
		UpdateCurrentTimeIf();
#ifdef NXAGENT_SERVER
                #ifdef TEST
                fprintf(stderr, "******Dispatch: Reading request from client [%d].\n",
                            client->index);
                #endif
#endif /* NXAGENT_SERVER */

	        result = ReadRequestFromClient(client);
	        if (result <= 0) 
	        {
		    if (result < 0)
			CloseDownClient(client);
		    break;
	        }

#ifdef NXAGENT_SERVER
                #ifdef TEST

                else
                {

                    if (MAJOROP > 127)
                    {
                      fprintf(stderr, "******Dispatch: Read [Extension] request OPCODE#%d MINOR#%d "
                                  "size [%d] client [%d].\n", MAJOROP, *((char *) client->requestBuffer + 1),
                                      client->req_len << 2, client->index);
                    }
                    else
                    {
                      fprintf(stderr, "******Dispatch: Read [%s] request OPCODE#%d size [%d] client [%d].\n",
                                  nxagentRequestLiteral[MAJOROP], MAJOROP, client->req_len << 2,
                                      client->index);
                    }
                }

                #endif
#endif

		client->sequence++;
		if (result > (maxBigRequestSize << 2))
		    result = BadLength;
		else
                {
                    result = (* client->requestVector[MAJOROP])(client);
#ifdef NXAGENT_SERVER
                    #ifdef TEST

                    if (MAJOROP > 127)
                    {
                      fprintf(stderr, "******Dispatch: Handled [Extension] request OPCODE#%d MINOR#%d "
                                  "size [%d] client [%d] result [%d].\n", MAJOROP,
                                      *((char *) client->requestBuffer + 1), client->req_len << 2,
                                          client->index, result);
                    }
                    else
                    {
                      fprintf(stderr, "******Dispatch: Handled [%s] request OPCODE#%d size [%d] client [%d] "
                                  "result [%d].\n", nxagentRequestLiteral[MAJOROP], MAJOROP,
                                      client->req_len << 2, client->index, result);
                    }

                    #endif

                    /*
                     * Can set isItTimeToYield to force
                     * the dispatcher to pay attention
                     * to another client.
                     */

                    nxagentDispatchHandler(client, client->req_len << 2, 0);
#endif
                }

                if (!SmartScheduleSignalEnable)
                    SmartScheduleTime = GetTimeInMillis();

		if (result != Success) 
		{
		    if (client->noClientException != Success)
                        CloseDownClient(client);
                    else
		        SendErrorToClient(client, MAJOROP,
					  MinorOpcodeOfRequest(client),
					  client->errorValue, result);
		    break;
	        }
#ifdef DAMAGEEXT
		FlushIfCriticalOutputPending ();
#endif
	    }
	    FlushAllOutput();
	    client = clients[clientReady[nready]];
	    if (client)
		client->smart_stop_tick = SmartScheduleTime;
#ifdef NXAGENT_SERVER
	    nxagentRequestingClient = NULL;
#endif
	}
	dispatchException &= ~DE_PRIORITYCHANGE;
    }
#if defined(DDXBEFORERESET)
    ddxBeforeReset ();
#endif

#ifdef NXAGENT_SERVER
    nxagentFreeTimeoutTimer();

    /* FIXME: maybe move the code up to the KillAllClients() call to ddxBeforeReset? */
    if ((dispatchException & DE_RESET) && 
            (serverGeneration > nxagentMaxAllowedResets))
    {
        dispatchException &= ~DE_RESET;
        dispatchException |= DE_TERMINATE;

        fprintf(stderr, "Info: Reached threshold of maximum allowed resets.\n");
    }

    nxagentResetAtomMap();

    if (serverGeneration > nxagentMaxAllowedResets)
    {
      /*
       * The session is terminating. Force an I/O
       * error on the display and wait until the
       * NX transport is gone.
       */
  
      fprintf(stderr, "Session: Terminating session at '%s'.\n", GetTimeAsString());
      saveAgentState("TERMINATING");

      nxagentWaitDisplay();

      fprintf(stderr, "Session: Session terminated at '%s'.\n", GetTimeAsString());
    }

    if (nxagentOption(Shadow))
    {
      NXShadowDestroy();
    }
    saveAgentState("TERMINATED");

    nxagentFreeAtomMap();
    nxagentFreeFontData();
#endif /* NXAGENT_SERVER */

    nxagentFreeAtomMap();

    KillAllClients();
    free(clientReady);
    dispatchException &= ~DE_RESET;
}

#undef MAJOROP

int
ProcReparentWindow(register ClientPtr client)
{
    register WindowPtr pWin, pParent;
    REQUEST(xReparentWindowReq);
    register int result;

    REQUEST_SIZE_MATCH(xReparentWindowReq);
    pWin = (WindowPtr)SecurityLookupWindow(stuff->window, client,
					   DixWriteAccess);
    if (!pWin)
        return(BadWindow);

#ifdef NXAGENT_SERVER
    nxagentRemoveSplashWindow();
#endif

    pParent = (WindowPtr)SecurityLookupWindow(stuff->parent, client,
					      DixWriteAccess);
    if (!pParent)
        return(BadWindow);
    if (SAME_SCREENS(pWin->drawable, pParent->drawable))
    {
        if ((pWin->backgroundState == ParentRelative) &&
            (pParent->drawable.depth != pWin->drawable.depth))
            return BadMatch;
	if ((pWin->drawable.class != InputOnly) &&
	    (pParent->drawable.class == InputOnly))
	    return BadMatch;
        result =  ReparentWindow(pWin, pParent, 
			 (short)stuff->x, (short)stuff->y, client);
	if (client->noClientException != Success)
            return(client->noClientException);
	else
            return(result);
    }
    else 
        return (BadMatch);
}


int
ProcQueryTree(register ClientPtr client)
{
    xQueryTreeReply reply = {0};
    int numChildren = 0;
    register WindowPtr pChild, pWin, pHead;
    Window  *childIDs = (Window *)NULL;
    REQUEST(xResourceReq);

    REQUEST_SIZE_MATCH(xResourceReq);
    pWin = (WindowPtr)SecurityLookupWindow(stuff->id, client,
					   DixReadAccess);
    if (!pWin)
        return(BadWindow);
    reply.type = X_Reply;
    reply.root = pWin->drawable.pScreen->root->drawable.id;
    reply.sequenceNumber = client->sequence;
    if (pWin->parent)
	reply.parent = pWin->parent->drawable.id;
    else
        reply.parent = (Window)None;
    pHead = RealChildHead(pWin);
    for (pChild = pWin->lastChild; pChild != pHead; pChild = pChild->prevSib)
#ifdef NXAGENT_SERVER
    {
        if (!IsViewportFrame(pChild))
        {
            numChildren++;
        }

    }
#else
        numChildren++;
#endif
    if (numChildren)
    {
	int curChild = 0;

	childIDs = (Window *) malloc(numChildren * sizeof(Window));
	if (!childIDs)
	    return BadAlloc;
	for (pChild = pWin->lastChild; pChild != pHead; pChild = pChild->prevSib)
#ifdef NXAGENT_SERVER
	{
            if (!IsViewportFrame(pChild))
            {
	        childIDs[curChild++] = pChild->drawable.id;
            }
        }
#else
            childIDs[curChild++] = pChild->drawable.id;
#endif
    }
    
    reply.nChildren = numChildren;
    reply.length = (numChildren * sizeof(Window)) >> 2;
    
    WriteReplyToClient(client, sizeof(xQueryTreeReply), &reply);
    if (numChildren)
    {
    	client->pSwapReplyFunc = (ReplySwapPtr) Swap32Write;
	WriteSwappedDataToClient(client, numChildren * sizeof(Window), childIDs);
	free(childIDs);
    }

    return(client->noClientException);
}


int
ProcConvertSelection(register ClientPtr client)
{
    Bool paramsOkay;
    xEvent event;
    WindowPtr pWin;
    REQUEST(xConvertSelectionReq);

    REQUEST_SIZE_MATCH(xConvertSelectionReq);
    pWin = (WindowPtr)SecurityLookupWindow(stuff->requestor, client,
					   DixReadAccess);
    if (!pWin)
        return(BadWindow);

#ifdef NXAGENT_CLIPBOARD
    if (((stuff->selection == XA_PRIMARY) ||
           (stuff->selection == MakeAtom("CLIPBOARD", 9, 0))) &&
               nxagentOption(Clipboard) != ClipboardNone)
    {
      int i = nxagentFindCurrentSelectionIndex(stuff->selection);
      if ((i < NumCurrentSelections) && (CurrentSelections[i].window != None))
      {
        if (nxagentConvertSelection(client, pWin, stuff->selection, stuff->requestor,
                                       stuff->property, stuff->target, stuff->time))
        {
          return (client->noClientException);
        }
      }
    }
#endif

    paramsOkay = (ValidAtom(stuff->selection) && ValidAtom(stuff->target));
    if (stuff->property != None)
	paramsOkay &= ValidAtom(stuff->property);
    if (paramsOkay)
    {
	int i;

	i = 0;
	while ((i < NumCurrentSelections) && 
	       CurrentSelections[i].selection != stuff->selection) i++;
	if ((i < NumCurrentSelections) &&
#ifdef NXAGENT_SERVER
	    (CurrentSelections[i].window != None) && (CurrentSelections[i].client != NullClient)
#else
	    (CurrentSelections[i].window != None)
#endif
#ifdef XCSECURITY
	    && (!client->CheckAccess ||
		(* client->CheckAccess)(client, CurrentSelections[i].window,
					RT_WINDOW, DixReadAccess,
					CurrentSelections[i].pWin))
#endif
	    )
	{        
	    memset(&event, 0, sizeof(xEvent));
	    event.u.u.type = SelectionRequest;
	    event.u.selectionRequest.time = stuff->time;
	    event.u.selectionRequest.owner = 
			CurrentSelections[i].window;
	    event.u.selectionRequest.requestor = stuff->requestor;
	    event.u.selectionRequest.selection = stuff->selection;
	    event.u.selectionRequest.target = stuff->target;
	    event.u.selectionRequest.property = stuff->property;
	    if (TryClientEvents(
		CurrentSelections[i].client, &event, 1, NoEventMask,
		NoEventMask /* CantBeFiltered */, NullGrab))
		return (client->noClientException);
	}
	memset(&event, 0, sizeof(xEvent));
	event.u.u.type = SelectionNotify;
	event.u.selectionNotify.time = stuff->time;
	event.u.selectionNotify.requestor = stuff->requestor;
	event.u.selectionNotify.selection = stuff->selection;
	event.u.selectionNotify.target = stuff->target;
	event.u.selectionNotify.property = None;
	(void) TryClientEvents(client, &event, 1, NoEventMask,
			       NoEventMask /* CantBeFiltered */, NullGrab);
	return (client->noClientException);
    }
    else 
    {
	client->errorValue = stuff->property;
        return (BadAtom);
    }
}


int
ProcOpenFont(register ClientPtr client)
{
    int	err;
    REQUEST(xOpenFontReq);

    REQUEST_FIXED_SIZE(xOpenFontReq, stuff->nbytes);
    client->errorValue = stuff->fid;
    LEGAL_NEW_RESOURCE(stuff->fid, client);

#ifdef NXAGENT_SERVER
    char fontReq[256];
    memcpy(fontReq,(char *)&stuff[1], (stuff->nbytes < 256) ? stuff->nbytes : 255);
    fontReq[stuff->nbytes] = '\0';
    if (strchr(fontReq, '*') || strchr(fontReq, '?'))
    {
#ifdef NXAGENT_FONTMATCH_DEBUG
       fprintf(stderr, "%s: try to find a common font with font pattern [%s]\n", __func__, fontReq);
#endif
       nxagentListRemoteFonts(fontReq, nxagentMaxFontNames);
       err = nxOpenFont(client, stuff->fid, (Mask) 0,
		stuff->nbytes, (char *)&stuff[1]);
    }
    else
#endif
    err = OpenFont(client, stuff->fid, (Mask) 0,
		stuff->nbytes, (char *)&stuff[1]);
    if (err == Success)
    {
	return(client->noClientException);
    }
    else
	return err;
}

int
ProcCloseFont(register ClientPtr client)
{
    FontPtr pFont;
    REQUEST(xResourceReq);

    REQUEST_SIZE_MATCH(xResourceReq);
    pFont = (FontPtr)SecurityLookupIDByType(client, stuff->id, RT_FONT,
					    DixDestroyAccess);
    if ( pFont != (FontPtr)NULL)	/* id was valid */
    {
        #ifdef NXAGENT_SERVER

        /*
         * When a client closes a font the resource should not be lost
         * if the reference counter is not 0, otherwise the server
         * will not be able to find this font looping through the
         * resources.
         */

        if (pFont -> refcnt > 0)
        {
          if (nxagentFindClientResource(serverClient -> index, RT_NX_FONT, pFont) == 0)
          {
            #ifdef TEST
            fprintf(stderr, "%s: Switching resource for font at [%p].\n", __func__,
                        (void *) pFont);
            #endif

            nxagentFontPriv(pFont) -> mirrorID = FakeClientID(serverClient -> index);

            AddResource(nxagentFontPriv(pFont) -> mirrorID, RT_NX_FONT, pFont);

          }
          #ifdef TEST
          else
          {
            fprintf(stderr, "%s: Found duplicated font at [%p], "
                        "resource switching skipped.\n", __func__, (void *) pFont);
          }
          #endif
        }

        #endif

        FreeResource(stuff->id, RT_NONE);
	return(client->noClientException);
    }
    else
    {
	client->errorValue = stuff->id;
        return (BadFont);
    }
}


int
ProcListFonts(register ClientPtr client)
{
    REQUEST(xListFontsReq);

    REQUEST_FIXED_SIZE(xListFontsReq, stuff->nbytes);

#ifdef NXAGENT_SERVER
    char tmp[256];
    memcpy(tmp, (unsigned char *) &stuff[1], (stuff->nbytes < 256) ? stuff->nbytes : 255);
    tmp[stuff->nbytes] = '\0';

#ifdef NXAGENT_FONTMATCH_DEBUG
    fprintf(stderr, "%s: ListFont request with pattern [%s] max_names [%d]\n", __func__, tmp, stuff->maxNames);
#endif
    nxagentListRemoteFonts(tmp, stuff -> maxNames < nxagentMaxFontNames ? nxagentMaxFontNames : stuff->maxNames);
#endif

    return ListFonts(client, (unsigned char *) &stuff[1], stuff->nbytes, 
	stuff->maxNames);
}

int
ProcListFontsWithInfo(register ClientPtr client)
{
    REQUEST(xListFontsWithInfoReq);

    REQUEST_FIXED_SIZE(xListFontsWithInfoReq, stuff->nbytes);

#ifdef NXAGENT_SERVER
    char tmp[256];
    memcpy(tmp, (unsigned char *) &stuff[1], (stuff->nbytes < 256) ? stuff->nbytes : 255);
    tmp[stuff->nbytes] = '\0';
#ifdef NXAGENT_FONTMATCH_DEBUG
    fprintf(stderr, "%s: ListFont with info request with pattern [%s] max_names [%d]\n", __func__, tmp, stuff->maxNames);
#endif
    nxagentListRemoteFonts(tmp, stuff -> maxNames < nxagentMaxFontNames ? nxagentMaxFontNames : stuff->maxNames);
#endif

    return StartListFontsWithInfo(client, stuff->nbytes,
				  (unsigned char *) &stuff[1], stuff->maxNames);
}

int
ProcFreePixmap(register ClientPtr client)
{
    PixmapPtr pMap;

    REQUEST(xResourceReq);

    REQUEST_SIZE_MATCH(xResourceReq);
    pMap = (PixmapPtr)SecurityLookupIDByType(client, stuff->id, RT_PIXMAP,
					     DixDestroyAccess);
    if (pMap) 
    {
        #ifdef NXAGENT_SERVER

        /*
         * When a client releases a pixmap the resource should not be
         * lost if the reference counter is not 0, otherwise the
         * server will not be able to find this pixmap looping through
         * the resources.
         */

        if (pMap -> refcnt > 0)
        {
          if (nxagentFindClientResource(serverClient -> index, RT_NX_PIXMAP, pMap) == 0)
          {
            #ifdef TEST
            fprintf(stderr, "ProcFreePixmap: Switching resource for pixmap at [%p].\n",
                       (void *) pMap);
            #endif

            nxagentPixmapPriv(pMap) -> mid = FakeClientID(serverClient -> index);

            AddResource(nxagentPixmapPriv(pMap) -> mid, RT_NX_PIXMAP, pMap);
          }
          #ifdef TEST
          else
          {
            fprintf(stderr, "%s: Found duplicated pixmap at [%p], "
                        "resource switching skipped.\n", __func__, (void *) pMap);
          }
          #endif
        }

        #endif

	FreeResource(stuff->id, RT_NONE);
	return(client->noClientException);
    }
    else 
    {
	client->errorValue = stuff->id;
	return (BadPixmap);
    }
}

/**********************
 * CloseDownClient
 *
 *  Client can either mark his resources destroy or retain.  If retained and
 *  then killed again, the client is really destroyed.
 *********************/

void
CloseDownClient(register ClientPtr client)
{
    #ifdef DEBUG
    fprintf(stderr, "%s: [%d]\n", __func__, client->clientState);
    #endif

#ifdef NXAGENT_SERVER
    /*
     * Need to reset the karma counter and get rid of the pending sync
     * replies.
     */

    nxagentWakeupByReset(client);
#endif

    xorg_CloseDownClient(client);
}