snapshots.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. /**
  2. * Copyright (c) 2018-2023 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  6. */
  7. import { List } from 'immutable';
  8. import { UUID } from '../../mol-util';
  9. import { PluginState } from '../../mol-plugin/state';
  10. import { StatefulPluginComponent } from '../component';
  11. import { PluginContext } from '../../mol-plugin/context';
  12. import { utf8ByteCount, utf8Write } from '../../mol-io/common/utf8';
  13. import { Asset } from '../../mol-util/assets';
  14. import { Zip } from '../../mol-util/zip/zip';
  15. import { readFromFile } from '../../mol-util/data-source';
  16. import { objectForEach } from '../../mol-util/object';
  17. import { PLUGIN_VERSION } from '../../mol-plugin/version';
  18. import { canvasToBlob } from '../../mol-canvas3d/util';
  19. export { PluginStateSnapshotManager };
  20. class PluginStateSnapshotManager extends StatefulPluginComponent<{
  21. current?: UUID | undefined,
  22. entries: List<PluginStateSnapshotManager.Entry>,
  23. isPlaying: boolean,
  24. nextSnapshotDelayInMs: number
  25. }> {
  26. static DefaultNextSnapshotDelayInMs = 1500;
  27. private entryMap = new Map<string, PluginStateSnapshotManager.Entry>();
  28. readonly events = {
  29. changed: this.ev()
  30. };
  31. getIndex(e: PluginStateSnapshotManager.Entry) {
  32. return this.state.entries.indexOf(e);
  33. }
  34. getEntry(id: string | undefined) {
  35. if (!id) return;
  36. return this.entryMap.get(id);
  37. }
  38. remove(id: string) {
  39. const e = this.entryMap.get(id);
  40. if (!e) return;
  41. if (e?.image) this.plugin.managers.asset.delete(e.image);
  42. this.entryMap.delete(id);
  43. this.updateState({
  44. current: this.state.current === id ? void 0 : this.state.current,
  45. entries: this.state.entries.delete(this.getIndex(e))
  46. });
  47. this.events.changed.next(void 0);
  48. }
  49. add(e: PluginStateSnapshotManager.Entry) {
  50. this.entryMap.set(e.snapshot.id, e);
  51. this.updateState({ current: e.snapshot.id, entries: this.state.entries.push(e) });
  52. this.events.changed.next(void 0);
  53. }
  54. replace(id: string, snapshot: PluginState.Snapshot, params?: PluginStateSnapshotManager.EntryParams) {
  55. const old = this.getEntry(id);
  56. if (!old) return;
  57. if (old?.image) this.plugin.managers.asset.delete(old.image);
  58. const idx = this.getIndex(old);
  59. // The id changes here!
  60. const e = PluginStateSnapshotManager.Entry(snapshot, {
  61. name: params?.name ?? old.name,
  62. description: params?.description ?? old.description,
  63. image: params?.image,
  64. });
  65. this.entryMap.set(snapshot.id, e);
  66. this.updateState({ current: e.snapshot.id, entries: this.state.entries.set(idx, e) });
  67. this.events.changed.next(void 0);
  68. }
  69. move(id: string, dir: -1 | 1) {
  70. const len = this.state.entries.size;
  71. if (len < 2) return;
  72. const e = this.getEntry(id);
  73. if (!e) return;
  74. const from = this.getIndex(e);
  75. let to = (from + dir) % len;
  76. if (to < 0) to += len;
  77. const f = this.state.entries.get(to)!;
  78. const entries = this.state.entries.asMutable();
  79. entries.set(to, e);
  80. entries.set(from, f);
  81. this.updateState({ current: e.snapshot.id, entries: entries.asImmutable() });
  82. this.events.changed.next(void 0);
  83. }
  84. clear() {
  85. if (this.state.entries.size === 0) return;
  86. this.entryMap.forEach(e => {
  87. if (e?.image) this.plugin.managers.asset.delete(e.image);
  88. });
  89. this.entryMap.clear();
  90. this.updateState({ current: void 0, entries: List<PluginStateSnapshotManager.Entry>() });
  91. this.events.changed.next(void 0);
  92. }
  93. setCurrent(id: string) {
  94. const e = this.getEntry(id);
  95. if (e) {
  96. this.updateState({ current: id as UUID });
  97. this.events.changed.next(void 0);
  98. }
  99. return e && e.snapshot;
  100. }
  101. getNextId(id: string | undefined, dir: -1 | 1) {
  102. const len = this.state.entries.size;
  103. if (!id) {
  104. if (len === 0) return void 0;
  105. const idx = dir === -1 ? len - 1 : 0;
  106. return this.state.entries.get(idx)!.snapshot.id;
  107. }
  108. const e = this.getEntry(id);
  109. if (!e) return;
  110. let idx = this.getIndex(e);
  111. if (idx < 0) return;
  112. idx = (idx + dir) % len;
  113. if (idx < 0) idx += len;
  114. return this.state.entries.get(idx)!.snapshot.id;
  115. }
  116. async setStateSnapshot(snapshot: PluginStateSnapshotManager.StateSnapshot): Promise<PluginState.Snapshot | undefined> {
  117. if (snapshot.version !== PLUGIN_VERSION) {
  118. // TODO
  119. // console.warn('state snapshot version mismatch');
  120. }
  121. this.clear();
  122. const entries = List<PluginStateSnapshotManager.Entry>().asMutable();
  123. for (const e of snapshot.entries) {
  124. this.entryMap.set(e.snapshot.id, e);
  125. entries.push(e);
  126. }
  127. const current = snapshot.current
  128. ? snapshot.current
  129. : snapshot.entries.length > 0
  130. ? snapshot.entries[0].snapshot.id
  131. : void 0;
  132. this.updateState({
  133. current,
  134. entries: entries.asImmutable(),
  135. isPlaying: false,
  136. nextSnapshotDelayInMs: snapshot.playback ? snapshot.playback.nextSnapshotDelayInMs : PluginStateSnapshotManager.DefaultNextSnapshotDelayInMs
  137. });
  138. this.events.changed.next(void 0);
  139. if (!current) return;
  140. const entry = this.getEntry(current);
  141. const next = entry && entry.snapshot;
  142. if (!next) return;
  143. await this.plugin.state.setSnapshot(next);
  144. if (snapshot.playback && snapshot.playback.isPlaying) this.play(true);
  145. return next;
  146. }
  147. private async syncCurrent(options?: { name?: string, description?: string, params?: PluginState.SnapshotParams }) {
  148. const snapshot = this.plugin.state.getSnapshot(options?.params);
  149. if (this.state.entries.size === 0 || !this.state.current) {
  150. this.add(PluginStateSnapshotManager.Entry(snapshot, { name: options?.name, description: options?.description }));
  151. } else {
  152. const current = this.getEntry(this.state.current);
  153. if (current?.image) this.plugin.managers.asset.delete(current.image);
  154. const image = (options?.params?.image ?? this.plugin.state.snapshotParams.value.image) ? await PluginStateSnapshotManager.getCanvasImageAsset(this.plugin, `${snapshot.id}-image.png`) : undefined;
  155. // TODO: this replaces the current snapshot which is not always intended
  156. this.replace(this.state.current, snapshot, { image });
  157. }
  158. }
  159. async getStateSnapshot(options?: { name?: string, description?: string, playOnLoad?: boolean, params?: PluginState.SnapshotParams }): Promise<PluginStateSnapshotManager.StateSnapshot> {
  160. // TODO: diffing and all that fancy stuff
  161. await this.syncCurrent(options);
  162. return {
  163. timestamp: +new Date(),
  164. version: PLUGIN_VERSION,
  165. name: options && options.name,
  166. description: options && options.description,
  167. current: this.state.current,
  168. playback: {
  169. isPlaying: !!(options && options.playOnLoad),
  170. nextSnapshotDelayInMs: this.state.nextSnapshotDelayInMs
  171. },
  172. entries: this.state.entries.valueSeq().toArray()
  173. };
  174. }
  175. async serialize(options?: { type: 'json' | 'molj' | 'zip' | 'molx', params?: PluginState.SnapshotParams }) {
  176. const json = JSON.stringify(await this.getStateSnapshot({ params: options?.params }), null, 2);
  177. if (!options?.type || options.type === 'json' || options.type === 'molj') {
  178. return new Blob([json], { type: 'application/json;charset=utf-8' });
  179. } else {
  180. const state = new Uint8Array(utf8ByteCount(json));
  181. utf8Write(state, 0, json);
  182. const zipDataObj: { [k: string]: Uint8Array } = {
  183. 'state.json': state
  184. };
  185. const assets: [UUID, Asset][] = [];
  186. // TODO: there can be duplicate entries: check for this?
  187. for (const { asset, file } of this.plugin.managers.asset.assets) {
  188. assets.push([asset.id, asset]);
  189. zipDataObj[`assets/${asset.id}`] = new Uint8Array(await file.arrayBuffer());
  190. }
  191. if (assets.length > 0) {
  192. const index = JSON.stringify(assets, null, 2);
  193. const data = new Uint8Array(utf8ByteCount(index));
  194. utf8Write(data, 0, index);
  195. zipDataObj['assets.json'] = data;
  196. }
  197. const zipFile = await this.plugin.runTask(Zip(zipDataObj));
  198. return new Blob([zipFile], { type: 'application/zip' });
  199. }
  200. }
  201. async open(file: File) {
  202. try {
  203. const fn = file.name.toLowerCase();
  204. if (fn.endsWith('json') || fn.endsWith('molj')) {
  205. const data = await this.plugin.runTask(readFromFile(file, 'string'));
  206. const snapshot = JSON.parse(data);
  207. if (PluginStateSnapshotManager.isStateSnapshot(snapshot)) {
  208. return this.setStateSnapshot(snapshot);
  209. } else if (PluginStateSnapshotManager.isStateSnapshot(snapshot.data)) {
  210. return this.setStateSnapshot(snapshot.data);
  211. } else {
  212. this.plugin.state.setSnapshot(snapshot);
  213. }
  214. } else {
  215. const data = await this.plugin.runTask(readFromFile(file, 'zip'));
  216. const assetData = Object.create(null);
  217. objectForEach(data, (v, k) => {
  218. if (k === 'state.json' || k === 'assets.json') return;
  219. const name = k.substring(k.indexOf('/') + 1);
  220. assetData[name] = v;
  221. });
  222. const stateFile = new File([data['state.json']], 'state.json');
  223. const stateData = await this.plugin.runTask(readFromFile(stateFile, 'string'));
  224. if (data['assets.json']) {
  225. const file = new File([data['assets.json']], 'assets.json');
  226. const json = JSON.parse(await this.plugin.runTask(readFromFile(file, 'string')));
  227. for (const [id, asset] of json) {
  228. this.plugin.managers.asset.set(asset, new File([assetData[id]], asset.name));
  229. }
  230. }
  231. const snapshot = JSON.parse(stateData);
  232. return this.setStateSnapshot(snapshot);
  233. }
  234. } catch (e) {
  235. console.error(e);
  236. this.plugin.log.error('Error reading state');
  237. }
  238. }
  239. private timeoutHandle: any = void 0;
  240. private next = async () => {
  241. this.timeoutHandle = void 0;
  242. const next = this.getNextId(this.state.current, 1);
  243. if (!next || next === this.state.current) {
  244. this.stop();
  245. return;
  246. }
  247. const snapshot = this.setCurrent(next)!;
  248. await this.plugin.state.setSnapshot(snapshot);
  249. const delay = typeof snapshot.durationInMs !== 'undefined' ? snapshot.durationInMs : this.state.nextSnapshotDelayInMs;
  250. if (this.state.isPlaying) this.timeoutHandle = setTimeout(this.next, delay);
  251. };
  252. play(delayFirst: boolean = false) {
  253. this.updateState({ isPlaying: true });
  254. if (delayFirst) {
  255. const e = this.getEntry(this.state.current);
  256. if (!e) {
  257. this.next();
  258. return;
  259. }
  260. this.events.changed.next(void 0);
  261. const snapshot = e.snapshot;
  262. const delay = typeof snapshot.durationInMs !== 'undefined' ? snapshot.durationInMs : this.state.nextSnapshotDelayInMs;
  263. this.timeoutHandle = setTimeout(this.next, delay);
  264. } else {
  265. this.next();
  266. }
  267. }
  268. stop() {
  269. this.updateState({ isPlaying: false });
  270. if (typeof this.timeoutHandle !== 'undefined') clearTimeout(this.timeoutHandle);
  271. this.timeoutHandle = void 0;
  272. this.events.changed.next(void 0);
  273. }
  274. togglePlay() {
  275. if (this.state.isPlaying) {
  276. this.stop();
  277. this.plugin.managers.animation.stop();
  278. } else {
  279. this.play();
  280. }
  281. }
  282. constructor(private plugin: PluginContext) {
  283. super({
  284. current: void 0,
  285. entries: List(),
  286. isPlaying: false,
  287. nextSnapshotDelayInMs: PluginStateSnapshotManager.DefaultNextSnapshotDelayInMs
  288. });
  289. // TODO make nextSnapshotDelayInMs editable
  290. }
  291. }
  292. namespace PluginStateSnapshotManager {
  293. export interface EntryParams {
  294. name?: string,
  295. description?: string,
  296. image?: Asset
  297. }
  298. export interface Entry extends EntryParams {
  299. timestamp: number,
  300. snapshot: PluginState.Snapshot
  301. }
  302. export function Entry(snapshot: PluginState.Snapshot, params: EntryParams): Entry {
  303. return { timestamp: +new Date(), snapshot, ...params };
  304. }
  305. export function isStateSnapshot(x?: any): x is StateSnapshot {
  306. const s = x as StateSnapshot;
  307. return !!s && !!s.timestamp && !!s.entries;
  308. }
  309. export interface StateSnapshot {
  310. timestamp: number,
  311. version: string,
  312. name?: string,
  313. description?: string,
  314. current: UUID | undefined,
  315. playback: {
  316. isPlaying: boolean,
  317. nextSnapshotDelayInMs: number,
  318. },
  319. entries: Entry[]
  320. }
  321. export async function getCanvasImageAsset(ctx: PluginContext, name: string): Promise<Asset | undefined> {
  322. if (!ctx.helpers.viewportScreenshot) return;
  323. const p = ctx.helpers.viewportScreenshot.getPreview(512);
  324. if (!p) return;
  325. const blob = await canvasToBlob(p.canvas, 'png');
  326. const file = new File([blob], name);
  327. const image: Asset = { kind: 'file', id: UUID.create22(), name };
  328. ctx.managers.asset.set(image, file);
  329. return image;
  330. }
  331. }