DrawioFile.js 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946
  1. /**
  2. * Copyright (c) 2006-2017, JGraph Ltd
  3. * Copyright (c) 2006-2017, Gaudenz Alder
  4. */
  5. DrawioFile = function(ui, data)
  6. {
  7. mxEventSource.call(this);
  8. /**
  9. * Holds the x-coordinate of the point.
  10. * @type number
  11. * @default 0
  12. */
  13. this.ui = ui;
  14. /**
  15. * Holds the x-coordinate of the point.
  16. * @type number
  17. * @default 0
  18. */
  19. this.data = data || '';
  20. this.shadowData = this.data;
  21. this.shadowPages = null;
  22. // Creates the stats object
  23. this.stats = {
  24. opened: 0, /* number of calls to open */
  25. merged: 0, /* number of calls to merge */
  26. fileMerged: 0, /* number of calls to mergeFile */
  27. fileReloaded: 0, /* number of calls to mergeFile */
  28. conflicts: 0, /* number of write conflicts when saving a file */
  29. timeouts: 0, /* number of time we have given up to retry after a write conflict */
  30. saved: 0, /* number of calls to fileSaved */
  31. closed: 0, /* number of calls to close */
  32. destroyed: 0, /* number of calls to close */
  33. joined: 0, /* number of join messages received */
  34. checksumErrors: 0, /* number of checksum errors */
  35. bytesSent: 0, /* number of bytes send in messages */
  36. bytesReceived: 0, /* number of bytes received in messages */
  37. msgSent: 0, /* number of messages sent */
  38. msgReceived: 0, /* number of messages received */
  39. cacheHits: 0, /* number of times the cache returned patches */
  40. cacheMiss: 0, /* number of times we have missed a cache entry */
  41. cacheFail: 0 /* number of times we have failed to read the cache */
  42. };
  43. };
  44. /**
  45. * Global switch for realtime collaboration type to use sync URL parameter
  46. * with the following possible values:
  47. *
  48. * - none: overwrite
  49. * - manual: manual sync
  50. * - auto: automatic sync
  51. */
  52. DrawioFile.SYNC = urlParams['sync'] || 'auto';
  53. /**
  54. * Specifies if last write wins should be used for values and styles.
  55. */
  56. DrawioFile.LAST_WRITE_WINS = true;
  57. // Extends mxEventSource
  58. mxUtils.extend(DrawioFile, mxEventSource);
  59. /**
  60. * Delay for last save in ms.
  61. */
  62. DrawioFile.prototype.allChangesSavedKey = 'allChangesSaved';
  63. /**
  64. * Specifies the delay between the last change and the autosave.
  65. */
  66. DrawioFile.prototype.autosaveDelay = 1500;
  67. /**
  68. * Specifies the maximum delay before an autosave is forced even if the graph
  69. * is being changed.
  70. */
  71. DrawioFile.prototype.maxAutosaveDelay = 30000;
  72. /**
  73. * Contains the thread for the next autosave.
  74. */
  75. DrawioFile.prototype.autosaveThread = null;
  76. /**
  77. * Stores the timestamp for hte last autosave.
  78. */
  79. DrawioFile.prototype.lastAutosave = null;
  80. /**
  81. * Stores the modified state.
  82. */
  83. DrawioFile.prototype.modified = false;
  84. /**
  85. * Holds a copy of the current file data.
  86. */
  87. DrawioFile.prototype.data = null;
  88. /**
  89. * Holds a copy of the last saved file data.
  90. */
  91. DrawioFile.prototype.shadowData = null;
  92. /**
  93. * Holds a copy of the parsed last saved file data.
  94. */
  95. DrawioFile.prototype.shadowPages = null;
  96. /**
  97. * Specifies if the graph change listener is enabled. Default is true.
  98. */
  99. DrawioFile.prototype.changeListenerEnabled = true;
  100. /**
  101. * Sets the delay for autosave in milliseconds. Default is 1500.
  102. */
  103. DrawioFile.prototype.lastAutosaveRevision = null;
  104. /**
  105. * Sets the delay between revisions when using autosave. Default is 0 which
  106. * creates a revision on every autosave.
  107. */
  108. DrawioFile.prototype.maxAutosaveRevisionDelay = 0;
  109. /**
  110. * Specifies if notify events should be ignored.
  111. */
  112. DrawioFile.prototype.inConflictState = false;
  113. /**
  114. * Specifies if notify events should be ignored.
  115. */
  116. DrawioFile.prototype.invalidChecksum = false;
  117. /**
  118. * Specifies if error reports should be sent.
  119. */
  120. DrawioFile.prototype.errorReportsEnabled = false;
  121. /**
  122. * Specifies if stats should be sent.
  123. */
  124. DrawioFile.prototype.reportEnabled = true;
  125. /**
  126. * Specifies if notify events should be ignored.
  127. */
  128. DrawioFile.prototype.getSize = function()
  129. {
  130. return (this.data != null) ? this.data.length : 0;
  131. };
  132. /**
  133. * Adds the listener for automatically saving the diagram for local changes.
  134. */
  135. DrawioFile.prototype.synchronizeFile = function(success, error)
  136. {
  137. if (this.savingFile)
  138. {
  139. if (error != null)
  140. {
  141. error({message: mxResources.get('busy')});
  142. }
  143. }
  144. else
  145. {
  146. if (this.sync != null)
  147. {
  148. this.sync.fileChanged(success, error);
  149. }
  150. else
  151. {
  152. this.updateFile(success, error);
  153. }
  154. }
  155. };
  156. /**
  157. * Adds the listener for automatically saving the diagram for local changes.
  158. */
  159. DrawioFile.prototype.updateFile = function(success, error, abort, shadow)
  160. {
  161. if (abort == null || !abort())
  162. {
  163. if (this.ui.getCurrentFile() != this || this.invalidChecksum)
  164. {
  165. if (error != null)
  166. {
  167. error();
  168. }
  169. }
  170. else
  171. {
  172. this.getLatestVersion(mxUtils.bind(this, function(latestFile)
  173. {
  174. try
  175. {
  176. if (abort == null || !abort())
  177. {
  178. if (this.ui.getCurrentFile() != this || this.invalidChecksum)
  179. {
  180. if (error != null)
  181. {
  182. error();
  183. }
  184. }
  185. else
  186. {
  187. if (latestFile != null)
  188. {
  189. this.mergeFile(latestFile, success, error, shadow);
  190. }
  191. else
  192. {
  193. this.reloadFile(success, error);
  194. }
  195. }
  196. }
  197. }
  198. catch (e)
  199. {
  200. if (error != null)
  201. {
  202. error(e);
  203. }
  204. }
  205. }), error);
  206. }
  207. }
  208. };
  209. /**
  210. * Adds the listener for automatically saving the diagram for local changes.
  211. */
  212. DrawioFile.prototype.mergeFile = function(file, success, error, diffShadow)
  213. {
  214. var reportError = true;
  215. try
  216. {
  217. this.stats.fileMerged++;
  218. // Takes copy of current shadow document
  219. var shadow = (this.shadowPages != null) ? this.shadowPages :
  220. this.ui.getPagesForNode(mxUtils.parseXml(
  221. this.shadowData).documentElement);
  222. // Loads new document as shadow document
  223. var pages = this.ui.getPagesForNode(
  224. mxUtils.parseXml(file.data).
  225. documentElement)
  226. if (pages != null && pages.length > 0)
  227. {
  228. this.shadowPages = pages;
  229. // Creates a patch for backup if the checksum fails
  230. this.backupPatch = (this.isModified()) ?
  231. this.ui.diffPages(shadow,
  232. this.ui.pages) : null;
  233. // Patches the current document
  234. var patches = [this.ui.diffPages((diffShadow != null) ?
  235. diffShadow : shadow, this.shadowPages)];
  236. var ignored = this.ignorePatches(patches);
  237. if (!ignored)
  238. {
  239. // Patching previous shadow to verify checksum
  240. var patched = this.ui.patchPages(shadow, patches[0]);
  241. var patchedDetails = {};
  242. var checksum = this.ui.getHashValueForPages(patched, patchedDetails);
  243. var currentDetails = {};
  244. var current = this.ui.getHashValueForPages(this.shadowPages, currentDetails);
  245. if (urlParams['test'] == '1')
  246. {
  247. EditorUi.debug('File.mergeFile', [this],
  248. 'backup', this.backupPatch,
  249. 'patches', patches,
  250. 'checksum', current == checksum, checksum);
  251. }
  252. if (checksum != null && checksum != current)
  253. {
  254. var fileData = this.compressReportData(this.getAnonymizedXmlForPages(pages));
  255. var data = this.compressReportData(this.getAnonymizedXmlForPages(patched));
  256. var from = this.ui.hashValue(file.getCurrentEtag());
  257. var to = this.ui.hashValue(this.getCurrentEtag());
  258. this.checksumError(error, patches,
  259. 'Shadow Details: ' + JSON.stringify(patchedDetails) +
  260. '\nChecksum: ' + checksum +
  261. '\nCurrent: ' + current +
  262. '\nCurrent Details: ' + JSON.stringify(currentDetails) +
  263. '\nFrom: ' + from +
  264. '\nTo: ' + to +
  265. '\n\nFile Data:\n' + fileData +
  266. '\nPatched Shadow:\n' + data, null, 'mergeFile');
  267. // Abnormal termination
  268. return;
  269. }
  270. else
  271. {
  272. // Patches the current document
  273. this.patch(patches,
  274. (DrawioFile.LAST_WRITE_WINS) ?
  275. this.backupPatch : null);
  276. }
  277. }
  278. }
  279. else
  280. {
  281. reportError = false;
  282. throw new Error(mxResources.get('notADiagramFile'));
  283. }
  284. this.invalidChecksum = false;
  285. this.inConflictState = false;
  286. this.setDescriptor(file.getDescriptor());
  287. this.descriptorChanged();
  288. this.backupPatch = null;
  289. if (success != null)
  290. {
  291. success();
  292. }
  293. }
  294. catch (e)
  295. {
  296. this.inConflictState = true;
  297. this.invalidChecksum = true;
  298. this.descriptorChanged();
  299. if (error != null)
  300. {
  301. error(e);
  302. }
  303. try
  304. {
  305. if (reportError)
  306. {
  307. if (this.errorReportsEnabled)
  308. {
  309. this.sendErrorReport('Error in mergeFile', null, e);
  310. }
  311. else
  312. {
  313. var user = this.getCurrentUser();
  314. var uid = (user != null) ? user.id : 'unknown';
  315. EditorUi.logError('Error in mergeFile', null,
  316. this.getMode() + '.' + this.getId(),
  317. uid, e);
  318. }
  319. }
  320. }
  321. catch (e2)
  322. {
  323. // ignore
  324. }
  325. }
  326. };
  327. /**
  328. * Adds the listener for automatically saving the diagram for local changes.
  329. */
  330. DrawioFile.prototype.getAnonymizedXmlForPages = function(pages)
  331. {
  332. var enc = new mxCodec(mxUtils.createXmlDocument());
  333. var file = enc.document.createElement('mxfile');
  334. if (pages != null)
  335. {
  336. for (var i = 0; i < pages.length; i++)
  337. {
  338. var temp = enc.encode(new mxGraphModel(pages[i].root));
  339. if (urlParams['dev'] != '1')
  340. {
  341. temp = this.ui.anonymizeNode(temp, true);
  342. }
  343. temp.setAttribute('id', pages[i].getId());
  344. if (pages[i].viewState)
  345. {
  346. this.ui.editor.graph.saveViewState(pages[i].viewState, temp, true);
  347. }
  348. file.appendChild(temp);
  349. }
  350. }
  351. return mxUtils.getPrettyXml(file);
  352. };
  353. /**
  354. * Adds the listener for automatically saving the diagram for local changes.
  355. */
  356. DrawioFile.prototype.compressReportData = function(data, limit, max)
  357. {
  358. limit = (limit != null) ? limit : 10000;
  359. if (max != null && data != null && data.length > max)
  360. {
  361. data = data.substring(0, max) + '[...]';
  362. }
  363. else if (data != null && data.length > limit)
  364. {
  365. data = Graph.compress(data) + '\n';
  366. }
  367. return data;
  368. };
  369. /**
  370. * Adds the listener for automatically saving the diagram for local changes.
  371. */
  372. DrawioFile.prototype.checksumError = function(error, patches, details, etag, functionName)
  373. {
  374. this.stats.checksumErrors++;
  375. this.inConflictState = true;
  376. this.invalidChecksum = true;
  377. this.descriptorChanged();
  378. if (this.sync != null)
  379. {
  380. this.sync.updateOnlineState();
  381. }
  382. if (error != null)
  383. {
  384. error();
  385. }
  386. try
  387. {
  388. if (this.errorReportsEnabled)
  389. {
  390. if (patches != null)
  391. {
  392. for (var i = 0; i < patches.length; i++)
  393. {
  394. this.ui.anonymizePatch(patches[i]);
  395. }
  396. }
  397. var fn = mxUtils.bind(this, function(file)
  398. {
  399. var json = this.compressReportData(
  400. JSON.stringify(patches, null, 2));
  401. var remote = (file != null) ? this.compressReportData(
  402. this.getAnonymizedXmlForPages(
  403. this.ui.getPagesForNode(
  404. mxUtils.parseXml(file.data).documentElement)), 25000) : 'n/a';
  405. this.sendErrorReport(
  406. 'Checksum Error in ' + functionName,
  407. ((details != null) ? (details) : '') +
  408. '\n\nPatches:\n' + json +
  409. ((remote != null) ? ('\n\nRemote:\n' + remote) : ''),
  410. null, 70000);
  411. });
  412. if (etag == null)
  413. {
  414. fn(null);
  415. }
  416. else
  417. {
  418. this.getLatestVersion(mxUtils.bind(this, function(file)
  419. {
  420. if (file != null && file.getCurrentEtag() == etag)
  421. {
  422. fn(file);
  423. }
  424. else
  425. {
  426. fn(null);
  427. }
  428. }), function() {});
  429. }
  430. }
  431. else
  432. {
  433. var user = this.getCurrentUser();
  434. var uid = (user != null) ? user.id : 'unknown';
  435. EditorUi.logError('Checksum Error in ' + functionName, null,
  436. this.getMode() + '.' + this.getId(), uid);
  437. }
  438. }
  439. catch (e)
  440. {
  441. // ignore
  442. }
  443. };
  444. /**
  445. * Adds the listener for automatically saving the diagram for local changes.
  446. */
  447. DrawioFile.prototype.sendErrorReport = function(title, details, error, max)
  448. {
  449. try
  450. {
  451. var shadow = this.compressReportData(
  452. this.getAnonymizedXmlForPages(
  453. this.shadowPages), 25000);
  454. var data = this.compressReportData(
  455. this.getAnonymizedXmlForPages(
  456. this.ui.pages), 25000);
  457. var user = this.getCurrentUser();
  458. var uid = (user != null) ? this.ui.hashValue(user.id) : 'unknown';
  459. var cid = (this.sync != null) ? this.sync.clientId : 'no sync';
  460. var filename = this.getTitle();
  461. var dot = filename.lastIndexOf('.');
  462. var ext = 'xml';
  463. if (dot > 0)
  464. {
  465. ext = filename.substring(dot);
  466. }
  467. var stack = (error != null) ? error.stack : new Error().stack;
  468. EditorUi.sendReport(title + ' ' + new Date().toISOString() + ':' +
  469. '\n\nBrowser=' + navigator.userAgent +
  470. '\nFile=' + this.ui.hashValue(this.getId()) + ' (' + this.getMode() + ')' +
  471. ((this.isModified()) ? ' modified' : '') +
  472. '\nSize/Type=' + this.getSize() + ' (' + ext + ')' +
  473. '\nUser=' + uid + ' (' + cid + ')' +
  474. '\nPrefix=' + this.ui.editor.graph.model.prefix +
  475. '\nSync=' + DrawioFile.SYNC +
  476. ((this.sync != null) ? (((this.sync.enabled) ? ' enabled' : '') +
  477. ((this.sync.isConnected()) ? ' connected' : '')) : '') +
  478. '\nPlugins=' + ((mxSettings.settings != null) ? mxSettings.getPlugins() : 'null') +
  479. '\n\nStats:\n' + JSON.stringify(this.stats, null, 2) +
  480. ((details != null) ? ('\n\n' + details) : '') +
  481. ((error != null) ? ('\n\nError: ' + error.message) : '') +
  482. '\n\nStack:\n' + stack +
  483. '\n\nShadow:\n' + shadow +
  484. '\n\nData:\n' + data, max);
  485. }
  486. catch (e)
  487. {
  488. // ignore
  489. }
  490. };
  491. /**
  492. * Adds the listener for automatically saving the diagram for local changes.
  493. */
  494. DrawioFile.prototype.reloadFile = function(success, error)
  495. {
  496. try
  497. {
  498. this.ui.spinner.stop();
  499. var fn = mxUtils.bind(this, function()
  500. {
  501. this.stats.fileReloaded++;
  502. this.reportEnabled = false;
  503. // Restores view state and current page
  504. var viewState = this.ui.editor.graph.getViewState();
  505. var selection = this.ui.editor.graph.getSelectionCells();
  506. var page = this.ui.currentPage;
  507. this.ui.loadFile(this.getHash(), true, null, mxUtils.bind(this, function()
  508. {
  509. if (this.ui.fileLoadedError == null)
  510. {
  511. this.ui.restoreViewState(page, viewState, selection);
  512. if (this.backupPatch != null)
  513. {
  514. this.patch([this.backupPatch]);
  515. }
  516. // Carry-over stats
  517. var file = this.ui.getCurrentFile();
  518. if (file != null)
  519. {
  520. file.stats = this.stats;
  521. }
  522. if (success != null)
  523. {
  524. success();
  525. }
  526. }
  527. }), true);
  528. });
  529. if (this.isModified() && this.backupPatch == null)
  530. {
  531. this.ui.confirm(mxResources.get('allChangesLost'), mxUtils.bind(this, function()
  532. {
  533. this.handleFileSuccess(DrawioFile.SYNC == 'manual');
  534. }), fn, mxResources.get('cancel'), mxResources.get('discardChanges'));
  535. }
  536. else
  537. {
  538. fn();
  539. }
  540. }
  541. catch (e)
  542. {
  543. if (error != null)
  544. {
  545. error(e);
  546. }
  547. }
  548. };
  549. /**
  550. * Shows a conflict dialog to the user.
  551. */
  552. DrawioFile.prototype.copyFile = function(success, error)
  553. {
  554. this.ui.editor.editAsNew(this.ui.getFileData(true),
  555. this.ui.getCopyFilename(this));
  556. };
  557. /**
  558. * Returns true if the patches in the given array are empty.
  559. */
  560. DrawioFile.prototype.ignorePatches = function(patches)
  561. {
  562. var ignore = true;
  563. for (var i = 0; i < patches.length && ignore; i++)
  564. {
  565. ignore = ignore && Object.keys(patches[i]).length == 0;
  566. }
  567. return ignore;
  568. };
  569. /**
  570. * Applies the given patches to the file.
  571. */
  572. DrawioFile.prototype.patch = function(patches, resolver)
  573. {
  574. // Saves state of undo history
  575. var undoMgr = this.ui.editor.undoManager;
  576. var history = undoMgr.history.slice();
  577. var nextAdd = undoMgr.indexOfNextAdd;
  578. // Hides graph during updates
  579. var graph = this.ui.editor.graph;
  580. graph.container.style.visibility = 'hidden';
  581. // Ignores change events
  582. var prev = this.changeListenerEnabled;
  583. this.changeListenerEnabled = false;
  584. // Folding and math change require special handling
  585. var fold = graph.foldingEnabled;
  586. var math = graph.mathEnabled;
  587. // Updates text editor if cell changes during validation
  588. var redraw = graph.cellRenderer.redraw;
  589. graph.cellRenderer.redraw = function(state)
  590. {
  591. if (state.view.graph.isEditing(state.cell))
  592. {
  593. state.view.graph.scrollCellToVisible(state.cell);
  594. state.view.graph.cellEditor.resize();
  595. }
  596. redraw.apply(this, arguments);
  597. };
  598. graph.model.beginUpdate();
  599. try
  600. {
  601. // Applies patches
  602. for (var i = 0; i < patches.length; i++)
  603. {
  604. this.ui.pages = this.ui.patchPages(this.ui.pages,
  605. patches[i], true, resolver, this.isModified());
  606. }
  607. // Always needs at least one page
  608. if (this.ui.pages.length == 0)
  609. {
  610. this.ui.pages.push(this.ui.createPage());
  611. }
  612. // Checks if current page was removed
  613. if (mxUtils.indexOf(this.ui.pages, this.ui.currentPage) < 0)
  614. {
  615. this.ui.selectPage(this.ui.pages[0], true);
  616. }
  617. }
  618. finally
  619. {
  620. // Changes visibility before action states are updated via model event
  621. graph.container.style.visibility = '';
  622. graph.model.endUpdate();
  623. // Restores previous state
  624. graph.cellRenderer.redraw = redraw;
  625. this.changeListenerEnabled = prev;
  626. // Restores history state
  627. undoMgr.history = history;
  628. undoMgr.indexOfNextAdd = nextAdd;
  629. undoMgr.fireEvent(new mxEventObject(mxEvent.CLEAR));
  630. if (this.ui.currentPage == null || this.ui.currentPage.needsUpdate)
  631. {
  632. // Updates the graph and background
  633. if (math != graph.mathEnabled)
  634. {
  635. this.ui.editor.updateGraphComponents();
  636. graph.refresh();
  637. }
  638. else
  639. {
  640. if (fold != graph.foldingEnabled)
  641. {
  642. graph.view.revalidate();
  643. }
  644. else
  645. {
  646. graph.view.validate();
  647. }
  648. graph.sizeDidChange();
  649. }
  650. }
  651. this.ui.updateTabContainer();
  652. }
  653. };
  654. /**
  655. * Adds the listener for automatically saving the diagram for local changes.
  656. */
  657. DrawioFile.prototype.save = function(revision, success, error, unloading, overwrite, manual)
  658. {
  659. if (!this.isEditable())
  660. {
  661. if (error != null)
  662. {
  663. error({message: mxResources.get('readOnly')});
  664. }
  665. else
  666. {
  667. throw new Error(mxResources.get('readOnly'));
  668. }
  669. }
  670. else if (!overwrite && this.invalidChecksum)
  671. {
  672. if (error != null)
  673. {
  674. error({message: mxResources.get('checksum')});
  675. }
  676. else
  677. {
  678. throw new Error(mxResources.get('checksum'));
  679. }
  680. }
  681. else
  682. {
  683. this.updateFileData();
  684. this.clearAutosave();
  685. }
  686. };
  687. /**
  688. * Translates this point by the given vector.
  689. *
  690. * @param {number} dx X-coordinate of the translation.
  691. * @param {number} dy Y-coordinate of the translation.
  692. */
  693. DrawioFile.prototype.updateFileData = function()
  694. {
  695. this.setData(this.ui.getFileData(null, null, null, null, null, null, null, null, this));
  696. };
  697. /**
  698. * Translates this point by the given vector.
  699. *
  700. * @param {number} dx X-coordinate of the translation.
  701. * @param {number} dy Y-coordinate of the translation.
  702. */
  703. DrawioFile.prototype.saveAs = function(filename, success, error) { };
  704. /**
  705. * Translates this point by the given vector.
  706. *
  707. * @param {number} dx X-coordinate of the translation.
  708. * @param {number} dy Y-coordinate of the translation.
  709. */
  710. DrawioFile.prototype.saveFile = function(title, revision, success, error) { };
  711. /**
  712. * Returns true if copy, export and print are not allowed for this file.
  713. */
  714. DrawioFile.prototype.getPublicUrl = function(fn)
  715. {
  716. fn(null);
  717. };
  718. /**
  719. * Returns true if copy, export and print are not allowed for this file.
  720. */
  721. DrawioFile.prototype.isRestricted = function()
  722. {
  723. return false;
  724. };
  725. /**
  726. * Translates this point by the given vector.
  727. *
  728. * @param {number} dx X-coordinate of the translation.
  729. * @param {number} dy Y-coordinate of the translation.
  730. */
  731. DrawioFile.prototype.isModified = function()
  732. {
  733. return this.modified;
  734. };
  735. /**
  736. * Translates this point by the given vector.
  737. *
  738. * @param {number} dx X-coordinate of the translation.
  739. * @param {number} dy Y-coordinate of the translation.
  740. */
  741. DrawioFile.prototype.setModified = function(value)
  742. {
  743. this.modified = value;
  744. };
  745. /**
  746. * Specifies if the autosave checkbox should be shown in the document
  747. * properties dialog. Default is false.
  748. */
  749. DrawioFile.prototype.isAutosaveOptional = function()
  750. {
  751. return false;
  752. };
  753. /**
  754. * Translates this point by the given vector.
  755. *
  756. * @param {number} dx X-coordinate of the translation.
  757. * @param {number} dy Y-coordinate of the translation.
  758. */
  759. DrawioFile.prototype.isAutosave = function()
  760. {
  761. return !this.inConflictState && this.ui.editor.autosave;
  762. };
  763. /**
  764. * Translates this point by the given vector.
  765. *
  766. * @param {number} dx X-coordinate of the translation.
  767. * @param {number} dy Y-coordinate of the translation.
  768. */
  769. DrawioFile.prototype.isRenamable = function()
  770. {
  771. return false;
  772. };
  773. /**
  774. * Translates this point by the given vector.
  775. *
  776. * @param {number} dx X-coordinate of the translation.
  777. * @param {number} dy Y-coordinate of the translation.
  778. */
  779. DrawioFile.prototype.rename = function(title, success, error) { };
  780. /**
  781. * Translates this point by the given vector.
  782. *
  783. * @param {number} dx X-coordinate of the translation.
  784. * @param {number} dy Y-coordinate of the translation.
  785. */
  786. DrawioFile.prototype.isMovable = function()
  787. {
  788. return false;
  789. };
  790. /**
  791. * Translates this point by the given vector.
  792. *
  793. * @param {number} dx X-coordinate of the translation.
  794. * @param {number} dy Y-coordinate of the translation.
  795. */
  796. DrawioFile.prototype.move = function(folderId, success, error) { };
  797. /**
  798. * Returns the hash of the file which consists of a prefix for the storage
  799. * type and the ID of the file.
  800. */
  801. DrawioFile.prototype.getHash = function()
  802. {
  803. return '';
  804. };
  805. /**
  806. * Returns the ID of the file.
  807. */
  808. DrawioFile.prototype.getId = function()
  809. {
  810. return '';
  811. };
  812. /**
  813. * Returns true if the file is editable.
  814. */
  815. DrawioFile.prototype.isEditable = function()
  816. {
  817. return !this.ui.editor.isChromelessView() || this.ui.editor.editable;
  818. };
  819. /**
  820. * Returns the location as a new object.
  821. * @type mx.Point
  822. */
  823. DrawioFile.prototype.getUi = function()
  824. {
  825. return this.ui;
  826. };
  827. /**
  828. * Returns the current title of the file.
  829. */
  830. DrawioFile.prototype.getTitle = function()
  831. {
  832. return '';
  833. };
  834. /**
  835. * Sets the current data of the file.
  836. */
  837. DrawioFile.prototype.setData = function(data)
  838. {
  839. this.data = data;
  840. };
  841. /**
  842. * Returns the current data of the file.
  843. */
  844. DrawioFile.prototype.getData = function()
  845. {
  846. return this.data;
  847. };
  848. /**
  849. * Opens this file in the editor.
  850. */
  851. DrawioFile.prototype.open = function()
  852. {
  853. this.stats.opened++;
  854. var data = this.getData();
  855. if (data != null)
  856. {
  857. this.ui.setFileData(data);
  858. // Updates shadow in case any page IDs have been updated
  859. // only if the file has not been modified and reopened
  860. if (!this.isModified())
  861. {
  862. this.shadowData = mxUtils.getXml(this.ui.getXmlFileData());
  863. this.shadowPages = null;
  864. }
  865. }
  866. this.installListeners();
  867. if (this.isSyncSupported())
  868. {
  869. this.startSync();
  870. }
  871. };
  872. /**
  873. * Hook for subclassers.
  874. */
  875. DrawioFile.prototype.isSyncSupported = function()
  876. {
  877. return false;
  878. };
  879. /**
  880. * Hook for subclassers.
  881. */
  882. DrawioFile.prototype.isRevisionHistorySupported = function()
  883. {
  884. return false;
  885. };
  886. /**
  887. * Hook for subclassers.
  888. */
  889. DrawioFile.prototype.getRevisions = function(success, error)
  890. {
  891. success(null);
  892. };
  893. /**
  894. * Hook for subclassers to get the latest descriptor of this file
  895. * and return it in the success handler.
  896. */
  897. DrawioFile.prototype.loadDescriptor = function(success, error)
  898. {
  899. success(null);
  900. };
  901. /**
  902. * Hook for subclassers to get the latest etag of this file
  903. * and return it in the success handler.
  904. */
  905. DrawioFile.prototype.loadPatchDescriptor = function(success, error)
  906. {
  907. this.loadDescriptor(mxUtils.bind(this, function(desc)
  908. {
  909. success(desc);
  910. }), error);
  911. };
  912. /**
  913. * Adds the listener for automatically saving the diagram for local changes.
  914. */
  915. DrawioFile.prototype.patchDescriptor = function(desc, patch)
  916. {
  917. this.setDescriptorEtag(desc, this.getDescriptorEtag(patch));
  918. };
  919. /**
  920. * Creates a starts the synchronization.
  921. */
  922. DrawioFile.prototype.startSync = function()
  923. {
  924. if ((DrawioFile.SYNC == 'auto' && urlParams['stealth'] != '1') &&
  925. (urlParams['rt'] == '1' || !this.ui.editor.chromeless ||
  926. this.ui.editor.editable))
  927. {
  928. if (this.sync == null)
  929. {
  930. this.sync = new DrawioFileSync(this);
  931. }
  932. this.sync.start();
  933. }
  934. };
  935. /**
  936. * Hook for subclassers to check if an error is a conflict.
  937. */
  938. DrawioFile.prototype.isConflict = function()
  939. {
  940. return false;
  941. };
  942. /**
  943. * Gets the channel ID for sync messages.
  944. */
  945. DrawioFile.prototype.getChannelId = function()
  946. {
  947. // Slash, space and plus replaced with underscore
  948. return Graph.compress(this.getHash()).replace(/[\/ +]/g, '_');
  949. };
  950. /**
  951. * Gets the channel ID from the given descriptor.
  952. */
  953. DrawioFile.prototype.getChannelKey = function(desc)
  954. {
  955. return null;
  956. };
  957. /**
  958. * Returns the current etag.
  959. */
  960. DrawioFile.prototype.getCurrentUser = function()
  961. {
  962. return null;
  963. };
  964. /**
  965. * Hook for subclassers to get the latest version of this file
  966. * and return it in the success handler.
  967. */
  968. DrawioFile.prototype.getLatestVersion = function(success, error)
  969. {
  970. success(null);
  971. };
  972. /**
  973. * Returns the last modified date of this file.
  974. */
  975. DrawioFile.prototype.getLastModifiedDate = function()
  976. {
  977. return new Date();
  978. };
  979. /**
  980. * Sets the current etag.
  981. */
  982. DrawioFile.prototype.setCurrentEtag = function(etag)
  983. {
  984. this.setDescriptorEtag(this.getDescriptor(), etag);
  985. };
  986. /**
  987. * Returns the current etag.
  988. */
  989. DrawioFile.prototype.getCurrentEtag = function()
  990. {
  991. return this.getDescriptorEtag(this.getDescriptor());
  992. };
  993. /**
  994. * Returns the descriptor from this file.
  995. */
  996. DrawioFile.prototype.getDescriptor = function()
  997. {
  998. return null;
  999. };
  1000. /**
  1001. * Sets the descriptor for this file.
  1002. */
  1003. DrawioFile.prototype.setDescriptor = function() { };
  1004. /**
  1005. * Updates the etag on the given descriptor.
  1006. */
  1007. DrawioFile.prototype.setDescriptorEtag = function(desc, etag) { };
  1008. /**
  1009. * Returns the etag from the given descriptor.
  1010. */
  1011. DrawioFile.prototype.getDescriptorEtag = function(desc)
  1012. {
  1013. return null;
  1014. };
  1015. /**
  1016. * Returns the secret from the given descriptor.
  1017. */
  1018. DrawioFile.prototype.getDescriptorSecret = function(desc)
  1019. {
  1020. return null;
  1021. };
  1022. /**
  1023. * Installs the change listener.
  1024. */
  1025. DrawioFile.prototype.installListeners = function()
  1026. {
  1027. if (this.changeListener == null)
  1028. {
  1029. this.changeListener = mxUtils.bind(this, function(sender, eventObject)
  1030. {
  1031. var edit = (eventObject != null) ? eventObject.getProperty('edit') : null;
  1032. if (this.changeListenerEnabled && this.isEditable() && (edit == null || !edit.ignoreEdit))
  1033. {
  1034. this.fileChanged();
  1035. }
  1036. });
  1037. this.ui.editor.graph.model.addListener(mxEvent.CHANGE, this.changeListener);
  1038. // Some options trigger autosave
  1039. this.ui.editor.graph.addListener('gridSizeChanged', this.changeListener);
  1040. this.ui.editor.graph.addListener('shadowVisibleChanged', this.changeListener);
  1041. this.ui.addListener('pageFormatChanged', this.changeListener);
  1042. this.ui.addListener('pageScaleChanged', this.changeListener);
  1043. this.ui.addListener('backgroundColorChanged', this.changeListener);
  1044. this.ui.addListener('backgroundImageChanged', this.changeListener);
  1045. this.ui.addListener('foldingEnabledChanged', this.changeListener);
  1046. this.ui.addListener('mathEnabledChanged', this.changeListener);
  1047. this.ui.addListener('gridEnabledChanged', this.changeListener);
  1048. this.ui.addListener('guidesEnabledChanged', this.changeListener);
  1049. this.ui.addListener('pageViewChanged', this.changeListener);
  1050. }
  1051. };
  1052. /**
  1053. * Returns the location as a new object.
  1054. * @type mx.Point
  1055. */
  1056. DrawioFile.prototype.addAllSavedStatus = function(status)
  1057. {
  1058. if (this.ui.statusContainer != null && this.ui.getCurrentFile() == this)
  1059. {
  1060. status = (status != null) ? status : mxUtils.htmlEntities(mxResources.get(this.allChangesSavedKey));
  1061. this.ui.editor.setStatus('<div title="'+ status + '">' + status + '</div>');
  1062. var links = this.ui.statusContainer.getElementsByTagName('div');
  1063. if (links.length > 0 && this.isRevisionHistorySupported())
  1064. {
  1065. links[0].style.cursor = 'pointer';
  1066. links[0].style.textDecoration = 'underline';
  1067. mxEvent.addListener(links[0], 'click', mxUtils.bind(this, function()
  1068. {
  1069. this.ui.actions.get('revisionHistory').funct();
  1070. }));
  1071. }
  1072. }
  1073. };
  1074. /**
  1075. * Adds the listener for automatically saving the diagram for local changes.
  1076. */
  1077. DrawioFile.prototype.addUnsavedStatus = function(err)
  1078. {
  1079. if (!this.inConflictState && this.ui.statusContainer != null && this.ui.getCurrentFile() == this)
  1080. {
  1081. if (err instanceof Error && err.message != null && err.message != '')
  1082. {
  1083. var status = mxUtils.htmlEntities(mxResources.get('unsavedChanges'));
  1084. this.ui.editor.setStatus('<div title="'+ status +
  1085. '" class="geStatusAlert" style="overflow:hidden;">' + status +
  1086. ' (' + mxUtils.htmlEntities(err.message) + ')</div>');
  1087. }
  1088. else
  1089. {
  1090. // FIXME: Handle multiple tabs
  1091. // if (this.ui.mode == null && urlParams['splash'] == '0')
  1092. // {
  1093. // try
  1094. // {
  1095. // this.ui.updateDraft();
  1096. // this.setModified(false);
  1097. // }
  1098. // catch (e)
  1099. // {
  1100. // // Keeps modified flag unchanged
  1101. // }
  1102. // }
  1103. var msg = this.getErrorMessage(err);
  1104. if (msg == null && this.lastSaved != null)
  1105. {
  1106. var str = this.ui.timeSince(new Date(this.lastSaved));
  1107. // Only show if more than a minute ago
  1108. if (str != null)
  1109. {
  1110. msg = mxResources.get('lastSaved', [str]);
  1111. }
  1112. }
  1113. if (msg != null && msg.length > 60)
  1114. {
  1115. msg = msg.substring(0, 60) + '...';
  1116. }
  1117. var status = mxUtils.htmlEntities(mxResources.get('unsavedChangesClickHereToSave')) +
  1118. ((msg != null && msg != '') ? ' (' + mxUtils.htmlEntities(msg) + ')' : '');
  1119. this.ui.editor.setStatus('<div title="'+ status +
  1120. '" class="geStatusAlert" style="cursor:pointer;overflow:hidden;">' +
  1121. status + '</div>');
  1122. // Installs click handler for saving
  1123. var links = this.ui.statusContainer.getElementsByTagName('div');
  1124. if (links != null && links.length > 0)
  1125. {
  1126. mxEvent.addListener(links[0], 'click', mxUtils.bind(this, function()
  1127. {
  1128. this.ui.actions.get((this.ui.mode == null || !this.isEditable()) ?
  1129. 'saveAs' : 'save').funct();
  1130. }));
  1131. }
  1132. else
  1133. {
  1134. var status = mxUtils.htmlEntities(mxResources.get('unsavedChanges'));
  1135. this.ui.editor.setStatus('<div title="'+ status +
  1136. '" class="geStatusAlert" style="overflow:hidden;">' + status +
  1137. ' (' + mxUtils.htmlEntities(err.message) + ')</div>');
  1138. }
  1139. }
  1140. }
  1141. };
  1142. /**
  1143. * Halts all timers and shows a conflict status message. The optional error
  1144. * handler is invoked first.
  1145. */
  1146. DrawioFile.prototype.addConflictStatus = function(fn, message)
  1147. {
  1148. if (this.invalidChecksum && message == null)
  1149. {
  1150. message = mxResources.get('checksum');
  1151. }
  1152. this.setConflictStatus(mxUtils.htmlEntities(mxResources.get('fileChangedSync')) +
  1153. ((message != null && message != '') ? ' (' + mxUtils.htmlEntities(message) + ')' : ''));
  1154. this.ui.spinner.stop();
  1155. this.clearAutosave();
  1156. var links = (this.ui.statusContainer != null) ? this.ui.statusContainer.getElementsByTagName('div') : null;
  1157. if (links != null && links.length > 0)
  1158. {
  1159. mxEvent.addListener(links[0], 'click', mxUtils.bind(this, function(evt)
  1160. {
  1161. if (mxEvent.getSource(evt).nodeName != 'IMG')
  1162. {
  1163. fn();
  1164. }
  1165. }));
  1166. }
  1167. else
  1168. {
  1169. this.ui.alert(mxUtils.htmlEntities(mxResources.get('fileChangedSync')), fn);
  1170. }
  1171. };
  1172. /**
  1173. * Halts all timers and shows a conflict status message. The optional error
  1174. * handler is invoked first.
  1175. */
  1176. DrawioFile.prototype.setConflictStatus = function(message)
  1177. {
  1178. this.ui.editor.setStatus('<div title="'+ message + '" class="geStatusAlert geBlink" style="cursor:pointer;overflow:hidden;">' +
  1179. message + ' <a href="https://desk.draw.io/support/solutions/articles/16000087947" target="_blank"><img border="0" ' +
  1180. 'style="margin-left:2px;cursor:help;opacity:0.5;width:16px;height:16px;" valign="bottom" src="' + Editor.helpImage +
  1181. '" style=""/></a></div>');
  1182. };
  1183. /**
  1184. * Shows a conflict dialog to the user.
  1185. */
  1186. DrawioFile.prototype.showRefreshDialog = function(success, error, message)
  1187. {
  1188. if (message == null)
  1189. {
  1190. message = mxResources.get('checksum');
  1191. }
  1192. if (this.ui.editor.isChromelessView() && !this.ui.editor.editable)
  1193. {
  1194. this.ui.alert(mxResources.get('fileChangedSync'), mxUtils.bind(this, function()
  1195. {
  1196. this.reloadFile(success, error);
  1197. }));
  1198. }
  1199. else
  1200. {
  1201. // Allows for escape key to be pressed while dialog is showing
  1202. this.addConflictStatus(mxUtils.bind(this, function()
  1203. {
  1204. this.showRefreshDialog(success, error);
  1205. }), message);
  1206. this.ui.showError(mxResources.get('error') + ' (' + message + ')',
  1207. mxResources.get('fileChangedSyncDialog'),
  1208. mxResources.get('makeCopy'), mxUtils.bind(this, function()
  1209. {
  1210. this.copyFile(success, error);
  1211. }), null, mxResources.get('synchronize'), mxUtils.bind(this, function()
  1212. {
  1213. this.reloadFile(success, error);
  1214. }), mxResources.get('cancel'), mxUtils.bind(this, function()
  1215. {
  1216. this.ui.hideDialog();
  1217. }), 360, 150);
  1218. }
  1219. };
  1220. /**
  1221. * Shows a dialog with no synchronize option.
  1222. */
  1223. DrawioFile.prototype.showCopyDialog = function(success, error, overwrite)
  1224. {
  1225. this.inConflictState = false;
  1226. this.invalidChecksum = false;
  1227. this.addUnsavedStatus();
  1228. this.ui.showError(mxResources.get('externalChanges'),
  1229. mxResources.get('fileChangedOverwriteDialog'),
  1230. mxResources.get('makeCopy'), mxUtils.bind(this, function()
  1231. {
  1232. this.copyFile(success, error);
  1233. }), null, mxResources.get('overwrite'), overwrite,
  1234. mxResources.get('cancel'), mxUtils.bind(this, function()
  1235. {
  1236. this.ui.hideDialog();
  1237. }), 360, 150);
  1238. };
  1239. /**
  1240. * Shows a conflict dialog to the user.
  1241. */
  1242. DrawioFile.prototype.showConflictDialog = function(overwrite, synchronize)
  1243. {
  1244. this.ui.showError(mxResources.get('externalChanges'),
  1245. mxResources.get('fileChangedSyncDialog'),
  1246. mxResources.get('overwrite'), overwrite, null,
  1247. mxResources.get('synchronize'), synchronize,
  1248. mxResources.get('cancel'), mxUtils.bind(this, function()
  1249. {
  1250. this.ui.hideDialog();
  1251. this.handleFileError(null, false);
  1252. }), 340, 150);
  1253. };
  1254. /**
  1255. * Checks if the client is authorized and calls the next step.
  1256. */
  1257. DrawioFile.prototype.redirectToNewApp = function(error)
  1258. {
  1259. this.ui.spinner.stop();
  1260. if (!this.redirectDialogShowing)
  1261. {
  1262. this.redirectDialogShowing = true;
  1263. var url = window.location.protocol + '//' + window.location.host + '/' + this.ui.getSearch(
  1264. ['create', 'title', 'mode', 'url', 'drive', 'splash', 'state']) + '#' + this.getHash();
  1265. var redirect = mxUtils.bind(this, function()
  1266. {
  1267. var fn = mxUtils.bind(this, function()
  1268. {
  1269. this.redirectDialogShowing = false;
  1270. if (window.location.href == url)
  1271. {
  1272. window.location.reload();
  1273. }
  1274. else
  1275. {
  1276. window.location.href = url;
  1277. }
  1278. });
  1279. if (error == null && this.isModified())
  1280. {
  1281. this.ui.confirm(mxResources.get('allChangesLost'), mxUtils.bind(this, function()
  1282. {
  1283. this.redirectDialogShowing = false;
  1284. }), fn, mxResources.get('cancel'), mxResources.get('discardChanges'));
  1285. }
  1286. else
  1287. {
  1288. fn();
  1289. }
  1290. });
  1291. if (error != null)
  1292. {
  1293. if (this.isModified())
  1294. {
  1295. this.ui.confirm(mxResources.get('redirectToNewApp'), mxUtils.bind(this, function()
  1296. {
  1297. this.redirectDialogShowing = false;
  1298. error();
  1299. }), redirect, mxResources.get('cancel'), mxResources.get('discardChanges'));
  1300. }
  1301. else
  1302. {
  1303. this.ui.confirm(mxResources.get('redirectToNewApp'), redirect, mxUtils.bind(this, function()
  1304. {
  1305. this.redirectDialogShowing = false;
  1306. error();
  1307. }));
  1308. }
  1309. }
  1310. else
  1311. {
  1312. this.ui.alert(mxResources.get('redirectToNewApp'), redirect);
  1313. }
  1314. }
  1315. };
  1316. /**
  1317. * Adds the listener for automatically saving the diagram for local changes.
  1318. */
  1319. DrawioFile.prototype.handleFileSuccess = function(saved)
  1320. {
  1321. this.ui.spinner.stop();
  1322. if (this.ui.getCurrentFile() == this)
  1323. {
  1324. if (this.isModified())
  1325. {
  1326. this.fileChanged();
  1327. }
  1328. else if (saved)
  1329. {
  1330. this.addAllSavedStatus();
  1331. if (this.sync != null)
  1332. {
  1333. this.sync.resetUpdateStatusThread();
  1334. if (this.sync.remoteFileChanged)
  1335. {
  1336. this.sync.remoteFileChanged = false;
  1337. this.sync.fileChangedNotify();
  1338. }
  1339. }
  1340. }
  1341. else
  1342. {
  1343. this.ui.editor.setStatus('');
  1344. }
  1345. }
  1346. };
  1347. /**
  1348. * Adds the listener for automatically saving the diagram for local changes.
  1349. */
  1350. DrawioFile.prototype.handleFileError = function(err, manual)
  1351. {
  1352. this.ui.spinner.stop();
  1353. if (this.ui.getCurrentFile() == this)
  1354. {
  1355. if (this.inConflictState)
  1356. {
  1357. this.handleConflictError(err, manual);
  1358. }
  1359. else
  1360. {
  1361. if (this.isModified())
  1362. {
  1363. this.addUnsavedStatus(err);
  1364. }
  1365. if (manual)
  1366. {
  1367. this.ui.handleError(err, (err != null) ? mxResources.get('errorSavingFile') : null);
  1368. }
  1369. else if (!this.isModified())
  1370. {
  1371. var msg = (err != null) ? ((err.error != null) ? err.error.message : err.message) : null;
  1372. if (msg != null && msg.length > 60)
  1373. {
  1374. msg = msg.substring(0, 60) + '...';
  1375. }
  1376. this.ui.editor.setStatus('<div class="geStatusAlert" style="cursor:pointer;overflow:hidden;">' +
  1377. mxUtils.htmlEntities(mxResources.get('error')) +
  1378. ((msg != null) ? ' (' + mxUtils.htmlEntities(msg) + ')' : '') + '</div>');
  1379. }
  1380. }
  1381. }
  1382. };
  1383. /**
  1384. * Adds the listener for automatically saving the diagram for local changes.
  1385. */
  1386. DrawioFile.prototype.handleConflictError = function(err, manual)
  1387. {
  1388. var success = mxUtils.bind(this, function()
  1389. {
  1390. this.handleFileSuccess(true);
  1391. });
  1392. var error = mxUtils.bind(this, function(err2)
  1393. {
  1394. this.handleFileError(err2, true);
  1395. });
  1396. var overwrite = mxUtils.bind(this, function()
  1397. {
  1398. if (this.ui.spinner.spin(document.body, mxResources.get('saving')))
  1399. {
  1400. this.ui.editor.setStatus('');
  1401. this.save(true, success, error, null, true, (this.constructor ==
  1402. GitHubFile && err != null) ? err.commitMessage : null)
  1403. }
  1404. });
  1405. var synchronize = mxUtils.bind(this, function()
  1406. {
  1407. if (this.ui.spinner.spin(document.body, mxResources.get('updatingDocument')))
  1408. {
  1409. this.synchronizeFile(mxUtils.bind(this, function()
  1410. {
  1411. this.ui.spinner.stop();
  1412. if (this.ui.spinner.spin(document.body, mxResources.get('saving')))
  1413. {
  1414. this.save(true, success, error, null, null, (this.constructor ==
  1415. GitHubFile && err != null) ? err.commitMessage : null)
  1416. }
  1417. }), error);
  1418. }
  1419. })
  1420. if (DrawioFile.SYNC == 'none')
  1421. {
  1422. this.showCopyDialog(success, error, overwrite);
  1423. }
  1424. else if (this.invalidChecksum)
  1425. {
  1426. this.showRefreshDialog(success, error, this.getErrorMessage(err));
  1427. }
  1428. else if (manual)
  1429. {
  1430. this.showConflictDialog(overwrite, synchronize);
  1431. }
  1432. else
  1433. {
  1434. this.addConflictStatus(mxUtils.bind(this, function()
  1435. {
  1436. this.ui.editor.setStatus(mxUtils.htmlEntities(
  1437. mxResources.get('updatingDocument')));
  1438. this.synchronizeFile(success, error);
  1439. }), this.getErrorMessage(err));
  1440. }
  1441. };
  1442. /**
  1443. * Adds the listener for automatically saving the diagram for local changes.
  1444. */
  1445. DrawioFile.prototype.getErrorMessage = function(err)
  1446. {
  1447. return (err != null) ? ((err.error != null) ? err.error.message : err.message) : null
  1448. };
  1449. /**
  1450. * Adds the listener for automatically saving the diagram for local changes.
  1451. */
  1452. DrawioFile.prototype.fileChanged = function()
  1453. {
  1454. this.setModified(true);
  1455. if (this.isAutosave())
  1456. {
  1457. this.addAllSavedStatus(mxUtils.htmlEntities(mxResources.get('saving')) + '...');
  1458. this.autosave(this.autosaveDelay, this.maxAutosaveDelay, mxUtils.bind(this, function(resp)
  1459. {
  1460. // Does not update status if another autosave was scheduled
  1461. if (this.autosaveThread == null)
  1462. {
  1463. this.handleFileSuccess(true);
  1464. }
  1465. }), mxUtils.bind(this, function(err)
  1466. {
  1467. this.handleFileError(err);
  1468. }));
  1469. }
  1470. else if ((!this.isAutosaveOptional() || !this.ui.editor.autosave) &&
  1471. !this.inConflictState)
  1472. {
  1473. this.addUnsavedStatus();
  1474. }
  1475. };
  1476. /**
  1477. * Invokes sync and updates shadow document.
  1478. */
  1479. DrawioFile.prototype.fileSaved = function(savedData, lastDesc, success, error)
  1480. {
  1481. this.lastSaved = new Date();
  1482. try
  1483. {
  1484. this.stats.saved++;
  1485. this.inConflictState = false;
  1486. this.invalidChecksum = false;
  1487. if (this.sync == null)
  1488. {
  1489. this.shadowData = savedData;
  1490. this.shadowPages = null;
  1491. if (success != null)
  1492. {
  1493. success();
  1494. }
  1495. }
  1496. else
  1497. {
  1498. this.sync.fileSaved(this.ui.getPagesForNode(
  1499. mxUtils.parseXml(savedData).documentElement),
  1500. lastDesc, success, error, savedData);
  1501. }
  1502. }
  1503. catch (e)
  1504. {
  1505. this.inConflictState = true;
  1506. this.invalidChecksum = true;
  1507. this.descriptorChanged();
  1508. if (error != null)
  1509. {
  1510. error(e);
  1511. }
  1512. try
  1513. {
  1514. if (this.errorReportsEnabled)
  1515. {
  1516. this.sendErrorReport('Error in fileSaved', null, e);
  1517. }
  1518. else
  1519. {
  1520. var user = this.getCurrentUser();
  1521. var uid = (user != null) ? user.id : 'unknown';
  1522. EditorUi.logError('Error in fileSaved', null,
  1523. this.getMode() + '.' + this.getId(),
  1524. uid, e);
  1525. }
  1526. }
  1527. catch (e2)
  1528. {
  1529. // ignore
  1530. }
  1531. }
  1532. };
  1533. /**
  1534. * Adds the listener for automatically saving the diagram for local changes.
  1535. */
  1536. DrawioFile.prototype.autosave = function(delay, maxDelay, success, error)
  1537. {
  1538. if (this.lastAutosave == null)
  1539. {
  1540. this.lastAutosave = new Date().getTime();
  1541. }
  1542. var tmp = (new Date().getTime() - this.lastAutosave < maxDelay) ? delay : 0;
  1543. this.clearAutosave();
  1544. // Starts new timer or executes immediately if not unsaved for maxDelay
  1545. var thread = window.setTimeout(mxUtils.bind(this, function()
  1546. {
  1547. this.lastAutosave = null;
  1548. if (this.autosaveThread == thread)
  1549. {
  1550. this.autosaveThread = null;
  1551. }
  1552. // Workaround for duplicate save if UI is blocking
  1553. // after save while pending autosave triggers
  1554. if (this.isModified() && this.isAutosaveNow())
  1555. {
  1556. var rev = this.isAutosaveRevision();
  1557. if (rev)
  1558. {
  1559. this.lastAutosaveRevision = new Date().getTime();
  1560. }
  1561. this.save(rev, mxUtils.bind(this, function(resp)
  1562. {
  1563. this.autosaveCompleted();
  1564. if (success != null)
  1565. {
  1566. success(resp);
  1567. }
  1568. }), mxUtils.bind(this, function(resp)
  1569. {
  1570. if (error != null)
  1571. {
  1572. error(resp);
  1573. }
  1574. }));
  1575. }
  1576. else
  1577. {
  1578. if (!this.isModified())
  1579. {
  1580. this.ui.editor.setStatus('');
  1581. }
  1582. if (success != null)
  1583. {
  1584. success(null);
  1585. }
  1586. }
  1587. }), tmp);
  1588. this.autosaveThread = thread;
  1589. };
  1590. /**
  1591. * Returns true if an autosave is required at the time of execution.
  1592. * This implementation returns true.
  1593. */
  1594. DrawioFile.prototype.isAutosaveNow = function()
  1595. {
  1596. return true;
  1597. };
  1598. /**
  1599. * Hooks for subclassers after the autosave has completed.
  1600. */
  1601. DrawioFile.prototype.autosaveCompleted = function() { };
  1602. /**
  1603. * Adds the listener for automatically saving the diagram for local changes.
  1604. */
  1605. DrawioFile.prototype.clearAutosave = function()
  1606. {
  1607. if (this.autosaveThread != null)
  1608. {
  1609. window.clearTimeout(this.autosaveThread);
  1610. this.autosaveThread = null;
  1611. }
  1612. };
  1613. /**
  1614. * Returns the location as a new object.
  1615. * @type mx.Point
  1616. */
  1617. DrawioFile.prototype.isAutosaveRevision = function()
  1618. {
  1619. var now = new Date().getTime();
  1620. return (this.lastAutosaveRevision == null) || (now - this.lastAutosaveRevision) > this.maxAutosaveRevisionDelay;
  1621. };
  1622. /**
  1623. * Translates this point by the given vector.
  1624. *
  1625. * @param {number} dx X-coordinate of the translation.
  1626. * @param {number} dy Y-coordinate of the translation.
  1627. */
  1628. DrawioFile.prototype.descriptorChanged = function()
  1629. {
  1630. this.fireEvent(new mxEventObject('descriptorChanged'));
  1631. };
  1632. /**
  1633. * Translates this point by the given vector.
  1634. *
  1635. * @param {number} dx X-coordinate of the translation.
  1636. * @param {number} dy Y-coordinate of the translation.
  1637. */
  1638. DrawioFile.prototype.contentChanged = function()
  1639. {
  1640. this.fireEvent(new mxEventObject('contentChanged'));
  1641. };
  1642. /**
  1643. * Returns the location as a new object.
  1644. */
  1645. DrawioFile.prototype.close = function(unloading)
  1646. {
  1647. this.updateFileData();
  1648. this.stats.closed++;
  1649. if (this.isAutosave() && this.isModified())
  1650. {
  1651. this.save(this.isAutosaveRevision(), null, null, unloading);
  1652. }
  1653. this.destroy();
  1654. };
  1655. /**
  1656. * Returns the location as a new object.
  1657. */
  1658. DrawioFile.prototype.hasSameExtension = function(title, newTitle)
  1659. {
  1660. if (title != null && newTitle != null)
  1661. {
  1662. var dot = title.lastIndexOf('.');
  1663. var ext = (dot > 0) ? title.substring(dot) : '';
  1664. dot = newTitle.lastIndexOf('.');
  1665. return ext === ((dot > 0) ? newTitle.substring(dot) : '');
  1666. }
  1667. return title == newTitle;
  1668. };
  1669. /**
  1670. * Removes the change listener.
  1671. */
  1672. DrawioFile.prototype.removeListeners = function()
  1673. {
  1674. if (this.changeListener != null)
  1675. {
  1676. this.ui.editor.graph.model.removeListener(this.changeListener);
  1677. this.ui.editor.graph.removeListener(this.changeListener);
  1678. this.ui.removeListener(this.changeListener);
  1679. this.changeListener = null;
  1680. }
  1681. };
  1682. /**
  1683. * Stops any pending autosaves and removes all listeners.
  1684. */
  1685. DrawioFile.prototype.destroy = function()
  1686. {
  1687. this.stats.destroyed++;
  1688. try
  1689. {
  1690. if (!this.ui.isOffline() && this.reportEnabled &&
  1691. (DrawioFile.SYNC == 'auto' ||
  1692. DrawioFile.SYNC == 'manual'))
  1693. {
  1694. var user = this.getCurrentUser();
  1695. var uid = (user != null) ? user.id : 'unknown';
  1696. EditorUi.logEvent({category: 'RT-END-' + DrawioFile.SYNC,
  1697. action: 'file-' + this.getId() +
  1698. '-mode-' + this.getMode() +
  1699. '-size-' + this.getSize() +
  1700. '-user-' + uid +
  1701. ((this.sync != null) ? ('-client-' + this.sync.clientId ) : ''),
  1702. label: this.stats});
  1703. }
  1704. }
  1705. catch (e)
  1706. {
  1707. // ignore
  1708. }
  1709. this.clearAutosave();
  1710. this.removeListeners();
  1711. if (this.sync != null)
  1712. {
  1713. this.sync.destroy();
  1714. this.sync = null;
  1715. }
  1716. };