Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: a157ee036e
Fetching contributors…

Cannot retrieve contributors at this time

file 215 lines (176 sloc) 7.205 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
package com.codecommit.cccp
package jedit

import java.awt.EventQueue
import java.io.File
import java.lang.ref.WeakReference
import javax.swing.JOptionPane
import org.gjt.sp.jedit
import jedit.{Buffer, jEdit => JEdit, EBPlugin, View}
import jedit.buffer.{BufferAdapter, JEditBuffer}
import jedit.textarea.Selection
import scala.util.parsing.input.CharSequenceReader

class CCCPPlugin extends EBPlugin {
  override def start() {
    val starter = new Thread {
      override def run() {
        CCCPPlugin.init()
      }
    }
    
    starter.setPriority(3)
    starter.start()
  }
  
  override def stop() {
    CCCPPlugin.shutdown()
  }
}

object CCCPPlugin {
  import SExp._
  
  val HomeProperty = "cccp.home"
  val ProtocolProperty = "cccp.protocol"
  val HostProperty = "cccp.host"
  val PortProperty = "cccp.port"
  
  def Home = new File(Option(JEdit.getProperty(HomeProperty)) getOrElse "/Users/daniel/Development/Scala/cccp/agent/dist/")
  var Backend = new Backend(Home, fatalServerError)
  
  def Protocol = Option(JEdit.getProperty(ProtocolProperty)) getOrElse "http"
  def Host = Option(JEdit.getProperty(HostProperty)) getOrElse "localhost"
  def Port = Option(JEdit.getProperty(PortProperty)) flatMap { s => try { Some(s.toInt) } catch { case _ => None } } getOrElse 8585
  
  @volatile
  private var _callId = 0
  private val callLock = new AnyRef
  
  @volatile
  private var ignoredFiles = Set[String]() // will only be written from the EDT
  
  def callId() = callLock synchronized {
    _callId += 1
    _callId
  }
  
  // TODO make this more controlled
  def reinit() {
    shutdown()
    Backend = new Backend(Home, fatalServerError)
    init()
  }
  
  private def init() {
    Backend.start()(receive)
    sendRPC(SExp(key("swank:init-connection"), SExp(key(":protocol"), Protocol, key(":host"), Host, key(":port"), Port)), callId())
  }
  
  private def shutdown() {
    sendRPC(SExp(key("swank:shutdown")), callId())
    Backend.stop()
  }
  
  def link(view: View) {
    val buffer = view.getBuffer
    val fileName = new File(buffer.getPath).getAbsolutePath
    
    EventQueue.invokeLater(new Runnable {
      def run() {
        for (id <- Option(JOptionPane.showInputDialog(view, "File ID:"))) {
          sendRPC(SExp(key("swank:link-file"), id, fileName), callId())
          
          buffer.addBufferListener(new BufferAdapter {
            override def contentInserted(editBuffer: JEditBuffer, startLine: Int, offset: Int, numLines: Int, length: Int) {
              contentChanged("insert", editBuffer, startLine, offset, numLines, length)
            }
            
            override def preContentRemoved(editBuffer: JEditBuffer, startLine: Int, offset: Int, numLines: Int, length: Int) {
              contentChanged("delete", editBuffer, startLine, offset, numLines, length)
            }
            
            private def contentChanged(change: String, editBuffer: JEditBuffer, startLine: Int, offset: Int, numLines: Int, length: Int) {
              editBuffer match {
                case buffer: Buffer => {
                  if (fileName == new File(buffer.getPath).getAbsolutePath) {
                    if (!ignoredFiles.contains(fileName)) {
                      val text = buffer.getText(offset, length)
                      val remainder = buffer.getLength - offset - text.length
                      sendChange(change, fileName, offset, text, remainder)
                    }
                  }
                }
                
                case _ => // ignore
              }
            }
          })
        }
      }
    })
  }
  
  def unlink(view: View) {
    val buffer = view.getBuffer
    val fileName = new File(buffer.getPath).getAbsolutePath
    
    EventQueue.invokeLater(new Runnable {
      def run() {
        val confirm = JOptionPane.showConfirmDialog(view, "Are you sure you wish to unlink the buffer? You should not attempt to relink on the same identifier following an unlink.", "Are you sure?", JOptionPane.YES_NO_OPTION)
        
        if (confirm == JOptionPane.YES_OPTION) {
          sendRPC(SExp(key("swank:unlink-file"), fileName), callId())
        }
      }
    })
  }
  
  private def applyActions(fileName: String, actions: Seq[EditorAction]) {
    val view = JEdit.getActiveView
    val buffer = JEdit.openFile(view, fileName)
    
    val field = classOf[JEditBuffer].getDeclaredField("undoInProgress")
    field.setAccessible(true)
    field.set(buffer, true)
    
    buffer.beginCompoundEdit()
    try {
      actions foreach {
        case InsertAt(offset, text) => buffer.insert(offset, text)
        case DeleteAt(offset, text) => buffer.remove(offset, text.length)
      }
    } finally {
      buffer.endCompoundEdit()
      field.set(buffer, false)
    }
    
    // TODO adjust undo/redo stack for new offsets
  }
  
  // TODO type safety
  private def sendChange(change: String, fileName: String, offset: Int, text: String, after: Int) {
    val pre = if (offset > 0) key(":retain") :: IntAtom(offset) :: Nil else Nil
    val mid = key(":" + change) :: StringAtom(text) :: Nil
    val post = if (after > 0) key(":retain") :: IntAtom(after) :: Nil else Nil
    val op = SExpList(pre ::: mid ::: post)
    sendRPC(SExp(key("swank:edit-file"), fileName, op), callId())
  }
  
  private def sendRPC(form: SExp, id: Int) {
    send(SExp(key(":swank-rpc"), form, id).toWireString)
  }
  
  private def send(chunk: String) {
    Backend.send(chunk)
  }
  
  private def receive(chunk: String) {
    SExp.read(new CharSequenceReader(chunk)) match {
      case SExpList(KeywordAtom(":edit-performed") :: StringAtom(fileName) :: (form: SExpList) :: Nil) => {
        val components = unmarshallOp(form.items.toList)
        
        val (_, actions) = components.foldLeft((0, Vector[EditorAction]())) {
          case ((offset, acc), Retain(length)) => (offset + length, acc)
          case ((offset, acc), Insert(text)) => (offset + text.length, acc :+ InsertAt(offset, text))
          case ((offset, acc), Delete(text)) => (offset + text.length, acc :+ DeleteAt(offset, text))
        }
        
        EventQueue.invokeLater(new Runnable {
          def run() {
            ignoredFiles += fileName
            applyActions(fileName, actions)
            ignoredFiles -= fileName
          }
        })
      }
      
      case _ => // TODO
    }
  }
  
  private def fatalServerError(msg: String) {
  }
  
  private def unmarshallOp(form: List[SExp]): List[OpComponent] = {
    val components = form zip (form drop 1) collect { case (KeywordAtom(id), se) => (id, se) }
    components collect {
      case (":retain", IntAtom(length)) if length > 0 => Retain(length)
      case (":insert", StringAtom(text)) => Insert(text)
      case (":delete", StringAtom(text)) => Delete(text)
    }
  }
  
  sealed trait OpComponent
  case class Retain(length: Int) extends OpComponent
  case class Insert(text: String) extends OpComponent
  case class Delete(text: String) extends OpComponent
  
  sealed trait EditorAction {
    val offset: Int
  }
  
  case class InsertAt(offset: Int, text: String) extends EditorAction
  case class DeleteAt(offset: Int, text: String) extends EditorAction
}
Something went wrong with that request. Please try again.