DriveRealtime.js 46 KB

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