DriveRealtime.js 48 KB

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