DriveRealtime.js 46 KB

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