示例#1
0
文件: color.c 项目: hsw28/mwsoft64
void alloc_color(int32_t i, int32_t r, int32_t g, int32_t b)
{
    XColor col;

    col.red =	r; col.green = g; col.blue = b;
    col.flags = DoRed | DoGreen | DoBlue;
    if (XAllocColor(G->display, cmap, &col))
    {
	idx[i].pixel = col.pixel;
    }else
    {
	if (cmap == DefaultColormap(G->display, G->screen_number))
	{
	    cmap = XCopyColormapAndFree(G->display, cmap);
	    XSetWindowColormap(G->display, G->imagewindow, cmap);
	    col.red =	r; col.green = g; col.blue = b;
	    col.flags = DoRed | DoGreen | DoBlue;
	    if (XAllocColor(G->display, cmap, &col))
	    {
		idx[i].pixel = col.pixel;
		fprintf(stderr,"allocating pixel %d: %d %d %d\n",i,r,g,b);
	    } else {
		fprintf(stderr,"unable to allocate color %d: %d %d %d\n",i,r,g,b);
	    }
	}
    }
}
示例#2
0
int gfx_init(char *title, int win_w, int win_h, char *font_path)
{
 e = evas_new();
 evas_set_output_method(e, RENDER_METHOD_ALPHA_SOFTWARE);

 if ((d = XOpenDisplay(NULL)) == NULL)
   return 0;

 vis = evas_get_optimal_visual(e, d);
 cmap = evas_get_optimal_colormap(e, d);
 a_win_del = XInternAtom(d, "WM_DELETE_WINDOW", False);
 
 win = XCreateSimpleWindow(d, DefaultRootWindow(d), 0, 0,
                           win_w, win_h, 0, 0, 0);
 
 XSelectInput(d, win, ButtonPressMask | ExposureMask);
 
 XSetWindowColormap(d, win, cmap);
 XSetWindowBorder(d, win, 0);
 
 XStoreName(d, win, title);
 
 XSync(d, False);
 XMapWindow(d, win);
 XSetWMProtocols(d, win, &a_win_del, 1);
 
 evas_set_output(e, d, win, vis, cmap);
 evas_set_output_size(e, win_w, win_h);
 evas_set_output_viewport(e, 0, 0, win_w, win_h);
 evas_font_add_path(e, font_path);

 return 1;
}
示例#3
0
文件: mikey1.1.c 项目: 10crimes/code
void redocolors() {
										
  int i;
  for (i = 0; i < COLORS; i++) {	/* Set up the colors gradient */
		// myRGB r=myRGB(thru,thru,thru);
		// myRGB r=( thru < 1 ? myRGB(0.0,thru*5.0,0.0)
						             // : myRGB(thru*2.0-1.0,1.0,thru*2.0-1.0)
						// );
    float thru=4.0*(float)((frameno*palspeed+i/2)%colors)/(float)COLORS;
		myRGB r;
		if (thru<1.0)
			r=myRGB(0.0,thru,0.0);
		else if (thru<2.0)
			r=myRGB(thru-1.0,1.0,thru-1.0);
		else if (thru<3.0)
			r=myRGB(1.0-(thru-2.0),1.0-(thru-2.0),1.0);
		else
			r=myRGB(0.0,0.0,1.0-(thru-3.0));

    #ifdef X11GFX
      xrgb[i].red = 65535 * r.r/255; // (1.0 - 1.0 * i / COLORS);
      xrgb[i].green = 65535 * r.g/255;
      xrgb[i].blue = 65535 * r.b/255;
      xrgb[i].flags = DoRed | DoGreen | DoBlue;
      xrgb[i].pixel=i;
    #endif

    #ifdef ALLEGRO
      RGB algrgb;
      algrgb.r=r.r/4;
      algrgb.g=r.g/4;
      algrgb.b=r.b/4;
      set_color(i,&algrgb);
    #endif

  }

    #ifdef X11GFX
			if (stylee == styleeTrueColor) {
        // XInstallColormap (d, colormap);
			  for (int i=0;i<colors;i++) {
				  if ( XAllocColor(d,colormap,&xrgb[i]) == 0 )
					  printf("Error allocating %i\n",i);
				  // works for true-color
			  }
			} else {
			XAllocColorCells(d,colormap,1,0,0,color,colors);

			  // for (int i=0;i<colors;i++) {
				  // xrgb[i].pixel=color[i];
			  // }
			  XStoreColors(d,colormap,xrgb,COLORS);
			  XSetWindowColormap(d,win,colormap);
        // fputs("Couldn't allocate enough colors cells.\n", 
        // stderr), exit(1);
			}

    #endif

}
示例#4
0
文件: mygraph.c 项目: ombt/ombt
// set up color map for a screen
int
SetUpColorMap(Display *display, int screen, 
	Window window, Visual *visual, Colormap &colormap)
{
	int status = NOTOK;

	// look for a pseudo-color visual
	if (visual == DefaultVisual(display, screen))
	{
		colormap = DefaultColormap(display, screen);
		status = OK;
	}
	else
	{
		if (visual == CopyFromParent) 
			visual = DefaultVisual(display, screen);
		colormap = XCreateColormap(display, window, visual, AllocNone);
		if (colormap != None)
		{
			XSetWindowColormap(display, window, colormap);
			status = OK;
		}
		else
		{
			colormap = DefaultColormap(display, screen);
		}
	}

	// all done 
	return(status);
}
示例#5
0
/* the following two functions change the colormap for 8-bit
   displays. They should check and do nothing on true color displays */
void ChooseColorMap(int which)
{

  Visual visual;
  XColor color;
  int i;

  if (dDepth!=8)return; /* only for 256 color display! */

  if (primo==0)
    {
      visual = *DefaultVisual(display, SCREEN);
      colormap= XCreateColormap(display, window, &visual, AllocAll); 
    }
  
  color.flags=DoRed | DoGreen | DoBlue;
  for (i=0; i< 256; i++)
    {
      color.pixel=i;
      color.red=0xffffL * ((long) (i+which) * 101 %256)/255L;
      color.green=0xffffL * ((long) (i+which) * 151 %256)/255L;
      color.blue=0xffffL * ((long) (i+which) * 171 %256)/255L;
      
      XStoreColor(display, colormap, &color);	  
    }
  
  if (primo==0)
    {
      XInstallColormap(display,colormap);
      XSetWindowColormap(display,window,colormap);
      primo=1;
    }
}
// Set up a window.
int initWindow( long width, long height ) {
  int defScreen;
  XSetWindowAttributes wAttr;
  XGCValues gcValues;
  char buffer[64] = "Graphics";
  XTextProperty xtp = {(unsigned char *)buffer, 125, 8, strlen(buffer)};

  /*
   * connect to the X server.  uses the server specified in the
   * DISPLAY environment variable
   */
  curDisplay = XOpenDisplay((char *) NULL);
  if ((Display *) NULL == curDisplay) {
    fprintf(stderr, "Fish School Stats Display:  could not open display.\n");
      exit(-1);
  }
   
  /*
   * begin to create a window
   */
  defdepth = DefaultDepth(curDisplay,0);
  bytesPerPixel = defdepth/8;
  bytesPerPixel = bytesPerPixel == 3 ? 4 : bytesPerPixel;

  defScreen = DefaultScreen(curDisplay);

  curWindow = XCreateWindow(curDisplay, DefaultRootWindow(curDisplay),
                            10, 10, width, height, 0, 
                            defdepth, InputOutput, 
                            DefaultVisual(curDisplay, defScreen),
                            0, &wAttr);


  /*
   * request mouse button and keypress events
   */
  wAttr.event_mask = ButtonPressMask | KeyPressMask | ExposureMask;
  XChangeWindowAttributes(curDisplay, curWindow, CWEventMask, &wAttr);

  /*
   * force it to appear on the screen
   */
  XSetWMName(curDisplay, curWindow, &xtp);
  XMapWindow(curDisplay, curWindow);

  /*
   * create a graphics context.  this stores a drawing state; stuff like
   * current color and line width.  this gc is for drawing into our
   * window. 
   */
  curGC = XCreateGC(curDisplay, curWindow, 0, &gcValues);
  defaultFont = XQueryFont(curDisplay, XGContextFromGC(curGC));

  XSetWindowColormap( curDisplay,
                      curWindow,
                      DefaultColormapOfScreen(DefaultScreenOfDisplay(curDisplay)));

  return(bytesPerPixel);
}
示例#7
0
void
setColormap(Display * display, Window window, Colormap cmap, Bool inwindow)
{
	XSetWindowColormap(display, window, cmap);
	/* Now, here we have a problem.  When we are running full-screen, the
	   window's override_redirect attribute is on.  So, the window manager
	   never gets the ColormapNotify event that gets generated on the
	   above XSetWindowColormap() call, and does not So, a quick solution
	   is to install it ourselves.  The problem with this is that it
	   violates the ICCCM convention that only window managers should
	   install colormaps. Indeed, Fvwm _enforces_ this by immediately
	   un-doing any XInstallColormap() performed by a client (which is why
	   this does not work right under Fvwm). */

	if (!inwindow) {
		XInstallColormap(display, cmap);
	}
}
示例#8
0
X11Tooltip::X11Tooltip( intf_thread_t *pIntf,
                                   X11Display &rDisplay ):
    OSTooltip( pIntf ), m_rDisplay( rDisplay )
{
    Window root = DefaultRootWindow( XDISPLAY );
    XSetWindowAttributes attr;
    // Bypass the window manager
    attr.override_redirect = True;

    // Create the window
    m_wnd = XCreateWindow( XDISPLAY, root, 0, 0, 1, 1, 0, 0,
                           InputOutput, CopyFromParent, CWOverrideRedirect,
                           &attr );

    // Set the colormap for 8bpp mode
    if( XPIXELSIZE == 1 )
    {
        XSetWindowColormap( XDISPLAY, m_wnd, m_rDisplay.getColormap() );
    }
}
示例#9
0
void
do_setcustompalette (XColor * inpal)
{
  int i, n, me = 0, flag[256], vid;
  int depth;
  long unsigned int plane_masks[3];
  XColor pal[256];
  int writeable_p;

  display.cmap = XDefaultColormap (display.dpy, display.screen);
  depth = DefaultDepth (display.dpy, display.screen);

  /* Decide, if the colormap is writable */
  {
    Visual *visual = DefaultVisual (display.dpy, display.screen);
#if defined(__cplusplus) || defined(c_plusplus)
    int visual_class = visual->c_class;
#else
    int visual_class = visual->class;
#endif
    writeable_p = (visual_class == PseudoColor || visual_class == GrayScale);
  }

  if (writeable_p)
    {
      if (XAllocColorCells (display.dpy, display.cmap, 0
			    ,plane_masks, 0, colour_table, 256) == 0)
	{
	  me = (*DefaultVisual (display.dpy, display.screen)).map_entries;
	  vid = (*DefaultVisual (display.dpy, display.screen)).visualid;
	  display.cmap = XCreateColormap (display.dpy, display.win
				,DefaultVisual (display.dpy, display.screen)
	  /*      ,PseudoColor */
					  ,AllocNone);
	  if (me == 256 && depth != 24)
	    {
	      if (XAllocColorCells (display.dpy, display.cmap, 0
				    ,plane_masks, 0, colour_table, 256) != 0) {
		  /* printf ("Allocated 256 cells\n"); */
	      }
	      else {
		  printf ("Couldn't allocate 256 cells\n");
	      }
	    }
	  else
	    for (i = 0; i < 256; i++)
	      colour_table[i] = i;
	}
      if (!display.cmap)
	HandleError ("No default colour map", FATAL);
    }

  for (i = 0; i < 256; i++)
    flag[i] = 0;

  for (n = 0; n < 256; n++)
    {
      pal[n].red = inpal[n].red << 10;
      pal[n].green = inpal[n].green << 10;
      pal[n].blue = inpal[n].blue << 10;
      pal[n].flags = DoRed | DoGreen | DoBlue;
      if (writeable_p)
	pal[n].pixel = colour_table[n];
      else
	{
	  if (XAllocColor (display.dpy
			   ,display.cmap, &(pal[n])) == 0)
	    HandleError ("alloc colour failed"
			 ,FATAL);
	  colour_table[n] = pal[n].pixel;
	  XSetForeground (display.dpy
			  ,display.pixcolour_gc[n]
			  ,colour_table[n]);
	}
      flag[n] = 1;
    }

  if (writeable_p)
    {
      XStoreColors (display.dpy, display.cmap, pal, 256);
      XFlush (display.dpy);
    }
  XSetWindowColormap (display.dpy, display.win, display.cmap);
}
示例#10
0
X11Window::X11Window( intf_thread_t *pIntf, GenericWindow &rWindow,
                      X11Display &rDisplay, bool dragDrop, bool playOnDrop,
                      X11Window *pParentWindow, GenericWindow::WindowType_t type ):
    OSWindow( pIntf ), m_rDisplay( rDisplay ), m_pParent( pParentWindow ),
    m_dragDrop( dragDrop ), m_pDropTarget( NULL ), m_type ( type )
{
    XSetWindowAttributes attr;
    unsigned long valuemask;
    std::string name_type;

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

        int i_screen = DefaultScreen( XDISPLAY );

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

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

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

        int i_screen = DefaultScreen( XDISPLAY );

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

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

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

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

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

        name_type = "TopWindow";
    }

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

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

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

    // Select events received by the window
    long event_mask;
    if( type == GenericWindow::VoutWindow )
    {
        event_mask =  ExposureMask|KeyPressMask|
                      LeaveWindowMask|FocusChangeMask;
    }
    else
    {
        event_mask =  ExposureMask|KeyPressMask|
                      PointerMotionMask|ButtonPressMask|ButtonReleaseMask|
                      LeaveWindowMask|FocusChangeMask;
    }
    XSelectInput( XDISPLAY, m_wnd, event_mask );

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

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

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

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

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

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

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

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

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

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

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

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

}
示例#11
0
void GlxContext::createContext(GlxContext* shared, unsigned int bitsPerPixel, const ContextSettings& settings)
{
    // Save the creation settings
    m_settings = settings;

    // Get the attributes of the target window
    XWindowAttributes windowAttributes;
    if (XGetWindowAttributes(m_display, m_window, &windowAttributes) == 0)
    {
        err() << "Failed to get the window attributes" << std::endl;
        return;
    }

    // Setup the visual infos to match
    XVisualInfo tpl;
    tpl.depth    = windowAttributes.depth;
    tpl.visualid = XVisualIDFromVisual(windowAttributes.visual);
    tpl.screen   = DefaultScreen(m_display);

    // Get all the visuals matching the template
    int nbVisuals = 0;
    XVisualInfo* visuals = XGetVisualInfo(m_display, VisualDepthMask | VisualIDMask | VisualScreenMask, &tpl, &nbVisuals);
    if (!visuals || (nbVisuals == 0))
    {
        if (visuals)
            XFree(visuals);
        err() << "There is no valid visual for the selected screen" << std::endl;
        return;
    }

    // Find the best visual
    int          bestScore  = 0xFFFF;
    XVisualInfo* bestVisual = NULL;
    for (int i = 0; i < nbVisuals; ++i)
    {
        // Get the current visual attributes
        int RGBA, doubleBuffer, red, green, blue, alpha, depth, stencil, multiSampling, samples;
        glXGetConfig(m_display, &visuals[i], GLX_RGBA,               &RGBA);
        glXGetConfig(m_display, &visuals[i], GLX_DOUBLEBUFFER,       &doubleBuffer); 
        glXGetConfig(m_display, &visuals[i], GLX_RED_SIZE,           &red);
        glXGetConfig(m_display, &visuals[i], GLX_GREEN_SIZE,         &green); 
        glXGetConfig(m_display, &visuals[i], GLX_BLUE_SIZE,          &blue); 
        glXGetConfig(m_display, &visuals[i], GLX_ALPHA_SIZE,         &alpha); 
        glXGetConfig(m_display, &visuals[i], GLX_DEPTH_SIZE,         &depth);        
        glXGetConfig(m_display, &visuals[i], GLX_STENCIL_SIZE,       &stencil);
        glXGetConfig(m_display, &visuals[i], GLX_SAMPLE_BUFFERS_ARB, &multiSampling);        
        glXGetConfig(m_display, &visuals[i], GLX_SAMPLES_ARB,        &samples);

        // First check the mandatory parameters
        if ((RGBA == 0) || (doubleBuffer == 0))
            continue;

        // Evaluate the current configuration
        int color = red + green + blue + alpha;
        int score = evaluateFormat(bitsPerPixel, m_settings, color, depth, stencil, multiSampling ? samples : 0);

        // Keep it if it's better than the current best
        if (score < bestScore)
        {
            bestScore  = score;
            bestVisual = &visuals[i];
        }
    }

    // Make sure that we have found a visual
    if (!bestVisual)
    {
        err() << "Failed to find a suitable pixel format for the window -- cannot create OpenGL context" << std::endl;
        return;
    }

    // Get the context to share display lists with
    GLXContext toShare = shared ? shared->m_context : NULL;

    // Create the OpenGL context -- first try context versions >= 3.0 if it is requested (they require special code)
    while (!m_context && (m_settings.majorVersion >= 3))
    {
        const GLubyte* name = reinterpret_cast<const GLubyte*>("glXCreateContextAttribsARB");
        PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = reinterpret_cast<PFNGLXCREATECONTEXTATTRIBSARBPROC>(glXGetProcAddress(name));
        if (glXCreateContextAttribsARB)
        {
            int nbConfigs = 0;
            GLXFBConfig* configs = glXChooseFBConfig(m_display, DefaultScreen(m_display), NULL, &nbConfigs);
            if (configs && nbConfigs)
            {
                // Create the context
                int attributes[] =
                {
                    GLX_CONTEXT_MAJOR_VERSION_ARB, static_cast<int>(m_settings.majorVersion),
                    GLX_CONTEXT_MINOR_VERSION_ARB, static_cast<int>(m_settings.minorVersion),
                    GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
                    0, 0
                };
                m_context = glXCreateContextAttribsARB(m_display, configs[0], toShare, true, attributes);
            }

            if (configs)
                XFree(configs);
        }

        // If we couldn't create the context, lower the version number and try again -- stop at 3.0
        // Invalid version numbers will be generated by this algorithm (like 3.9), but we really don't care
        if (!m_context)
        {
            if (m_settings.minorVersion > 0)
            {
                // If the minor version is not 0, we decrease it and try again
                m_settings.minorVersion--;
            }
            else
            {
                // If the minor version is 0, we decrease the major version
                m_settings.majorVersion--;
                m_settings.minorVersion = 9;
            }
        }
    }

    // If the OpenGL >= 3.0 context failed or if we don't want one, create a regular OpenGL 1.x/2.x context
    if (!m_context)
    {
        // set the context version to 2.0 (arbitrary)
        m_settings.majorVersion = 2;
        m_settings.minorVersion = 0;

        m_context = glXCreateContext(m_display, bestVisual, toShare, true);
        if (!m_context)
        {
            err() << "Failed to create an OpenGL context for this window" << std::endl;
            return;
        }
    }

    // Update the creation settings from the chosen format
    int depth, stencil, multiSampling, samples;
    glXGetConfig(m_display, bestVisual, GLX_DEPTH_SIZE,         &depth);
    glXGetConfig(m_display, bestVisual, GLX_STENCIL_SIZE,       &stencil);
    glXGetConfig(m_display, bestVisual, GLX_SAMPLE_BUFFERS_ARB, &multiSampling);        
    glXGetConfig(m_display, bestVisual, GLX_SAMPLES_ARB,        &samples);
    m_settings.depthBits         = static_cast<unsigned int>(depth);
    m_settings.stencilBits       = static_cast<unsigned int>(stencil);
    m_settings.antialiasingLevel = multiSampling ? samples : 0;

    // Change the target window's colormap so that it matches the context's one
    ::Window root = RootWindow(m_display, DefaultScreen(m_display));
    Colormap colorMap = XCreateColormap(m_display, root, bestVisual->visual, AllocNone);
    XSetWindowColormap(m_display, m_window, colorMap);

    // Free the temporary visuals array
    XFree(visuals);
}
示例#12
0
static void winopen(void)
{
	XWMHints *wmhints;
	XClassHint *classhint;

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

	XA_CLIPBOARD = XInternAtom(xdpy, "CLIPBOARD", False);
	XA_TARGETS = XInternAtom(xdpy, "TARGETS", False);
	XA_TIMESTAMP = XInternAtom(xdpy, "TIMESTAMP", False);
	XA_UTF8_STRING = XInternAtom(xdpy, "UTF8_STRING", False);
	WM_DELETE_WINDOW = XInternAtom(xdpy, "WM_DELETE_WINDOW", False);
	NET_WM_STATE = XInternAtom(xdpy, "_NET_WM_STATE", False);
	NET_WM_STATE_FULLSCREEN = XInternAtom(xdpy, "_NET_WM_STATE_FULLSCREEN", False);

	xscr = DefaultScreen(xdpy);

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

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

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

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

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

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

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

	mapped = 0;

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

	XDefineCursor(xdpy, xwin, xcarrow);

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

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

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

	x11fd = ConnectionNumber(xdpy);
}
示例#13
0
void
init_mandelbrot(ModeInfo * mi)
{
	Display    *display = MI_DISPLAY(mi);
	Window      window = MI_WINDOW(mi);
	mandelstruct *mp;

	if (mandels == NULL) {
		if ((mandels = (mandelstruct *) calloc(MI_NUM_SCREENS(mi),
					     sizeof (mandelstruct))) == NULL)
			return;
	}
	mp = &mandels[MI_SCREEN(mi)];
	mp->mi = mi;

	mp->screen_width = MI_WIDTH(mi);
	mp->screen_height = MI_HEIGHT(mi);
	mp->backwards = (Bool) (LRAND() & 1);
	if (mp->backwards)
		mp->column = mp->screen_width - 1;
	else
		mp->column = 0;
	mp->power = NRAND(3) + MINPOWER;
	mp->counter = 0;

	MI_CLEARWINDOW(mi);

	if (MI_IS_FULLRANDOM(mi)) {
		mp->binary = (Bool) (LRAND() & 1);
		mp->dem = (Bool) (LRAND() & 1);
		mp->interior = NRAND(interior_size);
#if 0
	/* too slow */
	  mp->pow = (NRAND(5) == 0);
	  mp->sin = (NRAND(5) == 0);
#endif
	} else {
	  mp->binary = binary_p;
	  mp->dem = dem_p;
	  if (index_p) {
		  mp->interior = INDEX;
	  } else if(alpha_p) {
		  mp->interior = ALPHA;
	  } else if(lyap_p) {
		  mp->interior = LYAPUNOV;
	  } else {
		  mp->interior = NONE;
	  }
	  mp->pow = pow_p;
	  mp->sin = sin_p;
	}

	mp->reptop = 300;

	/* these could be tuned a little closer, but the selection
	** process throws out the chaf anyway, it just takes slightly
	** longer
	*/
	mp->extreme_ul.real = -3.0;
	mp->extreme_ul.imag = -3.0;
	mp->extreme_lr.real = 3.0;
	mp->extreme_lr.imag = 3.0;

	if (!mp->gc) {
		if (MI_IS_INSTALL(mi) && MI_NPIXELS(mi) > 2) {
			XColor      color;

#ifndef STANDALONE
			mp->fg = MI_FG_PIXEL(mi);
			mp->bg = MI_BG_PIXEL(mi);
#endif
			mp->blackpixel = MI_BLACK_PIXEL(mi);
			mp->whitepixel = MI_WHITE_PIXEL(mi);
			if ((mp->cmap = XCreateColormap(display, window,
					MI_VISUAL(mi), AllocNone)) == None) {
				free_mandelbrot(display, mp);
				return;
			}
			XSetWindowColormap(display, window, mp->cmap);
			(void) XParseColor(display, mp->cmap, "black", &color);
			(void) XAllocColor(display, mp->cmap, &color);
			MI_BLACK_PIXEL(mi) = color.pixel;
			(void) XParseColor(display, mp->cmap, "white", &color);
			(void) XAllocColor(display, mp->cmap, &color);
			MI_WHITE_PIXEL(mi) = color.pixel;
#ifndef STANDALONE
			(void) XParseColor(display, mp->cmap, background, &color);
			(void) XAllocColor(display, mp->cmap, &color);
			MI_BG_PIXEL(mi) = color.pixel;
			(void) XParseColor(display, mp->cmap, foreground, &color);
			(void) XAllocColor(display, mp->cmap, &color);
			MI_FG_PIXEL(mi) = color.pixel;
#endif
			mp->colors = (XColor *) NULL;
			mp->ncolors = 0;
		}
		if ((mp->gc = XCreateGC(display, MI_WINDOW(mi),
			     (unsigned long) 0, (XGCValues *) NULL)) == None) {
			free_mandelbrot(display, mp);
			return;
		}
	}
	MI_CLEARWINDOW(mi);

  /* Set up colour map */
  mp->direction = (LRAND() & 1) ? 1 : -1;
  if (MI_IS_INSTALL(mi) && MI_NPIXELS(mi) > 2) {
    if (mp->colors != NULL) {
      if (mp->ncolors && !mp->no_colors)
        free_colors(display, mp->cmap, mp->colors, mp->ncolors);
      free(mp->colors);
      mp->colors = (XColor *) NULL;
    }
    mp->ncolors = MI_NCOLORS(mi);
    if (mp->ncolors < 2)
      mp->ncolors = 2;
    if (mp->ncolors <= 2)
      mp->mono_p = True;
    else
      mp->mono_p = False;

    if (mp->mono_p)
      mp->colors = (XColor *) NULL;
    else
      if ((mp->colors = (XColor *) malloc(sizeof (*mp->colors) *
          (mp->ncolors + 1))) == NULL) {
        free_mandelbrot(display, mp);
        return;
      }
    mp->cycle_p = has_writable_cells(mi);
    if (mp->cycle_p) {
      if (MI_IS_FULLRANDOM(mi)) {
        if (!NRAND(8))
          mp->cycle_p = False;
        else
          mp->cycle_p = True;
      } else {
        mp->cycle_p = cycle_p;
      }
    }
    if (!mp->mono_p) {
      if (!(LRAND() % 10))
        make_random_colormap(
#if STANDALONE
            display, MI_WINDOW(mi),
#else
            mi,
#endif
              mp->cmap, mp->colors, &mp->ncolors,
              True, True, &mp->cycle_p);
      else if (!(LRAND() % 2))
        make_uniform_colormap(
#if STANDALONE
            display, MI_WINDOW(mi),
#else
            mi,
#endif
                  mp->cmap, mp->colors, &mp->ncolors,
                  True, &mp->cycle_p);
      else
        make_smooth_colormap(
#if STANDALONE
            display, MI_WINDOW(mi),
#else
            mi,
#endif
                 mp->cmap, mp->colors, &mp->ncolors,
                 True, &mp->cycle_p);
    }
    XInstallColormap(display, mp->cmap);
    if (mp->ncolors < 2) {
      mp->ncolors = 2;
      mp->no_colors = True;
    } else
      mp->no_colors = False;
    if (mp->ncolors <= 2)
      mp->mono_p = True;

    if (mp->mono_p)
      mp->cycle_p = False;

  }
  if (MI_IS_INSTALL(mi) && MI_NPIXELS(mi) > 2) {
                if (mp->mono_p) {
			mp->cur_color = MI_BLACK_PIXEL(mi);
		}
  }
	Select(&mp->extreme_ul,&mp->extreme_lr,
		mp->screen_width,mp->screen_height,
		(int) mp->power,mp->reptop, mp->pow, mp->sin,
		&mp->ul,&mp->lr);
}
示例#14
0
void 
SRGP__initColor (requested_planes)
{
   srgp__available_depth = DefaultDepth(srgpx__display, srgpx__screen);

   if (srgp__available_depth == 1) {

      /***** PERFORMED FOR BILEVEL DISPLAYS */

      SRGP_BLACK = BlackPixel(srgpx__display,srgpx__screen);
      SRGP_WHITE = WhitePixel(srgpx__display,srgpx__screen);
      srgp__application_depth = 
	 srgp__max_pixel_value = 1;
      srgp__base_colorindex = 0;
   }
   

   else {

      /****** PERFORMED FOR COLOR DISPLAYS */

      SRGP_BLACK = 1;
      SRGP_WHITE = 0;

      if (requested_planes < 0) {
	 fprintf (stderr, "Fatal Error: insane parameter to SRGP_begin()\n\
            Application requesting negative number of planes.\n");
	 exit(1);
      }
      if ((requested_planes == 0) || 
	  (requested_planes > srgp__available_depth)) 
	 srgp__application_depth = srgp__available_depth;
      else
	 srgp__application_depth = requested_planes;
      srgp__max_pixel_value = (1 << srgp__application_depth) - 1;

      if (srgp__application_depth == srgp__available_depth) {

	 /***** APPL WANTS ENTIRE COLOR TABLE! */
	 srgpx__colormap = 
	    XCreateColormap (srgpx__display, 
			     srgp__curActiveCanvasSpec.drawable.win,
			     DefaultVisual(srgpx__display,srgpx__screen),
			     AllocAll);
	 XSetWindowColormap (srgpx__display, 
			     srgp__curActiveCanvasSpec.drawable.win,
			     srgpx__colormap);
      }
      else {

	 /***** APPL WANTS TO SHARE COLOR TABLE WITH THE OTHER CLIENTS */
	 unsigned long return_masks_here[8];
	 unsigned long return_pixels_here[1];
	 Status result;

	 srgpx__colormap = DefaultColormap(srgpx__display,srgpx__screen);

	 result = 
	    XAllocColorCells (srgpx__display,
			      srgpx__colormap,
			      TRUE /* contiguous planes desired */,
			      return_masks_here,
			      srgp__application_depth,
			      return_pixels_here,
			      1);
	 if (result == 0) {
	    fprintf (stderr, "%s\n%s\n%s\n%s\n%s\n",
		     "Fatal error: Color table too full to share.",
		     "A solution is to have the SRGP application request",
		     "   0 planes in the 4th parameter to SRGP_begin.",
		     "This gives SRGP permission to use its own complete",
		     "   color table, rather than try to share.");
	    exit(1);
	 }
	 
	 srgp__base_colorindex = return_pixels_here[0];
      }

      /* Only first two entries of LUT are init'd */
      XStoreNamedColor 
	 (srgpx__display, srgpx__colormap, "white", COLORINDEX(0), -1);
      XStoreNamedColor 
	 (srgpx__display, srgpx__colormap, "black", COLORINDEX(1), -1);
   }
EasyStr hxc_fileselect::choose(Display *d,char *Dir,char*name,char *Title,
                               int pass_mode,LPHXC_FILESELECTPARSE pr,char*defext)
{
    XD=d;
    DisplayDir=Dir;
    mode=pass_mode;
    Pixmap IconPixmap=0;
    Pixmap IconMaskPixmap=0;


    T_doesnt_exist=T("This file doesn't seem to exist.  Choose a different one.");
    T_folder_doesnt_exist=T("This folder doesn't seem to exist.  Choose a different one.");
    T_cant_find=T("Can't find file");
    T_okay=T("Okay");
    T_do_you_wanna=T("Do you want to load the file");
    T_confirm_load=T("Confirm Load");
    T_yes=T("Yes");
    T_no=T("No");
    T_create_new_question=T("You have tried to open a file that doesn't exist.  Do you want to create a new file with this name?");
    T_confirm_create=T("Confirm Create");
    T_overwrite_it=T("This file already exists.  Do you want to overwrite it?");
    T_confirm_overwrite=T("Overwrite File?");
    T_choose_folder=T("Choose folder");
    T_create_new_folder_question=T("This folder doesn't exist.  Do you want to create a new folder with this name?");
    T_error=T("Error");
    T_failed_to_create_folder=T("Couldn't create the folder.  Sorry!");
    if(!(T_load_but[0]))T_load_but=T("Load");
    if(!(T_save_but[0]))T_save_but=T("Save");
    if(!(T_okay_but[0]))T_okay_but=T("Okay");
    if(!(T_cancel_but[0]))T_cancel_but=T("Cancel");

    if (pr!=(LPHXC_FILESELECTPARSE)1) parse_routine=pr;

    chose_filename="";
    chose_path="";
    chose_option=0;

    if(defext) {
        default_extension=defext;
        if(defext[0]!='.')default_extension.Insert(".",0);
    } else {
        default_extension="";
    }

    hxc::load_res(XD);

    int scr=XDefaultScreen(XD);
    Win=XCreateSimpleWindow(XD,DefaultRootWindow(XD),
                            XDisplayWidth(XD,scr)/2-250,XDisplayHeight(XD,scr)/2-200,500,400,
                            0,hxc::col_grey,hxc::col_grey);
    if(hxc::colormap!=0) {
        XSetWindowColormap(XD,Win,hxc::colormap);
    }
    hxc::SetProp(XD,Win,cWinProc,(DWORD)WinProc);
    hxc::SetProp(XD,Win,cWinThis,(DWORD)this);

    Atom Prots[1]= {hxc::XA_WM_DELETE_WINDOW};
    XSetWMProtocols(XD,Win,Prots,1);

    XSelectInput(XD,Win,StructureNotifyMask | FocusChangeMask | ExposureMask);

    if(!lp_corner_ig) {
        if(lpig) {
            lp_corner_ig=lpig;
            corner_icon_index=0;
        }
    }
    if(lp_corner_ig) {
        IconPixmap=lp_corner_ig->CreateIconPixmap(corner_icon_index,hxc::gc);
        IconMaskPixmap=lp_corner_ig->CreateMaskBitmap(corner_icon_index);
        SetWindowHints(XD,Win,True,NormalState,IconPixmap,IconMaskPixmap,0,0);
    }



    lv.create(XD,Win,10,45,480,275,listview_notify_handler,this);
    lv.display_mode=1; //files

    if(lpig) {
        UpBut.create(XD,Win,10,10,25,25,
                     button_notify_handler,this,BT_ICON,"Up",1,hxc::col_bk);
        UpBut.set_icon(lpig,1);
        lv.lpig=lpig;
    } else {
        UpBut.create(XD,Win,10,10,25,25,
                     button_notify_handler,this,BT_TEXT,"Up",1,hxc::col_bk);
        lv.lpig=NULL;
    }

    int xp=400;

    CancelBut.create(XD,Win,xp,365,90,25,
                     button_notify_handler,this,BT_TEXT,T_cancel_but,3,hxc::col_bk);
    SetWindowGravity(XD,CancelBut.handle,SouthEastGravity);

    int bs=0;
    xp-=100;
    if(mode&FSM_CHOOSE_FOLDER) {
        xp-=30;
        FolBut.create(XD,Win,xp,365,120,25,
                      button_notify_handler,this,BT_TEXT,T_choose_folder,6,hxc::col_bk);
        SetWindowGravity(XD,FolBut.handle,SouthEastGravity);
        xp-=100;
        bs++;
    }
    if(mode&FSM_OK) {
        OkBut.create(XD,Win,xp,365,90,25,
                     button_notify_handler,this,BT_TEXT,T_okay_but,2,hxc::col_bk);
        SetWindowGravity(XD,OkBut.handle,SouthEastGravity);
        xp-=100;
        bs++;
    }
    if(mode&FSM_SAVE) {
        SaveBut.create(XD,Win,xp,365,90,25,
                       button_notify_handler,this,BT_TEXT,T_save_but,5,hxc::col_bk);
        SetWindowGravity(XD,SaveBut.handle,SouthEastGravity);
        xp-=100;
        bs++;
    }
    if(mode&FSM_LOAD) {
        LoadBut.create(XD,Win,xp,365,90,25,
                       button_notify_handler,this,BT_TEXT,T_load_but,4,hxc::col_bk);
        SetWindowGravity(XD,LoadBut.handle,SouthEastGravity);
        xp-=100;
        bs++;
    }
    one_choice=(bs==1);

    DirOutput.set_text(DisplayDir);
    DirOutput.create(XD,Win,40,10,420,25,edit_notifyproc,this);

    if(name)filename_ed.set_text(name,true);
    else {
        filename_ed.set_text("");
    }
    filename_ed.create(XD,Win,10,lv.h+lv.y+10,lv.w,25,edit_notifyproc,this);

    XStoreName(XD,Win,Title);

    XSetTransientForHint(XD,Win,Win);

    hxc::modal_children(XD,Win,Win);
    hxc::SetProp(XD,Win,hxc::cModal,Win);

    XMapWindow(XD,Win);

    set_path(DisplayDir);

    XFlush(XD);

    if (hxc::modal_notifyproc) hxc::modal_notifyproc(true);

    Close=0;
    LPWINDOWPROC WinProc;
    XEvent Ev;
    LOOP{
        if (hxc::wait_for_event(XD,&Ev)) {
            WinProc=(LPWINDOWPROC)  hxc::GetProp(XD,Ev.xany.window,cWinProc);
            if (WinProc) {
                //    	bool suppress=false;
                if(hxc::GetProp(XD,Ev.xany.window,hxc::cModal)!=Win) { //not modal
                    if (hxc::suppress_mess_for_modal(XD,&Ev)==0) {
                        WinProc((void*)  hxc::GetProp(XD,Ev.xany.window,cWinThis),Ev.xany.window,&Ev);
                    } else {
                        if(Ev.type==FocusIn) {
                            XRaiseWindow(XD,Win);
                        }
                    }
                } else {
                    WinProc((void*)  hxc::GetProp(XD,Ev.xany.window,cWinThis),Ev.xany.window,&Ev);
                }
            }
            if (Close) {
                if (XPending(XD)==0) break;
            }
        }
    }

    if (Close==3) {
        DisplayDir="";
    }

    hxc::modal_children(XD,Win,0);

    hxc::destroy_children_of(Win);
    hxc::RemoveProp(XD,Win,cWinProc);
    hxc::RemoveProp(XD,Win,cWinThis);
    hxc::RemoveProp(XD,Win,hxc::cModal);
    XDestroyWindow(XD,Win);

    if (IconPixmap) XFreePixmap(XD,IconPixmap);
    IconPixmap=0;
    if (IconMaskPixmap) XFreePixmap(XD,IconMaskPixmap);
    IconMaskPixmap=0;

    hxc::free_res(XD);

    if (hxc::modal_notifyproc) hxc::modal_notifyproc(0);

    return DisplayDir;
}
示例#16
0
void allocate_colors()
{
  XColor xcolor, exact_color;
  int red, green, blue;

  map = DefaultColormap(display, DefaultScreen(display));
  if(!XAllocNamedColor(display, map, background_color_name,
                       &xcolor, &exact_color))
    goto revert;

  color[background] = xcolor.pixel;
  exact_color.flags = DoRed | DoGreen | DoBlue;
  red = exact_color.red;
  blue = exact_color.blue;
  green = exact_color.green;
  
  red += 16384;
  if (red > 65535) red = 65535;
  blue += 16384;
  if (blue > 65535) blue = 65535;
  green += 16384;
  if (green > 65535) green = 65535;
  
  exact_color.red = red;
  exact_color.blue = blue;
  exact_color.green = green;
  
  if(!XAllocColor(display, map, &exact_color))
    goto revert;

  color[hilight] = exact_color.pixel;
  
  red -= 32768;
  if (red < 0) red = 0;
  blue -= 32768;
  if (blue < 0) blue = 0;
  green -= 32768;
  if (green < 0) green = 0;
  
  exact_color.red = red;
  exact_color.blue = blue;
  exact_color.green = green;
  
  if (!XAllocColor(display, map, &exact_color))
    goto revert;

  color[shadow] = exact_color.pixel;
  
  if (!XAllocNamedColor(display, map, foreground_color_name,
                   &xcolor, &exact_color))
    goto revert;

  color[text] = xcolor.pixel;

  exact_color.red = 0x9000;
  exact_color.green = 0xd000;
  exact_color.blue = 0x9000;
  if(!XAllocColor(display, map, &exact_color))
    goto revert;

  color[light_led] = exact_color.pixel;

  exact_color.red = 0x0;
  exact_color.green = 0x0;
  exact_color.blue = 0x8000;
  if(!XAllocColor(display, map, &exact_color))
    goto revert;

  color[dark_led] = exact_color.pixel;
  XSetWindowColormap(display, main_window, map);
  create_GCs();
  return;

revert:
  /* switch to black'n'white mode */
  create_GCs_bw();
}
示例#17
0
文件: mikey.c 项目: 10crimes/code
  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;
  }
示例#18
0
void init_graphics (char *window_name) {

 /* Open the toplevel window, get the colors, 2 graphics  *
  * contexts, load a font, and set up the toplevel window *
  * Calls build_menu to set up the menu.                  */

 char *display_name = NULL;
 int x, y;                                   /* window position */
 unsigned int border_width = 2;  /* ignored by OpenWindows */
 XTextProperty windowName;

/* X Windows' names for my colours. */
 char *cnames[NUM_COLOR] = {"white", "black", "grey55", "grey75", "blue", 
        "green", "yellow", "cyan", "red", "RGBi:0.0/0.5/0.0" };

 XColor exact_def;
 Colormap cmap;
 int i;
 unsigned long valuemask = 0; /* ignore XGCvalues and use defaults */
 XGCValues values;
 XEvent event;


 disp_type = SCREEN;         /* Graphics go to screen, not ps */

 for (i=0;i<=MAX_FONT_SIZE;i++) 
    font_is_loaded[i] = 0;     /* No fonts loaded yet. */

 /* connect to X server */
        /* connect to X server */
 if ( (display=XOpenDisplay(display_name)) == NULL )
 {
     fprintf( stderr, "Cannot connect to X server %s\n",
                          XDisplayName(display_name));
     exit( -1 );
 }

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

 x = y = 0;
        
 top_width = 2*display_width/3;
 top_height = 4*display_height/5;
 
 cmap = DefaultColormap(display, screen_num);
 private_cmap = None;

 for (i=0;i<NUM_COLOR;i++) {
    if (!XParseColor(display,cmap,cnames[i],&exact_def)) {
       fprintf(stderr, "Color name %s not in database", cnames[i]);
       exit(-1);
    }
    if (!XAllocColor(display, cmap, &exact_def)) {
       fprintf(stderr, "Couldn't allocate color %s.\n",cnames[i]); 

       if (private_cmap == None) {
          fprintf(stderr, "Will try to allocate a private colourmap.\n");
          fprintf(stderr, "Colours will only display correctly when your "
                          "cursor is in the graphics window.\n"
                          "Exit other colour applications and rerun this "
                          "program if you don't like that.\n\n");
                    
          private_cmap = XCopyColormapAndFree (display, cmap);
          cmap = private_cmap;
          if (!XAllocColor (display, cmap, &exact_def)) {
             fprintf (stderr, "Couldn't allocate color %s as private.\n",
                 cnames[i]);
             exit (1);
          }
       }

       else {
          fprintf (stderr, "Couldn't allocate color %s as private.\n",
              cnames[i]);
          exit (1);
       }
    }
    colors[i] = exact_def.pixel;
 }

 toplevel = XCreateSimpleWindow(display,RootWindow(display,screen_num),
          x, y, top_width, top_height, border_width, colors[BLACK],
          colors[WHITE]);  

 if (private_cmap != None) 
     XSetWindowColormap (display, toplevel, private_cmap);

 /* hints stuff deleted. */

 XSelectInput (display, toplevel, ExposureMask | StructureNotifyMask |
       ButtonPressMask);
 

 /* Create default Graphics Contexts.  valuemask = 0 -> use defaults. */
 gc = XCreateGC(display, toplevel, valuemask, &values);
 gc_menus = XCreateGC(display, toplevel, valuemask, &values);

 /* Create XOR graphics context for Rubber Banding */
 values.function = GXxor;   
 values.foreground = colors[BLACK];
 gcxor = XCreateGC(display, toplevel, (GCFunction | GCForeground),
       &values);
 
 /* specify font for menus.  */
 load_font(menu_font_size);
 font_is_loaded[menu_font_size] = 1;
 XSetFont(display, gc_menus, font_info[menu_font_size]->fid);

/* Set drawing defaults for user-drawable area.  Use whatever the *
 * initial values of the current stuff was set to.                */
 force_setfontsize(currentfontsize);
 force_setcolor (currentcolor);
 force_setlinestyle (currentlinestyle);
 force_setlinewidth (currentlinewidth);
 
 XStringListToTextProperty(&window_name, 1, &windowName);
 XSetWMName (display, toplevel, &windowName);
/* XSetWMIconName (display, toplevel, &windowName); */

 
 /* set line attributes */
/* XSetLineAttributes(display, gc, line_width, line_style,
           cap_style, join_style); */
 
 /* set dashes */
 /* XSetDashes(display, gc, dash_offset, dash_list, list_length); */

 XMapWindow (display, toplevel);
 build_textarea();
 build_menu();
 
/* The following is completely unnecessary if the user is using the       *
 * interactive (event_loop) graphics.  It waits for the first Expose      *
 * event before returning so that I can tell the window manager has got   *
 * the top-level window up and running.  Thus the user can start drawing  *
 * into this window immediately, and there's no danger of the window not  *
 * being ready and output being lost.                                     */

 XPeekIfEvent (display, &event, test_if_exposed, NULL); 
}
示例#19
0
int main (int argc, char **argv)
{
	int nTic1,nTic2,width,height;
	float smin,smax,bclip,wclip,x1beg,x1end,x2beg,x2end;
	char *edgecolor="cyan",*tricolor="yellow",*cmap="gray",
		*label1="",*label2="",*title="",
		*labelFont="",*titleFont="",
		*axesColor="",*gridColor="",*titleColor="",
		*style="seismic",*grid1="none",*grid2="none";
	Model *model;
	XrmValue from,to;
	ExposeCD exposeCD;
	Widget toplevel,axes;
	Display *dpy;
	Window win;
	Arg args[100];
	int nargs;
	float bhue=0,whue=240,sat=1,bright=1;

	/* initialize getpar */
	initargs(argc,argv);
        requestdoc(0);

	
	/* read model */
	model = readModel(stdin);
	
	/* determine minimum and maximum s(x,y) */
	minmax(model,&smin,&smax);
	
	/* get optional parameters */
	getparstring("edgecolor",&edgecolor);
	getparstring("tricolor",&tricolor);
	bclip = smin; getparfloat("bclip",&bclip);
	wclip = smax; getparfloat("wclip",&wclip);
        getparstring("cmap",&cmap);   

	/* initialize toolkit intrinsics and set toplevel parameters */
	toplevel = XtInitialize(argv[0],"Sxplot",NULL,0,&argc,argv);
	nargs = 0;
	if (getparint("width",&width))
		{XtSetArg(args[nargs],XtNwidth,width); nargs++;}
	if (getparint("height",&height))
		{XtSetArg(args[nargs],XtNheight,height); nargs++;}
	XtSetValues(toplevel,args,nargs);

	/* create axes and set axes parameters */
	axes = XtCreateManagedWidget("axes",xtcwpAxesWidgetClass,
		toplevel,NULL,0);


	nargs = 0;
	if (getparstring("grid1",&grid1)) {
		from.addr = (char *)grid1;
		XtConvertAndStore(axes,XtRString,&from,XtcwpRAxesGrid,&to);
		if (to.addr) XtSetArg(args[nargs],XtNgrid1,*((int*)to.addr));
		nargs++;
	}
	if (getparstring("grid2",&grid2)) {
		from.addr = (char *)grid2;
		XtConvertAndStore(axes,XtRString,&from,XtcwpRAxesGrid,&to);
		if (to.addr) XtSetArg(args[nargs],XtNgrid2,*((int*)to.addr));
		nargs++;
	}
	if (getparint("nTic1",&nTic1))
		{XtSetArg(args[nargs],XtNnTic1,nTic1); nargs++;}
	if (getparint("nTic2",&nTic2))
		{XtSetArg(args[nargs],XtNnTic2,nTic2); nargs++;}
	if (getparstring("label1",&label1))
		{XtSetArg(args[nargs],XtNlabel1,label1); nargs++;}
	if (getparstring("label2",&label2))
		{XtSetArg(args[nargs],XtNlabel2,label2); nargs++;}
	if (getparstring("title",&title))
		{XtSetArg(args[nargs],XtNtitle,title); nargs++;}
	if (getparstring("style",&style)) {
		from.size = (unsigned int) strlen(style);  from.addr = (char *)style;
		XtConvertAndStore(axes,XtRString,&from,XtcwpRAxesStyle,&to);
		if (to.addr) XtSetArg(args[nargs],XtNstyle,*((int*)to.addr));
		nargs++;
	}
	if (getparstring("axesColor",&axesColor)) {
		from.addr = (char *)axesColor;
		XtConvertAndStore(axes,XtRString,&from,XtRPixel,&to);
		if (to.addr) XtSetArg(args[nargs],XtNaxesColor,
			*((unsigned long*)to.addr));
		nargs++;
	}
	if (getparstring("gridColor",&gridColor)) {
		from.addr = (char *)gridColor;
		XtConvertAndStore(axes,XtRString,&from,XtRPixel,&to);
		if (to.addr) XtSetArg(args[nargs],XtNgridColor,
			*((unsigned long*)to.addr));
		nargs++;
	}
	if (getparstring("titleColor",&titleColor)) {
		from.addr = (char *)titleColor;
		XtConvertAndStore(axes,XtRString,&from,XtRPixel,&to);
		if (to.addr) XtSetArg(args[nargs],XtNtitleColor,
			*((unsigned long*)to.addr));
		nargs++;
	}
	if (getparstring("labelFont",&labelFont)) {
		from.addr = (char *)labelFont;
		XtConvertAndStore(axes,XtRString,&from,XtRFont,&to);
		if (to.addr) XtSetArg(args[nargs],XtNlabelFont,
			*((Font*)to.addr));
		nargs++;
	}
	if (getparstring("titleFont",&titleFont)) {
		from.addr = (char *)titleFont;
		XtConvertAndStore(axes,XtRString,&from,XtRFont,&to);
		if (to.addr) XtSetArg(args[nargs],XtNtitleFont,
			*((Font*)to.addr));
		nargs++;
	}
	XtSetValues(axes,args,nargs);
	x1beg = model->xmin; getparfloat("x1beg",&x1beg);
	x1end = model->xmax; getparfloat("x1end",&x1end);
	x2beg = model->ymin; getparfloat("x2beg",&x2beg);
	x2end = model->ymax; getparfloat("x2end",&x2end);
	XtcwpSetAxesValues(axes,x1beg,x1end,x2beg,x2end);

	/* add callbacks to axes widget */
	XtAddCallback(axes,XtNresizeCallback,(XtCallbackProc) resizeCB,NULL);
	exposeCD.model = model;
	exposeCD.edgecolor = edgecolor;
	exposeCD.tricolor = tricolor;
	exposeCD.bclip = bclip;
	exposeCD.wclip = wclip;
	XtAddCallback(axes,XtNexposeCallback,(XtCallbackProc) exposeCB,&exposeCD);
	XtAddCallback(axes,XtNinputCallback,(XtCallbackProc) inputCB,NULL);

	/* realize widgets */
	XtRealizeWidget(toplevel);

	/* if necessary, create private colormap */
	dpy = XtDisplay(toplevel);
	win = XtWindow(toplevel);

	if (STREQ(cmap,"gray")) {
	  XSetWindowColormap(dpy,win,XtcwpCreateGrayColormap(dpy,win));
	} else if (STREQ(cmap,"hue")) {
	  XSetWindowColormap(dpy,win,XtcwpCreateHueColormap(dpy,win,
														bhue,whue,sat,bright)); /* see Note below */
	}
	
	/* go */
	XtMainLoop();

	return EXIT_SUCCESS;
}
示例#20
0
void
init_tik_tak(ModeInfo * mi)
{
	Display    *display = MI_DISPLAY(mi);
	Window      window = MI_WINDOW(mi);
	int         i, max_objects, size_object;
	tik_takstruct *tiktak;

/* initialize */
	if (tik_taks == NULL) {
		if ((tik_taks = (tik_takstruct *) calloc(MI_NUM_SCREENS(mi),
				sizeof (tik_takstruct))) == NULL)
			return;
	}
	tiktak = &tik_taks[MI_SCREEN(mi)];
	tiktak->mi = mi;

	if (tiktak->gc == None) {
		if (MI_IS_INSTALL(mi) && MI_NPIXELS(mi) > 2) {
			XColor      color;

#ifndef STANDALONE
			tiktak->fg = MI_FG_PIXEL(mi);
			tiktak->bg = MI_BG_PIXEL(mi);
#endif
			tiktak->blackpixel = MI_BLACK_PIXEL(mi);
			tiktak->whitepixel = MI_WHITE_PIXEL(mi);
			if ((tiktak->cmap = XCreateColormap(display, window,
					MI_VISUAL(mi), AllocNone)) == None) {
				free_tik_tak(display, tiktak);
				return;
			}
			XSetWindowColormap(display, window, tiktak->cmap);
			(void) XParseColor(display, tiktak->cmap, "black", &color);
			(void) XAllocColor(display, tiktak->cmap, &color);
			MI_BLACK_PIXEL(mi) = color.pixel;
			(void) XParseColor(display, tiktak->cmap, "white", &color);
			(void) XAllocColor(display, tiktak->cmap, &color);
			MI_WHITE_PIXEL(mi) = color.pixel;
#ifndef STANDALONE
			(void) XParseColor(display, tiktak->cmap, background, &color);
			(void) XAllocColor(display, tiktak->cmap, &color);
			MI_BG_PIXEL(mi) = color.pixel;
			(void) XParseColor(display, tiktak->cmap, foreground, &color);
			(void) XAllocColor(display, tiktak->cmap, &color);
			MI_FG_PIXEL(mi) = color.pixel;
#endif
			tiktak->colors = (XColor *) NULL;
			tiktak->ncolors = 0;
		}
		if ((tiktak->gc = XCreateGC(display, MI_WINDOW(mi),
			     (unsigned long) 0, (XGCValues *) NULL)) == None) {
			free_tik_tak(display, tiktak);
			return;
		}
	}
/* Clear Display */
	MI_CLEARWINDOW(mi);
	tiktak->painted = False;
	XSetFunction(display, tiktak->gc, GXxor);


/*Set up tik_tak data */
	tiktak->direction = (LRAND() & 1) ? 1 : -1;
	tiktak->win_width = MI_WIDTH(mi);
	tiktak->win_height = MI_HEIGHT(mi);
	tiktak->num_object = MI_COUNT(mi);
        tiktak->x0 = tiktak->win_width / 2;
        tiktak->y0 = tiktak->win_height / 2;
	max_objects = MI_COUNT(mi);
	if (tiktak->num_object == 0) {
		tiktak->num_object = DEF_NUM_OBJECT;
		max_objects = DEF_NUM_OBJECT;
	} else if (tiktak->num_object < 0) {
		max_objects = -tiktak->num_object;
		tiktak->num_object = NRAND(-tiktak->num_object) + 1;
	}
	if (tiktak->object == NULL)
		if ((tiktak->object = (tik_takobject *) calloc(max_objects,
				sizeof (tik_takobject))) == NULL) {
			free_tik_tak(display, tiktak);
			return;
		}
	size_object = MIN( tiktak->win_width , tiktak->win_height) / 3;
	if ( abs( MI_SIZE(mi) ) > size_object) {
	   if ( MI_SIZE( mi ) < 0 )
	     {
		size_object = -size_object;
	     }
	}
   else
     {
	size_object = MI_SIZE(mi);
     }
	if (MI_IS_INSTALL(mi) && MI_NPIXELS(mi) > 2) {
/* Set up colour map */
		if (tiktak->colors != NULL) {
			if (tiktak->ncolors && !tiktak->no_colors)
				free_colors(display, tiktak->cmap, tiktak->colors, tiktak->ncolors);
			free(tiktak->colors);
			tiktak->colors = (XColor *) NULL;
		}
		tiktak->ncolors = MI_NCOLORS(mi);
		if (tiktak->ncolors < 2)
			tiktak->ncolors = 2;
		if (tiktak->ncolors <= 2)
			tiktak->mono_p = True;
		else
			tiktak->mono_p = False;

		if (tiktak->mono_p)
			tiktak->colors = (XColor *) NULL;
		else
			if ((tiktak->colors = (XColor *) malloc(sizeof (*tiktak->colors) *
					(tiktak->ncolors + 1))) == NULL) {
				free_tik_tak(display, tiktak);
				return;
			}
		tiktak->cycle_p = has_writable_cells(mi);
		if (tiktak->cycle_p) {
			if (MI_IS_FULLRANDOM(mi)) {
				if (!NRAND(8))
					tiktak->cycle_p = False;
				else
					tiktak->cycle_p = True;
			} else {
				tiktak->cycle_p = cycle_p;
			}
		}
		if (!tiktak->mono_p) {
			if (!(LRAND() % 10))
				make_random_colormap(
#ifdef STANDALONE
						MI_DISPLAY(mi), MI_WINDOW(mi),
#else
            mi,
#endif
						tiktak->cmap, tiktak->colors, &tiktak->ncolors,
						True, True, &tiktak->cycle_p);
			else if (!(LRAND() % 2))
				make_uniform_colormap(
#ifdef STANDALONE
						MI_DISPLAY(mi), MI_WINDOW(mi),
#else
            mi,
#endif
                  tiktak->cmap, tiktak->colors, &tiktak->ncolors,
						      True, &tiktak->cycle_p);
			else
				make_smooth_colormap(
#ifdef STANDALONE
						MI_DISPLAY(mi), MI_WINDOW(mi),
#else
            mi,
#endif
                 tiktak->cmap, tiktak->colors, &tiktak->ncolors,
						     True, &tiktak->cycle_p);
		}
		XInstallColormap(display, tiktak->cmap);
		if (tiktak->ncolors < 2) {
			tiktak->ncolors = 2;
			tiktak->no_colors = True;
		} else
			tiktak->no_colors = False;
		if (tiktak->ncolors <= 2)
			tiktak->mono_p = True;

		if (tiktak->mono_p)
			tiktak->cycle_p = False;

	}
	for (i = 0; i < tiktak->num_object; i++) {
		tik_takobject *object0;

		object0 = &tiktak->object[i];
		if (MI_IS_INSTALL(mi) && MI_NPIXELS(mi) > 2) {
			if (tiktak->ncolors > 2)
				object0->colour = NRAND(tiktak->ncolors - 2) + 2;
			else
				object0->colour = 1;	/* Just in case */
			XSetForeground(display, tiktak->gc, tiktak->colors[object0->colour].pixel);
		} else {
			if (MI_NPIXELS(mi) > 2)
				object0->colour = MI_PIXEL(mi, NRAND(MI_NPIXELS(mi)));
			else
				object0->colour = 1;	/*Xor'red so WHITE may not be appropriate */
			XSetForeground(display, tiktak->gc, object0->colour);
		}
		object0->angle = NRAND(90) * PI_RAD;
		object0->angle1 = NRAND(90) * PI_RAD;
		object0->velocity_a = (NRAND(7) - 3) * PI_RAD;
		object0->velocity_a1 = (NRAND(7) - 3) * PI_RAD;
		if (size_object == 0)
			object0->size_ob = 9;
		else if (size_object > 0)
			object0->size_ob = size_object;
		else
			object0->size_ob = NRAND(-size_object) + 1;
		object0->size_ob++;
		object0->num_point = NRAND(6)+3;
	   if (LRAND() & 1)
	     object0->size_mult = 1.0;
	   else
	     {
		object0->num_point *= 2;
		object0->size_mult = 1.0 - ( 1.0 / (float) ((LRAND() & 1) +
							    2 ) );
	     }
	   if (object0->xy != NULL)
			free(object0->xy);
	   if ((object0->xy = (XPoint *) malloc(sizeof( XPoint ) *
				(2 * object0->num_point + 2))) == NULL) {
			free_tik_tak(display, tiktak);
			return;
		}
	   if ((LRAND() & 1) || object0->size_ob < 10 )
	     {
		object0->inner = False;
		if ( object0->xy1 != NULL ) free( object0->xy1 );
		object0->xy1 = (XPoint *) NULL;
	     }
	   else
	     {
		object0->inner = True;
	        object0->size_ob1 = object0->size_ob -
		  NRAND( object0->size_ob / 5 ) - 1;
		object0->num_point1 = NRAND(6)+3;
		if (LRAND() & 1)
		  object0->size_mult1 = 1.0;
		else
		  {
		     object0->num_point1 *= 2;
		     object0->size_mult1 = 1.0 -
		        ( 1.0 / (float) ((LRAND() & 1) + 2 ) );
		  }
		if (object0->xy1 != NULL)
			free(object0->xy1);
		if ((object0->xy1 = (XPoint *) malloc(sizeof( XPoint ) *
				(2 * object0->num_point1 + 2))) == NULL) {
			free_tik_tak(display, tiktak);
			return;
		}
		object0->size_mult1 = 1.0;
	     }
		tik_tak_setupobject( mi , object0);
		tik_tak_reset_object( object0);
		tik_tak_drawobject(mi, object0 );
	}
	XFlush(display);
	XSetFunction(display, tiktak->gc, GXcopy);
}
static void winopen(void)
{
	XWMHints *wmhints;
	XClassHint *classhint;

	xdpy = XOpenDisplay(nil);
	if (!xdpy)
		winerror(&gapp, fz_throw("could not open display"));

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

	xscr = DefaultScreen(xdpy);

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

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

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

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

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

	xwin = XCreateWindow(xdpy, DefaultRootWindow(xdpy),
			10, 10, 200, 100, 1,
			ximage_get_depth(),
			InputOutput,
			ximage_get_visual(),
			0,
			nil);

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

	mapped = 0;

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

	XDefineCursor(xdpy, xwin, xcarrow);

	wmhints = XAllocWMHints();
	if (wmhints)
	{
		wmhints->flags = IconPixmapHint;
		wmhints->icon_pixmap = XCreateBitmapFromData(xdpy, xwin,
				(char *) gs_l_xbm_bits, gs_l_xbm_width, gs_l_xbm_height);
		if (wmhints->icon_pixmap)
		{
			XSetWMHints(xdpy, xwin, wmhints);
		}
		XFree(wmhints);
	}

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

	x11fd = ConnectionNumber(xdpy);
}
示例#22
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;
}
示例#23
0
文件: winX11.cpp 项目: Shuyoung/cisst
int svlWindowManagerX11::DoModal(bool show, bool fullscreen)
{
    Destroy();
    DestroyFlag = false;

    unsigned int i, atom_count;
    int x, y, prevright, prevbottom;
    unsigned int lastimage = 0;
    unsigned long black, white;
    XSizeHints wsh;

#if CISST_SVL_HAS_XV
    Atom atoms[3];
    unsigned int xvadaptorcount;
    XvAdaptorInfo *xvai;
    XVisualInfo xvvinfo;
    bool xvupdateimage = true;
#else // CISST_SVL_HAS_XV
    Atom atoms[2];
#endif // CISST_SVL_HAS_XV

    // setting decoration hints for borderless mode
    struct {
        unsigned long 	flags;
        unsigned long 	functions;
        unsigned long 	decorations;
        signed long 	input_mode;
        unsigned long 	status;
    } mwm;
    mwm.flags = MWM_HINTS_DECORATIONS;
    mwm.decorations = 0;
    mwm.functions = 0;
    mwm.input_mode = 0;
    mwm.status = 0;
    
    // resetting DestroyedSignal event
    if (DestroyedSignal) delete(DestroyedSignal);
    DestroyedSignal = new osaThreadSignal();
    if (DestroyedSignal == 0) goto labError;

    // initialize display and pick default screen
    xDisplay = XOpenDisplay(reinterpret_cast<char*>(0));
    xScreen = DefaultScreen(xDisplay);

#if CISST_SVL_HAS_XV
    // check if 24bpp is suppoted by the display
    if (XMatchVisualInfo(xDisplay, xScreen, 24, TrueColor, &xvvinfo) == 0) goto labError;
#endif // CISST_SVL_HAS_XV

    // pick colors
    black = BlackPixel(xDisplay, xScreen);
    white = WhitePixel(xDisplay, xScreen);

    // create windows
    xWindows = new Window[NumOfWins];
    memset(xWindows, 0, NumOfWins * sizeof(Window));
    xGCs = new GC[NumOfWins];
    memset(xGCs, 0, NumOfWins * sizeof(GC));

    // create atoms for overriding default window behaviours
    atoms[0] = XInternAtom(xDisplay, "WM_DELETE_WINDOW", False);
    atoms[1] = XInternAtom(xDisplay, "_MOTIF_WM_HINTS", False);
#if CISST_SVL_HAS_XV
    atoms[2] = XInternAtom(xDisplay, "XV_SYNC_TO_VBLANK", False);
#endif // CISST_SVL_HAS_XV

    // create title strings
    Titles = new std::string[NumOfWins];
    CustomTitles = new std::string[NumOfWins];
    CustomTitleEnabled = new int[NumOfWins];

#if CISST_SVL_HAS_XV
    xvImg = new XvImage*[NumOfWins];
    xvShmInfo = new XShmSegmentInfo[NumOfWins];
    xvPort = new XvPortID[NumOfWins];
    if (xvImg == 0 || xvShmInfo == 0 || xvPort == 0) goto labError;
    memset(xvImg, 0, NumOfWins * sizeof(XvImage*));
    memset(xvShmInfo, 0, NumOfWins * sizeof(XShmSegmentInfo));
    memset(xvPort, 0, NumOfWins * sizeof(XvPortID));
#else // CISST_SVL_HAS_XV
    // create images
    xImageBuffers = new unsigned char*[NumOfWins];
    for (i = 0; i < NumOfWins; i ++) {
        xImageBuffers[i] = new unsigned char[Width[i] * Height[i] * 4];
    }
    xImg = new XImage*[NumOfWins];
    memset(xImg, 0, NumOfWins * sizeof(XImage*));
    if (xImg == 0) goto labError;
    for (i = 0; i < NumOfWins; i ++) {
        xImg[i] = XCreateImage(xDisplay,
                               DefaultVisual(xDisplay, xScreen),
                               24,
                               ZPixmap,
                               0,
                               reinterpret_cast<char*>(xImageBuffers[i]),
                               Width[i],
                               Height[i],
                               32,
                               0);
    }
#endif // CISST_SVL_HAS_XV

    prevright = prevbottom = 0;
    for (i = 0; i < NumOfWins; i ++) {
        if (PosX == 0 || PosY == 0) {
            if (fullscreen) {
                x = prevright;
                y = 0;
                prevright += Width[i];
            }
            else {
                x = prevright;
                y = prevbottom;
                prevright += 50;
                prevbottom += 50;
            }
        }
        else {
            x = PosX[i];
            y = PosY[i];
        }

        xWindows[i] = XCreateSimpleWindow(xDisplay, DefaultRootWindow(xDisplay),
                                          x,
                                          y,
                                          Width[i],
                                          Height[i],
                                          0,
                                          black,
                                          white);
        if (xWindows[i] == 0) goto labError;

        // overriding default behaviours:
        //    - borderless mode
        //    - closing window
        if (fullscreen) {
            XChangeProperty(xDisplay, xWindows[i],
                            atoms[1], atoms[1], 32,
                            PropModeReplace, reinterpret_cast<unsigned char*>(&mwm), 5);
            atom_count = 2;
        }
        else {
            atom_count = 1;
        }
        XSetWMProtocols(xDisplay, xWindows[i], atoms, atom_count);

        wsh.flags = PPosition|PSize;
        wsh.x = x;
        wsh.y = y;
        wsh.width = Width[i];
        wsh.height = Height[i];
        XSetNormalHints(xDisplay, xWindows[i], &wsh);

        // set window title
        CustomTitleEnabled[i] = 0;

        std::ostringstream ostring;
        if (Title.length() > 0) {
            if (NumOfWins > 0) ostring << Title << " #" << i;
            else ostring << Title;
        }
        else {
            if (NumOfWins > 0) ostring << Title << "svlImageWindow #" << i;
            else ostring << "svlImageWindow";
        }

        Titles[i] = ostring.str();
        XSetStandardProperties(xDisplay, xWindows[i],
                               Titles[i].c_str(), Titles[i].c_str(),
                               None, NULL, 0, NULL);

        // set even mask
        XSelectInput(xDisplay, xWindows[i], ExposureMask|PointerMotionMask|ButtonPressMask|KeyPressMask);

        // set window colormap
        XSetWindowColormap(xDisplay, xWindows[i], DefaultColormapOfScreen(DefaultScreenOfDisplay(xDisplay)));

#if CISST_SVL_HAS_XV
        // query shared memory extension
        if (!XShmQueryExtension(xDisplay)) goto labError;

        // query video adaptors
        if (XvQueryAdaptors(xDisplay, DefaultRootWindow(xDisplay), &xvadaptorcount, &xvai) != Success) goto labError;
        xvPort[i] = xvai->base_id + i;
        XvFreeAdaptorInfo(xvai);

        // overriding default Xvideo vertical sync behavior
        XvSetPortAttribute (xDisplay, xvPort[i], atoms[2], 1);
#endif // CISST_SVL_HAS_XV

        // create graphics context
        xGCs[i] = XCreateGC(xDisplay, xWindows[i], 0, 0);

        // set default colors
        XSetBackground(xDisplay, xGCs[i], white);
        XSetForeground(xDisplay, xGCs[i], black);

#if CISST_SVL_HAS_XV
        // create image in shared memory
        xvImg[i] = XvShmCreateImage(xDisplay, xvPort[i], 0x32595559/*YUV2*/, 0, Width[i], Height[i], &(xvShmInfo[i]));
        if (xvImg[i]->width < static_cast<int>(Width[i]) || xvImg[i]->height < static_cast<int>(Height[i])) {
            CMN_LOG_INIT_ERROR << "DoModal - image too large for XV to display (requested="
                               << Width[i] << "x" << Height[i] << "; allowed="
                               << xvImg[i]->width << "x" << xvImg[i]->height << ")" << std::endl;
            goto labError;
        }
        xvShmInfo[i].shmid = shmget(IPC_PRIVATE, xvImg[i]->data_size, IPC_CREAT | 0777);
        xvShmInfo[i].shmaddr = xvImg[i]->data = reinterpret_cast<char*>(shmat(xvShmInfo[i].shmid, 0, 0));
        xvShmInfo[i].readOnly = False;
        if (!XShmAttach(xDisplay, &(xvShmInfo[i]))) goto labError;
#endif // CISST_SVL_HAS_XV

        // clear window
        XClearWindow(xDisplay, xWindows[i]);

        // show window if requested
        if (show) XMapRaised(xDisplay, xWindows[i]);
    }

    // signal that initialization is done
    if (InitReadySignal) InitReadySignal->Raise();

	// main message loop
    XEvent event;
    KeySym code;
    unsigned int winid;

    while (1) {
        osaSleep(0.001);
#if CISST_SVL_HAS_XV
        if (!xvupdateimage) {
            for (int events = XPending(xDisplay); events > 0; events --) {
#else // CISST_SVL_HAS_XV
        if (XPending(xDisplay)) {
#endif // CISST_SVL_HAS_XV
                XNextEvent(xDisplay, &event);

                // find recipient
                for (winid = 0; winid < NumOfWins; winid ++) {
                    if (event.xany.window == xWindows[winid]) break;
                }
                if (winid == NumOfWins) continue;

                // override default window behaviour
                if (event.type == ClientMessage) {
                    if (static_cast<unsigned long>(event.xclient.data.l[0]) == atoms[0]) {
                        // X11 server wants to close window
                        // Do nothing.... we will destroy it ourselves later
                    }
                    continue;
                }

                // window should be closed
                if (event.type == UnmapNotify) {
                    printf("destroy\n");
                    if (xGCs[winid]) {
                        XFreeGC(xDisplay, xGCs[winid]);
                        xGCs[winid] = 0;
                    }
                    xWindows[winid] = 0;
                    continue;
                }

                // window should be updated
                if (event.type == Expose && event.xexpose.count == 0) {
                    XClearWindow(xDisplay, xWindows[winid]);
                    continue;
                }

                if (event.type == KeyPress) {
                    code = XLookupKeysym(&event.xkey, 0);
                    if (code >= 48 && code <= 57) { // ascii numbers
                        OnUserEvent(winid, true, code);
                        continue;
                    }
                    if (code >= 97 && code <= 122) { // ascii letters
                        OnUserEvent(winid, true, code);
                        continue;
                    }
                    if (code == 13 ||
                        code == 32) { // special characters with correct ascii code
                        OnUserEvent(winid, true, code);
                        continue;
                    }
                    if (code >= 0xffbe && code <= 0xffc9) { // F1-F12
                        OnUserEvent(winid, false, winInput_KEY_F1 + (code - 0xffbe));
                        continue;
                    }
                    switch (code) {
                        case 0xFF55:
                            OnUserEvent(winid, false, winInput_KEY_PAGEUP);
                        break;

                        case 0xFF56:
                            OnUserEvent(winid, false, winInput_KEY_PAGEDOWN);
                        break;

                        case 0xFF50:
                            OnUserEvent(winid, false, winInput_KEY_HOME);
                        break;

                        case 0xFF57:
                            OnUserEvent(winid, false, winInput_KEY_END);
                        break;

                        case 0xFF63:
                            OnUserEvent(winid, false, winInput_KEY_INSERT);
                        break;

                        case 0xFFFF:
                            OnUserEvent(winid, false, winInput_KEY_DELETE);
                        break;

                        case 0xFF51:
                            OnUserEvent(winid, false, winInput_KEY_LEFT);
                        break;

                        case 0xFF53:
                            OnUserEvent(winid, false, winInput_KEY_RIGHT);
                        break;

                        case 0xFF52:
                            OnUserEvent(winid, false, winInput_KEY_UP);
                        break;

                        case 0xFF54:
                            OnUserEvent(winid, false, winInput_KEY_DOWN);
                        break;
                    }
                    continue;
                }

                if (event.type == ButtonPress) {
                    if (event.xbutton.button == Button1) {
                        if (!LButtonDown && !RButtonDown) {
                            LButtonDown = true;
                            XGrabPointer(xDisplay, xWindows[winid], false,
                                         PointerMotionMask|ButtonReleaseMask,
                                         GrabModeAsync, GrabModeAsync,
                                         None,
                                         None,
                                         CurrentTime);
                        }
                        OnUserEvent(winid, false, winInput_LBUTTONDOWN);
                    }
                    else if (event.xbutton.button == Button3) {
                        if (!LButtonDown && !RButtonDown) {
                            RButtonDown = true;
                            XGrabPointer(xDisplay, xWindows[winid], false,
                                         PointerMotionMask|ButtonReleaseMask,
                                         GrabModeAsync, GrabModeAsync,
                                         None,
                                         None,
                                         CurrentTime);
                        }
                        OnUserEvent(winid, false, winInput_RBUTTONDOWN);
                    }
                }
                
                if (event.type == ButtonRelease) {
                    if (event.xbutton.button == Button1) {
                        OnUserEvent(winid, false, winInput_LBUTTONUP);
                        if (LButtonDown && !RButtonDown) {
                            LButtonDown = false;
                            XUngrabPointer(xDisplay, CurrentTime);
                        }
                    }
                    else if (event.xbutton.button == Button3) {
                        OnUserEvent(winid, false, winInput_RBUTTONUP);
                        if (!LButtonDown && RButtonDown) {
                            RButtonDown = false;
                            XUngrabPointer(xDisplay, CurrentTime);
                        }
                    }
                }

                if (event.type == MotionNotify) {
                    SetMousePos(static_cast<short>(event.xmotion.x), static_cast<short>(event.xmotion.y));
                    OnUserEvent(winid, false, winInput_MOUSEMOVE);
                }

#if CISST_SVL_HAS_XV
                // image update complete
                if (event.type == XShmGetEventBase(xDisplay) + ShmCompletion) {
                    xvupdateimage = true;
                    continue;
                }
            }
            if (!xvupdateimage) signalImage.Wait(0.01);
#endif // CISST_SVL_HAS_XV
        }
        else {
            if (DestroyFlag) break;

            if (ImageCounter > lastimage) {
                csImage.Enter();
                    lastimage = ImageCounter;

#if CISST_SVL_HAS_XV
                    for (i = 0; i < NumOfWins; i ++) {
                        XvShmPutImage(xDisplay,
                                      xvPort[i],
                                      xWindows[i],
                                      xGCs[i],
                                      xvImg[i],
                                      0, 0, Width[i], Height[i],
                                      0, 0, Width[i], Height[i], True);
                    }
                    xvupdateimage = false;
#else // CISST_SVL_HAS_XV
                    for (i = 0; i < NumOfWins; i ++) {
                        xImg[i]->data = reinterpret_cast<char*>(xImageBuffers[i]);
                        XPutImage(xDisplay,
                                  xWindows[i],
                                  xGCs[i],
                                  xImg[i],
                                  0, 0, 0, 0,
                                  Width[i], Height[i]);
                    }
#endif // CISST_SVL_HAS_XV
/*
                    for (i = 0; i < NumOfWins; i ++) {
                        if (CustomTitleEnabled[i] < 0) {
                            // Restore original timestamp
                            XSetStandardProperties(xDisplay, xWindows[i],
                                                   Titles[i].c_str(), Titles[i].c_str(),
                                                   None, NULL, 0, NULL);
                        }
                        else if (CustomTitleEnabled[i] > 0) {
                            // Set custom timestamp
                            XSetStandardProperties(xDisplay, xWindows[i],
                                                   CustomTitles[i].c_str(), CustomTitles[i].c_str(),
                                                   None, NULL, 0, NULL);
                        }
                    }
*/
                csImage.Leave();
            }
        }
    }

labError:

#if CISST_SVL_HAS_XV
    if (xvShmInfo) {
        for (i = 0; i < NumOfWins; i ++) {
            XShmDetach(xDisplay, &(xvShmInfo[i]));
            shmdt(xvShmInfo[i].shmaddr);
        }
        delete [] xvShmInfo; 
        xvShmInfo = 0;
    }
#endif // CISST_SVL_HAS_XV
    XSync(xDisplay, 0);
    for (i = 0; i < NumOfWins; i ++) {
        if (xGCs[i]) XFreeGC(xDisplay, xGCs[i]);
        if (xWindows[i]) XDestroyWindow(xDisplay, xWindows[i]);
    }
    XCloseDisplay(xDisplay);
#if CISST_SVL_HAS_XV
    if (xvImg) {
        for (i = 0; i < NumOfWins; i ++) {
            if (xvImg[i]) XFree(xvImg[i]); 
        }
        delete [] xvImg; 
        xvImg = 0;
    }
    if (xvPort) {
        delete [] xvPort; 
        xvPort = 0;
    }
#else // CISST_SVL_HAS_XV
    if (xImg) {
        for (i = 0; i < NumOfWins; i ++) {
            if (xImg[i]) XDestroyImage(xImg[i]); 
        }
        delete [] xImg; 
        xImg = 0;
    }
    if (xImageBuffers) {
        delete [] xImageBuffers;
        xImageBuffers = 0;
    }
#endif // CISST_SVL_HAS_XV
    if (xGCs) {
        delete [] xGCs;
        xGCs = 0;
    }
    if (xWindows) {
        delete [] xWindows;
        xWindows = 0;
    }
    if (Titles) {
        delete [] Titles;
        Titles = 0;
    }
    if (CustomTitles) {
        delete [] CustomTitles;
        CustomTitles = 0;
    }
    if (CustomTitleEnabled) {
        delete [] CustomTitleEnabled;
        CustomTitleEnabled = 0;
    }

    xScreen = 0;
    xDisplay = 0;

    if (DestroyedSignal) DestroyedSignal->Raise();

    return 0;
}
示例#24
0
文件: vidrgb.cpp 项目: jeez/iqr
int main(int argc, char **argv)

{
  Atom                atomWMDeleteWindow;
  int	              screenNumber;
  Screen              *screen;
  Window              window;
  XWindowAttributes   windowAttributes;
  Colormap            colormap;
  PaletteInfo         paletteInfo;
  Image               image;
  XImage              *xImage;
  int                 x, y;
  int                 captureFrame;
  XEvent              event;
  bool                sizeChanged;


  // ProgramExit initialization

  display = NULL;
  v4l = -1;
  captureBuf = NULL;

  on_exit(ProgramExit, NULL);

  // Get command line options

  magnification = 1;

  if (argc > 1) {
    magnification = atoi(argv[1]);
  } // end if

  magnification = max(1, magnification);

  printf("Magnification is %i\n", magnification);

  // Open display

  if ((display = XOpenDisplay(NULL)) == NULL) { // NULL for DISPLAY
    printf("Error: XOpenDisplay() failed\n");
    exit(1);
  } // end if

  screenNumber = DefaultScreen(display);

  screen = XScreenOfDisplay(display, screenNumber);

  // Obtain WM protocols atom for ClientMessage exit event

  if ((atomWMDeleteWindow = XInternAtom(display, AtomWMDeleteWindowName, True)) == None) {
    printf("Error: %s atom does not exist\n", AtomWMDeleteWindowName);
    exit(1);
  } // end if

  // Create window, inheriting depth and visual from root window

  window = XCreateSimpleWindow(
    display,
    RootWindowOfScreen(screen),
    0, // x
    0, // y
    640, // width
    480, // height
    0,                          // border width
    BlackPixelOfScreen(screen), // border
    BlackPixelOfScreen(screen)  // background
    );

  XStoreName(display, window, "V4L RGB Test");

  XGetWindowAttributes(display, window, &windowAttributes);

  if (((windowAttributes.depth == 8) && (windowAttributes.visual->c_class != PseudoColor)) ||
      ((windowAttributes.depth > 8) && (windowAttributes.visual->c_class != TrueColor))) {
    printf("Error: Visual not supported\n");
    exit(1);
  } // end if

  // Create PseudoColor HI240 colormap, if needed

  if (windowAttributes.depth == 8) {
    colormap = XCreateColormap(display, window, windowAttributes.visual, AllocAll);
    paletteInfo.display = display;
    paletteInfo.colormap = colormap;
    Hi240BuildPalette((ulong) 0x10000, (Hi240StorePaletteEntry *) StoreColormapEntry, &paletteInfo);
    XSetWindowColormap(display, window, colormap);
  } // end if

  // Create image

  if (image.Create(
    display,
    window, // Defines visual, depth
    MaxImageWidth,
    MaxImageHeight,
    True // MITSHM
    ) < 0) {
    printf("Error: image.Create() failed\n");
    exit(1);
  } // end if

  image.Clear();

#if (1)
  printf("\nDisplay:\n");
  printf("Image byte order = %s\n", ByteOrderName(ImageByteOrder(display)));
  printf("Bitmap unit      = %i\n", BitmapUnit(display));
  printf("Bitmap bit order = %s\n", ByteOrderName(BitmapBitOrder(display)));
  printf("Bitmap pad       = %i\n", BitmapPad(display));

  printf("\nWindow:\n");
  printf("Depth            = %i\n", windowAttributes.depth);
  printf("Visual ID        = 0x%02x\n", windowAttributes.visual->visualid);
  printf("Visual class     = %s\n", VisualClassName(windowAttributes.visual->c_class));
  printf("Red mask         = 0x%08lx\n", windowAttributes.visual->red_mask);
  printf("Green mask       = 0x%08lx\n", windowAttributes.visual->green_mask);
  printf("Blue mask        = 0x%08lx\n", windowAttributes.visual->blue_mask);
  printf("Bits per R/G/B   = %i\n", windowAttributes.visual->bits_per_rgb); // log2 # colors

  xImage = image.X();
  printf("\nImage:\n");
  printf("Image byte order = %s\n", ByteOrderName(xImage->byte_order));
  printf("Bitmap unit      = %i\n", xImage->bitmap_unit);
  printf("Bitmap bit order = %s\n", ByteOrderName(xImage->bitmap_bit_order));
  printf("Bitmap pad       = %i\n", xImage->bitmap_pad);
  printf("Depth            = %i\n", xImage->depth);
  printf("Red mask         = 0x%08lx\n", xImage->red_mask);
  printf("Green mask       = 0x%08lx\n", xImage->green_mask);
  printf("Blue mask        = 0x%08lx\n", xImage->blue_mask);
  printf("Bits per pixel   = %i\n", xImage->bits_per_pixel); // ZPixmap
  printf("Bytes per line   = %i\n", xImage->bytes_per_line);
  printf("IsShared         = %s\n", image.IsShared() ? "True" : "False");
  printf("HasSharedPixmap  = %s\n", image.HasSharedPixmap() ? "True" : "False");
#endif

  // V4L stuff

  if ((v4l = open(BigPictureDevice, O_RDWR)) < 0) {
    printf("Error: Can't open %s: %s\n", BigPictureDevice, strerror(errno));
    exit(1);
  } // end if

  if (V4LMGetMMInfo(v4l, &v4lMMInfo) < 0) {
    printf("Error: V4LMGetMMInfo: %s\n", strerror(errno));
    exit(1);
  } // end if
#if (0)
  printf("Capture buffer size   = %i\n", v4lMMInfo.size);
  printf("Capture buffer frames = %i\n", v4lMMInfo.frames);
#endif
  if (v4lMMInfo.frames < 2) {
    printf("Error: V4LMGetMMInfo: frames < 2\n");
    exit(1);
  } // end if

  if ((captureBuf = (bits8 *) mmap(0, v4lMMInfo.size, PROT_READ | PROT_WRITE, MAP_SHARED, v4l, 0)) == MAP_FAILED) {
    printf("Error: mmap(): %s\n", strerror(errno));
    exit(1);
  } // end if

  if (V4LSetSource(v4l, BigPictureCompositeSource, VIDEO_MODE_NTSC) < 0) {
    printf("Error: V4LSetSource: %s\n", strerror(errno));
    exit(1);
  } // end if

  if (V4LGetCaps(v4l, &v4lCaps) < 0) {
    printf("Error: V4LGetCaps: %s\n", strerror(errno));
    exit(1);
  } // end if

  // Select V4L RGB capture format to exactly match image/visual (no LUTs!)

  if ((captureFormat = XImageCaptureFormat(image.X())) < 0) {
    printf("Error: No  match for visual/image\n");
    exit(1);
  } // end if

  // Initialize capture size based on window size

  windowWidth = windowAttributes.width;
  windowHeight = windowAttributes.height;;

  WindowResize(v4l, windowWidth, windowHeight, magnification); // Does V4LMSetFormat().

  // Initialize picture attributes to mid-range

  V4LSetBrightness(v4l, 65535 / 2);
  V4LSetContrast(v4l, 65535 / 2);
  V4LSetSaturation(v4l, 65535 / 2);
  V4LSetHue(v4l, 65535 / 2);

  // Ready to start: Display window, select events, and initiate capture sequence

  XMapRaised(display, window);

  XSetWMProtocols(display, window, &atomWMDeleteWindow, 1);

  XSelectInput(display, window, StructureNotifyMask | ExposureMask);

  captureFrame = 0;

  if (V4LMCapture(v4l, captureFrame) < 0) {
    printf("Error: V4LMCapture: %s\n", strerror(errno));
    exit(1);
  } // end if

  while (1) {

    if (XPending(display) > 0) {

      XNextEvent(display, &event);

      switch (event.type) {
      case ClientMessage: // From WM
	if (event.xclient.data.l[0] == atomWMDeleteWindow) {
	  exit(0);
	} // end if
	break;
      case ConfigureNotify:
	sizeChanged = false;
	if (event.xconfigure.width != windowWidth) {
	  sizeChanged = true;
	  windowWidth = event.xconfigure.width;
	} // end if
	if (event.xconfigure.height != windowHeight) {
	  sizeChanged = true;
	  windowHeight = event.xconfigure.height;
	} // end if
	if (sizeChanged) {
	  image.Clear();
	  XClearWindow(display, window);
	  WindowResize(v4l, windowWidth, windowHeight, magnification);
	} // end if
	break;
      case Expose:
	if (event.xexpose.count == 0) {
	  Put(window, image);
	} // end if
	break;
      } // end switch

    } else {

      // Wait for this frame

      if (V4LMSync(v4l, captureFrame) < 0) {
	printf("Error: V4LMSync: %s\n", strerror(errno));
	exit(1);
      } // end if

      // Start capture for next frame

      if (V4LMCapture(v4l, 1 - captureFrame) < 0) {
	printf("Error: V4LMCapture: %s\n", strerror(errno));
	exit(1);
      } // end if

      Draw(image, captureBuf + v4lMMInfo.offsets[captureFrame], magnification);

      Put(window, image);

      captureFrame = 1 - captureFrame; // 0<->1

    } // endif 

  } // end while

  printf("Error: Fell out of event loop!\n");

  exit(1);

} // end main
示例#25
0
void
init_toneclock(ModeInfo * mi)
{
	Display    *display = MI_DISPLAY(mi);
	Window      window = MI_WINDOW(mi);
	int         i, size_hour, istart;
	toneclockstruct *tclock;

/* initialize */
	if (toneclocks == NULL) {
		if ((toneclocks = (toneclockstruct *) calloc(MI_NUM_SCREENS(mi),
				sizeof (toneclockstruct))) == NULL)
			return;
	}
	tclock = &toneclocks[MI_SCREEN(mi)];
	tclock->mi = mi;

	if (tclock->gc == None) {
		if (MI_IS_INSTALL(mi) && MI_NPIXELS(mi) > 2) {
			XColor      color;

#ifndef STANDALONE
			tclock->fg = MI_FG_PIXEL(mi);
			tclock->bg = MI_BG_PIXEL(mi);
#endif
			tclock->blackpixel = MI_BLACK_PIXEL(mi);
			tclock->whitepixel = MI_WHITE_PIXEL(mi);
			if ((tclock->cmap = XCreateColormap(display, window,
					MI_VISUAL(mi), AllocNone)) == None) {
				free_toneclock(display, tclock);
				return;
			}
			XSetWindowColormap(display, window, tclock->cmap);
			(void) XParseColor(display, tclock->cmap, "black", &color);
			(void) XAllocColor(display, tclock->cmap, &color);
			MI_BLACK_PIXEL(mi) = color.pixel;
			(void) XParseColor(display, tclock->cmap, "white", &color);
			(void) XAllocColor(display, tclock->cmap, &color);
			MI_WHITE_PIXEL(mi) = color.pixel;
#ifndef STANDALONE
			(void) XParseColor(display, tclock->cmap, background, &color);
			(void) XAllocColor(display, tclock->cmap, &color);
			MI_BG_PIXEL(mi) = color.pixel;
			(void) XParseColor(display, tclock->cmap, foreground, &color);
			(void) XAllocColor(display, tclock->cmap, &color);
			MI_FG_PIXEL(mi) = color.pixel;
#endif
			tclock->colors = (XColor *) NULL;
			tclock->ncolors = 0;
		}
		if ((tclock->gc = XCreateGC(display, MI_WINDOW(mi),
			     (unsigned long) 0, (XGCValues *) NULL)) == None) {
			free_toneclock(display, tclock);
			return;
		}
	}
/* Clear Display */
	MI_CLEARWINDOW(mi);
	tclock->painted = False;
	XSetFunction(display, tclock->gc, GXxor);


/*Set up toneclock data */
	if (MI_IS_FULLRANDOM(mi)) {
	   if (NRAND(10))
	     tclock->original = False;
	   else
	     tclock->original = True;
	} else {
	   tclock->original = original;
	}
	tclock->direction = (LRAND() & 1) ? 1 : -1;
	tclock->win_width = MI_WIDTH(mi);
	tclock->win_height = MI_HEIGHT(mi);
	if (tclock->hour != NULL)
		free_hour(tclock);
	if ( tclock->original )
          {
	     tclock->num_hour = 12;
	  }
        else
          {
	     tclock->num_hour = MI_COUNT(mi);
	  }
        tclock->x0 = tclock->win_width / 2;
        tclock->y0 = tclock->win_height / 2;
	if (tclock->num_hour == 0) {
		tclock->num_hour = DEF_NUM_hour;
	} else if (tclock->num_hour < 0) {
		tclock->num_hour = NRAND(-tclock->num_hour) + 1;
	}
        if ( tclock->num_hour < 12 )
          istart = NRAND( 12 - tclock->num_hour );
        else
          istart = 0;
	if ((tclock->hour = (toneclockhour *) calloc(tclock->num_hour,
			sizeof (toneclockhour))) == NULL) {
		free_toneclock(display, tclock);
		return;
	}
	if (MI_IS_INSTALL(mi) && MI_NPIXELS(mi) > 2) {
/* Set up colour map */
		if (tclock->colors != NULL) {
			if (tclock->ncolors && !tclock->no_colors)
				free_colors(display, tclock->cmap, tclock->colors, tclock->ncolors);
			free(tclock->colors);
			tclock->colors = (XColor *) NULL;
		}
		tclock->ncolors = MI_NCOLORS(mi);
		if (tclock->ncolors < 2)
			tclock->ncolors = 2;
		if (tclock->ncolors <= 2)
			tclock->mono_p = True;
		else
			tclock->mono_p = False;

		if (tclock->mono_p)
			tclock->colors = (XColor *) NULL;
		else
			if ((tclock->colors = (XColor *) malloc(sizeof (*tclock->colors) *
					(tclock->ncolors + 1))) == NULL) {
				free_toneclock(display, tclock);
				return;
			}
		tclock->cycle_p = has_writable_cells(mi);
		if (tclock->cycle_p) {
			if (MI_IS_FULLRANDOM(mi)) {
				if (!NRAND(8))
					tclock->cycle_p = False;
				else
					tclock->cycle_p = True;
			} else {
				tclock->cycle_p = cycle_p;
			}
		}
		if (!tclock->mono_p) {
			if (!(LRAND() % 10))
				make_random_colormap(
#ifdef STANDALONE
						MI_DISPLAY(mi), MI_WINDOW(mi),
#else
            mi,
#endif
						tclock->cmap, tclock->colors, &tclock->ncolors,
						True, True, &tclock->cycle_p);
			else if (!(LRAND() % 2))
				make_uniform_colormap(
#ifdef STANDALONE
						MI_DISPLAY(mi), MI_WINDOW(mi),
#else
            mi,
#endif
                  tclock->cmap, tclock->colors, &tclock->ncolors,
						      True, &tclock->cycle_p);
			else
				make_smooth_colormap(
#ifdef STANDALONE
						MI_DISPLAY(mi), MI_WINDOW(mi),
#else
            mi,
#endif
                 tclock->cmap, tclock->colors, &tclock->ncolors,
						     True, &tclock->cycle_p);
		}
		XInstallColormap(display, tclock->cmap);
		if (tclock->ncolors < 2) {
			tclock->ncolors = 2;
			tclock->no_colors = True;
		} else
			tclock->no_colors = False;
		if (tclock->ncolors <= 2)
			tclock->mono_p = True;

		if (tclock->mono_p)
			tclock->cycle_p = False;

	}
#ifndef NO_DBUF
	if (tclock->dbuf != None)
		XFreePixmap(display, tclock->dbuf);
	tclock->dbuf = XCreatePixmap(display, window,
		tclock->win_width,
		tclock->win_height,
		MI_DEPTH(mi));
	/* Allocation checked */
	if (tclock->dbuf != None) {
		XGCValues   gcv;

		gcv.foreground = 0;
		gcv.background = 0;
		gcv.graphics_exposures = False;
		gcv.function = GXcopy;

		if (tclock->dbuf_gc != None)
			XFreeGC(display, tclock->dbuf_gc);
		if ((tclock->dbuf_gc = XCreateGC(display, (Drawable) tclock->dbuf,
			GCForeground | GCBackground | GCGraphicsExposures | GCFunction,
				&gcv)) == None) {
			XFreePixmap(display, tclock->dbuf);
			tclock->dbuf = None;
		} else {
			XFillRectangle(display, (Drawable) tclock->dbuf, tclock->dbuf_gc,
				0, 0, tclock->win_width, tclock->win_height);
			/*XSetBackground(display, MI_GC(mi), MI_BLACK_PIXEL(mi));
			XSetFunction(display, MI_GC(mi), GXcopy);*/
		}
	}
#endif
	tclock->angle = NRAND(360) * PI_RAD;
	tclock->velocity = (NRAND(7) - 3) * PI_RAD;
	size_hour = MIN( tclock->win_width , tclock->win_height) / 3;
   tclock->pulsating = False;
   tclock->moving = False;
   tclock->anglex = 0.0;
   tclock->angley = 0.0;
   tclock->fill = 0;
   tclock->radius = size_hour;
   tclock->max_radius =0.0;
   if ( ( !tclock->original && NRAND( 15 ) == 3 ) || tclock->num_hour > 12 )
     tclock->randomhour = True;
   else
     tclock->randomhour = False;
   if ( !tclock->original && tclock->win_width > 20 )
     {
	if ( abs( MI_SIZE(mi) ) > size_hour ) {
	   if ( MI_SIZE( mi ) < 0 )
	     {
		size_hour = -size_hour;
	     }
	}
	else
	  {
	     size_hour = MI_SIZE(mi);
          }
    	if ( size_hour < 0 )
          {
	     tclock->radius = MIN(NRAND( size_hour - 10) + 10,
		tclock->radius );
          }
        else
          {
  	     tclock->radius = MIN( size_hour , tclock->radius );
          }
	if ( MI_IS_FULLRANDOM( mi ) )
	  {
	     if ( NRAND(2) )
	       tclock->pulsating = True;
	     else
	       tclock->pulsating = False;
	     tclock->fill = NRAND( 101 );
	  }
	else
	  {
	     tclock->pulsating = pulsating;
	     tclock->fill = fill;
	  }
     }
   tclock->phase = 0.0;
   if ( tclock->pulsating )
	tclock->ph_vel = (NRAND(7) - 3) * PI_RAD;
   for (i = 0; i < tclock->num_hour; i++) {
		toneclockhour *hour0;

		hour0 = &tclock->hour[i];
		if (MI_IS_INSTALL(mi) && MI_NPIXELS(mi) > 2) {
			if (tclock->ncolors > 2)
				hour0->colour = NRAND(tclock->ncolors - 2) + 2;
			else
				hour0->colour = 1;	/* Just in case */
			XSetForeground(display, tclock->gc, tclock->colors[hour0->colour].pixel);
		} else {
			if (MI_NPIXELS(mi) > 2)
				hour0->colour = MI_PIXEL(mi, NRAND(MI_NPIXELS(mi)));
			else
				hour0->colour = 1;	/*Xor'red so WHITE may not be appropriate */
			XSetForeground(display, tclock->gc, hour0->colour);
		}
		hour0->angle = NRAND(360) * PI_RAD;
		hour0->velocity = (NRAND(7) - 3) * PI_RAD;
	        hour0->radius = tclock->radius / 5.0;
      		tclock->max_radius = MAX( tclock->max_radius , hour0->radius );
	        hour0->num_point = 12;
		hour0->num_point1 = 16;
                if ( tclock->randomhour )
	          {
		     int j;

		     hour0->point_numbers = tclock->hexadecimal_clock + i *
			     hour0->num_point1;
		     if ( NRAND( 14 ) == 4 )
		       {
			  for (j = 0; j < ( hour0->num_point1 / 4 ) - 1 ; j++)
			    {
			       hour0->point_numbers[ j * 4 ] = NRAND( 12 ) + 1;
			       hour0->point_numbers[ j * 4 + 1 ] = NRAND( 12 )
				 + 1;
			       hour0->point_numbers[ j * 4 + 2 ] = NRAND( 12 )
				 + 1;
			       hour0->point_numbers[ j * 4 + 3 ] = NRAND( 12 )
				 + 1;
			    }
			  hour0->point_numbers[ hour0->num_point1 / 4 ] = 1;
			  hour0->point_numbers[ 1 + hour0->num_point1 / 4 ] =
			    1;
			  hour0->point_numbers[ 2 + hour0->num_point1 / 4 ] =
			    1;
			  hour0->point_numbers[ 3 + hour0->num_point1 / 4 ] =
			    1;
		       }
		     else
		       {
			  for (j = 0; j < hour0->num_point1 / 4 ; j++)
			    {
			       hour0->point_numbers[ j * 4 ] = NRAND( 12 ) + 1;
			       hour0->point_numbers[ j * 4 + 1 ] =
				 hour0->point_numbers[ j * 4 ];
			       hour0->point_numbers[ j * 4 + 2 ] = NRAND( 12 )
				 + 1;
			       hour0->point_numbers[ j * 4 + 3 ] = NRAND( 12 )
				 + 1;
			    }
		       }
	          }
                else
	          hour0->point_numbers = original_clock[i+istart];
		if ( NRAND( 100 ) >= tclock->fill )
			hour0->draw = True;
		else
			hour0->draw = False;
#ifdef NO_DBUF
		{
		  int x0 , y0;

		  x0 = (int) (tclock->radius * sin( -tclock->angle - PI_RAD * i *
			360.0 / tclock->num_hour ) *
			0.5 * ( 1 + cos( tclock->phase ) ) + tclock->x0 +
			tclock->a_x * sin( tclock->anglex ) );
		  y0 = (int) (tclock->radius * cos( -tclock->angle - PI_RAD * i *
			360.0 / tclock->num_hour ) *
			0.5 * ( 1 + cos( tclock->phase ) ) + tclock->y0 +
			tclock->a_y * sin( tclock->angley ) );
	 	  toneclock_drawhour(mi , hour0 , x0 , y0 );
		}
#endif
	}
   tclock->a_x = 0;
   tclock->a_y = 0;
   if ( !tclock->original && tclock->win_width > 20 )
     {
	if ( tclock->radius < MIN( tclock->win_width , tclock->win_height) /
	     4 )
	  {
	     if ( MI_IS_FULLRANDOM( mi ) )
	       {
		  if ( NRAND(2) )
		    tclock->moving = True;
	       }
	     else
	       {
		    tclock->moving = move_clock;
	       }
	     if ( tclock->moving )
	       {
		  tclock->a_x = (int) floor( ( tclock->win_width / 2 ) - 1.05 *
					( tclock->radius + tclock->max_radius )
					);
		  tclock->a_y = (int) floor( ( tclock->win_height / 2 ) - 1.05 *
					( tclock->radius + tclock->max_radius )
					);
		  tclock->vx = (NRAND(15) - 7) * PI_RAD;
		  tclock->vy = (NRAND(15) - 7) * PI_RAD;
	       }
	  }
     }
	XFlush(display);
	XSetFunction(display, tclock->gc, GXcopy);
}
示例#26
0
void Xinitialize (int width, int height)
{
	XVisualInfo vinfo_return;
	XSetWindowAttributes wa;
	Pixmap mask, cur;
	XColor black, white;

	black.red = black.green = black.blue = 0;
	/* buggered if I care, its just for an invisible cursor :] */
	white.red = white.green = white.blue = 0;

	xWidth = width;
	xHeight = height;

#ifdef __DEBUG__
	printf ("xshm: connecting to X server\n");
#endif

	if ((dp = XOpenDisplay (0)) == 0) {
		printf ("xshm: could not open X display\n");
		exit (0);
		}

	XSetCloseDownMode (dp, DestroyAll);
	screen = DefaultScreen (dp);

	if (XMatchVisualInfo (dp, DefaultScreen (dp),
		8, PseudoColor, &vinfo_return) == False) {
		printf ("X: Screen doesn't support PseudoColor!\n");
		exit(666);
		}

	/* Make sure all is destroyed if killed off */
	/* Make sure we can do PsuedoColor colormap stuff */

	if (!XShmQueryExtension (dp)) {
		/* Check to see if the extensions are supported */
		fprintf (stderr, "X server doesn't support MITSHM extension.\n");
		exit(666);
	} else if (!XShmPixmapFormat (dp)) {
		fprintf (stderr, "X server doesn't do shared memory pixmaps.\n");
		exit(666);
	} 
#ifdef __DEBUG__
	else printf ("xshm: MITSHM present\n");
#endif


	wi = XCreateSimpleWindow (dp, RootWindow (dp, screen), 50, 50, xWidth, xHeight, 0, 0, 0);
        colours = XCreateColormap (dp, wi, DefaultVisual (dp, XDefaultScreen (dp)),
                                      AllocAll);
        XSetWindowColormap (dp, wi, colours);

        cur = XCreatePixmapFromBitmapData (dp, wi, (char *) nocursorm_bits,
                nocursorm_width, nocursorm_height, (unsigned long) 1,
                (unsigned long) 0, (unsigned int) 1);
        mask = XCreatePixmapFromBitmapData (dp, wi, (char *) nocursorm_bits,
                nocursorm_width, nocursorm_height, (unsigned long) 1,
                (unsigned long) 0, (unsigned int) 1);
	cursor = XCreatePixmapCursor (dp, cur, mask, &black, &white, 0, 0);

	XFreePixmap (dp, cur);
	XFreePixmap (dp, mask);

	XDefineCursor (dp, wi, cursor);

	XMapWindow(dp, wi);

	GetShmPixmap();
	XSetWindowBackgroundPixmap (dp, wi, pixmap);

	XSelectInput(dp, wi, KeyPressMask|KeyReleaseMask|ButtonPressMask|
		ButtonReleaseMask|PointerMotionMask|LeaveWindowMask|ExposureMask);
	atexit( Xuninitialize );
}
示例#27
0
文件: xf86.cpp 项目: dezro/snes9x
void S9xInitDisplay (int argc, char **argv)
{
	Screen			*scrn;
	XSetWindowAttributes	xattr;

	signal (SIGINT, quit);
	signal (SIGTERM, quit);

	if ((ourdisp = XOpenDisplay(NULL)) == NULL) {
		printf ("Can't connect to X server!\n");
		S9xExit ();
	}


	ourscreen = DefaultScreen (ourdisp);
	scrn = DefaultScreenOfDisplay (ourdisp);
	ourvideo.bitdepth = DefaultDepth (ourdisp, ourscreen);
	ourvideo.screendepth = ourvideo.bitdepth / 8;
	rootWindow = RootWindowOfScreen (scrn);

	xattr.override_redirect = True;
	inputwin = XCreateWindow (ourdisp, RootWindowOfScreen(scrn),
	                          10, 10, 100, 100, 0, 0, InputOutput,
	                          DefaultVisualOfScreen(scrn),
	                          CWOverrideRedirect, &xattr);
	XMapWindow (ourdisp, inputwin);

	ourvideo.height = HeightOfScreen (scrn);



	switch (ourvideo.bitdepth) {
		case  8:
			Settings.SixteenBit = FALSE;
			Settings.Transparency = FALSE;
			cmap = XCreateColormap (ourdisp, rootWindow,
			                        DefaultVisualOfScreen (scrn),
						AllocAll);
			XSetWindowColormap (ourdisp, inputwin, cmap);
			for (int i=0; i<256; i++) {
				colors[i].pixel = i;
				colors[i].flags = DoRed | DoGreen | DoBlue;
			}
			break;
		case 16:
			Settings.SixteenBit = TRUE;
			if (!Settings.ForceNoTransparency)
				Settings.Transparency = TRUE;
			break;
		case 24:
			if (is32or24 == 32) {
				ourvideo.bitdepth = 32;
				ourvideo.screendepth = 4;
			}
			Settings.SixteenBit = TRUE;
			if (!Settings.ForceNoTransparency)
				Settings.Transparency = TRUE;
			break;
		default:
			printf ("Color depth %d not supported!\n");
			S9xExit ();
			break;
	}
	printf ("Found %d bit display\n", ourvideo.bitdepth);

	XFree(scrn);

	XF86DGAGetVideo (ourdisp, ourscreen, &(ourvideo.vidMemBegin),
          	       &(ourvideo.width), &(ourvideo.banksize),
          	       &(ourvideo.memsize));

#ifdef USE_XF86VIDMODE
   {
	XF86VidModeModeInfo	**all_modes;
	int			mode_count;
	XF86VidModeModeLine	mod_tmp;
	int			dotclock_tmp;
	int			x;

	XF86VidModeGetModeLine (ourdisp, ourscreen, &dotclock_tmp, &mod_tmp);

	orig_mode = ModeLine2ModeInfo (mod_tmp, dotclock_tmp);
	if (orig_mode->hdisplay == 320 && orig_mode->vdisplay == 240) {
		mod320x240 = orig_mode;
	} else {
		XF86VidModeGetAllModeLines (ourdisp,ourscreen, &mode_count,
		                            &all_modes);
		for (x = 0; x < mode_count; x++)
			if (all_modes[x]->hdisplay == 320 &&
			    all_modes[x]->vdisplay == 240) {
				mod320x240 = (XF86VidModeModeInfo *) malloc (
				               sizeof(XF86VidModeModeInfo));
				*mod320x240 = *(all_modes[x]);
				break;
			} else
				XFree (all_modes[x]->c_private);

		if (mod320x240 == NULL) {
			printf ("No 320x240 mode available!\n");
			S9xExit ();
		}

	}
	XFree(all_modes);

   }
#endif

	GFX.Pitch = IMAGE_WIDTH * (Settings.SixteenBit ? 2 : 1);
	GFX.Screen = (uint8 *) malloc (IMAGE_HEIGHT * GFX.Pitch);

	if (Settings.Transparency)
		GFX.SubScreen = (uint8 *) malloc (IMAGE_HEIGHT * GFX.Pitch);

	switch (ourvideo.bitdepth) {
		case  8:
			mWide = IMAGE_WIDTH / 4;
			mHigh = IMAGE_HEIGHT;
			mEtoE = (ourvideo.width - IMAGE_WIDTH) /4;
			break;
		case 16:
			mWide = IMAGE_WIDTH / 2;
			mHigh = IMAGE_HEIGHT;
			mEtoE = (ourvideo.width - IMAGE_WIDTH) / 2;
			break;
		case 24:
			mWide = IMAGE_WIDTH;
			mHigh = IMAGE_HEIGHT;
			mEtoE = (ourvideo.width - IMAGE_WIDTH) * 3;
			break;
		case 32:
			mWide = IMAGE_WIDTH;
			mHigh = IMAGE_HEIGHT;
			mEtoE = (ourvideo.width - IMAGE_WIDTH) * 4;
		default:
			break;
	}
	ourvideo.scrnBegin = ourvideo.vidMemBegin + (320 - IMAGE_WIDTH) * ourvideo.screendepth / 2 + ourvideo.width * ourvideo.screendepth * 8;
}
示例#28
0
/* Ouvre une fenetre pour l'affichage du GUI */
void OpenWindow ()
{
 XTextProperty Name;
 XWMHints *IndicWM;
 XSizeHints *IndicNorm;
 unsigned long mask;
 XSetWindowAttributes Attr;

 /* Allocation des couleurs */
 MyAllocNamedColor(x11base->display,x11base->colormap,x11base->forecolor,&x11base->TabColor[fore]);
 MyAllocNamedColor(x11base->display,x11base->colormap,x11base->backcolor,&x11base->TabColor[back]);
 MyAllocNamedColor(x11base->display,x11base->colormap,x11base->shadcolor,&x11base->TabColor[shad]);
 MyAllocNamedColor(x11base->display,x11base->colormap,x11base->licolor,&x11base->TabColor[li]);
 MyAllocNamedColor(x11base->display,x11base->colormap,"#000000",&x11base->TabColor[black]);
 MyAllocNamedColor(x11base->display,x11base->colormap,"#FFFFFF",&x11base->TabColor[white]);

 /* Definition des caracteristiques de la fentre */
 mask=0;
 mask|=CWBackPixel;
 Attr.background_pixel=x11base->TabColor[back].pixel;
 
 x11base->win=XCreateWindow(x11base->display,
			DefaultRootWindow(x11base->display),
			x11base->size.x,
			x11base->size.y,
			x11base->size.width,
			x11base->size.height,0,
			CopyFromParent,
			InputOutput,
			CopyFromParent,
			mask,&Attr);

 XSetWindowColormap(x11base->display,x11base->win,x11base->colormap);
 x11base->gc=XCreateGC(x11base->display,x11base->win,0,NULL);

 /* Choix des evts recus par la fenetre */
 XSelectInput(x11base->display,x11base->win,KeyPressMask|ButtonPressMask|
	ExposureMask|ButtonReleaseMask|EnterWindowMask|LeaveWindowMask|ButtonMotionMask);
 XSelectInput(x11base->display,x11base->root,PropertyChangeMask);
 
 /* Specification des parametres utilises par le gestionnaire de fenetre */
 if (XStringListToTextProperty(&x11base->title,1,&Name)==0)
  fprintf(stderr,"Can't use icon name\n");
 IndicNorm=XAllocSizeHints();
 if (x11base->size.x!=-1)
 {
  IndicNorm->x=x11base->size.x;
  IndicNorm->y=x11base->size.y;
  IndicNorm->flags=PSize|PMinSize|PMaxSize|PResizeInc|PBaseSize|PPosition;
 }
 else
  IndicNorm->flags=PSize|PMinSize|PMaxSize|PResizeInc|PBaseSize;
 IndicNorm->width=x11base->size.width;
 IndicNorm->height=x11base->size.height;
 IndicNorm->min_width=x11base->size.width;
 IndicNorm->min_height=x11base->size.height;
 IndicNorm->max_width=x11base->size.width;
 IndicNorm->max_height=x11base->size.height;
 IndicWM=XAllocWMHints();
 IndicWM->input=True;
 IndicWM->initial_state=NormalState;
 IndicWM->flags=InputHint|StateHint;
 XSetWMProperties(x11base->display,x11base->win,&Name,
       &Name,NULL,0,IndicNorm,IndicWM,NULL);
 Scrapt=(char*)calloc(sizeof(char),1);
 
 /* Construction des atomes pour la communication inter-application */
 propriete=XInternAtom(x11base->display,"Prop_selection",False);
 wm_del_win = XInternAtom(x11base->display,"WM_DELETE_WINDOW",False);
 XSetWMProtocols(x11base->display,x11base->win,&wm_del_win,1);

}
示例#29
0
int XBSetColormap( XBWindow * XBWin ){
	XSetWindowColormap( XBWin->disp, XBWin->win, XBWin->cmap );
	return 0;
}
示例#30
0
文件: video_X.c 项目: eswartz/emul
static      vmResult
X_video_restart(void)
{
	/*  Allocate colors every time we enable, 
	   in case some color-hogging apps have left. */

	int         tries = 0;
	int         x, alloced;

	//  Allocate our colors.  For using_palette, allocate read/write
	//  colorcells for 17 colors (bg and text fg change).  Else,
	//  allocate 15 colors.
	//  Either way, cmap[] maps each color to the pixel used to
	//  display it.

	x11_cmap = DefaultColormap(x11_dpy, x11_screen);

	//  Go through twice:  first time, try to allocate colors
	//  from default colormap.  If this fails sufficiently,
	//  allocate a virtual colormap.
	do {

		//  This tells us if colors 0 and 16 (for video reg 7)
		//  can change at will, or if we need to redraw the screen for them
		using_palette = x11_class != TrueColor
			&& x11_class != StaticColor && x11_class != StaticGray;

		//  Get 15 immutable cells
		alloced = 0;
		for (x = 1; x < 16; x++) {
			XColor      color;
			XcmsColor   cmClrScrn, cmClrExact;
			XcmsColorFormat cmFmt;

			color.red = RGB_8_TO_16(vdp_palette[x][0]);
			color.green = RGB_8_TO_16(vdp_palette[x][1]);
			color.blue = RGB_8_TO_16(vdp_palette[x][2]);
			color.flags = DoRed | DoGreen | DoBlue;

			if (!XAllocColor(x11_dpy, x11_cmap, &color)) {
				if (!XAllocNamedColor(x11_dpy, x11_cmap, Xcolornames[x],
									  &color, &color)) {
					module_logger(&X_Video, _L|L_1, _("could not allocate color %d\n"), x);
					//return vmInternalError;
				} else {
					module_logger(&X_Video, _L|L_1, _("color #%d:  got named color '%s'\n"), x,
						 Xcolornames[x]);
					alloced++;
				}
			} else {
				module_logger(&X_Video, _L|L_1, _("color #%d:  got RGB color\n"), x);
				alloced += 2;
			}

			colormap[x] = color.pixel;

		}

		//  Get fg/bg colors
		if (using_palette) {
			if (!XAllocColorCells(x11_dpy, x11_cmap, False /* contiguous */ ,
								  x11_planes, 0, colormap, 1)) {
				using_palette = false;
			} else
				if (!XAllocColorCells
					(x11_dpy, x11_cmap, False /* contiguous */ ,
					 x11_planes, 0, colormap + 16, 1)) {
				using_palette = false;
				// free the one color we got
				XFreeColors(x11_dpy, x11_cmap, colormap, 1, x11_planes[0]);
			}
			if (!using_palette)
				module_logger(&X_Video, _L|LOG_ERROR |L_1,
					 _("Could not allocate 2 read/write colorcells\n"));
		}
//		if (!using_palette) {
//			cmap[0] = cmap[1];
//			cmap[16] = cmap[15];
//		}

		//  If we got an insufficient number of colors,
		//  try for virtual colormap.
		module_logger(&X_Video, _L|L_1, _("alloced = %d\n"), alloced);
		if (!tries && alloced < 16 &&
			(x11_class == GrayScale || x11_class == PseudoColor)) {
			x11_cmap = XCreateColormap(x11_dpy, vwin, x11_visual, AllocNone);
			XSetWindowColormap(x11_dpy, vwin, x11_cmap);
			module_logger(&X_Video, _L|LOG_USER, _("allocated custom colormap for window\n"));
		} else {
			tries = 1;
		}

	} while (++tries < 2);

	XSetWindowColormap(x11_dpy, vwin, x11_cmap);

	XSetWMNormalHints(x11_dpy, vwin, vwin_size_hints);
	XMapWindow(x11_dpy, vwin);

//	x_dirty_screen(0, 0, 32, 24);
	return vmOk;
}