Files
nezhacursor/gui/main_window.py

1171 lines
43 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import sys
from pathlib import Path
import logging
import os
from PIL import Image
from PyQt5.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLabel, QLineEdit, QPushButton, QFrame, QTextEdit,
QMessageBox, QApplication, QSystemTrayIcon, QMenu,
QDialog, QProgressBar, QStyle)
from PyQt5.QtCore import Qt, QTimer, QThread, pyqtSignal
from PyQt5.QtGui import QIcon, QPixmap
import time
sys.path.append(str(Path(__file__).parent.parent))
from utils.config import Config
from account_switcher import AccountSwitcher
def get_version():
try:
version_file = Path(__file__).parent.parent / 'version.txt'
with open(version_file, 'r', encoding='utf-8') as f:
return f.read().strip()
except Exception as e:
logging.error(f"读取版本号失败: {str(e)}")
return "未知版本"
class LoadingDialog(QDialog):
"""加载对话框"""
def __init__(self, parent=None, message="请稍候..."):
super().__init__(parent)
self.setWindowTitle("处理中")
self.setFixedSize(300, 100)
self.setWindowFlags(Qt.Dialog | Qt.CustomizeWindowHint | Qt.WindowTitleHint)
layout = QVBoxLayout()
# 添加消息标签
self.message_label = QLabel(message)
self.message_label.setAlignment(Qt.AlignCenter)
layout.addWidget(self.message_label)
# 添加进度条
self.progress_bar = QProgressBar()
self.progress_bar.setTextVisible(False)
self.progress_bar.setRange(0, 0) # 设置为循环模式
layout.addWidget(self.progress_bar)
self.setLayout(layout)
# 设置样式
self.setStyleSheet("""
QDialog {
background-color: #f8f9fa;
}
QLabel {
color: #0d6efd;
font-size: 14px;
font-weight: bold;
padding: 10px;
}
QProgressBar {
border: 2px solid #e9ecef;
border-radius: 5px;
text-align: center;
}
QProgressBar::chunk {
background-color: #0d6efd;
width: 10px;
margin: 0.5px;
}
""")
class ApiWorker(QThread):
"""API请求工作线程"""
finished = pyqtSignal(tuple) # 发送结果信号
def __init__(self, func, *args, **kwargs):
super().__init__()
self.func = func
self.args = args
self.kwargs = kwargs
def run(self):
try:
result = self.func(*self.args, **self.kwargs)
self.finished.emit((True, result))
except Exception as e:
self.finished.emit((False, str(e)))
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.config = Config()
self.switcher = AccountSwitcher()
# 添加激活状态缓存
self._activation_status = None # 缓存的激活状态
self._status_timer = None # 状态更新定时器
# 添加请求锁,防止重复提交
self._is_requesting = False
self._last_request_time = 0
self._request_cooldown = 2 # 请求冷却时间(秒)
version = get_version()
cursor_version = self.switcher.get_cursor_version()
self.setWindowTitle(f"听泉Cursor助手 v{version} (本机Cursor版本: {cursor_version})")
self.setMinimumSize(600, 500)
# 设置窗口图标
icon_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "icon", "two.ico")
if os.path.exists(icon_path):
window_icon = QIcon(icon_path)
if not window_icon.isNull():
self.setWindowIcon(window_icon)
logging.info(f"成功设置窗口图标: {icon_path}")
else:
logging.warning("图标文件加载失败")
# 创建系统托盘图标
self.tray_icon = QSystemTrayIcon(self)
self.tray_icon.setIcon(self.windowIcon())
self.tray_icon.setToolTip("听泉Cursor助手")
# 创建托盘菜单
tray_menu = QMenu()
show_action = tray_menu.addAction("显示主窗口")
show_action.triggered.connect(self.show)
quit_action = tray_menu.addAction("退出")
quit_action.triggered.connect(QApplication.instance().quit)
# 设置托盘菜单
self.tray_icon.setContextMenu(tray_menu)
# 连接托盘图标的信号
self.tray_icon.activated.connect(self.on_tray_icon_activated)
# 显示托盘图标
self.tray_icon.show()
# 创建主窗口部件
central_widget = QWidget()
self.setCentralWidget(central_widget)
# 创建主布局
main_layout = QVBoxLayout(central_widget)
# 设备ID区域
device_frame = QFrame()
device_layout = QHBoxLayout(device_frame)
device_layout.addWidget(QLabel("设备识别码(勿动):"))
self.hardware_id_edit = QLineEdit(self.switcher.hardware_id)
self.hardware_id_edit.setReadOnly(True)
device_layout.addWidget(self.hardware_id_edit)
copy_btn = QPushButton("复制ID")
copy_btn.clicked.connect(self.copy_device_id)
device_layout.addWidget(copy_btn)
main_layout.addWidget(device_frame)
# 会员状态区域
status_frame = QFrame()
status_layout = QVBoxLayout(status_frame)
status_layout.addWidget(QLabel("会员状态"))
self.status_text = QTextEdit()
self.status_text.setReadOnly(True)
self.status_text.setMinimumHeight(100)
status_layout.addWidget(self.status_text)
main_layout.addWidget(status_frame)
# 激活区域
activation_frame = QFrame()
activation_layout = QVBoxLayout(activation_frame)
# 激活码输入区域
activation_layout.addWidget(QLabel("激活(叠加)会员,多个激活码可叠加整体时长"))
input_frame = QFrame()
input_layout = QHBoxLayout(input_frame)
input_layout.addWidget(QLabel("激活码:"))
self.activation_edit = QLineEdit()
input_layout.addWidget(self.activation_edit)
activate_btn = QPushButton("激活")
activate_btn.setStyleSheet("""
QPushButton {
background-color: #0d6efd;
color: white;
border: none;
padding: 8px 25px;
border-radius: 4px;
font-size: 13px;
min-width: 80px;
}
QPushButton:hover {
background-color: #0b5ed7;
}
QPushButton:pressed {
background-color: #0a58ca;
}
""")
activate_btn.clicked.connect(self.activate_account)
input_layout.addWidget(activate_btn)
activation_layout.addWidget(input_frame)
main_layout.addWidget(activation_frame)
# 使用说明
usage_label = QLabel()
usage_text = (
"<p style='margin-bottom: 10px;'><b style='color: #0d6efd;'>使用步骤:</b></p>"
"<p style='line-height: 1.5;'>"
"1. <span style='color: #0d6efd;'>第一步:</span>输入激活码并点击<span style='color: #0d6efd;'>【激活】</span>按钮<br>"
"2. <span style='color: #198754;'>第二步:</span>激活成功后点击<span style='color: #198754;'>【刷新Cursor编辑器授权】</span>即可正常使用<br>"
"3. <span style='color: #dc3545;'>如果刷新无效:</span>请先点击<span style='color: #198754;'>【突破Cursor0.45.x限制】</span>,然后再点击刷新<br>"
"4. <span style='color: #6c757d;'>建议操作:</span>点击<span style='color: #dc3545;'>【禁用Cursor版本更新】</span>保持长期稳定"
"</p>"
)
usage_label.setText(usage_text)
usage_label.setStyleSheet("""
QLabel {
color: #333333;
font-size: 13px;
padding: 15px;
background-color: #f8f9fa;
border-radius: 4px;
border: 1px solid #dee2e6;
}
""")
usage_label.setTextFormat(Qt.RichText)
usage_label.setWordWrap(True)
activation_layout.addWidget(usage_label)
# 操作按钮区域
btn_frame = QFrame()
btn_layout = QVBoxLayout(btn_frame)
# 设置按钮样式
button_style = """
QPushButton {
background-color: #0d6efd;
color: white;
border: none;
padding: 15px;
border-radius: 6px;
font-size: 13px;
min-width: 300px;
margin: 5px;
}
QPushButton:hover {
background-color: #0b5ed7;
}
QPushButton:pressed {
background-color: #0a58ca;
}
"""
# 刷新授权按钮
refresh_btn = QPushButton("刷新 Cursor 编辑器授权")
refresh_btn.setStyleSheet(button_style)
refresh_btn.clicked.connect(self.refresh_cursor_auth)
refresh_btn.setMinimumHeight(50)
btn_layout.addWidget(refresh_btn)
# 突破限制按钮
bypass_btn = QPushButton("突破 Cursor 0.45.x 限制")
bypass_btn.setStyleSheet(button_style.replace("#0d6efd", "#198754").replace("#0b5ed7", "#157347").replace("#0a58ca", "#146c43"))
bypass_btn.clicked.connect(self.bypass_cursor_limit)
bypass_btn.setMinimumHeight(50)
btn_layout.addWidget(bypass_btn)
# 禁用更新按钮
disable_update_btn = QPushButton("禁用 Cursor 版本更新")
disable_update_btn.setStyleSheet(button_style.replace("#0d6efd", "#dc3545").replace("#0b5ed7", "#bb2d3b").replace("#0a58ca", "#b02a37"))
disable_update_btn.clicked.connect(self.disable_cursor_update)
disable_update_btn.setMinimumHeight(50)
btn_layout.addWidget(disable_update_btn)
# 设置按钮间距
btn_layout.setSpacing(10)
btn_layout.setContentsMargins(20, 10, 20, 10)
main_layout.addWidget(btn_frame)
# 启动时检查一次状态
QTimer.singleShot(0, self.check_status)
def on_tray_icon_activated(self, reason):
"""处理托盘图标的点击事件"""
if reason == QSystemTrayIcon.DoubleClick:
self.show()
self.activateWindow()
def closeEvent(self, event):
"""重写关闭事件,最小化到托盘而不是退出"""
if hasattr(self, 'tray_icon') and self.tray_icon.isVisible():
event.ignore()
self.hide()
self.tray_icon.showMessage(
"听泉Cursor助手",
"程序已最小化到系统托盘",
QSystemTrayIcon.Information,
2000
)
else:
event.accept()
if self._status_timer:
self._status_timer.stop()
super().closeEvent(event)
def copy_device_id(self):
"""复制设备ID到剪贴板"""
QApplication.clipboard().setText(self.hardware_id_edit.text())
QMessageBox.information(self, "提示", "设备ID已复制到剪贴板")
def show_loading_dialog(self, message="请稍候..."):
"""显示加载对话框"""
self.loading_dialog = LoadingDialog(self, message)
self.loading_dialog.setStyleSheet("""
QDialog {
background-color: #f8f9fa;
}
QLabel {
color: #0d6efd;
font-size: 14px;
font-weight: bold;
padding: 10px;
}
QProgressBar {
border: 2px solid #e9ecef;
border-radius: 5px;
text-align: center;
}
QProgressBar::chunk {
background-color: #0d6efd;
width: 10px;
margin: 0.5px;
}
""")
self.loading_dialog.show()
def hide_loading_dialog(self):
"""隐藏加载对话框"""
if hasattr(self, 'loading_dialog'):
self.loading_dialog.hide()
self.loading_dialog.deleteLater()
def activate_account(self):
"""激活账号"""
code = self.activation_edit.text().strip()
if not code:
# 创建自定义消息框
msg = QDialog(self)
msg.setWindowTitle("提示")
msg.setFixedWidth(400)
msg.setWindowFlags(msg.windowFlags() & ~Qt.WindowContextHelpButtonHint)
# 创建布局
layout = QVBoxLayout()
# 添加图标和文本
icon_label = QLabel()
icon_label.setPixmap(self.style().standardIcon(QStyle.SP_MessageBoxWarning).pixmap(32, 32))
icon_label.setAlignment(Qt.AlignCenter)
layout.addWidget(icon_label)
text_label = QLabel("请输入激活码")
text_label.setAlignment(Qt.AlignCenter)
text_label.setStyleSheet("font-size: 14px; font-weight: bold; color: #333333; padding: 10px;")
layout.addWidget(text_label)
# 添加购买信息
info_text = "获取会员激活码,请通过以下方式:\n\n" \
"• 官方自助网站cursor.nosqli.com\n" \
"• 微信客服behikcigar\n" \
"• 闲鱼店铺xxx\n\n" \
"————————————————————\n" \
"诚招代理商,欢迎加盟合作!"
info_label = QLabel(info_text)
info_label.setAlignment(Qt.AlignLeft)
info_label.setStyleSheet("""
QLabel {
color: #333333;
font-size: 14px;
padding: 15px;
background-color: #f8f9fa;
border-radius: 4px;
border: 1px solid #dee2e6;
margin: 10px;
}
""")
layout.addWidget(info_label)
# 添加复制按钮区域
btn_layout = QHBoxLayout()
# 复制网站按钮
copy_web_btn = QPushButton("复制网站")
copy_web_btn.clicked.connect(lambda: self.copy_and_show_tip(msg, "cursor.nosqli.com", "网站地址已复制到剪贴板"))
copy_web_btn.setStyleSheet("""
QPushButton {
background-color: #0d6efd;
color: white;
border: none;
padding: 8px 15px;
border-radius: 4px;
font-size: 13px;
}
QPushButton:hover {
background-color: #0b5ed7;
}
""")
btn_layout.addWidget(copy_web_btn)
# 复制微信按钮
copy_wx_btn = QPushButton("复制微信")
copy_wx_btn.clicked.connect(lambda: self.copy_and_show_tip(msg, "behikcigar", "微信号已复制到剪贴板"))
copy_wx_btn.setStyleSheet("""
QPushButton {
background-color: #198754;
color: white;
border: none;
padding: 8px 15px;
border-radius: 4px;
font-size: 13px;
}
QPushButton:hover {
background-color: #157347;
}
""")
btn_layout.addWidget(copy_wx_btn)
# 确定按钮
ok_btn = QPushButton("确定")
ok_btn.clicked.connect(msg.accept)
ok_btn.setStyleSheet("""
QPushButton {
background-color: #0d6efd;
color: white;
border: none;
padding: 8px 25px;
border-radius: 4px;
font-size: 13px;
min-width: 100px;
}
QPushButton:hover {
background-color: #0b5ed7;
}
""")
btn_layout.addWidget(ok_btn)
layout.addLayout(btn_layout)
msg.setLayout(layout)
msg.exec_()
return
try:
# 显示加载对话框
self.show_loading_dialog("正在验证激活码,请稍候...")
# 创建工作线程
self.worker = ApiWorker(self.switcher.check_activation_code, code)
self.worker.finished.connect(self.on_activation_complete)
self.worker.start()
except Exception as e:
self.hide_loading_dialog()
msg = QMessageBox(self)
msg.setWindowTitle("错误")
msg.setText(f"激活失败: {str(e)}")
msg.setIcon(QMessageBox.Critical)
msg.setStyleSheet("""
QMessageBox {
background-color: #f8f9fa;
min-width: 450px;
padding: 20px;
}
QMessageBox QLabel {
color: #333333;
font-size: 14px;
padding: 10px;
margin: 10px;
}
QMessageBox QLabel:first-child {
font-weight: bold;
color: #dc3545;
}
QPushButton {
background-color: #dc3545;
color: white;
border: none;
padding: 8px 25px;
border-radius: 4px;
font-size: 13px;
min-width: 100px;
margin: 10px;
}
QPushButton:hover {
background-color: #bb2d3b;
}
""")
msg.exec_()
def copy_and_show_tip(self, parent, text, tip):
"""复制文本并显示提示"""
QApplication.clipboard().setText(text)
QMessageBox.information(parent, "提示", tip)
def on_activation_complete(self, result):
"""激活完成回调"""
success, data = result
self.hide_loading_dialog()
if isinstance(data, tuple):
success, message, account_info = data
if success:
# 更新会员信息显示
self.update_status_display(account_info)
# 更新激活状态缓存
self._activation_status = account_info.get('status') == 'active'
# 更新状态定时器
if self._activation_status:
if self._status_timer:
self._status_timer.stop()
self._status_timer = QTimer(self)
self._status_timer.setSingleShot(False)
self._status_timer.timeout.connect(self.check_status)
self._status_timer.start(60 * 1000) # 每60秒检测一次
logging.info("已设置每分钟检测会员状态")
msg = QMessageBox(self)
msg.setWindowTitle("激活成功")
msg.setText("激活成功!")
msg.setInformativeText(message)
msg.setIcon(QMessageBox.Information)
msg.setStyleSheet("""
QMessageBox {
background-color: #f8f9fa;
min-width: 500px;
padding: 20px;
}
QMessageBox QLabel {
color: #333333;
font-size: 14px;
padding: 10px;
margin: 10px;
}
QMessageBox QLabel:first-child {
font-weight: bold;
font-size: 16px;
color: #198754;
}
QPushButton {
background-color: #198754;
color: white;
border: none;
padding: 8px 25px;
border-radius: 4px;
font-size: 13px;
min-width: 100px;
margin: 10px;
}
QPushButton:hover {
background-color: #157347;
}
""")
msg.exec_()
# 清空激活码输入框
self.activation_edit.clear()
else:
msg = QMessageBox(self)
msg.setWindowTitle("激活失败")
msg.setText(message)
msg.setIcon(QMessageBox.Critical)
msg.setStyleSheet("""
QMessageBox {
background-color: #f8f9fa;
min-width: 450px;
padding: 20px;
}
QMessageBox QLabel {
color: #333333;
font-size: 14px;
padding: 10px;
margin: 10px;
}
QMessageBox QLabel:first-child {
font-weight: bold;
color: #dc3545;
}
QPushButton {
background-color: #dc3545;
color: white;
border: none;
padding: 8px 25px;
border-radius: 4px;
font-size: 13px;
min-width: 100px;
margin: 10px;
}
QPushButton:hover {
background-color: #bb2d3b;
}
""")
msg.exec_()
# 更新显示为未激活状态
self.update_status_display(account_info)
else:
QMessageBox.critical(self, "错误", f"激活失败: {data}")
# 更新为未激活状态
device_info = self.switcher.get_device_info()
inactive_status = {
"status": "inactive",
"expire_time": "",
"total_days": 0,
"days_left": 0,
"device_info": device_info
}
self.update_status_display(inactive_status)
def update_status_display(self, status_info: dict):
"""更新状态显示"""
# 打印API返回的原始数据
logging.info("=== API返回数据 ===")
logging.info(f"状态信息: {status_info}")
# 更新状态文本
status_map = {
"active": "正常",
"inactive": "未激活",
"expired": "已过期"
}
status_text = status_map.get(status_info.get('status', 'inactive'), "未知")
# 构建状态文本
status_lines = [
f"会员状态:{status_text}",
f"到期时间:{status_info.get('expire_time', '')}",
f"总天数:{status_info.get('total_days', 0)}",
f"剩余天数:{status_info.get('days_left', 0)}"
]
# 添加设备信息
device_info = status_info.get('device_info', {})
if device_info:
status_lines.extend([
"",
"设备信息:",
f"系统:{device_info.get('os', '')}",
f"设备名:{device_info.get('device_name', '')}",
f"IP地址{device_info.get('ip', '')}",
f"地区:{device_info.get('location', '--')}"
])
# 更新状态文本
self.status_text.setPlainText("\n".join(status_lines))
def check_status(self):
"""检查会员状态从API获取"""
try:
# 只在首次检查时显示加载对话框
if self._activation_status is None:
self.show_loading_dialog("正在检查会员状态,请稍候...")
# 创建工作线程
self.worker = ApiWorker(self.switcher.get_member_status)
self.worker.finished.connect(self.on_status_check_complete)
self.worker.start()
except Exception as e:
if self._activation_status is None:
self.hide_loading_dialog()
QMessageBox.critical(self, "错误", f"检查状态失败: {str(e)}")
self._activation_status = False
logging.error(f"检查状态时发生错误: {str(e)}")
return False
def on_status_check_complete(self, result):
"""状态检查完成回调"""
success, data = result
# 只在首次检查时隐藏加载对话框
if self._activation_status is None:
self.hide_loading_dialog()
if success and data:
# 更新激活状态和定时器
self._activation_status = data.get('status') == 'active'
if self._activation_status:
# 设置定时器
if self._status_timer:
self._status_timer.stop()
self._status_timer = QTimer(self)
self._status_timer.setSingleShot(False)
self._status_timer.timeout.connect(self.check_status)
self._status_timer.start(60 * 1000) # 每60秒检测一次
logging.info("已设置每分钟检测会员状态")
else:
if self._status_timer:
self._status_timer.stop()
# 更新显示
self.update_status_display(data)
else:
# 停止定时器
if self._status_timer:
self._status_timer.stop()
self._activation_status = False
# 更新为未激活状态
device_info = self.switcher.get_device_info()
inactive_status = {
"status": "inactive",
"expire_time": "",
"total_days": 0,
"days_left": 0,
"device_info": device_info
}
self.update_status_display(inactive_status)
logging.warning("会员状态检查失败或未激活")
# 清除会员信息文件
try:
member_file = self.switcher.config.member_file
if member_file.exists():
member_file.unlink()
logging.info("已清除会员信息文件")
except Exception as e:
logging.error(f"清除会员信息文件时出错: {str(e)}")
return self._activation_status
def check_activation_status(self) -> bool:
"""检查是否已激活(使用缓存)
Returns:
bool: 是否已激活
"""
# 如果缓存的状态是None从API获取
if self._activation_status is None:
return self.check_status()
# 如果未激活,显示购买信息
if not self._activation_status:
self.show_purchase_info()
return self._activation_status
def show_purchase_info(self):
"""显示购买信息对话框"""
# 创建自定义消息框
msg = QDialog(self)
msg.setWindowTitle("会员未激活")
msg.setFixedWidth(400)
msg.setWindowFlags(msg.windowFlags() & ~Qt.WindowContextHelpButtonHint)
# 创建布局
layout = QVBoxLayout()
# 添加图标和文本
icon_label = QLabel()
icon_label.setPixmap(self.style().standardIcon(QStyle.SP_MessageBoxWarning).pixmap(32, 32))
icon_label.setAlignment(Qt.AlignCenter)
layout.addWidget(icon_label)
text_label = QLabel("您还未激活会员或会员已过期")
text_label.setAlignment(Qt.AlignCenter)
text_label.setStyleSheet("font-size: 14px; font-weight: bold; color: #333333; padding: 10px;")
layout.addWidget(text_label)
# 添加购买信息
info_text = "获取会员激活码,请通过以下方式:\n\n" \
"• 官方自助网站cursor.nosqli.com\n" \
"• 微信客服behikcigar\n" \
"• 闲鱼店铺xxx\n\n" \
"————————————————————\n" \
"诚招代理商,欢迎加盟合作!"
info_label = QLabel(info_text)
info_label.setAlignment(Qt.AlignLeft)
info_label.setStyleSheet("""
QLabel {
color: #333333;
font-size: 14px;
padding: 15px;
background-color: #f8f9fa;
border-radius: 4px;
border: 1px solid #dee2e6;
margin: 10px;
}
""")
layout.addWidget(info_label)
# 添加复制按钮区域
btn_layout = QHBoxLayout()
# 复制网站按钮
copy_web_btn = QPushButton("复制网站")
copy_web_btn.clicked.connect(lambda: self.copy_and_show_tip(msg, "cursor.nosqli.com", "网站地址已复制到剪贴板"))
copy_web_btn.setStyleSheet("""
QPushButton {
background-color: #0d6efd;
color: white;
border: none;
padding: 8px 15px;
border-radius: 4px;
font-size: 13px;
}
QPushButton:hover {
background-color: #0b5ed7;
}
""")
btn_layout.addWidget(copy_web_btn)
# 复制微信按钮
copy_wx_btn = QPushButton("复制微信")
copy_wx_btn.clicked.connect(lambda: self.copy_and_show_tip(msg, "behikcigar", "微信号已复制到剪贴板"))
copy_wx_btn.setStyleSheet("""
QPushButton {
background-color: #198754;
color: white;
border: none;
padding: 8px 15px;
border-radius: 4px;
font-size: 13px;
}
QPushButton:hover {
background-color: #157347;
}
""")
btn_layout.addWidget(copy_wx_btn)
# 确定按钮
ok_btn = QPushButton("确定")
ok_btn.clicked.connect(msg.accept)
ok_btn.setStyleSheet("""
QPushButton {
background-color: #0d6efd;
color: white;
border: none;
padding: 8px 25px;
border-radius: 4px;
font-size: 13px;
min-width: 100px;
}
QPushButton:hover {
background-color: #0b5ed7;
}
""")
btn_layout.addWidget(ok_btn)
layout.addLayout(btn_layout)
msg.setLayout(layout)
msg.exec_()
def refresh_cursor_auth(self):
"""刷新Cursor授权"""
if not self.check_activation_status():
return
if not self._check_request_throttle():
return
try:
# 显示加载对话框
self.show_loading_dialog("正在刷新授权,请稍候...")
# 创建工作线程
self.worker = ApiWorker(self.switcher.refresh_cursor_auth)
self.worker.finished.connect(self.on_refresh_auth_complete)
self.worker.start()
except Exception as e:
self._request_complete()
self.hide_loading_dialog()
self.show_custom_error("刷新授权失败", str(e))
def on_refresh_auth_complete(self, result):
"""刷新授权完成回调"""
success, data = result
self.hide_loading_dialog()
self._request_complete()
if isinstance(data, tuple):
success, message = data
if success:
self.show_custom_message("成功", "刷新授权成功", message, QStyle.SP_DialogApplyButton, "#198754")
else:
self.show_custom_error("刷新授权失败", message)
else:
self.show_custom_error("刷新授权失败", str(data))
def disable_cursor_update(self):
"""禁用Cursor更新"""
if not self.check_activation_status():
return
if not self._check_request_throttle():
return
try:
# 显示加载对话框
self.show_loading_dialog("正在禁用更新,请稍候...")
# 创建工作线程
from utils.cursor_registry import CursorRegistry
registry = CursorRegistry()
def disable_func():
try:
# 1. 先关闭所有Cursor进程
if sys.platform == "win32":
os.system("taskkill /f /im Cursor.exe >nul 2>&1")
time.sleep(2)
# 2. 处理updater文件
updater_path = Path(os.getenv('LOCALAPPDATA')) / "cursor-updater"
try:
# 如果是目录,则删除
if updater_path.is_dir():
import shutil
shutil.rmtree(str(updater_path))
logging.info("删除updater目录成功")
# 如果是文件,则删除
if updater_path.is_file():
updater_path.unlink()
logging.info("删除updater文件成功")
# 创建阻止文件
updater_path.touch()
logging.info("创建updater空文件成功")
# 设置文件权限
import subprocess
import stat
# 设置只读属性
os.chmod(str(updater_path), stat.S_IREAD)
logging.info("设置只读属性成功")
# 使用icacls设置权限只读
username = os.getenv('USERNAME')
cmd = f'icacls "{str(updater_path)}" /inheritance:r /grant:r "{username}:(R)"'
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
if result.returncode != 0:
logging.error(f"设置文件权限失败: {result.stderr}")
return False, "设置文件权限失败"
logging.info("设置文件权限成功")
# 验证设置
if not os.path.exists(updater_path):
return False, "文件创建失败"
if os.access(str(updater_path), os.W_OK):
return False, "文件权限设置失败"
except Exception as e:
logging.error(f"处理updater文件失败: {str(e)}")
return False, "处理updater文件失败"
# 3. 修改package.json配置
if not registry.fix_cursor_startup():
return False, "修改配置失败"
# 4. 重启Cursor
cursor_exe = registry.cursor_path / "Cursor.exe"
if cursor_exe.exists():
os.startfile(str(cursor_exe))
logging.info("Cursor重启成功")
return True, "Cursor更新已禁用程序已重启"
else:
return False, "未找到Cursor程序"
except Exception as e:
logging.error(f"禁用更新时发生错误: {str(e)}")
return False, str(e)
self.worker = ApiWorker(disable_func)
self.worker.finished.connect(lambda result: self.on_disable_update_complete(result))
self.worker.start()
except Exception as e:
self._request_complete()
self.hide_loading_dialog()
self.show_custom_error("禁用更新失败", str(e))
def on_disable_update_complete(self, result):
"""禁用更新完成回调"""
success, data = result
self.hide_loading_dialog()
self._request_complete()
if success:
self.show_custom_message(
"成功",
"禁用更新成功",
data,
QStyle.SP_DialogApplyButton,
"#198754"
)
else:
self.show_custom_error("禁用更新失败", str(data))
def bypass_cursor_limit(self):
"""突破Cursor版本限制"""
if not self.check_activation_status():
return
if not self._check_request_throttle():
return
try:
# 显示加载对话框
self.show_loading_dialog("正在突破版本限制,请稍候...")
# 创建工作线程
from utils.cursor_registry import CursorRegistry
registry = CursorRegistry()
def reset_func():
try:
# 1. 先关闭所有Cursor进程
if sys.platform == "win32":
os.system("taskkill /f /im Cursor.exe >nul 2>&1")
time.sleep(2)
# 2. 清理注册表
if not registry.clean_registry():
return False, "清理注册表失败"
# 3. 清理文件
if not registry.clean_cursor_files():
return False, "清理文件失败"
# 4. 重启Cursor
cursor_exe = self.cursor_path / "Cursor.exe"
if cursor_exe.exists():
os.startfile(str(cursor_exe))
logging.info("Cursor重启成功")
return True, "突破限制成功"
else:
return False, "未找到Cursor程序"
except Exception as e:
logging.error(f"突破限制时发生错误: {str(e)}")
return False, str(e)
self.worker = ApiWorker(reset_func)
self.worker.finished.connect(self.on_bypass_complete)
self.worker.start()
except Exception as e:
self._request_complete()
self.hide_loading_dialog()
self.show_custom_error("突破限制失败", str(e))
def on_bypass_complete(self, result):
"""突破限制完成回调"""
success, data = result
self.hide_loading_dialog()
self._request_complete()
if success:
self.show_custom_message(
"成功",
"突破限制成功",
"Cursor版本限制已突破编辑器已重启。",
QStyle.SP_DialogApplyButton,
"#198754"
)
else:
self.show_custom_error("突破限制失败", str(data))
def show_custom_message(self, title, header, message, icon_type, color):
"""显示自定义消息框"""
msg = QDialog(self)
msg.setWindowTitle(title)
msg.setFixedWidth(400)
msg.setWindowFlags(msg.windowFlags() & ~Qt.WindowContextHelpButtonHint)
layout = QVBoxLayout()
# 添加图标
icon_label = QLabel()
icon_label.setPixmap(self.style().standardIcon(icon_type).pixmap(32, 32))
icon_label.setAlignment(Qt.AlignCenter)
layout.addWidget(icon_label)
# 添加标题
text_label = QLabel(header)
text_label.setAlignment(Qt.AlignCenter)
text_label.setStyleSheet(f"""
font-size: 14px;
font-weight: bold;
color: {color};
padding: 10px;
""")
layout.addWidget(text_label)
# 添加详细信息
info_label = QLabel(message)
info_label.setAlignment(Qt.AlignLeft)
info_label.setWordWrap(True)
info_label.setStyleSheet("""
QLabel {
color: #333333;
font-size: 14px;
padding: 15px;
background-color: #f8f9fa;
border-radius: 4px;
border: 1px solid #dee2e6;
margin: 10px;
}
""")
layout.addWidget(info_label)
# 确定按钮
btn_layout = QHBoxLayout()
ok_btn = QPushButton("确定")
ok_btn.clicked.connect(msg.accept)
ok_btn.setStyleSheet(f"""
QPushButton {{
background-color: {color};
color: white;
border: none;
padding: 8px 25px;
border-radius: 4px;
font-size: 13px;
min-width: 100px;
}}
QPushButton:hover {{
background-color: {color.replace('fd', 'd7') if 'fd' in color else color.replace('54', '47')};
}}
""")
btn_layout.addWidget(ok_btn)
layout.addLayout(btn_layout)
msg.setLayout(layout)
msg.exec_()
def show_custom_error(self, header, message):
"""显示自定义错误消息框"""
self.show_custom_message(
"错误",
header,
message,
QStyle.SP_MessageBoxCritical,
"#dc3545"
)
def _check_request_throttle(self) -> bool:
"""检查是否可以发送请求(防重复提交)
Returns:
bool: 是否可以发送请求
"""
current_time = time.time()
# 如果正在请求中返回False
if self._is_requesting:
return False
# 如果距离上次请求时间小于冷却时间返回False
if current_time - self._last_request_time < self._request_cooldown:
return False
# 更新状态和时间
self._is_requesting = True
self._last_request_time = current_time
return True
def _request_complete(self):
"""请求完成,重置状态"""
self._is_requesting = False