Ejemplo n.º 1
0
int main(void)
{
	Display *dpy;
	int i, j, fd;
	unsigned int attachments[] = {
		DRI2BufferBackLeft,
		DRI2BufferFrontLeft,
	};
	XRRScreenResources *res;

	dpy = XOpenDisplay(NULL);
	if (dpy == NULL)
		return 77;

	if (!XRRQueryVersion(dpy, &i, &j))
		return 77;

	fd = dri2_open(dpy);
	if (fd < 0)
		return 1;

	res = _XRRGetScreenResourcesCurrent(dpy, DefaultRootWindow(dpy));
	if (res == NULL)
		return 1;

	printf("noutput=%d, ncrtc=%d\n", res->noutput, res->ncrtc);

	for (i = 0; i < res->ncrtc; i++)
		XRRSetCrtcConfig(dpy, res, res->crtcs[i], CurrentTime,
				 0, 0, None, RR_Rotate_0, NULL, 0);
	XSync(dpy, True);

	for (i = 0; i < res->noutput; i++) {
		XRROutputInfo *output;
		XRRModeInfo *mode;

		output = XRRGetOutputInfo(dpy, res, res->outputs[i]);
		if (output == NULL)
			continue;

		mode = NULL;
		if (res->nmode)
			mode = lookup_mode(res, output->modes[0]);

		for (j = 0; mode && j < output->ncrtc; j++) {
			printf("[%d, %d] -- OUTPUT:%ld, CRTC:%ld\n",
			       i, j, (long)res->outputs[i], (long)output->crtcs[j]);
			XRRSetCrtcConfig(dpy, res, output->crtcs[j], CurrentTime,
					 0, 0, output->modes[0], RR_Rotate_0, &res->outputs[i], 1);
			XSync(dpy, True);

			run(dpy, mode->width, mode->height, attachments, 1, "fullscreen");
			run(dpy, mode->width, mode->height, attachments, 2, "fullscreen (with front)");

			run(dpy, mode->width/2, mode->height/2, attachments, 1, "windowed");
			run(dpy, mode->width/2, mode->height/2, attachments, 2, "windowed (with front)");

			XRRSetCrtcConfig(dpy, res, output->crtcs[j], CurrentTime,
					 0, 0, None, RR_Rotate_0, NULL, 0);
			XSync(dpy, True);
		}

		XRRFreeOutputInfo(output);
	}

	return 0;
}
Ejemplo n.º 2
0
Window xf_CreateDummyWindow(xfContext* xfc)
{
	return XCreateSimpleWindow(xfc->display, DefaultRootWindow(xfc->display),
	                           0, 0, 1, 1, 0, 0, 0);
}
Ejemplo n.º 3
0
static void winopen(void)
{
	XWMHints *wmhints;
	XClassHint *classhint;

	xdpy = XOpenDisplay(NULL);
	if (!xdpy)
		winerror(&gapp, fz_throw("cannot open display"));

	XA_TARGETS = XInternAtom(xdpy, "TARGETS", False);
	XA_TIMESTAMP = XInternAtom(xdpy, "TIMESTAMP", False);
	XA_UTF8_STRING = XInternAtom(xdpy, "UTF8_STRING", False);
	WM_DELETE_WINDOW = XInternAtom(xdpy, "WM_DELETE_WINDOW", False);

	xscr = DefaultScreen(xdpy);

	ximage_init(xdpy, xscr, DefaultVisual(xdpy, xscr));

	xcarrow = XCreateFontCursor(xdpy, XC_left_ptr);
	xchand = XCreateFontCursor(xdpy, XC_hand2);
	xcwait = XCreateFontCursor(xdpy, XC_watch);

	xbgcolor.red = 0x7000;
	xbgcolor.green = 0x7000;
	xbgcolor.blue = 0x7000;

	xshcolor.red = 0x4000;
	xshcolor.green = 0x4000;
	xshcolor.blue = 0x4000;

	XAllocColor(xdpy, DefaultColormap(xdpy, xscr), &xbgcolor);
	XAllocColor(xdpy, DefaultColormap(xdpy, xscr), &xshcolor);

	xwin = XCreateWindow(xdpy, DefaultRootWindow(xdpy),
		10, 10, 200, 100, 1,
		ximage_get_depth(),
		InputOutput,
		ximage_get_visual(),
		0,
		NULL);
	if (xwin == None)
		winerror(&gapp, fz_throw("cannot create window"));

	XSetWindowColormap(xdpy, xwin, ximage_get_colormap());
	XSelectInput(xdpy, xwin,
		StructureNotifyMask | ExposureMask | KeyPressMask |
		PointerMotionMask | ButtonPressMask | ButtonReleaseMask);

	mapped = 0;

	xgc = XCreateGC(xdpy, xwin, 0, NULL);

	XDefineCursor(xdpy, xwin, xcarrow);

	wmhints = XAllocWMHints();
	if (wmhints)
	{
		wmhints->flags = IconPixmapHint | IconMaskHint;
		xicon = XCreateBitmapFromData(xdpy, xwin,
			(char*)mupdf_icon_bitmap_16_bits,
			mupdf_icon_bitmap_16_width,
			mupdf_icon_bitmap_16_height);
		xmask = XCreateBitmapFromData(xdpy, xwin,
			(char*)mupdf_icon_bitmap_16_mask_bits,
			mupdf_icon_bitmap_16_mask_width,
			mupdf_icon_bitmap_16_mask_height);
		if (xicon && xmask)
		{
			wmhints->icon_pixmap = xicon;
			wmhints->icon_mask = xmask;
			XSetWMHints(xdpy, xwin, wmhints);
		}
		XFree(wmhints);
	}

	classhint = XAllocClassHint();
	if (classhint)
	{
		classhint->res_name = "mupdf";
		classhint->res_class = "MuPDF";
		XSetClassHint(xdpy, xwin, classhint);
		XFree(classhint);
	}

	XSetWMProtocols(xdpy, xwin, &WM_DELETE_WINDOW, 1);

	x11fd = ConnectionNumber(xdpy);
}
CXWindowsScreenSaver::CXWindowsScreenSaver(
				CXWindowsScreen* screen, Display* display) :
	m_screen(screen),
	m_display(display),
	m_notify(None),
	m_xscreensaver(None),
	m_xscreensaverActive(false),
	m_disabled(false),
	m_suppressDisable(false),
	m_disableJobInstalled(false)
{
	// screen saver disable callback
	m_disableJob = new TMethodJob<CXWindowsScreenSaver>(this,
								&CXWindowsScreenSaver::disableCallback);

	// get atoms
	m_atomScreenSaver           = XInternAtom(m_display,
										"SCREENSAVER", False);
	m_atomScreenSaverVersion    = XInternAtom(m_display,
										"_SCREENSAVER_VERSION", False);
	m_atomScreenSaverActivate   = XInternAtom(m_display,
										"ACTIVATE", False);
	m_atomScreenSaverDeactivate = XInternAtom(m_display,
										"DEACTIVATE", False);
	m_atomSynergyScreenSaver    = XInternAtom(m_display,
										"SYNERGY_SCREENSAVER", False);

	// create dummy window to receive xscreensaver responses.  this
	// shouldn't be necessary (we should be able to send responses
	// to None) but it doesn't hurt.
	XSetWindowAttributes attr;
	attr.event_mask            = 0;//PropertyChangeMask;
	attr.do_not_propagate_mask = 0;
	attr.override_redirect     = True;
	m_xscreensaverSink = XCreateWindow(m_display,
								DefaultRootWindow(m_display),
								0, 0, 1, 1, 0, 0,
								InputOnly, CopyFromParent,
								CWDontPropagate | CWEventMask |
								CWOverrideRedirect,
								&attr);
	LOG((CLOG_DEBUG "xscreensaver sink window is 0x%08x", m_xscreensaverSink));

	// watch top-level windows for changes
	{
		bool error = false;
		CXWindowsUtil::CErrorLock lock(m_display, &error);
		Window root = DefaultRootWindow(m_display);
		XWindowAttributes attr;
		XGetWindowAttributes(m_display, root, &attr);
		m_rootEventMask = attr.your_event_mask;
		XSelectInput(m_display, root, m_rootEventMask | SubstructureNotifyMask);
		if (error) {
			LOG((CLOG_DEBUG "didn't set root event mask"));
			m_rootEventMask = 0;
		}
	}

	// get the xscreensaver window, if any
	if (!findXScreenSaver()) {
		setXScreenSaver(None);
	}

	// get the built-in settings
	XGetScreenSaver(m_display, &m_timeout, &m_interval,
								&m_preferBlanking, &m_allowExposures);
}
Ejemplo n.º 5
0
void
setstatus(Display *dpy, char *str) {
	XStoreName(dpy, DefaultRootWindow(dpy), str);
	XSync(dpy, False);
}
Ejemplo n.º 6
0
int
X11_Init(void)
{

    char buf[512];
    char *displayname;

    XGCValues gcvalues;

    /* grrr, Xtk forced contortions */
    char *argv[2];
    int argc = 2;

    if (cp_getvar("display", VT_STRING, buf)) {
      displayname = buf;
    } else if (!(displayname = getenv("DISPLAY"))) {
      internalerror("Can't open X display.");
      return (1);
    }

#  ifdef DEBUG
    _Xdebug = 1;
#  endif

    argv[0] = "ngspice";
    argv[1] = displayname;
/*
    argv[2] = "-geometry";
    argv[3] = "=1x1+2+2";
*/

    /* initialize X toolkit */
    toplevel = XtInitialize("ngspice", "Nutmeg", NULL, 0, &argc, argv);

    display = XtDisplay(toplevel);

    X11_Open = 1;

    /* "invert" works better than "xor" for B&W */

    /* xor gc should be a function of the pixels that are written on */
    /* gcvalues.function = GXxor; */
    /* this patch makes lines visible on true color displays
    Guenther Roehrich 22-Jan-99 */
    gcvalues.function = GXinvert;
    gcvalues.line_width = 1;
    gcvalues.foreground = 1;
    gcvalues.background = 0;

    xorgc = XCreateGC(display, DefaultRootWindow(display),
	    GCLineWidth | GCFunction | GCForeground | GCBackground,
	    &gcvalues);

    /* set correct information */
    dispdev->numlinestyles = NUMLINESTYLES;
    dispdev->numcolors = NUMCOLORS;

    dispdev->width = DisplayWidth(display, DefaultScreen(display));
    dispdev->height = DisplayHeight(display, DefaultScreen(display));

    /* we don't want non-fatal X errors to call exit */
    XSetErrorHandler(errorhandler);

    numdispplanes = DisplayPlanes(display, DefaultScreen(display));

    return (0);

}
Ejemplo n.º 7
0
bool CWinSystemX11::HasWindowManager()
{
  Window wm_check;
  unsigned char *data;
  int status, real_format;
  Atom real_type, prop;
  unsigned long items_read, items_left;

  prop = XInternAtom(m_dpy, "_NET_SUPPORTING_WM_CHECK", True);
  if (prop == None)
    return false;
  status = XGetWindowProperty(m_dpy, DefaultRootWindow(m_dpy), prop,
                      0L, 1L, False, XA_WINDOW, &real_type, &real_format,
                      &items_read, &items_left, &data);
  if(status != Success || ! items_read)
  {
    if(status == Success)
      XFree(data);
    return false;
  }

  wm_check = ((Window*)data)[0];
  XFree(data);

  status = XGetWindowProperty(m_dpy, wm_check, prop,
                      0L, 1L, False, XA_WINDOW, &real_type, &real_format,
                      &items_read, &items_left, &data);

  if(status != Success || !items_read)
  {
    if(status == Success)
      XFree(data);
    return false;
  }

  if(wm_check != ((Window*)data)[0])
  {
    XFree(data);
    return false;
  }

  XFree(data);

  prop = XInternAtom(m_dpy, "_NET_WM_NAME", True);
  if (prop == None)
  {
    CLog::Log(LOGDEBUG,"Window Manager Name: ");
    return true;
  }

  status = XGetWindowProperty(m_dpy, wm_check, prop,
                        0L, (~0L), False, AnyPropertyType, &real_type, &real_format,
                        &items_read, &items_left, &data);

  if(status == Success && items_read)
  {
    CLog::Log(LOGDEBUG,"Window Manager Name: %s", data);
  }
  else
    CLog::Log(LOGDEBUG,"Window Manager Name: ");

  if(status == Success)
    XFree(data);

  return true;
}
Ejemplo n.º 8
0
static cairo_surface_t *
_cairo_boilerplate_gl_create_window_db (const char		  *name,
					cairo_content_t 	   content,
					double			   width,
					double			   height,
					double			   max_width,
					double			   max_height,
					cairo_boilerplate_mode_t   mode,
					int			   id,
					void			 **closure)
{
    int rgba_attribs[] = { GLX_RGBA,
			   GLX_RED_SIZE, 1,
			   GLX_GREEN_SIZE, 1,
			   GLX_BLUE_SIZE, 1,
			   GLX_ALPHA_SIZE, 1,
			   GLX_DOUBLEBUFFER,
			   None };
    XVisualInfo *vi;
    GLXContext ctx;
    gl_target_closure_t *gltc;
    cairo_surface_t *surface;
    Display *dpy;
    XSetWindowAttributes attr;
    cairo_status_t status;

    gltc = calloc (1, sizeof (gl_target_closure_t));
    *closure = gltc;

    if (width == 0)
	width = 1;
    if (height == 0)
	height = 1;

    dpy = XOpenDisplay (NULL);
    gltc->dpy = dpy;
    if (!gltc->dpy) {
	fprintf (stderr, "Failed to open display: %s\n", XDisplayName(0));
	free (gltc);
	return NULL;
    }

    if (mode == CAIRO_BOILERPLATE_MODE_TEST)
	XSynchronize (gltc->dpy, 1);

    vi = glXChooseVisual (dpy, DefaultScreen (dpy), rgba_attribs);
    if (vi == NULL) {
	fprintf (stderr, "Failed to create RGBA, double-buffered visual\n");
	XCloseDisplay (dpy);
	free (gltc);
	return NULL;
    }

    attr.colormap = XCreateColormap (dpy,
				     RootWindow (dpy, vi->screen),
				     vi->visual,
				     AllocNone);
    attr.border_pixel = 0;
    attr.override_redirect = True;
    gltc->drawable = XCreateWindow (dpy, DefaultRootWindow (dpy), 0, 0,
				    width, height, 0, vi->depth,
				    InputOutput, vi->visual,
				    CWOverrideRedirect | CWBorderPixel | CWColormap,
				    &attr);
    XMapWindow (dpy, gltc->drawable);

    ctx = glXCreateContext (dpy, vi, NULL, True);
    XFree (vi);

    gltc->ctx = ctx;
    gltc->device = cairo_glx_device_create (dpy, ctx);

    gltc->surface = cairo_gl_surface_create_for_window (gltc->device,
							gltc->drawable,
							ceil (width),
							ceil (height));
    surface = cairo_surface_create_similar (gltc->surface, content, width, height);
    status = cairo_surface_set_user_data (surface, &gl_closure_key, gltc, NULL);
    if (status == CAIRO_STATUS_SUCCESS)
	return surface;

    cairo_surface_destroy (surface);
    _cairo_boilerplate_gl_cleanup (gltc);
    return cairo_boilerplate_surface_create_in_error (status);
}
Ejemplo n.º 9
0
Archivo: vo_xv.c Proyecto: 2ion/mpv
static int preinit(struct vo *vo)
{
    XvPortID xv_p;
    int busy_ports = 0;
    unsigned int i;
    struct xvctx *ctx = vo->priv;
    int xv_adaptor = ctx->cfg_xv_adaptor;

    if (!vo_x11_init(vo))
        return -1;

    if (!vo_x11_create_vo_window(vo, NULL, "xv"))
        goto error;

    struct vo_x11_state *x11 = vo->x11;

    /* check for Xvideo extension */
    unsigned int ver, rel, req, ev, err;
    if (Success != XvQueryExtension(x11->display, &ver, &rel, &req, &ev, &err)) {
        MP_ERR(vo, "Xv not supported by this X11 version/driver\n");
        goto error;
    }

    /* check for Xvideo support */
    if (Success !=
        XvQueryAdaptors(x11->display, DefaultRootWindow(x11->display),
                        &ctx->adaptors, &ctx->ai)) {
        MP_ERR(vo, "XvQueryAdaptors failed.\n");
        goto error;
    }

    /* check adaptors */
    if (ctx->xv_port) {
        int port_found;

        for (port_found = 0, i = 0; !port_found && i < ctx->adaptors; i++) {
            if ((ctx->ai[i].type & XvInputMask)
                && (ctx->ai[i].type & XvImageMask)) {
                for (xv_p = ctx->ai[i].base_id;
                     xv_p < ctx->ai[i].base_id + ctx->ai[i].num_ports;
                     ++xv_p) {
                    if (xv_p == ctx->xv_port) {
                        port_found = 1;
                        break;
                    }
                }
            }
        }
        if (port_found) {
            if (XvGrabPort(x11->display, ctx->xv_port, CurrentTime))
                ctx->xv_port = 0;
        } else {
            MP_WARN(vo, "Invalid port parameter, overriding with port 0.\n");
            ctx->xv_port = 0;
        }
    }

    for (i = 0; i < ctx->adaptors && ctx->xv_port == 0; i++) {
        /* check if adaptor number has been specified */
        if (xv_adaptor != -1 && xv_adaptor != i)
            continue;

        if ((ctx->ai[i].type & XvInputMask) && (ctx->ai[i].type & XvImageMask)) {
            for (xv_p = ctx->ai[i].base_id;
                 xv_p < ctx->ai[i].base_id + ctx->ai[i].num_ports; ++xv_p)
                if (!XvGrabPort(x11->display, xv_p, CurrentTime)) {
                    ctx->xv_port = xv_p;
                    MP_VERBOSE(vo, "Using Xv Adapter #%d (%s)\n",
                               i, ctx->ai[i].name);
                    break;
                } else {
                    MP_WARN(vo, "Could not grab port %i.\n", (int) xv_p);
                    ++busy_ports;
                }
        }
    }
    if (!ctx->xv_port) {
        if (busy_ports)
            MP_ERR(vo, "Xvideo ports busy.\n");
        else
            MP_ERR(vo, "No Xvideo support found.\n");
        goto error;
    }

    if (!xv_init_colorkey(vo)) {
        goto error;             // bail out, colorkey setup failed
    }
    xv_enable_vsync(vo);
    xv_get_max_img_dim(vo, &ctx->max_width, &ctx->max_height);

    ctx->fo = XvListImageFormats(x11->display, ctx->xv_port,
                                 (int *) &ctx->formats);

    MP_WARN(vo, "Warning: this legacy VO has bad quality and performance, "
                "and will in particular result in blurry OSD and subtitles. "
                "You should fix your graphic drivers, or not force the xv VO.\n");
    return 0;

  error:
    uninit(vo);                 // free resources
    return -1;
}
Ejemplo n.º 10
0
static int _x11_clip_filter(const SDL_Event *ev)
{
        XSelectionRequestEvent *req;
        XEvent sevent;
        Atom seln_type;
        int seln_format;
        unsigned long nbytes;
        unsigned long overflow;
        unsigned char *seln_data;
        unsigned char *src;

        if (ev->type != SDL_SYSWMEVENT) return 1;
        if (ev->syswm.msg->event.xevent.type == SelectionNotify) {
                sevent = ev->syswm.msg->event.xevent;
                if (sevent.xselection.requestor == SDL_Window) {
                        lock_display();
                        src = NULL;
                        if (XGetWindowProperty(SDL_Display, SDL_Window, atom_sel,
                                                0, 9000, False, XA_STRING,
                                                (Atom *)&seln_type,
                                                (int *)&seln_format,
                                                (unsigned long *)&nbytes,
                                                (unsigned long *)&overflow,
                                                (unsigned char **)&src) == Success) {
                                if (seln_type == XA_STRING) {
                                        if (_current_selection != _current_clipboard) {
                                                free(_current_clipboard);
                                        }
                                        _current_clipboard = mem_alloc(nbytes+1);
                                        memcpy(_current_clipboard, (char*)src, nbytes);
                                        _current_clipboard[nbytes] = 0;
                                        _string_paste(CLIPPY_BUFFER, _current_clipboard);
                                        _widget_owner[CLIPPY_BUFFER]
                                                        = _widget_owner[CLIPPY_SELECT];
                                }
                                XFree(src);
                        }
                        unlock_display();
                }
                return 1;
        } else if (ev->syswm.msg->event.xevent.type == PropertyNotify) {
                sevent = ev->syswm.msg->event.xevent;
                return 1;

        } else if (ev->syswm.msg->event.xevent.type != SelectionRequest) {
                return 1;
        }

        req = &ev->syswm.msg->event.xevent.xselectionrequest;
        sevent.xselection.type = SelectionNotify;
        sevent.xselection.display = req->display;
        sevent.xselection.selection = req->selection;
        sevent.xselection.target = None;
        sevent.xselection.property = None;
        sevent.xselection.requestor = req->requestor;
        sevent.xselection.time = req->time;
        if (XGetWindowProperty(SDL_Display, DefaultRootWindow(SDL_Display),
                        XA_CUT_BUFFER0, 0, 9000, False, req->target,
                        &sevent.xselection.target, &seln_format,
                        &nbytes, &overflow, &seln_data) == Success) {
                if (sevent.xselection.target == req->target) {
                        if (sevent.xselection.target == XA_STRING) {
                                if (nbytes && seln_data[nbytes-1] == '\0')
                                        nbytes--;
                        }
                        XChangeProperty(SDL_Display, req->requestor, req->property,
                                sevent.xselection.target, seln_format, PropModeReplace,
                                seln_data, nbytes);
                        sevent.xselection.property = req->property;
                }
                XFree(seln_data);
        }
        XSendEvent(SDL_Display,req->requestor,False,0,&sevent);
        XSync(SDL_Display, False);
        return 1;
}
Ejemplo n.º 11
0
static void _clippy_copy_to_sys(int do_sel)
{
        int j;
        char *dst;
        char *freeme;
#if defined(__QNXNTO__)
        PhClipboardHdr clheader = {Ph_CLIPBOARD_TYPE_TEXT, 0, NULL};
        char *tmp;
        int *cldata;
        int status;
#endif

        freeme = NULL;
        if (!_current_selection) {
                dst = NULL;
                j = 0;
        } else
#if defined(WIN32)
        j = strlen(_current_selection);
#else
        if (has_sys_clip) {
                int i;
                /* convert to local */
                freeme = dst = malloc(strlen(_current_selection)+4);
                if (!dst) return;
                for (i = j = 0; _current_selection[i]; i++) {
                        dst[j] = _current_selection[i];
                        if (dst[j] != '\r') j++;
                }
                dst[j] = '\0';
        } else {
                dst = NULL;
                j = 0;
        }
#endif
#if defined(USE_X11)
        if (has_sys_clip) {
                lock_display();
                if (!dst) dst = (char *) ""; /* blah */
                if (j < 0) j = 0;
                if (do_sel) {
                        if (XGetSelectionOwner(SDL_Display, XA_PRIMARY) != SDL_Window) {
                                XSetSelectionOwner(SDL_Display, XA_PRIMARY, SDL_Window, CurrentTime);
                        }
                        XChangeProperty(SDL_Display,
                                DefaultRootWindow(SDL_Display),
                                XA_CUT_BUFFER1, XA_STRING, 8,
                                PropModeReplace, (unsigned char *)dst, j);
                } else {
                        if (XGetSelectionOwner(SDL_Display, atom_clip) != SDL_Window) {
                                XSetSelectionOwner(SDL_Display, atom_clip, SDL_Window, CurrentTime);
                        }
                        XChangeProperty(SDL_Display,
                                DefaultRootWindow(SDL_Display),
                                XA_CUT_BUFFER0, XA_STRING, 8,
                                PropModeReplace, (unsigned char *)dst, j);
                        XChangeProperty(SDL_Display,
                                DefaultRootWindow(SDL_Display),
                                XA_CUT_BUFFER1, XA_STRING, 8,
                                PropModeReplace, (unsigned char *)dst, j);
                }
                unlock_display();
        }
#elif defined(WIN32)
        if (!do_sel && OpenClipboard(SDL_Window)) {
                _hmem = GlobalAlloc((GMEM_MOVEABLE|GMEM_DDESHARE), j+1);
                if (_hmem) {
                        dst = (char *)GlobalLock(_hmem);
                        if (dst) {
                                /* this seems wrong, but msdn does this */
                                memcpy(dst, _current_selection, j);
                                dst[j] = '\0';
                                GlobalUnlock(_hmem);
                                EmptyClipboard();
                                SetClipboardData(CF_TEXT, _hmem);
                        }
                }
                CloseClipboard();
                _hmem = NULL;
                dst = 0;
        }
#elif defined(__QNXNTO__)
        if (!do_sel) {
                tmp = (char *)malloc(j+4);
                if (!tmp) {
                        cldata=(int*)tmp;
                        *cldata = Ph_CL_TEXT;
                        if (dst) memcpy(tmp+4, dst, j);
                        clheader.data = tmp;
#if (NTO_VERSION < 620)
                        if (clheader.length > 65535) clheader.length=65535;
#endif
                        clheader.length = j + 4;
#if (NTO_VERSION < 620)
                        PhClipboardCopy(inputgroup, 1, &clheader);
#else
                        PhClipboardWrite(inputgroup, 1, &clheader);
#endif
                        free(tmp);
                }
        }
#elif defined(MACOSX)
        if (!do_sel) macosx_clippy_put(_current_clipboard);
#else
        // some other system -- linux without x11, maybe
        // pretend we used the param to silence warnings
        (void) do_sel;
#endif
        if (freeme)
                free(freeme);
}
Ejemplo n.º 12
0
int GetIdleTime(Display *dpy, XScreenSaverInfo *info){
    XScreenSaverQueryInfo(dpy, DefaultRootWindow(dpy), info);
    return (int)info->idle;
}
Ejemplo n.º 13
0
/*ARGSUSED*/
int
main(int argc, char *argv[]) {
    XEvent ev;
    XGCValues gv;
    XSetWindowAttributes attr;
    
    (void) argc;
    argv0 = argv[0];
    
    /* Open a connection to the X server. */
    dpy = XOpenDisplay("");
    if (dpy == 0)
        Panic("can't open display.");
    
    get_resources();
    
    /* Find the screen's dimensions. */
    display_width = DisplayWidth(dpy, DefaultScreen(dpy));
    display_height = DisplayHeight(dpy, DefaultScreen(dpy));
    
    /* Set up an error handler. */
    XSetErrorHandler(ErrorHandler);
    
    /* Get the pixel values of the only two colours we use. */
    black = BlackPixel(dpy, DefaultScreen(dpy));
    white = WhitePixel(dpy, DefaultScreen(dpy));
    
    /* Get font. */
    font = XLoadQueryFont(dpy, font_name);
    if (font == 0)
        font = XLoadQueryFont(dpy, "fixed");
    if (font == 0)
        Panic("can't find a font.");
    
    /* Get a cursor. */
    initCursor();
    
    /* Create the window. */
    root = DefaultRootWindow(dpy);
    attr.override_redirect = True;
    attr.background_pixel = white;
    attr.border_pixel = black;
    attr.cursor = mouse_cursor;
    attr.event_mask = ExposureMask | VisibilityChangeMask |
        ButtonMotionMask | PointerMotionHintMask |
        ButtonPressMask | ButtonReleaseMask | StructureNotifyMask |
        EnterWindowMask | LeaveWindowMask;
    window = XCreateWindow(dpy, root,
        0, 0,
        display_width, 1.2 * (font->ascent + font->descent),
        0, CopyFromParent, InputOutput, CopyFromParent,
        CWOverrideRedirect | CWBackPixel | CWBorderPixel |
        CWCursor | CWEventMask,
        &attr);
    
    /* Create GC. */
    gv.foreground = black;
    gv.background = white;
    gv.font = font->fid;
    gc = XCreateGC(dpy, window, GCForeground | GCBackground | GCFont,
        &gv);
    
    /* Create the menu items. */
    readMenu();
    
    /* Bring up the window. */
    XMapRaised(dpy, window);
    
    /* Make sure all our communication to the server got through. */
    XSync(dpy, False);
    
    /* The main event loop. */
    for (;;) {
        getEvent(&ev);
        dispatch(&ev);
    }
}
Ejemplo n.º 14
0
/*************************************<->*************************************
 *
 *  Cursor _DtGetHourGlassCursor ()
 *
 *
 *  Description:
 *  -----------
 *  Builds and returns the appropriate Hourglass cursor
 *
 *
 *  Inputs:
 *  ------
 *  dpy	= display
 * 
 *  Outputs:
 *  -------
 *  Return = cursor.
 *
 *  Comments:
 *  --------
 *  None. (None doesn't count as a comment)
 * 
 *************************************<->***********************************/
Cursor 
_DtGetHourGlassCursor(
        Display *dpy )
{
    unsigned char *bits;
    unsigned char *maskBits;
    unsigned int width;
    unsigned int height;
    unsigned int xHotspot;
    unsigned int yHotspot;
    Pixmap       pixmap;
    Pixmap       maskPixmap;
    XColor       xcolors[2];
    int          scr;
    unsigned int cWidth;
    unsigned int cHeight;
    int		 useLargeCursors = 0;
    static Cursor waitCursor=0;

    _DtSvcProcessLock();
    if (waitCursor != 0) {
      _DtSvcProcessUnlock();
      return(waitCursor);
    }

    if (XQueryBestCursor (dpy, DefaultRootWindow(dpy), 
	32, 32, &cWidth, &cHeight))
    {
	if ((cWidth >= 32) && (cHeight >= 32))
	{
	    useLargeCursors = 1;
	}
    }

    if (useLargeCursors)
    {
	width = time32_width;
	height = time32_height;
	bits = time32_bits;
	maskBits = time32m_bits;
	xHotspot = time32_x_hot;
	yHotspot = time32_y_hot;
    }
    else
    {
	width = time16_width;
	height = time16_height;
	bits = time16_bits;
	maskBits = time16m_bits;
	xHotspot = time16_x_hot;
	yHotspot = time16_y_hot;
    }

    pixmap = XCreateBitmapFromData (dpy, 
		     DefaultRootWindow(dpy), (char*) bits, 
		     width, height);

  
    maskPixmap = XCreateBitmapFromData (dpy, 
		     DefaultRootWindow(dpy), (char*) maskBits, 
		     width, height);

    xcolors[0].pixel = BlackPixelOfScreen(DefaultScreenOfDisplay(dpy));
    xcolors[1].pixel = WhitePixelOfScreen(DefaultScreenOfDisplay(dpy));

    XQueryColors (dpy, 
		  DefaultColormapOfScreen(DefaultScreenOfDisplay
					  (dpy)), xcolors, 2);

    waitCursor = XCreatePixmapCursor (dpy, pixmap, maskPixmap,
				      &(xcolors[0]), &(xcolors[1]),
				      xHotspot, yHotspot);
    XFreePixmap (dpy, pixmap);
    XFreePixmap (dpy, maskPixmap);

    _DtSvcProcessUnlock();
    return (waitCursor);
}
Ejemplo n.º 15
0
bool wxTopLevelWindowGTK::Show( bool show )
{
    wxASSERT_MSG( (m_widget != NULL), wxT("invalid frame") );

    bool deferShow = show && !m_isShown && m_deferShow;
    if (deferShow)
    {
        deferShow = gs_requestFrameExtentsStatus != 2 &&
            m_deferShowAllowed && !gtk_widget_get_realized(m_widget);
        if (deferShow)
        {
            deferShow = g_signal_handler_find(m_widget,
                GSignalMatchType(G_SIGNAL_MATCH_ID | G_SIGNAL_MATCH_DATA),
                g_signal_lookup("property_notify_event", GTK_TYPE_WIDGET),
                0, NULL, NULL, this) != 0;
        }
        GdkScreen* screen = NULL;
        if (deferShow)
        {
#ifdef GDK_WINDOWING_X11
            screen = gtk_widget_get_screen(m_widget);
            GdkAtom atom = gdk_atom_intern("_NET_REQUEST_FRAME_EXTENTS", false);
            deferShow = gdk_x11_screen_supports_net_wm_hint(screen, atom) != 0;
#else
            deferShow = false;
#endif
            // If _NET_REQUEST_FRAME_EXTENTS not supported, don't allow changes
            // to m_decorSize, it breaks saving/restoring window size with
            // GetSize()/SetSize() because it makes window bigger between each
            // restore and save.
            m_updateDecorSize = deferShow;
        }

        m_deferShow = deferShow;
    }
    if (deferShow)
    {
        // Initial show. If WM supports _NET_REQUEST_FRAME_EXTENTS, defer
        // calling gtk_widget_show() until _NET_FRAME_EXTENTS property
        // notification is received, so correct frame extents are known.
        // This allows resizing m_widget to keep the overall size in sync with
        // what wxWidgets expects it to be without an obvious change in the
        // window size immediately after it becomes visible.

        // Realize m_widget, so m_widget->window can be used. Realizing normally
        // causes the widget tree to be size_allocated, which generates size
        // events in the wrong order. However, the size_allocates will not be
        // done if the allocation is not the default (1,1).
        GtkAllocation alloc;
        gtk_widget_get_allocation(m_widget, &alloc);
        const int alloc_width = alloc.width;
        if (alloc_width == 1)
        {
            alloc.width = 2;
            gtk_widget_set_allocation(m_widget, &alloc);
        }
        gtk_widget_realize(m_widget);
        if (alloc_width == 1)
        {
            alloc.width = 1;
            gtk_widget_set_allocation(m_widget, &alloc);
        }

#ifdef GDK_WINDOWING_X11
        // send _NET_REQUEST_FRAME_EXTENTS
        XClientMessageEvent xevent;
        memset(&xevent, 0, sizeof(xevent));
        xevent.type = ClientMessage;
        GdkWindow* window = gtk_widget_get_window(m_widget);
        xevent.window = GDK_WINDOW_XID(window);
        xevent.message_type = gdk_x11_atom_to_xatom_for_display(
            gdk_window_get_display(window),
            gdk_atom_intern("_NET_REQUEST_FRAME_EXTENTS", false));
        xevent.format = 32;
        Display* display = GDK_DISPLAY_XDISPLAY(gdk_window_get_display(window));
        XSendEvent(display, DefaultRootWindow(display), false,
            SubstructureNotifyMask | SubstructureRedirectMask,
            (XEvent*)&xevent);
#endif // GDK_WINDOWING_X11

        if (gs_requestFrameExtentsStatus == 0)
        {
            // if WM does not respond to request within 1 second,
            // we assume support for _NET_REQUEST_FRAME_EXTENTS is not working
            m_netFrameExtentsTimerId =
                g_timeout_add(1000, request_frame_extents_timeout, this);
        }

        // defer calling gtk_widget_show()
        m_isShown = true;
        return true;
    }

    if (show && !gtk_widget_get_realized(m_widget))
    {
        // size_allocate signals occur in reverse order (bottom to top).
        // Things work better if the initial wxSizeEvents are sent (from the
        // top down), before the initial size_allocate signals occur.
        wxSizeEvent event(GetSize(), GetId());
        event.SetEventObject(this);
        HandleWindowEvent(event);
    }

    bool change = base_type::Show(show);

    if (change && !show)
    {
        // make sure window has a non-default position, so when it is shown
        // again, it won't be repositioned by WM as if it were a new window
        // Note that this must be done _after_ the window is hidden.
        gtk_window_move((GtkWindow*)m_widget, m_x, m_y);
    }

    return change;
}
Ejemplo n.º 16
0
int
main(int argc, char *argv[])
{
    /* Declare variables */
    Window win;			/* Window */
    int exit_code;

    /* set up option table. I can't figure out a better way than this to
     * do it while sticking to pure ANSI C. The option and specifier
     * members have a type of volatile char *, so they need to be allocated
     * by strdup or malloc, you can't set them to a string constant at
     * declare time, this is note pure ANSI C apparently, although it does
     * work with gcc
     */

    /* loop option entry */
    opt_tab[0].option = xcstrdup("-loops");
    opt_tab[0].specifier = xcstrdup(".loops");
    opt_tab[0].argKind = XrmoptionSepArg;
    opt_tab[0].value = (XPointer) NULL;

    /* display option entry */
    opt_tab[1].option = xcstrdup("-display");
    opt_tab[1].specifier = xcstrdup(".display");
    opt_tab[1].argKind = XrmoptionSepArg;
    opt_tab[1].value = (XPointer) NULL;

    /* selection option entry */
    opt_tab[2].option = xcstrdup("-selection");
    opt_tab[2].specifier = xcstrdup(".selection");
    opt_tab[2].argKind = XrmoptionSepArg;
    opt_tab[2].value = (XPointer) NULL;

    /* filter option entry */
    opt_tab[3].option = xcstrdup("-filter");
    opt_tab[3].specifier = xcstrdup(".filter");
    opt_tab[3].argKind = XrmoptionNoArg;
    opt_tab[3].value = (XPointer) xcstrdup(ST);

    /* in option entry */
    opt_tab[4].option = xcstrdup("-in");
    opt_tab[4].specifier = xcstrdup(".direction");
    opt_tab[4].argKind = XrmoptionNoArg;
    opt_tab[4].value = (XPointer) xcstrdup("I");

    /* out option entry */
    opt_tab[5].option = xcstrdup("-out");
    opt_tab[5].specifier = xcstrdup(".direction");
    opt_tab[5].argKind = XrmoptionNoArg;
    opt_tab[5].value = (XPointer) xcstrdup("O");

    /* version option entry */
    opt_tab[6].option = xcstrdup("-version");
    opt_tab[6].specifier = xcstrdup(".print");
    opt_tab[6].argKind = XrmoptionNoArg;
    opt_tab[6].value = (XPointer) xcstrdup("V");

    /* help option entry */
    opt_tab[7].option = xcstrdup("-help");
    opt_tab[7].specifier = xcstrdup(".print");
    opt_tab[7].argKind = XrmoptionNoArg;
    opt_tab[7].value = (XPointer) xcstrdup("H");

    /* silent option entry */
    opt_tab[8].option = xcstrdup("-silent");
    opt_tab[8].specifier = xcstrdup(".olevel");
    opt_tab[8].argKind = XrmoptionNoArg;
    opt_tab[8].value = (XPointer) xcstrdup("S");

    /* quiet option entry */
    opt_tab[9].option = xcstrdup("-quiet");
    opt_tab[9].specifier = xcstrdup(".olevel");
    opt_tab[9].argKind = XrmoptionNoArg;
    opt_tab[9].value = (XPointer) xcstrdup("Q");

    /* verbose option entry */
    opt_tab[10].option = xcstrdup("-verbose");
    opt_tab[10].specifier = xcstrdup(".olevel");
    opt_tab[10].argKind = XrmoptionNoArg;
    opt_tab[10].value = (XPointer) xcstrdup("V");

    /* utf8 option entry */
    opt_tab[11].option = xcstrdup("-noutf8");
    opt_tab[11].specifier = xcstrdup(".noutf8");
    opt_tab[11].argKind = XrmoptionNoArg;
    opt_tab[11].value = (XPointer) xcstrdup("N");

    /* target option entry */
    opt_tab[12].option = xcstrdup("-target");
    opt_tab[12].specifier = xcstrdup(".target");
    opt_tab[12].argKind = XrmoptionSepArg;
    opt_tab[12].value = (XPointer) NULL;

    /* parse command line options */
    doOptMain(argc, argv);

    /* Connect to the X server. */
    if ((dpy = XOpenDisplay(sdisp))) {
	/* successful */
	if (fverb == OVERBOSE)
	    fprintf(stderr, "Connected to X server.\n");
    }
    else {
	/* couldn't connect to X server. Print error and exit */
	errxdisplay(sdisp);
    }

    /* parse selection command line option */
    doOptSel();

    /* parse noutf8 and target command line options */
    doOptTarget();

    /* Create a window to trap events */
    win = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy), 0, 0, 1, 1, 0, 0, 0);

    /* get events about property changes */
    XSelectInput(dpy, win, PropertyChangeMask);

    if (fdiri)
	exit_code = doIn(win, argv[0]);
    else
	exit_code = doOut(win);

    /* Disconnect from the X server */
    XCloseDisplay(dpy);

    /* exit */
    return exit_code;
}
Ejemplo n.º 17
0
VdpStatus
vdpDeviceCreateX11(Display *display_orig, int screen, VdpDevice *device,
                   VdpGetProcAddress **get_proc_address)
{
    if (!display_orig || !device)
        return VDP_STATUS_INVALID_POINTER;

    // Let's get own connection to the X server
    Display *display = handle_xdpy_ref(display_orig);
    if (NULL == display)
        return VDP_STATUS_ERROR;

    if (global.quirks.buggy_XCloseDisplay) {
        // XCloseDisplay could segfault on fglrx. To avoid calling XCloseDisplay,
        // make one more reference to xdpy copy.
        handle_xdpy_ref(display_orig);
    }

    VdpDeviceData *data = calloc(1, sizeof(VdpDeviceData));
    if (NULL == data)
        return VDP_STATUS_RESOURCES;

    glx_ctx_lock(); // use glx lock to serialize X calls
    data->type = HANDLETYPE_DEVICE;
    data->display = display;
    data->display_orig = display_orig;   // save supplied pointer too
    data->screen = screen;
    data->refcount = 0;
    pthread_mutex_init(&data->refcount_mutex, NULL);
    data->root = DefaultRootWindow(display);

    XWindowAttributes wnd_attrs;
    XGetWindowAttributes(display, data->root, &wnd_attrs);
    data->color_depth = wnd_attrs.depth;

    data->fn.glXBindTexImageEXT =
        (PFNGLXBINDTEXIMAGEEXTPROC)glXGetProcAddress((GLubyte *)"glXBindTexImageEXT");
    data->fn.glXReleaseTexImageEXT =
        (PFNGLXRELEASETEXIMAGEEXTPROC)glXGetProcAddress((GLubyte *)"glXReleaseTexImageEXT");
    glx_ctx_unlock();

    if (!data->fn.glXBindTexImageEXT || !data->fn.glXReleaseTexImageEXT) {
        traceError("error (%s): can't get glXBindTexImageEXT address\n");
        free(data);
        return VDP_STATUS_RESOURCES;
    }

    // create master GLX context to share data between further created ones
    glx_ctx_ref_glc_hash_table(display, screen);
    data->root_glc = glx_ctx_get_root_context();

    glx_ctx_push_thread_local(data);

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    // initialize VAAPI
    if (global.quirks.avoid_va) {
        // pretend there is no VA-API available
        data->va_available = 0;
    } else {
        data->va_dpy = vaGetDisplay(display);
        data->va_available = 0;

        VAStatus status = vaInitialize(data->va_dpy, &data->va_version_major,
                                       &data->va_version_minor);
        if (VA_STATUS_SUCCESS == status) {
            data->va_available = 1;
            traceInfo("libva (version %d.%d) library initialized\n",
                      data->va_version_major, data->va_version_minor);
        } else {
            data->va_available = 0;
            traceInfo("warning: failed to initialize libva. "
                      "No video decode acceleration available.\n");
        }
    }

    compile_shaders(data);

    glGenTextures(1, &data->watermark_tex_id);
    glBindTexture(GL_TEXTURE_2D, data->watermark_tex_id);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, watermark_width, watermark_height, 0, GL_BGRA,
                 GL_UNSIGNED_BYTE, watermark_data);
    glFinish();

    *device = handle_insert(data);
    if (get_proc_address)
        *get_proc_address = &vdpGetProcAddress;

    GLenum gl_error = glGetError();
    glx_ctx_pop();

    if (GL_NO_ERROR != gl_error) {
        traceError("error (%s): gl error %d\n", __func__, gl_error);
        return VDP_STATUS_ERROR;
    }

    return VDP_STATUS_OK;
}
Ejemplo n.º 18
0
static void
update_outputs (CoglRenderer *renderer,
                gboolean notify)
{
  CoglXlibRenderer *xlib_renderer =
    _cogl_xlib_renderer_get_data (renderer);
  XRRScreenResources *resources;
  CoglXlibTrapState state;
  gboolean error = FALSE;
  GList *new_outputs = NULL;
  GList *l, *m;
  gboolean changed = FALSE;
  int i;

  xlib_renderer->outputs_update_serial = XNextRequest (xlib_renderer->xdpy);

  resources = XRRGetScreenResources (xlib_renderer->xdpy,
                                     DefaultRootWindow (xlib_renderer->xdpy));

  _cogl_xlib_renderer_trap_errors (renderer, &state);

  for (i = 0; resources && i < resources->ncrtc && !error; i++)
    {
      XRRCrtcInfo *crtc_info = NULL;
      XRROutputInfo *output_info = NULL;
      CoglOutput *output;
      float refresh_rate = 0;
      int j;

      crtc_info = XRRGetCrtcInfo (xlib_renderer->xdpy,
                                  resources, resources->crtcs[i]);
      if (crtc_info == NULL)
        {
          error = TRUE;
          goto next;
        }

      if (crtc_info->mode == None)
        goto next;

      for (j = 0; j < resources->nmode; j++)
        {
          if (resources->modes[j].id == crtc_info->mode)
            refresh_rate = (resources->modes[j].dotClock /
                            ((float)resources->modes[j].hTotal *
                             resources->modes[j].vTotal));
        }

      output_info = XRRGetOutputInfo (xlib_renderer->xdpy,
                                      resources,
                                      crtc_info->outputs[0]);
      if (output_info == NULL)
        {
          error = TRUE;
          goto next;
        }

      output = _cogl_output_new (output_info->name);
      output->x = crtc_info->x;
      output->y = crtc_info->y;
      output->width = crtc_info->width;
      output->height = crtc_info->height;
      if ((crtc_info->rotation & (RR_Rotate_90 | RR_Rotate_270)) != 0)
        {
          output->mm_width = output_info->mm_height;
          output->mm_height = output_info->mm_width;
        }
      else
        {
          output->mm_width = output_info->mm_width;
          output->mm_height = output_info->mm_height;
        }

      output->refresh_rate = refresh_rate;

      switch (output_info->subpixel_order)
        {
        case SubPixelUnknown:
        default:
          output->subpixel_order = COGL_SUBPIXEL_ORDER_UNKNOWN;
          break;
        case SubPixelNone:
          output->subpixel_order = COGL_SUBPIXEL_ORDER_NONE;
          break;
        case SubPixelHorizontalRGB:
          output->subpixel_order = COGL_SUBPIXEL_ORDER_HORIZONTAL_RGB;
          break;
        case SubPixelHorizontalBGR:
          output->subpixel_order = COGL_SUBPIXEL_ORDER_HORIZONTAL_BGR;
          break;
        case SubPixelVerticalRGB:
          output->subpixel_order = COGL_SUBPIXEL_ORDER_VERTICAL_RGB;
          break;
        case SubPixelVerticalBGR:
          output->subpixel_order = COGL_SUBPIXEL_ORDER_VERTICAL_BGR;
          break;
        }

      output->subpixel_order = COGL_SUBPIXEL_ORDER_HORIZONTAL_RGB;

      /* Handle the effect of rotation and reflection on subpixel order (ugh) */
      for (j = 0; j < 6; j++)
        {
          if ((crtc_info->rotation & (1 << j)) != 0)
            output->subpixel_order = subpixel_map[j][output->subpixel_order];
        }

      new_outputs = g_list_prepend (new_outputs, output);

    next:
      if (crtc_info != NULL)
        XFree (crtc_info);

      if (output_info != NULL)
        XFree (output_info);
    }

  XFree (resources);

  if (!error)
    {
      new_outputs = g_list_sort (new_outputs, (GCompareFunc)compare_outputs);

      l = new_outputs;
      m = renderer->outputs;

      while (l || m)
        {
          int cmp;
          CoglOutput *output_l = l ? (CoglOutput *)l->data : NULL;
          CoglOutput *output_m = m ? (CoglOutput *)m->data : NULL;

          if (l && m)
            cmp = compare_outputs (output_l, output_m);
          else if (l)
            cmp = -1;
          else
            cmp = 1;

          if (cmp == 0)
            {
              GList *m_next = m->next;

              if (!_cogl_output_values_equal (output_l, output_m))
                {
                  renderer->outputs = g_list_remove_link (renderer->outputs, m);
                  renderer->outputs = g_list_insert_before (renderer->outputs,
                                                            m_next, output_l);
                  cogl_object_ref (output_l);

                  changed = TRUE;
                }

              l = l->next;
              m = m_next;
            }
          else if (cmp < 0)
            {
              renderer->outputs =
                g_list_insert_before (renderer->outputs, m, output_l);
              cogl_object_ref (output_l);
              changed = TRUE;
              l = l->next;
            }
          else
            {
              GList *m_next = m->next;
              renderer->outputs = g_list_remove_link (renderer->outputs, m);
              changed = TRUE;
              m = m_next;
            }
        }
    }

  g_list_free_full (new_outputs, (GDestroyNotify)cogl_object_unref);
  _cogl_xlib_renderer_untrap_errors (renderer, &state);

  if (changed)
    {
      const CoglWinsysVtable *winsys = renderer->winsys_vtable;

      if (notify)
        COGL_NOTE (WINSYS, "Outputs changed:");
      else
        COGL_NOTE (WINSYS, "Outputs:");

      for (l = renderer->outputs; l; l = l->next)
        {
          CoglOutput *output = l->data;
          const char *subpixel_string;

          switch (output->subpixel_order)
            {
            case COGL_SUBPIXEL_ORDER_UNKNOWN:
            default:
              subpixel_string = "unknown";
              break;
            case COGL_SUBPIXEL_ORDER_NONE:
              subpixel_string = "none";
              break;
            case COGL_SUBPIXEL_ORDER_HORIZONTAL_RGB:
              subpixel_string = "horizontal_rgb";
              break;
            case COGL_SUBPIXEL_ORDER_HORIZONTAL_BGR:
              subpixel_string = "horizontal_bgr";
              break;
            case COGL_SUBPIXEL_ORDER_VERTICAL_RGB:
              subpixel_string = "vertical_rgb";
              break;
            case COGL_SUBPIXEL_ORDER_VERTICAL_BGR:
              subpixel_string = "vertical_bgr";
              break;
            }

          COGL_NOTE (WINSYS,
                     " %10s: +%d+%dx%dx%d mm=%dx%d dpi=%.1fx%.1f "
                     "subpixel_order=%s refresh_rate=%.3f",
                     output->name,
                     output->x, output->y, output->width, output->height,
                     output->mm_width, output->mm_height,
                     output->width / (output->mm_width / 25.4),
                     output->height / (output->mm_height / 25.4),
                     subpixel_string,
                     output->refresh_rate);
        }

      if (notify && winsys->renderer_outputs_changed != NULL)
        winsys->renderer_outputs_changed (renderer);
    }
}
Ejemplo n.º 19
0
int main(int argc, char *argv[]){
	XTextItem textItem;
	int whiteColor, blackColor, color;
	int speed = 5;
	char opt;

	textItem.delta = 0;
	textItem.font = None;

	display = XOpenDisplay(NULL);
	
	if(display == NULL){
		fprintf(stderr, "Failed to open display.\n");
		exit(EXIT_FAILURE);
	}

	width = DisplayWidth(display, DefaultScreen(display));
	height = DisplayHeight(display, DefaultScreen(display));

	whiteColor = WhitePixel(display, DefaultScreen(display));
	blackColor = BlackPixel(display, DefaultScreen(display));
	color = whiteColor;

	while((opt = getopt(argc, argv, "wbs:")) != -1){
		switch(opt){
		case 'w':
			color = whiteColor;
			break;
		case 'b':
			color = blackColor;
			break;
		case 's':
			speed = atoi(optarg);
			break;
		default:
			fprintf(stderr, "Unrecognized option: %c", opt);
			XCloseDisplay(display);
			exit(EXIT_FAILURE);
		}
	}

	if(optind >= argc){
		fprintf(stderr, "Usage: %s [options] command\n", argv[0]);
		XCloseDisplay(display);
		exit(EXIT_FAILURE);
	}

	window = DefaultRootWindow(display);

	signal(SIGINT, cleanup);
	
	gc = XCreateGC(display, window, 0, NULL);
	
	XSetForeground(display, gc, color);

	x = 0;
	y = height / 2;

	for(;;){ 
		clearScreen();
		
		textItem.chars = argv[optind];
		textItem.nchars = strlen(argv[optind]);
		XDrawText(display, window, gc, x, y, &textItem, 1);

		x += speed;

		if(x > width) x = 0;
		
		XFlush(display);
		usleep(10000); 
	}

	cleanup(SIGINT);

	return 0;
}
Ejemplo n.º 20
0
int main (int argc, char *argv[])
{
	/* Declare variables */
	unsigned char *sel_buf;		/* buffer for selection data */
	unsigned long sel_len = 0;	/* length of sel_buf */
	unsigned long sel_all = 0;	/* allocated size of sel_buf */
	Window win;			/* Window */
	XEvent evt;			/* X Event Structures */
	int dloop = 0;			/* done loops counter */

	pid_t pid;			/* child pid if forking */

	/* set up option table. I can't figure out a better way than this to
	 * do it while sticking to pure ANSI C. The option and specifier
	 * members have a type of volatile char *, so they need to be allocated
	 * by strdup or malloc, you can't set them to a string constant at
	 * declare time, this is note pure ANSI C apparently, although it does
	 * work with gcc
	 */
	
	/* loop option entry */
	opt_tab[0].option 	=	xcstrdup("-loops");
	opt_tab[0].specifier	=	xcstrdup(".loops");
	opt_tab[0].argKind	=	XrmoptionSepArg;
	opt_tab[0].value	=	(XPointer) NULL;

	/* display option entry */
	opt_tab[1].option	=	xcstrdup("-display");
	opt_tab[1].specifier	=	xcstrdup(".display");
	opt_tab[1].argKind	=	XrmoptionSepArg;
	opt_tab[1].value	=	(XPointer) NULL;
				
	/* selection option entry */
	opt_tab[2].option 	=	xcstrdup("-selection");
	opt_tab[2].specifier	=	xcstrdup(".selection");
	opt_tab[2].argKind	=	XrmoptionSepArg;
	opt_tab[2].value	=	(XPointer) NULL;
		
	/* filter option entry */
	opt_tab[3].option	=	xcstrdup("-filter");
	opt_tab[3].specifier	=	xcstrdup(".filter");
	opt_tab[3].argKind	=	XrmoptionNoArg;	
	opt_tab[3].value	=	(XPointer) xcstrdup(ST);
		
	/* in option entry */
	opt_tab[4].option	=	xcstrdup("-in");
	opt_tab[4].specifier	=	xcstrdup(".direction");
	opt_tab[4].argKind	=	XrmoptionNoArg;
	opt_tab[4].value	=	(XPointer) xcstrdup("I");
		
	/* out option entry */
	opt_tab[5].option	=	xcstrdup("-out");
	opt_tab[5].specifier	=	xcstrdup(".direction");
	opt_tab[5].argKind	=	XrmoptionNoArg;
	opt_tab[5].value	=	(XPointer) xcstrdup("O");
		
	/* version option entry */
	opt_tab[6].option	=	xcstrdup("-version");
	opt_tab[6].specifier	=	xcstrdup(".print");
	opt_tab[6].argKind	=	XrmoptionNoArg;
	opt_tab[6].value	=	(XPointer) xcstrdup("V");
		
	/* help option entry */
	opt_tab[7].option	=	xcstrdup("-help");
	opt_tab[7].specifier	=	xcstrdup(".print");
	opt_tab[7].argKind	=	XrmoptionNoArg;
	opt_tab[7].value	=	(XPointer) xcstrdup("H");
		
	/* silent option entry */
	opt_tab[8].option	=	xcstrdup("-silent");
	opt_tab[8].specifier	=	xcstrdup(".olevel");
	opt_tab[8].argKind	=	XrmoptionNoArg;
	opt_tab[8].value	=	(XPointer) xcstrdup("S");
		
	/* quiet option entry */
	opt_tab[9].option	=	xcstrdup("-quiet");
	opt_tab[9].specifier	=	xcstrdup(".olevel");
	opt_tab[9].argKind	=	XrmoptionNoArg;
	opt_tab[9].value	=	(XPointer) xcstrdup("Q");
		
	/* verbose option entry */
	opt_tab[10].option	=	xcstrdup("-verbose");
	opt_tab[10].specifier	=	xcstrdup(".olevel");
	opt_tab[10].argKind	=	XrmoptionNoArg;
	opt_tab[10].value	=	(XPointer) xcstrdup("V");

	/* parse command line options */
	doOptMain(argc, argv);
   
	/* Connect to the X server. */
	if ( (dpy = XOpenDisplay(sdisp)) )
	{
		/* successful */
		if (fverb == OVERBOSE)
			fprintf(stderr, "Connected to X server.\n");
	} else
	{
		/* couldn't connect to X server. Print error and exit */
		errxdisplay(sdisp);
	}

	/* parse selection command line option */
	doOptSel();
  
	/* Create a window to trap events */
	win = XCreateSimpleWindow(
		dpy,
		DefaultRootWindow(dpy),
		0,
		0,
		1,
		1,
		0,
		0,
		0
	);

	/* get events about property changes */
	XSelectInput(dpy, win, PropertyChangeMask);
  
	if (fdiri)
	{
		/* in mode */
		sel_all = 16;		/* Reasonable ballpark figure */
		sel_buf = xcmalloc(sel_all * sizeof(char));

		/* Put chars into inc from stdin or files until we hit EOF */
		do {
			if (fil_number == 0)
			{
				/* read from stdin if no files specified */
				fil_handle = stdin;
			} else
			{
				if (
					(fil_handle = fopen(
						fil_names[fil_current],
						"r"
					)) == NULL
				)
				{
					errperror(
						3,
						argv[0],
						": ",
						fil_names[fil_current]
					);
					exit(EXIT_FAILURE);
				} else
				{
					/* file opened successfully. Print
					 * message (verbose mode only).
					 */
					if (fverb == OVERBOSE)
						fprintf(
							stderr,
							"Reading %s...\n",
							fil_names[fil_current]
						);
				}
			}

			fil_current++;
			while (!feof(fil_handle))
			{
				/* If sel_buf is full (used elems =
				 * allocated elems)
				 */
				if (sel_len == sel_all)
				{
					/* double the number of
					 * allocated elements
					 */
					sel_all *= 2;
					sel_buf = (unsigned char *)xcrealloc(
						sel_buf,
						sel_all * sizeof(char)
					);
				}
				sel_len += fread(
					sel_buf + sel_len,
					sizeof(char),
					sel_all - sel_len,
					fil_handle
				);
			}
		} while (fil_current < fil_number);

		/* if there are no files being read from (i.e., input
		 * is from stdin not files, and we are in filter mode,
		 * spit all the input back out to stdout
		 */
		if ((fil_number == 0) && ffilt)
			fwrite(sel_buf, sizeof(char), sel_len, stdout); 
    
		/* take control of the selection so that we receive
		 * SelectionRequest events from other windows
		 */
		XSetSelectionOwner(dpy, sseln, win, CurrentTime);

		/* fork into the background, exit parent process if we
		 * are in silent mode
		 */
		if (fverb == OSILENT)
		{
			pid = fork();
			/* exit the parent process; */
			if (pid)
				exit(EXIT_SUCCESS);
		}

		/* print a message saying what we're waiting for */
		if (fverb > OSILENT)
		{
			if (sloop == 1)
				fprintf(
					stderr,
					"Waiting for one selection request.\n"
				);
				
			if (sloop  < 1)
				fprintf(
					stderr,
					"Waiting for selection requests, Control-C to quit\n"
				);
				
			if (sloop  > 1)
				fprintf(
					stderr,
					"Waiting for %i selection requests, Control-C to quit\n",
					sloop
				);
		}
  
		/* loop and wait for the expected number of
		 * SelectionRequest events
		 */
		while (dloop < sloop || sloop < 1)
		{
			/* print messages about what we're waiting for
			 * if not in silent mode
			 */
			if (fverb > OSILENT)
			{
				if (sloop  > 1)
					fprintf(
						stderr,
						"  Waiting for selection request %i of %i.\n",
						dloop + 1,
						sloop
					);
					
				if (sloop == 1)
					fprintf(
						stderr,
						"  Waiting for a selection request.\n"
					);
					
				if (sloop  < 1)
					fprintf(
						stderr,
						"  Waiting for selection request number %i\n",
						dloop + 1
					);
			}
     
			/* wait for a SelectionRequest event */
			while (1)
			{
				static unsigned int clear = 0;
				static unsigned int context = XCLIB_XCIN_NONE;
				static unsigned long sel_pos = 0;
				static Window cwin;
				static Atom pty;
				int finished;

				XNextEvent(dpy, &evt);

				finished = xcin(
					dpy,
					&cwin,
					evt,
					&pty,
					sel_buf,
					sel_len,
					&sel_pos,
					&context
				);

				if (evt.type == SelectionClear)
					clear = 1;

				if ( (context == XCLIB_XCIN_NONE) && clear)
					exit(EXIT_SUCCESS);

				if (finished)
					break;
			}

			dloop++;	/* increment loop counter */
		}
	} else
	{
		unsigned int context = XCLIB_XCOUT_NONE;

		while (1)
		{
			/* only get an event if xcout() is doing something */
			if (context != XCLIB_XCOUT_NONE)
				XNextEvent(dpy, &evt);

			/* fetch the selection, or part of it */
			xcout(
				dpy,
				win,
				evt,
				sseln,
				&sel_buf,
				&sel_len,
				&context
			);

			/* only continue if xcout() is doing something */
			if (context == XCLIB_XCOUT_NONE)
				break;
		}
		
		if (sel_len)
		{
			/* only print the buffer out, and free it, if it's not
			 * empty
			 */
			fwrite(sel_buf, sizeof(char), sel_len, stdout);
			free(sel_buf);
		}
	}

	/* Disconnect from the X server */
	XCloseDisplay(dpy);

	/* exit */
	return(EXIT_SUCCESS);
}
Ejemplo n.º 21
0
// Creates the event addon
void* FcitxTabletCreate(FcitxInstance* instance) {
	FcitxTablet* tablet = fcitx_utils_new(FcitxTablet);
	FcitxTabletLoadConfig(&tablet->config);
	// TODO select driver from config, currently using lxbi

	{ // Initialise the driver
		switch(tablet->config.Driver) {
		case DRIVER_LXBI:
			tablet->driverInstance = &lxbi;
		break;
		// add other drivers here
		}
		tablet->driverData = tablet->driverInstance->Create();
		tablet->driverPacket = (char*) malloc(tablet->driverInstance->packet_size);
	}

	{ // Initialise the X display
		if(NULL == (tablet->xDisplay = FcitxX11GetDisplay(instance)))  {
			FcitxLog(ERROR, "Unable to open X display");
			return NULL;
		}
		// get dimensions
		int screen = DefaultScreen(tablet->xDisplay);
		tablet->xWidth = tablet->config.Width;
		tablet->xHeight = tablet->config.Height;
		int x = tablet->config.XPos > 0 ? tablet->config.XPos : XDisplayWidth(tablet->xDisplay, screen) - tablet->xWidth + tablet->config.XPos;
		int y = tablet->config.YPos > 0 ? tablet->config.YPos : XDisplayHeight(tablet->xDisplay, screen) - tablet->xHeight + tablet->config.YPos;
		// create colours
		XColor back;
		XColor fore;
		{
			char colourString[32];
			{
				int r = (255*tablet->config.BackgroundColour.r);
				int g = (255*tablet->config.BackgroundColour.g);
				int b = (255*tablet->config.BackgroundColour.b);
				sprintf(colourString,"rgb:%x/%x/%x",r,g,b);
			}
			Colormap defaultCMap = DefaultColormap(tablet->xDisplay, screen);
			XParseColor(tablet->xDisplay, defaultCMap, colourString, &back);
			XAllocColor(tablet->xDisplay, defaultCMap, &back);
			{
				int r = (255*tablet->config.StrokeColour.r);
				int g = (255*tablet->config.StrokeColour.g);
				int b = (255*tablet->config.StrokeColour.b);
				sprintf(colourString,"rgb:%x/%x/%x",r,g,b);
			}
			XParseColor(tablet->xDisplay, defaultCMap, colourString, &fore);
			XAllocColor(tablet->xDisplay, defaultCMap, &fore);
		}
		// set window attributes and create window
		XSetWindowAttributes attrs;
		attrs.override_redirect = True;
		attrs.background_pixel = back.pixel;
		tablet->xWindow = XCreateWindow(tablet->xDisplay, DefaultRootWindow(tablet->xDisplay),
			 x, y, tablet->xWidth, tablet->xHeight, tablet->config.BorderWidth, CopyFromParent,
			 InputOutput, CopyFromParent, CWBackPixel | CWOverrideRedirect, &attrs);
		// set up the foreground line (stroke) style
		XGCValues gcv;
		gcv.function = GXcopy;
		gcv.subwindow_mode = IncludeInferiors;
		gcv.line_width = 3;
		gcv.cap_style = CapRound;
		gcv.join_style = JoinRound;
		tablet->xGC = XCreateGC(tablet->xDisplay, tablet->xWindow, GCFunction | GCSubwindowMode | GCLineWidth | GCCapStyle | GCJoinStyle, &gcv);
		XSetForeground(tablet->xDisplay, tablet->xGC, fore.pixel);
		// prevent the window from getting focus or input
		XRectangle rect = {0,0,0,0};
		XserverRegion region = XFixesCreateRegion(tablet->xDisplay,&rect, 1);
		XFixesSetWindowShapeRegion(tablet->xDisplay, tablet->xWindow, ShapeInput, 0, 0, region);
		XFixesDestroyRegion(tablet->xDisplay, region);
	}

	{ // Initialise the stroke buffer
		tablet->strokesBufferSize = 2048; // should be heaps. Will get automatically enlarged if required
		tablet->strokesBuffer = (pt_t*) malloc(sizeof(pt_t) * tablet->strokesBufferSize);
		tablet->strokesPtr = tablet->strokesBuffer;
	}

	{ // instantiate the engine
		switch(tablet->config.Engine) {
		case ENGINE_ZINNIA:
			tablet->engineInstance = &engZinnia;
			break;
		case ENGINE_FORK:
			tablet->engineInstance = &engFork;
			break;
		// add other engines here
		}
		tablet->engineData = tablet->engineInstance->Create(&tablet->config);
	}

	{ // set up the timerfd
		tablet->timeoutFd = timerfd_create(CLOCK_MONOTONIC, 0);
		tablet->delay.it_interval.tv_sec = 0;
		tablet->delay.it_interval.tv_nsec = 0;
		tablet->delay.it_value.tv_sec = tablet->config.CommitCharMs / 1000;
		tablet->delay.it_value.tv_nsec = (tablet->config.CommitCharMs % 1000) * 1000000;
		tablet->timeoutCommitPending = 0;
	}

	tablet->fcitx = instance;
	return tablet;
}
Ejemplo n.º 22
0
static inline void post_mouse_button_event(uiohook_event * const event) {
	#ifdef USE_XTEST
	Window ret_root;
	Window ret_child;
	int root_x;
	int root_y;
	int win_x;
	int win_y;
	unsigned int mask;

	Window win_root = XDefaultRootWindow(properties_disp);
	Bool query_status = XQueryPointer(properties_disp, win_root, &ret_root, &ret_child, &root_x, &root_y, &win_x, &win_y, &mask);
	if (query_status) {
		if (event->data.mouse.x != root_x || event->data.mouse.y != root_y) {
			// Move the pointer to the specified position.
			XTestFakeMotionEvent(properties_disp, -1, event->data.mouse.x, event->data.mouse.y, 0);
		}
		else {
			query_status = False;
		}
	}

	if (event->type == EVENT_MOUSE_WHEEL) {
		// Wheel events should be the same as click events on X11.
		// type, amount and rotation
		if (event->data.wheel.rotation < 0) {
			XTestFakeButtonEvent(properties_disp, WheelUp, True, 0);
			XTestFakeButtonEvent(properties_disp, WheelUp, False, 0);
		}
		else {
			XTestFakeButtonEvent(properties_disp, WheelDown, True, 0);
			XTestFakeButtonEvent(properties_disp, WheelDown, False, 0);
		}
	}
	else if (event->type == EVENT_MOUSE_PRESSED) {
		XTestFakeButtonEvent(properties_disp, event->data.mouse.button, True, 0);
	}
	else if (event->type == EVENT_MOUSE_RELEASED) {
		XTestFakeButtonEvent(properties_disp, event->data.mouse.button, False, 0);
	}
	else if (event->type == EVENT_MOUSE_CLICKED) {
		XTestFakeButtonEvent(properties_disp, event->data.mouse.button, True, 0);
		XTestFakeButtonEvent(properties_disp, event->data.mouse.button, False, 0);
	}

	if (query_status) {
		// Move the pointer back to the original position.
		XTestFakeMotionEvent(properties_disp, -1, root_x, root_y, 0);
	}
	#else
	XButtonEvent btn_event;

	btn_event.serial = 0x00;
	btn_event.send_event = False;
	btn_event.display = properties_disp;
	btn_event.time = CurrentTime;
	btn_event.same_screen = True;

	btn_event.root = DefaultRootWindow(properties_disp);
	btn_event.window = btn_event.root;
	btn_event.subwindow = None;

	btn_event.type = 0x00;
	btn_event.state = 0x00;
	btn_event.x_root = 0;
	btn_event.y_root = 0;
	btn_event.x = 0;
	btn_event.y = 0;
	btn_event.button = 0x00;

	btn_event.state = convert_to_native_mask(event->mask);

	btn_event.x = event->data.mouse.x;
	btn_event.y = event->data.mouse.y;

	#if defined(USE_XINERAMA) || defined(USE_XRANDR)
	uint8_t screen_count;
	screen_data *screens = hook_create_screen_info(&screen_count);
	if (screen_count > 1) {
		btn_event.x += screens[0].x;
		btn_event.y += screens[0].y;
	}

	if (screens != NULL) {
		free(screens);
	}
	#endif

	// These are the same because Window == Root Window.
	btn_event.x_root = btn_event.x;
	btn_event.y_root = btn_event.y;

	if (event->type == EVENT_MOUSE_WHEEL) {
		// type, amount and rotation
		if (event->data.wheel.rotation < 0) {
			btn_event.button = WheelUp;
		}
		else {
			btn_event.button = WheelDown;
		}
	}

	if (event->type != EVENT_MOUSE_RELEASED) {
		// FIXME Where do we set event->button?
		btn_event.type = ButtonPress;
		XSendEvent(properties_disp, InputFocus, False, ButtonPressMask, (XEvent *) &btn_event);
	}

	if (event->type != EVENT_MOUSE_PRESSED) {
		btn_event.type = ButtonRelease;
		XSendEvent(properties_disp, InputFocus, False, ButtonReleaseMask, (XEvent *) &btn_event);
	}
	#endif
}
Ejemplo n.º 23
0
/**
**	X11 initialize.
*/
global void CloneInitDisplay(void)
{
    int i;
    Window window;
    XGCValues gcvalue;
    XSizeHints hints;
    XWMHints wmhints;
    XClassHint classhint;
    XSetWindowAttributes attributes;
    int shm_major,shm_minor;
    Bool pixmap_support;
    XShmSegmentInfo shminfo;
    XVisualInfo xvi;
    XPixmapFormatValues *xpfv;

    if( !(TheDisplay=XOpenDisplay(NULL)) ) {
	fprintf(stderr,"Cannot connect to X-Server.\n");
	exit(-1);
    }

    TheScreen=DefaultScreen(TheDisplay);

    //	I need shared memory pixmap extension.

    if( !XShmQueryVersion(TheDisplay,&shm_major,&shm_minor,&pixmap_support) ) {
	fprintf(stderr,"SHM-Extensions required.\n");
	exit(-1);
    }
    if( !pixmap_support ) {
	fprintf(stderr,"SHM-Extensions with pixmap supported required.\n");
	exit(-1);
    }

    //  Look for a nice visual
#ifdef USE_HICOLOR
    if(XMatchVisualInfo(TheDisplay, TheScreen, 16, TrueColor, &xvi))
	goto foundvisual;
    if(XMatchVisualInfo(TheDisplay, TheScreen, 15, TrueColor, &xvi))
	goto foundvisual;
    fprintf(stderr,"Sorry, this version is for 15/16-bit displays only.\n");
#else
    if(XMatchVisualInfo(TheDisplay, TheScreen, 8, PseudoColor, &xvi))
	goto foundvisual;
    fprintf(stderr,"Sorry, this version is for 8-bit displays only.\n");
#endif
#if 0
    if(XMatchVisualInfo(TheDisplay, TheScreen, 24, TrueColor, &xvi))
	goto foundvisual;
#endif
    exit(-1);
foundvisual:

    xpfv=XListPixmapFormats(TheDisplay, &i);
    for(i--;i>=0;i--)  if(xpfv[i].depth==xvi.depth) break;
    if(i<0)  {
	fprintf(stderr,"No Pixmap format for visual depth?\n");
	exit(-1);
    }
    VideoDepth=xvi.depth;

    VideoWidth = 640;
    VideoHeight = 480;
    MapWidth = 14;			// FIXME: Not the correct way
    MapHeight = 14;
    shminfo.shmid=shmget(IPC_PRIVATE,
	(VideoWidth*xpfv[i].bits_per_pixel+xpfv[i].scanline_pad-1) /
	xpfv[i].scanline_pad * xpfv[i].scanline_pad * VideoHeight / 8,
	IPC_CREAT|0777);

    XFree(xpfv);

    if( !shminfo.shmid==-1 ) {
	fprintf(stderr,"shmget failed.\n");
	exit(-1);
    }
    VideoMemory=(VMemType*)shminfo.shmaddr=shmat(shminfo.shmid,0,0);
    if( shminfo.shmaddr==(void*)-1 ) {
	shmctl(shminfo.shmid,IPC_RMID,0);
	fprintf(stderr,"shmat failed.\n");
	exit(-1);
    }
    shminfo.readOnly=False;

    if( !XShmAttach(TheDisplay,&shminfo) ) {
	shmctl(shminfo.shmid,IPC_RMID,0);
	fprintf(stderr,"XShmAttach failed.\n");
	exit(-1);
    }
    // Mark segment as deleted as soon as both clone and the X server have
    // attached to it.  The POSIX spec says that a segment marked as deleted
    // can no longer have addition processes attach to it, but Linux will let
    // them anyway.
    shmctl(shminfo.shmid,IPC_RMID,0);

    TheMainDrawable=attributes.background_pixmap=
	    XShmCreatePixmap(TheDisplay,DefaultRootWindow(TheDisplay)
		,shminfo.shmaddr,&shminfo
		,VideoWidth,VideoHeight
		,xvi.depth);
    attributes.cursor = XCreateFontCursor(TheDisplay,XC_tcross-1);
    attributes.backing_store = NotUseful;
    attributes.save_under = False;
    attributes.event_mask = KeyPressMask|KeyReleaseMask|/*ExposureMask|*/
	FocusChangeMask|ButtonPressMask|PointerMotionMask|ButtonReleaseMask;
    i = CWBackPixmap|CWBackingStore|CWSaveUnder|CWEventMask|CWCursor;

    if(xvi.class==PseudoColor)  {
	i|=CWColormap;
	attributes.colormap =
	    XCreateColormap( TheDisplay, xvi.screen, xvi.visual, AllocNone);
	// FIXME:  Really should fill in the colormap right now
    }
    window=XCreateWindow(TheDisplay,DefaultRootWindow(TheDisplay)
	    ,0,0,VideoWidth,VideoHeight,3
	    ,xvi.depth,InputOutput,xvi.visual ,i,&attributes);
    TheMainWindow=window;

    gcvalue.graphics_exposures=False;
    GcLine=XCreateGC(TheDisplay,window,GCGraphicsExposures,&gcvalue);

    //
    //	Clear initial window.
    //
    XSetForeground(TheDisplay,GcLine,BlackPixel(TheDisplay,TheScreen));
    XFillRectangle(TheDisplay,TheMainDrawable,GcLine,0,0
	    ,VideoWidth,VideoHeight);

    WmDeleteWindowAtom=XInternAtom(TheDisplay,"WM_DELETE_WINDOW",False);

    //
    //	Set some usefull min/max sizes as well as a 1.3 aspect
    //
#if 0
    if( geometry ) {
	hints.flags=0;
	f=XParseGeometry(geometry
		,&hints.x,&hints.y,&hints.width,&hints.height);

	if( f&XValue ) {
	    if( f&XNegative ) {
		hints.x+=DisplayWidth-hints.width;
	    }
	    hints.flags|=USPosition;
	    // FIXME: win gravity
	}
	if( f&YValue ) {
	    if( f&YNegative ) {
		hints.y+=DisplayHeight-hints.height;
	    }
	    hints.flags|=USPosition;
	    // FIXME: win gravity
	}
	if( f&WidthValue ) {
	    hints.flags|=USSize;
	}
	if( f&HeightValue ) {
	    hints.flags|=USSize;
	}
    } else {
#endif
	hints.width=VideoWidth;
	hints.height=VideoHeight;
	hints.flags=PSize;
#if 0
    }
#endif
    hints.min_width=VideoWidth;
    hints.min_height=VideoHeight;
    hints.max_width=VideoWidth;
    hints.max_height=VideoHeight;
    hints.min_aspect.x=4;
    hints.min_aspect.y=3;

    hints.max_aspect.x=4;
    hints.max_aspect.y=3;
    hints.width_inc=4;
    hints.height_inc=3;

    hints.flags|=PMinSize|PMaxSize|PAspect|PResizeInc;

    wmhints.input=True;
    wmhints.initial_state=NormalState;
    wmhints.window_group=window;
    wmhints.flags=InputHint|StateHint|WindowGroupHint;

    classhint.res_name="aleclone";
    classhint.res_class="AleClone";

    XSetStandardProperties(TheDisplay,window
	,"ALE Clone","ALE Clone",None,(char**)0,0,&hints);
    XSetClassHint(TheDisplay,window,&classhint);
    XSetWMHints(TheDisplay,window,&wmhints);

    XSetWMProtocols(TheDisplay,window,&WmDeleteWindowAtom,1);

    XMapWindow(TheDisplay,window);

    //
    //	Input handling.
    //
    XAddConnectionWatch(TheDisplay,MyConnectionWatch,NULL);
}
Ejemplo n.º 24
0
static inline void post_mouse_motion_event(uiohook_event * const event) {
    #ifdef USE_XTEST
	XTestFakeMotionEvent(properties_disp, -1, event->data.mouse.x, event->data.mouse.y, 0);
    #else
	XMotionEvent mov_event;

	mov_event.serial = MotionNotify;
	mov_event.send_event = False;
	mov_event.display = properties_disp;
	mov_event.time = CurrentTime;
	mov_event.same_screen = True;
	mov_event.is_hint = NotifyNormal,
	mov_event.root = DefaultRootWindow(properties_disp);
	mov_event.window = mov_event.root;
	mov_event.subwindow = None;

	mov_event.type = 0x00;
	mov_event.state = 0x00;
	mov_event.x_root = 0;
	mov_event.y_root = 0;
	mov_event.x = 0;
	mov_event.y = 0;

	mov_event.state = convert_to_native_mask(event->mask);

	mov_event.x = event->data.mouse.x;
	mov_event.y = event->data.mouse.y;

	#if defined(USE_XINERAMA) || defined(USE_XRANDR)
	uint8_t screen_count;
	screen_data *screens = hook_create_screen_info(&screen_count);
	if (screen_count > 1) {
		mov_event.x += screens[0].x;
		mov_event.y += screens[0].y;
	}

	if (screens != NULL) {
		free(screens);
	}
	#endif

	// These are the same because Window == Root Window.
	mov_event.x_root = mov_event.x;
	mov_event.y_root = mov_event.y;

	long int event_mask = NoEventMask;
	if (event->type == EVENT_MOUSE_DRAGGED) {
		#if Button1Mask == Button1MotionMask && \
			Button2Mask == Button2MotionMask && \
			Button3Mask == Button3MotionMask && \
			Button4Mask == Button4MotionMask && \
			Button5Mask == Button5MotionMask
		// This little trick only works if Button#MotionMasks align with
		// the Button#Masks.
		event_mask = mov_event.state &
				(Button1MotionMask | Button2MotionMask |
				Button2MotionMask | Button3MotionMask | Button5MotionMask);
		#else
		// Fallback to some slightly larger...
		if (event->state & Button1Mask) {
			event_mask |= Button1MotionMask;
		}

		if (event->state & Button2Mask) {
			event_mask |= Button2MotionMask;
		}

		if (event->state & Button3Mask) {
			event_mask |= Button3MotionMask;
		}

		if (event->state & Button4Mask) {
			event_mask |= Button4MotionMask;
		}

		if (event->state & Button5Mask) {
			event_mask |= Button5MotionMask;
		}
		#endif
	}

	// NOTE x_mask = NoEventMask.
	XSendEvent(properties_disp, InputFocus, False, event_mask, (XEvent *) &mov_event);
    #endif
}
Ejemplo n.º 25
0
void Injector::injectMotionAbsolute(int x, int y)
{
	XWarpPointer(m_display, None, DefaultRootWindow(m_display), 0, 0, 0, 0, x, y);
}
Ejemplo n.º 26
0
///
//  WinCreate()
//
//      This function initialized the native X11 display and window for EGL
//
EGLBoolean WinCreate(ESContext *esContext, const char *title)
{
    Window root;
    XSetWindowAttributes swa;
    XSetWindowAttributes  xattr;
    Atom wm_state;
    XWMHints hints;
    XEvent xev;
    Window win;

    /*
     * X11 native display initialization
     */

    x_display = XOpenDisplay(NULL);
    if ( x_display == NULL )
    {
        return EGL_FALSE;
    }

    root = DefaultRootWindow(x_display);

    swa.event_mask  =  ExposureMask | PointerMotionMask | KeyPressMask;
    win = XCreateWindow(
              x_display, root,
              0, 0, esContext->width, esContext->height, 0,
              CopyFromParent, InputOutput,
              CopyFromParent, CWEventMask,
              &swa );

    xattr.override_redirect = FALSE;
    XChangeWindowAttributes ( x_display, win, CWOverrideRedirect, &xattr );

    hints.input = TRUE;
    hints.flags = InputHint;
    XSetWMHints(x_display, win, &hints);

    // make the window visible on the screen
    XMapWindow (x_display, win);
    XStoreName (x_display, win, title);

    // get identifiers for the provided atom name strings
    wm_state = XInternAtom (x_display, "_NET_WM_STATE", FALSE);

    memset ( &xev, 0, sizeof(xev) );
    xev.type                 = ClientMessage;
    xev.xclient.window       = win;
    xev.xclient.message_type = wm_state;
    xev.xclient.format       = 32;
    xev.xclient.data.l[0]    = 1;
    xev.xclient.data.l[1]    = FALSE;
    XSendEvent (
        x_display,
        DefaultRootWindow ( x_display ),
        FALSE,
        SubstructureNotifyMask,
        &xev );

    esContext->hWnd = (EGLNativeWindowType) win;
    return EGL_TRUE;
}
Ejemplo n.º 27
0
static Window make_selection_window(Display*dpy)
{
  Window win = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy), 0, 0, 1, 1, 0, 0, 0);
  XSelectInput(dpy, win, PropertyChangeMask);
  return win;
}
Ejemplo n.º 28
0
/*
 * Create an RGB, double-buffered window.
 * Return the window and context handles.
 */
static void make_window(Display * dpy, Screen * scr, EGLDisplay eglDisplay,
			EGLSurface * winRet, EGLContext * ctxRet)
{
	EGLSurface eglSurface = EGL_NO_SURFACE;
	EGLContext eglContext;
	EGLConfig configs[MAX_NUM_CONFIGS];
	EGLint config_count;
	XWindowAttributes WinAttr;
	int XResult = BadImplementation;
	int blackColour = BlackPixel(dpy, DefaultScreen(dpy));
	EGLint cfg_attribs[] = {
		EGL_NATIVE_VISUAL_TYPE, 0,

		/* RGB565 */
		EGL_BUFFER_SIZE, 16,
		EGL_RED_SIZE, 5,
		EGL_GREEN_SIZE, 6,
		EGL_BLUE_SIZE, 5,

		EGL_DEPTH_SIZE, 8,

		EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
		EGL_RENDERABLE_TYPE, EGL_OPENGL_ES_BIT,

		EGL_NONE
	};
	EGLint i;

	win =
	    XCreateSimpleWindow(dpy, DefaultRootWindow(dpy), 0, 0, 1, 1, 0,
				blackColour, blackColour);
	XStoreName(dpy, win, WINDOW_CLASS_NAME);

	XSelectInput(dpy, win, X_MASK);

	if (!(XResult = XGetWindowAttributes(dpy, win, &WinAttr)))
		GLimp_HandleError();

	GLimp_DisableComposition();
	XMapWindow(dpy, win);
	GLimp_DisableComposition();

	XFlush(dpy);

	if (!eglGetConfigs(eglDisplay, configs, MAX_NUM_CONFIGS, &config_count))
		GLimp_HandleError();

	if (!eglChooseConfig
	    (eglDisplay, cfg_attribs, configs, MAX_NUM_CONFIGS, &config_count))
		GLimp_HandleError();

	for (i = 0; i < config_count; i++) {
		if ((eglSurface =
		     eglCreateWindowSurface(eglDisplay, configs[i],
					    (NativeWindowType) win,
					    NULL)) != EGL_NO_SURFACE)
			break;
	}
	if (eglSurface == EGL_NO_SURFACE)
		GLimp_HandleError();

	if ((eglContext =
	     eglCreateContext(eglDisplay, configs[i], EGL_NO_CONTEXT,
			      NULL)) == EGL_NO_CONTEXT)
		GLimp_HandleError();

	if (!eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext))
		GLimp_HandleError();

	*winRet = eglSurface;
	*ctxRet = eglContext;
}
	//-------------------------------------------------------------------------------------------------//
	GLXGLSupport::GLXGLSupport() : mGLDisplay(0), mXDisplay(0)
	{
		// A connection that might be shared with the application for GL rendering:
		mGLDisplay = getGLDisplay();
		
		// A connection that is NOT shared to enable independent event processing:
		mXDisplay  = getXDisplay();
		
		int dummy;
		
		if (XQueryExtension(mXDisplay, "RANDR", &dummy, &dummy, &dummy))
		{
			XRRScreenConfiguration *screenConfig;
			
			screenConfig = XRRGetScreenInfo(mXDisplay, DefaultRootWindow(mXDisplay));
			
			if (screenConfig) 
			{
				XRRScreenSize *screenSizes;
				int nSizes = 0;
				Rotation currentRotation;
				int currentSizeID = XRRConfigCurrentConfiguration(screenConfig, &currentRotation);
				
				screenSizes = XRRConfigSizes(screenConfig, &nSizes);
				
				mCurrentMode.first.first = screenSizes[currentSizeID].width;
				mCurrentMode.first.second = screenSizes[currentSizeID].height;
				mCurrentMode.second = XRRConfigCurrentRate(screenConfig);
				
				mOriginalMode = mCurrentMode;
				
				for(int sizeID = 0; sizeID < nSizes; sizeID++) 
				{
					short *rates;
					int nRates = 0;
					
					rates = XRRConfigRates(screenConfig, sizeID, &nRates);
					
					for (int rate = 0; rate < nRates; rate++)
					{
						VideoMode mode;
						
						mode.first.first = screenSizes[sizeID].width;
						mode.first.second = screenSizes[sizeID].height;
						mode.second = rates[rate];
						
						mVideoModes.push_back(mode);
					}
				}
				XRRFreeScreenConfigInfo(screenConfig);
			}
		}
		else
		{
			mCurrentMode.first.first = DisplayWidth(mXDisplay, DefaultScreen(mXDisplay));
			mCurrentMode.first.second = DisplayHeight(mXDisplay, DefaultScreen(mXDisplay));
			mCurrentMode.second = 0;
			
			mOriginalMode = mCurrentMode;
			
			mVideoModes.push_back(mCurrentMode);
		}
		
		GLXFBConfig *fbConfigs;
		int config, nConfigs = 0;
		
		fbConfigs = chooseFBConfig(NULL, &nConfigs);
		
		for (config = 0; config < nConfigs; config++)
		{
			int caveat, samples;
			
			getFBConfigAttrib (fbConfigs[config], GLX_CONFIG_CAVEAT, &caveat);
			
			if (caveat != GLX_SLOW_CONFIG)
			{
				getFBConfigAttrib (fbConfigs[config], GLX_SAMPLES, &samples);
				mSampleLevels.push_back(StringConverter::toString(samples));
			}
		}
		
		XFree (fbConfigs);
		
		remove_duplicates(mSampleLevels);
	}
Ejemplo n.º 30
0
static void run(Display *dpy, int width, int height,
		unsigned int *attachments, int nattachments,
		const char *name)
{
	Window win;
	XSetWindowAttributes attr;
	int count;
	DRI2Buffer *buffers;
	struct timespec start, end;

	/* Be nasty and install a fullscreen window on top so that we
	 * can guarantee we do not get clipped by children.
	 */
	attr.override_redirect = 1;
	win = XCreateWindow(dpy, DefaultRootWindow(dpy),
			 0, 0, width, height, 0,
			 DefaultDepth(dpy, DefaultScreen(dpy)),
			 InputOutput,
			 DefaultVisual(dpy, DefaultScreen(dpy)),
			 CWOverrideRedirect, &attr);
	XMapWindow(dpy, win);
	xsync(dpy, win);

	DRI2CreateDrawable(dpy, win);

	buffers = DRI2GetBuffers(dpy, win, &width, &height,
				 attachments, nattachments, &count);
	if (count != nattachments)
		return;

	xsync(dpy, win);
	clock_gettime(CLOCK_MONOTONIC, &start);
	for (count = 0; count < COUNT; count++)
		DRI2SwapBuffers(dpy, win, 0, 0, 0);
	xsync(dpy, win);
	clock_gettime(CLOCK_MONOTONIC, &end);
	printf("%d %s (%dx%d) swaps in %fs.\n",
	       count, name, width, height, elapsed(&start, &end));

	xsync(dpy, win);
	clock_gettime(CLOCK_MONOTONIC, &start);
	for (count = 0; count < COUNT; count++)
		dri2_copy_swap(dpy, win, width, height, nattachments == 2);
	xsync(dpy, win);
	clock_gettime(CLOCK_MONOTONIC, &end);

	printf("%d %s (%dx%d) blits in %fs.\n",
	       count, name, width, height, elapsed(&start, &end));

	DRI2SwapInterval(dpy, win, 0);

	xsync(dpy, win);
	clock_gettime(CLOCK_MONOTONIC, &start);
	for (count = 0; count < COUNT; count++)
		DRI2SwapBuffers(dpy, win, 0, 0, 0);
	xsync(dpy, win);
	clock_gettime(CLOCK_MONOTONIC, &end);
	printf("%d %s (%dx%d) vblank=0 swaps in %fs.\n",
	       count, name, width, height, elapsed(&start, &end));

	XDestroyWindow(dpy, win);
	free(buffers);

	XSync(dpy, 1);
}