InputProvider::InputProvider () : display (NULL), root_window (0), xtest_available (false), down_keys (NULL) { display = XOpenDisplay (NULL); if (!display) { printf ("Unable to open XDisplay, input tests will not run.\n"); return; } // I guess we'll assume there is only one screen root_window = XRootWindow (display, 0); if (root_window <= 0) { printf ("Unable to get the root window, some of the input tests will not run.\n"); return; } int event_base, error_base, majorp, minorp; if (!XTestQueryExtension (display, &event_base, &error_base, &majorp, &minorp)) { printf ("XTEST Extension unavailable, input tests will not run.\n"); return; } xtest_available = true; keyboard_speed = 10; SendKeyInput (VK_NUMLOCK, true, false, false); MoveMouse (0,0); }
static void screensaver_init_x11 (ScreenSaver * screensaver) { #ifdef HAVE_XTEST int a, b, c, d; XLockDisplay (screensaver->display); screensaver->have_xtest = (XTestQueryExtension (screensaver->display, &a, &b, &c, &d) == True); if (screensaver->have_xtest) { screensaver->keycode1 = XKeysymToKeycode (screensaver->display, XK_Alt_L); if (screensaver->keycode1 == 0) { g_warning ("keycode1 not existant"); } screensaver->keycode2 = XKeysymToKeycode (screensaver->display, XK_Alt_R); if (screensaver->keycode2 == 0) { screensaver->keycode2 = XKeysymToKeycode (screensaver->display, XK_Alt_L); if (screensaver->keycode2 == 0) { g_warning ("keycode2 not existant"); } } screensaver->keycode = &screensaver->keycode1; } XUnlockDisplay (screensaver->display); #endif }
static void SysDisableScreenSaver( void ) { #if 0 static time_t fake_key_timer = 0; static char first_time = 1, has_test_ext = 0, t = 1; Display* display; extern unsigned long gpuDisp; display = (Display*)gpuDisp; if ( first_time ) { // check if xtest is available int a, b, c, d; has_test_ext = XTestQueryExtension( display, &a, &b, &c, &d ); first_time = 0; } if ( has_test_ext && fake_key_timer < time( NULL ) ) { XTestFakeRelativeMotionEvent( display, t *= -1, 0, 0 ); fake_key_timer = time( NULL ) + 55; } #endif }
static int32_t isXTestAvailable() { int32_t major_opcode, first_event, first_error; int32_t event_basep, error_basep, majorp, minorp; int32_t isXTestAvailable; /* check if XTest is available */ isXTestAvailable = XQueryExtension(awt_display, XTestExtensionName, &major_opcode, &first_event, &first_error); DTRACE_PRINTLN3("RobotPeer: XQueryExtension(XTEST) returns major_opcode = %d, first_event = %d, first_error = %d", major_opcode, first_event, first_error); if (isXTestAvailable) { /* check if XTest version is OK */ XTestQueryExtension(awt_display, &event_basep, &error_basep, &majorp, &minorp); DTRACE_PRINTLN4("RobotPeer: XTestQueryExtension returns event_basep = %d, error_basep = %d, majorp = %d, minorp = %d", event_basep, error_basep, majorp, minorp); if (majorp < 2 || (majorp == 2 && minorp < 2)) { /* bad version*/ DTRACE_PRINTLN2("XRobotPeer: XTEST version is %d.%d \n", majorp, minorp); if (majorp == 2 && minorp == 1) { DTRACE_PRINTLN("XRobotPeer: XTEST is 2.1 - no grab is available\n"); } else { isXTestAvailable = False; } } else { /* allow XTest calls even if someone else has the grab; e.g. during * a window resize operation. Works only with XTEST2.2*/ XTestGrabControl(awt_display, True); } } else { DTRACE_PRINTLN("RobotPeer: XTEST extension is unavailable"); } return isXTestAvailable; }
// ###################################################################### AutomateXWin::AutomateXWin(const char* win_name) : itsDisplay(NULL), itsScreen(0), itsImage(NULL), itsWidth(0), itsHeight(0), itsDepth(0) { char *dispName = XDisplayName(NULL); unsigned num_tries; int event_base, error_base; int major_version, minor_version; itsDisplay = XOpenDisplay(dispName); if(!itsDisplay) LFATAL("XOpenDisplay(%s) failed\n", dispName); if (!XTestQueryExtension (itsDisplay, &event_base, &error_base, &major_version, &minor_version)) { XCloseDisplay(itsDisplay); LFATAL("XTest extension not supported on server"); } LINFO("XTestQueryExtension passed."); LINFO("XTest information for server \"%s\":", DisplayString(itsDisplay)); LINFO(" Major version: %d", major_version); LINFO(" Minor version: %d", minor_version); LINFO(" First event number: %d", event_base); LINFO(" First error number: %d", error_base); itsScreen = DefaultScreen(itsDisplay); itsRootWin = RootWindow(itsDisplay, itsScreen); for(num_tries=0;;) { itsWindow = XWindowByName(itsDisplay, itsRootWin, win_name); if(itsWindow) break; if(++num_tries == 100) LFATAL("XWindowByName\n"); usleep(20000); } XFlush(itsDisplay); XSync(itsDisplay, False); #ifdef USE_SHM if(!XShmQueryExtension(itsDisplay)) LFATAL("XShmQueryExtension"); #endif GetWindowGeometry(); if(!XMatchVisualInfo(itsDisplay, itsScreen, itsDepth, DirectColor, &itsVInfo)) { return; } }
int main() { Display *xdpy; Window root; char *display_name = NULL; int ver; if ( (display_name = getenv("DISPLAY")) == (void *)NULL) { fprintf(stderr, "Error: DISPLAY environment variable not set\n"); exit(1); } printf("Display: %s\n", display_name); if ( (xdpy = XOpenDisplay(display_name)) == NULL) { fprintf(stderr, "Error: Can't open display: %s", display_name); exit(1); } if (XTestQueryExtension(xdpy, &ver, &ver, &ver, &ver) != True) { printf("No xtest :(\n"); return 1; } { int control, alt, key_l, key_two, del; control = XKeysymToKeycode(xdpy, XStringToKeysym("Control_L")); alt = XKeysymToKeycode(xdpy, XStringToKeysym("Alt_L")); key_l = XKeysymToKeycode(xdpy, XStringToKeysym("L")); key_two = XKeysymToKeycode(xdpy, XStringToKeysym("2")); del = XKeysymToKeycode(xdpy, XStringToKeysym("BackSpace")); printf("%d %d %d %d\n", control, alt, key_l, key_two); return; XTestFakeKeyEvent(xdpy, alt, True, CurrentTime); XTestFakeKeyEvent(xdpy, key_two, True, CurrentTime); XTestFakeKeyEvent(xdpy, key_two, False, CurrentTime); XTestFakeKeyEvent(xdpy, alt, False, CurrentTime); XTestFakeKeyEvent(xdpy, control, True, 100); XTestFakeKeyEvent(xdpy, key_l, True, CurrentTime); XTestFakeKeyEvent(xdpy, key_l, False, CurrentTime); XTestFakeKeyEvent(xdpy, control, False, CurrentTime); XTestFakeMotionEvent(xdpy, 0, 50, 55, CurrentTime); //XTestFakeButtonEvent(xdpy, 1, True, CurrentTime); //XTestFakeButtonEvent(xdpy, 1, False, CurrentTime); XTestFakeKeyEvent(xdpy, del, True, 50); XTestFakeKeyEvent(xdpy, del, False, CurrentTime); XTestFakeButtonEvent(xdpy, 2, True, CurrentTime); XTestFakeButtonEvent(xdpy, 2, False, CurrentTime); XFlush(xdpy); } return 0; }
static bool xtest() { if( xtest_inited ) return xtest_available; xtest_inited = true; int dummy1, dummy2, dummy3, dummy4; xtest_available = ( XTestQueryExtension( QX11Info::display(), &dummy1, &dummy2, &dummy3, &dummy4 ) == True ); return xtest_available; }
EffectHunter::EffectHunter(long winId, int mode, int sampleCount) :mFPSs() { mWinId = winId; mSampleCount = sampleCount; mFPSCount = 0; mFPS = 0; mTermFlag = false; mMode = mode; mLastXDamageEventTimeStamp = (struct timeval *)malloc(sizeof(struct timeval)); mFirstXDamageEventTimeStamp = (struct timeval *)malloc(sizeof(struct timeval)); int eventnum = 0, errornum = 0, majornum = 0, minornum = 0; mXWindowDisplay = XOpenDisplay(NULL); if (mXWindowDisplay == NULL) { std::cerr << "[Error]: Can't Open the Dispaly." << std::endl; exit(-1); } if (mWinId == 0) { mWinId = (long) RootWindow(mXWindowDisplay, DefaultScreen(mXWindowDisplay)); } if (!XTestQueryExtension(mXWindowDisplay, &eventnum, &errornum, &majornum, &minornum)) { std::cerr << "[Error]: XServer " << DisplayString(mXWindowDisplay) << " doesn't support the XTest extensions!" << std::endl; exit(-1); } struct sigaction act; if (mMode == SAMPLE_FPS) { int sig = 14; // SIGALRM sigemptyset(&act.sa_mask); act.sa_flags=SA_SIGINFO; act.sa_sigaction=sigAlarm; if (sigaction(sig, &act, NULL)<0) { std::cerr <<"[Error]: Failed to install alarm signal." << std::endl; } } else if (mMode == SAMPLE_TIMESTAMP) { int sig = 12; // SIGUSR 12 sigemptyset(&act.sa_mask); act.sa_flags=SA_SIGINFO; act.sa_sigaction=sigQuit; if (sigaction(sig, &act, NULL)<0) { std::cerr <<"[Error]: Failed to install stop signal." << std::endl; } } }
/* Connects to the X11 display, initializes extensions, register for events */ static int init_display(char* name) { dpy = XOpenDisplay(name); if (!dpy) { error("Cannot open display."); return -1; } /* We need XTest, XDamage and XFixes */ int event, error, major, minor; if (!XTestQueryExtension(dpy, &event, &error, &major, &minor)) { error("XTest not available!"); return -1; } if (!XDamageQueryExtension(dpy, &damageEvent, &error)) { error("XDamage not available!"); return -1; } if (!XFixesQueryExtension(dpy, &fixesEvent, &error)) { error("XFixes not available!"); return -1; } /* Get notified when new windows are created. */ Window root = DefaultRootWindow(dpy); XSelectInput(dpy, root, SubstructureNotifyMask); /* Register damage events for existing windows */ Window rootp, parent; Window *children; unsigned int i, nchildren; XQueryTree(dpy, root, &rootp, &parent, &children, &nchildren); /* FIXME: We never reset the handler, is that a good thing? */ XSetErrorHandler(xerror_handler); register_damage(dpy, root); for (i = 0; i < nchildren; i++) { register_damage(dpy, children[i]); } XFree(children); /* Register for cursor events */ XFixesSelectCursorInput(dpy, root, XFixesDisplayCursorNotifyMask); return 0; }
int pa__init(pa_module *m) { struct userdata *u; pa_modargs *ma; int xtest_event_base, xtest_error_base; int major_version, minor_version; pa_assert(m); if (!(ma = pa_modargs_new(m->argument, valid_modargs))) { pa_log("failed to parse module arguments"); goto fail; } m->userdata = u = pa_xnew0(struct userdata, 1); u->module = m; if (!(u->x11_wrapper = pa_x11_wrapper_get(m->core, pa_modargs_get_value(ma, "display", NULL)))) goto fail; if (!XTestQueryExtension( pa_x11_wrapper_get_display(u->x11_wrapper), &xtest_event_base, &xtest_error_base, &major_version, &minor_version)) { pa_log("XTest extension not supported."); goto fail; } pa_log_debug("XTest %i.%i supported.", major_version, minor_version); u->x11_client = pa_x11_client_new(u->x11_wrapper, NULL, x11_kill_cb, u); u->hook_slot = pa_hook_connect( &m->core->hooks[PA_CORE_HOOK_SINK_INPUT_SEND_EVENT], PA_HOOK_NORMAL, (pa_hook_cb_t) sink_input_send_event_hook_cb, u); pa_modargs_free(ma); return 0; fail: if (ma) pa_modargs_free(ma); pa__done(m); return -1; }
void KNotificationRestrictions::Private::startScreenSaverPrevention() { kDebug(297); QDBusMessage message = QDBusMessage::createMethodCall( "org.freedesktop.ScreenSaver", "/ScreenSaver", "org.freedesktop.ScreenSaver", "Inhibit"); message << determineProgramName(); message << reason; QDBusReply<uint> reply = QDBusConnection::sessionBus().call(message); if (reply.isValid()) { screenSaverDbusCookie = reply.value(); return; } #ifdef HAVE_XTEST if ( !haveXTest ) { int a,b,c,e; haveXTest = XTestQueryExtension(QX11Info::display(), &a, &b, &c, &e); if ( !haveXTest ) { kDebug(297) << "--- No XTEST!"; return; } } if ( !XTestKeyCode ) { XTestKeyCode = XKeysymToKeycode(QX11Info::display(), XK_Shift_L); if ( !XTestKeyCode ) { kDebug(297) << "--- No XKeyCode for XK_Shift_L!"; return; } } if ( !screensaverTimer ) { screensaverTimer = new QTimer( q ); connect( screensaverTimer, SIGNAL(timeout()), q, SLOT(screensaverFakeKeyEvent()) ); } kDebug(297) << "---- using XTest"; // send a fake event right away in case this got started after a period of // innactivity leading to the screensaver set to activate in <55s screensaverFakeKeyEvent(); screensaverTimer->start( 55000 ); #endif // HAVE_XTEST }
static MTClosure * mt_closure_init (void) { MTClosure *mt; gint ev_base, err_base, maj, min; mt = g_slice_new0 (MTClosure); mt->xtst_display = XOpenDisplay (NULL); if (!XTestQueryExtension (mt->xtst_display, &ev_base, &err_base, &maj, &min)) { XCloseDisplay (mt->xtst_display); g_slice_free (MTClosure, mt); g_critical ("No XTest extension found. Aborting.."); return NULL; } mt->client = gconf_client_get_default (); gconf_client_add_dir (mt->client, MT_GCONF_HOME, GCONF_CLIENT_PRELOAD_ONELEVEL, NULL); g_signal_connect (mt->client, "value_changed", G_CALLBACK (gconf_value_changed), mt); mt->delay_timer = mt_timer_new (); g_signal_connect (mt->delay_timer, "finished", G_CALLBACK (delay_timer_finished), mt); g_signal_connect (mt->delay_timer, "tick", G_CALLBACK (mt_main_timer_tick), mt); mt->dwell_timer = mt_timer_new (); g_signal_connect (mt->dwell_timer, "finished", G_CALLBACK (dwell_timer_finished), mt); g_signal_connect (mt->dwell_timer, "tick", G_CALLBACK (mt_main_timer_tick), mt); mt->service = mt_service_get_default (); mt_service_set_clicktype (mt->service, DWELL_CLICK_TYPE_SINGLE, NULL); mt->n_screens = gdk_display_get_n_screens (gdk_display_get_default ()); mt->x_old = -1; mt->y_old = -1; return mt; }
int main (int argc, char *argv[]) { Display *display; int eventbase, errorbase, majorver, minorver; int x, y; struct timespec delay = { 0, 500000 }; if (argc != 3) { fprintf (stderr, "Usage: grabcontrol <x> <y>\n"); exit (1); } x = atoi (argv[1]); y = atoi (argv[2]); if ((display = XOpenDisplay(XDisplayName(NULL))) == NULL) { fprintf (stderr, "Can't connect to X display\n"); exit(1); } if (!XTestQueryExtension(display, &eventbase, &errorbase, &majorver, &minorver)) { fprintf (stderr, "Can't find XTest support\n"); exit(1); } XTestGrabControl(display, True); XTestFakeMotionEvent (display, DefaultScreen (display), x, y, CurrentTime); XTestFakeButtonEvent(display, 1, True, CurrentTime); nanosleep (&delay, NULL); XTestFakeButtonEvent(display, 1, False, CurrentTime); XTestGrabControl(display, False); XFlush (display); return 0; }
bool ActionDefinition::requirementCheckXTest(QStringList &missingRequirements) const { #ifdef Q_WS_X11 int unused; XDisplayHelper xDisplayHelper; if(!XTestQueryExtension(xDisplayHelper.display(), &unused, &unused, &unused, &unused)) { missingRequirements << QObject::tr("missing XTest extension"); return false; } return true; #else Q_UNUSED(missingRequirements) return true; #endif }
Display * remoteDisplay (const char * DisplayName) { int Event, Error; int Major, Minor; // open the display Display * D = XOpenDisplay ( DisplayName ); // did we get it? if ( ! D ) { // nope, so show error and abort std::cerr << PROG << ": could not open display \"" << XDisplayName ( DisplayName ) << "\", aborting." << std::endl; exit ( EXIT_FAILURE ); } // does the remote display have the Xtest-extension? if ( ! XTestQueryExtension (D, &Event, &Error, &Major, &Minor ) ) { // nope, extension not supported std::cerr << PROG << ": XTest extension not supported on server \"" << DisplayString(D) << "\"" << std::endl; // close the display and go away XCloseDisplay ( D ); exit ( EXIT_FAILURE ); } // print some information std::cerr << "XTest for server \"" << DisplayString(D) << "\" is version " << Major << "." << Minor << "." << std::endl << std::endl;; // execute requests even if server is grabbed XTestGrabControl ( D, True ); // sync the server XSync ( D,True ); // return the display return D; }
void connect() { int eventnum = 0, errornum = 0, majornum = 0, minornum = 0; /* Get Display Pointer */ display = XOpenDisplay(NULL); if (display == NULL) { printf("FAIL to connect X Windows!\n"); exit(1); } if (!XTestQueryExtension(display, &eventnum, &errornum, &majornum, &minornum)) { printf("XTest is not supported on server %s!\n", "null"); } printf("connected %d.%d!\n",majornum,minornum); DefaultScreen(display); XSynchronize(display, True); XTestGrabControl(display, True); }
int mouse_move(int x, int y, Display *active_display) { int res = 0; Window win; int revert_to; static int is_xtest_available = -1; int ev, er, ma, mi; if (!active_display) { res = -1; return -1; } XGetInputFocus(active_display, &win, &revert_to); if (is_xtest_available == -1) is_xtest_available = XTestQueryExtension(active_display, &ev, &er, &ma, &mi); if (is_xtest_available) XTestFakeRelativeMotionEvent(active_display, x, y , CurrentTime); //flush events XFlush(active_display); if (res == BadValue || res == BadWindow) res = -1; return 1; }
int main(int argc, char **argv) { Display *display = NULL; int event_base; int error_base; int major_version, minor_version; if (argc == 2) { if (!(display = XOpenDisplay(argv[1]))) { printf("Cannot open display %s\n", argv[1]); return -1; } } else { printf("Usage: %s display\n", argv[0]); return -1; } if (!display && !(display = XOpenDisplay(NULL))) { printf("Cannot open default display\n"); return -1; } if (!XTestQueryExtension(display, &event_base, &error_base, &major_version, &minor_version)) { printf("XTEST extension not present\n"); return -1; } printf("XTEST extension present: event_base = %d, error_base = %d\n", event_base, error_base); printf("Extension version: %d.%d\n", major_version, minor_version); XTestFakeKeyEvent(display, 30, True, 10); XTestFakeKeyEvent(display, 30, False, 10); XCloseDisplay(display); return 0; }
int mouse_click(int mouse_button, int button_status, Display *active_display) { int result = -1; static int is_xtest_available = -1; int ev, er, ma, mi; int revert_to; Window win; if (is_xtest_available == -1) { is_xtest_available = XTestQueryExtension(active_display, &ev, &er, &ma, &mi); } if (is_xtest_available) { XGetInputFocus(active_display, &win, &revert_to); if (mouse_button == MOUSE_BUTTON_LEFT && button_status == MOUSE_BUTTON_PRESS) { XTestFakeButtonEvent(active_display, 1, True, CurrentTime); } else if (mouse_button == MOUSE_BUTTON_LEFT && button_status == MOUSE_BUTTON_RELEASE) { XTestFakeButtonEvent(active_display, 1, False, CurrentTime); } else if (mouse_button == MOUSE_BUTTON_MIDDLE && button_status == MOUSE_BUTTON_PRESS) { XTestFakeButtonEvent(active_display, 2, True, CurrentTime); } else if (mouse_button == MOUSE_BUTTON_MIDDLE && button_status == MOUSE_BUTTON_RELEASE) { XTestFakeButtonEvent(active_display, 2, False, CurrentTime); } else if (mouse_button == MOUSE_BUTTON_RIGHT && button_status == MOUSE_BUTTON_PRESS) { XTestFakeButtonEvent(active_display, 3, True, CurrentTime); } else if (mouse_button == MOUSE_BUTTON_RIGHT && button_status == MOUSE_BUTTON_RELEASE) { XTestFakeButtonEvent(active_display, 3, False, CurrentTime); } else if (mouse_button == MOUSE_SCROLL_UP) { XTestFakeButtonEvent(active_display, 4, True, CurrentTime); XTestFakeButtonEvent(active_display, 4, False, CurrentTime); } else if (mouse_button == MOUSE_SCROLL_DOWN) { XTestFakeButtonEvent(active_display, 5, True, CurrentTime); XTestFakeButtonEvent(active_display, 5, False, CurrentTime); } XFlush(active_display); result = 0; } else { perror("Cannot create mouse click events\n"); } return result; }
GdkDisplay *display; Display *xdisplay; int event_basep; int error_basep; int majorp; int minorp; jboolean result; gdk_threads_enter (); display = gdk_display_get_default (); xdisplay = GDK_DISPLAY_XDISPLAY (display); result = XTestQueryExtension (xdisplay, &event_basep, &error_basep, &majorp, &minorp); gdk_threads_leave (); return result; } JNIEXPORT void JNICALL Java_gnu_java_awt_peer_gtk_GdkRobotPeer_mouseMove (JNIEnv *env __attribute__((unused)), jobject obj __attribute__((unused)), jint x, jint y) { GdkDisplay *display; Display *xdisplay; int result;
int xtest_major_version = 0; int xtest_minor_version = 0; int dummy; /* * Open the display using the $DISPLAY environment variable to locate * the X server. See Section 2.1. */ if ((dpy = XOpenDisplay(NULL)) == NULL) { fprintf(stderr, "%s: can't open %s\en", "softwedge", XDisplayName(NULL)); exit(1); } Bool success = XTestQueryExtension(dpy, &dummy, &dummy, &xtest_major_version, &xtest_minor_version); if(success == False || xtest_major_version < 2 || (xtest_major_version <= 2 && xtest_minor_version < 2)) { fprintf(stderr,"XTEST extension not supported. Can't continue\n"); exit(1); } } void sw_read_loop() { char readbuf[2]; readbuf[1] = 0;
void X11KeyFaker::connect() { // Open the display. dpy = XOpenDisplay(displayName.toLatin1().data()); if (!dpy) { // Try again in a few milliseconds. Xnest may not be alive yet. // Give up after 10 seconds. if (++retryCount < 50) QTimer::singleShot(200, this, SLOT(connect())); else QTimer::singleShot(0, this, SIGNAL(couldNotConnect())); return; } // Query the XTest extension, which we need to fake the key events. int event_base, error_base, major, minor; if (!XTestQueryExtension (dpy, &event_base, &error_base, &major, &minor)) { XCloseDisplay(dpy); dpy = 0; QTimer::singleShot(0, this, SIGNAL(couldNotConnect())); return; } // Modify the Xnest's keyboard mappings to add Qtopia's special keysyms. int min_keycode = 1, max_keycode = 255; XDisplayKeycodes(dpy, &min_keycode, &max_keycode); bool ok = true; for (KeySym key = QTOPIAXK_Max; key >= QTOPIAXK_Min; --key) { // This is an extension keysym, not part of the standard X11 set. if (!allocateSpecialKeysym(dpy, min_keycode, max_keycode, key)) { ok = false; break; } } static const KeySym specials[] = { XF86XK_Back, // Qt::Key_Back XF86XK_AudioLowerVolume, // Qt::Key_VolumeUp XF86XK_AudioRaiseVolume, // Qt::Key_VolumeDown XK_F28, // Qt::Key_F28 NoSymbol }; int index = 0; while (ok && specials[index] != NoSymbol) { // This is a standard X11/XFree86 keysym that Qtopia uses, // but it may not be on the user's physical keyboard. if (!allocateSpecialKeysym (dpy, min_keycode, max_keycode, specials[index])) ok = false; ++index; } if (!ok) qWarning() << "There are insufficient spare X11 keycodes to allocate the special Qtopia keys"; // Change the root cursor to something more reasonable than "X". Cursor cursor = XCreateFontCursor(dpy, XC_left_ptr); XDefineCursor(dpy, RootWindow(dpy, DefaultScreen(dpy)), cursor); // Look up the shift keys. shiftKeycode = XKeysymToKeycode(dpy, XK_Shift_L); if (shiftKeycode == NoSymbol) shiftKeycode = XKeysymToKeycode(dpy, XK_Shift_R); modeSwitchKeycode = XKeysymToKeycode(dpy, XK_Mode_switch); // Make sure all of the above changes are flushed. XFlush(dpy); // Set up event handling for the display. QSocketNotifier *notifier = new QSocketNotifier (ConnectionNumber(dpy), QSocketNotifier::Read, this); QObject::connect(notifier, SIGNAL(activated(int)), this, SLOT(readyRead())); // Make sure the file descriptor is not inherited across exec's. fcntl(ConnectionNumber(dpy), F_SETFD, 1); // Notify interested parties that we are now connected to the X display. QTimer::singleShot(0, this, SIGNAL(connected())); }
int main( int argc, char ** argv) { MouseEvent event, prevevent; MouseEvent *pEvent = &event; prevevent.type = EVENT_NULL; prevevent.value = 0; Display *dpy; /* X server connection */ Window win; XWindowAttributes winattr; int xtest_major_version = 0; int xtest_minor_version = 0; int dummy; SOCKET s, s_accept; struct sockaddr_in s_add; //from anyone! struct sockaddr s_client; socklen_t s_client_size = sizeof( struct sockaddr ); int port = PORT; int recvsize; int button, yDelta = 0, yTmp; printf("RemotePad Server for X11 version %s\n", kVersionX11); printf("Application launched.\n"); /* * Open the display using the $DISPLAY environment variable to locate * the X server. See Section 2.1. */ if ((dpy = XOpenDisplay(NULL)) == NULL) { printf("%s: can't open DISPLAY: %s\n", argv[0], XDisplayName(NULL)); exit(1); } Bool success = XTestQueryExtension(dpy, &dummy, &dummy, &xtest_major_version, &xtest_minor_version); if(success == False || xtest_major_version < 2 || (xtest_major_version <= 2 && xtest_minor_version < 2)) { printf("XTEST extension not supported\n"); exit(1); } /* * create a small unmapped window on a screen just so xdm can use * it as a handle on which to killclient() us. */ win = XCreateWindow(dpy, DefaultRootWindow(dpy), 0, 0, 1, 1, 0, CopyFromParent, InputOutput, CopyFromParent, 0, (XSetWindowAttributes*)0); /* * get keyboard mapping to detect modifier keys for each keysym */ XDisplayKeycodes(dpy, &minKeycode, &maxKeycode); int keycodeCount = maxKeycode - minKeycode + 1; keyboardMapping = XGetKeyboardMapping(dpy, minKeycode, keycodeCount, &keysymsPerKeycode); //network stuff //configure socket if ( ( s = socket( PF_INET, SOCK_STREAM, 0 ) ) == -1 ) { perror ( "Failed to create socket :(" ); exit( 2 ); } int yes = 1; setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void *)&yes, sizeof(yes)); memset( &s_add, 0, sizeof( struct sockaddr_in ) ); s_add.sin_family = AF_INET; s_add.sin_port = htons( port ); s_add.sin_addr.s_addr = INADDR_ANY; if ( bind( s, (struct sockaddr * )&s_add, sizeof( struct sockaddr_in ) ) == -1 ) { perror( "Failed to bind socket" ); exit( 2 ); } if( listen( s , 1 ) ) { perror( "Can't listen!" ); exit( 2 ); } while( 1 ) { if(!findInterfaceAddresses(s)) printf("waiting for clients\n"); struct timeval tv; while (1) { fd_set fdset; FD_ZERO(&fdset); FD_SET(s, &fdset); tv.tv_sec = 5; tv.tv_usec = 0; select(s+1, &fdset, NULL, NULL, &tv); if (FD_ISSET(s, &fdset)) break; // sending a keep-alive event for an X server XGetWindowAttributes(dpy, win, &winattr); } s_accept = accept( s, &s_client, &s_client_size ); if ( s_accept == -1 ) { perror( "failed to accept!" ); return -1; } else { printf("Connected!\n"); } tv.tv_sec = 5; tv.tv_usec = 0; setsockopt(s_accept, SOL_SOCKET, SO_RCVTIMEO, (void *)&tv, sizeof(tv)); gettimeofday(&tv, NULL); MouseEvent versionEvent = {htonl(EVENT_VERSION), htonl(kVersionX11Current), htonl(tv.tv_sec), htonl(tv.tv_usec*1000)}; send(s_accept, (void *)&versionEvent, sizeof(MouseEvent), 0); while( 1 ) { recvsize = recv( s_accept, pEvent, sizeof( MouseEvent ), MSG_WAITALL ); if ( recvsize == sizeof( MouseEvent ) )//got data { event.type = ntohl(event.type); event.value = ntohl(event.value); event.tv_sec = ntohl(event.tv_sec); event.tv_nsec = ntohl(event.tv_nsec); switch( event.type ) { case EVENT_MOUSE_DELTA_X: // following event should be EVENT_MOUSE_DELTA_Y break; case EVENT_MOUSE_DELTA_Y: // printf( "move: %d, %d!\n", pEvent->move_info.dx, pEvent->move_info.dy ); if (prevevent.type == EVENT_MOUSE_DELTA_X) { XTestFakeRelativeMotionEvent( dpy, prevevent.value, event.value, 0 ); } else { // printf( "stray event EVENT_MOUSE_DELTA_Y\n" ); } break; case EVENT_MOUSE_DELTA_W: //no x-scrolling :-/ break; case EVENT_MOUSE_DELTA_Z: //no x-scrolling :-/ yDelta += event.value; if ( yDelta < 0 )//down { button = BUTTON_SCROLL_DOWN; yTmp = - yDelta; } else { button = BUTTON_SCROLL_UP; yTmp = yDelta; } // send as many clicks as necessary (ty synergy for this) for( ; yTmp >= SCROLL_AMT; yTmp -= SCROLL_AMT ) { XTestFakeButtonEvent( dpy, button, 1, 0 ); XTestFakeButtonEvent( dpy, button, 0, 0 ); } //fix yTmp: if ( yDelta < 0 )//we were scrolling down { yDelta = -yTmp; } else { yDelta = yTmp; } break; case EVENT_MOUSE_DOWN: //printf( "mouse down: %d", pEvent->button_info.button ); button = ButtonNumber[MouseNumber(event.value) % NButtons]; XTestFakeButtonEvent( dpy, button, 1, 0 ); break; case EVENT_MOUSE_UP: //printf( "mouse up: %d", pEvent->button_info.button ); button = ButtonNumber[MouseNumber(event.value) % NButtons]; XTestFakeButtonEvent( dpy, button, 0, 0 ); break; case EVENT_KEY_UP: case EVENT_KEY_DOWN: handleKeyEvent( dpy, pEvent ); break; case EVENT_ASCII: simulateKeyWithUnichar(dpy, pEvent); break; default: //printf( "unknown message type: %d\n", event.type ); break; } prevevent = event; XFlush( dpy ); } else if ( recvsize > 0 ) { // printf( "partial recv!\n" ); } else if ( recvsize == 0 ) { //connection terminated close( s_accept ); break; //exit this while loop, wait for another connection } else if (errno == EAGAIN) { // sending a keep-alive event for an X server XGetWindowAttributes(dpy, win, &winattr); // sending a keep-alive packet struct timeval tv; gettimeofday(&tv, NULL); MouseEvent event = {htonl(EVENT_NULL), 0, htonl(tv.tv_sec), htonl(tv.tv_usec*1000)}; send(s_accept, (void *)&event, sizeof(event), 0); } else { perror( "error in recv" ); shutdown(s_accept, SHUT_RDWR); close(s_accept); break; } } printf("Disconnected!\n"); } //shouldn't get here! return 0; }
static void spi_controller_register_with_devices (SpiDEController *controller) { DEControllerPrivateData *priv; int event_base, error_base, major_version, minor_version; priv = controller->priv; if (XTestQueryExtension (spi_get_display(), &event_base, &error_base, &major_version, &minor_version)) { XTestGrabControl (spi_get_display (), True); } /* calls to device-specific implementations and routines go here */ /* register with: keyboard hardware code handler */ /* register with: (translated) keystroke handler */ priv->have_xkb = XkbQueryExtension (spi_get_display (), &priv->xkb_major_extension_opcode, &priv->xkb_base_event_code, &priv->xkb_base_error_code, NULL, NULL); if (priv->have_xkb) { gint i; guint64 reserved = 0; priv->xkb_desc = XkbGetMap (spi_get_display (), XkbKeySymsMask, XkbUseCoreKbd); XkbSelectEvents (spi_get_display (), XkbUseCoreKbd, XkbStateNotifyMask, XkbStateNotifyMask); _numlock_physical_mask = XkbKeysymToModifiers (spi_get_display (), XK_Num_Lock); for (i = priv->xkb_desc->max_key_code; i >= priv->xkb_desc->min_key_code; --i) { if (priv->xkb_desc->map->key_sym_map[i].kt_index[0] == XkbOneLevelIndex) { if (XkbKeycodeToKeysym (spi_get_display (), i, 0, 0) != 0) { /* don't use this one if there's a grab client! */ /* Runtime errors are generated from these functions, * that are then quashed. Equivalent to: * try * {Blah} * except * {;} */ spi_x_error_trap (); XGrabKey (spi_get_display (), i, 0, spi_get_root_window (), TRUE, GrabModeSync, GrabModeSync); XSync (spi_get_display (), TRUE); XUngrabKey (spi_get_display (), i, 0, spi_get_root_window ()); if (!spi_x_error_release ()) { reserved = i; break; } } } } if (reserved) { priv->reserved_keycode = reserved; priv->reserved_keysym = XkbKeycodeToKeysym (spi_get_display (), reserved, 0, 0); } else { priv->reserved_keycode = XKeysymToKeycode (spi_get_display (), XK_numbersign); priv->reserved_keysym = XK_numbersign; } #ifdef SPI_RESERVED_DEBUG unsigned sym = 0; sym = XKeycodeToKeysym (spi_get_display (), reserved, 0); fprintf (stderr, "%x\n", sym); fprintf (stderr, "setting the reserved keycode to %d (%s)\n", reserved, XKeysymToString (XKeycodeToKeysym (spi_get_display (), reserved, 0))); #endif } spi_set_filter (global_filter_fn, controller); spi_set_events (KeyPressMask | KeyReleaseMask); x_default_error_handler = XSetErrorHandler (_spi_controller_device_error_handler); }
bool XRSERVER::main() { XRLOCKER locker(&this->lock); bool code = true; // check if XTest exists int eventBase = 0; int errorBase = 0; int majorVersion = 0; int minorVersion = 0; if (XTestQueryExtension(this->display, &eventBase, &errorBase, &majorVersion, &minorVersion) != True) { if (this->isVerbose(XREMOTE_LOG_FAIL)) { printf("xremote: error in XTestQueryExtension()\n"); } code = false; } // create socket if (!this->createSocket()) { if (this->isVerbose(XREMOTE_LOG_FAIL)) { printf("xremote: error in createSocket()\n"); } code = false; } // create window if (!this->createWindow(0, 0, 1, 1)) { if (this->isVerbose(XREMOTE_LOG_FAIL)) { printf("xremote: error in createWindow()\n"); } code = false; } // create cursor if (!this->createCursor()) { if (this->isVerbose(XREMOTE_LOG_FAIL)) { printf("xremote: error in createCursor()\n"); } code = false; } // start grab inputs if (!this->grabInput()) { if (this->isVerbose(XREMOTE_LOG_FAIL)) { printf("xremote: error in grabInput()\n"); } code = false; } // main loop this->allows = true; while (this->allows && code) { // receive network events if (!this->receiveAll()) { if (this->isVerbose(XREMOTE_LOG_FAIL)) { printf("xremote: error in receiveAll()\n"); } code = false; } // fetch next X events if (!this->pollXEvents()) { if (this->isVerbose(XREMOTE_LOG_FAIL)) { printf("xremote: error in pollXEvents()\n"); } code = false; } // send all event to network if (!this->sendAll()) { if (this->isVerbose(XREMOTE_LOG_FAIL)) { printf("xremote: error in sendAll()\n"); } code = false; } // send alive messages if (!this->isGrabbing()) { for (map<string, XRCLIENTREF>::iterator it = this->clients.begin(); it != this->clients.end(); ++it) { if ((time(NULL) - it->second.lastCheck) >= XREMOTE_CHECK_FREQ) { it->second.lastCheck = time(NULL); if ((time(NULL) - it->second.alive) >= XREMOTE_DEAD_CHECK) { this->clients.erase(it); XRNETNOTIFYEVENT event = { this->meta.getLocalPort(), XREVENT_RELEASE, XRNOTIFY_NONE, 0 }; this->sendEvent(it->second.meta, &event); } else if ((time(NULL) - it->second.alive) >= XREMOTE_ALIVE_CHECK) { XRNETNOTIFYEVENT event = { this->meta.getLocalPort(), XREVENT_ALIVE, XRNOTIFY_NONE, 0 }; this->sendEvent(it->second.meta, &event); } } } if (this->clients.size() == 0) { this->release(); } } else { locker.usleep(10000); } } this->allows = false; // reset buttons down for (map<int, bool>::iterator it = this->buttons.begin(); it != this->buttons.end(); ++it) { if (it->second) { XRNETPTREVENT event = { 0, XREVENT_PTR_UP, it->first, 0, 0 }; this->processButtonEvent(&event); } } // reset keys down for (map<unsigned int, bool>::iterator it = this->keys.begin(); it != this->keys.end(); ++it) { if (it->second) { XRNETKBDEVENT event = { 0, XREVENT_KBD_UP, it->first }; this->processKbdEvent(&event); } } // stop grabbing inputs if (!this->ungrabInput()) { if (this->isVerbose(XREMOTE_LOG_FAIL)) { printf("xremote: error in ungrabInput()\n"); } code = false; } // destroy cursor if (!this->destroyCursor()) { if (this->isVerbose(XREMOTE_LOG_FAIL)) { printf("xremote: error in destroyCursor()\n"); } code = false; } // destroy window if (!this->destroyWindow()) { if (this->isVerbose(XREMOTE_LOG_FAIL)) { printf("xremote: error in destroyWindow()\n"); } code = false; } // destroy socket if (!this->destroySocket()) { if (this->isVerbose(XREMOTE_LOG_FAIL)) { printf("xremote: error in destroySocket()\n"); } code = false; } return code; }
int main(int argc, char **argv) { // init vars have_xtest = False; numConfigs = 0; currConfig = 0; gui_selectConfig = 0; G15Version = 0; config_fd = 0; mled_state = G15_LED_M1; mkey_state = 0; recording = 0; // this is for keeping track of when to redraw gui_oldConfig = MAX_CONFIGS+1; // To make sure it will be redrawn at first was_recording = 1; #ifdef USE_XTEST int xtest_major_version = 0; int xtest_minor_version = 0; #endif struct sigaction new_action; int dummy=0,i=0; unsigned char user[256]; struct passwd *username; char splashpath[1024]; unsigned int dump = 0; unsigned int keysonly = 0; FILE *config; unsigned int convert = 0; memset(configDir,0,sizeof(configDir)); strncpy(configDir,getenv("HOME"),1024); strncat(configDir,"/.g15macro/",1024-strlen(configDir)); strncpy(configpath,getenv("HOME"),1024); memset(user,0,256); for(i=0;i<argc;i++){ if (!strncmp(argv[i], "-u",2) || !strncmp(argv[i], "--user",6)) { if(argv[i+1]!=NULL){ strncpy((char*)user,argv[i+1],128); i++; } } if (!strncmp(argv[i], "-d",2) || !strncmp(argv[i], "--dump",6)) { dump = 1; } if (!strncmp(argv[i], "-h",2) || !strncmp(argv[i], "--help",6)) { helptext(); exit(0); } if (!strncmp(argv[i], "-k",2) || !strncmp(argv[i], "--keysonly",10)) { keysonly = 1; } if (!strncmp(argv[i], "-g",2) || !strncmp(argv[i], "--debug",7)) { printf("Debugging Enabled\n"); debug = 1; } if (!strncmp(argv[i], "-v",2) || !strncmp(argv[i], "--version",9)) { printf("G15Macro version %s\n\n",PACKAGE_VERSION); exit(0); } if (!strncmp(argv[i], "-2",2) || !strncmp(argv[i], "--g15version2",13)) { G15Version = 1; // See declaration for info } } if(strlen((char*)user)){ username = getpwnam((char*)user); if (username==NULL) { username = getpwuid(geteuid()); printf("BEWARE: running as effective uid %i\n",username->pw_uid); } else { if(0==setuid(username->pw_uid)) { setgid(username->pw_gid); strncpy(configpath,username->pw_dir,1024); strncpy(configDir,username->pw_dir,1024); printf("running as user %s\n",username->pw_name); } else printf("Unable to run as user \"%s\" - you dont have permissions for that.\nRunning as \"%s\"\n",username->pw_name,getenv("USER")); } printf("BEWARE: this program will run files WITHOUT dropping any kind of privilegies.\n"); } canvas = (g15canvas *) malloc (sizeof (g15canvas)); if (canvas != NULL) { g15r_initCanvas(canvas); } else { printf("Unable to initialise the libg15render canvas\nExiting\n"); return 1; } do { dpy = XOpenDisplay(getenv("DISPLAY")); if (!dpy) { printf("Unable to open display %s - retrying\n",getenv("DISPLAY")); sleep(2); } }while(!dpy); /* completely ignore errors and carry on */ XSetErrorHandler(myx_error_handler); // Get keycodes for all keys strcpy(GKeyCodeCfg,configDir); strncat(GKeyCodeCfg,"GKeyCodes.cfg",1024-strlen(GKeyCodeCfg)); printf("%s\n",GKeyCodeCfg); getKeyDefs(GKeyCodeCfg); configure_mmediakeys(); change_keymap(0); XFlush(dpy); if(keysonly>0) goto close_and_exit; /* old binary config format */ strncat(configpath,"/.g15macro",1024-strlen(configpath)); strncat(configpath,"/g15macro-data",1024-strlen(configpath)); config_fd = open(configpath,O_RDONLY|O_SYNC); mstates[0] = malloc(sizeof(mstates_t)); mstates[1] = (mstates_t*)malloc(sizeof(mstates_t)); mstates[2] = (mstates_t*)malloc(sizeof(mstates_t)); if(config_fd>0) { printf("Converting old data\n"); read(config_fd,mstates[0],sizeof(mstates_t)); read(config_fd,mstates[1],sizeof(mstates_t)); read(config_fd,mstates[2],sizeof(mstates_t)); close(config_fd); strncpy(configpath,getenv("HOME"),1024); strncat(configpath,"/.g15macro",1024-strlen(configpath)); char configbak[1024]; strcpy(configbak,configpath); strncat(configpath,"/g15macro-data",1024-strlen(configpath)); strncat(configbak,"/g15macro-data.old",1024-strlen(configpath)); rename(configpath,configbak); convert = 1; } else cleanMstates(0); //0 = only NULL the pointers /* new format */ strncpy(configpath,getenv("HOME"),1024); strncat(configpath,"/.g15macro",1024-strlen(configpath)); mkdir(configpath,0777); strncat(configpath,"/g15macro.conf",1024-strlen(configpath)); config=fopen(configpath,"a"); fclose(config); 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); loadMultiConfig(); printf("I've now got the following macro files:\n"); for(i=0; i < MAX_CONFIGS;++i) { if(!configs[i]) continue; printf("%i:%s%s\n",i,configDir,configs[i]->configfile); } if(!convert) { memset(configpath,0,sizeof(configpath)); strcpy(configpath,configDir); strncat(configpath,configs[currConfig]->configfile,1024-strlen(configpath)); restore_config(configpath); } if(dump){ printf("G15Macro Dumping Codes..."); dump_config(stderr); exit(0); } g15_send_cmd (g15screen_fd,G15DAEMON_KEY_HANDLER, dummy); usleep(1000); g15_send_cmd (g15screen_fd,G15DAEMON_MKEYLEDS,mled_state); usleep(1000); root_win = DefaultRootWindow(dpy); if (!root_win) { printf("Cant find root window\n"); return 1; } have_xtest = False; #ifdef HAVE_XTEST #ifdef USE_XTEST have_xtest = XTestQueryExtension(dpy, &dummy, &dummy, &xtest_major_version, &xtest_minor_version); if(have_xtest == False || xtest_major_version < 2 || (xtest_major_version <= 2 && xtest_minor_version < 2)) { printf("Warning: XTEST extension not supported by Xserver. This is not fatal.\nReverting to XSendEvent for keypress emulation\n"); } #else //USE_XTEST printf("XTest disabled by configure option. Using XSendEvent instead.\n"); #endif //USE_XTEST #else //HAVE_XTEST printf("XTest disabled by configure: no devel package was found. Using XSendEvent instead.\n"); #endif //HAVE_XTEST printf("XTest enabled. Using XTest.\n"); new_action.sa_handler = g15macro_sighandler; new_action.sa_flags = 0; sigaction(SIGINT, &new_action, NULL); sigaction(SIGQUIT, &new_action, NULL); sigaction(SIGTERM, &new_action, NULL); sigaction(SIGPIPE, &new_action, NULL); sigaction(SIGHUP, &new_action, NULL); // So that forked processes that die can actually die instead of going defunct. struct sigaction act; memset(&act,0,sizeof(act)); act.sa_handler = &cleanupChildren; sigaction(SIGCHLD,&act,NULL); snprintf((char*)splashpath,1024,"%s/%s",DATADIR,"g15macro/splash/g15macro.wbmp"); g15r_loadWbmpSplash(canvas, splashpath); g15_send(g15screen_fd,(char *)canvas->buffer,G15_BUFFER_LEN); // Following piece of code is not documented (what i could find anyway) // But makes so that the user can never bring this screen to front. // TODO: Document it // #ifdef G15DAEMON_NEVER_SELECT // g15_send_cmd (g15screen_fd, G15DAEMON_NEVER_SELECT, dummy); // #endif usleep(1000); pthread_mutex_init(&x11mutex,NULL); pthread_mutex_init(&config_mutex,NULL); pthread_mutex_init(&gui_select,NULL); pthread_attr_t attr; pthread_attr_init(&attr); int thread_policy=SCHED_FIFO; pthread_attr_setschedpolicy(&attr,thread_policy); pthread_attr_setstacksize(&attr,32*1024); /* set stack to 32k - dont need 8Mb !! */ pthread_create(&Xkeys, &attr, xevent_thread, NULL); pthread_create(&Lkeys, &attr, Lkeys_thread, NULL); mainLoop(); cleanup(); close_and_exit: /* XCloseDisplay(dpy); */ return 0; }