Ubuntu – How to share the clipboard between two X servers

clipboardxorg

I've recently set up my Ubuntu machine so that I run another X session in pty8. I mostly run virtual machines or remote desktop sessions on this other X server, which helps mediate some of the frustrations that can happen with keyboard integration in these environments.

However, now if I copy something from some window on :0, I can't paste it into some window on :1.

Is there a way I can share the clipboard between these two sessions?

Best Answer

I came up with a solution that seems to work pretty well. I'm not sure if there's a better way, but I wrote a script that starts my VM and then monitors the clipboard on display :0 for changes. When a change is detected, it copies the clipboard contents to display :1. It does this bidirectionally, so I can copy and paste from the VM just fine too.

Here's the script:

#!/bin/bash

virtualbox --startvm "Windows 7" --fullscreen &
waitpid=$!

watch_clip() {
  local curr="" prev="" from=$1 to=:0

  # On first run, we need to copy from :0 to :1 but not vice versa
  if [[ "$from" == ":0" ]]; then
    xclip -o -selection clipboard -d :0 2> /dev/null | xclip -selection clipboard -d :1
    to=:1
  fi

  while true; do
    # Get the current clipboard contents
    curr=`xclip -o -selection clipboard -d $from 2> /dev/null`

    # Compare to previous results and copy if it's changed
    if [[ "$curr" != "$prev" ]]; then
      echo "$curr" | xclip -selection clipboard -d $to
    fi

    prev="$curr"   
    sleep 0.5
  done
}

watch_clip :0 &
watch_clip :1 &
wait $waitpid

Then all that's needed is the command to start the second X session:

startx ./.startwin7 -- :1

I haven't noticed any issues, but if anyone can think of a better way I'd definitely appreciate the input.