4

How do you read any arbitrary keypress in R (interactive-mode), such as cursor-up or shift, and return the actual key(s) pressed?

Ideally in a device-independent, OS-independent way (I'm on Mac OS 10.8.x)

I'm talking about reading any actual arbitrary keypress including cursor-keys or modifier-keys, so scan() and readline() won't do it - cursor-keys get intercepted by the interactive console. And not just waiting for a keypress.

It's not clear this is easy or device-independent. I looked at documentation: interactive(), options('device'), R_INTERACTIVE_DEVICE, R_DEFAULT_DEVICE

I read R-internals, which says "a graphics device... can handle requests/opportunities to take action such as... wait for an event, for example a mouse click or keypress." but it doesn't say much more.

I tried grDevices::getGraphicsEvent() but got:

> getGraphicsEvent('waiting for cursor keys', onKeybd=function(key) { print(key) } )
Error in setGraphicsEventEnv(which, as.environment(list(...))) : 
  this graphics device does not support event handling

It seems like if you dig deep enough you could use a toolkit-specific and/or OS-specific hack, e.g. with Quartz. This guy suggests Sudoku::playSudoku(), which uses Quartz to handle mouse and key input. I have Quartz. But a Quartz-specific solution won't work on Windows. This all seems quite messy.

Can someone please demystify all this?

Community
  • 1
  • 1
smci
  • 32,567
  • 20
  • 113
  • 146
  • 1
    I wondered whether Shiny would have anything for this, and found https://github.com/rstudio/ggvis/blob/master/R/events-keyboard.R from ggvis, not sure if that's any use or inspiration to you... – ping Apr 28 '14 at 10:19
  • I think you need a GUI. The terminal just do not send anything to the R process when you only press the shift key for instance. – Karl Forner Apr 29 '14 at 12:08
  • 1
    ping, Karl Forner et al: please give specific names of packages/functions, if you can? – smci Apr 29 '14 at 12:15
  • Did you make any progress on this. I can only get this to work with Windows and not mad @smci – MadmanLee Jul 31 '17 at 21:22
  • The consensus I got from many R users was there is no platform-independent way to do this, and you have to use some device- and OS-specific functions, if they even exist on your platform. Really yukky. Might as well use Shiny for a GUI. Or use something other than R. @MadmanLee – smci Aug 01 '17 at 00:42
  • 1
    That is a big bummer. For R to remain competitive, development needs to be equal in both windows and mac. All guis i developed in windows work great, but in mac only the "locator" functions works. – MadmanLee Aug 01 '17 at 18:35

0 Answers0