FreeCAD

Форк
0
/
addonmanager_connection_checker.py 
125 строк · 5.7 Кб
1
# SPDX-License-Identifier: LGPL-2.1-or-later
2
# ***************************************************************************
3
# *                                                                         *
4
# *   Copyright (c) 2022 FreeCAD Project Association                        *
5
# *                                                                         *
6
# *   This file is part of FreeCAD.                                         *
7
# *                                                                         *
8
# *   FreeCAD is free software: you can redistribute it and/or modify it    *
9
# *   under the terms of the GNU Lesser General Public License as           *
10
# *   published by the Free Software Foundation, either version 2.1 of the  *
11
# *   License, or (at your option) any later version.                       *
12
# *                                                                         *
13
# *   FreeCAD is distributed in the hope that it will be useful, but        *
14
# *   WITHOUT ANY WARRANTY; without even the implied warranty of            *
15
# *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      *
16
# *   Lesser General Public License for more details.                       *
17
# *                                                                         *
18
# *   You should have received a copy of the GNU Lesser General Public      *
19
# *   License along with FreeCAD. If not, see                               *
20
# *   <https://www.gnu.org/licenses/>.                                      *
21
# *                                                                         *
22
# ***************************************************************************
23

24
""" System for checking the network connection status asynchronously. """
25

26
import FreeCAD
27

28
from PySide import QtCore, QtWidgets
29

30
import NetworkManager
31
from addonmanager_workers_utility import ConnectionChecker
32

33
translate = FreeCAD.Qt.translate
34

35

36
class ConnectionCheckerGUI(QtCore.QObject):
37
    """Determine whether there is an active network connection, showing a progress message if it
38
    starts to take too long, and an error message if the network cannot be accessed."""
39

40
    connection_available = QtCore.Signal()
41
    check_complete = QtCore.Signal()
42

43
    def __init__(self):
44
        super().__init__()
45

46
        # Check the connection in a new thread, so FreeCAD stays responsive
47
        self.connection_checker = ConnectionChecker()
48
        self.signals_connected = False
49

50
        self.connection_message_timer = None
51
        self.connection_check_message = None
52

53
    def start(self):
54
        """Start the connection check"""
55
        self.connection_checker.start()
56
        self.connection_checker.success.connect(self._check_succeeded)
57
        self.connection_checker.failure.connect(self._network_connection_failed)
58
        self.signals_connected = True
59

60
        # If it takes longer than a half second to check the connection, show a message:
61
        self.connection_message_timer = QtCore.QTimer.singleShot(
62
            500, self._show_connection_check_message
63
        )
64

65
    def _show_connection_check_message(self):
66
        """Display a message informing the user that the check is in process"""
67
        if not self.connection_checker.isFinished():
68
            self.connection_check_message = QtWidgets.QMessageBox(
69
                QtWidgets.QMessageBox.Information,
70
                translate("AddonsInstaller", "Checking connection"),
71
                translate("AddonsInstaller", "Checking for connection to GitHub..."),
72
                QtWidgets.QMessageBox.Cancel,
73
            )
74
            self.connection_check_message.buttonClicked.connect(self.cancel_network_check)
75
            self.connection_check_message.show()
76

77
    def cancel_network_check(self, _):
78
        """Cancel the check"""
79
        if not self.connection_checker.isFinished():
80
            self._disconnect_signals()
81
            self.connection_checker.requestInterruption()
82
            self.connection_checker.wait(500)
83
            self.connection_check_message.close()
84
            self.check_complete.emit()
85

86
    def _network_connection_failed(self, message: str) -> None:
87
        """Callback for failed connection check. Displays an error message, then emits the
88
        check_complete signal (but not the connection available signal)."""
89
        # This must run on the main GUI thread
90
        if hasattr(self, "connection_check_message") and self.connection_check_message:
91
            self.connection_check_message.close()
92
        if NetworkManager.HAVE_QTNETWORK:
93
            QtWidgets.QMessageBox.critical(
94
                None, translate("AddonsInstaller", "Connection failed"), message
95
            )
96
        else:
97
            # pylint: disable=line-too-long
98
            QtWidgets.QMessageBox.critical(
99
                None,
100
                translate("AddonsInstaller", "Missing dependency"),
101
                translate(
102
                    "AddonsInstaller",
103
                    "Could not import QtNetwork -- see Report View for details. Addon Manager "
104
                    "unavailable.",
105
                ),
106
            )
107

108
        self._disconnect_signals()
109
        self.check_complete.emit()
110

111
    def _check_succeeded(self):
112
        """Emit both the connection_available and the check_complete signals, in that order."""
113

114
        if hasattr(self, "connection_check_message") and self.connection_check_message:
115
            self.connection_check_message.close()
116

117
        self.connection_available.emit()
118
        self._disconnect_signals()
119
        self.check_complete.emit()
120

121
    def _disconnect_signals(self):
122
        if self.signals_connected:
123
            self.connection_checker.success.disconnect(self._check_succeeded)
124
            self.connection_checker.failure.disconnect(self._network_connection_failed)
125
        self.signals_connected = False
126

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.