Ejemplo n.º 1
0
int
puglCreateWindow(PuglView* view, const char* title)
{
	PuglInternals* const impl = view->impl;

	impl->display = XOpenDisplay(NULL);
	impl->screen  = DefaultScreen(impl->display);

	XVisualInfo* const vi = getVisual(view);
	if (!vi) {
		XCloseDisplay(impl->display);
		impl->display = NULL;
		return 1;
	}

#ifdef PUGL_HAVE_GL
	int glxMajor, glxMinor;
	glXQueryVersion(impl->display, &glxMajor, &glxMinor);
	PUGL_LOGF("GLX Version %d.%d\n", glxMajor, glxMinor);
#endif

	Window xParent = view->parent
		? (Window)view->parent
		: RootWindow(impl->display, impl->screen);

	Colormap cmap = XCreateColormap(
		impl->display, xParent, vi->visual, AllocNone);

	XSetWindowAttributes attr;
	memset(&attr, 0, sizeof(XSetWindowAttributes));
	attr.background_pixel = BlackPixel(impl->display, impl->screen);
	attr.border_pixel     = BlackPixel(impl->display, impl->screen);
	attr.colormap         = cmap;
	attr.event_mask       = (ExposureMask | StructureNotifyMask |
	                         EnterWindowMask | LeaveWindowMask |
	                         KeyPressMask | KeyReleaseMask |
	                         ButtonPressMask | ButtonReleaseMask |
	                         PointerMotionMask | FocusChangeMask);

	impl->win = XCreateWindow(
		impl->display, xParent,
		0, 0, view->width, view->height, 0, vi->depth, InputOutput, vi->visual,
		CWBackPixel | CWBorderPixel | CWColormap | CWEventMask, &attr);

	if (!createContext(view, vi)) {
		XDestroyWindow(impl->display, impl->win);
		impl->win = 0;

		XCloseDisplay(impl->display);
		impl->display = NULL;

		return 1;
	}

	XSizeHints sizeHints;
	memset(&sizeHints, 0, sizeof(sizeHints));
	if (!view->resizable) {
		sizeHints.flags      = PMinSize|PMaxSize;
		sizeHints.min_width  = view->width;
		sizeHints.min_height = view->height;
		sizeHints.max_width  = view->width;
		sizeHints.max_height = view->height;
		XSetNormalHints(impl->display, impl->win, &sizeHints);
	} else if (view->min_width > 0 && view->min_height > 0) {
		sizeHints.flags      = PMinSize;
		sizeHints.min_width  = view->min_width;
		sizeHints.min_height = view->min_height;
		XSetNormalHints(impl->display, impl->win, &sizeHints);
	}

	if (title) {
		XStoreName(impl->display, impl->win, title);
	}

	if (!view->parent) {
		Atom wmDelete = XInternAtom(impl->display, "WM_DELETE_WINDOW", True);
		XSetWMProtocols(impl->display, impl->win, &wmDelete, 1);
	}

	if (glXIsDirect(impl->display, impl->ctx)) {
		PUGL_LOG("DRI enabled (to disable, set LIBGL_ALWAYS_INDIRECT=1\n");
	} else {
		PUGL_LOG("No DRI available\n");
	}

	XFree(vi);

	return PUGL_SUCCESS;
}
Ejemplo n.º 2
0
int main(void)
{
	Display *display;
	Window window;      //initialization for a window
	int screen;         //which screen

	/* open connection with the server */
	display = XOpenDisplay(NULL);
	if(display == NULL) {
		fprintf(stderr, "cannot open display\n");
		return 0;
	}

	screen = DefaultScreen(display);

	/* set window size */
	int width = 400;
	int height = 400;

	/* set window position */
	int x = 0;
	int y = 0;

	/* border width in pixels */
	int border_width = 0;

	/* create window */
	window = XCreateSimpleWindow(display, RootWindow(display, screen), x, y, width, height, border_width,
					BlackPixel(display, screen), WhitePixel(display, screen));

	/* create graph */
	GC gc;
	XGCValues values;
	long valuemask = 0;

	gc = XCreateGC(display, window, valuemask, &values);
	//XSetBackground (display, gc, WhitePixel (display, screen));
	XSetForeground (display, gc, BlackPixel (display, screen));
	XSetBackground(display, gc, 0X0000FF00);
	XSetLineAttributes (display, gc, 1, LineSolid, CapRound, JoinRound);

	/* map(show) the window */
	XMapWindow(display, window);
	XSync(display, 0);

	struct timespec timeStart, timeEnd;
	clock_gettime(CLOCK_REALTIME, &timeStart);
	/* draw points */
	int* repeatsBuffer;
	Compl z, c;
	int repeats;
	double temp, lengthsq;
	int i, j;
	repeatsBuffer  = (int*)malloc(sizeof(int) * width * height);

	#pragma omp parallel for num_threads(60) private(i,j,repeats,lengthsq,temp,z,c) schedule(static,10)
	for(i=0; i<width; i++) {
		for(j=0; j<height; j++) {
			z.real = 0.0;
			z.imag = 0.0;
			c.real = -2.0 + (double)i * (4.0/(double)width);
			c.imag = -2.0 + (double)j * (4.0/(double)height);
			repeats = 0;
			lengthsq = 0.0;

			while(repeats < 100000 && lengthsq < 4.0) { /* Theorem : If c belongs to M, then |Zn| <= 2. So Zn^2 <= 4 */
				temp = z.real*z.real - z.imag*z.imag + c.real;
				z.imag = 2*z.real*z.imag + c.imag;
				z.real = temp;
				lengthsq = z.real*z.real + z.imag*z.imag;
				repeats++;
			}
			repeatsBuffer[i*width+j]=repeats;
		}
	}

	clock_gettime(CLOCK_REALTIME, &timeEnd);

	printf("Time Usage: %lf s\n", (double)(timeEnd.tv_sec - timeStart.tv_sec) + (double)(timeEnd.tv_nsec - timeStart.tv_nsec)/1e9);
	fflush(stdout);
	for(i = 0; i < width * height; i++){
		XSetForeground (display, gc,  1024 * 1024 * (repeatsBuffer[i] % 256));
		XDrawPoint (display, window, gc, i/width, i%width);
	}
	XFlush(display);
	free(repeatsBuffer);

	sleep(2);
	return 0;
}
Ejemplo n.º 3
0
int main(int argc, char** argv)
{
    Display* dpy = XOpenDisplay(NULL);
    if (dpy == NULL)
    {
        fprintf(stderr, "Cannot open display\n");
        exit(1);
    }

    int s = DefaultScreen(dpy);
    Window win = XCreateSimpleWindow(dpy, RootWindow(dpy, s), 10, 10, 660, 200, 1,
                                     BlackPixel(dpy, s), WhitePixel(dpy, s));
    XSelectInput(dpy, win, ExposureMask | KeyPressMask);
    XMapWindow(dpy, win);

#if defined(__APPLE_CC__)
    XStoreName(dpy, win, "Geeks3D.com - X11 window under Mac OS X (Lion)");
#else
    XStoreName(dpy, win, "Geeks3D.com - X11 window under Linux (Mint 10)");
#endif

    Atom WM_DELETE_WINDOW = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
    XSetWMProtocols(dpy, win, &WM_DELETE_WINDOW, 1);

    bool uname_ok = false;
    struct utsname sname;
    int ret = uname(&sname);
    if (ret != -1)
    {
        uname_ok = true;
    }

    XEvent e;
    while (1)
    {
        XNextEvent(dpy, &e);
        if (e.type == Expose)
        {
            int y_offset = 20;

#if defined(__APPLE_CC__)
            const char* s1 = "X11 test app under Mac OS X Lion";
#else
            const char* s1 = "X11 test app under Linux";
#endif

            const char* s2 = "(C)2012 Geeks3D.com";
            XDrawString(dpy, win, DefaultGC(dpy, s), 10, y_offset, s1, strlen(s1));
            y_offset += 20;
            XDrawString(dpy, win, DefaultGC(dpy, s), 10, y_offset, s2, strlen(s2));
            y_offset += 20;

            if (uname_ok)
            {
                char buf[256] = {0};

                sprintf(buf, "System information:");
                XDrawString(dpy, win, DefaultGC(dpy, s), 10, y_offset, buf, strlen(buf));
                y_offset += 15;

                sprintf(buf, "- System: %s", sname.sysname);
                XDrawString(dpy, win, DefaultGC(dpy, s), 10, y_offset, buf, strlen(buf));
                y_offset += 15;

                sprintf(buf, "- Release: %s", sname.release);
                XDrawString(dpy, win, DefaultGC(dpy, s), 10, y_offset, buf, strlen(buf));
                y_offset += 15;

                sprintf(buf, "- Version: %s", sname.version);
                XDrawString(dpy, win, DefaultGC(dpy, s), 10, y_offset, buf, strlen(buf));
                y_offset += 15;

                sprintf(buf, "- Machine: %s", sname.machine);
                XDrawString(dpy, win, DefaultGC(dpy, s), 10, y_offset, buf, strlen(buf));
                y_offset += 20;
            }


            XWindowAttributes  wa;
            XGetWindowAttributes(dpy, win, &wa);
            int width = wa.width;
            int height = wa.height;
            char buf[128]= {0};
            sprintf(buf, "Current window size: %dx%d", width, height);
            XDrawString(dpy, win, DefaultGC(dpy, s), 10, y_offset, buf, strlen(buf));
            y_offset += 20;
        }

        if (e.type == KeyPress)
        {
            char buf[128] = {0};
            KeySym keysym;
            int len = XLookupString(&e.xkey, buf, sizeof buf, &keysym, NULL);
            if (keysym == XK_Escape)
                break;
        }

        if ((e.type == ClientMessage) &&
                (static_cast<unsigned int>(e.xclient.data.l[0]) == WM_DELETE_WINDOW))
        {
            break;
        }
    }

    XDestroyWindow(dpy, win);
    XCloseDisplay(dpy);
    return 0;
}
Ejemplo n.º 4
0
void *
winClipboardProc(void *pvNotUsed)
{
    Atom atomClipboard, atomClipboardManager;
    int iReturn;
    HWND hwnd = NULL;
    int iConnectionNumber = 0;

#ifdef HAS_DEVWINDOWS
    int fdMessageQueue = 0;
#else
    struct timeval tvTimeout;
#endif
    fd_set fdsRead;
    int iMaxDescriptor;
    Display *pDisplay = NULL;
    Window iWindow = None;
    int iRetries;
    Bool fUseUnicode;
    char szDisplay[512];
    int iSelectError;

    ErrorF("winClipboardProc - Hello\n");
    ++clipboardRestarts;

    /* Do we have Unicode support? */
    g_fUnicodeSupport = winClipboardDetectUnicodeSupport();

    /* Do we use Unicode clipboard? */
    fUseUnicode = g_fUnicodeClipboard && g_fUnicodeSupport;

    /* Save the Unicode support flag in a global */
    g_fUseUnicode = fUseUnicode;

    /* Allow multiple threads to access Xlib */
    if (XInitThreads() == 0) {
        ErrorF("winClipboardProc - XInitThreads failed.\n");
        goto winClipboardProc_Exit;
    }

    /* See if X supports the current locale */
    if (XSupportsLocale() == False) {
        ErrorF("winClipboardProc - Warning: Locale not supported by X.\n");
    }

    /* Set error handler */
    XSetErrorHandler(winClipboardErrorHandler);
    g_winClipboardProcThread = pthread_self();
    g_winClipboardOldIOErrorHandler =
        XSetIOErrorHandler(winClipboardIOErrorHandler);

    /* Set jump point for Error exits */
    iReturn = setjmp(g_jmpEntry);

    /* Check if we should continue operations */
    if (iReturn != WIN_JMP_ERROR_IO && iReturn != WIN_JMP_OKAY) {
        /* setjmp returned an unknown value, exit */
        ErrorF("winClipboardProc - setjmp returned: %d exiting\n", iReturn);
        goto winClipboardProc_Exit;
    }
    else if (iReturn == WIN_JMP_ERROR_IO) {
        /* TODO: Cleanup the Win32 window and free any allocated memory */
        ErrorF("winClipboardProc - setjmp returned for IO Error Handler.\n");
        pthread_exit(NULL);
    }

    /* Use our generated cookie for authentication */
    winSetAuthorization();

    /* Initialize retry count */
    iRetries = 0;

    /* Setup the display connection string x */
    /*
     * NOTE: Always connect to screen 0 since we require that screen
     * numbers start at 0 and increase without gaps.  We only need
     * to connect to one screen on the display to get events
     * for all screens on the display.  That is why there is only
     * one clipboard client thread.
     */
    snprintf(szDisplay, 512, "127.0.0.1:%s.0", display);

    /* Print the display connection string */
    ErrorF("winClipboardProc - DISPLAY=%s\n", szDisplay);

    /* Open the X display */
    do {
        pDisplay = XOpenDisplay(szDisplay);
        if (pDisplay == NULL) {
            ErrorF("winClipboardProc - Could not open display, "
                   "try: %d, sleeping: %d\n", iRetries + 1, WIN_CONNECT_DELAY);
            ++iRetries;
            sleep(WIN_CONNECT_DELAY);
            continue;
        }
        else
            break;
    }
    while (pDisplay == NULL && iRetries < WIN_CONNECT_RETRIES);

    /* Make sure that the display opened */
    if (pDisplay == NULL) {
        ErrorF("winClipboardProc - Failed opening the display, giving up\n");
        goto winClipboardProc_Done;
    }

    /* Save the display in the screen privates */
    g_pClipboardDisplay = pDisplay;

    ErrorF("winClipboardProc - XOpenDisplay () returned and "
           "successfully opened the display.\n");

    /* Get our connection number */
    iConnectionNumber = ConnectionNumber(pDisplay);

#ifdef HAS_DEVWINDOWS
    /* Open a file descriptor for the windows message queue */
    fdMessageQueue = open(WIN_MSG_QUEUE_FNAME, O_RDONLY);
    if (fdMessageQueue == -1) {
        ErrorF("winClipboardProc - Failed opening %s\n", WIN_MSG_QUEUE_FNAME);
        goto winClipboardProc_Done;
    }

    /* Find max of our file descriptors */
    iMaxDescriptor = max(fdMessageQueue, iConnectionNumber) + 1;
#else
    iMaxDescriptor = iConnectionNumber + 1;
#endif

    /* Create atoms */
    atomClipboard = XInternAtom(pDisplay, "CLIPBOARD", False);
    atomClipboardManager = XInternAtom(pDisplay, "CLIPBOARD_MANAGER", False);

    /* Create a messaging window */
    iWindow = XCreateSimpleWindow(pDisplay,
                                  DefaultRootWindow(pDisplay),
                                  1, 1,
                                  500, 500,
                                  0,
                                  BlackPixel(pDisplay, 0),
                                  BlackPixel(pDisplay, 0));
    if (iWindow == 0) {
        ErrorF("winClipboardProc - Could not create an X window.\n");
        goto winClipboardProc_Done;
    }

    XStoreName(pDisplay, iWindow, "xwinclip");

    /* Select event types to watch */
    if (XSelectInput(pDisplay, iWindow, PropertyChangeMask) == BadWindow)
        ErrorF("winClipboardProc - XSelectInput generated BadWindow "
               "on messaging window\n");

    /* Save the window in the screen privates */
    g_iClipboardWindow = iWindow;

    /* Create Windows messaging window */
    hwnd = winClipboardCreateMessagingWindow();

    /* Save copy of HWND in screen privates */
    g_hwndClipboard = hwnd;

    /* Assert ownership of selections if Win32 clipboard is owned */
    if (NULL != GetClipboardOwner()) {
        /* PRIMARY */
        iReturn = XSetSelectionOwner(pDisplay, XA_PRIMARY,
                                     iWindow, CurrentTime);
        if (iReturn == BadAtom || iReturn == BadWindow ||
            XGetSelectionOwner(pDisplay, XA_PRIMARY) != iWindow) {
            ErrorF("winClipboardProc - Could not set PRIMARY owner\n");
            goto winClipboardProc_Done;
        }

        /* CLIPBOARD */
        iReturn = XSetSelectionOwner(pDisplay, atomClipboard,
                                     iWindow, CurrentTime);
        if (iReturn == BadAtom || iReturn == BadWindow ||
            XGetSelectionOwner(pDisplay, atomClipboard) != iWindow) {
            ErrorF("winClipboardProc - Could not set CLIPBOARD owner\n");
            goto winClipboardProc_Done;
        }
    }

    /* Pre-flush X events */
    /* 
     * NOTE: Apparently you'll freeze if you don't do this,
     *       because there may be events in local data structures
     *       already.
     */
    winClipboardFlushXEvents(hwnd, iWindow, pDisplay, fUseUnicode);

    /* Pre-flush Windows messages */
    if (!winClipboardFlushWindowsMessageQueue(hwnd))
        return 0;

    /* Signal that the clipboard client has started */
    g_fClipboardStarted = TRUE;

    /* Loop for X events */
    while (1) {
        /* Setup the file descriptor set */
        /*
         * NOTE: You have to do this before every call to select
         *       because select modifies the mask to indicate
         *       which descriptors are ready.
         */
        FD_ZERO(&fdsRead);
        FD_SET(iConnectionNumber, &fdsRead);
#ifdef HAS_DEVWINDOWS
        FD_SET(fdMessageQueue, &fdsRead);
#else
        tvTimeout.tv_sec = 0;
        tvTimeout.tv_usec = 100;
#endif

        /* Wait for a Windows event or an X event */
        iReturn = select(iMaxDescriptor,        /* Highest fds number */
                         &fdsRead,      /* Read mask */
                         NULL,  /* No write mask */
                         NULL,  /* No exception mask */
#ifdef HAS_DEVWINDOWS
                         NULL   /* No timeout */
#else
                         &tvTimeout     /* Set timeout */
#endif
            );

#ifndef HAS_WINSOCK
        iSelectError = errno;
#else
        iSelectError = WSAGetLastError();
#endif

        if (iReturn < 0) {
#ifndef HAS_WINSOCK
            if (iSelectError == EINTR)
#else
            if (iSelectError == WSAEINTR)
#endif
                continue;

            ErrorF("winClipboardProc - Call to select () failed: %d.  "
                   "Bailing.\n", iReturn);
            break;
        }

        /* Branch on which descriptor became active */
        if (FD_ISSET(iConnectionNumber, &fdsRead)) {
            /* Process X events */
            /* Exit when we see that server is shutting down */
            iReturn = winClipboardFlushXEvents(hwnd,
                                               iWindow, pDisplay, fUseUnicode);
            if (WIN_XEVENTS_SHUTDOWN == iReturn) {
                ErrorF("winClipboardProc - winClipboardFlushXEvents "
                       "trapped shutdown event, exiting main loop.\n");
                break;
            }
        }

#ifdef HAS_DEVWINDOWS
        /* Check for Windows event ready */
        if (FD_ISSET(fdMessageQueue, &fdsRead))
#else
        if (1)
#endif
        {
            /* Process Windows messages */
            if (!winClipboardFlushWindowsMessageQueue(hwnd)) {
                ErrorF("winClipboardProc - "
                       "winClipboardFlushWindowsMessageQueue trapped "
                       "WM_QUIT message, exiting main loop.\n");
                break;
            }
        }
    }

 winClipboardProc_Exit:
    /* disable the clipboard, which means the thread will die */
    g_fClipboard = FALSE;

 winClipboardProc_Done:
    /* Close our Windows window */
    if (g_hwndClipboard) {
        /* Destroy the Window window (hwnd) */
        winDebug("winClipboardProc - Destroy Windows window\n");
        PostMessage(g_hwndClipboard, WM_DESTROY, 0, 0);
        winClipboardFlushWindowsMessageQueue(g_hwndClipboard);
    }

    /* Close our X window */
    if (pDisplay && iWindow) {
        iReturn = XDestroyWindow(pDisplay, iWindow);
        if (iReturn == BadWindow)
            ErrorF("winClipboardProc - XDestroyWindow returned BadWindow.\n");
        else
            ErrorF("winClipboardProc - XDestroyWindow succeeded.\n");
    }

#ifdef HAS_DEVWINDOWS
    /* Close our Win32 message handle */
    if (fdMessageQueue)
        close(fdMessageQueue);
#endif

#if 0
    /*
     * FIXME: XCloseDisplay hangs if we call it, as of 2004/03/26.  The
     * XSync and XSelectInput calls did not help.
     */

    /* Discard any remaining events */
    XSync(pDisplay, TRUE);

    /* Select event types to watch */
    XSelectInput(pDisplay, DefaultRootWindow(pDisplay), None);

    /* Close our X display */
    if (pDisplay) {
        XCloseDisplay(pDisplay);
    }
#endif

    /* global clipboard variable reset */
    g_fClipboardLaunched = FALSE;
    g_fClipboardStarted = FALSE;
    g_iClipboardWindow = None;
    g_pClipboardDisplay = NULL;
    g_hwndClipboard = NULL;

    /* checking if we need to restart */
    if (clipboardRestarts >= WIN_CLIPBOARD_RETRIES) {
        /* terminates clipboard thread but the main server still lives */
        ErrorF
            ("winClipboardProc - the clipboard thread has restarted %d times and seems to be unstable, disabling clipboard integration\n",
             clipboardRestarts);
        g_fClipboard = FALSE;
        return;
    }

    if (g_fClipboard) {
        sleep(WIN_CLIPBOARD_DELAY);
        ErrorF("winClipboardProc - trying to restart clipboard thread \n");
        /* Create the clipboard client thread */
        if (!winInitClipboard()) {
            ErrorF("winClipboardProc - winClipboardInit failed.\n");
            return;
        }

        winDebug("winClipboardProc - winInitClipboard returned.\n");
        /* Flag that clipboard client has been launched */
        g_fClipboardLaunched = TRUE;
    }
    else {
        ErrorF("winClipboardProc - Clipboard disabled  - Exit from server \n");
        /* clipboard thread has exited, stop server as well */
        kill(getpid(), SIGTERM);
    }

    return NULL;
}
Ejemplo n.º 5
0
void windrawstring(pdfapp_t *app, int x, int y, char *s)
{
	XSetForeground(xdpy, xgc, BlackPixel(xdpy, DefaultScreen(xdpy)));
	XDrawString(xdpy, xwin, xgc, x, y, s, strlen(s));
}
Ejemplo n.º 6
0
/*
** GLW_SetMode
*/
int GLW_SetMode( const char *drivername, int mode, qboolean fullscreen )
{
  int attrib[] = {
    GLX_RGBA,         // 0
    GLX_RED_SIZE, 4,      // 1, 2
    GLX_GREEN_SIZE, 4,      // 3, 4
    GLX_BLUE_SIZE, 4,     // 5, 6
    GLX_DOUBLEBUFFER,     // 7
    GLX_DEPTH_SIZE, 1,      // 8, 9
    GLX_STENCIL_SIZE, 1,    // 10, 11
    None
  };
  // these match in the array
#define ATTR_RED_IDX 2
#define ATTR_GREEN_IDX 4
#define ATTR_BLUE_IDX 6
#define ATTR_DEPTH_IDX 9
#define ATTR_STENCIL_IDX 11
  Window root;
  XVisualInfo *visinfo;
  XSetWindowAttributes attr;
  XSizeHints sizehints;
  unsigned long mask;
  int colorbits, depthbits, stencilbits;
  int tcolorbits, tdepthbits, tstencilbits;
  int dga_MajorVersion, dga_MinorVersion;
  int actualWidth, actualHeight;
  int i;
  const char*   glstring; // bk001130 - from cvs1.17 (mkv)

  CL_RefPrintf( PRINT_ALL, "Initializing OpenGL display\n");

  CL_RefPrintf (PRINT_ALL, "...setting mode %d:", mode );

  if ( !R_GetModeInfo( &glConfig.vidWidth, &glConfig.vidHeight, &glConfig.windowAspect, mode ) )
  {
    CL_RefPrintf( PRINT_ALL, " invalid mode\n" );
    return RSERR_INVALID_MODE;
  }
  CL_RefPrintf( PRINT_ALL, " %d %d\n", glConfig.vidWidth, glConfig.vidHeight);

  if (!(dpy = XOpenDisplay(NULL)))
  {
    fprintf(stderr, "Error couldn't open the X display\n");
    return RSERR_INVALID_MODE;
  }
  
  scrnum = DefaultScreen(dpy);
  root = RootWindow(dpy, scrnum);

  actualWidth = glConfig.vidWidth;
  actualHeight = glConfig.vidHeight;

  // Get video mode list
  if (!XF86VidModeQueryVersion(dpy, &vidmode_MajorVersion, &vidmode_MinorVersion))
  {
    vidmode_ext = qfalse;
  } else
  {
    CL_RefPrintf(PRINT_ALL, "Using XFree86-VidModeExtension Version %d.%d\n",
              vidmode_MajorVersion, vidmode_MinorVersion);
    vidmode_ext = qtrue;
  }

  // Check for DGA	
  dga_MajorVersion = 0, dga_MinorVersion = 0;
  if (in_dgamouse->value)
  {
    if (!XF86DGAQueryVersion(dpy, &dga_MajorVersion, &dga_MinorVersion))
    {
      // unable to query, probalby not supported
      CL_RefPrintf( PRINT_ALL, "Failed to detect XF86DGA Mouse\n" );
      Cvar_Set( "in_dgamouse", "0" );
    } else
    {
      CL_RefPrintf( PRINT_ALL, "XF86DGA Mouse (Version %d.%d) initialized\n",
                 dga_MajorVersion, dga_MinorVersion);
    }
  }

  if (vidmode_ext)
  {
    int best_fit, best_dist, dist, x, y;

    XF86VidModeGetAllModeLines(dpy, scrnum, &num_vidmodes, &vidmodes);

    // Are we going fullscreen?  If so, let's change video mode
    if (fullscreen)
    {
      best_dist = 9999999;
      best_fit = -1;

      for (i = 0; i < num_vidmodes; i++)
      {
        if (glConfig.vidWidth > vidmodes[i]->hdisplay ||
            glConfig.vidHeight > vidmodes[i]->vdisplay)
          continue;

        x = glConfig.vidWidth - vidmodes[i]->hdisplay;
        y = glConfig.vidHeight - vidmodes[i]->vdisplay;
        dist = (x * x) + (y * y);
        if (dist < best_dist)
        {
          best_dist = dist;
          best_fit = i;
        }
      }

      if (best_fit != -1)
      {
        actualWidth = vidmodes[best_fit]->hdisplay;
        actualHeight = vidmodes[best_fit]->vdisplay;

        // change to the mode
        XF86VidModeSwitchToMode(dpy, scrnum, vidmodes[best_fit]);
        vidmode_active = qtrue;

        // Move the viewport to top left
        XF86VidModeSetViewPort(dpy, scrnum, 0, 0);

        CL_RefPrintf(PRINT_ALL, "XFree86-VidModeExtension Activated at %dx%d\n",
                  actualWidth, actualHeight);

      } else
      {
        fullscreen = 0;
        CL_RefPrintf(PRINT_ALL, "XFree86-VidModeExtension: No acceptable modes found\n");
      }
    } else
    {
      CL_RefPrintf(PRINT_ALL, "XFree86-VidModeExtension:  Ignored on non-fullscreen/Voodoo\n");
    }
  }


  if (!r_colorbits->value)
    colorbits = 24;
  else
    colorbits = r_colorbits->value;

  if ( !Q_stricmp( r_glDriver->string, _3DFX_DRIVER_NAME ) )
    colorbits = 16;

  if (!r_depthbits->value)
    depthbits = 24;
  else
    depthbits = r_depthbits->value;
  stencilbits = r_stencilbits->value;

  for (i = 0; i < 16; i++)
  {
    // 0 - default
    // 1 - minus colorbits
    // 2 - minus depthbits
    // 3 - minus stencil
    if ((i % 4) == 0 && i)
    {
      // one pass, reduce
      switch (i / 4)
      {
      case 2 :
        if (colorbits == 24)
          colorbits = 16;
        break;
      case 1 :
        if (depthbits == 24)
          depthbits = 16;
        else if (depthbits == 16)
          depthbits = 8;
      case 3 :
        if (stencilbits == 24)
          stencilbits = 16;
        else if (stencilbits == 16)
          stencilbits = 8;
      }
    }

    tcolorbits = colorbits;
    tdepthbits = depthbits;
    tstencilbits = stencilbits;

    if ((i % 4) == 3)
    { // reduce colorbits
      if (tcolorbits == 24)
        tcolorbits = 16;
    }

    if ((i % 4) == 2)
    { // reduce depthbits
      if (tdepthbits == 24)
        tdepthbits = 16;
      else if (tdepthbits == 16)
        tdepthbits = 8;
    }

    if ((i % 4) == 1)
    { // reduce stencilbits
      if (tstencilbits == 24)
        tstencilbits = 16;
      else if (tstencilbits == 16)
        tstencilbits = 8;
      else
        tstencilbits = 0;
    }

    if (tcolorbits == 24)
    {
      attrib[ATTR_RED_IDX] = 8;
      attrib[ATTR_GREEN_IDX] = 8;
      attrib[ATTR_BLUE_IDX] = 8;
    } else
    {
      // must be 16 bit
      attrib[ATTR_RED_IDX] = 4;
      attrib[ATTR_GREEN_IDX] = 4;
      attrib[ATTR_BLUE_IDX] = 4;
    }

    attrib[ATTR_DEPTH_IDX] = tdepthbits; // default to 24 depth
    attrib[ATTR_STENCIL_IDX] = tstencilbits;

    visinfo = qglXChooseVisual(dpy, scrnum, attrib);
    if (!visinfo)
    {
      continue;
    }

    CL_RefPrintf( PRINT_ALL, "Using %d/%d/%d Color bits, %d depth, %d stencil display.\n", 
               attrib[ATTR_RED_IDX], attrib[ATTR_GREEN_IDX], attrib[ATTR_BLUE_IDX],
               attrib[ATTR_DEPTH_IDX], attrib[ATTR_STENCIL_IDX]);

    glConfig.colorBits = tcolorbits;
    glConfig.depthBits = tdepthbits;
    glConfig.stencilBits = tstencilbits;
    break;
  }

  if (!visinfo)
  {
    CL_RefPrintf( PRINT_ALL, "Couldn't get a visual\n" );
    return RSERR_INVALID_MODE;
  }

  /* window attributes */
  attr.background_pixel = BlackPixel(dpy, scrnum);
  attr.border_pixel = 0;
  attr.colormap = XCreateColormap(dpy, root, visinfo->visual, AllocNone);
  attr.event_mask = X_MASK;
  if (vidmode_active)
  {
    mask = CWBackPixel | CWColormap | CWSaveUnder | CWBackingStore | 
           CWEventMask | CWOverrideRedirect;
    attr.override_redirect = True;
    attr.backing_store = NotUseful;
    attr.save_under = False;
  } else
    mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;

  win = XCreateWindow(dpy, root, 0, 0, 
                      actualWidth, actualHeight, 
                      0, visinfo->depth, InputOutput,
                      visinfo->visual, mask, &attr);

  XStoreName( dpy, win, WINDOW_CLASS_NAME );

  /* GH: Don't let the window be resized */
  sizehints.flags = PMinSize | PMaxSize;
  sizehints.min_width = sizehints.max_width = actualWidth;
  sizehints.min_height = sizehints.max_height = actualHeight;

  XSetWMNormalHints( dpy, win, &sizehints );

  XMapWindow( dpy, win );

  if (vidmode_active)
    XMoveWindow(dpy, win, 0, 0);

  XFlush(dpy);
  XSync(dpy,False); // bk001130 - from cvs1.17 (mkv)
  ctx = qglXCreateContext(dpy, visinfo, NULL, True);
  XSync(dpy,False); // bk001130 - from cvs1.17 (mkv)

  /* GH: Free the visinfo after we're done with it */
  XFree( visinfo );

  qglXMakeCurrent(dpy, win, ctx);

  // bk001130 - from cvs1.17 (mkv)
  glstring = (char *)qglGetString (GL_RENDERER);
  CL_RefPrintf( PRINT_ALL, "GL_RENDERER: %s\n", glstring );

  // bk010122 - new software token (Indirect)
  if ( !Q_stricmp( glstring, "Mesa X11")
       || !Q_stricmp( glstring, "Mesa GLX Indirect") )
  {
    if ( !r_allowSoftwareGL->integer )
    {
      CL_RefPrintf( PRINT_ALL, "\n\n***********************************************************\n" );
      CL_RefPrintf( PRINT_ALL, " You are using software Mesa (no hardware acceleration)!   \n" );
      CL_RefPrintf( PRINT_ALL, " Driver DLL used: %s\n", drivername ); 
      CL_RefPrintf( PRINT_ALL, " If this is intentional, add\n" );
      CL_RefPrintf( PRINT_ALL, "       \"+set r_allowSoftwareGL 1\"\n" );
      CL_RefPrintf( PRINT_ALL, " to the command line when starting the game.\n" );
      CL_RefPrintf( PRINT_ALL, "***********************************************************\n");
      GLimp_Shutdown( );
      return RSERR_INVALID_MODE;
    } else
    {
      CL_RefPrintf( PRINT_ALL, "...using software Mesa (r_allowSoftwareGL==1).\n" );
    }
  }

  return RSERR_OK;
}
Ejemplo n.º 7
0
// real construction (Init() must have been called before!)
bool wxWindowX11::Create(wxWindow *parent, wxWindowID id,
                      const wxPoint& pos,
                      const wxSize& size,
                      long style,
                      const wxString& name)
{
    wxCHECK_MSG( parent, FALSE, wxT("can't create wxWindow without parent") );

    CreateBase(parent, id, pos, size, style, wxDefaultValidator, name);

    parent->AddChild(this);

    Display *xdisplay = (Display*) wxGlobalDisplay();
    int xscreen = DefaultScreen( xdisplay );
    Visual *xvisual = DefaultVisual( xdisplay, xscreen );
    Colormap cm = DefaultColormap( xdisplay, xscreen );

    m_backgroundColour = wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE);
    m_backgroundColour.CalcPixel( (WXColormap) cm );

    m_foregroundColour = *wxBLACK;
    m_foregroundColour.CalcPixel( (WXColormap) cm );

    Window xparent = (Window) parent->GetClientAreaWindow();

    // Add window's own scrollbars to main window, not to client window
    if (parent->GetInsertIntoMain())
    {
        // wxLogDebug( "Inserted into main: %s", GetName().c_str() );
        xparent = (Window) parent->GetMainWindow();
    }

    // Size (not including the border) must be nonzero (or a Value error results)!
    // Note: The Xlib manual doesn't mention this restriction of XCreateWindow.
    wxSize size2(size);
    if (size2.x <= 0)
        size2.x = 20;
    if (size2.y <= 0)
        size2.y = 20;

    wxPoint pos2(pos);
    if (pos2.x == -1)
        pos2.x = 0;
    if (pos2.y == -1)
        pos2.y = 0;

#if wxUSE_TWO_WINDOWS
    bool need_two_windows =
        ((( wxSUNKEN_BORDER | wxRAISED_BORDER | wxSIMPLE_BORDER | wxHSCROLL | wxVSCROLL ) & m_windowStyle) != 0);
#else
    bool need_two_windows = FALSE;
#endif

#if wxUSE_NANOX
    long xattributes = 0;
#else
    XSetWindowAttributes xattributes;
    long xattributes_mask = 0;

    xattributes_mask |= CWBackPixel;
    xattributes.background_pixel = m_backgroundColour.GetPixel();

    xattributes_mask |= CWBorderPixel;
    xattributes.border_pixel = BlackPixel( xdisplay, xscreen );

    xattributes_mask |= CWEventMask;
#endif

    if (need_two_windows)
    {
#if wxUSE_NANOX
        long backColor, foreColor;
        backColor = GR_RGB(m_backgroundColour.Red(), m_backgroundColour.Green(), m_backgroundColour.Blue());
        foreColor = GR_RGB(m_foregroundColour.Red(), m_foregroundColour.Green(), m_foregroundColour.Blue());

        Window xwindow = XCreateWindowWithColor( xdisplay, xparent, pos2.x, pos2.y, size2.x, size2.y,
                                    0, 0, InputOutput, xvisual, backColor, foreColor);
        XSelectInput( xdisplay, xwindow,
          GR_EVENT_MASK_CLOSE_REQ | ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
          ButtonMotionMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask |
          KeymapStateMask | FocusChangeMask | ColormapChangeMask | StructureNotifyMask |
                      PropertyChangeMask );

#else
        // Normal X11
        xattributes.event_mask =
            ExposureMask | StructureNotifyMask | ColormapChangeMask;

        Window xwindow = XCreateWindow( xdisplay, xparent, pos2.x, pos2.y, size2.x, size2.y,
            0, DefaultDepth(xdisplay,xscreen), InputOutput, xvisual, xattributes_mask, &xattributes );

#endif

        XSetWindowBackgroundPixmap( xdisplay, xwindow, None );

        m_mainWindow = (WXWindow) xwindow;
        wxAddWindowToTable( xwindow, (wxWindow*) this );

        XMapWindow( xdisplay, xwindow );

#if !wxUSE_NANOX
        xattributes.event_mask =
            ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
            ButtonMotionMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask |
            KeymapStateMask | FocusChangeMask | ColormapChangeMask | StructureNotifyMask |
            PropertyChangeMask | VisibilityChangeMask ;

        if (!HasFlag( wxFULL_REPAINT_ON_RESIZE ))
        {
            xattributes_mask |= CWBitGravity;
            xattributes.bit_gravity = StaticGravity;
        }
#endif

        if (HasFlag( wxSUNKEN_BORDER) || HasFlag( wxRAISED_BORDER))
        {
            pos2.x = 2;
            pos2.y = 2;
            size2.x -= 4;
            size2.y -= 4;
        }
        else if (HasFlag( wxSIMPLE_BORDER ))
        {
            pos2.x = 1;
            pos2.y = 1;
            size2.x -= 2;
            size2.y -= 2;
        }
        else
        {
            pos2.x = 0;
            pos2.y = 0;
        }

        // Make again sure the size is nonzero.
        if (size2.x <= 0)
            size2.x = 1;
        if (size2.y <= 0)
            size2.y = 1;

#if wxUSE_NANOX
        backColor = GR_RGB(m_backgroundColour.Red(), m_backgroundColour.Green(), m_backgroundColour.Blue());
        foreColor = GR_RGB(m_foregroundColour.Red(), m_foregroundColour.Green(), m_foregroundColour.Blue());

        xwindow = XCreateWindowWithColor( xdisplay, xwindow, pos2.x, pos2.y, size2.x, size2.y,
                                    0, 0, InputOutput, xvisual, backColor, foreColor);
        XSelectInput( xdisplay, xwindow,
          GR_EVENT_MASK_CLOSE_REQ | ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
          ButtonMotionMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask |
          KeymapStateMask | FocusChangeMask | ColormapChangeMask | StructureNotifyMask |
                      PropertyChangeMask );

#else
        xwindow = XCreateWindow( xdisplay, xwindow, pos2.x, pos2.y, size2.x, size2.y,
            0, DefaultDepth(xdisplay,xscreen), InputOutput, xvisual, xattributes_mask, &xattributes );
#endif

        XSetWindowBackgroundPixmap( xdisplay, xwindow, None );

        m_clientWindow = (WXWindow) xwindow;
        wxAddClientWindowToTable( xwindow, (wxWindow*) this );

        XMapWindow( xdisplay, xwindow );
    }
    else
    {
        // wxLogDebug( "No two windows needed %s", GetName().c_str() );
#if wxUSE_NANOX
        long backColor, foreColor;
        backColor = GR_RGB(m_backgroundColour.Red(), m_backgroundColour.Green(), m_backgroundColour.Blue());
        foreColor = GR_RGB(m_foregroundColour.Red(), m_foregroundColour.Green(), m_foregroundColour.Blue());

        Window xwindow = XCreateWindowWithColor( xdisplay, xparent, pos2.x, pos2.y, size2.x, size2.y,
                                    0, 0, InputOutput, xvisual, backColor, foreColor);
        XSelectInput( xdisplay, xwindow,
          GR_EVENT_MASK_CLOSE_REQ | ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
          ButtonMotionMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask |
          KeymapStateMask | FocusChangeMask | ColormapChangeMask | StructureNotifyMask |
                      PropertyChangeMask );

#else
        xattributes.event_mask =
            ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
            ButtonMotionMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask |
            KeymapStateMask | FocusChangeMask | ColormapChangeMask | StructureNotifyMask |
            PropertyChangeMask | VisibilityChangeMask ;

        if (!HasFlag( wxFULL_REPAINT_ON_RESIZE ))
        {
            xattributes_mask |= CWBitGravity;
            xattributes.bit_gravity = NorthWestGravity;
        }

        Window xwindow = XCreateWindow( xdisplay, xparent, pos2.x, pos2.y, size2.x, size2.y,
            0, DefaultDepth(xdisplay,xscreen), InputOutput, xvisual, xattributes_mask, &xattributes );
#endif

        XSetWindowBackgroundPixmap( xdisplay, xwindow, None );

        m_mainWindow = (WXWindow) xwindow;
        m_clientWindow = m_mainWindow;
        wxAddWindowToTable( xwindow, (wxWindow*) this );

        XMapWindow( xdisplay, xwindow );
    }

    // Is a subwindow, so map immediately
    m_isShown = TRUE;

    // Without this, the cursor may not be restored properly (e.g. in splitter
    // sample).
    SetCursor(*wxSTANDARD_CURSOR);
    SetFont(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));

    // Don't call this, it can have nasty repercussions for composite controls,
    // for example
    //    SetSize(pos.x, pos.y, size.x, size.y);

    return TRUE;
}
Ejemplo n.º 8
0
int main(int argc, char **argv)
{
  FILE *fp;
  int x_1,y_1,x_2,y_2,x_3,y_3;
  char a;
  int i,j;
  int outside;
  int ButtonPressed = 0;
  int temp_x, temp_y;
  pixel_count = 0;
  for(i=0;i<302;i++)
  {              
    for(j=0;j<302;j++)  
    {          
      cost[i][j] = 9999; 
    } 
  }

  if( (display_ptr = XOpenDisplay(display_name)) == NULL )
    { printf("Could not open display. \n"); exit(-1);}
  printf("Connected to X server  %s\n", XDisplayName(display_name) );
  screen_num = DefaultScreen( display_ptr );
  screen_ptr = DefaultScreenOfDisplay( display_ptr );
  color_map  = XDefaultColormap( display_ptr, screen_num );
  display_width  = DisplayWidth( display_ptr, screen_num );
  display_height = DisplayHeight( display_ptr, screen_num );

  printf("Width %d, Height %d, Screen Number %d\n", 
           display_width, display_height, screen_num);
  border_width = 10;
  win_x = 0; win_y = 0;
  win_width = display_width;
  win_height = display_height; 
  
  win= XCreateSimpleWindow( display_ptr, RootWindow( display_ptr, screen_num),
                            win_x, win_y, win_width, win_height, border_width,
                            BlackPixel(display_ptr, screen_num),
                            WhitePixel(display_ptr, screen_num) );
  size_hints = XAllocSizeHints();
  wm_hints = XAllocWMHints();
  class_hints = XAllocClassHint();
  if( size_hints == NULL || wm_hints == NULL || class_hints == NULL )
    { printf("Error allocating memory for hints. \n"); exit(-1);}

  size_hints -> flags = PPosition | PSize | PMinSize  ;
  size_hints -> min_width = 60;
  size_hints -> min_height = 60;

  XStringListToTextProperty( &win_name_string,1,&win_name);
  XStringListToTextProperty( &icon_name_string,1,&icon_name);
  
  wm_hints -> flags = StateHint | InputHint ;
  wm_hints -> initial_state = NormalState;
  wm_hints -> input = False;

  class_hints -> res_name = "x_use_example";
  class_hints -> res_class = "examples";

  XSetWMProperties( display_ptr, win, &win_name, &icon_name, argv, argc,
                    size_hints, wm_hints, class_hints );

  XSelectInput( display_ptr, win, 
            ExposureMask | StructureNotifyMask | ButtonPressMask );
  
  XMapWindow( display_ptr, win );

  XFlush(display_ptr);
  gc_red = XCreateGC( display_ptr, win, valuemask, &gc_red_values);
  XSetLineAttributes( display_ptr, gc_red, 3, LineSolid, CapRound, JoinRound);
  if( XAllocNamedColor( display_ptr, color_map, "red", 
      &tmp_color1, &tmp_color2 ) == 0 )
    {printf("failed to get color red\n"); exit(-1);} 
  else
    XSetForeground( display_ptr, gc_red, tmp_color1.pixel );
  gc_black = XCreateGC( display_ptr, win, valuemask, &gc_black_values);
  XSetLineAttributes(display_ptr, gc_black, 3, LineSolid,CapRound, JoinRound);
  if( XAllocNamedColor( display_ptr, color_map, "black", 
      &tmp_color1, &tmp_color2 ) == 0 )
    {printf("failed to get color black\n"); exit(-1);} 
  else
    XSetForeground( display_ptr, gc_black, tmp_color1.pixel );
  gc_blue = XCreateGC( display_ptr, win, valuemask, &gc_blue_values);
  XSetLineAttributes(display_ptr, gc_blue, 3, LineSolid,CapRound, JoinRound);
  if( XAllocNamedColor( display_ptr, color_map, "blue", 
      &tmp_color1, &tmp_color2 ) == 0 )
    {printf("failed to get blue yellow\n"); exit(-1);} 
  else
    XSetForeground( display_ptr, gc_blue, tmp_color1.pixel );
  gc_white = XCreateGC( display_ptr, win, valuemask, &gc_white_values);
  XSetLineAttributes(display_ptr, gc_white, 3, LineSolid,CapRound, JoinRound);
  if( XAllocNamedColor( display_ptr, color_map, "white", 
      &tmp_color1, &tmp_color2 ) == 0 )
    {printf("failed to get color white\n"); exit(-1);} 
  else
    XSetForeground( display_ptr, gc_white, tmp_color1.pixel );

  if ( argc != 2 ) 
  {
      printf( "Usage: %s filename.extension \n", argv[0] );
      exit(-1);
  }
  fp = fopen(argv[1], "r");
  if (fp == NULL) 
  {
    fprintf(stderr, "Can't open file %s!\n", argv[1]);
    printf( "Usage: %s filename.extension or Check whether file is present or not\n", argv[0] );
    exit(-1);
  } 
  triangle_count = 0;
  while (fscanf(fp, "%c %c%d%c%d%c %c%d%c%d%c %c%d%c%d%c%c", &a,&a,&x_1,&a,&y_1,&a,&a,&x_2,&a,&y_2,&a,&a,&x_3,&a,&y_3,&a,&a) != EOF) 
  {
    if(get_x_min(x_1,x_2,x_3) >= 0 && get_y_min(y_1,y_2,y_3) >= 0 && get_x_max(x_1,x_2,x_3) <= display_width - 300 && get_y_max(y_1,y_2,y_3) <= display_height - 200)
    {
      t[triangle_count].x1 = x_1;
      t[triangle_count].x2 = x_2;
      t[triangle_count].x3 = x_3;
      t[triangle_count].y1 = y_1;
      t[triangle_count].y2 = y_2;
      t[triangle_count].y3 = y_3;
      triangle_count++;
    }   
  }
  
  x_min = t[0].x1;
  x_max = x_min;
  y_min = t[0].y1;
  y_max = y_min;
  for(i=0;i<triangle_count;i++)
  {
    if(x_min > t[i].x1)
      x_min = t[i].x1;
    if(x_min > t[i].x2)
      x_min = t[i].x2;
    if(x_min > t[i].x2)
      x_min = t[i].x3;
    if(y_min > t[i].y1)
      y_min = t[i].y1;
    if(y_min > t[i].y2)
      y_min = t[i].y2;
    if(y_min > t[i].y3)
      y_min = t[i].y3;
    if(x_max < t[i].x1)
      x_max = t[i].x1;
    if(x_max < t[i].x2)
      x_max = t[i].x2;
    if(x_max < t[i].x3)
      x_max = t[i].x3;
    if(y_max < t[i].y1)
      y_max = t[i].y1;
    if(y_max < t[i].y2)
      y_max = t[i].y2;
    if(y_max < t[i].y3)
      y_max = t[i].y3;        
  }
   
  x_center = win_width / 2;
  y_center = win_height / 2;
  x_gap = x_max - x_min;
  y_gap = y_max - y_min;
  x_start = x_center - x_gap/2 - 50;
  y_start = y_center - y_gap/2 - 50;
  x_end = x_start + x_gap + 100;
  y_end = y_start + y_gap + 100;
  rec_width = x_end - x_start;
  rec_height = y_end - y_start;

  for(i=0;i<triangle_count;i++)
  {
    t[i].x1 = t[i].x1 + x_start + 50 - x_min;
    t[i].x2 = t[i].x2 + x_start + 50 - x_min;
    t[i].x3 = t[i].x3 + x_start + 50 - x_min;
    t[i].y1 = t[i].y1 + y_start + 50 - y_min;
    t[i].y2 = t[i].y2 + y_start + 50 - y_min;
    t[i].y3 = t[i].y3 + y_start + 50 - y_min;
  }
  for(i=0;i<triangle_count;i++)
  {
    t[i].point_1_inside_triangle = 0;
    t[i].point_2_inside_triangle = 0;
    t[i].point_3_inside_triangle = 0;       
  }
  for(i=0;i<triangle_count;i++)
  {
    for(j=0;j<triangle_count;j++)
    {
      if(j!=i)
      {
        if(point_in_triangle(t[i].x1,t[i].y1,t[j].x1,t[j].y1,t[j].x2,t[j].y2,t[j].x3,t[j].y3)==1)
        {
          t[i].point_1_inside_triangle = 1;
        }
        if(point_in_triangle(t[i].x2,t[i].y2,t[j].x1,t[j].y1,t[j].x2,t[j].y2,t[j].x3,t[j].y3)==1)
        {
          t[i].point_2_inside_triangle = 1;
        }
        if(point_in_triangle(t[i].x3,t[i].y3,t[j].x1,t[j].y1,t[j].x2,t[j].y2,t[j].x3,t[j].y3)==1)
        {
          t[i].point_3_inside_triangle = 1;
        }
      }
    }
  }
  
  while(1)
  { 
    XNextEvent( display_ptr, &report );
    switch( report.type )
	  {
	    case Expose:
	      for(i=0;i<triangle_count;i++)
        {
          XDrawLine(display_ptr, win, gc_black, t[i].x1, t[i].y1, t[i].x2, t[i].y2);
          XDrawLine(display_ptr, win, gc_black, t[i].x2, t[i].y2, t[i].x3, t[i].y3);
          XDrawLine(display_ptr, win, gc_black, t[i].x3, t[i].y3, t[i].x1, t[i].y1);
        }
        XDrawRectangle(display_ptr, win, gc_black, x_start, y_start, rec_width, rec_height ); 
        break;
        
      case ConfigureNotify:
          win_width = report.xconfigure.width;
          win_height = report.xconfigure.height;
          break;
        
      case ButtonPress:
      {  
        int x, y;
  	    x = report.xbutton.x;
        y = report.xbutton.y;
        if (report.xbutton.button == Button1 )
	      {
          outside = 0;
          if(x <= x_start || y <= y_start || x >= x_end || y >= y_end)
          {
            outside = 1;
          } 
          for(i=0;i<triangle_count;i++)
          {
            if(point_in_triangle(x,y,t[i].x1,t[i].y1,t[i].x2,t[i].y2,t[i].x3,t[i].y3)==1)
            {
              outside = 1;
              break;
            }
          }
          if(outside == 0)
          {
            ButtonPressed++;
            if(ButtonPressed == 1)
            { 
              temp_x = x;
              temp_y = y;
              pixel_count = 0;
              XFillArc( display_ptr, win, gc_red, x - win_height/150, y - win_height/150, win_height/100, win_height/100, 0, 360*64);
              pixel[pixel_count].name = pixel_count;
              pixel[pixel_count].x = x; 
              pixel[pixel_count].y = y;
              pixel_count++;
            }
            else if(ButtonPressed == 2)
            { 
              if(temp_x == x && temp_y == y)
              {
                ButtonPressed = 1;
                break;
              }
              XFillArc( display_ptr, win, gc_red, x - win_height/150, y - win_height/150, win_height/100, win_height/100, 0, 360*64);
              for(i=0;i<triangle_count;i++)
              {
                if(t[i].point_1_inside_triangle != 1)
                {
                  pixel[pixel_count].name = pixel_count;
                  pixel[pixel_count].x = t[i].x1; 
                  pixel[pixel_count].y = t[i].y1;
                  pixel_count++;
                }
                if(t[i].point_2_inside_triangle != 1)
                {
                  pixel[pixel_count].name = pixel_count;
                  pixel[pixel_count].x = t[i].x2; 
                  pixel[pixel_count].y = t[i].y2;
                  pixel_count++;
                }
                if(t[i].point_3_inside_triangle != 1)
                {
                  pixel[pixel_count].name = pixel_count;
                  pixel[pixel_count].x = t[i].x3; 
                  pixel[pixel_count].y = t[i].y3;
                  pixel_count++;
                }
              }
              pixel[pixel_count].name = pixel_count;
              pixel[pixel_count].x = x; 
              pixel[pixel_count].y = y;
              pixel_count++;
              for(i=0;i<pixel_count-1;i++)
              {         
                for(j=i+1;j<pixel_count;j++)
                {
                  if(can_see(pixel[i].x,pixel[i].y,pixel[j].x,pixel[j].y)==1)
                  {
                    cost[pixel[i].name][pixel[j].name] = cost[pixel[j].name][pixel[i].name] = eculidian_dist(pixel[i].x,pixel[i].y,pixel[j].x,pixel[j].y);
                  }
                }
              }
              dijsktra(pixel[0].name, pixel[pixel_count-1].name);
            }
            else
            {
              clear_cost();
              expose();
              ButtonPressed = 0;          
            }
          }
        }
        else
        {
          XFlush(display_ptr);
          XCloseDisplay(display_ptr);
          exit(0);
        }
      }
      break;
      default:
        break;
    }
  }
  exit(0);
}
Ejemplo n.º 9
0
unsigned long QXlibScreen::blackPixel()
{
    return BlackPixel(mDisplay->nativeDisplay(), mScreen);
}
Ejemplo n.º 10
0
void xskin_start_interface( int pipe_in ) {

  int xskin_sc;
  XEvent xskin_e;
  XSetWindowAttributes xskin_attr;

  XSizeHints xskin_hint;
  XClassHint xskin_chint;
  XTextProperty ct;
  char *namlist[2];


  /* setup window */

  xskin_d     = XOpenDisplay( NULL );
  xskin_sc    = DefaultScreen( xskin_d );
  xskin_r     = RootWindow( xskin_d, xskin_sc );
  xskin_gc    = DefaultGC( xskin_d, xskin_sc );
  xskin_vis   = DefaultVisual( xskin_d, xskin_sc );
  xskin_depth = DefaultDepth( xskin_d, xskin_sc );

  xskin_w = XCreateSimpleWindow( xskin_d, xskin_r, 0, 0,
				 skin_width, skin_height, 0,
				 WhitePixel( xskin_d, xskin_sc ),
				 BlackPixel( xskin_d, xskin_sc ) );

  xskin_attr.backing_store = True;
  xskin_attr.override_redirect = False;
  XChangeWindowAttributes( xskin_d, xskin_w,
			   CWBackingStore|CWOverrideRedirect, &xskin_attr );

  XSelectInput( xskin_d, xskin_w,
		KeyPressMask|ExposureMask|
		EnterWindowMask|LeaveWindowMask|
		ButtonPressMask|ButtonReleaseMask|
		Button1MotionMask );

  xskin_hint.flags = USSize | PMinSize | PMaxSize | USPosition;
  xskin_hint.width = xskin_hint.min_width = xskin_hint.max_width
    = skin_width;
  xskin_hint.height = xskin_hint.min_height = xskin_hint.max_height
    = skin_height;
  XSetNormalHints( xskin_d, xskin_w, &xskin_hint );

  xskin_chint.res_name  = XSKIN_RES_NAME;
  xskin_chint.res_class = XSKIN_RES_CLASS;
  XSetClassHint( xskin_d, xskin_w, &xskin_chint );

  namlist[0]=(char *)safe_malloc(strlen(XSKIN_WINDOW_NAME)+1);
  strcpy( namlist[0], XSKIN_WINDOW_NAME );
  XmbTextListToTextProperty( xskin_d, namlist, 1, XCompoundTextStyle, &ct );
  XSetWMName( xskin_d, xskin_w, &ct );
  XSetWMIconName( xskin_d, xskin_w, &ct );
  free(namlist[0]);


  /* setup pixmaps */

  if ( load_skins()!=0 ) goto finish;

  XSetWindowBackgroundPixmap( xskin_d, xskin_w, xskin_back );
  XClearWindow( xskin_d, xskin_w );

  XMapWindow( xskin_d, xskin_w );
  while( 1 ) {
    XNextEvent( xskin_d, &xskin_e );
    if ( xskin_e.type == Expose ) break; 
  }

  fshuf=0;
  frep=0;
  fequ=1;
  fpll=1;
  fplay=0;
  fpause=0;
  fremain=0;
  play_val=1;
  vol_val=50;
  last_current_time=0;
  total_time=0;
  speana_buf = NULL;
  strcpy( last_text, "welcome to timidity" );

  install_sighandler();

  repaint();
  ts_spectrum( -1, speana_buf );

  XFlush(xskin_d);

  xskin_jobs( pipe_in );   /* tskin main jobs */

finish:
  signal_vector(0);  /* finish */
}
Ejemplo n.º 11
0
 unsigned long XApplication::GetBlackColor() const
 {
   return BlackPixel(this->display, this->screen);
 }
Ejemplo n.º 12
0
void
WindowDevice::WINOPEN(const char *_title, int _xLoc, int _yLoc, int _width, int _height)
{
    // set the WindowDevices title, height, wdth, xLoc and yLoc
    strcpy(title, _title);

    height = _height;
    width = _width;  
    xLoc = _xLoc;
    yLoc = _yLoc;

#ifdef _UNIX
    if (winOpen == 0) { // we must close the old window
	XFreeGC(theDisplay, theGC);
	XDestroyWindow(theDisplay, theWindow); 
    }

    // define the position and size of the window - only hints
    hints.x = _xLoc;
    hints.y = _yLoc;
    hints.width = _width;
    hints.height = _height;
    hints.flags = PPosition | PSize;

    // set the defualt foreground and background colors
    XVisualInfo visual; 
    visual.visual = 0;
    int depth = DefaultDepth(theDisplay, theScreen);

    if (background == 0) {
      if (XMatchVisualInfo(theDisplay, theScreen, depth, PseudoColor, &visual) == 0) {
	  foreground = BlackPixel(theDisplay, theScreen);
	  background = WhitePixel(theDisplay, theScreen);    

      } else {
	foreground = 0;
	background = 255;
      }
    }

    // now open a window
    theWindow = XCreateSimpleWindow(theDisplay,RootWindow(theDisplay,0),
				    hints.x, hints.y,
				    hints.width,hints.height,4,
				    foreground, background);

    if (theWindow == 0) {
	opserr << "WindowDevice::WINOPEN() - could not open a window\n";
	exit(-1);
    }	
    
    XSetStandardProperties(theDisplay, theWindow, title, title, None, 0, 0, &hints);
    
    // create a graphical context
    theGC = XCreateGC(theDisplay, theWindow, 0, 0);

    // if we were unable to get space for our colors
    // we must create and use our own colormap
    if (colorFlag == 3 ) {

      // create the colormap if the 1st window
      if (numWindowDevice == 1) {
	int fail = false;
	//	XMatchVisualInfo(theDisplay, theScreen, depth, PseudoColor, &visual);
	if (XMatchVisualInfo(theDisplay, theScreen, depth, PseudoColor, &visual) == 0) {
	  opserr << "WindowDevice::initX11() - could not get a visual for PseudoColor\n";
	  opserr << "Colors diplayed will be all over the place\n";
	  cmap = DefaultColormap(theDisplay, theScreen);
	  fail = true;
        } else {
	  opserr << "WindowDevice::WINOPEN have created our own colormap, \n";
	  opserr << "windows may change color as move mouse from one window to\n";
	  opserr << "another - depends on your video card to use another colormap\n\n";	

	  cmap = XCreateColormap(theDisplay,theWindow,
				 visual.visual, AllocAll);
	}


	/*
	cmap = XCreateColormap(theDisplay,theWindow,
			   DefaultVisual(theDisplay,0),AllocAll);
	*/

	if (cmap == 0) {
	    opserr << "WindowDevice::initX11() - could not get a new color table\n";
	    exit(-1);
	}	    

	// we are going to try to allocate 256 new colors -- need 8 planes for this
	depth = DefaultDepth(theDisplay, theScreen);
	if (depth < 8) {
	    opserr << "WindowDevice::initX11() - needed at least 8 planes\n";
	    exit(-1);
	}	    
	if (fail == false) {
	  int cnt = 0;
	  for (int red = 0; red < 8; red++) {
	    for (int green = 0; green < 8; green++) {
		for (int blue = 0; blue < 4; blue++) {
		  pixels[32*red + 4*green + blue] = cnt;
		  colors[cnt].pixel = pixels[32*red + 4*green + blue];
		  colors[cnt].red = (65536/7)*red;
		  colors[cnt].green = (65536/7)*green;
		  colors[cnt].blue = (65536/3)*blue;
		  colors[cnt].flags = DoRed | DoGreen | DoBlue;
		  cnt++;
		}			
	    }
	  }
	  background = 0; //pixels[0];
	  foreground = 255; // pixels[255];
	  XStoreColors(theDisplay, cmap, colors, cnt);			    
	}
      }

      // now set the windows to use the colormap
      XSetWindowColormap(theDisplay, theWindow, cmap);    
    
    }

    XSetBackground(theDisplay, theGC, background);
    XSetForeground(theDisplay, theGC, foreground);

    XMapWindow(theDisplay,theWindow);
    XClearWindow(theDisplay, theWindow);      
    XFlush(theDisplay);

#else
    //    auxInitDisplayMode(AUX_SINGLE | AUX_RGBA);
    //    auxInitPosition(100,100,_width,_height);
    //    auxInitWindow("G3");

    if (winOpen == 0)
      oglDestroyWindow(title,theWND, theHRC, theHDC);      

    theWND = oglCreateWindow(title, xLoc, yLoc, width, height, &theHRC, &theHDC);
    if (theWND == NULL)
      exit(1);
    winOpen = 0;

    wglMakeCurrent(theHDC, theHRC);
    glClearColor(1.0f,1.0f,1.0f,1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    glViewport(0, 0, (GLsizei)width, (GLsizei)height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
//    gluOrtho2D(0.0, (GLdouble)width, 0.0, (GLdouble)height);
    glFlush();

#endif

    winOpen = 0;
}
Ejemplo n.º 13
0
/* This function should be written using GTK+ primitives*/
static void
gstroke_invisible_window_init (GtkWidget *widget)
{
  XSetWindowAttributes w_attr;
  XWindowAttributes orig_w_attr;
  unsigned long mask, col_border, col_background;
  unsigned int border_width;
  XSizeHints hints;
  Display *disp = GDK_WINDOW_XDISPLAY(gtk_widget_get_window(widget));
  Window wind = gdk_x11_window_get_xid(gtk_widget_get_window(widget));
  int screen = DefaultScreen (disp);

	if (!gstroke_draw_strokes())
		return;

  gstroke_disp = disp;

  /* X server should save what's underneath */
  XGetWindowAttributes (gstroke_disp, wind, &orig_w_attr);
  hints.x = orig_w_attr.x;
  hints.y = orig_w_attr.y;
  hints.width = orig_w_attr.width;
  hints.height = orig_w_attr.height;
  mask = CWSaveUnder;
  w_attr.save_under = True;

  /* inhibit all the decorations */
  mask |= CWOverrideRedirect;
  w_attr.override_redirect = True;

  /* Don't set a background, transparent window */
  mask |= CWBackPixmap;
  w_attr.background_pixmap = None;

  /* Default input window look */
  col_background = WhitePixel (gstroke_disp, screen);

  /* no border for the window */
#if 0
  border_width = 5;
#endif
  border_width = 0;

  col_border = BlackPixel (gstroke_disp, screen);

  gstroke_window = XCreateSimpleWindow (gstroke_disp, wind,
                                        0, 0,
                                        hints.width - 2 * border_width,
                                        hints.height - 2 * border_width,
                                        border_width,
                                        col_border, col_background);

  gstroke_gc = XCreateGC (gstroke_disp, gstroke_window, 0, NULL);

  XSetFunction (gstroke_disp, gstroke_gc, GXinvert);

  XChangeWindowAttributes (gstroke_disp, gstroke_window, mask, &w_attr);

  XSetLineAttributes (gstroke_disp, gstroke_gc, 2, LineSolid,
                      CapButt, JoinMiter);
  XMapRaised (gstroke_disp, gstroke_window);

#if 0
  /*FIXME: is this call really needed? If yes, does it need the real
    argc and argv? */
  hints.flags = PPosition | PSize;
  XSetStandardProperties (gstroke_disp, gstroke_window, "gstroke_test", NULL,
                          (Pixmap)NULL, NULL, 0, &hints);


  /* Receive the close window client message */
  {
    /* FIXME: is this really needed? If yes, something should be done
       with wmdelete...*/
    Atom wmdelete = XInternAtom (gstroke_disp, "WM_DELETE_WINDOW",
                                 False);
    XSetWMProtocols (gstroke_disp, gstroke_window, &wmdelete, True);
  }
#endif
}
Ejemplo n.º 14
0
  int main (void)
  {
    int i;
  
    int allocateOK;
  
    ximg = NULL;
  
  	
    d = XOpenDisplay (NULL);
  
    if (!d)
      fputs ("Couldn't open display\n", stderr), exit (1);
  
    screen = DefaultScreen (d);
    gc = DefaultGC (d, screen);
  
    /* Find a visual */
  
    vis.screen = screen;
    vlist = XGetVisualInfo (d, VisualScreenMask, &vis, &match);
  
    if (!vlist)
      fputs ("No matched visuals\n", stderr), exit (1);
  
    vis = vlist[0];
    XFree (vlist);
		
  	// That's not a fair comparison colormap_size is depth in bits!
    // if (vis.colormap_size < COLORS)
      // printf("Colormap is too small: %i.\n",vis.colormap_size); // , exit (1);
		// printf("Colour depth: %i\n",vis.colormap_size);
		// No way this number means nothing!  It is 64 for 16-bit truecolour and 256 for 8-bit!
  
    win = XCreateSimpleWindow (d, DefaultRootWindow (d),
			       0, 0, WIN_W, WIN_H, 0,
			       WhitePixel (d, screen), BlackPixel (d, screen));
  
	  int xclass=get_xvisinfo_class(vis);
		// printf("class = %i\n",xclass);
	  stylee = ( vis.depth > 8 ? styleeTrueColor : styleePrivate );
	  // printf("stylee=%i\n",stylee);
  
    if ( get_xvisinfo_class(vis) % 2 == 1) {	/* The odd numbers can redefine colors */
  
			  // printf("%i\n",get_xvisinfo_class(vis));
	  	
      colormap = DefaultColormap (d, screen);
		  Visual *defaultVisual=DefaultVisual(d,screen);
	  	
      /* Allocate cells */
      allocateOK = (XAllocColorCells (d, colormap, 1,
							      NULL, 0, color, COLORS) != 0);

			printf("Allocated OK? %i\n",allocateOK);
			
      if (allocateOK) {
  
			  // printf("Allocated OK\n");
        // This doesn't work for installed colormap!
  
        /* Modify the colorcells */
        for (i = 0; i < COLORS; i++)
				  xrgb[i].pixel = color[i];
  
        XStoreColors (d, colormap, xrgb, COLORS);
  
		  } else {

			  colormap = XCreateColormap(d,win,defaultVisual,AllocNone);
		  	
    	  // redocolors();
					  	
      }
  
		  // black = XBlackPixel(d,screen);
		  // white = XWhitePixel(d,screen);
  
			XAllocColorCells(d,colormap,1,0,0,color,colors);
			XSetWindowColormap(d,win,colormap);

    } else if ( get_xvisinfo_class(vis) == TrueColor) {
      colormap = DefaultColormap (d, screen);
					  // printf("TrueColor %i = %i\n",xclass,TrueColor);
      /* This will lookup the color and sets the xrgb[i].pixel value */
      // for (i = 0; i < COLORS; i++)
        // XAllocColor (d, colormap, &xrgb[i]);
    } else
      fprintf (stderr, "Not content with visual class %d.\n",
	       get_xvisinfo_class(vis) ), exit (1);
  
    /* Find out if MITSHM is supported and useable */
    printf ("MITSHM: ");
  
    if (XShmQueryVersion (d, &mitshm_major_code,
			  &mitshm_minor_code, &shared_pixmaps)) {
      int (*handler) (Display *, XErrorEvent *);
      ximg = XShmCreateImage (d, vis.visual,
			     vis.depth, XShmPixmapFormat (d),
			     NULL, &shminfo, WIN_W, WIN_H);
      shminfo.shmid = shmget (IPC_PRIVATE,
			      ximg->bytes_per_line * ximg->height,
			      IPC_CREAT | 0777);
      shminfo.shmaddr = (char *)shmat (shminfo.shmid, 0, 0);
		  ximg->data = (char *)shminfo.shmaddr;
  
      handler = XSetErrorHandler (mitshm_handler);
      XShmAttach (d, &shminfo);	/* Tell the server to attach */
      XSync (d, 0);
      XSetErrorHandler (handler);
  
      shmctl (shminfo.shmid, IPC_RMID, 0);
      /* Mark this shm segment for deletion at once. The segment will
       * automatically become released when both the server and this
       * client have detached from it.
       * (Process termination automagically detach shm segments) */
  
      if (!can_use_mitshm) {
        shmdt (shminfo.shmaddr);
        ximg = NULL;
      }
    }
  
    if (ximg == NULL) {
      can_use_mitshm = 0;
      /* XInitImage(ximg); */
      ximg = XCreateImage (d, vis.visual, vis.depth, ZPixmap,
			  0, (char *)malloc (WIN_W * WIN_H), WIN_W, WIN_H, 8, 0);
    }
  
    if (can_use_mitshm)
      printf ("YES!\n");
    else
      printf ("NO, using fallback instead.\n");
  
    // DrawFractal (ximg,xrgb);
  
    XSelectInput (d, win, ButtonPressMask | ExposureMask);
    XMapWindow (d, win);
  
  
  
  
    real_main();


  
      // XNextEvent (d, &ev);
      // switch (ev.type) {
      // case ButtonPress:
        // should_quit = 1;
        // break;
      // case Expose:
        // if (can_use_mitshm)
				  // XShmPutImage (d, win, gc, img, 0, 0, 0, 0, WIN_W, WIN_H, True);
        // else
				  // XPutImage (d, win, gc, img, 0, 0, 0, 0, WIN_W, WIN_H);
        // break;
      // default:
			  // break;
      // }
  
  
  
    if (get_xvisinfo_class(vis) % 2 == 1 || get_xvisinfo_class(vis) == TrueColor) {
      unsigned long color[COLORS];
  
      if (allocateOK) {
        for (i = 0; i < COLORS; i++)
				  color[i] = xrgb[i].pixel;
        XFreeColors (d, colormap, color, COLORS, 0);
      }				/* Allocated colors freed */
    } else {
      XUninstallColormap (d, colormap);
    }
  
    if (can_use_mitshm) {
      XShmDetach (d, &shminfo);	/* Server detached */
      XDestroyImage (ximg);	/* Image struct freed */
      shmdt (shminfo.shmaddr);	/* We're detached */
    } else
      XDestroyImage (ximg);	/* Image struct freed */
  
    XDestroyWindow (d, win);	/* Window removed */
    XCloseDisplay (d);		/* Display disconnected */
  
    /* So you can see how your computer compares to your friend's */
    getrusage (RUSAGE_SELF, &resource_utilization);
		float seconds=(float)resource_utilization.ru_utime.tv_sec
						     +(float)resource_utilization.ru_utime.tv_usec*0.000000001;
		printf("CPU seconds per frame: %f\n",seconds/(float)frameno);
    // printf ("CPU seconds consumed: %ds and %dµs\n",
	    // (int) resource_utilization.ru_utime.tv_sec,
	    // (int) resource_utilization.ru_utime.tv_usec);
  
    return 0;
  }
int XMessageBox::show()
{
   if (mDisplay == NULL)
      return -1;

   int retVal = 0;
   retVal = loadFont();
   if (retVal < 0)
      return retVal;

   // set the maximum window dimensions
   mScreenWidth = DisplayWidth(mDisplay, DefaultScreen(mDisplay));
   mScreenHeight = DisplayHeight(mDisplay, DefaultScreen(mDisplay));
   mMaxWindowWidth = min(mScreenWidth, MessageBox_MaxWinWidth);
   mMaxWindowHeight = min(mScreenHeight, MessageBox_MaxWinHeight);

   // split the message into a vector of lines
   splitMessage();

   // set the dialog dimensions
   setDimensions();

   mWin = XCreateSimpleWindow(
      mDisplay,
      DefaultRootWindow(mDisplay),
      (mScreenWidth - mMBWidth) / 2,  (mScreenHeight - mMBHeight) / 2,
      mMBWidth, mMBHeight,
      1, 
      BlackPixel(mDisplay, DefaultScreen(mDisplay)),
      WhitePixel(mDisplay, DefaultScreen(mDisplay)));

   mGC = XCreateGC(mDisplay, mWin, 0, 0);

   XSetFont(mDisplay, mGC, mFS->fid);

   // set input mask
   XSelectInput(mDisplay, mWin, 
      ExposureMask | PointerMotionMask | ButtonPressMask | ButtonReleaseMask);

   // set wm protocols in case they hit X
   Atom wm_delete_window = 
      XInternAtom(mDisplay, "WM_DELETE_WINDOW", False);
   Atom wm_protocols = 
      XInternAtom(mDisplay, "WM_PROTOCOLS", False);
   XSetWMProtocols (mDisplay, mWin, &wm_delete_window, 1);
   // set pop up dialog hint
   XSetTransientForHint(mDisplay, mWin, mWin);
   
   // set title
   XTextProperty wtitle;
   wtitle.value = (unsigned char *)mTitle;
   wtitle.encoding = XA_STRING;
   wtitle.format = 8;
   wtitle.nitems = strlen(mTitle);
   XSetWMName(mDisplay, mWin, &wtitle);

   // show window
   XMapWindow(mDisplay, mWin);
   // move it in case some bozo window manager repositioned it
   XMoveWindow(mDisplay, mWin, 
      (mScreenWidth - mMBWidth) / 2,  (mScreenHeight - mMBHeight) / 2);
   // raise it to top
   XRaiseWindow(mDisplay, mWin);

   XMessageBoxButton* clickedButton = NULL;
   XEvent event;
   Vector<XMessageBoxButton>::iterator iter;
   bool done = false;
   while (!done)
   {
      XNextEvent(mDisplay, &event);
      switch (event.type)
      {
         case Expose:
            repaint();
            break;
         case MotionNotify:
            for (iter = mButtons.begin(); iter != mButtons.end(); ++iter)
               iter->setMouseCoordinates(event.xmotion.x, event.xmotion.y);
            break;
         case ButtonPress:
            for (iter = mButtons.begin(); iter != mButtons.end(); ++iter)
            {
               if (iter->pointInRect(event.xbutton.x, event.xbutton.y))
               {
                  iter->setMouseDown(true);
                  iter->setMouseCoordinates(event.xbutton.x, event.xbutton.y);
                  break;
               }
            }
            break;
         case ButtonRelease:
            for (iter = mButtons.begin(); iter != mButtons.end(); ++iter)
            {
               if (iter->pointInRect(event.xbutton.x, event.xbutton.y) &&
                  iter->isMouseDown())
               {
                  // we got a winner!
                  clickedButton = iter;
                  done = true;
                  break;
               }
            }
            if (clickedButton == NULL)
            {
               // user released outside a button.  clear the button states
               for (iter = mButtons.begin(); iter != mButtons.end(); ++iter)
                  iter->setMouseDown(false);
            }
            break;
         case ClientMessage:
            if (event.xclient.message_type == wm_protocols &&
               event.xclient.data.l[0] == static_cast<long>(wm_delete_window))
               done = true;
            break;
      }
      repaint();
   }

   XUnmapWindow(mDisplay, mWin);
   XDestroyWindow(mDisplay, mWin);
   XFreeGC(mDisplay, mGC);
   XFreeFont(mDisplay, mFS);

   if (clickedButton != NULL)
      return clickedButton->getClickVal();
   else
      return -1;
}
Ejemplo n.º 16
0
void
drawswarm(Window win)
{
	swarmstruct *sp = &swarms[screen];
	int         b;

	/* <=- Wasp -=> */
	/* Age the arrays. */
	sp->wx[2] = sp->wx[1];
	sp->wx[1] = sp->wx[0];
	sp->wy[2] = sp->wy[1];
	sp->wy[1] = sp->wy[0];
	/* Accelerate */
	sp->wxv += balance_rand(WASPACC);
	sp->wyv += balance_rand(WASPACC);

	/* Speed Limit Checks */
	if (sp->wxv > WASPVEL)
		sp->wxv = WASPVEL;
	if (sp->wxv < -WASPVEL)
		sp->wxv = -WASPVEL;
	if (sp->wyv > WASPVEL)
		sp->wyv = WASPVEL;
	if (sp->wyv < -WASPVEL)
		sp->wyv = -WASPVEL;

	/* Move */
	sp->wx[0] = sp->wx[1] + sp->wxv;
	sp->wy[0] = sp->wy[1] + sp->wyv;

	/* Bounce Checks */
	if ((sp->wx[0] < sp->border) || (sp->wx[0] > sp->width - sp->border - 1)) {
		sp->wxv = -sp->wxv;
		sp->wx[0] += sp->wxv;
	}
	if ((sp->wy[0] < sp->border) || (sp->wy[0] > sp->height - sp->border - 1)) {
		sp->wyv = -sp->wyv;
		sp->wy[0] += sp->wyv;
	}
	/* Don't let things settle down. */
	sp->xv[LRAND() % sp->beecount] += balance_rand(3);
	sp->yv[LRAND() % sp->beecount] += balance_rand(3);

	/* <=- Bees -=> */
	for (b = 0; b < sp->beecount; b++) {
		int         distance, dx, dy;

		/* Age the arrays. */
		X(2, b) = X(1, b);
		X(1, b) = X(0, b);
		Y(2, b) = Y(1, b);
		Y(1, b) = Y(0, b);

		/* Accelerate */
		dx = sp->wx[1] - X(1, b);
		dy = sp->wy[1] - Y(1, b);
		distance = abs(dx) + abs(dy);	/* approximation */
		if (distance == 0)
			distance = 1;
		sp->xv[b] += (dx * BEEACC) / distance;
		sp->yv[b] += (dy * BEEACC) / distance;

		/* Speed Limit Checks */
		if (sp->xv[b] > BEEVEL)
			sp->xv[b] = BEEVEL;
		if (sp->xv[b] < -BEEVEL)
			sp->xv[b] = -BEEVEL;
		if (sp->yv[b] > BEEVEL)
			sp->yv[b] = BEEVEL;
		if (sp->yv[b] < -BEEVEL)
			sp->yv[b] = -BEEVEL;

		/* Move */
		X(0, b) = X(1, b) + sp->xv[b];
		Y(0, b) = Y(1, b) + sp->yv[b];

		/* Fill the segment lists. */
		sp->segs[b].x1 = X(0, b);
		sp->segs[b].y1 = Y(0, b);
		sp->segs[b].x2 = X(1, b);
		sp->segs[b].y2 = Y(1, b);
		sp->old_segs[b].x1 = X(1, b);
		sp->old_segs[b].y1 = Y(1, b);
		sp->old_segs[b].x2 = X(2, b);
		sp->old_segs[b].y2 = Y(2, b);
	}

	XSetForeground(dsp, Scr[screen].gc, BlackPixel(dsp, screen));
	XDrawLine(dsp, win, Scr[screen].gc,
		  sp->wx[1], sp->wy[1], sp->wx[2], sp->wy[2]);
	XDrawSegments(dsp, win, Scr[screen].gc, sp->old_segs, sp->beecount);

	XSetForeground(dsp, Scr[screen].gc, WhitePixel(dsp, screen));
	XDrawLine(dsp, win, Scr[screen].gc,
		  sp->wx[0], sp->wy[0], sp->wx[1], sp->wy[1]);
	if (!mono && Scr[screen].npixels > 2) {
		XSetForeground(dsp, Scr[screen].gc, Scr[screen].pixels[sp->pix]);
		if (++sp->pix >= Scr[screen].npixels)
			sp->pix = 0;
	}
	XDrawSegments(dsp, win, Scr[screen].gc, sp->segs, sp->beecount);
}
Ejemplo n.º 17
0
main()
{
	int llx,lly,urx,ury,width,height,
		scrwidth,scrheight,scrwidthmm,scrheightmm;
	float xres,yres;
	char buf[LBUF];
	Display *dpy;
	int scr;
	unsigned long black,white;
	GC gcpix,gcwin;
	Window win;
	Pixmap pix;
	XEvent ev;
	DPSContext dps;

	/* open display */
	if ((dpy=XOpenDisplay(NULL))==NULL) {
		fprintf(stderr,"Cannot connect to display %s\n",
			XDisplayName(NULL));
		exit(-1);
	}
	scr = DefaultScreen(dpy);
	black = BlackPixel(dpy,scr);
	white = WhitePixel(dpy,scr);
	
	/* determine BoundingBox */
	llx = LLX_DEFAULT;
	lly = LLY_DEFAULT;
	urx = URX_DEFAULT;
	ury = URY_DEFAULT;
	fgets(buf,LBUF,stdin);
	if (strstr(buf,"EPS")!=NULL) {
		while(fgets(buf,LBUF,stdin)!=NULL) { 
			if (buf[0]!='%' || buf[1]!='%') continue;
			if (strstr(buf,"%%BoundingBox:")==buf) {
				if (strstr(buf,"(atend)")==NULL) {
					sscanf(&buf[14],"%d %d %d %d",
						&llx,&lly,&urx,&ury);
				}
				break;
			} else if (strstr(buf,"%%EndComments")==buf) {
				break;
			} else if (strstr(buf,"%%EndProlog")==buf) {
				break;
			}
		}
	}

	/* width and height in pixels */
	scrwidth = WidthOfScreen(DefaultScreenOfDisplay(dpy));
	scrheight = HeightOfScreen(DefaultScreenOfDisplay(dpy));
	scrwidthmm = WidthMMOfScreen(DefaultScreenOfDisplay(dpy));
	scrheightmm = HeightMMOfScreen(DefaultScreenOfDisplay(dpy));
	xres = (int)(25.4*scrwidth/scrwidthmm)/72.0;
	yres = (int)(25.4*scrheight/scrheightmm)/72.0;
	if (xres*(urx-llx)>scrwidth || yres*(ury-lly)>scrheight) {
		xres = (scrwidth-32.0)/(urx-llx);
		yres = (scrheight-32.0)/(ury-lly);
		xres = yres = (xres<yres)?xres:yres;
	}
	width = (urx-llx)*xres;
	height = (ury-lly)*yres;

	/* create pixmap and its gc */
	pix = XCreatePixmap(dpy,DefaultRootWindow(dpy),width,height,
		DefaultDepth(dpy,scr));
	gcpix = XCreateGC(dpy,pix,0,NULL);

	/* create and set Display PostScript context for pixmap */
	dps = XDPSCreateSimpleContext(dpy,pix,gcpix,0,height,
		DPSDefaultTextBackstop,DPSDefaultErrorProc,NULL);
	if (dps==NULL) {
		fprintf(stderr,"Cannot create DPS context\n");
		exit(-1);
	}
	DPSPrintf(dps,"\n resyncstart\n");
	DPSSetContext(dps);
	DPSFlushContext(dps);
	DPSWaitContext(dps);

	/* paint white background */
	DPSPrintf(dps,
		"gsave\n"
		"1 setgray\n"
		"0 0 %d %d rectfill\n"
		"grestore\n",
		urx-llx,ury-lly);
	
	/* translate */
	DPSPrintf(dps,"%d %d translate\n",-llx,-lly);

	/* read PostScript from standard input and render in pixmap */
	DPSPrintf(dps,"/showpage {} def\n");
	while (fgets(buf,LBUF,stdin)!=NULL)
		DPSWritePostScript(dps,buf,strlen(buf));
	DPSFlushContext(dps);
	DPSWaitContext(dps);
	
	/* create and map window */
	win = XCreateSimpleWindow(dpy,DefaultRootWindow(dpy),
		100,100,width,height,1,black,white);
	XSetStandardProperties(dpy,win,"EPS Pixmap","EPSpix",
		None,NULL,0,NULL);
	XMapWindow(dpy,win);

	/* copy pixmap to window; in pixmap, black=0 and white=1 */
	gcwin = XCreateGC(dpy,win,0,NULL);
	XCopyArea(dpy,pix,win,gcwin,0,0,width,height,0,0);

	/* main event loop */
	XSelectInput(dpy,win,
		KeyPressMask |
		ExposureMask);
	while(True) {
        	XNextEvent(dpy,&ev);
		if (ev.type==Expose) {
			while (XCheckTypedEvent(dpy,Expose,&ev));
			XCopyArea(dpy,pix,win,gcwin,0,0,width,height,0,0);
		} else if (ev.type==KeyPress) {
			break;
		}
	}

	/* clean up */
	DPSDestroySpace(DPSSpaceFromContext(dps));
	XFreePixmap(dpy,pix);
	XFreeGC(dpy,gcpix);
	XFreeGC(dpy,gcwin);
}
Ejemplo n.º 18
0
int CreeTermGraph(TC *p,unsigned int largeur,unsigned int hauteur,char* titre)
{
  char *display_name = getenv("DISPLAY");
  unsigned long valuemask = 0;
  XGCValues values ;

  p->largeur = largeur;
  p->hauteur = hauteur;

  if ((p->display = XOpenDisplay(display_name)) == NULL)
    return -1;

  p->screen_num = DefaultScreen(p->display);

  p->win = XCreateSimpleWindow(p->display,
                               RootWindow(p->display,p->screen_num),
                               0,0,
                               largeur,hauteur,
                               1,
                               BlackPixel(p->display,p->screen_num),
                               WhitePixel(p->display,p->screen_num));

  XStoreName(p->display,p->win,titre);
  XMapWindow(p->display,p->win);
  XFlush(p->display);

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

  /***** Allocations des couleurs *****/
  p->cm = DefaultColormap(p->display,DefaultScreen(p->display));

  if (XAllocNamedColor(p->display,p->cm,"black",&(p->Noir),&(p->Noir)) == 0)
    return -1;

  if (XAllocNamedColor(p->display,p->cm,"white",&(p->Blanc),&(p->Blanc)) == 0)
    return -1;

  if (XAllocNamedColor(p->display,p->cm,"red",&(p->Rouge),&(p->Rouge)) == 0)
    return -1;

  if (XAllocNamedColor(p->display,p->cm,"blue",&(p->Bleu),&(p->Bleu)) == 0)
    return -1;

  if (XAllocNamedColor(p->display,p->cm,"green",&(p->Vert),&(p->Vert)) == 0)
    return -1;

  if (XAllocNamedColor(p->display,p->cm,"yellow",&(p->Jaune),&(p->Jaune)) == 0)
    return -1;
    
  if (XAllocNamedColor(p->display,p->cm,"brown",&(p->Brun),&(p->Brun)) == 0)
    return -1;
    
  if (XAllocNamedColor(p->display,p->cm,"gray",&(p->Gris),&(p->Gris)) == 0)
    return -1;
    
  if (XAllocNamedColor(p->display,p->cm,"magenta",&(p->Magenta),&(p->Magenta)) == 0)
    return -1;
    
  if (XAllocNamedColor(p->display,p->cm,"cyan",&(p->Cyan),&(p->Cyan)) == 0)
    return -1;

  if (XAllocNamedColor(p->display,p->cm,"orange",&(p->Orange),&(p->Orange)) == 0)
    return -1;

  XSetBackground(p->display, p->gc, p->Blanc.pixel);

  XSync(p->display, False);

  sleep(1);

  return 0;
}
Ejemplo n.º 19
0
QT_BEGIN_NAMESPACE

QXlibWindow::QXlibWindow(QWidget *window)
    : QPlatformWindow(window)
    , mGLContext(0)
    , mScreen(QXlibScreen::testLiteScreenForWidget(window))
{
    int x = window->x();
    int y = window->y();
    int w = window->width();
    int h = window->height();

#if !defined(QT_NO_OPENGL)
    if(window->platformWindowFormat().windowApi() == QPlatformWindowFormat::OpenGL
            && QApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::OpenGL)
            || window->platformWindowFormat().alpha()) {
#if !defined(QT_OPENGL_ES_2)
        XVisualInfo *visualInfo = qglx_findVisualInfo(mScreen->display()->nativeDisplay(),mScreen->xScreenNumber(),window->platformWindowFormat());
#else
        QPlatformWindowFormat windowFormat = correctColorBuffers(window->platformWindowFormat());

        EGLDisplay eglDisplay = mScreen->eglDisplay();
        EGLConfig eglConfig = q_configFromQPlatformWindowFormat(eglDisplay,windowFormat);
        VisualID id = QXlibEglIntegration::getCompatibleVisualId(mScreen->display()->nativeDisplay(), eglDisplay, eglConfig);

        XVisualInfo visualInfoTemplate;
        memset(&visualInfoTemplate, 0, sizeof(XVisualInfo));
        visualInfoTemplate.visualid = id;

        XVisualInfo *visualInfo;
        int matchingCount = 0;
        visualInfo = XGetVisualInfo(mScreen->display()->nativeDisplay(), VisualIDMask, &visualInfoTemplate, &matchingCount);
#endif //!defined(QT_OPENGL_ES_2)
        if (visualInfo) {
            mDepth = visualInfo->depth;
            mFormat = (mDepth == 32) ? QImage::Format_ARGB32_Premultiplied : QImage::Format_RGB32;
            mVisual = visualInfo->visual;
            Colormap cmap = XCreateColormap(mScreen->display()->nativeDisplay(), mScreen->rootWindow(), visualInfo->visual, AllocNone);

            XSetWindowAttributes a;
            a.background_pixel = WhitePixel(mScreen->display()->nativeDisplay(), mScreen->xScreenNumber());
            a.border_pixel = BlackPixel(mScreen->display()->nativeDisplay(), mScreen->xScreenNumber());
            a.colormap = cmap;
            x_window = XCreateWindow(mScreen->display()->nativeDisplay(), mScreen->rootWindow(),x, y, w, h,
                                     0, visualInfo->depth, InputOutput, visualInfo->visual,
                                     CWBackPixel|CWBorderPixel|CWColormap, &a);
        } else {
            qFatal("no window!");
        }
    } else
#endif //!defined(QT_NO_OPENGL)
    {
        mDepth = mScreen->depth();
        mFormat = (mDepth == 32) ? QImage::Format_ARGB32_Premultiplied : QImage::Format_RGB32;
        mVisual = mScreen->defaultVisual();

        x_window = XCreateSimpleWindow(mScreen->display()->nativeDisplay(), mScreen->rootWindow(),
                                       x, y, w, h, 0 /*border_width*/,
                                       mScreen->blackPixel(), mScreen->whitePixel());
    }

#ifdef MYX11_DEBUG
    qDebug() << "QTestLiteWindow::QTestLiteWindow creating" << hex << x_window << window;
#endif

    XSetWindowBackgroundPixmap(mScreen->display()->nativeDisplay(), x_window, XNone);

    XSelectInput(mScreen->display()->nativeDisplay(), x_window,
                 ExposureMask | KeyPressMask | KeyReleaseMask |
                 EnterWindowMask | LeaveWindowMask | FocusChangeMask |
                 PointerMotionMask | ButtonPressMask |  ButtonReleaseMask |
                 ButtonMotionMask | PropertyChangeMask |
                 StructureNotifyMask);

    gc = createGC();

    Atom protocols[5];
    int n = 0;
    protocols[n++] = QXlibStatic::atom(QXlibStatic::WM_DELETE_WINDOW);        // support del window protocol
    protocols[n++] = QXlibStatic::atom(QXlibStatic::WM_TAKE_FOCUS);                // support take focus window protocol
//    protocols[n++] = QXlibStatic::atom(QXlibStatic::_NET_WM_PING);                // support _NET_WM_PING protocol
#ifndef QT_NO_XSYNC
    protocols[n++] = QXlibStatic::atom(QXlibStatic::_NET_WM_SYNC_REQUEST);        // support _NET_WM_SYNC_REQUEST protocol
#endif // QT_NO_XSYNC
    if (window->windowFlags() & Qt::WindowContextHelpButtonHint)
        protocols[n++] = QXlibStatic::atom(QXlibStatic::_NET_WM_CONTEXT_HELP);
    XSetWMProtocols(mScreen->display()->nativeDisplay(), x_window, protocols, n);
}
Ejemplo n.º 20
0
int
ui_init( int *argc, char ***argv )
{
  char *displayName=NULL;	/* Use default display */
  XWMHints *wmHints;
  XSizeHints *sizeHints;
  XClassHint *classHint;
  char *windowNameList=(char *)"Fuse",*iconNameList=(char *)"Fuse";
  XTextProperty windowName, iconName;
  unsigned long windowFlags;
  XSetWindowAttributes windowAttributes;

  /* Allocate memory for various things */

  if( ui_widget_init() ) return 1;

  if(!(wmHints = XAllocWMHints())) {
    fprintf(stderr,"%s: failure allocating memory\n", fuse_progname);
    return 1;
  }

  if(!(sizeHints = XAllocSizeHints())) {
    fprintf(stderr,"%s: failure allocating memory\n", fuse_progname);
    return 1;
  }

  if(!(classHint = XAllocClassHint())) {
    fprintf(stderr,"%s: failure allocating memory\n", fuse_progname);
    return 1;
  }

  if(XStringListToTextProperty(&windowNameList,1,&windowName) == 0 ) {
    fprintf(stderr,"%s: structure allocation for windowName failed\n",
	    fuse_progname);
    return 1;
  }

  if(XStringListToTextProperty(&iconNameList,1,&iconName) == 0 ) {
    fprintf(stderr,"%s: structure allocation for iconName failed\n",
	    fuse_progname);
    return 1;
  }

  /* Open a connection to the X server */

  if ( ( display=XOpenDisplay(displayName)) == NULL ) {
    fprintf(stderr,"%s: cannot connect to X server %s\n", fuse_progname,
	    XDisplayName(displayName));
    return 1;
  }

  /* Set up our error handler */
  xerror_expecting = xerror_error = 0;
  XSetErrorHandler( xerror_handler );

  xui_screenNum = DefaultScreen(display);

  /* Create the main window */

  xui_mainWindow = XCreateSimpleWindow(
    display, RootWindow( display, xui_screenNum ), 0, 0,
    DISPLAY_ASPECT_WIDTH, DISPLAY_SCREEN_HEIGHT, 0,
    BlackPixel( display, xui_screenNum ), WhitePixel( display, xui_screenNum )
  );

  /* Set standard window properties */

  sizeHints->flags = PBaseSize | PResizeInc | PMaxSize | PMinSize;

  sizeHints->base_width = 0;
  sizeHints->base_height = 0;

  sizeHints->min_width    =     DISPLAY_ASPECT_WIDTH;
  sizeHints->min_height   =     DISPLAY_SCREEN_HEIGHT;
  sizeHints->width_inc    =     DISPLAY_ASPECT_WIDTH;
  sizeHints->height_inc   =     DISPLAY_SCREEN_HEIGHT;
  sizeHints->max_width    = 3 * DISPLAY_ASPECT_WIDTH;
  sizeHints->max_height   = 3 * DISPLAY_SCREEN_HEIGHT;

  if( settings_current.aspect_hint ) {
    sizeHints->flags |= PAspect;
    sizeHints->min_aspect.x = 4;
    sizeHints->min_aspect.y = 3;
    sizeHints->max_aspect.x = 4;
    sizeHints->max_aspect.y = 3;
  }

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

  classHint->res_name=(char *)fuse_progname;
  classHint->res_class=(char *)"Fuse";

  XSetWMProperties(display, xui_mainWindow, &windowName, &iconName,
		   *argv, *argc, sizeHints, wmHints, classHint);

  XFree( windowName.value );
  XFree( iconName.value );
  XFree( sizeHints );
  XFree( wmHints );
  XFree( classHint );

  /* Ask the server to use its backing store for this window */

  windowFlags=CWBackingStore;
  windowAttributes.backing_store=WhenMapped;

  XChangeWindowAttributes(display, xui_mainWindow, windowFlags,
			  &windowAttributes);

  /* Select which types of event we want to receive */

  XSelectInput(display, xui_mainWindow, ExposureMask | KeyPressMask |
	       KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
	       StructureNotifyMask | FocusChangeMask | PointerMotionMask );

  {
    static XColor dummy = { 0, 0, 0, 0, 4, 0 };
    XGCValues xgc;
    GC gc;

    Pixmap mask =
      XCreatePixmap( display, RootWindow( display, xui_screenNum ), 1, 1, 1 );

    xgc.function = GXclear;
    gc = XCreateGC( display, mask, GCFunction, &xgc );
    XFillRectangle( display, mask, gc, 0, 0, 1, 1 );
    nullpointer = XCreatePixmapCursor( display, mask,mask, &dummy,&dummy, 0,0 );
    XFreePixmap( display, mask );
    XFreeGC( display, gc );
  }

  /* Ask to be notified of window close requests */

  delete_window_atom = XInternAtom( display, "WM_DELETE_WINDOW", 0 );
  XSetWMProtocols( display, xui_mainWindow, &delete_window_atom, 1 );

  if( xdisplay_init() ) return 1;

  /* And finally display the window */
  XMapWindow(display,xui_mainWindow);

  ui_mouse_present = 1;

  return 0;
}
Ejemplo n.º 21
0
int set_full_screen(Display *dpy) {
    signal(SIGUSR1, fake_right_button);
    fulldisplay = dpy;
    Window curwin, rootw;
    Cursor hand_cursor;
    int x1, y1, winx, winy;
    unsigned int mask;
    XEvent ev;
    int screen_num;

    if (!dpy) {
        fprintf(stderr, "WTPEN : cannot get default display\n");
        exit(1);
    }

    /* style for line */
    unsigned int line_width = 8;
    int line_style = LineSolid;
    int cap_style  = CapRound;
    int join_style = JoinRound;

    screen_num = DefaultScreen(dpy);
    rootw = DefaultRootWindow(dpy);

    if (rootw == None) {
        fprintf(stderr, "WTPEN : full screen mode cannot get root window\n");
        exit(1);
    }

    hand_cursor = XCreateFontCursor(dpy, XC_hand2);

    drawgc = XCreateGC(dpy, rootw, 0, NULL);			// hier wordt getekend (met xor)
    XSetSubwindowMode(dpy, drawgc, IncludeInferiors);
    XSetForeground(dpy, drawgc,
                   WhitePixel(dpy, screen_num)
                   ^ BlackPixel(dpy, screen_num));
    XSetLineAttributes(dpy, drawgc, line_width, line_style,
                       cap_style, join_style);
    XSetFunction(dpy, drawgc, GXandInverted);
    //XSetFunction(dpy, drawgc, GXxor);

    fprintf(stderr, "full screen mode grab button\n");
    XGrabButton(dpy, AnyButton, 0, rootw, False,
                ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | OwnerGrabButtonMask,
                GrabModeSync, GrabModeAsync, None, hand_cursor);

	while (1) {
		fprintf (stderr, "fullscreen\n");	// wordt bij tekenen aangeroepen
        XAllowEvents(dpy, SyncPointer, CurrentTime);
        XWindowEvent(dpy, rootw, ButtonPressMask|ButtonReleaseMask|ButtonMotionMask, &ev);

        switch(ev.type) {
        case ButtonPress:
            kill(getppid(), SIGUSR2);
            if(ev.xbutton.button != Button1) {
                int num;
                XUngrabButton(dpy, AnyButton, 0, rootw);
                XFlush(dpy);
                record_coordinate(0xff, 0xff);
                clear_draw_area(dpy, rootw, drawgc);
                num = get_coordinates_num();
                return num;
            }
            XQueryPointer(dpy, rootw,
                          &rootw, &curwin,
                          &x1, &y1,	//root x, root y
                          &winx, &winy,
                          &mask);
            record_coordinate(x1, y1);
            break;
        case ButtonRelease:
            if (ev.xbutton.button == Button1) {
                if (get_coordinates_num() == 2) {
                    free_coordinates();
                    XUngrabButton(dpy, AnyButton, 0, rootw);
                    forward_click_event(dpy, &ev);
                    XFlush(dpy);
                    return 0;
                }
                record_coordinate(0xff, 0x00);
                kill(getppid(), SIGALRM);
            }
            break;
        case MotionNotify:
            if (ev.xmotion.state & Button1MotionMask) {
                CoordinateList *cl_end;
                XQueryPointer(dpy, rootw,
                              &rootw, &curwin,
                              &x1, &y1,	//root x, root y
                              &winx, &winy,
                              &mask);
                cl_end = coordinate_list_end();
                if (cl_end) {
                    if (!(cl_end->x == 0xff && cl_end->y == 0x00)) {
                        XDrawLine(dpy, rootw,
                                  drawgc,
                                  x1,
                                  y1,
                                  cl_end->x,
                                  cl_end->y);
                        record_coordinate(x1, y1);
                    }
                } else {
                    record_coordinate(x1, y1);
                }
            }
            break;
        default:
            break;
        }
    }
    fprintf(stderr, "exit fullscreen\n");		// wordt nooit bereikt
    return 1;
}
Ejemplo n.º 22
0
Archivo: xdemo.c Proyecto: cuzz/xrdp
int main(int argc, char **argv)
{
    XEvent          evt;
    Colormap        colormap;
    struct timeval  tv;
    int             screenNumber;
    long            eventMask;
    unsigned long   white;
    unsigned long   black;
    Status          rc;
    int             iters;
    int             opt;
    int             draw_lines;
    int             draw_rects;
    int             draw_stipples;
    int             draw_fonts;
    int             draw_image;
    int             zero_counters;
    int             scroll_type;
    char            image_file[256];
    char            proxy_app[256];
    char            msg[4096];

    // set some defaults
    g_winWidth = 640;
    g_winHeight = 480;
    iters = 5000;
    draw_lines = 1;
    draw_rects = 1;
    draw_stipples = 1;
    draw_fonts = 1;
    draw_image = 1;
    g_delay_dur = 1000;
    scroll_type = SCROLL_SMOOTH1;
    zero_counters = 0;
    strcpy(image_file, "yosemite.bmp");
    strcpy(msg, "To be or not to be!");

    // process cmd line args
    opterr = 0;
    while ((opt = getopt(argc, argv, "lrsg:c:f:i:d:o:z:")) != -1)
    {
        switch (opt)
        {
        case 'g':
            if (sscanf(optarg, "%dx%d", &g_winWidth, &g_winHeight) != 2) {
                fprintf(stderr, "\nerror: invalid geometry specified\n\n");
                usage();
                return -1;
            }
            break;

        case 'c':
            if (sscanf(optarg, "%d", &iters) != 1) {
                fprintf(stderr, "\nerror: invalid count specified\n\n");
                usage();
                return -1;
            }
            break;

        case 'l':
            draw_lines = 1;
            draw_rects = 0;
            draw_stipples = 0;
            draw_fonts = 0;
            draw_image = 0;
            break;

        case 'r':
            draw_rects = 1;
            draw_lines = 0;
            draw_stipples = 0;
            draw_fonts = 0;
            draw_image = 0;
            break;

        case 's':
            draw_stipples = 1;
            draw_lines = 0;
            draw_rects = 0;
            draw_fonts = 0;
            draw_image = 0;
            break;

        case 'f':
            if (strlen(optarg) <= 0) {
                fprintf(stderr, "\nerror: -f option requires an argument\n\n");
                usage();
                return -1;
            }
            draw_fonts = 1;
            strncpy(msg, optarg, 4096);
            draw_lines = 0;
            draw_rects = 0;
            draw_stipples = 0;
            draw_image = 0;
            break;

        case 'i':
            if (strlen(optarg) <= 0) {
                fprintf(stderr, "\nerror: -i option requires an argument\n\n");
                usage();
                return -1;
            }
            draw_image = 1;
            strncpy(image_file, optarg, 255);
            draw_lines = 0;
            draw_rects = 0;
            draw_stipples = 0;
            draw_fonts = 0;
            break;

        case 'h':
            usage();
            return 0;
            break;

        case 'v':
            printf("xdemo Ver 1.0\n");
            return 0;
            break;

        case 'd':
            if (sscanf(optarg, "%d", &g_delay_dur) != 1) {
                fprintf(stderr, "\nerror: -d option requires an argument\n\n");
                usage();
                return -1;
            }
            break;

        case 'z':
            if (strlen(optarg) <= 0) {
                fprintf(stderr, "\nerror: invalid proxy application specified\n\n");
                usage();
                return -1;
            }
            strcpy(proxy_app, optarg);
	    printf("##### LK_TODO: proxy_app=%s\n", proxy_app);
            zero_counters = 1;
            break;

        case 'o':
            if (strcmp(optarg, "jump") == 0) {
                scroll_type = SCROLL_JUMP;
            }
            else if (strcmp(optarg, "smooth1") == 0) {
                scroll_type = SCROLL_SMOOTH1;
            }
            else if (strcmp(optarg, "smooth2") == 0) {
                scroll_type = SCROLL_SMOOTH2;
            }
            else if (strcmp(optarg, "smooth3") == 0) {
                scroll_type = SCROLL_SMOOTH3;
            }
            else if (strcmp(optarg, "smooth4") == 0) {
                scroll_type = SCROLL_SMOOTH4;
            }
            else {
                fprintf(stderr, "\ninvalid scroll type specified\n\n");
                usage();
                return -1;
            }
            break;

        default:
            usage();
            return -1;
        }
    }

    // must have at least one operation
    if ((!draw_lines) && (!draw_rects) && (!draw_stipples) &&
        (!draw_fonts) && (!draw_image)) {
        usage();
        return -1;
    }

    g_disp = XOpenDisplay(NULL);
    if (!g_disp) {
        dprint("error opening X display\n");
        exit(-1);
    }

    screenNumber = DefaultScreen(g_disp);
    white = WhitePixel(g_disp, screenNumber);
    black = BlackPixel(g_disp, screenNumber);

    g_win = XCreateSimpleWindow(g_disp,
                                DefaultRootWindow(g_disp),
                                50, 50,                  // origin
                                g_winWidth, g_winHeight, // size
                                0, black,                // border
                                white );                 // backgd

    XMapWindow(g_disp, g_win);
    //eventMask = StructureNotifyMask | MapNotify | VisibilityChangeMask;
    eventMask = StructureNotifyMask | VisibilityChangeMask;
    XSelectInput(g_disp, g_win, eventMask);

    g_gc = XCreateGC(g_disp, g_win,
        0,                       // mask of values
        NULL );                  // array of values
    #if 0
    do
    {
        dprint("about to call XNextEvent(...)\n");
        XNextEvent(g_disp, &evt);// calls XFlush
        dprint("returned from XNextEvent(...)\n");
    }
    //while(evt.type != MapNotify);
    while(evt.type != VisibilityNotify);
    #endif

    // get access to the screen's color map
    colormap = DefaultColormap(g_disp, screenNumber);

    // alloc red color
    rc = XAllocNamedColor(g_disp, colormap, "red", &g_colors[0], &g_colors[0]);
    if (rc == 0) {
        printf("XAllocNamedColor - failed to allocated 'red' color.\n");
        exit(1);
    }

    rc = XAllocNamedColor(g_disp, colormap, "green", &g_colors[1], &g_colors[1]);
    if (rc == 0) {
        printf("XAllocNamedColor - failed to allocated 'green' color.\n");
        exit(1);
    }

    rc = XAllocNamedColor(g_disp, colormap, "blue", &g_colors[2], &g_colors[2]);
    if (rc == 0) {
        printf("XAllocNamedColor - failed to allocated 'blue' color.\n");
        exit(1);
    }
    rc = XAllocNamedColor(g_disp, colormap, "yellow", &g_colors[3], &g_colors[3]);
    if (rc == 0) {
        printf("XAllocNamedColor - failed to allocated 'yellow' color.\n");
        exit(1);
    }
    rc = XAllocNamedColor(g_disp, colormap, "orange", &g_colors[4], &g_colors[4]);
    if (rc == 0) {
        printf("XAllocNamedColor - failed to allocated 'orange' color.\n");
        exit(1);
    }

    if (zero_counters) {
        signal_tcp_proxy(proxy_app);
    }

    if (draw_lines) {
        start_timer(&tv);
        drawLines(iters);
        printf("drew %d lines in %d ms\n", iters, time_elapsed_ms(tv));
    }

    if (draw_rects) {
        start_timer(&tv);
        drawRectangles(iters);
        printf("drew %d rects in %d ms\n", iters, time_elapsed_ms(tv));
    }

    if (draw_stipples) {
        start_timer(&tv);
        // LK_TODO
    }

    if (draw_fonts) {
        start_timer(&tv);
    	drawFont(iters, msg);
        printf("drew %d strings in %d ms\n", iters, time_elapsed_ms(tv));
    }

    if (draw_image) {
        start_timer(&tv);
        drawBMP(image_file, scroll_type);
        printf("drew BMP in %d ms\n", time_elapsed_ms(tv));
    }

    if (zero_counters) {
        signal_tcp_proxy(proxy_app);
    }

    eventMask = ButtonPressMask|ButtonReleaseMask;

    XSelectInput(g_disp, g_win, eventMask);

    do
    {
        XNextEvent(g_disp, &evt); // calls XFlush()
    }
    while(evt.type != ButtonRelease);

    XDestroyWindow(g_disp, g_win);
    XCloseDisplay(g_disp);

    return 0;
}
Ejemplo n.º 23
0
void init_window(int argc, char *argv[])
{
   unsigned long get_color_pix(char *color_name);

   screen = DefaultScreen(display);

#if defined(HAVE_BZERO) && !defined(HAVE_MEMSET)
   bzero(&xsh, sizeof(xsh));
#else
   memset(&xsh, 0, sizeof(xsh));
#endif

   if (geometry) {
      int bitmask;

      bitmask = XGeometry(display, screen, geometry, NULL,
                          bwidth, 1, 1, 1, 1,
                          &(xsh.x), &(xsh.y), &(xsh.width), &(xsh.height));
      if (bitmask & (XValue | YValue)) {
         xsh.flags |= USPosition;
      }
      if (bitmask & (WidthValue | HeightValue)) {
         xsh.flags |= USSize;
      }
   } else {
      xsh.flags = USPosition | PSize;
      if (!landscape) {
         xsh.width = XLENG / shrink;
         xsh.height = YLENG / shrink;
         xsh.x = X0;
         xsh.y = Y0;
      } else {
         xsh.width = YLENG / shrink;
         xsh.height = XLENG / shrink;
         xsh.x = X0_LAND;
         xsh.y = Y0;
      }
   }

   /**  Color  **/
#ifdef COLOR_BUG
   reverse = 1;
#endif
   if (DisplayPlanes(display, screen) >= 3) {
      c_flg = 1;
      if (!reverse) {
         forepix = get_color_pix(fore_color);
         backpix = get_color_pix(back_color);
         highpix = get_color_pix(high_color);
         brdrpix = get_color_pix(brdr_color);
         mouspix = get_color_pix(mous_color);
      } else {
         forepix = get_color_pix(back_color);
         backpix = get_color_pix(fore_color);
         highpix = get_color_pix(high_color);
         brdrpix = get_color_pix(brdr_color);
         mouspix = get_color_pix(mous_color);
      }
   } else {
      if (!reverse) {
         forepix = BlackPixel(display, screen);
         highpix = BlackPixel(display, screen);
         backpix = WhitePixel(display, screen);
         brdrpix = BlackPixel(display, screen);
         mouspix = BlackPixel(display, screen);
      } else {
         forepix = WhitePixel(display, screen);
         highpix = WhitePixel(display, screen);
         backpix = BlackPixel(display, screen);
         brdrpix = WhitePixel(display, screen);
         mouspix = WhitePixel(display, screen);
      }
   }


   /**  Generate Window  **/
   main_window = XCreateSimpleWindow(display, DefaultRootWindow(display),
                                     xsh.x, xsh.y, xsh.width, xsh.height,
                                     bwidth, brdrpix, backpix);

   XSetStandardProperties(display, main_window, windowtitle, windowtitle,
                          None, argv, argc, &xsh);

   /* winatt.bit_gravity = SouthWestGravity; */
   XChangeWindowAttributes(display, main_window, CWBitGravity, &winatt);

   /**  Map Window  **/
   XSelectInput(display, main_window, StructureNotifyMask);
   XMapWindow(display, main_window);
   for (;;) {
      XNextEvent(display, &ev);
      if (ev.type == MapNotify)
         break;
   }
   XSelectInput(display, main_window,
                ButtonPressMask | PointerMotionMask | KeyPressMask |
                ExposureMask);
   /*  KeyReleaseMask|ExposureMask|StructureNotifyMask);
    */
   /**  Cursor  **/
   watch_cur = XCreateFontCursor(display, XC_watch);
   XDefineCursor(display, main_window, watch_cur);

   /**  GC  **/
   gcval.line_width = 1;
   gc = XCreateGC(display, main_window, GCLineWidth, &gcval);

   XSetFunction(display, gc, GXcopy);
   XSetGraphicsExposures(display, gc, False);
   XSetForeground(display, gc, forepix);
   XSetBackground(display, gc, backpix);

   font = XLoadFont(display, f_name[fno]);
   XSetFont(display, gc, font);
}
Ejemplo n.º 24
0
static void gui_draw_xor_box(GC gc, int x, int y, int width, int height)
{
    XSetForeground(gui->display, gc, WhitePixel(gui->display, gui->screen) ^ BlackPixel(gui->display, gui->screen));
    XDrawRectangle(gui->display, gui->root, gc, x, y, width, height);
}
Ejemplo n.º 25
0
	int main(int argc, char **argv)
	{
		static char *string = "Hello World!";
		Display *display;
		int screen_num;
		Window win;			//窗口ID
		unsigned int width, height;	//窗口尺寸
		unsigned int border_width = 0;	//边界空白
		unsigned int display_width, display_height;//屏幕尺寸
		int count;
		XEvent report;
		GC gc;
		unsigned long valuemask = 0;
		XGCValues values;
		char *display_name = NULL;
		//attribute vars
	        XSizeHints size_hints;
		XSetWindowAttributes attrib;
		unsigned long attribmask;
		//moving window
		Window root, child;
		unsigned int mask;
		int root_x, root_y, win_x, win_y, orig_x, orig_y;
	
		// 和X 服务器连接
		if ( (display=XOpenDisplay(display_name)) == NULL )
		{
			printf("Cannot connect to X server %s\n", 
					XDisplayName(display_name));
			exit(-1);
		}

		//获得缺省的 screen_num
		screen_num = DefaultScreen(display);

		//获得屏幕的宽度和高度
		display_width = DisplayWidth(display, screen_num);
		display_height = DisplayHeight(display, screen_num);
	
		//指定所建立窗口的宽度和高度
		width = display_width/3;
		height = display_height/4;
	
		//建立窗口
		win = XCreateSimpleWindow(display, 	//display
			RootWindow(display,screen_num), //父窗口
			100, 100, width, height, 		//位置和大小
			border_width, 			//边界宽度
			BlackPixel(display,screen_num), //前景色
			WhitePixel(display,screen_num));//背景色

		//设置属性
		attrib.override_redirect = True;
		attribmask = CWOverrideRedirect;
		XChangeWindowAttributes(display, win, attribmask, &attrib);


	
		//选择窗口感兴趣的事件掩码
		XSelectInput(display, win, 
			ExposureMask | KeyPressMask | 
			ButtonMotionMask | ButtonPressMask | ButtonReleaseMask
			| StructureNotifyMask);

		//建立GC
		gc = DefaultGC(display, screen_num);

		//显示窗口
		XMapWindow(display, win);

		//设置为键盘聚焦窗口
		XSetInputFocus(display, win, False, CurrentTime);

		//进入事件循环
		while (1)  {

			//取得队列中的事件
			XNextEvent(display, &report);
			switch  (report.type) {

			//曝光事件, 窗口应重绘
			case Expose:
				//取得最后一个曝光事件
				if (report.xexpose.count != 0) break;
				draw(display, win, gc);
				break;

			//窗口尺寸改变, 重新取得窗口的宽度和高度
			case ConfigureNotify:
				break;

			//取得位置
			case ButtonPress:
				//把窗口浮动到最上方
				XRaiseWindow(display, win);
				//设置键盘聚焦
				XSetInputFocus(display, win, False,CurrentTime);
				//取得指针相对于根窗口的位置和窗口的位置
				XQueryPointer(display,win,&root,&child,
					&root_x, &root_y, &win_x, &win_y,
					&mask);
				orig_x = root_x - win_x;
				orig_y = root_y - win_y;
				break;
			case MotionNotify:
				{
				int rx, ry, winx, winy;
				//取得指针相对于根窗口的位置和窗口的位置
				XQueryPointer(display,win,&root,&child,
                                        &rx, &ry, &winx, &winy, &mask);
				//移动窗口
				XMoveWindow(display, win, 
					rx - root_x + orig_x,
					ry - root_y + orig_y);
				}
				break;
			case ButtonRelease:
				break;
			case KeyPress:
				{
				char buffer[1024] = "";
				KeySym keysym;     //按键符号
				int count;         //返回的buffer中内容的长度
				XComposeStatus compose; //Compose状态
                                XWindowAttributes xa;
                                unsigned int w, h;

                                XGetWindowAttributes(display,win,&xa);
				w = xa.width; h = xa.height;

				//尖头移动窗口
				count = XLookupString(&report.xkey,buffer, 1024,
                                        &keysym, &compose);
				if(keysym == XK_Up){
					if(h > 10) h -= 2;
					//改变窗口大小
					XResizeWindow(display, win, w, h);
				} else if(keysym == XK_Down) {
					h += 2;
					XResizeWindow(display, win, w, h);
				} else if(keysym == XK_Left) {
					if(w > 10) w -= 2;
					XResizeWindow(display, win, w, h);
				} else if(keysym == XK_Right) {
					w += 2;
					XResizeWindow(display, win, w, h);
				} else if(keysym == XK_Escape) {
					exit(0);
				}
				}
				break;
			default:
				
				break;
			}
		}
	}
Ejemplo n.º 26
0
void
gui_move_window(winlist_t *win)
{
    xccore_t *xccore = (xccore_t *)win->data;
    int event_x, event_y;
    int offset_x, offset_y;
    int move_x, move_y;
    GC  moveGC;
    int draw_flag = False;
    int workarea_x, workarea_y;
    int workarea_x2, workarea_y2;
    unsigned int workarea_width, workarea_height;

    gui_get_workarea(&workarea_x, &workarea_y,
			&workarea_width, &workarea_height);

    workarea_x2 = workarea_x + workarea_width;
    workarea_y2 = workarea_y + workarea_height;

    gui_get_mouse_xy(&event_x, &event_y);
    offset_x = event_x - win->pos_x;
    offset_y = event_y - win->pos_y;

    moveGC = XCreateGC(gui->display, gui->root, 0, NULL);
    XSetSubwindowMode(gui->display, moveGC, IncludeInferiors);
    XSetForeground(gui->display, moveGC, BlackPixel(gui->display, gui->screen));
    XSetFunction(gui->display, moveGC, GXxor);

    XChangeActivePointerGrab(gui->display,
                PointerMotionMask | ButtonMotionMask | ButtonReleaseMask |
                OwnerGrabButtonMask, None, CurrentTime);

    XGrabServer(gui->display);

    XEvent myevent;
    while(1)
    {
	XNextEvent(gui->display, &myevent);
	switch(myevent.type)
	{
	    case ButtonRelease:
		if(myevent.xbutton.button == Button1)
		{
		    if (draw_flag)
		    {
			gui_draw_xor_box(moveGC, move_x - offset_x, move_y - offset_y, win->width, win->height);
		    }
		    XFreeGC(gui->display, moveGC);
		    gui_get_mouse_xy(&move_x, &move_y);
		    win->pos_x = move_x - offset_x;
		    win->pos_y = move_y - offset_y;

		    /* */
		    if (win->pos_x < workarea_x)
			win->pos_x = workarea_x;
		    if (win->pos_y < workarea_y)
			win->pos_y = workarea_y;
		    if (win->pos_x + win->width > workarea_x2)
			win->pos_x = workarea_x2 - win->width - 2;
		    if (win->pos_y + win->height > workarea_y2)
			win->pos_y = workarea_y2 - win->height - 2;

		    XMoveWindow(gui->display, win->window,
				 win->pos_x, win->pos_y);
		    XUngrabServer(gui->display);
		    gui_save_window_pos(); /* 儲存視窗位置 */
		    return;
		}
		break;

	    case MotionNotify:
		if (draw_flag)
		{
		    gui_draw_xor_box(moveGC, move_x - offset_x, move_y - offset_y, win->width, win->height);
		}
		gui_get_mouse_xy(&move_x, &move_y);
		gui_draw_xor_box(moveGC, move_x - offset_x, move_y - offset_y, win->width, win->height);
		draw_flag = True;
		break;
	    default:
		break;
	}
    }
}
Ejemplo n.º 27
0
ibool   MGLAPI XWINDC_initDriver(void *data,MGLDC *dc,int driverId,int modeId,ulong hwnd,
                                 int virtualX,int virtualY,int numBuffers,ibool stereo,int refreshRate)
/****************************************************************************
*
* Function:     XWINDC_initDriver
* Parameters:   dc  - Device context.
* Returns:      True if the device was correctly initialised.
*
* Description:  Initialises the device driver, and starts the specified
*               graphics mode. This is also where we fill in all of the
*               vectors in the device context to initialise our device
*               context properly.
*
****************************************************************************/
{
    Screen *scr;
    XSetWindowAttributes xswa;
    Display *dpy = dc->wm.xwindc.dpy;
    XVisualInfo *visinfo, vis;
    int nvis, npfv;
    Window root;
    int x,y;
    unsigned int w,h, bw, d;
    XPixmapFormatValues *pfv;

    _MGL_initInternal();
    dc->deviceType = MGL_WINDOWED_DEVICE;
    dc->xInch = dc->yInch = 0;

    g_state.d.hardwareCursor = false;

    dc->v = &g_state;
    dc->v->m.refCount++;
    dc->wm.xwindc.scr = scr = DefaultScreenOfDisplay(dpy);
    dc->wm.xwindc.gc  = DefaultGCOfScreen(scr);

    xswa.background_pixel = BlackPixel(dpy,XScreenNumberOfScreen(scr));
    xswa.backing_store = Always;

    dc->wm.xwindc.wnd = hwnd;
    XGetGeometry(dpy, hwnd, &root, &x, &y, &w, &h, &bw, &d);

    dc->mi.xRes = w;
    dc->mi.yRes = h;
    dc->mi.maxPage = 0;
    dc->mi.bytesPerLine = 0;
    dc->mi.pageSize = 0;
    dc->surface = NULL;
    dc->mi.bitsPerPixel = dc->wm.xwindc.depth = d;

    vis.visualid = XVisualIDFromVisual(DefaultVisual(dpy, XScreenNumberOfScreen(scr)));
    visinfo = XGetVisualInfo(dpy, VisualIDMask, &vis, &nvis);

    pfv = XListPixmapFormats(dpy, &npfv);
    switch (d) {
        case 8: dc->mi.maxColor = 0xFFUL;       break;
        case 15:    dc->mi.maxColor = 0x7FFFUL;     dc->pf= _MGL_pixelFormats[pfRGB555]; break;
        case 16:    dc->mi.maxColor = 0xFFFFUL;     dc->pf= _MGL_pixelFormats[visinfo->green_mask==0x7e0 ? pfRGB565 : pfRGB555]; break;
        case 24: {
            int i;
            dc->mi.maxColor = 0xFFFFFFUL;
            for(i=0; i<npfv; i++)
                if(pfv[i].depth == 24) break;
            if(pfv[i].bits_per_pixel==32){
                dc->mi.bitsPerPixel = 32;
                dc->pf= _MGL_pixelFormats[pfARGB32];
            }else
                dc->pf= _MGL_pixelFormats[pfRGB24];
            break;
            }
        case 32:    dc->mi.maxColor = 0xFFFFFFFFUL; dc->pf= _MGL_pixelFormats[pfARGB32]; break;
        }

    XFree(visinfo);

    if(d == 8){
        // Set up the private colormap if necesary
        dc->wm.xwindc.hpal = xswa.colormap = XCreateColormap(dpy, hwnd, DefaultVisualOfScreen(scr), AllocAll);
        XChangeWindowAttributes(dpy, hwnd, CWColormap, &xswa);
        }

    XMapRaised(dpy, hwnd);
    XClearWindow(dpy, hwnd);

    XWIN_initInternal(dc);
    dc->v->w.destroy = destroyDC;
    dc->r.realizePalette = XWIN_realizePalette;
    dc->r.getDefaultPalette = XWIN_getDefaultPalette;
    dc->r.putImage = XWIN_putImage;
    return true;
}
void XMessageBox::repaint()
{
   int white = WhitePixel(mDisplay, DefaultScreen(mDisplay));
   int black = BlackPixel(mDisplay, DefaultScreen(mDisplay));

   int x = 0;
   int y = 0;

   // line V margin
   y = y + MessageBox_LineVMargin * 2;

   // line H margin 
   x = MessageBox_LineHMargin;

   XSetForeground(mDisplay, mGC, black);
   for (unsigned int i = 0; i < mMessageLines.size(); ++i)
   {
      XDrawString(mDisplay, mWin, mGC, x, y, mMessageLines[i], 
         strlen(mMessageLines[i]));
      if (i < (mMessageLines.size() - 1))
         y = y + MessageBox_LineSpacer + mFontHeight;
   }
   XFlush(mDisplay);

   // line V margin
   y = y + MessageBox_LineVMargin;

   int maxButWidth = MessageBox_ButtonBoxWidth;
   int maxButHeight = MessageBox_ButtonBoxHeight;

   // compute size of text labels on buttons
   int fgColor, bgColor;

   int fontDirection, fontAscent, fontDescent;
   Vector<XMessageBoxButton>::iterator iter;
   for (iter = mButtons.begin(); iter != mButtons.end(); ++iter)
   {
      XCharStruct strInfo;
      XTextExtents(mFS, iter->getLabel(), strlen(iter->getLabel()), 
         &fontDirection, &fontAscent, &fontDescent,
         &strInfo);
//       if (maxButWidth < strInfo.width)
//          maxButWidth = strInfo.width;
//       if (maxButHeight < (strInfo.ascent + strInfo.descent))
//          maxButHeight = (strInfo.ascent + strInfo.descent);
      iter->setLabelWidth(strInfo.width);
   }
   int buttonBoxWidth = maxButWidth;
   int buttonBoxHeight = maxButHeight;

   // draw buttons
   // button V margin
   y = y + MessageBox_ButtonVMargin;

   // center the buttons 
   x = MessageBox_ButtonHMargin + (mMBWidth - getButtonLineWidth()) / 2;

   for (iter = mButtons.begin(); iter != mButtons.end(); ++iter)
   {
      if (iter->drawReverse())
      {
         fgColor = white;
         bgColor = black;
      }
      else
      {
         fgColor = black;
         bgColor = white;
      }

      XSetForeground(mDisplay, mGC, bgColor);
      XFillRectangle(mDisplay, mWin, mGC, x, y, 
         buttonBoxWidth, buttonBoxHeight);
      XSetForeground(mDisplay, mGC, fgColor);
      XDrawRectangle(mDisplay, mWin, mGC, x, y, 
         buttonBoxWidth, buttonBoxHeight);
      XDrawString(mDisplay, mWin, mGC, 
         x + ((buttonBoxWidth - iter->getLabelWidth()) / 2),
         y + mFontAscent + ((buttonBoxHeight - mFontAscent) / 2),
         iter->getLabel(),
         strlen(iter->getLabel()));
      iter->setButtonRect(x, y, buttonBoxWidth, buttonBoxHeight);
      x = x + buttonBoxWidth + MessageBox_ButtonSpacer;
   }   
}
Ejemplo n.º 29
0
static gboolean
skype_connect()
{
	Window root;
	Atom skype_inst;
	Atom type_ret;
	int format_ret;
	unsigned long nitems_ret;
	unsigned long bytes_after_ret;
	unsigned char *prop;
	int status;
	
	x11_error_code = 0;
	XSetErrorHandler(x11_error_handler);
	skype_debug_info("skype_x11", "Set the XErrorHandler\n");
#ifdef USE_XVFB_SERVER	
	if (!getenv("SKYPEDISPLAY"))
		setenv("SKYPEDISPLAY", ":25", 0);
#endif
	if (getenv("SKYPEDISPLAY"))
		disp = XOpenDisplay(getenv("SKYPEDISPLAY"));
	else
		disp = XOpenDisplay(getenv("DISPLAY"));
	if (disp == NULL)
	{
		skype_debug_info("skype_x11", "Couldn't open display\n");
		return FALSE;
	}
	skype_debug_info("skype_x11", "Opened display\n");
	message_start = XInternAtom( disp, "SKYPECONTROLAPI_MESSAGE_BEGIN", False );
	message_continue = XInternAtom( disp, "SKYPECONTROLAPI_MESSAGE", False );
	root = DefaultRootWindow( disp );
	win = XCreateSimpleWindow( disp, root, 0, 0, 1, 1,
		0, BlackPixel( disp, DefaultScreen( disp ) ),
		BlackPixel( disp, DefaultScreen( disp ) ));
	XFlush(disp);
	if (win == None)
	{
		XCloseDisplay(disp);
		disp = NULL;
		skype_debug_info("skype_x11", "Could not create X11 messaging window\n");
		return FALSE;
	}
	skype_debug_info("skype_x11", "Created X11 messaging window\n");
	skype_inst = XInternAtom(disp, "_SKYPE_INSTANCE", True);
	if (skype_inst == None)
	{
		XDestroyWindow(disp, win);
		XCloseDisplay(disp);
		win = (Window)None;
		disp = NULL;
		skype_debug_info("skype_x11", "Could not create skype Atom\n");
		return FALSE;
	}
	skype_debug_info("skype_x11", "Created skype Atom\n");
	status = XGetWindowProperty(disp, root, skype_inst, 0, 1, False, XA_WINDOW, &type_ret, &format_ret, &nitems_ret, &bytes_after_ret, &prop);
	if(status != Success || format_ret != 32 || nitems_ret < 1)
	{
		XDestroyWindow(disp, win);
		XCloseDisplay(disp);
		win = (Window)None;
		XFree(prop);
		disp = NULL;
		skype_debug_info("skype", "Skype instance not found\n");
		return FALSE;
	}
	skype_debug_info("skype_x11", "Skype instance found\n");
	skype_win = * (const unsigned long *) prop & 0xffffffff;
	XFree(prop);
	run_loop = TRUE;
	
	skype_debug_info("skype_x11", "Charging lasers...\n");
	receiving_thread = g_thread_create((GThreadFunc)receive_message_loop, NULL, FALSE, NULL);
	
	return TRUE;
}
Ejemplo n.º 30
0
// #includ ur #life
int main(int argc, char *argv[]) {
  bool q = false;
  if(argv[1] != NULL && strcmp(argv[1], "-q") == 0) q=true;
  Display *disp;
  Window win;
  XEvent e;
  int screen;
  int winy = 0;
  int winx = 0;
  int winheight = 300;
  int winwidth = 500;
  int borderwidth = 10;
  int stdcposx = 20;
  int stdcposy = 20;
  int cposx = stdcposx;
  int cposy = stdcposy;
  int lastdeltime = 0;
  int lastrowlength = 0;
  int lastkeysym = 0;
  char *msg = "Clear";
  int bwidth=strlen(msg)*6;
  int bheight=15;
  int btop=20;
  int bmargin = 2;
  int bleft=winwidth - bwidth - 20;
  GC white;
  XColor white_color;
  Colormap colormap;
  char whiteidk[] = "#FFFFFF";
  GC red;
  XColor red_color;
  Colormap rcolormap;
  char redidk[] = "#FF0000";

  disp = XOpenDisplay(NULL);
  if (disp == NULL) {
    fprintf(stderr, "Cannot open display\n");
    exit(1);
  }

  screen = DefaultScreen(disp);
  win = XCreateSimpleWindow(disp, RootWindow(disp, screen), winx, winy, winwidth, winheight, borderwidth,
  BlackPixel(disp, screen), WhitePixel(disp, screen));
  XSelectInput(disp, win, ExposureMask | KeyPressMask | ButtonPressMask);
  // Window XCreateWindow(display, parent, x, y, width, height, border_width, depth,
  //                    class, visual, valuemask, attributes)
  XMapWindow(disp, win);
  colormap = DefaultColormap(disp, 0);
  white = XCreateGC(disp, win, 0, 0);
  XParseColor(disp, colormap, whiteidk, &white_color);
  XAllocColor(disp, colormap, &white_color);
  XSetForeground(disp, white, white_color.pixel);
  rcolormap = DefaultColormap(disp, 0);
  red = XCreateGC(disp, win, 0, 0);
  XParseColor(disp, colormap, redidk, &red_color);
  XAllocColor(disp, colormap, &red_color);
  XSetForeground(disp, red, red_color.pixel);
  while (1) {
    XNextEvent(disp, &e);
    if (e.type == Expose)
      {
        XFillRectangle(disp, win, red, bleft, btop, bwidth, bheight);
        XDrawString(disp, win, white, bleft+bmargin, btop+bmargin+9, msg, strlen(msg));
        //http://tronche.com/gui/x/xlib/graphics/drawing-text/XDrawString.html
      }
      if(e.type == 4) // button press
        {
          int x=e.xbutton.x;
          int y=e.xbutton.y;
          int button = e.xbutton.button;
          if(!q) printf("Button pressed. X: %d, Y: %d Button: %d\n",x,y,button);
          if(button == 1)
            {
              if(y < bheight+btop && x < bwidth+bleft)
                {
                  if(y > btop && x > bleft)
                    {
                      if(!q) printf("You've hitten the button!!\nClearing...\n");
                      XFillRectangle(disp, win, white, 0, 0, winwidth, winheight);
                      cposx = stdcposx;
                      cposy = stdcposy;
                      if(!q) printf("Repainting clearbutton...\n");
                      XFillRectangle(disp, win, red, bleft, btop, bwidth, bheight);
                      XDrawString(disp, win, white, bleft+bmargin, btop+bmargin+9, msg, strlen(msg));
                    }
                  }
                }
              }
              if (e.type == KeyPress)
                {
                  if(!q) printf("Keycode: %d\n", e.xkey.keycode);
                  unsigned long keysym = XLookupKeysym(&e.xkey, 0);
                  if(!q) printf("Keysym: %lu\n",keysym);
                  char *ascii = XKeysymToString(keysym);
                  if(!q) printf("ASCII: %s\n",ascii);
                  if(keysym == 65307 && lastkeysym == 65406) // alt+ESC
                    {
                      printf("Exiting...\n");
                      return 0;
                    }
                    else if(keysym == 65293) // line break
                    {
                      cposy+=10;
                      lastrowlength = cposx;
                      cposx = stdcposx;
                    }
                    else if(keysym == 32) // " "
                    {
                      cposx+=6;
                    }
                    else if(keysym == 65288) // delete
                    {
                      time_t now = time(0);
                      if(!q) printf("Time: %ld\n",now);
                      int diff = now-lastdeltime;
                      if(!q) printf("Time since last deletion: %d\n",diff);
                      XFillRectangle(disp, win, white, cposx-6, cposy-9, 6, 11);
                      if(diff == 0)
                        {
                          XFillRectangle(disp, win, white, cposx-12, cposy-9, 6, 11);
                        }
                        lastdeltime = now;
                        if(cposx <= stdcposx)
                          {
                            if(cposy != stdcposy)
                              {
                                cposy-=10;
                                cposx = lastrowlength;
                              }
                            }
                            else
                              {
                                cposx-=6;
                                if(diff == 0 && cposx-6 > stdcposx)
                                  {
                                    cposx-=6;
                                  }
                                }
                              }
                              else if(keysym == 43) // plus
                              {
                                XDrawString(disp, win, DefaultGC(disp, screen), cposx, cposy, "+", 1);
                                cposx+=6;
                              }
                              else if(keysym == 44) // comma
                              {
                                XDrawString(disp, win, DefaultGC(disp, screen), cposx, cposy, ",", 1);
                                cposx+=6;
                              }
                              else if(keysym == 45) // minus
                              {
                                XDrawString(disp, win, DefaultGC(disp, screen), cposx, cposy, "-", 1);
                                cposx+=6;
                              }
                              else if(keysym == 46) // period
                              {
                                XDrawString(disp, win, DefaultGC(disp, screen), cposx, cposy, ".", 1);
                                cposx+=6;
                              }
                              else if(keysym == 65289) // tab
                              {
                                XDrawString(disp, win, DefaultGC(disp, screen), cposx, cposy, "   ", 3);
                                cposx+=18;
                              }
                              else
                                {
                                  if(lastkeysym != 65506 || lastkeysym != 65505)
                                    {
                                      if(keysym == 49)
                                        {
                                          ascii = "!";
                                        }
                                        else if(keysym == 43)
                                        {
                                          ascii = "?";
                                        }
                                      }
                                      if(keysym != 65506 && keysym != 65505)
                                        {
                                          XDrawString(disp, win, DefaultGC(disp, screen), cposx, cposy, ascii, strlen(ascii));
                                          cposx+=strlen(ascii)*6;
                                        }
                                      }
                                      lastkeysym = keysym;
                                    }
                                  }
                                  XCloseDisplay(disp);
                                  return 0;
                                }