Ejemplo n.º 1
0
int main(int, char **)
{
    Display *d = XOpenDisplay(NULL);
    XCloseDisplay(d);
    return 0;
}
Ejemplo n.º 2
0
Archivo: slock.c Proyecto: eepp/slock
int
main(int argc, char **argv) {
#ifndef HAVE_BSD_AUTH
	const char *pws;
#endif
	Display *dpy;
	int screen;

	srand(time(NULL));

	if((argc == 2) && !strcmp("-v", argv[1]))
		die("slock-%s, © 2006-2012 Anselm R Garbe, 2013 Philippe Proulx\n", VERSION);
	else if(argc != 1)
		usage();

#ifdef __linux__
	dontkillme();
#endif

	if(!getpwuid(getuid()))
		die("slock: no passwd entry for you\n");

#ifndef HAVE_BSD_AUTH
	pws = getpw();
#endif

	if(!(dpy = XOpenDisplay(0)))
		die("slock: cannot open display\n");
	/* Get the number of screens in display "dpy" and blank them all. */
	nscreens = ScreenCount(dpy);
	locks = malloc(sizeof(Lock *) * nscreens);
	if(locks == NULL)
		die("slock: malloc: %s\n", strerror(errno));
	int nlocks = 0;
	for(screen = 0; screen < nscreens; screen++) {
		if ( (locks[screen] = lockscreen(dpy, screen)) != NULL)
			nlocks++;
	}
	XSync(dpy, False);

	/* Did we actually manage to lock something? */
	if (nlocks == 0) { // nothing to protect
		free(locks);
		XCloseDisplay(dpy);
		return 1;
	}

	/* Everything is now blank. Now wait for the correct password. */
#ifdef HAVE_BSD_AUTH
	readpw(dpy);
#else
	readpw(dpy, pws);
#endif

	/* Password ok, unlock everything and quit. */
	for(screen = 0; screen < nscreens; screen++)
		unlockscreen(dpy, locks[screen]);

	free(locks);
	XCloseDisplay(dpy);

	return 0;
}
Ejemplo n.º 3
0
int find_device(const char* pre_device, bool verbose, bool list_devices,
        XID& device_id, const char*& device_name, XYinfo& device_axys)
{
    bool pre_device_is_id = true;
    int found = 0;

    Display* display = XOpenDisplay(NULL);
    if (display == NULL) {
        fprintf(stderr, "Unable to connect to X server\n");
        exit(1);
    }

    int xi_opcode, event, error;
    if (!XQueryExtension(display, "XInputExtension", &xi_opcode, &event, &error)) {
        fprintf(stderr, "X Input extension not available.\n");
        exit(1);
    }

    // verbose, get Xi version
    if (verbose) {
        XExtensionVersion *version = XGetExtensionVersion(display, INAME);

        if (version && (version != (XExtensionVersion*) NoSuchExtension)) {
            printf("DEBUG: %s version is %i.%i\n",
                INAME, version->major_version, version->minor_version);
            XFree(version);
        }
    }

    if (pre_device != NULL) {
        // check whether the pre_device is an ID (only digits)
        int len = strlen(pre_device);
        for (int loop=0; loop<len; loop++) {
	        if (!isdigit(pre_device[loop])) {
	            pre_device_is_id = false;
	            break;
	        }
        }
    }


    if (verbose)
        printf("DEBUG: Skipping virtual master devices and devices without axis valuators.\n");
    int ndevices;
    XDeviceInfoPtr list, slist;
    slist=list=(XDeviceInfoPtr) XListInputDevices (display, &ndevices);
    for (int i=0; i<ndevices; i++, list++)
    {
        if (list->use == IsXKeyboard || list->use == IsXPointer) // virtual master device
            continue;

        // if we are looking for a specific device
        if (pre_device != NULL) {
            if ((pre_device_is_id && list->id == (XID) atoi(pre_device)) ||
                (!pre_device_is_id && strcmp(list->name, pre_device) == 0)) {
                // OK, fall through
            } else {
                // skip, not this device
                continue;
            }
        }

        XAnyClassPtr any = (XAnyClassPtr) (list->inputclassinfo);
        for (int j=0; j<list->num_classes; j++)
        {

            if (any->c_class == ValuatorClass)
            {
                XValuatorInfoPtr V = (XValuatorInfoPtr) any;
                XAxisInfoPtr ax = (XAxisInfoPtr) V->axes;

                if (V->mode != Absolute) {
                    if (verbose)
                        printf("DEBUG: Skipping device '%s' id=%i, does not report Absolute events.\n",
                            list->name, (int)list->id);
                } else if (V->num_axes < 2 ||
                    (ax[0].min_value == -1 && ax[0].max_value == -1) ||
                    (ax[1].min_value == -1 && ax[1].max_value == -1)) {
                    if (verbose)
                        printf("DEBUG: Skipping device '%s' id=%i, does not have two calibratable axes.\n",
                            list->name, (int)list->id);
                } else {
                    /* a calibratable device (has 2 axis valuators) */
                    found++;
                    device_id = list->id;
                    device_name = my_strdup(list->name);
                    device_axys.x_min = ax[0].min_value;
                    device_axys.x_max = ax[0].max_value;
                    device_axys.y_min = ax[1].min_value;
                    device_axys.y_max = ax[1].max_value;

                    if (list_devices)
                        printf("Device \"%s\" id=%i\n", device_name, (int)device_id);
                }

            }

            /*
             * Increment 'any' to point to the next item in the linked
             * list.  The length is in bytes, so 'any' must be cast to
             * a character pointer before being incremented.
             */
            any = (XAnyClassPtr) ((char *) any + any->length);
        }

    }
    XFreeDeviceList(slist);
    XCloseDisplay(display);

    return found;
}
Ejemplo n.º 4
0
// main method largely inspired from opengl wiki
// http://www.opengl.org/wiki/Tutorial%3a_OpenGL_3.0_Context_Creation_%28GLX%29
int main (int argc, char** argv) {

    Display* display = XOpenDisplay(nullptr);
    if (display == nullptr) {
        printf("Failed to open X display\n");
        exit(1);
    }

    int visual_attribs[] = {
        GLX_RED_SIZE        , 8,
        GLX_GREEN_SIZE      , 8,
        GLX_BLUE_SIZE       , 8,
        GLX_ALPHA_SIZE      , 8,
        GLX_DEPTH_SIZE      , 24,
        GLX_DOUBLEBUFFER    , True,
        None
    };

    int glx_major, glx_minor;
    if (!glXQueryVersion(display, &glx_major, &glx_minor) ||
       ((glx_major == 1) && (glx_minor < 3)) || (glx_major < 1))
    {
        printf("Invalid GLX version");
        exit(1);
    }

    int fbcount;
    GLXFBConfig* fbc = glXChooseFBConfig(display, DefaultScreen(display), visual_attribs, &fbcount);
    if (fbc == nullptr) {
        printf("Failed to retrieve a framebuffer config\n");
        exit(1);
    }

    // Pick the FB config/visual with the most samples per pixel
    int best_fbc = -1, best_num_samp = -1;
    for (int i = 0; i < fbcount; i++) {
        XVisualInfo *vi = glXGetVisualFromFBConfig(display, fbc[i]);
        if (vi != nullptr) {
            int samp_buf, samples;
            glXGetFBConfigAttrib(display, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf);
            glXGetFBConfigAttrib(display, fbc[i], GLX_SAMPLES, &samples);
            if (best_fbc < 0 || (samp_buf && samples > best_num_samp)) {
                best_fbc = i, best_num_samp = samples;
            }
        }
        XFree(vi);
    }
    GLXFBConfig bestFbc = fbc[best_fbc];
    XFree(fbc);

    XVisualInfo *vi = glXGetVisualFromFBConfig(display, bestFbc);
    XSetWindowAttributes swa;
    Colormap cmap;
    swa.colormap = cmap = XCreateColormap(display, RootWindow(display, vi->screen), vi->visual, AllocNone);
    swa.background_pixmap = None;
    swa.border_pixel = 0;
    swa.event_mask = StructureNotifyMask | KeyPressMask;
    Window win = XCreateWindow(display, RootWindow(display, vi->screen), 0, 0, 800, 600,
        0, vi->depth, InputOutput, vi->visual, CWBorderPixel|CWColormap|CWEventMask, &swa);
    if (!win) {
        printf("Failed to create window.\n");
        exit(1);
    }
    XFree(vi);

    XStoreName(display, win, "Tutorial 02");
    XMapWindow(display, win);

    // Get the default screen's GLX extension list
    const char *glxExts = glXQueryExtensionsString(display, DefaultScreen(display));
    glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0;
    glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc) glXGetProcAddressARB((const GLubyte *) "glXCreateContextAttribsARB");

    GLXContext ctx = nullptr;

    // Install an X error handler so the application won't exit if GL 3.0
    // context allocation fails.
    ctxErrorOccurred = false;
    int (*oldHandler)(Display*, XErrorEvent*) = XSetErrorHandler(&ctxErrorHandler);

    // Check for the GLX_ARB_create_context extension string and the function.
    if (isExtensionSupported(glxExts, "GLX_ARB_create_context") && glXCreateContextAttribsARB) {
        int context_attribs[] = {
            GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
            GLX_CONTEXT_MINOR_VERSION_ARB, 1,
            None
        };
        ctx = glXCreateContextAttribsARB(display, bestFbc, 0, True, context_attribs);

        // Sync to ensure any errors generated are processed.
        XSync(display, False);
        if (ctxErrorOccurred || ctx == nullptr) {
            printf("Could not create GL 3.0 context\n");
            exit(1);
        }
    }

    // Sync to ensure any errors generated are processed.
    XSync(display, False);
    // Restore the original error handler
    XSetErrorHandler(oldHandler);

    glXMakeCurrent(display, win, ctx);

    // must be called AFTER the OpenGL context has been created
    glewInit(); 

    reshape(800, 600);

    bool done = false;
    while (!done) {
        while (XPending(display) > 0) {
            XEvent event;
            XNextEvent(display, &event);
            switch (event.type) {
            case Expose:
                break;
            case ConfigureNotify:
                reshape(event.xconfigure.width, event.xconfigure.height);
                break;
            case KeyPress:
                done = true;
                break;
            }
        }
        render();
        glXSwapBuffers(display, win);
    }

    glXDestroyContext(display, ctx);
    XDestroyWindow(display, win);
    XFreeColormap(display, cmap);
    XCloseDisplay(display);
}
Ejemplo n.º 5
0
int main(const int argc, const char **argv)
{
	if (argc > 2) {
		fprintf(stderr, "Unexpected arguments count.\n");
		return EXIT_FAILURE;
	}
	
	if (argc != 2) {
		show_help();
		return EXIT_FAILURE;
	}
	
	app_mode mode;
	
	if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0) {
		show_help();
		return EXIT_SUCCESS;
	} else if (strcmp(argv[1], "-t") == 0 || strcmp(argv[1], "--toggle") == 0) {
		printf("Started with toggle switching mode.\n");
		mode = TOGGLE;
	} else if (strcmp(argv[1], "-m") == 0 || strcmp(argv[1], "--modifier") == 0) {
		printf("Started with modifier mode.\n");
		mode = MODIFIER;
	} else {
		fprintf(stderr, "Unrecognized argument: '%s'.\n", argv[1]);
		show_help();
		return EXIT_FAILURE;
	}
	
	const paths my_paths = get_paths();
	
	const int key_on_num  = read_cfg_key_num(my_paths.on_key_cfg);
	const int key_off_num =
		(mode == TOGGLE) ? read_cfg_key_num(my_paths.off_key_cfg) : -1;
	
	printf("On-key number: %d\n", key_on_num);
	if (mode == TOGGLE) {
		printf("Off-key number: %d\n", key_off_num);
	}
	
	const char* on_bin_cache  = read_file_to_str(my_paths.on_bin);
	const char* off_bin_cache = read_file_to_str(my_paths.off_bin);
	
	Display *dpy = XOpenDisplay(NULL);
	Window   wnd = DefaultRootWindow(dpy);
	
	int  last_key_state = 0; // when is --toggle mode and on/off keys is same
	int  last_state     = 0;
	char keys_return[KEYS_LIMIT];
	while (1) {
		
		XQueryKeymap(dpy, keys_return);
		
		int on_key_state  = 0;
		int off_key_state = 0;
		
		// for triggering keyoffs
		int stored_keys[KEYS_LIMIT];
		int stored_keys_count = 0;
		
		int is_off_triggered = 0;
		
		for (int i=0; i<KEYS_LIMIT; i++) {
			
			if (keys_return[i] != 0) {
				
				int pos = 0;
				int num = keys_return[i];
				
				while (pos < 8) {
					
					if ((num & 0x01) == 1) {
						
						int key_num = i*8+pos;
						
						if (key_num == key_on_num) {
							on_key_state = 1;
						}
						if (mode == TOGGLE && key_num == key_off_num) {
							off_key_state = 1;
						}
						
						if (key_num != key_on_num && key_num != key_off_num) {
							stored_keys[stored_keys_count++] = key_num;
						}
					}
					
					++pos;
					num /= 2;
				}
			}
		}
		
		if (mode == TOGGLE) {
			
			// if on and off keys is same key
			if (key_on_num == key_off_num) {
				if (last_key_state == 1 && on_key_state == 0) {
					last_key_state = 0;
					on_key_state   = 0;
					off_key_state  = 0;
				} else if (last_key_state == 0 && on_key_state == 1) {
					last_key_state = 1;
					on_key_state   = 1;
					off_key_state  = 1;
				} else {
					on_key_state   = 0;
					off_key_state  = 0;
				}
			}
			
			if (last_state == 0) {
				if (on_key_state == 1) {
					last_state = 1;
					run_script(on_bin_cache);
					printf("On\n");
				}
			} else {
				if (off_key_state == 1) {
					last_state = 0;
					trig_off_keys(dpy, &stored_keys_count, stored_keys);
					run_script(off_bin_cache);
					printf("Off\n");
				}
			}
			
		} else if (mode == MODIFIER) {
			
			if (last_state != on_key_state) {
				last_state = on_key_state;
				if (last_state == 1) {
					run_script(on_bin_cache);
					printf("On\n");
				} else {
					trig_off_keys(dpy, &stored_keys_count, stored_keys);
					run_script(off_bin_cache);
					printf("Off\n");
				}
			}
			
		} else {
			fprintf(stderr, "Unknown mode\n");
			return EXIT_FAILURE;
		}
		
		usleep(SLEEP_TIME); // idle
	}
	
	XCloseDisplay(dpy);
	return EXIT_SUCCESS;
}
Ejemplo n.º 6
0
PUBLIC int csoundModuleInit(CSOUND *csound)
{
    const OENTRY  *ep = &(widgetOpcodes_[0]);
    int           initFlags = 0;
    int           *fltkFlags;
    int           enableDisplays = 0;
    OPARMS oparms;
     csound->GetOParms(csound, &oparms);

    if (csound->QueryGlobalVariable(csound,
                                    "FLTK_Flags") == (void*) 0) {
      if (csound->CreateGlobalVariable(csound,
                                       "FLTK_Flags", sizeof(int)) != 0)
        csound->Die(csound, "%s",
                    Str("widgets.cpp: error allocating FLTK flags"));
      initFlags = 1;
    }
    fltkFlags = getFLTKFlagsPtr(csound);
    if (((*fltkFlags) & 2) == 0 &&
        !(oparms.graphsoff || oparms.postscript)) {
#ifdef LINUX
      Display *dpy = XOpenDisplay(NULL);
      if (dpy != NULL) {
        XCloseDisplay(dpy);
#endif
        if (csound->SetIsGraphable(csound, 1) == 0) {
          enableDisplays = 1;
          (*fltkFlags) |= 64;

          if (!((*fltkFlags) & 256))
            csound->SetInternalYieldCallback(csound, CsoundYield_FLTK);
          flgraph_init(csound); /* Create space */
          csound->SetMakeGraphCallback(csound, MakeGraph_FLTK);
          csound->SetDrawGraphCallback(csound, DrawGraph_FLTK);
          csound->SetKillGraphCallback(csound, KillGraph_FLTK);
          csound->SetExitGraphCallback(csound, ExitGraph_FLTK);
           /* seemed to crash, but not anymore... */
          csound->RegisterResetCallback(csound, NULL, widget_reset);
          csound->Message(csound, "graph init... \n");

        }
#ifdef LINUX
      }
#endif
    }
    if (initFlags) {
#ifndef __MACH__
      if (enableDisplays)
#endif
        (*fltkFlags) |= 28;
    }
    if (!((*fltkFlags) & 129))
      for ( ; ep->opname != NULL; ep++) {
        if (csound->AppendOpcode(csound, ep->opname,
                                 (int)ep->dsblksiz, (int)ep->flags, (int)ep->thread,
                                 ep->outypes, ep->intypes,
                                 ep->iopadr, ep->kopadr, ep->aopadr) != 0) {
          csound->ErrorMsg(csound, Str("Error registering opcode '%s'"),
                                   ep->opname);
          return -1;
        }
      }
    else if (!((*fltkFlags) & 128)) {
      for ( ; ep->opname != NULL; ep++) {
        if (csound->AppendOpcode(
                                 csound, ep->opname, (int)ep->dsblksiz,
                                 (int)ep->flags,(int)ep->thread,
                ep->outypes, ep->intypes,
                (((int)ep->thread & 1) ? dummyWidgetOpcode : (SUBR) 0),
                (((int)ep->thread & 2) ? dummyWidgetOpcode : (SUBR) 0),
                (((int)ep->thread & 4) ? dummyWidgetOpcode : (SUBR) 0)) != 0) {
          csound->ErrorMsg(csound, Str("Error registering opcode '%s'"),
                                   ep->opname);
          return -1;
        }
      }
    }

    widget_init(csound);
    return 0;
}
/* This function gets the X Display and global info about it. Everything is
   stored in our object and will be cleaned when the object is disposed. Note
   here that caps for supported format are generated without any window or
   image creation */
GstXContext *
ximageutil_xcontext_get (GstElement * parent, const gchar * display_name)
{
  GstXContext *xcontext = NULL;
  XPixmapFormatValues *px_formats = NULL;
  gint nb_formats = 0, i;

  xcontext = g_new0 (GstXContext, 1);

  xcontext->disp = XOpenDisplay (display_name);
  GST_DEBUG_OBJECT (parent, "opened display %p", xcontext->disp);
  if (!xcontext->disp) {
    g_free (xcontext);
    return NULL;
  }
  xcontext->screen = DefaultScreenOfDisplay (xcontext->disp);
  xcontext->visual = DefaultVisualOfScreen (xcontext->screen);
  xcontext->root = RootWindowOfScreen (xcontext->screen);
  xcontext->white = WhitePixelOfScreen (xcontext->screen);
  xcontext->black = BlackPixelOfScreen (xcontext->screen);
  xcontext->depth = DefaultDepthOfScreen (xcontext->screen);

  xcontext->width = WidthOfScreen (xcontext->screen);
  xcontext->height = HeightOfScreen (xcontext->screen);

  xcontext->widthmm = WidthMMOfScreen (xcontext->screen);
  xcontext->heightmm = HeightMMOfScreen (xcontext->screen);

  xcontext->caps = NULL;

  GST_DEBUG_OBJECT (parent, "X reports %dx%d pixels and %d mm x %d mm",
      xcontext->width, xcontext->height, xcontext->widthmm, xcontext->heightmm);
  ximageutil_calculate_pixel_aspect_ratio (xcontext);

  /* We get supported pixmap formats at supported depth */
  px_formats = XListPixmapFormats (xcontext->disp, &nb_formats);

  if (!px_formats) {
    XCloseDisplay (xcontext->disp);
    g_free (xcontext);
    return NULL;
  }

  /* We get bpp value corresponding to our running depth */
  for (i = 0; i < nb_formats; i++) {
    if (px_formats[i].depth == xcontext->depth)
      xcontext->bpp = px_formats[i].bits_per_pixel;
  }

  XFree (px_formats);

  xcontext->endianness =
      (ImageByteOrder (xcontext->disp) ==
      LSBFirst) ? G_LITTLE_ENDIAN : G_BIG_ENDIAN;

#ifdef HAVE_XSHM
  /* Search for XShm extension support */
  if (XShmQueryExtension (xcontext->disp) &&
      ximageutil_check_xshm_calls (xcontext)) {
    xcontext->use_xshm = TRUE;
    GST_DEBUG ("ximageutil is using XShm extension");
  } else {
    xcontext->use_xshm = FALSE;
    GST_DEBUG ("ximageutil is not using XShm extension");
  }
#endif /* HAVE_XSHM */

  /* our caps system handles 24/32bpp RGB as big-endian. */
  if ((xcontext->bpp == 24 || xcontext->bpp == 32) &&
      xcontext->endianness == G_LITTLE_ENDIAN) {
    xcontext->endianness = G_BIG_ENDIAN;
    xcontext->r_mask_output = GUINT32_TO_BE (xcontext->visual->red_mask);
    xcontext->g_mask_output = GUINT32_TO_BE (xcontext->visual->green_mask);
    xcontext->b_mask_output = GUINT32_TO_BE (xcontext->visual->blue_mask);
    if (xcontext->bpp == 24) {
      xcontext->r_mask_output >>= 8;
      xcontext->g_mask_output >>= 8;
      xcontext->b_mask_output >>= 8;
    }
Ejemplo n.º 8
0
 void term() {
   if(display) {
     XCloseDisplay(display);
     display = nullptr;
   }
 }
Ejemplo n.º 9
0
 ~GlxWindowSystem() {
     XCloseDisplay(display);
 }
Ejemplo n.º 10
0
 WindowImplementation::~WindowImplementation(){
     glXDestroyContext(display, context);
     XDestroyWindow(display, xWindow);
     // XFreeColormap(display, colormap);
     XCloseDisplay(display );
 }
Ejemplo n.º 11
0
int main() {
	Display *dpy;
	Window root;
	int num;
	long jif1,jif2,jif3,jift;
	long lnum1,lnum2,lnum3,lnum4;
	char statnext[30], status[100];
	time_t current;
	FILE *infile;
	// get initial jiffies
	infile = fopen(CPU_FILE,"r");
	fscanf(infile,"cpu %ld %ld %ld %ld",&jif1,&jif2,&jif3,&jift);
	fclose(infile);
	// Setup X display and root window id:
	dpy=XOpenDisplay(NULL);
	if ( dpy == NULL) {
		fprintf(stderr, "ERROR: could not open display\n");
		exit(1);
	}
	root = XRootWindow(dpy,DefaultScreen(dpy));
// MAIN LOOP STARTS HERE:
	for (;;) {
		status[0]='\0';
	// CPU use:
		infile = fopen(CPU_FILE,"r");
		fscanf(infile,"cpu %ld %ld %ld %ld",&lnum1,&lnum2,&lnum3,&lnum4);
		fclose(infile);
		if (lnum4>jift)
			num = (int) 100*(((lnum1-jif1)+(lnum2-jif2)+(lnum3-jif3))/(lnum4-jift));
		else
			num = 0;
		jif1=lnum1; jif2=lnum2; jif3=lnum3; jift=lnum4;
		if (num > CPU_HI)
			sprintf(statnext,CPU_HI_STR,num);
		else
			sprintf(statnext,CPU_STR,num);
		strcat(status,statnext);
	// Memory use:
		infile = fopen(MEM_FILE,"r");
		fscanf(infile,"MemTotal: %ld kB\nMemFree: %ld kB\nBuffers: %ld kB\nCached: %ld kB\n",
			&lnum1,&lnum2,&lnum3,&lnum4);
		fclose(infile);
		sprintf(statnext,MEM_STR,100*lnum2/lnum1,100*lnum3/lnum1,100*lnum4/lnum1);
		strcat(status,statnext);
	// Audio volume:
		infile = fopen(AUD_FILE,"r");
		fscanf(infile,"%d",&num);
		fclose(infile);
		if (num == -1)
			sprintf(statnext,VOL_MUTE_STR,num);
		else
			sprintf(statnext,VOL_STR,num);
		strcat(status,statnext);
	// Power / Battery:
		infile = fopen(BATT_NOW,"r");
			fscanf(infile,"%ld\n",&lnum1);fclose(infile);
		infile = fopen(BATT_FULL,"r");
			fscanf(infile,"%ld\n",&lnum2);fclose(infile);
		infile = fopen(BATT_STAT,"r");
			fscanf(infile,"%s\n",statnext);fclose(infile);
		num = lnum1*100/lnum2;
		if (strncmp(statnext,"Charging",8) == 0) {
			sprintf(statnext,BAT_CHRG_STR,num);
		}
		else {
			if (num < BATT_LOW)
				sprintf(statnext,BAT_LOW_STR,num);
			else
				sprintf(statnext,BAT_STR,num);
		}
		strcat(status,statnext);
	// Date & Time:
		time(&current);
		strftime(statnext,38,DATE_TIME_STR,localtime(&current));
		strcat(status,statnext);
	// Set root name
		XStoreName(dpy,root,status);
		XFlush(dpy);
		sleep(INTERVAL);
	}
// NEXT LINES SHOULD NEVER EXECUTE, only here to satisfy my O.C.D.
	XCloseDisplay(dpy);
	return 0;
}
Ejemplo n.º 12
0
static void close_window (void) {
  XDestroyWindow(display, win);
  XCloseDisplay (display);
}
Ejemplo n.º 13
0
int main(int argc, char *argv[]) {
  Display *disp;
  int scr, prepare, tmp;
  Window selector, rootwin;
  XEvent event;
  cairo_surface_t *canvas;
  Atom setfull[2];
  XWindowAttributes scrattr;
  XSetWindowAttributes winattr;
  XVisualInfo vis;
  ScreenshotLoc initloc, endloc;
  pngstream pngstr;
  XImage *ximg;
  
  // Get the user's display
  if (!(disp = XOpenDisplay(NULL))) {
    printf("Could not get display!\n");
  }

  // Get screen, root
  scr = DefaultScreen(disp);
  rootwin = RootWindow(disp, scr);
		   
  XMatchVisualInfo(disp, scr, 32, TrueColor, &vis);
  
  // Get screen stats for width/height
  XGetWindowAttributes(disp, rootwin, &scrattr);

  // Set window attributes
  winattr.colormap = XCreateColormap(disp, rootwin, vis.visual, AllocNone);
  winattr.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | Button1MotionMask;
  winattr.background_pixmap = None;
  winattr.border_pixel = 0;
  // Make the selector window
  selector = XCreateWindow(disp,
			   rootwin,
			   0, 0,
			   scrattr.width, scrattr.height,
			   0,
			   vis.depth,
			   InputOutput,
			   vis.visual,
			   CWColormap | CWEventMask | CWBackPixmap | CWBorderPixel,
			   &winattr); 
  XStoreName(disp, selector, "cloudselect");
  // We need key release (any key == cancel), and button for hold/release
  //XSelectInput(disp, selector, ExposureMask|ButtonPressMask|ButtonReleaseMask|KeyReleaseMask);
  XMapWindow(disp, selector);

  // set our window to fullscreen
  setfull[0] = XInternAtom(disp, "_NET_WM_STATE_FULLSCREEN", False);
  setfull[1] = None;
  
  XChangeProperty(disp,
		  selector,
		  XInternAtom(disp, "_NET_WM_STATE", False),
		  XA_ATOM,
		  32,
		  PropModeReplace,
		  (unsigned char *)setfull,
		  1);

  RemoveDecorations(disp, selector);  
  
  // make a cairo surface to paint on
  canvas = cairo_xlib_surface_create(disp, selector, vis.visual, scrattr.width, scrattr.height);

  initloc.x = initloc.y = -1;

  prepare = 0;
  
  while (get_xevents(disp, &event)) {
    if (event.type == Expose) {
      paint(canvas, scrattr.width, scrattr.height);
    } else if (event.type == ButtonPress) {
      if (event.xbutton.button == Button1) {
	initloc.x = event.xbutton.x;
	initloc.y = event.xbutton.y;
      } else {
	printf("[INFO] Operation cancelled.\n");
	break;
      }
    } else if (event.type == ButtonRelease) { // We have completed selecting!
      if (event.xbutton.button == Button1) {
	endloc.x = event.xbutton.x;
	endloc.y = event.xbutton.y;

	// Negative resolutions are bad and make no sense anyway
	if (endloc.x < initloc.x) {
	  tmp = endloc.x;
	  endloc.x = initloc.x;
	  initloc.x = tmp;
	}
	if (endloc.y < initloc.y) {
	  tmp = endloc.y;
	  endloc.y = initloc.y;
	  initloc.y = tmp;
	}

	// Debug printf()s
	printf("Initial co-ordinates: (%d, %d)\n", initloc.x, initloc.y);
	printf("Final co-ordinates:   (%d, %d)\n", endloc.x, endloc.y);
	printf("Dimensions:           %dx%d\n", endloc.y-initloc.y, endloc.x-initloc.x);

	// Get selection as XImage
	ximg = XGetImage(disp, rootwin, initloc.x, initloc.y, (endloc.x-initloc.x), (endloc.y-initloc.y), XAllPlanes(), ZPixmap);

	// Pass XImage to mkpngstream
	pngstr = mkpngstream(disp, DefaultScreen(disp), vis.visual, ximg, initloc, endloc); // Make PNG stream to send to CloudApp
	if (!pngstr.data) {
	  printf("Making PNG stream failed...\n");
	  if (ximg) {
	    XFree(ximg); // XFree doesn't like NULL pointers
	  }
	} else {
	  test_write_file(pngstr, "test.png");
	}
	break;
      } else { // ... Wrong button!
	printf("[INFO Operation cancelled.\n");
	break;
      }
    } else if (event.type == MotionNotify) { // We only track Button1Motion, so...
      endloc.x = event.xmotion.x;
      endloc.y = event.xmotion.y;
      printf("[INFO] endloc.x: %d\nendloc.y: %d\n", endloc.x, endloc.y);
      printf("[INFO] initloc.x: %d\ninitloc.y: %d\n", initloc.x, initloc.y);
      paint(canvas, scrattr.width, scrattr.height);
      setrect(canvas, initloc, endloc);
    } else if (event.type == KeyRelease) {
      if (prepare == 1) break;
    }
    else if (event.type == KeyPress) {
      prepare = 1;
    }
  }

  cairo_surface_destroy(canvas);

  XCloseDisplay(disp);
  return 0;
}
Ejemplo n.º 14
0
/* PROGRAM EXECUTION BEGINS HERE */
int main(int argc, char** argv)
{
    /** Declare variables **/
    /* People */
    int total_number_of_people = 50;
    int total_num_initially_infected = 1;
    int total_num_infected = 1;
    int our_number_of_people = 50;
    int our_person1 = 0;
    int our_current_infected_person = 0;
    int our_num_initially_infected = 1;
    int our_num_infected = 0;
    int our_current_location_x = 0;
    int our_current_location_y = 0;
    int our_num_susceptible = 0;
    int our_num_immune = 0;
    int our_num_dead = 0;
    int my_current_person_id = 0;
    int my_num_infected_nearby = 0;
    int my_person2 = 0;

    /* Environment */
    int environment_width = 30;
    int environment_height = 30;

    /* Disease */
    int infection_radius = 3;
    int duration_of_disease = 50;
    int contagiousness_factor = 30;
    int deadliness_factor = 30;
#ifdef SHOW_RESULTS
    double our_num_infections = 0.0;
    double our_num_infection_attempts = 0.0;
    double our_num_deaths = 0.0;
    double our_num_recovery_attempts = 0.0;
#endif

    /* Time */
    int total_number_of_days = 250;
    int our_current_day = 0;
    int microseconds_per_day = 100000;

    /* Movement */
    int my_x_move_direction = 0; 
    int my_y_move_direction = 0;

    /* Distributed Memory Information */
    int total_number_of_processes = 1;
    int our_rank = 0;
    //#ifdef MPI
    // int current_rank = 0;
    // int current_displ = 0;
    //#endif

    /* getopt */
    int c = 0;

    /* Integer arrays, a.k.a. integer pointers */
    int *x_locations;
    int *y_locations;
    int *our_x_locations;
    int *our_y_locations;
    int *our_infected_x_locations;
    int *our_infected_y_locations;
    int *their_infected_x_locations;
    int *their_infected_y_locations;
    int *our_num_days_infected;
    int *recvcounts;
    int *displs;

    /* Character arrays, a.k.a. character pointers */
    char *states;
    char *our_states;

#ifdef TEXT_DISPLAY
    /* Array of character arrays, a.k.a. array of character pointers, for text
     *  display */
    char **environment;
#endif

#ifdef X_DISPLAY
    /* Declare X-related variables */
    Display *display;
    Window window;
    int screen;
    Atom delete_window;
    GC gc;
    XColor infected_color;
    XColor immune_color;
    XColor susceptible_color;
    XColor dead_color;
    Colormap colormap;
    char red[] = "#FF0000";
    char green[] = "#00FF00";
    char black[] = "#000000";
    char white[] = "#FFFFFF";
#endif

    //#ifdef MPI
    /* Each process initializes the distributed memory environment */
    //MPI_Init(&argc, &argv);
    //#endif

    /* ALG I: Each process determines its rank and the total number of processes     */
    //#ifdef MPI
    //  MPI_Comm_rank(MPI_COMM_WORLD, &our_rank);
    //  MPI_Comm_size(MPI_COMM_WORLD, &total_number_of_processes);
    //#else
    our_rank = 0;
    total_number_of_processes = 1;
    //#endif

    /* ALG II: Each process is given the parameters of the simulation */
    /* Get command line options -- this follows the idiom presented in the
     *  getopt man page (enter 'man 3 getopt' on the shell for more) */
    while((c = getopt(argc, argv, "n:i:w:h:t:T:c:d:D:m:")) != -1)
    {
        switch(c)
        {
            case 'n':
                total_number_of_people = atoi(optarg);
                break;
            case 'i':
                total_num_initially_infected = atoi(optarg);
                break;
            case 'w':
                environment_width = atoi(optarg);
                break;
            case 'h':
                environment_height = atoi(optarg);
                break;
            case 't':
                total_number_of_days = atoi(optarg);
                break;
            case 'T':
                duration_of_disease = atoi(optarg);
                break;
            case 'c':
                contagiousness_factor = atoi(optarg);
                break;
            case 'd':
                infection_radius = atoi(optarg);
                break;
            case 'D':
                deadliness_factor = atoi(optarg);
                break;
            case 'm':
                microseconds_per_day = atoi(optarg);
                break;
                /* If the user entered "-?" or an unrecognized option, we need 
                 *  to print a usage message before exiting. */
            case '?':
            default:
                fprintf(stderr, "Usage: ");
                //#ifdef MPI
                //              fprintf(stderr, "mpirun -np total_number_of_processes ");
                //#endif
                fprintf(stderr, "%s [-n total_number_of_people][-i total_num_initially_infected][-w environment_width][-h environment_height][-t total_number_of_days][-T duration_of_disease][-c contagiousness_factor][-d infection_radius][-D deadliness_factor][-m microseconds_per_day]\n", argv[0]);
                exit(-1);
        }
    }
    argc -= optind;
    argv += optind;

    /* ALG III: Each process makes sure that the total number of initially 
     *  infected people is less than the total number of people */
    if(total_num_initially_infected > total_number_of_people)
    {
        fprintf(stderr, "ERROR: initial number of infected (%d) must be less than total number of people (%d)\n", total_num_initially_infected, 
                total_number_of_people);
        exit(-1);
    }

    /* ALG IV: Each process determines the number of people for which it is 
     *  responsible */
    our_number_of_people = total_number_of_people / total_number_of_processes;

    /* ALG V: The last process is responsible for the remainder */
    if(our_rank == total_number_of_processes - 1)
    {
        our_number_of_people += total_number_of_people % total_number_of_processes;
    }

    /* ALG VI: Each process determines the number of initially infected people 
     *  for which it is responsible */
    our_num_initially_infected = total_num_initially_infected 
        / total_number_of_processes;

    /* ALG VII: The last process is responsible for the remainder */
    if(our_rank == total_number_of_processes - 1)
    {
        our_num_initially_infected += total_num_initially_infected 
            % total_number_of_processes;
    }

    /* Allocate the arrays */
    x_locations = (int*)malloc(total_number_of_people * sizeof(int));
    y_locations = (int*)malloc(total_number_of_people * sizeof(int));
    our_x_locations = (int*)malloc(our_number_of_people * sizeof(int));
    our_y_locations = (int*)malloc(our_number_of_people * sizeof(int));
    our_infected_x_locations = (int*)malloc(our_number_of_people * sizeof(int));
    our_infected_y_locations = (int*)malloc(our_number_of_people * sizeof(int));
    their_infected_x_locations = (int*)malloc(total_number_of_people 
            * sizeof(int));
    their_infected_y_locations = (int*)malloc(total_number_of_people 
            * sizeof(int));
    our_num_days_infected = (int*)malloc(our_number_of_people * sizeof(int));
    recvcounts = (int*)malloc(total_number_of_processes * sizeof(int));
    displs = (int*)malloc(total_number_of_processes * sizeof(int));
    states = (char*)malloc(total_number_of_people * sizeof(char));
    our_states = (char*)malloc(our_number_of_people * sizeof(char));

#ifdef TEXT_DISPLAY
    environment = (char**)malloc(environment_width * environment_height
            * sizeof(char*));
    for(our_current_location_x = 0;
            our_current_location_x <= environment_width - 1;
            our_current_location_x++)
    {
        environment[our_current_location_x] = (char*)malloc(environment_height
                * sizeof(char));
    }
#endif

    /* ALG VIII: Each process seeds the random number generator based on the
     *  current time */
    srandom(time(NULL));

    /* ALG IX: Each process spawns threads to set the states of the initially 
     *  infected people and set the count of its infected people */
#pragma omp parallel for private(my_current_person_id) \
    reduction(+:our_num_infected)
    for(my_current_person_id = 0; my_current_person_id 
            <= our_num_initially_infected - 1; my_current_person_id++)
    {
        our_states[my_current_person_id] = INFECTED;
        our_num_infected++;
    }

    /* ALG X: Each process spawns threads to set the states of the rest of its 
     *  people and set the count of its susceptible people */
#pragma omp parallel for private(my_current_person_id) \
    reduction(+:our_num_susceptible)
    for(my_current_person_id = our_num_initially_infected; 
            my_current_person_id <= our_number_of_people - 1; 
            my_current_person_id++)
    {
        our_states[my_current_person_id] = SUSCEPTIBLE;
        our_num_susceptible++;
    }

    /* ALG XI: Each process spawns threads to set random x and y locations for 
     *  each of its people */
#pragma omp parallel for private(my_current_person_id)
    for(my_current_person_id = 0;
            my_current_person_id <= our_number_of_people - 1; 
            my_current_person_id++)
    {
        our_x_locations[my_current_person_id] = random() % environment_width;
        our_y_locations[my_current_person_id] = random() % environment_height;
    }

    /* ALG XII: Each process spawns threads to initialize the number of days 
     *  infected of each of its people to 0 */
#pragma omp parallel for private(my_current_person_id)
    for(my_current_person_id = 0;
            my_current_person_id <= our_number_of_people - 1;
            my_current_person_id++)
    {
        our_num_days_infected[my_current_person_id] = 0;
    }

    /* ALG XIII: Rank 0 initializes the graphics display */
#ifdef X_DISPLAY
    if(our_rank == 0)
    {
        /* Initialize the X Windows Environment
         * This all comes from 
         *   http://en.wikibooks.org/wiki/X_Window_Programming/XLib
         *   http://tronche.com/gui/x/xlib-tutorial
         *   http://user.xmission.com/~georgeps/documentation/tutorials/
         *      Xlib_Beginner.html
         */

        /* Open a connection to the X server */
        display = XOpenDisplay(NULL);
        if(display == NULL)
        {
            fprintf(stderr, "Error: could not open X display\n");
        }
        screen = DefaultScreen(display);
        window = XCreateSimpleWindow(display, RootWindow(display, screen),
                0, 0, environment_width * PIXEL_WIDTH_PER_PERSON, 
                environment_height * PIXEL_HEIGHT_PER_PERSON, 1,
                BlackPixel(display, screen), WhitePixel(display, screen));
        delete_window = XInternAtom(display, "WM_DELETE_WINDOW", 0);
        XSetWMProtocols(display, window, &delete_window, 1);
        XSelectInput(display, window, ExposureMask | KeyPressMask);
        XMapWindow(display, window);
        colormap = DefaultColormap(display, 0);
        gc = XCreateGC(display, window, 0, 0);
        XParseColor(display, colormap, red, &infected_color);
        XParseColor(display, colormap, green, &immune_color);
        XParseColor(display, colormap, white, &dead_color);
        XParseColor(display, colormap, black, &susceptible_color);
        XAllocColor(display, colormap, &infected_color);
        XAllocColor(display, colormap, &immune_color);
        XAllocColor(display, colormap, &susceptible_color);
        XAllocColor(display, colormap, &dead_color);
    }
#endif

    /* ALG XIV: Each process starts a loop to run the simulation for the
     *  specified number of days */
    for(our_current_day = 0; our_current_day <= total_number_of_days - 1; 
            our_current_day++)
    {
        /* ALG XIV.A: Each process determines its infected x locations and 
         *  infected y locations */
        our_current_infected_person = 0;
        for(our_person1 = 0; our_person1 <= our_number_of_people - 1;
                our_person1++)
        {
            if(our_states[our_person1] == INFECTED)
            {
                our_infected_x_locations[our_current_infected_person] =
                    our_x_locations[our_person1];
                our_infected_y_locations[our_current_infected_person] =
                    our_y_locations[our_person1];
                our_current_infected_person++;
            }
        }
        //#ifdef MPI
        /* ALG XIV.B: Each process sends its count of infected people to all the
         *  other processes and receives their counts */
        //      MPI_Allgather(&our_num_infected, 1, MPI_INT, recvcounts, 1, 
        //              MPI_INT, MPI_COMM_WORLD);

        //      total_num_infected = 0;
        //      for(current_rank = 0; current_rank <= total_number_of_processes - 1;
        //              current_rank++)
        //      {
        //          total_num_infected += recvcounts[current_rank];
        //      }

        /* Set up the displacements in the receive buffer (see the man page for 
         *  MPI_Allgatherv) */
        //      current_displ = 0;
        //      for(current_rank = 0; current_rank <= total_number_of_processes - 1;
        //              current_rank++)
        //      {
        //          displs[current_rank] = current_displ;
        //          current_displ += recvcounts[current_rank];
        //      }

        /* ALG XIV.C: Each process sends the x locations of its infected people 
         *  to all the other processes and receives the x locations of their 
         *  infected people */
        //      MPI_Allgatherv(our_infected_x_locations, our_num_infected, MPI_INT, 
        //              their_infected_x_locations, recvcounts, displs, 
        //              MPI_INT, MPI_COMM_WORLD);

        /* ALG XIV.D: Each process sends the y locations of its infected people 
         *  to all the other processes and receives the y locations of their 
         *  infected people */
        //       MPI_Allgatherv(our_infected_y_locations, our_num_infected, MPI_INT, 
        //               their_infected_y_locations, recvcounts, displs, 
        //               MPI_INT, MPI_COMM_WORLD);
        //#else
        total_num_infected = our_num_infected;
        for(my_current_person_id = 0;
                my_current_person_id <= total_num_infected - 1;
                my_current_person_id++)
        {
            their_infected_x_locations[my_current_person_id] = 
                our_infected_x_locations[my_current_person_id];
            their_infected_y_locations[my_current_person_id] =
                our_infected_y_locations[my_current_person_id];
        }
        //#endif

#if defined(X_DISPLAY) || defined(TEXT_DISPLAY)
        /* ALG XIV.E: If display is enabled, Rank 0 gathers the states, x 
         *  locations, and y locations of the people for which each process is 
         *  responsible */
        //#ifdef MPI
        /* Set up the receive counts and displacements in the receive buffer 
         *  (see the man page for MPI_Gatherv) */
        //      current_displ = 0;
        //      for(current_rank = 0; current_rank <= total_number_of_processes - 1;
        //              current_rank++)
        //      {
        //          displs[current_rank] = current_displ;
        //          recvcounts[current_rank] = total_number_of_people
        //              / total_number_of_processes;
        //          if(current_rank == total_number_of_processes - 1)
        //          {
        //              recvcounts[current_rank] += total_number_of_people
        //                  % total_number_of_processes;
        //          }
        //          current_displ += recvcounts[current_rank];
        //      }

        //      MPI_Gatherv(our_states, our_number_of_people, MPI_CHAR, states,
        //              recvcounts, displs, MPI_CHAR, 0, MPI_COMM_WORLD);
        //      MPI_Gatherv(our_x_locations, our_number_of_people, MPI_INT, x_locations,
        //              recvcounts, displs, MPI_INT, 0, MPI_COMM_WORLD);
        //      MPI_Gatherv(our_y_locations, our_number_of_people, MPI_INT, y_locations,
        //              recvcounts, displs, MPI_INT, 0, MPI_COMM_WORLD);
        //#else
#pragma omp parallel for private(my_current_person_id)
        for(my_current_person_id = 0; my_current_person_id 
                <= total_number_of_people - 1; my_current_person_id++)
        {
            states[my_current_person_id] = our_states[my_current_person_id];
            x_locations[my_current_person_id] 
                = our_x_locations[my_current_person_id];
            y_locations[my_current_person_id] 
                = our_y_locations[my_current_person_id];
        }
        //#endif
#endif

        /* ALG XIV.F: If display is enabled, Rank 0 displays a graphic of the 
         *  current day */
#ifdef X_DISPLAY
        if(our_rank == 0)
        {
            XClearWindow(display, window);
            for(my_current_person_id = 0; my_current_person_id 
                    <= total_number_of_people - 1; my_current_person_id++)
            {
                if(states[my_current_person_id] == INFECTED)
                {
                    XSetForeground(display, gc, infected_color.pixel);
                }
                else if(states[my_current_person_id] == IMMUNE)
                {
                    XSetForeground(display, gc, immune_color.pixel);
                }
                else if(states[my_current_person_id] == SUSCEPTIBLE)
                {
                    XSetForeground(display, gc, susceptible_color.pixel);
                }
                else if(states[my_current_person_id] == DEAD)
                {
                    XSetForeground(display, gc, dead_color.pixel);
                }
                else
                {
                    fprintf(stderr, "ERROR: person %d has state '%c'\n",
                            my_current_person_id, states[my_current_person_id]);
                    exit(-1);
                }
                XFillRectangle(display, window, gc,
                        x_locations[my_current_person_id] 
                        * PIXEL_WIDTH_PER_PERSON, 
                        y_locations[my_current_person_id]
                        * PIXEL_HEIGHT_PER_PERSON, 
                        PIXEL_WIDTH_PER_PERSON, 
                        PIXEL_HEIGHT_PER_PERSON);
            }
            XFlush(display);
        }
#endif
#ifdef TEXT_DISPLAY
        if(our_rank == 0)
        {
            for(our_current_location_y = 0; 
                    our_current_location_y <= environment_height - 1;
                    our_current_location_y++)
            {
                for(our_current_location_x = 0; our_current_location_x 
                        <= environment_width - 1; our_current_location_x++)
                {
                    environment[our_current_location_x][our_current_location_y] 
                        = ' ';
                }
            }

            for(my_current_person_id = 0; 
                    my_current_person_id <= total_number_of_people - 1;
                    my_current_person_id++)
            {
                environment[x_locations[my_current_person_id]]
                    [y_locations[my_current_person_id]] = 
                    states[my_current_person_id];
            }

            printf("----------------------\n");
            for(our_current_location_y = 0;
                    our_current_location_y <= environment_height - 1;
                    our_current_location_y++)
            {
                for(our_current_location_x = 0; our_current_location_x 
                        <= environment_width - 1; our_current_location_x++)
                {
                    printf("%c", environment[our_current_location_x]
                            [our_current_location_y]);
                }
                printf("\n");
            }
        }
#endif

#if defined(X_DISPLAY) || defined(TEXT_DISPLAY)
        /* Wait between frames of animation */
        usleep(microseconds_per_day);
#endif

        /* ALG XIV.G: For each of the process’s people, each process spawns 
         *  threads to do the following */
#pragma omp parallel for private(my_current_person_id, my_x_move_direction, \
        my_y_move_direction)
        for(my_current_person_id = 0; my_current_person_id 
                <= our_number_of_people - 1; my_current_person_id++)
        {
            /* ALG XIV.G.1: If the person is not dead, then */
            if(our_states[my_current_person_id] != DEAD)
            {
                /* ALG XIV.G.1.a: The thread randomly picks whether the person 
                 *  moves left or right or does not move in the x dimension */
                my_x_move_direction = (random() % 3) - 1;

                /* ALG XIV.G.1.b: The thread randomly picks whether the person 
                 *  moves up or down or does not move in the y dimension */
                my_y_move_direction = (random() % 3) - 1;

                /* ALG XIV.G.1.c: If the person will remain in the bounds of the
                 *  environment after moving, then */
                if((our_x_locations[my_current_person_id] 
                            + my_x_move_direction >= 0)
                        && (our_x_locations[my_current_person_id] 
                            + my_x_move_direction < environment_width)
                        && (our_y_locations[my_current_person_id] 
                            + my_y_move_direction >= 0)
                        && (our_y_locations[my_current_person_id] 
                            + my_y_move_direction < environment_height))
                {
                    /* ALG XIV.G.i: The thread moves the person */
                    our_x_locations[my_current_person_id] 
                        += my_x_move_direction;
                    our_y_locations[my_current_person_id] 
                        += my_y_move_direction;
                }
            }
        }

        /* ALG XIV.H: For each of the process’s people, each process spawns 
         *  threads to do the following */
#pragma omp parallel for private(my_current_person_id, my_num_infected_nearby, \
        my_person2) reduction(+:our_num_infection_attempts) \
        reduction(+:our_num_infected) reduction(+:our_num_susceptible) \
        reduction(+:our_num_infections)
        for(my_current_person_id = 0; my_current_person_id 
                <= our_number_of_people - 1; my_current_person_id++)
        {
            /* ALG XIV.H.1: If the person is susceptible, then */
            if(our_states[my_current_person_id] == SUSCEPTIBLE)
            {
                /* ALG XIV.H.1.a: For each of the infected people (received
                 *  earlier from all processes) or until the number of infected 
                 *  people nearby is 1, the thread does the following */
                my_num_infected_nearby = 0;
                for(my_person2 = 0; my_person2 <= total_num_infected - 1
                        && my_num_infected_nearby < 1; my_person2++)
                {
                    /* ALG XIV.H.1.a.i: If person 1 is within the infection 
                     *  radius, then */
                    if((our_x_locations[my_current_person_id] 
                                > their_infected_x_locations[my_person2]
                                - infection_radius)
                            && (our_x_locations[my_current_person_id] 
                                < their_infected_x_locations[my_person2] 
                                + infection_radius)
                            && (our_y_locations[my_current_person_id]
                                > their_infected_y_locations[my_person2] 
                                - infection_radius)
                            && (our_y_locations[my_current_person_id]
                                < their_infected_y_locations[my_person2] 
                                + infection_radius))
                    {
                        /* ALG XIV.H.1.a.i.1: The thread increments the number 
                         *  of infected people nearby */
                        my_num_infected_nearby++;
                    }
                }

#ifdef SHOW_RESULTS
                if(my_num_infected_nearby >= 1)
                    our_num_infection_attempts++;
#endif

                /* ALG XIV.H.1.b: If there is at least one infected person 
                 *  nearby, and a random number less than 100 is less than or
                 *  equal to the contagiousness factor, then */
                if(my_num_infected_nearby >= 1 && (random() % 100) 
                        <= contagiousness_factor)
                {
                    /* ALG XIV.H.1.b.i: The thread changes person1’s state to 
                     *  infected */
                    our_states[my_current_person_id] = INFECTED;

                    /* ALG XIV.H.1.b.ii: The thread updates the counters */
                    our_num_infected++;
                    our_num_susceptible--;

#ifdef SHOW_RESULTS
                    our_num_infections++;
#endif
                }
            }
        }

        /* ALG XIV.I: For each of the process’s people, each process spawns 
         *  threads to do the following */
#pragma omp parallel for private(my_current_person_id) \
        reduction(+:our_num_recovery_attempts) reduction(+:our_num_dead) \
        reduction(+:our_num_infected) reduction(+:our_num_deaths) \
        reduction(+:our_num_immune)
        for(my_current_person_id = 0; my_current_person_id 
                <= our_number_of_people - 1; my_current_person_id++)
        {
            /* ALG XIV.I.1: If the person is infected and has been for the full 
             *  duration of the disease, then */
            if(our_states[my_current_person_id] == INFECTED
                    && our_num_days_infected[my_current_person_id] 
                    == duration_of_disease)
            {
#ifdef SHOW_RESULTS
                our_num_recovery_attempts++;
#endif
                /* ALG XIV.I.a: If a random number less than 100 is less than 
                 *  the deadliness factor, then */
                if((random() % 100) < deadliness_factor)
                {
                    /* ALG XIV.I.a.i: The thread changes the person’s state to 
                     *  dead */
                    our_states[my_current_person_id] = DEAD;

                    /* ALG XIV.I.a.ii: The thread updates the counters */
                    our_num_dead++;
                    our_num_infected--;

#ifdef SHOW_RESULTS
                    our_num_deaths++;
#endif
                }
                /* ALG XIV.I.b: Otherwise, */
                else
                {
                    /* ALG XIV.I.b.i: The thread changes the person’s state to 
                     *  immune */
                    our_states[my_current_person_id] = IMMUNE;

                    /* ALG XIV.I.b.ii: The thread updates the counters */
                    our_num_immune++;
                    our_num_infected--;
                }
            }
        }

        /* ALG XIV.J: For each of the process’s people, each process spawns 
         *  threads to do the following */
#pragma omp parallel for private(my_current_person_id)
        for(my_current_person_id = 0; my_current_person_id 
                <= our_number_of_people - 1; my_current_person_id++)
        {
            /* ALG XIV.J.1: If the person is infected, then */
            if(our_states[my_current_person_id] == INFECTED)
            {
                /* ALG XIV.J.1.a: Increment the number of days the person has 
                 *  been infected */
                our_num_days_infected[my_current_person_id]++;
            }
        }
    }

    /* ALG XV: If X display is enabled, then Rank 0 destroys the X Window and 
     *  closes the display */
#ifdef X_DISPLAY
    if(our_rank == 0)
    {
        XDestroyWindow(display, window);
        XCloseDisplay(display);
    }
#endif

#ifdef SHOW_RESULTS
    printf("Final counts: %d susceptible, %d infected, %d immune, \
            %d dead\nActual contagiousness: %f\nActual deadliness: \
            %f\n", our_num_susceptible, our_num_infected, our_num_immune, 
            our_num_dead, 100.0 * (our_num_infections / 
                (our_num_infection_attempts == 0 ? 1 : our_num_infection_attempts)),
            100.0 * (our_num_deaths / (our_num_recovery_attempts == 0 ? 1 
                    : our_num_recovery_attempts)));
#endif

    /* Deallocate the arrays -- we have finished using the memory, so now we
     *  "free" it back to the heap */
#ifdef TEXT_DISPLAY 
    for(our_current_location_x = environment_width - 1; 
            our_current_location_x >= 0; our_current_location_x--)
    {
        free(environment[our_current_location_x]);
    }
    free(environment);
#endif
    free(our_states);
    free(states);
    free(displs);
    free(recvcounts);
    free(our_num_days_infected);
    free(their_infected_y_locations);
    free(their_infected_x_locations);
    free(our_infected_y_locations);
    free(our_infected_x_locations);
    free(our_y_locations);
    free(our_x_locations);
    free(y_locations);
    free(x_locations);

    //#ifdef MPI
    /* MPI execution is finished; no MPI calls are allowed after this */
    //    MPI_Finalize();
    //#endif

    /* The program has finished executing successfully */
    return 0;
}
Ejemplo n.º 15
0
int
main(int argc, char *argv[])
{
    XETrapGetAvailRep     ret_avail;
    XETrapGetStatsRep     ret_stats;
    Widget  appW;
    XtAppContext app;
    char *tmp = NULL;
    XETC    *tc;
    Display *dpy;
    Bool done;
    char    buffer[10];
    ReqFlags   requests;
    EventFlags events;
    int i;

    /* Connect to Server */
    appW = XtAppInitialize(&app,"XTrap",NULL,(Cardinal)0L,
        (int *)&argc, (String *)argv, (String *)NULL,(ArgList)&tmp,
        (Cardinal)NULL);
    dpy = XtDisplay(appW);
#ifdef DEBUG
    XSynchronize(dpy, True);
#endif
    printf("Display:  %s \n", DisplayString(dpy));
    if ((tc = XECreateTC(dpy,0L, NULL)) == False)
    {
        fprintf(stderr,"%s: could not initialize extension\n",argv[0]);
        exit(1L);
    }

    (void)XEGetAvailableRequest(tc,&ret_avail);
    if (BitIsFalse(ret_avail.valid, XETrapStatistics))
    {
        printf("\nStatistics not available from '%s'.\n",
            DisplayString(dpy));
        exit(1L);
    }
    XETrapSetStatistics(tc, True);
    for (i=0; i<256L; i++)
    {
        BitTrue(requests, i);
    }
    XETrapSetRequests(tc, True, requests);
    for (i=KeyPress; i<=MotionNotify; i++)
    {
        BitTrue(events, i);
    }
    XETrapSetEvents(tc, True, events);
    done = False;
    while(done == False)
    {
        fprintf(stderr,"Stats Command (Zero, Quit, [Show])? ");
        fgets(buffer, sizeof(buffer), stdin);
        switch(toupper(buffer[0]))
        {
            case '\n':  /* Default command */
            case 'S':   /* Request fresh counters & display */
                (void)XEGetStatisticsRequest(tc,&ret_stats);
                (void)XEPrintStatistics(stdout,&ret_stats,tc);
                break;
            case 'Z':  /* Zero out counters */
                XETrapSetStatistics(tc, False);
                break;
            case 'Q':
                done = True;
                break;
            default:
                printf("Invalid command, reenter!\n");
                break;
        }
    }
    (void)XEFreeTC(tc);
    (void)XCloseDisplay(dpy);
    exit(0L);
}
Ejemplo n.º 16
0
Archivo: main.c Proyecto: csimons/cswm
int
main(int argc, char *argv[]) {
    int i, j;
    unsigned int mask;
    Window w;
    XEvent ev;
    XModifierKeymap *modmap;
    XSetWindowAttributes wa;

    if(argc == 2 && !strncmp("-v", argv[1], 3))
        eprint("cswm-"VERSION", Copyright 2006 Anselm R. Garbe, 2012 Christopher L. Simons\n");
    else if(argc != 1)
        eprint("usage: cswm [-v]\n");
    setlocale(LC_CTYPE, "");
    dpy = XOpenDisplay(0);
    if(!dpy)
        eprint("cswm: cannot open display\n");
    screen = DefaultScreen(dpy);
    root = RootWindow(dpy, screen);
    otherwm = False;
    XSetErrorHandler(xerrorstart);
    /* this causes an error if some other window manager is running */
    XSelectInput(dpy, root, SubstructureRedirectMask);
    XSync(dpy, False);
    if(otherwm)
        eprint("cswm: another window manager is already running\n");

    XSync(dpy, False);
    XSetErrorHandler(NULL);
    xerrorxlib = XSetErrorHandler(xerror);
    XSync(dpy, False);

    /* init atoms */
    wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
    wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
    wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
    netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
    netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
    XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
            PropModeReplace, (unsigned char *) netatom, NetLast);
    /* init cursors */
    cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
    cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
    cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
    /* init modifier map */
    numlockmask = 0;
    modmap = XGetModifierMapping(dpy);
    for (i = 0; i < 8; i++) {
        for (j = 0; j < modmap->max_keypermod; j++) {
            if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
                numlockmask = (1 << i);
        }
    }
    XFreeModifiermap(modmap);
    /* select for events */
    wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
        | EnterWindowMask | LeaveWindowMask;
    wa.cursor = cursor[CurNormal];
    XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
    grabkeys();
    /* style */
    normcol = getcolor(NORMCOLOR);
    selcol = getcolor(SELCOLOR);
    /* geometry */
    sx = 0;
    sy = SY;
    sw = DisplayWidth(dpy, screen);
    sh = SH;
    master = MASTER;
    nmaster = NMASTER;
    /* multihead support */
    selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
    scan();
    runAutostart();

    /* main event loop, also reads status text from stdin */
    XSync(dpy, False);

    while(running) {
         XNextEvent(dpy, &ev);
        if(handler[ev.type])
            (handler[ev.type])(&ev); /* call handler */
    }
    cleanup();
    XCloseDisplay(dpy);
    return 0;
}
Ejemplo n.º 17
0
int
main(int argc, char *argv[])
{
   const int winWidth = 400, winHeight = 300;
   Display *x_dpy;
   Window win;
   EGLSurface egl_surf;
   EGLContext egl_ctx;
   EGLDisplay egl_dpy;
   char *dpyName = NULL;
   EGLint egl_major, egl_minor, es_ver;
   int i;

   for (i = 1; i < argc; i++) {
      if (strcmp(argv[i], "-display") == 0) {
         dpyName = argv[i+1];
         i++;
      }
      else {
         usage();
         return -1;
      }
   }

   x_dpy = XOpenDisplay(dpyName);
   if (!x_dpy) {
      printf("Error: couldn't open display %s\n",
	     dpyName ? dpyName : getenv("DISPLAY"));
      return -1;
   }

   egl_dpy = eglGetDisplay(x_dpy);
   if (!egl_dpy) {
      printf("Error: eglGetDisplay() failed\n");
      return -1;
   }

   if (!eglInitialize(egl_dpy, &egl_major, &egl_minor)) {
      printf("Error: eglInitialize() failed\n");
      return -1;
   }

   es_ver = 1;
   /* decide the version from the executable's name */
   if (argc > 0 && argv[0] && strstr(argv[0], "es2"))
      es_ver = 2;
   make_x_window(x_dpy, egl_dpy,
                 "ES info", 0, 0, winWidth, winHeight, es_ver,
                 &win, &egl_ctx, &egl_surf);

   /*XMapWindow(x_dpy, win);*/
   if (!eglMakeCurrent(egl_dpy, egl_surf, egl_surf, egl_ctx)) {
      printf("Error: eglMakeCurrent() failed\n");
      return -1;
   }

   info(egl_dpy);

   eglDestroyContext(egl_dpy, egl_ctx);
   eglDestroySurface(egl_dpy, egl_surf);
   eglTerminate(egl_dpy);


   XDestroyWindow(x_dpy, win);
   XCloseDisplay(x_dpy);

   return 0;
}
Ejemplo n.º 18
0
int main (int argc, char **argv) {
	Cursor cursor;
	Display *display;
	Window root, blub, *blubs = NULL;
	unsigned clients;
	unsigned long pixel;
	char *cname;
	XColor color;
	int cnt;
	Atom prop;
	Pixmap save_pixmap = (Pixmap)None;

	display = XOpenDisplay(NULL);
	if(!display) return 1;

	cname = argc == 2 ? argv[1] : "black";

	screen = DefaultScreen(display);
	root = RootWindow(display, screen);
	pixel = BlackPixel(display, screen);

	if(XParseColor(display, DefaultColormap(display, screen), cname, &color)) {
	if(XAllocColor(display, DefaultColormap(display, screen), &color)) {
		pixel = color.pixel;
	}
	}

	XSetWindowBackground(display, root, pixel);
	XClearWindow(display, root);
	cursor = CreateCursorFromName(display,"watch");
	if (cursor) {
		XDefineCursor (display, root, cursor);
		XFreeCursor (display, cursor);
	}
	
	if (fork() == 0) {
		Window win;
		XEvent xev;

		close(0); close(1); close(2);
		chdir("/");

		display = XOpenDisplay(NULL);

		// open a client...
		if (display) {
			win = XCreateSimpleWindow (
				display, root, 0, 0, 1, 1, 0, 0, pixel
			);
			XSync(display, False);
		}
		// wait within event loop...
		for(;;) XNextEvent(display, &xev);
	}

	// wait until the child has opened a client
	cnt = 100;
	do {
	if (!XQueryTree (display, root, &blub, &blub, &blubs, &clients)) {
		XCloseDisplay(display);
		return 0;
	}
	usleep(50000);
	} while(clients < 1 && cnt--);

	save_pixmap = XCreatePixmap (display, root, 1, 1, 1);
	prop = XInternAtom (display, "_XSETROOT_ID", False);
	XChangeProperty (
		display, root, prop, XA_PIXMAP, 32, 
		PropModeReplace, (unsigned char *) &save_pixmap, 1
	);
	XSetCloseDownMode (display, RetainPermanent);

	// enable accessX
	// XAccess (display,NULL);
	XCloseDisplay(display);

	RunWindowManager();
	return 0;
}
Ejemplo n.º 19
0
GuiCalibratorX11::GuiCalibratorX11(Calibrator* calibrator0)
  : calibrator(calibrator0), time_elapsed(0)
{
    display = XOpenDisplay(NULL);
    if (display == NULL) {
        throw std::runtime_error("Unable to connect to X server");
    }
    screen_num = DefaultScreen(display);
    // Load font and get font information structure
    font_info = XLoadQueryFont(display, "9x15");
    if (font_info == NULL) {
        // fall back to native font
        font_info = XLoadQueryFont(display, "fixed");
        if (font_info == NULL) {
            XCloseDisplay(display);
            throw std::runtime_error("Unable to open neither '9x15' nor 'fixed' font");
        }
    }

#ifdef HAVE_X11_XRANDR
    // get screensize from xrandr
    int nsizes;
    XRRScreenSize* randrsize = XRRSizes(display, screen_num, &nsizes);
    if (nsizes != 0) {
        set_display_size(randrsize->width, randrsize->height);
    } else {
        set_display_size(DisplayWidth(display, screen_num),
                         DisplayHeight(display, screen_num));
    }
# else
    set_display_size(DisplayWidth(display, screen_num),
                     DisplayHeight(display, screen_num));
#endif

    // Register events on the window
    XSetWindowAttributes attributes;
    attributes.override_redirect = True;
    attributes.event_mask = ExposureMask | KeyPressMask | ButtonPressMask;

    win = XCreateWindow(display, RootWindow(display, screen_num),
                0, 0, display_width, display_height, 0,
                CopyFromParent, InputOutput, CopyFromParent,
                CWOverrideRedirect | CWEventMask,
                &attributes);
    XMapWindow(display, win);

    // Listen to events
    XGrabKeyboard(display, win, False, GrabModeAsync, GrabModeAsync,
                CurrentTime);
    calib_input = calibrator->register_events();
    if (!calib_input) {
            XGrabPointer(display, win, False, ButtonPressMask, GrabModeAsync,
                GrabModeAsync, None, None, CurrentTime);
    }

    Colormap colormap = DefaultColormap(display, screen_num);
    XColor color;
    for (int i = 0; i != nr_colors; i++) {
        XParseColor(display, colormap, colors[i], &color);
        XAllocColor(display, colormap, &color);
        pixel[i] = color.pixel;
    }
    XSetWindowBackground(display, win, pixel[GRAY]);
    XClearWindow(display, win);

    gc = XCreateGC(display, win, 0, NULL);
    XSetFont(display, gc, font_info->fid);

    // Setup timer for animation
    signal(SIGALRM, sigalarm_handler);
    struct itimerval timer;
    timer.it_value.tv_sec = time_step/1000;
    timer.it_value.tv_usec = (time_step % 1000) * 1000;
    timer.it_interval = timer.it_value;
    setitimer(ITIMER_REAL, &timer, NULL);
}
Ejemplo n.º 20
0
int
main(int argc, char *argv[])
{
  const int winWidth = 800, winHeight = 600;
  Display *x_dpy;
  Window win;
  EGLSurface egl_surf;
  EGLContext egl_ctx;
  EGLDisplay egl_dpy;
  char *dpyName = NULL;
  GLboolean printInfo = GL_FALSE;
  EGLint egl_major, egl_minor;
  const char *s;


  if (!InitTest(argc, argv)) {
    return -1;
  }

  x_dpy = XOpenDisplay(dpyName);
  if (!x_dpy) {
    printf("Error: couldn't open display %s\n",
           dpyName ? dpyName : getenv("DISPLAY"));
    return -1;
  }

  egl_dpy = eglGetDisplay(x_dpy);
  if (!egl_dpy) {
    printf("Error: eglGetDisplay() failed\n");
    return -1;
  }

  if (!eglInitialize(egl_dpy, &egl_major, &egl_minor)) {
    printf("Error: eglInitialize() failed\n");
    return -1;
  }

  s = eglQueryString(egl_dpy, EGL_VERSION);
  printf("EGL_VERSION = %s\n", s);

  s = eglQueryString(egl_dpy, EGL_VENDOR);
  printf("EGL_VENDOR = %s\n", s);

  s = eglQueryString(egl_dpy, EGL_EXTENSIONS);
  printf("EGL_EXTENSIONS = %s\n", s);

  s = eglQueryString(egl_dpy, EGL_CLIENT_APIS);
  printf("EGL_CLIENT_APIS = %s\n", s);

  make_x_window(x_dpy, egl_dpy,
               "OpenGL ES 2.x tri", 0, 0, winWidth, winHeight,
               &win, &egl_ctx, &egl_surf);

  XMapWindow(x_dpy, win);
  if (!eglMakeCurrent(egl_dpy, egl_surf, egl_surf, egl_ctx)) {
    printf("Error: eglMakeCurrent() failed\n");
    return -1;
  }

  if (printInfo) {
    printf("GL_RENDERER   = %s\n", (char *) glGetString(GL_RENDERER));
    printf("GL_VERSION    = %s\n", (char *) glGetString(GL_VERSION));
    printf("GL_VENDOR     = %s\n", (char *) glGetString(GL_VENDOR));
    printf("GL_EXTENSIONS = %s\n", (char *) glGetString(GL_EXTENSIONS));
  }


  InitRendering();
  LoadDefaultData();

  // render once
  testHelper->app()->resizeView(winWidth, winHeight);
  testHelper->app()->resetView();
  testHelper->app()->render();
  eglSwapBuffers(egl_dpy, egl_surf);

  // begin the event loop if not in testing mode
  bool testPassed = true;
  if (!testHelper->isTesting()) {
    event_loop(x_dpy, win, egl_dpy, egl_surf);
  }
  else {
    testPassed = DoTesting();
  }

  FinalizeTest();

  eglDestroyContext(egl_dpy, egl_ctx);
  eglDestroySurface(egl_dpy, egl_surf);
  eglTerminate(egl_dpy);


  XDestroyWindow(x_dpy, win);
  XCloseDisplay(x_dpy);

  return testPassed ? 0 : 1;
}
Ejemplo n.º 21
0
void
SplashInitPlatform(Splash * splash) {
    int shapeVersionMajor, shapeVersionMinor;

    // This setting enables the synchronous Xlib mode!
    // Don't use it == 1 in production builds!
#if (defined DEBUG)
    _Xdebug = 1;
#endif

    pthread_mutex_init(&splash->lock, NULL);

    // We should not ignore any errors.
    //XSetErrorHandler(HandleError);
//    XSetIOErrorHandler(HandleIOError);
    XSetIOErrorHandler(NULL);
    splash->display = XOpenDisplay(NULL);
    if (!splash->display) {
        splash->isVisible = -1;
        return;
    }

    shapeSupported = XShapeQueryExtension(splash->display, &shapeEventBase,
            &shapeErrorBase);
    if (shapeSupported) {
        XShapeQueryVersion(splash->display, &shapeVersionMajor,
                &shapeVersionMinor);
    }

    splash->screen = XDefaultScreenOfDisplay(splash->display);
    splash->visual = XDefaultVisualOfScreen(splash->screen);
    switch (splash->visual->class) {
    case TrueColor: {
            int depth = XDefaultDepthOfScreen(splash->screen);

            splash->byteAlignment = 1;
            splash->maskRequired = shapeSupported;
            initFormat(&splash->screenFormat, splash->visual->red_mask,
                    splash->visual->green_mask, splash->visual->blue_mask, 0);
            splash->screenFormat.byteOrder =
                (XImageByteOrder(splash->display) == LSBFirst ?
                 BYTE_ORDER_LSBFIRST : BYTE_ORDER_MSBFIRST);
            splash->screenFormat.depthBytes = (depth + 7) / 8;
            // TrueColor depth probably can't be less
            // than 8 bits, and it's always byte padded
            break;
        }
    case PseudoColor: {
            int availableColors;
            int numColors;
            int numComponents[3];
            unsigned long colorIndex[SPLASH_COLOR_MAP_SIZE];
            XColor xColors[SPLASH_COLOR_MAP_SIZE];
            int i;
            int depth = XDefaultDepthOfScreen(splash->screen);
            int scale = 65535 / MAX_COLOR_VALUE;

            availableColors = GetNumAvailableColors(splash->display, splash->screen,
                    splash->visual->map_entries);
            numColors = quantizeColors(availableColors, numComponents);
            if (numColors > availableColors) {
                // Could not allocate the color cells. Most probably
                // the pool got exhausted. Disable the splash screen.
                XCloseDisplay(splash->display);
                splash->isVisible = -1;
                splash->display = NULL;
                splash->screen = NULL;
                splash->visual = NULL;
                fprintf(stderr, "Warning: unable to initialize the splashscreen. Not enough available color cells.\n");
                return;
            }
            splash->cmap = AllocColors(splash->display, splash->screen,
                    numColors, colorIndex);
            for (i = 0; i < numColors; i++) {
                splash->colorIndex[i] = colorIndex[i];
            }
            initColorCube(numComponents, splash->colorMap, splash->dithers,
                    splash->colorIndex);
            for (i = 0; i < numColors; i++) {
                xColors[i].pixel = colorIndex[i];
                xColors[i].red = (unsigned short)
                    QUAD_RED(splash->colorMap[colorIndex[i]]) * scale;
                xColors[i].green = (unsigned short)
                    QUAD_GREEN(splash->colorMap[colorIndex[i]]) * scale;
                xColors[i].blue = (unsigned short)
                    QUAD_BLUE(splash->colorMap[colorIndex[i]]) * scale;
                xColors[i].flags = DoRed | DoGreen | DoBlue;
            }
            XStoreColors(splash->display, splash->cmap, xColors, numColors);
            initFormat(&splash->screenFormat, 0, 0, 0, 0);
            splash->screenFormat.colorIndex = splash->colorIndex;
            splash->screenFormat.depthBytes = (depth + 7) / 8;  // or always 8?
            splash->screenFormat.colorMap = splash->colorMap;
            splash->screenFormat.dithers = splash->dithers;
            splash->screenFormat.numColors = numColors;
            splash->screenFormat.byteOrder = BYTE_ORDER_NATIVE;
            break;
        }
    default:
        ; /* FIXME: should probably be fixed, but javaws splash screen doesn't support other visuals either */
    }
}
Ejemplo n.º 22
0
X11ScreenModeChecker::~X11ScreenModeChecker()
{
    XCloseDisplay(x11display);
}
Ejemplo n.º 23
0
// From <https://www.opengl.org/wiki/Programming_OpenGL_in_Linux:_GLX_and_Xlib>
int main(int argc, char** argv){
 Initialised = false;
 StartTime   = GetClock();

 double time;

 Display*             dpy;
 Window               root;
 XVisualInfo*         vi;
 Colormap             cmap;
 XSetWindowAttributes swa;
 Window               win;
 GLXContext           glc;
 XWindowAttributes    gwa;
 XEvent               xev;

 GLint att[] = {GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None};

 dpy = XOpenDisplay(0);

 if(dpy == 0){
  printf("\n\tcannot connect to X server\n\n");
  return 1;
 }

 root = DefaultRootWindow(dpy);

 vi = glXChooseVisual(dpy, 0, att);

 if(vi == 0){
  printf("\n\tno appropriate visual found\n\n");
  return 1;
 }else{
  // %p creates hexadecimal output like in glxinfo
  printf("\n\tvisual %p selected\n", (void*)vi->visualid);
 }

 cmap = XCreateColormap(dpy, root, vi->visual, AllocNone);

 swa.colormap = cmap;
 swa.event_mask = ExposureMask | KeyPressMask;

 win = XCreateWindow(
  dpy,
  root,
  0, 0, 640, 480, 0,
  vi->depth,
  InputOutput,
  vi->visual,
  CWColormap | CWEventMask,
  &swa
 );

 XMapWindow(dpy, win);
 XStoreName(dpy, win, "OpenGL Sample");

 glc = glXCreateContext(dpy, vi, 0, GL_TRUE);
 glXMakeCurrent(dpy, win, glc);

 if(!InitGLEW()){
  glXMakeCurrent   (dpy, None, 0);
  glXDestroyContext(dpy, glc);
  XDestroyWindow   (dpy, win);
  XCloseDisplay    (dpy);
  return 1;
 }
 if(!LoadShader ("OpenGL/Texture.vp", "OpenGL/Texture.fp")) return 1;
 if(!LoadTexture("Pic/greatwall.jpg")) return 1;
 Initialised = true;

 bool running = true;
 while(running){
  while(XCheckWindowEvent(dpy, win, 0xFFFFFFFF, &xev)){
   switch(xev.type){
    case Expose:
     XGetWindowAttributes(dpy, win, &gwa);
     Render(gwa.width, gwa.height);
     glXSwapBuffers(dpy, win);
     break;

    case KeyPress:
     // printf("KeyPress: keycode %u state %u\n", xev.xkey.keycode, xev.xkey.state);
     if(xev.xkey.keycode == Key_Escape) running = false;
     else OnKeyDown(xev.xkey.keycode);
     break;
   }
  }
  XGetWindowAttributes(dpy, win, &gwa);
  Render(gwa.width, gwa.height);
  glXSwapBuffers(dpy, win);
  RenderTime(GetClock()-time);
  time = GetClock();
  usleep(1000);
 }
 glXMakeCurrent   (dpy, None, 0);
 glXDestroyContext(dpy, glc);
 XDestroyWindow   (dpy, win);
 XCloseDisplay    (dpy);

 free(InputBuffer );
 free(OutputBuffer);

 return 0;
}
Ejemplo n.º 24
0
void glx_destroy() {
    XDestroyWindow(dpy, win);
    XCloseDisplay(dpy);
}
Ejemplo n.º 25
0
static void closeDisplay() {
  if (dsp != NULL) {
    XCloseDisplay(dsp);
    dsp=NULL;
  }
}
Ejemplo n.º 26
0
Archivo: main.cpp Proyecto: pol51/xlib
int main(int argc, char *argv[])
{
	Display *display;
	int screen;
	Window window;
	XEvent event;

	/* open connection with the server */
	display = XOpenDisplay(NULL);
	if (!display)
	{
		printf("Cannot open display\n");
		exit(EXIT_FAILURE);
	}
	screen = DefaultScreen(display);

	/* create window */
	window = XCreateSimpleWindow(display, RootWindow(display, screen),
		10, 10, 100, 100, 1, BlackPixel(display, screen),
		WhitePixel(display, screen));

	/* select kind of events we are interested in */
	XSelectInput(display, window, ExposureMask | KeyPressMask);

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

	int i = 0;
	char buffer[127];
	
	XWindowAttributes winInfos;
	
	/* event loop */
	while (1)
	{
		XNextEvent(display, &event);
		
		/* draw or redraw the window */
		//if (event.type == Expose)
		{
			
			XGetWindowAttributes(display, window, &winInfos);
        
			XFillRectangle(
				display, window, DefaultGC(display, screen), 20, 20, 10, 10);
			sprintf(buffer, "width=%d",	 winInfos.width);
			XDrawString(
				display, window, DefaultGC(display, screen),
				winInfos.width / 2, 10,
				buffer, strlen(buffer));
			sprintf(buffer, "height=%d", winInfos.height);
			XDrawString(
				display, window, DefaultGC(display, screen),
				0, winInfos.height / 2,
				buffer, strlen(buffer));
		}

		/* exit on key press */
		if (event.type == KeyPress)
			break;
	}

	/* close connection to server */
	XCloseDisplay(display);

	return EXIT_SUCCESS;
}
Ejemplo n.º 27
0
int main(int argc, char* argv[]) {
    init_handler_table();

    parse_arguments(argc, argv);
    if(!(g_display = XOpenDisplay(NULL)))
        die("herbstluftwm: cannot open display\n");
    checkotherwm();
    // remove zombies on SIGCHLD
    sigaction_signal(SIGCHLD, remove_zombies);
    sigaction_signal(SIGINT,  handle_signal);
    sigaction_signal(SIGQUIT, handle_signal);
    sigaction_signal(SIGTERM, handle_signal);
    // set some globals
    g_screen = DefaultScreen(g_display);
    g_screen_width = DisplayWidth(g_display, g_screen);
    g_screen_height = DisplayHeight(g_display, g_screen);
    g_root = RootWindow(g_display, g_screen);
    XSelectInput(g_display, g_root, ROOT_EVENT_MASK);

    // initialize subsystems
    for (int i = 0; i < LENGTH(g_modules); i++) {
        g_modules[i].init();
    }
    fetch_settings();

    // setup
    ensure_monitors_are_available();
    scan();
    tag_force_update_flags();
    all_monitors_apply_layout();
    ewmh_update_all();
    execute_autostart_file();
    clientlist_end_startup();

    // main loop
    XEvent event;
    int x11_fd;
    fd_set in_fds;
    x11_fd = ConnectionNumber(g_display);
    while (!g_aboutToQuit) {
        FD_ZERO(&in_fds);
        FD_SET(x11_fd, &in_fds);
        // wait for an event or a signal
        select(x11_fd + 1, &in_fds, 0, 0, NULL);
        if (g_aboutToQuit) {
            break;
        }
        while (XPending(g_display)) {
            XNextEvent(g_display, &event);
            void (*handler) (XEvent*) = g_default_handler[event.type];
            if (handler != NULL) {
                handler(&event);
            }
        }
    }

    // destroy all subsystems
    for (int i = LENGTH(g_modules); i --> 0;) {
        g_modules[i].destroy();
    }
    XCloseDisplay(g_display);
    // check if we shall restart an other window manager
    if (g_exec_before_quit) {
        if (g_exec_args) {
            // do actual exec
            HSDebug("==> Doing wmexec to %s\n", g_exec_args[0]);
            execvp(g_exec_args[0], g_exec_args);
            fprintf(stderr, "herbstluftwm: execvp \"%s\"", g_exec_args[0]);
            perror(" failed");
        }
        // on failure or if no other wm given, then fall back
        HSDebug("==> Doing wmexec to %s\n", argv[0]);
        execvp(argv[0], argv);
        fprintf(stderr, "herbstluftwm: execvp \"%s\"", argv[1]);
        perror(" failed");
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}
Ejemplo n.º 28
0
int main(int argc, char* argv[])
{
  Display* display;		/* pointer to X Display structure.           */
  int screen_num;		/* number of screen to place the window on.  */
  Window win;			/* pointer to the newly created window.      */
  unsigned int display_width,
               display_height;	/* height and width of the X display.        */
  unsigned int width, height;	/* height and width for the new window.      */
  char *display_name = getenv("DISPLAY");  /* address of the X display.      */
  GC gc;			/* GC (graphics context) used for drawing    */
				/*  in our window.			     */

  /* open connection with the X server. */
  display = XOpenDisplay(display_name);
  if (display == NULL) {
    fprintf(stderr, "%s: cannot connect to X server '%s'\n",
            argv[0], display_name);
    exit(1);
  }

  /* get the geometry of the default screen for our display. */
  screen_num = DefaultScreen(display);
  display_width = DisplayWidth(display, screen_num);
  display_height = DisplayHeight(display, screen_num);

  /* make the new window occupy 1/9 of the screen's size. */
  width = (display_width / 3);
  height = (display_height / 3);
  printf("window width - '%d'; height - '%d'\n", width, height);

  /* create a simple window, as a direct child of the screen's   */
  /* root window. Use the screen's white color as the background */
  /* color of the window. Place the new window's top-left corner */
  /* at the given 'x,y' coordinates.                             */
  win = create_simple_window(display, width, height, 0, 0);

  /* allocate a new GC (graphics context) for drawing in the window. */
  gc = create_gc(display, win, 0);
  XSync(display, False);

  {
    /* this variable will contain the ID of the newly created pixmap.    */
    Pixmap bitmap;
    /* these variables will contain the dimensions of the loaded bitmap. */
    unsigned int bitmap_width, bitmap_height;
    /* these variables will contain the location of the hotspot of the   */
    /* loaded bitmap.                                                    */
    int hotspot_x, hotspot_y;

    /* load the bitmap found in the file "icon.bmp", create a pixmap     */
    /* containing its data in the server, and put its ID in the 'bitmap' */
    /* variable.                                                         */
    int rc = XReadBitmapFile(display, win,
                             "icon.xbm",
                             &bitmap_width, &bitmap_height,
                             &bitmap,
                             &hotspot_x, &hotspot_y);
    /* check for failure or success. */
    switch (rc) {
        case BitmapOpenFailed:
            fprintf(stderr, "XReadBitmapFile - could not open file 'icon.bmp'.\n");
	    exit(1);
            break;
        case BitmapFileInvalid:
            fprintf(stderr,
                    "XReadBitmapFile - file '%s' doesn't contain a valid bitmap.\n",
                    "icon.xbm");
	    exit(1);
            break;
        case BitmapNoMemory:
            fprintf(stderr, "XReadBitmapFile - not enough memory.\n");
	    exit(1);
            break;
    }

    /* start drawing the given pixmap on to our window. */
    {
      int i, j;

      for(i=0; i<6; i++) {
        for(j=0; j<6; j++) {
          XCopyPlane(display, bitmap, win, gc,
                    0, 0,
                    bitmap_width, bitmap_height,
                    j*bitmap_width, i*bitmap_height,
                    1);
	  XSync(display, False);
	  usleep(100000);
        }
      }
    }
  }

  /* flush all pending requests to the X server. */
  XFlush(display);

  /* make a delay for a short period. */
  sleep(4);

  /* close the connection to the X server. */
  XCloseDisplay(display);
  return(0);
}
Ejemplo n.º 29
0
void cleanupXWindows(void) {
	//do not change
	XDestroyWindow(dpy, win);
	XCloseDisplay(dpy);
}
Ejemplo n.º 30
0
/*ARGSUSED*/
void 
Quit(Widget w, XEvent * event, String * params, Cardinal * num_params)
{
  XCloseDisplay(XtDisplay(w));
  exit(0);
}