├── .gitattributes ├── .gitignore ├── .travis.yml ├── DWords ├── __init__.py ├── __main__.py ├── app.py ├── async_thread.py ├── danmaku.py ├── data │ ├── dict_en_cn.sql │ └── dictionary.db ├── db.py ├── home.py ├── img │ └── logo.svg ├── launcher.py ├── mail.py ├── migrate.py ├── setting.py ├── synchronizer.py ├── utils.py └── version.py ├── LICENSE ├── MANIFEST.in ├── README.md ├── README_cn.md ├── logo.ico ├── logo.svg ├── requirements.txt ├── screenshot.png ├── setup.py ├── tests ├── __init__.py ├── test_danmaku.py ├── test_home.py ├── test_other.py ├── test_setting.py └── test_sync.py ├── win.py └── win.spec /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto 2 | *.sql linguist-vendored text eol=lf 3 | *.py text eol=lf 4 | *.md text eol=lf 5 | *.in text eol=lf 6 | *.txt text eol=lf 7 | *.yml text eol=lf 8 | *.spec text eol=lf 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ 2 | .vscode/ 3 | data/user.db 4 | *.pyc 5 | build/ 6 | dist/ 7 | *.egg-info/ 8 | .pytest_cache/ 9 | .coverage 10 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "3.7" 4 | 5 | sudo: required 6 | 7 | before_install: 8 | - sudo apt-get update 9 | - sudo apt-get install -y xvfb herbstluftwm 10 | - sudo apt-get install -y libdbus-1-3 libxkbcommon-x11-0 11 | 12 | install: 13 | - pip install -r requirements.txt 14 | - pip install pytest-qt pytest-cov 15 | - "export DISPLAY=:99.0" 16 | - "/sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_99.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :99 -screen 0 1920x1200x24 -ac +extension GLX +render -noreset" 17 | - sleep 3 18 | 19 | before_script: 20 | - "herbstluftwm &" 21 | - sleep 1 22 | 23 | script: 24 | - pytest --cov=DWords tests/ 25 | - python setup.py sdist 26 | 27 | after_success: 28 | - pip install codecov 29 | - codecov 30 | -------------------------------------------------------------------------------- /DWords/__init__.py: -------------------------------------------------------------------------------- 1 | from .version import VERSION as __version__ 2 | 3 | def real_path(path): 4 | import os 5 | return os.path.join(os.path.dirname(__file__), path) 6 | -------------------------------------------------------------------------------- /DWords/__main__.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from .app import App 3 | 4 | def main(): 5 | app = App(sys.argv) 6 | sys.exit(app.exec_()) 7 | 8 | if __name__ == '__main__': 9 | main() 10 | -------------------------------------------------------------------------------- /DWords/app.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from PyQt5.QtWidgets import QApplication, QSystemTrayIcon, QMenu, QMessageBox 3 | from PyQt5.QtGui import QFont, QIcon 4 | from PyQt5.QtCore import QCoreApplication, QTimer 5 | from .home import Home 6 | from .launcher import Launcher 7 | from .synchronizer import Synchronizer 8 | from .setting import Setting 9 | from .db import user_db, initialize 10 | from .async_thread import normal 11 | from . import utils, real_path 12 | 13 | class App(QApplication): 14 | def __init__(self, argv): 15 | super().__init__(argv) 16 | initialize() 17 | self._launcher = Launcher() 18 | self._synchronizer = Synchronizer() 19 | self._home = Home() 20 | self._setting = None 21 | 22 | self._home.onClickBurst.connect(self.clickBurst) 23 | self._home.onClickSetting.connect(self.clickSetting) 24 | self._home.onClickSync.connect(self.clickSync) 25 | self._launcher.onChangeWordCleared.connect(self._home.initLists) 26 | self._synchronizer.onSynchronizeDone.connect(self._home.initLists) 27 | 28 | self._timer = QTimer(self) 29 | self._timer.timeout.connect(self.autoSync) 30 | self._timer.start(utils.get_setting("sync_frequency")) 31 | self.autoSync() 32 | 33 | self.setQuitOnLastWindowClosed(False) 34 | self.setTrayIcon() 35 | 36 | def setTrayIcon(self): 37 | tray_icon = QSystemTrayIcon(QIcon(real_path("img/logo.svg")), self) 38 | tray_icon.show() 39 | menu = QMenu() 40 | menu.addAction("Burst!").triggered.connect(self.clickBurst) 41 | menu.addAction("Sync").triggered.connect(self.clickSync) 42 | menu.addAction("Setting").triggered.connect(self.clickSetting) 43 | menu.addAction("Exit").triggered.connect(self.clickExit) 44 | tray_icon.setContextMenu(menu) 45 | tray_icon.activated.connect(self.clickTrayIcon) 46 | tray_icon.setToolTip("DWords") 47 | 48 | def clickTrayIcon(self, e): 49 | if e == QSystemTrayIcon.Trigger: 50 | self._home.showNormal() 51 | self._home.show() 52 | self._home.activateWindow() 53 | 54 | def clickBurst(self): 55 | self._launcher.burst() 56 | 57 | def autoSync(self): 58 | if not utils.is_sync(): return 59 | self.clickSync(is_auto=True) 60 | self._timer.setInterval(utils.get_setting("sync_frequency")) 61 | 62 | @normal 63 | async def clickSync(self, *_, is_auto=False): 64 | if self._synchronizer._synchronizing: return 65 | self._home.sync_btn.setEnabled(False) 66 | self._home.sync_btn.setText("Syncing...") 67 | 68 | logging.info("Start synchronize") 69 | try: 70 | await self._synchronizer.sync() 71 | except Exception as e: 72 | if not is_auto: 73 | QMessageBox.critical(self._home, "Sync Error", str(e), QMessageBox.Yes) 74 | logging.error(f"Synchronize failed: {e}") 75 | else: 76 | logging.info("Synchronize succeed.") 77 | finally: 78 | self._home.sync_btn.setEnabled(True) 79 | self._home.sync_btn.setText("Sync") 80 | 81 | def clickSetting(self): 82 | if self._setting: 83 | self._setting.showNormal() 84 | self._setting.activateWindow() 85 | else: 86 | self._setting = Setting() 87 | self._setting.destroyed.connect(self.onSettingClose) 88 | 89 | def onSettingClose(self): 90 | self._setting = None 91 | 92 | def clickExit(self): 93 | self._launcher.clear() 94 | user_db.close() 95 | self.quit() 96 | -------------------------------------------------------------------------------- /DWords/async_thread.py: -------------------------------------------------------------------------------- 1 | from functools import wraps 2 | from PyQt5.QtCore import QThread, QObject, pyqtSignal 3 | 4 | _coroutines = {} 5 | 6 | class Work(QThread): 7 | 8 | def __init__(self, f, args, kw): 9 | super().__init__() 10 | self._f = f 11 | self._args = args 12 | self._kw = kw 13 | 14 | def run(self): 15 | try: 16 | res = self._f(*self._args, *self._kw) 17 | except Exception as e: 18 | self.succeed = False 19 | self.value = e 20 | else: 21 | self.succeed = True 22 | self.value = res 23 | 24 | class RunInThread(QObject): 25 | 26 | def __init__(self, f, *args, **kw): 27 | super().__init__() 28 | self._thread = Work(f, args, kw) 29 | 30 | def __await__(self): 31 | self._thread.finished.connect(self.onWorkFinished) 32 | self._thread.start() 33 | res = yield self 34 | return res 35 | 36 | def onWorkFinished(self): 37 | assert self._thread.isFinished() 38 | try: 39 | if self._thread.succeed: 40 | o = self.co.send(self._thread.value) 41 | else: 42 | o = self.co.throw(self._thread.value) 43 | o.co = self.co 44 | _coroutines[self.co] = o 45 | except StopIteration: 46 | del _coroutines[self.co] 47 | 48 | def normal(f): 49 | @wraps(f) 50 | def wrapper(*args, **kw): 51 | co = f(*args, **kw) 52 | try: 53 | o = co.send(None) 54 | o.co = co 55 | _coroutines[co] = o 56 | except StopIteration: 57 | pass 58 | 59 | return wrapper 60 | 61 | def thread(f): 62 | @wraps(f) 63 | def wrapper(*args, **kw): 64 | return RunInThread(f, *args, **kw) 65 | 66 | return wrapper 67 | -------------------------------------------------------------------------------- /DWords/danmaku.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtWidgets import * 2 | from PyQt5.QtGui import QIcon, QFont, QMouseEvent 3 | from PyQt5.QtCore import QTimer, Qt, QEvent, pyqtSignal, QRect 4 | from . import utils 5 | 6 | class WordLabel(QLabel): 7 | onEnter = pyqtSignal() 8 | onLeave = pyqtSignal() 9 | onMousePress = pyqtSignal(QMouseEvent) 10 | onMouseMove = pyqtSignal(QMouseEvent) 11 | onMouseRelease = pyqtSignal(QMouseEvent) 12 | 13 | def __init__(self, *argv, **kw): 14 | super().__init__(*argv, **kw) 15 | 16 | self.installEventFilter(self) 17 | 18 | def enterEvent(self, e): 19 | self.onEnter.emit() 20 | 21 | def leaveEvent(self, e): 22 | self.onLeave.emit() 23 | 24 | def mousePressEvent(self, e): 25 | self.onMousePress.emit(e) 26 | 27 | def mouseMoveEvent(self, e): 28 | self.onMouseMove.emit(e) 29 | 30 | def mouseReleaseEvent(self, e): 31 | self.onMouseRelease.emit(e) 32 | 33 | class Danmaku(QWidget): 34 | onModified = pyqtSignal(str) 35 | 36 | def __init__(self, word, paraphrase, y, show_paraphrase = None, color = None): 37 | super().__init__() 38 | self._word = word 39 | self._paraphrase = paraphrase 40 | self._stop_move = False 41 | self._show_detail = False 42 | 43 | self.modified = False 44 | self._show_paraphrase = show_paraphrase \ 45 | if show_paraphrase is not None else \ 46 | utils.get_setting("danmaku_default_show_paraphrase") 47 | self._color = color if color is not None else \ 48 | utils.get_setting("danmaku_default_color") 49 | self._cleared = False 50 | 51 | self.setWindowFlags( 52 | self.windowFlags() | 53 | Qt.WindowStaysOnTopHint | 54 | Qt.FramelessWindowHint | 55 | Qt.ToolTip | 56 | Qt.X11BypassWindowManagerHint # for gnome 57 | ) 58 | self.setAttribute(Qt.WA_TranslucentBackground, True) 59 | self.setAttribute(Qt.WA_DeleteOnClose) 60 | 61 | self.initUI() 62 | self.initPosition(y) 63 | 64 | # self.installEventFilter(self) 65 | 66 | # def eventFilter(self, o, e): 67 | # # due to flag `X11BypassWindowManagerHint`, event `WindowDeactivate` doesn't work 68 | # if e.type() == QEvent.WindowDeactivate: 69 | # self._show_detail = False 70 | # self._stop_move = False 71 | # self.setWindowOpacity(0.5) 72 | # self._continenter.hide() 73 | # return False 74 | 75 | # return super().eventFilter(o, e) 76 | 77 | @property 78 | def show_paraphrase(self): 79 | return self._show_paraphrase 80 | 81 | @show_paraphrase.setter 82 | def show_paraphrase(self, value): 83 | self._show_paraphrase = value 84 | self.modified = True 85 | self.onModified.emit('show_paraphrase') 86 | 87 | @property 88 | def color(self): 89 | return self._color 90 | 91 | @color.setter 92 | def color(self, value): 93 | self._color = value 94 | self.modified = True 95 | self.onModified.emit('color') 96 | 97 | @property 98 | def cleared(self): 99 | return self._cleared 100 | 101 | @cleared.setter 102 | def cleared(self, value): 103 | self._cleared = value 104 | self.modified = True 105 | self.onModified.emit('cleared') 106 | 107 | def setWordQss(self): 108 | bg_color, font_color = utils.COLORS[self.color] 109 | self._word_label.setStyleSheet(f"QLabel{{background-color:rgb({bg_color}); color:rgb({font_color}); padding:5; border-radius:6px}}") 110 | 111 | def initUI(self): 112 | self.setWindowOpacity(utils.get_setting("danmaku_transparency")) 113 | 114 | word = WordLabel(self._word) 115 | if self.show_paraphrase: 116 | word.setText(word.text() + " " + self._paraphrase.splitlines()[0]) 117 | 118 | word.onEnter.connect(self.enterWordEvent) 119 | word.onLeave.connect(self.leaveWordEvent) 120 | word.onMousePress.connect(self.mousePressWordEvent) 121 | word.onMouseMove.connect(self.mouseMoveWordEvent) 122 | word.onMouseRelease.connect(self.mouseReleaseWordEvent) 123 | 124 | self._word_label = word 125 | 126 | head = QHBoxLayout() 127 | head.addWidget(word) 128 | head.addStretch(1) 129 | word.setFont(QFont("Consolas", 18)) 130 | 131 | body = QVBoxLayout() 132 | body.addLayout(head) 133 | self.setLayout(body) 134 | 135 | self.setWordQss() 136 | 137 | continenter = QWidget(self) 138 | continenter.setObjectName("continenter") 139 | continenter.setStyleSheet("#continenter{background-color:white; padding:5; border-radius:6px}") 140 | continenter.hide() 141 | self._continenter = continenter 142 | 143 | body.addStretch(1) 144 | body.addWidget(continenter) 145 | 146 | detail = QVBoxLayout() 147 | continenter.setLayout(detail) 148 | 149 | paraphrase = QLabel(self._paraphrase) 150 | paraphrase.setFont(QFont("Consolas", 15)) 151 | paraphrase.setStyleSheet("QLabel{color:black;}") 152 | paraphrase.setWordWrap(True) 153 | paraphrase.setMaximumWidth(300) 154 | 155 | detail.addWidget(paraphrase) 156 | 157 | rbtns = QHBoxLayout() 158 | for name, (color, _) in utils.COLORS.items(): 159 | rbtn = QRadioButton(None) 160 | qss = f""" 161 | QRadioButton::indicator {{ width:13px; height:13px; background-color:rgb({color}); border: 2px solid rgb({color}); }} 162 | QRadioButton::indicator:checked {{ border: 2px solid black; }} 163 | """ 164 | rbtn.setStyleSheet(qss) 165 | rbtn.setChecked(name == self.color) 166 | rbtn.toggled.connect(self.clickColor) 167 | rbtn.color = name 168 | 169 | rbtns.addWidget(rbtn) 170 | 171 | detail.addLayout(rbtns) 172 | 173 | btns = QHBoxLayout() 174 | 175 | clear = QPushButton("Clear") 176 | clear.setStyleSheet("QPushButton{color:black;}") 177 | clear.clicked.connect(self.clickClear) 178 | btns.addWidget(clear) 179 | 180 | switch_paraphrase = QPushButton("Hide Paraphrase" if self.show_paraphrase else "Show Paraphrase") 181 | switch_paraphrase.setStyleSheet("QPushButton{color:black;}") 182 | switch_paraphrase.clicked.connect(self.clickSwitch) 183 | btns.addWidget(switch_paraphrase) 184 | self._switch_paraphrase = switch_paraphrase 185 | 186 | detail.addLayout(btns) 187 | self._clear = clear 188 | 189 | self.show() 190 | 191 | def clickColor(self, e): 192 | if e: 193 | sender = self.sender() 194 | self.color = sender.color 195 | self.setWordQss() 196 | 197 | def clickClear(self): 198 | self.cleared = not self.cleared 199 | self._clear.setText("Redo" if self.cleared else "Clear") 200 | 201 | def clickSwitch(self): 202 | self.show_paraphrase = not self.show_paraphrase 203 | if self.show_paraphrase: 204 | self._word_label.setText(self._word + " " + self._paraphrase.splitlines()[0]) 205 | else: 206 | self._word_label.setText(self._word) 207 | 208 | self._switch_paraphrase.setText("Hide Paraphrase" if self.show_paraphrase else "Show Paraphrase") 209 | 210 | def enterWordEvent(self): 211 | self.setWindowOpacity(1) 212 | 213 | def leaveWordEvent(self): 214 | if not self._show_detail: 215 | self.setWindowOpacity(utils.get_setting("danmaku_transparency")) 216 | 217 | def mousePressWordEvent(self, e): 218 | if e.button() == Qt.LeftButton: 219 | self._press_point = e.globalPos() - self.pos() 220 | self._press_start = e.globalPos() 221 | e.accept() 222 | 223 | def mouseMoveWordEvent(self, e): 224 | if e.buttons() & Qt.LeftButton: 225 | self.move(e.globalPos() - self._press_point) 226 | e.accept() 227 | 228 | def mouseReleaseWordEvent(self, e): 229 | if e.button() != Qt.LeftButton: 230 | return 231 | if (e.globalPos() - self._press_start).manhattanLength() < 10: 232 | self._show_detail = not self._show_detail 233 | if self._show_detail: 234 | self._stop_move = True 235 | self._continenter.show() 236 | else: 237 | self._stop_move = False 238 | self._continenter.hide() 239 | self.adjustSize() 240 | 241 | def initPosition(self, y): 242 | self._timer = QTimer(self) 243 | self._timer.setTimerType(Qt.PreciseTimer) 244 | self._timer.timeout.connect(self.update) 245 | speed = utils.get_setting("danmaku_speed") 246 | delta = 1 247 | while round(delta / speed) < 17: 248 | delta += 1 249 | 250 | self._timer.start(round(delta / speed)) 251 | self._delta = delta 252 | 253 | w = QDesktopWidget().availableGeometry().width() 254 | self.move(w, y) 255 | 256 | def update(self): 257 | if self._stop_move: return 258 | x = self.x() - self._delta 259 | self.move(x, self.y()) 260 | if x < -self.width(): 261 | self._timer.stop() 262 | self.close() 263 | -------------------------------------------------------------------------------- /DWords/data/dictionary.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luyuhuang/DWords/cf25661dfb8223dd7ba035861eb8fc57b41f2573/DWords/data/dictionary.db -------------------------------------------------------------------------------- /DWords/db.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | import uuid 3 | import os 4 | from contextlib import contextmanager 5 | from .version import VERSIONs 6 | from .migrate import SQLs 7 | from . import real_path 8 | 9 | class DB: 10 | def __init__(self, database): 11 | self._conn = sqlite3.connect(database) 12 | self._in_cursor = False 13 | 14 | def getOne(self, sql, param=()): 15 | assert not self._in_cursor, "Cannot call get in cursor" 16 | cursor = self._conn.execute(sql, param) 17 | res = cursor.fetchone() 18 | cursor.close() 19 | self._conn.rollback() 20 | return res 21 | 22 | def getAll(self, sql, param=()): 23 | assert not self._in_cursor, "Cannot call get in cursor" 24 | cursor = self._conn.execute(sql, param) 25 | res = cursor.fetchall() 26 | cursor.close() 27 | self._conn.rollback() 28 | return res 29 | 30 | @contextmanager 31 | def cursor(self): 32 | assert not self._in_cursor, "Cannot nest open cursor" 33 | try: 34 | self._in_cursor = True 35 | cursor = self._conn.cursor() 36 | yield cursor 37 | except: 38 | self._conn.rollback() 39 | raise 40 | else: 41 | self._conn.commit() 42 | finally: 43 | cursor.close() 44 | self._in_cursor = False 45 | 46 | def close(self): 47 | self._conn.close() 48 | 49 | if os.name == "nt": 50 | data_dir = os.path.join(os.environ["USERPROFILE"], ".DWords") 51 | else: 52 | data_dir = os.path.join(os.environ["HOME"], ".DWords") 53 | 54 | if not os.path.exists(data_dir): 55 | os.makedirs(data_dir) 56 | 57 | user_db = DB(os.path.join(data_dir, "user.db")) 58 | dictionary_db = DB(real_path("data/dictionary.db")) 59 | 60 | def initialize(): 61 | if not user_db.getOne("select * from sqlite_master where type = 'table' and name = 'sys'"): 62 | with user_db.cursor() as c: 63 | c.executescript(f""" 64 | create table sys ( 65 | id varchar(128) primary key, 66 | value text not null default '' 67 | ); 68 | insert into sys values('version', '-1'); 69 | insert into sys values('uuid', '{uuid.uuid1()}'); 70 | """) 71 | 72 | version, = map(int, user_db.getOne("select value from sys where id = 'version'")) 73 | with user_db.cursor() as c: 74 | for v in VERSIONs[version + 1:]: 75 | if v in SQLs: 76 | c.executescript(SQLs[v]) 77 | 78 | c.execute("update sys set value = ? where id = 'version'", (len(VERSIONs) - 1,)) 79 | 80 | -------------------------------------------------------------------------------- /DWords/home.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtWidgets import * 2 | from PyQt5.QtGui import QIcon, QFont, QPixmap, QBrush, QColor, QKeyEvent, QTextCursor 3 | from PyQt5.QtCore import QTimer, Qt, QEvent, pyqtSignal 4 | from .danmaku import Danmaku 5 | from .db import user_db, dictionary_db 6 | from . import utils, real_path 7 | import random 8 | 9 | class WordEditor(QTextEdit): 10 | onCommitWord = pyqtSignal() 11 | 12 | def keyPressEvent(self, e): 13 | ignore = False 14 | if e.key() == Qt.Key_Return: 15 | if e.modifiers() == Qt.ControlModifier: 16 | self.onCommitWord.emit() 17 | else: 18 | text = self.toPlainText() 19 | if "\n" not in text: 20 | paraphrase = utils.consult(text) 21 | if paraphrase: 22 | self.setPlainText(text + "\n" + paraphrase) 23 | cursor = self.textCursor() 24 | start = cursor.position() + len(text) + 1 25 | end = len(self.toPlainText()) 26 | cursor.setPosition(start, QTextCursor.MoveAnchor) 27 | cursor.setPosition(end, QTextCursor.KeepAnchor) 28 | self.setTextCursor(cursor) 29 | 30 | ignore = True 31 | 32 | if not ignore: 33 | super().keyPressEvent(e) 34 | 35 | class Home(QWidget): 36 | onClickBurst = pyqtSignal() 37 | onClickSetting = pyqtSignal() 38 | onClickSync = pyqtSignal() 39 | 40 | def __init__(self): 41 | super().__init__() 42 | self._closing = False 43 | self._is_hid_paraphrase = False 44 | self._list_order = 'Time' 45 | 46 | self.initUI() 47 | 48 | self.show() 49 | 50 | def initUI(self): 51 | self.setWindowTitle("DWords") 52 | self.setWindowIcon(QIcon(real_path("img/logo.svg"))) 53 | self.setMinimumWidth(400) 54 | 55 | body = QVBoxLayout() 56 | self.setLayout(body) 57 | 58 | head = QHBoxLayout() 59 | icon = QLabel() 60 | icon.setPixmap( 61 | QPixmap(real_path("img/logo.svg")) 62 | .scaled(50, 50, transformMode=Qt.SmoothTransformation) 63 | ) 64 | head.addWidget(icon) 65 | 66 | title = QLabel("DWords") 67 | title.setFont(QFont("Consolas", 18)) 68 | title.font().setStyleStrategy(QFont.PreferAntialias) 69 | head.addWidget(title) 70 | head.addStretch(1) 71 | body.addLayout(head) 72 | body.addSpacing(8) 73 | 74 | lists = QTabWidget() 75 | lists.setMinimumHeight(300) 76 | 77 | def create_list(): 78 | tree = QTreeWidget() 79 | tree.setContextMenuPolicy(Qt.CustomContextMenu) 80 | tree.customContextMenuRequested.connect(self.listMenu) 81 | tree.itemClicked.connect(self.clickList) 82 | tree.itemDoubleClicked.connect(self.doubleClickList) 83 | tree.setColumnCount(2) 84 | tree.setHeaderLabels(["Word", "Paraphrase"]) 85 | return tree 86 | 87 | self._curr_words = create_list() 88 | self._cleared_words = create_list() 89 | self._all_words = create_list() 90 | self.initLists() 91 | 92 | lists.addTab(self._curr_words, "Current Words") 93 | lists.addTab(self._cleared_words, "Cleared Words") 94 | lists.addTab(self._all_words, "All Words") 95 | body.addWidget(lists) 96 | 97 | list_btns = QHBoxLayout() 98 | add = QPushButton("+") 99 | add.setFixedWidth(22) 100 | add.clicked.connect(self.clickAdd) 101 | hide_paraphrase = QCheckBox("Hide Paraphrase") 102 | hide_paraphrase.toggled.connect(self.clickHideParaphrase) 103 | order_by_time = QRadioButton("Time") 104 | order_by_time.setChecked(True) 105 | order_by_time.toggled.connect(self.clickOrder) 106 | order_by_word = QRadioButton("A-Z") 107 | order_by_word.toggled.connect(self.clickOrder) 108 | 109 | list_btns.addWidget(add) 110 | list_btns.addWidget(hide_paraphrase) 111 | list_btns.addStretch(1) 112 | list_btns.addWidget(QLabel("Order By:")) 113 | list_btns.addWidget(order_by_time) 114 | list_btns.addWidget(order_by_word) 115 | 116 | body.addLayout(list_btns) 117 | 118 | burst = QPushButton("Burst!") 119 | burst.clicked.connect(self.clickBurst) 120 | setting = QPushButton("Setting") 121 | setting.clicked.connect(self.clickSetting) 122 | sync = QPushButton("Sync") 123 | sync.clicked.connect(self.clickSync) 124 | self.sync_btn = sync 125 | 126 | btns = QHBoxLayout() 127 | btns.addStretch(1) 128 | btns.addWidget(burst) 129 | btns.addWidget(sync) 130 | btns.addWidget(setting) 131 | 132 | body.addLayout(btns) 133 | 134 | self._editor = self.setEditor() 135 | body.addWidget(self._editor) 136 | 137 | def setEditor(self): 138 | editor = QWidget(self) 139 | editor.hide() 140 | layout = QVBoxLayout() 141 | editor.setLayout(layout) 142 | 143 | word_editor = WordEditor() 144 | word_editor.setMinimumHeight(100) 145 | word_editor.onCommitWord.connect(self.commitWord) 146 | layout.addWidget(word_editor) 147 | self._word_editor = word_editor 148 | 149 | commit = QPushButton("Commit") 150 | commit.clicked.connect(self.commitWord) 151 | close = QPushButton("Close") 152 | close.clicked.connect(self.clickCloseEditor) 153 | 154 | btns = QHBoxLayout() 155 | btns.addStretch(1) 156 | btns.addWidget(commit) 157 | btns.addWidget(close) 158 | 159 | layout.addLayout(btns) 160 | 161 | return editor 162 | 163 | def showEditor(self, word=None, paraphrase=None): 164 | self._editor.show() 165 | if word is not None and paraphrase is not None: 166 | self._word_editor.setText(word + '\n' + paraphrase) 167 | 168 | def hideEditor(self): 169 | self._editor.hide() 170 | self._word_editor.clear() 171 | 172 | def commitWord(self): 173 | text = self._word_editor.toPlainText() 174 | while True: 175 | if len(text) == 0: break 176 | 177 | word, *paraphrase = text.splitlines() 178 | paraphrase = '\n'.join(paraphrase) 179 | if len(word) == 0 or len(paraphrase) == 0: break 180 | 181 | utils.add_words((word, paraphrase)) 182 | self.initLists() 183 | 184 | break 185 | 186 | self._word_editor.clear() 187 | 188 | def clickCloseEditor(self): 189 | self.hideEditor() 190 | # self.adjustSize() 191 | 192 | def clickBurst(self): 193 | self.onClickBurst.emit() 194 | 195 | def clickSetting(self): 196 | self.onClickSetting.emit() 197 | 198 | def clickSync(self): 199 | self.onClickSync.emit() 200 | 201 | def initLists(self): 202 | def create_item(word, paraphrase, cleared): 203 | item = QTreeWidgetItem() 204 | item.setText(0, word) 205 | item.setText(1, '' if self._is_hid_paraphrase else paraphrase.splitlines()[0]) 206 | item.setToolTip(1, '' if self._is_hid_paraphrase else paraphrase) 207 | item.cleared = cleared 208 | item.paraphrase = paraphrase 209 | if cleared: 210 | item.setForeground(0, QBrush(QColor(0x27ae60))) 211 | item.setForeground(1, QBrush(QColor(0x27ae60))) 212 | return item 213 | 214 | if self._list_order == "A-Z": 215 | order_by = "order by word" 216 | elif self._list_order == "Time": 217 | order_by = "order by time desc, word" 218 | 219 | self._curr_words.clear() 220 | for word, paraphrase in user_db.getAll("select word, paraphrase from words where cleared = 0 " + order_by): 221 | self._curr_words.addTopLevelItem(create_item(word, paraphrase, False)) 222 | 223 | self._cleared_words.clear() 224 | for word, paraphrase in user_db.getAll("select word, paraphrase from words where cleared = 1 " + order_by): 225 | self._cleared_words.addTopLevelItem(create_item(word, paraphrase, True)) 226 | 227 | self._all_words.clear() 228 | for info in user_db.getAll("select word, paraphrase, cleared from words " + order_by): 229 | self._all_words.addTopLevelItem(create_item(*info)) 230 | 231 | def clickOrder(self, e): 232 | if e: 233 | rbtn = self.sender() 234 | self._list_order = rbtn.text() 235 | self.initLists() 236 | 237 | def clickList(self, item): 238 | if not self._is_hid_paraphrase: return 239 | if item.text(1) == '': 240 | item.setText(1, item.paraphrase.splitlines()[0]) 241 | item.setToolTip(1, item.paraphrase) 242 | else: 243 | item.setText(1, '') 244 | item.setToolTip(1, '') 245 | 246 | def doubleClickList(self, item): 247 | if self._is_hid_paraphrase: return 248 | self.showEditor(item.text(0), item.paraphrase) 249 | 250 | def clickHideParaphrase(self, e): 251 | self._is_hid_paraphrase = e 252 | for list_ in (self._curr_words, self._cleared_words, self._all_words): 253 | it = QTreeWidgetItemIterator(list_) 254 | while it.value(): 255 | item = it.value() 256 | item.setText(1, '' if e else item.paraphrase.splitlines()[0]) 257 | item.setToolTip(1, '' if e else item.paraphrase) 258 | it += 1 259 | 260 | def listMenu(self, pos): 261 | list_ = self.sender() 262 | item = list_.itemAt(pos) 263 | if not item: return 264 | 265 | menu = QMenu(self) 266 | menu.word = item.text(0) 267 | menu.paraphrase = item.paraphrase 268 | menu.addAction("Edit").triggered.connect(self.clickMenu) 269 | menu.addAction("Redo" if item.cleared else "Clear").triggered.connect(self.clickMenu) 270 | menu.addAction("Delete").triggered.connect(self.clickMenu) 271 | menu.exec(list_.mapToGlobal(pos)) 272 | 273 | def clickMenu(self): 274 | action = self.sender() 275 | act = action.text() 276 | word = action.parent().word 277 | paraphrase = action.parent().paraphrase 278 | refresh = False 279 | if act == "Edit": 280 | self.showEditor(word, paraphrase) 281 | elif act == "Clear": 282 | utils.set_word_attribute(word, cleared=True) 283 | refresh = True 284 | elif act == "Redo": 285 | utils.set_word_attribute(word, cleared=False) 286 | refresh = True 287 | elif act == "Delete": 288 | reply = QMessageBox.question( 289 | self, 'Tips', "Are you sure you want to delete this word?", 290 | QMessageBox.Yes | QMessageBox.No, QMessageBox.No 291 | ) 292 | if reply == QMessageBox.Yes: 293 | utils.delete_words(word) 294 | refresh = True 295 | 296 | if refresh: 297 | self.initLists() 298 | 299 | def clickAdd(self): 300 | self.showEditor() 301 | 302 | def closeEvent(self, e): 303 | self.hide() 304 | e.ignore() 305 | -------------------------------------------------------------------------------- /DWords/img/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 19 | 21 | 39 | 41 | 42 | 44 | image/svg+xml 45 | 47 | 48 | 49 | 50 | 51 | 56 | 61 | 64 | 70 | 73 | 78 | 84 | 85 | 90 | 91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /DWords/launcher.py: -------------------------------------------------------------------------------- 1 | import random 2 | from PyQt5.QtWidgets import QDesktopWidget 3 | from PyQt5.QtCore import QTimer, QObject, pyqtSignal 4 | from .danmaku import Danmaku 5 | from .db import user_db 6 | from . import utils 7 | 8 | class Launcher(QObject): 9 | onChangeWordCleared = pyqtSignal(str) 10 | 11 | def __init__(self): 12 | super().__init__() 13 | self._danmakus = {} 14 | self._burst_words = set() 15 | self._timer = QTimer(self) 16 | self._timer.timeout.connect(self.newDanmaku) 17 | self._timer.start(utils.get_setting("danmaku_frequency")) 18 | 19 | def newDanmaku(self): 20 | if self._burst_words: 21 | word = random.choice(list(self._burst_words)) 22 | paraphrase, show_paraphrase, color = user_db.getOne( 23 | "select paraphrase, show_paraphrase, color from words where word = ?", (word,) 24 | ) 25 | self._burst_words.remove(word) 26 | else: 27 | info = utils.random_one_word(*self._danmakus.keys()) 28 | if not info: return 29 | word, paraphrase, show_paraphrase, color = info 30 | self._timer.setInterval(utils.get_setting("danmaku_frequency")) 31 | 32 | height = QDesktopWidget().availableGeometry().height() 33 | y = random.randrange(0, int(height / 2)) 34 | 35 | def onDanmaClose(): 36 | del self._danmakus[word] 37 | 38 | danmaku = Danmaku(word, paraphrase, y, show_paraphrase, color) 39 | danmaku.destroyed.connect(onDanmaClose) 40 | danmaku.onModified.connect(self.modifyWord) 41 | self._danmakus[word] = danmaku 42 | 43 | def modifyWord(self, attr): 44 | danmaku = self.sender() 45 | utils.set_word_attribute(danmaku._word, **{attr: getattr(danmaku, attr)}) 46 | 47 | if attr == "cleared": 48 | self.onChangeWordCleared.emit(danmaku._word) 49 | 50 | def clear(self): 51 | for danmaku in self._danmakus.values(): 52 | danmaku.destroyed.disconnect() 53 | danmaku.close() 54 | 55 | self._danmakus = {} 56 | 57 | def burst(self): 58 | if self._burst_words: return 59 | 60 | curr_words = list(self._danmakus.keys()) 61 | words = user_db.getAll("select word from words " 62 | f"where cleared = 0 and word not in ({','.join('?' * len(curr_words))})", 63 | curr_words 64 | ) 65 | self._burst_words = set(map(lambda e: e[0], words)) 66 | if not self._burst_words: return 67 | 68 | self._timer.setInterval(1500) 69 | -------------------------------------------------------------------------------- /DWords/mail.py: -------------------------------------------------------------------------------- 1 | import json 2 | import poplib 3 | import smtplib 4 | import poplib 5 | import logging 6 | from html_text import extract_text 7 | from email import encoders, policy 8 | from email.header import Header, decode_header 9 | from email.mime.text import MIMEText 10 | from email.utils import parseaddr, formataddr 11 | from email.parser import Parser, FeedParser 12 | from dateutil.parser import parse as parse_timestr 13 | from . import utils 14 | from .db import user_db 15 | from .async_thread import thread 16 | 17 | class Mail: 18 | def __init__(self): 19 | pass 20 | 21 | async def __aenter__(self): 22 | logging.debug("Connecting...") 23 | await self._connect() 24 | logging.debug("Connected") 25 | 26 | async def __aexit__(self, type, value, tb): 27 | self._smtp.quit() 28 | self._pop3.quit() 29 | del self._smtp 30 | del self._pop3 31 | logging.debug("Disconnected") 32 | 33 | @thread 34 | def _connect(self): 35 | self._smtp = smtplib.SMTP_SSL(self._smtp_server, smtplib.SMTP_SSL_PORT, timeout=30) 36 | self._smtp.helo(self._smtp_server) 37 | self._smtp.ehlo(self._smtp_server) 38 | self._smtp.login(self._email, self._password) 39 | self._pop3 = poplib.POP3_SSL(self._pop3_server, poplib.POP3_SSL_PORT, timeout=30) 40 | self._pop3.user(self._email) 41 | self._pop3.pass_(self._password) 42 | 43 | def connect(self): 44 | self._smtp_server = utils.get_setting("smtp_server") 45 | self._pop3_server = utils.get_setting("pop3_server") 46 | self._email = utils.get_setting("email") 47 | self._password = utils.get_setting("password") 48 | 49 | if None in (self._smtp_server, self._pop3_server, self._email, self._password): 50 | raise Exception("Incomplete email setting") 51 | 52 | return self 53 | 54 | @thread 55 | def _push(self, uuid, words): 56 | subject = "DWords synchronize" 57 | content = json.dumps(words) 58 | 59 | msg = MIMEText(content, "plain", "utf-8") 60 | msg["From"] = f"{uuid}<{self._email}>" 61 | msg["Subject"] = subject 62 | msg["To"] = self._email 63 | 64 | self._smtp.sendmail(self._email, [self._email], msg.as_string()) 65 | 66 | async def push(self, uuid, words): 67 | logging.debug("Pushing...") 68 | await self._push(uuid, words) 69 | logging.info(f"{len(words)} word(s) pushed") 70 | 71 | def _decode_str(self, s): 72 | value, charset = decode_header(s)[0] 73 | if charset: 74 | value = value.decode(charset) 75 | return value 76 | 77 | def _guess_charset(self, msg): 78 | charset = msg.get_charset() 79 | if charset is None: 80 | content_type = msg.get('Content-Type', '').lower() 81 | pos = content_type.find('charset=') 82 | if pos >= 0: 83 | charset = content_type[pos + 8:].strip() 84 | 85 | return charset 86 | 87 | def _parse_content(self, msg): 88 | content_type = msg.get_content_type() 89 | if content_type == "multipart/alternative": 90 | plain, html = None, None 91 | for part in msg.get_payload(): 92 | ct = part.get_content_type() 93 | if ct == "text/plain": 94 | plain = part 95 | break 96 | elif ct == "text/html": 97 | html = part 98 | 99 | if plain: 100 | return self._parse_content(plain) 101 | elif html: 102 | return self._parse_content(html) 103 | 104 | elif content_type == "text/plain": 105 | content = msg.get_payload(decode=True) 106 | charset = self._guess_charset(msg) 107 | if charset: 108 | content = content.decode(charset) 109 | 110 | return content 111 | 112 | elif content_type == "text/html": 113 | content = msg.get_payload(decode=True) 114 | charset = self._guess_charset(msg) 115 | if charset: 116 | content = content.decode(charset) 117 | 118 | return extract_text(content) 119 | 120 | @thread 121 | def _pop3_stat(self): 122 | return self._pop3.stat() 123 | 124 | @thread 125 | def _pop3_retr(self, i): 126 | return self._pop3.retr(i) 127 | 128 | async def pull(self, uuid): 129 | logging.debug("Getting mail count...") 130 | count, _ = await self._pop3_stat() 131 | logging.debug(f"Mail count: {count}") 132 | last_id = user_db.getOne("select value from sys where id = 'last_mail_id'") 133 | if last_id: 134 | last_id, = last_id 135 | 136 | get_count, read_count = 0, 0 137 | for i in range(count, max(0, count - 50), -1): 138 | logging.debug(f"Retrieving mail {i}") 139 | _, lines, _ = await self._pop3_retr(i) 140 | msg = Parser(policy=policy.default).parsestr(b"\n".join(lines).decode("utf-8")) 141 | 142 | try: 143 | msg_id = msg.get("Message-Id") 144 | except Exception as e: 145 | logging.warning(f"Error getting Message-Id. The mail[{i}] is ignored. Error message: {e}") 146 | continue 147 | 148 | logging.debug(f"Got mail: {msg_id}") 149 | get_count += 1 150 | 151 | if msg_id == last_id: break 152 | if i == count: 153 | with user_db.cursor() as c: 154 | c.execute("update sys set value = ? where id = 'last_mail_id'", (msg_id,)) 155 | c.execute("insert or ignore into sys(id, value) values('last_mail_id', ?)", (msg_id,)) 156 | 157 | subject = msg.get("Subject") 158 | if not subject: continue 159 | subject = self._decode_str(subject) 160 | if not subject.startswith("DWords"): continue 161 | 162 | if subject == "DWords synchronize": 163 | from_id, email = parseaddr(msg.get("From")) 164 | from_id = self._decode_str(from_id) 165 | if from_id != uuid and email == self._email: 166 | content = self._parse_content(msg) 167 | try: 168 | words = json.loads(content) 169 | yield words 170 | read_count += 1 171 | except: 172 | pass 173 | 174 | elif subject == "DWords add": 175 | time = int(parse_timestr(msg.get("Date")).timestamp() * 1000) 176 | content = self._parse_content(msg) 177 | word, paraphrase = "", [] 178 | tostr = lambda w, p: "\n".join(p) if p else utils.consult(w) or "" 179 | words = {} 180 | for line in content.splitlines(): 181 | line = line.strip() 182 | if not line: continue 183 | if line.startswith("~~~") or line.startswith("..."): 184 | break 185 | elif line.startswith("---") or line.startswith(",,,"): 186 | if word: 187 | words[word] = ("add", time, {"paraphrase": tostr(word, paraphrase)}) 188 | word, paraphrase = "", [] 189 | else: 190 | if not word: 191 | word = line 192 | else: 193 | paraphrase.append(line) 194 | if word: 195 | words[word] = ("add", time, {"paraphrase": tostr(word, paraphrase)}) 196 | 197 | yield words 198 | read_count += 1 199 | 200 | logging.debug(f"Got {get_count} mail(s) and accepted {read_count} mail(s)") 201 | -------------------------------------------------------------------------------- /DWords/migrate.py: -------------------------------------------------------------------------------- 1 | SQLs = {} 2 | 3 | SQLs['0.1.0'] = """ 4 | create table words ( 5 | word varchar(128) primary key, 6 | time integer not null default 7 | (cast((julianday('now') - 2440587.5) * 86400000 as integer)), 8 | modify_time integer not null default 9 | (cast((julianday('now') - 2440587.5) * 86400000 as integer)), 10 | paraphrase text not null default '', 11 | show_paraphrase bool, 12 | color varchar(32), 13 | cleared bool not null default 0 14 | ); 15 | 16 | create table setting ( 17 | key varchar(128) primary key, 18 | value text not null default 'None' 19 | ); 20 | 21 | create table sync_cache ( 22 | word varchar(128) primary key, 23 | op varchar(8), 24 | time integer 25 | ); 26 | """ 27 | -------------------------------------------------------------------------------- /DWords/setting.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtWidgets import * 2 | from PyQt5.QtGui import QIcon, QPixmap, QFont 3 | from PyQt5.QtCore import Qt 4 | from .version import VERSION 5 | from . import utils, real_path 6 | 7 | class Setting(QDialog): 8 | 9 | def __init__(self): 10 | super().__init__() 11 | self._data = {} 12 | 13 | self.initUI() 14 | self.show() 15 | 16 | def initUI(self): 17 | self.setWindowTitle("DWords - Setting") 18 | self.setWindowIcon(QIcon(real_path("img/logo.svg"))) 19 | self.setMinimumWidth(330) 20 | self.setAttribute(Qt.WA_DeleteOnClose) 21 | 22 | body = QVBoxLayout() 23 | self.setLayout(body) 24 | 25 | setting = QTabWidget() 26 | body.addWidget(setting) 27 | 28 | self._common_setting = QWidget() 29 | self._account_setting = QWidget() 30 | self._danmaku_setting = QWidget() 31 | self._about = QWidget() 32 | 33 | self.initCommonSetting() 34 | self.initAccountSetting() 35 | self.initDanmakuSetting() 36 | self.initAbout() 37 | 38 | setting.addTab(self._common_setting, "Common") 39 | setting.addTab(self._account_setting, "Account") 40 | setting.addTab(self._danmaku_setting, "Danmaku") 41 | setting.addTab(self._about, "About") 42 | 43 | btns = QHBoxLayout() 44 | ok = QPushButton("OK") 45 | ok.clicked.connect(self.clickOK) 46 | apply = QPushButton("Apply") 47 | apply.clicked.connect(self.clickApply) 48 | cancel = QPushButton("Cancel") 49 | cancel.clicked.connect(self.clickCancel) 50 | btns.addStretch(1) 51 | btns.addWidget(ok) 52 | btns.addWidget(apply) 53 | btns.addWidget(cancel) 54 | 55 | body.addLayout(btns) 56 | 57 | def initCommonSetting(self): 58 | widget = self._common_setting 59 | layout = QVBoxLayout() 60 | widget.setLayout(layout) 61 | 62 | dictionary = utils.get_setting("dictionary") 63 | label_dict = QLabel("Dictionary: ") 64 | combo_dict = QComboBox() 65 | items = list(utils.DICT_TABLE_MAP.keys()) 66 | combo_dict.addItems(items) 67 | combo_dict.setCurrentText(dictionary) 68 | combo_dict.currentIndexChanged.connect(self.dictChanged) 69 | dict_ = QHBoxLayout() 70 | dict_.addWidget(label_dict) 71 | dict_.addWidget(combo_dict) 72 | layout.addLayout(dict_) 73 | self._combo_dict = combo_dict 74 | 75 | sync_frequency = utils.get_setting("sync_frequency") 76 | label_sync_frequency = QLabel(f"Synchronous frequency: per {int(sync_frequency / 60000)}m") 77 | layout.addWidget(label_sync_frequency) 78 | self._label_sync_frequency = label_sync_frequency 79 | 80 | slider_sync_frequency = QSlider(Qt.Horizontal) 81 | slider_sync_frequency.setValue(utils.value2progress("sync_frequency", sync_frequency)) 82 | slider_sync_frequency.valueChanged.connect(self.syncFrequencyChanged) 83 | layout.addWidget(slider_sync_frequency) 84 | 85 | layout.addStretch(1) 86 | 87 | def dictChanged(self, index): 88 | self._data["dictionary"] = self._combo_dict.itemText(index) 89 | 90 | def syncFrequencyChanged(self, progress): 91 | value = utils.progress2value("sync_frequency", progress) 92 | self._label_sync_frequency.setText(f"Synchronous frequency: per {int(value / 60000)}m") 93 | self._data["sync_frequency"] = value 94 | 95 | def initAccountSetting(self): 96 | widget = self._account_setting 97 | layout = QVBoxLayout() 98 | widget.setLayout(layout) 99 | 100 | label_email = QLabel("Email: ") 101 | edit_email = QLineEdit(utils.get_setting("email")) 102 | edit_email.key = "email" 103 | edit_email.textChanged.connect(self.accountSettingChanged) 104 | 105 | label_password = QLabel("Password: ") 106 | edit_password = QLineEdit(utils.get_setting("password")) 107 | edit_password.key = "password" 108 | edit_password.setEchoMode(QLineEdit.Password) 109 | edit_password.textChanged.connect(self.accountSettingChanged) 110 | 111 | label_smtp = QLabel("SMTP server: ") 112 | edit_smtp = QLineEdit(utils.get_setting("smtp_server")) 113 | edit_smtp.key = "smtp_server" 114 | edit_smtp.textChanged.connect(self.accountSettingChanged) 115 | 116 | label_pop3 = QLabel("POP3 server: ") 117 | edit_pop3 = QLineEdit(utils.get_setting("pop3_server")) 118 | edit_pop3.key = "pop3_server" 119 | edit_pop3.textChanged.connect(self.accountSettingChanged) 120 | 121 | layout.addWidget(label_email) 122 | layout.addWidget(edit_email) 123 | layout.addWidget(label_password) 124 | layout.addWidget(edit_password) 125 | layout.addWidget(label_smtp) 126 | layout.addWidget(edit_smtp) 127 | layout.addWidget(label_pop3) 128 | layout.addWidget(edit_pop3) 129 | 130 | def accountSettingChanged(self, value): 131 | self._data[self.sender().key] = value 132 | 133 | def initDanmakuSetting(self): 134 | widget = self._danmaku_setting 135 | layout = QVBoxLayout() 136 | widget.setLayout(layout) 137 | 138 | speed = utils.get_setting("danmaku_speed") 139 | label_speed = QLabel("Speed: %.2f" % (speed * 100)) 140 | layout.addWidget(label_speed) 141 | self._label_speed = label_speed 142 | 143 | slider_speed = QSlider(Qt.Horizontal) 144 | slider_speed.setValue(utils.value2progress("danmaku_speed", speed)) 145 | slider_speed.valueChanged.connect(self.speedChanged) 146 | layout.addWidget(slider_speed) 147 | 148 | frequency = utils.get_setting("danmaku_frequency") 149 | label_frequency = QLabel("Frequency: per %.2fs" % (frequency / 1000)) 150 | layout.addWidget(label_frequency) 151 | self._label_frequency = label_frequency 152 | 153 | slider_frequency = QSlider(Qt.Horizontal) 154 | slider_frequency.setValue(utils.value2progress("danmaku_frequency", frequency)) 155 | slider_frequency.valueChanged.connect(self.frequencyChanged) 156 | layout.addWidget(slider_frequency) 157 | 158 | default_color = utils.get_setting("danmaku_default_color") 159 | label_color = QLabel("Default Color") 160 | layout.addWidget(label_color) 161 | colors = QHBoxLayout() 162 | for name, (color, _) in utils.COLORS.items(): 163 | rbtn = QRadioButton(None) 164 | qss = f""" 165 | QRadioButton::indicator {{ width:13px; height:13px; background-color:rgb({color}); border: 2px solid rgb({color}); }} 166 | QRadioButton::indicator:checked {{ border: 2px solid black; }} 167 | """ 168 | rbtn.setStyleSheet(qss) 169 | rbtn.setChecked(name == default_color) 170 | rbtn.toggled.connect(self.clickColor) 171 | rbtn.color = name 172 | 173 | colors.addWidget(rbtn) 174 | 175 | layout.addLayout(colors) 176 | 177 | transparency = utils.get_setting("danmaku_transparency") 178 | label_transparency = QLabel(f"Transparency: {int(transparency * 100)}%") 179 | layout.addWidget(label_transparency) 180 | self._label_transparency = label_transparency 181 | 182 | slider_transparency = QSlider(Qt.Horizontal) 183 | slider_transparency.setValue(utils.value2progress("danmaku_transparency", transparency)) 184 | slider_transparency.valueChanged.connect(self.transparencyChanged) 185 | layout.addWidget(slider_transparency) 186 | 187 | default_show_paraphrase = utils.get_setting("danmaku_default_show_paraphrase") 188 | check_show_paraphrase = QCheckBox("Default show paraphrase") 189 | check_show_paraphrase.setChecked(default_show_paraphrase) 190 | check_show_paraphrase.toggled.connect(self.clickShowParaphrase) 191 | layout.addWidget(check_show_paraphrase) 192 | 193 | def speedChanged(self, progress): 194 | value = utils.progress2value("danmaku_speed", progress) 195 | self._label_speed.setText("Speed: %.2f" % (value * 100)) 196 | self._data["danmaku_speed"] = value 197 | 198 | def frequencyChanged(self, progress): 199 | value = utils.progress2value("danmaku_frequency", progress) 200 | self._label_frequency.setText("Frequency: per %.2fs" % (value / 1000)) 201 | self._data["danmaku_frequency"] = value 202 | 203 | def clickColor(self, e): 204 | if e: 205 | sender = self.sender() 206 | self._data["danmaku_default_color"] = sender.color 207 | 208 | def transparencyChanged(self, progress): 209 | value = utils.progress2value("danmaku_transparency", progress) 210 | self._label_transparency.setText(f"Transparency: {int(value * 100)}%") 211 | self._data["danmaku_transparency"] = value 212 | 213 | def clickShowParaphrase(self, e): 214 | self._data["danmaku_default_show_paraphrase"] = e 215 | 216 | def initAbout(self): 217 | widget = self._about 218 | layout = QVBoxLayout() 219 | widget.setLayout(layout) 220 | 221 | def add_line(widget): 222 | line = QHBoxLayout() 223 | line.addStretch(1) 224 | line.addWidget(widget) 225 | line.addStretch(1) 226 | layout.addLayout(line) 227 | 228 | label_icon = QLabel() 229 | label_icon.setPixmap( 230 | QPixmap(real_path("img/logo.svg")) 231 | .scaled(60, 60, transformMode=Qt.SmoothTransformation) 232 | ) 233 | add_line(label_icon) 234 | 235 | label_title = QLabel("DWords") 236 | label_title.setFont(QFont("Consolas", 18)) 237 | add_line(label_title) 238 | 239 | label_version = QLabel("Homepage | Version: " + VERSION) 240 | label_version.setOpenExternalLinks(True) 241 | add_line(label_version) 242 | add_line(QLabel("Licence: GPLv3")) 243 | 244 | label_author = QLabel("Author: Luyu Huang") 245 | label_author.setOpenExternalLinks(True) 246 | add_line(label_author) 247 | 248 | layout.addStretch(1) 249 | 250 | def apply(self): 251 | for key, value in self._data.items(): 252 | utils.set_setting(key, value) 253 | 254 | def clickOK(self): 255 | self.apply() 256 | self.close() 257 | 258 | def clickCancel(self): 259 | self.close() 260 | 261 | def clickApply(self): 262 | self.apply() 263 | -------------------------------------------------------------------------------- /DWords/synchronizer.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from PyQt5.QtCore import QObject, pyqtSignal 3 | from . import utils 4 | from .mail import Mail 5 | from .db import user_db 6 | 7 | class Synchronizer(QObject): 8 | FIELDS = ["time", "paraphrase", "show_paraphrase", "color", "cleared"] 9 | onSynchronizeDone = pyqtSignal() 10 | 11 | def __init__(self): 12 | super().__init__() 13 | self.UUID, = user_db.getOne("select value from sys where id = 'uuid'") 14 | self._mail = Mail() 15 | self._synchronizing = False 16 | self._add_count = 0 17 | self._del_count = 0 18 | 19 | async def _sync(self): 20 | async with self.connect(): 21 | cache = user_db.getAll("select word, op, time from sync_cache") 22 | words = {} 23 | for word, op, time in cache: 24 | if op == "add": 25 | values = user_db.getOne(f"select {','.join(self.FIELDS)} from words " 26 | "where word = ?", (word,)) 27 | 28 | data = dict(zip(self.FIELDS, values)) 29 | words[word] = ("add", time, data) 30 | elif op == "del": 31 | words[word] = ("del", time, None) 32 | 33 | await self.publish(words) 34 | 35 | with user_db.cursor() as c: 36 | c.execute("delete from sync_cache") 37 | 38 | words = await self.collect() 39 | 40 | for word, (op, time, data) in words.items(): 41 | modify_time = user_db.getOne("select modify_time from words where word = ?", (word,)) 42 | if not modify_time or time > modify_time[0]: 43 | self.accept(word, op, time, data) 44 | 45 | self.onSynchronizeDone.emit() 46 | logging.info(f"Add {self._add_count} word(s) and delete {self._del_count} word(s)") 47 | 48 | async def sync(self): 49 | assert not self._synchronizing, "Synchronizing" 50 | self._synchronizing = True 51 | 52 | try: 53 | await self._sync() 54 | finally: 55 | self._synchronizing = False 56 | self._add_count, self._del_count = 0, 0 57 | 58 | def connect(self): 59 | return self._mail.connect() 60 | 61 | async def publish(self, words): 62 | if not words: return 63 | await self._mail.push(self.UUID, words) 64 | 65 | async def collect(self): 66 | word_time_map = {} 67 | ans = {} 68 | async for words in self._mail.pull(self.UUID): 69 | for word, (op, time, data) in words.items(): 70 | if time > word_time_map.get(word, 0): 71 | word_time_map[word] = time 72 | ans[word] = (op, time, data) 73 | 74 | return ans 75 | 76 | def accept(self, word, op, time, data): 77 | if op == "add": 78 | keys, values = zip(*data.items()) 79 | with user_db.cursor() as c: 80 | sql = "update words set " + \ 81 | ",".join(key + "=?" for key in keys) + \ 82 | ", modify_time = ? where word = ?" 83 | c.execute(sql, values + (time, word)) 84 | 85 | sql = "insert or ignore into words(word, modify_time, " + \ 86 | ",".join(keys) + ")" + \ 87 | " values(?,?," + ",".join("?" * len(keys)) + ")" 88 | c.execute(sql, (word, time) + values) 89 | 90 | self._add_count += 1 91 | 92 | elif op == "del": 93 | with user_db.cursor() as c: 94 | c.execute("delete from words where word = ?", (word,)) 95 | 96 | self._del_count += 1 97 | -------------------------------------------------------------------------------- /DWords/utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | import logging 4 | import locale 5 | from .db import user_db, dictionary_db 6 | 7 | logging.basicConfig(format="[%(levelname)s] %(asctime)s | %(message)s", 8 | level=logging.INFO) 9 | 10 | COLORS = { 11 | 'red': ("231,76,60", "255,255,255"), 12 | 'yellow': ("241,196,15", "255,255,255"), 13 | 'orange': ("243,156,18", "255,255,255"), 14 | 'cyan': ("26,188,156", "255,255,255"), 15 | 'green': ("46,204,113", "255,255,255"), 16 | 'blue': ("52,152,219", "255,255,255"), 17 | 'purple': ("155,89,182", "255,255,255"), 18 | 'dark': ("52,73,94", "255,255,255"), 19 | 'white': ("236,240,241", "0,0,0"), 20 | } 21 | 22 | def random_one_word(*exceptions): 23 | return user_db.getOne("select word, paraphrase, show_paraphrase, color " 24 | "from words where cleared = 0 and " 25 | f"word not in ({','.join('?' * len(exceptions))}) " 26 | "order by random() limit 1", exceptions 27 | ) 28 | 29 | def clock(): 30 | return int(time.time() * 1000) 31 | 32 | def _on_modify(c, word, op): 33 | now = clock() 34 | c.execute("update sync_cache set op = ?, time = ? " 35 | "where word = ?", (op, now, word)) 36 | c.execute("insert or ignore into sync_cache(word, op, time) " 37 | "values(?, ?, ?)", (word, op, now)) 38 | 39 | def add_words(*words): 40 | now = clock() 41 | with user_db.cursor() as c: 42 | for word, paraphrase in words: 43 | c.execute("update words set paraphrase = ?, modify_time = ?, cleared = 0 " 44 | "where word = ?", (paraphrase, now, word)) 45 | c.execute("insert or ignore into words(word, paraphrase) " 46 | "values(?, ?)", (word, paraphrase)) 47 | _on_modify(c, word, "add") 48 | 49 | def delete_words(*words): 50 | with user_db.cursor() as c: 51 | c.execute(f"delete from words where word in ({','.join('?' * len(words))})", words) 52 | for word in words: 53 | _on_modify(c, word, "del") 54 | 55 | def set_word_attribute(word, **kw): 56 | with user_db.cursor() as c: 57 | for k, v in kw.items(): 58 | c.execute(f"update words set {k} = ? where word = ?", (v, word)) 59 | 60 | now = clock() 61 | c.execute("update words set modify_time = ? where word = ?", (now, word)) 62 | _on_modify(c, word, "add") 63 | 64 | DEFAULT_SETTING = { 65 | "dictionary": "None", 66 | "sync_frequency": 1000 * 60 * 10, 67 | 68 | "email": None, 69 | "password": None, 70 | "smtp_server": None, 71 | "pop3_server": None, 72 | 73 | "danmaku_speed": 1 / 10, 74 | "danmaku_frequency": 6000, 75 | "danmaku_default_show_paraphrase": False, 76 | "danmaku_default_color": "white", 77 | "danmaku_transparency": 0.5, 78 | } 79 | 80 | try: 81 | lang, _ = locale.getdefaultlocale() 82 | if lang == "zh_CN": 83 | DEFAULT_SETTING["dictionary"] = "EN-CN" 84 | except: 85 | pass 86 | 87 | def get_setting(key): 88 | value = user_db.getOne("select value from setting where key = ?", (key,)) 89 | if value is None: return DEFAULT_SETTING[key] 90 | return eval(value[0]) 91 | 92 | def set_setting(key, value): 93 | value = repr(value) 94 | with user_db.cursor() as c: 95 | c.execute("update setting set value = ? where key = ?", (value, key)) 96 | c.execute("insert or ignore into setting(key, value) values(?, ?)", (key, value)) 97 | 98 | def is_sync(): 99 | count, = user_db.getOne("select count(key) from setting " 100 | "where key in ('email', 'password', 'smtp_server', 'pop3_server') " 101 | "and value != 'None'") 102 | 103 | return count == 4 104 | 105 | VALUE_RANGE = { 106 | "danmaku_speed": (1 / 18, 1 / 5), 107 | "danmaku_frequency": (3000, 20000), 108 | "danmaku_transparency": (0.3, 1.0), 109 | "sync_frequency": (5 * 60 * 1000, 30 * 60 * 1000), 110 | } 111 | 112 | def progress2value(key, progress): 113 | MIN, MAX = VALUE_RANGE[key] 114 | return MIN + (MAX - MIN) * (progress / 99) 115 | 116 | def value2progress(key, value): 117 | MIN, MAX = VALUE_RANGE[key] 118 | return int((value - MIN) / (MAX - MIN) * 99) 119 | 120 | DICT_TABLE_MAP = { 121 | "None": None, 122 | "EN-CN": "dict_en_cn" 123 | } 124 | def consult(word): 125 | table = DICT_TABLE_MAP.get(get_setting("dictionary")) 126 | if table is None: return None 127 | 128 | res = dictionary_db.getOne(f"select paraphrase from {table} where word = ?", (word,)) 129 | if res is None: return None 130 | return res[0] 131 | -------------------------------------------------------------------------------- /DWords/version.py: -------------------------------------------------------------------------------- 1 | VERSIONs = [ 2 | '0.1.0', 3 | '0.1.1', 4 | '0.1.2', 5 | '0.2.0', 6 | ] 7 | 8 | VERSION = VERSIONs[-1] 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.in 2 | include *.md 3 | include *.txt 4 | include LICENSE 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | > This repository is out of date. Try to use the new version: . 2 | > 3 | > 这个仓库已经过时了. 试试用新版本: . 4 | 5 |

logo

6 |

DWords

7 |

Show words as Danmaku on the screen to help you remember them.

8 | 9 | [![PyPI Version](https://img.shields.io/pypi/v/DWords.svg)](https://pypi.org/project/DWords/) 10 | [![Build Status](https://api.travis-ci.org/luyuhuang/DWords.svg?branch=dev)](https://travis-ci.org/luyuhuang/DWords) 11 | [![codecov](https://codecov.io/gh/luyuhuang/DWords/branch/dev/graph/badge.svg)](https://codecov.io/gh/luyuhuang/DWords) 12 | [![License](https://img.shields.io/github/license/luyuhuang/DWords)](https://github.com/luyuhuang/DWords/blob/dev/LICENSE) 13 | 14 | ![Screenshot](screenshot.png) 15 | 16 | [简体中文](README_cn.md) 17 | 18 | ## Introduction 19 | 20 | DWords is a cross platform tool which show words as Danmaku on your screen to help you memorize them. The main purpose of DWords is to help non-English-speaking people study English, but not limited to English, you can also use it to memorize anything you want. 21 | 22 | Features: 23 | 24 | - Open source and cross platform 25 | - Memorize words with ubiquitous Danmakus while using a computer 26 | - Synchronize between multiple devices by email 27 | - Add words using you phone by email 28 | - Included dictionaries 29 | 30 | ## Installation 31 | 32 | DWords is written by Python3, we recommend install via pip. Please make sure your machine has been installed Python3. 33 | 34 | Running the following in your terminal and DWords is installed: 35 | 36 | ```sh 37 | pip3 install DWords 38 | ``` 39 | 40 | You can also install from source code: 41 | 42 | ```sh 43 | git clone https://github.com/luyuhuang/DWords.git 44 | cd DWords 45 | git checkout master 46 | python3 setup.py install 47 | ``` 48 | 49 | If you don't know Python, we also provide binary distributions for Windows. Click [here](https://github.com/luyuhuang/DWords/releases) to download it. Caution, binary distributions may not be trusted by antivirus software. 50 | 51 | ## Usage 52 | 53 | Type `DWords` in your terminal to start DWords. If you download binary distributions, double click `DWords.exe` to start it. 54 | 55 | ### Add words 56 | 57 | Click "+" button and enter into the input box below to add words. The format is: the first line is the word, the second line is a short explanation and followed by detailed explanations. The short explanation can be displayed directly on the Danmaku, while the detailed explanations can only be displayed on the details panel. Detailed explanation is optional. For example: 58 | 59 | ``` 60 | word 61 | a unit of language 62 | a unit of language that native speakers can identify; a brief statement. 63 | ``` 64 | 65 | And then click "Commit" button to add it, or press Ctrl + Enter. 66 | 67 | ### Using dictionary 68 | 69 | DWords included dictionaries, click "Setting" button and set it in the "Common" tab. Currently only English-Chinese dictionary is supported, including more than 30,000 words. Once setting up the dictionary, the explanation will appear automatically when you press Enter while input a word. 70 | 71 | ### Synchronize 72 | 73 | DWords can synchronize words between multiple devices. In order to use this feature, you need to set up an account first. Click "Setting" button and set the email address, email password, SMTP server and POP3 server in the "Account" tab. DWords'll synchronize data via send emails, so we recommend using an infrequently used mailbox. 74 | 75 | ### Add words by email 76 | 77 | Once setting up the account, you can add add words by sending email to the set up mailbox. Edit a email using any email client, with the subject "DWords add" and the format of content is similar to add words, but you can add more than one word, separated by triple dash "---" or triple comma ",,,"; Triple swung dash "~~~" or triple dot "..." tells DWords it's the end. For example: 78 | 79 | ``` 80 | world 81 | 世界 82 | --- 83 | word 84 | 单词 85 | ,,, 86 | hello 87 | 你好 88 | ... 89 | The content after "..." will be ignored. 90 | ``` 91 | 92 | Then send the email to the mailbox you set up. 93 | 94 | If you have set up the dictionary, you don't have to specify the explanation and DWords'll consult the dictionary automatically. 95 | 96 | ## Contribution 97 | 98 | If you find any problems or have any suggestions, open an [issue](https://github.com/luyuhuang/DWords/issues). We also welcome all kinds of pull requests. 99 | 100 | ## License 101 | 102 | DWords is distributed under the [GPLv3 License](https://github.com/luyuhuang/DWords/blob/dev/LICENSE) because PyQt5 is licensed under the GPLv3 (so we have no choice). You can use it for free and modify it freely, but you have to open source with the same license when you modify it. 103 | -------------------------------------------------------------------------------- /README_cn.md: -------------------------------------------------------------------------------- 1 |

logo

2 |

DWords

3 |

把单词变成屏幕上的弹幕来帮助你记住单词

4 | 5 | [![PyPI version](https://img.shields.io/pypi/v/DWords.svg)](https://pypi.org/project/DWords/) 6 | [![Build Status](https://api.travis-ci.org/luyuhuang/DWords.svg?branch=dev)](https://travis-ci.org/luyuhuang/DWords) 7 | [![codecov](https://codecov.io/gh/luyuhuang/DWords/branch/dev/graph/badge.svg)](https://codecov.io/gh/luyuhuang/DWords) 8 | [![License](https://img.shields.io/github/license/luyuhuang/DWords)](https://github.com/luyuhuang/DWords/blob/dev/LICENSE) 9 | 10 | ![Screenshot](screenshot.png) 11 | 12 | ## 介绍 13 | 14 | DWords 是一个跨平台工具, 它可以把单词变成弹幕显示在屏幕上来帮助你记住单词. DWords 的主要目的是帮助非英语母语的人学习英语, 但不仅限于英语, 你还可以用它来记住任何你想要记住的东西. 15 | 16 | 特性: 17 | 18 | - 开源跨平台 19 | - 通过随处可见的弹幕在使用电脑的同时记住单词 20 | - 通过电子邮件在多台设备之间同步 21 | - 通过电子邮件用手机添加单词 22 | - 内置词典 23 | 24 | ## 安装 25 | 26 | DWords 使用 Python3 编写, 我们推荐通过 pip 安装. 先确保你的电脑上已安装好了 Python3. 27 | 28 | 打开终端运行以下命令, DWords 就安装好了: 29 | 30 | ```sh 31 | pip3 install DWords 32 | ``` 33 | 34 | 你也可以通过源码安装: 35 | 36 | ```sh 37 | git clone https://github.com/luyuhuang/DWords.git 38 | cd DWords 39 | git checkout master 40 | python3 setup.py install 41 | ``` 42 | 43 | 如果你不会 Python, 我们也提供了 Windows 系统的二进制版本. 点击[这里](https://github.com/luyuhuang/DWords/releases)下载. 注意, 二进制版本可能不被杀毒软件信任. 44 | 45 | ## 使用方法 46 | 47 | 在终端键入 `DWords` 以启动 DWords. 如果你是下载的二进制版本, 双击 `DWords.exe` 启动. 48 | 49 | ### 添加单词 50 | 51 | 点击 "+" 按钮并在下方的输入框中输入单词. 格式如下: 第一行为单词, 第二行为简要释义, 接下来的是详细释义. 简要释义能够直接显示在弹幕上, 但详细释义只能显示在详细面板中. 详细释义是可选的. 比如: 52 | 53 | ``` 54 | word 55 | 单词 56 | n. 单词;词;字; eg. Do not write more than 200 words. 57 | ``` 58 | 59 | 然后点击 "Commit" 按钮添加它, 或者按下 Ctrl + Enter. 60 | 61 | ### 使用词典 62 | 63 | DWords 内置了词典, 点击 "Setting" 按钮在 "Common" 页签中设置它. 目前仅支持英汉词典, 收录了超过 3 万词. 一旦设置了词典, 在输入单词时按下 Enter 键, 释义就会自动出现. 64 | 65 | ### 同步 66 | 67 | DWords 支持在多个客户端之间同步单词. 为了启用这一功能, 你需要先设置账户. 点击 "Setting" 按钮在 "Account" 页签中设置邮箱地址, 邮箱密码, SMTP 服务器和 POP3 服务器. DWords 会通过发送邮件来同步数据, 所以推荐使用一个不常用的邮箱. 68 | 69 | ### 通过邮件添加单词 70 | 71 | 设置好了账户后, 你就可以通过发送邮件来添加单词. 随意使用一个邮件客户端编辑邮件, 主题为 "DWords add", 内容的格式与添加单词类似, 不过可以添加多个单词, 单词之间用三连杠 "---" 或者三逗号 ",,," 分割; 三波浪线 "~~~" 或者三点号 "..." 表示结束. 例如: 72 | 73 | ``` 74 | world 75 | 世界 76 | --- 77 | word 78 | 单词 79 | ,,, 80 | hello 81 | 你好 82 | ... 83 | 在 ... 之后的内容都会被忽略 84 | ``` 85 | 86 | 然后把这封邮件发送到你设置好的邮箱即可. 87 | 88 | 如果你已经设置了词典, 就不必指定释义, DWords 会自动查阅词典. 89 | 90 | ## 贡献 91 | 92 | 如果你遇到了任何问题, 或者有任何建议, 请提交 [issue](https://github.com/luyuhuang/DWords/issues). 我们也欢迎各种 pull request. 93 | 94 | ## 许可证 95 | 96 | DWords 在 [GPLv3 许可](https://github.com/luyuhuang/DWords/blob/dev/LICENSE)下发布, 因为 PyQt5 是在 GPLv3 下发布的 (所以我们别无选择). 你可以免费使用, 自由修改, 但是当你修改它时你必须使用同样的许可证开源. 97 | -------------------------------------------------------------------------------- /logo.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luyuhuang/DWords/cf25661dfb8223dd7ba035861eb8fc57b41f2573/logo.ico -------------------------------------------------------------------------------- /logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 19 | 21 | 39 | 41 | 42 | 44 | image/svg+xml 45 | 47 | 48 | 49 | 50 | 51 | 56 | 61 | 64 | 70 | 73 | 78 | 84 | 85 | 90 | 91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | html-text==0.5.1 2 | PyQt5==5.13.2 3 | python-dateutil==2.8.1 4 | -------------------------------------------------------------------------------- /screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luyuhuang/DWords/cf25661dfb8223dd7ba035861eb8fc57b41f2573/screenshot.png -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from DWords.version import VERSION 2 | from setuptools import setup, find_packages 3 | import os 4 | 5 | here = os.path.dirname(__file__) 6 | 7 | with open(os.path.join(here, "README.md"), encoding="utf-8") as f: 8 | long_description = f.read() 9 | 10 | with open(os.path.join(here, "requirements.txt")) as f: 11 | install_requires = [ 12 | line.strip() for line in f.readlines() if not line.startswith("#") 13 | ] 14 | 15 | setup( 16 | name="DWords", 17 | version=VERSION, 18 | description="Show words as Danmaku in the screen to helps you remember them.", 19 | long_description=long_description, 20 | long_description_content_type="text/markdown", 21 | url="https://github.com/luyuhuang/DWords", 22 | keywords="danmaku words english-learning vocabulary pyqt5", 23 | license="GPLv3", 24 | author="Luyu Huang", 25 | author_email="luyu_huang@foxmail.com", 26 | 27 | packages=find_packages(), 28 | install_requires=install_requires, 29 | package_data={ 30 | '': ['img/*', 'data/*.db'] 31 | }, 32 | entry_points={ 33 | "gui_scripts": ["DWords=DWords.__main__:main"] 34 | }, 35 | 36 | classifiers=[ 37 | "Intended Audience :: Education", 38 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 39 | "Natural Language :: English", 40 | "Operating System :: Microsoft :: Windows", 41 | "Operating System :: MacOS", 42 | "Operating System :: POSIX :: Linux", 43 | "Programming Language :: Python :: 3.6", 44 | "Programming Language :: Python :: 3.7", 45 | "Programming Language :: Python :: 3.8", 46 | "Programming Language :: Python :: 3 :: Only", 47 | ] 48 | ) 49 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | from DWords import db 3 | 4 | db.initialize() 5 | -------------------------------------------------------------------------------- /tests/test_danmaku.py: -------------------------------------------------------------------------------- 1 | import random 2 | import uuid 3 | from PyQt5.QtCore import Qt 4 | from DWords import danmaku 5 | from DWords import utils 6 | from DWords.launcher import Launcher 7 | from DWords.db import user_db 8 | 9 | def test_add_words(): 10 | utils.add_words( 11 | (str(uuid.uuid1()), str(uuid.uuid1())), 12 | (str(uuid.uuid1()), str(uuid.uuid1())), 13 | ) 14 | 15 | def test_danmaku(qtbot): 16 | word, paraphrase, _, color = utils.random_one_word() 17 | widget = danmaku.Danmaku(word, paraphrase, random.randrange(0, 200), False, color) 18 | qtbot.addWidget(widget) 19 | 20 | assert widget._word_label.text() == word 21 | 22 | def test_danmaku_with_paraphrase(qtbot): 23 | word, paraphrase, _, color = utils.random_one_word() 24 | widget = danmaku.Danmaku(word, paraphrase, random.randrange(0, 200), True, color) 25 | qtbot.addWidget(widget) 26 | 27 | assert widget._word_label.text() == word + " " + paraphrase 28 | 29 | def test_danmaku_panel(qtbot): 30 | word, paraphrase, _, color = utils.random_one_word() 31 | widget = danmaku.Danmaku(word, paraphrase, random.randrange(0, 200), True, color) 32 | qtbot.addWidget(widget) 33 | 34 | assert widget._continenter.isVisible() == False 35 | qtbot.mouseClick(widget._word_label, Qt.LeftButton) 36 | assert widget._continenter.isVisible() == True 37 | qtbot.mouseClick(widget._word_label, Qt.LeftButton) 38 | assert widget._continenter.isVisible() == False 39 | 40 | def test_danmaku_clear(qtbot): 41 | word, paraphrase, _, color = utils.random_one_word() 42 | widget = danmaku.Danmaku(word, paraphrase, random.randrange(0, 200), True, color) 43 | qtbot.addWidget(widget) 44 | 45 | launcher = Launcher() 46 | widget.onModified.connect(launcher.modifyWord) 47 | 48 | assert widget._continenter.isVisible() == False 49 | qtbot.mouseClick(widget._word_label, Qt.LeftButton) 50 | assert widget._continenter.isVisible() == True 51 | 52 | qtbot.mouseClick(widget._clear, Qt.LeftButton) 53 | cleared, = user_db.getOne("select cleared from words where word = ?", (word,)) 54 | assert cleared 55 | -------------------------------------------------------------------------------- /tests/test_home.py: -------------------------------------------------------------------------------- 1 | import uuid 2 | from PyQt5.QtCore import Qt 3 | from DWords import home 4 | from DWords.db import user_db 5 | 6 | def test_home(qtbot): 7 | widget = home.Home() 8 | qtbot.addWidget(widget) 9 | 10 | assert widget.windowTitle() == "DWords" 11 | 12 | def test_add_word(qtbot): 13 | widget = home.Home() 14 | qtbot.addWidget(widget) 15 | 16 | add = widget.layout().itemAt(3).itemAt(0).widget() 17 | assert add.text() == "+" 18 | qtbot.mouseClick(add, Qt.LeftButton) 19 | 20 | assert widget._word_editor.isVisible() == True 21 | 22 | word = str(uuid.uuid1()) 23 | paraphrase = str(uuid.uuid1()) 24 | widget._word_editor.setPlainText(word + "\n" + paraphrase) 25 | 26 | commit = widget._editor.layout().itemAt(1).itemAt(1).widget() 27 | assert commit.text() == "Commit" 28 | 29 | qtbot.mouseClick(commit, Qt.LeftButton) 30 | res, = user_db.getOne("select paraphrase from words where word = ?", (word,)) 31 | assert res == paraphrase 32 | 33 | close = widget._editor.layout().itemAt(1).itemAt(2).widget() 34 | assert close.text() == "Close" 35 | qtbot.mouseClick(close, Qt.LeftButton) 36 | assert widget._word_editor.isVisible() == False 37 | -------------------------------------------------------------------------------- /tests/test_other.py: -------------------------------------------------------------------------------- 1 | import uuid 2 | from DWords import utils 3 | 4 | def test_del_word(): 5 | word, paraphrase = str(uuid.uuid1()), str(uuid.uuid1()) 6 | utils.add_words((word, paraphrase)) 7 | utils.delete_words(word) 8 | 9 | def test_dictionary(): 10 | assert utils.consult('apple') != '' 11 | -------------------------------------------------------------------------------- /tests/test_setting.py: -------------------------------------------------------------------------------- 1 | from DWords.setting import Setting 2 | 3 | def test_setting(qtbot): 4 | widget = Setting() 5 | qtbot.addWidget(widget) 6 | 7 | assert widget.windowTitle() == "DWords - Setting" 8 | -------------------------------------------------------------------------------- /tests/test_sync.py: -------------------------------------------------------------------------------- 1 | import os 2 | import uuid 3 | import time 4 | import poplib 5 | from PyQt5.QtCore import QThread 6 | from DWords.synchronizer import Synchronizer 7 | from DWords.db import user_db 8 | from DWords import utils 9 | from DWords import async_thread 10 | 11 | def test_set_account(): 12 | utils.set_setting("email", os.environ["MAIL_ADDR"]) 13 | utils.set_setting("password", os.environ["MAIL_PASSWORD"]) 14 | utils.set_setting("smtp_server", os.environ["SMTP_SERVER"]) 15 | utils.set_setting("pop3_server", os.environ["POP3_SERVER"]) 16 | 17 | def test_add_words(): 18 | utils.add_words( 19 | (str(uuid.uuid1()), str(uuid.uuid1())), 20 | (str(uuid.uuid1()), str(uuid.uuid1())), 21 | ) 22 | 23 | @async_thread.normal 24 | async def _sync(): 25 | synchronizer = Synchronizer() 26 | await synchronizer.sync() 27 | 28 | def _delete_mails(): 29 | pop3_server = utils.get_setting("pop3_server") 30 | email = utils.get_setting("email") 31 | password = utils.get_setting("password") 32 | 33 | pop3 = poplib.POP3_SSL(pop3_server, poplib.POP3_SSL_PORT, timeout=30) 34 | pop3.user(email) 35 | pop3.pass_(password) 36 | 37 | count, _ = pop3.stat() 38 | for i in range(1, count + 1): 39 | pop3.dele(i) 40 | 41 | pop3.quit() 42 | 43 | def test_sync(qtbot): 44 | _delete_mails() 45 | 46 | num, = user_db.getOne("select count(*) from sync_cache where op = 'add'") 47 | 48 | _sync() 49 | qtbot.waitUntil(lambda: not async_thread._coroutines, timeout=30000) 50 | assert user_db.getOne("select count(*) from sync_cache")[0] == 0 51 | 52 | with user_db.cursor() as c: 53 | c.execute("delete from words") 54 | c.execute("delete from sys where id = 'last_mail_id'") 55 | c.execute("update sys set value = ? where id = 'uuid'", (str(uuid.uuid1()),)) 56 | 57 | _sync() 58 | qtbot.waitUntil(lambda: not async_thread._coroutines, timeout=30000) 59 | assert user_db.getOne("select count(*) from words")[0] == num 60 | -------------------------------------------------------------------------------- /win.py: -------------------------------------------------------------------------------- 1 | from DWords.__main__ import main 2 | 3 | main() 4 | -------------------------------------------------------------------------------- /win.spec: -------------------------------------------------------------------------------- 1 | # -*- mode: python ; coding: utf-8 -*- 2 | 3 | block_cipher = None 4 | 5 | 6 | a = Analysis(['win.py', 7 | 'DWords/__init__.py', 8 | 'DWords/__main__.py', 9 | 'DWords/app.py', 10 | 'DWords/async_thread.py', 11 | 'DWords/danmaku.py', 12 | 'DWords/db.py', 13 | 'DWords/home.py', 14 | 'DWords/launcher.py', 15 | 'DWords/mail.py', 16 | 'DWords/migrate.py', 17 | 'DWords/setting.py', 18 | 'DWords/synchronizer.py', 19 | 'DWords/utils.py', 20 | 'DWords/version.py' 21 | ], 22 | binaries=[], 23 | datas=[('DWords/data/dictionary.db', 'DWords/data/'), ('DWords/img/logo.svg', 'DWords/img/')], 24 | hiddenimports=[], 25 | hookspath=[], 26 | runtime_hooks=[], 27 | excludes=[], 28 | win_no_prefer_redirects=False, 29 | win_private_assemblies=False, 30 | cipher=block_cipher, 31 | noarchive=False) 32 | pyz = PYZ(a.pure, a.zipped_data, 33 | cipher=block_cipher) 34 | exe = EXE(pyz, 35 | a.scripts, 36 | a.binaries, 37 | a.zipfiles, 38 | a.datas, 39 | [], 40 | name='DWords', 41 | debug=False, 42 | bootloader_ignore_signals=False, 43 | strip=False, 44 | upx=True, 45 | upx_exclude=[], 46 | runtime_tmpdir=None, 47 | console=False , icon='logo.ico') 48 | --------------------------------------------------------------------------------