DriveRealtime.js 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819
  1. /**
  2. * Copyright (c) 2006-2016, JGraph Ltd
  3. * Copyright (c) 2006-2016, Gaudenz Alder
  4. */
  5. /**
  6. * Creates an object that synchronizes the graph model and given realtime model.
  7. * The session ID is used as a prefix in the model to produce unique IDs for new
  8. * cells.
  9. */
  10. function DriveRealtime(file, doc)
  11. {
  12. this.realtimeAutosaveDelay = this.defaultRealtimeAutosaveDelay;
  13. this.realtimeMaxAutosaveDelay = this.defaultRealtimeMaxAutosaveDelay;
  14. this.file = file;
  15. this.doc = doc;
  16. this.rtModel = this.doc.getModel();
  17. this.root = this.rtModel.getRoot();
  18. this.ui = file.getUi()
  19. this.graph = this.ui.editor.graph;
  20. this.model = this.graph.model;
  21. this.userId = this.ui.drive.user.id;
  22. this.ui.allowAnimation = false;
  23. this.codec = new mxCodec();
  24. this.disconnectListener = mxUtils.bind(this, function()
  25. {
  26. // LATER: How to reload realtime document without refreshing the page
  27. this.sessionExpiredError();
  28. });
  29. this.ui.drive.addListener('disconnected', this.disconnectListener);
  30. // Change of autosave triggers an immediate save to update thumbnail
  31. this.autosaveChangeListener = mxUtils.bind(this, function()
  32. {
  33. var prevValue = this.ui.drive.enableThumbnails;
  34. this.ui.drive.enableThumbnails = this.ui.editor.autosave;
  35. this.ui.editor.setStatus(mxResources.get('saving') + '...');
  36. this.file.save(true, mxUtils.bind(this, function()
  37. {
  38. this.ui.editor.setStatus(mxResources.get('allChangesSaved'));
  39. }));
  40. this.ui.drive.enableThumbnails = prevValue;
  41. });
  42. this.ui.editor.addListener('autosaveChanged', this.autosaveChangeListener);
  43. };
  44. /**
  45. * Specifies the key of the root element in the model. Default is root.
  46. */
  47. DriveRealtime.prototype.logLevel = 2;
  48. /**
  49. * True if a change event is fired for a remote change.
  50. */
  51. DriveRealtime.prototype.updateStatusInterval = 20000;
  52. /**
  53. * Specifies the key of the root element in the model. Default is root.
  54. */
  55. DriveRealtime.prototype.diagramsKey = 'diagrams';
  56. /**
  57. * Specifies the key of the root element in the model. Default is root.
  58. */
  59. DriveRealtime.prototype.diagrams = null;
  60. /**
  61. * Specifies the key of the root element in the model. Default is root.
  62. */
  63. DriveRealtime.prototype.rootKey = 'root';
  64. /**
  65. * Specifies the key of the root element in the model. Default is root.
  66. */
  67. DriveRealtime.prototype.diagramMap = null;
  68. /**
  69. * Specifies the key of the root element in the model. Default is root.
  70. */
  71. DriveRealtime.prototype.chatHistory = null;
  72. /**
  73. * True if a change event is fired for a remote change.
  74. */
  75. DriveRealtime.prototype.saving = false;
  76. /**
  77. * Sets the delay for autosave in milliseconds. Default is 5000.
  78. */
  79. DriveRealtime.prototype.defaultRealtimeAutosaveDelay = 5000;
  80. /**
  81. * Sets the delay for autosave in milliseconds. Default is 60000.
  82. */
  83. DriveRealtime.prototype.defaultRealtimeMaxAutosaveDelay = 60000;
  84. /**
  85. * Sets the delay for autosave in milliseconds. Default is 500.
  86. */
  87. DriveRealtime.prototype.realtimeHeartbeat = 30000;
  88. /**
  89. * True if a undoableEdit has been scheduled in <executeChange>.
  90. */
  91. DriveRealtime.prototype.ignoreChange = false;
  92. /**
  93. * True if a undoableEdit has been scheduled in <executeChange>.
  94. */
  95. DriveRealtime.prototype.ignorePageFormatChanged = false;
  96. /**
  97. * True if a undoableEdit has been scheduled in <executeChange>.
  98. */
  99. DriveRealtime.prototype.ignoreScaleChanged = false;
  100. /**
  101. * True if a undoableEdit has been scheduled in <executeChange>.
  102. */
  103. DriveRealtime.prototype.ignoreBackgroundColorChanged = false;
  104. /**
  105. * True if a undoableEdit has been scheduled in <executeChange>.
  106. */
  107. DriveRealtime.prototype.ignoreShadowVisibleChanged = false;
  108. /**
  109. * True if a undoableEdit has been scheduled in <executeChange>.
  110. */
  111. DriveRealtime.prototype.ignoreBackgroundImageChanged = false;
  112. /**
  113. * True if a undoableEdit has been scheduled in <executeChange>.
  114. */
  115. DriveRealtime.prototype.ignoreMathEnabledChanged = false;
  116. /**
  117. * Syncs initial state from collab model to graph model.
  118. */
  119. DriveRealtime.prototype.getDiagramMap = function()
  120. {
  121. return (this.ui.currentPage != null) ? this.ui.currentPage.mapping.diagramMap : this.diagramMap;
  122. };
  123. /**
  124. * Indirection for legacy support.
  125. */
  126. DriveRealtime.prototype.getCurrentPage = function()
  127. {
  128. return (this.page != null) ? this.page : this.ui.currentPage;
  129. };
  130. /**
  131. * Synchronizes the collaboration model and the graph model and installs
  132. * the required listeners to keep them in sync.
  133. */
  134. DriveRealtime.prototype.start = function()
  135. {
  136. if (urlParams['reset'] == '1')
  137. {
  138. this.root.clear();
  139. this.log('reset realtime');
  140. }
  141. var prefix = this.createPrefix();
  142. this.model.prefix = prefix + '-';
  143. this.ui.editor.resetGraph();
  144. // Creates diagrams list and default entry
  145. this.diagrams = this.root.get(this.diagramsKey);
  146. var diagramsCreated = false;
  147. if (this.diagrams == null)
  148. {
  149. this.diagrams = this.rtModel.createList();
  150. this.root.set(this.diagramsKey, this.diagrams);
  151. diagramsCreated = true;
  152. this.log('realtime model initialized');
  153. }
  154. // Specifies if the file should be saved immediately after setup
  155. var forceSave = false;
  156. if (this.file.getData() != '')
  157. {
  158. this.ui.fileNode = null;
  159. this.ui.pages = null;
  160. // Converts from XML to realtime
  161. this.ui.setFileData(this.file.getData());
  162. this.log('xml converted');
  163. // Logs conversion of old RT models (converted from XML backup)
  164. if (this.root.has('cells') && diagramsCreated)
  165. {
  166. try
  167. {
  168. var img = new Image();
  169. // Timestamp is added to bypass client-side cache
  170. img.src = 'https://log.draw.io/log?severity=CONFIG&msg=converted-oldrt&v=' +
  171. encodeURIComponent(EditorUi.VERSION) + '&ts=' + new Date().getTime();
  172. }
  173. catch (e)
  174. {
  175. // ignore
  176. }
  177. }
  178. if (this.ui.pages != null)
  179. {
  180. for (var i = 0; i < this.ui.pages.length; i++)
  181. {
  182. var page = this.ui.pages[i];
  183. var diagramMap = this.rtModel.createMap();
  184. this.diagrams.push(diagramMap);
  185. this.ui.updatePageRoot(page);
  186. page.mapping = new RealtimeMapping(this, diagramMap, page);
  187. if (this.file.isEditable())
  188. {
  189. // Read or create name for page
  190. if (page.getName() != '')
  191. {
  192. diagramMap.set('name', page.getName());
  193. }
  194. else if (!diagramMap.has('name'))
  195. {
  196. diagramMap.set('name', mxResources.get('pageWithNumber', [i + 1]));
  197. }
  198. }
  199. // Sync name and initialize
  200. page.setName(diagramMap.get('name') || mxResources.get('pageWithNumber', [i + 1]));
  201. page.mapping.init();
  202. }
  203. }
  204. else if (urlParams['pages'] == '0')
  205. {
  206. this.diagramMap = this.rtModel.createMap();
  207. this.diagrams.push(this.diagramMap);
  208. // Dummy node, should be XML node if used
  209. this.page = new DiagramPage(document.createElement('diagram'));
  210. this.page.mapping = new RealtimeMapping(this, this.diagramMap, this.page);
  211. this.diagramMap.set('name', mxResources.get('pageWithNumber', [1]));
  212. this.page.setName(this.diagramMap.get('name'));
  213. this.page.mapping.init();
  214. }
  215. else
  216. {
  217. this.ui.fileNode = mxUtils.createXmlDocument().createElement('mxfile');
  218. this.ui.pages = [];
  219. var diagramMap = this.rtModel.createMap();
  220. this.diagrams.push(diagramMap);
  221. var page = new DiagramPage(this.ui.fileNode.ownerDocument.createElement('diagram'));
  222. page.mapping = new RealtimeMapping(this, diagramMap, page);
  223. this.ui.currentPage = page;
  224. if (this.file.isEditable() && !page.mapping.diagramMap.has('name'))
  225. {
  226. page.mapping.diagramMap.set('name', mxResources.get('pageWithNumber', [1]));
  227. }
  228. page.setName(page.mapping.diagramMap.get('name') || mxResources.get('pageWithNumber', [1]));
  229. this.ui.pages.push(page);
  230. page.mapping.init();
  231. }
  232. forceSave = true;
  233. }
  234. else if (this.diagrams.length < 2 && urlParams['pages'] == '0')
  235. {
  236. this.ui.fileNode = null;
  237. this.ui.pages = null;
  238. if (this.diagrams.length == 0)
  239. {
  240. this.diagramMap = this.rtModel.createMap();
  241. this.diagrams.push(this.diagramMap);
  242. }
  243. else
  244. {
  245. this.diagramMap = this.diagrams.get(0);
  246. }
  247. // Dummy node, should be XML node if used
  248. this.page = new DiagramPage(document.createElement('diagram'));
  249. this.page.mapping = new RealtimeMapping(this, this.diagramMap, this.page);
  250. if (!this.diagramMap.has('name'))
  251. {
  252. this.diagramMap.set('name', mxResources.get('pageWithNumber', [1]));
  253. }
  254. this.page.setName(this.page.mapping.diagramMap.get('name'));
  255. // Avoids scroll offset when switching page
  256. this.page.mapping.init();
  257. this.ui.editor.fireEvent(new mxEventObject('resetGraphView'));
  258. }
  259. else
  260. {
  261. this.ui.fileNode = mxUtils.createXmlDocument().createElement('mxfile');
  262. this.ui.pages = [];
  263. if (this.diagrams.length == 0)
  264. {
  265. this.diagrams.push(this.rtModel.createMap());
  266. }
  267. var pageIndex = Math.max(0, Math.min(this.diagrams.length - 1, urlParams['page'] || 0));
  268. for (var i = 0; i < this.diagrams.length; i++)
  269. {
  270. var page = new DiagramPage(this.ui.fileNode.ownerDocument.createElement('diagram'));
  271. page.mapping = new RealtimeMapping(this, this.diagrams.get(i), page);
  272. if (this.file.isEditable() && !page.mapping.diagramMap.has('name'))
  273. {
  274. page.mapping.diagramMap.set('name', mxResources.get('pageWithNumber', [i + 1]));
  275. }
  276. page.setName(page.mapping.diagramMap.get('name') || mxResources.get('pageWithNumber', [i + 1]));
  277. this.ui.pages.push(page);
  278. }
  279. // Sets the current page
  280. this.ui.currentPage = this.ui.pages[Math.max(0, Math.min(this.ui.pages.length - 1, urlParams['page'] || 0))];;
  281. // Initializes graphs and mappings
  282. for (var i = 0; i < this.ui.pages.length; i++)
  283. {
  284. this.ui.pages[i].mapping.init();
  285. }
  286. }
  287. this.installReadOnlyListener();
  288. this.installUiChangeListeners();
  289. this.installGraphModelListener();
  290. this.installPageSelectListener();
  291. this.chatHistory = this.root.get('chatHistory');
  292. if (this.chatHistory == null)
  293. {
  294. this.initializeChat();
  295. }
  296. this.installSelectionModelListener();
  297. this.installCollaboratorListener();
  298. this.updateCollaborators();
  299. this.doc.addEventListener(gapi.drive.realtime.EventType.DOCUMENT_SAVE_STATE_CHANGED, mxUtils.bind(this, function(evt)
  300. {
  301. if (this.saving && !evt.isPending && !evt.isSaving && !forceSave)
  302. {
  303. // Checks if the mime type of the file has changed on the server-side
  304. // when the autosave is triggered to make sure we eventually check
  305. // the mime type even if the user continues to change the diagram
  306. // within the autosave interval, which will cancel the current thread.
  307. if (this.ui.isLegacyDriveDomain() && urlParams['ignoremime'] != '1')
  308. {
  309. this.ui.drive.verifyMimeType(this.file.getId());
  310. }
  311. // Adds tooltip to small spinner and saves a backup XML copy of the file
  312. if (this.file.isAutosave())
  313. {
  314. this.triggerAutosave();
  315. }
  316. else
  317. {
  318. this.ui.editor.setStatus(mxResources.get('allChangesSaved'));
  319. }
  320. this.saving = false;
  321. this.resetUpdateStatusThread();
  322. this.realtimeHeartbeat = DriveRealtime.prototype.realtimeHeartbeat;
  323. if (this.isAliveThread != null)
  324. {
  325. window.clearTimeout(this.isAliveThread);
  326. this.isAliveThread = null;
  327. }
  328. }
  329. if (this.file.isEditable())
  330. {
  331. var avail = 10485760 - this.rtModel.bytesUsed;
  332. if (avail > 0 && avail < 500000 && !this.sizeLimitWarningShown)
  333. {
  334. // Shows warning just once
  335. this.sizeLimitWarningShown = true;
  336. this.ui.showError(mxResources.get('warning'), mxResources.get('fileNearlyFullSeeFaq'),
  337. mxResources.get('close'), mxUtils.bind(this, function()
  338. {
  339. // Hides the dialog
  340. }), null, mxResources.get('show'), mxUtils.bind(this, function()
  341. {
  342. // Show FAQ entry
  343. window.open('https://desk.draw.io/support/solutions/articles/16000041695-what-does-the-error-message-file-nearly-full-please-see-faq-mean');
  344. })
  345. );
  346. }
  347. }
  348. }));
  349. var initialized = mxUtils.bind(this, function()
  350. {
  351. this.resetUpdateStatusThread();
  352. this.ui.resetScrollbars();
  353. this.updateStatus();
  354. forceSave = false;
  355. });
  356. // Updates backup and preview
  357. if (forceSave)
  358. {
  359. this.ui.editor.setStatus(mxResources.get('saving') + '...');
  360. this.file.save(false, initialized, initialized);
  361. }
  362. else
  363. {
  364. initialized();
  365. }
  366. // Implements separate undo history for each client
  367. if (this.previousUndoListener == null)
  368. {
  369. this.previousUndoListener = this.ui.editor.undoListener;
  370. this.ui.editor.undoListener = mxUtils.bind(this, function(sender, evt)
  371. {
  372. if (!this.ignoreChange)
  373. {
  374. this.previousUndoListener.apply(this, arguments);
  375. }
  376. });
  377. }
  378. };
  379. /**
  380. * Syncs initial state from graph model to collab model.
  381. */
  382. DriveRealtime.prototype.triggerAutosave = function()
  383. {
  384. this.ui.editor.setStatus(mxResources.get('updatingPreview'));
  385. this.file.autosave(this.realtimeAutosaveDelay, this.realtimeMaxAutosaveDelay, mxUtils.bind(this, function(resp)
  386. {
  387. // Updates autosave delay to take into account actual delay
  388. this.realtimeAutosaveDelay = this.defaultRealtimeAutosaveDelay + Math.min(10000, this.file.saveDelay);
  389. // Does not update status if another autosave was scheduled
  390. if (this.ui.getCurrentFile() == this.file && !this.saving)
  391. {
  392. this.ui.editor.setStatus(mxResources.get('allChangesSaved'));
  393. }
  394. }),
  395. mxUtils.bind(this, function(resp)
  396. {
  397. this.ui.editor.setStatus(mxResources.get('errorUpdatingPreview'));
  398. // Handles error where mime type cannot be overridden because it has been changed by another app and no
  399. // new revision was created. This happens eg. if draw.io pro overwrites the mime type and adds a new realtime
  400. // model to the file which is not visible for this app so we need to switch app to stay connected to RT.
  401. // This could be improved to let the RT viewers know that the realtime is no longer valid, but currently
  402. // the focus is on not losing data, so only clients that write to the file are being notified with this.
  403. if (this.ui.isLegacyDriveDomain() && urlParams['ignoremime'] != '1' && resp != null &&
  404. resp.error != null && (resp.error.code == 400 || resp.error.code == 403))
  405. {
  406. this.ui.drive.verifyMimeType(this.file.getId(), null, true);
  407. }
  408. }));
  409. };
  410. /**
  411. * Syncs initial state from graph model to collab model.
  412. */
  413. DriveRealtime.prototype.triggerAutosave = function()
  414. {
  415. this.ui.editor.setStatus(mxResources.get('updatingPreview'));
  416. this.file.autosave(this.realtimeAutosaveDelay, this.realtimeMaxAutosaveDelay, mxUtils.bind(this, function(resp)
  417. {
  418. // Updates autosave delay to take into account actual delay
  419. this.realtimeAutosaveDelay = this.defaultRealtimeAutosaveDelay + Math.min(10000, this.file.saveDelay);
  420. // Does not update status if another autosave was scheduled
  421. if (this.ui.getCurrentFile() == this.file && !this.saving)
  422. {
  423. this.ui.editor.setStatus(mxResources.get('allChangesSaved'));
  424. }
  425. }),
  426. mxUtils.bind(this, function(resp)
  427. {
  428. this.ui.editor.setStatus(mxResources.get('errorUpdatingPreview'));
  429. // Handles error where mime type cannot be overridden because it has been changed by another app and no
  430. // new revision was created. This happens eg. if draw.io pro overwrites the mime type and adds a new realtime
  431. // model to the file which is not visible for this app so we need to switch app to stay connected to RT.
  432. // This could be improved to let the RT viewers know that the realtime is no longer valid, but currently
  433. // the focus is on not losing data, so only clients that write to the file are being notified with this.
  434. if (this.ui.isLegacyDriveDomain() && urlParams['ignoremime'] != '1' && resp != null &&
  435. resp.error != null && (resp.error.code == 400 || resp.error.code == 403))
  436. {
  437. this.ui.drive.verifyMimeType(this.file.getId(), null, true);
  438. }
  439. }));
  440. };
  441. /**
  442. * Syncs initial state from graph model to collab model.
  443. */
  444. DriveRealtime.prototype.installReadOnlyListener = function()
  445. {
  446. // Handles change of read-only state
  447. this.doc.addEventListener(gapi.drive.realtime.EventType.ATTRIBUTE_CHANGED, mxUtils.bind(this, function(evt)
  448. {
  449. if (evt.attribute == 'is_read_only')
  450. {
  451. this.file.descriptorChanged();
  452. if (!this.file.isEditable())
  453. {
  454. this.ui.editor.graph.reset();
  455. this.ui.editor.setStatus(mxResources.get('readOnly'));
  456. }
  457. else
  458. {
  459. this.ui.editor.setStatus('');
  460. }
  461. }
  462. }));
  463. };
  464. /**
  465. * Syncs initial state from graph model to collab model.
  466. */
  467. DriveRealtime.prototype.installUiChangeListeners = function()
  468. {
  469. this.pageFormatListener = mxUtils.bind(this, function(sender, evt)
  470. {
  471. if (!this.ignorePageFormatChanged)
  472. {
  473. try
  474. {
  475. this.setFileModified();
  476. this.getDiagramMap().set('pageFormat', this.graph.pageFormat.width + ',' + this.graph.pageFormat.height);
  477. }
  478. catch (e)
  479. {
  480. this.ui.handleError(e);
  481. }
  482. }
  483. });
  484. this.ui.addListener('pageFormatChanged', this.pageFormatListener);
  485. this.pageScaleListener = mxUtils.bind(this, function(sender, evt)
  486. {
  487. if (!this.ignorePageScaleChanged)
  488. {
  489. try
  490. {
  491. this.setFileModified();
  492. this.getDiagramMap().set('pageScale', this.graph.pageScale);
  493. }
  494. catch (e)
  495. {
  496. this.ui.handleError(e);
  497. }
  498. }
  499. });
  500. this.ui.addListener('pageScaleChanged', this.pageScaleListener);
  501. this.backgroundColorListener = mxUtils.bind(this, function(sender, evt)
  502. {
  503. if (!this.ignoreBackgroundColorChanged)
  504. {
  505. try
  506. {
  507. this.setFileModified();
  508. this.getDiagramMap().set('backgroundColor', (this.graph.background != null) ? this.graph.background : '');
  509. }
  510. catch (e)
  511. {
  512. this.ui.handleError(e);
  513. }
  514. }
  515. });
  516. this.ui.addListener('backgroundColorChanged', this.backgroundColorListener);
  517. this.shadowVisibleListener = mxUtils.bind(this, function(sender, evt)
  518. {
  519. if (!this.ignoreShadowVisibleChanged)
  520. {
  521. // Special case: This listener is called after switching page
  522. // so we check if the value has actually changed
  523. if (this.getDiagramMap().get('shadowVisible') != ((this.graph.shadowVisible) ? '1' : '0'))
  524. {
  525. try
  526. {
  527. this.setFileModified();
  528. this.getDiagramMap().set('shadowVisible', (this.graph.shadowVisible) ? '1' : '0');
  529. }
  530. catch (e)
  531. {
  532. this.ui.handleError(e);
  533. }
  534. }
  535. }
  536. });
  537. this.graph.addListener('shadowVisibleChanged', this.shadowVisibleListener);
  538. this.foldingEnabledListener = mxUtils.bind(this, function(sender, evt)
  539. {
  540. if (!this.ignoreFoldingEnabledChanged)
  541. {
  542. try
  543. {
  544. this.setFileModified();
  545. this.getDiagramMap().set('foldingEnabled', (this.graph.foldingEnabled) ? '1' : '0');
  546. }
  547. catch (e)
  548. {
  549. this.ui.handleError(e);
  550. }
  551. }
  552. });
  553. this.ui.addListener('foldingEnabledChanged', this.foldingEnabledListener);
  554. this.graph.addListener('shadowVisibleChanged', this.shadowVisibleListener);
  555. this.pageVisibleListener = mxUtils.bind(this, function(sender, evt)
  556. {
  557. if (!this.ignorePageVisibleChanged)
  558. {
  559. try
  560. {
  561. this.setFileModified();
  562. this.getDiagramMap().set('pageVisible', (this.graph.pageVisible) ? '1' : '0');
  563. }
  564. catch (e)
  565. {
  566. this.ui.handleError(e);
  567. }
  568. }
  569. });
  570. this.ui.addListener('pageViewChanged', this.pageVisibleListener);
  571. this.backgroundImageListener = mxUtils.bind(this, function(sender, evt)
  572. {
  573. if (!this.ignoreBackgroundImageChanged)
  574. {
  575. try
  576. {
  577. this.setFileModified();
  578. this.getDiagramMap().set('backgroundImage', (this.graph.backgroundImage != null) ? JSON.stringify(this.graph.backgroundImage) : '');
  579. }
  580. catch (e)
  581. {
  582. this.ui.handleError(e);
  583. }
  584. }
  585. });
  586. this.ui.addListener('backgroundImageChanged', this.backgroundImageListener);
  587. this.mathEnabledListener = mxUtils.bind(this, function(sender, evt)
  588. {
  589. if (!this.ignoreMathEnabledChanged)
  590. {
  591. try
  592. {
  593. this.setFileModified();
  594. this.getDiagramMap().set('mathEnabled', (this.graph.mathEnabled) ? '1' : '0');
  595. }
  596. catch (e)
  597. {
  598. this.ui.handleError(e);
  599. }
  600. }
  601. });
  602. this.ui.addListener('mathEnabledChanged', this.mathEnabledListener);
  603. };
  604. /**
  605. * Returns true if the given event is local.
  606. */
  607. DriveRealtime.prototype.isLocalEvent = function(evt)
  608. {
  609. return evt.isLocal;
  610. };
  611. /**
  612. * Syncs initial state from graph model to collab model.
  613. */
  614. DriveRealtime.prototype.resetUpdateStatusThread = function()
  615. {
  616. if (this.updateStatusThread != null)
  617. {
  618. window.clearInterval(this.updateStatusThread);
  619. }
  620. this.updateStatusThread = window.setInterval(mxUtils.bind(this, function()
  621. {
  622. this.ui.drive.checkToken(mxUtils.bind(this, function()
  623. {
  624. this.updateStatus();
  625. }));
  626. }), this.updateStatusInterval);
  627. };
  628. /**
  629. * Translates this point by the given vector.
  630. *
  631. * @param {number} dx X-coordinate of the translation.
  632. * @param {number} dy Y-coordinate of the translation.
  633. */
  634. DriveRealtime.prototype.timeSince = function(date)
  635. {
  636. var seconds = Math.floor((new Date() - date) / 1000);
  637. var interval = Math.floor(seconds / 31536000);
  638. if (interval > 1)
  639. {
  640. return interval + ' ' + mxResources.get('years');
  641. }
  642. interval = Math.floor(seconds / 2592000);
  643. if (interval > 1)
  644. {
  645. return interval + ' ' + mxResources.get('months');
  646. }
  647. interval = Math.floor(seconds / 86400);
  648. if (interval > 1)
  649. {
  650. return interval + ' ' + mxResources.get('days');
  651. }
  652. interval = Math.floor(seconds / 3600);
  653. if (interval > 1)
  654. {
  655. return interval + ' ' + mxResources.get('hours');
  656. }
  657. interval = Math.floor(seconds / 60);
  658. if (interval > 1)
  659. {
  660. return interval + ' ' + mxResources.get('minutes');
  661. }
  662. if (interval == 1)
  663. {
  664. return interval + ' ' + mxResources.get('minute');
  665. }
  666. return null;
  667. };
  668. /**
  669. * Adds the listener for added and removed cells in the collab model and maps
  670. * them to the graph model.
  671. */
  672. DriveRealtime.prototype.updateStatus = function()
  673. {
  674. if (!this.saving)
  675. {
  676. // LATER: Check if realtime model contains last modified timestamp
  677. var mod = this.root.get('modifiedDate');
  678. if (mod != '')
  679. {
  680. // LATER: Write out modified date for more than 2 weeks ago
  681. var str = this.ui.timeSince(new Date(mod));
  682. if (str == null)
  683. {
  684. str = mxResources.get('lessThanAMinute');
  685. }
  686. this.ui.editor.setStatus(mxResources.get('lastChange', [str]) +
  687. (this.file.isEditable() ? '' : ' (' + mxResources.get('readOnly') + ')'));
  688. }
  689. }
  690. };
  691. /**
  692. * Currently the link back from map to page requires a loop.
  693. */
  694. DriveRealtime.prototype.getPageIndexForMap = function(map)
  695. {
  696. for (var i = 0; i < this.ui.pages.length; i++)
  697. {
  698. if (this.ui.pages[i].mapping.diagramMap == map)
  699. {
  700. return i;
  701. }
  702. }
  703. return null;
  704. };
  705. /**
  706. * Adds the listener for changes on the graph model and maps them to the collab
  707. * model as a single transaction.
  708. */
  709. DriveRealtime.prototype.installPageSelectListener = function()
  710. {
  711. // Adds a graph model listener to update the view
  712. this.pageChangeListener = mxUtils.bind(this, function(sender, evt)
  713. {
  714. var page = evt.getProperty('change').relatedPage;
  715. if (page.mapping == null)
  716. {
  717. page.mapping = new RealtimeMapping(this, this.rtModel.createMap(), page);
  718. page.mapping.init();
  719. if (this.file.isEditable())
  720. {
  721. page.mapping.diagramMap.set('name', page.getName());
  722. }
  723. }
  724. });
  725. this.ui.editor.addListener('beforePageChange', this.pageChangeListener);
  726. // Adds a graph model listener to update the view
  727. this.viewStateListener = mxUtils.bind(this, function(sender, evt)
  728. {
  729. var page = this.getCurrentPage();
  730. // Applies view state from realtime model without firing events
  731. if (page.viewState == null)
  732. {
  733. // Activates from realtime without calling event listeners
  734. page.mapping.activate(true);
  735. }
  736. });
  737. this.ui.editor.addListener('setViewState', this.viewStateListener);
  738. this.diagrams.addEventListener(gapi.drive.realtime.EventType.VALUES_ADDED, mxUtils.bind(this, function(evt)
  739. {
  740. if (!this.isLocalEvent(evt))
  741. {
  742. if (evt.movedFromList == null)
  743. {
  744. this.ignoreChange = true;
  745. // Switches to pages datastructure
  746. if (this.ui.pages == null)
  747. {
  748. this.ui.fileNode = mxUtils.createXmlDocument().createElement('mxfile');
  749. this.ui.pages = [];
  750. if (this.page != null)
  751. {
  752. this.ui.currentPage = this.page;
  753. this.ui.pages.push(this.ui.currentPage);
  754. this.diagramMap = null;
  755. this.page = null;
  756. }
  757. }
  758. for (var i = 0; i < evt.values.length; i++)
  759. {
  760. var page = new DiagramPage(document.createElement('diagram'));
  761. page.mapping = new RealtimeMapping(this, evt.values[i], page);
  762. page.setName(page.mapping.diagramMap.get('name') || mxResources.get('pageWithNumber',
  763. [this.ui.pages.length + 1]));
  764. this.ui.pages.splice(evt.index + i, 0, page);
  765. page.mapping.init();
  766. }
  767. // Shows tab container if pages are added with pages disabled
  768. if (this.ui.pages != null && this.ui.pages.length > 1 &&
  769. this.ui.tabContainer != null &&
  770. this.ui.tabContainer.style.height == '0px')
  771. {
  772. this.ui.editor.graph.view.validateBackground();
  773. }
  774. this.ui.updateTabContainer();
  775. this.ignoreChange = false;
  776. }
  777. else if (evt.movedFromList == this.diagrams && evt.movedFromIndex != null)
  778. {
  779. this.ignoreChange = true;
  780. for (var i = 0; i < evt.values.length; i++)
  781. {
  782. var index = this.getPageIndexForMap(evt.values[i]);
  783. if (index != null)
  784. {
  785. this.ui.movePage(index + i, evt.index + i);
  786. }
  787. }
  788. this.ignoreChange = false;
  789. this.ui.updateTabContainer();
  790. }
  791. }
  792. }));
  793. this.diagrams.addEventListener(gapi.drive.realtime.EventType.VALUES_REMOVED, mxUtils.bind(this, function(evt)
  794. {
  795. if (!this.isLocalEvent(evt))
  796. {
  797. if (evt.movedToList == null)
  798. {
  799. this.ignoreChange = true;
  800. for (var i = 0; i < evt.values.length; i++)
  801. {
  802. var index = this.getPageIndexForMap(evt.values[i]);
  803. if (index != null)
  804. {
  805. var page = this.ui.pages[index];
  806. if (page != null)
  807. {
  808. this.ui.removePage(page);
  809. page.mapping.destroy();
  810. }
  811. }
  812. }
  813. this.ignoreChange = false;
  814. }
  815. }
  816. }));
  817. };
  818. /**
  819. * Returns a string representation of the given ops.
  820. */
  821. DriveRealtime.prototype.processChange = function(change)
  822. {
  823. //console.log('processChange: ' + this.dump(change));
  824. if (change instanceof RenamePage)
  825. {
  826. change.page.mapping.diagramMap.set('name', change.page.getName());
  827. }
  828. else if (change instanceof ChangePage)
  829. {
  830. if (change.previousIndex == null)
  831. {
  832. this.diagrams.removeValue(change.relatedPage.mapping.diagramMap);
  833. }
  834. else
  835. {
  836. this.diagrams.insert(change.previousIndex, change.relatedPage.mapping.diagramMap);
  837. }
  838. }
  839. else if (change instanceof MovePage)
  840. {
  841. this.diagrams.move(change.newIndex, change.oldIndex + ((change.newIndex < change.oldIndex) ? 1 : 0));
  842. }
  843. else if (change instanceof mxRootChange)
  844. {
  845. // Only process the root change that sets the current root
  846. // ie. ignore previous root changes
  847. if (change.root == this.model.root)
  848. {
  849. this.getCurrentPage().mapping.initRealtime();
  850. }
  851. }
  852. else if (change instanceof mxChildChange)
  853. {
  854. if (change.parent != change.previous || change.index != change.previousIndex)
  855. {
  856. var childRtCell = change.child.rtCell;
  857. if (childRtCell == null)
  858. {
  859. childRtCell = this.getCurrentPage().mapping.createRealtimeCell(change.child);
  860. this.getCurrentPage().mapping.saveRealtimeCell(childRtCell.cell);
  861. }
  862. var parentRtCell = (change.parent != null) ? change.parent.rtCell : null;
  863. if (change.previous != null)
  864. {
  865. var previousParentRtCell = change.previous.rtCell;
  866. if (previousParentRtCell != null)
  867. {
  868. previousParentRtCell.children.removeValue(childRtCell);
  869. }
  870. }
  871. if (parentRtCell != null)
  872. {
  873. parentRtCell.children.insert(Math.min(parentRtCell.children.length, change.index), childRtCell);
  874. }
  875. childRtCell.parent = parentRtCell;
  876. }
  877. }
  878. else if (change.cell != null && change.cell.id != null)
  879. {
  880. var rtCell = change.cell.rtCell;
  881. if (rtCell != null)
  882. {
  883. if (change instanceof mxTerminalChange)
  884. {
  885. var term = (change.terminal != null) ? change.terminal.rtCell : null;
  886. rtCell[(change.source) ? 'source' : 'target'] = term;
  887. }
  888. else if (change instanceof mxGeometryChange)
  889. {
  890. rtCell.geometry = (change.geometry != null) ? mxUtils.getXml(this.codec.encode(change.geometry)) : null;
  891. }
  892. else if (change instanceof mxStyleChange)
  893. {
  894. rtCell.style = change.style;
  895. }
  896. else if (change instanceof mxValueChange)
  897. {
  898. if (mxUtils.isNode(change.value))
  899. {
  900. rtCell.value = null;
  901. rtCell.xmlValue = mxUtils.getXml(change.value);
  902. }
  903. else
  904. {
  905. rtCell.xmlValue = null;
  906. rtCell.value = change.value;
  907. }
  908. }
  909. else if (change instanceof mxCollapseChange)
  910. {
  911. rtCell.collapsed = (change.collapsed) ? '1' : '0';
  912. }
  913. else if (change instanceof mxVisibleChange)
  914. {
  915. rtCell.visible = (change.visible) ? '1' : '0';
  916. }
  917. }
  918. }
  919. };
  920. /**
  921. * Adds the listener for changes on the graph model and maps them to the collab
  922. * model as a single transaction.
  923. */
  924. DriveRealtime.prototype.setFileModified = function()
  925. {
  926. this.root.set('modifiedDate', new Date().getTime());
  927. this.file.setModified(true);
  928. if (!this.saving)
  929. {
  930. this.ui.editor.setStatus(mxResources.get('saving') + '...');
  931. this.saving = true;
  932. }
  933. };
  934. /**
  935. * Adds the listener for changes on the graph model and maps them to the collab
  936. * model as a single transaction.
  937. */
  938. DriveRealtime.prototype.installGraphModelListener = function()
  939. {
  940. // Adds a graph model listener to update the view
  941. this.graphModelChangeListener = mxUtils.bind(this, function(sender, evt)
  942. {
  943. var edit = evt.getProperty('edit');
  944. if (!this.ignoreChange && this.file.isEditable() && !edit.ignoreEdit)
  945. {
  946. //console.log('startEdit');
  947. // TODO: Queuing for async token refresh and too many updates
  948. this.ui.drive.checkToken(mxUtils.bind(this, function()
  949. {
  950. this.rtModel.beginCompoundOperation();
  951. this.setFileModified();
  952. try
  953. {
  954. var changes = edit.changes;
  955. if (edit.undone)
  956. {
  957. for (var i = changes.length - 1; i >= 0; i--)
  958. {
  959. this.processChange(changes[i]);
  960. }
  961. }
  962. else
  963. {
  964. for (var i = 0; i < changes.length; i++)
  965. {
  966. this.processChange(changes[i]);
  967. }
  968. }
  969. this.rtModel.endCompoundOperation();
  970. }
  971. catch (e)
  972. {
  973. this.rtModel.endCompoundOperation();
  974. this.ui.handleError(e);
  975. }
  976. if (this.isAliveThread == null)
  977. {
  978. this.isAliveThread = window.setTimeout(mxUtils.bind(this, function()
  979. {
  980. this.ui.editor.setStatus('<div class="geStatusAlert geBlink" style="cursor:pointer;">' +
  981. mxResources.get('noResponse') + '</div>');
  982. this.isAliveThread = window.setTimeout(mxUtils.bind(this, function()
  983. {
  984. this.isAliveThread = null;
  985. this.timeoutError();
  986. }), this.realtimeHeartbeat);
  987. }), this.realtimeHeartbeat);
  988. }
  989. }));
  990. //console.log('endEdit');
  991. }
  992. });
  993. this.model.addListener(mxEvent.CHANGE, this.graphModelChangeListener);
  994. };
  995. /**
  996. *
  997. */
  998. DriveRealtime.prototype.sessionExpiredError = function()
  999. {
  1000. // LATER: How to reload realtime document without refreshing the page
  1001. this.ui.showError(mxResources.get('error'), mxResources.get('sessionExpired'), mxResources.get('refresh'), mxUtils.bind(this, function()
  1002. {
  1003. this.ui.spinner.spin(document.body, mxResources.get('connecting'));
  1004. this.file.setModified(false);
  1005. window.location.reload();
  1006. }));
  1007. };
  1008. /**
  1009. *
  1010. */
  1011. DriveRealtime.prototype.timeoutError = function()
  1012. {
  1013. // LATER: How to reload realtime document without refreshing the page
  1014. this.ui.showError(mxResources.get('timeout'), mxResources.get('realtimeTimeout'), mxResources.get('discardChangesAndReconnect'), mxUtils.bind(this, function()
  1015. {
  1016. this.ui.spinner.spin(document.body, mxResources.get('connecting'));
  1017. this.file.setModified(false);
  1018. window.location.reload();
  1019. }), null, mxResources.get('ignore'), mxUtils.bind(this, function()
  1020. {
  1021. this.ui.editor.setStatus('<div class="geStatusAlert geBlink" style="cursor:pointer;">' +
  1022. mxResources.get('disconnected') + '</div>');
  1023. this.realtimeHeartbeat *= 2;
  1024. }));
  1025. };
  1026. /**
  1027. *
  1028. */
  1029. DriveRealtime.prototype.initializeChat = function()
  1030. {
  1031. this.chatHistory = this.rtModel.createList();
  1032. this.root.set('chatHistory', this.chatHistory);
  1033. //this.log('Chat history created');
  1034. };
  1035. /**
  1036. * Adds a listener to the graph selection model and writes changes
  1037. * in the RT selection map
  1038. */
  1039. DriveRealtime.prototype.installSelectionModelListener = function()
  1040. {
  1041. this.graphSelectionModelChangeListener = mxUtils.bind(this, function(sender, evt)
  1042. {
  1043. this.ui.drive.checkToken(mxUtils.bind(this, function()
  1044. {
  1045. if (this.file.isEditable() && !this.graph.isSelectionEmpty())
  1046. {
  1047. try
  1048. {
  1049. // LATER: Clear value if selection is empty. This is currently
  1050. // disabled to avoid using up the quota in this case but the
  1051. // better solution is to mark this "transient" (ie no history).
  1052. var cells = this.graph.getSelectionCells();
  1053. var selectedCellIds = '';
  1054. for (var i = 0; i < cells.length; i++)
  1055. {
  1056. selectedCellIds += cells[i].id + ',';
  1057. }
  1058. this.getCurrentPage().mapping.selectionMap.set(this.userId, selectedCellIds);
  1059. }
  1060. catch (e)
  1061. {
  1062. this.ui.handleError(e);
  1063. }
  1064. }
  1065. }));
  1066. });
  1067. this.graph.getSelectionModel().addListener(mxEvent.CHANGE, this.graphSelectionModelChangeListener);
  1068. };
  1069. /**
  1070. * Connects the collaborator event listeners to the draw function.
  1071. */
  1072. DriveRealtime.prototype.installCollaboratorListener = function()
  1073. {
  1074. this.doc.addEventListener(gapi.drive.realtime.EventType.COLLABORATOR_JOINED, mxUtils.bind(this, this.updateCollaborators));
  1075. this.doc.addEventListener(gapi.drive.realtime.EventType.COLLABORATOR_LEFT, mxUtils.bind(this, this.updateCollaborators));
  1076. };
  1077. /**
  1078. * Draw function for the collaborator list.
  1079. */
  1080. DriveRealtime.prototype.updateCollaborators = function()
  1081. {
  1082. var n = this.doc.getCollaborators().length - 1;
  1083. if (this.collaboratorsElement == null)
  1084. {
  1085. this.collaboratorsElement = document.createElement('a');
  1086. this.collaboratorsElement.setAttribute('href', 'javascript:void(0);');
  1087. this.collaboratorsElement.className = 'geItem';
  1088. this.collaboratorsElement.style.position = 'absolute';
  1089. this.collaboratorsElement.style.display = 'inline-block';
  1090. this.collaboratorsElement.style.verticalAlign = 'bottom';
  1091. this.collaboratorsElement.style.color = '#666';
  1092. this.collaboratorsElement.style.top = '10px';
  1093. this.collaboratorsElement.style.right = (uiTheme == 'atlas') ? '42px' : '68px';
  1094. this.collaboratorsElement.style.padding = '2px';
  1095. this.collaboratorsElement.style.fontSize = '8pt';
  1096. this.collaboratorsElement.style.verticalAlign = 'middle';
  1097. this.collaboratorsElement.style.backgroundPosition = '100% 60%';
  1098. this.collaboratorsElement.style.backgroundRepeat = 'no-repeat';
  1099. this.ui.toolbarContainer.appendChild(this.collaboratorsElement);
  1100. mxEvent.addListener(this.collaboratorsElement, 'click', mxUtils.bind(this, function(evt)
  1101. {
  1102. if (this.collabPanel == null)
  1103. {
  1104. var div = document.createElement('div');
  1105. div.className = 'geDialog';
  1106. div.style.position = 'absolute';
  1107. div.style.maxHeight = '400px';
  1108. div.style.maxWidth = '300px';
  1109. div.style.right = '38px';
  1110. div.style.padding = '14px';
  1111. div.style.paddingRight = '30px';
  1112. this.collabPanel = div;
  1113. }
  1114. if (this.collabPanel.parentNode == null)
  1115. {
  1116. this.collabPanel.style.top = (this.collaboratorsElement.clientTop + this.collaboratorsElement.clientHeight + this.ui.menubarHeight + 8) + 'px';
  1117. document.body.appendChild(this.collabPanel);
  1118. this.collabPanel.innerHTML = '';
  1119. var img = document.createElement('img');
  1120. img.setAttribute('src', Dialog.prototype.closeImage);
  1121. img.setAttribute('title', mxResources.get('close'));
  1122. img.className = 'geDialogClose';
  1123. img.style.top = '8px';
  1124. img.style.right = '8px';
  1125. mxEvent.addListener(img, 'click', mxUtils.bind(this, function()
  1126. {
  1127. if (this.collabPanel.parentNode != null)
  1128. {
  1129. this.collabPanel.parentNode.removeChild(this.collabPanel);
  1130. }
  1131. }));
  1132. this.collabPanel.appendChild(img);
  1133. if (this.doc.getCollaborators().length > 1)
  1134. {
  1135. for (var i = 0; i < this.doc.getCollaborators().length; i = i + 1)
  1136. {
  1137. var collaborator = this.doc.getCollaborators()[i];
  1138. if (!collaborator.isMe)
  1139. {
  1140. var elt = document.createElement('div');
  1141. elt.style.cursor = 'pointer';
  1142. elt.style.whiteSpace = 'nowrap';
  1143. var img = document.createElement('img');
  1144. img.src = collaborator.photoUrl;
  1145. img.style.backgroundColor = collaborator.color;
  1146. img.style.paddingBottom = '8px';
  1147. img.style.marginRight = '10px';
  1148. img.style.marginTop = '2px';
  1149. img.style.marginBottom = '2px';
  1150. img.style.height = '25px';
  1151. img.style.width = '25px';
  1152. img.setAttribute('align', 'absmiddle');
  1153. elt.appendChild(img);
  1154. mxUtils.write(elt, collaborator.displayName);
  1155. this.collabPanel.appendChild(elt);
  1156. // Click on collaborator shows selection cells, scrolls to first cell
  1157. mxEvent.addListener(elt, 'click', mxUtils.bind(this, function()
  1158. {
  1159. var value = this.getCurrentPage().mapping.selectionMap.get(collaborator.userId);
  1160. if (value != null)
  1161. {
  1162. var cellIds = value.split(',');
  1163. for (var i = 0; i < cellIds.length; i++)
  1164. {
  1165. var cell = this.model.getCell(cellIds[i]);
  1166. this.highlight(cell, collaborator.sessionId);
  1167. if (cell != null && i == 0)
  1168. {
  1169. this.graph.scrollCellToVisible(cell);
  1170. }
  1171. }
  1172. }
  1173. }));
  1174. }
  1175. }
  1176. }
  1177. else
  1178. {
  1179. mxUtils.write(this.collabPanel, mxResources.get('noOtherViewers'));
  1180. }
  1181. }
  1182. else if (this.collabPanel.parentNode != null)
  1183. {
  1184. this.collabPanel.parentNode.removeChild(this.collabPanel);
  1185. }
  1186. mxEvent.consume(evt);
  1187. }));
  1188. mxEvent.addListener(document.body, 'click', mxUtils.bind(this, function(evt)
  1189. {
  1190. if (!mxEvent.isConsumed(evt) && this.collabPanel != null && this.collabPanel.parentNode != null)
  1191. {
  1192. this.collabPanel.parentNode.removeChild(this.collabPanel);
  1193. }
  1194. }));
  1195. }
  1196. var viewers = mxResources.get((n == 0) ? 'noOtherViewers' : ((n == 1) ? 'otherViewer' : 'otherViewers'));
  1197. if (n > 0)
  1198. {
  1199. viewers = n + ' ' + viewers;
  1200. this.collaboratorsElement.style.paddingRight = '16px';
  1201. this.collaboratorsElement.style.backgroundImage = 'url(' + IMAGE_PATH + '/expanded.gif)';
  1202. this.collaboratorsElement.style.cursor = 'pointer';
  1203. }
  1204. else
  1205. {
  1206. this.collaboratorsElement.style.paddingRight = '0px';
  1207. this.collaboratorsElement.style.backgroundImage = '';
  1208. this.collaboratorsElement.style.cursor = 'default';
  1209. }
  1210. var html = '<div title="' + viewers + '" style="display:inline-block;white-space:nowrap;max-width:110px;overflow:hidden;text-overflow:ellipsis;">' + viewers + '</div>';
  1211. var names = new Object();
  1212. var count = 0;
  1213. for (var i = 0; i < this.doc.getCollaborators().length && count < 6; i = i + 1)
  1214. {
  1215. var c = this.doc.getCollaborators()[i];
  1216. if (!c.isMe && names[c.color] == null)
  1217. {
  1218. names[c.color] = c.displayName;
  1219. count++;
  1220. }
  1221. }
  1222. for (var color in names)
  1223. {
  1224. html += '<div title="' + mxUtils.htmlEntities(names[color]) + '" style="display:inline-block;background-color:' + color + ';width:13px;height:13px;margin-left:4px;margin-top:-1px;"></div>';
  1225. }
  1226. this.collaboratorsElement.innerHTML = html;
  1227. };
  1228. /**
  1229. * Creates and returns a prefix for cell IDs.
  1230. */
  1231. DriveRealtime.prototype.createPrefix = function()
  1232. {
  1233. var collabs = this.doc.getCollaborators();
  1234. for (var i = 0; i < collabs.length; i++)
  1235. {
  1236. if (collabs[i]['isMe'])
  1237. {
  1238. return collabs[i]['sessionId'];
  1239. }
  1240. }
  1241. return '';
  1242. };
  1243. DriveRealtime.prototype.highlight = function(cell, sessionId)
  1244. {
  1245. var state = this.graph.view.getState(cell);
  1246. if (state != null)
  1247. {
  1248. var color = 'red'; // session not found
  1249. for (var i = 0; i < this.doc.getCollaborators().length; i = i + 1)
  1250. {
  1251. var collaborator = this.doc.getCollaborators()[i];
  1252. if (collaborator.sessionId == sessionId)
  1253. {
  1254. color = collaborator.color;
  1255. break;
  1256. }
  1257. }
  1258. var sw = Math.max(5, mxUtils.getValue(state.style, mxConstants.STYLE_STROKEWIDTH, 1) + 4);
  1259. var hl = new mxCellHighlight(this.graph, color, sw, false);
  1260. hl.highlight(state);
  1261. // Fades out the highlight after a delay
  1262. window.setTimeout(function()
  1263. {
  1264. if (hl.shape != null)
  1265. {
  1266. mxUtils.setPrefixedStyle(hl.shape.node.style, 'transition', 'all 1200ms ease-in-out');
  1267. hl.shape.node.style.opacity = 0;
  1268. }
  1269. window.setTimeout(function()
  1270. {
  1271. hl.destroy();
  1272. }, 2000);
  1273. }, 1000);
  1274. }
  1275. };
  1276. /**
  1277. * Writes out a string representing the current state of the document.
  1278. */
  1279. DriveRealtime.prototype.dumpRoot = function()
  1280. {
  1281. return this.dump(this.root);
  1282. };
  1283. /**
  1284. * Creates a dump of the given map.
  1285. */
  1286. DriveRealtime.prototype.dump = function(obj)
  1287. {
  1288. var result = '';
  1289. if (obj != null)
  1290. {
  1291. if (obj.constructor == mxCell)
  1292. {
  1293. return obj.id;
  1294. }
  1295. else if (obj.constructor == mxRootChange)
  1296. {
  1297. result += 'mxRootChange[root=' + this.dump(obj.root) + ']';
  1298. }
  1299. else if (obj.constructor == mxChildChange)
  1300. {
  1301. result += 'mxChildChange[parent=' + this.dump(obj.parent) +
  1302. ', child=' + this.dump(obj.child.id) +
  1303. ', index=' + obj.index + ']';
  1304. }
  1305. else if (obj.constructor == mxTerminalChange)
  1306. {
  1307. result += 'mxTerminalChange[cell=' + this.dump(obj.cell) +
  1308. ', terminal=' + this.dump(obj.terminal) +
  1309. ', source=' + obj.source + ']';
  1310. }
  1311. else if (obj.constructor == mxValueChange)
  1312. {
  1313. result += 'mxValueChange[cell=' + this.dump(obj.cell) + ', value=' + obj.value + ']';
  1314. }
  1315. else if (obj.constructor == mxGeometryChange)
  1316. {
  1317. result += 'mxGeometryChange[cell=' + this.dump(obj.cell) + ', geometry=' +
  1318. ((obj.cell.geometry != null) ? mxUtils.getXml(this.codec.encode(obj.cell.geometry)) : '[null]') + ']';
  1319. }
  1320. else if (obj.constructor == mxStyleChange)
  1321. {
  1322. result += 'mxStyleChange[cell=' + this.dump(obj.cell) + ', style=' + obj.style + ']';
  1323. }
  1324. else if (obj.constructor == mxVisibleChange)
  1325. {
  1326. result += 'mxVisibleChange[cell=' + this.dump(obj.cell) + ', visible=' + obj.visible + ']';
  1327. }
  1328. else if (obj.constructor == mxCollapseChange)
  1329. {
  1330. result += 'mxCollapseChange[cell=' + this.dump(obj.cell) + ', collapsed=' + obj.collapsed + ']';
  1331. }
  1332. else if (obj.constructor == mxRtCell)
  1333. {
  1334. result += '[id=' + obj.cellId + ',parent=' + ((obj.parent != null) ? obj.parent.cellId : '[null]');
  1335. if (obj.children.length > 0)
  1336. {
  1337. result += ',\n' + obj.children.length + ' children=[' +
  1338. this.dump(obj.children.get(0));
  1339. for (var i = 1; i < obj.children.length; i++)
  1340. {
  1341. result += ',' + this.dump(obj.children.get(i));
  1342. }
  1343. result += ']';
  1344. }
  1345. result += ']\n';
  1346. }
  1347. else if (obj.keys != null)
  1348. {
  1349. var keys = obj.keys();
  1350. result += '{\n';
  1351. for (var i = 0; i < keys.length; i++)
  1352. {
  1353. result += keys[i] + '=' + this.dump(obj.get(keys[i])) + ';\n';
  1354. }
  1355. result += '}';
  1356. }
  1357. else if (obj.asArray != null)
  1358. {
  1359. var arr = obj.asArray();
  1360. result += '[';
  1361. for (var i = 0; i < arr.length; i++)
  1362. {
  1363. result += arr[i] + ';';
  1364. }
  1365. result += ']';
  1366. }
  1367. else
  1368. {
  1369. result = obj;
  1370. }
  1371. }
  1372. else
  1373. {
  1374. result = 'null';
  1375. }
  1376. return result;
  1377. };
  1378. /**
  1379. * Writes the given text to the log if <logging> is enabled.
  1380. */
  1381. DriveRealtime.prototype.check = function()
  1382. {
  1383. console.log('checking consistency');
  1384. this.checkChildren(this.model.getRoot());
  1385. console.log('checking consistency done');
  1386. };
  1387. /**
  1388. * Writes the given text to the log if <logging> is enabled.
  1389. */
  1390. DriveRealtime.prototype.checkChildren = function(cell)
  1391. {
  1392. if (cell.rtCell == null)
  1393. {
  1394. console.log('no realtime cell', 'cell', cell.id);
  1395. }
  1396. else
  1397. {
  1398. if (cell.getTerminal(true) != null && (cell.rtCell.source == null ||
  1399. cell.rtCell.source != cell.getTerminal(true).rtCell))
  1400. {
  1401. console.log('invalid source', 'edge', cell.id, 'source',
  1402. cell.getTerminal(true).id, 'rtSource', cell.rtCell.source);
  1403. }
  1404. if (cell.getTerminal(false) != null && (cell.rtCell.target == null ||
  1405. cell.rtCell.target != cell.getTerminal(false).rtCell))
  1406. {
  1407. console.log('invalid target', 'edge', cell.id, 'target',
  1408. cell.getTerminal(false).id, 'rtTarget', cell.rtCell.target);
  1409. }
  1410. var childCount = this.model.getChildCount(cell);
  1411. var children = cell.rtCell.children.asArray();
  1412. if (childCount != cell.rtCell.children.length)
  1413. {
  1414. console.log('invalid child count', 'cell', cell.id, 'children',
  1415. children.length, 'childCount', childCount);
  1416. }
  1417. for (var i = 0; i < cell.rtCell.children.length; i++)
  1418. {
  1419. var child = this.model.getChildAt(cell, i);
  1420. if (child == null)
  1421. {
  1422. console.log('no child', 'index', i, 'child', cell.rtCell.children.get(i));
  1423. }
  1424. else if (cell.rtCell.children.get(i) != child.rtCell)
  1425. {
  1426. console.log('invalid child', 'index', i, 'child',
  1427. cell.rtCell.children.get(i), 'graphChild', child);
  1428. }
  1429. }
  1430. }
  1431. for (var i = 0; i < childCount; i++)
  1432. {
  1433. var child = this.model.getChildAt(cell, i);
  1434. this.checkChildren(child);
  1435. }
  1436. };
  1437. /**
  1438. * Writes the given text to the log if <logging> is enabled.
  1439. */
  1440. DriveRealtime.prototype.log = function(message)
  1441. {
  1442. if (this.logLevel > 1)
  1443. {
  1444. //mxLog.debug.apply(mxLog, arguments);
  1445. //console.log(message);
  1446. }
  1447. };
  1448. /**
  1449. * Writes the given text to the log if <logging> is enabled.
  1450. */
  1451. DriveRealtime.prototype.warn = function(message)
  1452. {
  1453. if (this.logLevel > 0)
  1454. {
  1455. //mxLog.debug.apply(mxLog, arguments);
  1456. //console.log(message);
  1457. }
  1458. };
  1459. /**
  1460. * Destroys the instance and removes all listeners.
  1461. */
  1462. DriveRealtime.prototype.destroy = function(unloading)
  1463. {
  1464. unloading = (unloading != null) ? unloading : false;
  1465. if (this.pageFormatListener != null)
  1466. {
  1467. this.ui.removeListener(this.pageFormatListener);
  1468. this.pageFormatListener = null;
  1469. }
  1470. if (this.pageScaleListener != null)
  1471. {
  1472. this.ui.removeListener(this.pageScaleListener);
  1473. this.pageScaleListener = null;
  1474. }
  1475. if (this.backgroundColorListener != null)
  1476. {
  1477. this.ui.removeListener(this.backgroundColorListener);
  1478. this.backgroundColorListener = null;
  1479. }
  1480. if (this.shadowVisibleListener != null)
  1481. {
  1482. this.graph.removeListener(this.shadowVisibleListener);
  1483. this.shadowVisibleListener = null;
  1484. }
  1485. if (this.foldingEnabledListener != null)
  1486. {
  1487. this.ui.removeListener(this.foldingEnabledListener);
  1488. this.foldingEnabledListener = null;
  1489. }
  1490. if (this.pageVisibleListener != null)
  1491. {
  1492. this.ui.removeListener(this.pageVisibleListener);
  1493. this.pageVisibleListener = null;
  1494. }
  1495. if (this.backgroundImageListener != null)
  1496. {
  1497. this.ui.removeListener(this.backgroundImageListener);
  1498. this.backgroundImageListener = null;
  1499. }
  1500. if (this.mathEnabledListener != null)
  1501. {
  1502. this.ui.removeListener(this.mathEnabledListener);
  1503. this.mathEnabledListener = null;
  1504. }
  1505. if (this.previousUndoListener != null)
  1506. {
  1507. this.ui.editor.undoListener = this.previousUndoListener;
  1508. this.previousUndoListener = null;
  1509. }
  1510. if (this.graphSelectionModelChangeListener != null)
  1511. {
  1512. this.graph.selectionModel.removeListener(this.graphSelectionModelChangeListener);
  1513. this.graphSelectionModelChangeListener = null;
  1514. }
  1515. if (this.disconnectListener != null)
  1516. {
  1517. this.ui.drive.removeListener(this.disconnectListener);
  1518. this.disconnectListener = null;
  1519. }
  1520. if (this.autosaveChangeListener != null)
  1521. {
  1522. this.ui.editor.removeListener(this.autosaveChangeListener);
  1523. this.autosaveChangeListener = null;
  1524. }
  1525. if (this.graphModelChangeListener != null)
  1526. {
  1527. this.model.removeListener(this.graphModelChangeListener);
  1528. this.graphModelChangeListener = null;
  1529. }
  1530. if (this.pageChangeListener != null)
  1531. {
  1532. this.ui.editor.removeListener(this.pageChangeListener);
  1533. this.pageChangeListener = null;
  1534. }
  1535. if (this.viewStateListener != null)
  1536. {
  1537. this.ui.editor.removeListener(this.viewStateListener);
  1538. this.viewStateListener = null;
  1539. }
  1540. if (this.collaboratorsElement != null)
  1541. {
  1542. this.collaboratorsElement.parentNode.removeChild(this.collaboratorsElement);
  1543. this.collaboratorsElement = null;
  1544. }
  1545. if (this.updateStatusThread != null)
  1546. {
  1547. window.clearInterval(this.updateStatusThread);
  1548. this.updateStatusThread = null;
  1549. }
  1550. this.ui.allowAnimation = true;
  1551. try
  1552. {
  1553. // KNOWN: Cannot access g of null error in realtime
  1554. // when called from window.onBeforeUnload handler
  1555. if (!unloading && !this.doc.isClosed)
  1556. {
  1557. this.doc.close();
  1558. }
  1559. }
  1560. catch (e)
  1561. {
  1562. // ignores possible document closed errors
  1563. }
  1564. };