From db37d29dc8dd2b8eab7a454a0d449152dcf22f5d Mon Sep 17 00:00:00 2001 From: emdee Date: Sun, 20 Nov 2022 18:15:46 +0000 Subject: [PATCH] add third_party --- .github/workflows/ci.yml | 43 ++ requirements.txt | 2 + toxygen/third_party/qweechat/__init__.py | 19 + toxygen/third_party/qweechat/about.py | 61 ++ toxygen/third_party/qweechat/about.py.diff | 27 + toxygen/third_party/qweechat/about.py.dst | 61 ++ toxygen/third_party/qweechat/buffer.py | 250 ++++++++ toxygen/third_party/qweechat/buffer.py.diff | 27 + toxygen/third_party/qweechat/buffer.py.dst | 248 ++++++++ toxygen/third_party/qweechat/chat.py | 142 +++++ toxygen/third_party/qweechat/chat.py.diff | 27 + toxygen/third_party/qweechat/chat.py.dst | 142 +++++ toxygen/third_party/qweechat/config.py | 136 +++++ toxygen/third_party/qweechat/config.py.dst | 136 +++++ toxygen/third_party/qweechat/connection.py | 122 ++++ .../third_party/qweechat/connection.py.diff | 27 + .../third_party/qweechat/connection.py.dst | 122 ++++ .../third_party/qweechat/data/icons/README | 41 ++ .../qweechat/data/icons/application-exit.png | Bin 0 -> 1760 bytes .../qweechat/data/icons/bullet_green_8x8.png | Bin 0 -> 384 bytes .../qweechat/data/icons/bullet_yellow_8x8.png | Bin 0 -> 375 bytes .../qweechat/data/icons/dialog-close.png | Bin 0 -> 813 bytes .../qweechat/data/icons/dialog-ok-apply.png | Bin 0 -> 597 bytes .../qweechat/data/icons/dialog-password.png | Bin 0 -> 713 bytes .../qweechat/data/icons/dialog-warning.png | Bin 0 -> 596 bytes .../qweechat/data/icons/document-save.png | Bin 0 -> 1263 bytes .../qweechat/data/icons/edit-find.png | Bin 0 -> 1705 bytes .../qweechat/data/icons/help-about.png | Bin 0 -> 1636 bytes .../qweechat/data/icons/network-connect.png | Bin 0 -> 1679 bytes .../data/icons/network-disconnect.png | Bin 0 -> 1276 bytes .../qweechat/data/icons/preferences-other.png | Bin 0 -> 1906 bytes .../qweechat/data/icons/weechat.png | Bin 0 -> 1782 bytes toxygen/third_party/qweechat/debug.py | 51 ++ toxygen/third_party/qweechat/debug.py.diff | 27 + toxygen/third_party/qweechat/debug.py.dst | 51 ++ toxygen/third_party/qweechat/input.py | 96 +++ toxygen/third_party/qweechat/input.py.diff | 27 + toxygen/third_party/qweechat/input.py.dst | 95 +++ toxygen/third_party/qweechat/network.py | 358 +++++++++++ toxygen/third_party/qweechat/network.py.diff | 27 + toxygen/third_party/qweechat/network.py.dst | 356 +++++++++++ toxygen/third_party/qweechat/preferences.py | 57 ++ .../third_party/qweechat/preferences.py.diff | 27 + .../third_party/qweechat/preferences.py.dst | 57 ++ toxygen/third_party/qweechat/qweechat.py | 555 ++++++++++++++++++ toxygen/third_party/qweechat/qweechat.py.diff | 27 + toxygen/third_party/qweechat/qweechat.py.dst | 542 +++++++++++++++++ toxygen/third_party/qweechat/version.py | 30 + .../third_party/qweechat/weechat/__init__.py | 19 + toxygen/third_party/qweechat/weechat/color.py | 201 +++++++ .../third_party/qweechat/weechat/protocol.py | 361 ++++++++++++ .../third_party/qweechat/weechat/testproto.py | 252 ++++++++ 52 files changed, 4849 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 requirements.txt create mode 100644 toxygen/third_party/qweechat/__init__.py create mode 100644 toxygen/third_party/qweechat/about.py create mode 100644 toxygen/third_party/qweechat/about.py.diff create mode 100644 toxygen/third_party/qweechat/about.py.dst create mode 100644 toxygen/third_party/qweechat/buffer.py create mode 100644 toxygen/third_party/qweechat/buffer.py.diff create mode 100644 toxygen/third_party/qweechat/buffer.py.dst create mode 100644 toxygen/third_party/qweechat/chat.py create mode 100644 toxygen/third_party/qweechat/chat.py.diff create mode 100644 toxygen/third_party/qweechat/chat.py.dst create mode 100644 toxygen/third_party/qweechat/config.py create mode 100644 toxygen/third_party/qweechat/config.py.dst create mode 100644 toxygen/third_party/qweechat/connection.py create mode 100644 toxygen/third_party/qweechat/connection.py.diff create mode 100644 toxygen/third_party/qweechat/connection.py.dst create mode 100644 toxygen/third_party/qweechat/data/icons/README create mode 100644 toxygen/third_party/qweechat/data/icons/application-exit.png create mode 100644 toxygen/third_party/qweechat/data/icons/bullet_green_8x8.png create mode 100644 toxygen/third_party/qweechat/data/icons/bullet_yellow_8x8.png create mode 100644 toxygen/third_party/qweechat/data/icons/dialog-close.png create mode 100644 toxygen/third_party/qweechat/data/icons/dialog-ok-apply.png create mode 100644 toxygen/third_party/qweechat/data/icons/dialog-password.png create mode 100644 toxygen/third_party/qweechat/data/icons/dialog-warning.png create mode 100644 toxygen/third_party/qweechat/data/icons/document-save.png create mode 100644 toxygen/third_party/qweechat/data/icons/edit-find.png create mode 100644 toxygen/third_party/qweechat/data/icons/help-about.png create mode 100644 toxygen/third_party/qweechat/data/icons/network-connect.png create mode 100644 toxygen/third_party/qweechat/data/icons/network-disconnect.png create mode 100644 toxygen/third_party/qweechat/data/icons/preferences-other.png create mode 100644 toxygen/third_party/qweechat/data/icons/weechat.png create mode 100644 toxygen/third_party/qweechat/debug.py create mode 100644 toxygen/third_party/qweechat/debug.py.diff create mode 100644 toxygen/third_party/qweechat/debug.py.dst create mode 100644 toxygen/third_party/qweechat/input.py create mode 100644 toxygen/third_party/qweechat/input.py.diff create mode 100644 toxygen/third_party/qweechat/input.py.dst create mode 100644 toxygen/third_party/qweechat/network.py create mode 100644 toxygen/third_party/qweechat/network.py.diff create mode 100644 toxygen/third_party/qweechat/network.py.dst create mode 100644 toxygen/third_party/qweechat/preferences.py create mode 100644 toxygen/third_party/qweechat/preferences.py.diff create mode 100644 toxygen/third_party/qweechat/preferences.py.dst create mode 100644 toxygen/third_party/qweechat/qweechat.py create mode 100644 toxygen/third_party/qweechat/qweechat.py.diff create mode 100644 toxygen/third_party/qweechat/qweechat.py.dst create mode 100644 toxygen/third_party/qweechat/version.py create mode 100644 toxygen/third_party/qweechat/weechat/__init__.py create mode 100644 toxygen/third_party/qweechat/weechat/color.py create mode 100644 toxygen/third_party/qweechat/weechat/protocol.py create mode 100644 toxygen/third_party/qweechat/weechat/testproto.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..65f74dc --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,43 @@ +name: CI + +on: + - push + - pull_request + +jobs: + + build: + + strategy: + matrix: + python-version: + - "3.7" + - "3.8" + - "3.9" + - "3.10" + + name: Python ${{ matrix.python-version }} + runs-on: ubuntu-20.04 + + steps: + + - uses: actions/checkout@v2 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + + - name: Install dependencies + run: | + pip install -r requirements.txt + pip install bandit flake8 pylint + + - name: Lint with flake8 + run: make flake8 + + # - name: Lint with pylint + # run: make pylint + + - name: Lint with bandit + run: make bandit diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..c698f7e --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +PyQt5 + diff --git a/toxygen/third_party/qweechat/__init__.py b/toxygen/third_party/qweechat/__init__.py new file mode 100644 index 0000000..f510618 --- /dev/null +++ b/toxygen/third_party/qweechat/__init__.py @@ -0,0 +1,19 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# diff --git a/toxygen/third_party/qweechat/about.py b/toxygen/third_party/qweechat/about.py new file mode 100644 index 0000000..ac28af0 --- /dev/null +++ b/toxygen/third_party/qweechat/about.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# +# about.py - about dialog box +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +"""About dialog box.""" + +from PyQt5 import QtCore, QtWidgets as QtGui + +from qweechat.version import qweechat_version + + +class AboutDialog(QtGui.QDialog): + """About dialog.""" + + def __init__(self, app_name, author, weechat_site, *args): + QtGui.QDialog.__init__(*(self,) + args) + self.setModal(True) + self.setWindowTitle('About') + + close_button = QtGui.QPushButton('Close') + close_button.pressed.connect(self.close) + + hbox = QtGui.QHBoxLayout() + hbox.addStretch(1) + hbox.addWidget(close_button) + hbox.addStretch(1) + + vbox = QtGui.QVBoxLayout() + messages = [ + f'{app_name} {qweechat_version()}', + f'© 2011-2022 {author}', + '', + f'{weechat_site}', + '', + ] + for msg in messages: + label = QtGui.QLabel(msg) + label.setAlignment(QtCore.Qt.AlignHCenter) + vbox.addWidget(label) + vbox.addLayout(hbox) + + self.setLayout(vbox) + self.show() diff --git a/toxygen/third_party/qweechat/about.py.diff b/toxygen/third_party/qweechat/about.py.diff new file mode 100644 index 0000000..9fbe245 --- /dev/null +++ b/toxygen/third_party/qweechat/about.py.diff @@ -0,0 +1,27 @@ +*** about.py.dst 2022-11-19 18:31:51.000000000 +0000 +--- about.py 2022-11-19 18:32:41.000000000 +0000 +*************** +*** 20,30 **** + # along with QWeeChat. If not, see . + # + + """About dialog box.""" + +! from PySide6 import QtCore, QtWidgets as QtGui + + from qweechat.version import qweechat_version + + + class AboutDialog(QtGui.QDialog): +--- 20,30 ---- + # along with QWeeChat. If not, see . + # + + """About dialog box.""" + +! from PyQt5 import QtCore, QtWidgets as QtGui + + from qweechat.version import qweechat_version + + + class AboutDialog(QtGui.QDialog): diff --git a/toxygen/third_party/qweechat/about.py.dst b/toxygen/third_party/qweechat/about.py.dst new file mode 100644 index 0000000..01b7605 --- /dev/null +++ b/toxygen/third_party/qweechat/about.py.dst @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# +# about.py - about dialog box +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +"""About dialog box.""" + +from PySide6 import QtCore, QtWidgets as QtGui + +from qweechat.version import qweechat_version + + +class AboutDialog(QtGui.QDialog): + """About dialog.""" + + def __init__(self, app_name, author, weechat_site, *args): + QtGui.QDialog.__init__(*(self,) + args) + self.setModal(True) + self.setWindowTitle('About') + + close_button = QtGui.QPushButton('Close') + close_button.pressed.connect(self.close) + + hbox = QtGui.QHBoxLayout() + hbox.addStretch(1) + hbox.addWidget(close_button) + hbox.addStretch(1) + + vbox = QtGui.QVBoxLayout() + messages = [ + f'{app_name} {qweechat_version()}', + f'© 2011-2022 {author}', + '', + f'{weechat_site}', + '', + ] + for msg in messages: + label = QtGui.QLabel(msg) + label.setAlignment(QtCore.Qt.AlignHCenter) + vbox.addWidget(label) + vbox.addLayout(hbox) + + self.setLayout(vbox) + self.show() diff --git a/toxygen/third_party/qweechat/buffer.py b/toxygen/third_party/qweechat/buffer.py new file mode 100644 index 0000000..b51afd6 --- /dev/null +++ b/toxygen/third_party/qweechat/buffer.py @@ -0,0 +1,250 @@ +# -*- coding: utf-8 -*- +# +# buffer.py - management of WeeChat buffers/nicklist +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +"""Management of WeeChat buffers/nicklist.""" + +from pkg_resources import resource_filename + +from PyQt5 import QtCore, QtGui, QtWidgets +from PyQt5.QtCore import pyqtSignal +Signal = pyqtSignal + +from qweechat.chat import ChatTextEdit +from qweechat.input import InputLineEdit +from qweechat.weechat import color + + +class GenericListWidget(QtWidgets.QListWidget): + """Generic QListWidget with dynamic size.""" + + def __init__(self, *args): + super().__init__(*args) + self.setMaximumWidth(100) + self.setTextElideMode(QtCore.Qt.ElideNone) + self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) + self.setFocusPolicy(QtCore.Qt.NoFocus) + pal = self.palette() + pal.setColor(QtGui.QPalette.Highlight, QtGui.QColor('#ddddff')) + pal.setColor(QtGui.QPalette.HighlightedText, QtGui.QColor('black')) + self.setPalette(pal) + + def auto_resize(self): + size = self.sizeHintForColumn(0) + if size > 0: + size += 4 + self.setMaximumWidth(size) + + def clear(self, *args): + """Re-implement clear to set dynamic size after clear.""" + QtWidgets.QListWidget.clear(*(self,) + args) + self.auto_resize() + + def addItem(self, *args): + """Re-implement addItem to set dynamic size after add.""" + QtWidgets.QListWidget.addItem(*(self,) + args) + self.auto_resize() + + def insertItem(self, *args): + """Re-implement insertItem to set dynamic size after insert.""" + QtWidgets.QListWidget.insertItem(*(self,) + args) + self.auto_resize() + + +class BufferListWidget(GenericListWidget): + """Widget with list of buffers.""" + + def switch_prev_buffer(self): + if self.currentRow() > 0: + self.setCurrentRow(self.currentRow() - 1) + else: + self.setCurrentRow(self.count() - 1) + + def switch_next_buffer(self): + if self.currentRow() < self.count() - 1: + self.setCurrentRow(self.currentRow() + 1) + else: + self.setCurrentRow(0) + + +class BufferWidget(QtWidgets.QWidget): + """ + Widget with (from top to bottom): + title, chat + nicklist (optional) + prompt/input. + """ + + def __init__(self, display_nicklist=False): + super().__init__() + + # title + self.title = QtWidgets.QLineEdit() + self.title.setFocusPolicy(QtCore.Qt.NoFocus) + + # splitter with chat + nicklist + self.chat_nicklist = QtWidgets.QSplitter() + self.chat_nicklist.setSizePolicy(QtWidgets.QSizePolicy.Expanding, + QtWidgets.QSizePolicy.Expanding) + self.chat = ChatTextEdit(debug=False) + self.chat_nicklist.addWidget(self.chat) + self.nicklist = GenericListWidget() + if not display_nicklist: + self.nicklist.setVisible(False) + self.chat_nicklist.addWidget(self.nicklist) + + # prompt + input + self.hbox_edit = QtWidgets.QHBoxLayout() + self.hbox_edit.setContentsMargins(0, 0, 0, 0) + self.hbox_edit.setSpacing(0) + self.input = InputLineEdit(self.chat) + self.hbox_edit.addWidget(self.input) + prompt_input = QtWidgets.QWidget() + prompt_input.setLayout(self.hbox_edit) + + # vbox with title + chat/nicklist + prompt/input + vbox = QtWidgets.QVBoxLayout() + vbox.setContentsMargins(0, 0, 0, 0) + vbox.setSpacing(0) + vbox.addWidget(self.title) + vbox.addWidget(self.chat_nicklist) + vbox.addWidget(prompt_input) + + self.setLayout(vbox) + + def set_title(self, title): + """Set buffer title.""" + self.title.clear() + if title is not None: + self.title.setText(title) + + def set_prompt(self, prompt): + """Set prompt.""" + if self.hbox_edit.count() > 1: + self.hbox_edit.takeAt(0) + if prompt is not None: + label = QtWidgets.QLabel(prompt) + label.setContentsMargins(0, 0, 5, 0) + self.hbox_edit.insertWidget(0, label) + + +class Buffer(QtCore.QObject): + """A WeeChat buffer.""" + + bufferInput = Signal(str, str) + + def __init__(self, data=None): + QtCore.QObject.__init__(self) + self.data = data or {} + self.nicklist = {} + self.widget = BufferWidget(display_nicklist=self.data.get('nicklist', + 0)) + self.update_title() + self.update_prompt() + self.widget.input.textSent.connect(self.input_text_sent) + + def pointer(self): + """Return pointer on buffer.""" + return self.data.get('__path', [''])[0] + + def update_title(self): + """Update title.""" + try: + self.widget.set_title( + color.remove(self.data['title'])) + except Exception: # noqa: E722 + # TODO: Debug print the exception to be fixed. + # traceback.print_exc() + self.widget.set_title(None) + + def update_prompt(self): + """Update prompt.""" + try: + self.widget.set_prompt(self.data['local_variables']['nick']) + except Exception: # noqa: E722 + self.widget.set_prompt(None) + + def input_text_sent(self, text): + """Called when text has to be sent to buffer.""" + if self.data: + self.bufferInput.emit(self.data['full_name'], text) + + def nicklist_add_item(self, parent, group, prefix, name, visible): + """Add a group/nick in nicklist.""" + if group: + self.nicklist[name] = { + 'visible': visible, + 'nicks': [] + } + else: + self.nicklist[parent]['nicks'].append({ + 'prefix': prefix, + 'name': name, + 'visible': visible, + }) + + def nicklist_remove_item(self, parent, group, name): + """Remove a group/nick from nicklist.""" + if group: + if name in self.nicklist: + del self.nicklist[name] + else: + if parent in self.nicklist: + self.nicklist[parent]['nicks'] = [ + nick for nick in self.nicklist[parent]['nicks'] + if nick['name'] != name + ] + + def nicklist_update_item(self, parent, group, prefix, name, visible): + """Update a group/nick in nicklist.""" + if group: + if name in self.nicklist: + self.nicklist[name]['visible'] = visible + else: + if parent in self.nicklist: + for nick in self.nicklist[parent]['nicks']: + if nick['name'] == name: + nick['prefix'] = prefix + nick['visible'] = visible + break + + def nicklist_refresh(self): + """Refresh nicklist.""" + self.widget.nicklist.clear() + for group in sorted(self.nicklist): + for nick in sorted(self.nicklist[group]['nicks'], + key=lambda n: n['name']): + prefix_color = { + '': '', + ' ': '', + '+': 'yellow', + } + col = prefix_color.get(nick['prefix'], 'green') + if col: + icon = QtGui.QIcon( + resource_filename(__name__, + 'data/icons/bullet_%s_8x8.png' % + col)) + else: + pixmap = QtGui.QPixmap(8, 8) + pixmap.fill() + icon = QtGui.QIcon(pixmap) + item = QtWidgets.QListWidgetItem(icon, nick['name']) + self.widget.nicklist.addItem(item) + self.widget.nicklist.setVisible(True) diff --git a/toxygen/third_party/qweechat/buffer.py.diff b/toxygen/third_party/qweechat/buffer.py.diff new file mode 100644 index 0000000..2965c6f --- /dev/null +++ b/toxygen/third_party/qweechat/buffer.py.diff @@ -0,0 +1,27 @@ +*** buffer.py.dst 2022-11-19 18:31:51.000000000 +0000 +--- buffer.py 2022-11-19 18:32:41.000000000 +0000 +*************** +*** 22,32 **** + + """Management of WeeChat buffers/nicklist.""" + + from pkg_resources import resource_filename + +! from PySide6 import QtCore, QtGui, QtWidgets + + from qweechat.chat import ChatTextEdit + from qweechat.input import InputLineEdit + from qweechat.weechat import color + +--- 22,32 ---- + + """Management of WeeChat buffers/nicklist.""" + + from pkg_resources import resource_filename + +! from PyQt5 import QtCore, QtGui, QtWidgets + + from qweechat.chat import ChatTextEdit + from qweechat.input import InputLineEdit + from qweechat.weechat import color + diff --git a/toxygen/third_party/qweechat/buffer.py.dst b/toxygen/third_party/qweechat/buffer.py.dst new file mode 100644 index 0000000..2f6e32f --- /dev/null +++ b/toxygen/third_party/qweechat/buffer.py.dst @@ -0,0 +1,248 @@ +# -*- coding: utf-8 -*- +# +# buffer.py - management of WeeChat buffers/nicklist +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +"""Management of WeeChat buffers/nicklist.""" + +from pkg_resources import resource_filename + +from PySide6 import QtCore, QtGui, QtWidgets + +from qweechat.chat import ChatTextEdit +from qweechat.input import InputLineEdit +from qweechat.weechat import color + + +class GenericListWidget(QtWidgets.QListWidget): + """Generic QListWidget with dynamic size.""" + + def __init__(self, *args): + super().__init__(*args) + self.setMaximumWidth(100) + self.setTextElideMode(QtCore.Qt.ElideNone) + self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) + self.setFocusPolicy(QtCore.Qt.NoFocus) + pal = self.palette() + pal.setColor(QtGui.QPalette.Highlight, QtGui.QColor('#ddddff')) + pal.setColor(QtGui.QPalette.HighlightedText, QtGui.QColor('black')) + self.setPalette(pal) + + def auto_resize(self): + size = self.sizeHintForColumn(0) + if size > 0: + size += 4 + self.setMaximumWidth(size) + + def clear(self, *args): + """Re-implement clear to set dynamic size after clear.""" + QtWidgets.QListWidget.clear(*(self,) + args) + self.auto_resize() + + def addItem(self, *args): + """Re-implement addItem to set dynamic size after add.""" + QtWidgets.QListWidget.addItem(*(self,) + args) + self.auto_resize() + + def insertItem(self, *args): + """Re-implement insertItem to set dynamic size after insert.""" + QtWidgets.QListWidget.insertItem(*(self,) + args) + self.auto_resize() + + +class BufferListWidget(GenericListWidget): + """Widget with list of buffers.""" + + def switch_prev_buffer(self): + if self.currentRow() > 0: + self.setCurrentRow(self.currentRow() - 1) + else: + self.setCurrentRow(self.count() - 1) + + def switch_next_buffer(self): + if self.currentRow() < self.count() - 1: + self.setCurrentRow(self.currentRow() + 1) + else: + self.setCurrentRow(0) + + +class BufferWidget(QtWidgets.QWidget): + """ + Widget with (from top to bottom): + title, chat + nicklist (optional) + prompt/input. + """ + + def __init__(self, display_nicklist=False): + super().__init__() + + # title + self.title = QtWidgets.QLineEdit() + self.title.setFocusPolicy(QtCore.Qt.NoFocus) + + # splitter with chat + nicklist + self.chat_nicklist = QtWidgets.QSplitter() + self.chat_nicklist.setSizePolicy(QtWidgets.QSizePolicy.Expanding, + QtWidgets.QSizePolicy.Expanding) + self.chat = ChatTextEdit(debug=False) + self.chat_nicklist.addWidget(self.chat) + self.nicklist = GenericListWidget() + if not display_nicklist: + self.nicklist.setVisible(False) + self.chat_nicklist.addWidget(self.nicklist) + + # prompt + input + self.hbox_edit = QtWidgets.QHBoxLayout() + self.hbox_edit.setContentsMargins(0, 0, 0, 0) + self.hbox_edit.setSpacing(0) + self.input = InputLineEdit(self.chat) + self.hbox_edit.addWidget(self.input) + prompt_input = QtWidgets.QWidget() + prompt_input.setLayout(self.hbox_edit) + + # vbox with title + chat/nicklist + prompt/input + vbox = QtWidgets.QVBoxLayout() + vbox.setContentsMargins(0, 0, 0, 0) + vbox.setSpacing(0) + vbox.addWidget(self.title) + vbox.addWidget(self.chat_nicklist) + vbox.addWidget(prompt_input) + + self.setLayout(vbox) + + def set_title(self, title): + """Set buffer title.""" + self.title.clear() + if title is not None: + self.title.setText(title) + + def set_prompt(self, prompt): + """Set prompt.""" + if self.hbox_edit.count() > 1: + self.hbox_edit.takeAt(0) + if prompt is not None: + label = QtWidgets.QLabel(prompt) + label.setContentsMargins(0, 0, 5, 0) + self.hbox_edit.insertWidget(0, label) + + +class Buffer(QtCore.QObject): + """A WeeChat buffer.""" + + bufferInput = QtCore.Signal(str, str) + + def __init__(self, data=None): + QtCore.QObject.__init__(self) + self.data = data or {} + self.nicklist = {} + self.widget = BufferWidget(display_nicklist=self.data.get('nicklist', + 0)) + self.update_title() + self.update_prompt() + self.widget.input.textSent.connect(self.input_text_sent) + + def pointer(self): + """Return pointer on buffer.""" + return self.data.get('__path', [''])[0] + + def update_title(self): + """Update title.""" + try: + self.widget.set_title( + color.remove(self.data['title'])) + except Exception: # noqa: E722 + # TODO: Debug print the exception to be fixed. + # traceback.print_exc() + self.widget.set_title(None) + + def update_prompt(self): + """Update prompt.""" + try: + self.widget.set_prompt(self.data['local_variables']['nick']) + except Exception: # noqa: E722 + self.widget.set_prompt(None) + + def input_text_sent(self, text): + """Called when text has to be sent to buffer.""" + if self.data: + self.bufferInput.emit(self.data['full_name'], text) + + def nicklist_add_item(self, parent, group, prefix, name, visible): + """Add a group/nick in nicklist.""" + if group: + self.nicklist[name] = { + 'visible': visible, + 'nicks': [] + } + else: + self.nicklist[parent]['nicks'].append({ + 'prefix': prefix, + 'name': name, + 'visible': visible, + }) + + def nicklist_remove_item(self, parent, group, name): + """Remove a group/nick from nicklist.""" + if group: + if name in self.nicklist: + del self.nicklist[name] + else: + if parent in self.nicklist: + self.nicklist[parent]['nicks'] = [ + nick for nick in self.nicklist[parent]['nicks'] + if nick['name'] != name + ] + + def nicklist_update_item(self, parent, group, prefix, name, visible): + """Update a group/nick in nicklist.""" + if group: + if name in self.nicklist: + self.nicklist[name]['visible'] = visible + else: + if parent in self.nicklist: + for nick in self.nicklist[parent]['nicks']: + if nick['name'] == name: + nick['prefix'] = prefix + nick['visible'] = visible + break + + def nicklist_refresh(self): + """Refresh nicklist.""" + self.widget.nicklist.clear() + for group in sorted(self.nicklist): + for nick in sorted(self.nicklist[group]['nicks'], + key=lambda n: n['name']): + prefix_color = { + '': '', + ' ': '', + '+': 'yellow', + } + col = prefix_color.get(nick['prefix'], 'green') + if col: + icon = QtGui.QIcon( + resource_filename(__name__, + 'data/icons/bullet_%s_8x8.png' % + col)) + else: + pixmap = QtGui.QPixmap(8, 8) + pixmap.fill() + icon = QtGui.QIcon(pixmap) + item = QtWidgets.QListWidgetItem(icon, nick['name']) + self.widget.nicklist.addItem(item) + self.widget.nicklist.setVisible(True) diff --git a/toxygen/third_party/qweechat/chat.py b/toxygen/third_party/qweechat/chat.py new file mode 100644 index 0000000..328de1a --- /dev/null +++ b/toxygen/third_party/qweechat/chat.py @@ -0,0 +1,142 @@ +# -*- coding: utf-8 -*- +# +# chat.py - chat area +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +"""Chat area.""" + +import datetime + +from PyQt5 import QtCore, QtWidgets, QtGui + +from qweechat import config +from qweechat.weechat import color + + +class ChatTextEdit(QtWidgets.QTextEdit): + """Chat area.""" + + def __init__(self, debug, *args): + QtWidgets.QTextEdit.__init__(*(self,) + args) + self.debug = debug + self.readOnly = True + self.setFocusPolicy(QtCore.Qt.NoFocus) + self.setFontFamily('monospace') + self._textcolor = self.textColor() + self._bgcolor = QtGui.QColor('#FFFFFF') + self._setcolorcode = { + 'F': (self.setTextColor, self._textcolor), + 'B': (self.setTextBackgroundColor, self._bgcolor) + } + self._setfont = { + '*': self.setFontWeight, + '_': self.setFontUnderline, + '/': self.setFontItalic + } + self._fontvalues = { + False: { + '*': QtGui.QFont.Normal, + '_': False, + '/': False + }, + True: { + '*': QtGui.QFont.Bold, + '_': True, + '/': True + } + } + self._color = color.Color(config.color_options(), self.debug) + + def display(self, time, prefix, text, forcecolor=None): + if time == 0: + now = datetime.datetime.now() + else: + now = datetime.datetime.fromtimestamp(float(time)) + self.setTextColor(QtGui.QColor('#999999')) + self.insertPlainText(now.strftime('%H:%M ')) + prefix = self._color.convert(prefix) + text = self._color.convert(text) + if forcecolor: + if prefix: + prefix = '\x01(F%s)%s' % (forcecolor, prefix) + text = '\x01(F%s)%s' % (forcecolor, text) + if prefix: + self._display_with_colors(prefix + ' ') + if text: + self._display_with_colors(text) + if text[-1:] != '\n': + self.insertPlainText('\n') + else: + self.insertPlainText('\n') + self.scroll_bottom() + + def _display_with_colors(self, string): + self.setTextColor(self._textcolor) + self.setTextBackgroundColor(self._bgcolor) + self._reset_attributes() + items = string.split('\x01') + for i, item in enumerate(items): + if i > 0 and item.startswith('('): + pos = item.find(')') + if pos >= 2: + action = item[1] + code = item[2:pos] + if action == '+': + # set attribute + self._set_attribute(code[0], True) + elif action == '-': + # remove attribute + self._set_attribute(code[0], False) + else: + # reset attributes and color + if code == 'r': + self._reset_attributes() + self._setcolorcode[action][0]( + self._setcolorcode[action][1]) + else: + # set attributes + color + while code.startswith(('*', '!', '/', '_', '|', + 'r')): + if code[0] == 'r': + self._reset_attributes() + elif code[0] in self._setfont: + self._set_attribute( + code[0], + not self._font[code[0]]) + code = code[1:] + if code: + self._setcolorcode[action][0]( + QtGui.QColor(code)) + item = item[pos+1:] + if len(item) > 0: + self.insertPlainText(item) + + def _reset_attributes(self): + self._font = {} + for attr in self._setfont: + self._set_attribute(attr, False) + + def _set_attribute(self, attr, value): + self._font[attr] = value + self._setfont[attr](self._fontvalues[self._font[attr]][attr]) + + def scroll_bottom(self): + scroll = self.verticalScrollBar() + scroll.setValue(scroll.maximum()) diff --git a/toxygen/third_party/qweechat/chat.py.diff b/toxygen/third_party/qweechat/chat.py.diff new file mode 100644 index 0000000..bab42bc --- /dev/null +++ b/toxygen/third_party/qweechat/chat.py.diff @@ -0,0 +1,27 @@ +*** chat.py.dst 2022-11-19 18:31:51.000000000 +0000 +--- chat.py 2022-11-19 18:32:41.000000000 +0000 +*************** +*** 22,32 **** + + """Chat area.""" + + import datetime + +! from PySide6 import QtCore, QtWidgets, QtGui + + from qweechat import config + from qweechat.weechat import color + + +--- 22,32 ---- + + """Chat area.""" + + import datetime + +! from PyQt5 import QtCore, QtWidgets, QtGui + + from qweechat import config + from qweechat.weechat import color + + diff --git a/toxygen/third_party/qweechat/chat.py.dst b/toxygen/third_party/qweechat/chat.py.dst new file mode 100644 index 0000000..b8a3788 --- /dev/null +++ b/toxygen/third_party/qweechat/chat.py.dst @@ -0,0 +1,142 @@ +# -*- coding: utf-8 -*- +# +# chat.py - chat area +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +"""Chat area.""" + +import datetime + +from PySide6 import QtCore, QtWidgets, QtGui + +from qweechat import config +from qweechat.weechat import color + + +class ChatTextEdit(QtWidgets.QTextEdit): + """Chat area.""" + + def __init__(self, debug, *args): + QtWidgets.QTextEdit.__init__(*(self,) + args) + self.debug = debug + self.readOnly = True + self.setFocusPolicy(QtCore.Qt.NoFocus) + self.setFontFamily('monospace') + self._textcolor = self.textColor() + self._bgcolor = QtGui.QColor('#FFFFFF') + self._setcolorcode = { + 'F': (self.setTextColor, self._textcolor), + 'B': (self.setTextBackgroundColor, self._bgcolor) + } + self._setfont = { + '*': self.setFontWeight, + '_': self.setFontUnderline, + '/': self.setFontItalic + } + self._fontvalues = { + False: { + '*': QtGui.QFont.Normal, + '_': False, + '/': False + }, + True: { + '*': QtGui.QFont.Bold, + '_': True, + '/': True + } + } + self._color = color.Color(config.color_options(), self.debug) + + def display(self, time, prefix, text, forcecolor=None): + if time == 0: + now = datetime.datetime.now() + else: + now = datetime.datetime.fromtimestamp(float(time)) + self.setTextColor(QtGui.QColor('#999999')) + self.insertPlainText(now.strftime('%H:%M ')) + prefix = self._color.convert(prefix) + text = self._color.convert(text) + if forcecolor: + if prefix: + prefix = '\x01(F%s)%s' % (forcecolor, prefix) + text = '\x01(F%s)%s' % (forcecolor, text) + if prefix: + self._display_with_colors(prefix + ' ') + if text: + self._display_with_colors(text) + if text[-1:] != '\n': + self.insertPlainText('\n') + else: + self.insertPlainText('\n') + self.scroll_bottom() + + def _display_with_colors(self, string): + self.setTextColor(self._textcolor) + self.setTextBackgroundColor(self._bgcolor) + self._reset_attributes() + items = string.split('\x01') + for i, item in enumerate(items): + if i > 0 and item.startswith('('): + pos = item.find(')') + if pos >= 2: + action = item[1] + code = item[2:pos] + if action == '+': + # set attribute + self._set_attribute(code[0], True) + elif action == '-': + # remove attribute + self._set_attribute(code[0], False) + else: + # reset attributes and color + if code == 'r': + self._reset_attributes() + self._setcolorcode[action][0]( + self._setcolorcode[action][1]) + else: + # set attributes + color + while code.startswith(('*', '!', '/', '_', '|', + 'r')): + if code[0] == 'r': + self._reset_attributes() + elif code[0] in self._setfont: + self._set_attribute( + code[0], + not self._font[code[0]]) + code = code[1:] + if code: + self._setcolorcode[action][0]( + QtGui.QColor(code)) + item = item[pos+1:] + if len(item) > 0: + self.insertPlainText(item) + + def _reset_attributes(self): + self._font = {} + for attr in self._setfont: + self._set_attribute(attr, False) + + def _set_attribute(self, attr, value): + self._font[attr] = value + self._setfont[attr](self._fontvalues[self._font[attr]][attr]) + + def scroll_bottom(self): + scroll = self.verticalScrollBar() + scroll.setValue(scroll.maximum()) diff --git a/toxygen/third_party/qweechat/config.py b/toxygen/third_party/qweechat/config.py new file mode 100644 index 0000000..ffdf793 --- /dev/null +++ b/toxygen/third_party/qweechat/config.py @@ -0,0 +1,136 @@ +# -*- coding: utf-8 -*- +# +# config.py - configuration for QWeeChat +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +"""Configuration for QWeeChat.""" + +import configparser +import os + +from pathlib import Path + +CONFIG_DIR = '%s/.config/qweechat' % os.getenv('HOME') +CONFIG_FILENAME = '%s/qweechat.conf' % CONFIG_DIR + +CONFIG_DEFAULT_RELAY_LINES = 50 + +CONFIG_DEFAULT_SECTIONS = ('relay', 'look', 'color') +CONFIG_DEFAULT_OPTIONS = (('relay.hostname', '127.0.0.1'), + ('relay.port', '9000'), + ('relay.ssl', 'off'), + ('relay.password', ''), + ('relay.autoconnect', 'off'), + ('relay.lines', str(CONFIG_DEFAULT_RELAY_LINES)), + ('look.debug', 'off'), + ('look.statusbar', 'on')) + +# Default colors for WeeChat color options (option name, #rgb value) +CONFIG_DEFAULT_COLOR_OPTIONS = ( + ('separator', '#000066'), # 0 + ('chat', '#000000'), # 1 + ('chat_time', '#999999'), # 2 + ('chat_time_delimiters', '#000000'), # 3 + ('chat_prefix_error', '#FF6633'), # 4 + ('chat_prefix_network', '#990099'), # 5 + ('chat_prefix_action', '#000000'), # 6 + ('chat_prefix_join', '#00CC00'), # 7 + ('chat_prefix_quit', '#CC0000'), # 8 + ('chat_prefix_more', '#CC00FF'), # 9 + ('chat_prefix_suffix', '#330099'), # 10 + ('chat_buffer', '#000000'), # 11 + ('chat_server', '#000000'), # 12 + ('chat_channel', '#000000'), # 13 + ('chat_nick', '#000000'), # 14 + ('chat_nick_self', '*#000000'), # 15 + ('chat_nick_other', '#000000'), # 16 + ('', '#000000'), # 17 (nick1 -- obsolete) + ('', '#000000'), # 18 (nick2 -- obsolete) + ('', '#000000'), # 19 (nick3 -- obsolete) + ('', '#000000'), # 20 (nick4 -- obsolete) + ('', '#000000'), # 21 (nick5 -- obsolete) + ('', '#000000'), # 22 (nick6 -- obsolete) + ('', '#000000'), # 23 (nick7 -- obsolete) + ('', '#000000'), # 24 (nick8 -- obsolete) + ('', '#000000'), # 25 (nick9 -- obsolete) + ('', '#000000'), # 26 (nick10 -- obsolete) + ('chat_host', '#666666'), # 27 + ('chat_delimiters', '#9999FF'), # 28 + ('chat_highlight', '#3399CC'), # 29 + ('chat_read_marker', '#000000'), # 30 + ('chat_text_found', '#000000'), # 31 + ('chat_value', '#000000'), # 32 + ('chat_prefix_buffer', '#000000'), # 33 + ('chat_tags', '#000000'), # 34 + ('chat_inactive_window', '#000000'), # 35 + ('chat_inactive_buffer', '#000000'), # 36 + ('chat_prefix_buffer_inactive_buffer', '#000000'), # 37 + ('chat_nick_offline', '#000000'), # 38 + ('chat_nick_offline_highlight', '#000000'), # 39 + ('chat_nick_prefix', '#000000'), # 40 + ('chat_nick_suffix', '#000000'), # 41 + ('emphasis', '#000000'), # 42 + ('chat_day_change', '#000000'), # 43 +) +config_color_options = [] + + +def read(): + """Read config file.""" + global config_color_options + config = configparser.RawConfigParser() + if os.path.isfile(CONFIG_FILENAME): + config.read(CONFIG_FILENAME) + + # add missing sections/options + for section in CONFIG_DEFAULT_SECTIONS: + if not config.has_section(section): + config.add_section(section) + for option in reversed(CONFIG_DEFAULT_OPTIONS): + section, name = option[0].split('.', 1) + if not config.has_option(section, name): + config.set(section, name, option[1]) + section = 'color' + for option in reversed(CONFIG_DEFAULT_COLOR_OPTIONS): + if option[0] and not config.has_option(section, option[0]): + config.set(section, option[0], option[1]) + + # build list of color options + config_color_options = [] + for option in CONFIG_DEFAULT_COLOR_OPTIONS: + if option[0]: + config_color_options.append(config.get('color', option[0])) + else: + config_color_options.append('#000000') + + return config + + +def write(config): + """Write config file.""" + Path(CONFIG_DIR).mkdir(mode=0o0700, parents=True, exist_ok=True) + with open(CONFIG_FILENAME, 'w') as cfg: + config.write(cfg) + + +def color_options(): + """Return color options.""" + global config_color_options + return config_color_options diff --git a/toxygen/third_party/qweechat/config.py.dst b/toxygen/third_party/qweechat/config.py.dst new file mode 100644 index 0000000..42fbba4 --- /dev/null +++ b/toxygen/third_party/qweechat/config.py.dst @@ -0,0 +1,136 @@ +# -*- coding: utf-8 -*- +# +# config.py - configuration for QWeeChat +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +"""Configuration for QWeeChat.""" + +import configparser +import os + +from pathlib import Path + +CONFIG_DIR = '%s/.config/qweechat' % os.getenv('HOME') +CONFIG_FILENAME = '%s/qweechat.conf' % CONFIG_DIR + +CONFIG_DEFAULT_RELAY_LINES = 50 + +CONFIG_DEFAULT_SECTIONS = ('relay', 'look', 'color') +CONFIG_DEFAULT_OPTIONS = (('relay.hostname', ''), + ('relay.port', ''), + ('relay.ssl', 'off'), + ('relay.password', ''), + ('relay.autoconnect', 'off'), + ('relay.lines', str(CONFIG_DEFAULT_RELAY_LINES)), + ('look.debug', 'off'), + ('look.statusbar', 'off')) + +# Default colors for WeeChat color options (option name, #rgb value) +CONFIG_DEFAULT_COLOR_OPTIONS = ( + ('separator', '#000066'), # 0 + ('chat', '#000000'), # 1 + ('chat_time', '#999999'), # 2 + ('chat_time_delimiters', '#000000'), # 3 + ('chat_prefix_error', '#FF6633'), # 4 + ('chat_prefix_network', '#990099'), # 5 + ('chat_prefix_action', '#000000'), # 6 + ('chat_prefix_join', '#00CC00'), # 7 + ('chat_prefix_quit', '#CC0000'), # 8 + ('chat_prefix_more', '#CC00FF'), # 9 + ('chat_prefix_suffix', '#330099'), # 10 + ('chat_buffer', '#000000'), # 11 + ('chat_server', '#000000'), # 12 + ('chat_channel', '#000000'), # 13 + ('chat_nick', '#000000'), # 14 + ('chat_nick_self', '*#000000'), # 15 + ('chat_nick_other', '#000000'), # 16 + ('', '#000000'), # 17 (nick1 -- obsolete) + ('', '#000000'), # 18 (nick2 -- obsolete) + ('', '#000000'), # 19 (nick3 -- obsolete) + ('', '#000000'), # 20 (nick4 -- obsolete) + ('', '#000000'), # 21 (nick5 -- obsolete) + ('', '#000000'), # 22 (nick6 -- obsolete) + ('', '#000000'), # 23 (nick7 -- obsolete) + ('', '#000000'), # 24 (nick8 -- obsolete) + ('', '#000000'), # 25 (nick9 -- obsolete) + ('', '#000000'), # 26 (nick10 -- obsolete) + ('chat_host', '#666666'), # 27 + ('chat_delimiters', '#9999FF'), # 28 + ('chat_highlight', '#3399CC'), # 29 + ('chat_read_marker', '#000000'), # 30 + ('chat_text_found', '#000000'), # 31 + ('chat_value', '#000000'), # 32 + ('chat_prefix_buffer', '#000000'), # 33 + ('chat_tags', '#000000'), # 34 + ('chat_inactive_window', '#000000'), # 35 + ('chat_inactive_buffer', '#000000'), # 36 + ('chat_prefix_buffer_inactive_buffer', '#000000'), # 37 + ('chat_nick_offline', '#000000'), # 38 + ('chat_nick_offline_highlight', '#000000'), # 39 + ('chat_nick_prefix', '#000000'), # 40 + ('chat_nick_suffix', '#000000'), # 41 + ('emphasis', '#000000'), # 42 + ('chat_day_change', '#000000'), # 43 +) +config_color_options = [] + + +def read(): + """Read config file.""" + global config_color_options + config = configparser.RawConfigParser() + if os.path.isfile(CONFIG_FILENAME): + config.read(CONFIG_FILENAME) + + # add missing sections/options + for section in CONFIG_DEFAULT_SECTIONS: + if not config.has_section(section): + config.add_section(section) + for option in reversed(CONFIG_DEFAULT_OPTIONS): + section, name = option[0].split('.', 1) + if not config.has_option(section, name): + config.set(section, name, option[1]) + section = 'color' + for option in reversed(CONFIG_DEFAULT_COLOR_OPTIONS): + if option[0] and not config.has_option(section, option[0]): + config.set(section, option[0], option[1]) + + # build list of color options + config_color_options = [] + for option in CONFIG_DEFAULT_COLOR_OPTIONS: + if option[0]: + config_color_options.append(config.get('color', option[0])) + else: + config_color_options.append('#000000') + + return config + + +def write(config): + """Write config file.""" + Path(CONFIG_DIR).mkdir(mode=0o0700, parents=True, exist_ok=True) + with open(CONFIG_FILENAME, 'w') as cfg: + config.write(cfg) + + +def color_options(): + """Return color options.""" + global config_color_options + return config_color_options diff --git a/toxygen/third_party/qweechat/connection.py b/toxygen/third_party/qweechat/connection.py new file mode 100644 index 0000000..43d898f --- /dev/null +++ b/toxygen/third_party/qweechat/connection.py @@ -0,0 +1,122 @@ +# -*- coding: utf-8 -*- +# +# connection.py - connection window +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +"""Connection window.""" + +from PyQt5 import QtGui, QtWidgets + + +class ConnectionDialog(QtWidgets.QDialog): + """Connection window.""" + + def __init__(self, values, *args): + super().__init__(*args) + self.values = values + self.setModal(True) + self.setWindowTitle('Connect to WeeChat') + + grid = QtWidgets.QGridLayout() + grid.setSpacing(10) + + self.fields = {} + focus = None + + # hostname + grid.addWidget(QtWidgets.QLabel('Hostname'), 0, 0) + line_edit = QtWidgets.QLineEdit() + line_edit.setFixedWidth(200) + value = self.values.get('hostname', '') + line_edit.insert(value) + grid.addWidget(line_edit, 0, 1) + self.fields['hostname'] = line_edit + if not focus and not value: + focus = 'hostname' + + # port / SSL + grid.addWidget(QtWidgets.QLabel('Port'), 1, 0) + line_edit = QtWidgets.QLineEdit() + line_edit.setFixedWidth(200) + value = self.values.get('port', '') + line_edit.insert(value) + grid.addWidget(line_edit, 1, 1) + self.fields['port'] = line_edit + if not focus and not value: + focus = 'port' + + ssl = QtWidgets.QCheckBox('SSL') + ssl.setChecked(self.values['ssl'] == 'on') + grid.addWidget(ssl, 1, 2) + self.fields['ssl'] = ssl + + # password + grid.addWidget(QtWidgets.QLabel('Password'), 2, 0) + line_edit = QtWidgets.QLineEdit() + line_edit.setFixedWidth(200) + line_edit.setEchoMode(QtWidgets.QLineEdit.Password) + value = self.values.get('password', '') + line_edit.insert(value) + grid.addWidget(line_edit, 2, 1) + self.fields['password'] = line_edit + if not focus and not value: + focus = 'password' + + # TOTP (Time-Based One-Time Password) + label = QtWidgets.QLabel('TOTP') + label.setToolTip('Time-Based One-Time Password (6 digits)') + grid.addWidget(label, 3, 0) + line_edit = QtWidgets.QLineEdit() + line_edit.setPlaceholderText('6 digits') + validator = QtGui.QIntValidator(0, 999999, self) + line_edit.setValidator(validator) + line_edit.setFixedWidth(80) + value = self.values.get('totp', '') + line_edit.insert(value) + grid.addWidget(line_edit, 3, 1) + self.fields['totp'] = line_edit + if not focus and not value: + focus = 'totp' + + # lines + grid.addWidget(QtWidgets.QLabel('Lines'), 4, 0) + line_edit = QtWidgets.QLineEdit() + line_edit.setFixedWidth(200) + validator = QtGui.QIntValidator(0, 2147483647, self) + line_edit.setValidator(validator) + line_edit.setFixedWidth(80) + value = self.values.get('lines', '') + line_edit.insert(value) + grid.addWidget(line_edit, 4, 1) + self.fields['lines'] = line_edit + if not focus and not value: + focus = 'lines' + + self.dialog_buttons = QtWidgets.QDialogButtonBox() + self.dialog_buttons.setStandardButtons( + QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel) + self.dialog_buttons.rejected.connect(self.close) + + grid.addWidget(self.dialog_buttons, 5, 0, 1, 2) + self.setLayout(grid) + self.show() + + if focus: + self.fields[focus].setFocus() diff --git a/toxygen/third_party/qweechat/connection.py.diff b/toxygen/third_party/qweechat/connection.py.diff new file mode 100644 index 0000000..b7ca776 --- /dev/null +++ b/toxygen/third_party/qweechat/connection.py.diff @@ -0,0 +1,27 @@ +*** connection.py.dst 2022-11-19 18:31:51.000000000 +0000 +--- connection.py 2022-11-19 18:32:41.000000000 +0000 +*************** +*** 20,30 **** + # along with QWeeChat. If not, see . + # + + """Connection window.""" + +! from PySide6 import QtGui, QtWidgets + + + class ConnectionDialog(QtWidgets.QDialog): + """Connection window.""" + +--- 20,30 ---- + # along with QWeeChat. If not, see . + # + + """Connection window.""" + +! from PyQt5 import QtGui, QtWidgets + + + class ConnectionDialog(QtWidgets.QDialog): + """Connection window.""" + diff --git a/toxygen/third_party/qweechat/connection.py.dst b/toxygen/third_party/qweechat/connection.py.dst new file mode 100644 index 0000000..c9631ff --- /dev/null +++ b/toxygen/third_party/qweechat/connection.py.dst @@ -0,0 +1,122 @@ +# -*- coding: utf-8 -*- +# +# connection.py - connection window +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +"""Connection window.""" + +from PySide6 import QtGui, QtWidgets + + +class ConnectionDialog(QtWidgets.QDialog): + """Connection window.""" + + def __init__(self, values, *args): + super().__init__(*args) + self.values = values + self.setModal(True) + self.setWindowTitle('Connect to WeeChat') + + grid = QtWidgets.QGridLayout() + grid.setSpacing(10) + + self.fields = {} + focus = None + + # hostname + grid.addWidget(QtWidgets.QLabel('Hostname'), 0, 0) + line_edit = QtWidgets.QLineEdit() + line_edit.setFixedWidth(200) + value = self.values.get('hostname', '') + line_edit.insert(value) + grid.addWidget(line_edit, 0, 1) + self.fields['hostname'] = line_edit + if not focus and not value: + focus = 'hostname' + + # port / SSL + grid.addWidget(QtWidgets.QLabel('Port'), 1, 0) + line_edit = QtWidgets.QLineEdit() + line_edit.setFixedWidth(200) + value = self.values.get('port', '') + line_edit.insert(value) + grid.addWidget(line_edit, 1, 1) + self.fields['port'] = line_edit + if not focus and not value: + focus = 'port' + + ssl = QtWidgets.QCheckBox('SSL') + ssl.setChecked(self.values['ssl'] == 'on') + grid.addWidget(ssl, 1, 2) + self.fields['ssl'] = ssl + + # password + grid.addWidget(QtWidgets.QLabel('Password'), 2, 0) + line_edit = QtWidgets.QLineEdit() + line_edit.setFixedWidth(200) + line_edit.setEchoMode(QtWidgets.QLineEdit.Password) + value = self.values.get('password', '') + line_edit.insert(value) + grid.addWidget(line_edit, 2, 1) + self.fields['password'] = line_edit + if not focus and not value: + focus = 'password' + + # TOTP (Time-Based One-Time Password) + label = QtWidgets.QLabel('TOTP') + label.setToolTip('Time-Based One-Time Password (6 digits)') + grid.addWidget(label, 3, 0) + line_edit = QtWidgets.QLineEdit() + line_edit.setPlaceholderText('6 digits') + validator = QtGui.QIntValidator(0, 999999, self) + line_edit.setValidator(validator) + line_edit.setFixedWidth(80) + value = self.values.get('totp', '') + line_edit.insert(value) + grid.addWidget(line_edit, 3, 1) + self.fields['totp'] = line_edit + if not focus and not value: + focus = 'totp' + + # lines + grid.addWidget(QtWidgets.QLabel('Lines'), 4, 0) + line_edit = QtWidgets.QLineEdit() + line_edit.setFixedWidth(200) + validator = QtGui.QIntValidator(0, 2147483647, self) + line_edit.setValidator(validator) + line_edit.setFixedWidth(80) + value = self.values.get('lines', '') + line_edit.insert(value) + grid.addWidget(line_edit, 4, 1) + self.fields['lines'] = line_edit + if not focus and not value: + focus = 'lines' + + self.dialog_buttons = QtWidgets.QDialogButtonBox() + self.dialog_buttons.setStandardButtons( + QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel) + self.dialog_buttons.rejected.connect(self.close) + + grid.addWidget(self.dialog_buttons, 5, 0, 1, 2) + self.setLayout(grid) + self.show() + + if focus: + self.fields[focus].setFocus() diff --git a/toxygen/third_party/qweechat/data/icons/README b/toxygen/third_party/qweechat/data/icons/README new file mode 100644 index 0000000..0694819 --- /dev/null +++ b/toxygen/third_party/qweechat/data/icons/README @@ -0,0 +1,41 @@ +Copyright and license for images +================================ + + +Files: weechat.png, bullet_green_8x8.png, bullet_yellow_8x8.png + + Copyright (C) 2011-2022 Sébastien Helleu + Released under GPLv3. + + + +Files: application-exit.png, dialog-close.png, dialog-ok-apply.png, + dialog-password.png, dialog-warning.png, document-save.png, + edit-find.png, help-about.png, network-connect.png, + network-disconnect.png, preferences-other.png + + Files come from Debian package "oxygen-icon-theme": + + The Oxygen Icon Theme + Copyright (C) 2007 Nuno Pinheiro + Copyright (C) 2007 David Vignoni + Copyright (C) 2007 David Miller + Copyright (C) 2007 Johann Ollivier Lapeyre + Copyright (C) 2007 Kenneth Wimer + Copyright (C) 2007 Riccardo Iaconelli + and others + + License: + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 3 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library. If not, see . diff --git a/toxygen/third_party/qweechat/data/icons/application-exit.png b/toxygen/third_party/qweechat/data/icons/application-exit.png new file mode 100644 index 0000000000000000000000000000000000000000..dd76354c4a49d07e81d9e701164cdc2caa439a47 GIT binary patch literal 1760 zcmV<61|Ru}P)p00006VoOIv0RI600RN!9r;`8x25m`1 zK~#9!%~xA&R8B~-snS19x-23$A+!N!1U zpS{-J`^=dP{%cd7__wTFTq5L3n9C}U8AF>ylFu@&OUEOFlHLZ*uJlI%F%K>&s>$)B&E!`KG zJ$tfNRRvX1250a%%B@o5!oteTwQGA7U9W~=WQ2gMszz=dIg*H1RKPS%JV|pXxz=OH zDxW7#00RPS*VTHOn^irTgpDU_wqc-;TFjgv8>oQmsty1vlgSg%P0nrMFoNkc61vW< zd9*BD7mai_8;PKtVwUK-FCd%cgaxM*K;){;n>hmhvTZnt1Qu0SBTWK+JahUwJ8=R%=gy%}(+2iUliMIT0q>9FI4poGAQ7d@IE}~^a*jr$c(tYm zw@ONo<^7={_HGszvoD_!XQ$1Wfk;)A^l`WX9;XywJC5H14`oF~P*t%Fm$K5Sj4#cf zkFL^E=_lclca9w^d_tiR6M&6ll#wXu%N6iAr2xxsfmGUh-~b-9x5KNDKrk3Y<=nYQ zO`HhJFl11kr^?Hbm@@}~KmfLFGlcL59UW-fzdx@6+ydtGE8t&3iEJu`mc4tCYHO1s zI3N=|H)|H0DV0!cL%^P#K*h|N&@?Td{PJbA?AZe|l^P_#&b@>-pom4o;0^!A63*|~ zfk|uDAXru=D1n;U^s+;PUUn5R4N8=eb=XWdi6%QV`Mv607D3i zC%bX?@P6nq9STQH8|b@!868ItBb`ixEf|Y}xOg{DfWj3>-nfoT{{v{6f=DccSYZT_ z0v+LK2zodOClbQ3AHGM`l2wv8SH!R1euL=OUs3fem|4K^pb#{ovzds=T~%;O0YZf8 zH5}|rJ+=+FDFZegw))9i*UT9EOHkd zuA&SUzY6&>8BR1C-TjlIg>LuQzAbL`-^38wy(hGJ5BsbGCA*wXM4(98{n?k z#4++>DwLr+lmJ%6n-pI_4QLc#Bav@na#qd|B*j-x3-YjP3MgN$z?ggI5e|o?5S~wc zy8)5<4@E2ylc6cZg(2?%5%>aP>o%jh{yj;~nQ`D)+bLu|TY{i#LJt99LJ%gh+m=&R z{unG`)p`tjcZ-M#7Vz*p!2kIhRg3FH05VA)Z21MfA1?y3CI*>hBKgTuL|adB3s?lV zOPs5$St#8URp4Ql5b~pQdSwmJ-zT3}`}gCx{ZTD!!xW$AtOd{%83NC38{#FsyJazO z?q~T`&N0qVERG3=ch`n!fgq9sdRoro%(8h)t;5S^_eL zj2j(UMC*#foU#Hg(5=Vfm*SJgS7^}?G{@ps%zMfFQ6ne>u9iiRnQ+_qnI))%piOg& z&d{jS81)jcwIHl`36u->E-|MRpa4Cgi+?tB^!9A;>FO-crqk-9{|tL{3q_(%SiNy+ zbh7^)=0xswI6lyh62dTUFP?yTW#`O$W&#fW5B4{McG5)R9cTpr0000W=JYt1lxo8u(J%;uU=UKNhDeo#h1hJwE@2U|NGu`-12Hie zBqUfG>BP_wUlH20zQ0OcPwxJI*Sz_?PoDS9vpn;WzK|?cNB|&*yMs|%odukNy<_gf z1zT_`8tR1YlgcOC2xC2=Ah5!$9c(Vy7jdF{XbQlk7C=~8_1F|*t z$2p=qW;9ftMv=kJ*%`c&H>L>+$X<0osF&J^MOo`5e+6&!8D+~2d8%WEJpxrx1BT56 z4M>%ixl4S+%M?yQgZ+Vk0wljOS^8;8oSCtf+<66RNDVeR8lX-HfS>n5?l|{gri^?3 zH<7#6eW1xgah1fm#D|ZU@BQ7Q+sEmfJ<#bs+FbxhTp3n5+6i*aR@M}0#<&9u;`Zm1 VADNt6-dHbG3gNE4;CAQe>_4R>k1zlL literal 0 HcmV?d00001 diff --git a/toxygen/third_party/qweechat/data/icons/bullet_yellow_8x8.png b/toxygen/third_party/qweechat/data/icons/bullet_yellow_8x8.png new file mode 100644 index 0000000000000000000000000000000000000000..58ad5cf346e549fe49eb1f5ae7095b66e00765e2 GIT binary patch literal 375 zcmeAS@N?(olHy`uVBq!ia0vp^93afW1|*O0@9PFqjKx9jP7LeL$-D$|*pj^6T^Rm@ z;DWu&Cj&(|3p^r=85p>QL70(Y)*K0-7A{X0#}J9jtOxzQnH(k9AKc$#{rKEERyA!$ zb=!&;I!aR?txPU?At&2p=i2^@#qr|W{tKoniWAx$Ja(<M|c|3vzDc2lqR2)pL+Ur^(4!irYCtKxE@a6&z^p0hUOHWqG>yoW(})MEMB=>Z^b5f~&pmFi#h;1cQYKfI>v}zosW-1wEDpTmFSLgt;~#Tse6fLf T$i^&SP%(JA`njxgN@xNAV&9t! literal 0 HcmV?d00001 diff --git a/toxygen/third_party/qweechat/data/icons/dialog-close.png b/toxygen/third_party/qweechat/data/icons/dialog-close.png new file mode 100644 index 0000000000000000000000000000000000000000..2c2f99eb46be90636f98984936190752350370af GIT binary patch literal 813 zcmV+|1JeA7P)E-4*}<0=h{= zK~#9!WzSn^)dc{@@z4K%&e_h+uIFq=%jRlhi`pDHEu;s75`r%D5=B@K77|LMhcYtB zu_)9aeCwfntVjt2>7mQOAXr+9^^#1|9GtD`ZtZrqbGCB}A8nt9-{Tj40h@h9LxO!V z9temQ$rQNw4io<8j=*th8yKhw!#7%Y@2*Yv^ax`yi{s-m!^7olE_Z&Nw~vw86c}Jj z6W_OP-`>~P->3c$VnnTx?4w_de8rShOxK5(ZQP zN|Z|!OC5~hy?t0~b6;C=n z)zxm_N=G8;IHwSVh$J|ijD%uMd4=Yrnr+*49Xe*Zv@SC@uH(%k>N`8dd%G=7PDs_) zOYq`*G)E4Q?%sk^EO23`--RVK`hNN^?k3WC<(delcw71NvYRrn(QjIEF!*z;P z2uhTT6iX}?Q+l6#4nX_Phs8U3RT`;kCQ?HTF$&>1CPG%%bL18opHJB{Fr;&U2HSaeDWsC5=5FFCVs!)oxmmJTNUXBK&;g!bWF-JV!{;2kpSPBY zt%j7V5fT=NZ_tEgE_}eDQKnIe0AT%Feu*)BAN9$KbX`#*QJ}75wan!|7&yquoBWFk r1U3tiK&qRTdZHuDlvzL)B>?yjfS~`FyINaO00000NkvXXu0mjf;$wU` literal 0 HcmV?d00001 diff --git a/toxygen/third_party/qweechat/data/icons/dialog-ok-apply.png b/toxygen/third_party/qweechat/data/icons/dialog-ok-apply.png new file mode 100644 index 0000000000000000000000000000000000000000..f1d290c6473dabb354d792a7724cc4d786e0d0b6 GIT binary patch literal 597 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbKJbFq_W2nPqp?T7vkfLzW3kH}&M z2FBeW%xLxI@gtz1WQl7;NpOBzNqJ&XDnogBxn5>oc5!lIL8@MUQTpt6Hc~*BaQ29J1}sCcHRXtt1GHXmOGH)lM%P_}?T46j72hL`z}7OUIX7+O}{2xziz{THCiFfy5WZ;A{IDB&UcKSV;{RoH)Uf$$}Xeg zEh%MNlgsu*mLCYM+>uzlJFWgeM*RuXrem(nhrButRdw$5?mSlAbuhf^V07P+gudf0 z{U>84?9HBVFn{9F%!&8xCLb%9d?IVw;hY&)-Dh6tpLuD*tP>ftPFK%8nY-*l`L!VqTUG;r_P$YVDX-7H*P%?hDcmaPEcUoz-6%T!%dO3OC%>g6+NVstLmszmzt<>Qt7?C z&>Lmel#iLN65NIcr+@CUs@5)KU`=t-W%hANv3>KFDb&Kzily|<*}Xn@bJiRV-Knsw z^Od!vMbwO)D+&*u5x-n~!R%AWbGI8Bc`wA5oa}w0#u>{i7ZUz?lkj_IhPvbY2j=Pd RmjhkH;OXk;vd$@?2>>yI)$afR literal 0 HcmV?d00001 diff --git a/toxygen/third_party/qweechat/data/icons/dialog-password.png b/toxygen/third_party/qweechat/data/icons/dialog-password.png new file mode 100644 index 0000000000000000000000000000000000000000..2151029e0adbab6678e541f1ab0a080809f0a44f GIT binary patch literal 713 zcmV;)0yh1LP)XV#?~IOCxKK)w2oo1A+@;VeaPbyut7zx0 zg*$g461>2|wLx!D3q#AcA=E~F2t5(Mz=a5YE2cDliyv6lsB_=B(md)>FZ;t`KJNU^ z{hxEsAdKOQPitDR^x+AtUl5B>+fnMfq6tJR9n=ks_l7~o(q*rU;&vfJ$s zjYi|GQmI6#R4UZzbdXxDmh7{$()Zf;j%C?ZHk-w*RtuBsa=FBTK;ZMg;OpUVxG|Yb za4MC;^?Dtr(`md|EJ%_ca=HA`d4Peq3UR|?wcK;LT(5e)9v_d#ak*T^$z&2wr&FBC zWH^9b@ZA-PfD}cE%x3d_o6Yt_r_*VqQmKUPvW#A@m$F}2q*N-=d_G6;j2evwXR%n^ zkmv~5ZwN#?oz5dz*pkkU$K$gomWue~O*Zo*5_7Uzke@xKr zcHhI0wASl2A`)B>k#~N-zYC?kMSqbnKzF=eZw2O@C!=*gEtt=qgkZ2WcrqY7(0?$^FO?a>2XUw9*HDa1NaF z@OuwOwASng#Q>tJeKmRSTwoAd>whL*v@S-Ar+U%SIo(~bF70$q?I;f2hvwL{7^U;b zw*BD0M(BMqro}&V2*W@OP{GO3=%amW&w?cO?-~auS$=Y#<)@EOh2!YhoZXWkUa;=S z@ZZX3l4u!f_gAJi&FE}$2CGXn*ks=8+cm7Eys zU~b|CdHj)4a9W7hL>0$^_B%BP8QDjACRVHHHinKSo>&nW@cmT@orH{EYk+`G9GahX zI~Wi1Oy~%}gp}rxJT?oiC;2*<^i#R|~)W-VQBrF&w4GR~1a&85xL*&7(@?XNdKu7s+>4 ix2BaJzs}xZAN&D5t-?v>AdPzf0000M8$}SF`)$W|Vz+h^3K1d&siN<^An_F5_&0!O z)Rzj0@&v6^_10 zg~*Nh4_Qv0^%;Z#{w#!k|1X#ZQ;;@Dp6+HDfFwzvR;z(y+w7a5d4<3CPl}Rf7-tVSvZMG^9)A0BAQf8V&LJ zVG9{>Z3|Y_U^M`ViOHx#!ZB013K_`6*9ZV_uqB#YC@zDZ2d0D?f6(P|tQ3#a@s(2L z01}P3@xh-TA45^onUU7wF%q&o*g97OmE=lL4uFOcKDoWQ{=CRE|L5o=qZ!D84eqm0 z(TY!}fpk-G0x@+f4Xgl&tX`6`UHUODLTUZqH4rBXBHE6TT3rHJy|_6BfHj~JeTEX? z(^0ITcRZGj$IvMk;Sv)L>kUjP&dLt6R- zyYa=Bbgatf8{D{glU698=svQ`7Y~CniEsL{qWLobmqjQA_hgE!!xHWaYvFXB9A-fFUE*Y87hrIt&Mc0u2-(v~0T& zKomz11c4+VD@>5(9wI1v4m741bguyr;G&{9J{<$#x*U9p55;jL|g$=_H zfzf=j5U4rdp6zxU`u#o_*fcf*z=O+|E`3m`*1o|~wbT1m=)U#UEdfQHwk8G7iBS9~ z3|T7zz%osq?{>Q^UTjrN8wdl&ql1G#H#RoD-hSocXL!RJi!cf~kv-Q!YQ;po(4Rhx zD7a`UT{6*-j6*c%v3CUk-TC)uH2Mye-|{@~A`$TRl`GZ{4<78euIssuZ~ literal 0 HcmV?d00001 diff --git a/toxygen/third_party/qweechat/data/icons/edit-find.png b/toxygen/third_party/qweechat/data/icons/edit-find.png new file mode 100644 index 0000000000000000000000000000000000000000..9b3fe6bca06c7147d5dc79a2a2ae506d8fd03c9b GIT binary patch literal 1705 zcmV;a23GlrP)$x}9)U-ug zo3sy{CMQ9h%edX7L%Fta}YW=Y(#ro z8v=6z$aFYyPgA~6gG z6KpmIJRTn^DypC&B6>y#pT~>5oLm@mdSp4BXliW4mhK*$K6whW%FEf3wEZaoGJaKM z)q_ie7ctO(9B zy~qCNl-RdtFD{%rk1HQvMt*+&&y-902Le$OqWV8LK7i&`%`8*6GMyAePl2V-QbG#I zt&mY`VYS#%SGNEs1_p5M%vsb_&x4N9bL!}{4D0)p_zbTPRh5<8g1S07F?jw0LPJ9@ zJwt#jc5WbWpRIRSXBSqHZ2n?DG%7Ww@TMSXY9iz^ITw@?aB_P|`sK@(2b-E!!EUod ztyDjgTq4dOq86|td2s&$oH_j=u95bVc`SHDSS#`+_-W5ogEzmk+T-87;%z=SVUPlyU`E!uHlSY^Fu^ zZrzH*@4kntSFWOmdV=7kx5NSg~@1u%VvQ;cLwr&UV5%Y zE;VUw%{*3xl#qysh;0nr^g12LQj4&#$b)r@1L$pOKyP~!s>_QJJ0%u63P`&gnpQTV zVR=1NL?9_K@g{9d-?1y*yZaq9Q#m|YZq6q)IR$0|12-eZqS9=vUsgjg>(R5i0p*3c zFw_#hVwAQp+aGAv!P6#Mt? zgO-|c?AWpXsHmu=tmNIByK(&ees0e&8;#H^9OcLAgx!h{|y% zIy!pwZ=Fon?NYJiu2P|V=y7|3Y||>I^WjdOh(*R}XteRs>JnmuHw{Y+Q&FXkhcP3C z>zfd&Wl$#(p*VdK>KPu^+7r>2FGg=pI+~2JL?|95W*Jxi3FF6CJ@0UdiHULXVt6o$ zli?RdVWBP#>)k^1&YX_TZUHtqr(*kT203O8H{v07o9%nHQ7V)P=y50GM1=yE>-4x- z!{A7X7^{iE{IUXW0%%$$yufihMwpt49G8_8orKOT0gjZ)Fj%d@U_g$eMWlphI%ayZ z*m4bpkh58(P@=Y~9Ni^)ob(HEtyYbXDnvL^oQA%ZWys6RV-KRQhE4wLsd$~0x4Eto z-QH9jE1HfgbJh4HAjYXhS?FBT2=bvOPMXQRz%Y!H_WR(xKoyQ{+knrG?7+2weK_2= z1#>FOVX;_lum{zP5+EB*UH&!2MDO|*4DQ>4F9!DD)BZi^Y-xhq=?p5B%D^*Qacpet zM1x+xvnV&`R^d$F!&&(`59~(W4LXub|KaD>D3{aepb`JZWHQ~S=6qCCP;fibYCRPe z78W<$2g&Fs2>F*VhA@sWfe<$GRXjrAe@Ea~RCL2hbp@SQ00000NkvXXu0mjf61x&k literal 0 HcmV?d00001 diff --git a/toxygen/third_party/qweechat/data/icons/help-about.png b/toxygen/third_party/qweechat/data/icons/help-about.png new file mode 100644 index 0000000000000000000000000000000000000000..ee59e170aec98bd8d0413a12d76ba9779101dd47 GIT binary patch literal 1636 zcmV-q2AlbbP)s3VK~#9!#aCNwR7Dv6=G=C-yWMuNEwlxt5z&f*NJ#`90L4f& z5{VH4JYb9l@e-x-;0t0CjR^^uC^6xZC_WL4;w=&`u{2^Mp%D@;Du|Rjlosjkc6ZNh z#(#PyDa-D53om}jw=+9CbH4Aty4p>bp|Fajt+lNcdZ5@W;) zwZ@1ZF-uGnlf(?s8Ho{N1QAl0Nlbe*WdG&E>n;3BBN zK+Z)^GL4hx`>t0<&CMUZIBTmik|FvdHlV~S)_;9)+P=f*w@kdd_P(hT#)10`eQ6t| zJWE4~m+4?Stx}G^_7_S$QVfMJ8}hoUrwPE zViDlW-G^>8)kNp)S-14)%~{ZJ6WZF^7S@8F4+ z2VnbHLrScm2iWx0Gin;@I-hxb7C1*)*p%|7nlL2JT+1O8vQQ53h>0J6>B8C5-Lu4R z>pJuAgqpv2bZs5g(#LQRf&(IW4E%G=mLVuZ9+<{39C}ke?jPTXv)$(x1GvQiW3%G% zIHk)&DR7_TyEXGr3=7)!LN|4kL#!eqwPqH37Sx%hKG?OT;Clk4kn=c9-H<6FmVO{w z+F;@9@|utlz%WYF$bicW=@ESf7Yt9nw->YD-Bs8V9tQU~TvE-wyz7uS$uR%|cQL}P z8DKd_z!E<4FnCB3L|uL-0l&}y7XXP9f>8)WEfZlAxRK5hZFF5t;l_Xs44n@Q2m*Vo zHJQq0qcIjnpoTzLNE0kD0wUK)tVn7t9pQ)tE{#wS>8y>@7y5CrHwpMIl&C6^mlTBj z3^z-@Z+W1FK#bGe zC+Y?if^{K(7yZSW@OSujv(Qb*Ui0W9D>wT@#{+T<&;e-lVY|p=GWiWEOKMn3T$2kJ z3Jyw`=;Z>ff?KgCw!=;V%pf6IYa=*MxJ=#HK@FU8ci2}Dli~+?C>G@C+Ir`gkwPis)H&UK??1G z!P*wUb%AU$sJ&+9pOZ8zfZjg=AwHE_Mc)V5qD4B+jy;dM3H6B813C**YACukuCH&w za2U0k${UITz5{rQvi|)SfGa1j;GPR(m4TrQk zZ;C@3J{##Rl038I)SOHRP&36U3h2}hd$m| z_O-mw#M^V2rtK8bs%nfH4~(4}M5mild??*g%=e^`AnN_sfU2LNWmEm!6$?ezhW6Y4 zW1_(3wi!k)xgI)O;l)OW&@dTrvOuH?sE7xKa%mvbA7tgi5tzANhjFplF=MMl`&ti# zG6u?nwX86$aALV0Vy|%EK_3Wn&)0=)HPi5Q#&R0)2Y2`;XW;ra(Y48iLRkZM3dZKD ihgth@QIbQ5m9|N3V%o3% z;CIu00VOt896^hU5GhVfLZJ{qg$M=0P^f|W;Q-2{IDw)llY)ZG)8n1pwN74dE(RO0 zBqn{y3cPdgJA3WD*WPCzB_dB1|1SdgObZGMa(gNSHg4SbL1<`bTY7r>Xh=v%Du~Q{ z^qqqT4=(cd_6}aPYSp)HZf@>VMqtyXP0RP~+t*iFSt(bqUX@FiE@>F6a7AN!b#?Ve zhYlV31Z%B6K0Zf1Jv~>NF39D}m!+nrMrvzo<;IO0IzB$W zy|lEn4C_N@&YT$miBex*U-v0X!G;YRmh9cTw}VFO>gwddg9lPoRVDCP>g(&}_U+q} zmX@Z^pFc0xuV0sI*RBOll?E90SCI2|gj;UjylD)!wzf)lcegMaBz5c7Ev^|7h)QpB zbMxXUA+UAp)&+a^>}k1j<%-<7bBEp=gAEN0(%#-~k@)9%V`HOENJ!`$Pnb`VbNAi5 zcQ+uM8Xg%B2L}fkUW$(fnF>SV;>C+b4^2%?)PxhHQ~whIda!HPu39Kv-@SX+3UNnA z2T9PF@tVXQK72?Lj12S7_ZXGYfPjD>o|wSq&6~f@&CMOYfB(Mp_4P5dM)_@RZ8T_+ z04zQ9^z>MI;CgCm>cHByYiCS`06m|+ZQHg;)bVg+WTca|&dnVThY2sggA~_Df|_8+ zNsL6zI(x+F)2AgdF>#3dO_%`N>-O#2)1h*w;FFY;Byn+Zn)&YS?X^hIyUxx|vogtmI z{(h36FqtCbd1hv&6Dj;@QX+(4A}AbgMk6Fa&*)`%c({&pOU1RE1mLeI0a zvvpu#VAy0%L)Ll#m^*BuVlL?!jacEOAw)@|$Lq6a&oW9R%W^ZG=j7z*9Xoa$wv5H8 zSt?3p0$)Ck0FTulOG-){6cj+ut@5JRG(Zwur}|l9_>JDbf4?p&Dk3qSXem1l44sW*wtu^!lFSoAPS8n7!g(jPCQw^emz6YW0-=| zJ9qBPW(A2cqNb^Ml?;dt#e6oV)(;#w(8mVCe(o}8l@dwNAXVMc(qg*buwz)tn#!cS zyj+Tliv_xI;%Igt?6G5NJyFE~VndBeQ1izSV0Xd~`w@N$iQ%^lLe2D?B&_z@*wiRq z#a=QuZLXZCKOrYio@9R*Ww*3P6@LGsQk2+Gr;e$Gd^TPRd~wh?kOm$qBte4=Gi#il zQxB%?dKG$!I;srjrO%V7+$aeS4z9PKcz6~Bhz$+uh+6!wRp9UMpNvhMC?9HoB$#ua zZ0rGSIEF-Mb*QLxWnuQQ+0LcEE?sGDoTmJ_ZbLH&EPK@6<4(K|iwlm94~vHbC3Hcd9J){)8J5=Qf6#a~v9yUbk+YV7QcuiVBi2Vr1vb&(9Z3 z!d;vTRh|k5WE}JWD<^y};Ka(wl@lx{Sx&T2b-SORpN@`>W@|MypO=>>ELl#()VXLQc$oY^_MbB5EYqA0)O8D-UZ&Xf#2T-mh(N}HDD?5D)17p0C*m71D*lKj%4iF zTm+s4<^nIcj4uJ+aBcn}@G{OiJO2002ovPDHLkV1l7L5v%|J literal 0 HcmV?d00001 diff --git a/toxygen/third_party/qweechat/data/icons/network-disconnect.png b/toxygen/third_party/qweechat/data/icons/network-disconnect.png new file mode 100644 index 0000000000000000000000000000000000000000..623c8e08dfcb7838f9445102fdd80c596dd049c7 GIT binary patch literal 1276 zcmZ8g2{4;^6pyR5Zc7}|qK>xc8e58Xx3;y3lr|XRR>xXr*L|dRbvvur-RjneF_m=< zrD#JdGC@SDZjy-mzJ(wmHqJQruXfF}Z|48r@B6*?e)E6t`@TQzZIRLvFbN0*B5i#K z?f|0Z@evmR9$xgc6$FuJOKY^axcJzN-86XoBI1r)G+^V7kIc5kxp=a ze*S0KYX;C$1_lGd5ELBd1c$lXTsY-F1FEX3adC0e)6;-2EGz^*Emjfu^k~_PNQvB^ z!~j0Af`S47ii?YZx3aSOkNrQ)%*>RRmlKIZJRV+GutA{K`z!=`JvY(jGIPFOG{T*7s!HkY^d(&=xBO+dKZHZ$nNg$ z*w|PqmCB?y^%dFR0!6ceC2?Vje@AMN$>c_ARmU^U{@2E!a<=|5*cgREX=`h1Z*N~9 zYtv{nI{jFL$z%=;3=jweaKoOSo|#f3(A(VH3<^N1x3?E$2Q#%sMn=ZR$0sKzr)UXa zCv(-;I4{+>uV8y`RqN~P8yXs#nwmftgTXk_1a|{!puNAp|5#ygaA;^~cz77-jJCc2 zQ;dy`0l|rhiDS*FDWC}!H9I>yH#f&(vF7LJ7Zw)SZ1&>f;?mO6^71l=!{HW6a?7;1 zczrIHyRx#fy1L3+Ve@#rwY4=qpTEAozOk{fwY9a4SKi*<-r3m^2n4&kyL(%6dwYBP z`}+q62Zx7;M^$P^B%Px=lMyts2E3!EF%Gtl5Fud^Q8BSI;u4ZlGBUDqa`K8$Wfc{e z+PU-U>gpPr7qoSBFJ8K=r>AFd@V2}dBTQMPvWPA;zA-rhfkN5%h= z@F+PYH7zGMH?QO!kyQ7-v9YHTZn7=>EtVpXVw{ z0_+nH8K%CGXmq0ffe|Zp`~0{`;A3I!KNKjWJ}4@$I*8qM^LJDFq?#mJzJ@v>a-SM8 zHi#R;sJq{c#z^@!kk8n~2=-APGGRI7*tQQ&#&Ja$VtfIO9h&t%r0>IkqiN_jH3_>U zCGVKCt#5}(k-dEBvo0vFs?7$%Qug=VP?n+RuRe_C;y1GREMiFCZ^deaZm2n$=|K+P zOhOpQUdgUW7 zhqJ)&da1SR%ej>;j;x$u{|Uzco|j3L%o~c8Eh0F`b*QMUFQl^Lu3IZ2_`y}9hc2kn z$i`RR6O3GGx{V|tKf3|VolS`L^DEOwVhGQ*yj(=opge|Ps)Bn literal 0 HcmV?d00001 diff --git a/toxygen/third_party/qweechat/data/icons/preferences-other.png b/toxygen/third_party/qweechat/data/icons/preferences-other.png new file mode 100644 index 0000000000000000000000000000000000000000..711881ebf73e6c0960ca21701eb9fcaa3e2b7861 GIT binary patch literal 1906 zcmV-&2aWiNP)Px#32;bRa{vI{bpQa}bpfo0!-D_-00(qQO+^RU3LgwKH?g7@vj6}924YJ`L;(K) z{{a7>y{D4^00#0&L_t(o!@XAtOq5p;cCpx2D=k-7ZLv~Iqk=S+!{r81QBzSVit%i$ zHP!&eqeTTJ0znf<@jwCV!Lh5LAe6PBT!Ns>6%eoz7uaQ&l|?xeaB(g2rZZb0tzx5Q z>7RW0-_Fe2dGF1eZ{{B}=6`%#TwF%q$+T(HIQV-1+_`hVR904WG&VLub91v=EWY=9 zWMqUT>NumlhKUz1UX-@Bw!*{qhtSp4rNLA6Q>Ik5!ip6uoJVsJ?*s${9BWauKu3Eg z^gek4YPA}Qi;Ka}&#&3U#3T-F%n&-GwSW)e;^G>+9(6%)Zx1|w-VX|e;t9%kA!z3& zh;gHN{8O%6xq?UD3Ekb@pz2e>-Me?iD4$BFGupA|xVyW172PO=+S*#^=xB#_1jc=U zcJAO{uQ4((Fc`H3jN83?_wk(EYfxTZ4)PW`NSmb~l}TB0%7q7RZZ0z@_G{O#u}nxz zNZYk*r$7E4tIY*WI2m*DkD{VN*4EYrqEZoH>Ooyy4cxq0%%V>mA1Em)zEx3C39+%U zFlWx34cZRNjP#5&ND^Ft3n>@ihpk&6{LmpNEf)cWB|hOCR8>{MrAwFCj-5L?(SD{j zvq3jJJp71M+5{epm%xpZLdd(G12bmLgtD?*kdPP;F|jd_mzT#PA|k-d?2BNW^O3fk z>#SbAdO>}CJurMyQ&ZvFm0nPD=QjAPT?5G}$#5X}0QhhBhv48~u(GmB!8u=QYxg>v zHf>rWm&-vQ5U`q>8i`+mCkM2*<&g8)@s}al*pFwkefL*sx&( zb8>M6S2q_X6bgaI;|WkdA2EF}&hKfPdO63A9SgpH|2`~R?#W!|Im7JP7A!Y67hGLk z`KUK1PB?u!VR!-nXwUiCvu96Yc?FL}3(>g?d}cZoa&mIO)6-Kp7~kRBEs@A7o0^&{ z|H&0^<<-l}i(X@~%%+LOVmxkFa6{+ZNnFUx%!JLGH;Yhj#pkE2!QDb==pio?lPRVO zg|eGKW0b8RT}Fm*<(oDb^m-SIOc8Osld~hZxH*HNp#kvuNw9bC9x65tWP|vsw^xNF z_!)y29+HucY+l>Bsi`S74tfOz1+^lP2ppUoz!@)`zJWeO9f@L5QBm!vU!0PXxIrGEW-@y>l+{~O{f8lNk%$>AlZ*>b8`#V|EF{0YI4p+$FkhqJaBNd2S+D+ zFfh~yY&uwCV&YTOuR$2f0?KZoMOJd`@q-tXE{PfW0H}MY-k}e zSzG@rQ_{)FiGw*jt-89pBO@b&**n?+!N|xEHm=`D>Bg|EQZ+NSwdGNYIo8zNQ?<8u zLsC*I+q*Zk+uM7&+0g&dm}I0Q8?vQ2K0a$XBgI_D!otEF8wnMk&u6r2I|m*Z8ymsG zg&wS^s0hr>&BM_2QyUxJ&>tAcWDh|qRX}89ENtKIH`mY4fA~LXOfu4u4cXG1mz<9u zKVAo$in&cqP5nrz%+c8acy_j6#5E=khtkqgSg>HhuY)9`A(yLHZNs=hHP!2J-%u!CW7X z-M)Ph7ehj#OeqDNc;j`@QQtX1{ zOrdy4t@w`M;D8AP8k6kaJvqzD65%4QKZ}b?ST{6(?3puXe!`nArR*E5SWB|9vWQ|S z-6+?;p_cnq&B*!l**!vG2^17m^p}>_v6hwxNIGgDr-Ys!HIPgss$=>2W&N3%#mEO) zJws(#HzXt^Fh4(^92rcUIFXLUoOYg;mez}79}b7};eT<)s#WXf;mgw6n&*X=Y@o4G zjyL^2bar-XK;yn~&T+A5n=#rw>E$9XdCB zUFHl63wOnxLUnb`V~Ir4r&6ha(9|U9tE#&F7zqo=W~8~3JUl!OV6o}LUBkhH2OH4& zI&^OQCUwKtcgOt7%G*k7Yil>UWDN}sodg<_tfHbyNj4*PH|XpWe7hr-A#CyY+cu5k sJUy3bZujNOmy-xIUb@tiGty_-U$X~A41LTT%m4rY07*qoM6N<$f(bx|H~;_u literal 0 HcmV?d00001 diff --git a/toxygen/third_party/qweechat/data/icons/weechat.png b/toxygen/third_party/qweechat/data/icons/weechat.png new file mode 100644 index 0000000000000000000000000000000000000000..7eca5c8d6e06516fc48ba7e43acd40bb14221df8 GIT binary patch literal 1782 zcmVNAZT=Sa5^t9cV%T`Xkm0NZ*pfZasXu^ z000I_NklU2Igx703TG_wIVvi$B0N{)B|a#Xv|vf*^<-wW0>0L{*zSgo=_@ zNrfyG5v7Qfx2Q=3m0GE4m4`~aM5$USZKX!75{b4XSeBbQw$letW+^qqdWJ`+;e{CKj+R2aKGFy|KlS5Q^&@w&B)HJmLFqBUO(Ir zZ>p;g0+sL!VN8YE4t*6P7uaJK~2X05gPPKr=%TK@+n!kwn^%@O8k``S$_%H31HNd*53vTQ}}fT36Vm z5U^~C;uo%$o?N;U6vIpyC|`xz)xLJaKo^y-U1P{2BA=LiW7w;@dt}JhL_Yb(r<=to z0K5+1(20FV9@yJ`wBlR}2#&4&jI`aKup^4(WXruea&6H zb<(nIX~iL=z;A!h{|tb4)&V?q?r@z6%?E$`)r9TleAmtUdC&24MaOfDGVa{i{QCgh z%NM@&$kB6eUa;ax09^Ur&#eUM>CsLAIP~4u9&c>lx>H)QWaXci7Ur)F&AOSpcgpY9 z0Q~ulNuvXGDb?2S)|TDxOH(325cQ$!ScwfApY;pb z5df*qod-`wb5pgV34!#~=s1AcCrB39m;fThi<4s?8x>9gkZoV;Kknr;Kn&)R zcVQzvHFOJ%aR6xV8yGYy1?A}~K*r+r@o@n2wE)DHN1r}j%mg4RBLmDp=sN!VCqq{N z6n7mvw;kO4h?iC1a`eQImc+I9esLAR4FG7^y#IS{CIm5+#zYECUwPxN01E2>dizfu zk+F_$cU4t6XD~~w%uUZa=}$ibz;%f&2SYEmS@}9ri2xP?#mtRdc7AdQK=9!H!Dm3N zjm1?}QVD>tu(~jDM|sZJn%|}bAX^^z+Bbbi+guenGed|NZVg`=0x%m5-*hr4NDvu- zxs-}>~LY9`Zs*mDecP4oiV zU((An!&d?10d!ljZ3B_YfN7`_4^ zSO*Zg;cilmeV$W_stSOq-rn3hxE~_6lHBm%^P!spldeR@1Ta~4N8gXnbnb|sVFpx@ z5VDCBC{1HwdEyp>M{4amwzPVVhHe66bS3l4^vuAfo>MO~)5}bNn++CV!CGin4l*qsR!AGM?A~q(H1RNGT$%z}jafpUHU4#VnazmMOc!lvyT| z{=%5g7TH|C8XZ@7JwV_DSG0fa1UU6W<_&$|Sez&f!TBOlKF{Q2nR3g_&Jt7M9y6@~ zW*Mw9#9oHYvP0&d4v=>N_@!kwEJaM!`@nxYl*R${0B9-iEdW*l6srvL{d4^N@_$$U Y1seB0;07)3N&o-=07*qoM6N<$f|o=#y#N3J literal 0 HcmV?d00001 diff --git a/toxygen/third_party/qweechat/debug.py b/toxygen/third_party/qweechat/debug.py new file mode 100644 index 0000000..785be98 --- /dev/null +++ b/toxygen/third_party/qweechat/debug.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# +# debug.py - debug window +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +"""Debug window.""" + +from PyQt5 import QtWidgets + +from qweechat.chat import ChatTextEdit +from qweechat.input import InputLineEdit + + +class DebugDialog(QtWidgets.QDialog): + """Debug dialog.""" + + def __init__(self, *args): + QtWidgets.QDialog.__init__(*(self,) + args) + self.resize(1024, 768) + self.setWindowTitle('Debug console') + + self.chat = ChatTextEdit(debug=True) + self.input = InputLineEdit(self.chat) + + vbox = QtWidgets.QVBoxLayout() + vbox.addWidget(self.chat) + vbox.addWidget(self.input) + + self.setLayout(vbox) + self.show() + + def display_lines(self, lines): + for line in lines: + self.chat.display(*line[0], **line[1]) diff --git a/toxygen/third_party/qweechat/debug.py.diff b/toxygen/third_party/qweechat/debug.py.diff new file mode 100644 index 0000000..7201803 --- /dev/null +++ b/toxygen/third_party/qweechat/debug.py.diff @@ -0,0 +1,27 @@ +*** debug.py.dst 2022-11-19 18:31:51.000000000 +0000 +--- debug.py 2022-11-19 18:32:41.000000000 +0000 +*************** +*** 20,30 **** + # along with QWeeChat. If not, see . + # + + """Debug window.""" + +! from PySide6 import QtWidgets + + from qweechat.chat import ChatTextEdit + from qweechat.input import InputLineEdit + + +--- 20,30 ---- + # along with QWeeChat. If not, see . + # + + """Debug window.""" + +! from PyQt5 import QtWidgets + + from qweechat.chat import ChatTextEdit + from qweechat.input import InputLineEdit + + diff --git a/toxygen/third_party/qweechat/debug.py.dst b/toxygen/third_party/qweechat/debug.py.dst new file mode 100644 index 0000000..3267adc --- /dev/null +++ b/toxygen/third_party/qweechat/debug.py.dst @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# +# debug.py - debug window +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +"""Debug window.""" + +from PySide6 import QtWidgets + +from qweechat.chat import ChatTextEdit +from qweechat.input import InputLineEdit + + +class DebugDialog(QtWidgets.QDialog): + """Debug dialog.""" + + def __init__(self, *args): + QtWidgets.QDialog.__init__(*(self,) + args) + self.resize(1024, 768) + self.setWindowTitle('Debug console') + + self.chat = ChatTextEdit(debug=True) + self.input = InputLineEdit(self.chat) + + vbox = QtWidgets.QVBoxLayout() + vbox.addWidget(self.chat) + vbox.addWidget(self.input) + + self.setLayout(vbox) + self.show() + + def display_lines(self, lines): + for line in lines: + self.chat.display(*line[0], **line[1]) diff --git a/toxygen/third_party/qweechat/input.py b/toxygen/third_party/qweechat/input.py new file mode 100644 index 0000000..739a63f --- /dev/null +++ b/toxygen/third_party/qweechat/input.py @@ -0,0 +1,96 @@ +# -*- coding: utf-8 -*- +# +# input.py - input line for chat and debug window +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +"""Input line for chat and debug window.""" + +from PyQt5 import QtCore, QtWidgets +from PyQt5.QtCore import pyqtSignal +Signal = pyqtSignal + +class InputLineEdit(QtWidgets.QLineEdit): + """Input line.""" + + bufferSwitchPrev = Signal() + bufferSwitchNext = Signal() + textSent = Signal(str) + + def __init__(self, scroll_widget): + super().__init__() + self.scroll_widget = scroll_widget + self._history = [] + self._history_index = -1 + self.returnPressed.connect(self._input_return_pressed) + + def keyPressEvent(self, event): + key = event.key() + modifiers = event.modifiers() + scroll = self.scroll_widget.verticalScrollBar() + if modifiers == QtCore.Qt.ControlModifier: + if key == QtCore.Qt.Key_PageUp: + self.bufferSwitchPrev.emit() + elif key == QtCore.Qt.Key_PageDown: + self.bufferSwitchNext.emit() + else: + QtWidgets.QLineEdit.keyPressEvent(self, event) + elif modifiers == QtCore.Qt.AltModifier: + if key in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Up): + self.bufferSwitchPrev.emit() + elif key in (QtCore.Qt.Key_Right, QtCore.Qt.Key_Down): + self.bufferSwitchNext.emit() + elif key == QtCore.Qt.Key_PageUp: + scroll.setValue(scroll.value() - (scroll.pageStep() / 10)) + elif key == QtCore.Qt.Key_PageDown: + scroll.setValue(scroll.value() + (scroll.pageStep() / 10)) + elif key == QtCore.Qt.Key_Home: + scroll.setValue(scroll.minimum()) + elif key == QtCore.Qt.Key_End: + scroll.setValue(scroll.maximum()) + else: + QtWidgets.QLineEdit.keyPressEvent(self, event) + elif key == QtCore.Qt.Key_PageUp: + scroll.setValue(scroll.value() - scroll.pageStep()) + elif key == QtCore.Qt.Key_PageDown: + scroll.setValue(scroll.value() + scroll.pageStep()) + elif key == QtCore.Qt.Key_Up: + self._history_navigate(-1) + elif key == QtCore.Qt.Key_Down: + self._history_navigate(1) + else: + QtWidgets.QLineEdit.keyPressEvent(self, event) + + def _input_return_pressed(self): + self._history.append(self.text()) + self._history_index = len(self._history) + self.textSent.emit(self.text()) + self.clear() + + def _history_navigate(self, direction): + if self._history: + self._history_index += direction + if self._history_index < 0: + self._history_index = 0 + return + if self._history_index > len(self._history) - 1: + self._history_index = len(self._history) + self.clear() + return + self.setText(self._history[self._history_index]) diff --git a/toxygen/third_party/qweechat/input.py.diff b/toxygen/third_party/qweechat/input.py.diff new file mode 100644 index 0000000..1b4c420 --- /dev/null +++ b/toxygen/third_party/qweechat/input.py.diff @@ -0,0 +1,27 @@ +*** input.py.dst 2022-11-19 18:31:51.000000000 +0000 +--- input.py 2022-11-19 18:32:41.000000000 +0000 +*************** +*** 20,30 **** + # along with QWeeChat. If not, see . + # + + """Input line for chat and debug window.""" + +! from PySide6 import QtCore, QtWidgets + + + class InputLineEdit(QtWidgets.QLineEdit): + """Input line.""" + +--- 20,30 ---- + # along with QWeeChat. If not, see . + # + + """Input line for chat and debug window.""" + +! from PyQt5 import QtCore, QtWidgets + + + class InputLineEdit(QtWidgets.QLineEdit): + """Input line.""" + diff --git a/toxygen/third_party/qweechat/input.py.dst b/toxygen/third_party/qweechat/input.py.dst new file mode 100644 index 0000000..1ec3d3d --- /dev/null +++ b/toxygen/third_party/qweechat/input.py.dst @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +# +# input.py - input line for chat and debug window +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +"""Input line for chat and debug window.""" + +from PySide6 import QtCore, QtWidgets + + +class InputLineEdit(QtWidgets.QLineEdit): + """Input line.""" + + bufferSwitchPrev = QtCore.Signal() + bufferSwitchNext = QtCore.Signal() + textSent = QtCore.Signal(str) + + def __init__(self, scroll_widget): + super().__init__() + self.scroll_widget = scroll_widget + self._history = [] + self._history_index = -1 + self.returnPressed.connect(self._input_return_pressed) + + def keyPressEvent(self, event): + key = event.key() + modifiers = event.modifiers() + scroll = self.scroll_widget.verticalScrollBar() + if modifiers == QtCore.Qt.ControlModifier: + if key == QtCore.Qt.Key_PageUp: + self.bufferSwitchPrev.emit() + elif key == QtCore.Qt.Key_PageDown: + self.bufferSwitchNext.emit() + else: + QtWidgets.QLineEdit.keyPressEvent(self, event) + elif modifiers == QtCore.Qt.AltModifier: + if key in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Up): + self.bufferSwitchPrev.emit() + elif key in (QtCore.Qt.Key_Right, QtCore.Qt.Key_Down): + self.bufferSwitchNext.emit() + elif key == QtCore.Qt.Key_PageUp: + scroll.setValue(scroll.value() - (scroll.pageStep() / 10)) + elif key == QtCore.Qt.Key_PageDown: + scroll.setValue(scroll.value() + (scroll.pageStep() / 10)) + elif key == QtCore.Qt.Key_Home: + scroll.setValue(scroll.minimum()) + elif key == QtCore.Qt.Key_End: + scroll.setValue(scroll.maximum()) + else: + QtWidgets.QLineEdit.keyPressEvent(self, event) + elif key == QtCore.Qt.Key_PageUp: + scroll.setValue(scroll.value() - scroll.pageStep()) + elif key == QtCore.Qt.Key_PageDown: + scroll.setValue(scroll.value() + scroll.pageStep()) + elif key == QtCore.Qt.Key_Up: + self._history_navigate(-1) + elif key == QtCore.Qt.Key_Down: + self._history_navigate(1) + else: + QtWidgets.QLineEdit.keyPressEvent(self, event) + + def _input_return_pressed(self): + self._history.append(self.text()) + self._history_index = len(self._history) + self.textSent.emit(self.text()) + self.clear() + + def _history_navigate(self, direction): + if self._history: + self._history_index += direction + if self._history_index < 0: + self._history_index = 0 + return + if self._history_index > len(self._history) - 1: + self._history_index = len(self._history) + self.clear() + return + self.setText(self._history[self._history_index]) diff --git a/toxygen/third_party/qweechat/network.py b/toxygen/third_party/qweechat/network.py new file mode 100644 index 0000000..5e3fe65 --- /dev/null +++ b/toxygen/third_party/qweechat/network.py @@ -0,0 +1,358 @@ +# -*- coding: utf-8 -*- +# +# network.py - I/O with WeeChat/relay +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +"""I/O with WeeChat/relay.""" + +import hashlib +import secrets +import struct + +from PyQt5 import QtCore, QtNetwork +from PyQt5.QtCore import pyqtSignal +Signal = pyqtSignal + +from qweechat import config +from qweechat.debug import DebugDialog + + +# list of supported hash algorithms on our side +# (the hash algorithm will be negotiated with the remote WeeChat) +_HASH_ALGOS_LIST = [ + 'plain', + 'sha256', + 'sha512', + 'pbkdf2+sha256', + 'pbkdf2+sha512', +] +_HASH_ALGOS = ':'.join(_HASH_ALGOS_LIST) + +# handshake with remote WeeChat (before init) +_PROTO_HANDSHAKE = f'(handshake) handshake password_hash_algo={_HASH_ALGOS}\n' + +# initialize with the password (plain text) +_PROTO_INIT_PWD = 'init password=%(password)s%(totp)s\n' # nosec + +# initialize with the hashed password +_PROTO_INIT_HASH = ('init password_hash=' + '%(algo)s:%(salt)s%(iter)s:%(hash)s%(totp)s\n') + +_PROTO_SYNC_CMDS = [ + # get buffers + '(listbuffers) hdata buffer:gui_buffers(*) number,full_name,short_name,' + 'type,nicklist,title,local_variables', + # get lines + '(listlines) hdata buffer:gui_buffers(*)/own_lines/last_line(-%(lines)d)/' + 'data date,displayed,prefix,message', + # get nicklist for all buffers + '(nicklist) nicklist', + # enable synchronization + 'sync', +] + +STATUS_DISCONNECTED = 'disconnected' +STATUS_CONNECTING = 'connecting' +STATUS_AUTHENTICATING = 'authenticating' +STATUS_CONNECTED = 'connected' + +NETWORK_STATUS = { + STATUS_DISCONNECTED: { + 'label': 'Disconnected', + 'color': '#aa0000', + 'icon': 'dialog-close.png', + }, + STATUS_CONNECTING: { + 'label': 'Connecting…', + 'color': '#dd5f00', + 'icon': 'dialog-warning.png', + }, + STATUS_AUTHENTICATING: { + 'label': 'Authenticating…', + 'color': '#007fff', + 'icon': 'dialog-password.png', + }, + STATUS_CONNECTED: { + 'label': 'Connected', + 'color': 'green', + 'icon': 'dialog-ok-apply.png', + }, +} + + +class Network(QtCore.QObject): + """I/O with WeeChat/relay.""" + + statusChanged = Signal(str, str) + messageFromWeechat = Signal(QtCore.QByteArray) + + def __init__(self, *args): + super().__init__(*args) + self._init_connection() + self.debug_lines = [] + self.debug_dialog = None + self._lines = config.CONFIG_DEFAULT_RELAY_LINES + self._buffer = QtCore.QByteArray() + self._socket = QtNetwork.QSslSocket() + self._socket.connected.connect(self._socket_connected) + self._socket.readyRead.connect(self._socket_read) + self._socket.disconnected.connect(self._socket_disconnected) + + def _init_connection(self): + self.status = STATUS_DISCONNECTED + self._hostname = None + self._port = None + self._ssl = None + self._password = None + self._totp = None + self._handshake_received = False + self._handshake_timer = None + self._handshake_timer = False + self._pwd_hash_algo = None + self._pwd_hash_iter = 0 + self._server_nonce = None + + def set_status(self, status): + """Set current status.""" + self.status = status + self.statusChanged.emit(status, None) + + def pbkdf2(self, hash_name, salt): + """Return hashed password with PBKDF2-HMAC.""" + return hashlib.pbkdf2_hmac( + hash_name, + password=self._password.encode('utf-8'), + salt=salt, + iterations=self._pwd_hash_iter, + ).hex() + + def _build_init_command(self): + """Build the init command to send to WeeChat.""" + totp = f',totp={self._totp}' if self._totp else '' + if self._pwd_hash_algo == 'plain': + cmd = _PROTO_INIT_PWD % { + 'password': self._password, + 'totp': totp, + } + else: + client_nonce = secrets.token_bytes(16) + salt = self._server_nonce + client_nonce + pwd_hash = None + iterations = '' + if self._pwd_hash_algo == 'pbkdf2+sha512': + pwd_hash = self.pbkdf2('sha512', salt) + iterations = f':{self._pwd_hash_iter}' + elif self._pwd_hash_algo == 'pbkdf2+sha256': + pwd_hash = self.pbkdf2('sha256', salt) + iterations = f':{self._pwd_hash_iter}' + elif self._pwd_hash_algo == 'sha512': + pwd = salt + self._password.encode('utf-8') + pwd_hash = hashlib.sha512(pwd).hexdigest() + elif self._pwd_hash_algo == 'sha256': + pwd = salt + self._password.encode('utf-8') + pwd_hash = hashlib.sha256(pwd).hexdigest() + if not pwd_hash: + return None + cmd = _PROTO_INIT_HASH % { + 'algo': self._pwd_hash_algo, + 'salt': bytearray(salt).hex(), + 'iter': iterations, + 'hash': pwd_hash, + 'totp': totp, + } + return cmd + + def _build_sync_command(self): + """Build the sync commands to send to WeeChat.""" + cmd = '\n'.join(_PROTO_SYNC_CMDS) + '\n' + return cmd % {'lines': self._lines} + + def handshake_timer_expired(self): + if self.status == STATUS_AUTHENTICATING: + self._pwd_hash_algo = 'plain' + self.send_to_weechat(self._build_init_command()) + self.sync_weechat() + self.set_status(STATUS_CONNECTED) + + def _socket_connected(self): + """Slot: socket connected.""" + self.set_status(STATUS_AUTHENTICATING) + self.send_to_weechat(_PROTO_HANDSHAKE) + self._handshake_timer = QtCore.QTimer() + self._handshake_timer.setSingleShot(True) + self._handshake_timer.setInterval(2000) + self._handshake_timer.timeout.connect(self.handshake_timer_expired) + self._handshake_timer.start() + + def _socket_read(self): + """Slot: data available on socket.""" + data = self._socket.readAll() + self._buffer.append(data) + while len(self._buffer) >= 4: + remainder = None + length = struct.unpack('>i', self._buffer[0:4].data())[0] + if len(self._buffer) < length: + # partial message, just wait for end of message + break + # more than one message? + if length < len(self._buffer): + # save beginning of another message + remainder = self._buffer[length:] + self._buffer = self._buffer[0:length] + self.messageFromWeechat.emit(self._buffer) + if not self.is_connected(): + return + self._buffer.clear() + if remainder: + self._buffer.append(remainder) + + def _socket_disconnected(self): + """Slot: socket disconnected.""" + if self._handshake_timer: + self._handshake_timer.stop() + self._init_connection() + self.set_status(STATUS_DISCONNECTED) + + def is_connected(self): + """Return True if the socket is connected, False otherwise.""" + return self._socket.state() == QtNetwork.QAbstractSocket.ConnectedState + + def is_ssl(self): + """Return True if SSL is used, False otherwise.""" + return self._ssl + + def connect_weechat(self, hostname, port, ssl, password, totp, lines): + """Connect to WeeChat.""" + self._hostname = hostname + try: + self._port = int(port) + except ValueError: + self._port = 0 + self._ssl = ssl + self._password = password + self._totp = totp + try: + self._lines = int(lines) + except ValueError: + self._lines = config.CONFIG_DEFAULT_RELAY_LINES + if self._socket.state() == QtNetwork.QAbstractSocket.ConnectedState: + return + if self._socket.state() != QtNetwork.QAbstractSocket.UnconnectedState: + self._socket.abort() + if self._ssl: + self._socket.ignoreSslErrors() + self._socket.connectToHostEncrypted(self._hostname, self._port) + else: + self._socket.connectToHost(self._hostname, self._port) + self.set_status(STATUS_CONNECTING) + + def disconnect_weechat(self): + """Disconnect from WeeChat.""" + if self._socket.state() == QtNetwork.QAbstractSocket.UnconnectedState: + self.set_status(STATUS_DISCONNECTED) + return + if self._socket.state() == QtNetwork.QAbstractSocket.ConnectedState: + self.send_to_weechat('quit\n') + self._socket.waitForBytesWritten(1000) + else: + self.set_status(STATUS_DISCONNECTED) + self._socket.abort() + + def send_to_weechat(self, message): + """Send a message to WeeChat.""" + self.debug_print(0, '<==', message, forcecolor='#AA0000') + self._socket.write(message.encode('utf-8')) + + def init_with_handshake(self, response): + """Initialize with WeeChat using the handshake response.""" + self._pwd_hash_algo = response['password_hash_algo'] + self._pwd_hash_iter = int(response['password_hash_iterations']) + self._server_nonce = bytearray.fromhex(response['nonce']) + if self._pwd_hash_algo: + cmd = self._build_init_command() + if cmd: + self.send_to_weechat(cmd) + self.sync_weechat() + self.set_status(STATUS_CONNECTED) + return + # failed to initialize: disconnect + self.disconnect_weechat() + + def desync_weechat(self): + """Desynchronize from WeeChat.""" + self.send_to_weechat('desync\n') + + def sync_weechat(self): + """Synchronize with WeeChat.""" + self.send_to_weechat(self._build_sync_command()) + + def status_label(self, status): + """Return the label for a given status.""" + return NETWORK_STATUS.get(status, {}).get('label', '') + + def status_color(self, status): + """Return the color for a given status.""" + return NETWORK_STATUS.get(status, {}).get('color', 'black') + + def status_icon(self, status): + """Return the name of icon for a given status.""" + return NETWORK_STATUS.get(status, {}).get('icon', '') + + def get_options(self): + """Get connection options.""" + return { + 'hostname': self._hostname, + 'port': self._port, + 'ssl': 'on' if self._ssl else 'off', + 'password': self._password, + 'lines': str(self._lines), + } + + def debug_print(self, *args, **kwargs): + """Display a debug message.""" + self.debug_lines.append((args, kwargs)) + if self.debug_dialog: + self.debug_dialog.chat.display(*args, **kwargs) + + def _debug_dialog_closed(self, result): + """Called when debug dialog is closed.""" + self.debug_dialog = None + + def debug_input_text_sent(self, text): + """Send debug buffer input to WeeChat.""" + if self.network.is_connected(): + text = str(text) + pos = text.find(')') + if text.startswith('(') and pos >= 0: + text = '(debug_%s)%s' % (text[1:pos], text[pos+1:]) + else: + text = '(debug) %s' % text + self.network.debug_print(0, '<==', text, forcecolor='#AA0000') + self.network.send_to_weechat(text + '\n') + + def open_debug_dialog(self): + """Open a dialog with debug messages.""" + if not self.debug_dialog: + self.debug_dialog = DebugDialog() + self.debug_dialog.input.textSent.connect( + self.debug_input_text_sent) + self.debug_dialog.finished.connect(self._debug_dialog_closed) + self.debug_dialog.display_lines(self.debug_lines) + self.debug_dialog.chat.scroll_bottom() diff --git a/toxygen/third_party/qweechat/network.py.diff b/toxygen/third_party/qweechat/network.py.diff new file mode 100644 index 0000000..026d69c --- /dev/null +++ b/toxygen/third_party/qweechat/network.py.diff @@ -0,0 +1,27 @@ +*** network.py.dst 2022-11-19 18:31:51.000000000 +0000 +--- network.py 2022-11-19 18:32:41.000000000 +0000 +*************** +*** 24,34 **** + + import hashlib + import secrets + import struct + +! from PySide6 import QtCore, QtNetwork + + from qweechat import config + from qweechat.debug import DebugDialog + + +--- 24,34 ---- + + import hashlib + import secrets + import struct + +! from PyQt5 import QtCore, QtNetwork + + from qweechat import config + from qweechat.debug import DebugDialog + + diff --git a/toxygen/third_party/qweechat/network.py.dst b/toxygen/third_party/qweechat/network.py.dst new file mode 100644 index 0000000..b7d802c --- /dev/null +++ b/toxygen/third_party/qweechat/network.py.dst @@ -0,0 +1,356 @@ +# -*- coding: utf-8 -*- +# +# network.py - I/O with WeeChat/relay +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +"""I/O with WeeChat/relay.""" + +import hashlib +import secrets +import struct + +from PySide6 import QtCore, QtNetwork + +from qweechat import config +from qweechat.debug import DebugDialog + + +# list of supported hash algorithms on our side +# (the hash algorithm will be negotiated with the remote WeeChat) +_HASH_ALGOS_LIST = [ + 'plain', + 'sha256', + 'sha512', + 'pbkdf2+sha256', + 'pbkdf2+sha512', +] +_HASH_ALGOS = ':'.join(_HASH_ALGOS_LIST) + +# handshake with remote WeeChat (before init) +_PROTO_HANDSHAKE = f'(handshake) handshake password_hash_algo={_HASH_ALGOS}\n' + +# initialize with the password (plain text) +_PROTO_INIT_PWD = 'init password=%(password)s%(totp)s\n' # nosec + +# initialize with the hashed password +_PROTO_INIT_HASH = ('init password_hash=' + '%(algo)s:%(salt)s%(iter)s:%(hash)s%(totp)s\n') + +_PROTO_SYNC_CMDS = [ + # get buffers + '(listbuffers) hdata buffer:gui_buffers(*) number,full_name,short_name,' + 'type,nicklist,title,local_variables', + # get lines + '(listlines) hdata buffer:gui_buffers(*)/own_lines/last_line(-%(lines)d)/' + 'data date,displayed,prefix,message', + # get nicklist for all buffers + '(nicklist) nicklist', + # enable synchronization + 'sync', +] + +STATUS_DISCONNECTED = 'disconnected' +STATUS_CONNECTING = 'connecting' +STATUS_AUTHENTICATING = 'authenticating' +STATUS_CONNECTED = 'connected' + +NETWORK_STATUS = { + STATUS_DISCONNECTED: { + 'label': 'Disconnected', + 'color': '#aa0000', + 'icon': 'dialog-close.png', + }, + STATUS_CONNECTING: { + 'label': 'Connecting…', + 'color': '#dd5f00', + 'icon': 'dialog-warning.png', + }, + STATUS_AUTHENTICATING: { + 'label': 'Authenticating…', + 'color': '#007fff', + 'icon': 'dialog-password.png', + }, + STATUS_CONNECTED: { + 'label': 'Connected', + 'color': 'green', + 'icon': 'dialog-ok-apply.png', + }, +} + + +class Network(QtCore.QObject): + """I/O with WeeChat/relay.""" + + statusChanged = QtCore.Signal(str, str) + messageFromWeechat = QtCore.Signal(QtCore.QByteArray) + + def __init__(self, *args): + super().__init__(*args) + self._init_connection() + self.debug_lines = [] + self.debug_dialog = None + self._lines = config.CONFIG_DEFAULT_RELAY_LINES + self._buffer = QtCore.QByteArray() + self._socket = QtNetwork.QSslSocket() + self._socket.connected.connect(self._socket_connected) + self._socket.readyRead.connect(self._socket_read) + self._socket.disconnected.connect(self._socket_disconnected) + + def _init_connection(self): + self.status = STATUS_DISCONNECTED + self._hostname = None + self._port = None + self._ssl = None + self._password = None + self._totp = None + self._handshake_received = False + self._handshake_timer = None + self._handshake_timer = False + self._pwd_hash_algo = None + self._pwd_hash_iter = 0 + self._server_nonce = None + + def set_status(self, status): + """Set current status.""" + self.status = status + self.statusChanged.emit(status, None) + + def pbkdf2(self, hash_name, salt): + """Return hashed password with PBKDF2-HMAC.""" + return hashlib.pbkdf2_hmac( + hash_name, + password=self._password.encode('utf-8'), + salt=salt, + iterations=self._pwd_hash_iter, + ).hex() + + def _build_init_command(self): + """Build the init command to send to WeeChat.""" + totp = f',totp={self._totp}' if self._totp else '' + if self._pwd_hash_algo == 'plain': + cmd = _PROTO_INIT_PWD % { + 'password': self._password, + 'totp': totp, + } + else: + client_nonce = secrets.token_bytes(16) + salt = self._server_nonce + client_nonce + pwd_hash = None + iterations = '' + if self._pwd_hash_algo == 'pbkdf2+sha512': + pwd_hash = self.pbkdf2('sha512', salt) + iterations = f':{self._pwd_hash_iter}' + elif self._pwd_hash_algo == 'pbkdf2+sha256': + pwd_hash = self.pbkdf2('sha256', salt) + iterations = f':{self._pwd_hash_iter}' + elif self._pwd_hash_algo == 'sha512': + pwd = salt + self._password.encode('utf-8') + pwd_hash = hashlib.sha512(pwd).hexdigest() + elif self._pwd_hash_algo == 'sha256': + pwd = salt + self._password.encode('utf-8') + pwd_hash = hashlib.sha256(pwd).hexdigest() + if not pwd_hash: + return None + cmd = _PROTO_INIT_HASH % { + 'algo': self._pwd_hash_algo, + 'salt': bytearray(salt).hex(), + 'iter': iterations, + 'hash': pwd_hash, + 'totp': totp, + } + return cmd + + def _build_sync_command(self): + """Build the sync commands to send to WeeChat.""" + cmd = '\n'.join(_PROTO_SYNC_CMDS) + '\n' + return cmd % {'lines': self._lines} + + def handshake_timer_expired(self): + if self.status == STATUS_AUTHENTICATING: + self._pwd_hash_algo = 'plain' + self.send_to_weechat(self._build_init_command()) + self.sync_weechat() + self.set_status(STATUS_CONNECTED) + + def _socket_connected(self): + """Slot: socket connected.""" + self.set_status(STATUS_AUTHENTICATING) + self.send_to_weechat(_PROTO_HANDSHAKE) + self._handshake_timer = QtCore.QTimer() + self._handshake_timer.setSingleShot(True) + self._handshake_timer.setInterval(2000) + self._handshake_timer.timeout.connect(self.handshake_timer_expired) + self._handshake_timer.start() + + def _socket_read(self): + """Slot: data available on socket.""" + data = self._socket.readAll() + self._buffer.append(data) + while len(self._buffer) >= 4: + remainder = None + length = struct.unpack('>i', self._buffer[0:4].data())[0] + if len(self._buffer) < length: + # partial message, just wait for end of message + break + # more than one message? + if length < len(self._buffer): + # save beginning of another message + remainder = self._buffer[length:] + self._buffer = self._buffer[0:length] + self.messageFromWeechat.emit(self._buffer) + if not self.is_connected(): + return + self._buffer.clear() + if remainder: + self._buffer.append(remainder) + + def _socket_disconnected(self): + """Slot: socket disconnected.""" + if self._handshake_timer: + self._handshake_timer.stop() + self._init_connection() + self.set_status(STATUS_DISCONNECTED) + + def is_connected(self): + """Return True if the socket is connected, False otherwise.""" + return self._socket.state() == QtNetwork.QAbstractSocket.ConnectedState + + def is_ssl(self): + """Return True if SSL is used, False otherwise.""" + return self._ssl + + def connect_weechat(self, hostname, port, ssl, password, totp, lines): + """Connect to WeeChat.""" + self._hostname = hostname + try: + self._port = int(port) + except ValueError: + self._port = 0 + self._ssl = ssl + self._password = password + self._totp = totp + try: + self._lines = int(lines) + except ValueError: + self._lines = config.CONFIG_DEFAULT_RELAY_LINES + if self._socket.state() == QtNetwork.QAbstractSocket.ConnectedState: + return + if self._socket.state() != QtNetwork.QAbstractSocket.UnconnectedState: + self._socket.abort() + if self._ssl: + self._socket.ignoreSslErrors() + self._socket.connectToHostEncrypted(self._hostname, self._port) + else: + self._socket.connectToHost(self._hostname, self._port) + self.set_status(STATUS_CONNECTING) + + def disconnect_weechat(self): + """Disconnect from WeeChat.""" + if self._socket.state() == QtNetwork.QAbstractSocket.UnconnectedState: + self.set_status(STATUS_DISCONNECTED) + return + if self._socket.state() == QtNetwork.QAbstractSocket.ConnectedState: + self.send_to_weechat('quit\n') + self._socket.waitForBytesWritten(1000) + else: + self.set_status(STATUS_DISCONNECTED) + self._socket.abort() + + def send_to_weechat(self, message): + """Send a message to WeeChat.""" + self.debug_print(0, '<==', message, forcecolor='#AA0000') + self._socket.write(message.encode('utf-8')) + + def init_with_handshake(self, response): + """Initialize with WeeChat using the handshake response.""" + self._pwd_hash_algo = response['password_hash_algo'] + self._pwd_hash_iter = int(response['password_hash_iterations']) + self._server_nonce = bytearray.fromhex(response['nonce']) + if self._pwd_hash_algo: + cmd = self._build_init_command() + if cmd: + self.send_to_weechat(cmd) + self.sync_weechat() + self.set_status(STATUS_CONNECTED) + return + # failed to initialize: disconnect + self.disconnect_weechat() + + def desync_weechat(self): + """Desynchronize from WeeChat.""" + self.send_to_weechat('desync\n') + + def sync_weechat(self): + """Synchronize with WeeChat.""" + self.send_to_weechat(self._build_sync_command()) + + def status_label(self, status): + """Return the label for a given status.""" + return NETWORK_STATUS.get(status, {}).get('label', '') + + def status_color(self, status): + """Return the color for a given status.""" + return NETWORK_STATUS.get(status, {}).get('color', 'black') + + def status_icon(self, status): + """Return the name of icon for a given status.""" + return NETWORK_STATUS.get(status, {}).get('icon', '') + + def get_options(self): + """Get connection options.""" + return { + 'hostname': self._hostname, + 'port': self._port, + 'ssl': 'on' if self._ssl else 'off', + 'password': self._password, + 'lines': str(self._lines), + } + + def debug_print(self, *args, **kwargs): + """Display a debug message.""" + self.debug_lines.append((args, kwargs)) + if self.debug_dialog: + self.debug_dialog.chat.display(*args, **kwargs) + + def _debug_dialog_closed(self, result): + """Called when debug dialog is closed.""" + self.debug_dialog = None + + def debug_input_text_sent(self, text): + """Send debug buffer input to WeeChat.""" + if self.network.is_connected(): + text = str(text) + pos = text.find(')') + if text.startswith('(') and pos >= 0: + text = '(debug_%s)%s' % (text[1:pos], text[pos+1:]) + else: + text = '(debug) %s' % text + self.network.debug_print(0, '<==', text, forcecolor='#AA0000') + self.network.send_to_weechat(text + '\n') + + def open_debug_dialog(self): + """Open a dialog with debug messages.""" + if not self.debug_dialog: + self.debug_dialog = DebugDialog() + self.debug_dialog.input.textSent.connect( + self.debug_input_text_sent) + self.debug_dialog.finished.connect(self._debug_dialog_closed) + self.debug_dialog.display_lines(self.debug_lines) + self.debug_dialog.chat.scroll_bottom() diff --git a/toxygen/third_party/qweechat/preferences.py b/toxygen/third_party/qweechat/preferences.py new file mode 100644 index 0000000..fc415da --- /dev/null +++ b/toxygen/third_party/qweechat/preferences.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# +# preferences.py - preferences dialog box +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +"""Preferences dialog box.""" + +from PyQt5 import QtCore, QtWidgets as QtGui + + +class PreferencesDialog(QtGui.QDialog): + """Preferences dialog.""" + + def __init__(self, *args): + QtGui.QDialog.__init__(*(self,) + args) + self.setModal(True) + self.setWindowTitle('Preferences') + + close_button = QtGui.QPushButton('Close') + close_button.pressed.connect(self.close) + + hbox = QtGui.QHBoxLayout() + hbox.addStretch(1) + hbox.addWidget(close_button) + hbox.addStretch(1) + + vbox = QtGui.QVBoxLayout() + + label = QtGui.QLabel('Not yet implemented!') + label.setAlignment(QtCore.Qt.AlignHCenter) + vbox.addWidget(label) + + label = QtGui.QLabel('') + label.setAlignment(QtCore.Qt.AlignHCenter) + vbox.addWidget(label) + + vbox.addLayout(hbox) + + self.setLayout(vbox) + self.show() diff --git a/toxygen/third_party/qweechat/preferences.py.diff b/toxygen/third_party/qweechat/preferences.py.diff new file mode 100644 index 0000000..17a298b --- /dev/null +++ b/toxygen/third_party/qweechat/preferences.py.diff @@ -0,0 +1,27 @@ +*** preferences.py.dst 2022-11-19 18:31:51.000000000 +0000 +--- preferences.py 2022-11-19 18:32:41.000000000 +0000 +*************** +*** 20,30 **** + # along with QWeeChat. If not, see . + # + + """Preferences dialog box.""" + +! from PySide6 import QtCore, QtWidgets as QtGui + + + class PreferencesDialog(QtGui.QDialog): + """Preferences dialog.""" + +--- 20,30 ---- + # along with QWeeChat. If not, see . + # + + """Preferences dialog box.""" + +! from PyQt5 import QtCore, QtWidgets as QtGui + + + class PreferencesDialog(QtGui.QDialog): + """Preferences dialog.""" + diff --git a/toxygen/third_party/qweechat/preferences.py.dst b/toxygen/third_party/qweechat/preferences.py.dst new file mode 100644 index 0000000..f760bbc --- /dev/null +++ b/toxygen/third_party/qweechat/preferences.py.dst @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# +# preferences.py - preferences dialog box +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +"""Preferences dialog box.""" + +from PySide6 import QtCore, QtWidgets as QtGui + + +class PreferencesDialog(QtGui.QDialog): + """Preferences dialog.""" + + def __init__(self, *args): + QtGui.QDialog.__init__(*(self,) + args) + self.setModal(True) + self.setWindowTitle('Preferences') + + close_button = QtGui.QPushButton('Close') + close_button.pressed.connect(self.close) + + hbox = QtGui.QHBoxLayout() + hbox.addStretch(1) + hbox.addWidget(close_button) + hbox.addStretch(1) + + vbox = QtGui.QVBoxLayout() + + label = QtGui.QLabel('Not yet implemented!') + label.setAlignment(QtCore.Qt.AlignHCenter) + vbox.addWidget(label) + + label = QtGui.QLabel('') + label.setAlignment(QtCore.Qt.AlignHCenter) + vbox.addWidget(label) + + vbox.addLayout(hbox) + + self.setLayout(vbox) + self.show() diff --git a/toxygen/third_party/qweechat/qweechat.py b/toxygen/third_party/qweechat/qweechat.py new file mode 100644 index 0000000..98187be --- /dev/null +++ b/toxygen/third_party/qweechat/qweechat.py @@ -0,0 +1,555 @@ +# -*- coding: utf-8 -*- +# +# qweechat.py - WeeChat remote GUI using Qt toolkit +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +""" +QWeeChat is a WeeChat remote GUI using Qt toolkit. + +It requires requires WeeChat 0.3.7 or newer, running on local or remote host. +""" + +# +# History: +# +# 2011-05-27, Sébastien Helleu : +# start dev +# + +import sys +import traceback +from pkg_resources import resource_filename + +from PyQt5 import QtCore, QtGui, QtWidgets + +from qweechat import config +from qweechat.about import AboutDialog +from qweechat.buffer import BufferListWidget, Buffer +from qweechat.connection import ConnectionDialog +from qweechat.network import Network, STATUS_DISCONNECTED +from qweechat.preferences import PreferencesDialog +from qweechat.weechat import protocol + + +APP_NAME = 'QWeeChat' +AUTHOR = 'Sébastien Helleu' +WEECHAT_SITE = 'https://weechat.org/' + +# not QFrame +class MainWindow(QtWidgets.QMainWindow): + """Main window.""" + + def __init__(self, *args): + super().__init__(*args) + + self.config = config.read() + + self.resize(1000, 600) + self.setWindowTitle(APP_NAME) + + self.about_dialog = None + self.connection_dialog = None + self.preferences_dialog = None + + # network + self.network = Network() + self.network.statusChanged.connect(self._network_status_changed) + self.network.messageFromWeechat.connect(self._network_weechat_msg) + + # list of buffers + self.list_buffers = BufferListWidget() + self.list_buffers.currentRowChanged.connect(self._buffer_switch) + + # default buffer + self.buffers = [Buffer()] + self.stacked_buffers = QtWidgets.QStackedWidget() + self.stacked_buffers.addWidget(self.buffers[0].widget) + + # splitter with buffers + chat/input + splitter = QtWidgets.QSplitter() + splitter.addWidget(self.list_buffers) + splitter.addWidget(self.stacked_buffers) + + self.list_buffers.setSizePolicy(QtWidgets.QSizePolicy.Preferred, + QtWidgets.QSizePolicy.Preferred) + self.stacked_buffers.setSizePolicy(QtWidgets.QSizePolicy.Expanding, + QtWidgets.QSizePolicy.Expanding) + # MainWindow + self.setCentralWidget(splitter) + + if self.config.getboolean('look', 'statusbar'): + self.statusBar().visible = True + self.statusBar().visible = True + + # actions for menu and toolbar + actions_def = { + 'connect': [ + 'network-connect.png', + 'Connect to WeeChat', + 'Ctrl+O', + self.open_connection_dialog, + ], + 'disconnect': [ + 'network-disconnect.png', + 'Disconnect from WeeChat', + 'Ctrl+D', + self.network.disconnect_weechat, + ], + 'debug': [ + 'edit-find.png', + 'Open debug console window', + 'Ctrl+B', + self.network.open_debug_dialog, + ], + 'preferences': [ + 'preferences-other.png', + 'Change preferences', + 'Ctrl+P', + self.open_preferences_dialog, + ], + 'about': [ + 'help-about.png', + 'About QWeeChat', + 'Ctrl+H', + self.open_about_dialog, + ], + 'save connection': [ + 'document-save.png', + 'Save connection configuration', + 'Ctrl+S', + self.save_connection, + ], + 'quit': [ + 'application-exit.png', + 'Quit application', + 'Ctrl+Q', + self.close, + ], + } + self.actions = {} + for name, action in list(actions_def.items()): + self.actions[name] = QtWidgets.QAction( + QtGui.QIcon( + resource_filename(__name__, 'data/icons/%s' % action[0])), + name.capitalize(), self) + self.actions[name].setToolTip(f'{action[1]} ({action[2]})') + self.actions[name].setShortcut(action[2]) + self.actions[name].triggered.connect(action[3]) + + # menu + self.menu = self.menuBar() + menu_file = self.menu.addMenu('&File') + menu_file.addActions([self.actions['connect'], + self.actions['disconnect'], + self.actions['preferences'], + self.actions['save connection'], + self.actions['quit']]) + menu_window = self.menu.addMenu('&Window') + menu_window.addAction(self.actions['debug']) + menu_help = self.menu.addMenu('&Help') + menu_help.addAction(self.actions['about']) + self.network_status = QtWidgets.QLabel() + self.network_status.setFixedHeight(20) + self.network_status.setFixedWidth(200) + self.network_status.setContentsMargins(0, 0, 10, 0) + self.network_status.setAlignment(QtCore.Qt.AlignRight) + if hasattr(self, 'menuBar'): + if hasattr(self.menu, 'setCornerWidget'): + self.menu.setCornerWidget(self.network_status, + QtCore.Qt.TopRightCorner) + self.network_status_set(STATUS_DISCONNECTED) + + # toolbar + if hasattr(self, 'addToolBar'): + toolbar = self.addToolBar('toolBar') + toolbar.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon) + toolbar.addActions([self.actions['connect'], + self.actions['disconnect'], + self.actions['debug'], + self.actions['preferences'], + self.actions['about'], + self.actions['quit']]) + + self.buffers[0].widget.input.setFocus() + + # open debug dialog + if self.config.getboolean('look', 'debug'): + self.network.open_debug_dialog() + + # auto-connect to relay + if self.config.getboolean('relay', 'autoconnect'): + self.network.connect_weechat( + hostname=self.config.get('relay', 'hostname', fallback='127.0.0.1'), + port=self.config.get('relay', 'port', fallback='9000'), + ssl=self.config.getboolean('relay', 'ssl', fallback=''), + password=self.config.get('relay', 'password', fallback=''), + totp=None, + lines=self.config.get('relay', 'lines', fallback=''), + ) + + self.show() + + def _buffer_switch(self, index): + """Switch to a buffer.""" + if index >= 0: + self.stacked_buffers.setCurrentIndex(index) + self.stacked_buffers.widget(index).input.setFocus() + + def buffer_input(self, full_name, text): + """Send buffer input to WeeChat.""" + if self.network.is_connected(): + message = 'input %s %s\n' % (full_name, text) + self.network.send_to_weechat(message) + self.network.debug_print(0, '<==', message, forcecolor='#AA0000') + + def open_preferences_dialog(self): + """Open a dialog with preferences.""" + # TODO: implement the preferences dialog box + self.preferences_dialog = PreferencesDialog(self) + + def save_connection(self): + """Save connection configuration.""" + if self.network: + options = self.network.get_options() + for option in options: + self.config.set('relay', option, options[option]) + + def open_about_dialog(self): + """Open a dialog with info about QWeeChat.""" + self.about_dialog = AboutDialog(APP_NAME, AUTHOR, WEECHAT_SITE, self) + + def open_connection_dialog(self): + """Open a dialog with connection settings.""" + values = {} + for option in ('hostname', 'port', 'ssl', 'password', 'lines'): + values[option] = self.config.get('relay', option, fallback='') + self.connection_dialog = ConnectionDialog(values, self) + self.connection_dialog.dialog_buttons.accepted.connect( + self.connect_weechat) + + def connect_weechat(self): + """Connect to WeeChat.""" + self.network.connect_weechat( + hostname=self.connection_dialog.fields['hostname'].text(), + self.config.set('relay', 'hostname', hostname) + port=self.connection_dialog.fields['port'].text(), + ssl=self.connection_dialog.fields['ssl'].isChecked(), + password=self.connection_dialog.fields['password'].text(), + totp=self.connection_dialog.fields['totp'].text(), + lines=int(self.connection_dialog.fields['lines'].text()), + ) + self.connection_dialog.close() + + def _network_status_changed(self, status, extra): + """Called when the network status has changed.""" + if self.config.getboolean('look', 'statusbar'): + self.statusBar().showMessage(status) + self.network.debug_print(0, '', status, forcecolor='#0000AA') + self.network_status_set(status) + + def network_status_set(self, status): + """Set the network status.""" + pal = self.network_status.palette() + try: + pal.setColor(self.network_status.foregroundRole(), + self.network.status_color(status)) + except: + # dunno + pass + ssl = ' (SSL)' if status != STATUS_DISCONNECTED \ + and self.network.is_ssl() else '' + self.network_status.setPalette(pal) + icon = self.network.status_icon(status) + if icon: + self.network_status.setText( + ' %s' % + (resource_filename(__name__, 'data/icons/%s' % icon), + self.network.status_label(status) + ssl)) + else: + self.network_status.setText(status.capitalize()) + if status == STATUS_DISCONNECTED: + self.actions['connect'].setEnabled(True) + self.actions['disconnect'].setEnabled(False) + else: + self.actions['connect'].setEnabled(False) + self.actions['disconnect'].setEnabled(True) + + def _network_weechat_msg(self, message): + """Called when a message is received from WeeChat.""" + self.network.debug_print( + 0, '==>', + 'message (%d bytes):\n%s' + % (len(message), + protocol.hex_and_ascii(message.data(), 20)), + forcecolor='#008800', + ) + try: + proto = protocol.Protocol() + message = proto.decode(message.data()) + if message.uncompressed: + self.network.debug_print( + 0, '==>', + 'message uncompressed (%d bytes):\n%s' + % (message.size_uncompressed, + protocol.hex_and_ascii(message.uncompressed, 20)), + forcecolor='#008800') + self.network.debug_print(0, '', 'Message: %s' % message) + self.parse_message(message) + except Exception: # noqa: E722 + print('Error while decoding message from WeeChat:\n%s' + % traceback.format_exc()) + self.network.disconnect_weechat() + + def _parse_handshake(self, message): + """Parse a WeeChat message with handshake response.""" + for obj in message.objects: + if obj.objtype != 'htb': + continue + self.network.init_with_handshake(obj.value) + break + + def _parse_listbuffers(self, message): + """Parse a WeeChat message with list of buffers.""" + for obj in message.objects: + if obj.objtype != 'hda' or obj.value['path'][-1] != 'buffer': + continue + self.list_buffers.clear() + while self.stacked_buffers.count() > 0: + buf = self.stacked_buffers.widget(0) + self.stacked_buffers.removeWidget(buf) + self.buffers = [] + for item in obj.value['items']: + buf = self.create_buffer(item) + self.insert_buffer(len(self.buffers), buf) + self.list_buffers.setCurrentRow(0) + self.buffers[0].widget.input.setFocus() + + def _parse_line(self, message): + """Parse a WeeChat message with a buffer line.""" + for obj in message.objects: + lines = [] + if obj.objtype != 'hda' or obj.value['path'][-1] != 'line_data': + continue + for item in obj.value['items']: + if message.msgid == 'listlines': + ptrbuf = item['__path'][0] + else: + ptrbuf = item['buffer'] + index = [i for i, b in enumerate(self.buffers) + if b.pointer() == ptrbuf] + if index: + lines.append( + (index[0], + (item['date'], item['prefix'], + item['message'])) + ) + if message.msgid == 'listlines': + lines.reverse() + for line in lines: + self.buffers[line[0]].widget.chat.display(*line[1]) + + def _parse_nicklist(self, message): + """Parse a WeeChat message with a buffer nicklist.""" + buffer_refresh = {} + for obj in message.objects: + if obj.objtype != 'hda' or \ + obj.value['path'][-1] != 'nicklist_item': + continue + group = '__root' + for item in obj.value['items']: + index = [i for i, b in enumerate(self.buffers) + if b.pointer() == item['__path'][0]] + if index: + if not index[0] in buffer_refresh: + self.buffers[index[0]].nicklist = {} + buffer_refresh[index[0]] = True + if item['group']: + group = item['name'] + self.buffers[index[0]].nicklist_add_item( + group, item['group'], item['prefix'], item['name'], + item['visible']) + for index in buffer_refresh: + self.buffers[index].nicklist_refresh() + + def _parse_nicklist_diff(self, message): + """Parse a WeeChat message with a buffer nicklist diff.""" + buffer_refresh = {} + for obj in message.objects: + if obj.objtype != 'hda' or \ + obj.value['path'][-1] != 'nicklist_item': + continue + group = '__root' + for item in obj.value['items']: + index = [i for i, b in enumerate(self.buffers) + if b.pointer() == item['__path'][0]] + if not index: + continue + buffer_refresh[index[0]] = True + if item['_diff'] == ord('^'): + group = item['name'] + elif item['_diff'] == ord('+'): + self.buffers[index[0]].nicklist_add_item( + group, item['group'], item['prefix'], item['name'], + item['visible']) + elif item['_diff'] == ord('-'): + self.buffers[index[0]].nicklist_remove_item( + group, item['group'], item['name']) + elif item['_diff'] == ord('*'): + self.buffers[index[0]].nicklist_update_item( + group, item['group'], item['prefix'], item['name'], + item['visible']) + for index in buffer_refresh: + self.buffers[index].nicklist_refresh() + + def _parse_buffer_opened(self, message): + """Parse a WeeChat message with a new buffer (opened).""" + for obj in message.objects: + if obj.objtype != 'hda' or obj.value['path'][-1] != 'buffer': + continue + for item in obj.value['items']: + buf = self.create_buffer(item) + index = self.find_buffer_index_for_insert(item['next_buffer']) + self.insert_buffer(index, buf) + + def _parse_buffer(self, message): + """Parse a WeeChat message with a buffer event + (anything except a new buffer). + """ + for obj in message.objects: + if obj.objtype != 'hda' or obj.value['path'][-1] != 'buffer': + continue + for item in obj.value['items']: + index = [i for i, b in enumerate(self.buffers) + if b.pointer() == item['__path'][0]] + if not index: + continue + index = index[0] + if message.msgid == '_buffer_type_changed': + self.buffers[index].data['type'] = item['type'] + elif message.msgid in ('_buffer_moved', '_buffer_merged', + '_buffer_unmerged'): + buf = self.buffers[index] + buf.data['number'] = item['number'] + self.remove_buffer(index) + index2 = self.find_buffer_index_for_insert( + item['next_buffer']) + self.insert_buffer(index2, buf) + elif message.msgid == '_buffer_renamed': + self.buffers[index].data['full_name'] = item['full_name'] + self.buffers[index].data['short_name'] = item['short_name'] + elif message.msgid == '_buffer_title_changed': + self.buffers[index].data['title'] = item['title'] + self.buffers[index].update_title() + elif message.msgid == '_buffer_cleared': + self.buffers[index].widget.chat.clear() + elif message.msgid.startswith('_buffer_localvar_'): + self.buffers[index].data['local_variables'] = \ + item['local_variables'] + self.buffers[index].update_prompt() + elif message.msgid == '_buffer_closing': + self.remove_buffer(index) + + def parse_message(self, message): + """Parse a WeeChat message.""" + if message.msgid.startswith('debug'): + self.network.debug_print(0, '', '(debug message, ignored)') + elif message.msgid == 'handshake': + self._parse_handshake(message) + elif message.msgid == 'listbuffers': + self._parse_listbuffers(message) + elif message.msgid in ('listlines', '_buffer_line_added'): + self._parse_line(message) + elif message.msgid in ('_nicklist', 'nicklist'): + self._parse_nicklist(message) + elif message.msgid == '_nicklist_diff': + self._parse_nicklist_diff(message) + elif message.msgid == '_buffer_opened': + self._parse_buffer_opened(message) + elif message.msgid.startswith('_buffer_'): + self._parse_buffer(message) + elif message.msgid == '_upgrade': + self.network.desync_weechat() + elif message.msgid == '_upgrade_ended': + self.network.sync_weechat() + else: + print(f"Unknown message with id {message.msgid}") + + def create_buffer(self, item): + """Create a new buffer.""" + buf = Buffer(item) + buf.bufferInput.connect(self.buffer_input) + buf.widget.input.bufferSwitchPrev.connect( + self.list_buffers.switch_prev_buffer) + buf.widget.input.bufferSwitchNext.connect( + self.list_buffers.switch_next_buffer) + return buf + + def insert_buffer(self, index, buf): + """Insert a buffer in list.""" + self.buffers.insert(index, buf) + self.list_buffers.insertItem(index, '%s' + % (buf.data['local_variables']['name'])) + self.stacked_buffers.insertWidget(index, buf.widget) + + def remove_buffer(self, index): + """Remove a buffer.""" + if self.list_buffers.currentRow == index and index > 0: + self.list_buffers.setCurrentRow(index - 1) + self.list_buffers.takeItem(index) + self.stacked_buffers.removeWidget(self.stacked_buffers.widget(index)) + self.buffers.pop(index) + + def find_buffer_index_for_insert(self, next_buffer): + """Find position to insert a buffer in list.""" + index = -1 + if next_buffer == '0x0': + index = len(self.buffers) + else: + index = [i for i, b in enumerate(self.buffers) + if b.pointer() == next_buffer] + if index: + index = index[0] + if index < 0: + print('Warning: unable to find position for buffer, using end of ' + 'list by default') + index = len(self.buffers) + return index + + def closeEvent(self, event): + """Called when QWeeChat window is closed.""" + self.network.disconnect_weechat() + if self.network.debug_dialog: + self.network.debug_dialog.close() + config.write(self.config) + QtWidgets.QFrame.closeEvent(self, event) + + +def main(): + app = QtWidgets.QApplication(sys.argv) + app.setStyle(QtWidgets.QStyleFactory.create('Cleanlooks')) + app.setWindowIcon(QtGui.QIcon( + resource_filename(__name__, 'data/icons/weechat.png'))) + main_win = MainWindow() + main_win.show() + sys.exit(app.exec_()) + + +if __name__ == '__main__': + main() diff --git a/toxygen/third_party/qweechat/qweechat.py.diff b/toxygen/third_party/qweechat/qweechat.py.diff new file mode 100644 index 0000000..76db51a --- /dev/null +++ b/toxygen/third_party/qweechat/qweechat.py.diff @@ -0,0 +1,27 @@ +*** qweechat.py.dst 2022-11-19 18:31:51.000000000 +0000 +--- qweechat.py 2022-11-19 18:32:41.000000000 +0000 +*************** +*** 35,45 **** + + import sys + import traceback + from pkg_resources import resource_filename + +! from PySide6 import QtCore, QtGui, QtWidgets + + from qweechat import config + from qweechat.about import AboutDialog + from qweechat.buffer import BufferListWidget, Buffer + from qweechat.connection import ConnectionDialog +--- 35,45 ---- + + import sys + import traceback + from pkg_resources import resource_filename + +! from PyQt5 import QtCore, QtGui, QtWidgets + + from qweechat import config + from qweechat.about import AboutDialog + from qweechat.buffer import BufferListWidget, Buffer + from qweechat.connection import ConnectionDialog diff --git a/toxygen/third_party/qweechat/qweechat.py.dst b/toxygen/third_party/qweechat/qweechat.py.dst new file mode 100644 index 0000000..f58d920 --- /dev/null +++ b/toxygen/third_party/qweechat/qweechat.py.dst @@ -0,0 +1,542 @@ +# -*- coding: utf-8 -*- +# +# qweechat.py - WeeChat remote GUI using Qt toolkit +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +""" +QWeeChat is a WeeChat remote GUI using Qt toolkit. + +It requires requires WeeChat 0.3.7 or newer, running on local or remote host. +""" + +# +# History: +# +# 2011-05-27, Sébastien Helleu : +# start dev +# + +import sys +import traceback +from pkg_resources import resource_filename + +from PySide6 import QtCore, QtGui, QtWidgets + +from qweechat import config +from qweechat.about import AboutDialog +from qweechat.buffer import BufferListWidget, Buffer +from qweechat.connection import ConnectionDialog +from qweechat.network import Network, STATUS_DISCONNECTED +from qweechat.preferences import PreferencesDialog +from qweechat.weechat import protocol + + +APP_NAME = 'QWeeChat' +AUTHOR = 'Sébastien Helleu' +WEECHAT_SITE = 'https://weechat.org/' + + +class MainWindow(QtWidgets.QMainWindow): + """Main window.""" + + def __init__(self, *args): + super().__init__(*args) + + self.config = config.read() + + self.resize(1000, 600) + self.setWindowTitle(APP_NAME) + + self.about_dialog = None + self.connection_dialog = None + self.preferences_dialog = None + + # network + self.network = Network() + self.network.statusChanged.connect(self._network_status_changed) + self.network.messageFromWeechat.connect(self._network_weechat_msg) + + # list of buffers + self.list_buffers = BufferListWidget() + self.list_buffers.currentRowChanged.connect(self._buffer_switch) + + # default buffer + self.buffers = [Buffer()] + self.stacked_buffers = QtWidgets.QStackedWidget() + self.stacked_buffers.addWidget(self.buffers[0].widget) + + # splitter with buffers + chat/input + splitter = QtWidgets.QSplitter() + splitter.addWidget(self.list_buffers) + splitter.addWidget(self.stacked_buffers) + + self.setCentralWidget(splitter) + + if self.config.getboolean('look', 'statusbar'): + self.statusBar().visible = True + + # actions for menu and toolbar + actions_def = { + 'connect': [ + 'network-connect.png', + 'Connect to WeeChat', + 'Ctrl+O', + self.open_connection_dialog, + ], + 'disconnect': [ + 'network-disconnect.png', + 'Disconnect from WeeChat', + 'Ctrl+D', + self.network.disconnect_weechat, + ], + 'debug': [ + 'edit-find.png', + 'Open debug console window', + 'Ctrl+B', + self.network.open_debug_dialog, + ], + 'preferences': [ + 'preferences-other.png', + 'Change preferences', + 'Ctrl+P', + self.open_preferences_dialog, + ], + 'about': [ + 'help-about.png', + 'About QWeeChat', + 'Ctrl+H', + self.open_about_dialog, + ], + 'save connection': [ + 'document-save.png', + 'Save connection configuration', + 'Ctrl+S', + self.save_connection, + ], + 'quit': [ + 'application-exit.png', + 'Quit application', + 'Ctrl+Q', + self.close, + ], + } + self.actions = {} + for name, action in list(actions_def.items()): + self.actions[name] = QtGui.QAction( + QtGui.QIcon( + resource_filename(__name__, 'data/icons/%s' % action[0])), + name.capitalize(), self) + self.actions[name].setToolTip(f'{action[1]} ({action[2]})') + self.actions[name].setShortcut(action[2]) + self.actions[name].triggered.connect(action[3]) + + # menu + self.menu = self.menuBar() + menu_file = self.menu.addMenu('&File') + menu_file.addActions([self.actions['connect'], + self.actions['disconnect'], + self.actions['preferences'], + self.actions['save connection'], + self.actions['quit']]) + menu_window = self.menu.addMenu('&Window') + menu_window.addAction(self.actions['debug']) + menu_help = self.menu.addMenu('&Help') + menu_help.addAction(self.actions['about']) + self.network_status = QtWidgets.QLabel() + self.network_status.setFixedHeight(20) + self.network_status.setFixedWidth(200) + self.network_status.setContentsMargins(0, 0, 10, 0) + self.network_status.setAlignment(QtCore.Qt.AlignRight) + if hasattr(self.menu, 'setCornerWidget'): + self.menu.setCornerWidget(self.network_status, + QtCore.Qt.TopRightCorner) + self.network_status_set(STATUS_DISCONNECTED) + + # toolbar + toolbar = self.addToolBar('toolBar') + toolbar.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon) + toolbar.addActions([self.actions['connect'], + self.actions['disconnect'], + self.actions['debug'], + self.actions['preferences'], + self.actions['about'], + self.actions['quit']]) + + self.buffers[0].widget.input.setFocus() + + # open debug dialog + if self.config.getboolean('look', 'debug'): + self.network.open_debug_dialog() + + # auto-connect to relay + if self.config.getboolean('relay', 'autoconnect'): + self.network.connect_weechat( + hostname=self.config.get('relay', 'hostname', fallback=''), + port=self.config.get('relay', 'port', fallback=''), + ssl=self.config.getboolean('relay', 'ssl', fallback=''), + password=self.config.get('relay', 'password', fallback=''), + totp=None, + lines=self.config.get('relay', 'lines', fallback=''), + ) + + self.show() + + def _buffer_switch(self, index): + """Switch to a buffer.""" + if index >= 0: + self.stacked_buffers.setCurrentIndex(index) + self.stacked_buffers.widget(index).input.setFocus() + + def buffer_input(self, full_name, text): + """Send buffer input to WeeChat.""" + if self.network.is_connected(): + message = 'input %s %s\n' % (full_name, text) + self.network.send_to_weechat(message) + self.network.debug_print(0, '<==', message, forcecolor='#AA0000') + + def open_preferences_dialog(self): + """Open a dialog with preferences.""" + # TODO: implement the preferences dialog box + self.preferences_dialog = PreferencesDialog(self) + + def save_connection(self): + """Save connection configuration.""" + if self.network: + options = self.network.get_options() + for option in options: + self.config.set('relay', option, options[option]) + + def open_about_dialog(self): + """Open a dialog with info about QWeeChat.""" + self.about_dialog = AboutDialog(APP_NAME, AUTHOR, WEECHAT_SITE, self) + + def open_connection_dialog(self): + """Open a dialog with connection settings.""" + values = {} + for option in ('hostname', 'port', 'ssl', 'password', 'lines'): + values[option] = self.config.get('relay', option, fallback='') + self.connection_dialog = ConnectionDialog(values, self) + self.connection_dialog.dialog_buttons.accepted.connect( + self.connect_weechat) + + def connect_weechat(self): + """Connect to WeeChat.""" + self.network.connect_weechat( + hostname=self.connection_dialog.fields['hostname'].text(), + port=self.connection_dialog.fields['port'].text(), + ssl=self.connection_dialog.fields['ssl'].isChecked(), + password=self.connection_dialog.fields['password'].text(), + totp=self.connection_dialog.fields['totp'].text(), + lines=int(self.connection_dialog.fields['lines'].text()), + ) + self.connection_dialog.close() + + def _network_status_changed(self, status, extra): + """Called when the network status has changed.""" + if self.config.getboolean('look', 'statusbar'): + self.statusBar().showMessage(status) + self.network.debug_print(0, '', status, forcecolor='#0000AA') + self.network_status_set(status) + + def network_status_set(self, status): + """Set the network status.""" + pal = self.network_status.palette() + pal.setColor(self.network_status.foregroundRole(), + self.network.status_color(status)) + ssl = ' (SSL)' if status != STATUS_DISCONNECTED \ + and self.network.is_ssl() else '' + self.network_status.setPalette(pal) + icon = self.network.status_icon(status) + if icon: + self.network_status.setText( + ' %s' % + (resource_filename(__name__, 'data/icons/%s' % icon), + self.network.status_label(status) + ssl)) + else: + self.network_status.setText(status.capitalize()) + if status == STATUS_DISCONNECTED: + self.actions['connect'].setEnabled(True) + self.actions['disconnect'].setEnabled(False) + else: + self.actions['connect'].setEnabled(False) + self.actions['disconnect'].setEnabled(True) + + def _network_weechat_msg(self, message): + """Called when a message is received from WeeChat.""" + self.network.debug_print( + 0, '==>', + 'message (%d bytes):\n%s' + % (len(message), + protocol.hex_and_ascii(message.data(), 20)), + forcecolor='#008800', + ) + try: + proto = protocol.Protocol() + message = proto.decode(message.data()) + if message.uncompressed: + self.network.debug_print( + 0, '==>', + 'message uncompressed (%d bytes):\n%s' + % (message.size_uncompressed, + protocol.hex_and_ascii(message.uncompressed, 20)), + forcecolor='#008800') + self.network.debug_print(0, '', 'Message: %s' % message) + self.parse_message(message) + except Exception: # noqa: E722 + print('Error while decoding message from WeeChat:\n%s' + % traceback.format_exc()) + self.network.disconnect_weechat() + + def _parse_handshake(self, message): + """Parse a WeeChat message with handshake response.""" + for obj in message.objects: + if obj.objtype != 'htb': + continue + self.network.init_with_handshake(obj.value) + break + + def _parse_listbuffers(self, message): + """Parse a WeeChat message with list of buffers.""" + for obj in message.objects: + if obj.objtype != 'hda' or obj.value['path'][-1] != 'buffer': + continue + self.list_buffers.clear() + while self.stacked_buffers.count() > 0: + buf = self.stacked_buffers.widget(0) + self.stacked_buffers.removeWidget(buf) + self.buffers = [] + for item in obj.value['items']: + buf = self.create_buffer(item) + self.insert_buffer(len(self.buffers), buf) + self.list_buffers.setCurrentRow(0) + self.buffers[0].widget.input.setFocus() + + def _parse_line(self, message): + """Parse a WeeChat message with a buffer line.""" + for obj in message.objects: + lines = [] + if obj.objtype != 'hda' or obj.value['path'][-1] != 'line_data': + continue + for item in obj.value['items']: + if message.msgid == 'listlines': + ptrbuf = item['__path'][0] + else: + ptrbuf = item['buffer'] + index = [i for i, b in enumerate(self.buffers) + if b.pointer() == ptrbuf] + if index: + lines.append( + (index[0], + (item['date'], item['prefix'], + item['message'])) + ) + if message.msgid == 'listlines': + lines.reverse() + for line in lines: + self.buffers[line[0]].widget.chat.display(*line[1]) + + def _parse_nicklist(self, message): + """Parse a WeeChat message with a buffer nicklist.""" + buffer_refresh = {} + for obj in message.objects: + if obj.objtype != 'hda' or \ + obj.value['path'][-1] != 'nicklist_item': + continue + group = '__root' + for item in obj.value['items']: + index = [i for i, b in enumerate(self.buffers) + if b.pointer() == item['__path'][0]] + if index: + if not index[0] in buffer_refresh: + self.buffers[index[0]].nicklist = {} + buffer_refresh[index[0]] = True + if item['group']: + group = item['name'] + self.buffers[index[0]].nicklist_add_item( + group, item['group'], item['prefix'], item['name'], + item['visible']) + for index in buffer_refresh: + self.buffers[index].nicklist_refresh() + + def _parse_nicklist_diff(self, message): + """Parse a WeeChat message with a buffer nicklist diff.""" + buffer_refresh = {} + for obj in message.objects: + if obj.objtype != 'hda' or \ + obj.value['path'][-1] != 'nicklist_item': + continue + group = '__root' + for item in obj.value['items']: + index = [i for i, b in enumerate(self.buffers) + if b.pointer() == item['__path'][0]] + if not index: + continue + buffer_refresh[index[0]] = True + if item['_diff'] == ord('^'): + group = item['name'] + elif item['_diff'] == ord('+'): + self.buffers[index[0]].nicklist_add_item( + group, item['group'], item['prefix'], item['name'], + item['visible']) + elif item['_diff'] == ord('-'): + self.buffers[index[0]].nicklist_remove_item( + group, item['group'], item['name']) + elif item['_diff'] == ord('*'): + self.buffers[index[0]].nicklist_update_item( + group, item['group'], item['prefix'], item['name'], + item['visible']) + for index in buffer_refresh: + self.buffers[index].nicklist_refresh() + + def _parse_buffer_opened(self, message): + """Parse a WeeChat message with a new buffer (opened).""" + for obj in message.objects: + if obj.objtype != 'hda' or obj.value['path'][-1] != 'buffer': + continue + for item in obj.value['items']: + buf = self.create_buffer(item) + index = self.find_buffer_index_for_insert(item['next_buffer']) + self.insert_buffer(index, buf) + + def _parse_buffer(self, message): + """Parse a WeeChat message with a buffer event + (anything except a new buffer). + """ + for obj in message.objects: + if obj.objtype != 'hda' or obj.value['path'][-1] != 'buffer': + continue + for item in obj.value['items']: + index = [i for i, b in enumerate(self.buffers) + if b.pointer() == item['__path'][0]] + if not index: + continue + index = index[0] + if message.msgid == '_buffer_type_changed': + self.buffers[index].data['type'] = item['type'] + elif message.msgid in ('_buffer_moved', '_buffer_merged', + '_buffer_unmerged'): + buf = self.buffers[index] + buf.data['number'] = item['number'] + self.remove_buffer(index) + index2 = self.find_buffer_index_for_insert( + item['next_buffer']) + self.insert_buffer(index2, buf) + elif message.msgid == '_buffer_renamed': + self.buffers[index].data['full_name'] = item['full_name'] + self.buffers[index].data['short_name'] = item['short_name'] + elif message.msgid == '_buffer_title_changed': + self.buffers[index].data['title'] = item['title'] + self.buffers[index].update_title() + elif message.msgid == '_buffer_cleared': + self.buffers[index].widget.chat.clear() + elif message.msgid.startswith('_buffer_localvar_'): + self.buffers[index].data['local_variables'] = \ + item['local_variables'] + self.buffers[index].update_prompt() + elif message.msgid == '_buffer_closing': + self.remove_buffer(index) + + def parse_message(self, message): + """Parse a WeeChat message.""" + if message.msgid.startswith('debug'): + self.network.debug_print(0, '', '(debug message, ignored)') + elif message.msgid == 'handshake': + self._parse_handshake(message) + elif message.msgid == 'listbuffers': + self._parse_listbuffers(message) + elif message.msgid in ('listlines', '_buffer_line_added'): + self._parse_line(message) + elif message.msgid in ('_nicklist', 'nicklist'): + self._parse_nicklist(message) + elif message.msgid == '_nicklist_diff': + self._parse_nicklist_diff(message) + elif message.msgid == '_buffer_opened': + self._parse_buffer_opened(message) + elif message.msgid.startswith('_buffer_'): + self._parse_buffer(message) + elif message.msgid == '_upgrade': + self.network.desync_weechat() + elif message.msgid == '_upgrade_ended': + self.network.sync_weechat() + else: + print(f"Unknown message with id {message.msgid}") + + def create_buffer(self, item): + """Create a new buffer.""" + buf = Buffer(item) + buf.bufferInput.connect(self.buffer_input) + buf.widget.input.bufferSwitchPrev.connect( + self.list_buffers.switch_prev_buffer) + buf.widget.input.bufferSwitchNext.connect( + self.list_buffers.switch_next_buffer) + return buf + + def insert_buffer(self, index, buf): + """Insert a buffer in list.""" + self.buffers.insert(index, buf) + self.list_buffers.insertItem(index, '%s' + % (buf.data['local_variables']['name'])) + self.stacked_buffers.insertWidget(index, buf.widget) + + def remove_buffer(self, index): + """Remove a buffer.""" + if self.list_buffers.currentRow == index and index > 0: + self.list_buffers.setCurrentRow(index - 1) + self.list_buffers.takeItem(index) + self.stacked_buffers.removeWidget(self.stacked_buffers.widget(index)) + self.buffers.pop(index) + + def find_buffer_index_for_insert(self, next_buffer): + """Find position to insert a buffer in list.""" + index = -1 + if next_buffer == '0x0': + index = len(self.buffers) + else: + index = [i for i, b in enumerate(self.buffers) + if b.pointer() == next_buffer] + if index: + index = index[0] + if index < 0: + print('Warning: unable to find position for buffer, using end of ' + 'list by default') + index = len(self.buffers) + return index + + def closeEvent(self, event): + """Called when QWeeChat window is closed.""" + self.network.disconnect_weechat() + if self.network.debug_dialog: + self.network.debug_dialog.close() + config.write(self.config) + QtWidgets.QMainWindow.closeEvent(self, event) + + +def main(): + app = QtWidgets.QApplication(sys.argv) + app.setStyle(QtWidgets.QStyleFactory.create('Cleanlooks')) + app.setWindowIcon(QtGui.QIcon( + resource_filename(__name__, 'data/icons/weechat.png'))) + main_win = MainWindow() + main_win.show() + sys.exit(app.exec_()) + + +if __name__ == '__main__': + main() diff --git a/toxygen/third_party/qweechat/version.py b/toxygen/third_party/qweechat/version.py new file mode 100644 index 0000000..25bbf46 --- /dev/null +++ b/toxygen/third_party/qweechat/version.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# +# version.py - version of QWeeChat +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +"""Version of QWeeChat.""" + +VERSION = '0.0.1-dev' + + +def qweechat_version(): + """Return QWeeChat version.""" + return VERSION diff --git a/toxygen/third_party/qweechat/weechat/__init__.py b/toxygen/third_party/qweechat/weechat/__init__.py new file mode 100644 index 0000000..f510618 --- /dev/null +++ b/toxygen/third_party/qweechat/weechat/__init__.py @@ -0,0 +1,19 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# diff --git a/toxygen/third_party/qweechat/weechat/color.py b/toxygen/third_party/qweechat/weechat/color.py new file mode 100644 index 0000000..0ed52ef --- /dev/null +++ b/toxygen/third_party/qweechat/weechat/color.py @@ -0,0 +1,201 @@ +# -*- coding: utf-8 -*- +# +# color.py - remove/replace colors in WeeChat strings +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +"""Remove/replace colors in WeeChat strings.""" + +import re +import logging + +RE_COLOR_ATTRS = r'[*!/_|]*' +RE_COLOR_STD = r'(?:%s\d{2})' % RE_COLOR_ATTRS +RE_COLOR_EXT = r'(?:@%s\d{5})' % RE_COLOR_ATTRS +RE_COLOR_ANY = r'(?:%s|%s)' % (RE_COLOR_STD, RE_COLOR_EXT) +# \x19: color code, \x1A: set attribute, \x1B: remove attribute, \x1C: reset +RE_COLOR = re.compile( + r'(\x19(?:\d{2}|F%s|B\d{2}|B@\d{5}|E|\\*%s(~%s)?|@\d{5}|b.|\x1C))|\x1A.|' + r'\x1B.|\x1C' + % (RE_COLOR_ANY, RE_COLOR_ANY, RE_COLOR_ANY)) + +TERMINAL_COLORS = \ + '000000cd000000cd00cdcd000000cdcd00cd00cdcde5e5e5' \ + '4d4d4dff000000ff00ffff000000ffff00ff00ffffffffff' \ + '00000000002a0000550000800000aa0000d4002a00002a2a' \ + '002a55002a80002aaa002ad400550000552a005555005580' \ + '0055aa0055d400800000802a0080550080800080aa0080d4' \ + '00aa0000aa2a00aa5500aa8000aaaa00aad400d40000d42a' \ + '00d45500d48000d4aa00d4d42a00002a002a2a00552a0080' \ + '2a00aa2a00d42a2a002a2a2a2a2a552a2a802a2aaa2a2ad4' \ + '2a55002a552a2a55552a55802a55aa2a55d42a80002a802a' \ + '2a80552a80802a80aa2a80d42aaa002aaa2a2aaa552aaa80' \ + '2aaaaa2aaad42ad4002ad42a2ad4552ad4802ad4aa2ad4d4' \ + '55000055002a5500555500805500aa5500d4552a00552a2a' \ + '552a55552a80552aaa552ad455550055552a555555555580' \ + '5555aa5555d455800055802a5580555580805580aa5580d4' \ + '55aa0055aa2a55aa5555aa8055aaaa55aad455d40055d42a' \ + '55d45555d48055d4aa55d4d480000080002a800055800080' \ + '8000aa8000d4802a00802a2a802a55802a80802aaa802ad4' \ + '80550080552a8055558055808055aa8055d480800080802a' \ + '8080558080808080aa8080d480aa0080aa2a80aa5580aa80' \ + '80aaaa80aad480d40080d42a80d45580d48080d4aa80d4d4' \ + 'aa0000aa002aaa0055aa0080aa00aaaa00d4aa2a00aa2a2a' \ + 'aa2a55aa2a80aa2aaaaa2ad4aa5500aa552aaa5555aa5580' \ + 'aa55aaaa55d4aa8000aa802aaa8055aa8080aa80aaaa80d4' \ + 'aaaa00aaaa2aaaaa55aaaa80aaaaaaaaaad4aad400aad42a' \ + 'aad455aad480aad4aaaad4d4d40000d4002ad40055d40080' \ + 'd400aad400d4d42a00d42a2ad42a55d42a80d42aaad42ad4' \ + 'd45500d4552ad45555d45580d455aad455d4d48000d4802a' \ + 'd48055d48080d480aad480d4d4aa00d4aa2ad4aa55d4aa80' \ + 'd4aaaad4aad4d4d400d4d42ad4d455d4d480d4d4aad4d4d4' \ + '0808081212121c1c1c2626263030303a3a3a4444444e4e4e' \ + '5858586262626c6c6c7676768080808a8a8a9494949e9e9e' \ + 'a8a8a8b2b2b2bcbcbcc6c6c6d0d0d0dadadae4e4e4eeeeee' + +# WeeChat basic colors (color name, index in terminal colors) +WEECHAT_BASIC_COLORS = ( + ('default', 0), ('black', 0), ('darkgray', 8), ('red', 1), + ('lightred', 9), ('green', 2), ('lightgreen', 10), ('brown', 3), + ('yellow', 11), ('blue', 4), ('lightblue', 12), ('magenta', 5), + ('lightmagenta', 13), ('cyan', 6), ('lightcyan', 14), ('gray', 7), + ('white', 0)) + + +log = logging.getLogger(__name__) + + +class Color(): + def __init__(self, color_options, debug=False): + self.color_options = color_options + self.debug = debug + + def _rgb_color(self, index): + color = TERMINAL_COLORS[index*6:(index*6)+6] + col_r = int(color[0:2], 16) * 0.85 + col_g = int(color[2:4], 16) * 0.85 + col_b = int(color[4:6], 16) * 0.85 + return '%02x%02x%02x' % (col_r, col_g, col_b) + + def _convert_weechat_color(self, color): + try: + index = int(color) + return '\x01(Fr%s)' % self.color_options[index] + except Exception: # noqa: E722 + log.debug('Error decoding WeeChat color "%s"', color) + return '' + + def _convert_terminal_color(self, fg_bg, attrs, color): + try: + index = int(color) + return '\x01(%s%s#%s)' % (fg_bg, attrs, self._rgb_color(index)) + except Exception: # noqa: E722 + log.debug('Error decoding terminal color "%s"', color) + return '' + + def _convert_color_attr(self, fg_bg, color): + extended = False + if color[0].startswith('@'): + extended = True + color = color[1:] + attrs = '' + # keep_attrs = False + while color.startswith(('*', '!', '/', '_', '|')): + # TODO: manage the "keep attributes" flag + # if color[0] == '|': + # keep_attrs = True + attrs += color[0] + color = color[1:] + if extended: + return self._convert_terminal_color(fg_bg, attrs, color) + try: + index = int(color) + return self._convert_terminal_color(fg_bg, attrs, + WEECHAT_BASIC_COLORS[index][1]) + except Exception: # noqa: E722 + log.debug('Error decoding color "%s"', color) + return '' + + def _attrcode_to_char(self, code): + codes = { + '\x01': '*', + '\x02': '!', + '\x03': '/', + '\x04': '_', + } + return codes.get(code, '') + + def _convert_color(self, match): + color = match.group(0) + if color[0] == '\x19': + if color[1] == 'b': + # bar code, ignored + return '' + if color[1] == '\x1C': + # reset + return '\x01(Fr)\x01(Br)' + if color[1] in ('F', 'B'): + # foreground or background + return self._convert_color_attr(color[1], color[2:]) + if color[1] == '*': + # foreground with optional background + items = color[2:].split(',') + str_col = self._convert_color_attr('F', items[0]) + if len(items) > 1: + str_col += self._convert_color_attr('B', items[1]) + return str_col + if color[1] == '@': + # direct ncurses pair number, ignored + return '' + if color[1] == 'E': + # text emphasis, ignored + return '' + if color[1:].isdigit(): + return self._convert_weechat_color(int(color[1:])) + elif color[0] == '\x1A': + # set attribute + return '\x01(+%s)' % self._attrcode_to_char(color[1]) + elif color[0] == '\x1B': + # remove attribute + return '\x01(-%s)' % self._attrcode_to_char(color[1]) + elif color[0] == '\x1C': + # reset + return '\x01(Fr)\x01(Br)' + # should never be executed! + return match.group(0) + + def _convert_color_debug(self, match): + group = match.group(0) + for code in (0x01, 0x02, 0x03, 0x04, 0x19, 0x1A, 0x1B): + group = group.replace(chr(code), '' % code) + return group + + def convert(self, text): + if not text: + return '' + if self.debug: + return RE_COLOR.sub(self._convert_color_debug, text) + return RE_COLOR.sub(self._convert_color, text) + + +def remove(text): + """Remove colors in a WeeChat string.""" + if not text: + return '' + return re.sub(RE_COLOR, '', text) diff --git a/toxygen/third_party/qweechat/weechat/protocol.py b/toxygen/third_party/qweechat/weechat/protocol.py new file mode 100644 index 0000000..90ce7d2 --- /dev/null +++ b/toxygen/third_party/qweechat/weechat/protocol.py @@ -0,0 +1,361 @@ +# -*- coding: utf-8 -*- +# +# protocol.py - decode binary messages received from WeeChat/relay +# +# Copyright (C) 2011-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +# +# For info about protocol and format of messages, please read document +# "WeeChat Relay Protocol", available at: https://weechat.org/doc/ +# +# History: +# +# 2011-11-23, Sébastien Helleu : +# start dev +# + +"""Decode binary messages received from WeeChat/relay.""" + +import collections +import struct +import zlib + + +class WeechatDict(collections.OrderedDict): + def __str__(self): + return '{%s}' % ', '.join( + ['%s: %s' % (repr(key), repr(self[key])) for key in self]) + + +class WeechatObject: + def __init__(self, objtype, value, separator='\n'): + self.objtype = objtype + self.value = value + self.separator = separator + self.indent = ' ' if separator == '\n' else '' + self.separator1 = '\n%s' % self.indent if separator == '\n' else '' + + def _str_value(self, val): + if isinstance(val, str) and val is not None: + return '\'%s\'' % val + return str(val) + + def _str_value_hdata(self): + lines = ['%skeys: %s%s%spath: %s' % (self.separator1, + str(self.value['keys']), + self.separator, + self.indent, + str(self.value['path']))] + for i, item in enumerate(self.value['items']): + lines.append(' item %d:%s%s' % ( + (i + 1), self.separator, + self.separator.join( + ['%s%s: %s' % (self.indent * 2, key, + self._str_value(value)) + for key, value in item.items()]))) + return '\n'.join(lines) + + def _str_value_infolist(self): + lines = ['%sname: %s' % (self.separator1, self.value['name'])] + for i, item in enumerate(self.value['items']): + lines.append(' item %d:%s%s' % ( + (i + 1), self.separator, + self.separator.join( + ['%s%s: %s' % (self.indent * 2, key, + self._str_value(value)) + for key, value in item.items()]))) + return '\n'.join(lines) + + def _str_value_other(self): + return self._str_value(self.value) + + def __str__(self): + obj_cb = { + 'hda': self._str_value_hdata, + 'inl': self._str_value_infolist, + } + return '%s: %s' % (self.objtype, + obj_cb.get(self.objtype, self._str_value_other)()) + + +class WeechatObjects(list): + def __init__(self, separator='\n'): + super().__init__() + self.separator = separator + + def __str__(self): + return self.separator.join([str(obj) for obj in self]) + + +class WeechatMessage: + def __init__(self, size, size_uncompressed, compression, uncompressed, + msgid, objects): + self.size = size + self.size_uncompressed = size_uncompressed + self.compression = compression + self.uncompressed = uncompressed + self.msgid = msgid + self.objects = objects + + def __str__(self): + if self.compression != 0: + return 'size: %d/%d (%d%%), id=\'%s\', objects:\n%s' % ( + self.size, self.size_uncompressed, + 100 - ((self.size * 100) // self.size_uncompressed), + self.msgid, self.objects) + return 'size: %d, id=\'%s\', objects:\n%s' % (self.size, + self.msgid, + self.objects) + + +class Protocol: + """Decode binary message received from WeeChat/relay.""" + + def __init__(self): + self.data = '' + self._obj_cb = { + 'chr': self._obj_char, + 'int': self._obj_int, + 'lon': self._obj_long, + 'str': self._obj_str, + 'buf': self._obj_buffer, + 'ptr': self._obj_ptr, + 'tim': self._obj_time, + 'htb': self._obj_hashtable, + 'hda': self._obj_hdata, + 'inf': self._obj_info, + 'inl': self._obj_infolist, + 'arr': self._obj_array, + } + + def _obj_type(self): + """Read type in data (3 chars).""" + if len(self.data) < 3: + self.data = '' + return '' + objtype = self.data[0:3].decode() + self.data = self.data[3:] + return objtype + + def _obj_len_data(self, length_size): + """Read length (1 or 4 bytes), then value with this length.""" + if len(self.data) < length_size: + self.data = '' + return None + if length_size == 1: + length = struct.unpack('B', self.data[0:1])[0] + self.data = self.data[1:] + else: + length = self._obj_int() + if length < 0: + return None + if length > 0: + value = self.data[0:length] + self.data = self.data[length:] + else: + value = '' + return value + + def _obj_char(self): + """Read a char in data.""" + if len(self.data) < 1: + return 0 + value = struct.unpack('b', self.data[0:1])[0] + self.data = self.data[1:] + return value + + def _obj_int(self): + """Read an integer in data (4 bytes).""" + if len(self.data) < 4: + self.data = '' + return 0 + value = struct.unpack('>i', self.data[0:4])[0] + self.data = self.data[4:] + return value + + def _obj_long(self): + """Read a long integer in data (length on 1 byte + value as string).""" + value = self._obj_len_data(1) + if value is None: + return None + return int(value) + + def _obj_str(self): + """Read a string in data (length on 4 bytes + content).""" + value = self._obj_len_data(4) + if value in ("", None): + return "" + return value.decode() + + def _obj_buffer(self): + """Read a buffer in data (length on 4 bytes + data).""" + return self._obj_len_data(4) + + def _obj_ptr(self): + """Read a pointer in data (length on 1 byte + value as string).""" + value = self._obj_len_data(1) + if value is None: + return None + return '0x%s' % value + + def _obj_time(self): + """Read a time in data (length on 1 byte + value as string).""" + value = self._obj_len_data(1) + if value is None: + return None + return int(value) + + def _obj_hashtable(self): + """ + Read a hashtable in data + (type for keys + type for values + count + items). + """ + type_keys = self._obj_type() + type_values = self._obj_type() + count = self._obj_int() + hashtable = WeechatDict() + for _ in range(count): + key = self._obj_cb[type_keys]() + value = self._obj_cb[type_values]() + hashtable[key] = value + return hashtable + + def _obj_hdata(self): + """Read a hdata in data.""" + path = self._obj_str() + keys = self._obj_str() + count = self._obj_int() + list_path = path.split('/') if path else [] + list_keys = keys.split(',') if keys else [] + keys_types = [] + dict_keys = WeechatDict() + for key in list_keys: + items = key.split(':') + keys_types.append(items) + dict_keys[items[0]] = items[1] + items = [] + for _ in range(count): + item = WeechatDict() + item['__path'] = [] + pointers = [] + for _ in enumerate(list_path): + pointers.append(self._obj_ptr()) + for key, objtype in keys_types: + item[key] = self._obj_cb[objtype]() + item['__path'] = pointers + items.append(item) + return { + 'path': list_path, + 'keys': dict_keys, + 'count': count, + 'items': items, + } + + def _obj_info(self): + """Read an info in data.""" + name = self._obj_str() + value = self._obj_str() + return (name, value) + + def _obj_infolist(self): + """Read an infolist in data.""" + name = self._obj_str() + count_items = self._obj_int() + items = [] + for _ in range(count_items): + count_vars = self._obj_int() + variables = WeechatDict() + for _ in range(count_vars): + var_name = self._obj_str() + var_type = self._obj_type() + var_value = self._obj_cb[var_type]() + variables[var_name] = var_value + items.append(variables) + return { + 'name': name, + 'items': items + } + + def _obj_array(self): + """Read an array of values in data.""" + type_values = self._obj_type() + count_values = self._obj_int() + values = [] + for _ in range(count_values): + values.append(self._obj_cb[type_values]()) + return values + + def decode(self, data, separator='\n'): + """Decode binary data and return list of objects.""" + self.data = data + size = len(self.data) + size_uncompressed = size + uncompressed = None + # uncompress data (if it is compressed) + compression = struct.unpack('b', self.data[4:5])[0] + if compression: + uncompressed = zlib.decompress(self.data[5:]) + size_uncompressed = len(uncompressed) + 5 + uncompressed = b'%s%s%s' % (struct.pack('>i', size_uncompressed), + struct.pack('b', 0), uncompressed) + self.data = uncompressed + else: + uncompressed = self.data[:] + # skip length and compression flag + self.data = self.data[5:] + # read id + msgid = self._obj_str() + if msgid is None: + msgid = '' + # read objects + objects = WeechatObjects(separator=separator) + while len(self.data) > 0: + objtype = self._obj_type() + value = self._obj_cb[objtype]() + objects.append(WeechatObject(objtype, value, separator=separator)) + return WeechatMessage(size, size_uncompressed, compression, + uncompressed, msgid, objects) + + +def hex_and_ascii(data, bytes_per_line=10): + """Convert a QByteArray to hex + ascii output.""" + num_lines = ((len(data) - 1) // bytes_per_line) + 1 + if num_lines == 0: + return '' + lines = [] + for i in range(num_lines): + str_hex = [] + str_ascii = [] + for j in range(bytes_per_line): + # We can't easily iterate over individual bytes, so we are going to + # do it this way. + index = (i*bytes_per_line) + j + char = data[index:index+1] + if not char: + char = b'x' + byte = struct.unpack('B', char)[0] + str_hex.append(b'%02X' % int(byte)) + if 32 <= byte <= 127: + str_ascii.append(char) + else: + str_ascii.append(b'.') + fmt = b'%%-%ds %%s' % ((bytes_per_line * 3) - 1) + lines.append(fmt % (b' '.join(str_hex), + b''.join(str_ascii))) + return b'\n'.join(lines) diff --git a/toxygen/third_party/qweechat/weechat/testproto.py b/toxygen/third_party/qweechat/weechat/testproto.py new file mode 100644 index 0000000..2afabd9 --- /dev/null +++ b/toxygen/third_party/qweechat/weechat/testproto.py @@ -0,0 +1,252 @@ +# -*- coding: utf-8 -*- +# +# testproto.py - command-line program for testing WeeChat/relay protocol +# +# Copyright (C) 2013-2022 Sébastien Helleu +# +# This file is part of QWeeChat, a Qt remote GUI for WeeChat. +# +# QWeeChat is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# QWeeChat is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with QWeeChat. If not, see . +# + +"""Command-line program for testing WeeChat/relay protocol.""" + +import argparse +import os +import select +import shlex +import socket +import struct +import sys +import time +import traceback + +from qweechat.weechat import protocol + +qweechat_version = '0.1' + +NAME = 'qweechat-testproto' + + +class TestProto(object): + """Test of WeeChat/relay protocol.""" + + def __init__(self, args): + self.args = args + self.sock = None + self.has_quit = False + self.address = '{self.args.hostname}/{self.args.port} ' \ + '(IPv{0})'.format(6 if self.args.ipv6 else 4, self=self) + + def connect(self): + """ + Connect to WeeChat/relay. + Return True if OK, False if error. + """ + inet = socket.AF_INET6 if self.args.ipv6 else socket.AF_INET + try: + self.sock = socket.socket(inet, socket.SOCK_STREAM) + self.sock.connect((self.args.hostname, self.args.port)) + except Exception: + if self.sock: + self.sock.close() + print('Failed to connect to', self.address) + return False + + print(f'Connected to {self.address} socket {self.sock}') + return True + + def send(self, messages): + """ + Send a text message to WeeChat/relay. + Return True if OK, False if error. + """ + try: + for msg in messages.split(b'\n'): + if msg == b'quit': + self.has_quit = True + self.sock.sendall(msg + b'\n') + sys.stdout.write( + (b'\x1b[33m<-- ' + msg + b'\x1b[0m\n').decode()) + except Exception: # noqa: E722 + traceback.print_exc() + print('Failed to send message') + return False + return True + + def decode(self, message): + """ + Decode a binary message received from WeeChat/relay. + Return True if OK, False if error. + """ + try: + proto = protocol.Protocol() + msgd = proto.decode(message, + separator=b'\n' if self.args.debug > 0 + else ', ') + print('') + if self.args.debug >= 2 and msgd.uncompressed: + # display raw message + print('\x1b[32m--> message uncompressed ({0} bytes):\n' + '{1}\x1b[0m' + ''.format(msgd.size_uncompressed, + protocol.hex_and_ascii(msgd.uncompressed, 20))) + # display decoded message + print('\x1b[32m--> {0}\x1b[0m'.format(msgd)) + except Exception: # noqa: E722 + traceback.print_exc() + print('Error while decoding message from WeeChat') + return False + return True + + def send_stdin(self): + """ + Send commands from standard input if some data is available. + Return True if OK (it's OK if stdin has no commands), + False if error. + """ + inr = select.select([sys.stdin], [], [], 0)[0] + if inr: + data = os.read(sys.stdin.fileno(), 4096) + if data: + if not self.send(data.strip()): + self.sock.close() + return False + # open stdin to read user commands + sys.stdin = open('/dev/tty') + return True + + def mainloop(self): + """ + Main loop: read keyboard, send commands, read socket, + decode/display binary messages received from WeeChat/relay. + Return 0 if OK, 4 if send error, 5 if decode error. + """ + if self.has_quit: + return 0 + message = b'' + recvbuf = b'' + prompt = b'\x1b[36mrelay> \x1b[0m' + sys.stdout.write(prompt.decode()) + sys.stdout.flush() + try: + while not self.has_quit: + inr = select.select([sys.stdin, self.sock], [], [], 1)[0] + for _file in inr: + if _file == sys.stdin: + buf = os.read(_file.fileno(), 4096) + if buf: + message += buf + if b'\n' in message: + messages = message.split(b'\n') + msgsent = b'\n'.join(messages[:-1]) + if msgsent and not self.send(msgsent): + return 4 + message = messages[-1] + sys.stdout.write((prompt + message).decode()) + # sys.stdout.write(prompt + message) + sys.stdout.flush() + else: + buf = _file.recv(4096) + if buf: + recvbuf += buf + while len(recvbuf) >= 4: + remainder = None + length = struct.unpack('>i', recvbuf[0:4])[0] + if len(recvbuf) < length: + # partial message, just wait for the + # end of message + break + # more than one message? + if length < len(recvbuf): + # save beginning of another message + remainder = recvbuf[length:] + recvbuf = recvbuf[0:length] + if not self.decode(recvbuf): + return 5 + if remainder: + recvbuf = remainder + else: + recvbuf = b'' + sys.stdout.write((prompt + message).decode()) + sys.stdout.flush() + except Exception: # noqa: E722 + traceback.print_exc() + self.send(b'quit') + return 0 + + def __del__(self): + print('Closing connection with', self.address) + time.sleep(0.5) + self.sock.close() + + +def main(): + """Main function.""" + # parse command line arguments + parser = argparse.ArgumentParser( + formatter_class=argparse.RawDescriptionHelpFormatter, + fromfile_prefix_chars='@', + description='Command-line program for testing WeeChat/relay protocol.', + epilog=''' +Environment variable "QWEECHAT_PROTO_OPTIONS" can be set with default options. +Argument "@file.txt" can be used to read default options in a file. + +Some commands can be piped to the script, for example: + echo "init password=xxxx" | {name} localhost 5000 + {name} localhost 5000 < commands.txt + +The script returns: + 0: OK + 2: wrong arguments (command line) + 3: connection error + 4: send error (message sent to WeeChat) + 5: decode error (message received from WeeChat) +'''.format(name=NAME)) + parser.add_argument('-6', '--ipv6', action='store_true', + help='connect using IPv6') + parser.add_argument('-d', '--debug', action='count', default=0, + help='debug mode: long objects view ' + '(-dd: display raw messages)') + parser.add_argument('-v', '--version', action='version', + version=qweechat_version) + parser.add_argument('hostname', + help='hostname (or IP address) of machine running ' + 'WeeChat/relay') + parser.add_argument('port', type=int, + help='port of machine running WeeChat/relay') + if len(sys.argv) == 1: + parser.print_help() + sys.exit(0) + _args = parser.parse_args( + shlex.split(os.getenv('QWEECHAT_PROTO_OPTIONS') or '') + sys.argv[1:]) + + test = TestProto(_args) + + # connect to WeeChat/relay + if not test.connect(): + sys.exit(3) + + # send commands from standard input if some data is available + if not test.send_stdin(): + sys.exit(4) + + # main loop (wait commands, display messages received) + returncode = test.mainloop() + del test + sys.exit(returncode) + + +if __name__ == "__main__": + main()