DriveRealtime.js 48 KB

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