wide/editor/editors.go

350 lines
8.2 KiB
Go
Raw Normal View History

2014-09-12 13:10:58 +04:00
// 编辑器操作.
2014-08-18 17:45:43 +04:00
package editor
import (
"bytes"
"encoding/json"
"net/http"
"os"
"os/exec"
2014-09-04 19:09:51 +04:00
"runtime"
2014-08-18 17:45:43 +04:00
"strconv"
2014-09-01 16:50:51 +04:00
"strings"
2014-09-07 13:07:25 +04:00
"github.com/b3log/wide/conf"
"github.com/b3log/wide/user"
2014-09-11 20:22:24 +04:00
"github.com/b3log/wide/util"
2014-09-07 13:07:25 +04:00
"github.com/golang/glog"
"github.com/gorilla/websocket"
2014-08-18 17:45:43 +04:00
)
var editorWS = map[string]*websocket.Conn{}
2014-09-12 12:50:04 +04:00
// 代码片段. 这个结构可用于“查找使用”、“文件搜索”的返回值.
type snippet struct {
Path string `json:"path"` // 文件路径
Line int `json:"lline"` // 行号
Ch int `json:"ch"` // 列号
Contents []string `json:"contents"` // 代码行
}
2014-08-18 17:45:43 +04:00
func WSHandler(w http.ResponseWriter, r *http.Request) {
2014-08-31 13:39:39 +04:00
session, _ := user.Session.Get(r, "wide-session")
2014-08-18 17:45:43 +04:00
sid := session.Values["id"].(string)
editorWS[sid], _ = websocket.Upgrade(w, r, nil, 1024, 1024)
ret := map[string]interface{}{"output": "Editor initialized", "cmd": "init-editor"}
editorWS[sid].WriteJSON(&ret)
glog.Infof("Open a new [Editor] with session [%s], %d", sid, len(editorWS))
args := map[string]interface{}{}
for {
if err := editorWS[sid].ReadJSON(&args); err != nil {
if err.Error() == "EOF" {
return
}
if err.Error() == "unexpected EOF" {
return
}
glog.Error("Editor WS ERROR: " + err.Error())
return
}
code := args["code"].(string)
line := int(args["cursorLine"].(float64))
ch := int(args["cursorCh"].(float64))
2014-09-01 16:50:51 +04:00
offset := getCursorOffset(code, line, ch)
2014-08-18 17:45:43 +04:00
// glog.Infof("offset: %d", offset)
argv := []string{"-f=json", "autocomplete", strconv.Itoa(offset)}
var output bytes.Buffer
cmd := exec.Command("gocode", argv...)
cmd.Stdout = &output
stdin, _ := cmd.StdinPipe()
cmd.Start()
stdin.Write([]byte(code))
stdin.Close()
cmd.Wait()
ret = map[string]interface{}{"output": string(output.Bytes()), "cmd": "autocomplete"}
if err := editorWS[sid].WriteJSON(&ret); err != nil {
glog.Error("Editor WS ERROR: " + err.Error())
return
}
}
}
2014-09-13 09:10:24 +04:00
// 自动完成(代码补全).
2014-08-18 17:45:43 +04:00
func AutocompleteHandler(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var args map[string]interface{}
if err := decoder.Decode(&args); err != nil {
glog.Error(err)
http.Error(w, err.Error(), 500)
return
}
2014-09-03 10:53:42 +04:00
session, _ := user.Session.Get(r, "wide-session")
username := session.Values["username"].(string)
2014-09-02 20:26:10 +04:00
2014-08-18 17:45:43 +04:00
code := args["code"].(string)
line := int(args["cursorLine"].(float64))
ch := int(args["cursorCh"].(float64))
2014-09-01 16:50:51 +04:00
offset := getCursorOffset(code, line, ch)
2014-08-18 17:45:43 +04:00
// glog.Infof("offset: %d", offset)
2014-09-11 20:22:24 +04:00
userWorkspace := conf.Wide.GetUserWorkspace(username)
2014-09-05 07:07:29 +04:00
2014-09-04 19:09:51 +04:00
//glog.Infof("User [%s] workspace [%s]", username, userWorkspace)
userLib := userWorkspace + string(os.PathSeparator) + "pkg" + string(os.PathSeparator) +
runtime.GOOS + "_" + runtime.GOARCH
2014-09-13 12:50:18 +04:00
libPath := userLib
2014-09-04 19:09:51 +04:00
//glog.Infof("gocode set lib-path %s", libPath)
2014-09-04 19:13:11 +04:00
// FIXME: 使用 gocode set lib-path 在多工作空间环境下肯定是有问题的,需要考虑其他实现方式
2014-09-04 19:09:51 +04:00
argv := []string{"set", "lib-path", libPath}
2014-09-04 19:48:49 +04:00
cmd := exec.Command("gocode", argv...)
cmd.Start()
2014-08-18 17:45:43 +04:00
2014-09-11 20:22:24 +04:00
//gocode 试验性质特性:自动构建
2014-09-04 19:09:51 +04:00
//argv = []string{"set", "autobuild", "true"}
//cmd := exec.Command("gocode", argv...)
//cmd.Start()
2014-09-02 20:26:10 +04:00
2014-09-04 19:09:51 +04:00
argv = []string{"-f=json", "autocomplete", strconv.Itoa(offset)}
cmd = exec.Command("gocode", argv...)
2014-08-18 17:45:43 +04:00
stdin, _ := cmd.StdinPipe()
stdin.Write([]byte(code))
stdin.Close()
2014-09-03 10:53:42 +04:00
output, err := cmd.CombinedOutput()
if nil != err {
glog.Error(err)
http.Error(w, err.Error(), 500)
return
}
2014-08-18 17:45:43 +04:00
w.Header().Set("Content-Type", "application/json")
2014-09-03 10:53:42 +04:00
w.Write(output)
2014-08-18 17:45:43 +04:00
}
2014-09-01 16:50:51 +04:00
2014-09-12 13:10:58 +04:00
// 查找声明.
2014-09-11 20:22:24 +04:00
func FindDeclarationHandler(w http.ResponseWriter, r *http.Request) {
data := map[string]interface{}{"succ": true}
defer util.RetJSON(w, r, data)
session, _ := user.Session.Get(r, "wide-session")
username := session.Values["username"].(string)
decoder := json.NewDecoder(r.Body)
var args map[string]interface{}
if err := decoder.Decode(&args); err != nil {
glog.Error(err)
http.Error(w, err.Error(), 500)
return
}
2014-09-13 09:05:50 +04:00
path := args["path"].(string)
curDir := path[:strings.LastIndex(path, string(os.PathSeparator))]
filename := path[strings.LastIndex(path, string(os.PathSeparator))+1:]
2014-09-11 20:22:24 +04:00
2014-09-13 09:05:50 +04:00
fout, err := os.Create(path)
2014-09-11 20:22:24 +04:00
if nil != err {
glog.Error(err)
data["succ"] = false
return
}
code := args["code"].(string)
fout.WriteString(code)
if err := fout.Close(); nil != err {
glog.Error(err)
data["succ"] = false
return
}
line := int(args["cursorLine"].(float64))
ch := int(args["cursorCh"].(float64))
offset := getCursorOffset(code, line, ch)
2014-09-13 20:07:03 +04:00
// glog.Infof("offset [%d]", offset)
2014-09-11 20:22:24 +04:00
2014-09-12 06:10:21 +04:00
// TODO: 目前是调用 liteide_stub 工具来查找声明,后续需要重新实现
2014-09-11 20:22:24 +04:00
argv := []string{"type", "-cursor", filename + ":" + strconv.Itoa(offset), "-def", "."}
cmd := exec.Command("liteide_stub", argv...)
cmd.Dir = curDir
setCmdEnv(cmd, username)
output, err := cmd.CombinedOutput()
if nil != err {
glog.Error(err)
http.Error(w, err.Error(), 500)
return
}
2014-09-12 06:10:21 +04:00
found := strings.TrimSpace(string(output))
if "" == found {
data["succ"] = false
return
}
part := found[:strings.LastIndex(found, ":")]
cursorSep := strings.LastIndex(part, ":")
2014-09-13 09:05:50 +04:00
path = found[:cursorSep]
2014-09-12 06:10:21 +04:00
cursorLine := found[cursorSep+1 : strings.LastIndex(found, ":")]
cursorCh := found[strings.LastIndex(found, ":")+1:]
data["path"] = path
data["cursorLine"] = cursorLine
data["cursorCh"] = cursorCh
2014-09-11 20:22:24 +04:00
}
2014-09-12 13:10:58 +04:00
// 查找使用.
2014-09-12 11:55:52 +04:00
func FindUsagesHandler(w http.ResponseWriter, r *http.Request) {
data := map[string]interface{}{"succ": true}
defer util.RetJSON(w, r, data)
session, _ := user.Session.Get(r, "wide-session")
username := session.Values["username"].(string)
decoder := json.NewDecoder(r.Body)
var args map[string]interface{}
if err := decoder.Decode(&args); err != nil {
glog.Error(err)
http.Error(w, err.Error(), 500)
return
}
filePath := args["file"].(string)
curDir := filePath[:strings.LastIndex(filePath, string(os.PathSeparator))]
filename := filePath[strings.LastIndex(filePath, string(os.PathSeparator))+1:]
fout, err := os.Create(filePath)
if nil != err {
glog.Error(err)
data["succ"] = false
return
}
code := args["code"].(string)
fout.WriteString(code)
if err := fout.Close(); nil != err {
glog.Error(err)
data["succ"] = false
return
}
line := int(args["cursorLine"].(float64))
ch := int(args["cursorCh"].(float64))
offset := getCursorOffset(code, line, ch)
// TODO: 目前是调用 liteide_stub 工具来查找使用,后续需要重新实现
argv := []string{"type", "-cursor", filename + ":" + strconv.Itoa(offset), "-use", "."}
cmd := exec.Command("liteide_stub", argv...)
cmd.Dir = curDir
setCmdEnv(cmd, username)
output, err := cmd.CombinedOutput()
if nil != err {
glog.Error(err)
http.Error(w, err.Error(), 500)
return
}
result := strings.TrimSpace(string(output))
if "" == result {
data["succ"] = false
return
}
founds := strings.Split(result, "\n")
2014-09-12 12:50:04 +04:00
usages := []snippet{}
2014-09-12 11:55:52 +04:00
for _, found := range founds {
found = strings.TrimSpace(found)
part := found[:strings.LastIndex(found, ":")]
cursorSep := strings.LastIndex(part, ":")
path := found[:cursorSep]
2014-09-12 12:50:04 +04:00
cursorLine, _ := strconv.Atoi(found[cursorSep+1 : strings.LastIndex(found, ":")])
cursorCh, _ := strconv.Atoi(found[strings.LastIndex(found, ":")+1:])
2014-09-12 11:55:52 +04:00
2014-09-12 12:50:04 +04:00
usage := snippet{Path: path, Line: cursorLine, Ch: cursorCh /* TODO: 获取附近的代码片段 */}
2014-09-12 11:55:52 +04:00
usages = append(usages, usage)
}
data["usages"] = usages
}
2014-09-13 09:05:50 +04:00
// 计算光标偏移位置.
// line 指定了行号(第一行为 0ch 指定了列号(第一列为 0.
2014-09-01 16:50:51 +04:00
func getCursorOffset(code string, line, ch int) (offset int) {
lines := strings.Split(code, "\n")
2014-09-13 09:05:50 +04:00
// 计算前几行长度
2014-09-01 16:50:51 +04:00
for i := 0; i < line; i++ {
offset += len(lines[i])
}
2014-09-13 09:05:50 +04:00
// 计算当前行、当前列长度
curLine := lines[line]
var buffer bytes.Buffer
r := []rune(curLine)
for i := 0; i < ch; i++ {
buffer.WriteString(string(r[i]))
}
offset += line // 加换行符
offset += len(buffer.String()) // 加当前行列偏移
2014-09-01 16:50:51 +04:00
2014-09-13 09:05:50 +04:00
return offset
2014-09-01 16:50:51 +04:00
}
2014-09-11 20:22:24 +04:00
func setCmdEnv(cmd *exec.Cmd, username string) {
userWorkspace := conf.Wide.GetUserWorkspace(username)
cmd.Env = append(cmd.Env,
"GOPATH="+userWorkspace,
"GOOS="+runtime.GOOS,
"GOARCH="+runtime.GOARCH,
"GOROOT="+runtime.GOROOT(),
"PATH="+os.Getenv("PATH"))
}