Skip to content

Commit

Permalink
Update viewer variable when changing focused console (multiple consol…
Browse files Browse the repository at this point in the history
…es sharing the same kernel)
  • Loading branch information
dalthviz committed Dec 9, 2024
1 parent 2e9ca54 commit bb3ccc0
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,7 @@ target/
*/_version.py

# pycharm stuff
.idea/
.idea/

# spyder project config
.spyproject
24 changes: 24 additions & 0 deletions napari_console/qt_console.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from qtconsole.inprocess import QtInProcessKernelManager
from qtconsole.rich_jupyter_widget import RichJupyterWidget
from qtpy.QtGui import QColor
from qtpy.QtWidgets import QApplication


from napari.utils.naming import CallerFrame
Expand Down Expand Up @@ -161,6 +162,9 @@ def __init__(self, viewer: 'napari.viewer.Viewer', *, min_depth: int = 1, style_

# Set stylings
self._update_theme(style_sheet=style_sheet)

# Connect logic to update `viewer` variable when needed
QApplication.instance().focusChanged.connect(self._update_viewer_reference)

# TODO: Try to get console from jupyter to run without a shift click
# self.execute_on_complete_input = True
Expand Down Expand Up @@ -220,6 +224,26 @@ def _update_theme(self, event=None, style_sheet=''):
bracket_color = QColor(*str_to_rgb(theme['highlight']))
self._bracket_matcher.format.setBackground(bracket_color)

def _update_viewer_reference(self, old, new):
"""
Update the `viewer` variable to ensure it points to this console viewer
when multiple consoles are using the same kernel.
This is connected to the `QApplication.focusChanged` signal to check if
updating the `viewer` variable in the kernel is needed (i.e the focused
widget is this console control widget so `viewer` should point to
`self.viewer`).
Parameters
----------
old : qtpy.QtWidgets.QWidget
Widget that had previously the focus.
new : qtpy.QtWidgets.QWidget
Widget that now has the focus.
"""
if self._control == new:
self.push({'viewer': self.viewer})

def closeEvent(self, event):
"""Clean up the integrated console in napari."""
# Disconnect theme update
Expand Down

0 comments on commit bb3ccc0

Please # to comment.