1 21 22 package org.armedbear.j; 23 24 import java.awt.AWTEvent ; 25 import java.awt.Toolkit ; 26 import java.awt.datatransfer.Clipboard ; 27 import java.awt.datatransfer.ClipboardOwner ; 28 import java.awt.datatransfer.DataFlavor ; 29 import java.awt.datatransfer.StringSelection ; 30 import java.awt.datatransfer.Transferable ; 31 import java.awt.event.MouseEvent ; 32 import javax.swing.undo.CompoundEdit ; 33 34 public final class SystemSelection implements ClipboardOwner , Constants 35 { 36 private static SystemSelection systemSelection = 37 getSystemSelection(); 38 39 private final Clipboard clipboard; 40 private String primarySelection; 41 42 private SystemSelection(Clipboard clipboard) 43 { 44 this.clipboard = clipboard; 45 } 46 47 private static SystemSelection getSystemSelection() 48 { 49 try { 50 Clipboard clipboard = 51 Toolkit.getDefaultToolkit().getSystemSelection(); 52 return new SystemSelection(clipboard); 53 } 54 catch (Exception e) { 55 return null; 56 } 57 } 58 59 public void lostOwnership(Clipboard clipboard, Transferable contents) 60 { 61 primarySelection = null; 62 } 63 64 public void update(Editor editor) 65 { 66 try { 67 if (clipboard != null) { 68 StringSelection ss = null; 69 if (editor.getMark() != null && !editor.isColumnSelection()) { 70 primarySelection = new Region(editor).toString(); 71 ss = new StringSelection (primarySelection); 72 } else if (primarySelection != null) { 73 ss = new StringSelection (""); 75 } 76 if (ss != null) 77 clipboard.setContents(ss, this); 78 } 79 } 80 catch (OutOfMemoryError e) { 81 Log.error("SystemSelection.update() OutOfMemoryError"); 82 } 83 } 84 85 public String getPrimarySelection() 86 { 87 if (primarySelection != null) { 88 return primarySelection; 90 } 91 Transferable t = clipboard.getContents(this); 92 if (t != null) { 93 try { 94 return (String ) t.getTransferData(DataFlavor.stringFlavor); 95 } 96 catch (Exception e) {} 97 } 98 return null; 99 } 100 101 public static void updateSystemSelection(Editor editor) 102 { 103 if (systemSelection != null) 104 systemSelection.update(editor); 105 } 106 107 public static void pastePrimarySelection() 108 { 109 final Editor editor = Editor.currentEditor(); 110 if (!editor.checkReadOnly()) 111 return; 112 if (systemSelection == null) { 113 Log.debug("pastePrimarySelection systemSelection is null"); 114 return; 115 } 116 String s = systemSelection.getPrimarySelection(); 117 if (s == null || s.length() == 0) { 118 Log.debug("pastePrimarySelection no selection"); 119 return; 120 } 121 KillRing killRing = Editor.getKillRing(); 122 killRing.appendNew(s); 123 killRing.pop(); 126 AWTEvent e = editor.getDispatcher().getLastEvent(); 127 if (e instanceof MouseEvent ) { 128 CompoundEdit compoundEdit = editor.beginCompoundEdit(); 129 editor.mouseMoveDotToPoint((MouseEvent ) e); 130 editor.paste(s); 131 editor.endCompoundEdit(compoundEdit); 132 } else 133 editor.paste(s); 134 editor.setCurrentCommand(COMMAND_PASTE); 135 } 136 } 137 | Popular Tags |