package org.robolectric.shadows;

import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ClipboardManager;
import android.content.ClipboardManager.OnPrimaryClipChangedListener;
import com.google.android.collect.Lists;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.RealObject;
import java.util.Collection;
import static org.robolectric.Robolectric.directlyOn;

@SuppressWarnings("UnusedDeclaration")
@Implements(ClipboardManager.class)
public class ShadowClipboardManager {
  @RealObject private ClipboardManager realClipboardManager;
  private final Collection<OnPrimaryClipChangedListener> listeners = Lists.newArrayList();
  private ClipData clip;

  @Implementation
  public void setPrimaryClip(ClipData clip) {
    if (clip != null) {
       clip.prepareToLeaveProcess();
    }
    this.clip = clip;
    for (OnPrimaryClipChangedListener listener : listeners) {
      listener.onPrimaryClipChanged();
    }
  }

  @Implementation
  public ClipData getPrimaryClip() {
    return clip;
  }

  @Implementation
  public ClipDescription getPrimaryClipDescription() {
    return clip == null ? null : clip.getDescription();
  }

  @Implementation
  public boolean hasPrimaryClip() {
    return clip != null;
  }

  @Implementation
  public void addPrimaryClipChangedListener(OnPrimaryClipChangedListener listener) {
    listeners.add(listener);
  }

  @Implementation
  public void removePrimaryClipChangedListener(OnPrimaryClipChangedListener listener) {
    listeners.remove(listener);
  }

  @Implementation
  public void setText(CharSequence text) {
    setPrimaryClip(ClipData.newPlainText(null, text));
  }

  @Implementation
  public boolean hasText() {
    CharSequence text = directlyOn(realClipboardManager, ClipboardManager.class).getText();
    return text != null && text.length() > 0;
  }
}

@@ -921,16 +921,314 @@
  = clip;
+%0A%0A    // Synchronously copy the listeners, then handle the change event for each.%0A    OnPrimaryClipChangedListener%5B%5D listenersCopy;%0A    synchronized (listeners) %7B%0A      listenersCopy = new OnPrimaryClipChangedListener%5Blisteners.size()%5D;%0A      listenersCopy = listeners.toArray(listenersCopy);%0A    %7D
 %0A    for
@@ -1270,32 +1270,36 @@
 ener : listeners
+Copy
 ) %7B%0A      listen
@@ -1726,32 +1726,65 @@
 ner listener) %7B%0A
+    synchronized (listeners) %7B%0A  
     listeners.ad
@@ -1788,32 +1788,38 @@
 .add(listener);%0A
+    %7D%0A
   %7D%0A%0A  @Implemen
@@ -1909,24 +1909,57 @@
 listener) %7B%0A
+    synchronized (listeners) %7B%0A  
     listener
@@ -1978,16 +1978,22 @@
 tener);%0A
+    %7D%0A
   %7D%0A%0A  @

Add synchronization around the listeners in ShadowClipboardManager without synchronization tests fail:-