Skip to content

Commit

Permalink
Update fcstd mimerenderer
Browse files Browse the repository at this point in the history
  • Loading branch information
trungleduc committed Feb 7, 2023
1 parent ab8b938 commit 61e539c
Show file tree
Hide file tree
Showing 13 changed files with 161 additions and 167 deletions.
4 changes: 2 additions & 2 deletions jupytercad/notebook/cad_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ def disconnect(self) -> None:

def render(self) -> None:
from IPython.display import display

display({'application/FCStd': self._path}, raw=True)
if self._yconnector:
display({'application/FCStd': self._yconnector.room_name}, raw=True)

def _get_yobject_by_name(self, name: str) -> Optional[Y.YMap]:
if self._objects_array:
Expand Down
15 changes: 10 additions & 5 deletions jupytercad/notebook/y_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ def __init__(
def ydoc(self):
return self._doc

@property
def room_name(self):
return self._room_name

def disconnect_room(self) -> None:
asyncio.create_task(self.__stop())

Expand All @@ -62,19 +66,17 @@ async def connect_room(self) -> None:
headers=headers,
data=json.dumps({'format': fileFormat, 'type': fileType}),
)
room_name = response.text
self._room_name = response.text
ws_url = (
multi_urljoin(base_ws_url, WS_YROOM_URL, room_name)
multi_urljoin(base_ws_url, WS_YROOM_URL, response.text)
+ f'?token={token}'
)
self._synced = asyncio.Event()
await self.__start(ws_url=ws_url)
await self.synced()

async def synced(self):
if not self._ws:
return False
await asyncio.sleep(0.1) # TODO Need better solution!
await asyncio.sleep(0.25) # TODO Need better solution!
self._synced.set()

def __parse_env_variable(self) -> Optional[Dict[str, str]]:
Expand All @@ -93,3 +95,6 @@ async def __start(self, ws_url):
self._doc = Y.YDoc()
self._ws = await connect(ws_url)
WebsocketProvider(self._doc, self._ws)

def __del__(self):
print('Destructor called')
3 changes: 2 additions & 1 deletion src/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ export class JupyterCadWidgetFactory extends ABCWidgetFactory<
protected createNewWidget(
context: DocumentRegistry.IContext<JupyterCadModel>
): JupyterCadWidget {
const content = new JupyterCadPanel(context);
const { model } = context;
const content = new JupyterCadPanel({ model });
const toolbarModel = new ToolbarModel({ panel: content, context });
const toolbar = new ToolbarWidget({
model: toolbarModel,
Expand Down
94 changes: 39 additions & 55 deletions src/mainview.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,22 @@
import { DocumentRegistry } from '@jupyterlab/docregistry';
import { MapChange } from '@jupyter/ydoc';
import { IObservableMap, ObservableMap } from '@jupyterlab/observables';
import { User } from '@jupyterlab/services';

import { MapChange } from '@jupyter/ydoc';

import { CommandRegistry } from '@lumino/commands';
import { JSONValue } from '@lumino/coreutils';
import { ContextMenu } from '@lumino/widgets';
import { CommandRegistry } from '@lumino/commands';

import * as React from 'react';
import * as Color from 'd3-color';
import * as React from 'react';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';

import {
acceleratedRaycast,
computeBoundsTree,
disposeBoundsTree,
acceleratedRaycast
disposeBoundsTree
} from 'three-mesh-bvh';

import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { v4 as uuid } from 'uuid';

import { FloatingAnnotation } from './annotation/view';
import { throttle } from './tools';
import {
AxeHelper,
IDict,
Expand All @@ -34,8 +30,6 @@ import {
MainAction,
WorkerAction
} from './types';
import { FloatingAnnotation } from './annotation/view';
import { throttle } from './tools';

// Apply the BVH extension
THREE.BufferGeometry.prototype.computeBoundsTree = computeBoundsTree;
Expand All @@ -50,7 +44,7 @@ const SELECTED_MESH_COLOR = new THREE.Color('#AB5118');

interface IProps {
view: ObservableMap<JSONValue>;
context: DocumentRegistry.IContext<IJupyterCadModel>;
jcadModel: IJupyterCadModel;
}

interface IStates {
Expand Down Expand Up @@ -92,40 +86,38 @@ export class MainView extends React.Component<IProps, IStates> {
firstLoad: true
};

this._pointer = new THREE.Vector2();
this._model = this.props.jcadModel;
this._worker = this._model.getWorker();

this._context = props.context;
this._pointer = new THREE.Vector2();
this._collaboratorPointers = {};
this._context.ready.then(() => {
this._model = this._context.model;
this._worker = this._model.getWorker();
this._messageChannel = new MessageChannel();
this._messageChannel.port1.onmessage = msgEvent => {
this.messageHandler(msgEvent.data);
};
this._postMessage(
{ action: WorkerAction.REGISTER, payload: { id: this.state.id } },
this._messageChannel.port2
);
this._model.themeChanged.connect(this._handleThemeChange, this);
this._messageChannel = new MessageChannel();
this._messageChannel.port1.onmessage = msgEvent => {
this.messageHandler(msgEvent.data);
};
this._postMessage(
{ action: WorkerAction.REGISTER, payload: { id: this.state.id } },
this._messageChannel.port2
);
this._model.themeChanged.connect(this._handleThemeChange, this);

this._model.sharedObjectsChanged.connect(
this._onSharedObjectsChanged,
this
);
this._model.sharedOptionsChanged.connect(
this._onSharedOptionsChanged,
this
);
this._model.clientStateChanged.connect(
this._onClientSharedStateChanged,
this
);
this._model.sharedMetadataChanged.connect(
this._onSharedMetadataChanged,
this
);

this._model.sharedObjectsChanged.connect(
this._onSharedObjectsChanged,
this
);
this._model.sharedOptionsChanged.connect(
this._onSharedOptionsChanged,
this
);
this._model.clientStateChanged.connect(
this._onClientSharedStateChanged,
this
);
this._model.sharedMetadataChanged.connect(
this._onSharedMetadataChanged,
this
);
});
if (this._raycaster.params.Line) {
this._raycaster.params.Line.threshold = 0.1;
}
Expand All @@ -146,12 +138,7 @@ export class MainView extends React.Component<IProps, IStates> {
window.removeEventListener('resize', this._handleWindowResize);
this.props.view.changed.disconnect(this._onViewChanged, this);
this._controls.dispose();
this._postMessage({
action: WorkerAction.CLOSE_FILE,
payload: {
fileName: this._context.path
}
});

this._model.themeChanged.disconnect(this._handleThemeChange, this);
this._model.sharedOptionsChanged.disconnect(
this._onSharedOptionsChanged,
Expand Down Expand Up @@ -366,7 +353,6 @@ export class MainView extends React.Component<IProps, IStates> {
this._postMessage({
action: WorkerAction.LOAD_FILE,
payload: {
fileName: this._context.path,
content: this._model.getContent()
}
});
Expand Down Expand Up @@ -827,7 +813,6 @@ export class MainView extends React.Component<IProps, IStates> {
this._postMessage({
action: WorkerAction.LOAD_FILE,
payload: {
fileName: this._context.path,
content: this._model.getContent()
}
});
Expand Down Expand Up @@ -948,7 +933,6 @@ export class MainView extends React.Component<IProps, IStates> {

private divRef = React.createRef<HTMLDivElement>(); // Reference of render div

private _context: DocumentRegistry.IContext<IJupyterCadModel>;
private _model: IJupyterCadModel;
private _worker?: Worker = undefined;
private _messageChannel?: MessageChannel;
Expand Down
8 changes: 7 additions & 1 deletion src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,16 @@ export class JupyterCadModel implements IJupyterCadModel {
return this.sharedModel.objectsChanged;
}

get disposed(): ISignal<JupyterCadModel, void> {
return this._disposed;
}

dispose(): void {
if (this._isDisposed) {
return;
}
this._isDisposed = true;
this._disposed.emit();
Signal.clearData(this);
}

Expand Down Expand Up @@ -204,13 +209,15 @@ export class JupyterCadModel implements IJupyterCadModel {
private _readOnly = false;
private _isDisposed = false;

private _disposed = new Signal<this, void>(this);
private _contentChanged = new Signal<this, void>(this);
private _stateChanged = new Signal<this, IChangedArgs<any>>(this);
private _themeChanged = new Signal<this, IChangedArgs<any>>(this);
private _clientStateChanged = new Signal<
this,
Map<number, IJupyterCadClientState>
>(this);

static worker: Worker;
}

Expand All @@ -224,7 +231,6 @@ export class JupyterCadDoc
this._options = this.ydoc.getMap<Y.Map<any>>('options');
this._objects = this.ydoc.getArray<Y.Map<any>>('objects');
this._metadata = this.ydoc.getMap<string>('metadata');

this.undoManager.addToScope(this._objects);

this._objects.observeDeep(this._objectsObserver);
Expand Down
15 changes: 5 additions & 10 deletions src/notebookrenderer/index.ts
Original file line number Diff line number Diff line change
@@ -1,49 +1,44 @@
import { IJupyterWidgetRegistry } from '@jupyter-widgets/base';
import {
createRendermimePlugin,
JupyterFrontEnd,
JupyterFrontEndPlugin
} from '@jupyterlab/application';
import { ISessionContext, WidgetTracker } from '@jupyterlab/apputils';
import { IChangedArgs } from '@jupyterlab/coreutils';
import { IDocumentProviderFactory } from '@jupyterlab/docprovider';
import { MimeDocument } from '@jupyterlab/docregistry';
import { INotebookTracker } from '@jupyterlab/notebook';
import { IRenderMimeRegistry } from '@jupyterlab/rendermime';
import { IRenderMime } from '@jupyterlab/rendermime-interfaces';
import { ServerConnection } from '@jupyterlab/services';
import { IKernelConnection } from '@jupyterlab/services/lib/kernel/kernel';

import { JupyterCadFCModelFactory } from '../fcplugin/modelfactory';
import { IAnnotationModel, IDict } from '../types';
import { IAnnotation } from './../token';
import { NotebookRendererModel } from './model';
import { NotebookRendererModelFactory } from './modelFactory';
import { NotebookRenderer } from './view';

const MIME_TYPE = 'application/FCStd';

export const notebookRendererPlugin: JupyterFrontEndPlugin<void> = {
id: 'jupytercad:notebookRenderer',
autoStart: true,
requires: [IRenderMimeRegistry, IDocumentProviderFactory, IAnnotation],
requires: [IRenderMimeRegistry, IAnnotation],
activate: (
app: JupyterFrontEnd,
rendermime: IRenderMimeRegistry,
docProviderFactory: IDocumentProviderFactory,
annotationModel: IAnnotationModel
) => {
const model = new NotebookRendererModel({
const modelFactory = new NotebookRendererModelFactory({
manager: app.serviceManager,
docProviderFactory,
docModelFactory: new JupyterCadFCModelFactory({ annotationModel })
annotationModel
});

const rendererFactory: IRenderMime.IRendererFactory = {
safe: true,
mimeTypes: [MIME_TYPE],
createRenderer: options => {
const mimeType = options.mimeType;
return new NotebookRenderer({ mimeType, model });
return new NotebookRenderer({ mimeType, factory: modelFactory });
}
};

Expand Down
56 changes: 0 additions & 56 deletions src/notebookrenderer/model.ts

This file was deleted.

Loading

0 comments on commit 61e539c

Please sign in to comment.