Пример #1
0
void grab_keys(int mk, int uk, int dk,
	       int mm, int um, int dm,
	       int step) {
  Display* disp = GDK_DISPLAY();

  // ungrab any previous keys
  XUngrabKey(disp, AnyKey, AnyModifier, GDK_ROOT_WINDOW());

  volMuteKey = mk;
  volUpKey = uk;
  volDownKey = dk;
  volMuteMods = mm;
  volUpMods = um;
  volDownMods = dm;
  volStep = step;

  if (mk < 0 &&
      uk < 0 &&
      dk < 0)
    return;
  
  xErr = 0;
  errBuf = g_malloc(errBufSize*sizeof(gchar));
  printBuf = errBuf + snprintf(errBuf,errBufSize,_("Could not bind the following hotkeys:\n"));
  errBufSize -= (printBuf - errBuf);

  if (muteSymStr) g_free(muteSymStr);
  if (upSymStr)   g_free(upSymStr);
  if (downSymStr) g_free(downSymStr);
  muteSymStr = gtk_accelerator_name(XkbKeycodeToKeysym(GDK_DISPLAY(), volMuteKey, 0, 0),volMuteMods);
  upSymStr = gtk_accelerator_name(XkbKeycodeToKeysym(GDK_DISPLAY(),volUpKey,0, 0),volUpMods);
  downSymStr = gtk_accelerator_name(XkbKeycodeToKeysym(GDK_DISPLAY(), volDownKey, 0, 0),volDownMods);

  XErrorHandler old_hdlr = XSetErrorHandler(errhdl);
  if (volMuteKey > 0) {
    muteSerial = NextRequest(disp);
    XGrabKey(disp,volMuteKey,volMuteMods,GDK_ROOT_WINDOW(),1,GrabModeAsync,GrabModeAsync);
  }

  if (volUpKey > 0) {
    upSerial = NextRequest(disp);
    XGrabKey(disp,volUpKey,volUpMods,GDK_ROOT_WINDOW(),1,GrabModeAsync,GrabModeAsync);
  }

  if (volDownKey > 0) {
    downSerial = NextRequest(disp);
    XGrabKey(disp,volDownKey,volDownMods,GDK_ROOT_WINDOW(),1,GrabModeAsync,GrabModeAsync);
  }

  XFlush(disp);
  XSync(disp, False);
  (void) XSetErrorHandler(old_hdlr);
  
  if (xErr) 
    g_idle_add(idle_report_error, NULL);
  else
    g_free(errBuf);
}
Пример #2
0
void
FinishX(Display* aDisplay)
{
  unsigned long lastRequest = NextRequest(aDisplay) - 1;
  if (lastRequest == LastKnownRequestProcessed(aDisplay))
    return;

  XSync(aDisplay, False);
}
static int
XhivIOError(Display *dpy) {
    fprintf(stderr, "XIO:  fatal IO error %d (%s) on X server \"%s\"\r\n",
            errno, strerror (errno), DisplayString (dpy));
    fprintf (stderr,
         "      after %lu requests (%lu known processed) with %d events remaining.\r\n",
             NextRequest(dpy) - 1, LastKnownRequestProcessed(dpy),
             QLength(dpy));
    abort();
}
Пример #4
0
GdkGrabStatus
gdk_keyboard_grab (GdkWindow *	   window,
		   gboolean	   owner_events,
		   guint32	   time)
{
  gint return_val;
  unsigned long serial;
  GdkDisplay *display;
  GdkDisplayX11 *display_x11;
  GdkWindow *native;

  g_return_val_if_fail (window != NULL, 0);
  g_return_val_if_fail (GDK_IS_WINDOW (window), 0);

  native = gdk_window_get_toplevel (window);

  /* TODO: What do we do for offscreens and  children? We need to proxy the grab somehow */
  if (!GDK_IS_WINDOW_IMPL_X11 (GDK_WINDOW_OBJECT (native)->impl))
    return GDK_GRAB_SUCCESS;

  display = GDK_WINDOW_DISPLAY (native);
  display_x11 = GDK_DISPLAY_X11 (display);

  serial = NextRequest (GDK_WINDOW_XDISPLAY (native));

  if (!GDK_WINDOW_DESTROYED (native))
    {
#ifdef G_ENABLE_DEBUG
      if (_gdk_debug_flags & GDK_DEBUG_NOGRABS)
	return_val = GrabSuccess;
      else
#endif
	return_val = XGrabKeyboard (GDK_WINDOW_XDISPLAY (native),
				    GDK_WINDOW_XID (native),
				    owner_events,
				    GrabModeAsync, GrabModeAsync,
				    time);
	if (G_UNLIKELY (!display_x11->trusted_client && 
			return_val == AlreadyGrabbed))
	  /* we can't grab the keyboard, but we can do a GTK-local grab */
	  return_val = GrabSuccess;
    }
  else
    return_val = AlreadyGrabbed;

  if (return_val == GrabSuccess)
    _gdk_display_set_has_keyboard_grab (display,
					window,	native,
					owner_events,
					serial, time);

  return gdk_x11_convert_grab_status (return_val);
}
Пример #5
0
/* Find oldest possible serial for an outstanding expose event
 */
static gulong
find_current_serial (Display *xdisplay)
{
  XEvent xev;
  gulong serial = NextRequest (xdisplay);
  
  XSync (xdisplay, False);

  XCheckIfEvent (xdisplay, &xev, expose_serial_predicate, (XPointer)&serial);

  return serial;
}
Пример #6
0
void
Tk_Ungrab(
    Tk_Window tkwin)		/* Window whose grab should be released. */
{
    TkDisplay *dispPtr;
    TkWindow *grabWinPtr, *winPtr;
    unsigned int serial;

    grabWinPtr = (TkWindow *) tkwin;
    dispPtr = grabWinPtr->dispPtr;
    if (grabWinPtr != dispPtr->eventualGrabWinPtr) {
	return;
    }
    ReleaseButtonGrab(dispPtr);
    QueueGrabWindowChange(dispPtr, NULL);
    if (dispPtr->grabFlags & (GRAB_GLOBAL|GRAB_TEMP_GLOBAL)) {
	dispPtr->grabFlags &= ~(GRAB_GLOBAL|GRAB_TEMP_GLOBAL);
	serial = NextRequest(dispPtr->display);
	XUngrabPointer(dispPtr->display, CurrentTime);
	XUngrabKeyboard(dispPtr->display, CurrentTime);
	EatGrabEvents(dispPtr, serial);
    }

    /*
     * Generate events to move the pointer back to the window where it really
     * is. Some notes:
     * 1. As with grabs, only do this if the "real" window is not a descendant
     *    of the grab window, since in this case the pointer is already where
     *    it's supposed to be.
     * 2. If the "real" window is in some other application then don't
     *    generate any events at all, since everything's already been reported
     *    correctly.
     * 3. Only generate enter events. Don't generate leave events, because we
     *    never told the lower-level windows that they had the pointer in the
     *    first place.
     */

    for (winPtr = dispPtr->serverWinPtr; ; winPtr = winPtr->parentPtr) {
	if (winPtr == grabWinPtr) {
	    break;
	}
	if (winPtr == NULL) {
	    if ((dispPtr->serverWinPtr == NULL) ||
		    (dispPtr->serverWinPtr->mainPtr == grabWinPtr->mainPtr)) {
		MovePointer2(grabWinPtr, dispPtr->serverWinPtr,
			NotifyUngrab, 0, 1);
	    }
	    break;
	}
    }
}
Пример #7
0
Файл: DragBS.c Проект: att/uwin
/*
 * begin catching window errors
 */
static void
begin_protection(Display *display, Window win)
{
    DEBUGOUT(_LtDebug0(__FILE__, NULL, "%s:begin_protection(%d)\n",
		      __FILE__, __LINE__));

    bad_window = False;

    oldErrorHandler = XSetErrorHandler(protect_handler);

    firstProtectRequest = NextRequest(display);

    errorWindow = win;
}
Пример #8
0
PodcastUrlLoaderReply* PodcastUrlLoader::Load(const QUrl& url) {
  // Create a reply
  PodcastUrlLoaderReply* reply = new PodcastUrlLoaderReply(url, this);

  // Create a state object to track this request
  RequestState* state = new RequestState;
  state->redirects_remaining_ = kMaxRedirects + 1;
  state->reply_ = reply;

  // Start the first request
  NextRequest(url, state);

  return reply;
}
Пример #9
0
/* TtkSendVirtualEvent --
 * 	Send a virtual event notification to the specified target window.
 * 	Equivalent to "event generate $tgtWindow <<$eventName>>"
 *
 * 	Note that we use Tk_QueueWindowEvent, not Tk_HandleEvent,
 * 	so this routine does not reenter the interpreter.
 */
void TtkSendVirtualEvent(Tk_Window tgtWin, const char *eventName)
{
    XEvent event;

    memset(&event, 0, sizeof(event));
    event.xany.type = VirtualEvent;
    event.xany.serial = NextRequest(Tk_Display(tgtWin));
    event.xany.send_event = False;
    event.xany.window = Tk_WindowId(tgtWin);
    event.xany.display = Tk_Display(tgtWin);
    ((XVirtualEvent *) &event)->name = Tk_GetUid(eventName);

    Tk_QueueWindowEvent(&event, TCL_QUEUE_TAIL);
}
Пример #10
0
int
TkpChangeFocus(
    TkWindow *winPtr,		/* Window that is to receive the X focus. */
    int force)			/* Non-zero means claim the focus even if it
				 * didn't originally belong to topLevelPtr's
				 * application. */
{
    TkDisplay *dispPtr = winPtr->dispPtr;
    Window focusWindow;
    int dummy, serial;
    TkWindow *winPtr2;

    if (!force) {
        XGetInputFocus(dispPtr->display, &focusWindow, &dummy);
        winPtr2 = (TkWindow *) Tk_IdToWindow(dispPtr->display, focusWindow);
        if ((winPtr2 == NULL) || (winPtr2->mainPtr != winPtr->mainPtr)) {
            return 0;
        }
    }

    if (winPtr->window == None) {
        Tcl_Panic("ChangeXFocus got null X window");
    }

    /*
     * Change the foreground window so the focus window is raised to the top
     * of the system stacking order and gets the keyboard focus.
     */

    if (force) {
        TkWinSetForegroundWindow(winPtr);
    }
    XSetInputFocus(dispPtr->display, winPtr->window, RevertToParent,
                   CurrentTime);

    /*
     * Remember the current serial number for the X server and issue a dummy
     * server request. This marks the position at which we changed the focus,
     * so we can distinguish FocusIn and FocusOut events on either side of the
     * mark.
     */

    serial = NextRequest(winPtr->display);
    XNoOp(winPtr->display);
    return serial;
}
Пример #11
0
int XErrorHandler( Display* display, XErrorEvent* event )
{
    LBWARN << lunchbox::disableFlush;
    LBWARN << "X Error occured: " << lunchbox::disableHeader 
           << lunchbox::indent;

    char buffer[256];
    XGetErrorText( display, event->error_code, buffer, 256);

    LBWARN << buffer << std::endl;
    LBWARN << "Major opcode: " << (int)event->request_code << std::endl;
    LBWARN << "Minor opcode: " << (int)event->minor_code << std::endl;
    LBWARN << "Error code: " << (int)event->error_code << std::endl;
    LBWARN << "Request serial: " << event->serial << std::endl;
    LBWARN << "Current serial: " << NextRequest( display ) - 1 << std::endl;

    switch( event->error_code )
    {
        case BadValue:
            LBWARN << "  Value: " << event->resourceid << std::endl;
            break;

        case BadAtom:
            LBWARN << "  AtomID: " << event->resourceid << std::endl;
            break;

        default:
            LBWARN << "  ResourceID: " << event->resourceid << std::endl;
            break;
    }
    LBWARN << lunchbox::enableFlush << lunchbox::exdent 
           << lunchbox::enableHeader;

#ifndef NDEBUG
    if( getenv( "EQ_ABORT_WAIT" ))
    {
        LBWARN << "Caught X Error, entering infinite loop for debugging" 
               << std::endl;
        while( true ) ;
    }
#endif

    return 0;
}
Пример #12
0
void
FocusToEWin(EWin * ewin, int why)
{
   if (EDebug(EDBUG_TYPE_FOCUS))
      Eprintf("%s(%d) %#x %s why=%d\n", __func__, focus_inhibit,
	      (ewin) ? EwinGetClientXwin(ewin) : 0,
	      (ewin) ? EwinGetTitle(ewin) : "None", why);

   switch (why)
     {
     case FOCUS_EWIN_NEW:
	if (!Conf.focus.all_new_windows_get_focus)
	   return;
	if (!FocusEwinValid(ewin, 0, 0, 0))
	   break;
	focus_pending_new = ewin;
	focus_pending_why = why;
	focus_pending_ewin = ewin;
	break;

     default:
	if (ewin && !FocusEwinValid(ewin, 0, why == FOCUS_CLICK, 0))
	   break;
	focus_pending_why = why;
	focus_pending_ewin = ewin;
	break;

     case FOCUS_EWIN_UNMAP:
	focus_pending_why = why;
	focus_pending_ewin = NULL;
	if (ewin == Mode.focuswin)
	  {
	     Mode.focuswin = NULL;
	     focus_is_set = 0;
	     if (!EoIsGone(ewin))
		FocusEwinSetActive(ewin, 0);
	  }
	if (ewin == focus_pending_new)
	   focus_pending_new = NULL;
	break;
     }
   focus_request = (int)NextRequest(disp) - 1;
}
Пример #13
0
static void
ReleaseButtonGrab(
    register TkDisplay *dispPtr)/* Display whose button grab is to be
				 * released. */
{
    unsigned int serial;

    if (dispPtr->buttonWinPtr != NULL) {
	if (dispPtr->buttonWinPtr != dispPtr->serverWinPtr) {
	    MovePointer2(dispPtr->buttonWinPtr, dispPtr->serverWinPtr,
		    NotifyUngrab, 1, 1);
	}
	dispPtr->buttonWinPtr = NULL;
    }
    if (dispPtr->grabFlags & GRAB_TEMP_GLOBAL) {
	dispPtr->grabFlags &= ~GRAB_TEMP_GLOBAL;
	serial = NextRequest(dispPtr->display);
	XUngrabPointer(dispPtr->display, CurrentTime);
	XUngrabKeyboard(dispPtr->display, CurrentTime);
	EatGrabEvents(dispPtr, serial);
    }
}
Пример #14
0
/*
 * Grab the multimedia keys on the X server
 *
 * That basically means that whenever these keys are pressed
 * the events will be sent to us instead of the application
 * that has current focus.
 */
void mmkey_install(Display *display)
{
	modifier_masks mod_masks;
	struct mmkey_track install_info;
	Window root_window;
	int i, j;

	mmkey_build_modifier_list(display, &mod_masks);

	root_window = DefaultRootWindow(display);

	memset(&install_info, 0, sizeof(install_info));
	install_info.previous_handler = XSetErrorHandler(mmkey_catch_grab_error);
	track_install = &install_info;
	for (i = 0; i < lengthof(key_list); i++) {
		KeyCode key;

		key = XKeysymToKeycode(display, key_list[i].symbol);
		*(key_list[i].store) = key;

		if (key == None)
			continue;

		install_info.request[i].key_name = key_list[i].name;
		install_info.request[i].displayed = False;
		for (j = 0; j < mod_masks.count; j++) {
			install_info.request[i].serial[j] = NextRequest(display);
			XGrabKey(display, key, mod_masks.list[j], root_window,
			         False, GrabModeAsync, GrabModeAsync);
		}
		if (config.verbose)
			printf("Found multimedia key: %s\n", key_list[i].name);
	}

	/* The grab may fail, so make sure it is reported now */
	XSync(display, False);
	XSetErrorHandler(install_info.previous_handler);
	track_install = NULL;
}
Пример #15
0
void
Eprintf(const char *fmt, ...)
{
   FILE               *fprt;
   va_list             args;
   struct timeval      tv;

   if (tv0.tv_sec == 0)
      gettimeofday(&tv0, NULL);

   fprt = Conf.log.dest ? stderr : stdout;

   gettimeofday(&tv, NULL);
   _tvdiff(&tv, &tv0, &tv);

   if (Conf.log.difftime)
     {
	static struct timeval tv1 = { 0, 0 };
	struct timeval      tvd;
	unsigned long       nreq;

	_tvdiff(&tvd, &tv1, &tv);
	tv1 = tv;

	nreq = (disp) ? NextRequest(disp) : 0;
	fprintf(fprt, "[%d] %#8lx %4ld.%06ld [%3ld.%06ld]: ", getpid(), nreq,
		(long)tv1.tv_sec, tv1.tv_usec, (long)tvd.tv_sec, tvd.tv_usec);
     }
   else
     {
	fprintf(fprt, "[%d] %4ld.%06ld: ", getpid(),
		(long)tv.tv_sec, tv.tv_usec);
     }

   va_start(args, fmt);
   vfprintf(fprt, fmt, args);
   va_end(args);
}
Пример #16
0
int fbx_init(fbx_struct *fb, fbx_wh wh, int width_, int height_, int useShm)
{
	int width, height;
	int rmask, gmask, bmask, ps, i;
	#ifdef _WIN32
	BMINFO bminfo;  HBITMAP hmembmp=0;  RECT rect;  HDC hdc=NULL;
	#else
	XWindowAttributes xwa;  int shmok=1, alphaFirst, pixmap=0;
	#endif

	if(!fb) _throw("Invalid argument");

	#ifdef _WIN32

	if(!wh) _throw("Invalid argument");
	_w32(GetClientRect(wh, &rect));
	if(width_>0) width=width_;
	else
	{
		width=rect.right-rect.left;  if(width<=0) width=MINWIDTH;
	}
	if(height_>0) height=height_;
	else
	{
		height=rect.bottom-rect.top;  if(height<=0) height=MINHEIGHT;
	}
	if(fb->wh==wh)
	{
		if(width==fb->width && height==fb->height && fb->hmdc && fb->hdib
			&& fb->bits)
			return 0;
		else if(fbx_term(fb)==-1) return -1;
	}
	memset(fb, 0, sizeof(fbx_struct));
	fb->wh=wh;

	_w32(hdc=GetDC(fb->wh));
	_w32(fb->hmdc=CreateCompatibleDC(hdc));
	_w32(hmembmp=CreateCompatibleBitmap(hdc, width, height));
	_w32(GetDeviceCaps(hdc, RASTERCAPS)&RC_BITBLT);
	_w32(GetDeviceCaps(fb->hmdc, RASTERCAPS)&RC_DI_BITMAP);
	bminfo.bmi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
	bminfo.bmi.bmiHeader.biBitCount=0;
	_w32(GetDIBits(fb->hmdc, hmembmp, 0, 1, NULL, &bminfo.bmi, DIB_RGB_COLORS));
	_w32(GetDIBits(fb->hmdc, hmembmp, 0, 1, NULL, &bminfo.bmi, DIB_RGB_COLORS));
	_w32(DeleteObject(hmembmp));  hmembmp=0;
		/* (we only needed it to get the screen properties) */
	ps=bminfo.bmi.bmiHeader.biBitCount/8;
	if(width>0) bminfo.bmi.bmiHeader.biWidth=width;
	if(height>0) bminfo.bmi.bmiHeader.biHeight=height;
	fb->width=bminfo.bmi.bmiHeader.biWidth;
	fb->height=bminfo.bmi.bmiHeader.biHeight;

	if(ps<3)
	{
		/* Make the buffer BGRA */
		bminfo.bmi.bmiHeader.biCompression=BI_BITFIELDS;
		bminfo.bmi.bmiHeader.biBitCount=32;
		ps=4;
		(*(DWORD *)&bminfo.bmi.bmiColors[0])=0xFF0000;
		(*(DWORD *)&bminfo.bmi.bmiColors[1])=0xFF00;
		(*(DWORD *)&bminfo.bmi.bmiColors[2])=0xFF;
	}

	fb->pitch=BMPPAD(fb->width*ps);  /* Windoze bitmaps are always padded */

	if(bminfo.bmi.bmiHeader.biCompression==BI_BITFIELDS)
	{
		rmask=(*(DWORD *)&bminfo.bmi.bmiColors[0]);
		gmask=(*(DWORD *)&bminfo.bmi.bmiColors[1]);
		bmask=(*(DWORD *)&bminfo.bmi.bmiColors[2]);
	}
	else
	{
		rmask=0xFF0000;
		gmask=0xFF00;
		bmask=0xFF;
	}

	fb->format=-1;
	for(i=0; i<FBX_FORMATS; i++)
		if(rmask==fbx_rmask[i] && gmask==fbx_gmask[i] && bmask==fbx_bmask[i]
			&& ps==fbx_ps[i] && fbx_alphafirst[i]==0) fb->format=i;
	if(fb->format==-1) _throw("Display has unsupported pixel format");

	bminfo.bmi.bmiHeader.biHeight=-bminfo.bmi.bmiHeader.biHeight;
		/* (our convention is top-down) */
	_w32(fb->hdib=CreateDIBSection(hdc, &bminfo.bmi, DIB_RGB_COLORS,
		(void **)&fb->bits, NULL, 0));
	_w32(SelectObject(fb->hmdc, fb->hdib));
	ReleaseDC(fb->wh, hdc);
	return 0;

	finally:
	if(hmembmp) DeleteObject(hmembmp);
	if(hdc) ReleaseDC(fb->wh, hdc);

	#else

	if(!wh.dpy || !wh.d) _throw("Invalid argument");
	if(wh.v)
	{
		_x11(XGetGeometry(wh.dpy, wh.d, &xwa.root, &xwa.x, &xwa.y,
			(unsigned int *)&xwa.width, (unsigned int *)&xwa.height,
			(unsigned int *)&xwa.border_width, (unsigned int *)&xwa.depth));
		xwa.visual=wh.v;
		useShm=0;
		pixmap=1;
	}
	else
	{
		_x11(XGetWindowAttributes(wh.dpy, wh.d, &xwa));
	}
	if(width_>0) width=width_;  else width=xwa.width;
	if(height_>0) height=height_;  else height=xwa.height;
	if(fb->wh.dpy==wh.dpy && fb->wh.d==wh.d)
	{
		if(width==fb->width && height==fb->height && fb->xi && fb->xgc && fb->bits)
			return 0;
		else if(fbx_term(fb)==-1) return -1;
	}
	memset(fb, 0, sizeof(fbx_struct));
	fb->wh.dpy=wh.dpy;  fb->wh.d=wh.d;

	#ifdef USESHM
	if(!useShm)
	{
		static int alreadyWarned=0;
		if(!alreadyWarned && warningFile)
		{
			fprintf(warningFile, "[FBX] Disabling shared memory blitting\n");
			alreadyWarned=1;
		}
	}
	if(useShm && XShmQueryExtension(fb->wh.dpy))
	{
		static int alreadyWarned=0;
		fb->shminfo.shmid=-1;
		if(!(fb->xi=XShmCreateImage(fb->wh.dpy, xwa.visual, xwa.depth,
			ZPixmap, NULL, &fb->shminfo, width, height)))
		{
			useShm=0;  goto noshm;
		}
		if((fb->shminfo.shmid=shmget(IPC_PRIVATE,
			fb->xi->bytes_per_line*fb->xi->height+1, IPC_CREAT|0777))==-1)
		{
			useShm=0;  XDestroyImage(fb->xi);  goto noshm;
		}
		if((fb->shminfo.shmaddr=fb->xi->data
			=(char *)shmat(fb->shminfo.shmid, 0, 0))==(char *)-1)
		{
			useShm=0;  XDestroyImage(fb->xi);
			shmctl(fb->shminfo.shmid, IPC_RMID, 0);  goto noshm;
		}
		fb->shminfo.readOnly=False;
		XLockDisplay(fb->wh.dpy);
		XSync(fb->wh.dpy, False);
		prevHandler=XSetErrorHandler(xhandler);
		extok=1;
		serial=NextRequest(fb->wh.dpy);
		XShmAttach(fb->wh.dpy, &fb->shminfo);
		XSync(fb->wh.dpy, False);
		XSetErrorHandler(prevHandler);
		shmok=extok;
		if(!alreadyWarned && !shmok && warningFile)
		{
			fprintf(warningFile,
				"[FBX] WARNING: MIT-SHM extension failed to initialize (this is normal on a\n");
			fprintf(warningFile,
				"[FBX]    remote connection.)  Will use X Pixmap drawing instead.\n");
			alreadyWarned=1;
		}
		XUnlockDisplay(fb->wh.dpy);
		if(shmok)
		{
			char *env=getenv("FBX_USESHMPIXMAPS");
			if(env && !strcmp(env, "1"))
			{
				static int alreadyWarned=0;
				if(!alreadyWarned && warningFile)
				{
					fprintf(warningFile, "[FBX] Using MIT-SHM pixmaps\n");
					alreadyWarned=1;
				}
				fb->pm=XShmCreatePixmap(fb->wh.dpy, fb->wh.d, fb->shminfo.shmaddr,
					&fb->shminfo, width, height, xwa.depth);
				if(!fb->pm) shmok=0;
			}
		}
		shmctl(fb->shminfo.shmid, IPC_RMID, 0);
		if(!shmok)
		{
			useShm=0;  XDestroyImage(fb->xi);  shmdt(fb->shminfo.shmaddr);
			shmctl(fb->shminfo.shmid, IPC_RMID, 0);  goto noshm;
		}
		fb->xattach=1;  fb->shm=1;
	}
	else if(useShm)
	{
		static int alreadyWarned=0;
		if(!alreadyWarned && warningFile)
		{
			fprintf(warningFile,
				"[FBX] WARNING: MIT-SHM extension not available.  Will use X pixmap\n");
			fprintf(warningFile, "[FBX]    drawing instead.\n");
			alreadyWarned=1;
		}
		useShm=0;
	}
	noshm:
	if(!useShm)
	#endif
	{
		if(!pixmap)
			_x11(fb->pm=XCreatePixmap(fb->wh.dpy, fb->wh.d, width, height,
				xwa.depth));
		_x11(fb->xi=XCreateImage(fb->wh.dpy, xwa.visual, xwa.depth, ZPixmap, 0,
			NULL, width, height, 8, 0));
		if((fb->xi->data=(char *)malloc(fb->xi->bytes_per_line*fb->xi->height+1))
			==NULL)
			_throw("Memory allocation error");
	}
	ps=fb->xi->bits_per_pixel/8;
	fb->width=fb->xi->width;
	fb->height=fb->xi->height;
	fb->pitch=fb->xi->bytes_per_line;
	if(fb->width!=width || fb->height!=height)
		_throw("Bitmap returned does not match requested size");
	rmask=fb->xi->red_mask;  gmask=fb->xi->green_mask;  bmask=fb->xi->blue_mask;
	alphaFirst=0;
	if(fb->xi->byte_order==MSBFirst)
	{
		if(ps<4)
		{
			rmask=fb->xi->blue_mask;  gmask=fb->xi->green_mask;
			bmask=fb->xi->red_mask;
		}
		else alphaFirst=1;
	}

	fb->format=-1;
	for(i=0; i<FBX_FORMATS; i++)
		if(rmask==fbx_rmask[i] && gmask==fbx_gmask[i] && bmask==fbx_bmask[i]
			&& ps==fbx_ps[i] && fbx_alphafirst[i]==alphaFirst) fb->format=i;
	if(fb->format==-1) _throw("Display has unsupported pixel format");

	fb->bits=fb->xi->data;
	fb->pixmap=pixmap;
	_x11(fb->xgc=XCreateGC(fb->wh.dpy, fb->pm? fb->pm:fb->wh.d, 0, NULL));
	return 0;

	finally:

	#endif

	fbx_term(fb);
	return -1;
}
Пример #17
0
void         
gdk_superwin_scroll (GdkSuperWin *superwin,
                     gint dx,
                     gint dy)
{
  gint width, height;

  gint first_resize_x = 0;
  gint first_resize_y = 0;
  gint first_resize_width = 0;
  gint first_resize_height = 0;

  unsigned long first_resize_serial = 0;
  unsigned long move_serial = 0;
  unsigned long last_resize_serial = 0;
  gint move_x = 0;
  gint move_y = 0;

  /* get the current dimensions of the window */
  gdk_window_get_size (superwin->shell_window, &width, &height);

  /* calculate the first resize. */

  /* for the first move resize, the width + height default to the
     width and height of the window. */
  first_resize_width = width;
  first_resize_height = height;

  /* if scrolling left ( dx < 0 ) need to extend window right by
     ABS(dx) and left side of window won't move. */
  if (dx < 0) {
    /* left side of the window doesn't move. */
    first_resize_x = 0;
    /* right side of window will be the width + the offset of the
       scroll */
    first_resize_width = width + ABS(dx);
  }

  /* if scrolling right ( dx > 0 ) need to extend window left by
     ABS(dx) and right side of the window doesn't move */
  if (dx > 0) {
    /* left side of the window will be offset to the left by ABS(dx) (
       x will be < 0 ) */
    first_resize_x = -dx;
    /* right side of the window won't move.  We have to add the offset
       to the width so that it doesn't. */
    first_resize_width = width + dx;
  }

  /* if scrolling down ( dy < 0 ) need to extend window down by
     ABS(dy) and top of window won't move */
  if (dy < 0) {
    /* top of window not moving */
    first_resize_y = 0;
    /* bottom of window will be the height + the offset of the scroll */
    first_resize_height = height + ABS(dy);
  }

  /* if scrolling up ( dy > 0 ) need to extend window up by ABS(dy)
     and bottom of window won't move. */
  if (dy > 0) {
    /* top of the window will be moved up by ABS(dy) ( y will be < 0 ) */
    first_resize_y = -dy;
    /* this will cause the bottom of the window not to move since
       we're moving y by the offset up. */
    first_resize_height = height + dy; 
  }

  /* calculate our move offsets  */

  /* if scrolling left ( dx < 0 ) we need to move the window left by
     ABS(dx) */
  if (dx < 0) {
    /* dx will be negative - this will move it left */
    move_x = dx;
  }

  /* if scrolling right ( dx > 0 ) we need to move the window right by
     ABS(dx).  Because we already resized the window to -dx by moving
     it to zero we are actually moving the window to the right. */
  if (dx > 0) {
    move_x = 0;
  }

  /* If scrolling down ( dy < 0 ) we need to move the window up by
     ABS(dy) */
  if (dy < 0) {
    /* dy will be negative - this will move it up */
    move_y = dy;
  }

  /* If scrolling up ( dy > 0 ) we need to move the window down by
     ABS(dy).  In this case we already resized the top of the window
     to -dy so by moving it to zero we are actually moving the window
     down. */
  if (dy > 0) {
    move_y = 0;
  }

  /* save the serial of the first request */
  first_resize_serial = NextRequest(GDK_DISPLAY());

  /* move our window */
  gdk_window_move_resize(superwin->bin_window,
                         first_resize_x, first_resize_y,
                         first_resize_width, first_resize_height);

  /* window move - this move will cause all of the exposes to happen
     and is where all the translation magic has to be applied.  we
     need to save the serial of this operation since any expose events
     with serial request numbers lower than it will have to have their
     coordinates translated into the new coordinate system. */

  move_serial = NextRequest(GDK_DISPLAY());

  gdk_window_move(superwin->bin_window,
                  move_x, move_y);

  /* last resize.  This will resize the window to its original
     position. */

  /* save the request of the last resize */
  last_resize_serial = NextRequest(GDK_DISPLAY());

  gdk_window_move_resize(superwin->bin_window,
                         0, 0, width, height);

  /* now that we have moved everything, repaint the damaged areas */

  /* if scrolling left ( dx < 0 ) moving window left so expose area at
     the right of the window.  Clip the width of the exposure to the
     width of the window or the offset, whichever is smaller.  Also
     clip the start to the origin ( 0 ) if the width minus the
     absolute value of the offset is < 0 to handle > 1 page
     scrolls. */
  if (dx < 0) {
    gdk_superwin_expose_area(superwin, MAX(0, width - ABS(dx)), 0,
                             MIN(width, ABS(dx)), height);
    /* If we've exposed this area add an antiexpose for it.  When the
       window was moved left the expose will be offset by ABS(dx).
       For greated than one page scrolls, the expose will be offset by
       the actual offset of the move, hence the MAX(height,
       ABS(dy)). */
    gdk_superwin_add_antiexpose(superwin, move_serial,
                                MAX(width, ABS(dx)),
                                0, MIN(width, ABS(dx)), height);
  }

  /* if scrolling right ( dx > 0 ) moving window right so expose area
     at the left of the window.  Clip the width of the exposure to the
     width of the window or the offset, whichever is smaller. */
  if (dx > 0) {
    gdk_superwin_expose_area(superwin, 0, 0, 
                             MIN(width, ABS(dx)), height);
    /* If we've exposed this area add an antiexpose for it. */
    gdk_superwin_add_antiexpose(superwin, move_serial,
                                0, 0, MIN(width, ABS(dx)), height);
  }

  /* if scrolling down ( dy < 0 ) moving window up so expose area at
     the bottom of the window.  Clip the exposed area to the height of
     the window or the offset, whichever is smaller.  Also clip the
     start to the origin ( 0 ) if the the height minus the absolute
     value of the offset is < 0 to handle > 1 page scrolls. */

  if (dy < 0) {
    gdk_superwin_expose_area(superwin, 0, MAX(0, height - ABS(dy)),
                             width, MIN(height, ABS(dy)));
    /* If we've exposed this area add an antiexpose for it.  When the
       was moved up before the second move the expose will be offset
       by ABS(dy).  For greater than one page scrolls, the expose will
       be offset by actual offset of the move, hence the MAX(height,
       ABS(dy)).  */
        gdk_superwin_add_antiexpose(superwin, move_serial,
                                    0,
                                    MAX(height, ABS(dy)),
                                    width, MIN(height, ABS(dy)));
  }

  /* if scrolling up ( dy > 0 ) moving window down so expose area at
     the top of the window.  Clip the exposed area to the height or
     the offset, whichever is smaller. */
  if (dy > 0) {
    gdk_superwin_expose_area(superwin, 0, 0,
                             width, MIN(height, ABS(dy)));
    /* if we've exposed this area add an antiexpose for it. */
    gdk_superwin_add_antiexpose(superwin, move_serial,
                                0, 0, width, MIN(height, ABS(dy)));
  }

  /* if we are scrolling right or down ( dx > 0 or dy > 0 ) we need to
     add our translation before the fist move_resize.  Once we do this
     all previous expose events will be translated into the new
     coordinate space */
  if (dx > 0 || dy > 0) {
    gdk_superwin_add_translation(superwin, first_resize_serial,
                                 MAX(0, dx), MAX(0, dy));
  }

  /* If we are scrolling left or down ( x < 0 or y < 0 ) we need to
     add our translation before the last move_resize.  Once we do this
     all previous expose events will be translated in the new
     coordinate space. */
  if (dx < 0 || dy < 0) {
    gdk_superwin_add_translation(superwin, last_resize_serial,
                                 MIN(0, dx), MIN(0, dy));
  }

  /* sync so we get the windows moved now */
  XSync(GDK_DISPLAY(), False);
}
Пример #18
0
int XDPSImageFileIntoDrawable(
    DPSContext context,
    Screen *screen,
    Drawable dest,
    FILE *file,
    int drawableHeight,
    int drawableDepth,
    XRectangle *bbox,
    int xOffset, int yOffset,
    double pixelsPerPoint,
    Bool clear, Bool createMask,
    Bool waitForCompletion,
    Bool *doneFlag)
{
#define BUFSIZE 256
#define EXECLEN 6
    char buf[BUFSIZE];
    static char eobuf[] = "\n$Adobe$DPS$Lib$Dict /execSuccess true put\n\
stop\n\
Magic end of data line )))))))))) 99#2 2#99 <xyz> // 7gsad,32h4ghNmndFgj2\n";
    XDPSStandardColormap maskMap;
    XDPSStandardColormap rgbMap;
    unsigned int flags = 0;
    int status;
    Bool inited;
    DPSPointer cookie;
    int doublings;
    int ms;
    XDPSStatusProc oldProc;
    unsigned long startReqNum = 0, endReqNum;

    if (screen == NULL || dest == None || 
	drawableHeight <= 0 || drawableDepth <= 0 ||
	pixelsPerPoint <= 0) {
	return dps_status_illegal_value;
    }

    if (context == NULL) {
        context = XDPSGetSharedContext(DisplayOfScreen(screen));
	if (context == NULL) {
	    FillPixmapWithGray(screen, dest, bbox, xOffset, yOffset,
			       pixelsPerPoint,
			       createMask);
	    return dps_status_no_extension;
	}
    }	

    (*rewindFunction)(file, rewindClientData);

    if (!waitForCompletion) {
	DPSWaitContext(context);
	/* Any status events before this point go to old handler */
	startReqNum = NextRequest(DisplayOfScreen(screen));
    }

    status = _XDPSTestComponentInitialized(context,
					   dps_init_bit_preview, &inited);
    if (status != dps_status_success) return status;
    if (!inited) {
	(void) _XDPSSetComponentInitialized(context, dps_init_bit_preview);
	_DPSPDefineExecFunction(context);
    }

    if (createMask) {
	if (drawableDepth != 1) return dps_status_illegal_value;
	maskMap.colormap = None;
	maskMap.red_max = 1;
	maskMap.red_mult = -1;
	maskMap.base_pixel = 1;
	rgbMap.colormap = None;
	rgbMap.red_max = rgbMap.green_max = rgbMap.blue_max = 
		rgbMap.red_mult = rgbMap.green_mult = rgbMap.blue_mult =
		rgbMap.base_pixel = 0;
	flags = XDPSContextGrayMap | XDPSContextRGBMap;
    }

    status = XDPSPushContextParameters(context, screen, drawableDepth,
				     dest, drawableHeight,
				     &rgbMap, &maskMap,
				     flags | XDPSContextScreenDepth |
					      XDPSContextDrawable, &cookie);

    if (status != dps_status_success) return status;

    _DPSPSetMatrix(context, xOffset, yOffset, pixelsPerPoint);

    if (clear) _DPSPClearArea(context, (int) bbox->x, (int) bbox->y,
			      (int) bbox->width, (int) bbox->height);

    if (createMask) _DPSPSetMaskTransfer(context);

    /* Prepare to read PostScript code */
    _DPSPSaveBeforeExec(context, !waitForCompletion);
    DPSWritePostScript(context, "\nexec\n", EXECLEN);

    imaging = True;
    while ((*getsFunction)(buf, BUFSIZE, file, getsClientData) != NULL) {
	DPSWritePostScript(context, buf, strlen(buf));
    }
    imaging = False;

    /* This marks the end of the data stream */
    DPSWritePostScript(context, eobuf, strlen(eobuf));

    if (!waitForCompletion) {
	*doneFlag = False;
	oldProc = XDPSRegisterStatusProc(context, HandlePreviewStatus);
	SetUpStatusVariables(context, cookie, doneFlag, startReqNum, oldProc);
	XDPSSetStatusMask(context, 0, 0, PSFROZENMASK);

	ms = timeStart;

	/* Check for done until we run out of time */
	doublings = 0;
	while (1) {
	    if (XDPSGetContextStatus(context) == PSFROZEN) {
		waitForCompletion = True;
		XDPSUnfreezeContext(context);
		break;
	    }
	    if (doublings >= maxDoubles) break;

	    /* Wait a while */
	    msleep(ms);
	    ms *= 2;
	    doublings++;
	}
    }

    /* If previous decided imaging is done, it changed waitForCompletion */

    if (waitForCompletion) return FinishUp(context, cookie);
    else {
	endReqNum = NextRequest(DisplayOfScreen(screen)) - 1;
	SetEndReqNum(context, endReqNum);
	return dps_status_imaging_incomplete;
    }
#undef EXECLEN
#undef BUFSIZE
}
Пример #19
0
/* ARGSUSED */
void
SetCommand(Widget w, ResCommand command, char *msg)
{
  XClientMessageEvent client_event;
  Display             *dpy = XtDisplay(w);

  if (msg == NULL)
    {
      /* "Click the mouse pointer on any toolkit client" */
      msg = res_labels[6];
    }
  
  SetMessage(global_screen_data.info_label,
	     msg,
	     "Click the mouse pointer on any toolkit client");
  
  if (global_client.window == None) {
      if ( (global_client.window = GetClientWindow(w, NULL, NULL)) == None ) {
	  return;
      }
  }

/* printf("[SetCommand] global_client.window: %d 0x%x\n", */
/*        global_client.window, */
/*        global_client.window); */
       
  global_client.ident = GetNewIdent();

  global_client.command = command;
  global_client.atom = atom_comm;

  BuildHeader(&(global_client)); 

  if (!XtOwnSelection(w,
		      global_client.atom,
		      CurrentTime,
		      ConvertCommand,
		      LoseSelection,
		      SelectionDone))
    {
      /* "Unable to own the Resource/Attribute Selection" */
      SetMessage(global_screen_data.info_label,
		 res_labels[7],
		 "Unable to own the Resource/Attribute Selection");
    }

  client_event.window = global_client.window;
  client_event.type = ClientMessage;
  client_event.message_type = atom_resource_editor;
  client_event.format = EDITRES_SEND_EVENT_FORMAT;
  client_event.data.l[0] = XtLastTimestampProcessed(dpy);
  client_event.data.l[1] = global_client.atom;
  client_event.data.l[2] = (long) global_client.ident;
  client_event.data.l[3] = global_effective_protocol_version;

  global_error_code = NO_ERROR;                 /* Reset Error code. */
  global_old_error_handler = XSetErrorHandler(HandleXErrors);
  global_serial_num = NextRequest(dpy);

  XSendEvent(dpy,
	     global_client.window,
	     FALSE,
	     (long)0, 
	     (XEvent*)&client_event);

  XSync(dpy, FALSE);
  XSetErrorHandler(global_old_error_handler);

  if (global_error_code == NO_WINDOW) {
      char error_buf[BUFSIZ];


      global_error_code = NO_ERROR;	/* Reset Error code. */
      sprintf(error_buf,
	      "The communication window with%s%s.",
	      " application is no longer available\n",
	      "Please select a new widget tree");
    
      global_client.window = None;
      SetCommand(w, LocalSendWidgetTree, error_buf);

      return;
    }   
  
  TellUserAboutMessage(global_screen_data.info_label, command);
  global_client.timeout = XtAppAddTimeOut(XtWidgetToApplicationContext(w),
					  CLIENT_TIME_OUT, 
					  ClientTimedOut,
					  (XtPointer)w);
  startWait(XtWidgetToApplicationContext(w),
	    CLIENT_TIME_OUT / 1000);

}   /* SetCommand() */
Пример #20
0
// wrapper so we can call a macro
static unsigned long getNextRequest (void *aClosure) {
  return NextRequest(GDK_DISPLAY());
}
Пример #21
0
void TopWindow::Open(Ctrl *owner)
{
	LLOG("TopWindow::Open");
	GuiLock __; 
	if(dokeys && (!GUI_AKD_Conservative() || GetAccessKeysDeep() <= 1))
		DistributeAccessKeys();
	USRLOG("   OPEN " + Desc(this));
	LLOG("OPEN " << Name() << " owner: " << UPP::Name(owner));
	IgnoreMouseUp();
	bool weplace = owner && center == 1 || center == 2 || !GetRect().IsEmpty();
	if(fullscreen)
		SetRect(0, 0, Xwidth, Xheight);
	else
		CenterRect(owner);
	LLOG("Open NextRequest " << NextRequest(Xdisplay));
	Create(owner, false, false);
	XSetWMProperties (Xdisplay, GetWindow(), NULL, NULL, NULL, 0, NULL, NULL, NULL);
	xminsize.cx = xmaxsize.cx = Null;
	title2.Clear();
	if(!weplace) {
		LLOG("SyncCaption");
		SyncCaption();
	}
	LLOG("SyncSizeHints");
	size_hints->flags = 0;
	SyncSizeHints();
	Rect r = GetRect();
	size_hints->x = r.left;
	size_hints->y = r.top;
	size_hints->width = r.Width();
	size_hints->height = r.Height();
	size_hints->win_gravity = StaticGravity;
	size_hints->flags |= PPosition|PSize|PWinGravity;
	if(owner) {
		ASSERT(owner->IsOpen());
		LLOG("XSetTransientForHint");
		XSetTransientForHint(Xdisplay, GetWindow(), owner->GetWindow());
	}
	LLOG("XSetWMNormalHints");
	XSetWMNormalHints(Xdisplay, GetWindow(), size_hints);
	Atom protocols[3];
	protocols[0] = XAtom("WM_DELETE_WINDOW");
	protocols[1] = XAtom("WM_TAKE_FOCUS");
	protocols[2] = XAtom("_NET_WM_PING");
	LLOG("XSetWMProtocols");
	XSetWMProtocols(Xdisplay, GetWindow(), protocols, 3);
	String x = GetExeTitle().ToString();
	const char *progname = ~x;
	class_hint->res_name = (char *)progname;
	class_hint->res_class = (char *)progname;
	XSetClassHint(Xdisplay, GetWindow(), class_hint);
	LLOG("WndShow(" << visible << ")");
	WndShow(visible);
	if(visible) {
		XEvent e;
		LLOG("XWindowEvent");
		XWindowEvent(Xdisplay, top->window, VisibilityChangeMask, &e);
		ignoretakefocus = true;
		SetTimeCallback(500, THISBACK(EndIgnoreTakeFocus));
		LLOG("SetWndFocus");
		SetWndFocus();
		for(int i = 0; i < 50; i++) {
			// X11 tries to move our window, so ignore the first set of ConfigureNotify
			// and move the window into position after FocusIn - but not if we want WM to
			// place the window
			if(weplace)
				while(XCheckTypedWindowEvent(Xdisplay, top->window, ConfigureNotify, &e)) {
					if(e.xconfigure.window != top->window)
						ProcessEvent(&e);
				}	
			if(XCheckTypedWindowEvent(Xdisplay, top->window, FocusIn, &e)) {
				ProcessEvent(&e);
				if(e.xfocus.window == top->window)
					break;
			}
			Sleep(10);
		}
	}
	if(weplace) {
		WndSetPos(GetRect());
		LLOG("SyncCaption");
		SyncCaption();
	}
	LLOG(">Open NextRequest " << NextRequest(Xdisplay));
	LLOG(">OPENED " << Name());
	PlaceFocus();
	StateH(OPEN);
	Vector<int> fe = GetPropertyInts(top->window, XAtom("_NET_FRAME_EXTENTS"));
	if(fe.GetCount() >= 4 &&
	   fe[0] >= 0 && fe[0] <= 16 && fe[1] >= 0 && fe[1] <= 16 && //fluxbox returns wrong numbers - quick&dirty workaround
	   fe[2] >= 0 && fe[2] <= 64 && fe[3] >= 0 && fe[3] <= 48)
	{
		GuiLock __;
		windowFrameMargin.left = max(windowFrameMargin.left, fe[0]);
		windowFrameMargin.right = max(windowFrameMargin.right, fe[1]);
		windowFrameMargin.top = max(windowFrameMargin.top, fe[2]);
		windowFrameMargin.bottom = max(windowFrameMargin.bottom, fe[3]);
	}
	if(IsOpen() && top)
		top->owner = owner;

	long curr_pid = getpid();

	static Window wm_client_leader;
	ONCELOCK {
		wm_client_leader = XCreateSimpleWindow(Xdisplay, Xroot, 0, 0, 1, 1, 0, 0, 0);
		XChangeProperty(Xdisplay, wm_client_leader, XAtom("WM_CLIENT_LEADER"),
		                XA_WINDOW, 32, PropModeReplace, (byte *)&wm_client_leader, 1);
		XChangeProperty(Xdisplay, wm_client_leader, XAtom("_NET_WM_PID"), XA_CARDINAL, 32,
		                PropModeReplace, (byte *) &curr_pid, 1);
	}

	Window win = GetWindow();
	XChangeProperty(Xdisplay, win, XAtom("_NET_WM_PID"), XA_CARDINAL, 32,
	                PropModeReplace, (byte *) &curr_pid, 1);
	XChangeProperty(Xdisplay, win, XAtom("WM_CLIENT_LEADER"),
	                XA_WINDOW, 32, PropModeReplace, (byte *)&wm_client_leader, 1);

	int version = 5;
	XChangeProperty(Xdisplay, win, XAtom("XdndAware"), XA_ATOM, 32,
					0, (byte *)&version, 1);

	SyncState();
	FixIcons();
}
Пример #22
0
int
TkPointerEvent(
    register XEvent *eventPtr,	/* Pointer to the event. */
    TkWindow *winPtr)		/* Tk's information for window where event was
				 * reported. */
{
    register TkWindow *winPtr2;
    TkDisplay *dispPtr = winPtr->dispPtr;
    unsigned int serial;
    int outsideGrabTree = 0;
    int ancestorOfGrab = 0;
    int appGrabbed = 0;		/* Non-zero means event is being reported to
				 * an application that is affected by the
				 * grab. */

    /*
     * Collect information about the grab (if any).
     */

    switch (TkGrabState(winPtr)) {
    case TK_GRAB_IN_TREE:
	appGrabbed = 1;
	break;
    case TK_GRAB_ANCESTOR:
	appGrabbed = 1;
	outsideGrabTree = 1;
	ancestorOfGrab = 1;
	break;
    case TK_GRAB_EXCLUDED:
	appGrabbed = 1;
	outsideGrabTree = 1;
	break;
    }

    if ((eventPtr->type == EnterNotify) || (eventPtr->type == LeaveNotify)) {
	/*
	 * Keep track of what window the mouse is *really* over. Any events
	 * that we generate have a special send_event value, which is detected
	 * below and used to ignore the event for purposes of setting
	 * serverWinPtr.
	 */

	if (eventPtr->xcrossing.send_event != GENERATED_GRAB_EVENT_MAGIC) {
	    if ((eventPtr->type == LeaveNotify) &&
		    (winPtr->flags & TK_TOP_HIERARCHY)) {
		dispPtr->serverWinPtr = NULL;
	    } else {
		dispPtr->serverWinPtr = winPtr;
	    }
	}

	/*
	 * When a grab is active, X continues to report enter and leave events
	 * for windows outside the tree of the grab window:
	 * 1. Detect these events and ignore them except for windows above the
	 *    grab window.
	 * 2. Allow Enter and Leave events to pass through the windows above
	 *    the grab window, but never let them end up with the pointer *in*
	 *    one of those windows.
	 */

	if (dispPtr->grabWinPtr != NULL) {
	    if (outsideGrabTree && appGrabbed) {
		if (!ancestorOfGrab) {
		    return 0;
		}
		switch (eventPtr->xcrossing.detail) {
		case NotifyInferior:
		    return 0;
		case NotifyAncestor:
		    eventPtr->xcrossing.detail = NotifyVirtual;
		    break;
		case NotifyNonlinear:
		    eventPtr->xcrossing.detail = NotifyNonlinearVirtual;
		    break;
		}
	    }

	    /*
	     * Make buttons have the same grab-like behavior inside a grab as
	     * they do outside a grab: do this by ignoring enter and leave
	     * events except for the window in which the button was pressed.
	     */

	    if ((dispPtr->buttonWinPtr != NULL)
		    && (winPtr != dispPtr->buttonWinPtr)) {
		return 0;
	    }
	}
	return 1;
    }

    if (!appGrabbed) {
	return 1;
    }

    if (eventPtr->type == MotionNotify) {
	/*
	 * When grabs are active, X reports motion events relative to the
	 * window under the pointer. Instead, it should report the events
	 * relative to the window the button went down in, if there is a
	 * button down. Otherwise, if the pointer window is outside the
	 * subtree of the grab window, the events should be reported relative
	 * to the grab window. Otherwise, the event should be reported to the
	 * pointer window.
	 */

	winPtr2 = winPtr;
	if (dispPtr->buttonWinPtr != NULL) {
	    winPtr2 = dispPtr->buttonWinPtr;
	} else if (outsideGrabTree || (dispPtr->serverWinPtr == NULL)) {
	    winPtr2 = dispPtr->grabWinPtr;
	}
	if (winPtr2 != winPtr) {
	    TkChangeEventWindow(eventPtr, winPtr2);
	    Tk_QueueWindowEvent(eventPtr, TCL_QUEUE_HEAD);
	    return 0;
	}
	return 1;
    }

    /*
     * Process ButtonPress and ButtonRelease events:
     * 1. Keep track of whether a button is down and what window it went down
     *    in.
     * 2. If the first button goes down outside the grab tree, pretend it went
     *    down in the grab window. Note: it's important to redirect events to
     *    the grab window like this in order to make things like menus work,
     *    where button presses outside the grabbed menu need to be seen. An
     *    application can always ignore the events if they occur outside its
     *    window.
     * 3. If a button press or release occurs outside the window where the
     *    first button was pressed, retarget the event so it's reported to the
     *    window where the first button was pressed.
     * 4. If the last button is released in a window different than where the
     *    first button was pressed, generate Enter/Leave events to move the
     *    mouse from the button window to its current window.
     * 5. If the grab is set at a time when a button is already down, or if
     *    the window where the button was pressed was deleted, then
     *    dispPtr->buttonWinPtr will stay NULL. Just forget about the
     *    auto-grab for the button press; events will go to whatever window
     *    contains the pointer. If this window isn't in the grab tree then
     *    redirect events to the grab window.
     * 6. When a button is pressed during a local grab, the X server sets a
     *    grab of its own, since it doesn't even know about our local grab.
     *    This causes enter and leave events no longer to be generated in the
     *    same way as for global grabs. To eliminate this problem, set a
     *    temporary global grab when the first button goes down and release it
     *    when the last button comes up.
     */

    if ((eventPtr->type == ButtonPress) || (eventPtr->type == ButtonRelease)) {
	winPtr2 = dispPtr->buttonWinPtr;
	if (winPtr2 == NULL) {
	    if (outsideGrabTree) {
		winPtr2 = dispPtr->grabWinPtr;			/* Note 5. */
	    } else {
		winPtr2 = winPtr;				/* Note 5. */
	    }
	}
	if (eventPtr->type == ButtonPress) {
	    if ((eventPtr->xbutton.state & ALL_BUTTONS) == 0) {
		if (outsideGrabTree) {
		    TkChangeEventWindow(eventPtr, dispPtr->grabWinPtr);
		    Tk_QueueWindowEvent(eventPtr, TCL_QUEUE_HEAD);
		    return 0;					/* Note 2. */
		}
		if (!(dispPtr->grabFlags & GRAB_GLOBAL)) {	/* Note 6. */
		    serial = NextRequest(dispPtr->display);
		    if (XGrabPointer(dispPtr->display,
			    dispPtr->grabWinPtr->window, True,
			    ButtonPressMask|ButtonReleaseMask|ButtonMotionMask,
			    GrabModeAsync, GrabModeAsync, None, None,
			    CurrentTime) == 0) {
			EatGrabEvents(dispPtr, serial);
			if (XGrabKeyboard(dispPtr->display, winPtr->window,
				False, GrabModeAsync, GrabModeAsync,
				CurrentTime) == 0) {
			    dispPtr->grabFlags |= GRAB_TEMP_GLOBAL;
			} else {
			    XUngrabPointer(dispPtr->display, CurrentTime);
			}
		    }
		}
		dispPtr->buttonWinPtr = winPtr;
		return 1;
	    }
	} else {
	    if ((eventPtr->xbutton.state & ALL_BUTTONS)
		    == buttonStates[eventPtr->xbutton.button - Button1]) {
		ReleaseButtonGrab(dispPtr);			/* Note 4. */
	    }
	}
	if (winPtr2 != winPtr) {
	    TkChangeEventWindow(eventPtr, winPtr2);
	    Tk_QueueWindowEvent(eventPtr, TCL_QUEUE_HEAD);
	    return 0;						/* Note 3. */
	}
    }

    return 1;
}
Пример #23
0
int
Tk_Grab(
    Tcl_Interp *interp,		/* Used for error reporting. */
    Tk_Window tkwin,		/* Window on whose behalf the pointer is to be
				 * grabbed. */
    int grabGlobal)		/* Non-zero means issue a grab to the server
				 * so that no other application gets mouse or
				 * keyboard events. Zero means the grab only
				 * applies within this application. */
{
    int grabResult, numTries;
    TkWindow *winPtr = (TkWindow *) tkwin;
    TkDisplay *dispPtr = winPtr->dispPtr;
    TkWindow *winPtr2;
    unsigned int serial;

    ReleaseButtonGrab(dispPtr);
    if (dispPtr->eventualGrabWinPtr != NULL) {
	if ((dispPtr->eventualGrabWinPtr == winPtr)
		&& (grabGlobal == ((dispPtr->grabFlags & GRAB_GLOBAL) != 0))) {
	    return TCL_OK;
	}
	if (dispPtr->eventualGrabWinPtr->mainPtr != winPtr->mainPtr) {
	alreadyGrabbed:
	    Tcl_SetResult(interp, "grab failed: another application has grab",
		    TCL_STATIC);
	    return TCL_ERROR;
	}
	Tk_Ungrab((Tk_Window) dispPtr->eventualGrabWinPtr);
    }

    Tk_MakeWindowExist(tkwin);
#ifndef MAC_OSX_TK
    if (!grabGlobal)
#else
    if (0)
#endif
    {
	Window dummy1, dummy2;
	int dummy3, dummy4, dummy5, dummy6;
	unsigned int state;

	/*
	 * Local grab. However, if any mouse buttons are down, turn it into a
	 * global grab temporarily, until the last button goes up. This does
	 * two things: (a) it makes sure that we see the button-up event; and
	 * (b) it allows us to track mouse motion among all of the windows of
	 * this application.
	 */

	dispPtr->grabFlags &= ~(GRAB_GLOBAL|GRAB_TEMP_GLOBAL);
	XQueryPointer(dispPtr->display, winPtr->window, &dummy1,
		&dummy2, &dummy3, &dummy4, &dummy5, &dummy6, &state);
	if ((state & ALL_BUTTONS) != 0) {
	    dispPtr->grabFlags |= GRAB_TEMP_GLOBAL;
	    goto setGlobalGrab;
	}
    } else {
	dispPtr->grabFlags |= GRAB_GLOBAL;
    setGlobalGrab:

	/*
	 * Tricky point: must ungrab before grabbing. This is needed in case
	 * there is a button auto-grab already in effect. If there is, and the
	 * mouse has moved to a different window, X won't generate enter and
	 * leave events to move the mouse if we grab without ungrabbing.
	 */

	XUngrabPointer(dispPtr->display, CurrentTime);
	serial = NextRequest(dispPtr->display);

	/*
	 * Another tricky point: there are races with some window managers
	 * that can cause grabs to fail because the window manager hasn't
	 * released its grab quickly enough. To work around this problem,
	 * retry a few times after AlreadyGrabbed errors to give the grab
	 * release enough time to register with the server.
	 */

	grabResult = 0;			/* Needed only to prevent gcc compiler
					 * warnings. */
	for (numTries = 0; numTries < 10; numTries++) {
	    grabResult = XGrabPointer(dispPtr->display, winPtr->window,
		    True, ButtonPressMask|ButtonReleaseMask|ButtonMotionMask
		    |PointerMotionMask, GrabModeAsync, GrabModeAsync, None,
		    None, CurrentTime);
	    if (grabResult != AlreadyGrabbed) {
		break;
	    }
	    Tcl_Sleep(100);
	}
	if (grabResult != 0) {
	grabError:
	    if (grabResult == GrabNotViewable) {
		Tcl_SetResult(interp, "grab failed: window not viewable",
			TCL_STATIC);
	    } else if (grabResult == AlreadyGrabbed) {
		goto alreadyGrabbed;
	    } else if (grabResult == GrabFrozen) {
		Tcl_SetResult(interp,
			"grab failed: keyboard or pointer frozen", TCL_STATIC);
	    } else if (grabResult == GrabInvalidTime) {
		Tcl_SetResult(interp, "grab failed: invalid time",
			TCL_STATIC);
	    } else {
		char msg[64 + TCL_INTEGER_SPACE];

		sprintf(msg, "grab failed for unknown reason (code %d)",
			grabResult);
		Tcl_AppendResult(interp, msg, NULL);
	    }
	    return TCL_ERROR;
	}
	grabResult = XGrabKeyboard(dispPtr->display, Tk_WindowId(tkwin),
		False, GrabModeAsync, GrabModeAsync, CurrentTime);
	if (grabResult != 0) {
	    XUngrabPointer(dispPtr->display, CurrentTime);
	    goto grabError;
	}

	/*
	 * Eat up any grab-related events generated by the server for the
	 * grab. There are several reasons for doing this:
	 *
	 * 1. We have to synthesize the events for local grabs anyway, since
	 *    the server doesn't participate in them.
	 * 2. The server doesn't always generate the right events for global
	 *    grabs (e.g. it generates events even if the current window is in
	 *    the grab tree, which we don't want).
	 * 3. We want all the grab-related events to be processed immediately
	 *    (before other events that are already queued); events coming
	 *    from the server will be in the wrong place, but events we
	 *    synthesize here will go to the front of the queue.
	 */

	EatGrabEvents(dispPtr, serial);
    }

    /*
     * Synthesize leave events to move the pointer from its current window up
     * to the lowest ancestor that it has in common with the grab window.
     * However, only do this if the pointer is outside the grab window's
     * subtree but inside the grab window's application.
     */

    if ((dispPtr->serverWinPtr != NULL)
	    && (dispPtr->serverWinPtr->mainPtr == winPtr->mainPtr)) {
	for (winPtr2 = dispPtr->serverWinPtr; ; winPtr2 = winPtr2->parentPtr) {
	    if (winPtr2 == winPtr) {
		break;
	    }
	    if (winPtr2 == NULL) {
		MovePointer2(dispPtr->serverWinPtr, winPtr, NotifyGrab, 1, 0);
		break;
	    }
	}
    }
    QueueGrabWindowChange(dispPtr, winPtr);
    return TCL_OK;
}
Пример #24
0
void PodcastUrlLoader::RequestFinished(RequestState* state, QNetworkReply* reply) {
  reply->deleteLater();

  if (reply->attribute(QNetworkRequest::RedirectionTargetAttribute).isValid()) {
    const QUrl next_url = reply->url().resolved(
          reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl());

    NextRequest(next_url, state);
    return;
  }

  // Check for errors.
  if (reply->error() != QNetworkReply::NoError) {
    SendErrorAndDelete(reply->errorString(), state);
    return;
  }

  const QVariant http_status =
      reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
  if (http_status.isValid() && http_status.toInt() != 200) {
    SendErrorAndDelete(QString("HTTP %1: %2").arg(
        reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString(),
        reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString()), state);
    return;
  }

  // Check the mime type.
  const QString content_type = reply->header(QNetworkRequest::ContentTypeHeader).toString();
  if (parser_->SupportsContentType(content_type)) {
    const QVariant ret = parser_->Load(reply, reply->url());

    if (ret.canConvert<Podcast>()) {
      state->reply_->SetFinished(PodcastList() << ret.value<Podcast>());
    } else if (ret.canConvert<OpmlContainer>()) {
      state->reply_->SetFinished(ret.value<OpmlContainer>());
    } else {
      SendErrorAndDelete(tr("Failed to parse the XML for this RSS feed"), state);
      return;
    }

    delete state;
    return;
  } else if (content_type.contains("text/html")) {
    // I don't want a full HTML parser here, so do this the dirty way.
    const QString page_text = QString::fromUtf8(reply->readAll());
    int pos = 0;
    while ((pos = html_link_re_.indexIn(page_text, pos)) != -1) {
      const QString link = html_link_re_.cap(1).toLower();
      pos += html_link_re_.matchedLength();

      if (html_link_rel_re_.indexIn(link) == -1 ||
          html_link_type_re_.indexIn(link) == -1 ||
          html_link_href_re_.indexIn(link) == -1) {
        continue;
      }

      const QString link_type = html_link_type_re_.cap(1);
      const QString href = Utilities::DecodeHtmlEntities(html_link_href_re_.cap(1));

      if (parser_->supported_mime_types().contains(link_type)) {
        NextRequest(QUrl(href), state);
        return;
      }
    }

    SendErrorAndDelete(tr("HTML page did not contain any RSS feeds"), state);
  } else {
    SendErrorAndDelete(tr("Unknown content-type") + ": " + content_type, state);
  }
}
Пример #25
0
void
Tk_OwnSelection(
    Tk_Window tkwin,		/* Window to become new selection owner. */
    Atom selection,		/* Selection that window should own. */
    Tk_LostSelProc *proc,	/* Function to call when selection is taken
				 * away from tkwin. */
    ClientData clientData)	/* Arbitrary one-word argument to pass to
				 * proc. */
{
    register TkWindow *winPtr = (TkWindow *) tkwin;
    TkDisplay *dispPtr = winPtr->dispPtr;
    TkSelectionInfo *infoPtr;
    Tk_LostSelProc *clearProc = NULL;
    ClientData clearData = NULL;/* Initialization needed only to prevent
				 * compiler warning. */

    if (dispPtr->multipleAtom == None) {
	TkSelInit(tkwin);
    }
    Tk_MakeWindowExist(tkwin);

    /*
     * This code is somewhat tricky. First, we find the specified selection on
     * the selection list. If the previous owner is in this process, and is a
     * different window, then we need to invoke the clearProc. However, it's
     * dangerous to call the clearProc right now, because it could invoke a
     * Tcl script that wrecks the current state (e.g. it could delete the
     * window). To be safe, defer the call until the end of the function when
     * we no longer care about the state.
     */

    for (infoPtr = dispPtr->selectionInfoPtr; infoPtr != NULL;
	    infoPtr = infoPtr->nextPtr) {
	if (infoPtr->selection == selection) {
	    break;
	}
    }
    if (infoPtr == NULL) {
	infoPtr = (TkSelectionInfo*) ckalloc(sizeof(TkSelectionInfo));
	infoPtr->selection = selection;
	infoPtr->nextPtr = dispPtr->selectionInfoPtr;
	dispPtr->selectionInfoPtr = infoPtr;
    } else if (infoPtr->clearProc != NULL) {
	if (infoPtr->owner != tkwin) {
	    clearProc = infoPtr->clearProc;
	    clearData = infoPtr->clearData;
	} else if (infoPtr->clearProc == LostSelection) {
	    /*
	     * If the selection handler is one created by "selection own", be
	     * sure to free the record for it; otherwise there will be a
	     * memory leak.
	     */

	    ckfree((char *) infoPtr->clearData);
	}
    }

    infoPtr->owner = tkwin;
    infoPtr->serial = NextRequest(winPtr->display);
    infoPtr->clearProc = proc;
    infoPtr->clearData = clientData;

    /*
     * Note that we are using CurrentTime, even though ICCCM recommends
     * against this practice (the problem is that we don't necessarily have a
     * valid time to use). We will not be able to retrieve a useful timestamp
     * for the TIMESTAMP target later.
     */

    infoPtr->time = CurrentTime;

    /*
     * Note that we are not checking to see if the selection claim succeeded.
     * If the ownership does not change, then the clearProc may never be
     * invoked, and we will return incorrect information when queried for the
     * current selection owner.
     */

    XSetSelectionOwner(winPtr->display, infoPtr->selection, winPtr->window,
	    infoPtr->time);

    /*
     * Now that we are done, we can invoke clearProc without running into
     * reentrancy problems.
     */

    if (clearProc != NULL) {
	(*clearProc)(clearData);
    }
}
static int
X11Error(Display *display, XErrorEvent *event) {
  // Get an indication of how long ago the request that caused the error was
  // made.
  unsigned long age = NextRequest(display) - event->serial;

  // Get a string to represent the request that caused the error.
  nsAutoCString message;
  if (event->request_code < 128) {
    // Core protocol request
    message.AppendInt(event->request_code);
  } else {
    // Extension request

    // man XSetErrorHandler says "the error handler should not call any
    // functions (directly or indirectly) on the display that will generate
    // protocol requests or that will look for input events" so we use another
    // temporary Display to request extension information.  This assumes on
    // the DISPLAY environment variable has been set and matches what was used
    // to open |display|.
    Display *tmpDisplay = XOpenDisplay(NULL);
    if (tmpDisplay) {
      int nExts;
      char** extNames = XListExtensions(tmpDisplay, &nExts);
      int first_error;
      if (extNames) {
        for (int i = 0; i < nExts; ++i) {
          int major_opcode, first_event;
          if (XQueryExtension(tmpDisplay, extNames[i],
                              &major_opcode, &first_event, &first_error)
              && major_opcode == event->request_code) {
            message.Append(extNames[i]);
            message.Append('.');
            message.AppendInt(event->minor_code);
            break;
          }
        }

        XFreeExtensionList(extNames);
      }
      XCloseDisplay(tmpDisplay);

#ifdef MOZ_WIDGET_GTK2
      // GDK2 calls XCloseDevice the devices that it opened on startup, but
      // the XI protocol no longer ensures that the devices will still exist.
      // If they have been removed, then a BadDevice error results.  Ignore
      // this error.
      if (message.EqualsLiteral("XInputExtension.4") &&
          event->error_code == first_error + 0) {
        return 0;
      }
#endif
    }
  }

  char buffer[BUFSIZE];
  if (message.IsEmpty()) {
    buffer[0] = '\0';
  } else {
    XGetErrorDatabaseText(display, "XRequest", message.get(), "",
                          buffer, sizeof(buffer));
  }

  nsAutoCString notes;
  if (buffer[0]) {
    notes.Append(buffer);
  } else {
    notes.Append("Request ");
    notes.AppendInt(event->request_code);
    notes.Append('.');
    notes.AppendInt(event->minor_code);
  }

  notes.Append(": ");

  // Get a string to describe the error.
  XGetErrorText(display, event->error_code, buffer, sizeof(buffer));
  notes.Append(buffer);

  // For requests where Xlib gets the reply synchronously, |age| will be 1
  // and the stack will include the function making the request.  For
  // asynchronous requests, the current stack will often be unrelated to the
  // point of making the request, even if |age| is 1, but sometimes this may
  // help us count back to the point of the request.  With XSynchronize on,
  // the stack will include the function making the request, even though
  // |age| will be 2 for asynchronous requests because XSynchronize is
  // implemented by an empty request from an XSync, which has not yet been
  // processed.
  if (age > 1) {
    // XSynchronize returns the previous "after function".  If a second
    // XSynchronize call returns the same function after an enable call then
    // synchronization must have already been enabled.
    if (XSynchronize(display, True) == XSynchronize(display, False)) {
      notes.Append("; sync");
    } else {
      notes.Append("; ");
      notes.AppendInt(uint32_t(age));
      notes.Append(" requests ago");
    }
  }

#ifdef MOZ_CRASHREPORTER
  switch (XRE_GetProcessType()) {
  case GeckoProcessType_Default:
  case GeckoProcessType_Plugin:
  case GeckoProcessType_Content:
    CrashReporter::AppendAppNotesToCrashReport(notes);
    break;
  default: 
    ; // crash report notes not supported.
  }
#endif

#ifdef DEBUG
  // The resource id is unlikely to be useful in a crash report without
  // context of other ids, but add it to the debug console output.
  notes.Append("; id=0x");
  notes.AppendInt(uint32_t(event->resourceid), 16);
#ifdef MOZ_X11
  // Actually, for requests where Xlib gets the reply synchronously,
  // MOZ_X_SYNC=1 will not be necessary, but we don't have a table to tell us
  // which requests get a synchronous reply.
  if (!PR_GetEnv("MOZ_X_SYNC")) {
    notes.Append("\nRe-running with MOZ_X_SYNC=1 in the environment may give a more helpful backtrace.");
  }
#endif
#endif

#ifdef MOZ_WIDGET_QT
  // We should not abort here if MOZ_X_SYNC is not set
  // until http://bugreports.qt.nokia.com/browse/QTBUG-4042
  // not fixed, just print error value
  if (!PR_GetEnv("MOZ_X_SYNC")) {
    fprintf(stderr, "XError: %s\n", notes.get());
    return 0; // temporary workaround for bug 161472
  }
#endif

  NS_RUNTIMEABORT(notes.get());
  return 0; // not reached
}
Пример #27
0
/*
 * XmuPrintDefaultErrorMessage - print a nice error that looks like the usual
 * message.  Returns 1 if the caller should consider exitting else 0.
 */
int
XmuPrintDefaultErrorMessage(Display *dpy, XErrorEvent *event, FILE *fp)
{
    char buffer[BUFSIZ];
    char mesg[BUFSIZ];
    char number[32];
    _Xconst char *mtype = "XlibMessage";
    register _XExtension *ext = (_XExtension *)NULL;
    _XExtension *bext = (_XExtension *)NULL;
    XGetErrorText(dpy, event->error_code, buffer, BUFSIZ);
    XGetErrorDatabaseText(dpy, mtype, "XError", "X Error", mesg, BUFSIZ);
    (void) fprintf(fp, "%s:  %s\n  ", mesg, buffer);
    XGetErrorDatabaseText(dpy, mtype, "MajorCode", "Request Major code %d",
	mesg, BUFSIZ);
    (void) fprintf(fp, mesg, event->request_code);
    if (event->request_code < 128) {
	XmuSnprintf(number, sizeof(number), "%d", event->request_code);
	XGetErrorDatabaseText(dpy, "XRequest", number, "", buffer, BUFSIZ);
    } else {
	/* XXX this is non-portable */
	for (ext = dpy->ext_procs;
	     ext && (ext->codes.major_opcode != event->request_code);
	     ext = ext->next)
	  ;
	if (ext)
	  XmuSnprintf(buffer, sizeof(buffer), "%s", ext->name);
	else
	    buffer[0] = '\0';
    }
    (void) fprintf(fp, " (%s)", buffer);
    fputs("\n  ", fp);
    if (event->request_code >= 128) {
	XGetErrorDatabaseText(dpy, mtype, "MinorCode", "Request Minor code %d",
			      mesg, BUFSIZ);
	(void) fprintf(fp, mesg, event->minor_code);
	if (ext) {
	    XmuSnprintf(mesg, sizeof(mesg),
			"%s.%d", ext->name, event->minor_code);
	    XGetErrorDatabaseText(dpy, "XRequest", mesg, "", buffer, BUFSIZ);
	    (void) fprintf(fp, " (%s)", buffer);
	}
	fputs("\n  ", fp);
    }
    if (event->error_code >= 128) {
	/* kludge, try to find the extension that caused it */
	buffer[0] = '\0';
	for (ext = dpy->ext_procs; ext; ext = ext->next) {
	    if (ext->error_string)
		(*ext->error_string)(dpy, event->error_code, &ext->codes,
				     buffer, BUFSIZ);
	    if (buffer[0]) {
		bext = ext;
		break;
	    }
	    if (ext->codes.first_error &&
		ext->codes.first_error < event->error_code &&
		(!bext || ext->codes.first_error > bext->codes.first_error))
		bext = ext;
	}
	if (bext)
	    XmuSnprintf(buffer, sizeof(buffer), "%s.%d", bext->name,
			event->error_code - bext->codes.first_error);
	else
	    strcpy(buffer, "Value");
	XGetErrorDatabaseText(dpy, mtype, buffer, "", mesg, BUFSIZ);
	if (mesg[0]) {
	    fputs("  ", fp);
	    (void) fprintf(fp, mesg, event->resourceid);
	    fputs("\n", fp);
	}
	/* let extensions try to print the values */
	for (ext = dpy->ext_procs; ext; ext = ext->next) {
	    if (ext->error_values)
		(*ext->error_values)(dpy, event, fp);
	}
    } else if ((event->error_code == BadWindow) ||
	       (event->error_code == BadPixmap) ||
	       (event->error_code == BadCursor) ||
	       (event->error_code == BadFont) ||
	       (event->error_code == BadDrawable) ||
	       (event->error_code == BadColor) ||
	       (event->error_code == BadGC) ||
	       (event->error_code == BadIDChoice) ||
	       (event->error_code == BadValue) ||
	       (event->error_code == BadAtom)) {
	if (event->error_code == BadValue)
	    XGetErrorDatabaseText(dpy, mtype, "Value", "Value 0x%x",
				  mesg, BUFSIZ);
	else if (event->error_code == BadAtom)
	    XGetErrorDatabaseText(dpy, mtype, "AtomID", "AtomID 0x%x",
				  mesg, BUFSIZ);
	else
	    XGetErrorDatabaseText(dpy, mtype, "ResourceID", "ResourceID 0x%x",
				  mesg, BUFSIZ);
	(void) fprintf(fp, mesg, event->resourceid);
	fputs("\n  ", fp);
    }
    XGetErrorDatabaseText(dpy, mtype, "ErrorSerial", "Error Serial #%d",
	mesg, BUFSIZ);
    (void) fprintf(fp, mesg, event->serial);
    fputs("\n  ", fp);
    XGetErrorDatabaseText(dpy, mtype, "CurrentSerial", "Current Serial #%d",
	mesg, BUFSIZ);
    (void) fprintf(fp, mesg, NextRequest(dpy)-1);
    fputs("\n", fp);
    if (event->error_code == BadImplementation) return 0;
    return 1;
}
Пример #28
0
XdviGetWindowProperty(Display *display,
		      Window w,
		      Atom property,
		      long long_offset,
		      long long_length,
		      Bool delete,
		      Atom req_type,
		      Atom *actual_type_return,
		      int *actual_format_return,
		      unsigned long *nitems_return,
		      unsigned long *bytes_after_return,
		      unsigned char **prop_return)
{
    int retval;

    xdvi_next_request = NextRequest(display);
    xerrno = 0;

    retval = XGetWindowProperty(display, w, property, long_offset,
				long_length, delete, req_type,
				actual_type_return, actual_format_return,
				nitems_return, bytes_after_return, prop_return);

    return (xerrno != 0 ? BadWindow : retval);
}

/* helper function to set a string property of type `prop' for window `win' */
void
set_string_property(const char *str, Atom prop, Window win)
{
    XChangeProperty(DISP, win, prop, prop, 8, PropModeReplace,
Пример #29
0
static void
gdk_window_queue (GdkWindow          *window,
		  GdkWindowQueueItem *item)
{
  GdkX11Display *display_x11 = GDK_X11_DISPLAY (GDK_WINDOW_DISPLAY (window));
  
  if (!display_x11->translate_queue)
    display_x11->translate_queue = g_queue_new ();

  /* Keep length of queue finite by, if it grows too long,
   * figuring out the latest relevant serial and discarding
   * irrelevant queue items.
   */
  if (display_x11->translate_queue->length >= 64)
    {
      gulong serial = find_current_serial (GDK_WINDOW_XDISPLAY (window));
      GList *tmp_list = display_x11->translate_queue->head;
      
      while (tmp_list)
	{
	  GdkWindowQueueItem *item = tmp_list->data;
	  GList *next = tmp_list->next;
	  
	  /* an overflow-safe (item->serial < serial) */
	  if (item->serial - serial > (gulong) G_MAXLONG)
	    {
	      queue_delete_link (display_x11->translate_queue, tmp_list);
	      queue_item_free (item);
	    }

	  tmp_list = next;
	}
    }

  /* Catch the case where someone isn't processing events and there
   * is an event stuck in the event queue with an old serial:
   * If we can't reduce the queue length by the above method,
   * discard anti-expose items. (We can't discard translate
   * items 
   */
  if (display_x11->translate_queue->length >= 64)
    {
      GList *tmp_list = display_x11->translate_queue->head;
      
      while (tmp_list)
	{
	  GdkWindowQueueItem *item = tmp_list->data;
	  GList *next = tmp_list->next;
	  
	  queue_delete_link (display_x11->translate_queue, tmp_list);
	  queue_item_free (item);

	  tmp_list = next;
	}
    }

  item->window = window;
  item->serial = NextRequest (GDK_WINDOW_XDISPLAY (window));
  
  g_object_add_weak_pointer (G_OBJECT (window),
			     (gpointer *)&(item->window));

  g_queue_push_tail (display_x11->translate_queue, item);
}