Exemple #1
0
static Lock *
lockscreen(Display *dpy, int screen)     /* Here is the meat */
{
    int count;
    Lock *lock;
    XSetWindowAttributes wa;

    if (dpy == NULL || screen < 0)
        return NULL;

    lock = malloc(sizeof(Lock));

    if (lock == NULL)
        return NULL;

    lock->screen = screen;
    lock->root = RootWindow(dpy, lock->screen);
    /* init */
    wa.override_redirect = true;
    wa.background_pixel = BlackPixel(dpy, lock->screen);
    lock->win = XCreateWindow(dpy, lock->root, 0, 0, DisplayWidth(dpy, lock->screen), DisplayHeight(dpy, lock->screen),
                              0, DefaultDepth(dpy, lock->screen), CopyFromParent,
                              DefaultVisual(dpy, lock->screen), CWOverrideRedirect | CWBackPixel, &wa);
    XMapRaised(dpy, lock->win);

    for (count = 0; count < 10000; ++count)
    {
        if (XGrabPointer(dpy, lock->root, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
                         GrabModeAsync, GrabModeAsync, None, None, CurrentTime) == GrabSuccess)
            break;
    }

    if (count < 10000)
    {
        for (count = 0; count < 10000; ++count)
        {
            if (XGrabKeyboard(dpy, lock->root, True, GrabModeAsync, GrabModeAsync, CurrentTime)
                    == GrabSuccess)
                break;
        }
    }

    if (count >= 10000)  // timed out
    {
        unlockscreen(dpy, lock);
        lock = NULL;
    }
    else
        XSelectInput(dpy, lock->root, SubstructureNotifyMask);

    return lock;
}
Exemple #2
0
GLWindow::WindowPos GLWindow::getRootWindowPos(void) const
	{
	return WindowPos(DisplayWidth(display,screen),DisplayHeight(display,screen));
	}
Exemple #3
0
/**
 * Initialize the x11 grab device demuxer (public device demuxer API).
 *
 * @param s1 Context from avformat core
 * @return <ul>
 *          <li>AVERROR(ENOMEM) no memory left</li>
 *          <li>AVERROR(EIO) other failure case</li>
 *          <li>0 success</li>
 *         </ul>
 */
static int x11grab_read_header(AVFormatContext *s1)
{
    X11GrabContext *x11grab = s1->priv_data;
    Display *dpy;
    AVStream *st = NULL;
    XImage *image;
    int x_off = 0, y_off = 0, ret = 0, screen, use_shm;
    char *param, *offset;
    AVRational framerate;

    param = av_strdup(s1->filename);
    if (!param)
        goto out;

    offset = strchr(param, '+');
    if (offset) {
        sscanf(offset, "%d,%d", &x_off, &y_off);
        x11grab->draw_mouse = !strstr(offset, "nomouse");
        *offset = 0;
    }

    ret = av_parse_video_size(&x11grab->width, &x11grab->height,
                              x11grab->video_size);
    if (ret < 0) {
        av_log(s1, AV_LOG_ERROR, "Couldn't parse video size.\n");
        goto out;
    }

    ret = av_parse_video_rate(&framerate, x11grab->framerate);
    if (ret < 0) {
        av_log(s1, AV_LOG_ERROR, "Could not parse framerate: %s.\n",
               x11grab->framerate);
        goto out;
    }
    av_log(s1, AV_LOG_INFO,
           "device: %s -> display: %s x: %d y: %d width: %d height: %d\n",
           s1->filename, param, x_off, y_off, x11grab->width, x11grab->height);

    dpy = XOpenDisplay(param);
    if (!dpy) {
        av_log(s1, AV_LOG_ERROR, "Could not open X display.\n");
        ret = AVERROR(EIO);
        goto out;
    }

    st = avformat_new_stream(s1, NULL);
    if (!st) {
        ret = AVERROR(ENOMEM);
        goto out;
    }
    avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */

    screen = DefaultScreen(dpy);

    if (x11grab->follow_mouse) {
        int screen_w, screen_h;
        Window w;

        screen_w = DisplayWidth(dpy, screen);
        screen_h = DisplayHeight(dpy, screen);
        XQueryPointer(dpy, RootWindow(dpy, screen), &w, &w, &x_off, &y_off,
                      &ret, &ret, &ret);
        x_off -= x11grab->width / 2;
        y_off -= x11grab->height / 2;
        x_off  = FFMIN(FFMAX(x_off, 0), screen_w - x11grab->width);
        y_off  = FFMIN(FFMAX(y_off, 0), screen_h - x11grab->height);
        av_log(s1, AV_LOG_INFO,
               "followmouse is enabled, resetting grabbing region to x: %d y: %d\n",
               x_off, y_off);
    }

    use_shm = XShmQueryExtension(dpy);
    av_log(s1, AV_LOG_INFO,
           "shared memory extension %sfound\n", use_shm ? "" : "not ");

    if (use_shm && setup_shm(s1, dpy, &image) < 0) {
        av_log(s1, AV_LOG_WARNING, "Falling back to XGetImage\n");
        use_shm = 0;
    }

    if (!use_shm) {
        image = XGetImage(dpy, RootWindow(dpy, screen),
                          x_off, y_off,
                          x11grab->width, x11grab->height,
                          AllPlanes, ZPixmap);
    }

    if (x11grab->draw_mouse && setup_mouse(dpy, screen) < 0) {
        av_log(s1, AV_LOG_WARNING,
               "XFixes not available, cannot draw the mouse cursor\n");
        x11grab->draw_mouse = 0;
    }

    x11grab->frame_size = x11grab->width * x11grab->height * image->bits_per_pixel / 8;
    x11grab->dpy        = dpy;
    x11grab->time_base  = (AVRational) { framerate.den, framerate.num };
    x11grab->time_frame = av_gettime() / av_q2d(x11grab->time_base);
    x11grab->x_off      = x_off;
    x11grab->y_off      = y_off;
    x11grab->image      = image;
    x11grab->use_shm    = use_shm;

    ret = pixfmt_from_image(s1, image, &st->codecpar->format);
    if (ret < 0)
        goto out;

    st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
    st->codecpar->codec_id   = AV_CODEC_ID_RAWVIDEO;
    st->codecpar->width      = x11grab->width;
    st->codecpar->height     = x11grab->height;
    st->codecpar->bit_rate   = x11grab->frame_size * 1 / av_q2d(x11grab->time_base) * 8;

    st->avg_frame_rate       = av_inv_q(x11grab->time_base);

out:
    av_free(param);
    return ret;
}
void
setup(void) {
	int x, y, screen = DefaultScreen(dc->dpy);
	Window root = RootWindow(dc->dpy, screen);
	XSetWindowAttributes swa;
	XIM xim;
#ifdef XINERAMA
	int n;
	XineramaScreenInfo *info;
#endif

	clip = XInternAtom(dc->dpy, "CLIPBOARD",   False);
	utf8 = XInternAtom(dc->dpy, "UTF8_STRING", False);

	/* calculate menu geometry */
	bh = dc->font.height + 2;
	lines = MAX(lines, 0);
	mh = (lines + 1) * bh;
#ifdef XINERAMA
	if((info = XineramaQueryScreens(dc->dpy, &n))) {
		int a, j, di, i = 0, area = 0;
		unsigned int du;
		Window w, pw, dw, *dws;
		XWindowAttributes wa;

		XGetInputFocus(dc->dpy, &w, &di);
		if(w != root && w != PointerRoot && w != None) {
			/* find top-level window containing current input focus */
			do {
				if(XQueryTree(dc->dpy, (pw = w), &dw, &w, &dws, &du) && dws)
					XFree(dws);
			} while(w != root && w != pw);
			/* find xinerama screen with which the window intersects most */
			if(XGetWindowAttributes(dc->dpy, pw, &wa))
				for(j = 0; j < n; j++)
					if((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) {
						area = a;
						i = j;
					}
		}
		/* no focused window is on screen, so use pointer location instead */
		if(!area && XQueryPointer(dc->dpy, root, &dw, &dw, &x, &y, &di, &di, &du))
			for(i = 0; i < n; i++)
				if(INTERSECT(x, y, 1, 1, info[i]))
					break;

		x = info[i].x_org;
		y = info[i].y_org + (topbar ? 0 : info[i].height - mh);
		mw = info[i].width;
		XFree(info);
	}
	else
#endif
	{
		x = 0;
		y = topbar ? 0 : DisplayHeight(dc->dpy, screen) - mh;
		mw = DisplayWidth(dc->dpy, screen);
	}
	promptw = prompt ? textw(dc, prompt) : 0;
	inputw = MIN(inputw, mw/3);
	match();

	/* create menu window */
	swa.override_redirect = True;
	swa.background_pixel = normcol->BG;
	swa.event_mask = ExposureMask | KeyPressMask | VisibilityChangeMask;
	win = XCreateWindow(dc->dpy, root, x, y, mw, mh, 0,
	                    DefaultDepth(dc->dpy, screen), CopyFromParent,
	                    DefaultVisual(dc->dpy, screen),
	                    CWOverrideRedirect | CWBackPixel | CWEventMask, &swa);

	/* open input methods */
	xim = XOpenIM(dc->dpy, NULL, NULL, NULL);
	xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
	                XNClientWindow, win, XNFocusWindow, win, NULL);

	XMapRaised(dc->dpy, win);
	resizedc(dc, mw, mh);
	drawmenu();
}
//-------------------------------------------------------------------------------------------------//
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);
}
Exemple #6
0
static int init(char *options)
{
        int res;
        SDL_Rect **rects;
        int *bpp, n;
        int bpps[] = { 8, 15, 16, 24, 32, 0 };
        SDL_PixelFormat fmt;
        const SDL_VideoInfo *vi;
#if defined(__XWIN__)
        Display *dsp;
#endif
        SDL_Rect rect = { 0, 0, 0, 0 };
        int i;
        GrxVideoMode mode, *modep = &modes[1];
        GrxVideoModeExt ext, *extp = &exts[0];
        GRX_ENTER();
        res = FALSE;
        if(detect()) {
            if(options) {
                if(!strncmp(options, "fs", 2)) fullscreen = TRUE;
                else if(!strncmp(options, "ww", 2)) fullscreen = FALSE;
            }
            memzero(modep,(sizeof(modes) - sizeof(modes[0])));
            if(fullscreen) {
                memzero(&fmt, sizeof fmt);
                for(bpp = bpps; *bpp; bpp++) {
                    fmt.BitsPerPixel = *bpp;
                    rects = SDL_ListModes(&fmt, SDL_HWSURFACE|SDL_FULLSCREEN);
                    if(rects != NULL && rects != (SDL_Rect **) -1) {
                        for(n = 0; rects[n] != NULL; n++);
                        for(i = n - 1; i >= 0; i--) {
                            if(!build_video_mode(n-i,
                                                 SDL_HWSURFACE|SDL_FULLSCREEN,
                                                 rects[i], &fmt, &mode, &ext))
                                continue;
                            add_video_mode(&mode,&ext,&modep,&extp);
                        }
                    }
                }
            }
            if(modep == &modes[1]) {
                if((vi = SDL_GetVideoInfo()) == NULL) {
                    DBGPRINTF(DBG_DRIVER, ("SDL_GetVideoInfo() failed\n"));
                    goto done;
                }
#if defined(__WIN32__)
                MaxWidth = GetSystemMetrics(SM_CXSCREEN);
                MaxHeight = GetSystemMetrics(SM_CYSCREEN);
#elif defined(__XWIN__)
                if((dsp = XOpenDisplay("")) != NULL) {
                    MaxWidth = DisplayWidth(dsp, DefaultScreen(dsp));
                    MaxHeight = DisplayHeight(dsp, DefaultScreen(dsp));
                    XCloseDisplay(dsp);
                }
                else {
                    MaxWidth = 9600;
                    MaxHeight = 7200;
                }
#endif
                for(i = 0; i < NUM_RESOS; i++) {
                    rect.w = resos[i].w;
                    rect.h = resos[i].h;
                    if(!build_video_mode(i+1, SDL_SWSURFACE, &rect, vi->vfmt,
                                         &mode, &ext))
                        continue;
                    mode.present = rect.w <= MaxWidth && rect.h <= MaxHeight;
                    add_video_mode(&mode,&ext,&modep,&extp);
                }
            }
            res = TRUE;
        }
done:        if(!res) reset();
        GRX_RETURN(res);
}
Exemple #7
0
int main(int argc,char **argv){
    ProgData pdata;
    int exit_status = 0;
    
    SetupDefaultArgs(&pdata.args);

    if (!ParseArgs(argc, argv, &pdata.args)) {
        exit(1);
    }
    if (pdata.args.rescue_path != NULL) {
        exit(rmdRescue(pdata.args.rescue_path));
    }
    if(XInitThreads ()==0){
        fprintf(stderr,"Couldn't initialize thread support!\n");
        exit(7);
    }
    if(pdata.args.display!=NULL){
        pdata.dpy = XOpenDisplay(pdata.args.display);
        XSetErrorHandler(rmdErrorHandler);
    }
    else{
        fprintf(stderr,"No display specified for connection!\n");
        exit(8);
    }
    if (pdata.dpy == NULL) {
        fprintf(stderr, "Cannot connect to X server %s\n",pdata.args.display);
        exit(9);
    }
    else{
        EncData enc_data;
        CacheData cache_data;
#ifdef HAVE_LIBJACK
        JackData jdata;

        // Give jack access to program data, mainly for program state
        jdata.pdata = &pdata;
        pdata.jdata = &jdata;
#endif

        // Query display specs
        pdata.specs.screen = DefaultScreen(pdata.dpy);
        pdata.specs.width  = DisplayWidth(pdata.dpy, pdata.specs.screen);
        pdata.specs.height = DisplayHeight(pdata.dpy, pdata.specs.screen);
        pdata.specs.root   = RootWindow(pdata.dpy, pdata.specs.screen);
        pdata.specs.visual = DefaultVisual(pdata.dpy, pdata.specs.screen);
        pdata.specs.gc     = DefaultGC(pdata.dpy, pdata.specs.screen);
        pdata.specs.depth  = DefaultDepth(pdata.dpy, pdata.specs.screen);

        if((pdata.specs.depth!=32)&&
           (pdata.specs.depth!=24)&&
           (pdata.specs.depth!=16)){
            fprintf(stderr,"Only 32bpp,24bpp and 16bpp"
                           " color depth modes are currently supported.\n");
            exit(10);
        }
        if (!SetBRWindow(pdata.dpy, &pdata.brwin, &pdata.specs, &pdata.args))
            exit(11);

        if( !pdata.args.nowmcheck && 
            rmdWMIsCompositing( pdata.dpy, pdata.specs.screen ) ) {

            fprintf(stderr,"\nDetected compositing window manager.\n"
                           "Reverting to full screen capture at every frame.\n"
                           "To disable this check run with --no-wm-check\n"
                           "(though that is not advised, since it will "
                           "probably produce faulty results).\n\n");
            pdata.args.full_shots=1;
            pdata.args.noshared=0;
        
        }

        QueryExtensions(pdata.dpy,
                        &pdata.args,
                        &pdata.damage_event,
                        &pdata.damage_error,
                        &pdata.shm_opcode);


        if((exit_status=InitializeData(&pdata,&enc_data,&cache_data))==0){

            if(!strcmp(pdata.args.pause_shortcut,
                      pdata.args.stop_shortcut)||
                RegisterShortcut(pdata.dpy,
                                 pdata.specs.root,
                                 pdata.args.pause_shortcut,
                                 &(pdata.pause_key)) ||
                RegisterShortcut(pdata.dpy,
                                 pdata.specs.root,
                                 pdata.args.stop_shortcut,
                                 &(pdata.stop_key))){

                fprintf(stderr,"Invalid shortcut,"
                               " or shortcuts are the same!\n\n"
                               "Using defaults.\n");

                RegisterShortcut(pdata.dpy,
                                 pdata.specs.root,
                                 "Control+Mod1+p",
                                 &(pdata.pause_key));
                RegisterShortcut(pdata.dpy,
                                 pdata.specs.root,
                                 "Control+Mod1+s",
                                 &(pdata.stop_key));
            }

            //this is where the capturing happens.
            rmdThreads(&pdata);

            XCloseDisplay(pdata.dpy);
            fprintf(stderr,".\n");

            //encode and then cleanup cache
            if(!pdata.args.encOnTheFly && !pdata.args.no_encode){
                if (!pdata.aborted) {
                    EncodeCache(&pdata);
                }
                fprintf(stderr,"Cleanning up cache...\n");
                if(PurgeCache(pdata.cache_data,!pdata.args.nosound))
                    fprintf(stderr,"Some error occured "
                                "while cleaning up cache!\n");
                fprintf(stderr,"Done!!!\n");
            }


            if (pdata.aborted && pdata.args.encOnTheFly) {
                if(remove(pdata.args.filename)){
                    perror("Error while removing file:\n");
                    return 1;
                }
                else{
                    fprintf(stderr,"SIGABRT received,file %s removed\n",
                                pdata.args.filename);
                    return 0;
                }
            }
            else
                fprintf(stderr,"Goodbye!\n");


            CleanUp();
        }
    }

    return exit_status;
}
Exemple #8
0
void initX() {
    int x,y;
    unsigned int border_width = 4;
    unsigned int display_width, display_height;
    char *window_name = "postplot";
    char *icon_name = "postplot";
    Pixmap icon_pixmap;
    XSizeHints *size_hints;
    XIconSize *size_list;
    XWMHints *wm_hints;
    XClassHint *class_hints;
    XTextProperty windowName, iconName;
    XSetWindowAttributes attr;
    int icount;
    XFontStruct *font_info;
    char *display_name = NULL;

    int dbug=0;

    if (!(size_hints = XAllocSizeHints())) {
        fprintf(stderr, "%s: failure allocating SizeHints memory\n", progname);
        exit (0);
    }
    if (!(wm_hints = XAllocWMHints())) {
        fprintf(stderr, "%s: failure allocating WMHints memory\n", progname);
        exit (0);
    }
    if (!(class_hints = XAllocClassHint())) {
        fprintf(stderr, "%s: failure allocating ClassHint memory\n", progname);
        exit (0);
    }

    /* Connect to X server */
    if ( (dpy=XOpenDisplay(display_name)) == NULL ) {
        (void) fprintf( stderr, "%s: cannot connect to X server %s\n",
            progname, XDisplayName(display_name));
        exit(-1);
    }

    /* Get screen size from display structure macro */
    screen_num = DefaultScreen(dpy);
    display_width = DisplayWidth(dpy, screen_num);
    display_height = DisplayHeight(dpy, screen_num);

    /* eventually we want to set x,y from command line or
       resource database */

    x=y=0;

    /* Size window */
    width = display_width/2, height = display_height/2;


    /* Create opaque window */
    win = XCreateSimpleWindow(dpy, RootWindow(dpy,screen_num),
        x,y,width, height, border_width, WhitePixel(dpy,screen_num),
        BlackPixel(dpy,screen_num));

    /* Get available icon sizes from window manager */

    if (XGetIconSizes(dpy, RootWindow(dpy, screen_num),
            &size_list, &icount) == 0) {
        if (dbug) fprintf(stderr, 
		"%s: WM didn't set icon sizes - using default.\n", progname);
    } else {
        /* should eventually create a pixmap here */
        ;
    }

    /* Create pixmap of depth 1 (bitmap) for icon */
    icon_pixmap = XCreateBitmapFromData(dpy, win,
        icon_bitmap_bits, icon_bitmap_width, icon_bitmap_height);
    
    size_hints->flags = PPosition | PSize | PMinSize;
    size_hints->min_width =  300;
    size_hints->min_height = 200;

    if (XStringListToTextProperty(&window_name, 1, &windowName) == 0) {
        fprintf(stderr, "%s: structure allocation for windowName failed.\n",
            progname);
        exit(-1);
    }

    if (XStringListToTextProperty(&icon_name, 1, &iconName) == 0) {
        fprintf(stderr, "%s: structure allocation for iconName failed.\n",
            progname);
        exit(-1);
    }
    
    wm_hints->initial_state = NormalState;
    wm_hints->input = True;
    wm_hints->icon_pixmap = icon_pixmap;

    wm_hints->flags = StateHint | IconPixmapHint | InputHint;

    class_hints->res_name = progname;
    class_hints->res_class = "pdp";

    XSetWMProperties(dpy, win, &windowName, &iconName,
             (char **) NULL, (int) 0, size_hints, wm_hints, class_hints);

    /* Select event types wanted */
    XSelectInput(dpy, win, ExposureMask | KeyPressMask |
        ButtonPressMask | ButtonReleaseMask | StructureNotifyMask | 
	Button1MotionMask );

    init_colors();
    load_font(&font_info);

    /* Create GC for text and drawing */
    getGC(win, &gc, font_info);
    getGC(win, &gcx, font_info);
    XSetFunction(dpy, gcx, GXxor);

    /* Display window */
    XMapWindow(dpy, win);

    /* turn on backing store */
    attr.backing_store = Always;
    XChangeWindowAttributes(dpy,win,CWBackingStore,&attr);     
}
Exemple #9
0
int save_image (FILE *file)
{
	int 		x_loc,y_loc;
#ifdef X11WM
	Window    	canvas_root_win, child_win;
        XImage		*ximage;
#else
	void *ximage = NULL;
#endif
	char		r[MAX_COLORS],g[MAX_COLORS],b[MAX_COLORS];
	unsigned int	x_width,y_height,border_width,depth;
	int		width, height;
#ifdef X11WM
	int		screen = DefaultScreen(connect_id.display);
	int		scrn_width=DisplayWidth(connect_id.display,screen);
        int		scrn_height=DisplayHeight(connect_id.display,screen);
#else
	int		screen;
	int		scrn_width;
        int		scrn_height;
#endif
	int		x1,y1;

	/* 
 	 * Get allocated memory for the XImage structure and copy the
 	 * canvas window to it.
	 */
	/* Get the application window's position */

#ifdef X11WM
	XRaiseWindow(connect_id.display,connect_id.drawable);
	if (	XGetGeometry(
		connect_id.display,connect_id.drawable, &canvas_root_win,
	   	&x_loc, &y_loc, &x_width, &y_height, &border_width, &depth) == 0
				||
		XTranslateCoordinates(connect_id.display,connect_id.drawable,
		canvas_root_win,0,0,&x1,&y1,&child_win) == False)
	  {
	   err_warn(1,fperr,"Error - getting raster image.\n");
	   return 0;
	  }

	width = x_width;
	height = y_height;

	/* Find the new x location and the width, if necessary. */

	if ((-x1 > width) || (x1 > scrn_width)) {
	   err_warn(1,fperr,"Error - X for getting raster image.\n");
	   return 0;
	  }
	if (x1 < 0)
	  {
	   width=width+x1;
	   x1=0;
	  }
	else if (x1+width > scrn_width)
	  {
	   width=scrn_width-x1;
	  }

	if ((-y1 > height) || (y1 > scrn_height)) {
	   err_warn(1,fperr,"Error - Y for getting raster image.\n");
	   return 0;
	  }
	if (y1 < 0)
	  {
	   height=height+y1;
	   y1=0;
	  }
	else if (y1+height > scrn_height)
	  {
	   height=scrn_height-y1;
	  }

        /* This way is good because the root window will create partially obscure windows.
	 * But this method doesn't work for the Mac which has a rootless window.
         * ximage = XGetImage(cptr->connect_id.display,
                RootWindowOfScreen(DefaultScreenOfDisplay(cptr->connect_id.display)),
                   x1, y1, width, height, XAllPlanes(), ZPixmap);
         */
	ximage = XGetImage(connect_id.display,
		           connect_id.drawable,
                           0, 0, width, height, XAllPlanes(), ZPixmap);
#elif defined QTWM
	vcs_Qt_window_get_image_by_id(connect_id.wkst_id,&ximage);
#else
	fprintf(stderr,"insert here your WM to get image\n");
#endif
        if (ximage == NULL)
	  {
	   err_warn(1,fperr,"Error - getting raster image.\n");
	   return 0;
	  }
	/* If display has 8 bit color */
#ifdef X11WM
        if (ximage->depth == 8) {
           /* Convert X colors to u_char arrays */
           convert_gks_color(r, g, b);

           /* Save the image and its colormap in a Sun Raster file */
           ras_write_ximage(file,  ximage, r, g, b, MAX_COLORS);
        } else {
           /* Save the image with no colormap in a Sun Raster file */
           ras_write_ximage(file, ximage, NULL, NULL, NULL, 0);
	}
#elif defined QTWM
	ras_write_ximage(file, ximage, NULL, NULL, NULL, 0);
#else
	fprintf(stderr,"insert here your write to ras func\n");
#endif

	/* Print out image information
        print_image_info(x_loc, y_loc, ximage, MAX_COLORS);
	*/

	/* Remove the image from memory */
#ifdef X11WM
        XDestroyImage(ximage);
#elif defined QTWM
	free(ximage);
#else
	fprintf(stderr,"insert here your destroy ximage func\n");
#endif
	return 1;
}
Exemple #10
0
/*****************************************************************************
 * 
 * This routine is responsible for reading and parsing the config file
 *
 ****************************************************************************/
void ParseOptions(char *filename)
{
  FILE *fd = (FILE *)0;
  char line[256];
  char *tline,*orig_tline,*tmp;
  int Clength,n,desk;
  
  Scr.FvwmRoot = NULL;
  Scr.Hilite = NULL;
  Scr.VScale = 32;
  
  Scr.MyDisplayWidth = DisplayWidth(dpy, Scr.screen);
  Scr.MyDisplayHeight = DisplayHeight(dpy, Scr.screen);
  
  Scr.VxMax = 3*Scr.MyDisplayWidth - Scr.MyDisplayWidth;
  Scr.VyMax = 3*Scr.MyDisplayHeight - Scr.MyDisplayHeight;
  if(Scr.VxMax <0)
    Scr.VxMax = 0;
  if(Scr.VyMax <0)
    Scr.VyMax = 0;
  Scr.Vx = 0;
  Scr.Vy = 0;
  
  fd = fopen(filename,"r");
  if(fd == (FILE *)0)
    {
      fprintf(stderr,"%s: can't open config file %s",MyName,filename);
      exit(1);
    }
  
  tline = fgets(line,(sizeof line)-1,fd);
  orig_tline = tline;
  Clength = strlen(MyName);
  while(tline != (char *)0)
    {
      int g_x, g_y, flags;
      unsigned width,height;
      
      while(isspace(*tline))tline++;
      
      if((strlen(&tline[0])>1)&&
	 (mystrncasecmp(tline, CatString3("*", MyName, "Geometry"),Clength+9)==0))
	{
	  tmp = &tline[Clength+9];
	  while(((isspace(*tmp))&&(*tmp != '\n'))&&(*tmp != 0))
	    {
	      tmp++;
	    }
	  tmp[strlen(tmp)-1] = 0;
	  
	  flags = XParseGeometry(tmp,&g_x,&g_y,&width,&height);
	  if (flags & WidthValue) 
	    window_w = width;
	  if (flags & HeightValue) 
	    window_h = height;
	  if (flags & XValue) 
	    {
	      window_x = g_x;
	      usposition = 1;
	    }
	  if (flags & YValue) 
	    {
	      window_y = g_y;
	      usposition = 1;
	    }
	}
      else if((strlen(&tline[0])>1)&&
	 (mystrncasecmp(tline, CatString3("*", MyName, "IconGeometry"),
		      Clength+13)==0))
	{
	  tmp = &tline[Clength+13];
	  while(((isspace(*tmp))&&(*tmp != '\n'))&&(*tmp != 0))
	    {
	      tmp++;
	    }
	  tmp[strlen(tmp)-1] = 0;
	  
	  flags = XParseGeometry(tmp,&g_x,&g_y,&width,&height);
	  if (flags & WidthValue) 
	    icon_w = width;
	  if (flags & HeightValue) 
	    icon_h = height;
	  if (flags & XValue) 
	    {
	      icon_x = g_x;
	    }
	  if (flags & YValue) 
	    {
	      icon_y = g_y;
	    }
	}
      else if((strlen(&tline[0])>1)&&
	      (mystrncasecmp(tline,CatString3("*",MyName,"Label"),Clength+6)==0))
	{
	  desk = desk1;
	  sscanf(&tline[Clength+6],"%d",&desk);
	  if((desk >= desk1)&&(desk <=desk2))
	    {
	      n = 0;
	      while(isspace(tline[Clength+6+n]))n++;
	      while(!isspace(tline[Clength+6+n]))n++;
	      free(Desks[desk - desk1].label);
	      CopyString(&Desks[desk - desk1].label,&tline[Clength+6+n]);
	    }
	}
      else if((strlen(&tline[0])>1)&&
	      (mystrncasecmp(tline, CatString3("*", MyName, "Font"),Clength+5)==0))
	{
	  CopyString(&font_string,&tline[Clength+5]);
	  if(mystrncasecmp(font_string,"none",4) == 0)
	    uselabel = 0;

	}
      else if((strlen(&tline[0])>1)&&
	      (mystrncasecmp(tline, CatString3("*", MyName, "Fore"),Clength+5)==0))
	{
	  CopyString(&PagerFore,&tline[Clength+5]);
	}
      else if((strlen(&tline[0])>1)&&
	      (mystrncasecmp(tline,CatString3("*", MyName, "Back"),Clength+5)==0))
	{
	  CopyString(&PagerBack,&tline[Clength+5]);
	}	
      else if((strlen(&tline[0])>1)&&
	      (mystrncasecmp(tline,CatString3("*",MyName,"Hilight"),Clength+8)==0))
	{
	  if(Scr.d_depth > 1)
	    CopyString(&HilightC,&tline[Clength+8]);
	}	
      else if((strlen(&tline[0])>1)&&
	      (mystrncasecmp(tline,CatString3("*",MyName,"SmallFont"),
			   Clength+10)==0))
	{
	  CopyString(&smallFont,&tline[Clength+10]);
	}	
      else if((strlen(&tline[0])>1)&&
	      (mystrncasecmp(tline,CatString3("*",MyName,"StartIconic"),
			   Clength+12)==0))
	{
	  StartIconic = 1;
	}	
      else if((strlen(&tline[0])>1)&&
	      (mystrncasecmp(tline,CatString3("*",MyName,"Rows"),
			   Clength+5)==0))
	{
	  sscanf(&tline[Clength+5],"%d",&Rows);
	}	
      else if((strlen(&tline[0])>1)&&
	      (mystrncasecmp(tline,CatString3("*",MyName,"Columns"),
			   Clength+8)==0))
	{
	  sscanf(&tline[Clength+8],"%d",&Columns);
	}	
      else if((strlen(&tline[0])>1)&&
	      (mystrncasecmp(tline,"HiBackColor",11)==0))
	{
	  if(Scr.d_depth > 1)
	    CopyString(&HiBack,&tline[11]);
	}	
      else if((strlen(&tline[0])>1)&&
	      (mystrncasecmp(tline,"HiForeColor",11)==0))
	{
	  if(Scr.d_depth > 1)
	    CopyString(&HiFore,&tline[11]);
	}	
      else if((strlen(&tline[0])>1)&&
	      (mystrncasecmp(tline,"StickyIcons",11)==0))
	{
	  StickyIcons = 1;
	}	
      else if((strlen(&tline[0])>1)&&
	      (mystrncasecmp(tline,"DeskTopSize",11)==0))
	{
	  sscanf(&tline[11],"%dx%d",&Scr.VxMax,&Scr.VyMax);
	  Scr.VxMax = Scr.VxMax*Scr.MyDisplayWidth - Scr.MyDisplayWidth;
	  Scr.VyMax = Scr.VyMax*Scr.MyDisplayHeight - Scr.MyDisplayHeight;
	}
      else if((strlen(&tline[0])>1)&&
	      (mystrncasecmp(tline,"DeskTopScale",12)==0))
	{
	  sscanf(&tline[12],"%d",&Scr.VScale);
	}
      tline = fgets(line,(sizeof line)-1,fd);
      orig_tline = tline;
    }
  return;
}
    GtkEGLSupport::GtkEGLSupport()
    {
	mNativeDisplay = getNativeDisplay();
        mGLDisplay = getGLDisplay();

		int dummy;

        if (XQueryExtension((Display*)mNativeDisplay, "RANDR", &dummy, &dummy, &dummy))
        {
            XRRScreenConfiguration *screenConfig;

            mRandr = true;
            screenConfig = XRRGetScreenInfo((Display*)mNativeDisplay, DefaultRootWindow((Display*)mNativeDisplay));

            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((Display*)mNativeDisplay, DefaultScreen(mNativeDisplay));
            mCurrentMode.first.second = DisplayHeight((Display*)mNativeDisplay, DefaultScreen(mNativeDisplay));
            mCurrentMode.second = 0;
            mOriginalMode = mCurrentMode;
            mVideoModes.push_back(mCurrentMode);
        }

		EGLConfig *glConfigs;
        int config, nConfigs = 0;

        glConfigs = chooseGLConfig(NULL, &nConfigs);

        for (config = 0; config < nConfigs; config++)
        {
            int caveat, samples;

            getGLConfigAttrib(glConfigs[config], EGL_CONFIG_CAVEAT, &caveat);

            if (caveat != EGL_SLOW_CONFIG)
            {
                getGLConfigAttrib(glConfigs[config], EGL_SAMPLES, &samples);
                mSampleLevels.push_back(StringConverter::toString(samples));
            }
        }

        free(glConfigs);

        removeDuplicates(mSampleLevels);
    }
/* Must be called in the gl thread */
GstGLWindow *
gst_gl_window_new (gulong external_gl_context)
{
    GstGLWindow *window = g_object_new (GST_GL_TYPE_WINDOW, NULL);
    GstGLWindowPrivate *priv = window->priv;

    EGLint config_attrib[] = {
        EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
        EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
        EGL_DEPTH_SIZE, 16,
        EGL_NONE
    };

    EGLint context_attrib[] = {
        EGL_CONTEXT_CLIENT_VERSION, 2,
        EGL_NONE
    };

    EGLint majorVersion;
    EGLint minorVersion;
    EGLint numConfigs;
    EGLConfig config;

    XSetWindowAttributes win_attr;
    XTextProperty text_property;
    XWMHints wm_hints;
    unsigned long mask;
    const gchar *title = "OpenGL renderer";
    Atom wm_atoms[3];

    static gint x = 0;
    static gint y = 0;

    setlocale (LC_NUMERIC, "C");

    priv->x_lock = g_mutex_new ();
    priv->cond_send_message = g_cond_new ();
    priv->running = TRUE;
    priv->visible = FALSE;
    priv->parent = 0;
    priv->allow_extra_expose_events = TRUE;

    g_mutex_lock (priv->x_lock);

    priv->device = XOpenDisplay (priv->display_name);

    XSynchronize (priv->device, FALSE);

    g_debug ("gl device id: %ld\n", (gulong) priv->device);

    priv->disp_send = XOpenDisplay (priv->display_name);

    XSynchronize (priv->disp_send, FALSE);

    g_debug ("gl display sender: %ld\n", (gulong) priv->disp_send);

    priv->screen_num = DefaultScreen (priv->device);
    priv->root = RootWindow (priv->device, priv->screen_num);
    priv->depth = DefaultDepth (priv->device, priv->screen_num);

    g_debug ("gl root id: %lud\n", (gulong) priv->root);

    priv->device_width = DisplayWidth (priv->device, priv->screen_num);
    priv->device_height = DisplayHeight (priv->device, priv->screen_num);

    priv->visual_info = g_new0 (XVisualInfo, 1);
    XMatchVisualInfo (priv->device, priv->screen_num, priv->depth, TrueColor,
                      priv->visual_info);

    win_attr.event_mask =
        StructureNotifyMask | ExposureMask | VisibilityChangeMask;
    win_attr.do_not_propagate_mask = NoEventMask;

    win_attr.background_pixmap = None;
    win_attr.background_pixel = 0;
    win_attr.border_pixel = 0;

    win_attr.colormap =
        XCreateColormap (priv->device, priv->root, priv->visual_info->visual,
                         AllocNone);

    mask = CWBackPixmap | CWBorderPixel | CWColormap | CWEventMask;

    x += 20;
    y += 20;

    priv->internal_win_id = XCreateWindow (priv->device, priv->root, x, y,
                                           1, 1, 0, priv->visual_info->depth, InputOutput,
                                           priv->visual_info->visual, mask, &win_attr);

    if (!priv->internal_win_id) {
        g_debug ("XCreateWindow failed\n");
        goto failure;
    }

    XSync (priv->device, FALSE);

    XSetWindowBackgroundPixmap (priv->device, priv->internal_win_id, None);

    g_debug ("gl window id: %lud\n", (gulong) priv->internal_win_id);

    g_debug ("gl window props: x:%d y:%d\n", x, y);

    wm_atoms[0] = XInternAtom (priv->device, "WM_DELETE_WINDOW", True);
    if (wm_atoms[0] == None)
        g_debug ("Cannot create WM_DELETE_WINDOW\n");

    wm_atoms[1] = XInternAtom (priv->device, "WM_GL_WINDOW", False);
    if (wm_atoms[1] == None)
        g_debug ("Cannot create WM_GL_WINDOW\n");

    wm_atoms[2] = XInternAtom (priv->device, "WM_QUIT_LOOP", False);
    if (wm_atoms[2] == None)
        g_debug ("Cannot create WM_QUIT_LOOP\n");

    XSetWMProtocols (priv->device, priv->internal_win_id, wm_atoms, 2);

    wm_hints.flags = StateHint;
    wm_hints.initial_state = NormalState;
    wm_hints.input = False;

    XStringListToTextProperty ((char **) &title, 1, &text_property);

    XSetWMProperties (priv->device, priv->internal_win_id, &text_property,
                      &text_property, 0, 0, NULL, &wm_hints, NULL);

    XFree (text_property.value);

    priv->gl_display = eglGetDisplay ((EGLNativeDisplayType) priv->device);

    if (eglInitialize (priv->gl_display, &majorVersion, &minorVersion))
        g_debug ("egl initialized: %d.%d\n", majorVersion, minorVersion);
    else {
        g_debug ("failed to initialize egl %ld, %s\n", (gulong) priv->gl_display,
                 EGLErrorString ());
        goto failure;
    }

    if (eglChooseConfig (priv->gl_display, config_attrib, &config, 1,
                         &numConfigs))
        g_debug ("config set: %ld, %ld\n", (gulong) config, (gulong) numConfigs);
    else {
        g_debug ("failed to set config %ld, %s\n", (gulong) priv->gl_display,
                 EGLErrorString ());
        goto failure;
    }

    priv->gl_surface =
        eglCreateWindowSurface (priv->gl_display, config,
                                (EGLNativeWindowType) priv->internal_win_id, NULL);
    if (priv->gl_surface != EGL_NO_SURFACE)
        g_debug ("surface created: %ld\n", (gulong) priv->gl_surface);
    else {
        g_debug ("failed to create surface %ld, %ld, %ld, %s\n",
                 (gulong) priv->gl_display, (gulong) priv->gl_surface,
                 (gulong) priv->gl_display, EGLErrorString ());
        goto failure;
    }

    g_debug ("about to create gl context\n");

    priv->gl_context =
        eglCreateContext (priv->gl_display, config,
                          (EGLContext) (guint) external_gl_context, context_attrib);

    if (priv->gl_context != EGL_NO_CONTEXT)
        g_debug ("gl context created: %ld\n", (gulong) priv->gl_context);
    else {
        g_debug ("failed to create glcontext %ld, %ld, %s\n",
                 (gulong) priv->gl_context, (gulong) priv->gl_display,
                 EGLErrorString ());
        goto failure;
    }

    if (!eglMakeCurrent (priv->gl_display, priv->gl_surface, priv->gl_surface,
                         priv->gl_context)) {
        g_debug ("failed to make opengl context current %ld, %s\n",
                 (gulong) priv->gl_display, EGLErrorString ());
        goto failure;
    }

    g_mutex_unlock (priv->x_lock);

    return window;

failure:
    g_mutex_unlock (priv->x_lock);
    g_object_unref (G_OBJECT (window));
    return NULL;
}
Exemple #13
0
void GLWindow::initWindow(const char* sWindowName,int* visualProperties)
	{
	/* Get a handle to the root window: */
	root=RootWindow(display,screen);
	
	/* Query for GLX extension: */
	int errorBase,eventBase;
	if(!glXQueryExtension(display,&errorBase,&eventBase))
		Misc::throwStdErr("GLWindow: GLX extension not supported");
	
	/* Find a suitable, OpenGL-capable visual: */
	static int defaultVisualProperties[]={GLX_RGBA,GLX_DEPTH_SIZE,16,GLX_DOUBLEBUFFER,None};
	XVisualInfo* visInfo=glXChooseVisual(display,screen,visualProperties!=0?visualProperties:defaultVisualProperties);
	if(visInfo==0)
		Misc::throwStdErr("GLWindow: No suitable visual found");
	
	/* Create an OpenGL context: */
	context=glXCreateContext(display,visInfo,0,GL_TRUE);
	if(context==0)
		Misc::throwStdErr("GLWindow: Unable to create GL context");
	
	/* Create an X colormap (visual might not be default): */
	colorMap=XCreateColormap(display,root,visInfo->visual,AllocNone);
	
	/* Create an X window with the selected visual: */
	XSetWindowAttributes swa;
	swa.colormap=colorMap;
	swa.border_pixel=0;
	if(fullscreen) // Create a fullscreen window
		{
		windowPos.origin[0]=0;
		windowPos.origin[1]=0;
		windowPos.size[0]=DisplayWidth(display,screen);
		windowPos.size[1]=DisplayHeight(display,screen);
		swa.override_redirect=True;
		}
	else
		swa.override_redirect=False;
	swa.event_mask=PointerMotionMask|EnterWindowMask|LeaveWindowMask|ButtonPressMask|ButtonReleaseMask|KeyPressMask|KeyReleaseMask|ExposureMask|StructureNotifyMask;
	unsigned long attributeMask=CWBorderPixel|CWColormap|CWOverrideRedirect|CWEventMask;
	window=XCreateWindow(display,root,
	                     windowPos.origin[0],windowPos.origin[1],windowPos.size[0],windowPos.size[1],
	                     0,visInfo->depth,InputOutput,visInfo->visual,attributeMask,&swa);
	XSetStandardProperties(display,window,sWindowName,sWindowName,None,0,0,0);
	
	/* Delete the visual information structure: */
	XFree(visInfo);
	
	/* Initiate window manager communication: */
	wmProtocolsAtom=XInternAtom(display,"WM_PROTOCOLS",False);
	wmDeleteWindowAtom=XInternAtom(display,"WM_DELETE_WINDOW",False);
	XSetWMProtocols(display,window,&wmDeleteWindowAtom,1);
	
	/* Display the window on the screen: */
	XMapWindow(display,window);
	
	if(fullscreen)
		{
		/* Grab pointer and keyboard: */
		XGrabPointer(display,window,True,0,GrabModeAsync,GrabModeAsync,None,None,CurrentTime);
		XGrabKeyboard(display,window,True,GrabModeAsync,GrabModeAsync,CurrentTime);
		}
	
	/* Gobble up the initial rush of X events regarding window creation: */
	#if 0
	XEvent event;
	while(XCheckWindowEvent(display,window,StructureNotifyMask,&event))
		{
		switch(event.type)
			{
			case ConfigureNotify:
				/* Retrieve the final window size: */
				windowWidth=event.xconfigure.width;
				windowHeight=event.xconfigure.height;
				break;
			}
		}
	#else
	while(true)
		{
		/* Look at the next event: */
		XEvent event;
		XPeekEvent(display,&event);
		if(event.type==Expose)
			break; // Leave this event for the caller to process
		
		/* Process the next event: */
		XNextEvent(display,&event);
		switch(event.type)
			{
			case ConfigureNotify:
				/* Retrieve the final window position and size: */
				windowPos.origin[0]=event.xconfigure.x;
				windowPos.origin[1]=event.xconfigure.y;
				windowPos.size[0]=event.xconfigure.width;
				windowPos.size[1]=event.xconfigure.height;
				break;
			}
		}
	#endif
	}
Exemple #14
0
void XRRConfiguration::Update()
{
    if (SConfig::GetInstance().m_LocalCoreStartupParameter.strFullscreenResolution == "Auto")
        return;

    if (!bValid)
        return;

    if (outputInfo)
    {
        XRRFreeOutputInfo(outputInfo);
        outputInfo = nullptr;
    }
    if (crtcInfo)
    {
        XRRFreeCrtcInfo(crtcInfo);
        crtcInfo = nullptr;
    }
    fullMode = 0;

    // Get the resolution setings for fullscreen mode
    unsigned int fullWidth, fullHeight;
    char *output_name = nullptr;
    if (SConfig::GetInstance().m_LocalCoreStartupParameter.strFullscreenResolution.find(':') ==
            std::string::npos)
    {
        fullWidth = fb_width;
        fullHeight = fb_height;
    }
    else
        sscanf(SConfig::GetInstance().m_LocalCoreStartupParameter.strFullscreenResolution.c_str(),
               "%m[^:]: %ux%u", &output_name, &fullWidth, &fullHeight);

    for (int i = 0; i < screenResources->noutput; i++)
    {
        XRROutputInfo *output_info = XRRGetOutputInfo(dpy, screenResources, screenResources->outputs[i]);
        if (output_info && output_info->crtc && output_info->connection == RR_Connected)
        {
            XRRCrtcInfo *crtc_info = XRRGetCrtcInfo(dpy, screenResources, output_info->crtc);
            if (crtc_info)
            {
                if (!output_name || !strcmp(output_name, output_info->name))
                {
                    // Use the first output for the default setting.
                    if (!output_name)
                    {
                        output_name = strdup(output_info->name);
                        SConfig::GetInstance().m_LocalCoreStartupParameter.strFullscreenResolution =
                            StringFromFormat("%s: %ux%u", output_info->name, fullWidth, fullHeight);
                    }
                    outputInfo = output_info;
                    crtcInfo = crtc_info;
                    for (int j = 0; j < output_info->nmode && fullMode == 0; j++)
                    {
                        for (int k = 0; k < screenResources->nmode && fullMode == 0; k++)
                        {
                            if (output_info->modes[j] == screenResources->modes[k].id)
                            {
                                if (fullWidth == screenResources->modes[k].width &&
                                        fullHeight == screenResources->modes[k].height)
                                {
                                    fullMode = screenResources->modes[k].id;
                                    if (crtcInfo->x + (int)screenResources->modes[k].width > fs_fb_width)
                                        fs_fb_width = crtcInfo->x + screenResources->modes[k].width;
                                    if (crtcInfo->y + (int)screenResources->modes[k].height > fs_fb_height)
                                        fs_fb_height = crtcInfo->y + screenResources->modes[k].height;
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (crtc_info->x + (int)crtc_info->width > fs_fb_width)
                        fs_fb_width = crtc_info->x + crtc_info->width;
                    if (crtc_info->y + (int)crtc_info->height > fs_fb_height)
                        fs_fb_height = crtc_info->y + crtc_info->height;
                }
            }
            if (crtc_info && crtcInfo != crtc_info)
                XRRFreeCrtcInfo(crtc_info);
        }
        if (output_info && outputInfo != output_info)
            XRRFreeOutputInfo(output_info);
    }
    fs_fb_width_mm = fs_fb_width * DisplayHeightMM(dpy, screen) / DisplayHeight(dpy, screen);
    fs_fb_height_mm = fs_fb_height * DisplayHeightMM(dpy, screen) / DisplayHeight(dpy, screen);

    if (output_name)
        free(output_name);

    if (outputInfo && crtcInfo && fullMode)
    {
        INFO_LOG(VIDEO, "Fullscreen Resolution %dx%d", fullWidth, fullHeight);
    }
    else
    {
        ERROR_LOG(VIDEO, "Failed to obtain fullscreen size.\n"
                  "Using current desktop resolution for fullscreen.");
    }
}
Exemple #15
0
/* MUST BE CALLED BEFORE load_prefs                     */
void init_globals()
{
/*  for DEBUG */
/* anim_data *test_ad; */
  
  disp_width = DisplayWidth(XtDisplay(shell),
            XScreenNumberOfScreen(XtScreen(shell)));
  disp_height = DisplayHeight(XtDisplay(shell),
            XScreenNumberOfScreen(XtScreen(shell)));
  fprintf (stderr,"display screen width=%d, display screen height=%d\n", 
            disp_width, disp_height);    
            
/*  calculate initial position of product display screens and TAB screens */
/*  width & height are the size of the product display portal  */
/*                 in each product display screen */
/*  115 is the total width of the sidebar and window margins */
/*                 in each product display screen */
  spacexy = 10;
 
  screen1x = 20;
  screen1y = screen2y = 45;
  screen2x = disp_width - spacexy - width - 115;
  
  screen3x = screen3y = 200;
 
  tab1x = 50;
  tab1y = tab2y = disp_height - tabheight - spacexy;
  tab2x = disp_width - tabwidth - spacexy;

  tab3x = tab3y = 400;
    
  main_screen = screen_1 = screen_2 = NULL;
  screen_3 = NULL;
  
  scroll1_xpos = scroll1_ypos = scroll2_xpos = scroll2_ypos = 0;
  scroll3_xpos = scroll3_ypos = 0;
  
  selected_screen = SCREEN_1;

  map_flag1 = az_line_flag1 = range_ring_flag1 = FALSE;
  map_flag2 = az_line_flag2 = range_ring_flag2 = FALSE;  
  map_flag3 = az_line_flag3 = range_ring_flag3 = FALSE;


/*  defined in prefs.c */
/* #define ROAD_NONE 0 */
/* #define ROAD_MAJOR 12 */
/* #define ROAD_MORE 31  // NOTE: only upto 15 in CONUS maps */
  road_d = 31;    /*   */
/*  defined in prefs.c */
/* #define RAIL_NONE 70 */
/* #define RAIL_MAJOR 75 // NOTE: only upto 72 in CONUS maps                 */
  rail_d = 70;
/*  settings not yet defined   */
  admin_d = 0;   /*  eliminates all ( */

  co_d = TRUE;


  anim1.loop_size = anim2.loop_size = anim3.loop_size = 0;
  anim1.anim_type = anim2.anim_type = anim3.anim_type = 1;
  anim1.reset_ts_flag = anim2.reset_ts_flag = anim3.reset_ts_flag = ANIM_NO_INIT;

  anim1.reset_es_flag = anim2.reset_es_flag = anim3.reset_es_flag = ANIM_NO_INIT;
  anim1.reset_au_flag = anim2.reset_au_flag = anim3.reset_au_flag = ANIM_NO_INIT;

  anim1.lower_vol_num = anim2.lower_vol_num = anim3.lower_vol_num = -1;
  anim1.first_index_num = anim2.first_index_num = anim3.first_index_num = -1;
  anim1.last_index_num = anim2.last_index_num = anim3.last_index_num = -1;

  anim1.lower_vol_time = anim2.lower_vol_time = anim3.lower_vol_time = -1;
  anim1.upper_vol_time = anim2.upper_vol_time = anim3.upper_vol_time = -1;

  anim1.es_first_index = anim2.es_first_index = anim2.es_first_index = -1;


/*  PERSISTENT GLOBAL STRINGS */
    hide_xmstr = XmStringCreateLtoR("Hide Center Location Icon", XmFONTLIST_DEFAULT_TAG);
    show_xmstr = XmStringCreateLtoR("Show Center Location Icon", XmFONTLIST_DEFAULT_TAG);

/* DEBUG */
/* test_ad = &anim1; */
/* fprintf(stderr,"DEBUG init_globals, anim type is %d, first index num is %d\n", */
/*         test_ad->anim_type, test_ad->first_index_num); */

  sd1 = malloc(sizeof(screen_data));
  setup_default_screen_data_values(sd1);
  sd2 = malloc(sizeof(screen_data));
  setup_default_screen_data_values(sd2);
  sd3 = malloc(sizeof(screen_data));
  setup_default_screen_data_values(sd3);

  sd = sd1;
  
  disk_last_filename[0] = '\0';  
  
  
  /* DEFAULT SETTINGS, NOT INITITALIZATIONS */
  linked_flag = FALSE;
  prod_filter = FILTER_PROD_ID;
  area_label = AREA_LBL_NONE;
  area_symbol = AREA_SYM_POINT;
  area_line_type = AREA_LINE_SOLID;
  include_points_flag = FALSE;
  overlay_flag = verbose_flag = FALSE;
  /*CVG 9.0 */
  large_screen_flag = large_image_flag = FALSE;
  
  select_all_flag = TRUE; 
  ctr_loc_icon_visible_flag = FALSE;
 
}
Exemple #16
0
void sdl_monitor_info::refresh()
{
	#if (SDLMAME_SDL2)
	SDL_DisplayMode dmode;

	#if defined(SDLMAME_WIN32)
	SDL_GetDesktopDisplayMode(m_handle, &dmode);
	#else
	SDL_GetCurrentDisplayMode(m_handle, &dmode);
	#endif
	SDL_Rect dimensions;
	SDL_GetDisplayBounds(m_handle, &dimensions);

	m_pos_size = SDL_Rect_to_osd_rect(dimensions);
	m_usuable_pos_size = SDL_Rect_to_osd_rect(dimensions);
	m_is_primary = (m_handle == 0);

	#else
	#if defined(SDLMAME_WIN32)  // Win32 version
	MONITORINFOEX info;
	info.cbSize = sizeof(info);
	GetMonitorInfo((HMONITOR)m_handle, (LPMONITORINFO)&info);
	m_pos_size = RECT_to_osd_rect(info.rcMonitor);
	m_usuable_pos_size = RECT_to_osd_rect(info.rcWork);
	m_is_primary = ((info.dwFlags & MONITORINFOF_PRIMARY) != 0);
	char *temp = utf8_from_wstring(info.szDevice);
	strncpy(m_name, temp, ARRAY_LENGTH(m_name) - 1);
	osd_free(temp);
	#elif defined(SDLMAME_MACOSX)   // Mac OS X Core Imaging version
	CGDirectDisplayID primary;
	CGRect dbounds;

	// get the main display
	primary = CGMainDisplayID();
	dbounds = CGDisplayBounds(primary);

	m_is_primary = (m_handle == 0);
	m_pos_size = osd_rect(0, 0, dbounds.size.width - dbounds.origin.x, dbounds.size.height - dbounds.origin.y);
	m_usuable_pos_size = m_pos_size;
	strncpy(m_name, "Mac OS X display", ARRAY_LENGTH(m_name) - 1);
	#elif defined(SDLMAME_X11) || defined(SDLMAME_NO_X11)       // X11 version
	{
		#if defined(SDLMAME_X11)
		// X11 version
		int screen;
		SDL_SysWMinfo info;
		SDL_VERSION(&info.version);

		if ( SDL_GetWMInfo(&info) && (info.subsystem == SDL_SYSWM_X11) )
		{
			screen = DefaultScreen(info.info.x11.display);
			SDL_VideoDriverName(m_name, ARRAY_LENGTH(m_name) - 1);
			m_pos_size = osd_rect(0, 0,
					DisplayWidth(info.info.x11.display, screen),
					DisplayHeight(info.info.x11.display, screen));

			/* FIXME: If Xinerame is used we should compile a list of monitors
			 * like we do for other targets and ignore SDL.
			 */
			if ((XineramaIsActive(info.info.x11.display)) && video_config.restrictonemonitor)
			{
				XineramaScreenInfo *xineinfo;
				int numscreens;

				xineinfo = XineramaQueryScreens(info.info.x11.display, &numscreens);

				m_pos_size = osd_rect(0, 0, xineinfo[0].width, xineinfo[0].height);

				XFree(xineinfo);
			}
			m_usuable_pos_size = m_pos_size;
			m_is_primary = (m_handle == 0);
		}
		else
		#endif // defined(SDLMAME_X11)
		{
			static int first_call=0;
			static int cw = 0, ch = 0;

			SDL_VideoDriverName(m_name, ARRAY_LENGTH(m_name) - 1);
			if (first_call==0)
			{
				const char *dimstr = osd_getenv(SDLENV_DESKTOPDIM);
				const SDL_VideoInfo *sdl_vi;

				sdl_vi = SDL_GetVideoInfo();
				#if (SDL_VERSION_ATLEAST(1,2,10))
				cw = sdl_vi->current_w;
				ch = sdl_vi->current_h;
				#endif
				first_call=1;
				if ((cw==0) || (ch==0))
				{
					if (dimstr != NULL)
					{
						sscanf(dimstr, "%dx%d", &cw, &ch);
					}
					if ((cw==0) || (ch==0))
					{
						osd_printf_warning("WARNING: SDL_GetVideoInfo() for driver <%s> is broken.\n", m_name);
						osd_printf_warning("         You should set SDLMAME_DESKTOPDIM to your desktop size.\n");
						osd_printf_warning("            e.g. export SDLMAME_DESKTOPDIM=800x600\n");
						osd_printf_warning("         Assuming 1024x768 now!\n");
						cw=1024;
						ch=768;
					}
				}
			}
			m_pos_size = osd_rect(0, 0, cw, ch);
			m_usuable_pos_size = m_pos_size;
			m_is_primary = (m_handle == 0);
		}
	}
	#elif defined(SDLMAME_OS2)      // OS2 version
	m_pos_size = osd_rect(0, 0,
			WinQuerySysValue( HWND_DESKTOP, SV_CXSCREEN ),
			WinQuerySysValue( HWND_DESKTOP, SV_CYSCREEN ) );
	m_usuable_pos_size = m_pos_size;
	m_is_primary = (m_handle == 0);
	strncpy(m_name, "OS/2 display", ARRAY_LENGTH(m_name) - 1);
	#else
	#error Unknown SDLMAME_xx OS type!
	#endif

	{
		static int info_shown=0;
		if (!info_shown)
		{
			osd_printf_verbose("SDL Device Driver     : %s\n", m_name);
			osd_printf_verbose("SDL Monitor Dimensions: %d x %d\n", m_pos_size.width(), m_pos_size.height());
			info_shown = 1;
		}
	}
	#endif //  (SDLMAME_SDL2)
}
void compute(int X_RESN, int Y_RESN)
{
        Window          win;                            /* initialization for a window */
        unsigned
        int             width, height,                  /* window size */
                        x, y,                           /* window position */
                        border_width,                   /*border width in pixels */
                        display_width, display_height,  /* size of screen */
                        screen;                         /* which screen */

        char            *window_name = "Julia Set", *display_name = NULL;
        GC              gc;
        unsigned
        long            valuemask = 0;
        XGCValues       values;
        Display         *display;
        XSizeHints      size_hints;
        Pixmap          bitmap;
        XPoint          points[800];
        FILE            *fp, *fopen ();
        char            str[100];
        Status          rc;
        int             tmp=1;
        XSetWindowAttributes attr[1];
       
       if ( DEBUG  )
         printf("3. Finished Declaring X-Window parameters\n ");

       /* Important variables */
        int i, j, k;
        int *TheK = (int *)malloc( (X_RESN*Y_RESN)*sizeof(int) );

       
        /* connect to Xserver */
        if ( DEBUG  )
         printf("4. Connecting to X-Server\n ");
	 
        if (  (display = XOpenDisplay (display_name)) == NULL ) {
           fprintf (stderr, "drawon: cannot connect to X server %s\n",
                                XDisplayName (display_name) );
          exit (-1);
        }
        
        /* get screen size */

        screen = DefaultScreen (display);
        display_width = DisplayWidth (display, screen);
        display_height = DisplayHeight (display, screen);

        /* set window size */

        width = X_RESN;
        height = Y_RESN;

        /* set window position */

        x = 0;
        y = 0;

        /* create opaque window */
        if ( DEBUG  )
         printf("5. Creating an X-Window\n");
	  
        border_width = 4;
        win = XCreateSimpleWindow (display, RootWindow (display, screen),
                                x, y, width, height, border_width,
                                BlackPixel (display, screen), WhitePixel (display, screen));

        size_hints.flags = USPosition|USSize;
        size_hints.x = x;
        size_hints.y = y;
        size_hints.width = width;
        size_hints.height = height;
        size_hints.min_width = 300;
        size_hints.min_height = 300;

        XSetNormalHints (display, win, &size_hints);
        XStoreName(display, win, window_name);

        /* create graphics context */

        gc = XCreateGC (display, win, valuemask, &values);

        

         /* allocate the set of colors we will want to use for the drawing. */
        if ( DEBUG  )
         printf("6. Setting Display Attributes\n ");

        XSetBackground (display, gc, WhitePixel (display, screen));
        XSetForeground (display, gc, BlackPixel (display, screen));
        XSetLineAttributes (display, gc, 1, LineSolid, CapRound, JoinRound);

        

        attr[0].backing_store = Always;
        attr[0].backing_planes = 1;
        attr[0].backing_pixel = BlackPixel(display, screen);

        XChangeWindowAttributes(display, win, CWBackingStore | CWBackingPlanes | CWBackingPixel, attr);

        XMapWindow (display, win);
        XSync(display, 0);

        

        int white, black;
        int generic,process;
        int minc, maxc;

        if ( DEBUG  )
         printf("7. Computing the Numerical Value of Black and White Pixel\n");

        white = WhitePixel (display, screen);       /* color value for white */
        black = BlackPixel (display, screen);       /* color value for black */
        
        minc = (white > black) ? black : white;
        maxc = (white > black) ? white : black;
        
	/* Loop around each point and determine the color*/
	
	if ( DEBUG  )
         printf("8. Entering the Iterate function to compute the Color at each point\n");
	 
	iterate(maxc, minc, X_RESN, Y_RESN,TheK);
        
	if (DEBUG )
	{
	  printf("10. Value for white = %d\n",white);
	  printf("11. Value for black = %d\n",black);
	}  
	
    
    	clock_t t1, t2;
        t1=clock();
           
	if ( DEBUG  )
         printf("12. Loop Around each Pixel, Set the Color and Plot the Point\n ");
    
       for(i = 0; i < Y_RESN ; i++)
        {
                for(j=0; j < X_RESN; j++)
                 {
                        XSetForeground(display, gc, TheK[i*Y_RESN+j]  );
                        XDrawPoint (display, win, gc, j, i);
                 }

        }
	t2=clock();   
       
        if ( DEBUG  )
         printf("13. End of Code\n ");
       
       
	printf("Total Time Taken for Plotting= %f Seconds\n",((double)( t2 - t1 )/ (double) CLOCKS_PER_SEC ) ); 

        sleep(5);
        XFlush (display);
        
	if ( DEBUG  )
         printf("14. Free the Assigned Memory\n");
	
	free(TheK);

}
Exemple #18
0
/*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ main() $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*/
int
main(int argc, char *argv[])
{
    int             glyph_height,
                    max_vertical_lines;
    char            window_title[100],
                    work_dir[MAX_PATH_LENGTH];
    static String   fallback_res[] =
    {
        "*mwmDecorations : 42",
        "*mwmFunctions : 12",
        ".view_dc.form*background : NavajoWhite2",
        ".view_dc.form.buttonbox2.searchbox*background : NavajoWhite1",
        ".view_dc.form.dc_textSW.dc_text.background : NavajoWhite1",
        ".view_dc.form.buttonbox*background : PaleVioletRed2",
        ".view_dc.form.buttonbox*foreground : Black",
        ".view_dc.form.buttonbox*highlightColor : Black",
        NULL
    };
    Widget          form_w,
                    button_w,
                    buttonbox_w,
                    h_separator_w;
    XmFontListEntry entry;
    XFontStruct     *font_struct;
    XmFontList      fontlist;
    XmFontType      dummy;
    Arg             args[MAXARGS];
    Cardinal        argcount;
    uid_t           euid, /* Effective user ID. */
                    ruid; /* Real user ID. */

    CHECK_FOR_VERSION(argc, argv);

    /* Initialise global values. */
    p_work_dir = work_dir;
    init_view_dc(&argc, argv);

    /*
     * SSH uses wants to look at .Xauthority and with setuid flag
     * set we cannot do that. So when we initialize X lets temporaly
     * disable it. After XtAppInitialize() we set it back.
     */
    euid = geteuid();
    ruid = getuid();
    if (euid != ruid)
    {
        if (seteuid(ruid) == -1)
        {
            (void)fprintf(stderr, "Failed to seteuid() to %d : %s\n",
                          ruid, strerror(errno));
        }
    }

    (void)strcpy(window_title, "DIR_CONFIG ");
    (void)strcat(window_title, p_title);
    argcount = 0;
    XtSetArg(args[argcount], XmNtitle, window_title);
    argcount++;
    appshell = XtAppInitialize(&app, "AFD", NULL, 0,
                               &argc, argv, fallback_res, args, argcount);
    disable_drag_drop(appshell);

    if (euid != ruid)
    {
        if (seteuid(euid) == -1)
        {
            (void)fprintf(stderr, "Failed to seteuid() to %d : %s\n",
                          euid, strerror(errno));
        }
    }

    /* Get display pointer. */
    if ((display = XtDisplay(appshell)) == NULL)
    {
        (void)fprintf(stderr,
                      "ERROR   : Could not open Display : %s (%s %d)\n",
                      strerror(errno), __FILE__, __LINE__);
        exit(INCORRECT);
    }

#ifdef HAVE_XPM
    /* Setup AFD logo as icon. */
    setup_icon(display, appshell);
#endif

    /* Create managing widget. */
    form_w = XmCreateForm(appshell, "form", NULL, 0);

    if ((entry = XmFontListEntryLoad(XtDisplay(form_w), font_name,
                                     XmFONT_IS_FONT, "TAG1")) == NULL)
    {
        if ((entry = XmFontListEntryLoad(XtDisplay(form_w), "fixed",
                                         XmFONT_IS_FONT, "TAG1")) == NULL)
        {
            (void)fprintf(stderr,
                          "Failed to load font with XmFontListEntryLoad() : %s (%s %d)\n",
                          strerror(errno), __FILE__, __LINE__);
            exit(INCORRECT);
        }
    }
    font_struct = (XFontStruct *)XmFontListEntryGetFont(entry, &dummy);
    glyph_height = font_struct->ascent + font_struct->descent;
    fontlist = XmFontListAppendEntry(NULL, entry);
    XmFontListEntryFree(&entry);

    /* Calculate the maximum lines to show. */
    max_vertical_lines = (8 * (DisplayHeight(display, DefaultScreen(display)) /
                               glyph_height)) / 10;
    if (max_y > max_vertical_lines)
    {
        max_y = max_vertical_lines;
    }

    argcount = 0;
    XtSetArg(args[argcount], XmNleftAttachment,   XmATTACH_FORM);
    argcount++;
    XtSetArg(args[argcount], XmNrightAttachment,  XmATTACH_FORM);
    argcount++;
    XtSetArg(args[argcount], XmNbottomAttachment, XmATTACH_FORM);
    argcount++;
    XtSetArg(args[argcount], XmNfractionBase,     21);
    argcount++;
    buttonbox_w = XmCreateForm(form_w, "buttonbox", args, argcount);

    /* Create a horizontal separator. */
    argcount = 0;
    XtSetArg(args[argcount], XmNorientation,           XmHORIZONTAL);
    argcount++;
    XtSetArg(args[argcount], XmNbottomAttachment,      XmATTACH_WIDGET);
    argcount++;
    XtSetArg(args[argcount], XmNbottomWidget,          buttonbox_w);
    argcount++;
    XtSetArg(args[argcount], XmNleftAttachment,        XmATTACH_FORM);
    argcount++;
    XtSetArg(args[argcount], XmNrightAttachment,       XmATTACH_FORM);
    argcount++;
    h_separator_w = XmCreateSeparator(form_w, "h_separator", args, argcount);
    XtManageChild(h_separator_w);

    button_w = XtVaCreateManagedWidget("Close",
                                       xmPushButtonWidgetClass, buttonbox_w,
                                       XmNfontList,         fontlist,
                                       XmNtopAttachment,    XmATTACH_POSITION,
                                       XmNtopPosition,      2,
                                       XmNbottomAttachment, XmATTACH_POSITION,
                                       XmNbottomPosition,   19,
                                       XmNleftAttachment,   XmATTACH_POSITION,
                                       XmNleftPosition,     1,
                                       XmNrightAttachment,  XmATTACH_POSITION,
                                       XmNrightPosition,    20,
                                       NULL);
    XtAddCallback(button_w, XmNactivateCallback,
                  (XtCallbackProc)close_button, (XtPointer)0);
    XtManageChild(buttonbox_w);

    /* Create DIR_CONFIG data as a ScrolledText window. */
    argcount = 0;
    XtSetArg(args[argcount], XmNfontList,               fontlist);
    argcount++;
    XtSetArg(args[argcount], XmNeditable,               False);
    argcount++;
    XtSetArg(args[argcount], XmNeditMode,               XmMULTI_LINE_EDIT);
    argcount++;
    XtSetArg(args[argcount], XmNwordWrap,               False);
    argcount++;
    XtSetArg(args[argcount], XmNscrollHorizontal,       False);
    argcount++;
    XtSetArg(args[argcount], XmNcursorPositionVisible,  False);
    argcount++;
    XtSetArg(args[argcount], XmNautoShowCursorPosition, False);
    argcount++;
    XtSetArg(args[argcount], XmNleftAttachment,         XmATTACH_FORM);
    argcount++;
    XtSetArg(args[argcount], XmNleftOffset,             3);
    argcount++;
    XtSetArg(args[argcount], XmNrightAttachment,        XmATTACH_FORM);
    argcount++;
    XtSetArg(args[argcount], XmNrightOffset,            3);
    argcount++;
    XtSetArg(args[argcount], XmNbottomAttachment,       XmATTACH_WIDGET);
    argcount++;
    XtSetArg(args[argcount], XmNbottomWidget,           h_separator_w);
    argcount++;
    XtSetArg(args[argcount], XmNbottomOffset,           3);
    argcount++;
    XtSetArg(args[argcount], XmNrows,                   max_y);
    argcount++;
    XtSetArg(args[argcount], XmNcolumns,                max_x);
    argcount++;
    XtSetArg(args[argcount], XmNvalue,                  view_buffer);
    argcount++;
    text_w = XmCreateScrolledText(form_w, "dc_text", args, argcount);
    XtManageChild(text_w);

    /* Create a horizontal separator. */
    argcount = 0;
    XtSetArg(args[argcount], XmNorientation,           XmHORIZONTAL);
    argcount++;
    XtSetArg(args[argcount], XmNbottomAttachment,      XmATTACH_WIDGET);
    argcount++;
    XtSetArg(args[argcount], XmNbottomWidget,          text_w);
    argcount++;
    XtSetArg(args[argcount], XmNleftAttachment,        XmATTACH_FORM);
    argcount++;
    XtSetArg(args[argcount], XmNrightAttachment,       XmATTACH_FORM);
    argcount++;
    h_separator_w = XmCreateSeparator(form_w, "h_separator", args, argcount);
    XtManageChild(h_separator_w);

    argcount = 0;
    XtSetArg(args[argcount], XmNtopAttachment,          XmATTACH_FORM);
    argcount++;
    XtSetArg(args[argcount], XmNtopOffset,              1);
    argcount++;
    XtSetArg(args[argcount], XmNleftAttachment,         XmATTACH_FORM);
    argcount++;
    XtSetArg(args[argcount], XmNrightAttachment,        XmATTACH_FORM);
    argcount++;
    XtSetArg(args[argcount], XmNbottomAttachment,       XmATTACH_WIDGET);
    argcount++;
    XtSetArg(args[argcount], XmNbottomWidget,           h_separator_w);
    argcount++;
    XtSetArg(args[argcount], XmNbottomOffset,           1);
    argcount++;
    XtSetArg(args[argcount], XmNfractionBase,           31);
    argcount++;
    buttonbox_w = XmCreateForm(form_w, "buttonbox2", args, argcount);

    searchbox_w = XtVaCreateWidget("searchbox",
                                   xmTextWidgetClass,        buttonbox_w,
                                   XmNtopAttachment,         XmATTACH_POSITION,
                                   XmNtopPosition,           5,
                                   XmNbottomAttachment,      XmATTACH_POSITION,
                                   XmNbottomPosition,        26,
                                   XmNleftAttachment,        XmATTACH_POSITION,
                                   XmNleftPosition,          1,
                                   XmNrightAttachment,       XmATTACH_POSITION,
                                   XmNrightPosition,         20,
                                   XmNfontList,              fontlist,
                                   XmNrows,                  1,
                                   XmNeditable,              True,
                                   XmNcursorPositionVisible, True,
                                   XmNmarginHeight,          1,
                                   XmNmarginWidth,           1,
                                   XmNshadowThickness,       1,
                                   XmNhighlightThickness,    0,
                                   NULL);
    XtManageChild(searchbox_w);
    button_w = XtVaCreateManagedWidget("Search",
                                       xmPushButtonWidgetClass, buttonbox_w,
                                       XmNleftAttachment,       XmATTACH_POSITION,
                                       XmNleftPosition,         22,
                                       XmNrightAttachment,      XmATTACH_POSITION,
                                       XmNrightPosition,        28,
                                       XmNtopAttachment,        XmATTACH_FORM,
                                       XmNfontList,             fontlist,
                                       NULL);
    XtAddCallback(button_w, XmNactivateCallback,
                  (XtCallbackProc)search_button, (XtPointer)0);
    XtManageChild(buttonbox_w);
    XtManageChild(form_w);

    /* Free font list. */
    XmFontListFree(fontlist);

#ifdef WITH_EDITRES
    XtAddEventHandler(appshell, (EventMask)0, True,
                      _XEditResCheckMessages, NULL);
#endif

    /* Realize all widgets. */
    XtRealizeWidget(appshell);

    /* We want the keyboard focus on the Close button. */
    XmProcessTraversal(button_w, XmTRAVERSE_CURRENT);

    /* Write window ID, so afd_ctrl can set focus if it is called again. */
    write_window_id(XtWindow(appshell), getpid(), VIEW_DC);

    /* Start the main event-handling loop. */
    XtAppMainLoop(app);

    exit(SUCCESS);
}
Exemple #19
0
void xopenw ( char win_name[], int win_index, float xsize,
              float ysize, int *ixsize, int *iysize, int *iret )
/************************************************************************
 * xopenw								*
 *									*
 * This subroutine opens one xw window and sets the initial		*
 * graphics context along with basic window attributes.			*
 *									*
 * xopenw ( win_name, win_index, xsize, ysize, ixsize, iysize, iret )	*
 *									*
 * Input parameters:							*
 *	win_name[]	char		window name			*
 *	win_index	int		window index			*
 *	xsize		float		Right edge of window		*
 *	ysize		float		Bottom edge of window		*
 *									*
 * Output parameters:							*
 *	*ixsize		int		Right edge of window		*
 *	*iysize		int		Bottom edge of window		*
 *	*iret		int		Return code			*
 *					G_NORMAL = normal return	*
 **									*
 * Log:									*
 * A. Hardy/GSC          2/01   Copied from the XW driver and           *
 *                              removed size limitations                *
 ***********************************************************************/
{
    int			dhght, dwdth, gemscreen, xpos, ypos, ier;
    unsigned int	xwdth, xhght, xbord, xdpth;
    char		gemname [WNAME_LEN];

    Cursor		curs;
    Window		gwin;
    GC			gemgc;

    XGCValues		 values;
    XSizeHints		 gemhint;
    XSetWindowAttributes gemxswa;
    XColor		 cred;

    Window_str      	*cwin;
    winloop_t		*cloop;
    /*---------------------------------------------------------------------*/

    *iret = G_NORMAL;

    current_window = win_index;

    cwin  = &(gemwindow[current_window]);
    cloop = &(cwin->loop[cwin->curr_loop]);

    strcpy(cwin->name, win_name);

    strcpy(gemname, win_name);

    gemscreen = DefaultScreen( (XtPointer)gemdisplay );

    /*
     * Determine window height and width.
     */

    dwdth = DisplayWidth( (XtPointer)gemdisplay, gemscreen );
    dhght = DisplayHeight( (XtPointer)gemdisplay, gemscreen );

    if ( G_ABS ( xsize - RMISSD ) < RDIFFD )
        gemhint.width = 0.7 * (float) dwdth ;
    else if ( ( xsize > 0.0 ) && ( xsize <= 1.0 ) )
        gemhint.width = (float) dwdth * xsize ;
    else if ( xsize < 100.0 ) gemhint.width = 100 ;
    else gemhint.width = (int) xsize ;

    if ( G_ABS ( ysize - RMISSD ) < RDIFFD )
        gemhint.height = 0.7 * (float) dhght ;
    else if ( ( ysize > 0.0 ) && ( ysize <= 1.0 ) )
        gemhint.height = (float) dhght * ysize ;
    else if ( ysize < 100.0 ) gemhint.height = 100 ;
    else gemhint.height = (int) ysize ;

    if ( gemhint.width  < 100 ) gemhint.width  = 100 ;
    if ( gemhint.height < 100 ) gemhint.height = 100 ;

    /*
     * Determine window location.
     */

    gemhint.x = dwdth - ( gemhint.width ) - ( current_window * 30 ) - 20;
    if ( gemhint.x < 0 ) gemhint.x = 0;

    gemhint.y = ( current_window * 30 );

    gemhint.flags  = USPosition | USSize;

    /*
     * Create the window and set standard properties and attributes.
     */

    gwin = XCreateSimpleWindow( gemdisplay, root, gemhint.x, gemhint.y,
                                gemhint.width, gemhint.height, 5,
                                WhitePixel ( (XtPointer)gemdisplay, gemscreen ),
                                BlackPixel ( (XtPointer)gemdisplay, gemscreen ) );

    cwin->window = gwin;

    XSetStandardProperties( gemdisplay, gwin, gemname, gemname, None,
                            NULL, 0, &gemhint );

    gemxswa.bit_gravity = CenterGravity;

    XChangeWindowAttributes (gemdisplay, gwin, (CWBitGravity), &gemxswa );

    /*
     * Get the geometry and window size information.
     */
    XGetGeometry( gemdisplay, gwin, &root, &xpos,
                  &ypos, &xwdth, &xhght, &xbord, &xdpth );

    cwin->width  = xwdth;
    cwin->height = xhght;
    cwin->depth  = xdpth;

    /*
     * Create graphics contexts.
     */
    gemgc = XCreateGC( gemdisplay, gwin, 0, 0 );

    /*
     * Turn of NoExpose and GraphicsExpose events.  They
     * don't seem to be needed and were causing many events
     * to seen in xxevent().
     */
    values.graphics_exposures = False;
    XChangeGC( gemdisplay, gemgc, GCGraphicsExposures, &values);

    cwin->gc = gemgc;

    /*
     * Set backgound colors.
     */
    XSetBackground( gemdisplay, gemgc,
                    BlackPixel ( (XtPointer)gemdisplay, gemscreen ) ) ;

    /*
     * Set fill rule.
     */
    XSetFillRule ( gemdisplay, gemgc, EvenOddRule );

    /*
     * Create one pixmap.
     */
    cwin->pxms[cwin->curr_loop][0] =
        XCreatePixmap(gemdisplay, root, xwdth, xhght, xdpth);

    cwin->curpxm[cwin->curr_loop] = 0;
    cloop->pxm_wdth	= xwdth;
    cloop->pxm_hght	= xhght;
    cloop->roamflg	= 0;
    cloop->xoffset	= 0;
    cloop->yoffset	= 0;

    cloop->pxm_x	= 0;
    cloop->pxm_y	= 0;
    cwin->area_w	= xwdth;
    cwin->area_h	= xhght;
    cwin->win_x		= 0;
    cwin->win_y		= 0;

    /*
     * return device size
     */
    *ixsize = xwdth;
    *iysize = xhght;

    /*
     * clear the pixmap,
     */
    xclrpxm(&(cwin->curpxm[cwin->curr_loop]), &ier);

    /*
     * Select the events to be processed.
     */
    XSelectInput ( gemdisplay, gwin, ExposureMask );

    /*
     * Set the cursor to be the customary red arrow.
     */
    curs = XCreateFontCursor ( gemdisplay, XC_top_left_arrow );
    XDefineCursor ( gemdisplay, gwin, curs );
    cred.red	= 65535;
    cred.blue	= 0;
    cred.green	= 0;
    cred.flags	= DoRed | DoBlue | DoGreen;
    XRecolorCursor ( gemdisplay, curs, &cred, &cred );

}
int main(int argc, char *argv[])
{
#ifdef USERC
    char match[128];
    int config_line_count, len;
    char *config_line;
#endif

    console = fopen("/dev/console","w");
    if (!console) console = stderr;

    if (!(argv0 = strrchr(argv[0],'/')))
	argv0 = argv[0];
    else 
	++argv0;

    if (argc < 6) {
	fprintf(stderr,
#ifdef FVWM1
		"%s: module should be executed by fvwm only\n",
#else
		"%s: module should be executed by fvwm2 only\n",
#endif
		argv0);
	exit(-1);
    }

    fd[0] = atoi(argv[1]);
    fd[1] = atoi(argv[2]);

    if (!(dpy = XOpenDisplay(NULL))) {
	fprintf(console, "%s: couldn't open display %s\n",
		argv0,
		XDisplayName(NULL));
	exit(-1);
    }
    signal (SIGPIPE, DeadPipe);

    {
	int s = DefaultScreen(dpy);
	dwidth = DisplayWidth(dpy, s);
	dheight = DisplayHeight(dpy, s);
    }

    fd_width = GetFdWidth();
    
#ifdef USERC
    strcpy(match, "*");
    strcat(match, argv0);
    len = strlen(match);
#ifdef FVWM1
    if ((config_line = GetConfigLine(argv[3], match))) {
	char **args = NULL;
	config_line_count = parse_line(config_line, &args);
	parse_args("config args", 
		   config_line_count, args, 0);
	free(config_line);
	free(args);
    }
#else
    GetConfigLine(fd, &config_line);
    while (config_line != NULL) {
	if (strncmp(match,config_line,len)==0) {
	    char **args = NULL;
	    int cllen = strlen(config_line);
	    if (config_line[cllen - 1] == '\n')
		config_line[cllen - 1] = 0;
	    config_line_count = parse_line(config_line, &args);
	    parse_args("config args", 
		       config_line_count, args, 0);
	    free(args);
	}
	GetConfigLine(fd, &config_line);
    }
#endif /* FVWM1 */
#endif /* USERC */

    if (strcmp(argv0, "FvwmCascade") && (!strcmp(argv0, "FvwmTile") ||
	(argc >= 7 && !strcmp(argv[6], "-tile"))))
      {
	FvwmTile = 1;
	FvwmCascade = 0;
	resize = 1;
      }
    else
      {
	FvwmCascade = 1;
	FvwmTile = 0;
	resize = 0;
      }
    parse_args("module args", argc, argv, 6);

#ifdef FVWM1
    {
	char msg[256];
	sprintf(msg, "SET_MASK %lu\n",(unsigned long)(
	    M_CONFIGURE_WINDOW|
	    M_END_WINDOWLIST
	    ));
	SendInfo(fd,msg,0);
	
#ifdef FVWM1_MOVENULL
	/* avoid interactive placement in fvwm version 1 */
	if (!ofsx) ++ofsx;
	if (!ofsy) ++ofsy;
#endif
    }
#else
    SetMessageMask(fd,
		   M_CONFIGURE_WINDOW 
		   | M_END_WINDOWLIST
	);
#endif

    if (FvwmTile)
    {
      if (!maxx) maxx = dwidth;
      if (!maxy) maxy = dheight;
    }

    SendInfo(fd,"Send_WindowList",0);
    while (get_window());
    if (wins_count)
    {
      if (FvwmCascade)
	cascade_windows();
      else /* FvwmTile */
	tile_windows();
    }
    free_window_list(&wins);
    if (console != stderr)
	fclose(console);
    return 0;
}
Exemple #21
0
/*Function returns a pointer to a full-screen dump (XImage structure)*/
XImage* fullScreenCapture()
{
	int screen_num;
	Display *dpy;
	XImage *image;
	/*Connecting to X server*/
	dpy = XOpenDisplay(NULL);
	if (!dpy)
	{
		fprintf(stderr, "Error: Unable to establish connection to X server\n");
		return NULL;
	}
	/*Getting default screen*/
	screen_num = DefaultScreen(dpy);

	/*Doing a full-screen dump*/
	image = XGetImage (dpy, RootWindow(dpy, screen_num), 0, 0, DisplayWidth(dpy,screen_num),  DisplayHeight(dpy,screen_num), AllPlanes, ZPixmap);

	if (!image) {
		fprintf (stderr, "Error: Unable to get image from X server\n");
		XCloseDisplay(dpy);
		return NULL;
		}
	/*Finishing*/
	XCloseDisplay(dpy);
	return image;
}
Exemple #22
0
    //-------------------------------------------------------------------------------------------------//
    void GLXWindow::create(const String& name, uint width, uint height,
               bool fullScreen, const NameValuePairList *miscParams)
    {
        Display *xDisplay = mGLSupport->getXDisplay();
        String title = name;
        uint samples = 0;
        short frequency = 0;
        bool vsync = false;
        bool hidden = false;
        unsigned int vsyncInterval = 1;
        int gamma = 0;
        ::GLXContext glxContext = 0;
        ::GLXDrawable glxDrawable = 0;
        Window externalWindow = 0;
        Window parentWindow = DefaultRootWindow(xDisplay);
        int left = DisplayWidth(xDisplay, DefaultScreen(xDisplay))/2 - width/2;
        int top  = DisplayHeight(xDisplay, DefaultScreen(xDisplay))/2 - height/2;
        String border;
        
        mIsFullScreen = fullScreen;
        
        if(miscParams)
        {
            NameValuePairList::const_iterator opt;
            NameValuePairList::const_iterator end = miscParams->end();
            
            // NB: Do not try to implement the externalGLContext option.
            //
            //   Accepting a non-current context would expose us to the 
            //   risk of segfaults when we made it current. Since the
            //   application programmers would be responsible for these
            //   segfaults, they are better discovering them in their code.
        
            if ((opt = miscParams->find("currentGLContext")) != end &&
                StringConverter::parseBool(opt->second))
            {
                if (! glXGetCurrentContext())
                {
                    OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "currentGLContext was specified with no current GL context", "GLXWindow::create");
                }
                
                glxContext = glXGetCurrentContext();
                glxDrawable = glXGetCurrentDrawable();
            }
            
            // Note: Some platforms support AA inside ordinary windows
            if((opt = miscParams->find("FSAA")) != end) 
                samples = StringConverter::parseUnsignedInt(opt->second);
            
            if((opt = miscParams->find("displayFrequency")) != end) 
                frequency = (short)StringConverter::parseInt(opt->second);
            
            if((opt = miscParams->find("vsync")) != end) 
                vsync = StringConverter::parseBool(opt->second);

            if((opt = miscParams->find("hidden")) != end)
                hidden = StringConverter::parseBool(opt->second);

            if((opt = miscParams->find("vsyncInterval")) != end) 
                vsyncInterval = StringConverter::parseUnsignedInt(opt->second);

            if ((opt = miscParams->find("gamma")) != end)
                gamma = StringConverter::parseBool(opt->second);

            if((opt = miscParams->find("left")) != end) 
                left = StringConverter::parseInt(opt->second);
            
            if((opt = miscParams->find("top")) != end) 
                top = StringConverter::parseInt(opt->second);
            
            if((opt = miscParams->find("title")) != end) 
                title = opt->second;
            
            if ((opt = miscParams->find("externalGLControl")) != end)
                mIsExternalGLControl = StringConverter::parseBool(opt->second);
            
#if OGRE_NO_QUAD_BUFFER_STEREO == 0
			if ((opt = miscParams->find("stereoMode")) != end)
			{
				StereoModeType stereoMode = StringConverter::parseStereoMode(opt->second);
				if (SMT_NONE != stereoMode)
					mStereoEnabled = true;
			}
#endif

            if((opt = miscParams->find("parentWindowHandle")) != end) 
            {
                vector<String>::type tokens = StringUtil::split(opt->second, " :");
                
                if (tokens.size() == 3)
                {
                    // deprecated display:screen:xid format
                    parentWindow = StringConverter::parseUnsignedLong(tokens[2]);
                }
                else
                {
                    // xid format
                    parentWindow = StringConverter::parseUnsignedLong(tokens[0]);
                }
            }
            else if((opt = miscParams->find("externalWindowHandle")) != end) 
            {
                vector<String>::type tokens = StringUtil::split(opt->second, " :");
                
                LogManager::getSingleton().logMessage(
                                                      "GLXWindow::create: The externalWindowHandle parameter is deprecated.\n"
                                                      "Use the parentWindowHandle or currentGLContext parameter instead.");
                
                if (tokens.size() == 3)
                {
                    // Old display:screen:xid format
                    // The old GLX code always created a "parent" window in this case:
                    parentWindow = StringConverter::parseUnsignedLong(tokens[2]);
                }
                else if (tokens.size() == 4)
                {
                    // Old display:screen:xid:visualinfo format
                    externalWindow = StringConverter::parseUnsignedLong(tokens[2]);
                }
                else
                {
                    // xid format
                    externalWindow = StringConverter::parseUnsignedLong(tokens[0]);
                }
            }

            if ((opt = miscParams->find("border")) != end)
                border = opt->second;
        }
        
        // Ignore fatal XErrorEvents during parameter validation:
        oldXErrorHandler = XSetErrorHandler(safeXErrorHandler);
        // Validate parentWindowHandle
        
        if (parentWindow != DefaultRootWindow(xDisplay))
        {
            XWindowAttributes windowAttrib;
            
            if (! XGetWindowAttributes(xDisplay, parentWindow, &windowAttrib) ||
                windowAttrib.root != DefaultRootWindow(xDisplay))
            {
                OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Invalid parentWindowHandle (wrong server or screen)", "GLXWindow::create");
            }
        }
        
        // Validate externalWindowHandle
        
        if (externalWindow != 0)
        {
            XWindowAttributes windowAttrib;
            
            if (! XGetWindowAttributes(xDisplay, externalWindow, &windowAttrib) ||
                windowAttrib.root != DefaultRootWindow(xDisplay))
            {
                OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Invalid externalWindowHandle (wrong server or screen)", "GLXWindow::create");
            }
            glxDrawable = externalWindow;
        }

        // Derive fbConfig
        
        ::GLXFBConfig fbConfig = 0;
        
        if (glxDrawable)
        {
            fbConfig = mGLSupport->getFBConfigFromDrawable (glxDrawable, &width, &height);
        }

        if (! fbConfig && glxContext)
        {
            fbConfig = mGLSupport->getFBConfigFromContext (glxContext);
        }
            
        mIsExternal = (glxDrawable != 0);
        
        XSetErrorHandler(oldXErrorHandler);
        
        if (! fbConfig)
        {
            int minAttribs[] = {
                GLX_DRAWABLE_TYPE,  GLX_WINDOW_BIT,
                GLX_RENDER_TYPE,    GLX_RGBA_BIT,
                GLX_RED_SIZE,      1,
                GLX_BLUE_SIZE,    1,
                GLX_GREEN_SIZE,  1,
#if OGRE_NO_QUAD_BUFFER_STEREO == 0
				GLX_STEREO, mStereoEnabled ? True : False,
#endif
                None
            };
            
            int maxAttribs[] = {
                GLX_SAMPLES,        static_cast<int>(samples),
                GLX_DOUBLEBUFFER,   1,
                GLX_STENCIL_SIZE,   INT_MAX,
                GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT, 1,
                None
            };

            fbConfig = mGLSupport->selectFBConfig(minAttribs, maxAttribs);

            // Now check the actual supported fsaa value
            GLint maxSamples;
            mGLSupport->getFBConfigAttrib(fbConfig, GLX_SAMPLES, &maxSamples);
            mFSAA = maxSamples;

            if (gamma != 0)
            {
                mGLSupport->getFBConfigAttrib(fbConfig, GL_FRAMEBUFFER_SRGB_CAPABLE_EXT, &gamma);
            }

            mHwGamma = (gamma != 0);
        }
        
    if (! fbConfig)
    {
      // This should never happen.
      OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unexpected failure to determine a GLXFBConfig","GLXWindow::create");
    }
        
        mIsTopLevel = (! mIsExternal && parentWindow == DefaultRootWindow(xDisplay));
        
        if (! mIsTopLevel)
        {
            mIsFullScreen = false;
            left = top = 0;
        }
        
        if (mIsFullScreen) 
        {
            mGLSupport->switchMode (width, height, frequency);
        }
        
        if (! mIsExternal)
        {
            XSetWindowAttributes attr;
            ulong mask;
            XVisualInfo *visualInfo = mGLSupport->getVisualFromFBConfig (fbConfig);
            
            attr.background_pixel = 0;
            attr.border_pixel = 0;
            attr.colormap = XCreateColormap(xDisplay, DefaultRootWindow(xDisplay), visualInfo->visual, AllocNone);
            attr.event_mask = StructureNotifyMask | VisibilityChangeMask | FocusChangeMask;
            mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
            
            if(mIsFullScreen && mGLSupport->mAtomFullScreen == None) 
            {
                LogManager::getSingleton().logMessage("GLXWindow::switchFullScreen: Your WM has no fullscreen support");
                
                // A second best approach for outdated window managers
                attr.backing_store = NotUseful;
                attr.save_under = False;
                attr.override_redirect = True;
                mask |= CWSaveUnder | CWBackingStore | CWOverrideRedirect;
                left = top = 0;
            } 
            
            // Create window on server
            mWindow = XCreateWindow(xDisplay, parentWindow, left, top, width, height, 0, visualInfo->depth, InputOutput, visualInfo->visual, mask, &attr);
            
            XFree(visualInfo);
            
            if(!mWindow) 
            {
                OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to create an X Window", "GLXWindow::create");
            }
            
            if (mIsTopLevel)
            {
                XWMHints *wmHints;
                XSizeHints *sizeHints;
                
                if ((wmHints = XAllocWMHints()) != NULL) 
                {
                    wmHints->initial_state = NormalState;
                    wmHints->input = True;
                    wmHints->flags = StateHint | InputHint;
                    
                    int depth = DisplayPlanes(xDisplay, DefaultScreen(xDisplay));
                    
                    // Check if we can give it an icon
                    if(depth == 24 || depth == 32) 
                    {
                        if(mGLSupport->loadIcon("GLX_icon.png", &wmHints->icon_pixmap, &wmHints->icon_mask))
                        {
                            wmHints->flags |= IconPixmapHint | IconMaskHint;
                        }
                    }
                }
                
                if ((sizeHints = XAllocSizeHints()) != NULL)
                {
                    // Is this really necessary ? Which broken WM might need it?
                    sizeHints->flags = USPosition;

                    if(!fullScreen && border == "fixed")
                    {
                        sizeHints->min_width = sizeHints->max_width = width;
                        sizeHints->min_height = sizeHints->max_height = height;
                        sizeHints->flags |= PMaxSize | PMinSize;
                    }
                }
                
                XTextProperty titleprop;
                vector<char>::type  title_ (title.begin(), title.end());
                title_.push_back(0);

                char *lst = &title_[0];
                XStringListToTextProperty((char **)&lst, 1, &titleprop);
                XSetWMProperties(xDisplay, mWindow, &titleprop, NULL, NULL, 0, sizeHints, wmHints, NULL);
                
                XFree(titleprop.value);
                XFree(wmHints);
                XFree(sizeHints);
                
                XSetWMProtocols(xDisplay, mWindow, &mGLSupport->mAtomDeleteWindow, 1);
                
                XWindowAttributes windowAttrib;
                
                XGetWindowAttributes(xDisplay, mWindow, &windowAttrib);
                
                left = windowAttrib.x;
                top = windowAttrib.y;
                width = windowAttrib.width;
                height = windowAttrib.height;
            }
            
            glxDrawable = mWindow;
            
            // setHidden takes care of mapping or unmapping the window
            // and also calls setFullScreen if appropriate.
            setHidden(hidden);
            XFlush(xDisplay);
            
            WindowEventUtilities::_addRenderWindow(this);
        }
        
        mContext = new GLXContext(mGLSupport, fbConfig, glxDrawable, glxContext);
        
        // apply vsync settings. call setVSyncInterval first to avoid 
        // setting vsync more than once.
        setVSyncInterval(vsyncInterval);
        setVSyncEnabled(vsync);
        
        int fbConfigID;
        
        mGLSupport->getFBConfigAttrib(fbConfig, GLX_FBCONFIG_ID, &fbConfigID);
        
        LogManager::getSingleton().logMessage("GLXWindow::create used FBConfigID = " + StringConverter::toString(fbConfigID));
        
        mName = name;
        mWidth = width;
        mHeight = height;
        mLeft = left;
        mTop = top;
        mActive = true;
        mClosed = false;
    }
Exemple #23
0
static struct lock *
lockscreen(Display *dpy, struct xrandr *rr, int screen)
{
	char curs[] = {0, 0, 0, 0, 0, 0, 0, 0};
	int i, ptgrab, kbgrab;
	struct lock *lock;
	XColor color, dummy;
	XSetWindowAttributes wa;
	Cursor invisible;

	if (dpy == NULL || screen < 0 || !(lock = malloc(sizeof(struct lock))))
		return NULL;

	lock->screen = screen;
	lock->root = RootWindow(dpy, lock->screen);

	for (i = 0; i < NUMCOLS; i++) {
		XAllocNamedColor(dpy, DefaultColormap(dpy, lock->screen),
		                 colorname[i], &color, &dummy);
		lock->colors[i] = color.pixel;
	}

	/* init */
	wa.override_redirect = 1;
	wa.background_pixel = lock->colors[INIT];
	lock->win = XCreateWindow(dpy, lock->root, 0, 0,
	                          DisplayWidth(dpy, lock->screen),
	                          DisplayHeight(dpy, lock->screen),
	                          0, DefaultDepth(dpy, lock->screen),
	                          CopyFromParent,
	                          DefaultVisual(dpy, lock->screen),
	                          CWOverrideRedirect | CWBackPixel, &wa);
	lock->pmap = XCreateBitmapFromData(dpy, lock->win, curs, 8, 8);
	invisible = XCreatePixmapCursor(dpy, lock->pmap, lock->pmap,
	                                &color, &color, 0, 0);
	XDefineCursor(dpy, lock->win, invisible);

	/* Try to grab mouse pointer *and* keyboard for 600ms, else fail the lock */
	for (i = 0, ptgrab = kbgrab = -1; i < 6; i++) {
		if (ptgrab != GrabSuccess) {
			ptgrab = XGrabPointer(dpy, lock->root, False,
			                      ButtonPressMask | ButtonReleaseMask |
			                      PointerMotionMask, GrabModeAsync,
			                      GrabModeAsync, None, invisible, CurrentTime);
		}
		if (kbgrab != GrabSuccess) {
			kbgrab = XGrabKeyboard(dpy, lock->root, True,
			                       GrabModeAsync, GrabModeAsync, CurrentTime);
		}

		/* input is grabbed: we can lock the screen */
		if (ptgrab == GrabSuccess && kbgrab == GrabSuccess) {
			XMapRaised(dpy, lock->win);
			if (rr->active)
				XRRSelectInput(dpy, lock->win, RRScreenChangeNotifyMask);

			XSelectInput(dpy, lock->root, SubstructureNotifyMask);
			return lock;
		}

		/* retry on AlreadyGrabbed but fail on other errors */
		if ((ptgrab != AlreadyGrabbed && ptgrab != GrabSuccess) ||
		    (kbgrab != AlreadyGrabbed && kbgrab != GrabSuccess))
			break;

		usleep(100000);
	}

	/* we couldn't grab all input: fail out */
	if (ptgrab != GrabSuccess)
		fprintf(stderr, "slock: unable to grab mouse pointer for screen %d\n",
		        screen);
	if (kbgrab != GrabSuccess)
		fprintf(stderr, "slock: unable to grab keyboard for screen %d\n",
		        screen);
	return NULL;
}
Exemple #24
0
/**
 * Grab a frame from x11 (public device demuxer API).
 *
 * @param s1 Context from avformat core
 * @param pkt Packet holding the brabbed frame
 * @return frame size in bytes
 */
static int x11grab_read_packet(AVFormatContext *s1, AVPacket *pkt)
{
    X11GrabContext *s = s1->priv_data;
    Display *dpy      = s->dpy;
    XImage *image     = s->image;
    int x_off         = s->x_off;
    int y_off         = s->y_off;
    int follow_mouse  = s->follow_mouse;
    int screen, pointer_x, pointer_y, _, same_screen = 1;
    Window w, root;
    int64_t curtime, delay;
    struct timespec ts;

    /* Calculate the time of the next frame */
    s->time_frame += INT64_C(1000000);

    /* wait based on the frame rate */
    for (;;) {
        curtime = av_gettime();
        delay   = s->time_frame * av_q2d(s->time_base) - curtime;
        if (delay <= 0) {
            if (delay < INT64_C(-1000000) * av_q2d(s->time_base))
                s->time_frame += INT64_C(1000000);
            break;
        }
        ts.tv_sec  = delay / 1000000;
        ts.tv_nsec = (delay % 1000000) * 1000;
        nanosleep(&ts, NULL);
    }

    av_init_packet(pkt);
    pkt->data = image->data;
    pkt->size = s->frame_size;
    pkt->pts  = curtime;

    screen = DefaultScreen(dpy);
    root   = RootWindow(dpy, screen);

    if (follow_mouse || s->draw_mouse)
        same_screen = XQueryPointer(dpy, root, &w, &w,
                                    &pointer_x, &pointer_y, &_, &_, &_);

    if (follow_mouse && same_screen) {
        int screen_w, screen_h;

        screen_w = DisplayWidth(dpy, screen);
        screen_h = DisplayHeight(dpy, screen);
        if (follow_mouse == -1) {
            // follow the mouse, put it at center of grabbing region
            x_off += pointer_x - s->width / 2 - x_off;
            y_off += pointer_y - s->height / 2 - y_off;
        } else {
            // follow the mouse, but only move the grabbing region when mouse
            // reaches within certain pixels to the edge.
            if (pointer_x > x_off + s->width - follow_mouse)
                x_off += pointer_x - (x_off + s->width - follow_mouse);
            else if (pointer_x < x_off + follow_mouse)
                x_off -= (x_off + follow_mouse) - pointer_x;
            if (pointer_y > y_off + s->height - follow_mouse)
                y_off += pointer_y - (y_off + s->height - follow_mouse);
            else if (pointer_y < y_off + follow_mouse)
                y_off -= (y_off + follow_mouse) - pointer_y;
        }
        // adjust grabbing region position if it goes out of screen.
        s->x_off = x_off = FFMIN(FFMAX(x_off, 0), screen_w - s->width);
        s->y_off = y_off = FFMIN(FFMAX(y_off, 0), screen_h - s->height);

        if (s->show_region && s->region_win)
            XMoveWindow(dpy, s->region_win,
                        s->x_off - REGION_WIN_BORDER,
                        s->y_off - REGION_WIN_BORDER);
    }

    if (s->show_region && same_screen) {
        if (s->region_win) {
            XEvent evt = { .type = NoEventMask };
            // Clean up the events, and do the initial draw or redraw.
            while (XCheckMaskEvent(dpy, ExposureMask | StructureNotifyMask,
                                   &evt))
                ;
            if (evt.type)
                x11grab_draw_region_win(s);
        } else {
/*********************************************************
 * createAndPopupProductDescriptionShell
 *
 * function to create, set and popup an EPICS product description shell
 *  widget hierarchy:
 *
 * productDescriptionShell
 *    form
 *	nameLabel
 *	separator
 *	descriptionLabel
 *	versionInfoLabel
 *	developedAtLabel
 *	okButton
*********************************************************/
Widget createAndPopupProductDescriptionShell(
XtAppContext appContext,	/* application context		*/
Widget topLevelShell,		/* application's topLevel shell	*/
char *name,			/* product/program name		*/
XmFontList nameFontList,	/*   and font list (or NULL)	*/
Pixmap namePixmap,		/* name Pixmap (or NULL)	*/
char *description,		/* product description		*/
XmFontList descriptionFontList,/*   and font list (or NULL)	*/
char *versionInfo,		/* product version number	*/
char *developedAt,		/* at and by...			*/
XmFontList otherFontList,	/*   and font list (or NULL)	*/
int background,		/* background color (or -1)	*/
int foreground,		/* foreground color (or -1)	*/
int seconds)			/* seconds to leave posted	*/
{
	Display *display;
	Widget productDescriptionShell, form;
	Arg args[15];
	Widget children[6], nameLabel, descriptionLabel, versionInfoLabel,
	    separator, developedAtLabel;
	XmString nameXmString = (XmString)NULL, descriptionXmString = (XmString)NULL,
	    versionInfoXmString = (XmString)NULL,
	    developedAtXmString = (XmString)NULL, okXmString = (XmString)NULL;
	Dimension formHeight, nameHeight;
	Dimension shellHeight, shellWidth;
	Dimension screenHeight, screenWidth;
	Position newY, newX;
	int n, offset, screen;


	/* Create the shell */
	n = 0;
	if (background >= 0) {
		XtSetArg(args[n],XmNbackground,(unsigned long)background); 
		n++;
	}
	if (foreground >= 0) {
		XtSetArg(args[n],XmNforeground,(unsigned long)foreground); 
		n++;
	}
	XtSetArg(args[n],XmNmwmDecorations, MWM_DECOR_ALL|
	    MWM_DECOR_BORDER|MWM_DECOR_RESIZEH|MWM_DECOR_TITLE|MWM_DECOR_MENU|
	    MWM_DECOR_MINIMIZE|MWM_DECOR_MAXIMIZE); 
	n++;
	XtSetArg(args[n],XmNtitle,"Version"); 
	n++;
	productDescriptionShell = XtCreatePopupShell("productDescriptionShell",
	    topLevelShellWidgetClass,topLevelShell,args, n);
	display=XtDisplay(productDescriptionShell);
	screen=DefaultScreen(display);

	n = 0;
	if (background >= 0) {
		XtSetArg(args[n],XmNbackground,(unsigned long)background); 
		n++; 
	}
	if (foreground >= 0) {
		XtSetArg(args[n],XmNforeground,(unsigned long)foreground); 
		n++; 
	}
	XtSetArg(args[n],XmNnoResize,True); 
	n++;
	XtSetArg(args[n],XmNshadowThickness,2); 
	n++;
	XtSetArg(args[n],XmNshadowType,XmSHADOW_OUT); 
	n++;
	XtSetArg(args[n],XmNautoUnmanage,False); 
	n++;
	form = XmCreateForm(productDescriptionShell,"form",args,n);

	/* Generate XmStrings */
	if (name != NULL) nameXmString = XmStringCreateLtoR(name,
	    XmFONTLIST_DEFAULT_TAG);
	if (description != NULL) descriptionXmString =
	XmStringCreateLtoR(description,XmFONTLIST_DEFAULT_TAG);
	if (versionInfo != NULL) versionInfoXmString =
	XmStringCreateLtoR(versionInfo,XmFONTLIST_DEFAULT_TAG);
	if (developedAt != NULL) developedAtXmString =
	XmStringCreateLtoR(developedAt,XmFONTLIST_DEFAULT_TAG);

	/* Create the label children  */
	/* Name */
	n = 0;
	if (namePixmap == (Pixmap) NULL) {
		XtSetArg(args[n],XmNlabelString,nameXmString); 
		n++;
		if (nameFontList != NULL) {
			XtSetArg(args[n],XmNfontList,nameFontList); 
			n++;
		}
	} else {
		XtSetArg(args[n],XmNlabelType,XmPIXMAP); 
		n++;
		XtSetArg(args[n],XmNlabelPixmap,namePixmap); 
		n++;
	}
	XtSetArg(args[n],XmNalignment,XmALIGNMENT_BEGINNING); 
	n++;
	XtSetArg(args[n],XmNleftAttachment,XmATTACH_POSITION); 
	n++;
	XtSetArg(args[n],XmNleftPosition,1); 
	n++;
	XtSetArg(args[n],XmNresizable,False); 
	n++;
	if (background >= 0) {
		XtSetArg(args[n],XmNbackground,(unsigned long)background); 
		n++; 
	}
	if (foreground >= 0) {
		XtSetArg(args[n],XmNforeground,(unsigned long)foreground); 
		n++; 
	}
	nameLabel = XmCreateLabel(form,"nameLabel",args,n);


	/* Separator */
	n = 0;
	XtSetArg(args[n],XmNtopAttachment,XmATTACH_FORM); 
	n++;
	XtSetArg(args[n],XmNbottomAttachment,XmATTACH_FORM); 
	n++;
	XtSetArg(args[n],XmNleftAttachment,XmATTACH_WIDGET); 
	n++;
	XtSetArg(args[n],XmNleftWidget,nameLabel); 
	n++;
	XtSetArg(args[n],XmNorientation,XmVERTICAL); 
	n++;
	XtSetArg(args[n],XmNshadowThickness,2); 
	n++;
	XtSetArg(args[n],XmNseparatorType,XmSHADOW_ETCHED_IN); 
	n++;
	if (background >= 0) {
		XtSetArg(args[n],XmNbackground,(unsigned long)background); 
		n++; 
	}
	if (foreground >= 0) {
		XtSetArg(args[n],XmNforeground,(unsigned long)foreground); 
		n++; 
	}
	separator = XmCreateSeparator(form,"separator",args,n);

	/* Description */
	n = 0;
	XtSetArg(args[n],XmNalignment,XmALIGNMENT_BEGINNING); 
	n++;
	XtSetArg(args[n],XmNlabelString,descriptionXmString); 
	n++;
	XtSetArg(args[n],XmNtopAttachment,XmATTACH_POSITION); 
	n++;
	XtSetArg(args[n],XmNtopPosition,5); 
	n++;
	XtSetArg(args[n],XmNleftAttachment,XmATTACH_WIDGET); 
	n++;
	XtSetArg(args[n],XmNleftWidget,separator); 
	n++;
	XtSetArg(args[n],XmNrightAttachment,XmATTACH_POSITION); 
	n++;
	XtSetArg(args[n],XmNrightPosition,90); 
	n++;
	if (descriptionFontList != NULL) {
		XtSetArg(args[n],XmNfontList,descriptionFontList); 
		n++;
	}
	if (background >= 0) {
		XtSetArg(args[n],XmNbackground,(unsigned long)background); 
		n++; 
	}
	if (foreground >= 0) {
		XtSetArg(args[n],XmNforeground,(unsigned long)foreground); 
		n++; 
	}
	descriptionLabel = XmCreateLabel(form,"descriptionLabel",args,n);

	/* Version info */
	n = 0;
	XtSetArg(args[n],XmNalignment,XmALIGNMENT_BEGINNING); 
	n++;
	XtSetArg(args[n],XmNlabelString,versionInfoXmString); 
	n++;
	XtSetArg(args[n],XmNtopAttachment,XmATTACH_WIDGET); 
	n++;
	XtSetArg(args[n],XmNtopWidget,descriptionLabel); 
	n++;
	XtSetArg(args[n],XmNleftAttachment,XmATTACH_OPPOSITE_WIDGET); 
	n++;
	XtSetArg(args[n],XmNleftWidget,descriptionLabel); 
	n++;
	XtSetArg(args[n],XmNrightAttachment,XmATTACH_POSITION); 
	n++;
	XtSetArg(args[n],XmNrightPosition,90); 
	n++;
	if (otherFontList != NULL) {
		XtSetArg(args[n],XmNfontList,otherFontList); 
		n++;
	}
	if (background >= 0) {
		XtSetArg(args[n],XmNbackground,(unsigned long)background); 
		n++; 
	}
	if (foreground >= 0) {
		XtSetArg(args[n],XmNforeground,(unsigned long)foreground); 
		n++; 
	}
	versionInfoLabel = XmCreateLabel(form,"versionInfoLabel",args,n);

	/* Developed at/by... */
	n = 0;
	XtSetArg(args[n],XmNalignment,XmALIGNMENT_BEGINNING); 
	n++;
	XtSetArg(args[n],XmNlabelString,developedAtXmString); 
	n++;
	XtSetArg(args[n],XmNtopAttachment,XmATTACH_WIDGET); 
	n++;
	XtSetArg(args[n],XmNtopWidget,versionInfoLabel); 
	n++;
	XtSetArg(args[n],XmNleftAttachment,XmATTACH_OPPOSITE_WIDGET); 
	n++;
	XtSetArg(args[n],XmNleftWidget,versionInfoLabel); 
	n++;
	XtSetArg(args[n],XmNrightAttachment,XmATTACH_POSITION); 
	n++;
	XtSetArg(args[n],XmNrightPosition,90); 
	n++;
	XtSetArg(args[n],XmNbottomAttachment,XmATTACH_POSITION); 
	n++;
	XtSetArg(args[n],XmNbottomPosition,90); 
	n++;

	if (otherFontList != NULL) {
		XtSetArg(args[n],XmNfontList,otherFontList); 
		n++;
	}
	if (background >= 0) {
		XtSetArg(args[n],XmNbackground,(unsigned long)background); 
		n++; 
	}
	if (foreground >= 0) {
		XtSetArg(args[n],XmNforeground,(unsigned long)foreground); 
		n++; 
	}
	developedAtLabel = XmCreateLabel(form,"developedAtLabel",args,n);


	/* OK button */
	okXmString = XmStringCreateLocalized("OK");
	n = 0;
	XtSetArg(args[n],XmNlabelString,okXmString); 
	n++;
	XtSetArg(args[n],XmNtopAttachment,XmATTACH_FORM); 
	n++;
	XtSetArg(args[n],XmNtopOffset,8); 
	n++;
	XtSetArg(args[n],XmNrightAttachment,XmATTACH_FORM); 
	n++;
	XtSetArg(args[n],XmNrightOffset,8); 
	n++;
	if (otherFontList != NULL) {
		XtSetArg(args[n],XmNfontList,otherFontList); 
		n++;
	}
	if (background >= 0) {
		XtSetArg(args[n],XmNbackground,(unsigned long)background); 
		n++; 
	}
	if (foreground >= 0) {
		XtSetArg(args[n],XmNforeground,(unsigned long)foreground); 
		n++; 
	}
	okButton = XmCreatePushButton(form,"okButton",args,n);
	XtAddCallback(okButton,XmNactivateCallback,
	    (XtCallbackProc)closeProductDescriptionCallback,
	    (XtPointer)productDescriptionShell); 
	n++;
	XmStringFree(okXmString);

	children[0] = nameLabel; 
	children[1] = descriptionLabel;
	children[2] = versionInfoLabel; 
	children[3] = developedAtLabel;
	children[4] = separator;
	XtManageChildren(children,5);
	XtManageChild(form);

	XtPopup(productDescriptionShell,XtGrabNone);

	/* Center nameLabel vertically in form space */
	XtSetArg(args[0],XmNheight,&nameHeight);
	XtGetValues(nameLabel,args,1);
	XtSetArg(args[0],XmNheight,&formHeight);
	XtGetValues(form,args,1);
	offset = (formHeight - nameHeight);
	offset = offset/2;
	XtSetArg(args[0],XmNtopOffset,offset);
	XtSetValues(nameLabel,args,1);

	/* Center the whole thing on the screen */
	screenHeight=DisplayHeight(display,screen);
	screenWidth=DisplayWidth(display,screen);

	n=0;
	XtSetArg(args[n],XmNheight,&shellHeight); 
	n++;
	XtSetArg(args[n],XmNwidth,&shellWidth); 
	n++;
	XtGetValues(productDescriptionShell,args,n);

	newY=(screenHeight-shellHeight)/2;
	newX=(screenWidth-shellWidth)/2;

	n=0;
	XtSetArg(args[n],XmNy,newY); 
	n++;
	XtSetArg(args[n],XmNx,newX); 
	n++;
	XtSetValues(productDescriptionShell,args,n);

#ifdef WIN32
	/* Seems to be an Exceed bug that it doesn't get set the first time */
	n=0;
	XtSetArg(args[n],XmNy,newY); 
	n++;
	XtSetArg(args[n],XmNx,newX); 
	n++;
	XtSetValues(productDescriptionShell,args,n);
#endif    

#if DEBUG_POSITION
	{
		Position newx, newy;

		printf("createAndPopupProductDescriptionShell:\n");
		printf("  sizeof(XtArgVal)=%d sizeof(Position)=%d sizeof(Dimension)=%d sizeof(100)=%d\n",
		    sizeof(XtArgVal),sizeof(Position),sizeof(Dimension),sizeof(100));
		printf("  shellHeight=%d  shellWidth=%d\n",shellHeight,shellWidth);
		printf("  screenHeight=%d  screenWidth=%d\n",screenHeight,screenWidth);
		printf("  newY=%hd  newX=%hd\n",newY,newX);
		printf("  newY=%hx  newX=%hx\n",newY,newX);
		printf("  newY=%x  newX=%x\n",newY,newX);

		printf("(1) args[0].value=%4x  args[1].value=%4x\n",args[0].value,args[1].value);

		n=0;
		XtSetArg(args[n],XmNy,&newy); 
		n++;
		XtSetArg(args[n],XmNx,&newx); 
		n++;
		XtGetValues(productDescriptionShell,args,n);

		printf("(1) newy=%d  newx=%d\n",newy,newx);

		n=0;
		XtSetArg(args[n],XmNy,474); 
		n++;
		XtSetArg(args[n],XmNx,440); 
		n++;
		XtSetValues(productDescriptionShell,args,n);

		printf("(2) args[0].value=%4x  args[1].value=%4x\n",args[0].value,args[1].value);

		n=0;
		XtSetArg(args[n],XmNy,&newy); 
		n++;
		XtSetArg(args[n],XmNx,&newx); 
		n++;
		XtGetValues(productDescriptionShell,args,n);

		printf("(2) newy=%d  newx=%d\n",newy,newx);

		n=0;
		XtSetArg(args[n],XmNy,newY); 
		n++;
		XtSetArg(args[n],XmNx,newX); 
		n++;
		XtSetValues(productDescriptionShell,args,n);

		printf("(3) args[0].value=%4x  args[1].value=%4x\n",args[0].value,args[1].value);

		n=0;
		XtSetArg(args[n],XmNy,&newy); 
		n++;
		XtSetArg(args[n],XmNx,&newx); 
		n++;
		XtGetValues(productDescriptionShell,args,n);

		printf("(3) newy=%d  newx=%d\n",newy,newx);

	}
#endif    

	/* Free strings */
	if (nameXmString != (XmString)NULL) XmStringFree(nameXmString);
	if (descriptionXmString != (XmString)NULL) XmStringFree(descriptionXmString);
	if (versionInfoXmString != (XmString)NULL) XmStringFree(versionInfoXmString);
	if (developedAtXmString != (XmString)NULL) XmStringFree(developedAtXmString);

	/* Register timeout procedure to make the dialog go away after N seconds */
	XtAppAddTimeOut(appContext,(unsigned long)(1000*seconds),
	    (XtTimerCallbackProc)popdownProductDescriptionShell,
	    (XtPointer)productDescriptionShell);

	return(productDescriptionShell);
}
Exemple #26
0
/*
 * Create an RGB, double-buffered window.
 * Return the window and context handles.
 */
static void
make_window( Display *dpy, const char *name,
             int x, int y, int width, int height,
             Window *winRet, GLXContext *ctxRet)
{
   int attribs[] = { GLX_RGBA,
                     GLX_RED_SIZE, 1,
                     GLX_GREEN_SIZE, 1,
                     GLX_BLUE_SIZE, 1,
                     GLX_DOUBLEBUFFER,
                     GLX_DEPTH_SIZE, 1,
                     None };
   int stereoAttribs[] = { GLX_RGBA,
                           GLX_RED_SIZE, 1,
                           GLX_GREEN_SIZE, 1,
                           GLX_BLUE_SIZE, 1,
                           GLX_DOUBLEBUFFER,
                           GLX_DEPTH_SIZE, 1,
                           GLX_STEREO,
                           None };
   int scrnum;
   XSetWindowAttributes attr;
   unsigned long mask;
   Window root;
   Window win;
   GLXContext ctx;
   XVisualInfo *visinfo;

   scrnum = DefaultScreen( dpy );
   root = RootWindow( dpy, scrnum );

   if (fullscreen) {
      x = 0; y = 0;
      width = DisplayWidth( dpy, scrnum );
      height = DisplayHeight( dpy, scrnum );
   }

   if (stereo)
      visinfo = glXChooseVisual( dpy, scrnum, stereoAttribs );
   else
      visinfo = glXChooseVisual( dpy, scrnum, attribs );
   if (!visinfo) {
      if (stereo) {
         printf("Error: couldn't get an RGB, "
                "Double-buffered, Stereo visual\n");
      } else
         printf("Error: couldn't get an RGB, Double-buffered visual\n");
      exit(1);
   }

   /* window attributes */
   attr.background_pixel = 0;
   attr.border_pixel = 0;
   attr.colormap = XCreateColormap( dpy, root, visinfo->visual, AllocNone);
   attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask;
   /* XXX this is a bad way to get a borderless window! */
   mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;

   win = XCreateWindow( dpy, root, x, y, width, height,
		        0, visinfo->depth, InputOutput,
		        visinfo->visual, mask, &attr );

   if (fullscreen)
      no_border(dpy, win);

   /* set hints and properties */
   {
      XSizeHints sizehints;
      sizehints.x = x;
      sizehints.y = y;
      sizehints.width  = width;
      sizehints.height = height;
      sizehints.flags = USSize | USPosition;
      XSetNormalHints(dpy, win, &sizehints);
      XSetStandardProperties(dpy, win, name, name,
                              None, (char **)NULL, 0, &sizehints);
   }

   ctx = glXCreateContext( dpy, visinfo, NULL, True );
   if (!ctx) {
      printf("Error: glXCreateContext failed\n");
      exit(1);
   }

   XFree(visinfo);

   *winRet = win;
   *ctxRet = ctx;
}
Exemple #27
0
static int
glw_x11_init(glw_x11_t *gx11)
{
  int attribs[10];
  int na = 0;
  
  XInitThreads();

  int use_locales = XSupportsLocale() && XSetLocaleModifiers("") != NULL;

  if((gx11->display = XOpenDisplay(gx11->displayname_real)) == NULL) {
    TRACE(TRACE_ERROR, "GLW", "Unable to open X display \"%s\"\n",
	    gx11->displayname_real);
    return 1;
  }

  if(!glXQueryExtension(gx11->display, NULL, NULL)) {
    TRACE(TRACE_ERROR, "GLW", 
	  "OpenGL GLX extension not supported by display \"%s\"\n",
	    gx11->displayname_real);
    return 1;
  }


  gx11->screen        = DefaultScreen(gx11->display);
  gx11->screen_width  = DisplayWidth(gx11->display, gx11->screen);
  gx11->screen_height = DisplayHeight(gx11->display, gx11->screen);
  gx11->root          = RootWindow(gx11->display, gx11->screen);
 
  attribs[na++] = GLX_RGBA;
  attribs[na++] = GLX_RED_SIZE;
  attribs[na++] = 1;
  attribs[na++] = GLX_GREEN_SIZE;
  attribs[na++] = 1;
  attribs[na++] = GLX_BLUE_SIZE; 
  attribs[na++] = 1;
  attribs[na++] = GLX_DOUBLEBUFFER;
  attribs[na++] = None;
  
  gx11->xvi = glXChooseVisual(gx11->display, gx11->screen, attribs);

  if(gx11->xvi == NULL) {
    TRACE(TRACE_ERROR, "GLW", "Unable to find an adequate Visual on \"%s\"\n",
	    gx11->displayname_real);
    return 1;
  }
  
  if(GLXExtensionSupported(gx11->display, "GLX_SGI_swap_control")) {
    TRACE(TRACE_DEBUG, "GLW", "GLX_SGI_swap_control extension is present");
    gx11->glXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC)
      glXGetProcAddress((const GLubyte*)"glXSwapIntervalSGI");
  }

  build_blank_cursor(gx11);

  if(use_locales)
    gx11->im = XOpenIM(gx11->display, NULL, NULL, NULL);


  gx11->atom_deletewindow = 
    XInternAtom(gx11->display, "WM_DELETE_WINDOW", 0);

#if ENABLE_VDPAU
  if(GLXExtensionSupported(gx11->display, "GLX_EXT_texture_from_pixmap")) {

    gx11->gr.gr_be.gbr_bind_tex_image = (PFNGLXBINDTEXIMAGEEXTPROC)
      glXGetProcAddress((const GLubyte*)"glXBindTexImageEXT");

    gx11->gr.gr_be.gbr_release_tex_image = (PFNGLXRELEASETEXIMAGEEXTPROC)
      glXGetProcAddress((const GLubyte*)"glXReleaseTexImageEXT");

    gx11->gr.gr_be.gbr_vdpau_dev = vdpau_init_x11(gx11->display, gx11->screen,
						  vdpau_preempted, gx11);

  } else {
    TRACE(TRACE_DEBUG, "VDPAU", 
	  "GLX_EXT_texture_from_pixmap extension not present, disabling VDPAU");
  }
#endif

  probe_wm(gx11);


  gx11->is_fullscreen = gx11->want_fullscreen;

  int fs = 0;
  if(gx11->wm_flags == 0) {
    fs = 1; // No window manager, open in fullscreen mode
  } else {
    /* If window manager cannot do fullscreen, ask window to open 
       in fullscreen mode */
    fs = gx11->want_fullscreen && !(gx11->wm_flags & GX11_WM_CAN_FULLSCREEN);
  }

  if(window_open(gx11, fs))
    return -1;

  // Fullscreen via window manager
  if(gx11->want_fullscreen && !fs)
    wm_set_fullscreen(gx11, 1);

  return 0;
}
Exemple #28
0
int main(int argc, const char **argv) {
    /* process command line arguments */
    command_line(argc,argv);
    /* some ugly but needed initializations */
    XInitThreads();
    g_type_init();
    /* open X connection & create window */
    if (!(dpy= XOpenDisplay(NULL))) die("Failed opening X display\n");
    scr = DefaultScreen(dpy);
    root = RootWindow(dpy,scr);
    if (!sw) sw = DisplayWidth(dpy,scr);
    if (!sh) sh = DisplayHeight(dpy,scr);
    win = XCreateSimpleWindow(dpy,root,0,0,sw,sh,1,0,0);
    /* set attributes and map */
    XStoreName(dpy,win,"Slider");
    XSetWindowAttributes wa;
    wa.event_mask =  ExposureMask|KeyPressMask|ButtonPressMask|StructureNotifyMask;
    XChangeWindowAttributes(dpy,win,CWEventMask,&wa);
    XMapWindow(dpy, win);
    /* check for EWMH compliant WM */
    Atom type, NET_CHECK = XInternAtom(dpy,"_NET_SUPPORTING_WM_CHECK",False);
    Window *wins;
    int fmt;
    unsigned long after,nwins;
    XGetWindowProperty(dpy,root,NET_CHECK,0,UINT_MAX,False,XA_WINDOW,
                       &type,&fmt,&nwins,&after,(unsigned char**)&wins);
    if ( type == XA_WINDOW && nwins > 0 && wins[0] != None) netwm = True;
    else netwm = False;
    XFree(wins);
    /* set up Xlib graphics contexts */
    XGCValues val;
    XColor color;
    Colormap cmap = DefaultColormap(dpy,scr);
    /* black, background, default */
    val.foreground = BlackPixel(dpy,scr);
    gc = XCreateGC(dpy,root,GCForeground,&val);
    /* white, mute_white */
    val.foreground = WhitePixel(dpy,scr);
    wgc = XCreateGC(dpy,root,GCForeground,&val);
    /* dotted lines for loading slides in overview mode */
    XAllocNamedColor(dpy,cmap,colors[0],&color,&color);
    val.foreground = color.pixel;
    val.line_style = LineDoubleDash;
    lgc = XCreateGC(dpy,root,GCForeground|GCLineStyle,&val); /* lines */
    /* highlight box for slide overview */
    XAllocNamedColor(dpy,cmap,colors[1],&color,&color);
    val.foreground = color.pixel;
    val.line_width = 3;
    hgc = XCreateGC(dpy,root,GCForeground|GCLineWidth,&val);
    /* pixmap for overview */
    sorter.view = XCreatePixmap(dpy,root,sw,sh,DefaultDepth(dpy,scr));
    /* create cursor(s) */
    char curs_data = 0;
    Pixmap curs_map = XCreateBitmapFromData(dpy,win,&curs_data,1,1);
    invisible_cursor = XCreatePixmapCursor(dpy,curs_map,curs_map,&color,&color,0,0);
    XFreePixmap(dpy,curs_map);
    /* start rendering thread */
    pthread_t render_thread;
    pthread_create(&render_thread,NULL,render_all,NULL);
    /* wait for first frame to render */
    while (!first_page_rendered) usleep(50000);
    if (fullscreen_mode) {
        fullscreen_mode = ! fullscreen_mode;
        fullscreen(NULL);
    }
    XDefineCursor(dpy,win,invisible_cursor);
    /* main loop */
    draw(NULL);
    XEvent ev;
    running = True;
    if (autoplay && autoplaydelay > 0) {
        int fd, r;
        struct timeval tv;
        fd_set rfds;
        fd = ConnectionNumber(dpy);
        while (running) {
            memset(&tv,0,sizeof(tv));
            tv.tv_sec = autoplaydelay;
            FD_ZERO(&rfds);
            FD_SET(fd,&rfds);
            r = select(fd+1,&rfds,0,0,&tv);
            if (r == 0) move("down");
            while (XPending(dpy)) {
                XNextEvent(dpy,&ev);
                if (ev.type > 32) continue; /* workaround for cairo F(&* up. */
                if (handler[ev.type]) handler[ev.type](&ev);
            }
        }
    }
    else while ( running && ! XNextEvent(dpy, &ev) ) {
            if (ev.type > 32) continue; /* workaround for cairo F(&* up. */
            if (handler[ev.type]) handler[ev.type](&ev);
        }

    /* clean up */
    if (presenter_mode) {
        printf("SLIDER END\n");
        fflush(stdout);
    }
    if (show.rendered < show.count) { /* quiting before render thread ended */
        cancel_render = True;	/* give thread time to quit */
        usleep(250000);
    }
    int i;
    for (i = 0; i < show.rendered; i++)
        XFreePixmap(dpy,show.slide[i]);
    XFreePixmap(dpy,sorter.view);
    free(show.slide);
    free(uri);
    XCloseDisplay(dpy);
    return 0;
}
Exemple #29
0
void _glfwPlatformGetMonitorWorkarea(_GLFWmonitor* monitor, int* xpos, int* ypos, int* width, int* height)
{
    int areaX = 0, areaY = 0, areaWidth = 0, areaHeight = 0;

    if (_glfw.x11.randr.available && !_glfw.x11.randr.monitorBroken)
    {
        XRRScreenResources* sr;
        XRRCrtcInfo* ci;

        sr = XRRGetScreenResourcesCurrent(_glfw.x11.display, _glfw.x11.root);
        ci = XRRGetCrtcInfo(_glfw.x11.display, sr, monitor->x11.crtc);

        areaX = ci->x;
        areaY = ci->y;

        const XRRModeInfo* mi = getModeInfo(sr, ci->mode);

        if (ci->rotation == RR_Rotate_90 || ci->rotation == RR_Rotate_270)
        {
            areaWidth  = mi->height;
            areaHeight = mi->width;
        }
        else
        {
            areaWidth  = mi->width;
            areaHeight = mi->height;
        }

        XRRFreeCrtcInfo(ci);
        XRRFreeScreenResources(sr);
    }
    else
    {
        areaWidth  = DisplayWidth(_glfw.x11.display, _glfw.x11.screen);
        areaHeight = DisplayHeight(_glfw.x11.display, _glfw.x11.screen);
    }

    if (_glfw.x11.NET_WORKAREA && _glfw.x11.NET_CURRENT_DESKTOP)
    {
        Atom* extents = NULL;
        Atom* desktop = NULL;
        const unsigned long extentCount =
            _glfwGetWindowPropertyX11(_glfw.x11.root,
                                      _glfw.x11.NET_WORKAREA,
                                      XA_CARDINAL,
                                      (unsigned char**) &extents);

        if (_glfwGetWindowPropertyX11(_glfw.x11.root,
                                      _glfw.x11.NET_CURRENT_DESKTOP,
                                      XA_CARDINAL,
                                      (unsigned char**) &desktop) > 0)
        {
            if (extentCount >= 4 && *desktop < extentCount / 4)
            {
                const int globalX = extents[*desktop * 4 + 0];
                const int globalY = extents[*desktop * 4 + 1];
                const int globalWidth  = extents[*desktop * 4 + 2];
                const int globalHeight = extents[*desktop * 4 + 3];

                if (areaX < globalX)
                {
                    areaWidth -= globalX - areaX;
                    areaX = globalX;
                }

                if (areaY < globalY)
                {
                    areaHeight -= globalY - areaY;
                    areaY = globalY;
                }

                if (areaX + areaWidth > globalX + globalWidth)
                    areaWidth = globalX - areaX + globalWidth;
                if (areaY + areaHeight > globalY + globalHeight)
                    areaHeight = globalY - areaY + globalHeight;
            }
        }

        if (extents)
            XFree(extents);
        if (desktop)
            XFree(desktop);
    }

    if (xpos)
        *xpos = areaX;
    if (ypos)
        *ypos = areaY;
    if (width)
        *width = areaWidth;
    if (height)
        *height = areaHeight;
}