1/**************************************************************
2 *
3 * Xquartz initialization code
4 *
5 * Copyright (c) 2007-2008 Apple Inc.
6 * Copyright (c) 2001-2004 Torrey T. Lyons. All Rights Reserved.
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
22 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
23 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 * DEALINGS IN THE SOFTWARE.
25 *
26 * Except as contained in this notice, the name(s) of the above copyright
27 * holders shall not be used in advertising or otherwise to promote the sale,
28 * use or other dealings in this Software without prior written authorization.
29 */
30
31#ifdef HAVE_DIX_CONFIG_H
32#include <dix-config.h>
33#endif
34
35#include <X11/X.h>
36#include <X11/Xproto.h>
37#include "os.h"
38#include "servermd.h"
39#include "inputstr.h"
40#include "scrnintstr.h"
41#include "mibstore.h"		// mi backing store implementation
42#include "mipointer.h"		// mi software cursor
43#include "micmap.h"		// mi colormap code
44#include "fb.h"			// fb framebuffer code
45#include "site.h"
46#include "globals.h"
47#include "dix.h"
48#include "xkbsrv.h"
49
50#include <X11/extensions/XI.h>
51#include <X11/extensions/XIproto.h>
52#include "exevents.h"
53#include "extinit.h"
54
55#include "xserver-properties.h"
56
57#include <sys/types.h>
58#include <sys/time.h>
59#include <sys/syslimits.h>
60#include <stdio.h>
61#include <fcntl.h>
62#include <unistd.h>
63
64#define HAS_UTSNAME 1
65#include <sys/utsname.h>
66
67#define NO_CFPLUGIN
68#include <IOKit/hidsystem/IOHIDLib.h>
69
70#ifdef MITSHM
71#include "shmint.h"
72#endif
73
74#include "darwin.h"
75#include "darwinEvents.h"
76#include "quartzKeyboard.h"
77#include "quartz.h"
78
79#ifdef ENABLE_DEBUG_LOG
80FILE *debug_log_fp = NULL;
81#endif
82
83/*
84 * X server shared global variables
85 */
86int                     darwinScreensFound = 0;
87DevPrivateKeyRec        darwinScreenKeyRec;
88io_connect_t            darwinParamConnect = 0;
89int                     darwinEventReadFD = -1;
90int                     darwinEventWriteFD = -1;
91// int                     darwinMouseAccelChange = 1;
92int                     darwinFakeButtons = 0;
93
94// location of X11's (0,0) point in global screen coordinates
95int                     darwinMainScreenX = 0;
96int                     darwinMainScreenY = 0;
97
98// parameters read from the command line or user preferences
99int                     darwinDesiredDepth = -1;
100int                     darwinSyncKeymap = FALSE;
101
102// modifier masks for faking mouse buttons - ANY of these bits trigger it  (not all)
103#ifdef NX_DEVICELCMDKEYMASK
104int                     darwinFakeMouse2Mask = NX_DEVICELALTKEYMASK | NX_DEVICERALTKEYMASK;
105int                     darwinFakeMouse3Mask = NX_DEVICELCMDKEYMASK | NX_DEVICERCMDKEYMASK;
106#else
107int                     darwinFakeMouse2Mask = NX_ALTERNATEMASK;
108int                     darwinFakeMouse3Mask = NX_COMMANDMASK;
109#endif
110
111// Modifier mask for overriding event delivery to appkit (might be useful to set this to rcommand for input menu
112unsigned int            darwinAppKitModMask = 0; // Any of these bits
113
114// Modifier mask for items in the Window menu (0 and -1 cause shortcuts to be disabled)
115unsigned int            windowItemModMask = NX_COMMANDMASK;
116
117// devices
118DeviceIntPtr            darwinKeyboard = NULL;
119DeviceIntPtr            darwinPointer = NULL;
120DeviceIntPtr            darwinTabletCurrent = NULL;
121DeviceIntPtr            darwinTabletStylus = NULL;
122DeviceIntPtr            darwinTabletCursor = NULL;
123DeviceIntPtr            darwinTabletEraser = NULL;
124
125// Common pixmap formats
126static PixmapFormatRec formats[] = {
127        { 1,    1,      BITMAP_SCANLINE_PAD },
128        { 4,    8,      BITMAP_SCANLINE_PAD },
129        { 8,    8,      BITMAP_SCANLINE_PAD },
130        { 15,   16,     BITMAP_SCANLINE_PAD },
131        { 16,   16,     BITMAP_SCANLINE_PAD },
132        { 24,   32,     BITMAP_SCANLINE_PAD },
133        { 32,   32,     BITMAP_SCANLINE_PAD }
134};
135const int NUMFORMATS = sizeof(formats)/sizeof(formats[0]);
136
137#ifndef OSNAME
138#define OSNAME " Darwin"
139#endif
140#ifndef OSVENDOR
141#define OSVENDOR ""
142#endif
143#ifndef PRE_RELEASE
144#define PRE_RELEASE XORG_VERSION_SNAP
145#endif
146#ifndef BUILD_DATE
147#define BUILD_DATE ""
148#endif
149#ifndef XORG_RELEASE
150#define XORG_RELEASE "?"
151#endif
152
153void
154DarwinPrintBanner(void)
155{
156  // this should change depending on which specific server we are building
157  ErrorF("Xquartz starting:\n");
158  ErrorF("X.Org X Server %s\nBuild Date: %s\n", XSERVER_VERSION, BUILD_DATE );
159}
160
161
162/*
163 * DarwinSaveScreen
164 *  X screensaver support. Not implemented.
165 */
166static Bool DarwinSaveScreen(ScreenPtr pScreen, int on)
167{
168    // FIXME
169    if (on == SCREEN_SAVER_FORCER) {
170    } else if (on == SCREEN_SAVER_ON) {
171    } else {
172    }
173    return TRUE;
174}
175
176/*
177 * DarwinScreenInit
178 *  This is a callback from dix during AddScreen() from InitOutput().
179 *  Initialize the screen and communicate information about it back to dix.
180 */
181static Bool DarwinScreenInit(int index, ScreenPtr pScreen, int argc, char **argv) {
182    int         dpi;
183    static int  foundIndex = 0;
184    Bool        ret;
185    DarwinFramebufferPtr dfb;
186
187    if (!dixRegisterPrivateKey(&darwinScreenKeyRec, PRIVATE_SCREEN, 0))
188	return FALSE;
189
190    // reset index of found screens for each server generation
191    if (index == 0) {
192        foundIndex = 0;
193
194        // reset the visual list
195        miClearVisualTypes();
196    }
197
198    // allocate space for private per screen storage
199    dfb = malloc(sizeof(DarwinFramebufferRec));
200
201    // SCREEN_PRIV(pScreen) = dfb;
202    dixSetPrivate(&pScreen->devPrivates, darwinScreenKey, dfb);
203
204    // setup hardware/mode specific details
205    ret = QuartzAddScreen(foundIndex, pScreen);
206    foundIndex++;
207    if (! ret)
208        return FALSE;
209
210    // setup a single visual appropriate for our pixel type
211    if(!miSetVisualTypesAndMasks(dfb->depth, dfb->visuals, dfb->bitsPerRGB,
212                                 dfb->preferredCVC, dfb->redMask,
213                                 dfb->greenMask, dfb->blueMask)) {
214        return FALSE;
215    }
216
217// TODO: Make PseudoColor visuals not suck in TrueColor mode
218//    if(dfb->depth > 8)
219//        miSetVisualTypesAndMasks(8, PseudoColorMask, 8, PseudoColor, 0, 0, 0);
220    if(dfb->depth > 15)
221        miSetVisualTypesAndMasks(15, TrueColorMask, 5, TrueColor, RM_ARGB(0,5,5,5), GM_ARGB(0,5,5,5), BM_ARGB(0,5,5,5));
222    if(dfb->depth > 24)
223        miSetVisualTypesAndMasks(24, TrueColorMask, 8, TrueColor, RM_ARGB(0,8,8,8), GM_ARGB(0,8,8,8), BM_ARGB(0,8,8,8));
224
225    miSetPixmapDepths();
226
227    // machine independent screen init
228    // setup _Screen structure in pScreen
229    if (monitorResolution)
230        dpi = monitorResolution;
231    else
232        dpi = 96;
233
234    // initialize fb
235    if (! fbScreenInit(pScreen,
236                dfb->framebuffer,                 // pointer to screen bitmap
237                dfb->width, dfb->height,          // screen size in pixels
238                dpi, dpi,                         // dots per inch
239                dfb->pitch/(dfb->bitsPerPixel/8), // pixel width of framebuffer
240                dfb->bitsPerPixel))               // bits per pixel for screen
241    {
242        return FALSE;
243    }
244
245    if (! fbPictureInit(pScreen, 0, 0)) {
246        return FALSE;
247    }
248
249#ifdef MITSHM
250    ShmRegisterFbFuncs(pScreen);
251#endif
252
253    // this must be initialized (why doesn't X have a default?)
254    pScreen->SaveScreen = DarwinSaveScreen;
255
256    // finish mode dependent screen setup including cursor support
257    if (!QuartzSetupScreen(index, pScreen)) {
258        return FALSE;
259    }
260
261    // create and install the default colormap and
262    // set pScreen->blackPixel / pScreen->white
263    if (!miCreateDefColormap( pScreen )) {
264        return FALSE;
265    }
266
267    pScreen->x = dfb->x;
268    pScreen->y = dfb->y;
269
270    /*    ErrorF("Screen %d added: %dx%d @ (%d,%d)\n",
271	  index, dfb->width, dfb->height, dfb->x, dfb->y); */
272
273    return TRUE;
274}
275
276/*
277 =============================================================================
278
279 mouse and keyboard callbacks
280
281 =============================================================================
282*/
283
284/*
285 * DarwinMouseProc: Handle the initialization, etc. of a mouse
286 */
287static int DarwinMouseProc(DeviceIntPtr pPointer, int what) {
288#define NBUTTONS 7
289#define NAXES 2
290	// 7 buttons: left, right, middle, then four scroll wheel "buttons"
291    CARD8 map[NBUTTONS + 1] = {0, 1, 2, 3, 4, 5, 6, 7};
292    Atom btn_labels[NBUTTONS] = {0};
293    Atom axes_labels[NAXES] = {0};
294
295    switch (what) {
296        case DEVICE_INIT:
297            pPointer->public.on = FALSE;
298
299            btn_labels[0] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_LEFT);
300            btn_labels[1] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_MIDDLE);
301            btn_labels[2] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_RIGHT);
302            btn_labels[3] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_WHEEL_UP);
303            btn_labels[4] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_WHEEL_DOWN);
304            btn_labels[5] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_HWHEEL_LEFT);
305            btn_labels[6] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_HWHEEL_RIGHT);
306
307            axes_labels[0] = XIGetKnownProperty(AXIS_LABEL_PROP_REL_X);
308            axes_labels[1] = XIGetKnownProperty(AXIS_LABEL_PROP_REL_Y);
309
310
311            // Set button map.
312            InitPointerDeviceStruct((DevicePtr)pPointer, map, NBUTTONS,
313                                    btn_labels,
314                                    (PtrCtrlProcPtr)NoopDDA,
315                                    GetMotionHistorySize(), NAXES,
316                                    axes_labels);
317            InitAbsoluteClassDeviceStruct(pPointer);
318//            InitValuatorAxisStruct(pPointer, 0, 0, XQUARTZ_VALUATOR_LIMIT, 1, 0, 1, Absolute);
319//            InitValuatorAxisStruct(pPointer, 1, 0, XQUARTZ_VALUATOR_LIMIT, 1, 0, 1, Absolute);
320            break;
321        case DEVICE_ON:
322            pPointer->public.on = TRUE;
323            AddEnabledDevice( darwinEventReadFD );
324            return Success;
325        case DEVICE_CLOSE:
326        case DEVICE_OFF:
327            pPointer->public.on = FALSE;
328            RemoveEnabledDevice(darwinEventReadFD);
329            return Success;
330    }
331
332    return Success;
333#undef NBUTTONS
334#undef NAXES
335}
336
337static int DarwinTabletProc(DeviceIntPtr pPointer, int what) {
338#define NBUTTONS 3
339#define NAXES 5
340    CARD8 map[NBUTTONS + 1] = {0, 1, 2, 3};
341    Atom btn_labels[NBUTTONS] = {0};
342    Atom axes_labels[NAXES] = {0};
343
344    switch (what) {
345        case DEVICE_INIT:
346            pPointer->public.on = FALSE;
347
348            btn_labels[0] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_LEFT);
349            btn_labels[1] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_MIDDLE);
350            btn_labels[2] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_RIGHT);
351
352            axes_labels[0] = XIGetKnownProperty(AXIS_LABEL_PROP_ABS_X);
353            axes_labels[1] = XIGetKnownProperty(AXIS_LABEL_PROP_ABS_Y);
354            axes_labels[2] = XIGetKnownProperty(AXIS_LABEL_PROP_ABS_PRESSURE);
355            axes_labels[3] = XIGetKnownProperty(AXIS_LABEL_PROP_ABS_TILT_X);
356            axes_labels[4] = XIGetKnownProperty(AXIS_LABEL_PROP_ABS_TILT_Y);
357
358            // Set button map.
359            InitPointerDeviceStruct((DevicePtr)pPointer, map, NBUTTONS,
360                                    btn_labels,
361                                    (PtrCtrlProcPtr)NoopDDA,
362                                    GetMotionHistorySize(), NAXES,
363                                    axes_labels);
364            InitProximityClassDeviceStruct(pPointer);
365			InitAbsoluteClassDeviceStruct(pPointer);
366
367            InitValuatorAxisStruct(pPointer, 0, axes_labels[0], 0, XQUARTZ_VALUATOR_LIMIT, 1, 0, 1, Absolute);
368            InitValuatorAxisStruct(pPointer, 1, axes_labels[1], 0, XQUARTZ_VALUATOR_LIMIT, 1, 0, 1, Absolute);
369            InitValuatorAxisStruct(pPointer, 2, axes_labels[2], 0, XQUARTZ_VALUATOR_LIMIT, 1, 0, 1, Absolute);
370            InitValuatorAxisStruct(pPointer, 3, axes_labels[3], -XQUARTZ_VALUATOR_LIMIT, XQUARTZ_VALUATOR_LIMIT, 1, 0, 1, Absolute);
371            InitValuatorAxisStruct(pPointer, 4, axes_labels[4], -XQUARTZ_VALUATOR_LIMIT, XQUARTZ_VALUATOR_LIMIT, 1, 0, 1, Absolute);
372//          pPointer->use = IsXExtensionDevice;
373            break;
374        case DEVICE_ON:
375            pPointer->public.on = TRUE;
376            AddEnabledDevice( darwinEventReadFD );
377            return Success;
378        case DEVICE_CLOSE:
379        case DEVICE_OFF:
380            pPointer->public.on = FALSE;
381            RemoveEnabledDevice(darwinEventReadFD);
382            return Success;
383    }
384    return Success;
385#undef NBUTTONS
386#undef NAXES
387}
388
389/*
390 * DarwinKeybdProc
391 *  Callback from X
392 */
393static int DarwinKeybdProc( DeviceIntPtr pDev, int onoff )
394{
395    switch ( onoff ) {
396        case DEVICE_INIT:
397            DarwinKeyboardInit( pDev );
398            break;
399        case DEVICE_ON:
400            pDev->public.on = TRUE;
401            AddEnabledDevice( darwinEventReadFD );
402            break;
403        case DEVICE_OFF:
404            pDev->public.on = FALSE;
405            RemoveEnabledDevice( darwinEventReadFD );
406            break;
407        case DEVICE_CLOSE:
408            break;
409    }
410
411    return Success;
412}
413
414/*
415===========================================================================
416
417 Utility routines
418
419===========================================================================
420*/
421
422/*
423 * DarwinParseModifierList
424 *  Parse a list of modifier names and return a corresponding modifier mask
425 */
426int DarwinParseModifierList(const char *constmodifiers, int separatelr)
427{
428    int result = 0;
429
430    if (constmodifiers) {
431        char *modifiers = strdup(constmodifiers);
432        char *modifier;
433        int nxkey;
434        char *p = modifiers;
435
436        while (p) {
437            modifier = strsep(&p, " ,+&|/"); // allow lots of separators
438            nxkey = DarwinModifierStringToNXMask(modifier, separatelr);
439            if(nxkey)
440                result |= nxkey;
441            else
442                ErrorF("fakebuttons: Unknown modifier \"%s\"\n", modifier);
443        }
444        free(modifiers);
445    }
446    return result;
447}
448
449/*
450===========================================================================
451
452 Functions needed to link against device independent X
453
454===========================================================================
455*/
456
457/*
458 * InitInput
459 *  Register the keyboard and mouse devices
460 */
461void InitInput( int argc, char **argv )
462{
463    XkbRMLVOSet rmlvo = { .rules = "base", .model = "empty", .layout = "empty",
464                          .variant = NULL, .options = NULL };
465    /* We need to really have rules... or something... */
466    XkbSetRulesDflts(&rmlvo);
467
468    darwinKeyboard = AddInputDevice(serverClient, DarwinKeybdProc, TRUE);
469    darwinKeyboard->name = strdup("keyboard");
470
471    /* here's the snippet from the current gdk sources:
472    if (!strcmp (tmp_name, "pointer"))
473        gdkdev->info.source = GDK_SOURCE_MOUSE;
474    else if (!strcmp (tmp_name, "wacom") ||
475             !strcmp (tmp_name, "pen"))
476        gdkdev->info.source = GDK_SOURCE_PEN;
477    else if (!strcmp (tmp_name, "eraser"))
478        gdkdev->info.source = GDK_SOURCE_ERASER;
479    else if (!strcmp (tmp_name, "cursor"))
480        gdkdev->info.source = GDK_SOURCE_CURSOR;
481    else
482        gdkdev->info.source = GDK_SOURCE_PEN;
483    */
484
485    darwinPointer = AddInputDevice(serverClient, DarwinMouseProc, TRUE);
486    darwinPointer->name = strdup("pointer");
487
488    darwinTabletStylus = AddInputDevice(serverClient, DarwinTabletProc, TRUE);
489    darwinTabletStylus->name = strdup("pen");
490
491    darwinTabletCursor = AddInputDevice(serverClient, DarwinTabletProc, TRUE);
492    darwinTabletCursor->name = strdup("cursor");
493
494    darwinTabletEraser = AddInputDevice(serverClient, DarwinTabletProc, TRUE);
495    darwinTabletEraser->name = strdup("eraser");
496
497    darwinTabletCurrent = darwinTabletStylus;
498
499    DarwinEQInit();
500
501    QuartzInitInput(argc, argv);
502}
503
504
505/*
506 * DarwinAdjustScreenOrigins
507 *  Shift all screens so the X11 (0, 0) coordinate is at the top
508 *  left of the global screen coordinates.
509 *
510 *  Screens can be arranged so the top left isn't on any screen, so
511 *  instead use the top left of the leftmost screen as (0,0). This
512 *  may mean some screen space is in -y, but it's better that (0,0)
513 *  be onscreen, or else default xterms disappear. It's better that
514 *  -y be used than -x, because when popup menus are forced
515 *  "onscreen" by dumb window managers like twm, they'll shift the
516 *  menus down instead of left, which still looks funny but is an
517 *  easier target to hit.
518 */
519void
520DarwinAdjustScreenOrigins(ScreenInfo *pScreenInfo)
521{
522    int i, left, top;
523
524    left = pScreenInfo->screens[0]->x;
525    top  = pScreenInfo->screens[0]->y;
526
527    /* Find leftmost screen. If there's a tie, take the topmost of the two. */
528    for (i = 1; i < pScreenInfo->numScreens; i++) {
529        if (pScreenInfo->screens[i]->x < left  ||
530            (pScreenInfo->screens[i]->x == left && pScreenInfo->screens[i]->y < top))
531        {
532            left = pScreenInfo->screens[i]->x;
533            top = pScreenInfo->screens[i]->y;
534        }
535    }
536
537    darwinMainScreenX = left;
538    darwinMainScreenY = top;
539
540    DEBUG_LOG("top = %d, left=%d\n", top, left);
541
542    /* Shift all screens so that there is a screen whose top left
543     * is at X11 (0,0) and at global screen coordinate
544     * (darwinMainScreenX, darwinMainScreenY).
545     */
546
547    if (darwinMainScreenX != 0 || darwinMainScreenY != 0) {
548        for (i = 0; i < pScreenInfo->numScreens; i++) {
549            pScreenInfo->screens[i]->x -= darwinMainScreenX;
550            pScreenInfo->screens[i]->y -= darwinMainScreenY;
551            DEBUG_LOG("Screen %d placed at X11 coordinate (%d,%d).\n",
552                      i, pScreenInfo->screens[i]->x, pScreenInfo->screens[i]->y);
553        }
554    }
555}
556
557
558/*
559 * InitOutput
560 *  Initialize screenInfo for all actually accessible framebuffers.
561 *
562 *  The display mode dependent code gets called three times. The mode
563 *  specific InitOutput routines are expected to discover the number
564 *  of potentially useful screens and cache routes to them internally.
565 *  Inside DarwinScreenInit are two other mode specific calls.
566 *  A mode specific AddScreen routine is called for each screen to
567 *  actually initialize the screen with the ScreenPtr structure.
568 *  After other screen setup has been done, a mode specific
569 *  SetupScreen function can be called to finalize screen setup.
570 */
571void InitOutput( ScreenInfo *pScreenInfo, int argc, char **argv )
572{
573    int i;
574
575    pScreenInfo->imageByteOrder = IMAGE_BYTE_ORDER;
576    pScreenInfo->bitmapScanlineUnit = BITMAP_SCANLINE_UNIT;
577    pScreenInfo->bitmapScanlinePad = BITMAP_SCANLINE_PAD;
578    pScreenInfo->bitmapBitOrder = BITMAP_BIT_ORDER;
579
580    // List how we want common pixmap formats to be padded
581    pScreenInfo->numPixmapFormats = NUMFORMATS;
582    for (i = 0; i < NUMFORMATS; i++)
583        pScreenInfo->formats[i] = formats[i];
584
585    // Discover screens and do mode specific initialization
586    QuartzInitOutput(argc, argv);
587
588    // Add screens
589    for (i = 0; i < darwinScreensFound; i++) {
590        AddScreen(DarwinScreenInit, argc, argv);
591    }
592
593    DarwinAdjustScreenOrigins(pScreenInfo);
594}
595
596
597/*
598 * OsVendorFatalError
599 */
600void OsVendorFatalError( void )
601{
602    ErrorF( "   OsVendorFatalError\n" );
603}
604
605
606/*
607 * OsVendorInit
608 *  Initialization of Darwin OS support.
609 */
610void OsVendorInit(void)
611{
612    if (serverGeneration == 1) {
613        DarwinPrintBanner();
614#ifdef ENABLE_DEBUG_LOG
615	{
616	  char *home_dir=NULL, *log_file_path=NULL;
617	  home_dir = getenv("HOME");
618	  if (home_dir) asprintf(&log_file_path, "%s/%s", home_dir, DEBUG_LOG_NAME);
619	  if (log_file_path) {
620	    if (!access(log_file_path, F_OK)) {
621	      debug_log_fp = fopen(log_file_path, "a");
622	      if (debug_log_fp) ErrorF("Debug logging enabled to %s\n", log_file_path);
623	    }
624	    free(log_file_path);
625	  }
626	}
627#endif
628    }
629}
630
631
632/*
633 * ddxProcessArgument
634 *  Process device-dependent command line args. Returns 0 if argument is
635 *  not device dependent, otherwise Count of number of elements of argv
636 *  that are part of a device dependent commandline option.
637 */
638int ddxProcessArgument( int argc, char *argv[], int i )
639{
640//    if ( !strcmp( argv[i], "-fullscreen" ) ) {
641//        ErrorF( "Running full screen in parallel with Mac OS X Quartz window server.\n" );
642//        return 1;
643//    }
644
645//    if ( !strcmp( argv[i], "-rootless" ) ) {
646//        ErrorF( "Running rootless inside Mac OS X window server.\n" );
647//        return 1;
648//    }
649
650    // This command line arg is passed when launched from the Aqua GUI.
651    if ( !strncmp( argv[i], "-psn_", 5 ) ) {
652        return 1;
653    }
654
655    if ( !strcmp( argv[i], "-fakebuttons" ) ) {
656        darwinFakeButtons = TRUE;
657        ErrorF( "Faking a three button mouse\n" );
658        return 1;
659    }
660
661    if ( !strcmp( argv[i], "-nofakebuttons" ) ) {
662        darwinFakeButtons = FALSE;
663        ErrorF( "Not faking a three button mouse\n" );
664        return 1;
665    }
666
667    if (!strcmp( argv[i], "-fakemouse2" ) ) {
668        if ( i == argc-1 ) {
669            FatalError( "-fakemouse2 must be followed by a modifer list\n" );
670        }
671        if (!strcasecmp(argv[i+1], "none") || !strcmp(argv[i+1], ""))
672            darwinFakeMouse2Mask = 0;
673        else
674            darwinFakeMouse2Mask = DarwinParseModifierList(argv[i+1], 1);
675        ErrorF("Modifier mask to fake mouse button 2 = 0x%x\n",
676               darwinFakeMouse2Mask);
677        return 2;
678    }
679
680    if (!strcmp( argv[i], "-fakemouse3" ) ) {
681        if ( i == argc-1 ) {
682            FatalError( "-fakemouse3 must be followed by a modifer list\n" );
683        }
684        if (!strcasecmp(argv[i+1], "none") || !strcmp(argv[i+1], ""))
685            darwinFakeMouse3Mask = 0;
686        else
687            darwinFakeMouse3Mask = DarwinParseModifierList(argv[i+1], 1);
688        ErrorF("Modifier mask to fake mouse button 3 = 0x%x\n",
689               darwinFakeMouse3Mask);
690        return 2;
691    }
692
693    if ( !strcmp( argv[i], "+synckeymap" ) ) {
694        darwinSyncKeymap = TRUE;
695        return 1;
696    }
697
698    if ( !strcmp( argv[i], "-synckeymap" ) ) {
699        darwinSyncKeymap = FALSE;
700        return 1;
701    }
702
703    if ( !strcmp( argv[i], "-depth" ) ) {
704        if ( i == argc-1 ) {
705            FatalError( "-depth must be followed by a number\n" );
706        }
707        darwinDesiredDepth = atoi( argv[i+1] );
708        if(darwinDesiredDepth != -1 &&
709           darwinDesiredDepth != 8 &&
710           darwinDesiredDepth != 15 &&
711           darwinDesiredDepth != 24) {
712            FatalError( "Unsupported pixel depth. Use 8, 15, or 24 bits\n" );
713        }
714
715        ErrorF( "Attempting to use pixel depth of %i\n", darwinDesiredDepth );
716        return 2;
717    }
718
719    if (!strcmp( argv[i], "-showconfig" ) || !strcmp( argv[i], "-version" )) {
720        DarwinPrintBanner();
721        exit(0);
722    }
723
724    return 0;
725}
726
727
728/*
729 * ddxUseMsg --
730 *  Print out correct use of device dependent commandline options.
731 *  Maybe the user now knows what really to do ...
732 */
733void ddxUseMsg( void )
734{
735    ErrorF("\n");
736    ErrorF("\n");
737    ErrorF("Device Dependent Usage:\n");
738    ErrorF("\n");
739    ErrorF("-depth <8,15,24> : use this bit depth.\n");
740    ErrorF("-fakebuttons : fake a three button mouse with Command and Option keys.\n");
741    ErrorF("-nofakebuttons : don't fake a three button mouse.\n");
742    ErrorF("-fakemouse2 <modifiers> : fake middle mouse button with modifier keys.\n");
743    ErrorF("-fakemouse3 <modifiers> : fake right mouse button with modifier keys.\n");
744    ErrorF("  ex: -fakemouse2 \"option,shift\" = option-shift-click is middle button.\n");
745    ErrorF("-version : show the server version.\n");
746    ErrorF("\n");
747}
748
749
750/*
751 * ddxGiveUp --
752 *      Device dependent cleanup. Called by dix before normal server death.
753 */
754void ddxGiveUp( void )
755{
756    ErrorF( "Quitting Xquartz\n" );
757}
758
759
760/*
761 * AbortDDX --
762 *      DDX - specific abort routine.  Called by AbortServer(). The attempt is
763 *      made to restore all original setting of the displays. Also all devices
764 *      are closed.
765 */
766void AbortDDX( void )
767{
768    ErrorF( "   AbortDDX\n" );
769    OsAbort();
770}
771
772#include "mivalidate.h" // for union _Validate used by windowstr.h
773#include "windowstr.h"  // for struct _Window
774#include "scrnintstr.h" // for struct _Screen
775
776// This is copied from Xserver/hw/xfree86/common/xf86Helper.c.
777// Quartz mode uses this when switching in and out of Quartz.
778// Quartz or IOKit can use this when waking from sleep.
779// Copyright (c) 1997-1998 by The XFree86 Project, Inc.
780
781/*
782 * xf86SetRootClip --
783 *	Enable or disable rendering to the screen by
784 *	setting the root clip list and revalidating
785 *	all of the windows
786 */
787
788void
789xf86SetRootClip (ScreenPtr pScreen, int enable)
790{
791    WindowPtr	pWin = pScreen->root;
792    WindowPtr	pChild;
793    Bool	WasViewable = (Bool)(pWin->viewable);
794    Bool	anyMarked = TRUE;
795    RegionPtr	pOldClip = NULL;
796    WindowPtr   pLayerWin;
797    BoxRec	box;
798
799    if (WasViewable)
800    {
801	for (pChild = pWin->firstChild; pChild; pChild = pChild->nextSib)
802	{
803	    (void) (*pScreen->MarkOverlappedWindows)(pChild,
804						     pChild,
805						     &pLayerWin);
806	}
807	(*pScreen->MarkWindow) (pWin);
808	anyMarked = TRUE;
809	if (pWin->valdata)
810	{
811	    if (HasBorder (pWin))
812	    {
813		RegionPtr	borderVisible;
814
815		borderVisible = RegionCreate(NullBox, 1);
816		RegionSubtract(borderVisible,
817				&pWin->borderClip, &pWin->winSize);
818		pWin->valdata->before.borderVisible = borderVisible;
819	    }
820	    pWin->valdata->before.resized = TRUE;
821	}
822    }
823
824    /*
825     * Use REGION_BREAK to avoid optimizations in ValidateTree
826     * that assume the root borderClip can't change well, normally
827     * it doesn't...)
828     */
829    if (enable)
830    {
831	box.x1 = 0;
832	box.y1 = 0;
833	box.x2 = pScreen->width;
834	box.y2 = pScreen->height;
835	RegionReset(&pWin->borderClip, &box);
836	RegionBreak(&pWin->clipList);
837    }
838    else
839    {
840	RegionEmpty(&pWin->borderClip);
841	RegionBreak(&pWin->clipList);
842    }
843
844    ResizeChildrenWinSize (pWin, 0, 0, 0, 0);
845
846    if (WasViewable)
847    {
848	if (pWin->backStorage)
849	{
850	    pOldClip = RegionCreate(NullBox, 1);
851	    RegionCopy(pOldClip, &pWin->clipList);
852	}
853
854	if (pWin->firstChild)
855	{
856	    anyMarked |= (*pScreen->MarkOverlappedWindows)(pWin->firstChild,
857							   pWin->firstChild,
858							   (WindowPtr *)NULL);
859	}
860	else
861	{
862	    (*pScreen->MarkWindow) (pWin);
863	    anyMarked = TRUE;
864	}
865
866
867	if (anyMarked)
868	    (*pScreen->ValidateTree)(pWin, NullWindow, VTOther);
869    }
870
871    if (WasViewable)
872    {
873	if (anyMarked)
874	    (*pScreen->HandleExposures)(pWin);
875	if (anyMarked && pScreen->PostValidateTree)
876	    (*pScreen->PostValidateTree)(pWin, NullWindow, VTOther);
877    }
878    if (pWin->realized)
879	WindowsRestructured ();
880    FlushAllOutput ();
881}
882