wide/editor/editors.go

434 lines
10 KiB
Go
Raw Normal View History

2014-10-29 13:15:18 +03:00
// Editor manipulations.
2014-08-18 17:45:43 +04:00
package editor
import (
"bytes"
"encoding/json"
"net/http"
"os"
"os/exec"
2014-10-28 08:22:39 +03:00
"path/filepath"
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-10-29 13:15:18 +03:00
"time"
2014-09-07 13:07:25 +04:00
"github.com/b3log/wide/conf"
2014-10-11 10:08:29 +04:00
"github.com/b3log/wide/file"
2014-09-17 10:35:48 +04:00
"github.com/b3log/wide/session"
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
)
2014-10-29 13:15:18 +03:00
// WSHandler handles request of creating editor channel.
2014-08-18 17:45:43 +04:00
func WSHandler(w http.ResponseWriter, r *http.Request) {
2014-10-29 13:15:18 +03:00
httpSession, _ := session.HTTPSession.Get(r, "wide-session")
sid := httpSession.Values["id"].(string)
conn, _ := websocket.Upgrade(w, r, nil, 1024, 1024)
editorChan := util.WSChannel{Sid: sid, Conn: conn, Request: r, Time: time.Now()}
2014-08-18 17:45:43 +04:00
2014-10-29 13:15:18 +03:00
session.EditorWS[sid] = &editorChan
2014-08-18 17:45:43 +04:00
ret := map[string]interface{}{"output": "Editor initialized", "cmd": "init-editor"}
2014-10-29 13:15:18 +03:00
editorChan.Conn.WriteJSON(&ret)
2014-08-18 17:45:43 +04:00
2014-10-29 13:15:18 +03:00
glog.Infof("Open a new [Editor] with session [%s], %d", sid, len(session.EditorWS))
2014-08-18 17:45:43 +04:00
args := map[string]interface{}{}
for {
2014-10-29 13:15:18 +03:00
if err := session.EditorWS[sid].Conn.ReadJSON(&args); err != nil {
2014-08-18 17:45:43 +04:00
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)
2014-10-26 10:41:34 +03:00
gocode := conf.Wide.GetExecutableInGOBIN("gocode")
2014-08-18 17:45:43 +04:00
argv := []string{"-f=json", "autocomplete", strconv.Itoa(offset)}
var output bytes.Buffer
2014-09-15 05:52:36 +04:00
cmd := exec.Command(gocode, argv...)
2014-08-18 17:45:43 +04:00
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"}
2014-10-29 13:15:18 +03:00
if err := session.EditorWS[sid].Conn.WriteJSON(&ret); err != nil {
2014-08-18 17:45:43 +04:00
glog.Error("Editor WS ERROR: " + err.Error())
return
}
}
}
2014-10-29 13:15:18 +03:00
// AutocompleteHandler handles request of code autocompletion.
2014-08-18 17:45:43 +04:00
func AutocompleteHandler(w http.ResponseWriter, r *http.Request) {
var args map[string]interface{}
2014-10-28 16:32:19 +03:00
if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
2014-08-18 17:45:43 +04:00
glog.Error(err)
http.Error(w, err.Error(), 500)
return
}
2014-09-17 10:35:48 +04:00
session, _ := session.HTTPSession.Get(r, "wide-session")
2014-09-03 10:53:42 +04:00
username := session.Values["username"].(string)
2014-09-02 20:26:10 +04:00
2014-09-16 18:39:22 +04:00
path := args["path"].(string)
fout, err := os.Create(path)
if nil != err {
glog.Error(err)
http.Error(w, err.Error(), 500)
return
}
2014-08-18 17:45:43 +04:00
code := args["code"].(string)
2014-09-16 18:39:22 +04:00
fout.WriteString(code)
if err := fout.Close(); nil != err {
glog.Error(err)
http.Error(w, err.Error(), 500)
return
}
2014-09-15 06:08:49 +04:00
2014-08-18 17:45:43 +04:00
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-10-28 08:22:39 +03:00
workspaces := filepath.SplitList(userWorkspace)
2014-10-26 09:46:15 +03:00
libPath := ""
for _, workspace := range workspaces {
userLib := workspace + conf.PathSeparator + "pkg" + conf.PathSeparator +
runtime.GOOS + "_" + runtime.GOARCH
libPath += userLib + conf.PathListSeparator
}
2014-09-05 07:07:29 +04:00
2014-10-26 09:46:15 +03:00
glog.V(5).Infof("gocode set lib-path %s", libPath)
2014-09-04 19:09:51 +04:00
2014-10-29 13:15:18 +03:00
// FIXME: using gocode set lib-path has some issues while accrossing workspaces
2014-10-26 10:41:34 +03:00
gocode := conf.Wide.GetExecutableInGOBIN("gocode")
2014-09-04 19:09:51 +04:00
argv := []string{"set", "lib-path", libPath}
2014-09-17 12:13:00 +04:00
exec.Command(gocode, argv...).Run()
2014-09-02 20:26:10 +04:00
2014-09-04 19:09:51 +04:00
argv = []string{"-f=json", "autocomplete", strconv.Itoa(offset)}
2014-09-17 12:13:00 +04:00
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-10-29 13:15:18 +03:00
// GetExprInfoHandler handles request of getting expression infomation.
2014-10-10 07:18:52 +04:00
func GetExprInfoHandler(w http.ResponseWriter, r *http.Request) {
data := map[string]interface{}{"succ": true}
defer util.RetJSON(w, r, data)
session, _ := session.HTTPSession.Get(r, "wide-session")
username := session.Values["username"].(string)
var args map[string]interface{}
2014-10-28 16:32:19 +03:00
if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
2014-10-10 07:18:52 +04:00
glog.Error(err)
http.Error(w, err.Error(), 500)
return
}
path := args["path"].(string)
2014-10-13 10:34:42 +04:00
curDir := path[:strings.LastIndex(path, conf.PathSeparator)]
filename := path[strings.LastIndex(path, conf.PathSeparator)+1:]
2014-10-10 07:18:52 +04:00
fout, err := os.Create(path)
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-10-12 18:58:08 +04:00
// glog.Infof("offset [%d]", offset)
2014-10-10 07:18:52 +04:00
2014-10-26 10:41:34 +03:00
ide_stub := conf.Wide.GetExecutableInGOBIN("ide_stub")
2014-10-10 07:18:52 +04:00
argv := []string{"type", "-cursor", filename + ":" + strconv.Itoa(offset), "-info", "."}
cmd := exec.Command(ide_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
}
exprInfo := strings.TrimSpace(string(output))
if "" == exprInfo {
data["succ"] = false
return
}
data["info"] = exprInfo
}
2014-10-29 13:15:18 +03:00
// FindDeclarationHandler handles request of finding declaration.
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)
2014-09-17 10:35:48 +04:00
session, _ := session.HTTPSession.Get(r, "wide-session")
2014-09-11 20:22:24 +04:00
username := session.Values["username"].(string)
var args map[string]interface{}
2014-10-28 16:32:19 +03:00
if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
2014-09-11 20:22:24 +04:00
glog.Error(err)
http.Error(w, err.Error(), 500)
return
}
2014-09-13 09:05:50 +04:00
path := args["path"].(string)
2014-10-13 10:34:42 +04:00
curDir := path[:strings.LastIndex(path, conf.PathSeparator)]
filename := path[strings.LastIndex(path, conf.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-10-13 08:22:50 +04:00
// glog.Infof("offset [%d]", offset)
2014-09-11 20:22:24 +04:00
2014-10-26 10:41:34 +03:00
ide_stub := conf.Wide.GetExecutableInGOBIN("ide_stub")
2014-09-11 20:22:24 +04:00
argv := []string{"type", "-cursor", filename + ":" + strconv.Itoa(offset), "-def", "."}
2014-09-15 05:52:36 +04:00
cmd := exec.Command(ide_stub, argv...)
2014-09-11 20:22:24 +04:00
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-10-29 13:15:18 +03:00
// FindUsagesHandler handles request of finding usages.
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)
2014-09-17 10:35:48 +04:00
session, _ := session.HTTPSession.Get(r, "wide-session")
2014-09-12 11:55:52 +04:00
username := session.Values["username"].(string)
var args map[string]interface{}
2014-10-28 16:32:19 +03:00
if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
2014-09-12 11:55:52 +04:00
glog.Error(err)
http.Error(w, err.Error(), 500)
return
}
2014-10-10 07:18:52 +04:00
filePath := args["path"].(string)
2014-10-13 10:34:42 +04:00
curDir := filePath[:strings.LastIndex(filePath, conf.PathSeparator)]
filename := filePath[strings.LastIndex(filePath, conf.PathSeparator)+1:]
2014-09-12 11:55:52 +04:00
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)
2014-10-12 18:00:26 +04:00
// glog.Infof("offset [%d]", offset)
2014-09-12 11:55:52 +04:00
2014-10-26 10:41:34 +03:00
ide_stub := conf.Wide.GetExecutableInGOBIN("ide_stub")
2014-09-15 05:52:36 +04:00
argv := []string{"type", "-cursor", filename + ":" + strconv.Itoa(offset), "-use", "."}
2014-09-15 05:22:49 +04:00
cmd := exec.Command(ide_stub, argv...)
2014-09-12 11:55:52 +04:00
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-10-11 10:08:29 +04:00
usages := []*file.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-10-12 18:00:26 +04:00
usage := &file.Snippet{Path: path, Line: cursorLine, Ch: cursorCh, Contents: []string{""}}
2014-09-12 11:55:52 +04:00
usages = append(usages, usage)
}
2014-10-12 18:00:26 +04:00
data["founds"] = usages
2014-09-12 11:55:52 +04:00
}
2014-10-29 13:15:18 +03:00
// getCursorOffset calculates the cursor offset.
2014-09-25 09:37:59 +04:00
//
2014-10-29 13:15:18 +03:00
// line is the line number, starts with 0 that means the first line
// ch is the column number, starts with 0 that means the first column
2014-09-01 16:50:51 +04:00
func getCursorOffset(code string, line, ch int) (offset int) {
lines := strings.Split(code, "\n")
2014-10-29 13:15:18 +03:00
// calculate sum length of lines before
2014-09-01 16:50:51 +04:00
for i := 0; i < line; i++ {
offset += len(lines[i])
}
2014-10-29 13:15:18 +03:00
// calculate length of the current line and column
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]))
}
2014-10-29 13:15:18 +03:00
offset += len(buffer.String()) // append length of current line
offset += line // append number of '\n'
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"))
}