ready to code-like

This commit is contained in:
Cai
2025-09-21 14:03:40 +08:00
parent b1f832a2fb
commit 588fc3b697
14 changed files with 562 additions and 20 deletions

View File

@@ -5,7 +5,6 @@ bootstrap_paths()
from apps import create_app from apps import create_app
from apps.extensions import socketio from apps.extensions import socketio
# 工厂创建 app工厂里已经做了加载配置/注册蓝图/注册 namespaces
app = create_app() app = create_app()
if __name__ == "__main__": if __name__ == "__main__":

View File

@@ -13,6 +13,7 @@ class Config:
SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.getenv("SECRET_KEY", "cakebaker") # 覆盖优先 SECRET_KEY = os.getenv("SECRET_KEY", "cakebaker") # 覆盖优先
VSCODE_WEB_URL = GLOBAL_CONFIG['VSCODE_WEB']['url'] VSCODE_WEB_URL = GLOBAL_CONFIG['VSCODE_WEB']['url']
CODE_LIKE_URL = GLOBAL_CONFIG['CODE_LIKE']['url']
USER_DATA_DIR = GLOBAL_CONFIG['USER_DATA']['dir'] USER_DATA_DIR = GLOBAL_CONFIG['USER_DATA']['dir']
COURSE_DATA_DIR = GLOBAL_CONFIG['COURSE_DATA']['dir'] COURSE_DATA_DIR = GLOBAL_CONFIG['COURSE_DATA']['dir']

View File

@@ -158,6 +158,12 @@ class ChatManager:
path_dir, path_dir,
"--extensions-dir", "/share/extension/" "--extensions-dir", "/share/extension/"
] ]
try:# 创建.config,.local文件夹
subprocess.run(["sudo", "mkdir", "-p", f"/home/{user_id}/.config"], check=True)
subprocess.run(["sudo", "mkdir", "-p", f"/home/{user_id}/.local"], check=True)
subprocess.run(["sudo", "chown", "-R", f"{user_id}:shared_group_{user_id}", f"/home/{user_id}/.config", f"/home/{user_id}/.local"], check=True)
except Exception as e:
print("mkdir .config .local error"+str(e))
pop = subprocess.Popen( pop = subprocess.Popen(
cmd, cmd,

View File

@@ -4,7 +4,7 @@ let system_message_idx=0
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function() {
data = window.appData; data = window.appData;
console.log(data); console.log(data);
socket = io('wss://hsamooc.cn/agent',{ socket = io('wss://hsamooc.com/agent',{
query:{ query:{
user_uuid:data.user_uuid, user_uuid:data.user_uuid,
folder:data.folder folder:data.folder
@@ -13,6 +13,7 @@ document.addEventListener('DOMContentLoaded', function() {
socket.on('connect', function() { socket.on('connect', function() {
console.log('Connected to server'); console.log('Connected to server');
socket.emit('login',JSON.stringify(data)); socket.emit('login',JSON.stringify(data));
OpenIframe();
}); });
// 监听来自服务器的消息 // 监听来自服务器的消息
socket.on('message', function(data) { socket.on('message', function(data) {

View File

@@ -10,11 +10,8 @@
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.2.0/github-markdown.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.2.0/github-markdown.min.css">
</head> </head>
<body class="markdown-body"> <body class="markdown-body">
<h1>二分</h1> <h1>二分查找与二分答案</h1>
<blockquote> <h2>二分查找</h2>
<p>Auto-generated at 2025-09-05 19:48</p>
</blockquote>
<h2>阶段一:示例阶段</h2>
<h3>引入</h3> <h3>引入</h3>
<p>二分是一个很简单基础,但很重要的知识点,为以后许多高级的数据结构与算法铺垫。</p> <p>二分是一个很简单基础,但很重要的知识点,为以后许多高级的数据结构与算法铺垫。</p>
<p>下面是一个用二分的简单场景:</p> <p>下面是一个用二分的简单场景:</p>
@@ -47,7 +44,7 @@
<p>第三行一个整数q表示询问的次数。(1&lt;=q&lt;=10^4)</p> <p>第三行一个整数q表示询问的次数。(1&lt;=q&lt;=10^4)</p>
<p>后q行每行一个整数b表示询问的数。(0&lt;=b&lt;=10^8)</p> <p>后q行每行一个整数b表示询问的数。(0&lt;=b&lt;=10^8)</p>
<h5>输出</h5> <h5>输出</h5>
<p>q行每行一个整数对应每次询问的返回结果</p> <p>q行每行一个整数对应每次询问的返回结果</p>
<h5>提示:</h5> <h5>提示:</h5>
<p>完成代码后通知Agent进行评测。</p> <p>完成代码后通知Agent进行评测。</p>
<p>如果你还不完全会这个算法询问Agent获取提示并进行学习。</p> <p>如果你还不完全会这个算法询问Agent获取提示并进行学习。</p>

View File

@@ -0,0 +1,234 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Code Development Platform</title>
<style>
</style>
<link rel="stylesheet" href="/static/css/desktop.css">
<link rel="stylesheet" href="/static/css/chatbox_approve_icon.css">
<script>
document.cookie = "vscode-tkn=44edc269-6f88-46ab-9790-dc253f66ac36; path=/; SameSite=None; Secure";
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/1.1.1/marked.min.js"></script>
<script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://unpkg.com/split.js/dist/split.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
<div class="maxcontainer" id="maxcontainer" style="height: 100%;">
<!-- 左侧内容 -->
<div class="sidebar" id="leftSidebar" style="width: 100%;height: 100%;">
<div id="markdown-content"style="width: 100%;height: 93%;">
<!-- 动态加载的 HTML 会显示在这里 -->
</div>
<div id="markdown-content-process"style="width: 100%;height: 5%;">
</div>
<div id="progress-detail" style="position: absolute; top: 0; left: 0; display: none; padding: 10px; background-color: rgba(0, 0, 0, 0.7); color: white; border-radius: 5px;">
<!-- 这里将显示鼠标悬停的详情 -->
</div>
</div>
<div id="dragbar" class="resizer"></div>
<!-- 中间嵌入的 Vscode-web 窗口,带有 tkn 参数 -->
<div class="vscode-web"id="vscodeWeb" >
</div>
<div id="dragbar2" class="resizer"></div>
<!-- 右侧内容 -->
<div class="sidebar" id="rightSidebar"style="width: 100%;height: 100%;">
<div class="chatbox-header">
<div class="slider-container">
<label for="fontSizeSlider">Aa</label>
<input type="range" id="fontSizeSlider" min="12" max="24" value="16" />
</div>
<div class="language-toggle btn-group btn-group-toggle" data-toggle="buttons">
<label class="btn btn-outline-secondary " id="label_for_en">
<input type="radio" name="language" id="english" autocomplete="off" > En
</label>
<label class="btn btn-outline-secondary active" id="label_for_zh">
<input type="radio" name="language" id="chinese" autocomplete="off" checked> Zn
</label>
</div>
</div>
<div class="chatbox" id="chatbox" >
<!-- 消息会在这里显示 -->
</div>
<div class="input-area">
<textarea id="messageInput" rows="2" class="form-control" placeholder="输入你的消息 (支持 Markdown 语法)"></textarea>
<button class="btn btn-primary" onclick="sendMessage()">发送</button>
</div>
<script type="text/javascript">
window.appData = {
user_uuid:"{{user_uuid}}",
course_id:"{{course_id}}",
lesson_name:"{{lesson_name}}",
chapter_name:"{{chapter_name}}",
folder:"{{workspace_path}}"
}
</script>
</div>
</div>
<!-- 侧边工具栏 -->
<div class="sidebar-tools" id="sidebarTools">
<div class="tool-button" onclick="sendInitiativeFunctionCall('sample_judge')">
<div class="icon">+</div>
<div class="description">代码试运行</div>
</div>
<div class="tool-button" onclick="sendInitiativeFunctionCall('judge')">
<div class="icon"></div>
<div class="description">代码提交</div>
</div>
<!-- <div class="tool-button">
<div class="icon">-</div>
<div class="description">工具2</div>
</div>
<div class="tool-button">
<div class="icon">?</div>
<div class="description">工具3</div>
</div> -->
</div>
<!-- 切换按钮 -->
<div class="toggle-button" id="toggleButton">
<div class="icon" id="toggleButton_icon"></div>
</div>
<script src="/static/js/chatbox.js"></script>
<script>
// 实现左右边栏可拖动
const dragbar = document.getElementById('dragbar');
const dragbar2 = document.getElementById('dragbar2');
const container = document.getElementById('maxcontainer');
let leftWidth = 300; // 设置左侧栏的初始宽度
let rightWidth = 300; // 设置右侧栏的初始宽度
let isDraggingLeft = false;
let isDraggingRight = false;
// 当鼠标按下时,禁用 iframe 的鼠标事件
dragbar.addEventListener('mousedown', function(e) {
isDraggingLeft = true;
document.querySelectorAll('iframe').forEach(function(iframe) {
iframe.style.pointerEvents = 'none'; // 禁止 iframe 捕获鼠标事件
});
});
dragbar2.addEventListener('mousedown', function(e) {
isDraggingRight = true;
document.querySelectorAll('iframe').forEach(function(iframe) {
iframe.style.pointerEvents = 'none'; // 禁止 iframe 捕获鼠标事件
});
});
document.addEventListener('mousemove', function(e) {
if (isDraggingLeft) {
leftWidth = e.clientX; // 更新左侧栏宽度
container.style.gridTemplateColumns = `${leftWidth}px 5px 1fr 5px ${rightWidth}px`;
} else if (isDraggingRight) {
rightWidth = window.innerWidth - e.clientX; // 更新右侧栏宽度
container.style.gridTemplateColumns = `${leftWidth}px 5px 1fr 5px ${rightWidth}px`;
}
});
document.addEventListener('mouseup', function() {
isDraggingLeft = false;
isDraggingRight = false;
document.querySelectorAll('iframe').forEach(function(iframe) {
iframe.style.pointerEvents = 'auto'; // 恢复 iframe 的鼠标事件
});
});
// 使用 fetch 发送请求到 Flask 服务器,获取 session 信息
fetch('/get_session', {
method: 'GET',
credentials: 'include' // 包含 Cookie确保 Flask 可以识别 session
})
.then(response => {
if (response.ok) return response.json();
throw new Error('Failed to fetch session');
})
.then(data => {
console.log('Session data:', data);
})
.catch(error => {
console.error('Error fetching session:', error);
});
function OpenIframe(){
// 等待1s再加载
setTimeout(() => {
// 在成功获取 session 后创建并插入 iframe
const iframe = document.createElement('iframe');
const sessionInfo = data
iframe.src = '{{vscode_web_url}}/{{user_uuid}}/{{user_id}}/{{course_id}}/{{chapter_name}}/{{lesson_name}}/22';
iframe.style.width = '100%';
iframe.style.height = '99%';
// 将 iframe 插入到指定的 div 中
document.getElementById('vscodeWeb').appendChild(iframe);
},1500);
}
// 动态加载 Markdown 文件
function loadMarkdown(course_id, chapter_name, lesson_name) {
fetch(`/${course_id}-${chapter_name}-${lesson_name}-markdown`)
.then(response => response.json())
.then(data => {
if (data.html_url) {
document.getElementById('markdown-content').innerHTML = `<iframe id="markdown-content-iframe" src="${data.html_url}"style="width: 100%;height: 100%;"></iframe>`;
document.getElementById('markdown-content-iframe').addEventListener('load', function() {
// 在这里执行你想要的操作
console.log('Iframe has finished loading');
next_chapter();
});
} else {
console.error('Markdown file not found');
}
})
.catch(error => {
console.error('Error loading markdown:', error);
});
}
document.addEventListener('DOMContentLoaded', function() {
loadMarkdown('{{course_id}}','{{chapter_name}}','{{lesson_name}}');
});
// 侧边工具栏切换
const sidebarTools = document.getElementById('sidebarTools');
const toggleButton = document.getElementById('toggleButton');
toggleButton.addEventListener('click', function() {
sidebarTools.classList.toggle('open');
toggleButton.classList.toggle('open');
if (document.getElementById('toggleButton_icon').innerText === ''){
document.getElementById('toggleButton_icon').innerText = '';
}else{
document.getElementById('toggleButton_icon').innerText = '';
}
});
</script>
</body>
</html>

View File

@@ -5,10 +5,12 @@ from flask import Blueprint, current_app, session, redirect, url_for, render_tem
from ..services.backboard_service import realtime_response from ..services.backboard_service import realtime_response
from ..extension_ase.ase_client.manager import ChatManager from ..extension_ase.ase_client.manager import ChatManager
import subprocess import subprocess
from ..auth.decorators import require_role
bp = Blueprint("vscode", __name__) bp = Blueprint("vscode", __name__)
@bp.route("/desktop/<user_uuid>/<course_id>/<chapter_name>/<lesson_name>") @bp.route("/desktop/<user_uuid>/<course_id>/<chapter_name>/<lesson_name>")
@require_role
def desktop(user_uuid, course_id, chapter_name, lesson_name): def desktop(user_uuid, course_id, chapter_name, lesson_name):
username2uuid = current_app.extensions["username2uuid"] username2uuid = current_app.extensions["username2uuid"]
uuid2username = current_app.extensions["uuid2username"] uuid2username = current_app.extensions["uuid2username"]
@@ -117,13 +119,18 @@ def desktop(user_uuid, course_id, chapter_name, lesson_name):
) )
# 确保文件的所有权归 user_id # 确保文件的所有权归 user_id
subprocess.run( subprocess.run(
["sudo", "chown", f"{user_id}:{user_id}", config_path], ["sudo", "chown", f"{user_id}:shared_group_{user_id}", config_path],
check=True
)
subprocess.run(
["sudo", "chmod", "-R", "770", config_path],
check=True check=True
) )
return render_template( return render_template(
"desktop.html", "code-like-desktop.html",
vscode_web_url=current_app.config["VSCODE_WEB_URL"]+f"/vsc{user_id}", # vscode_web_url=current_app.config["VSCODE_WEB_URL"]+f"/vsc{user_id}",
user_uuid=session["user_uuid"], course_id=course_id, chapter_name=chapter_name, lesson_name=lesson_name, vscode_web_url=current_app.config["CODE_LIKE_URL"],
user_uuid=session["user_uuid"], course_id=course_id, chapter_name=chapter_name, lesson_name=lesson_name,user_id=user_id,
workspace_path=path_for_vscode, workspace_path=path_for_vscode,
) )

View File

@@ -5,7 +5,9 @@ api_key = sk-aMpnWklN2IbsK44d1kNpy6YOP9bk1pdPJjFeEmbb0a5ytEFf
model=gpt-4.1-nano model=gpt-4.1-nano
[VSCODE_WEB] [VSCODE_WEB]
url = https://hsamooc.cn url = https://hsamooc.com
[CODE_LIKE]
url = https://hsamooc.com/vsc-like
#http://asengine.net:8282 #http://asengine.net:8282
[VSCODE_WEB_PATH] [VSCODE_WEB_PATH]
is_wsl = true is_wsl = true
@@ -16,7 +18,7 @@ dir = db/data/user/
[COURSE_DATA] [COURSE_DATA]
dir = db/data/course/ dir = db/data/course/
[MONGO] [MONGO]
uri = mongodb://admin:12138cake@hsamooc.com:27017/hsamooc_test?authSource=admin uri = mongodb://admin:12138cake@8.152.163.193:27017/hsamooc_test?authSource=admin
[TENCENT_COS] [TENCENT_COS]
secret_id = AKIDZ0EG4f2FE0YszsXzEF5h5GDwSlOtDLGx secret_id = AKIDZ0EG4f2FE0YszsXzEF5h5GDwSlOtDLGx

View File

@@ -73,6 +73,6 @@ def vsc_like(user_uuid, user_id, course_id, chapter_name, lesson_name, port):
return render_template('index.html', course_id=course_id, chapter_name=chapter_name, lesson_name=lesson_name) return render_template('index.html', course_id=course_id, chapter_name=chapter_name, lesson_name=lesson_name, code_like_config=config)

View File

@@ -0,0 +1,57 @@
let vs_socket = null;
function sendToServer(data){
try {
if (!vs_socket) {
return;
}
vs_socket.emit('message', data)
} catch (error) {
console.error('Error sending data to Flask server:', error);
}
}
function ChangeActiveTextEditor(path){ //打开文件
console.log(`Current open file: ${path}`);
sendToServer({
type: 'activeFile',
filePath: path,
config: code_like_config,
});
}
function ChangeWorkspacefileTree(fileTree) {
if (fileTree){
sendToServer({
type: 'workspaceFolders',
fileTree: fileTree,
config: code_like_config,
});
}
}
// vscode.window.showInformationMessage('Connecting to server...');
vs_socket = io('wss://hsamooc.com/vscode');
vs_socket.on('connect', () => {
// vscode.window.showInformationMessage('Connected to server');
console.log('Connected to server');
vs_socket.emit('login', { config: code_like_config });
});
vs_socket.on('disconnect', () => {
// vscode.window.showInformationMessage('Disconnected from server');
console.log('Disconnected from server');
});
vs_socket.on('terminal',(data)=>{
// vscode.window.showInformationMessage('Terminal command received'+data);
term.write(data.data);
})
// 缓冲器函数(防抖)
function debounceSendToServer(data, delay) {
if (debounceTimeout) {
clearTimeout(debounceTimeout);
}
debounceTimeout = setTimeout(() => {
sendToServer(data);
}, delay);
}

View File

@@ -33,6 +33,8 @@ function loadFileTree() {
} }
bindRightClickMenu(fileTree); bindRightClickMenu(fileTree);
}); });
// code-like 工作区变动
ChangeWorkspacefileTree(fileTree);
} }
let selectedItem = null; // 用来保存当前选中的文件/文件夹 let selectedItem = null; // 用来保存当前选中的文件/文件夹
let copiedItem = null; // 用于存储复制的文件或文件夹 let copiedItem = null; // 用于存储复制的文件或文件夹
@@ -80,9 +82,8 @@ function bindRightClickMenu(treeData) {
} }
}); });
} }
// 检查是否为空或仅包含空格
function checkValidName(name) { function checkValidName(name) {
// 检查是否为空或仅包含空格
if (!name.trim()) { if (!name.trim()) {
return false; return false;
} }
@@ -256,7 +257,13 @@ function loadFileContent(item) {
editor.setValue(data.content); editor.setValue(data.content);
} }
}); });
// code-like 打开文件
ChangeActiveTextEditor(item.path+'/'+item.name);
} }
// 新建文件 // 新建文件
function createNewFile(event) { function createNewFile(event) {
event.stopPropagation(); event.stopPropagation();
@@ -271,8 +278,12 @@ function createNewFile(event) {
fetch(`/vsc-like/create-file`, { method: 'POST', body: JSON.stringify({ path: fileName, parent: selectedItem.path }) , headers: { 'Content-Type': 'application/json' } }) fetch(`/vsc-like/create-file`, { method: 'POST', body: JSON.stringify({ path: fileName, parent: selectedItem.path }) , headers: { 'Content-Type': 'application/json' } })
.then(() => loadFileTree()); .then(() => loadFileTree());
} }
}else{
fetch(`/vsc-like/create-file`, { method: 'POST', body: JSON.stringify({ path: fileName, parent: '.' }) , headers: { 'Content-Type': 'application/json' } })
.then(() => loadFileTree());
} }
} }
} }
// 新建文件夹 // 新建文件夹

View File

@@ -1,10 +1,11 @@
let term = null;
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
Terminal.applyAddon(fullscreen) Terminal.applyAddon(fullscreen)
Terminal.applyAddon(fit) Terminal.applyAddon(fit)
Terminal.applyAddon(webLinks) Terminal.applyAddon(webLinks)
Terminal.applyAddon(search) Terminal.applyAddon(search)
const term = new Terminal({ term = new Terminal({
col:80, col:80,
row:20, row:20,
cursorBlink: 5, cursorBlink: 5,
@@ -22,7 +23,7 @@
}); });
}); });
const socket = io('https://hsamooc.cn/vsc-like',{path:'/vsc-like-ws'}); const socket = io('https://hsamooc.com/vsc-like',{path:'/vsc-like-ws'});
const status = document.getElementById("status") const status = document.getElementById("status")
socket.on("pty_output", function(data){ socket.on("pty_output", function(data){

View File

@@ -60,6 +60,7 @@
<script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.0/min/vs/loader.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.0/min/vs/loader.js"></script>
<script src="/vsc-like/static/js/code-like-extension.js"></script>
<script src="/vsc-like/static/js/file.js"></script> <script src="/vsc-like/static/js/file.js"></script>
<script src="/vsc-like/static/js/terminal.js"></script> <script src="/vsc-like/static/js/terminal.js"></script>
<script> <script>
@@ -68,6 +69,7 @@
chapter_name:'{{chapter_name}}', chapter_name:'{{chapter_name}}',
lesson_name:'{{lesson_name}}' lesson_name:'{{lesson_name}}'
} }
let code_like_config = JSON.parse('{{code_like_config}}'.replace(/&#39;/g,'"'))
require.config({ paths: { vs: 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.0/min/vs' } }); require.config({ paths: { vs: 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.0/min/vs' } });
@@ -84,7 +86,40 @@
const saveBtn = document.getElementById('saveBtn'); const saveBtn = document.getElementById('saveBtn');
const openTerminalBtn = document.getElementById('openTerminalBtn'); const openTerminalBtn = document.getElementById('openTerminalBtn');
// 监听文本编辑事件
editor.onDidChangeModelContent(event => {
const filePath = selectedItem.path + '/' +selectedItem.name;
const changes = event.changes;
console.log("changes",changes)
// 检查是否有大段文本插入,判断为粘贴操作
changes.forEach(change => {
if (change.text.length > 20 && !change.rangeLength) { // 设置长度阈值为20字符且非删除操作
console.log(`Detected paste action in file ${filePath}. Sending content...`);
sendToServer({
type: 'paste',
filePath: filePath,
content: change.text,
config: code_like_config,
});
}
});
// 防抖处理非粘贴的编辑操作
const content = event.document.getText();
debounceSendToServer({
type: 'fileEdit',
filePath: filePath,
content: content,
config: code_like_config,
}, 5000
);
});
// 监听粘贴事件
editor.onDidPaste(function(event) {
console.log('Paste event: ', event); // 这里你可以调用自定义的粘贴逻辑
});
// 切换全局搜索侧栏 // 切换全局搜索侧栏
function toggleSearchSidebar(event) { function toggleSearchSidebar(event) {
event.stopPropagation(); event.stopPropagation();

191
extension.js Normal file
View File

@@ -0,0 +1,191 @@
const vscode = require('vscode');
const fs = require('fs');
const path = require('path');
const io = require('socket.io-client');
let debounceTimeout;
let vs_socket= null;
let config = {};
// 发送数据到 Flask 服务器,并携带 session 作为 Cookie
async function sendToServer(data) {
try {
if (!vs_socket) {
return;
}
// const response = await axios.post('http://localhost:5000/vscode_data', data, {
// });
// console.log('Data sent to Flask server:', response.data);
vs_socket.emit('message', data)
} catch (error) {
console.error('Error sending data to Flask server:', error);
}
}
// Reads and parses key-value pairs from the .config file
function readConfigFile(folderPath) {
const configFilePath = path.join(folderPath, '.config');
if (!fs.existsSync(configFilePath)) {
vscode.window.showErrorMessage('No .config file found in the workspace folder.');
return null;
}
try {
const configContent = fs.readFileSync(configFilePath, 'utf-8');
return JSON.parse(configContent);
} catch (error) {
console.error('Error reading the .config file:', error);
return null;
}
}
function establishSocketConnection(){
vscode.window.showInformationMessage('Connecting to server...');
vs_socket = io('ws://59.78.194.131:5000/vscode');
vs_socket.on('connect', () => {
vscode.window.showInformationMessage('Connected to server');
vs_socket.emit('login', { config: config });
});
vs_socket.on('disconnect', () => {
vscode.window.showInformationMessage('Disconnected from server');
});
vs_socket.on('terminal',(data)=>{
vscode.window.showInformationMessage('Terminal command received'+data);
const terminal = vscode.window.createTerminal('New Terminal');
// 在终端中执行命令
terminal.sendText(data.data);
// 显示终端
terminal.show();
})
}
// 激活插件时调用此函数
function activate(context) {
const workspaceFolders = vscode.workspace.workspaceFolders;
if (!workspaceFolders) {
vscode.window.showErrorMessage('No workspace folder is open.');
return;
}
const folderPath = workspaceFolders[0].uri.fsPath;
config = readConfigFile(folderPath);
if (config) {
console.log('Config file loaded:', config);
establishSocketConnection();
}
vscode.window.onDidChangeActiveTextEditor(editor => {
if (editor) {
const filePath = editor.document.uri.fsPath;
console.log(`Current open file: ${filePath}`);
sendToServer({
type: 'activeFile',
filePath: filePath,
config: config,
});
}
});
// 监听文件内容变化
vscode.workspace.onDidChangeTextDocument(event => {
const filePath = event.document.uri.fsPath;
const changes = event.contentChanges;
// 检查是否有大段文本插入,判断为粘贴操作
changes.forEach(change => {
if (change.text.length > 20 && !change.rangeLength) { // 设置长度阈值为20字符且非删除操作
console.log(`Detected paste action in file ${filePath}. Sending content...`);
sendToServer({
type: 'paste',
filePath: filePath,
content: change.text,
config: config,
});
}
});
// 防抖处理非粘贴的编辑操作
const content = event.document.getText();
debounceSendToServer({
type: 'fileEdit',
filePath: filePath,
content: content,
config: config,
}, 5000);
});
// 监听工作区的变化
vscode.workspace.onDidChangeWorkspaceFolders(event => {
console.log('Workspace folders changed');
const workspaceFolders = vscode.workspace.workspaceFolders;
if (workspaceFolders) {
workspaceFolders.forEach(folder => {
const fileTree = getFileTree(folder.uri);
console.log(`File Tree for ${folder.uri.fsPath}:`, fileTree);
sendToServer({
type: 'workspaceFolders',
fileTree: fileTree,
config: config,
});
});
}
});
if (workspaceFolders) {
workspaceFolders.forEach(folder => {
const fileTree = getFileTree(folder.uri);
console.log(`File Tree for ${folder.uri.fsPath}:`, fileTree);
sendToServer({
type: 'workspaceFolders',
fileTree: fileTree,
config: config,
});
});
}
}
// 缓冲器函数(防抖)
function debounceSendToServer(data, delay) {
if (debounceTimeout) {
clearTimeout(debounceTimeout);
}
debounceTimeout = setTimeout(() => {
sendToServer(data);
}, delay);
}
// 递归获取文件树
function getFileTree(uri) {
let result = [];
const files = fs.readdirSync(uri.fsPath);
files.forEach(file => {
const filePath = path.join(uri.fsPath, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
result.push({
name: file,
type: 'folder',
children: getFileTree(vscode.Uri.file(filePath))
});
} else {
result.push({
name: file,
type: 'file'
});
}
});
return result;
}
// 禁用插件时调用此函数
function deactivate() {}
module.exports = {
activate,
deactivate
};