Highlight current mouse position

9,580

Solution 1

While I like Mikeserv's answer for cleverness, it has the downside that it will create a window which "steals" the focus and has to be clicked away. I also find it takes just slightly too long to start: about 0.2 to 0.3 seconds, which is just slightly too slow for a "smooth" experience.

I finally got around to digging into XLib, and clobbered together a basic C program to do this. The visual effect is roughly similar to what Windows (XP) has (from memory). It's not very beautiful, but it works ;-) It doesn't "steal" focus, starts near-instantaneous, and you can click "through" it.

enter image description here

You can compile it with cc find-cursor.c -o find-cursor -lX11 -lXext -lXfixes. There are some variables at the top you can tweak to change the size, speed, etc.

I released this as a program at https://github.com/arp242/find-cursor. I recommend you use this version, as it has some improvements that the below script doesn't have (such as commandline arguments and ability to click "through" the window). I've left the below as-is due to its simplicity.

/*
 * https://github.com/arp242/find-cursor
 * Copyright © 2015 Martin Tournoij <[email protected]>
 * See below for full copyright
 */

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

#include <X11/Xlib.h>
#include <X11/Xutil.h>


// Some variables you can play with :-)
int size = 220;
int step = 40;
int speed = 400;
int line_width = 2;
char color_name[] = "black";


int main(int argc, char* argv[]) {
    // Setup display and such
    char *display_name = getenv("DISPLAY");
    if (!display_name) {
        fprintf(stderr, "%s: cannot connect to X server '%s'\n", argv[0], display_name);
        exit(1);
    }

    Display *display = XOpenDisplay(display_name);
    int screen = DefaultScreen(display);

    // Get the mouse cursor position
    int win_x, win_y, root_x, root_y = 0;
    unsigned int mask = 0;
    Window child_win, root_win;
    XQueryPointer(display, XRootWindow(display, screen),
        &child_win, &root_win,
        &root_x, &root_y, &win_x, &win_y, &mask);

    // Create a window at the mouse position
    XSetWindowAttributes window_attr;
    window_attr.override_redirect = 1;
    Window window = XCreateWindow(display, XRootWindow(display, screen),
        root_x - size/2, root_y - size/2,   // x, y position
        size, size,                         // width, height
        0,                                  // border width
        DefaultDepth(display, screen),      // depth
        CopyFromParent,                     // class
        DefaultVisual(display, screen),     // visual
        CWOverrideRedirect,                 // valuemask
        &window_attr                        // attributes
    );
    XMapWindow(display, window);
    XStoreName(display, window, "find-cursor");

    XClassHint *class = XAllocClassHint();
    class->res_name = "find-cursor";
    class->res_class = "find-cursor";
    XSetClassHint(display, window, class);
    XFree(class);

    // Keep the window on top
    XEvent e;
    memset(&e, 0, sizeof(e));
    e.xclient.type = ClientMessage;
    e.xclient.message_type = XInternAtom(display, "_NET_WM_STATE", False);
    e.xclient.display = display;
    e.xclient.window = window;
    e.xclient.format = 32;
    e.xclient.data.l[0] = 1;
    e.xclient.data.l[1] = XInternAtom(display, "_NET_WM_STATE_STAYS_ON_TOP", False);
    XSendEvent(display, XRootWindow(display, screen), False, SubstructureRedirectMask, &e);

    XRaiseWindow(display, window);
    XFlush(display);

    // Prepare to draw on this window
    XGCValues values;
    values.graphics_exposures = False;

    unsigned long valuemask = 0;
    GC gc = XCreateGC(display, window, valuemask, &values);

    Colormap colormap = DefaultColormap(display, screen);
    XColor color;
    XAllocNamedColor(display, colormap, color_name, &color, &color);
    XSetForeground(display, gc, color.pixel);
    XSetLineAttributes(display, gc, line_width, LineSolid, CapButt, JoinBevel);

    // Draw the circles
    for (int i=1; i<=size; i+=step) { 
        XDrawArc(display, window, gc,
            size/2 - i/2, size/2 - i/2,   // x, y position
            i, i,                         // Size
            0, 360 * 64);                 // Make it a full circle

        XSync(display, False);
        usleep(speed * 100);
    }
    XFreeGC(display, gc);
    XCloseDisplay(display);
}


/*
 *  The MIT License (MIT)
 * 
 *  Copyright © 2015 Martin Tournoij
 * 
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to
 *  deal in the Software without restriction, including without limitation the
 *  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 *  sell copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 * 
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 * 
 *  The software is provided "as is", without warranty of any kind, express or
 *  implied, including but not limited to the warranties of merchantability,
 *  fitness for a particular purpose and noninfringement. In no event shall the
 *  authors or copyright holders be liable for any claim, damages or other
 *  liability, whether in an action of contract, tort or otherwise, arising
 *  from, out of or in connection with the software or the use or other dealings
 *  in the software.
 */

Solution 2

The following will probably work for you:

#!/bin/sh
unset X Y; sleep 1
eval "$(xdotool getmouselocation -shell 2>/dev/null)"
for n in X Y; do  : "$(($n-=$n>25?25:$n))"; done
xwd -root -silent |
xv -    -crop "$X" "$Y" 50 50 \
        -geometry "50x50+$X+$Y" \
        -nodecor -viewonly -rv -quit

It depends on the three utilities xv, xwd, and xdotool. The first two are very common X utilities, and the third I'm reasonably sure you already have.

After sleeping one second, xdotool writes the mouse's current coordinates to its stdout in an eval-friendly -shell format like:

X=[num]
Y=[num]
windowID=[num]

eval sets the shell variables accordingly, and the for loop subtracts half of the soon-to-be-displayed image's size from each of $X and $Y's values or, if either value is less than 25, sets them to 0.

xwd dumps the root window over a pipe to xv, which crops around the mouse location to an image size of 50x50 and displays a negative of the image under the current mouse cursor in a little window sans any window manager decorations.

The end result is something like this:

findmouse

...though I guess my mouse cursor doesn't show-up in screen shots. Rest assured, though, it was right over the white box there when I took the picture.

You can see in the image how I also wrote it as a shell function and backgrounded it. It is mainly for that reason there is a sleep in there at all - pressing the RETURN key will scroll the terminal if you're already at the bottom, and xwd was fast enough to grab its picture of the screen before the terminal scrolled - which would offset my negative in the image a little and I didn't like it.

Anyway, because xv is run with both the -viewonly and -quit switches, it will disappear as soon as a mouse-button is clicked or a keyboard key is pressed - but will remain until you do either.

Undoubtedly you could do much more elaborate things with ImageMagick or even xv alone as well - but I just did a little negative box under the mouse cursor. You can find the xv docs here and the docs for xwd in man xwd.

Share:
9,580

Related videos on Youtube

deshtop
Author by

deshtop

Updated on September 18, 2022

Comments

  • deshtop
    deshtop over 1 year

    I'm running a dual-screen setup and have my trackpad disabled most of the time (which includes hiding the mousepointer). When I reenable the trackpad (and display the mouse pointer again), I've lost track where the pointer was before.

    I'm looking for a tool to highlight the current mouse position (e.g. by a circle). Ideally this would be a single command flashing the circle for a short period of time.

    I'm aware that xdotool can find the current position, yet there is no highlighting; also, key-mon doesn't provide this functionality. I've also read that cairo composition manager provides such functionality, yet I'm wondering if there is a smaller tool to achieve this.

    In case there is no such tool: What is the easiest way to display such a circle around the cursor using the data provided by xdotool getmouselocation?

    In case this is relevant: I don't use a desktop environment, just the xmonad window manager.

  • deshtop
    deshtop about 9 years
    This looks good, except for the fact that my distro (debian) doesn't provide xv. If possible i'd like to avoid compiling xv on my own and let apt handle the package management.
  • mikeserv
    mikeserv about 9 years
    @deshtop - here's a repo, if you want it. You can also probably do similar things with the ImageMagick display utility. And of course there is always feh. I didn't have feh installed at the moment when writing that up, and, though I tried once or twice, I couldn't easily figure on how to make display open without window manged borders.
  • deshtop
    deshtop about 9 years
    Thanks for the repo, yet i'm a bit cautious with non-official repositories. I'll see if i can use ImageMagick
  • mikeserv
    mikeserv about 9 years
    @deshtop - you probably can . At the very least you can configure xmonad not to decorate the display window that this would launch - or else you could launch display as -iconic then use xdotool to remove its decorations and uniconify (or whatever that's called) it.
  • gandalf3
    gandalf3 about 8 years
    How easy would it be to turn this into a shaped window with a hole in the middle for mouse events to go through? I attempted to turn your example into something like what the OP is looking for here, but having no experience with xlib, I ended up hopelessly lost..
  • Grzegorz Wierzowiecki
    Grzegorz Wierzowiecki almost 8 years
    FTR: How to compile it under Ubuntu: askubuntu.com/q/801252/31300
  • Martin Tournoij
    Martin Tournoij about 7 years
    @gandalf3 Almost a year later I finally got around at implementing that :-) I didn't modify the above snippet so it could maintain its simplicity, I only modified the version at github.com/Carpetsmoker/find-cursor .
  • gandalf3
    gandalf3 about 7 years
    @Carpetsmoker Works like a charm, brilliant! Thanks for this :) Now to have it update position to follow the mouse..
  • Aquarius Power
    Aquarius Power almost 7 years
    the -f option should prevent the application from exiting and keep following right? but it exited and I had to put in a while true loop, is that a bug?
  • Aquarius Power
    Aquarius Power almost 7 years
    this sounds really interesting, but xv seems a no go on ubuntu 14.04 (it was not compiling despite all deps were supplied), and display is opening a big window, and I have no idea yet how to use feh it just scanned all the files on my home (current path) looking for pictures, funny.. hehe is a cataloguer.
  • Martin Tournoij
    Martin Tournoij almost 7 years
    The application shows the circle and then exits @AquariusPower, so that's the expected behaviour. The way to use it is to map a key combination to start it. The -f option means it will follow the mouse cursor around while running, but doesn't actually change that basic concept (this isn't compatible with all window managers, which is why it's an option).
  • Grzegorz Wierzowiecki
    Grzegorz Wierzowiecki almost 6 years
    Could you consider extending your program to work continuously and display after each mouse click? (e.g. combine with stackoverflow.com/a/8792991/544721 ?) Otherwise, could you provide other tool that may trigger find-cursor after each click? Also I would love to make different clicks for primary, secondary and tertiary pointer device keys... (tree calls to find-ucros with different colour option?) -> btw. asked here: twitter.com/GWierzowiecki/status/1019930612529057792
  • Grzegorz Wierzowiecki
    Grzegorz Wierzowiecki almost 6 years
    btw. I've found this for screenkey, but not sure if picked up : github.com/wavexx/screenkey/issues/73
  • balasaheb barde
    balasaheb barde over 3 years
    Thank you Martin for this useful utility.
  • ACK_stoverflow
    ACK_stoverflow about 3 years
    This is awesome, thank you! A few tips for anyone else: to compile on Debian Buster I had to apt install libx11-dev libxdamage-dev libxrender-dev libxext-dev. Also, I couldn't get xcape to work, but it's easily doable with xmodmap: xmodmap -e 'keysym Control_L = Control_L F13'. (Putting Control_L before F13 allows Control_L to pass through synergy.) Finding the cursor used to be difficult on my 7 screen 4 PC synergy setup!