示例#1
0
void wsScreenSaverOn(Display *mDisplay)
{
    int nothing;

#ifdef CONFIG_XDPMS

    if (dpms_disabled) {
        if (DPMSQueryExtension(mDisplay, &nothing, &nothing)) {
            if (!DPMSEnable(mDisplay))
                mp_msg(MSGT_GPLAYER, MSGL_ERR, MSGTR_WS_DpmsUnavailable);                     // restoring power saving settings
            else {
                // DPMS does not seem to be enabled unless we call DPMSInfo
                BOOL onoff;
                CARD16 state;
                DPMSInfo(mDisplay, &state, &onoff);

                if (onoff)
                    mp_msg(MSGT_GPLAYER, MSGL_V, "Successfully enabled DPMS.\n");
                else
                    mp_msg(MSGT_GPLAYER, MSGL_STATUS, MSGTR_WS_DpmsNotEnabled);
            }
        }
    }

#endif

    if (timeout_save) {
        int dummy, interval, prefer_blank, allow_exp;
        XGetScreenSaver(mDisplay, &dummy, &interval, &prefer_blank, &allow_exp);
        XSetScreenSaver(mDisplay, timeout_save, interval, prefer_blank, allow_exp);
        XGetScreenSaver(mDisplay, &timeout_save, &interval, &prefer_blank, &allow_exp);
    }
}
示例#2
0
 void RestoreDPMS()
 {
     if (m_dpmsdeactivated)
     {
         m_dpmsdeactivated = false;
         DPMSEnable(qt_xdisplay());
         VERBOSE(VB_GENERAL, "DPMS Reactivated.");
     }
 }
示例#3
0
文件: pm.c 项目: clcarwin/x11vnc
void set_dpms_mode(char *mode) {
#if NO_X11
	return;
#else
	RAWFB_RET_VOID
#if LIBVNCSERVER_HAVE_DPMS
	if (dpy && DPMSCapable(dpy)) {
		CARD16 level;
		CARD16 want;
		BOOL enabled;
		if (!strcmp(mode, "off")) {
			want = DPMSModeOff;
		} else if (!strcmp(mode, "on")) {
			want = DPMSModeOn;
		} else if (!strcmp(mode, "standby")) {
			want = DPMSModeStandby;
		} else if (!strcmp(mode, "suspend")) {
			want = DPMSModeSuspend;
		} else if (!strcmp(mode, "enable")) {
			DPMSEnable(dpy);
			return;
		} else if (!strcmp(mode, "disable")) {
			DPMSDisable(dpy);
			return;
		} else {
			return;
		}
		if (DPMSInfo(dpy, &level, &enabled)) {
			char *from = "unk";
			if (enabled && level != want) {
				XErrorHandler old_handler = XSetErrorHandler(trap_xerror);
				trapped_xerror = 0;

				rfbLog("DPMSInfo level: %d enabled: %d\n", level, enabled);
				if (level == DPMSModeStandby) {
					from = "DPMSModeStandby";
				} else if (level == DPMSModeSuspend) {
					from = "DPMSModeSuspend";
				} else if (level == DPMSModeOff) {
					from = "DPMSModeOff";
				} else if (level == DPMSModeOn) {
					from = "DPMSModeOn";
				}

				rfbLog("switching DPMS state from %s to %s\n", from, mode);
				
				DPMSForceLevel(dpy, want);
			
				XSetErrorHandler(old_handler);
				trapped_xerror = 0;
			}
		}
	}
#endif
#endif
}
示例#4
0
 void RestoreDPMS(void)
 {
     if (m_dpmsdeactivated && m_display)
     {
         m_dpmsdeactivated = false;
         Status status = DPMSEnable(m_display->GetDisplay());
         m_display->Sync();
         LOG(VB_GENERAL, LOG_INFO, LOC +
             QString("DPMS Reactivated %1").arg(status));
     }
 }
示例#5
0
/**
 * Sets the DPMS state of the display.
 * @param enabled @c 0 to disable DPMS characteristics of the server, enable it otherwise.
 * @ingroup Ecore_X_DPMS_Group
 */
EAPI void
ecore_x_dpms_enabled_set(int enabled)
{
#ifdef ECORE_XDPMS
   LOGFN(__FILE__, __LINE__, __FUNCTION__);
   if (enabled)
     DPMSEnable(_ecore_x_disp);
   else
     DPMSDisable(_ecore_x_disp);

#endif /* ifdef ECORE_XDPMS */
}
/**
 * Restore previously saved screen saver settings.
 */
void X11ScreenSaverSettingsRestore()
{
    int     timeout, interval, preferBlank, allowExp;
    Display *display = QX11Info::display();

    XGetScreenSaver(display, &timeout, &interval, &preferBlank, &allowExp);
    timeout = gX11ScreenSaverTimeout;
    XSetScreenSaver(display, timeout, interval, preferBlank, allowExp);

    if (gX11DpmsState && gX11ScreenSaverDpmsAvailable)
        DPMSEnable(display);
}
示例#7
0
文件: DPMSSupport.cpp 项目: A600/xbmc
bool DPMSSupport::PlatformSpecificEnablePowerSaving(PowerSavingMode mode)
{
  Display* dpy = g_Windowing.GetDisplay();
  if (dpy == NULL) return false;

  // This is not needed on my ATI Radeon, but the docs say that DPMSForceLevel
  // after a DPMSDisable (from SDL) should not normally work.
  DPMSEnable(dpy);
  DPMSForceLevel(dpy, X_DPMS_MODES[mode]);
  // There shouldn't be any errors if we called DPMSEnable; if they do happen,
  // they're asynchronous and messy to detect.
  XFlush(dpy);
  return true;
}
示例#8
0
void
CXWindowsScreenSaver::enableDPMS(bool enable)
{
#if HAVE_X11_EXTENSIONS_DPMS_H
	if (m_dpms) {
		if (enable) {
			DPMSEnable(m_display);
		}
		else {
			DPMSDisable(m_display);
		}
	}
#endif
}
示例#9
0
void X11Helper::CloseXConnection()
{
	if(display_supports_dpms_extension)
	{
		if(dpms_state_at_startup)
		{
			DPMSEnable(Dpy);
		}
		else
		{
			DPMSDisable(Dpy);
		}
	}
	// The window should have been shut down
	DEBUG_ASSERT( Dpy != nullptr );
	DEBUG_ASSERT( Win == None );
	XCloseDisplay( Dpy );
	Dpy = nullptr;
}
示例#10
0
/* called on signal or if DPMS changed, or other problem */
void reset(int sig) {
	if (grab) {
		if (verbose) {
			fprintf(stderr, "calling XUngrabServer()\n");
		}
		XUngrabServer(dpy);
	}
	if (verbose) {
		fprintf(stderr, "resetting original DPMS values.\n"); 
	}
	fprintf(stderr, "blockdpy: reset sig=%d called\n", sig);
	DPMSEnable(dpy);
	DPMSSetTimeouts(dpy, standby, suspend, off);
	XFlush(dpy);
	if (sig) {
		XCloseDisplay(dpy);
		exit(0);
	}
}
示例#11
0
文件: slock.c 项目: iddumied/Slock
int
main(int argc, char **argv) {
  char curs[] = {0, 0, 0, 0, 0, 0, 0, 0};
	char buf[32], passwd[256];
	int num, screen;

#ifndef HAVE_BSD_AUTH
	const char *pws;
#endif
	unsigned int len;
	Bool running = True;
	Cursor invisible;
	Display *dpy;
	KeySym ksym;
	Pixmap pmap;
	Window root, w;
	XColor black, dummy;
	XEvent ev;
	XSetWindowAttributes wa;

	if((argc == 2) && !strcmp("-v", argv[1]))
		die("slock-"VERSION", © 2006-2008 Anselm R Garbe\n");
	else if(argc != 1)
		die("usage: slock [-vb]\n");
  
  backlight_of();
  
#ifndef HAVE_BSD_AUTH
	pws = get_password();
#endif

	if(!(dpy = XOpenDisplay(0)))
		die("slock: cannot open display\n");
	screen = DefaultScreen(dpy);
	root = RootWindow(dpy, screen);

	/* init */
	wa.override_redirect = 1;
	wa.background_pixel = BlackPixel(dpy, screen);
	w = XCreateWindow(dpy, root, 0, 0, DisplayWidth(dpy, screen), DisplayHeight(dpy, screen),
			0, DefaultDepth(dpy, screen), CopyFromParent,
			DefaultVisual(dpy, screen), CWOverrideRedirect | CWBackPixel, &wa);
	XAllocNamedColor(dpy, DefaultColormap(dpy, screen), "black", &black, &dummy);
	pmap = XCreateBitmapFromData(dpy, w, curs, 8, 8);
	invisible = XCreatePixmapCursor(dpy, pmap, pmap, &black, &black, 0, 0);
	XDefineCursor(dpy, w, invisible);
	XMapRaised(dpy, w);
	for(len = 1000; len; len--) {
		if(XGrabPointer(dpy, root, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
			GrabModeAsync, GrabModeAsync, None, invisible, CurrentTime) == GrabSuccess)
			break;
		usleep(1000);
	}
	if((running = running && (len > 0))) {
		for(len = 1000; len; len--) {
			if(XGrabKeyboard(dpy, root, True, GrabModeAsync, GrabModeAsync, CurrentTime)
				== GrabSuccess)
				break;
			usleep(1000);
		}
		running = (len > 0);
	}
	len = 0;
	XSync(dpy, False);

	/* main event loop */
	while(running && !XNextEvent(dpy, &ev)) {
		if(len == 0 && DPMSCapable(dpy)) {
			DPMSEnable(dpy);
			DPMSForceLevel(dpy, DPMSModeOff);
		}
		if(ev.type == KeyPress) {
			buf[0] = 0;
			num = XLookupString(&ev.xkey, buf, sizeof buf, &ksym, 0);
			if(IsKeypadKey(ksym)) {
				if(ksym == XK_KP_Enter)
					ksym = XK_Return;
				else if(ksym >= XK_KP_0 && ksym <= XK_KP_9)
					ksym = (ksym - XK_KP_0) + XK_0;
			}
			if(IsFunctionKey(ksym) || IsKeypadKey(ksym)
					|| IsMiscFunctionKey(ksym) || IsPFKey(ksym)
					|| IsPrivateKeypadKey(ksym))
				continue;
			switch(ksym) {
			case XK_Return:
				passwd[len] = 0;
#ifdef HAVE_BSD_AUTH
				running = !auth_userokay(getlogin(), NULL, "auth-xlock", passwd);
#else
				running = strcmp(crypt(passwd, pws), pws);
#endif
				if (running != 0)
					XBell(dpy, 100);
				len = 0;
				break;
			case XK_Escape:
				len = 0;
				break;
			case XK_BackSpace:
				if(len)
					--len;
				break;
			default:
				if(num && !iscntrl((int) buf[0]) && (len + num < sizeof passwd)) { 
					memcpy(passwd + len, buf, num);
					len += num;
				}
				break;
			}
		}
	}
	XUngrabPointer(dpy, CurrentTime);
	XFreePixmap(dpy, pmap);
	XDestroyWindow(dpy, w);
	XCloseDisplay(dpy);
  backlight_on();
	return 0;
}
示例#12
0
文件: sflock.c 项目: YmarkusY/sflock
int
main(int argc, char **argv) {
    char curs[] = {0, 0, 0, 0, 0, 0, 0, 0};
    char buf[32], passwd[256], passdisp[256];
    int num, screen, width, height, update, sleepmode, term, pid;

#ifndef HAVE_BSD_AUTH
    const char *pws;
#endif
    unsigned int len;
    Bool running = True;
    Cursor invisible;
    Display *dpy;
    KeySym ksym;
    Pixmap pmap;
    Window root, w;
    XColor black, red, dummy;
    XEvent ev;
    XSetWindowAttributes wa;
    XFontStruct* font;
    GC gc; 
    XGCValues values;

    // defaults
    char* passchar = "*";
    char* fontname = "-*-dejavu sans-bold-r-*-*-*-420-100-100-*-*-iso8859-1";
    char* username = "******"; 
    int showline = 1;

    for (int i = 0; i < argc; i++) {
        if (!strcmp(argv[i], "-c")) {
            if (i + 1 < argc) 
                passchar = argv[i + 1];
            else
                die("error: no password character given.\n");
        } else
            if (!strcmp(argv[i], "-f")) {
                if (i + 1 < argc) 
                    fontname = argv[i + 1];
                else
                    die("error: font not specified.\n");
        }else
	    if (!strcmp(argv[i], "-u")) {
                if (i + 1 < argc) 
                    username = argv[i + 1];
                else
                    die("error: username not specified.\n");
            }
            else
                if (!strcmp(argv[i], "-v")) 
                    die("sflock-"VERSION", © 2010 Ben Ruijl\n");
                else 
                    if (!strcmp(argv[i], "-h")) 
                        showline = 0;
                    else 
                        if (!strcmp(argv[i], "?")) 
                            die("usage: sflock [-v] [-c passchars] [-f fontname] [-u username]\n");
    }

    // fill with password characters
    for (int i = 0; i < sizeof passdisp; i+= strlen(passchar)) 
        for (int j = 0; j < strlen(passchar); j++)
            passdisp[i + j] = passchar[j];


    /* disable tty switching */
    if ((term = open("/dev/console", O_RDWR)) == -1) {
        perror("error opening console");
    }

    if ((ioctl(term, VT_LOCKSWITCH)) == -1) {
        perror("error locking console"); 
    }

    /* deamonize */
    pid = fork();
    if (pid < 0) 
        die("Could not fork sflock.");
    if (pid > 0) 
        exit(0); // exit parent 

#ifndef HAVE_BSD_AUTH
    pws = get_password(username);
#else
    username = getlogin();
#endif

    if(!(dpy = XOpenDisplay(0)))
        die("sflock: cannot open dpy\n");

    screen = DefaultScreen(dpy);
    root = RootWindow(dpy, screen);
    width = DisplayWidth(dpy, screen);
    height = DisplayHeight(dpy, screen);

    wa.override_redirect = 1;
    wa.background_pixel = XBlackPixel(dpy, screen);
    w = XCreateWindow(dpy, root, 0, 0, width, height,
            0, DefaultDepth(dpy, screen), CopyFromParent,
            DefaultVisual(dpy, screen), CWOverrideRedirect | CWBackPixel, &wa);

    XAllocNamedColor(dpy, DefaultColormap(dpy, screen), "orange red", &red, &dummy);
    XAllocNamedColor(dpy, DefaultColormap(dpy, screen), "black", &black, &dummy);
    pmap = XCreateBitmapFromData(dpy, w, curs, 8, 8);
    invisible = XCreatePixmapCursor(dpy, pmap, pmap, &black, &black, 0, 0);
    XDefineCursor(dpy, w, invisible);
    XMapRaised(dpy, w);

    font = XLoadQueryFont(dpy, fontname);

    if (font == 0) {
        die("error: could not find font. Try using a full description.\n");
    }

    gc = XCreateGC(dpy, w, (unsigned long)0, &values);
    XSetFont(dpy, gc, font->fid);
    XSetForeground(dpy, gc, XWhitePixel(dpy, screen));

    for(len = 1000; len; len--) {
        if(XGrabPointer(dpy, root, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
                    GrabModeAsync, GrabModeAsync, None, invisible, CurrentTime) == GrabSuccess)
            break;
        usleep(1000);
    }
    if((running = running && (len > 0))) {
        for(len = 1000; len; len--) {
            if(XGrabKeyboard(dpy, root, True, GrabModeAsync, GrabModeAsync, CurrentTime)
                    == GrabSuccess)
                break;
            usleep(1000);
        }
        running = (len > 0);
    }

    len = 0;
    XSync(dpy, False);
    update = True;
    sleepmode = False;

    /* main event loop */
    while(running && !XNextEvent(dpy, &ev)) {
        if (sleepmode) {
            DPMSEnable(dpy);
            DPMSForceLevel(dpy, DPMSModeOff);
            XFlush(dpy);
        }

        if (update) {
            int x, y, dir, ascent, descent;
            XCharStruct overall;

            XClearWindow(dpy, w);
            XTextExtents (font, passdisp, len, &dir, &ascent, &descent, &overall);
            x = (width - overall.width) / 2;
            y = (height + ascent - descent) / 2;

            XDrawString(dpy,w,gc, (width - XTextWidth(font, username, strlen(username))) / 2, y - ascent - 20, username, strlen(username));

            if (showline)
                XDrawLine(dpy, w, gc, width * 3 / 8 , y - ascent - 10, width * 5 / 8, y - ascent - 10);

            XDrawString(dpy,w,gc, x, y, passdisp, len);
            update = False;
        }

        if (ev.type == MotionNotify) {
            sleepmode = False;
        }

        if(ev.type == KeyPress) {
            sleepmode = False;

            buf[0] = 0;
            num = XLookupString(&ev.xkey, buf, sizeof buf, &ksym, 0);
            if(IsKeypadKey(ksym)) {
                if(ksym == XK_KP_Enter)
                    ksym = XK_Return;
                else if(ksym >= XK_KP_0 && ksym <= XK_KP_9)
                    ksym = (ksym - XK_KP_0) + XK_0;
            }
            if(IsFunctionKey(ksym) || IsKeypadKey(ksym)
                    || IsMiscFunctionKey(ksym) || IsPFKey(ksym)
                    || IsPrivateKeypadKey(ksym))
                continue;

            switch(ksym) {
                case XK_Return:
                    passwd[len] = 0;
#ifdef HAVE_BSD_AUTH
                    running = !auth_userokay(getlogin(), NULL, "auth-xlock", passwd);
#else
                    running = strcmp(crypt(passwd, pws), pws);
#endif
                    if (running != 0)
                        // change background on wrong password
                        XSetWindowBackground(dpy, w, red.pixel);
                    len = 0;
                    break;
                case XK_Escape:
                    len = 0;

                    if (DPMSCapable(dpy)) {
                        sleepmode = True;
                    }

                    break;
                case XK_BackSpace:
                    if(len)
                        --len;
                    break;
                default:
                    if(num && !iscntrl((int) buf[0]) && (len + num < sizeof passwd)) { 
                        memcpy(passwd + len, buf, num);
                        len += num;
                    }

                    break;
            }

            update = True; // show changes
        }
    }

    /* free and unlock */
    setreuid(geteuid(), 0);
    if ((ioctl(term, VT_UNLOCKSWITCH)) == -1) {
        perror("error unlocking console"); 
    }

    close(term);
    setuid(getuid()); // drop rights permanently


    XUngrabPointer(dpy, CurrentTime);
    XFreePixmap(dpy, pmap);
    XFreeFont(dpy, font);
    XFreeGC(dpy, gc);
    XDestroyWindow(dpy, w);
    XCloseDisplay(dpy);
    return 0;
}
示例#13
0
int main(int argc, char **argv) {
  Display *dpy;
  int g15screen_fd;
  int event;
  int error;
  BOOL enabled = True;
  CARD16 power = 0;
  int dummy = 0, lights = True, change = 0;
  int i;
  struct sigaction new_action;
  char * enable_cmd = NULL;
  char * disable_cmd = NULL;
  int dpms_timeout = 0;
  
  for (i=0;i<argc;i++) {
    char argument[20];
    memset(argument,0,20);
    strncpy(argument,argv[i],19);
    if (!strncmp(argument, "-a",2) || !strncmp(argument, "--activate",10)) {
      if(argv[i+1]!=NULL){
        sscanf(argv[i+1],"%i",&dpms_timeout);
        i++;
      }else{
        printf("%s --activate requires an argument <minutes to activation>\n",argv[0]);
        exit(1);
      }
    }
    if (!strncmp(argument, "-e",2) || !strncmp(argument, "--cmd-enable",12)) {
      if(argv[i+1]!=NULL){
        enable_cmd = malloc(strlen(argv[i+1])+1);
        memcpy(enable_cmd, argv[i+1], strlen(argv[i+1]));
        i++;
      }
    }
    if (!strncmp(argument, "-d",2) || !strncmp(argument, "--cmd-disable",13)) {
      if(argv[i+1]!=NULL){
        disable_cmd = malloc(strlen(argv[i+1])+1);
        memcpy(disable_cmd, argv[i+1], strlen(argv[i+1]));
        i++;
      }
    }
    if (!strncmp(argument, "-v",2) || !strncmp(argument, "--version",9)) {
      printf("%s version %s\n",argv[0],VERSION);
      exit(0);     
    }
    if (!strncmp(argument, "-b",2) || !strncmp(argument, "--bright",13)) {
      bright=1;
    }
    if (!strncmp(argument, "-h",2) || !strncmp(argument, "--help",6)) {
      printf("  %s version %s\n  (c)2007 Mike Lampard\n\n",argv[0],VERSION);
      printf(" -a or --activate <minutes>        - cause DPMS to be activated in <minutes> if no activity.\n");
      printf("                                     By default, %s will simply monitor DPMS status, and\n",argv[0]);
      printf("                                     requires a screensaver to activate. \n");
      printf("                                     In this mode, no screensver is needed.\n");
      printf("                                     %s will shut the monitor down on its own after <minutes>\n",argv[0]);
      printf("                                     with no keyboard or mouse activity.\n");
      printf(" -e or --cmd-enable <cmd to run>   - Run program <cmd> when DPMS is activated.\n\n");
      printf(" -d or --cmd-disable <cmd to run>  - Run program <cmd> when DPMS is de-activated.\n\n");
      printf(" -b or --bright                    - When the keyboard is woken up, set the LEDs to bright.\n\n");
      printf(" -v or --version                   - Show program version\n\n");
      printf(" -h or --help                      - This page\n\n");
      exit(0);
    }
  }
  dpy = XOpenDisplay(getenv("DISPLAY"));
  if (!dpy) {
    printf("Unable to open display %s - exiting\n",getenv("DISPLAY"));
    return 1;
  }
  
  do {
      if((g15screen_fd = new_g15_screen(G15_G15RBUF))<0){
        printf("Sorry, cant connect to the G15daemon - retrying\n");
        sleep(2);
      }
  }while(g15screen_fd<0);

  if (!DPMSQueryExtension (dpy, &event, &error)) {
     printf ("XDPMS extension not supported.\n");
     return 1;
  }

  if (!DPMSCapable(dpy)) {
     printf("DPMS is not enabled... exiting\n");
     return 1; 
  }
  
  if (dpms_timeout>0) {
    DPMSEnable(dpy);
    DPMSSetTimeouts(dpy,dpms_timeout*60,dpms_timeout*60,0);
  }

  new_action.sa_handler = sighandler;
  new_action.sa_flags = 0;
  sigaction(SIGINT, &new_action, NULL);
  sigaction(SIGQUIT, &new_action, NULL);

  while(!leaving) {    
   int fg_check = g15_send_cmd (g15screen_fd, G15DAEMON_IS_FOREGROUND, dummy);
   
   if (! DPMSInfo (dpy, &power, &enabled)) {
     printf ("unable to get DPMS state.\n");
     return 1;
   }

   switch(power) {
    case DPMSModeOn: {
      if (lights == False) {
          change = 1;
          fork_child(enable_cmd);
      }
      lights = True;
      break;
    }
    case DPMSModeStandby:
    case DPMSModeSuspend:
    case DPMSModeOff: {
      if(lights == True){
          change = 1;
          fork_child(disable_cmd);
      }
      lights = False;
      break;
    }
   }
   
   if (fg_check==1 && lights == True && change == 0) { // foreground 
       g15_send_cmd (g15screen_fd, G15DAEMON_SWITCH_PRIORITIES, dummy);
   }

   if(change) {
    toggle_g15lights(g15screen_fd,lights,fg_check);
    change=0;
   }
   sleep (1);
  }

  close(g15screen_fd);
  if(enable_cmd!=NULL)
    free(enable_cmd);
  if(disable_cmd!=NULL)
    free(disable_cmd);
  XCloseDisplay(dpy);
  return 0;
}
示例#14
0
void XDisplay::enableDPMS()
{
    DPMSEnable(this->connection);
}
示例#15
0
int main(int argc, char** argv) {

	int verbose = 0, bg = 0;
	int i, ev, er;
	char *lock_cmd = "xlock";
	char *flag_file = NULL;
	char estr[100], cmd[500];
	struct stat sbuf;
	CARD16 power;
	CARD16 desired = DPMSModeOff;
	BOOL state;
	

	/* setup the lock command. it may be reset by -lock below. */
	if (getenv("XLOCK_CMD")) {
		lock_cmd = (char *) getenv("XLOCK_CMD");
	}

	/* process cmd line: */
	for (i=1; i<argc; i++) {
		if (!strcmp(argv[i], "-display")) {
			sprintf(estr, "DISPLAY=%s", argv[++i]);
			putenv(strdup(estr));
		} else if (!strcmp(argv[i], "-auth")) {
			sprintf(estr, "XAUTHORITY=%s", argv[++i]);
			putenv(strdup(estr));
		} else if (!strcmp(argv[i], "-lock")) {
			lock_cmd = argv[++i];
		} else if (!strcmp(argv[i], "-f")) {
			flag_file = argv[++i];
			unlink(flag_file);
		} else if (!strcmp(argv[i], "-grab")) {
			grab = 1;
		} else if (!strcmp(argv[i], "-bg")) {
			bg = 1;
		} else if (!strcmp(argv[i], "-v")) {
			verbose = 1;
		} else if (!strcmp(argv[i], "-standby")) {
			desired = DPMSModeStandby;
		} else if (!strcmp(argv[i], "-suspend")) {
			desired = DPMSModeSuspend;
		} else if (!strcmp(argv[i], "-off")) {
			desired = DPMSModeOff;
		}
	}

	/* we want it to go into background to avoid blocking, so add '&'. */
	strcpy(cmd, lock_cmd);
	strcat(cmd, " &");
	lock_cmd = cmd;

	/* close any file descriptors we may have inherited (e.g. port 5900) */
	for (i=3; i<=100; i++) {
		close(i);
	}

	/* open DISPLAY */
	dpy = XOpenDisplay(NULL);
	if (! dpy) {
		fprintf(stderr, "XOpenDisplay failed.\n");
		exit(1);
	}

	/* check for DPMS extension */
	if (! DPMSQueryExtension(dpy, &ev, &er)) {
		fprintf(stderr, "DPMSQueryExtension failed.\n");
		exit(1);
	}
	if (! DPMSCapable(dpy)) {
		fprintf(stderr, "DPMSCapable failed.\n");
		exit(1);
	}
	/* make sure DPMS is enabled */
	if (! DPMSEnable(dpy)) {
		fprintf(stderr, "DPMSEnable failed.\n");
		exit(1);
	}

	/* retrieve the timeouts for later resetting */
	if (! DPMSGetTimeouts(dpy, &standby, &suspend, &off)) {
		fprintf(stderr, "DPMSGetTimeouts failed.\n");
		exit(1);
	}
	if (! standby || ! suspend || ! off) {
		/* if none, set to some reasonable values */
		standby = 900;
		suspend = 1200;
		off = 1800;
	}
	if (verbose) {
		fprintf(stderr, "DPMS timeouts: %d %d %d\n", standby,
		    suspend, off);
	}

	/* now set them to very small values */
	if (desired == DPMSModeOff) {
		if (! DPMSSetTimeouts(dpy, 1, 1, 1)) {
			fprintf(stderr, "DPMSSetTimeouts failed.\n");
			exit(1);
		}
	} else if (desired == DPMSModeSuspend) {
		if (! DPMSSetTimeouts(dpy, 1, 1, 0)) {
			fprintf(stderr, "DPMSSetTimeouts failed.\n");
			exit(1);
		}
	} else if (desired == DPMSModeStandby) {
		if (! DPMSSetTimeouts(dpy, 1, 0, 0)) {
			fprintf(stderr, "DPMSSetTimeouts failed.\n");
			exit(1);
		}
	}
	XFlush(dpy);

	/* set handlers for clean up in case we terminate via signal */
	signal(SIGHUP,  reset);
	signal(SIGINT,  reset);
	signal(SIGQUIT, reset);
	signal(SIGABRT, reset);
	signal(SIGTERM, reset);

	/* force state into DPMS Off (lowest power) mode */
	if (! DPMSForceLevel(dpy, desired)) {
		fprintf(stderr, "DPMSForceLevel failed.\n");
		exit(1);
	}
	XFlush(dpy);

	/* read state */
	msleep(500);
	if (! DPMSInfo(dpy, &power, &state)) {
		fprintf(stderr, "DPMSInfo failed.\n");
		exit(1);
	}
	fprintf(stderr, "power: %d state: %d\n", power, state); 

	/* grab display if desired. NOT WORKING */
	if (grab) {
		if (verbose) {
			fprintf(stderr, "calling XGrabServer()\n");
		}
		XGrabServer(dpy);
	}

	/* go into background if desired. */
	if (bg) {
		pid_t p;
		if ((p = fork()) != 0) {
			if (p < 0) {
				fprintf(stderr, "problem forking.\n");
				exit(1);
			} else {
				/* XXX no fd closing */
				exit(0);
			}
		}
	}

	/* main loop: */
	while (1) {
		/* reassert DPMSModeOff (desired) */
		if (verbose) fprintf(stderr, "reasserting desired DPMSMode\n");
		DPMSForceLevel(dpy, desired);
		XFlush(dpy);

		/* wait a bit */
		msleep(200);

		/* check for flag file appearence */
		if (flag_file && stat(flag_file, &sbuf) == 0) {
			if (verbose) {
				fprintf(stderr, "flag found: %s\n", flag_file);
			}
			unlink(flag_file);
			reset(0);
			exit(0);
		}

		/* check state and power level */
		if (! DPMSInfo(dpy, &power, &state)) {
			fprintf(stderr, "DPMSInfo failed.\n");
			reset(0);
			exit(1);
		}
		if (verbose) {
			fprintf(stderr, "power: %d state: %d\n", power, state); 
		}
		if (!state || power != desired) {
			/* Someone (or maybe a cat) is evidently watching...  */
			fprintf(stderr, "DPMS CHANGE: power: %d state: %d\n",
			    power, state); 
			break;
		}
	}
	reset(0);
	fprintf(stderr, "locking screen with command: \"%s\"\n", lock_cmd); 
	system(lock_cmd);
	exit(0);
}