Skip to content

Commit

Permalink
Render objects
Browse files Browse the repository at this point in the history
  • Loading branch information
trungleduc committed Feb 17, 2023
1 parent 8b2923c commit 06e592f
Show file tree
Hide file tree
Showing 10 changed files with 73 additions and 29 deletions.
3 changes: 2 additions & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,13 @@ jobs:
name: extension-artifacts

- name: Install and Test
# TODO Update JupyterLab version
run: |
set -eux
# Remove NodeJS, twice to take care of system and locally installed node versions.
sudo rm -rf $(which node)
sudo rm -rf $(which node)
pip install "jupyterlab>=4.0.0a32" jupytercad*.whl
pip install "jupyterlab==4.0.0a32" jupytercad*.whl
jupyter labextension list
jupyter labextension list 2>&1 | grep -ie "jupytercad.*OK"
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/check-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:
matrix:
group: [check_release]
python-version: ["3.9"]
node-version: ["14.x"]
node-version: ["18.x"]

steps:
- name: Checkout
Expand Down
28 changes: 15 additions & 13 deletions jupytercad/notebook/cad_document.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import json
import logging
import os
from typing import List, Optional, Union
from typing import Dict, List, Optional, Union

import y_py as Y

from .objects import OBJECT_FACTORY, PythonJcadObject
from .utils import normalize_path
from .y_connector import YDocConnector
from pydantic import BaseModel

logger = logging.getLogger(__file__)

Expand All @@ -31,12 +29,14 @@ def objects(self) -> List[str]:
return [x['name'] for x in self._objects_array]
return []

def get_object(self, name: str) -> Optional[PythonJcadObject]:
def get_object(self, name: str) -> Optional['PythonJcadObject']:
from .objects import OBJECT_FACTORY

if self.check_exist(name):
data = self._get_yobject_by_name(name).to_json()
return OBJECT_FACTORY.create_object(data)
return OBJECT_FACTORY.create_object(data, self)

def update_object(self, object: PythonJcadObject) -> None:
def update_object(self, object: 'PythonJcadObject') -> None:
yobject: Optional[Y.YMap] = self._get_yobject_by_name(object.name)
if yobject:
with self._ydoc.begin_transaction() as t:
Expand All @@ -48,7 +48,7 @@ def remove_object(self, name: str) -> None:
with self.ydoc.begin_transaction() as t:
self._objects_array.delete(t, index)

def add_object(self, new_object: PythonJcadObject) -> None:
def add_object(self, new_object: 'PythonJcadObject') -> None:
if self._objects_array is not None and not self.check_exist(
new_object.name
):
Expand All @@ -65,6 +65,13 @@ def check_exist(self, name: str) -> bool:
return name in self.objects
return False

def render(self) -> Dict:
return {
'application/FCStd': json.dumps(
{'commId': self._yconnector.comm_id}
),
}

def _get_yobject_by_name(self, name: str) -> Optional[Y.YMap]:
if self._objects_array:
for item in self._objects_array:
Expand All @@ -80,9 +87,4 @@ def _get_yobject_index_by_name(self, name: str) -> int:
return -1

def _repr_mimebundle_(self, **kwargs):
data = {
'application/FCStd': json.dumps(
{'commId': self._yconnector.comm_id}
),
}
return data
return self.render()
37 changes: 33 additions & 4 deletions jupytercad/notebook/objects/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from typing import Dict, Optional, Union
from typing import Any, Dict, Optional, Union
from pydantic import BaseModel, Extra
from ..cad_document import CadDocument
from ._schema.box import IBox
from ._schema.cone import ICone
from ._schema.cut import ICut
Expand All @@ -9,10 +11,14 @@
from ._schema.jcad import Parts
from ._schema.sphere import ISphere
from ._schema.torus import ITorus
from pydantic import BaseModel


class PythonJcadObject(BaseModel):
class Config:
arbitrary_types_allowed = True
underscore_attrs_are_private = True
extra = Extra.allow

name: str
shape: Parts
parameters: Union[
Expand All @@ -27,6 +33,24 @@ class PythonJcadObject(BaseModel):
ITorus,
]

_caddoc = Optional[CadDocument]
_parent = Optional[CadDocument]

def __init__(__pydantic_self__, parent, **data: Any) -> None: # noqa
super().__init__(**data)
__pydantic_self__._caddoc = CadDocument()
__pydantic_self__._caddoc.add_object(__pydantic_self__)
__pydantic_self__._parent = parent

def _repr_mimebundle_(self, **kwargs):
return self._caddoc.render()

def update_object(self):
if self._caddoc is not None:
self._caddoc.update_object(self)
if self._parent is not None:
self._parent.update_object(self)


class SingletonMeta(type):

Expand All @@ -47,7 +71,9 @@ def register_factory(self, shape_type: str, cls: type[BaseModel]) -> None:
if shape_type not in self._factories:
self._factories[shape_type] = cls

def create_object(self, data: Dict) -> Optional[PythonJcadObject]:
def create_object(
self, data: Dict, parent: Optional[CadDocument] = None
) -> Optional[PythonJcadObject]:
object_type = data.get('shape', None)
name: str = data.get('name', None)
if object_type and object_type in self._factories:
Expand All @@ -58,7 +84,10 @@ def create_object(self, data: Dict) -> Optional[PythonJcadObject]:
args[field] = params.get(field, None)
obj_params = Model(**args)
return PythonJcadObject(
name=name, shape=object_type, parameters=obj_params
parent=parent,
name=name,
shape=object_type,
parameters=obj_params,
)

return None
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ version_cmd = "hatch version"

[tool.jupyter-releaser.hooks]
before-build-npm = [
"python -m pip install jupyterlab>=4.0.0a32",
"python -m pip install jupyterlab==4.0.0a32 datamodel-code-generator",
"jlpm",
"jlpm build:prod",
]
Expand Down
2 changes: 2 additions & 0 deletions src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ export class JupyterCadModel implements IJupyterCadModel {
return;
}
this._isDisposed = true;
this._sharedModel.dispose();
this._disposed.emit();
Signal.clearData(this);
}
Expand Down Expand Up @@ -257,6 +258,7 @@ export class JupyterCadDoc
this._objects.unobserveDeep(this._objectsObserver);
this._metadata.unobserve(this._metaObserver);
this._options.unobserve(this._optionsObserver);
super.dispose();
}

get objects(): Array<IJCadObject> {
Expand Down
2 changes: 1 addition & 1 deletion src/notebookrenderer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { IKernelConnection } from '@jupyterlab/services/lib/kernel/kernel';

import { IAnnotationModel } from '../types';
import { IAnnotation } from './../token';
import { NotebookRendererModel } from './modelFactory';
import { NotebookRendererModel } from './model';
import { IJupyterCadWidgetManager } from './token';
import { NotebookRenderer } from './view';
import { JupyterCadWidgetManager } from './widgetManager';
Expand Down
File renamed without changes.
11 changes: 4 additions & 7 deletions src/notebookrenderer/view.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { MessageLoop } from '@lumino/messaging';
import { Widget } from '@lumino/widgets';
import { Panel, Widget } from '@lumino/widgets';

import { JupyterCadPanel } from '../widget';
import { NotebookRendererModel } from './modelFactory';
import { NotebookRendererModel } from './model';
import { IRenderMime } from '@jupyterlab/rendermime';
import { IJupyterCadModel } from '../types';

export const CLASS_NAME = 'mimerenderer-jupytercad';

export class NotebookRenderer extends Widget {
export class NotebookRenderer extends Panel implements IRenderMime.IRenderer {
/**
* Construct a new output widget.
*/
Expand Down Expand Up @@ -36,10 +36,7 @@ export class NotebookRenderer extends Widget {
return;
}
this._jcadWidget = new JupyterCadPanel({ model: this._jcadModel });

MessageLoop.sendMessage(this._jcadWidget, Widget.Msg.BeforeAttach);
this.node.appendChild(this._jcadWidget.node);
MessageLoop.sendMessage(this._jcadWidget, Widget.Msg.AfterAttach);
this.addWidget(this._jcadWidget);
}

onResize = (): void => {
Expand Down
15 changes: 14 additions & 1 deletion src/notebookrenderer/yCommProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@ import * as decoding from 'lib0/decoding';
import * as encoding from 'lib0/encoding';
import * as syncProtocol from 'y-protocols/sync';
import * as Y from 'yjs';
import { IDisposable } from '@lumino/disposable';

export enum YMessageType {
SYNC = 0,
AWARENESS = 1
}
export class YCommProvider {
export class YCommProvider implements IDisposable {
constructor(options: { comm: IComm; ydoc: Y.Doc }) {
this._comm = options.comm;
this._ydoc = options.ydoc;
Expand All @@ -30,6 +31,17 @@ export class YCommProvider {
}
}

get isDisposed(): boolean {
return this._isDisposed;
}

dispose(): void {
if (this._isDisposed) {
return;
}
this._comm.close();
this._isDisposed = true;
}
private _onMsg = (msg: ICommMsgMsg<'iopub' | 'shell'>) => {
if (msg.buffers) {
const buffer = msg.buffers[0] as ArrayBuffer;
Expand Down Expand Up @@ -66,6 +78,7 @@ export class YCommProvider {
private _comm: IComm;
private _ydoc: Y.Doc;
private _synced: boolean;
private _isDisposed = false;
}

namespace Private {
Expand Down

0 comments on commit 06e592f

Please sign in to comment.