DriveRealtime.js 48 KB

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