DriveRealtime.js 46 KB

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