1""" Defines a KernelClient that provides signals and slots.
2"""
3import atexit
4import errno
5from threading import Thread
6import time
7
8import zmq
9# import ZMQError in top-level namespace, to avoid ugly attribute-error messages
10# during garbage collection of threads at exit:
11from zmq import ZMQError
12from zmq.eventloop import ioloop, zmqstream
13
14from qtpy import QtCore
15
16# Local imports
17from traitlets import Type, Instance
18from jupyter_client.channels import HBChannel
19from jupyter_client import KernelClient
20from jupyter_client.channels import InvalidPortNumber
21from jupyter_client.threaded import ThreadedKernelClient, ThreadedZMQSocketChannel
22
23from .kernel_mixins import QtKernelClientMixin
24from .util import SuperQObject
25
26class QtHBChannel(SuperQObject, HBChannel):
27    # A longer timeout than the base class
28    time_to_dead = 3.0
29
30    # Emitted when the kernel has died.
31    kernel_died = QtCore.Signal(object)
32
33    def call_handlers(self, since_last_heartbeat):
34        """ Reimplemented to emit signals instead of making callbacks.
35        """
36        # Emit the generic signal.
37        self.kernel_died.emit(since_last_heartbeat)
38
39from jupyter_client import protocol_version_info
40
41major_protocol_version = protocol_version_info[0]
42
43class QtZMQSocketChannel(ThreadedZMQSocketChannel,SuperQObject):
44    """A ZMQ socket emitting a Qt signal when a message is received."""
45    message_received = QtCore.Signal(object)
46
47    def process_events(self):
48        """ Process any pending GUI events.
49        """
50        QtCore.QCoreApplication.instance().processEvents()
51
52
53    def call_handlers(self, msg):
54        """This method is called in the ioloop thread when a message arrives.
55
56        It is important to remember that this method is called in the thread
57        so that some logic must be done to ensure that the application level
58        handlers are called in the application thread.
59        """
60        # Emit the generic signal.
61        self.message_received.emit(msg)
62
63
64class QtKernelClient(QtKernelClientMixin, ThreadedKernelClient):
65    """ A KernelClient that provides signals and slots.
66    """
67
68    iopub_channel_class = Type(QtZMQSocketChannel)
69    shell_channel_class = Type(QtZMQSocketChannel)
70    stdin_channel_class = Type(QtZMQSocketChannel)
71    hb_channel_class = Type(QtHBChannel)
72