Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
trungleduc committed Feb 7, 2023
1 parent ab8b938 commit 3f24cac
Show file tree
Hide file tree
Showing 12 changed files with 88 additions and 103 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
8 changes: 6 additions & 2 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,9 +66,9 @@ 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()
Expand Down
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
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ const controlPanel: JupyterFrontEndPlugin<void> = {
tracker: IJupyterCadTracker,
annotationModel: IAnnotationModel
) => {
console.log('hello2')
const controlModel = new ControlPanelModel({ tracker });

const leftControlPanel = new LeftPanelWidget({
Expand Down
99 changes: 43 additions & 56 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 @@ -363,15 +350,16 @@ export class MainView extends React.Component<IProps, IStates> {
if (!this._model) {
return;
}
console.log('sending', this._model.getContent())
this._postMessage({
action: WorkerAction.LOAD_FILE,
payload: {
fileName: this._context.path,
content: this._model.getContent()
}
});
}
}

};

private _projectVector = (
Expand Down Expand Up @@ -822,12 +810,12 @@ export class MainView extends React.Component<IProps, IStates> {
private _onSharedObjectsChanged(
_: IJupyterCadDoc,
change: IJcadObjectDocChange
): void {
): void {
console.log('_onSharedObjectsChanged', change)
if (change.objectChange) {
this._postMessage({
action: WorkerAction.LOAD_FILE,
payload: {
fileName: this._context.path,
content: this._model.getContent()
}
});
Expand Down Expand Up @@ -948,7 +936,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
1 change: 1 addition & 0 deletions src/notebookrenderer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export const notebookRendererPlugin: JupyterFrontEndPlugin<void> = {
const model = new NotebookRendererModel({
manager: app.serviceManager,
docProviderFactory,
annotationModel,
docModelFactory: new JupyterCadFCModelFactory({ annotationModel })
});

Expand Down
39 changes: 23 additions & 16 deletions src/notebookrenderer/model.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
import { IDocumentProviderFactory } from '@jupyterlab/docprovider';
import { Context, DocumentRegistry } from '@jupyterlab/docregistry';
import { ServiceManager } from '@jupyterlab/services';
import { ServerConnection, ServiceManager } from '@jupyterlab/services';
import { IDisposable } from '@lumino/disposable';
import { JupyterCadModel } from '../model';
import { WebsocketProvider as YWebsocketProvider } from 'y-websocket';
import { IAnnotationModel, IJupyterCadModel } from '../types';
import { URLExt } from '@jupyterlab/coreutils';

import { IJupyterCadModel } from '../types';
const Y_DOCUMENT_PROVIDER_URL = 'api/yjs';

export class NotebookRendererModel implements IDisposable {
constructor(options: NotebookRendererModel.IOptions) {
this._docProviderFactory = options.docProviderFactory;
this._manager = options.manager;
this._docModelFactory = options.docModelFactory;
this._annotationModel = options.annotationModel;
}

get isDisposed(): boolean {
Expand All @@ -24,24 +29,25 @@ export class NotebookRendererModel implements IDisposable {
this._isDisposed = true;
}

async createContext(
path: string
): Promise<DocumentRegistry.IContext<IJupyterCadModel> | undefined> {
if (this._context) {
return this._context;
}
this._context = new Context({
path,
manager: this._manager,
factory: this._docModelFactory,
docProviderFactory: this._docProviderFactory
});
await this._context.initialize(false);
return this._context;
async createJcadModel(roomId: string): Promise<IJupyterCadModel | undefined> {
console.log('path', roomId);
const server = ServerConnection.makeSettings();
const serverUrl = URLExt.join(server.wsUrl, Y_DOCUMENT_PROVIDER_URL);

const jcadModel = new JupyterCadModel(this._annotationModel);
const ywsProvider = new YWebsocketProvider(
serverUrl,
roomId,
jcadModel.sharedModel.ydoc
);
console.log('ywsProvider', ywsProvider);

return jcadModel;
}

private _context: Context<IJupyterCadModel> | undefined;
private _isDisposed = false;
private _annotationModel: IAnnotationModel;
private _manager: ServiceManager.IManager;
private _docProviderFactory: IDocumentProviderFactory;
private _docModelFactory: DocumentRegistry.IModelFactory<IJupyterCadModel>;
Expand All @@ -51,6 +57,7 @@ export namespace NotebookRendererModel {
export interface IOptions {
manager: ServiceManager.IManager;
docProviderFactory: IDocumentProviderFactory;
annotationModel: IAnnotationModel;
docModelFactory: DocumentRegistry.IModelFactory<IJupyterCadModel>;
}
}
12 changes: 4 additions & 8 deletions src/notebookrenderer/view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,11 @@ export class NotebookRenderer extends Widget {
}
async renderModel(mimeModel: IRenderMime.IMimeModel): Promise<void> {
const path = mimeModel.data[this._mimeType] as string;
const context = await this._model.createContext(path);
if (!context) {
const model = await this._model.createJcadModel(path);
if (!model) {
return;
}
const content = new JupyterCadPanel(context);
const toolbar = new ToolbarWidget({
model: new ToolbarModel({ panel: content, context })
});
this._jcadWidget = new JupyterCadWidget({ context, content, toolbar });
this._jcadWidget = new JupyterCadPanel({model});

MessageLoop.sendMessage(this._jcadWidget, Widget.Msg.BeforeAttach);
this.node.appendChild(this._jcadWidget.node);
Expand All @@ -52,7 +48,7 @@ export class NotebookRenderer extends Widget {
);
}
};
private _jcadWidget: JupyterCadWidget;
private _jcadWidget: JupyterCadPanel;
private _model: NotebookRendererModel;
private _mimeType: string;
}
12 changes: 2 additions & 10 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ export type ValueOf<T> = T[keyof T];
export enum WorkerAction {
LOAD_FILE = 'LOAD_FILE',
SAVE_FILE = 'SAVE_FILE',
CLOSE_FILE = 'CLOSE_FILE',
REGISTER = 'REGISTER'
}

Expand All @@ -46,19 +45,11 @@ export interface IRegister extends IMainId {
export interface ILoadFile extends IMainId {
action: WorkerAction.LOAD_FILE;
payload: {
fileName: string;
content: IJCadContent;
};
}

export interface ICloseFile extends IMainId {
action: WorkerAction.CLOSE_FILE;
payload: {
fileName: string;
};
}

export type IWorkerMessage = ILoadFile | IRegister | ICloseFile;
export type IWorkerMessage = ILoadFile | IRegister;

/**
* Action definitions for main thread
Expand All @@ -68,6 +59,7 @@ export enum MainAction {
INITIALIZED = 'INITIALIZED'
}


export interface IFace {
vertexCoord: Array<number>;
normalCoord: Array<number>;
Expand Down
8 changes: 4 additions & 4 deletions src/widget.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ export class JupyterCadPanel extends ReactWidget {
*
* @param context - The documents context.
*/
constructor(context: DocumentRegistry.IContext<IJupyterCadModel>) {
constructor(options: {model: IJupyterCadModel}) {
super();
this.addClass('jp-jupytercad-panel');
this._context = context;
this._jcadModel = options.model;

this._view = new ObservableMap<JSONValue>();
}
Expand Down Expand Up @@ -78,9 +78,9 @@ export class JupyterCadPanel extends ReactWidget {
}

render(): JSX.Element {
return <MainView view={this._view} context={this._context} />;
return <MainView view={this._view} jcadModel={this._jcadModel} />;
}

private _view: ObservableMap<JSONValue>;
private _context: DocumentRegistry.IContext<IJupyterCadModel>;
private _jcadModel: IJupyterCadModel;
}
Loading

0 comments on commit 3f24cac

Please sign in to comment.