wide/editor/editors.go

466 lines
11 KiB
Go
Raw Normal View History

2015-12-30 11:13:43 +03:00
// Copyright (c) 2014-2016, b3log.org & hacpai.com
2014-11-20 06:30:18 +03:00
//
2014-11-12 18:13:14 +03:00
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
2014-11-20 06:30:18 +03:00
//
2014-11-12 18:13:14 +03:00
// http://www.apache.org/licenses/LICENSE-2.0
2014-11-20 06:30:18 +03:00
//
2014-11-12 18:13:14 +03:00
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2014-12-07 06:14:10 +03:00
// Package editor includes editor related 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-12-13 13:47:41 +03:00
"github.com/b3log/wide/log"
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/gorilla/websocket"
2014-08-18 17:45:43 +04:00
)
2014-12-13 13:47:41 +03:00
// Logger.
var logger = log.NewLogger(os.Stdout)
2014-10-29 13:15:18 +03:00
// WSHandler handles request of creating editor channel.
2014-12-11 10:32:24 +03:00
// XXX: NOT used at present
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")
2014-11-26 08:49:27 +03:00
if httpSession.IsNew {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
2014-10-29 13:15:18 +03:00
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
ret := map[string]interface{}{"output": "Editor initialized", "cmd": "init-editor"}
2014-11-20 08:59:08 +03:00
err := editorChan.WriteJSON(&ret)
2014-11-20 06:30:18 +03:00
if nil != err {
return
}
session.EditorWS[sid] = &editorChan
2014-08-18 17:45:43 +04:00
2014-12-14 18:05:54 +03:00
logger.Tracef("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-11-20 09:11:54 +03:00
if err := session.EditorWS[sid].ReadJSON(&args); err != nil {
2014-08-18 17:45:43 +04:00
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
2015-01-11 07:12:06 +03:00
logger.Tracef("offset: %d", offset)
2014-08-18 17:45:43 +04:00
2014-11-26 06:54:01 +03:00
gocode := util.Go.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-11-20 08:59:08 +03:00
if err := session.EditorWS[sid].WriteJSON(&ret); err != nil {
2014-12-13 13:47:41 +03:00
logger.Error("Editor WS ERROR: " + err.Error())
2014-08-18 17:45:43 +04:00
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-12-13 13:47:41 +03:00
logger.Error(err)
2014-08-18 17:45:43 +04:00
http.Error(w, err.Error(), 500)
return
}
2014-09-17 10:35:48 +04:00
session, _ := session.HTTPSession.Get(r, "wide-session")
2014-11-26 08:49:27 +03:00
if session.IsNew {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
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 {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2014-09-16 18:39:22 +04:00
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 {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2014-09-16 18:39:22 +04:00
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
2015-01-11 07:12:06 +03:00
logger.Tracef("offset: %d", offset)
2014-08-18 17:45:43 +04:00
userWorkspace := conf.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-12-18 10:54:58 +03:00
logger.Tracef("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-11-26 06:54:01 +03:00
gocode := util.Go.GetExecutableInGOBIN("gocode")
2015-03-10 06:49:38 +03:00
exec.Command(gocode, []string{"set", "lib-path", libPath}...).Run()
2014-09-02 20:26:10 +04:00
2015-03-10 06:49:38 +03:00
argv := []string{"-f=json", "--in=" + path, "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
2014-09-03 10:53:42 +04:00
output, err := cmd.CombinedOutput()
if nil != err {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2014-09-03 10:53:42 +04:00
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) {
2015-11-24 10:42:28 +03:00
result := util.NewResult()
defer util.RetResult(w, r, result)
2014-10-10 07:18:52 +04:00
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-12-13 13:47:41 +03:00
logger.Error(err)
2014-10-10 07:18:52 +04:00
http.Error(w, err.Error(), 500)
return
}
path := args["path"].(string)
2015-08-05 06:09:52 +03:00
curDir := filepath.Dir(path)
filename := filepath.Base(path)
2014-10-10 07:18:52 +04:00
fout, err := os.Create(path)
if nil != err {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2015-11-24 10:42:28 +03:00
result.Succ = false
2014-10-10 07:18:52 +04:00
return
}
code := args["code"].(string)
fout.WriteString(code)
if err := fout.Close(); nil != err {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2015-11-24 10:42:28 +03:00
result.Succ = false
2014-10-10 07:18:52 +04:00
return
}
line := int(args["cursorLine"].(float64))
ch := int(args["cursorCh"].(float64))
offset := getCursorOffset(code, line, ch)
2014-10-12 18:58:08 +04:00
2015-01-11 07:12:06 +03:00
logger.Tracef("offset [%d]", offset)
2014-10-10 07:18:52 +04:00
2015-08-05 07:58:39 +03:00
ideStub := util.Go.GetExecutableInGOBIN("gotools")
2015-08-05 06:09:52 +03:00
argv := []string{"types", "-pos", filename + ":" + strconv.Itoa(offset), "-info", "."}
2014-12-07 06:14:10 +03:00
cmd := exec.Command(ideStub, argv...)
2014-10-10 07:18:52 +04:00
cmd.Dir = curDir
setCmdEnv(cmd, username)
output, err := cmd.CombinedOutput()
if nil != err {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2014-10-10 07:18:52 +04:00
http.Error(w, err.Error(), 500)
return
}
exprInfo := strings.TrimSpace(string(output))
if "" == exprInfo {
2015-11-24 10:42:28 +03:00
result.Succ = false
2014-10-10 07:18:52 +04:00
return
}
2015-11-24 10:42:28 +03:00
result.Data = exprInfo
2014-10-10 07:18:52 +04:00
}
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) {
2015-11-24 10:42:28 +03:00
result := util.NewResult()
defer util.RetResult(w, r, result)
2014-09-11 20:22:24 +04:00
2014-09-17 10:35:48 +04:00
session, _ := session.HTTPSession.Get(r, "wide-session")
2014-11-26 08:49:27 +03:00
if session.IsNew {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
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-12-13 13:47:41 +03:00
logger.Error(err)
2014-09-11 20:22:24 +04:00
http.Error(w, err.Error(), 500)
return
}
2014-09-13 09:05:50 +04:00
path := args["path"].(string)
2015-08-05 06:09:52 +03:00
curDir := filepath.Dir(path)
filename := filepath.Base(path)
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 {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2015-11-24 10:42:28 +03:00
result.Succ = false
2014-09-11 20:22:24 +04:00
return
}
code := args["code"].(string)
fout.WriteString(code)
if err := fout.Close(); nil != err {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2015-11-24 10:42:28 +03:00
result.Succ = false
2014-09-11 20:22:24 +04:00
return
}
line := int(args["cursorLine"].(float64))
ch := int(args["cursorCh"].(float64))
offset := getCursorOffset(code, line, ch)
2014-10-13 08:22:50 +04:00
2015-01-11 07:12:06 +03:00
logger.Tracef("offset [%d]", offset)
2014-09-11 20:22:24 +04:00
2015-08-05 07:58:39 +03:00
ideStub := util.Go.GetExecutableInGOBIN("gotools")
2015-08-05 06:09:52 +03:00
argv := []string{"types", "-pos", filename + ":" + strconv.Itoa(offset), "-def", "."}
2014-12-07 06:14:10 +03:00
cmd := exec.Command(ideStub, argv...)
2014-09-11 20:22:24 +04:00
cmd.Dir = curDir
setCmdEnv(cmd, username)
output, err := cmd.CombinedOutput()
if nil != err {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2014-09-11 20:22:24 +04:00
http.Error(w, err.Error(), 500)
return
}
2014-09-12 06:10:21 +04:00
found := strings.TrimSpace(string(output))
if "" == found {
2015-11-24 10:42:28 +03:00
result.Succ = false
2014-09-12 06:10:21 +04:00
return
}
part := found[:strings.LastIndex(found, ":")]
cursorSep := strings.LastIndex(part, ":")
2014-09-13 09:05:50 +04:00
path = found[:cursorSep]
2015-08-05 06:09:52 +03:00
2014-11-04 19:27:43 +03:00
cursorLine, _ := strconv.Atoi(found[cursorSep+1 : strings.LastIndex(found, ":")])
cursorCh, _ := strconv.Atoi(found[strings.LastIndex(found, ":")+1:])
2014-09-12 06:10:21 +04:00
2015-11-24 10:42:28 +03:00
data := map[string]interface{}{}
2015-11-27 11:55:28 +03:00
result.Data = &data
2015-11-24 10:42:28 +03:00
2015-08-05 06:09:52 +03:00
data["path"] = filepath.ToSlash(path)
2014-09-12 06:10:21 +04:00
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) {
2015-11-24 10:42:28 +03:00
result := util.NewResult()
defer util.RetResult(w, r, result)
2014-09-12 11:55:52 +04:00
2014-09-17 10:35:48 +04:00
session, _ := session.HTTPSession.Get(r, "wide-session")
2014-11-26 08:49:27 +03:00
if session.IsNew {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
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-12-13 13:47:41 +03:00
logger.Error(err)
2014-09-12 11:55:52 +04:00
http.Error(w, err.Error(), 500)
return
}
2014-10-10 07:18:52 +04:00
filePath := args["path"].(string)
2015-08-05 06:09:52 +03:00
curDir := filepath.Dir(filePath)
filename := filepath.Base(filePath)
2014-09-12 11:55:52 +04:00
fout, err := os.Create(filePath)
if nil != err {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2015-11-24 10:42:28 +03:00
result.Succ = false
2014-09-12 11:55:52 +04:00
return
}
code := args["code"].(string)
fout.WriteString(code)
if err := fout.Close(); nil != err {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2015-11-24 10:42:28 +03:00
result.Succ = false
2014-09-12 11:55:52 +04:00
return
}
line := int(args["cursorLine"].(float64))
ch := int(args["cursorCh"].(float64))
offset := getCursorOffset(code, line, ch)
2015-01-11 07:12:06 +03:00
logger.Tracef("offset [%d]", offset)
2014-09-12 11:55:52 +04:00
2015-08-05 07:58:39 +03:00
ideStub := util.Go.GetExecutableInGOBIN("gotools")
2015-08-05 06:09:52 +03:00
argv := []string{"types", "-pos", filename + ":" + strconv.Itoa(offset), "-use", "."}
2014-12-07 06:14:10 +03:00
cmd := exec.Command(ideStub, argv...)
2014-09-12 11:55:52 +04:00
cmd.Dir = curDir
setCmdEnv(cmd, username)
output, err := cmd.CombinedOutput()
if nil != err {
2014-12-13 13:47:41 +03:00
logger.Error(err)
2014-09-12 11:55:52 +04:00
http.Error(w, err.Error(), 500)
return
}
2015-11-24 10:42:28 +03:00
out := strings.TrimSpace(string(output))
if "" == out {
result.Succ = false
2014-09-12 11:55:52 +04:00
return
}
2015-11-24 10:42:28 +03:00
founds := strings.Split(out, "\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, ":")
2015-08-05 06:09:52 +03:00
path := filepath.ToSlash(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)
}
2015-11-24 10:42:28 +03:00
result.Data = 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.GetUserWorkspace(username)
2014-09-11 20:22:24 +04:00
cmd.Env = append(cmd.Env,
"GOPATH="+userWorkspace,
"GOOS="+runtime.GOOS,
"GOARCH="+runtime.GOARCH,
"GOROOT="+runtime.GOROOT(),
"PATH="+os.Getenv("PATH"))
}