Exemplo n.º 1
0
// Check whether the running window manager is EWMH-compliant
//
static void detectEWMH(void)
{
    Window* windowFromRoot = NULL;
    Window* windowFromChild = NULL;

    // First we need a couple of atoms, which should already be there
    Atom supportingWmCheck =
        XInternAtom(_glfw.x11.display, "_NET_SUPPORTING_WM_CHECK", True);
    Atom wmSupported =
        XInternAtom(_glfw.x11.display, "_NET_SUPPORTED", True);
    if (supportingWmCheck == None || wmSupported == None)
        return;

    // Then we look for the _NET_SUPPORTING_WM_CHECK property of the root window
    if (_glfwGetWindowProperty(_glfw.x11.root,
                               supportingWmCheck,
                               XA_WINDOW,
                               (unsigned char**) &windowFromRoot) != 1)
    {
        if (windowFromRoot)
            XFree(windowFromRoot);
        return;
    }

    _glfwGrabXErrorHandler();

    // It should be the ID of a child window (of the root)
    // Then we look for the same property on the child window
    if (_glfwGetWindowProperty(*windowFromRoot,
                               supportingWmCheck,
                               XA_WINDOW,
                               (unsigned char**) &windowFromChild) != 1)
    {
        XFree(windowFromRoot);
        if (windowFromChild)
            XFree(windowFromChild);
        return;
    }

    _glfwReleaseXErrorHandler();

    // It should be the ID of that same child window
    if (*windowFromRoot != *windowFromChild)
    {
        XFree(windowFromRoot);
        XFree(windowFromChild);
        return;
    }

    XFree(windowFromRoot);
    XFree(windowFromChild);

    // We are now fairly sure that an EWMH-compliant window manager is running

    Atom* supportedAtoms;
    unsigned long atomCount;

    // Now we need to check the _NET_SUPPORTED property of the root window
    // It should be a list of supported WM protocol and state atoms
    atomCount = _glfwGetWindowProperty(_glfw.x11.root,
                                       wmSupported,
                                       XA_ATOM,
                                       (unsigned char**) &supportedAtoms);

    // See which of the atoms we support that are supported by the WM
    _glfw.x11.NET_WM_STATE =
        getSupportedAtom(supportedAtoms, atomCount, "_NET_WM_STATE");
    _glfw.x11.NET_WM_STATE_ABOVE =
        getSupportedAtom(supportedAtoms, atomCount, "_NET_WM_STATE_ABOVE");
    _glfw.x11.NET_WM_STATE_FULLSCREEN =
        getSupportedAtom(supportedAtoms, atomCount, "_NET_WM_STATE_FULLSCREEN");
    _glfw.x11.NET_WM_FULLSCREEN_MONITORS =
        getSupportedAtom(supportedAtoms, atomCount, "_NET_WM_FULLSCREEN_MONITORS");
    _glfw.x11.NET_WM_NAME =
        getSupportedAtom(supportedAtoms, atomCount, "_NET_WM_NAME");
    _glfw.x11.NET_WM_ICON_NAME =
        getSupportedAtom(supportedAtoms, atomCount, "_NET_WM_ICON_NAME");
    _glfw.x11.NET_WM_PID =
        getSupportedAtom(supportedAtoms, atomCount, "_NET_WM_PID");
    _glfw.x11.NET_WM_PING =
        getSupportedAtom(supportedAtoms, atomCount, "_NET_WM_PING");
    _glfw.x11.NET_ACTIVE_WINDOW =
        getSupportedAtom(supportedAtoms, atomCount, "_NET_ACTIVE_WINDOW");
    _glfw.x11.NET_FRAME_EXTENTS =
        getSupportedAtom(supportedAtoms, atomCount, "_NET_FRAME_EXTENTS");
    _glfw.x11.NET_REQUEST_FRAME_EXTENTS =
        getSupportedAtom(supportedAtoms, atomCount, "_NET_REQUEST_FRAME_EXTENTS");
    _glfw.x11.NET_WM_BYPASS_COMPOSITOR =
        getSupportedAtom(supportedAtoms, atomCount, "_NET_WM_BYPASS_COMPOSITOR");

    XFree(supportedAtoms);

    _glfw.x11.hasEWMH = GL_TRUE;
}
Exemplo n.º 2
0
Arquivo: main.c Projeto: dylex/dzen
static void
set_docking_ewmh_info(Display *dpy, Window w, int dock) {
	unsigned long strut[12] = { 0 };
	unsigned long strut_s[4] = { 0 };
	XWindowAttributes wa;
	Atom type;
	unsigned int desktop;
	pid_t cur_pid;
	char *host_name;
	XTextProperty txt_prop;
	XRectangle si;
#ifdef DZEN_XINERAMA
	XineramaScreenInfo *xsi;
	int screen_count,i,max_height;
#endif

	host_name = emalloc(HOST_NAME_MAX);
	if( (gethostname(host_name, HOST_NAME_MAX) > -1) &&
			(cur_pid = getpid()) ) {

		XStringListToTextProperty(&host_name, 1, &txt_prop);
		XSetWMClientMachine(dpy, w, &txt_prop);
		XFree(txt_prop.value);

		XChangeProperty(
				dpy,
				w,
				XInternAtom(dpy, "_NET_WM_PID", False),
				XInternAtom(dpy, "CARDINAL", False),
				32,
				PropModeReplace,
				(unsigned char *)&cur_pid,
				1
				);

	}
	free(host_name);


	XGetWindowAttributes(dpy, w, &wa);
#ifdef DZEN_XINERAMA
	queryscreeninfo(dpy,&si,dzen.xinescreen);
#else
	qsi_no_xinerama(dpy,&si);
#endif
	if(wa.y - si.y == 0) {
		strut[2] = si.y + wa.height;
		strut[8] = wa.x;
		strut[9] = wa.x + wa.width - 1;

		strut_s[2] = strut[2];
	}
	else if((wa.y - si.y + wa.height) == si.height) {
#ifdef DZEN_XINERAMA
		max_height = si.height;
		xsi = XineramaQueryScreens(dpy,&screen_count);
		for(i=0; i < screen_count; i++) {
			if(xsi[i].height > max_height)
				max_height = xsi[i].height;
		}
		XFree(xsi);
		/* Adjust strut value if there is a larger screen */ 
		strut[3] = max_height - (si.height + si.y) + wa.height;
#else
		strut[3] = wa.height;
#endif
		strut[10] = wa.x;
		strut[11] = wa.x + wa.width - 1;

		strut_s[3] = strut[3];
	}

	if(strut[2] != 0 || strut[3] != 0) {
		XChangeProperty(
				dpy,
				w,
				XInternAtom(dpy, "_NET_WM_STRUT_PARTIAL", False),
				XInternAtom(dpy, "CARDINAL", False),
				32,
				PropModeReplace,
				(unsigned char *)&strut,
				12
				);
		XChangeProperty(
				dpy,
				w,
				XInternAtom(dpy, "_NET_WM_STRUT", False),
				XInternAtom(dpy, "CARDINAL", False),
				32,
				PropModeReplace,
				(unsigned char *)&strut,
				4
				);
	}

	if(dock) {
		type = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DOCK", False);
		XChangeProperty(
				dpy,
				w,
				XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False),
				XInternAtom(dpy, "ATOM", False),
				32,
				PropModeReplace,
				(unsigned char *)&type,
				1
				);

		/* some window managers honor this properties*/
		type = XInternAtom(dpy, "_NET_WM_STATE_ABOVE", False);
		XChangeProperty(
				dpy,
				w,
				XInternAtom(dpy, "_NET_WM_STATE", False),
				XInternAtom(dpy, "ATOM", False),
				32,
				PropModeReplace,
				(unsigned char *)&type,
				1
				);

		type = XInternAtom(dpy, "_NET_WM_STATE_STICKY", False);
		XChangeProperty(
				dpy,
				w,
				XInternAtom(dpy, "_NET_WM_STATE", False),
				XInternAtom(dpy, "ATOM", False),
				32,
				PropModeAppend,
				(unsigned char *)&type,
				1
				);


		desktop = 0xffffffff;
		XChangeProperty(
				dpy,
				w,
				XInternAtom(dpy, "_NET_WM_DESKTOP", False),
				XInternAtom(dpy, "CARDINAL", False),
				32,
				PropModeReplace,
				(unsigned char *)&desktop,
				1
				);
	}

}
CXWindowsClipboard::CXWindowsClipboard(Display* display,
				Window window, ClipboardID id) :
	m_display(display),
	m_window(window),
	m_id(id),
	m_open(false),
	m_time(0),
	m_owner(false),
	m_timeOwned(0),
	m_timeLost(0)
{
	// get some atoms
	m_atomTargets         = XInternAtom(m_display, "TARGETS", False);
	m_atomMultiple        = XInternAtom(m_display, "MULTIPLE", False);
	m_atomTimestamp       = XInternAtom(m_display, "TIMESTAMP", False);
	m_atomInteger         = XInternAtom(m_display, "INTEGER", False);
	m_atomAtom            = XInternAtom(m_display, "ATOM", False);
	m_atomAtomPair        = XInternAtom(m_display, "ATOM_PAIR", False);
	m_atomData            = XInternAtom(m_display, "CLIP_TEMPORARY", False);
	m_atomINCR            = XInternAtom(m_display, "INCR", False);
	m_atomMotifClipLock   = XInternAtom(m_display, "_MOTIF_CLIP_LOCK", False);
	m_atomMotifClipHeader = XInternAtom(m_display, "_MOTIF_CLIP_HEADER", False);
	m_atomMotifClipAccess = XInternAtom(m_display,
								"_MOTIF_CLIP_LOCK_ACCESS_VALID", False);
	m_atomGDKSelection    = XInternAtom(m_display, "GDK_SELECTION", False);

	// set selection atom based on clipboard id
	switch (id) {
	case kClipboardClipboard:
		m_selection = XInternAtom(m_display, "CLIPBOARD", False);
		break;

	case kClipboardSelection:
	default:
		m_selection = XA_PRIMARY;
		break;
	}

	// add converters, most desired first
	m_converters.push_back(new CXWindowsClipboardHTMLConverter(m_display,
								"text/html"));
	m_converters.push_back(new CXWindowsClipboardBMPConverter(m_display));
	m_converters.push_back(new CXWindowsClipboardUTF8Converter(m_display,
								"text/plain;charset=UTF-8"));
	m_converters.push_back(new CXWindowsClipboardUTF8Converter(m_display,
								"UTF8_STRING"));
	m_converters.push_back(new CXWindowsClipboardUCS2Converter(m_display,
								"text/plain;charset=ISO-10646-UCS-2"));
	m_converters.push_back(new CXWindowsClipboardUCS2Converter(m_display,
								"text/unicode"));
	m_converters.push_back(new CXWindowsClipboardTextConverter(m_display,
								"text/plain"));
	m_converters.push_back(new CXWindowsClipboardTextConverter(m_display,
								"STRING"));

	// we have no data
	clearCache();
}
Exemplo n.º 4
0
void winwidget_create_window(winwidget ret, int w, int h)
{
	XSetWindowAttributes attr;
	XEvent ev;
	XClassHint *xch;
	MWMHints mwmhints;
	Atom prop = None;
	int x = 0;
	int y = 0;
	char *tmpname;

	D(("winwidget_create_window %dx%d\n", w, h));

	if (ret->full_screen) {
		w = scr->width;
		h = scr->height;

#ifdef HAVE_LIBXINERAMA
		if (opt.xinerama && xinerama_screens) {
			w = xinerama_screens[xinerama_screen].width;
			h = xinerama_screens[xinerama_screen].height;
			x = xinerama_screens[xinerama_screen].x_org;
			y = xinerama_screens[xinerama_screen].y_org;
		}
#endif				/* HAVE_LIBXINERAMA */
	} else if (opt.geom_flags) {
		if (opt.geom_flags & WidthValue) {
			w = opt.geom_w;
		}
		if (opt.geom_flags & HeightValue) {
			h = opt.geom_h;
		}
		if (opt.geom_flags & XValue) {
			if (opt.geom_flags & XNegative) {
				x = scr->width - opt.geom_x;
			} else {
				x = opt.geom_x;
			}
		}
		if (opt.geom_flags & YValue) {
			if (opt.geom_flags & YNegative) {
				y = scr->height - opt.geom_y;
			} else {
				y = opt.geom_y;
			}
		}
	} else if (opt.screen_clip) {
		if (w > scr->width)
			w = scr->width;
		if (h > scr->height)
			h = scr->height;

#ifdef HAVE_LIBXINERAMA
		if (opt.xinerama && xinerama_screens) {
			if (w > xinerama_screens[xinerama_screen].width)
				w = xinerama_screens[xinerama_screen].width;
			if (h > xinerama_screens[xinerama_screen].height)
				h = xinerama_screens[xinerama_screen].height;
		}
#endif				/* HAVE_LIBXINERAMA */
	}

	if (opt.paused) {
		printf("name %s\n", ret->name);
		tmpname = estrjoin(" ", ret->name, "[Paused]", NULL);
		free(ret->name);
		ret->name = tmpname;
	}

	ret->x = x;
	ret->y = y;
	ret->w = w;
	ret->h = h;
	ret->visible = False;

	attr.backing_store = NotUseful;
	attr.override_redirect = False;
	attr.colormap = cm;
	attr.border_pixel = 0;
	attr.background_pixel = 0;
	attr.save_under = False;
	attr.event_mask =
	    StructureNotifyMask | ButtonPressMask | ButtonReleaseMask |
	    PointerMotionMask | EnterWindowMask | LeaveWindowMask |
	    KeyPressMask | KeyReleaseMask | ButtonMotionMask | ExposureMask
	    | FocusChangeMask | PropertyChangeMask | VisibilityChangeMask;

	memset(&mwmhints, 0, sizeof(mwmhints));
	if (opt.borderless || ret->full_screen) {
		prop = XInternAtom(disp, "_MOTIF_WM_HINTS", True);
		if (prop == None) {
			weprintf
			    ("Window Manager does not support MWM hints. "
			     "To get a borderless window I have to bypass your wm.");
			attr.override_redirect = True;
			mwmhints.flags = 0;
		} else {
			mwmhints.flags = MWM_HINTS_DECORATIONS;
			mwmhints.decorations = 0;
		}
	}

	ret->win =
	    XCreateWindow(disp, DefaultRootWindow(disp), x, y, w, h, 0,
			  depth, InputOutput, vis,
			  CWOverrideRedirect | CWSaveUnder | CWBackingStore
			  | CWColormap | CWBackPixel | CWBorderPixel | CWEventMask, &attr);

	if (mwmhints.flags) {
		XChangeProperty(disp, ret->win, prop, prop, 32,
				PropModeReplace, (unsigned char *) &mwmhints, PROP_MWM_HINTS_ELEMENTS);
	}
	if (ret->full_screen) {
		Atom prop_fs = XInternAtom(disp, "_NET_WM_STATE_FULLSCREEN", False);
		Atom prop_state = XInternAtom(disp, "_NET_WM_STATE", False);

		memset(&ev, 0, sizeof(ev));
		ev.xclient.type = ClientMessage;
		ev.xclient.message_type = prop_state;
		ev.xclient.display = disp;
		ev.xclient.window = ret->win;
		ev.xclient.format = 32;
		ev.xclient.data.l[0] = 1;
		ev.xclient.data.l[1] = prop_fs;

		XChangeProperty(disp, ret->win, prop_state, XA_ATOM, 32,
				PropModeReplace, (unsigned char *) &prop_fs, 1);
	}

	XSetWMProtocols(disp, ret->win, &wmDeleteWindow, 1);
	winwidget_update_title(ret);
	xch = XAllocClassHint();
	xch->res_name = "feh";
	xch->res_class = "feh";
	XSetClassHint(disp, ret->win, xch);
	XFree(xch);

	/* Size hints */
	if (ret->full_screen || opt.geom_flags) {
		XSizeHints xsz;

		xsz.flags = USPosition;
		xsz.x = x;
		xsz.y = y;
		XSetWMNormalHints(disp, ret->win, &xsz);
		XMoveWindow(disp, ret->win, x, y);
	}
	if (opt.hide_pointer)
		winwidget_set_pointer(ret, 0);

	/* set the icon name property */
	XSetIconName(disp, ret->win, "feh");
	/* set the command hint */
	XSetCommand(disp, ret->win, cmdargv, cmdargc);

	winwidget_register(ret);
	return;
}
Exemplo n.º 5
0
void* ClassicUICreate(FcitxInstance* instance)
{
    FcitxAddon* classicuiaddon = FcitxAddonsGetAddonByName(FcitxInstanceGetAddons(instance), FCITX_CLASSIC_UI_NAME);
    FcitxClassicUI* classicui = fcitx_utils_malloc0(sizeof(FcitxClassicUI));
    classicui->owner = instance;
    if (!LoadClassicUIConfig(classicui)) {
        free(classicui);
        return NULL;
    }
    if (GetSkinDesc() == NULL) {
        free(classicui);
        return NULL;
    }
    classicui->dpy = FcitxX11GetDisplay(instance);
    if (classicui->dpy == NULL) {
        free(classicui);
        return NULL;
    }

    FcitxX11GetDPI(instance, &classicui->dpi, NULL);
    if (classicui->dpi <= 0)
        classicui->dpi = 96;

    if (LoadSkinConfig(&classicui->skin, &classicui->skinType)) {
        free(classicui);
        return NULL;
    }

    classicui->isfallback = FcitxUIIsFallback(instance, classicuiaddon);

    classicui->iScreen = DefaultScreen(classicui->dpy);

    classicui->protocolAtom = XInternAtom(classicui->dpy, "WM_PROTOCOLS", False);
    classicui->killAtom = XInternAtom(classicui->dpy, "WM_DELETE_WINDOW", False);


    InitSkinMenu(classicui);
    FcitxUIRegisterMenu(instance, &classicui->skinMenu);
    /* Main Menu Initial */
    FcitxMenuInit(&classicui->mainMenu);
    classicui->mainMenu.UpdateMenu = UpdateMainMenu;
    classicui->mainMenu.MenuAction = MainMenuAction;
    classicui->mainMenu.priv = classicui;
    classicui->mainMenu.mark = -1;


    classicui->inputWindow = CreateInputWindow(classicui);
    classicui->mainWindow = CreateMainWindow(classicui);
    classicui->trayWindow = CreateTrayWindow(classicui);
    classicui->messageWindow = CreateMessageWindow(classicui);
    classicui->mainMenuWindow = CreateMainMenuWindow(classicui);

    FcitxIMEventHook resethk;
    resethk.arg = classicui;
    resethk.func = ClassicUIInputReset;
    FcitxInstanceRegisterResetInputHook(instance, resethk);

    DisplaySkin(classicui, classicui->skinType);

    /* ensure order ! */
    FcitxModuleAddFunction(classicuiaddon, ClassicUILoadImage);
    FcitxModuleAddFunction(classicuiaddon, ClassicUIGetKeyBoardFontColor);
    FcitxModuleAddFunction(classicuiaddon, ClassicUIGetFont);

    return classicui;
}
Exemplo n.º 6
0
//----------------------------------------------------------------------------------------------------------------------
// tool_replay_mode
//----------------------------------------------------------------------------------------------------------------------
static bool tool_replay_mode()
{
    VOGL_FUNC_TRACER

    dynamic_string trace_filename(g_command_line_params().get_value_as_string_or_empty("", 1));
    if (trace_filename.is_empty())
    {
        vogl_error_printf("%s: No trace file specified!\n", VOGL_FUNCTION_INFO_CSTR);
        return false;
    }

    dynamic_string actual_trace_filename;
    vogl_unique_ptr<vogl_trace_file_reader> pTrace_reader(vogl_open_trace_file(
                trace_filename,
                actual_trace_filename,
                g_command_line_params().get_value_as_string_or_empty("loose_file_path").get_ptr()));
    if (!pTrace_reader.get())
    {
        vogl_error_printf("%s: File not found, or unable to determine file type of trace file \"%s\"\n", VOGL_FUNCTION_INFO_CSTR, trace_filename.get_ptr());
        return false;
    }

    vogl_printf("Reading trace file %s\n", actual_trace_filename.get_ptr());

    vogl_gl_replayer replayer;
    vogl_replay_window window;

    uint replayer_flags = get_replayer_flags_from_command_line_params();

    // TODO: This will create a window with default attributes, which seems fine for the majority of traces.
    // Unfortunately, some GL call streams *don't* want an alpha channel, or depth, or stencil etc. in the default framebuffer so this may become a problem.
    // Also, this design only supports a single window, which is going to be a problem with multiple window traces.
    if (!window.open(g_command_line_params().get_value_as_int("width", 0, 1024, 1, 65535), g_command_line_params().get_value_as_int("height", 0, 768, 1, 65535), g_command_line_params().get_value_as_int("msaa", 0, 0, 0, 65535)))
    {
        vogl_error_printf("%s: Failed initializing replay window\n", VOGL_FUNCTION_INFO_CSTR);
        return false;
    }

    if (!replayer.init(replayer_flags, &window, pTrace_reader->get_sof_packet(), pTrace_reader->get_multi_blob_manager()))
    {
        vogl_error_printf("%s: Failed initializing GL replayer\n", VOGL_FUNCTION_INFO_CSTR);
        return false;
    }

    // Disable all glGetError() calls in vogl_utils.cpp.
    vogl_disable_gl_get_error();

    XSelectInput(window.get_display(), window.get_xwindow(),
                 EnterWindowMask | LeaveWindowMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | ExposureMask | FocusChangeMask | KeyPressMask | KeyReleaseMask | PropertyChangeMask | StructureNotifyMask | KeymapStateMask);

    Atom wmDeleteMessage = XInternAtom(window.get_display(), "WM_DELETE_WINDOW", False);
    XSetWMProtocols(window.get_display(), window.get_xwindow(), &wmDeleteMessage, 1);

    // Bool win_mapped = false;

    vogl_gl_state_snapshot *pSnapshot = NULL;
    int64_t snapshot_loop_start_frame = -1;
    int64_t snapshot_loop_end_frame = -1;

    vogl::hash_map<uint64_t> keys_pressed, keys_down;

    int loop_frame = g_command_line_params().get_value_as_int("loop_frame", 0, -1);
    int loop_len = math::maximum<int>(g_command_line_params().get_value_as_int("loop_len", 0, 1), 1);
    int loop_count = math::maximum<int>(g_command_line_params().get_value_as_int("loop_count", 0, cINT32_MAX), 1);
    bool endless_mode = g_command_line_params().get_value_as_bool("endless");

    timer tm;
    tm.start();

    for (;;)
    {
        tmZone(TELEMETRY_LEVEL0, TMZF_NONE, "Main Loop");

        while (X11_Pending(window.get_display()))
        {
            XEvent newEvent;

            // Watch for new X eventsn
            XNextEvent(window.get_display(), &newEvent);

            switch (newEvent.type)
            {
                case KeyPress:
                {
                    KeySym xsym = XLookupKeysym(&newEvent.xkey, 0);

                    //printf("KeyPress 0%04llX %" PRIu64 "\n", (uint64_t)xsym, (uint64_t)xsym);

                    keys_down.insert(xsym);
                    keys_pressed.insert(xsym);

                    break;
                }
                case KeyRelease:
                {
                    KeySym xsym = XLookupKeysym(&newEvent.xkey, 0);

                    //printf("KeyRelease 0x%04llX %" PRIu64 "\n", (uint64_t)xsym, (uint64_t)xsym);

                    keys_down.erase(xsym);

                    break;
                }
                case FocusIn:
                case FocusOut:
                {
                    //printf("FocusIn/FocusOut\n");

                    keys_down.reset();

                    break;
                }
                case MappingNotify:
                {
                    //XRefreshKeyboardMapping(&newEvent);
                    break;
                }
                case UnmapNotify:
                {
                    // printf("UnmapNotify\n");
                    // win_mapped = false;

                    keys_down.reset();

                    break;
                }
                case MapNotify:
                {
                    // printf("MapNotify\n");
                    // win_mapped = true;

                    keys_down.reset();

                    if (!replayer.update_window_dimensions())
                        goto error_exit;

                    break;
                }
                case ConfigureNotify:
                {
                    if (!replayer.update_window_dimensions())
                        goto error_exit;

                    break;
                }
                case DestroyNotify:
                {
                    vogl_message_printf("Exiting\n");
                    goto normal_exit;
                }
                case ClientMessage:
                {
                    if (newEvent.xclient.data.l[0] == (int)wmDeleteMessage)
                    {
                        vogl_message_printf("Exiting\n");
                        goto normal_exit;
                    }

                    break;
                }
                default:
                    break;
            }
        }

        if (replayer.get_at_frame_boundary())
        {
            if ((!pSnapshot) && (loop_frame != -1) && (static_cast<int64_t>(replayer.get_frame_index()) == loop_frame))
            {
                vogl_debug_printf("%s: Capturing replayer state at start of frame %u\n", VOGL_FUNCTION_INFO_CSTR, replayer.get_frame_index());

                pSnapshot = replayer.snapshot_state();

                if (pSnapshot)
                {
                    vogl_printf("Snapshot succeeded\n");

                    snapshot_loop_start_frame = pTrace_reader->get_cur_frame();
                    snapshot_loop_end_frame = pTrace_reader->get_cur_frame() + loop_len;

                    vogl_debug_printf("%s: Loop start: %" PRIi64 " Loop end: %" PRIi64 "\n", VOGL_FUNCTION_INFO_CSTR, snapshot_loop_start_frame, snapshot_loop_end_frame);
                }
                else
                {
                    vogl_error_printf("Snapshot failed!\n");
                    loop_frame = -1;
                }
            }
        }

        vogl_gl_replayer::status_t status = replayer.process_pending_window_resize();
        if (status == vogl_gl_replayer::cStatusOK)
        {
            for (;;)
            {
                status = replayer.process_next_packet(*pTrace_reader);

                if ((status == vogl_gl_replayer::cStatusNextFrame) ||
                    (status == vogl_gl_replayer::cStatusResizeWindow) ||
                    (status == vogl_gl_replayer::cStatusAtEOF) ||
                    (status == vogl_gl_replayer::cStatusHardFailure))
                {
                    break;
                }
            }
        }

        if (status == vogl_gl_replayer::cStatusHardFailure)
            break;

        if (status == vogl_gl_replayer::cStatusAtEOF)
        {
            vogl_message_printf("%s: At trace EOF, frame index %u\n", VOGL_FUNCTION_INFO_CSTR, replayer.get_frame_index());
        }

        if (replayer.get_at_frame_boundary() &&
                pSnapshot && 
                (loop_count > 0) &&
                ((pTrace_reader->get_cur_frame() == snapshot_loop_end_frame) || (status == vogl_gl_replayer::cStatusAtEOF)))
        {
            status = replayer.begin_applying_snapshot(pSnapshot, false);
            if ((status != vogl_gl_replayer::cStatusOK) && (status != vogl_gl_replayer::cStatusResizeWindow))
                goto error_exit;

            pTrace_reader->seek_to_frame(static_cast<uint>(snapshot_loop_start_frame));

            vogl_debug_printf("%s: Applying snapshot and seeking back to frame %" PRIi64 "\n", VOGL_FUNCTION_INFO_CSTR, snapshot_loop_start_frame);
            loop_count--;
        }
        else
        {
            bool print_progress = (status == vogl_gl_replayer::cStatusAtEOF) ||
                    ((replayer.get_at_frame_boundary()) && ((replayer.get_frame_index() % 100) == 0));
            if (print_progress)
            {
                if (pTrace_reader->get_type() == cBINARY_TRACE_FILE_READER)
                {
                    vogl_binary_trace_file_reader &binary_trace_reader = *static_cast<vogl_binary_trace_file_reader *>(pTrace_reader.get());

                    vogl_printf("Replay now at frame index %u, trace file offet %" PRIu64 ", GL call counter %" PRIu64 ", %3.2f%% percent complete\n",
                               replayer.get_frame_index(),
                               binary_trace_reader.get_cur_file_ofs(),
                               replayer.get_last_parsed_call_counter(),
                               binary_trace_reader.get_trace_file_size() ? (binary_trace_reader.get_cur_file_ofs() * 100.0f) / binary_trace_reader.get_trace_file_size() : 0);
                }
            }

            if (status == vogl_gl_replayer::cStatusAtEOF)
            {
                if (!endless_mode)
                {
                    double time_since_start = tm.get_elapsed_secs();

                    vogl_printf("%u total swaps, %.3f secs, %3.3f avg fps\n", replayer.get_total_swaps(), time_since_start, replayer.get_frame_index() / time_since_start);
                    break;
                }

                vogl_printf("Resetting state and rewinding back to frame 0\n");

                replayer.reset_state();

                if (!pTrace_reader->seek_to_frame(0))
                {
                    vogl_error_printf("%s: Failed rewinding trace reader!\n", VOGL_FUNCTION_INFO_CSTR);
                    goto error_exit;
                }
            }
        }

        telemetry_tick();
    }

normal_exit:
    return true;

error_exit:
    return false;
}
Exemplo n.º 7
0
/**
 * Try to figure out if we have a window manager and query some of its
 * capabilities
 */
static void
probe_wm(glw_x11_t *gx11)
{
  int i, format;
  Atom *items, type;
  unsigned long bytes_after, r, nitems;
  unsigned char *prop_return;
  int wm_window_id;
  char *wm_name;

  Atom NET_SUPPORTED =
    XInternAtom(gx11->display, "_NET_SUPPORTED", 0);
  Atom STATE_FS =
    XInternAtom(gx11->display, "_NET_WM_STATE_FULLSCREEN", 0);
  Atom NET_SUPPORTING_WM_CHECK =
    XInternAtom(gx11->display, "_NET_SUPPORTING_WM_CHECK", 0);
  Atom NET_WM_NAME =
    XInternAtom(gx11->display, "_NET_WM_NAME", 0);

  if(XGetWindowProperty(gx11->display, gx11->root, NET_SUPPORTING_WM_CHECK,
			0, 16384, False, AnyPropertyType, &type, &format, &r,
			&bytes_after, &prop_return) != Success ||
     r == 0 || prop_return == NULL) {
    TRACE(TRACE_INFO, "GLW",
	  "No window manager found (NET_SUPPORTING_WM_CHECK not set)");
    return;
  }


  wm_window_id = *(int *)prop_return;
  XFree(prop_return);
  prop_return = NULL;

  if(XGetWindowProperty(gx11->display, wm_window_id, NET_WM_NAME,
			0, 16384, False, AnyPropertyType, &type, &format, &r,
			&bytes_after, &prop_return) != Success || 
     r == 0 || prop_return == NULL) {
    TRACE(TRACE_INFO, "GLW",
	  "No window manager found (NET_WM_NAME not set on wm window)");
    return;
  }

  wm_name = mystrdupa((char *)prop_return);
  XFree(prop_return);
  prop_return = NULL;

  if(XGetWindowProperty(gx11->display, gx11->root, NET_SUPPORTED,
			0, 16384, False, AnyPropertyType, &type, &format,
			&nitems, &bytes_after, &prop_return) != Success ||
     r == 0 || prop_return == NULL) {
    TRACE(TRACE_INFO, "GLW",
	  "No window manager found (NET_SUPPORTING_WM_CHECK not set)");
    return;
  }

  items = (Atom *)prop_return;

  gx11->wm_flags |= GX11_WM_DETECTED;

  for(i = 0; i < nitems; i++) {
    if(items[i] == STATE_FS)
      gx11->wm_flags |= GX11_WM_CAN_FULLSCREEN;
  }

  TRACE(TRACE_DEBUG, "GLW", "Window manager (%s) detected%s",
	wm_name,
	gx11->wm_flags & GX11_WM_CAN_FULLSCREEN ? ", can fullscreen" : "");

  prop_set_string(prop_create(gx11->gr.gr_uii.uii_prop, "windowmanager"),
		  wm_name);

  XFree(prop_return);
}
Exemplo n.º 8
0
int main(int argc, char* argv[]) 
{

  char *orpg_build_str; 

  Atom WM_DELETE_WINDOW;

/*   char *charval=NULL; */


int standalone_flag = FALSE;


/*    if((charval = getenv("STANDALONE_CVG")) != NULL)  */
/*        standalone_flag = TRUE; */
/*    else  */
/*        standalone_flag = FALSE; */



#ifdef LITTLE_ENDIAN_MACHINE
    fprintf(stderr, "\nThis CVG binary was compiled for the PC Linux Platform.\n");
#else
    fprintf(stderr, "\nThis CVG binary was compiled for the Solaris Sparc Platform.\n");
#endif



#ifdef LIB_LINK_STATIC
standalone_flag = TRUE;
#endif

#ifdef LIB_LINK_DYNAMIC
standalone_flag = FALSE;
#endif


  /* check presence of required libraries    */
  /* function has some dependency on cvg.mak */
  check_libraries(standalone_flag);

  init_prefs();
                                                  
  fprintf(stderr,"CVG START - FINISHED INITIALIZING PREFERENCES\n");


  if(standalone_flag == TRUE) {
      use_cvg_list_flag = prev_cvg_list_flag = TRUE;                
  } else {
      use_cvg_list_flag = prev_cvg_list_flag = FALSE;
  } 
  write_descript_source(use_cvg_list_flag);




  /*  should be moved to preferences!! */
  if((orpg_build_str = getenv("CV_ORPG_BUILD")) == NULL) {
        orpg_build_i = CVG_DEFAULT_BUILD;
        printf("Variable CV_ORPG_BUILD is not set.  CVG assumes default build %d\n", orpg_build_i);
  } else {
        orpg_build_i = atoi(orpg_build_str);  
        printf("CVG using variable CV_ORPG_BUILD to set ORPG Build to %d\n", orpg_build_i); 
  }
  write_orpg_build(orpg_build_i);



  shell = XtAppInitialize(&app,"CVG.RESOURCE",NULL,0,&argc,argv,fallbacks,
                             NULL,0);

  /* intercept the normal window menu 'Close' function */
  XtVaSetValues(shell, XmNdeleteResponse, XmDO_NOTHING, NULL);
  WM_DELETE_WINDOW = XInternAtom ( XtDisplay(shell), "WM_DELETE_WINDOW", FALSE );
  XmAddWMProtocolCallback ( shell, WM_DELETE_WINDOW, exit_callback, NULL );


/* set attrribute so radio buttons are always round */
/*  REQUIRED ON LINUX */
XtVaSetValues(XmGetXmDisplay(XtDisplay(shell)),
     XmNenableToggleVisual,     TRUE,
     NULL);


  
  XtVaSetValues(shell, 
		XmNtitle,  CVG_VERSION_STRING, 


#ifdef SUNOS
                XmNwidth,  615,
                XmNheight, 560,
#endif
#ifdef LINUX
                XmNwidth,  610,
                XmNheight, 570,
#endif


        XmNmwmDecorations,    MWM_DECOR_BORDER^MWM_DECOR_MINIMIZE^MWM_DECOR_TITLE^MWM_DECOR_MENU,
/*  limit available window functions */
        XmNmwmFunctions,      MWM_FUNC_CLOSE^MWM_FUNC_MINIMIZE^MWM_FUNC_MOVE,

        XmNx,         10,
        XmNy,         5, 

/* LINUX KDE ISSUE -  it wouold be convenient to allow the
   applicaion shell to be sized by the widgets by
       a. not specifying an initial size for the shell
       b. setting XmNallowShellResize to TRUE BEFORE widgets are managed
   however when using a SelectionBox with the application shell
   on Linux, KDE crashes when no ititial size is specified for the shell
*/
/*Also, when specifying an initial size for the application shell
    a warning that DialogStype should be XmDIALOG_MODELESS is provided
*/
/* Note: a combination of
       a. Initial size specified for shell
       b. setting XmNallowShellResize to TRUE AFTER managing all widgets
   results in the initial movement of the window, three row selection
   list, and a problem displaying all wigets
*/

/* XmNallowShellResize, TRUE, */
		NULL);
 

  XtRealizeWidget(shell);


  init_globals();
                                                
  fprintf(stderr,"CVG START - FINISHED INITIALIZING GLOBAL DATA\n");  
  
  load_prefs();


  /* CVG 9.1 - erase existing cvg product list to avoid potential problems */
  sprintf(list_fname, "%s/cvg_db_list.lb", config_dir); 
  if(stat(list_fname, &db_list_stat) == 0) {
    res = remove(list_fname);
    fprintf(stderr,"Removed existing cvg product list\n");
  }


  fprintf(stderr,"CVG START - FINISHED LOADING PREFERENCES\n");


/* /// CODE FOR BACKGROUND TASK /////// */

  new_pid = fork();

  switch(new_pid) {
    
      case  -1:  /* Error */
           perror("fork failed");
           exit(1);    
      case  0:  /* child */
         { /*  begin child block */
        
/*  future exec'd executable */
           execlp("cvg_read_db", "cvg_read_db", (char *)0);
/*             read_db(); */
            
         } /*  end child block */
           break;
      default:  /* parent */ 

      fprintf(stderr,"CVG START - READ_DATABASE PROCESS STARTED, PID=%d\n",
                        (int) new_pid);


                        
      init_db_prod_list();
/* DEBUG */
/* fprintf(stderr,"DEBUG CVG START - finished init_db_prod_list\n"); */
          
      setup_gui_display(); 
/* DEBUG */
/* fprintf(stderr,"DEBUG CVG START - finished setup_gui_display\n"); */

      XtAppAddTimeOut(app, 5000, build_list, NULL);          
          
      XtAppMainLoop(app);
    
  } /*  end switch */



/* ///////////////////////////////////////// */

/*   XtAppMainLoop(app); */

  return 0;
}
Exemplo n.º 9
0
int main () {
  Display   *display;
  Window     win;
  XEvent     report;
  Atom       _request, _extents, _type, _normal, _desktop;
  XEvent     msg;
  int        x=10,y=10,h=100,w=400;

  display = XOpenDisplay(NULL);

  if (display == NULL) {
    fprintf(stderr, "couldn't connect to X server :0\n");
    return 0;
  }

  _type = XInternAtom(display, "_NET_WM_WINDOW_TYPE", False);
  _normal = XInternAtom(display, "_NET_WM_WINDOW_TYPE_NORMAL", False);
  _desktop = XInternAtom(display, "_NET_WM_WINDOW_TYPE_DESKTOP", False);
  _request = XInternAtom(display, "_NET_REQUEST_FRAME_EXTENTS", False);
  _extents = XInternAtom(display, "_NET_FRAME_EXTENTS", False);

  win = XCreateWindow(display, RootWindow(display, 0),
		      x, y, w, h, 10, CopyFromParent, CopyFromParent,
		      CopyFromParent, 0, NULL);
  XSelectInput(display, win, PropertyChangeMask);

  printf("requesting for type normal\n");
  XChangeProperty(display, win, _type, XA_ATOM, 32,
                  PropModeReplace, (unsigned char*)&_normal, 1);
  msg.xclient.type = ClientMessage;
  msg.xclient.message_type = _request;
  msg.xclient.display = display;
  msg.xclient.window = win;
  msg.xclient.format = 32;
  msg.xclient.data.l[0] = 0l;
  msg.xclient.data.l[1] = 0l;
  msg.xclient.data.l[2] = 0l;
  msg.xclient.data.l[3] = 0l;
  msg.xclient.data.l[4] = 0l;
  XSendEvent(display, RootWindow(display, 0), False,
             SubstructureNotifyMask | SubstructureRedirectMask, &msg);
  XFlush(display);

  printf("waiting for extents\n");
  while (1) {
    XNextEvent(display, &report);

    if (report.type == PropertyNotify &&
        report.xproperty.atom == _extents)
    {
        Atom ret_type;
        int ret_format;
        unsigned long ret_items, ret_bytesleft;
        unsigned long *prop_return;
        XGetWindowProperty(display, win, _extents, 0, 4,
                           False, XA_CARDINAL, &ret_type, &ret_format,
                           &ret_items, &ret_bytesleft,
                           (unsigned char**) &prop_return);
        if (ret_type == XA_CARDINAL && ret_format == 32 && ret_items == 4)
            printf("got new extents %d, %d, %d, %d\n",
                   prop_return[0], prop_return[1], prop_return[2],
                   prop_return[3]);
        break;
    }
  }

  printf("requesting for type desktop\n");
  XChangeProperty(display, win, _type, XA_ATOM, 32,
                  PropModeReplace, (unsigned char*)&_desktop, 1);
  msg.xclient.type = ClientMessage;
  msg.xclient.message_type = _request;
  msg.xclient.display = display;
  msg.xclient.window = win;
  msg.xclient.format = 32;
  msg.xclient.data.l[0] = 0l;
  msg.xclient.data.l[1] = 0l;
  msg.xclient.data.l[2] = 0l;
  msg.xclient.data.l[3] = 0l;
  msg.xclient.data.l[4] = 0l;
  XSendEvent(display, RootWindow(display, 0), False,
	     SubstructureNotifyMask | SubstructureRedirectMask, &msg);
  XFlush(display);

  printf("waiting for extents\n");
  while (1) {
    XNextEvent(display, &report);

    if (report.type == PropertyNotify &&
        report.xproperty.atom == _extents)
    {
        Atom ret_type;
        int ret_format;
        unsigned long ret_items, ret_bytesleft;
        unsigned long *prop_return;
        XGetWindowProperty(display, win, _extents, 0, 4,
                           False, XA_CARDINAL, &ret_type, &ret_format,
                           &ret_items, &ret_bytesleft,
                           (unsigned char**) &prop_return);
        if (ret_type == XA_CARDINAL && ret_format == 32 && ret_items == 4)
            printf("got new extents %d, %d, %d, %d\n",
                   prop_return[0], prop_return[1], prop_return[2],
                   prop_return[3]);
        break;
    }
  }

  return 1;
}
Exemplo n.º 10
0
Arquivo: fsm.c Projeto: krazeivan/fvwm
/*
 * proxy stuff
 */
static
char *GetClientID(Display *dpy, Window window)
{
	char *client_id = NULL;
	Window client_leader = None;
	XTextProperty tp;
	Atom actual_type;
	int actual_format;
	unsigned long nitems;
	unsigned long bytes_after;
	unsigned char *prop = NULL;

	if (!SessionSupport)
	{
		return NULL;
	}

	if (!_XA_WM_CLIENT_LEADER)
	{
		_XA_WM_CLIENT_LEADER = XInternAtom(
			dpy, "WM_CLIENT_LEADER", False);
	}
	if (!_XA_SM_CLIENT_ID)
	{
		_XA_SM_CLIENT_ID = XInternAtom(dpy, "SM_CLIENT_ID", False);
	}

	if (XGetWindowProperty(
		    dpy, window, _XA_WM_CLIENT_LEADER, 0L, 1L, False,
		    AnyPropertyType, &actual_type, &actual_format, &nitems,
		    &bytes_after, &prop) == Success)
	{
		if (actual_type == XA_WINDOW && actual_format == 32 &&
		    nitems == 1 && bytes_after == 0)
		{
			client_leader = (Window)(*(long *)prop);
		}
	}

	if (!client_leader)
	{
		client_leader = window;
	}

	if (client_leader)
	{
		if (XGetTextProperty(dpy, client_leader, &tp, _XA_SM_CLIENT_ID))
		{
			if (tp.encoding == XA_STRING && tp.format == 8 &&
			    tp.nitems != 0)
			{
				client_id = (char *) tp.value;
			}
		}
	}

	if (prop)
	{
		XFree (prop);
	}

	return client_id;
}
Exemplo n.º 11
0
Arquivo: fsm.c Projeto: krazeivan/fvwm
static
void set_session_manager(Display *dpy, Window window, char *sm)
{
	Window client_leader = None;
	Atom actual_type;
	int actual_format;
	unsigned long nitems;
	unsigned long bytes_after;
	unsigned char *prop = NULL;
	char *dummy_id;
	static Atom _XA_SESSION_MANAGER = None;

	if (!SessionSupport)
	{
		return;
	}

	dummy_id = "0";

	if (!_XA_SESSION_MANAGER)
	{
		_XA_SESSION_MANAGER = XInternAtom (
			dpy, "SESSION_MANAGER", False);
	}
	if (!_XA_WM_CLIENT_LEADER)
	{
		_XA_WM_CLIENT_LEADER = XInternAtom(
			dpy, "WM_CLIENT_LEADER", False);
	}
	if (!_XA_SM_CLIENT_ID)
	{
		_XA_SM_CLIENT_ID = XInternAtom(dpy, "SM_CLIENT_ID", False);
	}

	if (XGetWindowProperty(
		    dpy, window, _XA_WM_CLIENT_LEADER, 0L, 1L, False,
		    AnyPropertyType, &actual_type, &actual_format, &nitems,
		    &bytes_after, &prop) == Success)
	{
		if (actual_type == XA_WINDOW && actual_format == 32 &&
		    nitems == 1 && bytes_after == 0)
		{
			client_leader = (Window)(*(long *)prop);
		}
	}

	if (!client_leader)
	{
		client_leader = window;
	}

#ifdef FVWM_DEBUG_FSM
	fprintf(
		stderr, "[%s][fsm_init] Proxy %s window 0x%lx\n",
		module_name, (sm)? "On":"Off", client_leader);

#endif

	/* set the client id for ksmserver */
	if (sm)
	{
		XChangeProperty(
			dpy, client_leader, _XA_SESSION_MANAGER, XA_STRING,
			8, PropModeReplace, (unsigned char *)sm, strlen(sm));
		XChangeProperty(
			dpy, client_leader, _XA_SM_CLIENT_ID, XA_STRING,
			8, PropModeReplace, (unsigned char *)dummy_id,
			strlen(dummy_id));
	}
	else
	{
		XDeleteProperty(dpy, client_leader, _XA_SESSION_MANAGER);
		XDeleteProperty(dpy, client_leader, _XA_SM_CLIENT_ID);
	}
}
Exemplo n.º 12
0
bool OpenGLApp::initAPI(){
	PixelFormat pf;
	initPixelFormat(pf);
	selectPixelFormat(pf);

	int iAttribs[256] = {
		GLX_RGBA,
		GLX_DOUBLEBUFFER,
		GLX_RED_SIZE,     pf.redBits,
		GLX_GREEN_SIZE,   pf.greenBits,
		GLX_BLUE_SIZE,    pf.blueBits,
		GLX_ALPHA_SIZE,   pf.alphaBits,
		GLX_DEPTH_SIZE,   pf.depthBits,
		GLX_STENCIL_SIZE, pf.stencilBits,
		GLX_ACCUM_RED_SIZE,   pf.accumBits / 4,
		GLX_ACCUM_GREEN_SIZE, pf.accumBits / 4,
		GLX_ACCUM_BLUE_SIZE,  pf.accumBits / 4,
		GLX_ACCUM_ALPHA_SIZE, pf.accumBits / 4,
	};

	XVisualInfo *vi;
	while (true){
		int *iAtt = iAttribs + 22;
		if (/*GLX_ARB_multisample_supported && */pf.fsaaLevel > 0){
			*iAtt++ = 100000;
			*iAtt++ = GL_TRUE;

			*iAtt++ = 100001;
			*iAtt++ = pf.fsaaLevel;
		}

		*iAtt++ = None;

		vi = glXChooseVisual(display, screen, iAttribs);
		if (vi == NULL){
			if (pf.fsaaLevel > 0){
				pf.fsaaLevel -= 2;
			} else {
				printf("Error: Couldn't set visual\n");
				return false;
			}
		} else break;
	}


	int x, y, w, h;
	if (fullscreen){
		x = 0;
		y = 0;
		w = fullscreenWidth;
		h = fullscreenHeight;
	} else {
		x = windowedLeft;
		y = windowedTop;
		w = windowedRight - windowedLeft;
		h = windowedBottom - windowedTop;
	}
	middleX = w / 2;
	middleY = h / 2;

    ctx = glXCreateContext(display, vi, 0, GL_TRUE);


	XSetWindowAttributes attr;
	attr.colormap = XCreateColormap(display, RootWindow(display, screen), vi->visual, AllocNone);

	attr.border_pixel = 0;
	attr.override_redirect = fullscreen;
    attr.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask;

	window = XCreateWindow(display, RootWindow(display, vi->screen),
			x, y, w, h, 0, vi->depth, InputOutput, vi->visual,
			CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect, &attr);

	if (!fullscreen){
	    Atom wmDelete;
        wmDelete = XInternAtom(display, "WM_DELETE_WINDOW", True);
        XSetWMProtocols(display, window, &wmDelete, 1);
		char *title = "OpenGL";
        XSetStandardProperties(display, window, title, title, None, NULL, 0, NULL);
	}
    XMapRaised(display, window);

	Pixmap blank;
	XColor dummy;
	char data = 0;

	// Create a blank cursor for cursor hiding
	blank = XCreateBitmapFromData(display, window, &data, 1, 1);
	blankCursor = XCreatePixmapCursor(display, blank, blank, &dummy, &dummy, 0, 0);
	XFreePixmap(display, blank);


	XGrabKeyboard(display, window, True, GrabModeAsync, GrabModeAsync, CurrentTime);
	//if (captureMouse) showCursor(false);//XGrabPointer(display, window, True, ButtonPressMask, GrabModeAsync, GrabModeAsync, window, blankCursor, CurrentTime);
	cursorVisible = true;


    glXMakeCurrent(display, window, ctx);

	//printf((char *) glXGetClientString(display, GLX_EXTENSIONS));


	initExtensions(display, screen);

	// Set some of my preferred defaults
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
	glFrontFace(GL_CW);

	if (/*GLX_ARB_multisample_supported && */pf.fsaaLevel > 0){
		glEnable(GL_MULTISAMPLE_ARB);
	}

	renderer = new OpenGLRenderer(ctx, display, screen);

//	renderer->setAnisotropic(anisotropic);

	return true;
}
Exemplo n.º 13
0
int xv_init( xv_handle_t handle, Display *dpy, __u32 fourcc, int width, int height, int bpp )
{
	unsigned int version, release;
	unsigned int request_base, event_base, error_base;
	
	int i;

	if( XvQueryExtension( dpy, &version, &release, &request_base, &event_base, &error_base ) != Success )
	{
#ifdef DEBUG
		fprintf( stderr, "XvQueryExtension failed\n" );
#endif
		return -1;
	}
	
	if( XvQueryAdaptors( dpy, DefaultRootWindow( dpy ), &handle->num_adaptors, &handle->p_adaptor_info ) != Success )
	{
#ifdef DEBUG
		fprintf( stderr, "XvQueryAdaptors failed\n" );
#endif
		return -1;
	}

/* 	printf( "%d adaptors found\n", handle->num_adaptors ); */
	
	if( handle->num_adaptors == 0 )
	{
		return -2;
	}
	

	for( i = 0; i < handle->num_adaptors; i++ )
	{
/* 		int format; */
		unsigned int num_encodings;
		XvEncodingInfo *p_encoding_info;
		int encoding;

		XvAttribute *at;
		unsigned int num_attributes;
		int attribute;

		XvImageFormatValues *xvimage_formats;
		unsigned int num_xvimage_formats;
		int format;
		

#ifdef DEBUG
		printf( "Adaptor: %d\n", i );
		printf( "Name: %s\n", handle->p_adaptor_info[i].name );
		printf( "Ports: %lu\n", handle->p_adaptor_info[i].num_ports );
		printf( "Formats: %lu\n", handle->p_adaptor_info[i].num_formats );
		
		for( format = 0; format < handle->p_adaptor_info[i].num_formats; format++ )
		{
			printf( "+Format: %d\n", format );
			printf( " +Depth: %d\n", handle->p_adaptor_info[i].formats[format].depth );
			printf( " +VisualID: %lu\n", handle->p_adaptor_info[i].formats[format].visual_id );
		}

			
		if( XvQueryEncodings( dpy, handle->p_adaptor_info[i].base_id, &num_encodings, &p_encoding_info ) != Success )
		{
			fprintf( stderr, "XvQueryEncodings failed\n" );
		}
		printf( " +num_encodings: %d\n", num_encodings );
		
		for( encoding = 0; encoding < num_encodings; encoding++ )
		{
			printf( "  +Encoding: %d\n", encoding );
			printf( "  +Name: %s\n", p_encoding_info[encoding].name );
			printf( "  +Resolution: %lu x %lu\n", 
					p_encoding_info[encoding].width, 
					p_encoding_info[encoding].height );
		}
#endif //DEBUG

		at = XvQueryPortAttributes( dpy, handle->p_adaptor_info[i].base_id, &num_attributes );
#ifdef DEBUG
		printf( "num_attributes: %d\n", num_attributes );
#endif
		for( attribute = 0; attribute < num_attributes; attribute++ )
		{
			int val;
			Atom atom;
			
			if( !strcmp( at[attribute].name, "XV_COLORKEY" ) )
			{
#ifdef DEBUG
				printf( "attribute: %d\n", attribute );
				printf( "name: %s\n", at[attribute].name );
#endif
				atom = (Atom)XInternAtom( dpy, at[attribute].name, 0 );
#ifdef DEBUG
				printf( "atom: %p\n", atom );
#endif
				XvGetPortAttribute( dpy, 
									handle->p_adaptor_info[i].base_id, 
									atom, 
									&val );
#ifdef DEBUG
				printf( "Attribute: %d\n", attribute );
				printf( "Name: %s\n", at[attribute].name );
				printf( "min: %x\n", at[attribute].min_value );
				printf( "max: %x\n", at[attribute].max_value );
				printf( "value: %x\n", val );
#endif
				handle->atom_colorkey = XInternAtom( dpy, at[attribute].name, 0 );
			}
			if( !strcmp( at[attribute].name, "XV_BRIGHTNESS" ) )
			{
				handle->atom_brightness = XInternAtom( dpy, at[attribute].name, 0 );
				handle->brightness_min = at[attribute].min_value;
				handle->brightness_max = at[attribute].max_value;
			}
			if( !strcmp( at[attribute].name, "XV_HUE" ) )
			{
				handle->atom_hue = XInternAtom( dpy, at[attribute].name, 0 );
				handle->hue_min = at[attribute].min_value;
				handle->hue_max = at[attribute].max_value;
			}
			if( !strcmp( at[attribute].name, "XV_CONTRAST" ) )
			{
				handle->atom_contrast = XInternAtom( dpy, at[attribute].name, 0 );
				handle->contrast_min = at[attribute].min_value;
				handle->contrast_max = at[attribute].max_value;
			}
			if( !strcmp( at[attribute].name, "XV_DOUBLE_BUFFER" ) )
			{
				Atom _atom;
				_atom = XInternAtom( dpy, at[attribute].name, 0 );
				XvSetPortAttribute( dpy, handle->p_adaptor_info[i].base_id, _atom, 1 );
#ifdef DEBUG
				printf( "Xv: DOUBLE_BUFFER available\n" );
#endif
			}	
		}

		xvimage_formats = XvListImageFormats( dpy, handle->p_adaptor_info[i].base_id, &num_xvimage_formats );
/* 		printf( "num_xvimage_formats: %d\n", num_xvimage_formats ); */
		for( format = 0; format < num_xvimage_formats; format++ )
		{
			char imageName[5] = {0, 0, 0, 0, 0};
			memcpy(imageName, &(xvimage_formats[format].id), 4);
#ifdef DEBUG
			fprintf(stdout, "      id: 0x%x", xvimage_formats[format].id);
#endif
			if( isprint( imageName[0]) && isprint(imageName[1]) &&
			    isprint( imageName[2]) && isprint(imageName[3])) 
			{
#ifdef DEBUG
				fprintf(stdout, " (%s)\n", imageName);
#endif
				if( xvimage_formats[format].id == fourcc )
				{
					handle->xv_mode_id = fourcc;
					break;
				}
			} else {
#ifdef DEBUG
				fprintf(stdout, "\n");
#endif
			}
		}

		if( handle->xv_mode_id != fourcc )
		{
			return -3;
		}

		if( XvGrabPort( dpy, handle->p_adaptor_info[i].base_id, CurrentTime ) != Success )
		{
/* 			fprintf( stderr, "Failed to grab port!\n" ); */
			return -1;
		}
	}

	handle->use_shm = 1;

	if( handle->use_shm )
	{
		memset( &handle->shminfo, 0, sizeof( XShmSegmentInfo ) );
		handle->image = XvShmCreateImage( dpy, 
						  handle->p_adaptor_info[0].base_id, 
						  handle->xv_mode_id, 
						  (char*)NULL, 
						  width,
						  height, 
						  &handle->shminfo );

		if( handle->image )
		{
			handle->shminfo.shmid = shmget( IPC_PRIVATE, handle->image->data_size, IPC_CREAT | 0777 );
			if( handle->shminfo.shmid == -1 )
			{
/* 				fprintf( stderr, "shmget failed\n" ); */
				return -1;
			}
			handle->shminfo.shmaddr = handle->image->data = shmat( handle->shminfo.shmid, 0, 0 );
			shmctl(handle->shminfo.shmid, IPC_RMID, 0);
			/* destroy when we terminate, now if shmat failed */

			if( handle->shminfo.shmaddr == ( void * ) -1 )
			{
/* 				fprintf( stderr, "shmat failed\n" ); */
				return -1;
			}
			
			handle->shminfo.readOnly = False;
			if( !XShmAttach( dpy, &handle->shminfo ) )
			{
/* 				fprintf( stderr, "XShmAttach failed\n" ); */
				shmdt( handle->shminfo.shmaddr );
				XFree( handle->image );
				return -1;
			}
		}
		else
		{
/* 			fprintf( stderr, "XvShmCreateImage failed\n" ); */
			return -1;
		}
	}
	else
	{
		char * data = (char*) malloc( width*height*(bpp/8));
		handle->image = XvCreateImage( dpy, handle->p_adaptor_info[0].base_id, handle->xv_mode_id, data, width, height );
	}	

	handle->display = dpy;

	return 0;
}
Exemplo n.º 14
0
// Initialize X11 display and look for supported X11 extensions
//
static GLboolean initExtensions(void)
{
    // Find or create window manager atoms
    _glfw.x11.WM_PROTOCOLS = XInternAtom(_glfw.x11.display,
                                         "WM_PROTOCOLS",
                                         False);
    _glfw.x11.WM_STATE = XInternAtom(_glfw.x11.display, "WM_STATE", False);
    _glfw.x11.WM_DELETE_WINDOW = XInternAtom(_glfw.x11.display,
                                             "WM_DELETE_WINDOW",
                                             False);
    _glfw.x11.MOTIF_WM_HINTS = XInternAtom(_glfw.x11.display,
                                           "_MOTIF_WM_HINTS",
                                           False);

#if defined(_GLFW_HAS_XF86VM)
    // Check for XF86VidMode extension
    _glfw.x11.vidmode.available =
        XF86VidModeQueryExtension(_glfw.x11.display,
                                  &_glfw.x11.vidmode.eventBase,
                                  &_glfw.x11.vidmode.errorBase);
#endif /*_GLFW_HAS_XF86VM*/

    // Check for RandR extension
    _glfw.x11.randr.available =
        XRRQueryExtension(_glfw.x11.display,
                          &_glfw.x11.randr.eventBase,
                          &_glfw.x11.randr.errorBase);

    if (_glfw.x11.randr.available)
    {
        XRRScreenResources* sr;

        if (!XRRQueryVersion(_glfw.x11.display,
                             &_glfw.x11.randr.versionMajor,
                             &_glfw.x11.randr.versionMinor))
        {
            _glfwInputError(GLFW_PLATFORM_ERROR,
                            "X11: Failed to query RandR version");
            return GL_FALSE;
        }

        // The GLFW RandR path requires at least version 1.3
        if (_glfw.x11.randr.versionMajor == 1 &&
            _glfw.x11.randr.versionMinor < 3)
        {
            _glfw.x11.randr.available = GL_FALSE;
        }

        sr = XRRGetScreenResources(_glfw.x11.display, _glfw.x11.root);

        if (!sr->ncrtc || !XRRGetCrtcGammaSize(_glfw.x11.display, sr->crtcs[0]))
        {
            // This is either a headless system or an older Nvidia binary driver
            // with broken gamma support
            // Flag it as useless and fall back to Xf86VidMode gamma, if
            // available
            _glfwInputError(GLFW_PLATFORM_ERROR,
                            "X11: RandR gamma ramp support seems broken");
            _glfw.x11.randr.gammaBroken = GL_TRUE;
        }

        XRRFreeScreenResources(sr);
    }

    if (XineramaQueryExtension(_glfw.x11.display,
                               &_glfw.x11.xinerama.versionMajor,
                               &_glfw.x11.xinerama.versionMinor))
    {
        if (XineramaIsActive(_glfw.x11.display))
            _glfw.x11.xinerama.available = GL_TRUE;
    }

#if defined(_GLFW_HAS_XINPUT)
    if (XQueryExtension(_glfw.x11.display,
                        "XInputExtension",
                        &_glfw.x11.xi.majorOpcode,
                        &_glfw.x11.xi.eventBase,
                        &_glfw.x11.xi.errorBase))
    {
        _glfw.x11.xi.versionMajor = 2;
        _glfw.x11.xi.versionMinor = 0;

        if (XIQueryVersion(_glfw.x11.display,
                           &_glfw.x11.xi.versionMajor,
                           &_glfw.x11.xi.versionMinor) != BadRequest)
        {
            _glfw.x11.xi.available = GL_TRUE;
        }
    }
#endif /*_GLFW_HAS_XINPUT*/

    // Check if Xkb is supported on this display
    _glfw.x11.xkb.versionMajor = 1;
    _glfw.x11.xkb.versionMinor = 0;
    _glfw.x11.xkb.available =
        XkbQueryExtension(_glfw.x11.display,
                          &_glfw.x11.xkb.majorOpcode,
                          &_glfw.x11.xkb.eventBase,
                          &_glfw.x11.xkb.errorBase,
                          &_glfw.x11.xkb.versionMajor,
                          &_glfw.x11.xkb.versionMinor);

    if (_glfw.x11.xkb.available)
    {
        Bool supported;

        if (XkbSetDetectableAutoRepeat(_glfw.x11.display, True, &supported))
        {
            if (supported)
                _glfw.x11.xkb.detectable = GL_TRUE;
        }
    }

    // Update the key code LUT
    // FIXME: We should listen to XkbMapNotify events to track changes to
    // the keyboard mapping.
    createKeyTables();

    // Detect whether an EWMH-conformant window manager is running
    detectEWMH();

    // Find or create string format atoms
    _glfw.x11.NULL_ = XInternAtom(_glfw.x11.display, "NULL", False);
    _glfw.x11.UTF8_STRING =
        XInternAtom(_glfw.x11.display, "UTF8_STRING", False);
    _glfw.x11.COMPOUND_STRING =
        XInternAtom(_glfw.x11.display, "COMPOUND_STRING", False);
    _glfw.x11.ATOM_PAIR = XInternAtom(_glfw.x11.display, "ATOM_PAIR", False);

    // Find or create selection property atom
    _glfw.x11.GLFW_SELECTION =
        XInternAtom(_glfw.x11.display, "GLFW_SELECTION", False);

    // Find or create standard clipboard atoms
    _glfw.x11.TARGETS = XInternAtom(_glfw.x11.display, "TARGETS", False);
    _glfw.x11.MULTIPLE = XInternAtom(_glfw.x11.display, "MULTIPLE", False);
    _glfw.x11.CLIPBOARD = XInternAtom(_glfw.x11.display, "CLIPBOARD", False);

    // Find or create clipboard manager atoms
    _glfw.x11.CLIPBOARD_MANAGER =
        XInternAtom(_glfw.x11.display, "CLIPBOARD_MANAGER", False);
    _glfw.x11.SAVE_TARGETS =
        XInternAtom(_glfw.x11.display, "SAVE_TARGETS", False);

    // Find Xdnd (drag and drop) atoms, if available
    _glfw.x11.XdndAware = XInternAtom(_glfw.x11.display, "XdndAware", True);
    _glfw.x11.XdndEnter = XInternAtom(_glfw.x11.display, "XdndEnter", True);
    _glfw.x11.XdndPosition = XInternAtom(_glfw.x11.display, "XdndPosition", True);
    _glfw.x11.XdndStatus = XInternAtom(_glfw.x11.display, "XdndStatus", True);
    _glfw.x11.XdndActionCopy = XInternAtom(_glfw.x11.display, "XdndActionCopy", True);
    _glfw.x11.XdndDrop = XInternAtom(_glfw.x11.display, "XdndDrop", True);
    _glfw.x11.XdndLeave = XInternAtom(_glfw.x11.display, "XdndLeave", True);
    _glfw.x11.XdndFinished = XInternAtom(_glfw.x11.display, "XdndFinished", True);
    _glfw.x11.XdndSelection = XInternAtom(_glfw.x11.display, "XdndSelection", True);

    return GL_TRUE;
}
Exemplo n.º 15
0
guint
egg_tray_icon_send_message (EggTrayIcon *icon,
			    gint         timeout,
			    const gchar *message,
			    gint         len)
{
  guint stamp;

  g_return_val_if_fail (EGG_IS_TRAY_ICON (icon), 0);
  g_return_val_if_fail (timeout >= 0, 0);
  g_return_val_if_fail (message != NULL, 0);

#ifdef GDK_WINDOWING_X11
  if (icon->manager_window == None)
    return 0;
#endif

  if (len < 0)
    len = strlen (message);

  stamp = icon->stamp++;

#ifdef GDK_WINDOWING_X11
  /* Get ready to send the message */
  egg_tray_icon_send_manager_message (icon, SYSTEM_TRAY_BEGIN_MESSAGE,
				      icon->manager_window,
				      timeout, len, stamp);

  /* Now to send the actual message */
  gdk_error_trap_push ();
  while (len > 0)
    {
      XClientMessageEvent ev;
      Display *xdisplay;

      xdisplay = GDK_DISPLAY_XDISPLAY (gtk_widget_get_display (GTK_WIDGET (icon)));

      ev.type = ClientMessage;
      ev.window = icon->manager_window;
      ev.format = 8;
      ev.message_type = XInternAtom (xdisplay,
				     "_NET_SYSTEM_TRAY_MESSAGE_DATA", False);
      if (len > 20)
	{
	  memcpy (&ev.data, message, 20);
	  len -= 20;
	  message += 20;
	}
      else
	{
	  memcpy (&ev.data, message, len);
	  len = 0;
	}

      XSendEvent (xdisplay,
		  icon->manager_window, False, StructureNotifyMask, (XEvent *)&ev);
      XSync (xdisplay, False);
    }
  gdk_error_trap_pop ();
#endif

  return stamp;
}
Exemplo n.º 16
0
void S9xInitDisplay (int argc, char **argv)
{
	GUI.display = XOpenDisplay(NULL);
	if (GUI.display == NULL)
		FatalError("Failed to connect to X server.");

	GUI.screen     = DefaultScreenOfDisplay(GUI.display);
	GUI.screen_num = XScreenNumberOfScreen(GUI.screen);
	GUI.visual     = DefaultVisualOfScreen(GUI.screen);

	XVisualInfo	plate, *matches;
	int			count;

	plate.visualid = XVisualIDFromVisual(GUI.visual);
	matches = XGetVisualInfo(GUI.display, VisualIDMask, &plate, &count);
	if (!count)
		FatalError("Your X Window System server is unwell!");

	GUI.depth = matches[0].depth;
	if ((GUI.depth != 15 && GUI.depth != 16 && GUI.depth != 24) || (matches[0].c_class != TrueColor))
		FatalError("Requiers 15, 16, 24 or 32-bit color depth supporting TrueColor.");

	GUI.red_shift   = ffs(matches[0].red_mask)   - 1;
	GUI.green_shift = ffs(matches[0].green_mask) - 1;
	GUI.blue_shift  = ffs(matches[0].blue_mask)  - 1;
	GUI.red_size    = matches[0].red_mask   >> GUI.red_shift;
	GUI.green_size  = matches[0].green_mask >> GUI.green_shift;
	GUI.blue_size   = matches[0].blue_mask  >> GUI.blue_shift;
	if (GUI.depth == 16 && GUI.green_size == 63)
		GUI.green_shift++;

	XFree(matches);

	switch (GUI.depth)
	{
		default:
		case 32:
		case 24:
			S9xSetRenderPixelFormat(RGB555);
			GUI.pixel_format = 555;
			break;

		case 16:
			if (GUI.red_size != GUI.green_size || GUI.blue_size != GUI.green_size)
			{
				// 565 format
				if (GUI.green_shift > GUI.blue_shift && GUI.green_shift > GUI.red_shift)
					S9xSetRenderPixelFormat(GBR565);
				else
				if (GUI.red_shift > GUI.blue_shift)
					S9xSetRenderPixelFormat(RGB565);
				else
					S9xSetRenderPixelFormat(BGR565);

				GUI.pixel_format = 565;
				break;
			}
			// FALL ...
		case 15:
			if (GUI.green_shift > GUI.blue_shift && GUI.green_shift > GUI.red_shift)
				S9xSetRenderPixelFormat(GBR555);
			else
			if (GUI.red_shift > GUI.blue_shift)
				S9xSetRenderPixelFormat(RGB555);
			else
				S9xSetRenderPixelFormat(BGR555);

			GUI.pixel_format = 555;
			break;
	}

	S9xBlitFilterInit();
	S9xBlit2xSaIFilterInit();
	S9xBlitHQ2xFilterInit();

	XSetWindowAttributes	attrib;

	memset(&attrib, 0, sizeof(attrib));
	attrib.background_pixel = BlackPixelOfScreen(GUI.screen);
	attrib.colormap = XCreateColormap(GUI.display, RootWindowOfScreen(GUI.screen), GUI.visual, AllocNone);

	GUI.window = XCreateWindow(GUI.display, RootWindowOfScreen(GUI.screen),
							   (WidthOfScreen(GUI.screen) - SNES_WIDTH * 2) / 2, (HeightOfScreen(GUI.screen) - SNES_HEIGHT_EXTENDED * 2) / 2,
							   SNES_WIDTH * 2, SNES_HEIGHT_EXTENDED * 2, 0, GUI.depth, InputOutput, GUI.visual, CWBackPixel | CWColormap, &attrib);

	static XColor	bg, fg;
	static char		data[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
	Pixmap			bitmap;

	bitmap = XCreateBitmapFromData(GUI.display, GUI.window, data, 8, 8);
	GUI.point_cursor = XCreatePixmapCursor(GUI.display, bitmap, bitmap, &fg, &bg, 0, 0);
	XDefineCursor(GUI.display, GUI.window, GUI.point_cursor);
	GUI.cross_hair_cursor = XCreateFontCursor(GUI.display, XC_crosshair);

	GUI.gc = DefaultGCOfScreen(GUI.screen);

	XSizeHints	Hints;
	XWMHints	WMHints;

	memset((void *) &Hints, 0, sizeof(XSizeHints));
	memset((void *) &WMHints, 0, sizeof(XWMHints));

	Hints.flags      = PSize | PMinSize | PMaxSize;
	Hints.min_width  = Hints.max_width  = Hints.base_width  = SNES_WIDTH * 2;
	Hints.min_height = Hints.max_height = Hints.base_height = SNES_HEIGHT_EXTENDED * 2;
	WMHints.input    = True;
	WMHints.flags    = InputHint;

	XSetWMHints(GUI.display, GUI.window, &WMHints);
	XSetWMNormalHints(GUI.display, GUI.window, &Hints);
	XSelectInput(GUI.display, GUI.window, FocusChangeMask | ExposureMask | KeyPressMask | KeyReleaseMask | StructureNotifyMask | ButtonPressMask | ButtonReleaseMask);

	XMapRaised(GUI.display, GUI.window);
	XClearWindow(GUI.display, GUI.window);

	SetupImage();

	switch (GUI.depth)
	{
		default:
		case 32:
			GUI.bytes_per_pixel = 4;
			break;

		case 24:
			if (GUI.image->bits_per_pixel == 24)
				GUI.bytes_per_pixel = 3;
			else
				GUI.bytes_per_pixel = 4;
			break;

		case 15:
		case 16:
			GUI.bytes_per_pixel = 2;
			break;
	}

	wmDeleteMessage = XInternAtom(GUI.display, "WM_DELETE_WINDOW", false);
	XSetWMProtocols(GUI.display, GUI.window, &wmDeleteMessage, 1);
}
Exemplo n.º 17
0
int
S9xXVDisplayDriver::init (void)
{
    int                 padding;
    int                 depth = 0, num_formats, num_attrs, highest_formats = 0;
    XvImageFormatValues *formats = NULL;
    XvAdaptorInfo       *adaptors;
    XvAttribute         *port_attr;
    VisualID            visualid = None;
    unsigned int        num_adaptors;
    GdkScreen           *screen;
    GdkWindow           *root;

    buffer[0] = malloc (image_padded_size);
    buffer[1] = malloc (scaled_padded_size);

    padding = (image_padded_size - image_size) / 2;
    padded_buffer[0] = (void *) (((uint8 *) buffer[0]) + padding);

    padding = (scaled_padded_size - scaled_size) / 2;
    padded_buffer[1] = (void *) (((uint8 *) buffer[1]) + padding);

    memset (buffer[0], 0, image_padded_size);
    memset (buffer[1], 0, scaled_padded_size);

    /* Setup XV */
    gtk_widget_realize (drawing_area);

    display = gdk_x11_display_get_xdisplay (gtk_widget_get_display (drawing_area));
    screen = gtk_widget_get_screen (drawing_area);
    root = gdk_screen_get_root_window (screen);

    xv_portid = -1;
    XvQueryAdaptors (display,
                     GDK_COMPAT_WINDOW_XID (root),
                     &num_adaptors,
                     &adaptors);


    for (int i = 0; i < (int) num_adaptors; i++)
    {
        if (adaptors[i].type & XvInputMask &&
            adaptors[i].type & XvImageMask)
        {
            formats = XvListImageFormats (display,
                                          adaptors[i].base_id,
                                          &num_formats);

            if (num_formats > highest_formats)
            {
                xv_portid = adaptors[i].base_id;
                highest_formats = num_formats;
                visualid = adaptors[i].formats->visual_id;
            }

            free (formats);
        }
    }

    XvFreeAdaptorInfo (adaptors);

    if (xv_portid < 0)
    {
        fprintf (stderr, "Could not open Xv output port.\n");
        return -1;
    }

    /* Set XV_AUTOPAINT_COLORKEY _only_ if available */
    port_attr = XvQueryPortAttributes (display, xv_portid, &num_attrs);

    for (int i = 0; i < num_attrs; i++)
    {
        if (!strcmp (port_attr[i].name, "XV_AUTOPAINT_COLORKEY"))
        {
            Atom colorkey;

            colorkey = XInternAtom (display, "XV_AUTOPAINT_COLORKEY", True);
            if (colorkey != None)
                XvSetPortAttribute (display, xv_portid, colorkey, 1);
        }
    }

    /* Try to find an RGB format */
    format = FOURCC_YUY2;
    bpp = 100;

    formats = XvListImageFormats (display,
                                  xv_portid,
                                  &num_formats);

    for (int i = 0; i < num_formats; i++)
    {
        if (formats[i].id == 0x3 || formats[i].type == XvRGB)
        {
            if (formats[i].bits_per_pixel < bpp)
            {
                format = formats[i].id;
                bpp = formats[i].bits_per_pixel;
                bytes_per_pixel = (bpp == 15) ? 2 : bpp >> 3;
                depth = formats[i].depth;

                this->rshift = get_inv_shift (formats[i].red_mask, bpp);
                this->gshift = get_inv_shift (formats[i].green_mask, bpp);
                this->bshift = get_inv_shift (formats[i].blue_mask, bpp);

                /* Check for red-blue inversion on SiliconMotion drivers */
                if (formats[i].red_mask  == 0x001f &&
                    formats[i].blue_mask == 0x7c00)
                {
                    int copy = this->rshift;
                    this->rshift = this->bshift;
                    this->bshift = copy;
                }

                /* on big-endian Xv still seems to like LSB order */
                if (config->force_inverted_byte_order)
                    S9xSetEndianess (ENDIAN_MSB);
                else
                    S9xSetEndianess (ENDIAN_LSB);
            }
        }
    }
Exemplo n.º 18
0
/*
 * Class:     org_jdesktop_jdic_dock_internal_impl_UnixDockService
 * Method:    createDockWindow
 * Signature: ()J
 */
JNIEXPORT jlong JNICALL Java_org_jdesktop_jdic_dock_internal_impl_UnixDockService_createDockWindow(JNIEnv *env, jobject obj)
{
    Window win;
    XWMHints   *  wm_hints;
    XClassHint *  class_hints;
    XTextProperty windowName, iconName;
    Atom wm_delete_window;
    Atom _NET_WM_WINDOW_TYPE;
    Atom _NET_WM_WINDOW_TYPE_DOCK;
    Atom _NET_WM_STRUT;
    Atom _NET_WM_STATE;
    Atom _NET_WM_STATE_STICKY;
    char *       window_name = "JDIC Dock";
    char *       icon_name = "JDIC Dock Icon";

    (*LockIt)(env);
    /*  Allocate memory for our structures  */

    if (    !( wm_hints    = XAllocWMHints()   ) ||
            !( class_hints = XAllocClassHint() )    ) {
        fprintf(stderr, "Couldn't allocate memory.\n");
        (*UnLockIt)(env);
        return 0;
    }

    win = XCreateWindow(display,RootWindow(display,screen_num),
            0,0,10,10,1,
            CopyFromParent,
            CopyFromParent,
            CopyFromParent,
            0,
            0);

    /*  Set hints for window manager before mapping window  */

    if ( XStringListToTextProperty(&window_name, 1, &windowName) == 0 ) {
        fprintf(stderr, "%s: structure allocation for windowName failed.\n",
                window_name);
        (*UnLockIt)(env);
        return 0;
    }
    if ( XStringListToTextProperty(&icon_name, 1, &iconName) == 0 ) {
        fprintf(stderr, "%s: structure allocation for iconName failed.\n",
                window_name);
        (*UnLockIt)(env);
        return 0;
    }

    wm_hints->flags         = StateHint | InputHint;
    wm_hints->initial_state = NormalState;
    wm_hints->input         = True;

    class_hints->res_name   = "JDIC Dock";
    class_hints->res_class  = "JDIC Dock";

    XSetWMProperties(display, win, &windowName, &iconName, NULL, 0,
            NULL, wm_hints, class_hints);

    /*  Choose which events we want to handle  */

    XSelectInput(display, win, ExposureMask | KeyPressMask |
                 ButtonPressMask | StructureNotifyMask);

    wm_delete_window = XInternAtom(display,"WM_DELETE_WINDOW",False);
    _NET_WM_WINDOW_TYPE = XInternAtom(display,"_NET_WM_WINDOW_TYPE",False);
    _NET_WM_WINDOW_TYPE_DOCK = XInternAtom(display,"_NET_WM_WINDOW_TYPE_DOCK",False);
    _NET_WM_STATE = XInternAtom(display,"_NET_WM_STATE",False);
    _NET_WM_STATE_STICKY = XInternAtom(display,"_NET_WM_STATE_STICKY",False);

    XSetWMProtocols(display, win, &wm_delete_window, 1);

    XChangeProperty(display, win, _NET_WM_WINDOW_TYPE, XA_ATOM , 32, PropModeReplace,
                    (unsigned char *)&_NET_WM_WINDOW_TYPE_DOCK, 1);
    XChangeProperty(display, win, _NET_WM_STATE,XA_ATOM , 32, PropModeReplace,
                    (unsigned char *)&_NET_WM_STATE_STICKY, 1);

    dprintf("Window ID = %x \n",win);

    (*UnLockIt)(env);

    return (jlong) win;
}
Exemplo n.º 19
0
static BOOL xf_event_PropertyNotify(xfContext* xfc, XEvent* event, BOOL app)
{
	/*
	 * This section handles sending the appropriate commands to the rail server
	 * when the window has been minimized, maximized, restored locally
	 * ie. not using the buttons on the rail window itself
	 */

	if (app)
	{
	        rdpWindow* window;
		
		window = xf_rdpWindowFromWindow(xfc, event->xproperty.window);

		if (window == NULL)
			return TRUE;
	
	        if ((((Atom) event->xproperty.atom == xfc->_NET_WM_STATE) && (event->xproperty.state != PropertyDelete)) ||
	            (((Atom) event->xproperty.atom == xfc->WM_STATE) && (event->xproperty.state != PropertyDelete)))
	        {
	        	int i;
	                BOOL status;
	                BOOL maxVert = FALSE;
	                BOOL maxHorz = FALSE;
	                BOOL minimized = FALSE;
	                unsigned long nitems;
	                unsigned long bytes;
	                unsigned char* prop;
	
	                if ((Atom) event->xproperty.atom == xfc->_NET_WM_STATE)
	                {
				status = xf_GetWindowProperty(xfc, event->xproperty.window,
						xfc->_NET_WM_STATE, 12, &nitems, &bytes, &prop);

				if (!status)
				{
					       DEBUG_X11_LMS("No return _NET_WM_STATE, window is not maximized");
				}

				for (i = 0; i < nitems; i++)
				{
					if ((Atom) ((UINT16**) prop)[i] == XInternAtom(xfc->display, "_NET_WM_STATE_MAXIMIZED_VERT", False))
					{
						maxVert = TRUE;
					}
	
					if ((Atom) ((UINT16**) prop)[i] == XInternAtom(xfc->display, "_NET_WM_STATE_MAXIMIZED_HORZ", False))
					{
						maxHorz = TRUE;
					}
				}
	
				XFree(prop);
	                }
	
	                if ((Atom) event->xproperty.atom == xfc->WM_STATE)
	                {
				status = xf_GetWindowProperty(xfc, event->xproperty.window, xfc->WM_STATE, 1, &nitems, &bytes, &prop);

				if (!status)
				{
					DEBUG_X11_LMS("No return WM_STATE, window is not minimized");
				}
				else
				{
					/* If the window is in the iconic state */
					if (((UINT32) *prop == 3))
						minimized = TRUE;
					else
						minimized = FALSE;

					XFree(prop);
				}
	                }
	

	                if (maxVert && maxHorz && !minimized && (xfc->window->rail_state != WINDOW_SHOW_MAXIMIZED))
	                {
	                	DEBUG_X11_LMS("Send SC_MAXIMIZE command to rail server.");
	                	xfc->window->rail_state = WINDOW_SHOW_MAXIMIZED;
	                	xf_rail_send_client_system_command(xfc, window->windowId, SC_MAXIMIZE);
	                }
	                else if (minimized && (xfc->window->rail_state != WINDOW_SHOW_MINIMIZED))
	                {
	                	DEBUG_X11_LMS("Send SC_MINIMIZE command to rail server.");
	                	xfc->window->rail_state = WINDOW_SHOW_MINIMIZED;
	                	xf_rail_send_client_system_command(xfc, window->windowId, SC_MINIMIZE);
	                }
	                else if (!minimized && !maxVert && !maxHorz && (xfc->window->rail_state != WINDOW_SHOW))
	                {
	                	DEBUG_X11_LMS("Send SC_RESTORE command to rail server");
	                	xfc->window->rail_state = WINDOW_SHOW;
	                	xf_rail_send_client_system_command(xfc, window->windowId, SC_RESTORE);
	                }
               }       
        }

	return TRUE;
}
Exemplo n.º 20
0
X11Window::X11Window( intf_thread_t *pIntf, GenericWindow &rWindow,
                      X11Display &rDisplay, bool dragDrop, bool playOnDrop,
                      X11Window *pParentWindow, GenericWindow::WindowType_t type ):
    OSWindow( pIntf ), m_rDisplay( rDisplay ), m_pParent( pParentWindow ),
    m_dragDrop( dragDrop ), m_pDropTarget( NULL ), m_type ( type )
{
    XSetWindowAttributes attr;
    unsigned long valuemask;
    std::string name_type;

    if( type == GenericWindow::FullscreenWindow )
    {
        m_wnd_parent = DefaultRootWindow( XDISPLAY );

        int i_screen = DefaultScreen( XDISPLAY );

        attr.event_mask = ExposureMask | StructureNotifyMask;
        attr.background_pixel = BlackPixel( XDISPLAY, i_screen );
        attr.backing_store = Always;
        valuemask = CWBackingStore | CWBackPixel | CWEventMask;

        if( NET_WM_STATE_FULLSCREEN == None )
        {
            attr.override_redirect = True;
            valuemask = valuemask | CWOverrideRedirect;
        }

        name_type = "Fullscreen";
    }
    else if( type == GenericWindow::VoutWindow )
    {
        m_wnd_parent = pParentWindow->m_wnd;

        int i_screen = DefaultScreen( XDISPLAY );

        attr.event_mask = ExposureMask | StructureNotifyMask;
        attr.backing_store = Always;
        attr.background_pixel = BlackPixel( XDISPLAY, i_screen );
        valuemask = CWBackingStore | CWBackPixel | CWEventMask;

        name_type = "VoutWindow";
    }
    else if( type == GenericWindow::FscWindow )
    {
        m_wnd_parent = DefaultRootWindow( XDISPLAY );

        attr.event_mask = ExposureMask | StructureNotifyMask;
        valuemask = CWEventMask;

        name_type = "FscWindow";
    }
    else
    {
        m_wnd_parent = DefaultRootWindow( XDISPLAY );

        attr.event_mask = ExposureMask | StructureNotifyMask;
        valuemask = CWEventMask;

        name_type = "TopWindow";
    }

    // Create the window
    m_wnd = XCreateWindow( XDISPLAY, m_wnd_parent, -10, 0, 10, 10, 0, 0,
                           InputOutput, CopyFromParent, valuemask, &attr );

    // wait for X server to process the previous commands
    XSync( XDISPLAY, false );

    // Set the colormap for 8bpp mode
    if( XPIXELSIZE == 1 )
    {
        XSetWindowColormap( XDISPLAY, m_wnd, m_rDisplay.getColormap() );
    }

    // Select events received by the window
    long event_mask = ExposureMask|KeyPressMask|
                      PointerMotionMask|ButtonPressMask|ButtonReleaseMask|
                      LeaveWindowMask|FocusChangeMask;
    XSelectInput( XDISPLAY, m_wnd, event_mask );

    // Store a pointer on the generic window in a map
    X11Factory *pFactory = (X11Factory*)X11Factory::instance( getIntf() );
    pFactory->m_windowMap[m_wnd] = &rWindow;

    // Changing decorations
    struct {
        unsigned long flags;
        unsigned long functions;
        unsigned long decorations;
        signed   long input_mode;
        unsigned long status;
    } motifWmHints;
    Atom hints_atom = XInternAtom( XDISPLAY, "_MOTIF_WM_HINTS", False );
    motifWmHints.flags = 2;    // MWM_HINTS_DECORATIONS;
    motifWmHints.decorations = 0;
    XChangeProperty( XDISPLAY, m_wnd, hints_atom, hints_atom, 32,
                     PropModeReplace, (unsigned char *)&motifWmHints,
                     sizeof( motifWmHints ) / sizeof( uint32_t ) );

    // Drag & drop
    if( m_dragDrop )
    {
        // Create a Dnd object for this window
        m_pDropTarget = new X11DragDrop( getIntf(), m_rDisplay, m_wnd,
                                         playOnDrop, &rWindow );

        // Register the window as a drop target
        Atom xdndAtom = XInternAtom( XDISPLAY, "XdndAware", False );
        char xdndVersion = 5;
        XChangeProperty( XDISPLAY, m_wnd, xdndAtom, XA_ATOM, 32,
                         PropModeReplace, (unsigned char *)&xdndVersion, 1 );

        // Store a pointer to be used in X11Loop
        pFactory->m_dndMap[m_wnd] = m_pDropTarget;
    }

    // Change the window title
    std::string name_window = "VLC (" + name_type + ")";
    XStoreName( XDISPLAY, m_wnd, name_window.c_str() );

    // Set the WM_TRANSIENT_FOR property
    if( type == GenericWindow::FscWindow )
    {
        // Associate the fsc window to the fullscreen window
        VoutManager* pVoutManager = VoutManager::instance( getIntf() );
        GenericWindow* pGenericWin = pVoutManager->getVoutMainWindow();
        X11Window *pWin = (X11Window*)pGenericWin->getOSWindow();
        Window wnd = pWin->getDrawable();
        XSetTransientForHint( XDISPLAY, m_wnd, wnd );
    }
    else
    {
        // Associate the regular top-level window to the offscren main window
        XSetTransientForHint( XDISPLAY, m_wnd, m_rDisplay.getMainWindow() );
    }

    // initialize Class Hint
    XClassHint classhint;
    classhint.res_name = (char*) "vlc";
    classhint.res_class = (char*) "Vlc";
    XSetClassHint( XDISPLAY, m_wnd, &classhint );

    // copies WM_HINTS from the main window
    XWMHints *wm = XGetWMHints( XDISPLAY, m_rDisplay.getMainWindow() );
    if( wm )
    {
        XSetWMHints( XDISPLAY, m_wnd, wm );
        XFree( wm );
    }

    // initialize WM_CLIENT_MACHINE
    char* hostname = NULL;
    long host_name_max = sysconf( _SC_HOST_NAME_MAX );
    if( host_name_max <= 0 )
        host_name_max = _POSIX_HOST_NAME_MAX;
    hostname = new (std::nothrow) char[host_name_max];
    if( hostname && gethostname( hostname, host_name_max ) == 0 )
    {
        hostname[host_name_max - 1] = '\0';

        XTextProperty textprop;
        textprop.value = (unsigned char *) hostname;
        textprop.encoding = XA_STRING;
        textprop.format = 8;
        textprop.nitems = strlen( hostname );
        XSetWMClientMachine( XDISPLAY, m_wnd, &textprop);
    }
    delete[] hostname;

    // initialize EWMH pid
    pid_t pid = getpid();
    assert(  NET_WM_PID != None );
    XChangeProperty( XDISPLAY, m_wnd, NET_WM_PID, XA_CARDINAL, 32,
                     PropModeReplace, (unsigned char *)&pid, 1 );

    if( NET_WM_WINDOW_TYPE != None )
    {
        if( type == GenericWindow::FullscreenWindow )
        {
            // Some Window Managers like Gnome3 limit fullscreen to the
            // subarea outside the task bar if no window type is provided.
            // For those WMs, setting type window to normal ensures a clean
            // 100% fullscreen
            XChangeProperty( XDISPLAY, m_wnd, NET_WM_WINDOW_TYPE,
                         XA_ATOM, 32, PropModeReplace,
                         (unsigned char *)&NET_WM_WINDOW_TYPE_NORMAL, 1 );
        }
    }
}
Exemplo n.º 21
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;
}
/** The initialization function 
  * This function opens the frame buffer device and allocates memory for display 
  * also it finds the frame buffer supported display formats
  */
OMX_ERRORTYPE omx_xvideo_sink_component_Init(OMX_COMPONENTTYPE *openmaxStandComp) {
  omx_xvideo_sink_component_PrivateType* omx_xvideo_sink_component_Private = openmaxStandComp->pComponentPrivate;
  omx_xvideo_sink_component_PortType* pPort = (omx_xvideo_sink_component_PortType *) omx_xvideo_sink_component_Private->ports[OMX_BASE_SINK_INPUTPORT_INDEX];
  int yuv_width  = pPort->sPortParam.format.video.nFrameWidth;
  int yuv_height = pPort->sPortParam.format.video.nFrameHeight;
  int err,i;

  omx_xvideo_sink_component_Private->dpy = XOpenDisplay(NULL);
  omx_xvideo_sink_component_Private->screen = DefaultScreen(omx_xvideo_sink_component_Private->dpy);

  XGetWindowAttributes(omx_xvideo_sink_component_Private->dpy, 
    DefaultRootWindow(omx_xvideo_sink_component_Private->dpy), 
    &omx_xvideo_sink_component_Private->attribs);
  
  XMatchVisualInfo(omx_xvideo_sink_component_Private->dpy, 
    omx_xvideo_sink_component_Private->screen, 
    omx_xvideo_sink_component_Private->attribs.depth, TrueColor, &
    omx_xvideo_sink_component_Private->vinfo);
  
  omx_xvideo_sink_component_Private->wmDeleteWindow = XInternAtom(omx_xvideo_sink_component_Private->dpy, "WM_DELETE_WINDOW", False);

  omx_xvideo_sink_component_Private->hint.x = 1;
  omx_xvideo_sink_component_Private->hint.y = 1;
  omx_xvideo_sink_component_Private->hint.width = yuv_width;
  omx_xvideo_sink_component_Private->hint.height = yuv_height;
  omx_xvideo_sink_component_Private->hint.flags = PPosition | PSize;

  omx_xvideo_sink_component_Private->xswa.colormap = XCreateColormap(omx_xvideo_sink_component_Private->dpy, 
                                                                     DefaultRootWindow(omx_xvideo_sink_component_Private->dpy), 
                                                                     omx_xvideo_sink_component_Private->vinfo.visual, AllocNone);
  omx_xvideo_sink_component_Private->xswa.event_mask = StructureNotifyMask | ExposureMask;
  omx_xvideo_sink_component_Private->xswa.background_pixel = 0;
  omx_xvideo_sink_component_Private->xswa.border_pixel = 0;

  omx_xvideo_sink_component_Private->window = 
                        XCreateWindow(omx_xvideo_sink_component_Private->dpy, 
                                      DefaultRootWindow(omx_xvideo_sink_component_Private->dpy), 0, 0, yuv_width, 
                                      yuv_height, 0, omx_xvideo_sink_component_Private->vinfo.depth, InputOutput, 
                                      omx_xvideo_sink_component_Private->vinfo.visual, 
                                      CWBackPixel | CWBorderPixel | CWColormap | 
                                      CWEventMask, &omx_xvideo_sink_component_Private->xswa);

  XSelectInput(omx_xvideo_sink_component_Private->dpy, omx_xvideo_sink_component_Private->window, StructureNotifyMask);
  XSetStandardProperties(omx_xvideo_sink_component_Private->dpy, omx_xvideo_sink_component_Private->window, "xvcam", "xvcam", None, NULL, 0,
                        &omx_xvideo_sink_component_Private->hint);

  XSetWMProtocols(omx_xvideo_sink_component_Private->dpy, 
                  omx_xvideo_sink_component_Private->window, 
                  &omx_xvideo_sink_component_Private->wmDeleteWindow, 1);
  XMapWindow(omx_xvideo_sink_component_Private->dpy, omx_xvideo_sink_component_Private->window);

  if (XShmQueryExtension(omx_xvideo_sink_component_Private->dpy))
    omx_xvideo_sink_component_Private->CompletionType = XShmGetEventBase(omx_xvideo_sink_component_Private->dpy) + ShmCompletion;
  else
    return OMX_ErrorUndefined;

  if (Success !=
     XvQueryExtension(omx_xvideo_sink_component_Private->dpy, 
                      &omx_xvideo_sink_component_Private->ver, 
                      &omx_xvideo_sink_component_Private->rel, 
                      &omx_xvideo_sink_component_Private->req, 
                      &omx_xvideo_sink_component_Private->ev, &err))
    fprintf(stderr, "Couldn't do Xv stuff\n");

  if (Success !=
     XvQueryAdaptors(omx_xvideo_sink_component_Private->dpy, 
                     DefaultRootWindow(omx_xvideo_sink_component_Private->dpy), 
                     &omx_xvideo_sink_component_Private->adapt, 
                     &omx_xvideo_sink_component_Private->ai))
    fprintf(stderr, "Couldn't do Xv stuff\n");

  for (i = 0; i < (int) omx_xvideo_sink_component_Private->adapt; i++) {
    omx_xvideo_sink_component_Private->xv_port = omx_xvideo_sink_component_Private->ai[i].base_id;
  }

  if (omx_xvideo_sink_component_Private->adapt > 0)
    XvFreeAdaptorInfo(omx_xvideo_sink_component_Private->ai);

  omx_xvideo_sink_component_Private->gc = XCreateGC(omx_xvideo_sink_component_Private->dpy, omx_xvideo_sink_component_Private->window, 0, 0);

  omx_xvideo_sink_component_Private->yuv_image = XvShmCreateImage(omx_xvideo_sink_component_Private->dpy, 
                                                                  omx_xvideo_sink_component_Private->xv_port, 
                                                                  GUID_I420_PLANAR, 0, yuv_width,
                                                                  yuv_height, &omx_xvideo_sink_component_Private->yuv_shminfo);
  
  omx_xvideo_sink_component_Private->yuv_shminfo.shmid = shmget(IPC_PRIVATE, omx_xvideo_sink_component_Private->yuv_image->data_size, IPC_CREAT | 0777);
  omx_xvideo_sink_component_Private->yuv_shminfo.shmaddr = (char *) shmat(omx_xvideo_sink_component_Private->yuv_shminfo.shmid, 0, 0);
  omx_xvideo_sink_component_Private->yuv_image->data = omx_xvideo_sink_component_Private->yuv_shminfo.shmaddr;
  omx_xvideo_sink_component_Private->yuv_shminfo.readOnly = False;

  if (!XShmAttach(omx_xvideo_sink_component_Private->dpy, &omx_xvideo_sink_component_Private->yuv_shminfo)) {
    printf("XShmAttach go boom boom!\n");
    return OMX_ErrorUndefined;
  }

  return OMX_ErrorNone;
}
Exemplo n.º 23
0
char *Sys_GetClipboardData( clipboard_t clip )
{
#ifndef DEDICATED
	// derived from SDL clipboard code (http://hg.assembla.com/SDL_Clipboard)
	Window        owner;
	Atom          selection;
	Atom          converted;
	Atom          selectionType;
	int           selectionFormat;
	unsigned long nbytes;
	unsigned long overflow;
	char          *src;

	if ( x11.display == NULL )
	{
		SDL_SysWMinfo info;

		SDL_VERSION( &info.version );
		if ( SDL_GetWMInfo( &info ) != 1 || info.subsystem != SDL_SYSWM_X11 )
		{
			Com_Printf("Not on X11? (%d)\n",info.subsystem);
			return NULL;
		}

		x11.display = info.info.x11.display;
		x11.window = info.info.x11.window;
		x11.lockDisplay = info.info.x11.lock_func;
		x11.unlockDisplay = info.info.x11.unlock_func;
		x11.utf8 = XInternAtom( x11.display, "UTF8_STRING", False );

		SDL_EventState( SDL_SYSWMEVENT, SDL_ENABLE );
		//SDL_SetEventFilter( Sys_ClipboardFilter );
	}

	x11.lockDisplay();

	switch ( clip )
	{
	// preference order; we use fall-through
	default: // SELECTION_CLIPBOARD
		selection = XInternAtom( x11.display, "CLIPBOARD", False );
		owner = XGetSelectionOwner( x11.display, selection );
		if ( owner != None && owner != x11.window )
		{
			break;
		}

	case SELECTION_PRIMARY:
		selection = XA_PRIMARY;
		owner = XGetSelectionOwner( x11.display, selection );
		if ( owner != None && owner != x11.window )
		{
			break;
		}

	case SELECTION_SECONDARY:
		selection = XA_SECONDARY;
		owner = XGetSelectionOwner( x11.display, selection );
	}

	converted = XInternAtom( x11.display, "UNVANQUISHED_SELECTION", False );
	x11.unlockDisplay();

	if ( owner == None || owner == x11.window )
	{
		selection = XA_CUT_BUFFER0;
		owner = RootWindow( x11.display, DefaultScreen( x11.display ) );
	}
	else
	{
		SDL_Event event;

		x11.lockDisplay();
		owner = x11.window;
		//FIXME: when we can respond to clipboard requests, don't alter selection
		XConvertSelection( x11.display, selection, x11.utf8, converted, owner, CurrentTime );
		x11.unlockDisplay();

		for (;;)
		{
			SDL_WaitEvent( &event );

			if ( event.type == SDL_SYSWMEVENT )
			{
				XEvent xevent = event.syswm.msg->event.xevent;

				if ( xevent.type == SelectionNotify &&
				     xevent.xselection.requestor == owner )
				{
					break;
				}
			}
		}
	}

	x11.lockDisplay ();

	if ( XGetWindowProperty( x11.display, owner, converted, 0, INT_MAX / 4,
	                         False, x11.utf8, &selectionType, &selectionFormat,
	                         &nbytes, &overflow, (unsigned char **) &src ) == Success )
	{
		char *dest = NULL;

		if ( selectionType == x11.utf8 )
		{
			dest = Z_Malloc( nbytes + 1 );
			memcpy( dest, src, nbytes );
			dest[ nbytes ] = 0;
		}
		XFree( src );

		x11.unlockDisplay();
		return dest;
	}

	x11.unlockDisplay();
#endif // !DEDICATED
	return NULL;
}
Exemplo n.º 24
0
void * x11_window_create_window( xwl_native_window_t * handle, const char * utf8_title, unsigned int * attributes, int pixel_format )
{
	// using X11, 'pixel_format' here refers to the visualID we want to create the window with.
	Window native_window = 0;
	XSetWindowAttributes window_attribs;
	int window_width;
	int window_height;
	int cwmask;

	XVisualInfo * visual = x11_fetch_visual( pixel_format );
	if ( !visual )
	{
		xwl_set_error( "Unable to fetch visual" );
		return 0;
	}

	// fill in atributes
	window_width = attributes[ XWL_WINDOW_WIDTH ];
	window_height = attributes[ XWL_WINDOW_HEIGHT ];

	window_attribs.background_pixel = 0;
	window_attribs.border_pixel = 0;

	// we now have the visual; move on to creating the window now...
	window_attribs.event_mask = FocusChangeMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | KeyPressMask | KeyReleaseMask | StructureNotifyMask | EnterWindowMask | LeaveWindowMask;

	// fprintf( stdout, "[xwl] Create a color map... \n");
	window_attribs.colormap = XCreateColormap( x11_current_display(), RootWindow(x11_current_display(), x11_current_screen()), visual->visual, AllocNone );

	cwmask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;

	// fprintf( stdout, "[xwl] Attempting to create a window\n" );
	// fprintf( stdout, "root: %p\n", (void*)RootWindow(x11_current_display(), x11_current_screen()) );
	// fprintf( stdout, "display: %p\n", x11_current_display() );
	// fprintf( stdout, "screen: %i\n", x11_current_screen() );
	// fprintf( stdout, "window_width: %i\n", window_width );
	// fprintf( stdout, "window_height: %i\n", window_height );
	// fprintf( stdout, "visual->visual: %p\n", visual->visual );
	// fprintf( stdout, "visual->depth: %i\n", visual->depth );
	// fprintf( stdout, "cwmask: %i\n", cwmask );
	native_window = XCreateWindow( x11_current_display(), RootWindow(x11_current_display(), x11_current_screen()), 0, 0, window_width, window_height, 0, visual->depth, InputOutput, visual->visual, cwmask, &window_attribs );
	// fprintf( stdout, "[xwl] native_window = %i\n", (int)native_window );

	// free the visual
	// fprintf( stdout, "[xwl] Freeing visual...\n" );
	XFree( visual );


	//set window name
	// XStoreName is NOT Unicode aware! So basically, don't use anything except "Host Portable Character Encoding", (essentially, ASCII), or the result will be implementation-dependent.
	XStoreName( x11_current_display(), native_window, utf8_title );

	// to work around XStoreName's shortcomings, we use XChangeProperty with _NEW_WM_NAME
	XChangeProperty( x11_current_display(), native_window,
					XInternAtom(x11_current_display(), "_NET_WM_NAME", False),
					XInternAtom(x11_current_display(), "UTF8_STRING", False),
					8, PropModeReplace, (unsigned char*)utf8_title, strlen(utf8_title) );

	// send a message to the xserver to convert this window to fullscreen
	if ( attributes[ XWL_USE_FULLSCREEN ] )
	{
		Atom wm_state = XInternAtom( x11_current_display(), "_NET_WM_STATE", False );
		Atom fullscreen = XInternAtom( x11_current_display(), "_NET_WM_STATE_FULLSCREEN", False );

		XEvent ev;
		memset( &ev, 0, sizeof(XEvent) );
		ev.type = ClientMessage;
		ev.xclient.window = native_window;
		ev.xclient.message_type = wm_state;
		ev.xclient.format = 32;
		ev.xclient.data.l[0] = 1;
		ev.xclient.data.l[1] = fullscreen;
		ev.xclient.data.l[2] = 0;

		// fprintf( stdout, "[xwl] converting window to fullscreen...\n" );
		XSendEvent( x11_current_display(), DefaultRootWindow(x11_current_display()), False,
			SubstructureRedirectMask | SubstructureNotifyMask, &ev );
	}

	// show the window
	XMapWindow( x11_current_display(), native_window );

	XFlush( x11_current_display() );

	// standard init
	//myAtomClose = XInternAtom( x11_current_display(), "WM_DELETE_WINDOW", 0 );
	//XSetWMProtocols( x11_current_display(), handle, &myAtomClose, 1 );

	handle->handle.handle = (void*)native_window;
	//wh->handle.userdata = params->userdata;

	return (void*)native_window;
} // x11_window_create_window
Exemplo n.º 25
0
bool X11Helper::getGroupNames(Display* display, XkbConfig* xkbConfig, FetchType fetchType)
{
	static const char* OPTIONS_SEPARATOR = ",";

	Atom real_prop_type;
	int fmt;
	unsigned long nitems, extra_bytes;
	char *prop_data = NULL;
	Status ret;

	Atom rules_atom = XInternAtom(display, _XKB_RF_NAMES_PROP_ATOM, False);

	/* no such atom! */
	if (rules_atom == None) {       /* property cannot exist */
		kWarning() << "Failed to fetch layouts from server:" << "could not find the atom" << _XKB_RF_NAMES_PROP_ATOM;
		return false;
	}

	ret = XGetWindowProperty(display,
			DefaultRootWindow(display),
			rules_atom, 0L, _XKB_RF_NAMES_PROP_MAXLEN,
			False, XA_STRING, &real_prop_type, &fmt,
			&nitems, &extra_bytes,
			(unsigned char **) (void *) &prop_data);

	/* property not found! */
	if (ret != Success) {
		kWarning() << "Failed to fetch layouts from server:" << "Could not get the property";
		return false;
	}

	/* has to be array of strings */
	if ((extra_bytes > 0) || (real_prop_type != XA_STRING) || (fmt != 8)) {
		if (prop_data)
			XFree(prop_data);
		kWarning() << "Failed to fetch layouts from server:" << "Wrong property format";
		return false;
	}

//	qDebug() << "prop_data:" << nitems << prop_data;
	QStringList names;
	for(char* p=prop_data; p-prop_data < (long)nitems && p != NULL; p += strlen(p)+1) {
		names.append( p );
//		kDebug() << " " << p;
	}

	if( names.count() < 4 ) { //{ rules, model, layouts, variants, options }
		XFree(prop_data);
		return false;
	}

	if( fetchType == ALL || fetchType == LAYOUTS_ONLY ) {
		QStringList layouts = names[2].split(OPTIONS_SEPARATOR);
		QStringList variants = names[3].split(OPTIONS_SEPARATOR);

		for(int ii=0; ii<layouts.count(); ii++) {
			xkbConfig->layouts << (layouts[ii] != NULL ? layouts[ii] : "");
			xkbConfig->variants << (ii < variants.count() && variants[ii] != NULL ? variants[ii] : "");
		}
//		kDebug() << "Fetched layout groups from X server:"
//				<< "\tlayouts:" << xkbConfig->layouts
//				<< "\tvariants:" << xkbConfig->variants;
	}

	if( fetchType == ALL || fetchType == MODEL_ONLY ) {
		xkbConfig->keyboardModel = (names[1] != NULL ? names[1] : "");
//		kDebug() << "Fetched keyboard model from X server:" << xkbConfig->keyboardModel;
	}

	if( fetchType == ALL ) {
		if( names.count() >= 5 ) {
			QString options = (names[4] != NULL ? names[4] : "");
			xkbConfig->options = options.split(OPTIONS_SEPARATOR);
//			kDebug() << "Fetched xkbOptions from X server:" << options;
		}
	}

	XFree(prop_data);
	return true;
}
Exemplo n.º 26
0
/* Create auxiliary (toplevel) windows with the current visual */
static void create_aux_windows(_THIS)
{
    int x = 0, y = 0;
    char classname[1024];
    XSetWindowAttributes xattr;
    XWMHints *hints;
    unsigned long app_event_mask;
    int def_vis = (SDL_Visual == DefaultVisual(SDL_Display, SDL_Screen));

    /* Look up some useful Atoms */
    WM_DELETE_WINDOW = XInternAtom(SDL_Display, "WM_DELETE_WINDOW", False);

    /* Don't create any extra windows if we are being managed */
    if ( SDL_windowid ) {
	FSwindow = 0;
	WMwindow = SDL_strtol(SDL_windowid, NULL, 0);
        return;
    }

    if(FSwindow)
	XDestroyWindow(SDL_Display, FSwindow);

#if SDL_VIDEO_DRIVER_X11_XINERAMA
    if ( use_xinerama ) {
        x = xinerama_info.x_org;
        y = xinerama_info.y_org;
    }
#endif
    xattr.override_redirect = True;
    xattr.background_pixel = def_vis ? BlackPixel(SDL_Display, SDL_Screen) : 0;
    xattr.border_pixel = 0;
    xattr.colormap = SDL_XColorMap;

    FSwindow = XCreateWindow(SDL_Display, SDL_Root,
                             x + X11_wmXAdjust,
                             y + X11_wmYAdjust,
                             32, 32, 0,
			     this->hidden->depth, InputOutput, SDL_Visual,
			     CWOverrideRedirect | CWBackPixel | CWBorderPixel
			     | CWColormap,
			     &xattr);

    XSelectInput(SDL_Display, FSwindow, StructureNotifyMask);

    /* Tell KDE to keep the fullscreen window on top */
    {
	XEvent ev;
	long mask;

	SDL_memset(&ev, 0, sizeof(ev));
	ev.xclient.type = ClientMessage;
	ev.xclient.window = SDL_Root;
	ev.xclient.message_type = XInternAtom(SDL_Display,
					      "KWM_KEEP_ON_TOP", False);
	ev.xclient.format = 32;
	ev.xclient.data.l[0] = FSwindow;
	ev.xclient.data.l[1] = CurrentTime;
	mask = SubstructureRedirectMask;
	XSendEvent(SDL_Display, SDL_Root, False, mask, &ev);
    }

    hints = NULL;
    if(WMwindow) {
	/* All window attributes must survive the recreation */
	hints = XGetWMHints(SDL_Display, WMwindow);
	XDestroyWindow(SDL_Display, WMwindow);
    }

    /* Create the window for windowed management */
    /* (reusing the xattr structure above) */
    WMwindow = XCreateWindow(SDL_Display, SDL_Root,
                             x, y, 32, 32, 0,
			     this->hidden->depth, InputOutput, SDL_Visual,
			     CWBackPixel | CWBorderPixel | CWColormap,
			     &xattr);

    /* Set the input hints so we get keyboard input */
    if(!hints) {
	hints = XAllocWMHints();
	hints->input = True;
	hints->flags = InputHint;
    }
    XSetWMHints(SDL_Display, WMwindow, hints);
    XFree(hints);
    X11_SetCaptionNoLock(this, this->wm_title, this->wm_icon);

    app_event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
	| PropertyChangeMask | StructureNotifyMask | KeymapStateMask;
    XSelectInput(SDL_Display, WMwindow, app_event_mask);

    /* Set the class hints so we can get an icon (AfterStep) */
    get_classname(classname, sizeof(classname));
    {
	XClassHint *classhints;
	classhints = XAllocClassHint();
	if(classhints != NULL) {
	    classhints->res_name = classname;
	    classhints->res_class = classname;
	    XSetClassHint(SDL_Display, WMwindow, classhints);
	    XFree(classhints);
	}
    }

	{
		pid_t pid = getpid();
		char hostname[256];

		if (pid > 0 && gethostname(hostname, sizeof(hostname)) > -1) {
			Atom _NET_WM_PID = XInternAtom(SDL_Display, "_NET_WM_PID", False);
			Atom WM_CLIENT_MACHINE = XInternAtom(SDL_Display, "WM_CLIENT_MACHINE", False);
			
			hostname[sizeof(hostname)-1] = '\0';
			XChangeProperty(SDL_Display, WMwindow, _NET_WM_PID, XA_CARDINAL, 32,
					PropModeReplace, (unsigned char *)&pid, 1);
			XChangeProperty(SDL_Display, WMwindow, WM_CLIENT_MACHINE, XA_STRING, 8,
					PropModeReplace, (unsigned char *)hostname, SDL_strlen(hostname));
		}
	}

	/* Setup the communication with the IM server */
	/* create_aux_windows may be called several times against the same
	   Display.  We should reuse the SDL_IM if one has been opened for
	   the Display, so we should not simply reset SDL_IM here.  */

	#ifdef X_HAVE_UTF8_STRING
	if (SDL_X11_HAVE_UTF8) {
		/* Discard obsolete resources if any.  */
		if (SDL_IM != NULL && SDL_Display != XDisplayOfIM(SDL_IM)) {
			/* Just a double check. I don't think this
		           code is ever executed. */
			SDL_SetError("display has changed while an IM is kept");
			if (SDL_IC) {
				XUnsetICFocus(SDL_IC);
				XDestroyIC(SDL_IC);
				SDL_IC = NULL;
			}
			XCloseIM(SDL_IM);
			SDL_IM = NULL;
		}

		/* Open an input method.  */
		if (SDL_IM == NULL) {
			char *old_locale = NULL, *old_modifiers = NULL;
			const char *p;
			size_t n;
			/* I'm not comfortable to do locale setup
			   here.  However, we need C library locale
			   (and xlib modifiers) to be set based on the
			   user's preference to use XIM, and many
			   existing game programs doesn't take care of
			   users' locale preferences, so someone other
			   than the game program should do it.
			   Moreover, ones say that some game programs
			   heavily rely on the C locale behaviour,
			   e.g., strcol()'s, and we can't change the C
			   library locale.  Given the situation, I
			   couldn't find better place to do the
			   job... */

			/* Save the current (application program's)
			   locale settings.  */
			p = setlocale(LC_ALL, NULL);
			if ( p ) {
				n = SDL_strlen(p)+1;
				old_locale = SDL_stack_alloc(char, n);
				if ( old_locale ) {
					SDL_strlcpy(old_locale, p, n);
				}
			}
			p = XSetLocaleModifiers(NULL);
			if ( p ) {
				n = SDL_strlen(p)+1;
				old_modifiers = SDL_stack_alloc(char, n);
				if ( old_modifiers ) {
					SDL_strlcpy(old_modifiers, p, n);
				}
			}

			/* Fetch the user's preferences and open the
			   input method with them.  */
			setlocale(LC_ALL, "");
			XSetLocaleModifiers("");
			SDL_IM = XOpenIM(SDL_Display, NULL, classname, classname);

			/* Restore the application's locale settings
			   so that we don't break the application's
			   expected behaviour.  */
			if ( old_locale ) {
				/* We need to restore the C library
				   locale first, since the
				   interpretation of the X modifier
				   may depend on it.  */
				setlocale(LC_ALL, old_locale);
				SDL_stack_free(old_locale);
			}
			if ( old_modifiers ) {
				XSetLocaleModifiers(old_modifiers);
				SDL_stack_free(old_modifiers);
			}
		}

		/* Create a new input context for the new window just created.  */
		if (SDL_IM == NULL) {
			SDL_SetError("no input method could be opened");
		} else {
			if (SDL_IC != NULL) {
				/* Discard the old IC before creating new one.  */
			    XUnsetICFocus(SDL_IC);
			    XDestroyIC(SDL_IC);
			}
			/* Theoretically we should check the current IM supports
			   PreeditNothing+StatusNothing style (i.e., root window method)
			   before creating the IC.  However, it is the bottom line method,
			   and we supports any other options.  If the IM didn't support
			   root window method, the following call fails, and SDL falls
			   back to pre-XIM keyboard handling.  */
			SDL_IC = pXCreateIC(SDL_IM,
					XNClientWindow, WMwindow,
					XNFocusWindow, WMwindow,
					XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
					XNResourceName, classname,
					XNResourceClass, classname,
					NULL);

			if (SDL_IC == NULL) {
				SDL_SetError("no input context could be created");
				XCloseIM(SDL_IM);
				SDL_IM = NULL;
			} else {
				/* We need to receive X events that an IM wants and to pass
				   them to the IM through XFilterEvent. The set of events may
				   vary depending on the IM implementation and the options
				   specified through various routes. Although unlikely, the
				   xlib specification allows IM to change the event requirement
				   with its own circumstances, it is safe to call SelectInput
				   whenever we re-create an IC.  */
				unsigned long mask = 0;
				char *ret = pXGetICValues(SDL_IC, XNFilterEvents, &mask, NULL);
				if (ret != NULL) {
					XUnsetICFocus(SDL_IC);
					XDestroyIC(SDL_IC);
					SDL_IC = NULL;
					SDL_SetError("no input context could be created");
					XCloseIM(SDL_IM);
					SDL_IM = NULL;
				} else {
					XSelectInput(SDL_Display, WMwindow, app_event_mask | mask);
					XSetICFocus(SDL_IC);
				}
			}
		}
	}
Exemplo n.º 27
0
bool
XimServer::setupConnection(bool useDefaultIM)
{
    const char *buf;
    if (!useDefaultIM) {
	return false;
    } else {
	buf = "@server=uim";
    }
    mServerAtom = XInternAtom(XimServer::gDpy, buf, 0);
    Window owner = XGetSelectionOwner(XimServer::gDpy, mServerAtom);
    if (owner != None) {
	if (!useDefaultIM)
	    printf("Another instance exists (uim-%s).\n", mIMName);
	else
	    printf("Another instance exists (uim).\n");
	return false;
    }
    mSelectionWin = XCreateSimpleWindow(XimServer::gDpy,
					DefaultRootWindow(XimServer::gDpy),
					0, 0, 1, 1,
					1, 0, 0);
    XSetSelectionOwner(XimServer::gDpy, mServerAtom, mSelectionWin, CurrentTime);
    XSelectInput(XimServer::gDpy, DefaultRootWindow(XimServer::gDpy), 0);
    XSync(XimServer::gDpy, False);

    Atom type;
    int format;
    unsigned long nr_prop, nr_bytes;
    Atom *prop;
    int mode = PropModePrepend;
    int valuechange = 1;

    XGetWindowProperty(XimServer::gDpy, DefaultRootWindow(XimServer::gDpy),
		       xim_servers, 0, 8192 ,False,
		       XA_ATOM, &type, &format,
		       &nr_prop, &nr_bytes, (unsigned char **)(uintptr_t)&prop);
    int i;
    if (type != XA_ATOM || format != 32)
	mode = PropModeReplace;
    else {
	for (i = 0; i < (int)nr_prop; i++) {
	    if (prop[i] == mServerAtom) {
		mode = PropModeAppend;
		valuechange = 0;
		break;
	    }
	}
    }
    if (nr_prop)
	XFree(prop);

    XChangeProperty(XimServer::gDpy, DefaultRootWindow(XimServer::gDpy),
		    xim_servers,
		    XA_ATOM, 32,
		    mode, (unsigned char *)&mServerAtom,
		    valuechange ? 1 : 0);
    std::pair<Window, XimServer *> p(mSelectionWin, this);
    gServerMap.insert(p);
    return true;
}
Exemplo n.º 28
0
void start_net()
{
	if (systray_profile)
		fprintf(stderr, "[%f] %s:%d\n", profiling_get_time(), __FUNCTION__, __LINE__);
	if (net_sel_win) {
		// protocol already started
		if (!systray_enabled)
			stop_net();
		return;
	} else {
		if (!systray_enabled)
			return;
	}

	Window win = XGetSelectionOwner(server.display, server.atom._NET_SYSTEM_TRAY_SCREEN);

	// freedesktop systray specification
	if (win != None) {
		// search pid
		Atom _NET_WM_PID, actual_type;
		int actual_format;
		unsigned long nitems;
		unsigned long bytes_after;
		unsigned char *prop = 0;
		int pid;

		_NET_WM_PID = XInternAtom(server.display, "_NET_WM_PID", True);
		int ret = XGetWindowProperty(server.display,
		                             win,
		                             _NET_WM_PID,
		                             0,
		                             1024,
		                             False,
		                             AnyPropertyType,
		                             &actual_type,
		                             &actual_format,
		                             &nitems,
		                             &bytes_after,
		                             &prop);

		fprintf(stderr, RED "tint2 : another systray is running" RESET);
		if (ret == Success && prop) {
			pid = prop[1] * 256;
			pid += prop[0];
			fprintf(stderr, " pid=%d", pid);
		}
		fprintf(stderr, RESET "\n");
		return;
	}

	// init systray protocol
	net_sel_win = XCreateSimpleWindow(server.display, server.root_win, -1, -1, 1, 1, 0, 0, 0);
	fprintf(stderr, "systray window %ld\n", net_sel_win);

	// v0.3 trayer specification. tint2 always horizontal.
	// Vertical panel will draw the systray horizontal.
	long orientation = 0;
	XChangeProperty(server.display,
	                net_sel_win,
	                server.atom._NET_SYSTEM_TRAY_ORIENTATION,
	                XA_CARDINAL,
	                32,
	                PropModeReplace,
	                (unsigned char *)&orientation,
	                1);
	if (systray.icon_size > 0) {
		long icon_size = systray.icon_size;
		XChangeProperty(server.display,
		                net_sel_win,
		                server.atom._NET_SYSTEM_TRAY_ICON_SIZE,
		                XA_CARDINAL,
		                32,
		                PropModeReplace,
		                (unsigned char *)&icon_size,
		                1);
	}
	long padding = 0;
	XChangeProperty(server.display,
	                net_sel_win,
	                server.atom._NET_SYSTEM_TRAY_PADDING,
	                XA_CARDINAL,
	                32,
	                PropModeReplace,
	                (unsigned char *)&padding,
	                1);

	VisualID vid;
	if (systray_composited)
		vid = XVisualIDFromVisual(server.visual32);
	else
		vid = XVisualIDFromVisual(server.visual);
	XChangeProperty(server.display,
	                net_sel_win,
					XInternAtom(server.display, "_NET_SYSTEM_TRAY_VISUAL", False),
	                XA_VISUALID,
	                32,
	                PropModeReplace,
	                (unsigned char *)&vid,
	                1);

	XSetSelectionOwner(server.display, server.atom._NET_SYSTEM_TRAY_SCREEN, net_sel_win, CurrentTime);
	if (XGetSelectionOwner(server.display, server.atom._NET_SYSTEM_TRAY_SCREEN) != net_sel_win) {
		stop_net();
		fprintf(stderr, RED "tint2 : can't get systray manager" RESET "\n");
		return;
	}

	fprintf(stderr, GREEN "tint2 : systray started" RESET "\n");
	if (systray_profile)
		fprintf(stderr, "[%f] %s:%d\n", profiling_get_time(), __FUNCTION__, __LINE__);
	XClientMessageEvent ev;
	ev.type = ClientMessage;
	ev.window = server.root_win;
	ev.message_type = server.atom.MANAGER;
	ev.format = 32;
	ev.data.l[0] = CurrentTime;
	ev.data.l[1] = server.atom._NET_SYSTEM_TRAY_SCREEN;
	ev.data.l[2] = net_sel_win;
	ev.data.l[3] = 0;
	ev.data.l[4] = 0;
	XSendEvent(server.display, server.root_win, False, StructureNotifyMask, (XEvent *)&ev);
}
Exemplo n.º 29
0
void
CXWindowsClipboard::motifFillCache()
{
	LOG((CLOG_DEBUG "Motif fill clipboard %d", m_id));

	// get the Motif clipboard header property from the root window
	Atom target;
	SInt32 format;
	CString data;
	Window root = RootWindow(m_display, DefaultScreen(m_display));
	if (!CXWindowsUtil::getWindowProperty(m_display, root,
								m_atomMotifClipHeader,
								&data, &target, &format, False)) {
		return;
	}

	// check that the header is okay
	const CMotifClipHeader* header =
						reinterpret_cast<const CMotifClipHeader*>(data.data());
	if (data.size() < sizeof(CMotifClipHeader) ||
		header->m_id != kMotifClipHeader ||
		header->m_numItems < 1) {
		return;
	}

	// get the Motif item property from the root window
	char name[18 + 20];
	sprintf(name, "_MOTIF_CLIP_ITEM_%d", header->m_item);
    Atom atomItem = XInternAtom(m_display, name, False);
	data = "";
	if (!CXWindowsUtil::getWindowProperty(m_display, root,
								atomItem, &data,
								&target, &format, False)) {
		return;
	}

	// check that the item is okay
	const CMotifClipItem* item =
					reinterpret_cast<const CMotifClipItem*>(data.data());
	if (data.size() < sizeof(CMotifClipItem) ||
		item->m_id != kMotifClipItem ||
		item->m_numFormats - item->m_numDeletedFormats < 1) {
		return;
	}

	// format list is after static item structure elements
	const SInt32 numFormats = item->m_numFormats - item->m_numDeletedFormats;
	const SInt32* formats   = reinterpret_cast<const SInt32*>(item->m_size +
								reinterpret_cast<const char*>(data.data()));

	// get the available formats
	typedef std::map<Atom, CString> CMotifFormatMap;
	CMotifFormatMap motifFormats;
	for (SInt32 i = 0; i < numFormats; ++i) {
		// get Motif format property from the root window
		sprintf(name, "_MOTIF_CLIP_ITEM_%d", formats[i]);
    	Atom atomFormat = XInternAtom(m_display, name, False);
		CString data;
		if (!CXWindowsUtil::getWindowProperty(m_display, root,
									atomFormat, &data,
									&target, &format, False)) {
			continue;
		}

		// check that the format is okay
		const CMotifClipFormat* motifFormat =
						reinterpret_cast<const CMotifClipFormat*>(data.data());
		if (data.size() < sizeof(CMotifClipFormat) ||
			motifFormat->m_id != kMotifClipFormat ||
			motifFormat->m_length < 0 ||
			motifFormat->m_type == None ||
			motifFormat->m_deleted != 0) {
			continue;
		}

		// save it
		motifFormats.insert(std::make_pair(motifFormat->m_type, data));
	}
	//const UInt32 numMotifFormats = motifFormats.size();

	// try each converter in order (because they're in order of
	// preference).
	for (ConverterList::const_iterator index = m_converters.begin();
								index != m_converters.end(); ++index) {
		IXWindowsClipboardConverter* converter = *index;

		// skip already handled targets
		if (m_added[converter->getFormat()]) {
			continue;
		}

		// see if atom is in target list
		CMotifFormatMap::const_iterator index2 =
								motifFormats.find(converter->getAtom());
		if (index2 == motifFormats.end()) {
			continue;
		}

		// get format
		const CMotifClipFormat* motifFormat =
								reinterpret_cast<const CMotifClipFormat*>(
									index2->second.data());
		const Atom target                   = motifFormat->m_type;

		// get the data (finally)
		Atom actualTarget;
		CString targetData;
		if (!motifGetSelection(motifFormat, &actualTarget, &targetData)) {
			LOG((CLOG_DEBUG1 "  no data for target %s", CXWindowsUtil::atomToString(m_display, target).c_str()));
			continue;
		}

		// add to clipboard and note we've done it
		IClipboard::EFormat format = converter->getFormat();
		m_data[format]  = converter->toIClipboard(targetData);
		m_added[format] = true;
		LOG((CLOG_DEBUG "  added format %d for target %s", format, CXWindowsUtil::atomToString(m_display, target).c_str()));
	}
}
Exemplo n.º 30
0
static gboolean
get_work_area (NotifyStack  *stack,
               GdkRectangle *rect)
{
        Atom            workarea;
        Atom            type;
        Window          win;
        int             format;
        gulong          num;
        gulong          leftovers;
        gulong          max_len = 4 * 32;
        guchar         *ret_workarea;
        long           *workareas;
        int             result;
        int             disp_screen;

	workarea = XInternAtom(GDK_DISPLAY_XDISPLAY(gdk_display_get_default()), "_NET_WORKAREA", True);


        disp_screen = GDK_SCREEN_XNUMBER (stack->screen);

        /* Defaults in case of error */
        rect->x = 0;
        rect->y = 0;
        rect->width = gdk_screen_get_width (stack->screen);
        rect->height = gdk_screen_get_height (stack->screen);

        if (workarea == None)
                return FALSE;


	win = XRootWindow(GDK_DISPLAY_XDISPLAY(gdk_display_get_default()), disp_screen);

	result = XGetWindowProperty(GDK_DISPLAY_XDISPLAY(gdk_display_get_default()),
		win,
		workarea,
		0,
		max_len,
		False,
		AnyPropertyType,
		&type,
		&format,
		&num,
		&leftovers,
		&ret_workarea);


        if (result != Success
            || type == None
            || format == 0
            || leftovers
            || num % 4) {
                return FALSE;
        }

        workareas = (long *) ret_workarea;
        rect->x = workareas[disp_screen * 4];
        rect->y = workareas[disp_screen * 4 + 1];
        rect->width = workareas[disp_screen * 4 + 2];
        rect->height = workareas[disp_screen * 4 + 3];

        XFree (ret_workarea);

        return TRUE;
}