Beispiel #1
0
static void set_left_handed_mouse()
{
    unsigned char *buttons;
    gint n_buttons, i;
    gint idx_1 = 0, idx_3 = 1;

    buttons = g_alloca (DEFAULT_PTR_MAP_SIZE);
    n_buttons = XGetPointerMapping (GDK_DISPLAY_XDISPLAY(gdk_display_get_default()), buttons, DEFAULT_PTR_MAP_SIZE);
    if (n_buttons > DEFAULT_PTR_MAP_SIZE)
    {
        buttons = g_alloca (n_buttons);
        n_buttons = XGetPointerMapping (GDK_DISPLAY_XDISPLAY(gdk_display_get_default()), buttons, n_buttons);
    }

    for (i = 0; i < n_buttons; i++)
    {
        if (buttons[i] == 1)
            idx_1 = i;
        else if (buttons[i] == ((n_buttons < 3) ? 2 : 3))
            idx_3 = i;
    }

    if ((left_handed && idx_1 < idx_3) ||
        (!left_handed && idx_1 > idx_3))
    {
        buttons[idx_1] = ((n_buttons < 3) ? 2 : 3);
        buttons[idx_3] = 1;
        XSetPointerMapping (GDK_DISPLAY_XDISPLAY(gdk_display_get_default()), buttons, n_buttons);
    }
}
Beispiel #2
0
int
xnestPointerProc(DeviceIntPtr pDev, int onoff)
{
  CARD8 map[MAXBUTTONS];
  int nmap;
  int i;

  switch (onoff)
    {
    case DEVICE_INIT: 
      nmap = XGetPointerMapping(xnestDisplay, map, MAXBUTTONS);
      for (i = 0; i <= nmap; i++)
	map[i] = i; /* buttons are already mapped */
      InitPointerDeviceStruct(&pDev->public, map, nmap,
			      miPointerGetMotionEvents,
			      xnestChangePointerControl,
			      miPointerGetMotionBufferSize());
      break;
    case DEVICE_ON: 
      xnestEventMask |= XNEST_POINTER_EVENT_MASK;
      for (i = 0; i < xnestNumScreens; i++)
	XSelectInput(xnestDisplay, xnestDefaultWindows[i], xnestEventMask);
      break;
    case DEVICE_OFF: 
      xnestEventMask &= ~XNEST_POINTER_EVENT_MASK;
      for (i = 0; i < xnestNumScreens; i++)
	XSelectInput(xnestDisplay, xnestDefaultWindows[i], xnestEventMask);
      break;
    case DEVICE_CLOSE: 
      break;
    }
  return Success;
}
Beispiel #3
0
/*
 * ask the user to press in the root with each button in succession
 */
static int 
verify_okay_to_kill(Display *dpy, int screenno)
{
    unsigned char pointer_map[256];
    int count = XGetPointerMapping (dpy, pointer_map, 256);
    int i;
    int button;
    static char *msg = "the root window";
    Window root = RootWindow (dpy, screenno);
    int okay = 0;

    for (i = 0; i < count; i++) {
	button = (int) pointer_map[i];
	if (button == 0) continue;	/* disabled */
	if (get_window_id (dpy, screenno, button, msg) != root) {
	    okay = 0;
	    break;
	}
	okay++;				/* must have at least one button */
    }
    if (okay) {
	return 1;
    } else {
	printf ("Aborting.\n");
	return 0;
    }
}
Beispiel #4
0
void MouseSetup::apply()
{
    unsigned char map[20];
    int num_buttons = XGetPointerMapping( kapp->getDisplay(), map, 20 );
    if ( num_buttons == 1 )
    {
        map[0] = ( unsigned char ) 1;
    }
    else if ( num_buttons == 2 )
    {
        if ( handed == RIGHT_HANDED )
        {
            map[0] = ( unsigned char ) 1;
            map[1] = ( unsigned char ) 3;
        } else {
            map[0] = ( unsigned char ) 3;
            map[1] = ( unsigned char ) 1;
        }
    }
    else // 3 or more buttons
    {
        if ( handed == RIGHT_HANDED )
        {
            map[0] = ( unsigned char ) 1;
            map[2] = ( unsigned char ) 3;
        } else {
            map[0] = ( unsigned char ) 3;
            map[2] = ( unsigned char ) 1;
        }
    }

        int retval;
        while ( ( retval = XSetPointerMapping(
                      kapp->getDisplay(), map, num_buttons ) ) == MappingBusy ) {};
}
Beispiel #5
0
int 
SetPointerMap(unsigned char *map, int n)
{
    unsigned char defmap[MAXBUTTONCODES];
    int j;
    int retries, timeout;

    if (n == 0) {				/* reset to default */
	n = XGetPointerMapping (dpy, defmap, MAXBUTTONCODES);
	for (j = 0; j < n; j++) defmap[j] = (unsigned char) (j + 1);
	map = defmap;
    }

    for (retries = 5, timeout = 2; retries > 0; retries--, timeout *= 2) {
	int result;

	switch (result = XSetPointerMapping (dpy, map, n)) {
	  case MappingSuccess:
	    return 0;
	  case MappingBusy:
	    mapping_busy_pointer (timeout);
	    continue;
	  case MappingFailed:
	    fprintf (stderr, "%s:  bad pointer mapping\n", ProgramName);
	    return -1;
	  default:
	    fprintf (stderr, "%s:  bad return %d from XSetPointerMapping\n",
		     ProgramName, result);
	    return -1;
	}
    }
    fprintf (stderr, "%s:  unable to set pointer mapping\n", ProgramName);
    return -1;
}
Beispiel #6
0
/* xmouse_get_mouse_num_buttons:
 *  Return the number of buttons on the mouse.
 */
static unsigned int xmouse_get_mouse_num_buttons(void)
{
   int num_buttons;
   unsigned char map[32];
   ALLEGRO_SYSTEM_XGLX *system = (void *)al_get_system_driver();

   ASSERT(xmouse_installed);

   _al_mutex_lock(&system->lock);
   num_buttons = XGetPointerMapping(system->x11display, map, sizeof(map));
   _al_mutex_unlock(&system->lock);
   
   if (num_buttons > (int)sizeof(map))
      num_buttons = sizeof(map);
   
   #ifdef DEBUGMODE
   char debug[num_buttons * 4 + 1];
   debug[0] = 0;
   int i;
   for (i = 0; i < num_buttons; i++) {
      sprintf(debug + strlen(debug), "%2d,", map[i]);
   }
   ALLEGRO_DEBUG("XGetPointerMapping: %s\n", debug);
   #endif

   if (num_buttons < 1)
      num_buttons = 1;

   return num_buttons;
}
Beispiel #7
0
// choose a window
static int get_button1(void)
{
    char* button_name = XGetDefault(dpy, nameProg, "Button");
    int button = -1;                    // button number or negative for all

    if (!button_name)
        button = SelectButtonFirst;
    else if (!parse_button(button_name, &button))
        error_exit("invalid button specification \"%s\"", button_name);

    if (button >= 0 || button == SelectButtonFirst)
    {
        unsigned char pointer_map[256];         // 8 bits of pointer num
        int count, j;
        unsigned int ub = (unsigned int) button;

        count = XGetPointerMapping(dpy, pointer_map, 256);
        if (count <= 0)
            error_exit("no pointer mapping");

        if (button >= 0)                        // check button
        {
            for (j = 0; j < count; j++)
                if (ub == (unsigned int) pointer_map[j]) break;
            if (j == count)
                error_exit("button %u not mapped", ub);
        }
        else                                    // get first entry
            button = (int)((unsigned int)pointer_map[0]);
    }

    return button;
}
Beispiel #8
0
KGlobalSettings::KMouseSettings & KGlobalSettings::mouseSettings()
{
    if ( ! s_mouseSettings )
    {
        s_mouseSettings = new KMouseSettings;
        KMouseSettings & s = *s_mouseSettings; // for convenience

#ifndef Q_WS_WIN
        KConfigGroup g( KGlobal::config(), "Mouse" );
        QString setting = g.readEntry("MouseButtonMapping");
        if (setting == "RightHanded")
            s.handed = KMouseSettings::RightHanded;
        else if (setting == "LeftHanded")
            s.handed = KMouseSettings::LeftHanded;
        else
        {
#ifdef Q_WS_X11
            // get settings from X server
            // This is a simplified version of the code in input/mouse.cpp
            // Keep in sync !
            s.handed = KMouseSettings::RightHanded;
            unsigned char map[20];
            int num_buttons = XGetPointerMapping(kapp->getDisplay(), map, 20);
            if( num_buttons == 2 )
            {
                if ( (int)map[0] == 1 && (int)map[1] == 2 )
                    s.handed = KMouseSettings::RightHanded;
                else if ( (int)map[0] == 2 && (int)map[1] == 1 )
                    s.handed = KMouseSettings::LeftHanded;
            }
            else if( num_buttons >= 3 )
            {
                if ( (int)map[0] == 1 && (int)map[2] == 3 )
                    s.handed = KMouseSettings::RightHanded;
                else if ( (int)map[0] == 3 && (int)map[2] == 1 )
                    s.handed = KMouseSettings::LeftHanded;
            }
#else
        // FIXME(E): Implement in Qt Embedded
#endif
        }
#endif //Q_WS_WIN
    }
#ifdef Q_WS_WIN
    //not cached
    s_mouseSettings->handed = (GetSystemMetrics(SM_SWAPBUTTON) ? KMouseSettings::LeftHanded : KMouseSettings::RightHanded);
#endif
    return *s_mouseSettings;
}
Beispiel #9
0
void
PrintPointerMap(FILE *fp)
{
    unsigned char pmap[256];		/* there are 8 bits of buttons */
    int count, i;

    count = XGetPointerMapping (dpy, pmap, 256);

    fprintf (fp, "There are %d pointer buttons defined.\n\n", count);
    fprintf (fp, "    Physical        Button\n");
    fprintf (fp, "     Button          Code\n");
/*               "      ###            ###\n"               */
    for (i = 0; i < count; i++) {
	fprintf (fp, "      %3u            %3u\n", 
		 i+1, (unsigned int) pmap[i]);
    }
    fprintf (fp, "\n");
    return;
}
int fgPlatformGlutDeviceGet ( GLenum eWhat )
{
    switch( eWhat )
    {
    case GLUT_HAS_KEYBOARD:
        /*
         * X11 has a core keyboard by definition, although it can
         * be present as a virtual/dummy keyboard. For now, there
         * is no reliable way to tell if a real keyboard is present.
         */
        return 1;

    /* X11 has a mouse by definition */
    case GLUT_HAS_MOUSE:
        return 1 ;

    case GLUT_NUM_MOUSE_BUTTONS:
        /* We should be able to pass NULL when the last argument is zero,
         * but at least one X server has a bug where this causes a segfault.
         *
         * In XFree86/Xorg servers, a mouse wheel is seen as two buttons
         * rather than an Axis; "freeglut_main.c" expects this when
         * checking for a wheel event.
         */
        {
            unsigned char map;
            int nbuttons = XGetPointerMapping(fgDisplay.pDisplay.Display, &map,0);
            return nbuttons;
        }

    default:
        fgWarning( "glutDeviceGet(): missing enum handle %d", eWhat );
        break;
    }

    /* And now -- the failure. */
    return -1;
}
Beispiel #11
0
void MouseConfig::GetSettings( void )
{
  int accel_num, accel_den, threshold;
  XGetPointerControl( kapp->getDisplay(), 
		      &accel_num, &accel_den, &threshold );
  accel_num /= accel_den;   // integer acceleration only

  // get settings from X server
  int h = RIGHT_HANDED;
  unsigned char map[5];
  num_buttons = XGetPointerMapping(kapp->getDisplay(), map, 5);
      
  switch (num_buttons)
    {
    case 1:
      /* disable button remapping */
      if (GUI)
	{
	  rightHanded->setEnabled(FALSE);
	  leftHanded->setEnabled(FALSE);
	  handedEnabled = FALSE;
	}
      break;
    case 2:
      if ( (int)map[0] == 1 && (int)map[1] == 2 )
	h = RIGHT_HANDED;
      else if ( (int)map[0] == 2 && (int)map[1] == 1 )
	h = LEFT_HANDED;
      else
	{
	  /* custom button setup: disable button remapping */
	  if (GUI)
	    {
	      rightHanded->setEnabled(FALSE);
	      leftHanded->setEnabled(FALSE);
	    }
	}
      break;
    case 3:
      middle_button = (int)map[1];
      if ( (int)map[0] == 1 && (int)map[2] == 3 )
	h = RIGHT_HANDED;
      else if ( (int)map[0] == 3 && (int)map[2] == 1 )
	h = LEFT_HANDED;
      else
	{
	  /* custom button setup: disable button remapping */
	  if (GUI)
	    {
	      rightHanded->setEnabled(FALSE);
	      leftHanded->setEnabled(FALSE);
	      handedEnabled = FALSE;
	    }
	}
      break;
    default:
      /* custom setup with > 3 buttons: disable button remapping */
      if (GUI)
	{
	  rightHanded->setEnabled(FALSE);
	  leftHanded->setEnabled(FALSE);
	  handedEnabled = FALSE;
	}
      break;
    }

  config->setGroup("Mouse");
  int a = config->readNumEntry("Acceleration",-1);
  if (a == -1)
    accelRate = accel_num;
  else
    accelRate = a;

  int t = config->readNumEntry("Threshold",-1);
  if (t == -1)
    thresholdMove = threshold;
  else
    thresholdMove = t;

  QString key = config->readEntry("MouseButtonMapping");
  if (key == "RightHanded")
    handed = RIGHT_HANDED;
  else if (key == "LeftHanded")
    handed = LEFT_HANDED;
  else if (key == NULL)
    handed = h;

  // the GUI should always show the real values
  if (GUI)
    {
      setAccel(accel_num);
      setThreshold(threshold);
      setHandedness(h);
    }
}
Beispiel #12
0
/*
 * Returns various device information.
 */
int FGAPIENTRY glutDeviceGet( GLenum eWhat )
{
    FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutDeviceGet" );

    /* XXX WARNING: we are mostly lying in this function. */
    switch( eWhat )
    {
    case GLUT_HAS_KEYBOARD:
        /*
         * Win32 is assumed a keyboard, and this cannot be queried,
         * except for WindowsCE.
         *
         * X11 has a core keyboard by definition, although it can
         * be present as a virtual/dummy keyboard. For now, there
         * is no reliable way to tell if a real keyboard is present.
         */
#if defined(_WIN32_CE)
        return ( GetKeyboardStatus() & KBDI_KEYBOARD_PRESENT ) ? 1 : 0;
#   if FREEGLUT_LIB_PRAGMAS
#       pragma comment (lib,"Kbdui.lib")
#   endif

#else
        return 1;
#endif

#if TARGET_HOST_POSIX_X11

    /* X11 has a mouse by definition */
    case GLUT_HAS_MOUSE:
        return 1 ;

    case GLUT_NUM_MOUSE_BUTTONS:
        /* We should be able to pass NULL when the last argument is zero,
         * but at least one X server has a bug where this causes a segfault.
         *
         * In XFree86/Xorg servers, a mouse wheel is seen as two buttons
         * rather than an Axis; "freeglut_main.c" expects this when
         * checking for a wheel event.
         */
        {
            unsigned char map;
            int nbuttons = XGetPointerMapping(fgDisplay.Display, &map,0);
            return nbuttons;
        }

#elif TARGET_HOST_MS_WINDOWS

    case GLUT_HAS_MOUSE:
        /*
         * MS Windows can be booted without a mouse.
         */
        return GetSystemMetrics( SM_MOUSEPRESENT );

    case GLUT_NUM_MOUSE_BUTTONS:
#  if defined(_WIN32_WCE)
        return 1;
#  else
        return GetSystemMetrics( SM_CMOUSEBUTTONS );
#  endif
#endif

    case GLUT_HAS_JOYSTICK:
        return fgJoystickDetect ();

    case GLUT_OWNS_JOYSTICK:
        return fgState.JoysticksInitialised;

    case GLUT_JOYSTICK_POLL_RATE:
        return fgStructure.CurrentWindow ? fgStructure.CurrentWindow->State.JoystickPollRate : 0;

    /* XXX The following two are only for Joystick 0 but this is an improvement */
    case GLUT_JOYSTICK_BUTTONS:
        return glutJoystickGetNumButtons ( 0 );

    case GLUT_JOYSTICK_AXES:
        return glutJoystickGetNumAxes ( 0 );

    case GLUT_HAS_DIAL_AND_BUTTON_BOX:
        return fgInputDeviceDetect ();

    case GLUT_NUM_DIALS:
        if ( fgState.InputDevsInitialised ) return 8;
        return 0;

    case GLUT_NUM_BUTTON_BOX_BUTTONS:
        return 0;

    case GLUT_HAS_SPACEBALL:
        return fgHasSpaceball();

    case GLUT_HAS_TABLET:
        return 0;

    case GLUT_NUM_SPACEBALL_BUTTONS:
        return fgSpaceballNumButtons();

    case GLUT_NUM_TABLET_BUTTONS:
        return 0;

    case GLUT_DEVICE_IGNORE_KEY_REPEAT:
        return fgStructure.CurrentWindow ? fgStructure.CurrentWindow->State.IgnoreKeyRepeat : 0;

    case GLUT_DEVICE_KEY_REPEAT:
        return fgState.KeyRepeat;

    default:
        fgWarning( "glutDeviceGet(): missing enum handle %d", eWhat );
        break;
    }

    /* And now -- the failure. */
    return -1;
}
Beispiel #13
0
int
main(int argc, char *argv[])
{
    int i;				/* iterator, temp variable */
    char *displayname = NULL;		/* name of server to contact */
    int screenno;			/* screen number of dpy */
    XID id = None;			/* resource to kill */
    char *button_name = NULL;		/* name of button for window select */
    int button;				/* button number or negative for all */
    Bool kill_all = False;
    Bool top = False;

    ProgramName = argv[0];
    button = SelectButtonFirst;

    for (i = 1; i < argc; i++) {
	char *arg = argv[i];

	if (arg[0] == '-') {
	    switch (arg[1]) {
	      case 'd':			/* -display displayname */
		if (++i >= argc) usage ();
		displayname = argv[i];
		continue;
	      case 'i':			/* -id resourceid */
		if (++i >= argc) usage ();
		id = parse_id (argv[i]);
		continue;
	      case 'b':			/* -button number */
		if (++i >= argc) usage ();
		button_name = argv[i];
		continue;
	      case 'f':			/* -frame */
		top = True;
		continue;
	      case 'a':			/* -all */
		kill_all = True;
		continue;
	      default:
		usage ();
	    }
	} else {
	    usage ();
	}
    }					/* end for */

    dpy = XOpenDisplay (displayname);
    if (!dpy) {
	fprintf (stderr, "%s:  unable to open display \"%s\"\n",
		 ProgramName, XDisplayName (displayname));
	Exit (1);
    }
    screenno = DefaultScreen (dpy);

    if (kill_all) {
	if (verify_okay_to_kill (dpy, screenno)) 
	  kill_all_windows (dpy, screenno, top);
	Exit (0);
    }

    /*
     * if no id was given, we need to choose a window
     */

    if (id == None) {
	if (!button_name)
	    button_name = XGetDefault (dpy, ProgramName, "Button");

	if (button_name && !parse_button (button_name, &button)) {
	    fprintf (stderr, "%s:  invalid button specification \"%s\"\n",
		     ProgramName, button_name);
	    Exit (1);
	}

	if (button >= 0 || button == SelectButtonFirst) {
	    unsigned char pointer_map[256];	 /* 8 bits of pointer num */
	    int count, j;
	    unsigned int ub = (unsigned int) button;


	    count = XGetPointerMapping (dpy, pointer_map, 256);
	    if (count <= 0) {
		fprintf (stderr, 
			 "%s:  no pointer mapping, can't select window\n",
			 ProgramName);
		Exit (1);
	    }

	    if (button >= 0) {			/* check button */
		for (j = 0; j < count; j++) {
		    if (ub == (unsigned int) pointer_map[j]) break;
		}
		if (j == count) {
		    fprintf (stderr,
	 "%s:  no button number %u in pointer map, can't select window\n",
			     ProgramName, ub);
		    Exit (1);
	        }
	    } else {				/* get first entry */
		button = (int) ((unsigned int) pointer_map[0]);
	    }
	}
	if ((id = get_window_id (dpy, screenno, button,
				"the window whose client you wish to kill"))) {
	    if (id == RootWindow(dpy,screenno)) id = None;
	    else if (!top) {
		XID indicated = id;
		if ((id = XmuClientWindow(dpy, indicated)) == indicated) {
		    
		    /* Try not to kill the window manager when the user
		     * indicates an icon to xkill.
		     */

		    if (! wm_state_set(dpy, id) && wm_running(dpy, screenno))
			id = None;

		} 
	    }
	}
    }

    if (id != None) {
	printf ("%s:  killing creator of resource 0x%lx\n", ProgramName, id);
	XSync (dpy, 0);			/* give xterm a chance */
	XKillClient (dpy, id);
	XSync (dpy, 0);
    }

    Exit (0);
    /*NOTREACHED*/
    return 0;
}
Beispiel #14
0
/*
 * process the -buttonmap string
 */
void initialize_pointer_map(char *pointer_remap) {
#if NO_X11
	if (!pointer_remap) {}
	return;
#else
	unsigned char map[MAX_BUTTONS];
	int i, k;
	/*
	 * This routine counts the number of pointer buttons on the X
	 * server (to avoid problems, even crashes, if a client has more
	 * buttons).  And also initializes any pointer button remapping
	 * from -buttonmap option.
	 */
	
	if (!raw_fb_str) {
		X_LOCK;
		num_buttons = XGetPointerMapping(dpy, map, MAX_BUTTONS);
		X_UNLOCK;
	} else {
		num_buttons = 5;
	}

	if (num_buttons < 0) {
		num_buttons = 0;
	}

	/* FIXME: should use info in map[] */
	for (i=1; i<= MAX_BUTTONS; i++) {
		for (k=0; k < MAX_BUTTON_EVENTS; k++) {
			pointer_map[i][k].end = 1;
		}
		pointer_map[i][0].keysym  = NoSymbol;
		pointer_map[i][0].keycode = NoSymbol;
		pointer_map[i][0].button = i;
		pointer_map[i][0].end    = 0;
		pointer_map[i][0].down   = 0;
		pointer_map[i][0].up     = 0;
	}

	if (pointer_remap && *pointer_remap != '\0') {
		/* -buttonmap, format is like: 12-21=2 */
		char *p, *q, *remap = strdup(pointer_remap);	
		int n;

		if ((p = strchr(remap, '=')) != NULL) {
			/* undocumented max button number */
			n = atoi(p+1);	
			*p = '\0';
			if (n < num_buttons || num_buttons == 0) {
				num_buttons = n;
			} else {
				rfbLog("warning: increasing number of mouse "
				    "buttons from %d to %d\n", num_buttons, n);
				num_buttons = n;
			}
		}
		if ((q = strchr(remap, '-')) != NULL) {
			/*
			 * The '-' separates the 'from' and 'to' lists,
			 * then it is kind of like tr(1).  
			 */
			char str[2];
			int from;

			rfbLog("remapping pointer buttons using string:\n");
			rfbLog("   \"%s\"\n", remap);

			p = remap;
			q++;
			i = 0;
			str[1] = '\0';
			while (*p != '-') {
				str[0] = *p;
				from = atoi(str);
				buttonparse(from, &q);
				p++;
			}
		}
		free(remap);
	}
#endif	/* NO_X11 */
}
Beispiel #15
0
main()
{
      Window w2;

      Display *dpy = XOpenDisplay(NIL);
      assert(dpy);
      Screen *scr = DefaultScreenOfDisplay(dpy);

      // CreateWindow

      Window w = XCreateWindow(dpy, RootWindowOfScreen(scr), 10, 100, 200, 300, 0, CopyFromParent,
			       CopyFromParent, CopyFromParent,
			       0, NIL);

      XDestroyWindow(dpy, w);

      // CreateWindow with arguments

      XSetWindowAttributes swa;
      swa.background_pixel = WhitePixelOfScreen(scr);
      swa.bit_gravity = NorthWestGravity;
      swa.border_pixel = BlackPixelOfScreen(scr);
      swa.colormap = DefaultColormapOfScreen(scr);
      swa.cursor = None;
      swa.win_gravity = NorthGravity;

      w = XCreateWindow(dpy, RootWindowOfScreen(scr), 10, 100, 200, 300, 0, CopyFromParent,
			CopyFromParent, CopyFromParent,
			CWBackPixel | CWBitGravity | CWBorderPixel | CWColormap | CWCursor | CWWinGravity, 
			&swa);
      
      // CreateWindow with other arguments

      XDestroyWindow(dpy, w);

      Pixmap pixmap = XCreatePixmap(dpy, RootWindowOfScreen(scr), 45, 25, DefaultDepthOfScreen(scr));
      assert(pixmap);

      swa.background_pixmap = pixmap;
      swa.border_pixmap = pixmap;

      w = XCreateWindow(dpy, RootWindowOfScreen(scr), 10, 100, 200, 300, 0, CopyFromParent,
			CopyFromParent, CopyFromParent,
			CWBackPixmap | CWBorderPixmap,
			&swa);
      
      // ChangeWindowAttributes

      swa.backing_planes = 0x1;
      swa.backing_pixel = WhitePixelOfScreen(scr);
      swa.save_under = True;
      swa.event_mask = KeyPressMask | KeyReleaseMask;
      swa.do_not_propagate_mask = ButtonPressMask | Button4MotionMask;
      swa.override_redirect = False;
      XChangeWindowAttributes(dpy, w, CWBackingPlanes | CWBackingPixel | CWSaveUnder | CWEventMask
			      | CWDontPropagate | CWOverrideRedirect, &swa);

      // GetWindowAttributes

      XWindowAttributes wa;
      Status success = XGetWindowAttributes(dpy, w, &wa);

      // DestroyWindow (done)

      // DestroySubwindows

      w2 = XCreateWindow(dpy, w, 20, 30, 40, 50, 3, CopyFromParent, CopyFromParent, CopyFromParent, 0, NIL);
      XDestroySubwindows(dpy, w);

      // ChangeSaveSet

//        Display *dpy2 = XOpenDisplay(NIL);
//        assert(dpy2);
//        XAddToSaveSet(dpy2, w);
//        XCloseDisplay(dpy2);

      // ReparentWindow

      w2 = XCreateWindow(dpy, RootWindowOfScreen(scr), 20, 30, 40, 50, 3, 
			 CopyFromParent, CopyFromParent, CopyFromParent, 0, NIL);
      XReparentWindow(dpy, w2, w, 10, 5);

      // MapWindow

      XMapWindow(dpy, w);

      // MapSubwindows
      
      XMapSubwindows(dpy, w);

      // UnmapWindow
      
      XUnmapWindow(dpy, w);

      // UnmapSubwindows

      XMapWindow(dpy, w);
      XUnmapSubwindows(dpy, w2);
      XMapSubwindows(dpy, w);

      // ConfigureWindow

      Window w3 = XCreateWindow(dpy, w, 10, 50, 100, 10, 2,
			 CopyFromParent, CopyFromParent, CopyFromParent, 0, NIL);

      XMapWindow(dpy, w3);

      XWindowChanges wc;
      wc.x = -5;
      wc.y = -10;
      wc.width = 50;
      wc.height = 40;
      wc.border_width = 7;
      wc.sibling = w2;
      wc.stack_mode = Opposite;
      XConfigureWindow(dpy, w3, 
		       CWX | CWY | CWWidth | CWHeight | CWBorderWidth | CWSibling | CWStackMode, 
		       &wc);

      // CirculateWindow

      XCirculateSubwindows(dpy, w, RaiseLowest);

      // GetGeometry

      Window root;
      int x, y;
      unsigned width, height, border_width, depth;
      XGetGeometry(dpy, w, &root, &x, &y, &width, &height, &border_width, &depth);

      // QueryTree

      Window parent;
      Window *children;
      unsigned nchildren;
      success = XQueryTree(dpy, w, &root, &parent, &children, &nchildren);
      XFree(children);

      // InternAtom

      Atom a = XInternAtom(dpy, "WM_PROTOCOLS", True);

      // GetAtomName

      char *string = XGetAtomName(dpy, XA_PRIMARY);
      XFree(string);

      // ChangeProperty

      XStoreName(dpy, w, "test window");

      // DeleteProperty

      XDeleteProperty(dpy, w, XA_WM_NAME);

      // GetProperty
      // TODO

      // ListProperties

      int num_prop;
      Atom *list = XListProperties(dpy, w, &num_prop);
      XFree(list);

      // SetSelectionOwner

      XSetSelectionOwner(dpy, XA_PRIMARY, w, 12000);
      XSetSelectionOwner(dpy, XA_SECONDARY, w, CurrentTime);

      // GetSelectionOwner

      Window wx = XGetSelectionOwner(dpy, XA_PRIMARY);

      // ConvertSelection

      XConvertSelection(dpy, XA_SECONDARY, XA_CURSOR, XA_POINT, w, CurrentTime);

      // SendEvent

      // GrabPointer

      std::cerr << "Grabbing" << std::endl;
      int res = XGrabPointer(dpy, w, False, Button5MotionMask | PointerMotionHintMask,
			     GrabModeSync, GrabModeAsync, w, None, CurrentTime);
      XSync(dpy, False);
//      sleep(5);

      // UngrabPointer

      std::cerr << "Ungrabbing" << std::endl;
      XUngrabPointer(dpy, CurrentTime);

      // GrabButton

      XGrabButton(dpy, 3, ShiftMask | ControlMask, w, False, PointerMotionHintMask | Button2MotionMask, 
		  GrabModeAsync, GrabModeSync, None, None);
		  
      XGrabButton(dpy, 2, AnyModifier, w, False, PointerMotionHintMask | Button2MotionMask, 
		  GrabModeAsync, GrabModeSync, None, None);
		  
      // UngrabButton

      XUngrabButton(dpy, 2, LockMask, w);

      // ChangeActivePointerGrab

      XChangeActivePointerGrab(dpy, ButtonPressMask, None, CurrentTime);

      // GrabKeyboard

      XGrabKeyboard(dpy, w, True, GrabModeSync, GrabModeSync, 12000);

      // UngrabKeyboard

      XUngrabKeyboard(dpy, 13000);

      // GrabKey

      XGrabKey(dpy, XKeysymToKeycode(dpy, XK_Tab), ShiftMask | Mod3Mask, w, True, GrabModeSync,
	       GrabModeSync);

      // UngrabKey

      XUngrabKey(dpy, AnyKey, AnyModifier, w);

      // AllowEvents

      XAllowEvents(dpy, AsyncPointer, 14000);

      // GrabServer

      XGrabServer(dpy);

      // UngrabServer

      XUngrabServer(dpy);

      // QueryPointer

      Window child;
      int root_x, root_y, win_x, win_y;
      unsigned mask;
      Bool bres = XQueryPointer(dpy, w, &root, &child, &root_x, &root_y, &win_x, &win_y, &mask);

      // GetMotionEvents

      int nevents;
      XGetMotionEvents(dpy, w, 15000, 16000, &nevents);

      // TranslateCoordinates

      int dest_x, dest_y;

      XTranslateCoordinates(dpy, w, w2, 10, 20, &dest_x, &dest_y, &child);

      // WarpPointer

      XWarpPointer(dpy, w, w2, 0, 0, 100, 100, 20, 30);

      // SetInputFocus

      XSetInputFocus(dpy,w, RevertToPointerRoot, 17000);
      XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, 17000);

      // GetInputFocus

      Window focus;
      int revert_to;
      XGetInputFocus(dpy, &focus, &revert_to);

      // QueryKeymap

      char keys_return[32];
      XQueryKeymap(dpy, keys_return);

      // OpenFont

      Font fid = XLoadFont(dpy, "cursor");

      // CloseFont

      XUnloadFont(dpy, fid);

      // QueryFont

      XFontStruct *fs = XLoadQueryFont(dpy, "cursor");
      assert(fs);

      // QueryTextExtents

      int direction, font_ascent, font_descent;
      XCharStruct overall;
      XQueryTextExtents(dpy, fs -> fid, "toto", 4, &direction, &font_ascent, &font_descent, &overall);
      XQueryTextExtents(dpy, fs -> fid, "odd__length", 11, &direction, &font_ascent, &font_descent, &overall);

      XChar2b c2bs;
      c2bs.byte1 = '$';
      c2bs.byte2 = 'B';
      XQueryTextExtents16(dpy, fs -> fid, &c2bs, 1, &direction, &font_ascent, &font_descent, &overall);

      XQueryTextExtents(dpy, fs -> fid, longString, strlen(longString), &direction, &font_ascent, 
			&font_descent, &overall);

      // ListFonts

      int actual_count;
      char **fontList = XListFonts(dpy, "*", 100, &actual_count);
      XFree((char *)fontList);

      // ListFontsWithInfo

      int count;
      XFontStruct *info;
      char **names = XListFontsWithInfo(dpy, "*", 100, &count, &info);
      XFreeFontInfo(names, info, count);

      // SetFontPath
      // GetFontPath

      int npaths;
      char **charList = XGetFontPath(dpy, &npaths);

      char **charList2 = new char *[npaths + 1];
      memcpy(charList2, charList, npaths * sizeof(char *));
      charList2[npaths] = charList2[0];

      XSetFontPath(dpy, charList2, npaths + 1);
      XSetFontPath(dpy, charList, npaths); // Reset to some reasonnable value

      XFreeFontPath(charList);
      delete [] charList2;

      // CreatePixmap

      Pixmap pix2 = XCreatePixmap(dpy, w, 100, 200, DefaultDepthOfScreen(scr));

      // FreePixmap

      XFreePixmap(dpy, pix2);

      // CreateGC

      Pixmap bitmap = XCreateBitmapFromData(dpy, RootWindowOfScreen(scr), 
					    "\000\000\001\000\000\001\000\000\001\377\377\377", 3, 4);

      XGCValues gcv;
      gcv.function = GXand;
      gcv.plane_mask = 0x1;
      gcv.foreground = WhitePixelOfScreen(scr);
      gcv.background = BlackPixelOfScreen(scr);
      gcv.line_width = 2;
      gcv.line_style = LineDoubleDash;
      gcv.cap_style = CapProjecting;
      gcv.join_style = JoinRound;
      gcv.fill_style = FillStippled;
      gcv.fill_rule = EvenOddRule;
      gcv.arc_mode = ArcPieSlice;
      gcv.tile = pixmap;
      gcv.stipple = bitmap;
      gcv.ts_x_origin = 3;
      gcv.ts_y_origin = 4;
      gcv.font = fs -> fid;
      gcv.subwindow_mode = ClipByChildren;
      gcv.graphics_exposures = True;
      gcv.clip_x_origin = 5;
      gcv.clip_y_origin = 6;
      gcv.clip_mask = bitmap;
      gcv.dash_offset = 1;
      gcv.dashes = 0xc2;
      
      GC gc = XCreateGC(dpy, w, 
			  GCFunction | GCPlaneMask | GCForeground | GCBackground | GCLineWidth
			| GCLineStyle | GCCapStyle | GCJoinStyle | GCFillStyle | GCFillRule | GCTile
			| GCStipple | GCTileStipXOrigin | GCTileStipYOrigin | GCFont | GCSubwindowMode
			| GCGraphicsExposures | GCClipXOrigin | GCClipYOrigin | GCClipMask | GCDashOffset
			| GCDashList | GCArcMode,
			&gcv);

      // ChangeGC

      gcv.function = GXandReverse;

      // Only a few of these should appear, since the values are cached on the client side by the Xlib.

      XChangeGC(dpy, gc, GCFunction | GCLineStyle | GCStipple | GCGraphicsExposures | GCDashList, &gcv);

      // CopyGC
      
      GC gc2 = XCreateGC(dpy, w, 0, NIL);
      XCopyGC(dpy, gc, GCFunction | GCLineStyle | GCStipple | GCGraphicsExposures | GCDashList, gc2);

      // SetDashes

      XSetDashes(dpy, gc, 3, "\001\377\001", 3);

      // SetClipRectangles

      XRectangle rectangles[] = { { 10, 20, 30, 40 }, { 100, 200, 5, 3 }, { -5, 1, 12, 24 } };
      XSetClipRectangles(dpy, gc, 12, 9, rectangles, SIZEOF(rectangles), Unsorted);

      // FreeGC

	    // done already

      // ClearArea

      XClearArea(dpy, w, 30, 10, 10, 100, False);

      // CopyArea

      XCopyArea(dpy, w, pixmap, gc, 0, 0, 100, 100, 10, 10);

      // CopyPlane

      // This won't work if the Screen doesn't have at least 3 planes
      XCopyPlane(dpy, pixmap, w, gc, 20, 10, 40, 30, 0, 0, 0x4);

      // PolyPoint

      XDrawPoint(dpy, w, gc, 1, 2);

      XPoint points[] = { { 3, 4 }, { 5, 6 } };
      XDrawPoints(dpy, w, gc, points, SIZEOF(points), CoordModeOrigin);

      // PolyLine

      XDrawLines(dpy, w, gc, points, SIZEOF(points), CoordModePrevious);

      // PolySegment

      XSegment segments[] = { { 7, 8, 9, 10 }, { 11, 12, 13, 14 }, { 15, 16, 17, 18 } };
      XDrawSegments(dpy, w, gc, segments, SIZEOF(segments));

      // PolyRectangle

      XDrawRectangles(dpy, w, gc, rectangles, SIZEOF(rectangles));

      // PolyArc

      XArc arcs[] = { { 10, 20, 30, 40, 50, 60 }, { -70, 80, 90, 100, 110, 120 }, 
		      { 10, 20, 30, 40, 50, -30 } };

      XDrawArcs(dpy, w, gc, arcs, SIZEOF(arcs));

      // FillPoly

      XFillPolygon(dpy, w, gc, points, SIZEOF(points), Convex, CoordModePrevious);

      // PolyFillRectangle
      
      XFillRectangles(dpy, w, gc, rectangles, SIZEOF(rectangles));

      // PolyFillArc
      
      XFillArcs(dpy, w, gc, arcs, SIZEOF(arcs));

      // PutImage
      // GetImage

      XImage *image = XGetImage(dpy, w, 10, 20, 40, 30, AllPlanes, ZPixmap);
      XPutImage(dpy, w, gc, image, 0, 0, 50, 60, 40, 30);
      XSync(dpy, False); // Make the next request starts at the beginning of a packet

      // PolyText8
      XTextItem textItems[3];
      textItems[0].chars = "toto";
      textItems[0].nchars = strlen(textItems[0].chars);
      textItems[0].delta = -3;
      textItems[0].font = fs->fid;
      textItems[1].chars = "titi";
      textItems[1].nchars = strlen(textItems[1].chars);
      textItems[1].delta = 3;
      textItems[1].font = None;
      textItems[2].chars = "tutu";
      textItems[2].nchars = strlen(textItems[2].chars);
      textItems[2].delta = 0;
      textItems[2].font = fs->fid;

      XDrawText(dpy, w, gc, 10, 10, textItems, 3);


      XTextItem textItems2[3];
      textItems2[0].chars = "totox";
      textItems2[0].nchars = strlen(textItems2[0].chars);
      textItems2[0].delta = -3;
      textItems2[0].font = fs->fid;
      textItems2[1].chars = "titi";
      textItems2[1].nchars = strlen(textItems2[1].chars);
      textItems2[1].delta = 3;
      textItems2[1].font = None;
      textItems2[2].chars = "tutu";
      textItems2[2].nchars = strlen(textItems2[2].chars);
      textItems2[2].delta = 0;
      textItems2[2].font = fs->fid;

      XDrawText(dpy, w, gc, 10, 10, textItems2, 3);

      // PolyText16

      XChar2b c2b2[] = { 0, 't', 0, 'x' };

      XTextItem16 items16[] = { { &c2bs, 1, -5, None }, { NULL, 0, 0, None }, { c2b2, 2, 0, fs -> fid } };
      XDrawText16(dpy, w, gc, 10, 0, items16, SIZEOF(items16));

      // ImageText8

      XDrawImageString(dpy, w, gc, 10, 10, "toto", 4);

      // ImageText16

      XDrawImageString16(dpy, w, gc, 10, 10, &c2bs, 1);
      XDrawImageString16(dpy, w, gc, 10, 20, c2b2, 2);

      // CreateColormap
      // Don't forget to tell the kids how it was when we had only 8 bits per pixel.

      Colormap colormap = XCreateColormap(dpy, w, DefaultVisualOfScreen(scr), None);

      // FreeColormap

      XFreeColormap(dpy, colormap);
      colormap = XCreateColormap(dpy, w, DefaultVisualOfScreen(scr), None);

      // CopyColormapAndFree

      Colormap colormap2 = XCopyColormapAndFree(dpy, colormap);

      // InstallColormap

      XInstallColormap(dpy, colormap2);

      // UninstallColormap

      XUninstallColormap(dpy, colormap2);

      // ListInstalledColormaps

      int num;
      Colormap *colormapList = XListInstalledColormaps(dpy, w, &num);

      // AllocColor

      XColor screen;
      screen.red = 0;
      screen.green = 32767;
      screen.blue = 65535;
      screen.flags = DoRed | DoGreen | DoBlue;
      success = XAllocColor(dpy, colormap, &screen);

      // AllocNamedColor

      XColor screen2, exact;
      success = XAllocNamedColor(dpy, colormap, "Wheat", &screen2, &exact);

      // AllocColorCells

      unsigned long plane_masks, pixels;
      success = XAllocColorCells(dpy, colormap, False, &plane_masks, 1, &pixels, 1);

      // AllocColorPlanes

      unsigned long rmask, gmask, bmask;
      success = XAllocColorPlanes(dpy, colormap, False, &pixels, 1, 0, 0, 0, &rmask, &gmask, &bmask);

      // FreeColors

      unsigned long pixels2[2] = { screen.pixel, screen2.pixel };
      XFreeColors(dpy, colormap, pixels2, 2, 0);

      // StoreColors

      success = XAllocColorCells(dpy, colormap, False, NIL, 0, pixels2, 2);

      // On many contemporary (that is, year 2000) video cards, you can't allocate read / write cells
      // I want my requests to be sent, however.
      if (!success) {
	    XSetErrorHandler(errorHandler);
      }

      XColor colors[2];
      colors[0] = screen;  colors[0].pixel = pixels2[0];
      colors[1] = screen2; colors[1].pixel = pixels2[1];
      XStoreColors(dpy, colormap, colors, 2);

      // StoreNamedColor

      XStoreNamedColor(dpy, colormap, "Wheat", colors[0].pixel, DoBlue);

      XSync(dpy, False);
      XSetErrorHandler(NIL); // Restore the default handler

      // QueryColors

      screen2.pixel = WhitePixelOfScreen(scr);
      XQueryColor(dpy, colormap, &screen2);

      // LookupColor

      success = XLookupColor(dpy, colormap, "DarkCyan", &exact, &screen);

      // CreateCursor

      Cursor cursor = XCreatePixmapCursor(dpy, pixmap, None, &exact, colors, 10, 10);

      // CreateGlyphCursor
      
      Cursor cursor2 = XCreateGlyphCursor(dpy, fs -> fid, fs -> fid, 'X', 0, &exact, colors);

      // FreeCursor
      
      XFreeCursor(dpy, cursor2);

      // RecolorCursor

      XRecolorCursor(dpy, cursor, colors, &exact);

      // QueryBestSize

      success = XQueryBestSize(dpy, CursorShape, RootWindowOfScreen(scr), 100, 20, &width, &height);

      // QueryExtension

      int major_opcode, first_event, first_error;
      XQueryExtension(dpy, "toto", &major_opcode, &first_event, &first_error);

      // ListExtensions

      int nextensions;
      char **extensionList = XListExtensions(dpy, &nextensions);
      for(char **p = extensionList; nextensions; nextensions--, p++) std::cout << *p << std::endl;
      XFree(extensionList);

      // ChangeKeyboardMapping
      // GetKeyboardMapping

      int min_keycodes, max_keycodes;
      XDisplayKeycodes(dpy, &min_keycodes, &max_keycodes);

      int keysyms_per_keycode;
      KeySym *keysyms = XGetKeyboardMapping(dpy, min_keycodes, max_keycodes - min_keycodes + 1,
					    &keysyms_per_keycode);
      XChangeKeyboardMapping(dpy, min_keycodes, keysyms_per_keycode, keysyms, 
			     max_keycodes - min_keycodes + 1);

      // ChangeKeyboardControl
      // GetKeyboardControl

      XKeyboardState keyboardState;
      XGetKeyboardControl(dpy, &keyboardState);

      XKeyboardControl keyboardValues;
      keyboardValues.key_click_percent = keyboardState.key_click_percent;
      keyboardValues.bell_percent = keyboardState.bell_percent;
      keyboardValues.bell_pitch = keyboardState.bell_pitch;
      keyboardValues.bell_duration = keyboardState.bell_duration;
      keyboardValues.led = 1;
      keyboardValues.led_mode = LedModeOn;
      keyboardValues.key = min_keycodes;
      keyboardValues.auto_repeat_mode = AutoRepeatModeDefault;
      XChangeKeyboardControl(dpy, 
			       KBKeyClickPercent | KBBellPercent | KBBellPitch | KBBellDuration
			     | KBLed | KBLedMode | KBKey | KBAutoRepeatMode,
			     &keyboardValues);

      // Bell

      XBell(dpy, 90);

      // ChangePointerControl
      // GetPointerControl

      int accel_numerator, accel_denominator, threshold;
      XGetPointerControl(dpy, &accel_numerator, &accel_denominator, &threshold);

      XChangePointerControl(dpy, True, True, accel_numerator, accel_denominator, threshold);

      // SetScreenSaver
      // GetScreenSaver

      int timeout, interval, prefer_blanking, allow_exposures;
      XGetScreenSaver(dpy, &timeout, &interval, &prefer_blanking, &allow_exposures);
      XSetScreenSaver(dpy, timeout, interval, prefer_blanking, allow_exposures);

      // ChangeHosts
      // ListHosts

      int nhosts;
      Bool state;
      XHostAddress *hostList = XListHosts(dpy, &nhosts, &state);

      XHostAddress host;
      host.family = FamilyInternet;
      host.length = 4;
      host.address = "\001\002\003\004";
      XAddHost(dpy, &host);

      // SetAccessControl

      XSetAccessControl(dpy, EnableAccess);

      // SetCloseDownMode

      XSetCloseDownMode(dpy, RetainTemporary);

      // KillClient

      XKillClient(dpy, AllTemporary);

      // RotateProperties

      Atom properties[] = { XInternAtom(dpy, "CUT_BUFFER0", False), 
			    XInternAtom(dpy, "CUT_BUFFER1", False),
			    XInternAtom(dpy, "CUT_BUFFER2", False) };
      XRotateWindowProperties(dpy, RootWindowOfScreen(scr), properties, SIZEOF(properties), -1);

      // ForceScreenSaver

      XForceScreenSaver(dpy, ScreenSaverReset);

      // SetPointerMapping
      // GetPointerMapping

      unsigned char map[64];
      int map_length = XGetPointerMapping(dpy, map, 64);
      XSetPointerMapping(dpy, map, map_length);

      // SetModifierMapping
      // GetModifierMapping

      XModifierKeymap *modmap = XGetModifierMapping(dpy);
      XSetModifierMapping(dpy, modmap);

      // NoOperation

      XNoOp(dpy);

      for(;;) {
	    XEvent e;
	    XNextEvent(dpy, &e);
	    std::cout << "Got an event of type " << e.type << std::endl;
      }
}
Beispiel #16
0
static Bool
init_x11( char * error_buf )
{
	/*XXX*/ /* Namely, support for -display host:0.0 etc. */
	XrmQuark common_quarks_list[20];  /*XXX change number of elements if necessary */
	XrmQuarkList ql = common_quarks_list;
	XGCValues gcv;
	char *common_quarks =
		"String."
		"Blinkinvisibletime.blinkinvisibletime."
		"Blinkvisibletime.blinkvisibletime."
		"Clicktimeframe.clicktimeframe."
		"Doubleclicktimeframe.doubleclicktimeframe."
		"Wheeldown.wheeldown."
		"Wheelup.wheelup."
		"Submenudelay.submenudelay."
		"Scrollfirst.scrollfirst."
		"Scrollnext.scrollnext";

	char * atom_names[AI_count] = {
		"RESOLUTION_X",
		"RESOLUTION_Y",
		"PIXEL_SIZE",
		"SPACING",
		"RELATIVE_WEIGHT",
		"FOUNDRY",
		"AVERAGE_WIDTH",
		"CHARSET_REGISTRY",
		"CHARSET_ENCODING",
		"CREATE_EVENT",
		"WM_DELETE_WINDOW",
		"WM_PROTOCOLS",
		"WM_TAKE_FOCUS",
		"_NET_WM_STATE",
		"_NET_WM_STATE_SKIP_TASKBAR",
		"_NET_WM_STATE_MAXIMIZED_VERT",
		"_NET_WM_STATE_MAXIMIZED_HORZ",
		"_NET_WM_NAME",
		"_NET_WM_ICON_NAME",
		"UTF8_STRING",
		"TARGETS",
		"INCR",
		"PIXEL",
		"FOREGROUND",
		"BACKGROUND",
		"_MOTIF_WM_HINTS",
		"_NET_WM_STATE_MODAL",
		"_NET_SUPPORTED",
		"_NET_WM_STATE_MAXIMIZED_HORIZ",
		"text/plain;charset=UTF-8",
		"_NET_WM_STATE_STAYS_ON_TOP",
		"_NET_CURRENT_DESKTOP",
		"_NET_WORKAREA",
		"_NET_WM_STATE_ABOVE"
	};
	char hostname_buf[256], *hostname = hostname_buf;

	guts. click_time_frame = 200;
	guts. double_click_time_frame = 200;
	guts. visible_timeout = 500;
	guts. invisible_timeout = 500;
	guts. insert = true;
	guts. last_time = CurrentTime;

	guts. ri_head = guts. ri_tail = 0;
	DISP = XOpenDisplay( do_display);
	
	if (!DISP) {
		char * disp = getenv("DISPLAY");
		snprintf( error_buf, 256, "Error: Can't open display '%s'", 
					do_display ? do_display : (disp ? disp : ""));
		free( do_display);
		do_display = nil;
		return false;
	}
	free( do_display);
	do_display = nil;
	XSetErrorHandler( x_error_handler);
	guts.main_error_handler = x_error_handler;
	(void)x_io_error_handler;
	XCHECKPOINT;
	guts.connection = ConnectionNumber( DISP);

	{
		struct sockaddr name;
		unsigned int l = sizeof( name);
		guts. local_connection = getsockname( guts.connection, &name, &l) >= 0 && l == 0;
	}
	
#ifdef HAVE_X11_EXTENSIONS_SHAPE_H
	if ( XShapeQueryExtension( DISP, &guts.shape_event, &guts.shape_error)) {
		guts. shape_extension = true;
	} else {
		guts. shape_extension = false;
	}
#else
	guts. shape_extension = false;
#endif
#ifdef USE_MITSHM
	if ( !do_no_shmem && XShmQueryExtension( DISP)) {
		guts. shared_image_extension = true;
		guts. shared_image_completion_event = XShmGetEventBase( DISP) + ShmCompletion;
	} else {
		guts. shared_image_extension = false;
		guts. shared_image_completion_event = -1;
	}
#else
	guts. shared_image_extension = false;
	guts. shared_image_completion_event = -1;
#endif
	guts. randr_extension = false;
#ifdef HAVE_X11_EXTENSIONS_XRANDR_H
	{
		int dummy;
		if ( XRRQueryExtension( DISP, &dummy, &dummy))
			guts. randr_extension = true;
	}	 
#endif
#ifdef HAVE_X11_EXTENSIONS_XRENDER_H
	{
		int dummy;
		if ( XRenderQueryExtension( DISP, &dummy, &dummy))
			guts. render_extension = true;
	}	 
#endif
#ifdef HAVE_X11_EXTENSIONS_XCOMPOSITE_H
	{
		int dummy;
		if (XQueryExtension(DISP, COMPOSITE_NAME, &guts.composite_opcode, &dummy, &dummy))
			guts. composite_extension = true;
	}	 
#endif
	XrmInitialize();
	guts.db = get_database();
	XrmStringToQuarkList( common_quarks, common_quarks_list);
	guts.qString = *ql++;
	guts.qBlinkinvisibletime = *ql++;
	guts.qblinkinvisibletime = *ql++;
	guts.qBlinkvisibletime = *ql++;
	guts.qblinkvisibletime = *ql++;
	guts.qClicktimeframe = *ql++;
	guts.qclicktimeframe = *ql++;
	guts.qDoubleclicktimeframe = *ql++;
	guts.qdoubleclicktimeframe = *ql++;
	guts.qWheeldown = *ql++;
	guts.qwheeldown = *ql++;
	guts.qWheelup = *ql++;
	guts.qwheelup = *ql++;
	guts.qSubmenudelay = *ql++;
	guts.qsubmenudelay = *ql++;
	guts.qScrollfirst = *ql++;
	guts.qscrollfirst = *ql++;
	guts.qScrollnext = *ql++;
	guts.qscrollnext = *ql++;

	guts. mouse_buttons = XGetPointerMapping( DISP, guts. buttons_map, 256);
	XCHECKPOINT;

	guts. limits. request_length = XMaxRequestSize( DISP);
	guts. limits. XDrawLines = guts. limits. request_length - 3;
	guts. limits. XFillPolygon = guts. limits. request_length - 4;
	guts. limits. XDrawSegments = (guts. limits. request_length - 3) / 2;
	guts. limits. XDrawRectangles = (guts. limits. request_length - 3) / 2;
	guts. limits. XFillRectangles = (guts. limits. request_length - 3) / 2;
	guts. limits. XFillArcs =
		guts. limits. XDrawArcs = (guts. limits. request_length - 3) / 3;
	XCHECKPOINT;
	SCREEN = DefaultScreen( DISP);

	/* XXX - return code? */
	guts. root = RootWindow( DISP, SCREEN);
	guts. displaySize. x = DisplayWidth( DISP, SCREEN);
	guts. displaySize. y = DisplayHeight( DISP, SCREEN);
	XQueryBestCursor( DISP, guts. root,
							guts. displaySize. x,     /* :-) */
							guts. displaySize. y,
							&guts. cursor_width,
							&guts. cursor_height);
	XCHECKPOINT;
	
	TAILQ_INIT( &guts.paintq);
	TAILQ_INIT( &guts.peventq);
	TAILQ_INIT( &guts.bitmap_gc_pool);
	TAILQ_INIT( &guts.screen_gc_pool);
	TAILQ_INIT( &guts.argb_gc_pool);

	guts. currentFocusTime = CurrentTime;
	guts. windows = hash_create();
	guts. menu_windows = hash_create();
	guts. ximages = hash_create();
	gcv. graphics_exposures = false;
	guts. menugc = XCreateGC( DISP, guts. root, GCGraphicsExposures, &gcv);
	guts. resolution. x = 25.4 * guts. displaySize. x / DisplayWidthMM( DISP, SCREEN) + .5;
	guts. resolution. y = 25.4 * DisplayHeight( DISP, SCREEN) / DisplayHeightMM( DISP, SCREEN) + .5;
	guts. depth = DefaultDepth( DISP, SCREEN);
	guts. idepth = get_idepth();
	if ( guts.depth == 1) guts. qdepth = 1; else
	if ( guts.depth <= 4) guts. qdepth = 4; else
	if ( guts.depth <= 8) guts. qdepth = 8; else
		guts. qdepth = 24;
	guts. byte_order = ImageByteOrder( DISP);
	guts. bit_order = BitmapBitOrder( DISP);
	if ( BYTEORDER == LSB32 || BYTEORDER == LSB64)
		guts. machine_byte_order = LSBFirst;
	else if ( BYTEORDER == MSB32 || BYTEORDER == MSB64)
		guts. machine_byte_order = MSBFirst;
	else {
		sprintf( error_buf, "UAA_001: weird machine byte order: %08x", BYTEORDER);
		return false;
	}  

	XInternAtoms( DISP, atom_names, AI_count, 0, guts. atoms);

	guts. null_pointer = nilHandle;
	guts. pointer_invisible_count = 0;
	guts. files = plist_create( 16, 16);
	prima_rebuild_watchers();
	guts. wm_event_timeout = 100;
	guts. menu_timeout = 200;
	guts. scroll_first = 200;
	guts. scroll_next = 50;
	apc_timer_create( CURSOR_TIMER);
	apc_timer_set_timeout(CURSOR_TIMER, 2);
	apc_timer_create( MENU_TIMER);
	apc_timer_set_timeout( MENU_TIMER,  guts. menu_timeout);
	apc_timer_create( MENU_UNFOCUS_TIMER);
	apc_timer_set_timeout( MENU_UNFOCUS_TIMER, 50);
	if ( !prima_init_clipboard_subsystem( error_buf)) return false;
	if ( !prima_init_color_subsystem( error_buf)) return false;
	if ( !prima_init_font_subsystem( error_buf)) return false;
#ifdef WITH_GTK2
	if (!prima_gtk_init()) return false;
#endif
	bzero( &guts. cursor_gcv, sizeof( guts. cursor_gcv));
	guts. cursor_gcv. cap_style = CapButt;
	guts. cursor_gcv. function = GXcopy;

	gethostname( hostname, 256);
	hostname[255] = '\0';
	XStringListToTextProperty((char **)&hostname, 1, &guts. hostname);
	
	guts. net_wm_maximization = prima_wm_net_state_read_maximization( guts. root, NET_SUPPORTED);

	if ( do_sync) XSynchronize( DISP, true);
	return true;
}
Beispiel #17
0
void Application::initialize ( int *argcp, char **argv )
{
    DebugPrintf(2, "Application::initialize(%p %d, %p)\n", argcp, *argcp, argv);

    DebugPrintf(3, "Application::initialize - Initializing privileges.\n");

    // The Solaris sendmail operates differently than the HP/IBM sendmail. 
    // sendmail on Solaris runs as 'root' and so has access permissions 
    // to any file on the system. sendmail on HP/IBM runs as set-group-id 
    // 'mail' and so requires that all mailboxes that it may deliver e-mail 
    // to be writable either by being group mail group writable, or by being 
    // writable by the world. On those platforms, then, dtmail is required 
    // to always run with set-group-id mail otherwise, when mailboxes are 
    // saved, they will loose their group ownership and sendmail will no 
    // onger be able to deliver to those mailboxes.

    // we have to be set-gid to group "mail" when opening and storing
    // folders.  But we don't want to do everything as group mail.
    // here we record our original gid, and set the effective gid
    // back the the real gid.  We'll set it back when we're dealing
    // with folders...
    //
    _originalEgid = getegid();	// remember effective group ID
    _originalRgid = getgid();	// remember real group ID
    disableGroupPrivileges();	// disable group privileges from here on

    DebugPrintf(3, "Application::initialize - Initializing Xt.\n");

    _w = XtOpenApplication (
			&_appContext, 
			_applicationClass, 
			(XrmOptionDescList) NULL, 0, 
			argcp, argv, ApplicationFallbacks,
			sessionShellWidgetClass, (ArgList) NULL, 0 );
    
    // Extract and save a pointer to the X display structure
    DebugPrintf(3, "Application::initialize - Extracting display.\n");
    _display = XtDisplay ( _w );

    // Set virtual BMenu mouse binding
    int numButtons = XGetPointerMapping(_display, (unsigned char *)NULL, 0);
    _bMenuButton = (numButtons < 3) ? Button2 : Button3;
    
    // The Application class is less likely to need to handle
    // "surprise" widget destruction than other classes, but
    // we might as well install a callback to be safe and consistent
    DebugPrintf(3, "Application::initialize - Installing destroy handler.\n");
    installDestroyHandler();
    
    // Center the shell, and make sure it isn't visible
    DebugPrintf(3, "Application::initialize - Setting window size.\n");
    XtVaSetValues ( _w,
		   XmNmappedWhenManaged, FALSE,
		   XmNx, DisplayWidth ( _display, 0 ) / 2,
		   XmNy, DisplayHeight ( _display, 0 ) / 2,
		   XmNwidth,  1,
		   XmNheight, 1,
		   NULL );
    
    // The instance name of this object was set in the UIComponent 
    // constructor, before the name of the program was available
    // Free the old name and reset it to argv[0]
    DebugPrintf(3, "Application::initialize - Deleting name %p\n", _name);
    free(_name);
    _name = strdup ( argv[0] );

    // Force the shell window to exist so dialogs popped up from
    // this shell behave correctly
    DebugPrintf(3, "Application::initialize - Realizing shell window.\n");
    XtRealizeWidget ( _w );
    
    getResources(_appResources, XtNumber(_appResources));

    // Initialize and manage any windows registered
    // with this application.
    
    for ( int i = 0; i < _numWindows; i++ )
    {
	DebugPrintf(3, "Application::initialize - Initializing windows[%d]\n", i);
	_windows[i]->initialize();
	DebugPrintf(3, "Application::initialize - Managing windows[%d]\n", i);
	_windows[i]->manage();
    }
}
Beispiel #18
0
static void 
do_pointer(char *line, int len)
{
    int n;
    int i;
    unsigned long val;
    union op *uop;
    struct op_pointer *opp;
    unsigned char buttons[MAXBUTTONCODES];
    int nbuttons;
    char *strval;
    Bool ok;

    if (len < 2 || !line || *line == '\0') {  /* =1 minimum */
	badmsg0 ("buttons input line");
	return;
    }

    nbuttons = XGetPointerMapping (dpy, buttons, MAXBUTTONCODES);

    n = skip_space (line, len);
    line += n, len -= n;

    if (line[0] != '=') {
	badmsg0 ("buttons pointer code list, missing equal sign");
	return;
    }

    line++, len--;			/* skip = */
    n = skip_space (line, len);
    line += n, len -= n;

    i = 0;
    if (len < 7 || strncasecmp (line, "default", 7) != 0) {
	while (len > 0) {
	    n = skip_space (line, len);
	    line += n, len -= n;
	    if (line[0] == '\0') break;
	    n = skip_word (line, len);
	    if (n < 1) {
		badmsg ("skip of word in buttons line:  %s", line);
		return;
	    }
	    strval = copy_to_scratch(line, n);
	    ok = parse_number (strval, &val);
	    if (!ok || val >= MAXBUTTONCODES) {
		badmsg ("value %s given for buttons list", strval);
		return;
	    }
	    buttons[i++] = (unsigned char) val;
	    line += n, len -= n;
	}
    }
    
    if (i > 0 && i != nbuttons) {
	fprintf (stderr, "Warning: Only changing the first %d of %d buttons.\n",
		 i, nbuttons);
	i = nbuttons;
    }

    uop = AllocStruct (union op);
    if (!uop) {
	badmsg ("attempt to allocate a %ld byte pointer opcode",
		(long) sizeof (struct op_pointer));
	return;
    }
    opp = &uop->pointer;

    opp->type = doPointer;
    opp->count = i;
    for (i = 0; i < opp->count; i++) {
	opp->button_codes[i] = buttons[i];
    }

    add_to_work_queue (uop);
}