-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathcontroller.tsx
More file actions
439 lines (397 loc) · 16.5 KB
/
controller.tsx
File metadata and controls
439 lines (397 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
import app from "app";
import BrainSpinner, { BrainSpinnerWithError, CoverWithLogin } from "components/brain_spinner";
import { fetchGistContent } from "libs/gist";
import { InputKeyboardNoLoop } from "libs/input";
import Toast from "libs/toast";
import { getUrlParamValue, hasUrlParam, isNoElementFocused } from "libs/utils";
import window, { document } from "libs/window";
import { type WithBlockerProps, withBlocker } from "libs/with_blocker_hoc";
import { type RouteComponentProps, withRouter } from "libs/with_router_hoc";
import messages from "messages";
import { PureComponent } from "react";
import { connect } from "react-redux";
import type { BlockerFunction } from "react-router-dom";
import type { APIOrganization, APIUser } from "types/api_types";
import { APIAnnotationTypeEnum, type APICompoundType } from "types/api_types";
import ApiLoader from "viewer/api/api_loader";
import type { ViewMode } from "viewer/constants";
import constants, { ControlModeEnum } from "viewer/constants";
import { initializeSceneController } from "viewer/controller/scene_controller";
import UrlManager from "viewer/controller/url_manager";
import ArbitraryController from "viewer/controller/viewmodes/arbitrary_controller";
import PlaneController from "viewer/controller/viewmodes/plane_controller";
import { wkInitializedAction } from "viewer/model/actions/actions";
import { redoAction, saveNowAction, undoAction } from "viewer/model/actions/save_actions";
import { setIsInAnnotationViewAction } from "viewer/model/actions/ui_actions";
import { HANDLED_ERROR } from "viewer/model_initialization";
import { Model } from "viewer/singletons";
import type { TraceOrViewCommand, WebknossosState } from "viewer/store";
import Store from "viewer/store";
import { AnnotationTool } from "./model/accessors/tool_accessor";
import { setViewModeAction, updateLayerSettingAction } from "./model/actions/settings_actions";
import type DataLayer from "./model/data_layer";
import {
GeneralEditingKeyboardShortcuts,
GeneralKeyboardShortcuts,
} from "./view/keyboard_shortcuts/keyboard_shortcut_constants";
import { loadKeyboardShortcuts } from "./view/keyboard_shortcuts/keyboard_shortcut_persistence";
import type { KeyboardShortcutNoLoopedHandlerMap } from "./view/keyboard_shortcuts/keyboard_shortcut_types";
import { buildKeyBindingsFromConfigAndMapping } from "./view/keyboard_shortcuts/keyboard_shortcut_utils";
export type ControllerStatus = "loading" | "loaded" | "failedLoading";
type OwnProps = {
initialMaybeCompoundType: APICompoundType | null;
initialCommandType: TraceOrViewCommand;
controllerStatus: ControllerStatus;
setControllerStatus: (arg0: ControllerStatus) => void;
};
type StateProps = {
viewMode: ViewMode;
user: APIUser | null | undefined;
isUiReady: boolean;
isWkInitialized: boolean;
};
type Props = OwnProps & StateProps;
type PropsWithRouter = Props & RouteComponentProps & WithBlockerProps;
type State = {
gotUnhandledError: boolean;
organizationToSwitchTo: APIOrganization | null | undefined;
};
type ControllerEditAllowedKeyboardHandlerIdMap = KeyboardShortcutNoLoopedHandlerMap<
GeneralKeyboardShortcuts | GeneralEditingKeyboardShortcuts
>;
type ControllerViewOnlyKeyboardHandlerIdMap =
KeyboardShortcutNoLoopedHandlerMap<GeneralKeyboardShortcuts>;
type ControllerKeyboardHandlerIdMap =
| ControllerEditAllowedKeyboardHandlerIdMap
| ControllerViewOnlyKeyboardHandlerIdMap;
class Controller extends PureComponent<PropsWithRouter, State> {
keyboardNoLoop?: InputKeyboardNoLoop;
_isMounted: boolean = false;
state: State = {
gotUnhandledError: false,
organizationToSwitchTo: null,
};
unsubscribeKeyboardListener: any = () => {};
// Main controller, responsible for setting modes and everything
// that has to be controlled in any mode.
//
// We have a matrix of modes like this:
//
// Annotation Mode \ View mode Plane Arbitrary
// Skeleton annotation X X
// Volume annotation X /
//
// In order to maximize code reuse, there is - besides the main
// controller - a controller for each row, each column and each
// cross in this matrix.
componentDidMount() {
this._isMounted = true;
Store.dispatch(setIsInAnnotationViewAction(true));
UrlManager.initialize();
if (!this.isWebGlSupported()) {
Toast.error(messages["webgl.disabled"]);
}
this.tryFetchingModel();
}
componentWillUnmount() {
this._isMounted = false;
this.keyboardNoLoop?.destroy();
Store.dispatch(setIsInAnnotationViewAction(false));
this.props.setBlocking({
shouldBlock: false,
});
this.unsubscribeKeyboardListener();
}
tryFetchingModel() {
this.props.setControllerStatus("loading");
// Preview a working annotation version if the showVersionRestore URL parameter is supplied
const version = hasUrlParam("showVersionRestore")
? hasUrlParam("version")
? Number.parseInt(getUrlParamValue("version"), 10)
: 1
: undefined;
Model.fetch(this.props.initialMaybeCompoundType, this.props.initialCommandType, true, version)
.then(() => this.modelFetchDone())
.catch((error) => {
this.props.setControllerStatus("failedLoading");
const isNotFoundError = error.status === 404;
if (
this.props.initialMaybeCompoundType === APIAnnotationTypeEnum.CompoundProject &&
isNotFoundError
) {
Toast.error(messages["tracing.compound_project_not_found"], {
sticky: true,
});
}
if (error.organizationToSwitchTo != null && this.props.user != null) {
this.setState({
organizationToSwitchTo: error.organizationToSwitchTo,
});
}
if (error !== HANDLED_ERROR && !isNotFoundError) {
// Don't throw errors for errors already handled by the model
// or "Not Found" errors because they are already handled elsewhere.
Toast.error(`${messages["tracing.unhandled_initialization_error"]} ${error.toString()}`, {
sticky: true,
});
this.setState({
gotUnhandledError: true,
});
throw error;
}
});
}
modelFetchDone() {
const beforeUnload = (args: BeforeUnloadEvent | BlockerFunction): boolean | undefined => {
// Navigation blocking can be triggered by two sources:
// 1. The browser's native beforeunload event
// 2. The React-Router block function (useBlocker or withBlocker HOC)
if (!Model.stateSaved() && Store.getState().annotation.restrictions.allowUpdate) {
window.onbeforeunload = null; // clear the event handler otherwise it would be called twice. Once from history.block once from the beforeunload event
setTimeout(() => {
if (!this._isMounted) {
return false;
}
Store.dispatch(saveNowAction());
// restore the event handler in case a user chose to stay on the page
window.onbeforeunload = beforeUnload;
}, 500);
// The native event requires a truthy return value to show a generic message
// The React Router blocker accepts a boolean
return "preventDefault" in args ? true : !confirm(messages["save.leave_page_unfinished"]);
}
// The native event requires an empty return value to not show a message
return;
};
window.onbeforeunload = beforeUnload;
this.props.setBlocking({
// @ts-expect-error beforeUnload signature is overloaded
shouldBlock: beforeUnload,
});
UrlManager.startUrlUpdater();
initializeSceneController();
this.initKeyboard();
this.initTaskScript();
window.webknossos = new ApiLoader(Model);
app.vent.emit("webknossos:initialized");
Store.dispatch(wkInitializedAction());
this.props.setControllerStatus("loaded");
}
async initTaskScript() {
// Loads a Gist from GitHub with a user script if there is a
// script assigned to the task
const { task } = Store.getState();
if (task?.script != null) {
const { script } = task;
const content = await fetchGistContent(script.gist, script.name);
try {
// biome-ignore lint/security/noGlobalEval: This loads a user provided frontend API script.
eval(content);
} catch (error) {
Toast.error(
`Error executing the task script "${script.name}". See console for more information.`,
);
console.error(error);
}
}
}
isWebGlSupported() {
return (
window.WebGLRenderingContext &&
document.createElement("canvas").getContext("experimental-webgl")
);
}
getKeyboardShortcutsHandlerMap(): ControllerKeyboardHandlerIdMap {
let leastRecentlyUsedSegmentationLayer: DataLayer | null = null;
function toggleSegmentationOpacity() {
let segmentationLayer = Model.getVisibleSegmentationLayer();
if (segmentationLayer != null) {
// If there is a visible segmentation layer, disable and remember it.
leastRecentlyUsedSegmentationLayer = segmentationLayer;
} else if (leastRecentlyUsedSegmentationLayer != null) {
// If no segmentation layer is visible, use the least recently toggled
// layer (note that toggling the layer via the switch-button won't update
// the local variable here).
segmentationLayer = leastRecentlyUsedSegmentationLayer;
} else {
// As a fallback, simply use some segmentation layer
segmentationLayer = Model.getSomeSegmentationLayer();
}
if (segmentationLayer == null) {
return;
}
const segmentationLayerName = segmentationLayer.name;
const isSegmentationDisabled =
Store.getState().datasetConfiguration.layers[segmentationLayerName].isDisabled;
Store.dispatch(
updateLayerSettingAction(segmentationLayerName, "isDisabled", !isSegmentationDisabled),
);
}
const isInViewMode =
Store.getState().temporaryConfiguration.controlMode === ControlModeEnum.VIEW;
const editRelatedHandlers: KeyboardShortcutNoLoopedHandlerMap<GeneralEditingKeyboardShortcuts> =
{
[GeneralEditingKeyboardShortcuts.SAVE]: {
onPressed: (event: KeyboardEvent) => {
event.preventDefault();
event.stopPropagation();
Model.forceSave();
},
},
// Undo
[GeneralEditingKeyboardShortcuts.UNDO]: {
onPressed: (event: KeyboardEvent) => {
event.preventDefault();
event.stopPropagation();
Store.dispatch(undoAction());
},
},
[GeneralEditingKeyboardShortcuts.REDO]: {
onPressed: (event: KeyboardEvent) => {
event.preventDefault();
event.stopPropagation();
Store.dispatch(redoAction());
},
},
};
// Wrapped in a function to ensure each time the map is used, a new instance of getHandleToggleSegmentation
// is created and thus "leastRecentlyUsedSegmentationLayer" not being shared between key binding maps.
const keyboardShortcutsHandlerMapForController: ControllerKeyboardHandlerIdMap = {
[GeneralKeyboardShortcuts.SWITCH_VIEWMODE_PLANE]: {
onPressed: () => {
Store.dispatch(setViewModeAction(constants.MODE_PLANE_TRACING));
},
},
[GeneralKeyboardShortcuts.SWITCH_VIEWMODE_ARBITRARY]: {
onPressed: () => {
Store.dispatch(setViewModeAction(constants.MODE_ARBITRARY));
},
},
[GeneralKeyboardShortcuts.SWITCH_VIEWMODE_ARBITRARY_PLANE]: {
onPressed: () => {
Store.dispatch(setViewModeAction(constants.MODE_ARBITRARY_PLANE));
},
},
[GeneralKeyboardShortcuts.CYCLE_VIEWMODE]: {
onPressed: () => {
// rotate allowed modes
const state = Store.getState();
const isProofreadingActive = state.uiInformation.activeTool === AnnotationTool.PROOFREAD;
const currentViewMode = state.temporaryConfiguration.viewMode;
if (isProofreadingActive && currentViewMode === constants.MODE_PLANE_TRACING) {
// Skipping cycling view mode as m in proofreading is used to toggle multi cut tool.
return;
}
const { allowedModes } = state.annotation.restrictions;
const index = (allowedModes.indexOf(currentViewMode) + 1) % allowedModes.length;
Store.dispatch(setViewModeAction(allowedModes[index]));
},
},
[GeneralKeyboardShortcuts.TOGGLE_SEGMENTATION]: {
onPressed: toggleSegmentationOpacity,
...(isInViewMode ? {} : editRelatedHandlers),
},
};
return keyboardShortcutsHandlerMapForController;
}
initKeyboard() {
// avoid scrolling while pressing space
document.addEventListener("keydown", (event: KeyboardEvent) => {
if (
(event.which === 32 || event.which === 18 || (event.which >= 37 && event.which <= 40)) &&
isNoElementFocused()
) {
event.preventDefault();
}
});
this.reloadKeyboardShortcuts();
this.unsubscribeKeyboardListener = app.vent.on("refreshKeyboardShortcuts", () =>
this.reloadKeyboardShortcuts(),
);
}
reloadKeyboardShortcuts() {
if (this.keyboardNoLoop) {
this.keyboardNoLoop.destroy();
}
const keybindingConfig = loadKeyboardShortcuts();
const keyboardControls = buildKeyBindingsFromConfigAndMapping(
keybindingConfig,
this.getKeyboardShortcutsHandlerMap(),
);
this.keyboardNoLoop = new InputKeyboardNoLoop(keyboardControls);
}
render() {
const status = this.props.controllerStatus;
const { user, viewMode, isUiReady, isWkInitialized } = this.props;
const { gotUnhandledError, organizationToSwitchTo } = this.state;
let cover = null;
// Show the brain spinner during loading and until the UI is ready
if (status === "loading" || (status === "loaded" && !isUiReady)) {
cover = <BrainSpinner />;
} else if (status === "failedLoading" && user != null) {
cover = (
<BrainSpinnerWithError
gotUnhandledError={gotUnhandledError}
organizationToSwitchTo={organizationToSwitchTo}
/>
);
} else if (status === "failedLoading") {
cover = (
<CoverWithLogin
onLoggedIn={() => {
// Close existing error toasts for "Not Found" errors before trying again.
// If they get relevant again, they will be recreated anyway.
Toast.close("404");
this.tryFetchingModel();
}}
/>
);
}
// If wk is not initialized yet, only render the cover. If it is initialized, start rendering the controllers
// in the background, hidden by the cover.
// The _isMounted check is important, because when switching pages without a reload, there is a short period of time
// where the old tracing view instance still exists and isWkInitialized is true, although it has not been newly initialized yet.
// In this scenario, this `render` method here is called before `componentWillUnmount` of the TracingLayoutView is called.
if (!this._isMounted || !isWkInitialized) {
return cover;
}
const { allowedModes } = Store.getState().annotation.restrictions;
if (!allowedModes.includes(viewMode)) {
// Since this mode is not allowed, render nothing. A warning about this will be
// triggered in the model. Don't throw an error since the store might change so that
// the render function can succeed.
return null;
}
const isArbitrary = constants.MODES_ARBITRARY.includes(viewMode);
const isPlane = constants.MODES_PLANE.includes(viewMode);
if (isArbitrary) {
return (
<>
{cover != null ? cover : null}
<ArbitraryController viewMode={viewMode} />
</>
);
} else if (isPlane) {
return (
<>
{cover != null ? cover : null}
<PlaneController />
</>
);
} else {
// At the moment, all possible view modes consist of the union of MODES_ARBITRARY and MODES_PLANE
// In case we add new viewmodes, the following error will be thrown.
throw new Error("The current mode is none of the four known mode types");
}
}
}
function mapStateToProps(state: WebknossosState): StateProps {
return {
isUiReady: state.uiInformation.isUiReady,
isWkInitialized: state.uiInformation.isWkInitialized,
viewMode: state.temporaryConfiguration.viewMode,
user: state.activeUser,
};
}
const connector = connect(mapStateToProps);
export default connector(withBlocker(withRouter<PropsWithRouter>(Controller)));