Example #1
0
void X11Window::poll()
{
    bool needsResizeUpdate = false;

    XEvent event, peekEvent;
    while(XPending(m_display) > 0) {
        XNextEvent(m_display, &event);

        // check for repeated key releases
        bool repatedKeyRelease = false;
        if(event.type == KeyRelease && XPending(m_display)) {
            XPeekEvent(m_display, &peekEvent);
            if((peekEvent.type == KeyPress) && (peekEvent.xkey.keycode == event.xkey.keycode) && ((peekEvent.xkey.time-event.xkey.time) < 2))
                repatedKeyRelease = true;
        }

        // process keydown and keyrelease events first
        if(event.type == KeyPress || (event.type == KeyRelease && !repatedKeyRelease)) {
            // remove caps lock and shift maks
            XKeyEvent xkey = event.xkey;
            xkey.state &= ~(ShiftMask | LockMask);

            // lookup keysym and translate it
            KeySym keysym;
            char buf[32];
            XLookupString(&xkey, buf, sizeof(buf), &keysym, 0);
            Fw::Key keyCode = Fw::KeyUnknown;

            if(m_keyMap.find(keysym) != m_keyMap.end())
                keyCode = m_keyMap[keysym];

            if(event.type == KeyPress)
                processKeyDown(keyCode);
            else if(event.type == KeyRelease)
                processKeyUp(keyCode);
        }

        // call filter because xim will discard KeyPress events when keys still composing
        if(XFilterEvent(&event, m_window))
            continue;

        // discard repated key releases
        if(repatedKeyRelease)
            continue;

        switch(event.type) {
            case ClientMessage: {
                // close event
                if((Atom)event.xclient.data.l[0] == m_wmDelete && m_onClose)
                    m_onClose();
                break;
            }
            case ConfigureNotify: {
                Size newSize(event.xconfigure.width, event.xconfigure.height);
                Point newPos(event.xconfigure.x, event.xconfigure.y);

                // updates window size
                if(m_size != newSize) {
                    m_size = newSize;
                    needsResizeUpdate = true;
                }

                // checks if the window is maximized
                if(m_visible) {
                    m_maximized = false;
                    Atom wmState = XInternAtom(m_display, "_NET_WM_STATE", False);
                    Atom wmStateMaximizedVert = XInternAtom(m_display, "_NET_WM_STATE_MAXIMIZED_VERT", False);
                    Atom wmStateMaximizedHorz = XInternAtom(m_display, "_NET_WM_STATE_MAXIMIZED_HORZ", False);
                    Atom actualType;
                    ulong i, numItems, bytesAfter;
                    uchar *propertyValue = NULL;
                    int actualFormat;

                    if(XGetWindowProperty(m_display, m_window, wmState,
                                        0, 1024, False, XA_ATOM, &actualType,
                                        &actualFormat, &numItems, &bytesAfter,
                                        &propertyValue) == Success) {
                        Atom *atoms = (Atom*)propertyValue;
                        int maximizedMask = 0;

                        for(i=0; i<numItems; ++i) {
                            if(atoms[i] == wmStateMaximizedVert)
                                maximizedMask |= 1;
                            else if(atoms[i] == wmStateMaximizedHorz)
                                maximizedMask |= 2;
                        }

                        if(maximizedMask == 3)
                            m_maximized = true;

                        XFree(propertyValue);
                    }
                }

                // updates window pos
                if(m_visible)
                    m_position = newPos;
                updateUnmaximizedCoords();
                break;
            }
            case SelectionRequest: {
                XEvent respond;
                XSelectionRequestEvent *req = &(event.xselectionrequest);

                Atom targets = XInternAtom(m_display, "TARGETS", False);
                if(req->target == targets) {
                    Atom typeList[] = { XInternAtom(m_display, "UTF8_STRING", False),
                                        XInternAtom(m_display, "TEXT", False),
                                        XInternAtom(m_display, "STRING", False),
                                        XInternAtom(m_display, "text/plain", False),
                                        XInternAtom(m_display, "COMPOUND_TEXT", False),
                                        XA_STRING };

                    XChangeProperty(m_display, req->requestor,
                                    req->property, req->target,
                                    8, PropModeReplace,
                                    (uchar *)&typeList,
                                    sizeof(typeList));
                    respond.xselection.property = req->property;
                } else {
                    XChangeProperty(m_display,
                                    req->requestor,
                                    req->property, req->target,
                                    8,
                                    PropModeReplace,
                                    (uchar *)m_clipboardText.c_str(),
                                    m_clipboardText.length());
                    respond.xselection.property = req->property;
                }

                respond.xselection.type = SelectionNotify;
                respond.xselection.display = req->display;
                respond.xselection.requestor = req->requestor;
                respond.xselection.selection = req->selection;
                respond.xselection.target = req->target;
                respond.xselection.time = req->time;
                XSendEvent(m_display, req->requestor, 0, 0, &respond);
                XFlush(m_display);
                break;
            }
            // process text events
            case KeyPress: {
                // text cant be insert while holding ctrl or alt
                if(event.xkey.state & ControlMask || event.xkey.state & Mod1Mask)
                    break;

                // process key text events
                KeySym keysym;
                char buf[32];
                memset(buf, 0, 32);
                int len;

                // lookup for keyText
                if(m_xic) { // with xim we can get latin1 input correctly
                    Status status;
                    len = XmbLookupString(m_xic, &event.xkey, buf, sizeof(buf), &keysym, &status);
                } else { // otherwise use XLookupString, but often it doesn't work right with dead keys
                    static XComposeStatus compose = {NULL, 0};
                    len = XLookupString(&event.xkey, buf, sizeof(buf), &keysym, &compose);
                }

                // filter unwanted characters
                if(len == 0 || (uchar)(buf[0]) < 32 || keysym == XK_BackSpace || keysym == XK_Return || keysym == XK_Delete || keysym == XK_Escape)
                    break;
                std::string text = buf;

                //g_logger.debug("char: ", buf[0], " code: ", (int)((uchar)buf[0]));

                if(m_onInputEvent && text.length() > 0) {
                    m_inputEvent.reset(Fw::KeyTextInputEvent);
                    m_inputEvent.keyText = text;
                    m_onInputEvent(m_inputEvent);
                }
                break;
            }
            case ButtonPress:
            case ButtonRelease: {
                m_inputEvent.reset();
                m_inputEvent.type = (event.type == ButtonPress) ? Fw::MousePressInputEvent : Fw::MouseReleaseInputEvent;
                switch(event.xbutton.button) {
                    case Button1:
                        m_inputEvent.mouseButton = Fw::MouseLeftButton;
                        m_mouseButtonStates[Fw::MouseLeftButton] = (event.type == ButtonPress);
                        break;
                    case Button3:
                        m_inputEvent.mouseButton = Fw::MouseRightButton;
                        m_mouseButtonStates[Fw::MouseRightButton] = (event.type == ButtonPress);
                        break;
                    case Button2:
                        m_inputEvent.mouseButton = Fw::MouseMidButton;
                        m_mouseButtonStates[Fw::MouseMidButton] = (event.type == ButtonPress);
                        break;
                    case Button4:
                        if(event.type == ButtonPress) {
                            m_inputEvent.type = Fw::MouseWheelInputEvent;
                            m_inputEvent.mouseButton = Fw::MouseMidButton;
                            m_inputEvent.wheelDirection = Fw::MouseWheelUp;
                        }
                        break;
                    case Button5:
                        if(event.type == ButtonPress) {
                            m_inputEvent.type = Fw::MouseWheelInputEvent;
                            m_inputEvent.mouseButton = Fw::MouseMidButton;
                            m_inputEvent.wheelDirection = Fw::MouseWheelDown;
                        }
                        break;
                    default:
                        m_inputEvent.type = Fw::NoInputEvent;
                        break;
                }
                if(m_inputEvent.type != Fw::NoInputEvent && m_onInputEvent)
                    m_onInputEvent(m_inputEvent);
                break;
            }

            case MotionNotify: {
                m_inputEvent.reset();
                m_inputEvent.type = Fw::MouseMoveInputEvent;
                Point newMousePos(event.xbutton.x, event.xbutton.y);
                m_inputEvent.mouseMoved = newMousePos - m_inputEvent.mousePos;
                m_inputEvent.mousePos = newMousePos;
                if(m_onInputEvent)
                    m_onInputEvent(m_inputEvent);
                break;
            }
            case MapNotify:
                m_visible = true;
                needsResizeUpdate = true;
                break;
            case UnmapNotify:
                m_visible = false;
                releaseAllKeys();
                break;
            case FocusIn:
                m_focused = true;
                releaseAllKeys();
                break;
            case FocusOut:
                m_focused = false;
                releaseAllKeys();
                break;
            case Expose:
                // window needs redraw
                break;
        }
    }

    if(needsResizeUpdate && m_onResize)
        m_onResize(m_size);

    fireKeysPress();
}
Example #2
0
void NETWM::set_active_window(Window win)
{
    //Set NET-WM active window
    XChangeProperty(fl_display, root_win, _XA_NET_ACTIVE_WINDOW, XA_WINDOW, 32,
                    PropModeReplace, (unsigned char *)&win, 1);
}
Example #3
0
/* put data into a selection, in response to a SelecionRequest event from
 * another window (and any subsequent events relating to an INCR transfer).
 *
 * Arguments are:
 *
 * A display
 * 
 * A window
 * 
 * The event to respond to
 * 
 * A pointer to an Atom. This gets set to the property nominated by the other
 * app in it's SelectionRequest. Things are likely to break if you change the
 * value of this yourself.
 * 
 * The target(UTF8_STRING or XA_STRING) to respond to
 *
 * A pointer to an array of chars to read selection data from.
 * 
 * The length of the array of chars.
 *
 * In the case of an INCR transfer, the position within the array of chars
 * that is being processed.
 *
 * The context that event is the be processed within.
 */
int
xcin(Display * dpy,
     Window * win,
     XEvent evt,
     Atom * pty, Atom target, unsigned char *txt, unsigned long len, unsigned long *pos,
     unsigned int *context)
{
    unsigned long chunk_len;	/* length of current chunk (for incr
				 * transfers only)
				 */
    XEvent res;			/* response to event */
    static Atom inc;
    static Atom targets;
    static long chunk_size;

    if (!targets) {
	targets = XInternAtom(dpy, "TARGETS", False);
    }

    if (!inc) {
	inc = XInternAtom(dpy, "INCR", False);
    }

    /* We consider selections larger than a quarter of the maximum
       request size to be "large". See ICCCM section 2.5 */
    if (!chunk_size) {
	chunk_size = XExtendedMaxRequestSize(dpy) / 4;
	if (!chunk_size) {
	    chunk_size = XMaxRequestSize(dpy) / 4;
	}
    }

    switch (*context) {
    case XCLIB_XCIN_NONE:
	if (evt.type != SelectionRequest)
	    return (0);

	/* set the window and property that is being used */
	*win = evt.xselectionrequest.requestor;
	*pty = evt.xselectionrequest.property;

	/* reset position to 0 */
	*pos = 0;

	/* put the data into an property */
	if (evt.xselectionrequest.target == targets) {
	    Atom types[2] = { targets, target };

	    /* send data all at once (not using INCR) */
	    XChangeProperty(dpy,
			    *win,
			    *pty,
			    XA_ATOM,
			    32, PropModeReplace, (unsigned char *) types,
			    (int) (sizeof(types) / sizeof(Atom))
		);
	}
	else if (len > chunk_size) {
	    /* send INCR response */
	    XChangeProperty(dpy, *win, *pty, inc, 32, PropModeReplace, 0, 0);

	    /* With the INCR mechanism, we need to know
	     * when the requestor window changes (deletes)
	     * its properties
	     */
	    XSelectInput(dpy, *win, PropertyChangeMask);

	    *context = XCLIB_XCIN_INCR;
	}
	else {
	    /* send data all at once (not using INCR) */
	    XChangeProperty(dpy,
			    *win,
			    *pty, target, 8, PropModeReplace, (unsigned char *) txt, (int) len);
	}

	/* Perhaps FIXME: According to ICCCM section 2.5, we should
	   confirm that XChangeProperty succeeded without any Alloc
	   errors before replying with SelectionNotify. However, doing
	   so would require an error handler which modifies a global
	   variable, plus doing XSync after each XChangeProperty. */

	/* set values for the response event */
	res.xselection.property = *pty;
	res.xselection.type = SelectionNotify;
	res.xselection.display = evt.xselectionrequest.display;
	res.xselection.requestor = *win;
	res.xselection.selection = evt.xselectionrequest.selection;
	res.xselection.target = evt.xselectionrequest.target;
	res.xselection.time = evt.xselectionrequest.time;

	/* send the response event */
	XSendEvent(dpy, evt.xselectionrequest.requestor, 0, 0, &res);
	XFlush(dpy);

	/* if len < chunk_size, then the data was sent all at
	 * once and the transfer is now complete, return 1
	 */
	if (len > chunk_size)
	    return (0);
	else
	    return (1);

	break;

    case XCLIB_XCIN_INCR:
	/* length of current chunk */

	/* ignore non-property events */
	if (evt.type != PropertyNotify)
	    return (0);

	/* ignore the event unless it's to report that the
	 * property has been deleted
	 */
	if (evt.xproperty.state != PropertyDelete)
	    return (0);

	/* set the chunk length to the maximum size */
	chunk_len = chunk_size;

	/* if a chunk length of maximum size would extend
	 * beyond the end ot txt, set the length to be the
	 * remaining length of txt
	 */
	if ((*pos + chunk_len) > len)
	    chunk_len = len - *pos;

	/* if the start of the chunk is beyond the end of txt,
	 * then we've already sent all the data, so set the
	 * length to be zero
	 */
	if (*pos > len)
	    chunk_len = 0;

	if (chunk_len) {
	    /* put the chunk into the property */
	    XChangeProperty(dpy,
			    *win, *pty, target, 8, PropModeReplace, &txt[*pos], (int) chunk_len);
	}
	else {
	    /* make an empty property to show we've
	     * finished the transfer
	     */
	    XChangeProperty(dpy, *win, *pty, target, 8, PropModeReplace, 0, 0);
	}
	XFlush(dpy);

	/* all data has been sent, break out of the loop */
	if (!chunk_len)
	    *context = XCLIB_XCIN_NONE;

	*pos += chunk_size;

	/* if chunk_len == 0, we just finished the transfer,
	 * return 1
	 */
	if (chunk_len > 0)
	    return (0);
	else
	    return (1);
	break;
    }
    return (0);
}
Example #4
0
// Create the X11 window (and its colormap)
//
static GLboolean createWindow(_GLFWwindow* window,
                              const _GLFWwndconfig* wndconfig)
{
    unsigned long wamask;
    XSetWindowAttributes wa;
    XVisualInfo* visual = _GLFW_X11_CONTEXT_VISUAL;

    // Every window needs a colormap
    // Create one based on the visual used by the current context
    // TODO: Decouple this from context creation

    window->x11.colormap = XCreateColormap(_glfw.x11.display,
                                           _glfw.x11.root,
                                           visual->visual,
                                           AllocNone);

    // Create the actual window
    {
        wamask = CWBorderPixel | CWColormap | CWEventMask;

        wa.colormap = window->x11.colormap;
        wa.border_pixel = 0;
        wa.event_mask = StructureNotifyMask | KeyPressMask | KeyReleaseMask |
                        PointerMotionMask | ButtonPressMask | ButtonReleaseMask |
                        ExposureMask | FocusChangeMask | VisibilityChangeMask |
                        EnterWindowMask | LeaveWindowMask | PropertyChangeMask;

        _glfwGrabXErrorHandler();

        window->x11.handle = XCreateWindow(_glfw.x11.display,
                                           _glfw.x11.root,
                                           0, 0,
                                           wndconfig->width, wndconfig->height,
                                           0,              // Border width
                                           visual->depth,  // Color depth
                                           InputOutput,
                                           visual->visual,
                                           wamask,
                                           &wa);

        _glfwReleaseXErrorHandler();

        if (!window->x11.handle)
        {
            _glfwInputXError(GLFW_PLATFORM_ERROR,
                             "X11: Failed to create window");
            return GL_FALSE;
        }

        if (!wndconfig->decorated)
        {
            MotifWmHints hints;
            hints.flags = MWM_HINTS_DECORATIONS;
            hints.decorations = 0;

            XChangeProperty(_glfw.x11.display, window->x11.handle,
                            _glfw.x11.MOTIF_WM_HINTS,
                            _glfw.x11.MOTIF_WM_HINTS, 32,
                            PropModeReplace,
                            (unsigned char*) &hints,
                            sizeof(MotifWmHints) / sizeof(long));
        }

        XSaveContext(_glfw.x11.display,
                     window->x11.handle,
                     _glfw.x11.context,
                     (XPointer) window);
    }

    if (window->monitor && !_glfw.x11.hasEWMH)
    {
        // This is the butcher's way of removing window decorations
        // Setting the override-redirect attribute on a window makes the window
        // manager ignore the window completely (ICCCM, section 4)
        // The good thing is that this makes undecorated fullscreen windows
        // easy to do; the bad thing is that we have to do everything manually
        // and some things (like iconify/restore) won't work at all, as those
        // are tasks usually performed by the window manager

        XSetWindowAttributes attributes;
        attributes.override_redirect = True;
        XChangeWindowAttributes(_glfw.x11.display,
                                window->x11.handle,
                                CWOverrideRedirect,
                                &attributes);

        window->x11.overrideRedirect = GL_TRUE;
    }

    // Declare the WM protocols supported by GLFW
    {
        int count = 0;
        Atom protocols[2];

        // The WM_DELETE_WINDOW ICCCM protocol
        // Basic window close notification protocol
        if (_glfw.x11.WM_DELETE_WINDOW)
            protocols[count++] = _glfw.x11.WM_DELETE_WINDOW;

        // The _NET_WM_PING EWMH protocol
        // Tells the WM to ping the GLFW window and flag the application as
        // unresponsive if the WM doesn't get a reply within a few seconds
        if (_glfw.x11.NET_WM_PING)
            protocols[count++] = _glfw.x11.NET_WM_PING;

        if (count > 0)
        {
            XSetWMProtocols(_glfw.x11.display, window->x11.handle,
                            protocols, count);
        }
    }

    if (_glfw.x11.NET_WM_PID)
    {
        const pid_t pid = getpid();

        XChangeProperty(_glfw.x11.display,  window->x11.handle,
                        _glfw.x11.NET_WM_PID, XA_CARDINAL, 32,
                        PropModeReplace,
                        (unsigned char*) &pid, 1);
    }

    // Set ICCCM WM_HINTS property
    {
        XWMHints* hints = XAllocWMHints();
        if (!hints)
        {
            _glfwInputError(GLFW_OUT_OF_MEMORY,
                            "X11: Failed to allocate WM hints");
            return GL_FALSE;
        }

        hints->flags = StateHint;
        hints->initial_state = NormalState;

        XSetWMHints(_glfw.x11.display, window->x11.handle, hints);
        XFree(hints);
    }

    // Set ICCCM WM_NORMAL_HINTS property (even if no parts are set)
    {
        XSizeHints* hints = XAllocSizeHints();
        hints->flags = 0;

        if (wndconfig->monitor)
        {
            hints->flags |= PPosition;
            _glfwPlatformGetMonitorPos(wndconfig->monitor, &hints->x, &hints->y);
        }
        else
        {
            // HACK: Explicitly setting PPosition to any value causes some WMs,
            //       notably Compiz and Metacity, to honor the position of
            //       unmapped windows set by XMoveWindow
            hints->flags |= PPosition;
            hints->x = hints->y = 0;
        }

        if (!wndconfig->resizable)
        {
            hints->flags |= (PMinSize | PMaxSize);
            hints->min_width  = hints->max_width  = wndconfig->width;
            hints->min_height = hints->max_height = wndconfig->height;
        }

        XSetWMNormalHints(_glfw.x11.display, window->x11.handle, hints);
        XFree(hints);
    }

    // Set ICCCM WM_CLASS property
    // HACK: Until a mechanism for specifying the application name is added, the
    //       initial window title is used as the window class name
    if (strlen(wndconfig->title))
    {
        XClassHint* hint = XAllocClassHint();
        hint->res_name = (char*) wndconfig->title;
        hint->res_class = (char*) wndconfig->title;

        XSetClassHint(_glfw.x11.display, window->x11.handle, hint);
        XFree(hint);
    }

    if (_glfw.x11.xi.available)
    {
        // Select for XInput2 events

        XIEventMask eventmask;
        unsigned char mask[] = { 0 };

        eventmask.deviceid = 2;
        eventmask.mask_len = sizeof(mask);
        eventmask.mask = mask;
        XISetMask(mask, XI_Motion);

        XISelectEvents(_glfw.x11.display, window->x11.handle, &eventmask, 1);
    }

    if (_glfw.x11.XdndAware)
    {
        // Announce support for Xdnd (drag and drop)
        const Atom version = 5;
        XChangeProperty(_glfw.x11.display, window->x11.handle,
                        _glfw.x11.XdndAware, XA_ATOM, 32,
                        PropModeReplace, (unsigned char*) &version, 1);
    }

    if (_glfw.x11.NET_REQUEST_FRAME_EXTENTS)
    {
        // Ensure _NET_FRAME_EXTENTS is set, allowing glfwGetWindowFrameSize to
        // function before the window is mapped

        XEvent event;
        memset(&event, 0, sizeof(event));

        event.type = ClientMessage;
        event.xclient.window = window->x11.handle;
        event.xclient.format = 32; // Data is 32-bit longs
        event.xclient.message_type = _glfw.x11.NET_REQUEST_FRAME_EXTENTS;

        XSendEvent(_glfw.x11.display,
                   _glfw.x11.root,
                   False,
                   SubstructureNotifyMask | SubstructureRedirectMask,
                   &event);
        XIfEvent(_glfw.x11.display, &event, isFrameExtentsEvent, (XPointer) window);
    }

    _glfwPlatformSetWindowTitle(window, wndconfig->title);

    XRRSelectInput(_glfw.x11.display, window->x11.handle,
                   RRScreenChangeNotifyMask);

    _glfwPlatformGetWindowPos(window, &window->x11.xpos, &window->x11.ypos);
    _glfwPlatformGetWindowSize(window, &window->x11.width, &window->x11.height);

    return GL_TRUE;
}
    Bool RenderWindowLinux::Open( const VideoMode & p_VideoMode, const std::string & p_Title, const Uint32 p_Style )
	{
	    // open a connection with X server
	    if( ( m_pDisplay = XOpenDisplay( NULL ) ) == NULL )
        {
            std::cout << "[RenderWindowLinux::Create] Can not connect to X server." << std::endl;
            return false;
        }

        // Initialize the X thread
        // Should we?!?!
        XInitThreads( );

	    // Get the screen
	    m_Screen = DefaultScreen( m_pDisplay );

        // Creat the window attributes
        XSetWindowAttributes WindowAttributes;
        WindowAttributes.colormap = DefaultColormap( m_pDisplay, m_Screen );
        WindowAttributes.event_mask =   KeyPressMask | KeyReleaseMask |
                                        ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | PointerMotionMask |
                                        EnterWindowMask | LeaveWindowMask | VisibilityChangeMask |
                                        FocusChangeMask | ExposureMask | StructureNotifyMask;

        // Create the window
        m_Window = XCreateWindow( m_pDisplay,
                                 DefaultRootWindow( m_pDisplay ),
                                 0, 0, p_VideoMode.GetSize( ).x, p_VideoMode.GetSize( ).y,
                                 0,
                                 DefaultDepth( m_pDisplay, m_Screen ),
                                 InputOutput,
                                 DefaultVisual( m_pDisplay, m_Screen ),
                                 CWBorderPixel | CWEventMask | CWColormap,
                                 &WindowAttributes );



        // It's very important to set the delete message. Else we wont be able to close the window.
        ::Atom wmDeleteMessage = XInternAtom( m_pDisplay, "WM_DELETE_WINDOW", false );
        XSetWMProtocols( m_pDisplay, m_Window, &wmDeleteMessage, 1 );

        // Set the window title
        SetTitle( p_Title.c_str( ) );


        // Let's set up the window decoration and the functionality
        ::Atom PropertyAtom = XInternAtom( m_pDisplay, "_MOTIF_WM_HINTS", false );
        if( PropertyAtom )
        {
            struct HintsStruct
            {
                Uint32 Flags;
                Uint32 Functions;
                Uint32 Decorations;
                Int32 InputMode;
                Uint32 State;
            };

            HintsStruct Hints;
            Hints.Flags = MWM_HINTS_FUNCTIONS | MWM_HINTS_FUNCTIONS;
            Hints.Functions = 0;
            Hints.Decorations = 0;


            // Go through all the styles we want to apply to the window
            if( p_Style == Bit::Style::Default )
            {
                Hints.Functions |= MWM_FUNC_ALL;
                Hints.Decorations |= MWM_DECOR_ALL;
            }
            else
            {
                // Always set the resize and maximize functions and decorations.
                // Some window managers seems to require this.
                // Resizing can be disabled.
                Hints.Functions |= MWM_FUNC_RESIZE | MWM_FUNC_MAXIMIZE;
                Hints.Decorations |= MWM_DECOR_RESIZEH | MWM_DECOR_MAXIMIZE;


                if( p_Style & Bit::Style::Close )
                {
                     Hints.Functions |= MWM_FUNC_CLOSE;
                }

                if( p_Style & Bit::Style::Minimize )
                {
                     Hints.Functions |= MWM_FUNC_MINIMIZE;
                     Hints.Decorations |= MWM_DECOR_MINIMIZE;
                }

                if( p_Style & Bit::Style::TitleBar )
                {
                     Hints.Functions |= MWM_FUNC_MOVE | MWM_FUNC_MINIMIZE;
                     Hints.Decorations |= MWM_DECOR_BORDER | MWM_DECOR_TITLE | MWM_DECOR_MENU | MWM_DECOR_MINIMIZE;
                }
            }

            // Apply the changes
            XChangeProperty( m_pDisplay, m_Window, PropertyAtom, PropertyAtom, 32, PropModeReplace, (unsigned char *) &Hints, 5 );

            // Force x server to disable window resizing
            if (!( p_Style & Bit::Style::Resize ) )
            {
                XSizeHints * SizeHints = XAllocSizeHints( );
                SizeHints->flags = PMinSize | PMaxSize;
                SizeHints->min_width = p_VideoMode.GetSize( ).x;
                SizeHints->min_height = p_VideoMode.GetSize( ).y;
                SizeHints->max_width = p_VideoMode.GetSize( ).x;
                SizeHints->max_height = p_VideoMode.GetSize( ).y;

                // Set the hints
                XSetWMNormalHints( m_pDisplay, m_Window, SizeHints);

                // Free the size hints
                XFree(SizeHints);
            }
        }
        else
        {
            std::cout << "[RenderWindowLinux::Open] Can not get the property atom \"_MOTIF_WM_HINTS\"." << std::endl;
        }

        // Display the window.
        XMapWindow( m_pDisplay, m_Window );
        XFlush( m_pDisplay );


		// Set the rest of the member variables
		m_VideoMode = p_VideoMode;
		m_Title = p_Title;
		m_Style = p_Style;
		m_Size = p_VideoMode.GetSize( );
		m_Open = true;
		m_Focused = true;
		return true;
	}
Example #6
0
static PyObject *
setRootResource(PyObject *s, PyObject *args)
{
    Display *dpy;
    Window  root;
    Resource **resources, **p;
    char *key, *val, *rstring;
    int fnd, nrec;

    if (!PyArg_ParseTuple(args, "ss", &key, &val)) {
	return NULL;
    }

    if (openDisplay(&dpy, &root) < 0) {
	PyErr_SetString(PyExc_SystemError, "Could not open display.");
	return NULL;
    }

    resources = getCurrentResources(dpy);
    fnd = 0;
    nrec = 0;
    if (resources) {
	p = resources;
	while (*p) {
	    if (!strcmp(key, (*p)->key)) {
		free((*p)->val);
		(*p)->val = strdup(val);
		fnd = 1;
		break;
	    }

	    p++;
	}

	p = resources;
	while (*p) {
	    nrec++;
	    p++;
	}
    }

    if (!fnd) {
	Resource *newrec;

	newrec = (Resource *) malloc(sizeof(Resource));
	newrec->key = strdup(key);
	newrec->val = strdup(val);

	if (nrec > 0)
	    resources = (Resource **) realloc(resources, (nrec+2) * sizeof(Resource *));
	else
	    resources = (Resource **) malloc(2*sizeof(Resource *));

	resources[nrec] = newrec;
	resources[nrec+1] = NULL;
    }

    rstring = NULL;
    p = resources;
    while (*p) {
	int len;
	char *tmpstr;

	len = strlen((*p)->key) + strlen((*p)->val) + 3;
	tmpstr = (char *) malloc(len*sizeof(char));
	strcpy(tmpstr, (*p)->key);
	strcat(tmpstr, ":");
	strcat(tmpstr, (*p)->val);
	strcat(tmpstr, "\n");

	if (rstring) {
	    rstring = (char *)realloc(rstring, (strlen(rstring)+len+1)*sizeof(char));
	    strcat(rstring, tmpstr);
	} else {
	    rstring = tmpstr;
	}

	p++;
    }

    XChangeProperty(dpy, root, XA_RESOURCE_MANAGER, XA_STRING, 
		    8, PropModeReplace, (unsigned char *)rstring,
		    strlen(rstring));

    free(rstring);
    freeResources(resources);

    closeDisplay(dpy);

    Py_INCREF(Py_None);
    return Py_None;
}
Example #7
0
void
xaw_pop_instance (widget_instance *instance, Boolean up)
{
    Widget widget = instance->widget;

    if (up)
    {
        if (XtIsSubclass (widget, dialogWidgetClass))
        {
            /* For dialogs, we need to call XtPopup on the parent instead
               of calling XtManageChild on the widget.
               Also we need to hack the shell's WM_PROTOCOLS to get it to
               understand what the close box is supposed to do!!
             */
            Display *dpy = XtDisplay (widget);
            Widget shell = XtParent (widget);
            Atom props [2];
            int i = 0;
            props [i++] = XInternAtom (dpy, "WM_DELETE_WINDOW", False);
            XChangeProperty (dpy, XtWindow (shell),
                             XInternAtom (dpy, "WM_PROTOCOLS", False),
                             XA_ATOM, 32, PropModeAppend,
                             (unsigned char *) props, i);

            /* Center the widget in its parent.  Why isn't this kind of crap
               done automatically?  I thought toolkits were supposed to make
               life easier?
             */
            {
                unsigned int x, y, w, h;
                Widget topmost = instance->parent;
                Arg args[2];

                w = shell->core.width;
                h = shell->core.height;
                while (topmost->core.parent && XtIsRealized (topmost->core.parent))
                    topmost = topmost->core.parent;
                if (topmost->core.width < w) x = topmost->core.x;
                else x = topmost->core.x + ((topmost->core.width - w) / 2);
                if (topmost->core.height < h) y = topmost->core.y;
                else y = topmost->core.y + ((topmost->core.height - h) / 2);
                /* Using XtMoveWidget caused the widget to come
                   out in the wrong place with vtwm.
                   Question of virtual vs real coords, perhaps.  */
                XtSetArg (args[0], XtNx, x);
                XtSetArg (args[1], XtNy, y);
                XtSetValues (shell, args, 2);
            }

            /* Finally, pop it up. */
            XtPopup (shell, XtGrabNonexclusive);
        }
        else
            XtManageChild (widget);
    }
    else
    {
        if (XtIsSubclass (widget, dialogWidgetClass))
            XtUnmanageChild (XtParent (widget));
        else
            XtUnmanageChild (widget);
    }
}
void
gdk_property_change (GdkWindow    *window,
		     GdkAtom       property,
		     GdkAtom       type,
		     gint          format,
		     GdkPropMode   mode,
		     const guchar *data,
		     gint          nelements)
{
  GdkDisplay *display;
  Window xwindow;
  Atom xproperty;
  Atom xtype;

  g_return_if_fail (!window || GDK_WINDOW_IS_X11 (window));

  if (!window)
    {
      GdkScreen *screen;
      
      screen = gdk_screen_get_default ();
      window = gdk_screen_get_root_window (screen);
      
      GDK_NOTE (MULTIHEAD, g_message ("gdk_property_change(): window is NULL\n"));
    }
  else if (!GDK_WINDOW_IS_X11 (window))
    return;

  if (GDK_WINDOW_DESTROYED (window))
    return;

  gdk_window_ensure_native (window);

  display = gdk_drawable_get_display (window);
  xproperty = gdk_x11_atom_to_xatom_for_display (display, property);
  xtype = gdk_x11_atom_to_xatom_for_display (display, type);
  xwindow = GDK_WINDOW_XID (window);

  if (xtype == XA_ATOM ||
      xtype == gdk_x11_get_xatom_by_name_for_display (display, "ATOM_PAIR"))
    {
      /*
       * data is an array of GdkAtom, we need to convert it
       * to an array of X Atoms
       */
      gint i;
      GdkAtom *atoms = (GdkAtom*) data;
      Atom *xatoms;

      xatoms = g_new (Atom, nelements);
      for (i = 0; i < nelements; i++)
	xatoms[i] = gdk_x11_atom_to_xatom_for_display (display, atoms[i]);

      XChangeProperty (GDK_DISPLAY_XDISPLAY (display), xwindow,
		       xproperty, xtype,
		       format, mode, (guchar *)xatoms, nelements);
      g_free (xatoms);
    }
  else
    XChangeProperty (GDK_DISPLAY_XDISPLAY (display), xwindow, xproperty, 
		     xtype, format, mode, (guchar *)data, nelements);
}
Example #9
0
void x11_window_create()
{
	if (cfgLoadInt("pvr", "nox11", 0) == 0)
	{
		XInitThreads();
		// X11 variables
		Window       x11Window = 0;
		Display*     x11Display = 0;
		long         x11Screen = 0;
		XVisualInfo* x11Visual = 0;
		Colormap     x11Colormap = 0;

		/*
		Step 0 - Create a NativeWindowType that we can use it for OpenGL ES output
		*/
		Window sRootWindow;
		XSetWindowAttributes sWA;
		unsigned int ui32Mask;
		int i32Depth;

		// Initializes the display and screen
		x11Display = XOpenDisplay(NULL);
		if (!x11Display && !(x11Display = XOpenDisplay(":0")))
		{
			printf("Error: Unable to open X display\n");
			return;
		}
		x11Screen = XDefaultScreen(x11Display);

		// Gets the window parameters
		sRootWindow = RootWindow(x11Display, x11Screen);

		int depth = CopyFromParent;

		#if !defined(GLES)
			// Get a matching FB config
			static int visual_attribs[] =
			{
				GLX_X_RENDERABLE    , True,
				GLX_DRAWABLE_TYPE   , GLX_WINDOW_BIT,
				GLX_RENDER_TYPE     , GLX_RGBA_BIT,
				GLX_X_VISUAL_TYPE   , GLX_TRUE_COLOR,
				GLX_RED_SIZE        , 8,
				GLX_GREEN_SIZE      , 8,
				GLX_BLUE_SIZE       , 8,
				GLX_ALPHA_SIZE      , 8,
				GLX_DEPTH_SIZE      , 24,
				GLX_STENCIL_SIZE    , 8,
				GLX_DOUBLEBUFFER    , True,
				//GLX_SAMPLE_BUFFERS  , 1,
				//GLX_SAMPLES         , 4,
				None
			};

			int glx_major, glx_minor;

			// FBConfigs were added in GLX version 1.3.
			if (!glXQueryVersion(x11Display, &glx_major, &glx_minor) ||
					((glx_major == 1) && (glx_minor < 3)) || (glx_major < 1))
			{
				printf("Invalid GLX version");
				exit(1);
			}

			int fbcount;
			GLXFBConfig* fbc = glXChooseFBConfig(x11Display, x11Screen, visual_attribs, &fbcount);
			if (!fbc)
			{
				printf("Failed to retrieve a framebuffer config\n");
				exit(1);
			}
			printf("Found %d matching FB configs.\n", fbcount);

			GLXFBConfig bestFbc = fbc[0];
			XFree(fbc);

			// Get a visual
			XVisualInfo *vi = glXGetVisualFromFBConfig(x11Display, bestFbc);
			printf("Chosen visual ID = 0x%lx\n", vi->visualid);


			depth = vi->depth;
			x11Visual = vi;

			x11Colormap = XCreateColormap(x11Display, RootWindow(x11Display, x11Screen), vi->visual, AllocNone);
		#else
			i32Depth = DefaultDepth(x11Display, x11Screen);
			x11Visual = new XVisualInfo;
			XMatchVisualInfo(x11Display, x11Screen, i32Depth, TrueColor, x11Visual);
			if (!x11Visual)
			{
				printf("Error: Unable to acquire visual\n");
				return;
			}
			x11Colormap = XCreateColormap(x11Display, sRootWindow, x11Visual->visual, AllocNone);
		#endif

		sWA.colormap = x11Colormap;

		// Add to these for handling other events
		sWA.event_mask = StructureNotifyMask | ExposureMask | ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask;
		ui32Mask = CWBackPixel | CWBorderPixel | CWEventMask | CWColormap;

		x11_width = cfgLoadInt("x11", "width", DEFAULT_WINDOW_WIDTH);
		x11_height = cfgLoadInt("x11", "height", DEFAULT_WINDOW_HEIGHT);
		x11_fullscreen = (cfgLoadInt("x11", "fullscreen", DEFAULT_FULLSCREEN) > 0);

		if (x11_width < 0 || x11_height < 0)
		{
			x11_width = XDisplayWidth(x11Display, x11Screen);
			x11_height = XDisplayHeight(x11Display, x11Screen);
		}

		// Creates the X11 window
		x11Window = XCreateWindow(x11Display, RootWindow(x11Display, x11Screen), (ndcid%3)*640, (ndcid/3)*480, x11_width, x11_height,
			0, depth, InputOutput, x11Visual->visual, ui32Mask, &sWA);

		// Capture the close window event
		wmDeleteMessage = XInternAtom(x11Display, "WM_DELETE_WINDOW", False);
		XSetWMProtocols(x11Display, x11Window, &wmDeleteMessage, 1);

		if(x11_fullscreen)
		{

			// fullscreen
			Atom wmState = XInternAtom(x11Display, "_NET_WM_STATE", False);
			Atom wmFullscreen = XInternAtom(x11Display, "_NET_WM_STATE_FULLSCREEN", False);
			XChangeProperty(x11Display, x11Window, wmState, XA_ATOM, 32, PropModeReplace, (unsigned char *)&wmFullscreen, 1);

			XMapRaised(x11Display, x11Window);
		}
		else
		{
			XMapWindow(x11Display, x11Window);
		}

		#if !defined(GLES)
			#define GLX_CONTEXT_MAJOR_VERSION_ARB       0x2091
			#define GLX_CONTEXT_MINOR_VERSION_ARB       0x2092
			typedef GLXContext (*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, Bool, const int*);

			glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0;
			glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)glXGetProcAddressARB((const GLubyte*)"glXCreateContextAttribsARB");
			verify(glXCreateContextAttribsARB != 0);
			int context_attribs[] =
			{
				GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
				GLX_CONTEXT_MINOR_VERSION_ARB, 1,
				GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_DEBUG_BIT_ARB,
				GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
				None
			};

			x11_glc = glXCreateContextAttribsARB(x11Display, bestFbc, 0, True, context_attribs);
			XSync(x11Display, False);

			if (!x11_glc)
			{
				die("Failed to create GL3.1 context\n");
			}
		#endif

		XFlush(x11Display);

		//(EGLNativeDisplayType)x11Display;
		x11_disp = (void*)x11Display;
		x11_win = (void*)x11Window;
		x11_vis = (void*)x11Visual->visual;
	}
	else
	{
		printf("Not creating X11 window ..\n");
	}
}
Example #10
0
void wsCreateWindow( wsTWindow * win,int X,int Y,int wX,int hY,int bW,int cV,unsigned char D,char * label )
{
 int depth;

 win->Property=D;
 if ( D & wsShowFrame ) win->Decorations=1;
 wsHGC=DefaultGC( wsDisplay,wsScreen );
// The window position and size.
 switch ( X )
  {
   case -1: win->X=( wsMaxX / 2 ) - ( wX / 2 ) + wsOrgX; break;
   case -2: win->X=wsMaxX - wX - 1 + wsOrgX; break;
   default: win->X=X; break;
  }
 switch ( Y )
  {
   case -1: win->Y=( wsMaxY / 2 ) - ( hY / 2 ) + wsOrgY; break;
   case -2: win->Y=wsMaxY - hY - 1 + wsOrgY; break;
   default: win->Y=Y; break;
  }
 win->Width=wX;
 win->Height=hY;
 win->OldX=win->X;
 win->OldY=win->Y;
 win->OldWidth=win->Width;
 win->OldHeight=win->Height;

// Border size for window.
 win->BorderWidth=bW;
// Hide Mouse Cursor
 win->wsCursor=None;
 win->wsMouseEventType=cV;
 win->wsCursorData[0]=0;
 win->wsCursorPixmap=XCreateBitmapFromData( wsDisplay,wsRootWin,win->wsCursorData,1,1 );
 if ( !(cV & wsShowMouseCursor) ) win->wsCursor=XCreatePixmapCursor( wsDisplay,win->wsCursorPixmap,win->wsCursorPixmap,&win->wsColor,&win->wsColor,0,0 );

 depth = vo_find_depth_from_visuals( wsDisplay,wsScreen,NULL );
 if ( depth < 15 )
  {
   mp_msg( MSGT_GPLAYER,MSGL_FATAL,MSGTR_WS_ColorDepthTooLow );
   exit( 0 );
  }
 XMatchVisualInfo( wsDisplay,wsScreen,depth,TrueColor,&win->VisualInfo );

// ---
 win->AtomLeaderClient=XInternAtom( wsDisplay,"WM_CLIENT_LEADER",False );
 win->AtomDeleteWindow=XInternAtom( wsDisplay,"WM_DELETE_WINDOW",False );
 win->AtomTakeFocus=XInternAtom( wsDisplay,"WM_TAKE_FOCUS",False );
 win->AtomRolle=XInternAtom( wsDisplay,"WM_WINDOW_ROLE",False );
 win->AtomWMSizeHint=XInternAtom( wsDisplay,"WM_SIZE_HINT",False );
 win->AtomWMNormalHint=XInternAtom( wsDisplay,"WM_NORMAL_HINT",False );
 win->AtomProtocols=XInternAtom( wsDisplay,"WM_PROTOCOLS",False );
 win->AtomsProtocols[0]=win->AtomDeleteWindow;
 win->AtomsProtocols[1]=win->AtomTakeFocus;
 win->AtomsProtocols[2]=win->AtomRolle;
// ---

 win->WindowAttrib.background_pixel=BlackPixel( wsDisplay,wsScreen );
 win->WindowAttrib.border_pixel=WhitePixel( wsDisplay,wsScreen );
 win->WindowAttrib.colormap=XCreateColormap( wsDisplay,wsRootWin,win->VisualInfo.visual,AllocNone );
 win->WindowAttrib.event_mask=StructureNotifyMask | FocusChangeMask |
                              ExposureMask | PropertyChangeMask |
                              EnterWindowMask | LeaveWindowMask |
                              VisibilityChangeMask |
                              KeyPressMask | KeyReleaseMask;
 if ( ( cV & wsHandleMouseButton ) ) win->WindowAttrib.event_mask|=ButtonPressMask | ButtonReleaseMask;
 if ( ( cV & wsHandleMouseMove ) ) win->WindowAttrib.event_mask|=PointerMotionMask;
 win->WindowAttrib.cursor=win->wsCursor;
 win->WindowAttrib.override_redirect=False;
 if ( D & wsOverredirect ) win->WindowAttrib.override_redirect=True;

 win->WindowMask=CWBackPixel | CWBorderPixel |
                 CWColormap | CWEventMask | CWCursor |
                 CWOverrideRedirect;

 win->WindowID=XCreateWindow( wsDisplay,
  (win->Parent != 0?win->Parent:wsRootWin),
  win->X,win->Y,win->Width,win->Height,win->BorderWidth,
  win->VisualInfo.depth,
  InputOutput,
  win->VisualInfo.visual,
  win->WindowMask,&win->WindowAttrib );

 wsClassHint.res_name="MPlayer";

 wsClassHint.res_class="MPlayer";
 XSetClassHint( wsDisplay,win->WindowID,&wsClassHint );

 win->SizeHint.flags=PPosition | PSize | PResizeInc | PWinGravity;// | PBaseSize;
 win->SizeHint.x=win->X;
 win->SizeHint.y=win->Y;
 win->SizeHint.width=win->Width;
 win->SizeHint.height=win->Height;

 if ( D & wsMinSize )
  {
   win->SizeHint.flags|=PMinSize;
   win->SizeHint.min_width=win->Width;
   win->SizeHint.min_height=win->Height;
  }
 if ( D & wsMaxSize )
  {
   win->SizeHint.flags|=PMaxSize;
   win->SizeHint.max_width=win->Width;
   win->SizeHint.max_height=win->Height;
  }

 win->SizeHint.height_inc=1;
 win->SizeHint.width_inc=1;
 win->SizeHint.base_width=win->Width;
 win->SizeHint.base_height=win->Height;
 win->SizeHint.win_gravity=StaticGravity;
 XSetWMNormalHints( wsDisplay,win->WindowID,&win->SizeHint );

 win->WMHints.flags=InputHint | StateHint;
 win->WMHints.input=True;
 win->WMHints.initial_state=NormalState;
 XSetWMHints( wsDisplay,win->WindowID,&win->WMHints );

 wsWindowDecoration( win,win->Decorations );
 XStoreName( wsDisplay,win->WindowID,label );
 XmbSetWMProperties( wsDisplay,win->WindowID,label,label,NULL,0,NULL,NULL,NULL );

 XSetWMProtocols( wsDisplay,win->WindowID,win->AtomsProtocols,3 );
 XChangeProperty( wsDisplay,win->WindowID,
                  win->AtomLeaderClient,
                  XA_WINDOW,32,PropModeReplace,
                  (unsigned char *)&LeaderWindow,1 );

 wsTextProperty.value=label;
 wsTextProperty.encoding=XA_STRING;
 wsTextProperty.format=8;
 wsTextProperty.nitems=strlen( label );
 XSetWMIconName( wsDisplay,win->WindowID,&wsTextProperty );

 win->wGC=XCreateGC( wsDisplay,win->WindowID,
  GCForeground | GCBackground,
  &win->wGCV );

 win->Visible=0;
 win->Focused=0;
 win->Mapped=0;
 win->Rolled=0;
 if ( D & wsShowWindow ) XMapWindow( wsDisplay,win->WindowID );

 wsCreateImage( win,win->Width,win->Height );
// --- End of creating --------------------------------------------------------------------------

 {
  int i;
  for ( i=0;i < wsWLCount;i++ )
   if ( wsWindowList[i] == NULL ) break;
  if ( i == wsWLCount )
   {  mp_msg( MSGT_GPLAYER,MSGL_FATAL,MSGTR_WS_TooManyOpenWindows ); exit( 0 ); }
  wsWindowList[i]=win;
 }

 XFlush( wsDisplay );
 XSync( wsDisplay,False );

 win->ReDraw=NULL;
 win->ReSize=NULL;
 win->Idle=NULL;
 win->MouseHandler=NULL;
 win->KeyHandler=NULL;
 mp_dbg( MSGT_GPLAYER,MSGL_DBG2,"[ws] window is created. ( %s ).\n",label );
}
Example #11
0
/* send selection data in response to a request returns 0 */
int xcin (Display *dpy, Window win, XEvent rev, char *txt)
{
	unsigned int			incr = F;	/* incr mode flag */
	XEvent				res;		/* response to event */
	Atom				inc;
	unsigned int			selc = F;	/* SelClear event */

	if (rev.type == SelectionClear)
		return(1);
	
	/* send only continue if this is a SelectionRequest event */
	if (rev.type != SelectionRequest)
		return(0);
	
	/* test whether to use INCR or not */
	if ( strlen(txt) > XC_CHUNK )
	{
		incr = T;
		inc = XInternAtom(dpy, "INCR", False);
	}

	/* put the data into an property */
	if (incr)
	{
		/* send INCR response */
		XChangeProperty(
			dpy,
			rev.xselectionrequest.requestor,
			rev.xselectionrequest.property,
			inc,
			32,
			PropModeReplace,
			0,
			0
		);

		/* With the INCR mechanism, we need to know when the
		 * requestor window changes (deletes) its properties
		 */
		XSelectInput(
			dpy,
			rev.xselectionrequest.requestor,
			PropertyChangeMask
		);
	} else 
	{
		/* send data all at once (not using INCR) */
		XChangeProperty(
			dpy,
			rev.xselectionrequest.requestor,
			rev.xselectionrequest.property,
			XA_STRING,
			8,
			PropModeReplace,
			(unsigned char*) txt,
			strlen(txt)
		);
	}
	
	/* set values for the response event */
	res.xselection.property  = rev.xselectionrequest.property;
	res.xselection.type      = SelectionNotify;
	res.xselection.display   = rev.xselectionrequest.display;
	res.xselection.requestor = rev.xselectionrequest.requestor;
	res.xselection.selection = rev.xselectionrequest.selection;
	res.xselection.target    = rev.xselectionrequest.target;
	res.xselection.time      = rev.xselectionrequest.time;

	/* send the response event */
	XSendEvent(dpy, rev.xselectionrequest.requestor, 0, 0, &res);
	XFlush(dpy);

	if (incr)
	{
		unsigned int sel_pos = 0; /* position in sel_str */
		unsigned int sel_end = 0;
		char *chk_str;

		chk_str = (char *)xcmalloc(XC_CHUNK);

		while (1)
		{
			unsigned int chk_pos = 0;

			while (1)
			{
				XEvent	spe;

				XNextEvent(dpy, &spe);
				if (spe.type == SelectionClear)
				{
					selc = T;
					continue;
				}
				if (spe.type != PropertyNotify)
					continue;
				if (spe.xproperty.state == PropertyDelete)
					break;
			}
	    

			if (!sel_end)
			{
				for (chk_pos=0; chk_pos<=XC_CHUNK; chk_pos++)
				{
					if (txt[sel_pos] == (char)NULL)
					{
						sel_end = 1;
						break;
					}
					chk_str[chk_pos] = txt[sel_pos];
					sel_pos++;
				}
			}

			if (chk_pos)
			{
				XChangeProperty(
					dpy,
					rev.xselectionrequest.requestor,
					rev.xselectionrequest.property,
					XA_STRING,
					8,
					PropModeReplace,
					chk_str,
					chk_pos
				);
			} else
			{
				XChangeProperty(
					dpy,
					rev.xselectionrequest.requestor,
					rev.xselectionrequest.property,
					XA_STRING,
					8,
					PropModeReplace,
					0,
					0	
				);
			}
			XFlush(dpy);

			/* no more chars to send, break out of the loop */
			if (!chk_pos)
				break;
		}
	}
	return(selc);
}
Example #12
0
File: xsm.c Project: aosm/X11
Status
StartSession(char *name, Bool use_default)
{
    int database_read = 0;
    Dimension width;
    char title[256];


    /*
     * If we're not using the default session, lock it.
     * If using the default session, it will be locked as
     * soon as the user assigns the session a name.
     */

    if (!use_default && !LockSession (name, True))
	return (0);


    /*
     * Get important environment variables.
     */

    GetEnvironment ();


    /*
     * Set the main window's title to the session name.
     */

    sprintf (title, "xsm: %s", name);

    XtVaSetValues (topLevel,
	XtNtitle, title,		/* session name */
	NULL);

    XtRealizeWidget (topLevel);


    /*
     * Set WM_DELETE_WINDOW support on main window.  If the user tries
     * to delete the main window, the shutdown prompt will come up.
     */

    SetWM_DELETE_WINDOW (topLevel, "DelMainWinAction()");


    /*
     * Read the session save file.  Make sure the session manager
     * has an SM_CLIENT_ID, so that other managers (like the WM) can
     * identify it.
     */

    set_session_save_file_name (name);

    if (use_default)
	need_to_name_session = True;
    else
    {
	database_read = ReadSave (name, &sm_id);
	need_to_name_session = !database_read;
    }

    if (!sm_id)
    {
	sm_id = SmsGenerateClientID (NULL);
	if (!sm_id) return (0);
    }
    XChangeProperty (XtDisplay (topLevel), XtWindow (topLevel),
	XInternAtom (XtDisplay (topLevel), "SM_CLIENT_ID", False),
	XA_STRING, 8, PropModeReplace,
	(unsigned char *) sm_id, strlen (sm_id));


    /*
     * Adjust some label widths
     */

    XtVaGetValues (clientInfoButton,
	XtNwidth, &width,
	NULL);

    XtVaSetValues (checkPointButton,
	XtNwidth, width,
	NULL);

    XtVaGetValues (logButton,
	XtNwidth, &width,
	NULL);

    XtVaSetValues (shutdownButton,
	XtNwidth, width,
	NULL);
    

    XtMapWidget (topLevel);


    if (!database_read)
    {
	/*
	 * Start default apps (e.g. twm, smproxy)
	 */

	StartDefaultApps ();
    }
    else
    {
	/*
	 * Restart window manager first.  When the session manager
	 * gets a WM_STATE stored on its top level window, we know
	 * the window manager is running.  At that time, we can start
	 * the rest of the applications.
	 */

	XtAddEventHandler (topLevel, PropertyChangeMask, False,
	    PropertyChangeXtHandler, NULL);

	if (!Restart (RESTART_MANAGERS))
	{
	    XtRemoveEventHandler (topLevel, PropertyChangeMask, False,
	        PropertyChangeXtHandler, NULL);

	    /*
	     * Restart the rest of the session aware clients.
	     */

	    Restart (RESTART_REST_OF_CLIENTS);

	    /*
	     * Start apps that aren't session aware that were specified
	     * by the user.
	     */
	    
	    StartNonSessionAwareApps ();
	}
    }

    return (1);
}
Example #13
0
// needs to be run after SelectEGLConfiguration()
// for gEglConfig to be valid
int PVRShellInitOS::OpenX11Window(const PVRShell &shell)
{
    XSetWindowAttributes	wa;
    XSizeHints				sh;
    XEvent					event;
    unsigned long			mask;
    #ifdef BUILD_OGL
    XF86VidModeModeInfo **modes;       // modes of display
    int numModes;                      // number of modes of display
    int chosenMode;
    int edimx,edimy;                   //established width and height of the chosen modeline
    int i;
    #endif
    MyHints mwmhints;
    Atom prop;

	int depth = DefaultDepth(x11display, x11screen);
	x11visual = new XVisualInfo;
	XMatchVisualInfo( x11display, x11screen, depth, TrueColor, x11visual);

    if( !x11visual )
    {
    	shell.PVRShellOutputDebug( "Unable to acquire visual" );
    	return false;
    }

    x11colormap = XCreateColormap( x11display, RootWindow(x11display, x11screen), x11visual->visual, AllocNone );

    #ifdef BUILD_OGL
    originalMode_dotclock = XF86VidModeBadClock;
    if(shell.m_pShellData->bFullScreen) {

        // Get mode lines to see if there is requested modeline
        XF86VidModeGetAllModeLines(x11display, x11screen, &numModes, &modes);
        /* look for mode with requested resolution */
        chosenMode = -1;
        i=0;
        while((chosenMode == -1)&&(i<numModes))
        {
            if ((modes[i]->hdisplay == shell.m_pShellData->nShellDimX) && (modes[i]->vdisplay == shell.m_pShellData->nShellDimY))
            {
                chosenMode = i;
            }
            ++i;
        }

        // If there is no requested resolution among modelines then terminate
        if(chosenMode == -1)
        {
            shell.PVRShellOutputDebug( "Chosen resolution for full screen mode does not match any modeline available.\n" );
            return false;
        }

        /* save desktop-resolution before switching modes */
        XF86VidModeGetModeLine(x11display,x11screen, &originalMode_dotclock, &originalMode );

        XF86VidModeSwitchToMode(x11display, x11screen, modes[chosenMode]);
        XF86VidModeSetViewPort(x11display, x11screen, 0, 0);
        edimx = modes[chosenMode]->hdisplay;
        edimy = modes[chosenMode]->vdisplay;
        printf("Fullscreen Resolution %dx%d (chosen mode = %d)\n", edimx, edimy,chosenMode);
        XFree(modes);       //to musi byc globalne

        wa.colormap = x11colormap;
        wa.background_pixel = 0xFFFFFFFF;
        wa.border_pixel = 0;
        wa.override_redirect = true;

        // add to these for handling other events
        wa.event_mask = StructureNotifyMask | ExposureMask | ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask;

        // The diffrence is that we want to ignore influence of window manager for outr fullscreen window
        mask = CWBackPixel | CWBorderPixel | CWEventMask | CWColormap | CWOverrideRedirect;

        x11window = XCreateWindow( x11display, RootWindow(x11display, x11screen), 0, 0, edimx, edimy, 0,
                                    CopyFromParent, InputOutput, CopyFromParent, mask, &wa);
        // keeping the pointer of mouse and keyboard in window to prevent from scrolling the virtual screen
        XWarpPointer(x11display, None ,x11window, 0, 0, 0, 0, 0, 0);
        // Map and then wait till mapped, grabbing should be after mapping the window
        XMapWindow( x11display, x11window );
        XGrabKeyboard(x11display, x11window, True, GrabModeAsync, GrabModeAsync, CurrentTime);
        XGrabPointer(x11display, x11window, True, ButtonPressMask, GrabModeAsync, GrabModeAsync, x11window, None, CurrentTime);
        XIfEvent( x11display, &event, WaitForMapNotify, (char*)x11window );

    } else {
    #endif
        wa.colormap = x11colormap;
        wa.background_pixel = 0xFFFFFFFF;
        wa.border_pixel = 0;

        // add to these for handling other events
        wa.event_mask = StructureNotifyMask | ExposureMask | ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask;

        mask = CWBackPixel | CWBorderPixel | CWEventMask | CWColormap ;

        x11window = XCreateWindow( x11display, RootWindow(x11display, x11screen), shell.m_pShellData->nShellPosX, shell.m_pShellData->nShellPosY,
                                    shell.m_pShellData->nShellDimX, shell.m_pShellData->nShellDimY, 0,
                                    CopyFromParent, InputOutput, CopyFromParent, mask, &wa);
        // todo:meh remove this?
        sh.flags = USPosition;
        sh.x = shell.m_pShellData->nShellPosX;
        sh.y = shell.m_pShellData->nShellPosY;
        XSetStandardProperties( x11display, x11window, szTitle, szTitle, None, 0, 0, &sh );
        // Map and then wait till mapped
        XMapWindow( x11display, x11window );
        XIfEvent( x11display, &event, WaitForMapNotify, (char*)x11window );
        // An attempt to hide a border for fullscreen on non OGL apis (OGLES,OGLES2)
        if(shell.m_pShellData->bFullScreen) {
            memset(&mwmhints, 0, sizeof(mwmhints));
            prop = XInternAtom(x11display, "_MOTIF_WM_HINTS", False);
            mwmhints.flags = 2;//MWM_HINTS_DECORATIONS;
            mwmhints.decorations = 0;
            XChangeProperty(x11display, x11window, prop, prop, 32, PropModeReplace,
            (unsigned char *) &mwmhints,5);
        }
        //
        Atom wmDelete = XInternAtom(x11display, "WM_DELETE_WINDOW", True);
        XSetWMProtocols(x11display, x11window, &wmDelete, 1);
        XSetWMColormapWindows( x11display, x11window, &x11window, 1 );
    #ifdef BUILD_OGL
    }
    #endif

    XFlush( x11display );

    return true;
}
Example #14
0
// Set the window manager decorations according to the
// given wxWidgets style
bool wxSetWMDecorations(Window w, long style)
{
#if wxUSE_NANOX
    GR_WM_PROPERTIES wmProp;

    wmProp.flags = 0;
    wmProp.props = 0;

    if (style & wxRESIZE_BORDER)
    {
        wmProp.props |= GR_WM_PROPS_APPFRAME ;
        wmProp.flags |= GR_WM_FLAGS_PROPS ;
    }

    if (style & wxCLOSE_BOX)
    {
        wmProp.props |= GR_WM_PROPS_CLOSEBOX ;
        wmProp.flags |= GR_WM_FLAGS_PROPS ;
    }

    if ((style & wxCAPTION) ||
        (style & wxTINY_CAPTION))
    {
        wmProp.props |= GR_WM_PROPS_CAPTION ;
        wmProp.flags |= GR_WM_FLAGS_PROPS ;

        // The default dialog style doesn't include any kind
        // of border, which is a bit odd. Anyway, inclusion
        // of a caption surely implies a border.
        style |= wxRESIZE_BORDER;
    }

    if (style & wxRESIZE_BORDER)
    {
        wmProp.props |= GR_WM_PROPS_APPFRAME ;
        wmProp.flags |= GR_WM_FLAGS_PROPS ;
    }

    if (style & wxSIMPLE_BORDER)
    {
        wmProp.props |= GR_WM_PROPS_BORDER ;
        wmProp.flags |= GR_WM_FLAGS_PROPS ;
    }

    if (style & wxMINIMIZE_BOX)
    {
    }

    if (style & wxMAXIMIZE_BOX)
    {
        wmProp.props |= GR_WM_PROPS_MAXIMIZE ;
        wmProp.flags |= GR_WM_FLAGS_PROPS ;
    }

    if ( !(style & wxBORDER) && !(style & wxRESIZE_BORDER) )
    {
        wmProp.props |= GR_WM_PROPS_NODECORATE ;
        wmProp.flags |= GR_WM_FLAGS_PROPS ;
    }

    GrSetWMProperties(w, & wmProp);

#else

    Atom mwm_wm_hints = XInternAtom(wxGlobalDisplay(),"_MOTIF_WM_HINTS", False);
    if (mwm_wm_hints == 0)
       return false;

    MwmHints hints;
    hints.flags = MWM_HINTS_DECORATIONS | MWM_HINTS_FUNCTIONS;
    hints.decorations = 0;
    hints.functions = 0;

    if ((style & wxSIMPLE_BORDER) || (style & wxNO_BORDER))
    {
        // leave zeros
    }
    else
    {
        hints.decorations = MWM_DECOR_BORDER;
        hints.functions = MWM_FUNC_MOVE;

        if ((style & wxCAPTION) != 0)
            hints.decorations |= MWM_DECOR_TITLE;

        if ((style & wxSYSTEM_MENU) != 0)
            hints.decorations |= MWM_DECOR_MENU;

        if ((style & wxCLOSE_BOX) != 0)
            hints.functions |= MWM_FUNC_CLOSE;

        if ((style & wxMINIMIZE_BOX) != 0)
        {
            hints.functions |= MWM_FUNC_MINIMIZE;
            hints.decorations |= MWM_DECOR_MINIMIZE;
        }

        if ((style & wxMAXIMIZE_BOX) != 0)
        {
            hints.functions |= MWM_FUNC_MAXIMIZE;
            hints.decorations |= MWM_DECOR_MAXIMIZE;
        }

        if ((style & wxRESIZE_BORDER) != 0)
        {
            hints.functions |= MWM_FUNC_RESIZE;
            hints.decorations |= MWM_DECOR_RESIZEH;
        }
    }

    XChangeProperty(wxGlobalDisplay(),
                    w,
                    mwm_wm_hints, mwm_wm_hints,
                    32, PropModeReplace,
                    (unsigned char *) &hints, PROP_MOTIF_WM_HINTS_ELEMENTS);

#endif
    return true;
}
Example #15
0
void xf_cliprdr_init(xfInfo* xfi, rdpChannels* chanman)
{
	int n;
	UINT32 id;
	clipboardContext* cb;

	cb = (clipboardContext*) malloc(sizeof(clipboardContext));
	ZeroMemory(cb, sizeof(clipboardContext));

	xfi->clipboard_context = cb;

	cb->channels = chanman;
	cb->request_index = -1;

	cb->root_window = DefaultRootWindow(xfi->display);
	cb->clipboard_atom = XInternAtom(xfi->display, "CLIPBOARD", FALSE);

	if (cb->clipboard_atom == None)
	{
		DEBUG_WARN("unable to get CLIPBOARD atom");
	}

	id = 1;
	cb->property_atom = XInternAtom(xfi->display, "_FREERDP_CLIPRDR", FALSE);
	cb->identity_atom = XInternAtom(xfi->display, "_FREERDP_CLIPRDR_ID", FALSE);

	XChangeProperty(xfi->display, xfi->drawable, cb->identity_atom,
			XA_INTEGER, 32, PropModeReplace, (BYTE*) &id, 1);

	XSelectInput(xfi->display, cb->root_window, PropertyChangeMask);

	n = 0;
	cb->format_mappings[n].target_format = XInternAtom(xfi->display, "_FREERDP_RAW", FALSE);
	cb->format_mappings[n].format_id = CB_FORMAT_RAW;

	n++;
	cb->format_mappings[n].target_format = XInternAtom(xfi->display, "UTF8_STRING", FALSE);
	cb->format_mappings[n].format_id = CB_FORMAT_UNICODETEXT;

	n++;
	cb->format_mappings[n].target_format = XA_STRING;
	cb->format_mappings[n].format_id = CB_FORMAT_TEXT;

	n++;
	cb->format_mappings[n].target_format = XInternAtom(xfi->display, "image/png", FALSE);
	cb->format_mappings[n].format_id = CB_FORMAT_PNG;

	n++;
	cb->format_mappings[n].target_format = XInternAtom(xfi->display, "image/jpeg", FALSE);
	cb->format_mappings[n].format_id = CB_FORMAT_JPEG;

	n++;
	cb->format_mappings[n].target_format = XInternAtom(xfi->display, "image/gif", FALSE);
	cb->format_mappings[n].format_id = CB_FORMAT_GIF;

	n++;
	cb->format_mappings[n].target_format = XInternAtom(xfi->display, "image/bmp", FALSE);
	cb->format_mappings[n].format_id = CB_FORMAT_DIB;

	n++;
	cb->format_mappings[n].target_format = XInternAtom(xfi->display, "text/html", FALSE);
	cb->format_mappings[n].format_id = CB_FORMAT_HTML;

	cb->num_format_mappings = n + 1;
	cb->targets[0] = XInternAtom(xfi->display, "TIMESTAMP", FALSE);
	cb->targets[1] = XInternAtom(xfi->display, "TARGETS", FALSE);
	cb->num_targets = 2;

	cb->incr_atom = XInternAtom(xfi->display, "INCR", FALSE);
}
Example #16
0
void
XtSetWMColormapWindows(
    Widget widget,
    Widget *list,
    Cardinal count)
{
    Window *data;
    Widget *checked, *top, *temp, hookobj;
    Cardinal i, j, checked_count;
    Boolean match;
    Atom xa_wm_colormap_windows;
    WIDGET_TO_APPCON(widget);

    LOCK_APP(app);
    if ( !XtIsRealized(widget) || (count == 0) ) {
	UNLOCK_APP(app);
	return;
    }

    top = checked = (Widget *) __XtMalloc( (Cardinal) sizeof(Widget) * count);


/*
 * The specification calls for only adding the windows that have unique
 * colormaps to the property to this function, so we will make a pass through
 * the widget list removing all the widgets with non-unique colormaps.
 *
 * We will also remove any unrealized widgets from the list at this time.
 */

    for (checked_count = 0, i = 0; i < count; i++) {
	if (!XtIsRealized(list[i])) continue;

	*checked = list[i];
	match = FALSE;

/*
 * Don't check first element for matching colormap since there is nothing
 * to check it against.
 */

	if (checked != top)
	    for (j = 0, temp = top; j < checked_count ; j++, temp++)
		if ( (*temp)->core.colormap == (*checked)->core.colormap) {
		    match = TRUE;
		    break;
		}

/*
 * If no colormap was found to match then add this widget to the linked list.
 */

	if (!match) {
	    checked++;
	    checked_count++;
	}
    }

/*
 * Now that we have the list of widgets we need to convert it to a list of
 * windows and set the property.
 */

    data = (Window *) __XtMalloc( (Cardinal) sizeof(Window) * checked_count);

    for ( i = 0 ; i < checked_count ; i++)
	data[i] = XtWindow(top[i]);

    xa_wm_colormap_windows = XInternAtom(XtDisplay(widget),
					 "WM_COLORMAP_WINDOWS", FALSE);

    XChangeProperty(XtDisplay(widget), XtWindow(widget),
		    xa_wm_colormap_windows, XA_WINDOW, 32,
		    PropModeReplace, (unsigned char *) data, (int) i);

    hookobj = XtHooksOfDisplay(XtDisplay(widget));
    if (XtHasCallbacks(hookobj, XtNchangeHook) == XtCallbackHasSome) {
	XtChangeHookDataRec call_data;

	call_data.type = XtHsetWMColormapWindows;
	call_data.widget = widget;
	call_data.event_data = (XtPointer) list;
	call_data.num_event_data = count;
	XtCallCallbackList(hookobj,
		((HookObject)hookobj)->hooks.changehook_callbacks,
		(XtPointer)&call_data);
    }

    XtFree( (char *) data);
    XtFree( (char *) top);
    UNLOCK_APP(app);
}
Example #17
0
void
panel_start_gui(panel *p)
{
    Atom state[3];
    XWMHints wmhints;
    guint32 val;
 
    
    ENTER;

    // main toplevel window
    p->topgwin =  gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_container_set_border_width(GTK_CONTAINER(p->topgwin), 0);
    gtk_window_set_resizable(GTK_WINDOW(p->topgwin), FALSE);
    gtk_window_set_wmclass(GTK_WINDOW(p->topgwin), "panel", "fbpanel");
    gtk_window_set_title(GTK_WINDOW(p->topgwin), "panel");
    gtk_window_set_position(GTK_WINDOW(p->topgwin), GTK_WIN_POS_NONE);
    gtk_window_set_decorated(GTK_WINDOW(p->topgwin), FALSE);
    
    g_signal_connect(G_OBJECT(p->topgwin), "delete-event",
          G_CALLBACK(panel_delete_event), p);
    g_signal_connect(G_OBJECT(p->topgwin), "destroy-event",
          G_CALLBACK(panel_destroy_event), p);
    g_signal_connect (G_OBJECT (p->topgwin), "size-request",
          (GCallback) panel_size_req, p);
    g_signal_connect (G_OBJECT (p->topgwin), "size-allocate",
          (GCallback) panel_size_alloc, p);
    g_signal_connect (G_OBJECT (p->topgwin), "configure-event",
          (GCallback) panel_configure_event, p);
    g_signal_connect (G_OBJECT (p->topgwin), "realize",
          (GCallback) panel_realize, p);
    g_signal_connect (G_OBJECT (p->topgwin), "style-set",
          (GCallback) panel_style_set, p);
    
    gtk_widget_realize(p->topgwin);
    //gdk_window_set_decorations(p->topgwin->window, 0);
    gtk_widget_set_app_paintable(p->topgwin, TRUE);
    
    // background box all over toplevel
    p->bbox = gtk_bgbox_new();
    gtk_container_add(GTK_CONTAINER(p->topgwin), p->bbox);
    gtk_widget_show(p->bbox);
    gtk_container_set_border_width(GTK_CONTAINER(p->bbox), 0);
    if (p->transparent) {
        p->bg = fb_bg_get_for_display();
        gtk_bgbox_set_background(p->bbox, BG_ROOT, p->tintcolor, p->alpha);        
    }

    // main layout manager as a single child of background widget box
    p->lbox = p->my_box_new(FALSE, 0);
    gtk_container_set_border_width(GTK_CONTAINER(p->lbox), 0);
    gtk_container_add(GTK_CONTAINER(p->bbox), p->lbox);
    gtk_widget_show(p->lbox);
    if (p->round_corners)
        make_round_corners(p);
 
    p->box = p->my_box_new(FALSE, p->spacing); 
    gtk_container_set_border_width(GTK_CONTAINER(p->box), 0);
    gtk_box_pack_start(GTK_BOX(p->lbox), p->box, TRUE, TRUE, 0);
    gtk_widget_show(p->box);
      
    p->topxwin = GDK_WINDOW_XWINDOW(GTK_WIDGET(p->topgwin)->window);
    DBG("topxwin = %x\n", p->topxwin);

    /* the settings that should be done before window is mapped */
    wmhints.flags = InputHint;
    wmhints.input = 0;
    XSetWMHints (GDK_DISPLAY(), p->topxwin, &wmhints); 
#define WIN_HINTS_SKIP_FOCUS      (1<<0)	/* "alt-tab" skips this win */
    val = WIN_HINTS_SKIP_FOCUS;
    XChangeProperty(GDK_DISPLAY(), p->topxwin,
          XInternAtom(GDK_DISPLAY(), "_WIN_HINTS", False), XA_CARDINAL, 32,
          PropModeReplace, (unsigned char *) &val, 1);

    if (p->setdocktype) {
        state[0] = a_NET_WM_WINDOW_TYPE_DOCK;
        XChangeProperty(GDK_DISPLAY(), p->topxwin, a_NET_WM_WINDOW_TYPE, XA_ATOM,
              32, PropModeReplace, (unsigned char *) state, 1);
    }

    /* window mapping point */
    gtk_widget_show_all(p->topgwin);

    /* the settings that should be done after window is mapped */

    /* send it to running wm */
    Xclimsg(p->topxwin, a_NET_WM_DESKTOP, 0xFFFFFFFF, 0, 0, 0, 0);
    /* and assign it ourself just for case when wm is not running */
    val = 0xFFFFFFFF;
    XChangeProperty(GDK_DISPLAY(), p->topxwin, a_NET_WM_DESKTOP, XA_CARDINAL, 32,
          PropModeReplace, (unsigned char *) &val, 1);

    state[0] = a_NET_WM_STATE_SKIP_PAGER;
    state[1] = a_NET_WM_STATE_SKIP_TASKBAR;
    state[2] = a_NET_WM_STATE_STICKY;
    XChangeProperty(GDK_DISPLAY(), p->topxwin, a_NET_WM_STATE, XA_ATOM,
          32, PropModeReplace, (unsigned char *) state, 3);

    XSelectInput (GDK_DISPLAY(), GDK_ROOT_WINDOW(), PropertyChangeMask);
    gdk_window_add_filter(gdk_get_default_root_window (), (GdkFilterFunc)panel_event_filter, p);

    calculate_position(p);
    gdk_window_move_resize(p->topgwin->window, p->ax, p->ay, p->aw, p->ah);
    if (p->setstrut)
        panel_set_wm_strut(p);
  
    RET();
}
Example #18
0
bool MPlayer::init( char * p_filename, MCStack *p_stack, MCRectangle p_rect )
{
	
	// Are we already running a movie? If we are, then stop.
	if ( m_window != DNULL && m_filename != NULL )
		quit();
	
	Window w ;
	if ( p_stack == NULL )
		return false ;
	
	// Locate the window for the stack
	Window stack_window = p_stack->getwindow();
	if ( stack_window == DNULL)
		return false ;
	
	
	// Create a new window
	XSetWindowAttributes xswa;
	unsigned long xswamask = CWBorderPixel | CWColormap;
	xswa.border_pixel = 0;
	xswa.colormap = ((MCScreenDC *)MCscreen) -> getcmapnative() ; 

	w = XCreateWindow(MCdpy, stack_window, 
					  p_rect . x,
					  p_rect . y,
					  p_rect . width,
					  p_rect . height ,
					  0, ((MCScreenDC *)MCscreen)->getrealdepth(), InputOutput,
					  ((MCScreenDC *)MCscreen)-> getvisnative() ->visual,
	                  xswamask, &xswa);
	
	if ( w == DNULL )
		return False;
	
	
	// Set-up our hints so that we have NO window decorations.
	MwmHints mwmhints;
	mwmhints.flags	= MWM_HINTS_DECORATIONS ;
	mwmhints.decorations = 0 ;
	XChangeProperty(MCdpy, w, MCmwmhintsatom, MCmwmhintsatom, 32,
	                PropModeReplace, (unsigned char *)&mwmhints,
	                sizeof(mwmhints) / 4);

	
	// Ensure the newly created window stays above the stack window & map ( show ) 
	XSetTransientForHint(MCdpy, w, stack_window);
	XMapWindow(MCdpy, w);
	
	m_window = w ;
	MClastvideowindow = w ;
	
	if ( m_filename == NULL ) 
		m_filename = strdup(p_filename) ;
	m_player_rect = p_rect ;
	m_stack = p_stack ;

	if ( !launch_player() )
	{
		XUnmapWindow (MCdpy, m_window);
		XDestroyWindow (MCdpy, m_window);
		m_window = DNULL;
		MClastvideowindow = DNULL ;
		return false;
	}

	// We will be playing at start by default, so mark it as such
	m_playing = true ;
	// Start the media stopped
	pause();

	return true ;
}
bool CUnixEventEmitter::processMessage (XEvent &event, CEventServer *server)
{
	if (!server)
		server=&_InternalServer;

	XWindowAttributes xwa;
	XGetWindowAttributes (_dpy, _win, &xwa);

	switch (event.type)
	{
	case ButtonPress:
	{
		//nlinfo("%d %d %d", event.xbutton.button, event.xbutton.x, event.xbutton.y);
		float fX = (float) event.xbutton.x / (float) xwa.width;
		float fY = 1.0f - (float) event.xbutton.y / (float) xwa.height;
		TMouseButton button=getMouseButton(event.xbutton.state);
		switch(event.xbutton.button)
		{
		case Button1:
			server->postEvent(new CEventMouseDown(fX, fY, (TMouseButton)(leftButton|(button&~(leftButton|middleButton|rightButton))), this));
			break;
		case Button2:
			server->postEvent(new CEventMouseDown(fX, fY, (TMouseButton)(middleButton|(button&~(leftButton|middleButton|rightButton))), this));
			break;
		case Button3:
			server->postEvent(new CEventMouseDown(fX, fY, (TMouseButton)(rightButton|(button&~(leftButton|middleButton|rightButton))), this));
			break;
		case Button4:
			server->postEvent(new CEventMouseWheel(fX, fY, button, true, this));
			break;
		case Button5:
			server->postEvent(new CEventMouseWheel(fX, fY, button, false, this));
			break;
		}
		break;
	}
	case ButtonRelease:
	{
		//nlinfo("%d %d %d", event.xbutton.button, event.xbutton.x, event.xbutton.y);
		float fX = (float) event.xbutton.x / (float) xwa.width;
		float fY = 1.0f - (float) event.xbutton.y / (float) xwa.height;
		switch(event.xbutton.button)
		{
		case Button1:
			server->postEvent(new CEventMouseUp(fX, fY, leftButton, this));
			break;
		case Button2:
			server->postEvent(new CEventMouseUp(fX, fY, middleButton, this));
			break;
		case Button3:
			server->postEvent(new CEventMouseUp(fX, fY, rightButton, this));
			break;
		}
		break;
	}
	case MotionNotify:
	{
		TMouseButton button=getMouseButton (event.xbutton.state);

		// if raw mode should be emulated
		if(_emulateRawMode)
		{
			// when we just wrapped back the pointer to 0.5 / 0.5, ignore event
			if(event.xbutton.x == xwa.width / 2 && event.xbutton.y == xwa.height / 2)
				break;

			// post a CGDMouseMove with the movement delta to the event server
			server->postEvent(
				new CGDMouseMove(this, NULL /* no mouse device */,
					event.xbutton.x - (xwa.width / 2),
					(xwa.height / 2) - event.xbutton.y));

			// move the pointer back to the center of the window
			XWarpPointer(_dpy, None, _win, None, None, None, None,
				(xwa.width / 2), (xwa.height / 2));
		}
		// if in normal mouse mode
		else
		{
			// get the relative mouse position
			float fX = (float) event.xbutton.x / (float) xwa.width;
			float fY = 1.0f - (float) event.xbutton.y / (float) xwa.height;

			// post a normal mouse move event to the event server
			server->postEvent (new CEventMouseMove (fX, fY, button, this));
		}
		break;
	}
	case KeyPress:
	{
		// save keycode because XFilterEvent could set it to 0
		uint keyCode = event.xkey.keycode;
		KeySym k;
		static char Text[256];
		int c = 0;

		// check if event is filtered
		bool filtered = XFilterEvent(&event, _win);

		// if key event is filtered, we shouldn't use XLookupString to retrieve KeySym
		if (!filtered)
		{
			Status status = XLookupNone;

#ifdef X_HAVE_UTF8_STRING
			if (_ic)
				c = Xutf8LookupString(_ic, &event.xkey, Text, sizeof(Text), &k, &status);
#endif

			if (status == XLookupNone)
				c = XLookupString(&event.xkey, Text, sizeof(Text), &k, NULL);
		}
		else
		{
			k = XKeycodeToKeysym(_dpy, keyCode, 0);
		}

		// send CEventKeyDown event only if keyCode is defined
		if (keyCode)
		{
			TKey key = getKeyFromKeySym(k);
			if(key == KeyNOKEY)
				key = getKeyFromKeycode(keyCode);

			// search for key in map
			std::map<TKey, bool>::const_iterator it = _PressedKeys.find(key);

			// if key is not found or value is false, that's the first time
			bool firstTime = (it == _PressedKeys.end()) || !it->second;

			server->postEvent (new CEventKeyDown (key, getKeyButton(event.xbutton.state), firstTime, this));
			_PressedKeys[key] = true;

			// don't send a control character when deleting
			if (key == KeyDELETE)
				c = 0;
		}

		Text[c] = '\0';
		if(c>0)
		{
#ifdef X_HAVE_UTF8_STRING
			ucstring ucstr;
			ucstr.fromUtf8(Text);

			CEventChar *charEvent = new CEventChar (ucstr[0], getKeyButton(event.xbutton.state), this);

			// raw if not processed by IME
			charEvent->setRaw(keyCode != 0);

			server->postEvent (charEvent);
#else
			for (int i = 0; i < c; i++)
			{
				CEventChar *charEvent = new CEventChar ((ucchar)(unsigned char)Text[i], getKeyButton(event.xbutton.state), this);

				// raw if not processed by IME
				charEvent->setRaw(keyCode != 0);

				server->postEvent (charEvent);
			}
#endif
		}
		break;
	}
	case KeyRelease:
	{
		if (!keyRepeat(_dpy, &event))
		{
			KeySym k;
			// only need to get correct KeySym
			int c = XLookupString(&event.xkey, NULL, 0, &k, NULL);

			TKey key = getKeyFromKeySym(k);
			if(key == KeyNOKEY)
				key = getKeyFromKeycode(event.xkey.keycode);

			server->postEvent (new CEventKeyUp (key, getKeyButton(event.xbutton.state), this));
			_PressedKeys[key] = false;
		}
		break;
	}
	case SelectionRequest:
	{
		XEvent respond;
		XSelectionRequestEvent req = event.xselectionrequest;

		respond.xselection.type= SelectionNotify;
		respond.xselection.display= req.display;
		respond.xselection.requestor= req.requestor;
		respond.xselection.selection=req.selection;
		respond.xselection.target= req.target;
		respond.xselection.time = req.time;
		respond.xselection.property = req.property;

		if (req.property == None)
		{
			respond.xselection.property = req.target;
		}
		if (req.target == XA_TARGETS)
		{
			Atom targets[] =
			{
				XA_TARGETS,
				XA_STRING,
				XA_UTF8_STRING
			};

			respond.xselection.property = req.property;

			XChangeProperty(req.display, req.requestor, req.property, XA_ATOM, 32, PropModeReplace, (unsigned char *)targets, 3 /* number of element */);
		}
		else if (req.target == XA_STRING)
		{
			respond.xselection.property = req.property;
			std::string str = _CopiedString.toString();
			XChangeProperty(req.display, req.requestor, req.property, XA_STRING, 8, PropModeReplace, (const unsigned char*)str.c_str(), str.length());
		}
		else if (req.target == XA_UTF8_STRING)
		{
			respond.xselection.property = req.property;
			std::string str = _CopiedString.toUtf8();
			XChangeProperty(req.display, req.requestor, respond.xselection.property, XA_UTF8_STRING, 8, PropModeReplace, (const unsigned char*)str.c_str(), str.length());
		}
		else
		{
			// Note: Calling XGetAtomName with arbitrary value crash the client, maybe req.target have been sanitized by X11 server
			respond.xselection.property = None;
		}

		XSendEvent (_dpy, req.requestor, 0, 0, &respond);

		break;
	}
	case SelectionClear:
		_SelectionOwned = false;
		_CopiedString = "";
		break;
	case SelectionNotify:
	{
		Atom target = event.xselection.target;

		Atom actualType = 0;
		int actualFormat = 0;
		unsigned long nitems = 0, bytesLeft = 0;

		// some applications are sending ATOM and other TARGETS
		if (target == XA_TARGETS || target == XA_ATOM)
		{
			Atom *supportedTargets = NULL;

			// list NeL selection properties
			if (XGetWindowProperty(_dpy, _win, XA_NEL_SEL, 0, XMaxRequestSize(_dpy), False, AnyPropertyType, &actualType, &actualFormat, &nitems, &bytesLeft, (unsigned char**)&supportedTargets) != Success)
				return false;

			if (bytesLeft > 0)
			{
				nlwarning("Paste: Supported TARGETS list too long.");
			}

			Atom bestTarget = 0;
			sint bestTargetElect = 0;

			// Elect best type
			for (uint i=0; i < nitems; i++)
			{
				// nlwarning(" - Type=%s (%u)", XGetAtomName(_dpy, supportedTargets[i]), (uint)supportedTargets[i]);
				if (supportedTargets[i] == XA_UTF8_STRING )
				{
					if (bestTargetElect < 2)
					{
						bestTarget = XA_UTF8_STRING;
						bestTargetElect = 2;
					}
				}
				else if (supportedTargets[i] == XA_STRING )
				{
					if (bestTargetElect < 1)
					{
						bestTarget = XA_STRING;
						bestTargetElect = 1;
					}
				}
			}

			XFree(supportedTargets);

			if (!bestTargetElect)
			{
				nlwarning("Paste buffer is not a text buffer.");
				return false;
			}

			// request string conversion
			XConvertSelection(_dpy, XA_CLIPBOARD, bestTarget, XA_NEL_SEL, _win, CurrentTime);
		}
		else if (target == XA_UTF8_STRING || target == XA_STRING)
		{
			uint8 *data = NULL;

			// get selection
			if (XGetWindowProperty(_dpy, _win, XA_NEL_SEL, 0, XMaxRequestSize(_dpy), False, AnyPropertyType, &actualType, &actualFormat, &nitems, &bytesLeft, (unsigned char**)&data) != Success)
				return false;

			ucstring text;
			std::string tmpData = (const char*)data;
			XFree(data);

			// convert buffer to ucstring
			if (target == XA_UTF8_STRING)
			{
				text = ucstring::makeFromUtf8(tmpData);
			}
			else if (target == XA_STRING)
			{
				text = tmpData;
			}
			else
			{
				nlwarning("Unknow format %u", (uint)target);
			}

			// sent string event to event server
			server->postEvent (new CEventString (text, this));
		}
		else
		{
			nlwarning("Unknow target %u", (uint)target);
		}

		break;
	}
	case FocusIn:
		// keyboard focus
//		server->postEvent (new CEventSetFocus (true, this));
		if (_ic) XSetICFocus(_ic);
		break;
	case FocusOut:
		// keyboard focus
//		server->postEvent (new CEventSetFocus (false, this));
		if (_ic) XUnsetICFocus(_ic);
		break;
	case KeymapNotify:
		break;
	case MappingNotify:
		// update keymap
		XRefreshKeyboardMapping((XMappingEvent *)&event);
		break;
	case DestroyNotify:
		// XIM server has crashed
		createIM();
		break;
	case ClientMessage:
		if ((event.xclient.format == 32) && ((Atom)event.xclient.data.l[0] == XA_WM_DELETE_WINDOW))
		{
			server->postEvent(new CEventDestroyWindow(this));
		}
		break;
	default:
		//	nlinfo("UnknownEvent");
		//	XtDispatchEvent(&event);
		return false;
	}

	return true;
}
Example #20
0
void X11Support::setWindowPropertyCardinalArray(unsigned long window, const QString& name, const QVector<unsigned long>& values)
{
	XChangeProperty(QX11Info::display(), window, atom(name), XA_CARDINAL, 32, PropModeReplace, reinterpret_cast<const unsigned char*>(values.data()), values.size());
}
Example #21
0
static PyObject *
osk_struts_set (PyObject *self, PyObject *args)
{
    Display       *dpy;
    unsigned long  xid;
    unsigned long  struts[12] = { 0, };
    PyObject      *obj, *seq, **items;
    int            i;

    if (!PyArg_ParseTuple (args, "kO", &xid, &obj))
        return NULL;

    seq = PySequence_Fast (obj, "expected sequence type");
    if (!seq)
        return NULL;

    if (PySequence_Fast_GET_SIZE (seq) != 12)
    {
        PyErr_SetString (PyExc_ValueError, "expected 12 values");
        return NULL;
    }

    items = PySequence_Fast_ITEMS (seq);

    for (i = 0; i < 12; i++, items++)
    {
        struts[i] = PyLong_AsUnsignedLongMask (*items);

        if (PyErr_Occurred ())
        {
            Py_DECREF (seq);
            return NULL;
        }

        if (struts[i] < 0)
        {
            PyErr_SetString (PyExc_ValueError, "expected value >= 0");
            Py_DECREF (seq);
            return NULL;
        }
    }

    Py_DECREF (seq);

    dpy = GDK_DISPLAY_XDISPLAY (gdk_display_get_default ());

    gdk_error_trap_push ();

    XChangeProperty (dpy, xid,
                     XInternAtom (dpy, "_NET_WM_STRUT", False),
                     XA_CARDINAL, 32, PropModeReplace,
                     (unsigned char *) &struts, 4);

    XChangeProperty (dpy, xid,
                     XInternAtom (dpy, "_NET_WM_STRUT_PARTIAL", False),
                     XA_CARDINAL, 32, PropModeReplace,
                     (unsigned char *) &struts, 12);


    gdk_error_trap_pop_ignored ();

    Py_RETURN_NONE;
}
Example #22
0
void X11Support::setWindowPropertyVisualId(unsigned long window, const QString& name, unsigned long value)
{
	XChangeProperty(QX11Info::display(), window, atom(name), XA_VISUALID, 32, PropModeReplace, reinterpret_cast<const unsigned char*>(&value), 1);
}
Example #23
0
// Enter fullscreen mode
//
static void enterFullscreenMode(_GLFWwindow* window)
{
    if (_glfw.x11.saver.count == 0)
    {
        // Remember old screen saver settings
        XGetScreenSaver(_glfw.x11.display,
                        &_glfw.x11.saver.timeout,
                        &_glfw.x11.saver.interval,
                        &_glfw.x11.saver.blanking,
                        &_glfw.x11.saver.exposure);

        // Disable screen saver
        XSetScreenSaver(_glfw.x11.display, 0, 0, DontPreferBlanking,
                        DefaultExposures);
    }

    _glfw.x11.saver.count++;

    _glfwSetVideoMode(window->monitor, &window->videoMode);

    if (_glfw.x11.NET_WM_BYPASS_COMPOSITOR)
    {
        const unsigned long value = 1;

        XChangeProperty(_glfw.x11.display,  window->x11.handle,
                        _glfw.x11.NET_WM_BYPASS_COMPOSITOR, XA_CARDINAL, 32,
                        PropModeReplace, (unsigned char*) &value, 1);
    }

    if (_glfw.x11.NET_WM_STATE && _glfw.x11.NET_WM_STATE_FULLSCREEN)
    {
        int x, y;
        _glfwPlatformGetMonitorPos(window->monitor, &x, &y);
        _glfwPlatformSetWindowPos(window, x, y);

        if (_glfw.x11.NET_ACTIVE_WINDOW)
        {
            // Ask the window manager to raise and focus the GLFW window
            // Only focused windows with the _NET_WM_STATE_FULLSCREEN state end
            // up on top of all other windows ("Stacking order" in EWMH spec)

            XEvent event;
            memset(&event, 0, sizeof(event));

            event.type = ClientMessage;
            event.xclient.window = window->x11.handle;
            event.xclient.format = 32; // Data is 32-bit longs
            event.xclient.message_type = _glfw.x11.NET_ACTIVE_WINDOW;
            event.xclient.data.l[0] = 1; // Sender is a normal application
            event.xclient.data.l[1] = 0; // We don't really know the timestamp

            XSendEvent(_glfw.x11.display,
                       _glfw.x11.root,
                       False,
                       SubstructureNotifyMask | SubstructureRedirectMask,
                       &event);
        }

        // Ask the window manager to make the GLFW window a fullscreen window
        // Fullscreen windows are undecorated and, when focused, are kept
        // on top of all other windows

        XEvent event;
        memset(&event, 0, sizeof(event));

        event.type = ClientMessage;
        event.xclient.window = window->x11.handle;
        event.xclient.format = 32; // Data is 32-bit longs
        event.xclient.message_type = _glfw.x11.NET_WM_STATE;
        event.xclient.data.l[0] = _NET_WM_STATE_ADD;
        event.xclient.data.l[1] = _glfw.x11.NET_WM_STATE_FULLSCREEN;
        event.xclient.data.l[2] = 0; // No secondary property
        event.xclient.data.l[3] = 1; // Sender is a normal application

        XSendEvent(_glfw.x11.display,
                   _glfw.x11.root,
                   False,
                   SubstructureNotifyMask | SubstructureRedirectMask,
                   &event);
    }
    else if (window->x11.overrideRedirect)
    {
        // In override-redirect mode we have divorced ourselves from the
        // window manager, so we need to do everything manually

        GLFWvidmode mode;
        _glfwPlatformGetVideoMode(window->monitor, &mode);

        XRaiseWindow(_glfw.x11.display, window->x11.handle);
        XSetInputFocus(_glfw.x11.display, window->x11.handle,
                       RevertToParent, CurrentTime);
        XMoveWindow(_glfw.x11.display, window->x11.handle, 0, 0);
        XResizeWindow(_glfw.x11.display, window->x11.handle,
                      mode.width, mode.height);
    }
}
Example #24
0
/**
 * Filters through SDL_Events searching for clipboard requests from the X
 * server.
 *
 * @param evt   The event to filter.
 */
static int widgetClipboardFilterX11(const SDL_Event *evt)
{
	// We are only interested in window manager events
	if (evt->type == SDL_SYSWMEVENT)
	{
		XEvent xevent = evt->syswm.msg->event.xevent;

		// See if the event is a selection/clipboard request
		if (xevent.type == SelectionRequest)
		{
			// Get the request in question
			XSelectionRequestEvent *request = &xevent.xselectionrequest;

			// Generate a reply to the selection request
			XSelectionEvent reply;

			reply.type = SelectionNotify;
			reply.serial = xevent.xany.send_event;
			reply.send_event = True;
			reply.display = info.info.x11.display;
			reply.requestor = request->requestor;
			reply.selection = request->selection;
			reply.property = request->property;
			reply.target = None;
			reply.time = request->time;

			// They want to know what we can provide/offer
			if (request->target == XA_TARGETS)
			{
				Atom possibleTargets[] =
				{
					XA_STRING,
					XA_UTF8_STRING,
					XA_COMPOUND_TEXT
				};

				XChangeProperty(info.info.x11.display, request->requestor,
				                request->property, XA_ATOM, 32, PropModeReplace,
				                (unsigned char *) possibleTargets, 3);
			}
			// They want a string (all we can provide)
			else if (request->target == XA_STRING
			      || request->target == XA_UTF8_STRING
			      || request->target == XA_COMPOUND_TEXT)
			{
				int len;
				char *xdata = XFetchBytes(info.info.x11.display, &len);

				XChangeProperty(info.info.x11.display, request->requestor,
				                request->property, request->target, 8,
				                PropModeReplace, (unsigned char *) xdata,
				                len);
				XFree(xdata);
			}
			else
			{
				// Did not have what they wanted, so no property set
				reply.property = None;
			}

			// Dispatch the event
			XSendEvent(request->display, request->requestor, 0, NoEventMask,
			           (XEvent *) &reply);
			XSync(info.info.x11.display, False);
		}
	}

	return 1;
}
Example #25
0
static GLUTwindow *
processWindowWorkList(GLUTwindow * window)
{
  int workMask;

  if (window->prevWorkWin) {
    window->prevWorkWin = processWindowWorkList(window->prevWorkWin);
  } else {
    beforeEnd = &window->prevWorkWin;
  }

  /* Capture work mask for work that needs to be done to this
     window, then clear the window's work mask (excepting the
     dummy work bit, see below).  Then, process the captured
     work mask.  This allows callbacks in the processing the
     captured work mask to set the window's work mask for
     subsequent processing. */

  workMask = window->workMask;
  assert((workMask & GLUT_DUMMY_WORK) == 0);

  /* Set the dummy work bit, clearing all other bits, to
     indicate that the window is currently on the window work
     list _and_ that the window's work mask is currently being
     processed.  This convinces __glutPutOnWorkList that this
     window is on the work list still. */
  window->workMask = GLUT_DUMMY_WORK;

  /* Optimization: most of the time, the work to do is a
     redisplay and not these other types of work.  Check for
     the following cases as a group to before checking each one
     individually one by one. This saves about 25 MIPS
     instructions in the common redisplay only case. */
  if (workMask & (GLUT_EVENT_MASK_WORK | GLUT_DEVICE_MASK_WORK |
      GLUT_CONFIGURE_WORK | GLUT_COLORMAP_WORK | GLUT_MAP_WORK)) {
#if !defined(_WIN32)
    /* Be sure to set event mask BEFORE map window is done. */
    if (workMask & GLUT_EVENT_MASK_WORK) {
      long eventMask;

      /* Make sure children are not propogating events this
         window is selecting for.  Be sure to do this before
         enabling events on the children's parent. */
      if (window->children) {
        GLUTwindow *child = window->children;
        unsigned long attribMask = CWDontPropagate;
        XSetWindowAttributes wa;

        wa.do_not_propagate_mask = window->eventMask & GLUT_DONT_PROPAGATE_FILTER_MASK;
        if (window->eventMask & GLUT_HACK_STOP_PROPAGATE_MASK) {
          wa.event_mask = child->eventMask | (window->eventMask & GLUT_HACK_STOP_PROPAGATE_MASK);
          attribMask |= CWEventMask;
        }
        do {
          XChangeWindowAttributes(__glutDisplay, child->win,
            attribMask, &wa);
          child = child->siblings;
        } while (child);
      }
      eventMask = window->eventMask;
      if (window->parent && window->parent->eventMask & GLUT_HACK_STOP_PROPAGATE_MASK)
        eventMask |= (window->parent->eventMask & GLUT_HACK_STOP_PROPAGATE_MASK);
      XSelectInput(__glutDisplay, window->win, eventMask);
      if (window->overlay)
        XSelectInput(__glutDisplay, window->overlay->win,
          window->eventMask & GLUT_OVERLAY_EVENT_FILTER_MASK);
    }
#endif /* !_WIN32 */
    /* Be sure to set device mask BEFORE map window is done. */
    if (workMask & GLUT_DEVICE_MASK_WORK) {
      __glutUpdateInputDeviceMaskFunc(window);
    }
    /* Be sure to configure window BEFORE map window is done. */
    if (workMask & GLUT_CONFIGURE_WORK) {
#if defined(_WIN32)
      RECT changes;
      POINT point;
      UINT flags = SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER
	| SWP_NOSENDCHANGING | SWP_NOSIZE | SWP_NOZORDER;

      GetClientRect(window->win, &changes);
      
      /* If this window is a toplevel window, translate the 0,0 client
         coordinate into a screen coordinate for proper placement. */
      if (!window->parent) {
        point.x = 0;
        point.y = 0;
        ClientToScreen(window->win, &point);
        changes.left = point.x;
        changes.top = point.y;
      }
      if (window->desiredConfMask & (CWX | CWY)) {
        changes.left = window->desiredX;
        changes.top = window->desiredY;
	flags &= ~SWP_NOMOVE;
      }
      if (window->desiredConfMask & (CWWidth | CWHeight)) {
        changes.right = changes.left + window->desiredWidth;
        changes.bottom = changes.top + window->desiredHeight;
	flags &= ~SWP_NOSIZE;
	/* XXX If overlay exists, resize the overlay here, ie.
	   if (window->overlay) ... */
      }
      if (window->desiredConfMask & CWStackMode) {
	flags &= ~SWP_NOZORDER;
	/* XXX Overlay support might require something special here. */
      }

      /* Adjust the window rectangle because Win32 thinks that the x, y,
         width & height are the WHOLE window (including decorations),
         whereas GLUT treats the x, y, width & height as only the CLIENT
         area of the window.  Only do this to top level windows
         that are not in game mode (since game mode windows do
         not have any decorations). */
      if (!window->parent && window != __glutGameModeWindow) {
        AdjustWindowRect(&changes,
          WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
          FALSE);
      }

      /* Do the repositioning, moving, and push/pop. */
      SetWindowPos(window->win,
        window->desiredStack == Above ? HWND_TOP : HWND_NOTOPMOST,
        changes.left, changes.top,
        changes.right - changes.left, changes.bottom - changes.top,
        flags);

      /* Zero out the mask. */
      window->desiredConfMask = 0;

      /* This hack causes the window to go back to the right position
         when it is taken out of fullscreen mode. */
      if (workMask & GLUT_FULL_SCREEN_WORK) {
        window->desiredConfMask |= CWX | CWY;
        window->desiredX = point.x;
        window->desiredY = point.y;
      }
#else /* !_WIN32 */
      XWindowChanges changes;

      changes.x = window->desiredX;
      changes.y = window->desiredY;
      if (window->desiredConfMask & (CWWidth | CWHeight)) {
        changes.width = window->desiredWidth;
        changes.height = window->desiredHeight;
        if (window->overlay)
          XResizeWindow(__glutDisplay, window->overlay->win,
            window->desiredWidth, window->desiredHeight);
        if (__glutMotifHints != None) {
          if (workMask & GLUT_FULL_SCREEN_WORK) {
            MotifWmHints hints;

            hints.flags = MWM_HINTS_DECORATIONS;
            hints.decorations = 0;  /* Absolutely no
                                       decorations. */
            XChangeProperty(__glutDisplay, window->win,
              __glutMotifHints, __glutMotifHints, 32,
              PropModeReplace, (unsigned char *) &hints, 4);
            if (workMask & GLUT_MAP_WORK) {
              /* Handle case where glutFullScreen is called
                 before the first time that the window is
                 mapped. Some window managers will randomly or
                 interactively position the window the first
                 time it is mapped if the window's
                 WM_NORMAL_HINTS property does not request an
                 explicit position. We don't want any such
                 window manager interaction when going
                 fullscreen.  Overwrite the WM_NORMAL_HINTS
                 property installed by glutCreateWindow's
                 XSetWMProperties property with one explicitly
                 requesting a fullscreen window. */
              XSizeHints hints;

              hints.flags = USPosition | USSize;
              hints.x = 0;
              hints.y = 0;
              hints.width = window->desiredWidth;
              hints.height = window->desiredHeight;
              XSetWMNormalHints(__glutDisplay, window->win, &hints);
            }
          } else {
            XDeleteProperty(__glutDisplay, window->win, __glutMotifHints);
          }
        }
      }
      if (window->desiredConfMask & CWStackMode) {
        changes.stack_mode = window->desiredStack;
        /* Do not let glutPushWindow push window beneath the
           underlay. */
        if (window->parent && window->parent->overlay
          && window->desiredStack == Below) {
          changes.stack_mode = Above;
          changes.sibling = window->parent->overlay->win;
          window->desiredConfMask |= CWSibling;
        }
      }
      XConfigureWindow(__glutDisplay, window->win,
        window->desiredConfMask, &changes);
      window->desiredConfMask = 0;
#endif
    }
#if !defined(_WIN32)
    /* Be sure to establish the colormaps BEFORE map window is
       done. */
    if (workMask & GLUT_COLORMAP_WORK) {
      __glutEstablishColormapsProperty(window);
    }
#endif
    if (workMask & GLUT_MAP_WORK) {
      switch (window->desiredMapState) {
      case WithdrawnState:
        if (window->parent) {
          XUnmapWindow(__glutDisplay, window->win);
        } else {
          XWithdrawWindow(__glutDisplay, window->win,
            __glutScreen);
        }
        window->shownState = 0;
        break;
      case NormalState:
        XMapWindow(__glutDisplay, window->win);
        window->shownState = 1;
        break;
#ifdef _WIN32
      case GameModeState:  /* Not an Xlib value. */
        ShowWindow(window->win, SW_SHOW);
        window->shownState = 1;
        break;
#endif
      case IconicState:
        XIconifyWindow(__glutDisplay, window->win, __glutScreen);
        window->shownState = 0;
        break;
      }
    }
  }
  if (workMask & (GLUT_REDISPLAY_WORK | GLUT_OVERLAY_REDISPLAY_WORK | GLUT_REPAIR_WORK | GLUT_OVERLAY_REPAIR_WORK)) {
    if (window->forceReshape) {
      /* Guarantee that before a display callback is generated
         for a window, a reshape callback must be generated. */
      __glutSetWindow(window);
      window->reshape(window->width, window->height);
      window->forceReshape = False;

      /* Setting the redisplay bit on the first reshape is
         necessary to make the "Mesa glXSwapBuffers to repair
         damage" hack operate correctly.  Without indicating a
         redisplay is necessary, there's not an initial back
         buffer render from which to blit from when damage
         happens to the window. */
      workMask |= GLUT_REDISPLAY_WORK;
    }
    /* The code below is more involved than otherwise necessary
       because it is paranoid about the overlay or entire window
       being removed or destroyed in the course of the callbacks.
       Notice how the global __glutWindowDamaged is used to record
       the layers' damage status.  See the code in glutLayerGet for
       how __glutWindowDamaged is used. The  point is to not have to
       update the "damaged" field after  the callback since the
       window (or overlay) may be destroyed (or removed) when the
       callback returns. */

    if (window->overlay && window->overlay->display) {
      int num = window->num;
      Window xid = window->overlay ? window->overlay->win : None;

      /* If an overlay display callback is registered, we
         differentiate between a redisplay needed for the
         overlay and/or normal plane.  If there is no overlay
         display callback registered, we simply use the
         standard display callback. */

      if (workMask & (GLUT_REDISPLAY_WORK | GLUT_REPAIR_WORK)) {
        if (__glutMesaSwapHackSupport) {
          if (window->usedSwapBuffers) {
            if ((workMask & (GLUT_REPAIR_WORK | GLUT_REDISPLAY_WORK)) == GLUT_REPAIR_WORK) {
	      SWAP_BUFFERS_WINDOW(window);
              goto skippedDisplayCallback1;
            }
          }
        }
        /* Render to normal plane. */
#ifdef _WIN32
        window->renderDc = window->hdc;
#endif
        window->renderWin = window->win;
        window->renderCtx = window->ctx;
        __glutWindowDamaged = (workMask & GLUT_REPAIR_WORK);
        __glutSetWindow(window);
        window->usedSwapBuffers = 0;
        window->display();
        __glutWindowDamaged = 0;

      skippedDisplayCallback1:;
      }
      if (workMask & (GLUT_OVERLAY_REDISPLAY_WORK | GLUT_OVERLAY_REPAIR_WORK)) {
        window = __glutWindowList[num];
        if (window && window->overlay &&
          window->overlay->win == xid && window->overlay->display) {

          /* Render to overlay. */
#ifdef _WIN32
          window->renderDc = window->overlay->hdc;
#endif
          window->renderWin = window->overlay->win;
          window->renderCtx = window->overlay->ctx;
          __glutWindowDamaged = (workMask & GLUT_OVERLAY_REPAIR_WORK);
          __glutSetWindow(window);
          window->overlay->display();
          __glutWindowDamaged = 0;
        } else {
          /* Overlay may have since been destroyed or the
             overlay callback may have been disabled during
             normal display callback. */
        }
      }
    } else {
      if (__glutMesaSwapHackSupport) {
        if (!window->overlay && window->usedSwapBuffers) {
          if ((workMask & (GLUT_REPAIR_WORK | GLUT_REDISPLAY_WORK)) == GLUT_REPAIR_WORK) {
	    SWAP_BUFFERS_WINDOW(window);
            goto skippedDisplayCallback2;
          }
        }
      }
      /* Render to normal plane (and possibly overlay). */
      __glutWindowDamaged = (workMask & (GLUT_OVERLAY_REPAIR_WORK | GLUT_REPAIR_WORK));
      __glutSetWindow(window);
      window->usedSwapBuffers = 0;
      window->display();
      __glutWindowDamaged = 0;

    skippedDisplayCallback2:;
    }
  }
  /* Combine workMask with window->workMask to determine what
     finish and debug work there is. */
  workMask |= window->workMask;

  if (workMask & GLUT_FINISH_WORK) {
    /* Finish work makes sure a glFinish gets done to indirect
       rendering contexts.  Indirect contexts tend to have much 
       longer latency because lots of OpenGL extension requests 
       can queue up in the X protocol stream. __glutSetWindow
       is where the finish works gets queued for indirect
       contexts. */
    __glutSetWindow(window);
#if !defined(_WIN32)
    if (!window->isDirect)
#endif
    {
       glFinish();
    }
  }
  if (workMask & GLUT_DEBUG_WORK) {
    __glutSetWindow(window);
    glutReportErrors();
  }
  /* Strip out dummy, finish, and debug work bits. */
  window->workMask &= ~(GLUT_DUMMY_WORK | GLUT_FINISH_WORK | GLUT_DEBUG_WORK);
  if (window->workMask) {
    /* Leave on work list. */
    return window;
  } else {
    /* Remove current window from work list. */
    return window->prevWorkWin;
  }
}
Example #26
0
DockWnd::DockWnd(QWidget *main)
        : QWidget(NULL, "dock",  WType_TopLevel | WStyle_Customize | WStyle_NoBorder | WStyle_StaysOnTop)
{
    setMouseTracking(true);
    connect(this, SIGNAL(toggleWin()), main, SLOT(toggleShow()));
    connect(this, SIGNAL(showPopup(QPoint)), main, SLOT(showDockPopup(QPoint)));
    connect(this, SIGNAL(doubleClicked()), main, SLOT(dockDblClicked()));
    connect(pClient, SIGNAL(event(ICQEvent*)), this, SLOT(processEvent(ICQEvent*)));
    connect(pMain, SIGNAL(iconChanged()), this, SLOT(reset()));
    connect(pMain, SIGNAL(msgChanged()), this, SLOT(reset()));
    m_state = 0;
    showIcon = State;
    QTimer *t = new QTimer(this);
    connect(t, SIGNAL(timeout()), this, SLOT(timer()));
    t->start(800);
    bNoToggle = false;
#ifdef WIN32
    QWidget::hide();
    QWidget::setIcon(Pict(pClient->getStatusIcon()));
    gDock = this;
    oldDockProc = (WNDPROC)SetWindowLongW(winId(), GWL_WNDPROC, (LONG)DockWindowProc);
    if (oldDockProc == 0)
        oldDockProc = (WNDPROC)SetWindowLongA(winId(), GWL_WNDPROC, (LONG)DockWindowProc);
    NOTIFYICONDATAA notifyIconData;
    notifyIconData.cbSize = sizeof(notifyIconData);
    notifyIconData.hIcon = topData()->winIcon;
    notifyIconData.hWnd = winId();
    notifyIconData.szTip[0] = 0;
    notifyIconData.uCallbackMessage = WM_DOCK;
    notifyIconData.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
    notifyIconData.uID = 0;
    Shell_NotifyIconA(NIM_ADD, &notifyIconData);
#else
    setMinimumSize(22, 22);
    resize(22, 22);
    bInit = false;
    inTray = false;
    inNetTray = false;

    Display *dsp = x11Display();
    WId win = winId();

    if (bEnlightenment){
        wharfIcon = NULL;
        bInit = true;
        resize(48, 48);
        setFocusPolicy(NoFocus);
        move(pMain->getDockX(), pMain->getDockY());
        reset();
        MWMHints mwm;
        mwm.flags = MWM_HINTS_DECORATIONS;
        mwm.functions = 0;
        mwm.decorations = 0;
        mwm.inputMode = 0;
        mwm.status = 0;
        Atom a = XInternAtom(dsp, "_MOTIF_WM_HINTS", False);
        XChangeProperty(dsp, win, a, a, 32, PropModeReplace,
                        (unsigned char *)&mwm, sizeof(MWMHints) / 4);
        XStoreName(dsp, win, "SIM");
        XClassHint *xch = XAllocClassHint();
        xch->res_name  = (char*)"SIM";
        xch->res_class = (char*)"Epplet";
        XSetClassHint(dsp, win, xch);
        XFree(xch);
        XSetIconName(dsp, win, "SIM");
        unsigned long val = (1 << 0) /* | (1 << 9) */ ;
        a = XInternAtom(dsp, "_WIN_STATE", False);
        XChangeProperty(dsp, win, a, XA_CARDINAL, 32, PropModeReplace,
                        (unsigned char *)&val, 1);
        val = 2;
        a = XInternAtom(dsp, "_WIN_LAYER", False);
        XChangeProperty(dsp, win, a, XA_CARDINAL, 32, PropModeReplace,
                        (unsigned char *)&val, 1);
        val = (1 << 0) | (1 << 1) | (1 << 2) | (1 << 5);
        a = XInternAtom(dsp, "_WIN_HINTS", False);
        XChangeProperty(dsp, win, a, XA_CARDINAL, 32, PropModeReplace,
                        (unsigned char *)&val, 1);
        win_name = "SIM";
        win_version = VERSION;
        win_info = "";
        while (!comms_win)
        {
            ECommsSetup(dsp);
            sleep(1);
        }
        char s[256];
        snprintf(s, sizeof(s), "set clientname %s", win_name);
        ECommsSend(s);
        snprintf(s, sizeof(s), "set version %s", win_version);
        ECommsSend(s);
        snprintf(s, sizeof(s), "set info %s", win_info);
        ECommsSend(s);
        ESYNC;

        set_background_properties(this);

        show();
        return;
    }

    wharfIcon = new WharfIcon(this);

    setBackgroundMode(X11ParentRelative);
    const QPixmap &pict = Pict(pClient->getStatusIcon());
    setIcon(pict);

    XClassHint classhint;
    classhint.res_name  = (char*)"sim";
    classhint.res_class = (char*)"Wharf";
    XSetClassHint(dsp, win, &classhint);

    Screen *screen = XDefaultScreenOfDisplay(dsp);
    int screen_id = XScreenNumberOfScreen(screen);
    char buf[32];
    snprintf(buf, sizeof(buf), "_NET_SYSTEM_TRAY_S%d", screen_id);
    Atom selection_atom = XInternAtom(dsp, buf, false);
    XGrabServer(dsp);
    Window manager_window = XGetSelectionOwner(dsp, selection_atom);
    if (manager_window != None)
        XSelectInput(dsp, manager_window, StructureNotifyMask);
    XUngrabServer(dsp);
    XFlush(dsp);
    if (manager_window != None){
        inNetTray = true;
        if (!send_message(dsp, manager_window, SYSTEM_TRAY_REQUEST_DOCK, win, 0, 0)){
            inNetTray = false;
        }
    }

    Atom kde_net_system_tray_window_for_atom = XInternAtom(dsp, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);

    long data[1];
    data[0] = 0;
    XChangeProperty(dsp, win, kde_net_system_tray_window_for_atom, XA_WINDOW,
                    32, PropModeReplace,
                    (unsigned char*)data, 1);

    XWMHints *hints;
    hints = XGetWMHints(dsp, win);
    hints->initial_state = WithdrawnState;
    hints->icon_x = 0;
    hints->icon_y = 0;
    hints->icon_window = wharfIcon->winId();
    hints->window_group = win;
    hints->flags = WindowGroupHint | IconWindowHint | IconPositionHint | StateHint;
    XSetWMHints(dsp, win, hints);
    XFree( hints );
    XSetCommand(dsp, win, _argv, _argc);

    if (!inNetTray){
        move(-21, -21);
        resize(22, 22);
    }
    show();
#endif
    reset();
}
Example #27
0
/*
 * update_default_decorations
 *
 * Description: update the default decorations
 */
void
update_default_decorations (GdkScreen *screen)
{
    long	    *data;
    Window	    xroot;
    GdkDisplay	    *gdkdisplay = gdk_display_get_default ();
    Display	    *xdisplay = gdk_x11_display_get_xdisplay (gdkdisplay);
    Atom	    bareAtom, activeAtom;
    decor_frame_t   *frame;
    decor_frame_t   *bare_frame = gwd_get_decor_frame ("bare");
    decor_extents_t extents;
    unsigned int    i;

    xroot = RootWindowOfScreen (gdk_x11_screen_get_xscreen (screen));

    bareAtom   = XInternAtom (xdisplay, DECOR_BARE_ATOM_NAME, FALSE);
    activeAtom = XInternAtom (xdisplay, DECOR_ACTIVE_ATOM_NAME, FALSE);

    if (bare_frame->border_shadow_active)
    {
	decor_layout_t layout;
	unsigned int   frame_type = 0;
	unsigned int   frame_state = 0;
	unsigned int   frame_actions = 0;
	unsigned int   nQuad;
	decor_quad_t   quads[N_QUADS_MAX];

	long *data = decor_alloc_property (1, WINDOW_DECORATION_TYPE_PIXMAP);

	decor_get_default_layout (&bare_frame->window_context_active, 1, 1, &layout);

	nQuad = decor_set_lSrStSbS_window_quads (quads, &bare_frame->window_context_active,
						 &layout);

	decor_quads_to_property (data, 0, bare_frame->border_shadow_active->pixmap,
				 &bare_frame->win_extents, &bare_frame->win_extents,
				 &bare_frame->win_extents, &bare_frame->win_extents,
				 0, 0, quads, nQuad, frame_type, frame_state, frame_actions);

	XChangeProperty (xdisplay, xroot,
			 bareAtom,
			 XA_INTEGER,
			 32, PropModeReplace, (guchar *) data,
			 PROP_HEADER_SIZE + BASE_PROP_SIZE + QUAD_PROP_SIZE * N_QUADS_MAX);

	if (minimal)
	{
	    XChangeProperty (xdisplay, xroot,
			     activeAtom,
			     XA_INTEGER,
			     32, PropModeReplace, (guchar *) data,
			     PROP_HEADER_SIZE + BASE_PROP_SIZE + QUAD_PROP_SIZE * N_QUADS_MAX);
	}

        free (data);
    }
    else
    {
	XDeleteProperty (xdisplay, xroot, bareAtom);

	if (minimal)
	{
	    XDeleteProperty (xdisplay, xroot, activeAtom);
	}
    }

    if (minimal)
    {
	gwd_decor_frame_unref (bare_frame);
	return;
    }

    XDeleteProperty (xdisplay, xroot,
                     activeAtom);

    data = decor_alloc_property (WINDOW_TYPE_FRAMES_NUM * 2, WINDOW_DECORATION_TYPE_PIXMAP);

    /* All active states and all inactive states */
    for (i = 0; i < WINDOW_TYPE_FRAMES_NUM * 2; ++i)
    {
        frame = gwd_get_decor_frame (default_frames[i].name);
        extents = frame->win_extents;

        if (default_frames[i].d)
        {
            if (default_frames[i].d->surface)
                cairo_surface_destroy (default_frames[i].d->surface);

            free (default_frames[i].d);
        }

        default_frames[i].d = calloc (1, sizeof (decor_t));

        default_frames[i].d->context = i < WINDOW_TYPE_FRAMES_NUM ? &frame->window_context_active : &frame->window_context_inactive;
        default_frames[i].d->shadow  =  i < WINDOW_TYPE_FRAMES_NUM ? frame->border_shadow_active : frame->border_shadow_inactive;
        default_frames[i].d->layout  = pango_layout_new (frame->pango_context);

        decor_get_default_layout (default_frames[i].d->context, 1, 1, &default_frames[i].d->border_layout);

        default_frames[i].d->width  = default_frames[i].d->border_layout.width;
        default_frames[i].d->height = default_frames[i].d->border_layout.height;

        default_frames[i].d->frame = frame;
        default_frames[i].d->active = i < WINDOW_TYPE_FRAMES_NUM ? TRUE : FALSE;

        extents.top += frame->titlebar_height;

        default_frames[i].d->draw = theme_draw_window_decoration;
	default_frames[i].d->surface = create_native_surface_and_wrap (default_frames[i].d->width,
	                                                               default_frames[i].d->height,
	                                                               frame->style_window_rgba);

	unsigned int j, k;

	for (j = 0; j < 3; ++j)
	{
	    for (k = 0; k < 3; k++)
	    {
		default_frames[i].d->event_windows[j][k].window = None;
	    }
	}

	for (j = 0; j < BUTTON_NUM; ++j)
	{
	    default_frames[i].d->button_windows[j].window = None;
	    default_frames[i].d->button_states[j] = 0;
	}

        if (default_frames[i].d->surface)
        {
            gint	    nQuad;
            unsigned int   frame_type = populate_frame_type (default_frames[i].d);
            unsigned int   frame_state = populate_frame_state (default_frames[i].d);
            unsigned int   frame_actions = populate_frame_actions (default_frames[i].d);
            decor_quad_t    quads[N_QUADS_MAX];

            nQuad = decor_set_lSrStSbS_window_quads (quads, default_frames[i].d->context,
                                                     &default_frames[i].d->border_layout);

            default_frames[i].d->picture = XRenderCreatePicture (xdisplay,
                                                                 cairo_xlib_surface_get_drawable (default_frames[i].d->surface),
                                                                 xformat_rgba, 0, NULL);

            (*default_frames[i].d->draw) (default_frames[i].d);

            decor_quads_to_property (data, i, cairo_xlib_surface_get_drawable (default_frames[i].d->surface),
                                     &extents, &extents,
                                     &extents, &extents, 0, 0, quads, nQuad, frame_type, frame_state, frame_actions);
        }

        gwd_decor_frame_unref (frame);
    }

    XChangeProperty (xdisplay, xroot,
                     activeAtom,
                     XA_INTEGER,
                     32, PropModeAppend, (guchar *) data,
                     PROP_HEADER_SIZE + (WINDOW_TYPE_FRAMES_NUM * 2) * (BASE_PROP_SIZE + QUAD_PROP_SIZE * N_QUADS_MAX));

    free (data);

    gwd_decor_frame_unref (bare_frame);
}
Example #28
0
void wsXDNDMakeAwareness(wsWindow* win) {
    long int xdnd_version = XDND_VERSION;
    XChangeProperty (wsDisplay, win->WindowID, XA_XdndAware, XA_ATOM,
            32, PropModeAppend, (char *)&xdnd_version, 1);
}
Example #29
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;
    if( type == GenericWindow::VoutWindow )
    {
        event_mask =  ExposureMask|KeyPressMask|
                      LeaveWindowMask|FocusChangeMask;
    }
    else
    {
        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 = 4;
        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* pWin = pVoutManager->getVoutMainWindow();
        Window wnd = (Window) pWin->getOSHandle();
        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 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 );

}
Example #30
0
void StartupId::start_startupid( const QString& icon_P )
    {

    const QColor startup_colors[ StartupId::NUM_BLINKING_PIXMAPS ]
    = { Qt::black, Qt::darkGray, Qt::lightGray, Qt::white, Qt::white };


    QPixmap icon_pixmap = KIconLoader::global()->loadIcon( icon_P, KIconLoader::Small, 0,
        KIconLoader::DefaultState, QStringList(), 0, true ); // return null pixmap if not found
    if( icon_pixmap.isNull())
        icon_pixmap = SmallIcon( QLatin1String( "system-run" ) );
    if( startup_window == None )
        {
        XSetWindowAttributes attrs;
        attrs.override_redirect = True;
        attrs.save_under = True; // useful saveunder if possible to avoid redrawing
        attrs.colormap = QX11Info::appColormap();
        attrs.background_pixel = WhitePixel( QX11Info::display(), QX11Info::appScreen());
        attrs.border_pixel = BlackPixel( QX11Info::display(), QX11Info::appScreen());
        startup_window = XCreateWindow( QX11Info::display(), DefaultRootWindow( QX11Info::display()),
            0, 0, 1, 1, 0, QX11Info::appDepth(), InputOutput, static_cast< Visual* >( QX11Info::appVisual()),
            CWOverrideRedirect | CWSaveUnder | CWColormap | CWBackPixel | CWBorderPixel, &attrs );
        XClassHint class_hint;
        QByteArray cls = QApplication::applicationName().toLatin1();
        class_hint.res_name = cls.data();
        class_hint.res_class = const_cast< char* >( QX11Info::appClass());
        XSetWMProperties( QX11Info::display(), startup_window, NULL, NULL, NULL, 0, NULL, NULL, &class_hint );
        XChangeProperty( QX11Info::display(), winId(),
            XInternAtom( QX11Info::display(), "WM_WINDOW_ROLE", False ), XA_STRING, 8, PropModeReplace,
            (unsigned char *)"startupfeedback", strlen( "startupfeedback" ));
        }
    XResizeWindow( QX11Info::display(), startup_window, icon_pixmap.width(), icon_pixmap.height());
    if( blinking )
        { // no mask
        XShapeCombineMask( QX11Info::display(), startup_window, ShapeBounding, 0, 0, None, ShapeSet );
        int window_w = icon_pixmap.width();
        int window_h = icon_pixmap.height();
        for( int i = 0;
             i < NUM_BLINKING_PIXMAPS;
             ++i )
            {
            pixmaps[ i ] = QPixmap( window_w, window_h );
            pixmaps[ i ].fill( startup_colors[ i ] );
            QPainter p( &pixmaps[ i ] );
            p.drawPixmap( 0, 0, icon_pixmap );
            p.end();
            }
        color_index = 0;
        }
    else if( bouncing )
        {
        XResizeWindow( QX11Info::display(), startup_window, 20, 20 );
        pixmaps[ 0 ] = make24bpp( scalePixmap( icon_pixmap, 16, 16 ));
        pixmaps[ 1 ] = make24bpp( scalePixmap( icon_pixmap, 14, 18 ));
        pixmaps[ 2 ] = make24bpp( scalePixmap( icon_pixmap, 12, 20 ));
        pixmaps[ 3 ] = make24bpp( scalePixmap( icon_pixmap, 18, 14 ));
        pixmaps[ 4 ] = make24bpp( scalePixmap( icon_pixmap, 20, 12 ));
        frame = 0;
        }
    else
        {
        icon_pixmap = make24bpp( icon_pixmap );
        if( !icon_pixmap.mask().isNull() ) // set mask
            XShapeCombineMask( QX11Info::display(), startup_window, ShapeBounding, 0, 0,
                icon_pixmap.mask().handle(), ShapeSet );
        else // clear mask
            XShapeCombineMask( QX11Info::display(), startup_window, ShapeBounding, 0, 0, None, ShapeSet );
        XSetWindowBackgroundPixmap( QX11Info::display(), startup_window, icon_pixmap.handle());
        XClearWindow( QX11Info::display(), startup_window );
        }
    update_startupid();
    }