DriveRealtime.js 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749
  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. var page = this.ui.pages[index];
  758. if (page != null)
  759. {
  760. this.ui.removePage(page);
  761. page.mapping.destroy();
  762. }
  763. }
  764. }
  765. this.ignoreChange = false;
  766. }
  767. }
  768. }));
  769. };
  770. /**
  771. * Returns a string representation of the given ops.
  772. */
  773. DriveRealtime.prototype.processChange = function(change)
  774. {
  775. //console.log('processChange: ' + this.dump(change));
  776. if (change instanceof RenamePage)
  777. {
  778. change.page.mapping.diagramMap.set('name', change.page.getName());
  779. }
  780. else if (change instanceof ChangePage)
  781. {
  782. if (change.previousIndex == null)
  783. {
  784. this.diagrams.removeValue(change.relatedPage.mapping.diagramMap);
  785. }
  786. else
  787. {
  788. this.diagrams.insert(change.previousIndex, change.relatedPage.mapping.diagramMap);
  789. }
  790. }
  791. else if (change instanceof MovePage)
  792. {
  793. this.diagrams.move(change.newIndex, change.oldIndex + ((change.newIndex < change.oldIndex) ? 1 : 0));
  794. }
  795. else if (change instanceof mxRootChange)
  796. {
  797. // Only process the root change that sets the current root
  798. // ie. ignore previous root changes
  799. if (change.root == this.model.root)
  800. {
  801. this.getCurrentPage().mapping.initRealtime();
  802. }
  803. }
  804. else if (change instanceof mxChildChange)
  805. {
  806. if (change.parent != change.previous || change.index != change.previousIndex)
  807. {
  808. var childRtCell = change.child.rtCell;
  809. if (childRtCell == null)
  810. {
  811. childRtCell = this.getCurrentPage().mapping.createRealtimeCell(change.child);
  812. this.getCurrentPage().mapping.saveRealtimeCell(childRtCell.cell);
  813. }
  814. var parentRtCell = (change.parent != null) ? change.parent.rtCell : null;
  815. if (change.previous != null)
  816. {
  817. var previousParentRtCell = change.previous.rtCell;
  818. if (previousParentRtCell != null)
  819. {
  820. previousParentRtCell.children.removeValue(childRtCell);
  821. }
  822. }
  823. if (parentRtCell != null)
  824. {
  825. parentRtCell.children.insert(Math.min(parentRtCell.children.length, change.index), childRtCell);
  826. }
  827. childRtCell.parent = parentRtCell;
  828. }
  829. }
  830. else if (change.cell != null && change.cell.id != null)
  831. {
  832. var rtCell = change.cell.rtCell;
  833. if (rtCell != null)
  834. {
  835. if (change instanceof mxTerminalChange)
  836. {
  837. var term = (change.terminal != null) ? change.terminal.rtCell : null;
  838. rtCell[(change.source) ? 'source' : 'target'] = term;
  839. }
  840. else if (change instanceof mxGeometryChange)
  841. {
  842. rtCell.geometry = (change.geometry != null) ? mxUtils.getXml(this.codec.encode(change.geometry)) : null;
  843. }
  844. else if (change instanceof mxStyleChange)
  845. {
  846. rtCell.style = change.style;
  847. }
  848. else if (change instanceof mxValueChange)
  849. {
  850. if (mxUtils.isNode(change.value))
  851. {
  852. rtCell.value = null;
  853. rtCell.xmlValue = mxUtils.getXml(change.value);
  854. }
  855. else
  856. {
  857. rtCell.xmlValue = null;
  858. rtCell.value = change.value;
  859. }
  860. }
  861. else if (change instanceof mxCollapseChange)
  862. {
  863. rtCell.collapsed = (change.collapsed) ? '1' : '0';
  864. }
  865. else if (change instanceof mxVisibleChange)
  866. {
  867. rtCell.visible = (change.visible) ? '1' : '0';
  868. }
  869. }
  870. }
  871. };
  872. /**
  873. * Adds the listener for changes on the graph model and maps them to the collab
  874. * model as a single transaction.
  875. */
  876. DriveRealtime.prototype.setFileModified = function()
  877. {
  878. this.root.set('modifiedDate', new Date().getTime());
  879. this.file.setModified(true);
  880. if (!this.saving)
  881. {
  882. this.ui.editor.setStatus(mxResources.get('saving') + '...');
  883. this.saving = true;
  884. }
  885. };
  886. /**
  887. * Adds the listener for changes on the graph model and maps them to the collab
  888. * model as a single transaction.
  889. */
  890. DriveRealtime.prototype.installGraphModelListener = function()
  891. {
  892. // Adds a graph model listener to update the view
  893. this.graphModelChangeListener = mxUtils.bind(this, function(sender, evt)
  894. {
  895. var edit = evt.getProperty('edit');
  896. if (!this.ignoreChange && this.file.isEditable() && !edit.ignoreEdit)
  897. {
  898. //console.log('startEdit');
  899. // TODO: Queuing for async token refresh and too many updates
  900. this.ui.drive.checkToken(mxUtils.bind(this, function()
  901. {
  902. this.rtModel.beginCompoundOperation();
  903. this.setFileModified();
  904. try
  905. {
  906. var changes = edit.changes;
  907. if (edit.undone)
  908. {
  909. for (var i = changes.length - 1; i >= 0; i--)
  910. {
  911. this.processChange(changes[i]);
  912. }
  913. }
  914. else
  915. {
  916. for (var i = 0; i < changes.length; i++)
  917. {
  918. this.processChange(changes[i]);
  919. }
  920. }
  921. this.rtModel.endCompoundOperation();
  922. }
  923. catch (e)
  924. {
  925. this.rtModel.endCompoundOperation();
  926. this.ui.handleError(e);
  927. }
  928. if (this.isAliveThread == null)
  929. {
  930. this.isAliveThread = window.setTimeout(mxUtils.bind(this, function()
  931. {
  932. this.ui.editor.setStatus('<div class="geStatusAlert geBlink" style="cursor:pointer;">' +
  933. mxResources.get('noResponse') + '</div>');
  934. this.isAliveThread = window.setTimeout(mxUtils.bind(this, function()
  935. {
  936. this.isAliveThread = null;
  937. this.timeoutError();
  938. }), this.realtimeHeartbeat);
  939. }), this.realtimeHeartbeat);
  940. }
  941. }));
  942. //console.log('endEdit');
  943. }
  944. });
  945. this.model.addListener(mxEvent.CHANGE, this.graphModelChangeListener);
  946. };
  947. /**
  948. *
  949. */
  950. DriveRealtime.prototype.sessionExpiredError = function()
  951. {
  952. // LATER: How to reload realtime document without refreshing the page
  953. this.ui.showError(mxResources.get('error'), mxResources.get('sessionExpired'), mxResources.get('refresh'), mxUtils.bind(this, function()
  954. {
  955. this.ui.spinner.spin(document.body, mxResources.get('connecting'));
  956. this.file.setModified(false);
  957. window.location.reload();
  958. }));
  959. };
  960. /**
  961. *
  962. */
  963. DriveRealtime.prototype.timeoutError = function()
  964. {
  965. // LATER: How to reload realtime document without refreshing the page
  966. this.ui.showError(mxResources.get('timeout'), mxResources.get('realtimeTimeout'), mxResources.get('discardChangesAndReconnect'), mxUtils.bind(this, function()
  967. {
  968. this.ui.spinner.spin(document.body, mxResources.get('connecting'));
  969. this.file.setModified(false);
  970. window.location.reload();
  971. }), null, mxResources.get('ignore'), mxUtils.bind(this, function()
  972. {
  973. this.ui.editor.setStatus('<div class="geStatusAlert geBlink" style="cursor:pointer;">' +
  974. mxResources.get('disconnected') + '</div>');
  975. this.realtimeHeartbeat *= 2;
  976. }));
  977. };
  978. /**
  979. *
  980. */
  981. DriveRealtime.prototype.initializeChat = function()
  982. {
  983. this.chatHistory = this.rtModel.createList();
  984. this.root.set('chatHistory', this.chatHistory);
  985. //this.log('Chat history created');
  986. };
  987. /**
  988. * Adds a listener to the graph selection model and writes changes
  989. * in the RT selection map
  990. */
  991. DriveRealtime.prototype.installSelectionModelListener = function()
  992. {
  993. this.graphSelectionModelChangeListener = mxUtils.bind(this, function(sender, evt)
  994. {
  995. this.ui.drive.checkToken(mxUtils.bind(this, function()
  996. {
  997. if (this.file.isEditable() && !this.graph.isSelectionEmpty())
  998. {
  999. try
  1000. {
  1001. // LATER: Clear value if selection is empty. This is currently
  1002. // disabled to avoid using up the quota in this case but the
  1003. // better solution is to mark this "transient" (ie no history).
  1004. var cells = this.graph.getSelectionCells();
  1005. var selectedCellIds = '';
  1006. for (var i = 0; i < cells.length; i++)
  1007. {
  1008. selectedCellIds += cells[i].id + ',';
  1009. }
  1010. this.getCurrentPage().mapping.selectionMap.set(this.userId, selectedCellIds);
  1011. }
  1012. catch (e)
  1013. {
  1014. this.ui.handleError(e);
  1015. }
  1016. }
  1017. }));
  1018. });
  1019. this.graph.getSelectionModel().addListener(mxEvent.CHANGE, this.graphSelectionModelChangeListener);
  1020. };
  1021. /**
  1022. * Connects the collaborator event listeners to the draw function.
  1023. */
  1024. DriveRealtime.prototype.installCollaboratorListener = function()
  1025. {
  1026. this.doc.addEventListener(gapi.drive.realtime.EventType.COLLABORATOR_JOINED, mxUtils.bind(this, this.updateCollaborators));
  1027. this.doc.addEventListener(gapi.drive.realtime.EventType.COLLABORATOR_LEFT, mxUtils.bind(this, this.updateCollaborators));
  1028. };
  1029. /**
  1030. * Draw function for the collaborator list.
  1031. */
  1032. DriveRealtime.prototype.updateCollaborators = function()
  1033. {
  1034. var n = this.doc.getCollaborators().length - 1;
  1035. if (this.collaboratorsElement == null)
  1036. {
  1037. this.collaboratorsElement = document.createElement('a');
  1038. this.collaboratorsElement.setAttribute('href', 'javascript:void(0);');
  1039. this.collaboratorsElement.className = 'geItem';
  1040. this.collaboratorsElement.style.position = 'absolute';
  1041. this.collaboratorsElement.style.display = 'inline-block';
  1042. this.collaboratorsElement.style.verticalAlign = 'bottom';
  1043. this.collaboratorsElement.style.color = '#666';
  1044. this.collaboratorsElement.style.top = '10px';
  1045. this.collaboratorsElement.style.right = (uiTheme == 'atlas') ? '42px' : '68px';
  1046. this.collaboratorsElement.style.padding = '2px';
  1047. this.collaboratorsElement.style.fontSize = '8pt';
  1048. this.collaboratorsElement.style.verticalAlign = 'middle';
  1049. this.collaboratorsElement.style.backgroundPosition = '100% 60%';
  1050. this.collaboratorsElement.style.backgroundRepeat = 'no-repeat';
  1051. this.ui.toolbarContainer.appendChild(this.collaboratorsElement);
  1052. mxEvent.addListener(this.collaboratorsElement, 'click', mxUtils.bind(this, function(evt)
  1053. {
  1054. if (this.collabPanel == null)
  1055. {
  1056. var div = document.createElement('div');
  1057. div.className = 'geDialog';
  1058. div.style.position = 'absolute';
  1059. div.style.maxHeight = '400px';
  1060. div.style.maxWidth = '300px';
  1061. div.style.right = '38px';
  1062. div.style.padding = '14px';
  1063. div.style.paddingRight = '30px';
  1064. this.collabPanel = div;
  1065. }
  1066. if (this.collabPanel.parentNode == null)
  1067. {
  1068. this.collabPanel.style.top = (this.collaboratorsElement.clientTop + this.collaboratorsElement.clientHeight + this.ui.menubarHeight + 8) + 'px';
  1069. document.body.appendChild(this.collabPanel);
  1070. this.collabPanel.innerHTML = '';
  1071. var img = document.createElement('img');
  1072. img.setAttribute('src', Dialog.prototype.closeImage);
  1073. img.setAttribute('title', mxResources.get('close'));
  1074. img.className = 'geDialogClose';
  1075. img.style.top = '8px';
  1076. img.style.right = '8px';
  1077. mxEvent.addListener(img, 'click', mxUtils.bind(this, function()
  1078. {
  1079. if (this.collabPanel.parentNode != null)
  1080. {
  1081. this.collabPanel.parentNode.removeChild(this.collabPanel);
  1082. }
  1083. }));
  1084. this.collabPanel.appendChild(img);
  1085. if (this.doc.getCollaborators().length > 1)
  1086. {
  1087. for (var i = 0; i < this.doc.getCollaborators().length; i = i + 1)
  1088. {
  1089. var collaborator = this.doc.getCollaborators()[i];
  1090. if (!collaborator.isMe)
  1091. {
  1092. var elt = document.createElement('div');
  1093. elt.style.cursor = 'pointer';
  1094. elt.style.whiteSpace = 'nowrap';
  1095. var img = document.createElement('img');
  1096. img.src = collaborator.photoUrl;
  1097. img.style.backgroundColor = collaborator.color;
  1098. img.style.paddingBottom = '8px';
  1099. img.style.marginRight = '10px';
  1100. img.style.marginTop = '2px';
  1101. img.style.marginBottom = '2px';
  1102. img.style.height = '25px';
  1103. img.style.width = '25px';
  1104. img.setAttribute('align', 'absmiddle');
  1105. elt.appendChild(img);
  1106. mxUtils.write(elt, collaborator.displayName);
  1107. this.collabPanel.appendChild(elt);
  1108. // Click on collaborator shows selection cells, scrolls to first cell
  1109. mxEvent.addListener(elt, 'click', mxUtils.bind(this, function()
  1110. {
  1111. var value = this.getCurrentPage().mapping.selectionMap.get(collaborator.userId);
  1112. if (value != null)
  1113. {
  1114. var cellIds = value.split(',');
  1115. for (var i = 0; i < cellIds.length; i++)
  1116. {
  1117. var cell = this.model.getCell(cellIds[i]);
  1118. this.highlight(cell, collaborator.sessionId);
  1119. if (cell != null && i == 0)
  1120. {
  1121. this.graph.scrollCellToVisible(cell);
  1122. }
  1123. }
  1124. }
  1125. }));
  1126. }
  1127. }
  1128. }
  1129. else
  1130. {
  1131. mxUtils.write(this.collabPanel, mxResources.get('noOtherViewers'));
  1132. }
  1133. }
  1134. else if (this.collabPanel.parentNode != null)
  1135. {
  1136. this.collabPanel.parentNode.removeChild(this.collabPanel);
  1137. }
  1138. mxEvent.consume(evt);
  1139. }));
  1140. mxEvent.addListener(document.body, 'click', mxUtils.bind(this, function(evt)
  1141. {
  1142. if (!mxEvent.isConsumed(evt) && this.collabPanel != null && this.collabPanel.parentNode != null)
  1143. {
  1144. this.collabPanel.parentNode.removeChild(this.collabPanel);
  1145. }
  1146. }));
  1147. }
  1148. var viewers = mxResources.get((n == 0) ? 'noOtherViewers' : ((n == 1) ? 'otherViewer' : 'otherViewers'));
  1149. if (n > 0)
  1150. {
  1151. viewers = n + ' ' + viewers;
  1152. this.collaboratorsElement.style.paddingRight = '16px';
  1153. this.collaboratorsElement.style.backgroundImage = 'url(' + IMAGE_PATH + '/expanded.gif)';
  1154. this.collaboratorsElement.style.cursor = 'pointer';
  1155. }
  1156. else
  1157. {
  1158. this.collaboratorsElement.style.paddingRight = '0px';
  1159. this.collaboratorsElement.style.backgroundImage = '';
  1160. this.collaboratorsElement.style.cursor = 'default';
  1161. }
  1162. var html = '<div title="' + viewers + '" style="display:inline-block;white-space:nowrap;max-width:110px;overflow:hidden;text-overflow:ellipsis;">' + viewers + '</div>';
  1163. var names = new Object();
  1164. var count = 0;
  1165. for (var i = 0; i < this.doc.getCollaborators().length && count < 6; i = i + 1)
  1166. {
  1167. var c = this.doc.getCollaborators()[i];
  1168. if (!c.isMe && names[c.color] == null)
  1169. {
  1170. names[c.color] = c.displayName;
  1171. count++;
  1172. }
  1173. }
  1174. for (var color in names)
  1175. {
  1176. 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>';
  1177. }
  1178. this.collaboratorsElement.innerHTML = html;
  1179. };
  1180. /**
  1181. * Creates and returns a prefix for cell IDs.
  1182. */
  1183. DriveRealtime.prototype.createPrefix = function()
  1184. {
  1185. var collabs = this.doc.getCollaborators();
  1186. for (var i = 0; i < collabs.length; i++)
  1187. {
  1188. if (collabs[i]['isMe'])
  1189. {
  1190. return collabs[i]['sessionId'];
  1191. }
  1192. }
  1193. return '';
  1194. };
  1195. DriveRealtime.prototype.highlight = function(cell, sessionId)
  1196. {
  1197. var state = this.graph.view.getState(cell);
  1198. if (state != null)
  1199. {
  1200. var color = 'red'; // session not found
  1201. for (var i = 0; i < this.doc.getCollaborators().length; i = i + 1)
  1202. {
  1203. var collaborator = this.doc.getCollaborators()[i];
  1204. if (collaborator.sessionId == sessionId)
  1205. {
  1206. color = collaborator.color;
  1207. break;
  1208. }
  1209. }
  1210. var sw = Math.max(5, mxUtils.getValue(state.style, mxConstants.STYLE_STROKEWIDTH, 1) + 4);
  1211. var hl = new mxCellHighlight(this.graph, color, sw, false);
  1212. hl.highlight(state);
  1213. // Fades out the highlight after a delay
  1214. window.setTimeout(function()
  1215. {
  1216. if (hl.shape != null)
  1217. {
  1218. mxUtils.setPrefixedStyle(hl.shape.node.style, 'transition', 'all 1200ms ease-in-out');
  1219. hl.shape.node.style.opacity = 0;
  1220. }
  1221. window.setTimeout(function()
  1222. {
  1223. hl.destroy();
  1224. }, 2000);
  1225. }, 1000);
  1226. }
  1227. };
  1228. /**
  1229. * Writes out a string representing the current state of the document.
  1230. */
  1231. DriveRealtime.prototype.dumpRoot = function()
  1232. {
  1233. return this.dump(this.root);
  1234. };
  1235. /**
  1236. * Creates a dump of the given map.
  1237. */
  1238. DriveRealtime.prototype.dump = function(obj)
  1239. {
  1240. var result = '';
  1241. if (obj != null)
  1242. {
  1243. if (obj.constructor == mxCell)
  1244. {
  1245. return obj.id;
  1246. }
  1247. else if (obj.constructor == mxRootChange)
  1248. {
  1249. result += 'mxRootChange[root=' + this.dump(obj.root) + ']';
  1250. }
  1251. else if (obj.constructor == mxChildChange)
  1252. {
  1253. result += 'mxChildChange[parent=' + this.dump(obj.parent) +
  1254. ', child=' + this.dump(obj.child.id) +
  1255. ', index=' + obj.index + ']';
  1256. }
  1257. else if (obj.constructor == mxTerminalChange)
  1258. {
  1259. result += 'mxTerminalChange[cell=' + this.dump(obj.cell) +
  1260. ', terminal=' + this.dump(obj.terminal) +
  1261. ', source=' + obj.source + ']';
  1262. }
  1263. else if (obj.constructor == mxValueChange)
  1264. {
  1265. result += 'mxValueChange[cell=' + this.dump(obj.cell) + ', value=' + obj.value + ']';
  1266. }
  1267. else if (obj.constructor == mxGeometryChange)
  1268. {
  1269. result += 'mxGeometryChange[cell=' + this.dump(obj.cell) + ', geometry=' +
  1270. ((obj.cell.geometry != null) ? mxUtils.getXml(this.codec.encode(obj.cell.geometry)) : '[null]') + ']';
  1271. }
  1272. else if (obj.constructor == mxStyleChange)
  1273. {
  1274. result += 'mxStyleChange[cell=' + this.dump(obj.cell) + ', style=' + obj.style + ']';
  1275. }
  1276. else if (obj.constructor == mxVisibleChange)
  1277. {
  1278. result += 'mxVisibleChange[cell=' + this.dump(obj.cell) + ', visible=' + obj.visible + ']';
  1279. }
  1280. else if (obj.constructor == mxCollapseChange)
  1281. {
  1282. result += 'mxCollapseChange[cell=' + this.dump(obj.cell) + ', collapsed=' + obj.collapsed + ']';
  1283. }
  1284. else if (obj.constructor == mxRtCell)
  1285. {
  1286. result += '[id=' + obj.cellId + ',parent=' + ((obj.parent != null) ? obj.parent.cellId : '[null]');
  1287. if (obj.children.length > 0)
  1288. {
  1289. result += ',\n' + obj.children.length + ' children=[' +
  1290. this.dump(obj.children.get(0));
  1291. for (var i = 1; i < obj.children.length; i++)
  1292. {
  1293. result += ',' + this.dump(obj.children.get(i));
  1294. }
  1295. result += ']';
  1296. }
  1297. result += ']\n';
  1298. }
  1299. else if (obj.keys != null)
  1300. {
  1301. var keys = obj.keys();
  1302. result += '{\n';
  1303. for (var i = 0; i < keys.length; i++)
  1304. {
  1305. result += keys[i] + '=' + this.dump(obj.get(keys[i])) + ';\n';
  1306. }
  1307. result += '}';
  1308. }
  1309. else if (obj.asArray != null)
  1310. {
  1311. var arr = obj.asArray();
  1312. result += '[';
  1313. for (var i = 0; i < arr.length; i++)
  1314. {
  1315. result += arr[i] + ';';
  1316. }
  1317. result += ']';
  1318. }
  1319. else
  1320. {
  1321. result = obj;
  1322. }
  1323. }
  1324. else
  1325. {
  1326. result = 'null';
  1327. }
  1328. return result;
  1329. };
  1330. /**
  1331. * Writes the given text to the log if <logging> is enabled.
  1332. */
  1333. DriveRealtime.prototype.check = function()
  1334. {
  1335. console.log('checking consistency');
  1336. this.checkChildren(this.model.getRoot());
  1337. console.log('checking consistency done');
  1338. };
  1339. /**
  1340. * Writes the given text to the log if <logging> is enabled.
  1341. */
  1342. DriveRealtime.prototype.checkChildren = function(cell)
  1343. {
  1344. if (cell.rtCell == null)
  1345. {
  1346. console.log('no realtime cell', 'cell', cell.id);
  1347. }
  1348. else
  1349. {
  1350. if (cell.getTerminal(true) != null && (cell.rtCell.source == null ||
  1351. cell.rtCell.source != cell.getTerminal(true).rtCell))
  1352. {
  1353. console.log('invalid source', 'edge', cell.id, 'source',
  1354. cell.getTerminal(true).id, 'rtSource', cell.rtCell.source);
  1355. }
  1356. if (cell.getTerminal(false) != null && (cell.rtCell.target == null ||
  1357. cell.rtCell.target != cell.getTerminal(false).rtCell))
  1358. {
  1359. console.log('invalid target', 'edge', cell.id, 'target',
  1360. cell.getTerminal(false).id, 'rtTarget', cell.rtCell.target);
  1361. }
  1362. var childCount = this.model.getChildCount(cell);
  1363. var children = cell.rtCell.children.asArray();
  1364. if (childCount != cell.rtCell.children.length)
  1365. {
  1366. console.log('invalid child count', 'cell', cell.id, 'children',
  1367. children.length, 'childCount', childCount);
  1368. }
  1369. for (var i = 0; i < cell.rtCell.children.length; i++)
  1370. {
  1371. var child = this.model.getChildAt(cell, i);
  1372. if (child == null)
  1373. {
  1374. console.log('no child', 'index', i, 'child', cell.rtCell.children.get(i));
  1375. }
  1376. else if (cell.rtCell.children.get(i) != child.rtCell)
  1377. {
  1378. console.log('invalid child', 'index', i, 'child',
  1379. cell.rtCell.children.get(i), 'graphChild', child);
  1380. }
  1381. }
  1382. }
  1383. for (var i = 0; i < childCount; i++)
  1384. {
  1385. var child = this.model.getChildAt(cell, i);
  1386. this.checkChildren(child);
  1387. }
  1388. };
  1389. /**
  1390. * Writes the given text to the log if <logging> is enabled.
  1391. */
  1392. DriveRealtime.prototype.log = function(message)
  1393. {
  1394. if (this.logLevel > 1)
  1395. {
  1396. //mxLog.debug.apply(mxLog, arguments);
  1397. //console.log(message);
  1398. }
  1399. };
  1400. /**
  1401. * Writes the given text to the log if <logging> is enabled.
  1402. */
  1403. DriveRealtime.prototype.warn = function(message)
  1404. {
  1405. if (this.logLevel > 0)
  1406. {
  1407. //mxLog.debug.apply(mxLog, arguments);
  1408. //console.log(message);
  1409. }
  1410. };
  1411. /**
  1412. * Destroys the instance and removes all listeners.
  1413. */
  1414. DriveRealtime.prototype.destroy = function(unloading)
  1415. {
  1416. unloading = (unloading != null) ? unloading : false;
  1417. if (this.pageFormatListener != null)
  1418. {
  1419. this.ui.removeListener(this.pageFormatListener);
  1420. this.pageFormatListener = null;
  1421. }
  1422. if (this.pageScaleListener != null)
  1423. {
  1424. this.ui.removeListener(this.pageScaleListener);
  1425. this.pageScaleListener = null;
  1426. }
  1427. if (this.backgroundColorListener != null)
  1428. {
  1429. this.ui.removeListener(this.backgroundColorListener);
  1430. this.backgroundColorListener = null;
  1431. }
  1432. if (this.shadowVisibleListener != null)
  1433. {
  1434. this.graph.removeListener(this.shadowVisibleListener);
  1435. this.shadowVisibleListener = null;
  1436. }
  1437. if (this.foldingEnabledListener != null)
  1438. {
  1439. this.ui.removeListener(this.foldingEnabledListener);
  1440. this.foldingEnabledListener = null;
  1441. }
  1442. if (this.backgroundImageListener != null)
  1443. {
  1444. this.ui.removeListener(this.backgroundImageListener);
  1445. this.backgroundImageListener = null;
  1446. }
  1447. if (this.mathEnabledListener != null)
  1448. {
  1449. this.ui.removeListener(this.mathEnabledListener);
  1450. this.mathEnabledListener = null;
  1451. }
  1452. if (this.previousUndoListener != null)
  1453. {
  1454. this.ui.editor.undoListener = this.previousUndoListener;
  1455. this.previousUndoListener = null;
  1456. }
  1457. if (this.graphSelectionModelChangeListener != null)
  1458. {
  1459. this.graph.selectionModel.removeListener(this.graphSelectionModelChangeListener);
  1460. this.graphSelectionModelChangeListener = null;
  1461. }
  1462. if (this.disconnectListener != null)
  1463. {
  1464. this.ui.drive.removeListener(this.disconnectListener);
  1465. this.disconnectListener = null;
  1466. }
  1467. if (this.autosaveChangeListener != null)
  1468. {
  1469. this.ui.editor.removeListener(this.autosaveChangeListener);
  1470. this.autosaveChangeListener = null;
  1471. }
  1472. if (this.graphModelChangeListener != null)
  1473. {
  1474. this.model.removeListener(this.graphModelChangeListener);
  1475. this.graphModelChangeListener = null;
  1476. }
  1477. if (this.viewStateListener != null)
  1478. {
  1479. this.ui.editor.removeListener(this.viewStateListener);
  1480. this.viewStateListener = null;
  1481. }
  1482. if (this.collaboratorsElement != null)
  1483. {
  1484. this.collaboratorsElement.parentNode.removeChild(this.collaboratorsElement);
  1485. this.collaboratorsElement = null;
  1486. }
  1487. if (this.updateStatusThread != null)
  1488. {
  1489. window.clearInterval(this.updateStatusThread);
  1490. this.updateStatusThread = null;
  1491. }
  1492. this.ui.allowAnimation = true;
  1493. try
  1494. {
  1495. // KNOWN: Cannot access g of null error in realtime
  1496. // when called from window.onBeforeUnload handler
  1497. if (!unloading && !this.doc.isClosed)
  1498. {
  1499. this.doc.close();
  1500. }
  1501. }
  1502. catch (e)
  1503. {
  1504. // ignores possible document closed errors
  1505. }
  1506. };