Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions spyder_notebook/notebookplugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ def on_application_available(self) -> None:
)
widget = self.get_widget()
widget.sig_new_recent_file.connect(application.add_recent_file)
widget.sig_enable_save_requested.connect(self._enable_save_actions)

@on_plugin_available(plugin=Plugins.Preferences)
def on_preferences_available(self):
Expand All @@ -106,6 +107,7 @@ def on_application_teardown(self) -> None:
application = self.get_plugin(Plugins.Application)
widget = self.get_widget()
widget.sig_new_recent_file.disconnect(application.add_recent_file)
widget.sig_file_action_enabled.connect(self._enable_file_action)

@on_plugin_teardown(plugin=Plugins.Preferences)
def on_preferences_teardown(self):
Expand Down Expand Up @@ -261,3 +263,28 @@ def _handle_switcher_selection(self, item, mode, search_text):
self.switch_to_plugin()
switcher = self.get_plugin(Plugins.Switcher)
switcher.hide()

def _enable_save_actions(
self,
save_enabled: bool,
save_all_enabled: bool
) -> None:
"""
Enable or disable file action for this plugin.
"""
# Moving this import to the top of the file interferes with the
# async loop in Jupyter
from spyder.plugins.application.api import ApplicationActions

application = self.get_plugin(Plugins.Application, error=False)
if application:
application.enable_file_action(
ApplicationActions.SaveFile,
save_enabled,
self.NAME
)
application.enable_file_action(
ApplicationActions.SaveAll,
save_all_enabled,
self.NAME
)
1 change: 1 addition & 0 deletions spyder_notebook/server/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@
"@jupyterlab/markedparser-extension": "~4.4.9",
"@jupyterlab/mathjax-extension": "~4.4.9",
"@jupyterlab/metadataform-extension": "~4.4.9",
"@jupyterlab/notebook": "~4.4.9",
"@jupyterlab/notebook-extension": "~4.4.9",
"@jupyterlab/pdf-extension": "~4.4.9",
"@jupyterlab/services-extension": "~4.4.9",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@
"build": "tsc -b"
},
"dependencies": {
"@jupyter-notebook/application": "~7.4.7",
"@jupyterlab/application": "~4.4.9",
"@jupyterlab/docmanager": "~4.4.9",
"@jupyterlab/mainmenu": "~4.4.9"
"@jupyterlab/mainmenu": "~4.4.9",
"@jupyterlab/notebook": "~4.4.9"
},
"devDependencies": {
"typescript": "~5.5.4"
Expand Down
53 changes: 51 additions & 2 deletions spyder_notebook/server/packages/application-extension/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,22 @@ import {

import { IThemeManager } from '@jupyterlab/apputils';

import { PageConfig } from '@jupyterlab/coreutils';
import {
IChangedArgs,
PageConfig
} from '@jupyterlab/coreutils';

import { IDocumentManager } from '@jupyterlab/docmanager';

import { IMainMenu } from '@jupyterlab/mainmenu';

import {
INotebookModel,
NotebookPanel
} from '@jupyterlab/notebook';

import { INotebookShell } from '@jupyter-notebook/application';

/**
* A regular expression to match path to notebooks and documents
*
Expand Down Expand Up @@ -104,13 +114,52 @@ const theme: JupyterFrontEndPlugin<void> = {
}
};

/**
* Send message to Spyder if notebook becomes dirty or non-dirty
*/
const monitorDirty: JupyterFrontEndPlugin<void> = {
id: '@spyder-notebook/application-extension:monitor-dirty',
description:
'Send message to Spyder if notebook becomes dirty or non-dirty.',
autoStart: true,
requires: [INotebookShell],
activate: (
app: JupyterFrontEnd,
notebookShell: INotebookShell
) => {
const onNotebookModelStateChange = (
model: INotebookModel,
args: IChangedArgs<any>
): void => {
if (args.name == 'dirty') {
alert(':SpyderComm:dirty:' + args.newValue)
};
};

const onNotebookShellChange = async () => {
const current = notebookShell.currentWidget;
if (!(current instanceof NotebookPanel)) {
return;
}

const notebook = current.content;
await current.context.ready;

notebook.model?.stateChanged.connect(onNotebookModelStateChange);
};

notebookShell.currentChanged.connect(onNotebookShellChange);
},
};

/**
* Export the plugins as default.
*/
const plugins: JupyterFrontEndPlugin<any>[] = [
menus,
opener,
theme
theme,
monitorDirty
];

export default plugins;
3 changes: 3 additions & 0 deletions spyder_notebook/server/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3280,6 +3280,7 @@ __metadata:
"@jupyterlab/markedparser-extension": ~4.4.9
"@jupyterlab/mathjax-extension": ~4.4.9
"@jupyterlab/metadataform-extension": ~4.4.9
"@jupyterlab/notebook": ~4.4.9
"@jupyterlab/notebook-extension": ~4.4.9
"@jupyterlab/pdf-extension": ~4.4.9
"@jupyterlab/services-extension": ~4.4.9
Expand Down Expand Up @@ -3315,9 +3316,11 @@ __metadata:
version: 0.0.0-use.local
resolution: "@spyder-notebook/application-extension@workspace:packages/application-extension"
dependencies:
"@jupyter-notebook/application": ~7.4.7
"@jupyterlab/application": ~4.4.9
"@jupyterlab/docmanager": ~4.4.9
"@jupyterlab/mainmenu": ~4.4.9
"@jupyterlab/notebook": ~4.4.9
typescript: ~5.5.4
languageName: unknown
linkType: soft
Expand Down
88 changes: 88 additions & 0 deletions spyder_notebook/widgets/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
from spyder.utils.image_path_manager import get_image_path
from spyder.utils.qthelpers import add_actions
from spyder.utils.palette import SpyderPalette
from spyder.widgets.browser import WebPage
from spyder.widgets.findreplace import FindReplace

# Local imports
Expand Down Expand Up @@ -90,6 +91,43 @@ def open_in_browser(self, url):
self.close()


class NotebookWebPage(WebPage):
"""
Object to view and edit notebooks rendered as web pages.

Spyder notebooks communicate with Spyder itself with the JavaScript
alert() function where the message starts with a special prefix.
This class raises a signal if such a message is received.
"""

SPYDER_COMM_PREFIX = ':SpyderComm:'
"""
Prefix for alert() messages used to communicate with Spyder.
"""

sig_message_received = Signal(str)
"""
This signal is emitted when a Spyder comms message is received.
"""

def javaScriptAlert(self, securityOrigin, msg: str) -> None:
"""
Called whenever the JavaScript function alert() is called.

If the message starts with `SPYDER_COMM_PREFIX`, then this is a
message to communicate to Spyder so emit `sig_message_received`.
Otherwise, this is a standard JavaScript alert() to communicate to
the user, so let the base class handle it.

Overloads the function in QWebEnginePage.
"""
if msg.startswith(self.SPYDER_COMM_PREFIX):
msg = msg.removeprefix(self.SPYDER_COMM_PREFIX)
self.sig_message_received.emit(msg)
else:
super().javaScriptAlert(securityOrigin, msg)


class NotebookWidget(DOMWidget):
"""WebView widget for notebooks."""

Expand All @@ -103,6 +141,16 @@ class NotebookWidget(DOMWidget):
This signal is emitted when the widget loses focus.
"""

sig_dirty_changed = Signal(bool)
"""
This signal is emitted when the notebook becomes dirty or non-dirty.

Parameters
----------
new_value : bool
Whether the notebook is now dirty.
"""

def __init__(self, parent, actions=None):
"""
Constructor.
Expand All @@ -117,6 +165,12 @@ def __init__(self, parent, actions=None):
will be added.
"""
super().__init__(parent)

# Use our subclass of QtWebEnginePage to view notebooks
web_page = NotebookWebPage(self)
web_page.sig_message_received.connect(self.on_message_received)
self.setPage(web_page)

self.CONTEXT_NAME = str(id(self))
self.setup()
self.actions = actions
Expand Down Expand Up @@ -176,6 +230,19 @@ def _set_info(self, html):
"""Set informational html with css from local path."""
self.setHtml(html, QUrl.fromLocalFile(self.css_path))

def on_message_received(self, msg: str) -> None:
"""
Handle messages from notebooks communicated with alert().

The only message implemented at the moment indicates that a notebook
has become dirty or non-dirty.
"""
msg_class, msg_args = msg.split(':', 2)
if msg_class == 'dirty':
self.sig_dirty_changed.emit(msg_args == 'true')
else:
logger.warning(f'Unknown message class from notebook, {msg = }')

def show_blank(self):
"""Show a blank page."""
blank_template = Template(BLANK)
Expand Down Expand Up @@ -255,6 +322,16 @@ class NotebookClient(QFrame):

CONF_SECTION = CONF_SECTION

sig_dirty_changed = Signal(bool)
"""
This signal is emitted when the notebook becomes dirty or non-dirty.

Parameters
----------
new_value : bool
Whether the notebook is now dirty.
"""

def __init__(self, parent, filename, actions=None, ini_message=None):
"""
Constructor.
Expand Down Expand Up @@ -282,6 +359,7 @@ def __init__(self, parent, filename, actions=None, ini_message=None):
self.file_url = None
self.server_url = None
self.path = None
self.dirty = False

self.notebookwidget = NotebookWidget(self, actions)
if ini_message:
Expand All @@ -291,6 +369,8 @@ def __init__(self, parent, filename, actions=None, ini_message=None):
self.notebookwidget.show_blank()
self.static = False

self.notebookwidget.sig_dirty_changed.connect(
self._handle_dirty_changed)
self.notebookwidget.sig_focus_in_event.connect(
lambda: self._apply_stylesheet(focus=True))
self.notebookwidget.sig_focus_out_event.connect(
Expand Down Expand Up @@ -460,6 +540,14 @@ def _apply_stylesheet(self, focus=False):

self.setStyleSheet(css.toString())

def _handle_dirty_changed(self, new_value: bool) -> None:
"""
Handle signal that a notebook became dirty or not.

Store the new value and emit the signal again.
"""
self.dirty = new_value
self.sig_dirty_changed.emit(new_value)

# -----------------------------------------------------------------------------
# Tests
Expand Down
21 changes: 21 additions & 0 deletions spyder_notebook/widgets/dom.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,27 @@ def __init__(self, parent):
else:
self.dom = self.page().mainFrame()

def setPage(self, page):
"""
Change the web page of the web view.

Overrides the function in QWebEngineView in order to update self.dom.

Parameters
----------
page : QWebEnginePage
The new web page.

Returns
-------
None.
"""
super().setPage(page)
if WEBENGINE:
self.dom = self.page()
else:
self.dom = self.page().mainFrame()

def evaluate(self, script):
"""
Evaluate script in page frame.
Expand Down
Loading
Loading