snapshots.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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. private defaultSnapshotId: UUID | undefined = undefined;
  29. readonly events = {
  30. changed: this.ev(),
  31. opened: this.ev(),
  32. };
  33. getIndex(e: PluginStateSnapshotManager.Entry) {
  34. return this.state.entries.indexOf(e);
  35. }
  36. getEntry(id: string | undefined) {
  37. if (!id) return;
  38. return this.entryMap.get(id);
  39. }
  40. remove(id: string) {
  41. const e = this.entryMap.get(id);
  42. if (!e) return;
  43. if (e?.image) this.plugin.managers.asset.delete(e.image);
  44. this.entryMap.delete(id);
  45. this.updateState({
  46. current: this.state.current === id ? void 0 : this.state.current,
  47. entries: this.state.entries.delete(this.getIndex(e))
  48. });
  49. this.events.changed.next(void 0);
  50. }
  51. add(e: PluginStateSnapshotManager.Entry) {
  52. this.entryMap.set(e.snapshot.id, e);
  53. this.updateState({ current: e.snapshot.id, entries: this.state.entries.push(e) });
  54. this.events.changed.next(void 0);
  55. }
  56. replace(id: string, snapshot: PluginState.Snapshot, params?: PluginStateSnapshotManager.EntryParams) {
  57. const old = this.getEntry(id);
  58. if (!old) return;
  59. this.defaultSnapshotId = undefined;
  60. if (old?.image) this.plugin.managers.asset.delete(old.image);
  61. const idx = this.getIndex(old);
  62. // The id changes here!
  63. const e = PluginStateSnapshotManager.Entry(snapshot, {
  64. key: params?.key ?? old.key,
  65. name: params?.name ?? old.name,
  66. description: params?.description ?? old.description,
  67. image: params?.image,
  68. });
  69. this.entryMap.set(snapshot.id, e);
  70. this.updateState({ current: e.snapshot.id, entries: this.state.entries.set(idx, e) });
  71. this.events.changed.next(void 0);
  72. }
  73. move(id: string, dir: -1 | 1) {
  74. const len = this.state.entries.size;
  75. if (len < 2) return;
  76. const e = this.getEntry(id);
  77. if (!e) return;
  78. const from = this.getIndex(e);
  79. let to = (from + dir) % len;
  80. if (to < 0) to += len;
  81. const f = this.state.entries.get(to)!;
  82. const entries = this.state.entries.asMutable();
  83. entries.set(to, e);
  84. entries.set(from, f);
  85. this.updateState({ current: e.snapshot.id, entries: entries.asImmutable() });
  86. this.events.changed.next(void 0);
  87. }
  88. update(e: PluginStateSnapshotManager.Entry, options: { key?: string, name?: string, description?: string }) {
  89. const idx = this.getIndex(e);
  90. if (idx < 0) return;
  91. const entries = this.state.entries.set(idx, {
  92. ...e,
  93. key: options.key?.trim() || undefined,
  94. name: options.name?.trim() || undefined,
  95. description: options.description?.trim() || undefined
  96. });
  97. this.updateState({ entries });
  98. this.entryMap.set(e.snapshot.id, this.state.entries.get(idx)!);
  99. this.events.changed.next(void 0);
  100. }
  101. clear() {
  102. if (this.state.entries.size === 0) return;
  103. this.entryMap.forEach(e => {
  104. if (e?.image) this.plugin.managers.asset.delete(e.image);
  105. });
  106. this.entryMap.clear();
  107. this.updateState({ current: void 0, entries: List<PluginStateSnapshotManager.Entry>() });
  108. this.events.changed.next(void 0);
  109. }
  110. applyKey(key: string) {
  111. const e = this.state.entries.find(e => e.key === key);
  112. if (!e) return;
  113. this.updateState({ current: e.snapshot.id as UUID });
  114. this.events.changed.next(void 0);
  115. this.plugin.state.setSnapshot(e.snapshot);
  116. }
  117. setCurrent(id: string) {
  118. const e = this.getEntry(id);
  119. if (e) {
  120. this.updateState({ current: id as UUID });
  121. this.events.changed.next(void 0);
  122. }
  123. return e && e.snapshot;
  124. }
  125. getNextId(id: string | undefined, dir: -1 | 1) {
  126. const len = this.state.entries.size;
  127. if (!id) {
  128. if (len === 0) return void 0;
  129. const idx = dir === -1 ? len - 1 : 0;
  130. return this.state.entries.get(idx)!.snapshot.id;
  131. }
  132. const e = this.getEntry(id);
  133. if (!e) return;
  134. let idx = this.getIndex(e);
  135. if (idx < 0) return;
  136. idx = (idx + dir) % len;
  137. if (idx < 0) idx += len;
  138. return this.state.entries.get(idx)!.snapshot.id;
  139. }
  140. async setStateSnapshot(snapshot: PluginStateSnapshotManager.StateSnapshot): Promise<PluginState.Snapshot | undefined> {
  141. if (snapshot.version !== PLUGIN_VERSION) {
  142. // TODO
  143. // console.warn('state snapshot version mismatch');
  144. }
  145. this.clear();
  146. const entries = List<PluginStateSnapshotManager.Entry>().asMutable();
  147. for (const e of snapshot.entries) {
  148. this.entryMap.set(e.snapshot.id, e);
  149. entries.push(e);
  150. }
  151. const current = snapshot.current
  152. ? snapshot.current
  153. : snapshot.entries.length > 0
  154. ? snapshot.entries[0].snapshot.id
  155. : void 0;
  156. this.updateState({
  157. current,
  158. entries: entries.asImmutable(),
  159. isPlaying: false,
  160. nextSnapshotDelayInMs: snapshot.playback ? snapshot.playback.nextSnapshotDelayInMs : PluginStateSnapshotManager.DefaultNextSnapshotDelayInMs
  161. });
  162. this.events.changed.next(void 0);
  163. if (!current) return;
  164. const entry = this.getEntry(current);
  165. const next = entry && entry.snapshot;
  166. if (!next) return;
  167. await this.plugin.state.setSnapshot(next);
  168. if (snapshot.playback && snapshot.playback.isPlaying) this.play(true);
  169. return next;
  170. }
  171. private async syncCurrent(options?: { name?: string, description?: string, params?: PluginState.SnapshotParams }) {
  172. const isEmpty = this.state.entries.size === 0;
  173. const canReplace = this.state.entries.size === 1 && this.state.current && this.state.current === this.defaultSnapshotId;
  174. if (!isEmpty && !canReplace) return;
  175. const snapshot = this.plugin.state.getSnapshot(options?.params);
  176. const image = (options?.params?.image ?? this.plugin.state.snapshotParams.value.image) ? await PluginStateSnapshotManager.getCanvasImageAsset(this.plugin, `${snapshot.id}-image.png`) : undefined;
  177. if (isEmpty) {
  178. this.add(PluginStateSnapshotManager.Entry(snapshot, { name: options?.name, description: options?.description, image }));
  179. } else if (canReplace) {
  180. // Replace the current state only if there is a single snapshot that has been created automatically
  181. const current = this.getEntry(this.state.current);
  182. if (current?.image) this.plugin.managers.asset.delete(current.image);
  183. this.replace(this.state.current!, snapshot, { image });
  184. }
  185. this.defaultSnapshotId = snapshot.id;
  186. }
  187. async getStateSnapshot(options?: { name?: string, description?: string, playOnLoad?: boolean, params?: PluginState.SnapshotParams }): Promise<PluginStateSnapshotManager.StateSnapshot> {
  188. await this.syncCurrent(options);
  189. return {
  190. timestamp: +new Date(),
  191. version: PLUGIN_VERSION,
  192. name: options && options.name,
  193. description: options && options.description,
  194. current: this.state.current,
  195. playback: {
  196. isPlaying: !!(options && options.playOnLoad),
  197. nextSnapshotDelayInMs: this.state.nextSnapshotDelayInMs
  198. },
  199. entries: this.state.entries.valueSeq().toArray()
  200. };
  201. }
  202. async serialize(options?: { type: 'json' | 'molj' | 'zip' | 'molx', params?: PluginState.SnapshotParams }) {
  203. const json = JSON.stringify(await this.getStateSnapshot({ params: options?.params }), null, 2);
  204. if (!options?.type || options.type === 'json' || options.type === 'molj') {
  205. return new Blob([json], { type: 'application/json;charset=utf-8' });
  206. } else {
  207. const state = new Uint8Array(utf8ByteCount(json));
  208. utf8Write(state, 0, json);
  209. const zipDataObj: { [k: string]: Uint8Array } = {
  210. 'state.json': state
  211. };
  212. const assets: [UUID, Asset][] = [];
  213. // TODO: there can be duplicate entries: check for this?
  214. for (const { asset, file } of this.plugin.managers.asset.assets) {
  215. assets.push([asset.id, asset]);
  216. zipDataObj[`assets/${asset.id}`] = new Uint8Array(await file.arrayBuffer());
  217. }
  218. if (assets.length > 0) {
  219. const index = JSON.stringify(assets, null, 2);
  220. const data = new Uint8Array(utf8ByteCount(index));
  221. utf8Write(data, 0, index);
  222. zipDataObj['assets.json'] = data;
  223. }
  224. const zipFile = await this.plugin.runTask(Zip(zipDataObj));
  225. return new Blob([zipFile], { type: 'application/zip' });
  226. }
  227. }
  228. async open(file: File) {
  229. try {
  230. const fn = file.name.toLowerCase();
  231. if (fn.endsWith('json') || fn.endsWith('molj')) {
  232. const data = await this.plugin.runTask(readFromFile(file, 'string'));
  233. const snapshot = JSON.parse(data);
  234. if (PluginStateSnapshotManager.isStateSnapshot(snapshot)) {
  235. await this.setStateSnapshot(snapshot);
  236. } else if (PluginStateSnapshotManager.isStateSnapshot(snapshot.data)) {
  237. await this.setStateSnapshot(snapshot.data);
  238. } else {
  239. await this.plugin.state.setSnapshot(snapshot);
  240. }
  241. } else {
  242. const data = await this.plugin.runTask(readFromFile(file, 'zip'));
  243. const assetData = Object.create(null);
  244. objectForEach(data, (v, k) => {
  245. if (k === 'state.json' || k === 'assets.json') return;
  246. const name = k.substring(k.indexOf('/') + 1);
  247. assetData[name] = v;
  248. });
  249. const stateFile = new File([data['state.json']], 'state.json');
  250. const stateData = await this.plugin.runTask(readFromFile(stateFile, 'string'));
  251. if (data['assets.json']) {
  252. const file = new File([data['assets.json']], 'assets.json');
  253. const json = JSON.parse(await this.plugin.runTask(readFromFile(file, 'string')));
  254. for (const [id, asset] of json) {
  255. this.plugin.managers.asset.set(asset, new File([assetData[id]], asset.name));
  256. }
  257. }
  258. const snapshot = JSON.parse(stateData);
  259. await this.setStateSnapshot(snapshot);
  260. }
  261. this.events.opened.next(void 0);
  262. } catch (e) {
  263. console.error(e);
  264. this.plugin.log.error('Error reading state');
  265. }
  266. }
  267. private timeoutHandle: any = void 0;
  268. private next = async () => {
  269. this.timeoutHandle = void 0;
  270. const next = this.getNextId(this.state.current, 1);
  271. if (!next || next === this.state.current) {
  272. this.stop();
  273. return;
  274. }
  275. const snapshot = this.setCurrent(next)!;
  276. await this.plugin.state.setSnapshot(snapshot);
  277. const delay = typeof snapshot.durationInMs !== 'undefined' ? snapshot.durationInMs : this.state.nextSnapshotDelayInMs;
  278. if (this.state.isPlaying) this.timeoutHandle = setTimeout(this.next, delay);
  279. };
  280. play(delayFirst: boolean = false) {
  281. this.updateState({ isPlaying: true });
  282. if (delayFirst) {
  283. const e = this.getEntry(this.state.current);
  284. if (!e) {
  285. this.next();
  286. return;
  287. }
  288. this.events.changed.next(void 0);
  289. const snapshot = e.snapshot;
  290. const delay = typeof snapshot.durationInMs !== 'undefined' ? snapshot.durationInMs : this.state.nextSnapshotDelayInMs;
  291. this.timeoutHandle = setTimeout(this.next, delay);
  292. } else {
  293. this.next();
  294. }
  295. }
  296. stop() {
  297. this.updateState({ isPlaying: false });
  298. if (typeof this.timeoutHandle !== 'undefined') clearTimeout(this.timeoutHandle);
  299. this.timeoutHandle = void 0;
  300. this.events.changed.next(void 0);
  301. }
  302. togglePlay() {
  303. if (this.state.isPlaying) {
  304. this.stop();
  305. this.plugin.managers.animation.stop();
  306. } else {
  307. this.play();
  308. }
  309. }
  310. dispose() {
  311. super.dispose();
  312. this.entryMap.clear();
  313. }
  314. constructor(private plugin: PluginContext) {
  315. super({
  316. current: void 0,
  317. entries: List(),
  318. isPlaying: false,
  319. nextSnapshotDelayInMs: PluginStateSnapshotManager.DefaultNextSnapshotDelayInMs
  320. });
  321. // TODO make nextSnapshotDelayInMs editable
  322. }
  323. }
  324. namespace PluginStateSnapshotManager {
  325. export interface EntryParams {
  326. key?: string,
  327. name?: string,
  328. description?: string,
  329. image?: Asset
  330. }
  331. export interface Entry extends EntryParams {
  332. timestamp: number,
  333. snapshot: PluginState.Snapshot
  334. }
  335. export function Entry(snapshot: PluginState.Snapshot, params: EntryParams): Entry {
  336. return { timestamp: +new Date(), snapshot, ...params };
  337. }
  338. export function isStateSnapshot(x?: any): x is StateSnapshot {
  339. const s = x as StateSnapshot;
  340. return !!s && !!s.timestamp && !!s.entries;
  341. }
  342. export interface StateSnapshot {
  343. timestamp: number,
  344. version: string,
  345. name?: string,
  346. description?: string,
  347. current: UUID | undefined,
  348. playback: {
  349. isPlaying: boolean,
  350. nextSnapshotDelayInMs: number,
  351. },
  352. entries: Entry[]
  353. }
  354. export async function getCanvasImageAsset(ctx: PluginContext, name: string): Promise<Asset | undefined> {
  355. if (!ctx.helpers.viewportScreenshot) return;
  356. const p = ctx.helpers.viewportScreenshot.getPreview(512);
  357. if (!p) return;
  358. const blob = await canvasToBlob(p.canvas, 'png');
  359. const file = new File([blob], name);
  360. const image: Asset = { kind: 'file', id: UUID.create22(), name };
  361. ctx.managers.asset.set(image, file);
  362. return image;
  363. }
  364. }