DrawioFile.js 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907
  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. this.ui = ui;
  9. this.setData(data || '');
  10. this.initialData = this.getData();
  11. this.created = new Date().getTime();
  12. // Creates the stats object
  13. this.stats = {
  14. opened: 0, /* number of calls to open */
  15. merged: 0, /* number of calls to merge */
  16. fileMerged: 0, /* number of calls to mergeFile */
  17. fileReloaded: 0, /* number of calls to mergeFile */
  18. conflicts: 0, /* number of write conflicts when saving a file */
  19. timeouts: 0, /* number of time we have given up to retry after a write conflict */
  20. saved: 0, /* number of calls to fileSaved */
  21. closed: 0, /* number of calls to close */
  22. destroyed: 0, /* number of calls to close */
  23. joined: 0, /* number of join messages received */
  24. checksumErrors: 0, /* number of checksum errors */
  25. bytesSent: 0, /* number of bytes send in messages */
  26. bytesReceived: 0, /* number of bytes received in messages */
  27. msgSent: 0, /* number of messages sent */
  28. msgReceived: 0, /* number of messages received */
  29. cacheHits: 0, /* number of times the cache returned patches */
  30. cacheMiss: 0, /* number of times we have missed a cache entry */
  31. cacheFail: 0 /* number of times we have failed to read the cache */
  32. };
  33. };
  34. /**
  35. * Global switch for realtime collaboration type to use sync URL parameter
  36. * with the following possible values:
  37. *
  38. * - none: overwrite
  39. * - manual: manual sync
  40. * - auto: automatic sync
  41. */
  42. DrawioFile.SYNC = urlParams['sync'] || 'auto';
  43. /**
  44. * Specifies if last write wins should be used for values and styles.
  45. */
  46. DrawioFile.LAST_WRITE_WINS = true;
  47. /**
  48. * Specifies if export is restricted.
  49. */
  50. DrawioFile.RESTRICT_EXPORT = false;
  51. // Extends mxEventSource
  52. mxUtils.extend(DrawioFile, mxEventSource);
  53. /**
  54. * Specifies the resource key for all changes saved status message.
  55. */
  56. DrawioFile.prototype.allChangesSavedKey = 'allChangesSaved';
  57. /**
  58. * Specifies the resource key for saving spinner.
  59. */
  60. DrawioFile.prototype.savingSpinnerKey = 'saving';
  61. /**
  62. * Specifies the resource key for saving status message.
  63. */
  64. DrawioFile.prototype.savingStatusKey = 'saving';
  65. /**
  66. * Specifies the delay between the last change and the autosave.
  67. */
  68. DrawioFile.prototype.autosaveDelay = 1500;
  69. /**
  70. * Specifies the maximum delay before an autosave is forced even if the graph
  71. * is being changed.
  72. */
  73. DrawioFile.prototype.maxAutosaveDelay = 30000;
  74. /**
  75. * Specifies the delay for loading the file after an optimistic sync message.
  76. * This should be the delay for the file to be saved minus the delay for the
  77. * sync message to travel.
  78. */
  79. DrawioFile.prototype.optimisticSyncDelay = 300;
  80. /**
  81. * Contains the thread for the next autosave.
  82. */
  83. DrawioFile.prototype.autosaveThread = null;
  84. /**
  85. * Stores the time stamp for the last autosave.
  86. */
  87. DrawioFile.prototype.lastAutosave = null;
  88. /**
  89. * Stores the time stamp for the last autosave.
  90. */
  91. DrawioFile.prototype.lastSaved = null;
  92. /**
  93. * Stores the time stamp for the last autosave.
  94. */
  95. DrawioFile.prototype.lastChanged = null;
  96. /**
  97. * Stores the time stamp when the file was opened.
  98. */
  99. DrawioFile.prototype.opened = null;
  100. /**
  101. * Stores the modified state.
  102. */
  103. DrawioFile.prototype.modified = false;
  104. /**
  105. * Stores a shadow of the modified state.
  106. */
  107. DrawioFile.prototype.shadowModified = false;
  108. /**
  109. * Holds a copy of the current file data.
  110. */
  111. DrawioFile.prototype.data = null;
  112. /**
  113. * Holds a copy of the parsed last saved file data.
  114. */
  115. DrawioFile.prototype.shadowPages = null;
  116. /**
  117. * Specifies if the graph change listener is enabled. Default is true.
  118. */
  119. DrawioFile.prototype.changeListenerEnabled = true;
  120. /**
  121. * Sets the delay for autosave in milliseconds. Default is 1500.
  122. */
  123. DrawioFile.prototype.lastAutosaveRevision = null;
  124. /**
  125. * Sets the delay between revisions when using autosave. Default is 300000
  126. * ie 5 mins. Set this to 0 to create a revision on every autosave.
  127. */
  128. DrawioFile.prototype.maxAutosaveRevisionDelay = 300000;
  129. /**
  130. * Specifies if notify events should be ignored.
  131. */
  132. DrawioFile.prototype.inConflictState = false;
  133. /**
  134. * Specifies if notify events should be ignored.
  135. */
  136. DrawioFile.prototype.invalidChecksum = false;
  137. /**
  138. * Specifies if stats should be sent.
  139. */
  140. DrawioFile.prototype.ageStart = null;
  141. /**
  142. * Specifies if notify events should be ignored.
  143. */
  144. DrawioFile.prototype.getSize = function()
  145. {
  146. return (this.data != null) ? this.data.length : 0;
  147. };
  148. /**
  149. * Returns the shadow pages. If they do not exist they are created.
  150. */
  151. DrawioFile.prototype.getShadowPages = function()
  152. {
  153. if (this.shadowPages == null)
  154. {
  155. this.shadowPages = this.ui.getPagesForXml(this.initialData);
  156. }
  157. return this.shadowPages;
  158. };
  159. /**
  160. * Sets the shadow pages.
  161. */
  162. DrawioFile.prototype.setShadowPages = function(pages)
  163. {
  164. this.shadowPages = pages;
  165. };
  166. /**
  167. * Adds the listener for automatically saving the diagram for local changes.
  168. */
  169. DrawioFile.prototype.synchronizeFile = function(success, error)
  170. {
  171. if (this.savingFile)
  172. {
  173. if (error != null)
  174. {
  175. error({message: mxResources.get('busy')});
  176. }
  177. }
  178. else
  179. {
  180. var acceptResponse = true;
  181. var timeoutThread = window.setTimeout(mxUtils.bind(this, function()
  182. {
  183. acceptResponse = false;
  184. if (error != null)
  185. {
  186. error({code: App.ERROR_TIMEOUT, message: mxResources.get('timeout'), retry: mxUtils.bind(this, function()
  187. {
  188. this.synchronizeFile(success, error);
  189. })});
  190. }
  191. }), this.ui.timeout);
  192. var errorWrapper = mxUtils.bind(this, function(e)
  193. {
  194. if (acceptResponse)
  195. {
  196. window.clearTimeout(timeoutThread);
  197. if (error != null)
  198. {
  199. error(e);
  200. }
  201. }
  202. });
  203. var abort = mxUtils.bind(this, function()
  204. {
  205. return !acceptResponse;
  206. });
  207. if (this.sync != null)
  208. {
  209. this.sync.fileChanged(mxUtils.bind(this, function(patched)
  210. {
  211. if (acceptResponse)
  212. {
  213. window.clearTimeout(timeoutThread);
  214. this.sync.cleanup(success, error, patched);
  215. }
  216. }), errorWrapper, abort);
  217. }
  218. else
  219. {
  220. this.updateFile(mxUtils.bind(this, function()
  221. {
  222. if (acceptResponse)
  223. {
  224. window.clearTimeout(timeoutThread);
  225. if (success != null)
  226. {
  227. success();
  228. }
  229. }
  230. }), errorWrapper, abort);
  231. }
  232. }
  233. };
  234. /**
  235. * Adds the listener for automatically saving the diagram for local changes.
  236. * Immediate is passed through to scheduleCleanup.
  237. */
  238. DrawioFile.prototype.updateFile = function(success, error, abort, shadow, immediate)
  239. {
  240. if (abort == null || !abort())
  241. {
  242. EditorUi.debug('DrawioFile.updateFile', [this],
  243. 'immediate', immediate, 'invalidChecksum',
  244. this.invalidChecksum);
  245. if (this.ui.getCurrentFile() != this || this.invalidChecksum)
  246. {
  247. if (error != null)
  248. {
  249. error();
  250. }
  251. }
  252. else
  253. {
  254. this.getLatestVersion(mxUtils.bind(this, function(latestFile)
  255. {
  256. try
  257. {
  258. if (abort == null || !abort())
  259. {
  260. EditorUi.debug('DrawioFile.updateFile', [this],
  261. 'invalidChecksum', this.invalidChecksum,
  262. 'latestFile', [latestFile]);
  263. if (this.ui.getCurrentFile() != this || this.invalidChecksum)
  264. {
  265. if (error != null)
  266. {
  267. error();
  268. }
  269. }
  270. else
  271. {
  272. if (latestFile != null)
  273. {
  274. this.mergeFile(latestFile, success, error,
  275. shadow, immediate);
  276. }
  277. else
  278. {
  279. this.reloadFile(success, error);
  280. }
  281. }
  282. }
  283. }
  284. catch (e)
  285. {
  286. if (error != null)
  287. {
  288. error(e);
  289. }
  290. }
  291. }), error);
  292. }
  293. }
  294. };
  295. /**
  296. * Adds the listener for automatically saving the diagram for local changes.
  297. * Immediate is passed through to scheduleCleanup.
  298. */
  299. DrawioFile.prototype.mergeFile = function(file, success, error, diffShadow, immediate)
  300. {
  301. var reportError = true;
  302. try
  303. {
  304. // Loads new document as shadow document
  305. var pages = file.getShadowPages();
  306. if (pages != null && pages.length > 0)
  307. {
  308. // Patches the current document
  309. var shadow = this.getShadowPages();
  310. var patches = [this.ui.diffPages((diffShadow != null) ?
  311. diffShadow : shadow, pages)];
  312. var ignored = this.ignorePatches(patches);
  313. if (!ignored)
  314. {
  315. try
  316. {
  317. this.stats.fileMerged++;
  318. if (this.sync != null)
  319. {
  320. this.sync.sendLocalChanges();
  321. }
  322. // Computes local changes
  323. var changes = (!this.isModified()) ? null :
  324. this.ui.diffPages(shadow, (this.isRealtime()) ?
  325. this.ownPages : this.ui.pages);
  326. // Patching previous shadow to verify checksum
  327. var patchedDetails = {};
  328. var currentDetails = {};
  329. var patched = this.ui.patchPages(this.ui.clonePages(shadow), patches[0]);
  330. var checksum = this.ui.getHashValueForPages(patched, patchedDetails);
  331. var current = this.ui.getHashValueForPages(pages, currentDetails);
  332. EditorUi.debug('File.mergeFile', [this], 'file', [file], 'ui', this.ui.pages,
  333. 'shadow', shadow, 'pages', pages, 'patched', patched, 'patches', patches,
  334. 'changes', changes, 'checksum', checksum, 'current', current, 'valid',
  335. checksum == current, 'from', this.getCurrentRevisionId(), 'to',
  336. file.getCurrentRevisionId(), 'modified', this.isModified(),
  337. 'immediate', immediate);
  338. if (checksum != null && checksum != current)
  339. {
  340. this.checksumError(error, patches, null, null, 'mergeFile',
  341. checksum, current, file.getCurrentRevisionId());
  342. // Abnormal termination
  343. return;
  344. }
  345. else
  346. {
  347. this.setShadowPages(pages);
  348. // Patches the realtime document
  349. if (this.sync != null)
  350. {
  351. var pending = this.sync.patchRealtime(
  352. patches, (DrawioFile.LAST_WRITE_WINS) ?
  353. changes : null, null, immediate);
  354. if (pending != null && !mxUtils.isEmptyObject(pending))
  355. {
  356. patches.push(pending);
  357. }
  358. }
  359. // Patches the current document
  360. this.patch(patches, (DrawioFile.LAST_WRITE_WINS) ?
  361. changes : null);
  362. }
  363. this.invalidChecksum = false;
  364. this.inConflictState = false;
  365. this.setDescriptor(file.getDescriptor());
  366. this.descriptorChanged();
  367. if (success != null)
  368. {
  369. success();
  370. }
  371. }
  372. catch (e)
  373. {
  374. this.inConflictState = true;
  375. this.invalidChecksum = true;
  376. this.descriptorChanged();
  377. if (error != null)
  378. {
  379. error(e);
  380. }
  381. try
  382. {
  383. if (reportError)
  384. {
  385. var user = this.getCurrentUser();
  386. var uid = (user != null) ? user.id : 'unknown';
  387. EditorUi.logError('Error in mergeFile', null,
  388. this.getMode() + '.' + this.getId(),
  389. uid, e);
  390. }
  391. }
  392. catch (e2)
  393. {
  394. // ignore
  395. }
  396. }
  397. }
  398. else
  399. {
  400. this.invalidChecksum = false;
  401. this.inConflictState = false;
  402. this.setDescriptor(file.getDescriptor());
  403. this.descriptorChanged();
  404. EditorUi.debug('File.mergeFile', [this],
  405. 'file', [file], 'ignored', ignored);
  406. if (success != null)
  407. {
  408. success();
  409. }
  410. }
  411. }
  412. else
  413. {
  414. reportError = false;
  415. throw new Error(mxResources.get('notADiagramFile'));
  416. }
  417. }
  418. catch (e)
  419. {
  420. if (error != null)
  421. {
  422. error(e);
  423. }
  424. }
  425. };
  426. /**
  427. * Adds the listener for automatically saving the diagram for local changes.
  428. */
  429. DrawioFile.prototype.getAnonymizedXmlForPages = function(pages)
  430. {
  431. var enc = new mxCodec(mxUtils.createXmlDocument());
  432. var file = enc.document.createElement('mxfile');
  433. if (pages != null)
  434. {
  435. for (var i = 0; i < pages.length; i++)
  436. {
  437. var temp = enc.encode(new mxGraphModel(pages[i].root));
  438. if (urlParams['dev'] != '1')
  439. {
  440. temp = this.ui.anonymizeNode(temp, true);
  441. }
  442. temp.setAttribute('id', pages[i].getId());
  443. if (pages[i].viewState)
  444. {
  445. this.ui.editor.graph.saveViewState(pages[i].viewState, temp, true);
  446. }
  447. file.appendChild(temp);
  448. }
  449. }
  450. return mxUtils.getPrettyXml(file);
  451. };
  452. /**
  453. * Adds the listener for automatically saving the diagram for local changes.
  454. */
  455. DrawioFile.prototype.compressReportData = function(data, limit, max)
  456. {
  457. limit = (limit != null) ? limit : 10000;
  458. if (max != null && data != null && data.length > max)
  459. {
  460. data = data.substring(0, max) + '[...]';
  461. }
  462. else if (data != null && data.length > limit)
  463. {
  464. data = Graph.compress(data) + '\n';
  465. }
  466. return data;
  467. };
  468. /**
  469. * Adds the listener for automatically saving the diagram for local changes.
  470. */
  471. DrawioFile.prototype.checksumError = function(fn, patches, details, etag, functionName, checksum, current, rev)
  472. {
  473. this.stats.checksumErrors++;
  474. this.inConflictState = true;
  475. this.invalidChecksum = true;
  476. this.descriptorChanged();
  477. if (this.sync != null)
  478. {
  479. this.sync.updateOnlineState();
  480. }
  481. if (fn != null)
  482. {
  483. fn();
  484. }
  485. try
  486. {
  487. var user = this.getCurrentUser();
  488. var uid = (user != null) ? user.id : 'unknown';
  489. var id = (this.getId() != '') ? this.getId() :
  490. ('(' + this.ui.hashValue(this.getTitle()) + ')');
  491. var bytes = JSON.stringify(patches).length;
  492. var limit = 1000;
  493. var data = null;
  494. if (patches != null && bytes < limit)
  495. {
  496. for (var i = 0; i < patches.length; i++)
  497. {
  498. this.ui.anonymizePatch(patches[i]);
  499. }
  500. data = JSON.stringify(patches);
  501. if (data != null && data.length < limit)
  502. {
  503. data = Graph.compress(data);
  504. }
  505. else
  506. {
  507. data = null;
  508. }
  509. }
  510. this.getLatestVersion(mxUtils.bind(this, function(latestFile)
  511. {
  512. // Logs checksum error for file
  513. try
  514. {
  515. var type = (data != null) ? 'report' : 'error';
  516. var latest = this.ui.getHashValueForPages(latestFile.getShadowPages());
  517. var latestVersion = 'unknown';
  518. var latestAgent = 'unknown';
  519. var latestType = 'unknown';
  520. try
  521. {
  522. var node = (latestFile.initialData != null && latestFile.initialData.length > 0) ?
  523. mxUtils.parseXml(latestFile.initialData).documentElement : null;
  524. if (node != null)
  525. {
  526. if (node.getAttribute('version') != null)
  527. {
  528. latestVersion = node.getAttribute('version');
  529. }
  530. if (node.getAttribute('agent') != null)
  531. {
  532. latestAgent = node.getAttribute('agent');
  533. }
  534. if (node.getAttribute('type') != null)
  535. {
  536. latestType = node.getAttribute('type');
  537. }
  538. }
  539. }
  540. catch (e)
  541. {
  542. // ignore
  543. }
  544. EditorUi.logError('Checksum ' + type + ' in ' + functionName,
  545. null, this.getMode() + '.' + id,
  546. 'user_' + uid + ((this.sync != null) ?
  547. '-client_' + this.sync.clientId : '-nosync') +
  548. '-bytes_' + bytes + '-patches_' + patches.length +
  549. ((data != null) ? ('-json_' + data) : '') +
  550. '-size_' + this.getSize() +
  551. ((checksum != null) ? ('-expected_' + checksum) : '') +
  552. ((current != null) ? ('-current_' + current) : '') +
  553. ((rev != null) ? ('-rev_' + this.ui.hashValue(rev)) : '') +
  554. ((latest != null) ? ('-latest_' + latest) : '') +
  555. '-latestRev_' + this.ui.hashValue(
  556. latestFile.getCurrentRevisionId()) +
  557. ('-latestVersion_' + latestVersion) +
  558. ('-latestAgent_' + latestAgent) +
  559. ('-latestType_' + latestType));
  560. EditorUi.logEvent({category: 'CHECKSUM-ERROR-SYNC-FILE-' + id,
  561. action: functionName, label: 'user_' + uid + ((this.sync != null) ?
  562. '-client_' + this.sync.clientId : '-nosync') +
  563. '-bytes_' + bytes + '-patches_' + patches.length +
  564. '-size_' + this.getSize()});
  565. }
  566. catch (e)
  567. {
  568. // ignore
  569. }
  570. }), function() {});
  571. }
  572. catch (e)
  573. {
  574. // ignore
  575. }
  576. };
  577. /**
  578. * Adds the listener for automatically saving the diagram for local changes.
  579. */
  580. DrawioFile.prototype.sendErrorReport = function(title, details, error, max)
  581. {
  582. try
  583. {
  584. var shadow = this.compressReportData(
  585. this.getAnonymizedXmlForPages(
  586. this.getShadowPages()), 25000);
  587. var data = this.compressReportData(
  588. this.getAnonymizedXmlForPages(
  589. this.ui.pages), 25000);
  590. var user = this.getCurrentUser();
  591. var uid = (user != null) ? this.ui.hashValue(user.id) : 'unknown';
  592. var cid = (this.sync != null) ? '-client_' + this.sync.clientId : '-nosync';
  593. var filename = this.getTitle();
  594. var dot = filename.lastIndexOf('.');
  595. var ext = 'xml';
  596. if (dot > 0)
  597. {
  598. ext = filename.substring(dot);
  599. }
  600. var stack = (error != null) ? error.stack : new Error().stack;
  601. EditorUi.sendReport(title + ' ' + new Date().toISOString() + ':' +
  602. '\n\nAppVersion=' + navigator.appVersion +
  603. '\nFile=' + this.ui.hashValue(this.getId()) + ' (' + this.getMode() + ')' +
  604. ((this.isModified()) ? ' modified' : '') +
  605. '\nSize/Type=' + this.getSize() + ' (' + ext + ')' +
  606. '\nUser=' + uid + cid +
  607. '\nPrefix=' + this.ui.editor.graph.model.prefix +
  608. '\nSync=' + DrawioFile.SYNC +
  609. ((this.sync != null) ? (((this.sync.enabled) ? ' enabled' : '') +
  610. ((this.sync.isConnected()) ? ' connected' : '')) : '') +
  611. '\nPlugins=' + ((mxSettings.settings != null) ? mxSettings.getPlugins() : 'null') +
  612. '\n\nStats:\n' + JSON.stringify(this.stats, null, 2) +
  613. ((details != null) ? ('\n\n' + details) : '') +
  614. ((error != null) ? ('\n\nError: ' + error.message) : '') +
  615. '\n\nStack:\n' + stack +
  616. '\n\nShadow:\n' + shadow +
  617. '\n\nData:\n' + data, max);
  618. }
  619. catch (e)
  620. {
  621. // ignore
  622. }
  623. };
  624. /**
  625. * Adds the listener for automatically saving the diagram for local changes.
  626. */
  627. DrawioFile.prototype.reloadFile = function(success, error)
  628. {
  629. try
  630. {
  631. this.stats.fileReloaded++;
  632. // Saves current view state and changes since last save
  633. var changes = this.ui.diffPages(this.getShadowPages(),
  634. (this.isRealtime()) ? this.ownPages : this.ui.pages)
  635. var graph = this.ui.editor.graph;
  636. var selection = graph.getSelectionCells();
  637. var viewState = graph.getViewState();
  638. var page = this.ui.currentPage;
  639. this.getLatestVersion(mxUtils.bind(this, function(latestFile)
  640. {
  641. EditorUi.debug('DrawioFile.reloadFile', [this],
  642. 'modified', this.isModified(), 'rev', this.getCurrentRevisionId(),
  643. 'changes', [changes], 'viewState', [viewState],
  644. 'latestFile', latestFile);
  645. if (latestFile != null)
  646. {
  647. this.ui.replaceFileData(latestFile.getData(), [changes]);
  648. this.ui.restoreViewState(page, viewState, selection);
  649. this.setDescriptor(latestFile.getDescriptor());
  650. this.descriptorChanged();
  651. if (success != null)
  652. {
  653. success();
  654. }
  655. }
  656. else
  657. {
  658. // Loads file from scratch with new spinner and resets undo history
  659. // This should never be called as latestFile should not be null
  660. this.ui.spinner.stop();
  661. this.ui.loadFile(this.getHash(), true, null, mxUtils.bind(this, function()
  662. {
  663. if (this.ui.fileLoadedError == null)
  664. {
  665. // Carry-over stats
  666. var file = this.ui.getCurrentFile();
  667. if (file != null)
  668. {
  669. file.stats = this.stats;
  670. file.patch([changes]);
  671. file.fileChanged();
  672. }
  673. this.ui.restoreViewState(page, viewState, selection);
  674. if (success != null)
  675. {
  676. success();
  677. }
  678. }
  679. else if (error != null)
  680. {
  681. error(this.ui.fileLoadedError);
  682. }
  683. }), true);
  684. }
  685. }), error);
  686. }
  687. catch (e)
  688. {
  689. if (error != null)
  690. {
  691. error(e);
  692. }
  693. }
  694. };
  695. /**
  696. * Shows a conflict dialog to the user.
  697. */
  698. DrawioFile.prototype.copyFile = function(success, error)
  699. {
  700. this.ui.editor.editAsNew(this.ui.getFileData(true),
  701. this.ui.getCopyFilename(this));
  702. };
  703. /**
  704. * Returns true if the patches in the given array are empty.
  705. */
  706. DrawioFile.prototype.ignorePatches = function(patches)
  707. {
  708. var ignore = true;
  709. if (patches != null)
  710. {
  711. for (var i = 0; i < patches.length && ignore; i++)
  712. {
  713. ignore = ignore && mxUtils.isEmptyObject(patches[i]);
  714. }
  715. }
  716. return ignore;
  717. };
  718. /**
  719. * Applies the given patches to the file. If sendChanges is true the snapshot in
  720. * the sync client is not updated so a diff can be computed and propagated.
  721. */
  722. DrawioFile.prototype.patch = function(patches, resolver, undoable, sendChanges)
  723. {
  724. if (patches != null)
  725. {
  726. // Saves state of undo history
  727. var undoMgr = this.ui.editor.undoManager;
  728. var history = undoMgr.history.slice();
  729. var nextAdd = undoMgr.indexOfNextAdd;
  730. // Hides graph during updates
  731. var graph = this.ui.editor.graph;
  732. graph.container.style.visibility = 'hidden';
  733. // Ignores change events
  734. var prev = this.changeListenerEnabled;
  735. this.changeListenerEnabled = undoable;
  736. // Folding and math change require special handling
  737. var fold = graph.foldingEnabled;
  738. var math = graph.mathEnabled;
  739. // Updates text editor if cell changes during validation
  740. var redraw = graph.cellRenderer.redraw;
  741. graph.cellRenderer.redraw = function(state)
  742. {
  743. if (state.view.graph.isEditing(state.cell))
  744. {
  745. state.view.graph.scrollCellToVisible(state.cell);
  746. state.view.graph.cellEditor.resize();
  747. }
  748. redraw.apply(this, arguments);
  749. };
  750. graph.model.beginUpdate();
  751. try
  752. {
  753. if (undoable)
  754. {
  755. var oldPages = this.ui.pages.slice();
  756. var currentPage = this.ui.currentPage;
  757. var pages = this.ui.applyPatches(this.ui.pages,
  758. patches, true, resolver, this.isModified());
  759. for (var i = 0; i < pages.length; i++)
  760. {
  761. var index = mxUtils.indexOf(this.ui.pages, pages[i]);
  762. if (index < 0)
  763. {
  764. this.ui.insertPage(pages[i], Math.min(
  765. i, this.ui.pages.length));
  766. }
  767. else
  768. {
  769. this.ui.movePage(index, i);
  770. }
  771. }
  772. for (var i = 0; i < oldPages.length; i++)
  773. {
  774. if (mxUtils.indexOf(pages, oldPages[i]) < 0)
  775. {
  776. this.ui.removePage(oldPages[i]);
  777. }
  778. }
  779. // Reselects the current page
  780. if (mxUtils.indexOf(this.ui.pages, currentPage) >= 0)
  781. {
  782. this.ui.selectPage(currentPage, true);
  783. }
  784. }
  785. else
  786. {
  787. this.ui.pages = this.ui.applyPatches(this.ui.pages,
  788. patches, true, resolver, this.isModified());
  789. }
  790. // Always needs at least one page
  791. if (this.ui.pages.length == 0)
  792. {
  793. this.ui.pages.push(this.ui.createPage());
  794. }
  795. // Checks if current page was removed
  796. if (mxUtils.indexOf(this.ui.pages, this.ui.currentPage) < 0)
  797. {
  798. this.ui.selectPage(this.ui.pages[0], true);
  799. }
  800. // Checks if default parent was replaced
  801. graph.checkDefaultParent();
  802. }
  803. finally
  804. {
  805. // Changes visibility before action states are updated via model event
  806. graph.container.style.visibility = '';
  807. graph.model.endUpdate();
  808. // Restores previous state
  809. graph.cellRenderer.redraw = redraw;
  810. this.changeListenerEnabled = prev;
  811. // Restores history state
  812. if (!undoable)
  813. {
  814. undoMgr.history = history;
  815. undoMgr.indexOfNextAdd = nextAdd;
  816. undoMgr.fireEvent(new mxEventObject(mxEvent.CLEAR));
  817. }
  818. if (this.ui.currentPage == null || this.ui.currentPage.needsUpdate)
  819. {
  820. // Updates the graph and background
  821. if (math != graph.mathEnabled)
  822. {
  823. this.ui.editor.updateGraphComponents();
  824. graph.refresh();
  825. }
  826. else
  827. {
  828. if (fold != graph.foldingEnabled)
  829. {
  830. graph.view.revalidate();
  831. }
  832. else
  833. {
  834. graph.view.validate();
  835. }
  836. graph.sizeDidChange();
  837. }
  838. }
  839. // Updates snapshot for finding local changes in sync
  840. if (this.sync != null && this.isRealtime() && !sendChanges)
  841. {
  842. this.sync.snapshot = this.ui.clonePages(this.ui.pages);
  843. }
  844. this.ui.editor.fireEvent(new mxEventObject('pagesPatched', 'patches', patches));
  845. }
  846. EditorUi.debug('DrawioFile.patch', [this],
  847. 'patches', patches, 'resolver', resolver,
  848. 'undoable', undoable);
  849. }
  850. return patches;
  851. };
  852. /**
  853. * Adds the listener for automatically saving the diagram for local changes.
  854. */
  855. DrawioFile.prototype.save = function(revision, success, error, unloading, overwrite, manual)
  856. {
  857. try
  858. {
  859. EditorUi.debug('DrawioFile.save', [this], 'revision', revision,
  860. 'unloading', unloading, 'overwrite', overwrite, 'manual', manual,
  861. 'saving', this.savingFile, 'editable', this.isEditable(),
  862. 'invalidChecksum', this.invalidChecksum);
  863. if (!this.isEditable())
  864. {
  865. if (error != null)
  866. {
  867. error({message: mxResources.get('readOnly')});
  868. }
  869. else
  870. {
  871. throw new Error(mxResources.get('readOnly'));
  872. }
  873. }
  874. else if (!overwrite && this.invalidChecksum)
  875. {
  876. if (error != null)
  877. {
  878. error({message: mxResources.get('checksum')});
  879. }
  880. else
  881. {
  882. throw new Error(mxResources.get('checksum'));
  883. }
  884. }
  885. else
  886. {
  887. this.updateFileData();
  888. this.clearAutosave();
  889. if (success != null)
  890. {
  891. success();
  892. }
  893. }
  894. }
  895. catch (e)
  896. {
  897. if (error != null)
  898. {
  899. error(e);
  900. }
  901. else
  902. {
  903. throw e;
  904. }
  905. }
  906. };
  907. /**
  908. * Translates this point by the given vector.
  909. *
  910. * @param {number} dx X-coordinate of the translation.
  911. * @param {number} dy Y-coordinate of the translation.
  912. */
  913. DrawioFile.prototype.createData = function()
  914. {
  915. var actualPages = this.ui.pages;
  916. if (this.isRealtime())
  917. {
  918. // Uses ownPages for getting file data below
  919. this.ui.pages = this.ownPages;
  920. // Updates view state in own current page
  921. if (this.ui.currentPage != null)
  922. {
  923. var ownPage = this.ui.getPageById(
  924. this.ui.currentPage.getId(),
  925. this.ownPages);
  926. if (ownPage != null)
  927. {
  928. ownPage.viewState = this.ui.editor.graph.getViewState();
  929. ownPage.needsUpdate = true;
  930. }
  931. }
  932. }
  933. var result = this.ui.getFileData(null, null, null, null,
  934. null, null, null, null, this, !this.isCompressed());
  935. this.ui.pages = actualPages;
  936. return result;
  937. };
  938. /**
  939. * Translates this point by the given vector.
  940. *
  941. * @param {number} dx X-coordinate of the translation.
  942. * @param {number} dy Y-coordinate of the translation.
  943. */
  944. DrawioFile.prototype.updateFileData = function()
  945. {
  946. // Sends pending local changes and updates own pages
  947. if (this.sync != null)
  948. {
  949. this.sync.sendLocalChanges();
  950. }
  951. this.setData(this.createData());
  952. if (this.sync != null)
  953. {
  954. this.sync.fileDataUpdated();
  955. }
  956. };
  957. /**
  958. * Translates this point by the given vector.
  959. *
  960. * @param {number} dx X-coordinate of the translation.
  961. * @param {number} dy Y-coordinate of the translation.
  962. */
  963. DrawioFile.prototype.isCompressedStorage = function()
  964. {
  965. return Editor.defaultCompressed;
  966. };
  967. /**
  968. * Translates this point by the given vector.
  969. *
  970. * @param {number} dx X-coordinate of the translation.
  971. * @param {number} dy Y-coordinate of the translation.
  972. */
  973. DrawioFile.prototype.isCompressed = function()
  974. {
  975. var compressed = (this.ui.fileNode != null) ? this.ui.fileNode.getAttribute('compressed') : null;
  976. if (compressed != null)
  977. {
  978. return compressed != 'false';
  979. }
  980. else
  981. {
  982. return this.isCompressedStorage() && Editor.compressXml;
  983. }
  984. };
  985. /**
  986. * Translates this point by the given vector.
  987. *
  988. * @param {number} dx X-coordinate of the translation.
  989. * @param {number} dy Y-coordinate of the translation.
  990. */
  991. DrawioFile.prototype.setLocked = function(locked)
  992. {
  993. this.ui.fileNode.setAttribute('locked',
  994. (locked) ? 'true' : 'false');
  995. this.ui.fireEvent(new mxEventObject('lockedChanged'));
  996. this.fileChanged();
  997. if (locked)
  998. {
  999. this.ui.editor.graph.clearSelection();
  1000. }
  1001. };
  1002. /**
  1003. * Translates this point by the given vector.
  1004. *
  1005. * @param {number} dx X-coordinate of the translation.
  1006. * @param {number} dy Y-coordinate of the translation.
  1007. */
  1008. DrawioFile.prototype.isLocked = function()
  1009. {
  1010. var locked = (this.ui.fileNode != null) ? this.ui.fileNode.getAttribute('locked') : null;
  1011. if (locked != null)
  1012. {
  1013. return locked == 'true';
  1014. }
  1015. return false;
  1016. };
  1017. /**
  1018. * Translates this point by the given vector.
  1019. *
  1020. * @param {number} dx X-coordinate of the translation.
  1021. * @param {number} dy Y-coordinate of the translation.
  1022. */
  1023. DrawioFile.prototype.saveAs = function(filename, success, error) { };
  1024. /**
  1025. * Translates this point by the given vector.
  1026. *
  1027. * @param {number} dx X-coordinate of the translation.
  1028. * @param {number} dy Y-coordinate of the translation.
  1029. */
  1030. DrawioFile.prototype.saveFile = function(title, revision, success, error) { };
  1031. /**
  1032. * Returns true if copy, export and print are not allowed for this file.
  1033. */
  1034. DrawioFile.prototype.getFileUrl = function()
  1035. {
  1036. return null;
  1037. };
  1038. /**
  1039. * Returns true if copy, export and print are not allowed for this file.
  1040. */
  1041. DrawioFile.prototype.getFolderUrl = function(fn)
  1042. {
  1043. return null;
  1044. };
  1045. /**
  1046. * Returns true if copy, export and print are not allowed for this file.
  1047. */
  1048. DrawioFile.prototype.getPublicUrl = function(fn)
  1049. {
  1050. fn(null);
  1051. };
  1052. /**
  1053. * Returns true if copy, export and print are not allowed for this file.
  1054. */
  1055. DrawioFile.prototype.isRestricted = function()
  1056. {
  1057. return DrawioFile.RESTRICT_EXPORT;
  1058. };
  1059. /**
  1060. * Translates this point by the given vector.
  1061. *
  1062. * @param {number} dx X-coordinate of the translation.
  1063. * @param {number} dy Y-coordinate of the translation.
  1064. */
  1065. DrawioFile.prototype.isModified = function()
  1066. {
  1067. return this.modified;
  1068. };
  1069. /**
  1070. * Translates this point by the given vector.
  1071. *
  1072. * @param {number} dx X-coordinate of the translation.
  1073. * @param {number} dy Y-coordinate of the translation.
  1074. */
  1075. DrawioFile.prototype.getShadowModified = function()
  1076. {
  1077. return this.shadowModified;
  1078. };
  1079. /**
  1080. * Translates this point by the given vector.
  1081. *
  1082. * @param {number} dx X-coordinate of the translation.
  1083. * @param {number} dy Y-coordinate of the translation.
  1084. */
  1085. DrawioFile.prototype.setShadowModified = function(value)
  1086. {
  1087. this.shadowModified = value;
  1088. };
  1089. /**
  1090. * Translates this point by the given vector.
  1091. *
  1092. * @param {number} dx X-coordinate of the translation.
  1093. * @param {number} dy Y-coordinate of the translation.
  1094. */
  1095. DrawioFile.prototype.setModified = function(value)
  1096. {
  1097. this.modified = value;
  1098. this.shadowModified = value;
  1099. };
  1100. /**
  1101. * Specifies if the autosave checkbox should be shown in the document
  1102. * properties dialog. Default is false.
  1103. */
  1104. DrawioFile.prototype.isAutosaveOptional = function()
  1105. {
  1106. return false;
  1107. };
  1108. /**
  1109. * Translates this point by the given vector.
  1110. *
  1111. * @param {number} dx X-coordinate of the translation.
  1112. * @param {number} dy Y-coordinate of the translation.
  1113. */
  1114. DrawioFile.prototype.isAutosave = function()
  1115. {
  1116. return !this.inConflictState && this.ui.editor.autosave;
  1117. };
  1118. /**
  1119. * Translates this point by the given vector.
  1120. *
  1121. * @param {number} dx X-coordinate of the translation.
  1122. * @param {number} dy Y-coordinate of the translation.
  1123. */
  1124. DrawioFile.prototype.isRenamable = function()
  1125. {
  1126. return false;
  1127. };
  1128. /**
  1129. * Translates this point by the given vector.
  1130. *
  1131. * @param {number} dx X-coordinate of the translation.
  1132. * @param {number} dy Y-coordinate of the translation.
  1133. */
  1134. DrawioFile.prototype.rename = function(title, success, error) { };
  1135. /**
  1136. * Translates this point by the given vector.
  1137. *
  1138. * @param {number} dx X-coordinate of the translation.
  1139. * @param {number} dy Y-coordinate of the translation.
  1140. */
  1141. DrawioFile.prototype.isMovable = function()
  1142. {
  1143. return false;
  1144. };
  1145. /**
  1146. * Translates this point by the given vector.
  1147. *
  1148. * @param {number} dx X-coordinate of the translation.
  1149. * @param {number} dy Y-coordinate of the translation.
  1150. */
  1151. DrawioFile.prototype.isTrashed = function()
  1152. {
  1153. return false;
  1154. };
  1155. /**
  1156. * Translates this point by the given vector.
  1157. *
  1158. * @param {number} dx X-coordinate of the translation.
  1159. * @param {number} dy Y-coordinate of the translation.
  1160. */
  1161. DrawioFile.prototype.move = function(folderId, success, error) { };
  1162. /**
  1163. * Translates this point by the given vector.
  1164. *
  1165. * @param {number} dx X-coordinate of the translation.
  1166. * @param {number} dy Y-coordinate of the translation.
  1167. */
  1168. DrawioFile.prototype.share = function()
  1169. {
  1170. if (this.ui.drive != null)
  1171. {
  1172. this.ui.confirm(mxResources.get('saveItToGoogleDriveToCollaborate', [this.getTitle()]),
  1173. mxUtils.bind(this, function()
  1174. {
  1175. this.ui.pickFolder(App.MODE_GOOGLE, mxUtils.bind(this, function(folderId)
  1176. {
  1177. var graph = this.ui.editor.graph;
  1178. var selection = graph.getSelectionCells();
  1179. var viewState = graph.getViewState();
  1180. var page = this.ui.currentPage;
  1181. this.ui.createFile(this.getTitle(), this.ui.getFileData(null, null, null, null, null,
  1182. null, null, null, this), null, App.MODE_GOOGLE, null, true, folderId, null, null,
  1183. mxUtils.bind(this, function()
  1184. {
  1185. this.ui.restoreViewState(page, viewState, selection);
  1186. this.ui.actions.get('share').funct();
  1187. }));
  1188. }));
  1189. }), null, mxResources.get('saveToGoogleDrive', null, 'Save to Google Drive'), mxResources.get('cancel'));
  1190. }
  1191. else
  1192. {
  1193. this.ui.alert(mxResources.get('sharingAvailable'), null, 380);
  1194. }
  1195. };
  1196. /**
  1197. * Returns the hash of the file which consists of a prefix for the storage
  1198. * type and the ID of the file.
  1199. */
  1200. DrawioFile.prototype.getHash = function()
  1201. {
  1202. return '';
  1203. };
  1204. /**
  1205. * Returns the ID of the file.
  1206. */
  1207. DrawioFile.prototype.getId = function()
  1208. {
  1209. return '';
  1210. };
  1211. /**
  1212. * Returns true if the file is editable.
  1213. */
  1214. DrawioFile.prototype.isEditable = function()
  1215. {
  1216. return !this.ui.editor.isChromelessView() || this.ui.editor.editable;
  1217. };
  1218. /**
  1219. * Returns the location as a new object.
  1220. * @type mx.Point
  1221. */
  1222. DrawioFile.prototype.getUi = function()
  1223. {
  1224. return this.ui;
  1225. };
  1226. /**
  1227. * Returns the current title of the file.
  1228. */
  1229. DrawioFile.prototype.getTitle = function()
  1230. {
  1231. return '';
  1232. };
  1233. /**
  1234. * Sets the current data of the file.
  1235. */
  1236. DrawioFile.prototype.setData = function(data)
  1237. {
  1238. this.data = data;
  1239. EditorUi.debug('DrawioFile.setData',
  1240. [this], 'data', [data]);
  1241. };
  1242. /**
  1243. * Returns the current data of the file.
  1244. */
  1245. DrawioFile.prototype.getData = function()
  1246. {
  1247. return this.data;
  1248. };
  1249. /**
  1250. * Removes external fonts.
  1251. */
  1252. DrawioFile.prototype.removeExtFonts = function(elems)
  1253. {
  1254. for (var i = 0; elems != null && i < elems.length; i++)
  1255. {
  1256. var e = elems[i];
  1257. if (e.id != null && e.id.indexOf('extFont_') == 0)
  1258. {
  1259. e.parentNode.removeChild(e);
  1260. }
  1261. }
  1262. };
  1263. /**
  1264. * Opens this file in the editor.
  1265. */
  1266. DrawioFile.prototype.open = function()
  1267. {
  1268. this.stats.opened++;
  1269. var data = this.getData();
  1270. if (data != null)
  1271. {
  1272. this.ui.setFileData(data);
  1273. // Updates shadow in case any page IDs have been updated
  1274. // only if the file has not been modified and reopened
  1275. if (!this.isModified())
  1276. {
  1277. this.setShadowPages(this.ui.clonePages(this.ui.pages));
  1278. }
  1279. }
  1280. this.installListeners();
  1281. if (this.isSyncSupported())
  1282. {
  1283. this.startSync();
  1284. }
  1285. EditorUi.debug('DrawioFile.open', [this]);
  1286. };
  1287. /**
  1288. * Returns true if polling should be used to update the file.
  1289. */
  1290. DrawioFile.prototype.isPolling = function()
  1291. {
  1292. return false;
  1293. };
  1294. /**
  1295. * Returns the polling interval.
  1296. */
  1297. DrawioFile.prototype.getPollingInterval = function()
  1298. {
  1299. return 10000;
  1300. };
  1301. /**
  1302. * Hook for subclassers.
  1303. */
  1304. DrawioFile.prototype.isSyncSupported = function()
  1305. {
  1306. return false;
  1307. };
  1308. /**
  1309. * Returns true if the realtime model was initialized.
  1310. */
  1311. DrawioFile.prototype.isRealtime = function()
  1312. {
  1313. return this.ownPages != null && this.ui.pages != null;
  1314. };
  1315. /**
  1316. * Returns true if the file supportes realtime collaboration.
  1317. */
  1318. DrawioFile.prototype.isRealtimeSupported = function()
  1319. {
  1320. return false;
  1321. };
  1322. /**
  1323. * Returns true if realtime collaboration is enabled for this file.
  1324. */
  1325. DrawioFile.prototype.isRealtimeEnabled = function()
  1326. {
  1327. return Editor.enableRealtime && urlParams['fast-sync'] != '0';
  1328. };
  1329. /**
  1330. * Returns true if all changes should be sent out immediately.
  1331. */
  1332. DrawioFile.prototype.setRealtimeEnabled = function()
  1333. {
  1334. // do nothing
  1335. };
  1336. /**
  1337. * Returns true if realtime can be enabled and disabled for this file.
  1338. */
  1339. DrawioFile.prototype.isRealtimeOptional = function()
  1340. {
  1341. return false;
  1342. };
  1343. /**
  1344. * Returns the ready state of realtime collaboration websocket.
  1345. *
  1346. * 0 - CONNECTING
  1347. * 1 - OPEN
  1348. * 2 - CLOSING
  1349. * 3 - CLOSED
  1350. */
  1351. DrawioFile.prototype.getRealtimeState = function()
  1352. {
  1353. return (this.sync != null && this.sync.p2pCollab != null) ?
  1354. this.sync.p2pCollab.getState() : 3 /* CLOSED */;
  1355. };
  1356. /**
  1357. * Returns true if all changes should be sent out immediately.
  1358. */
  1359. DrawioFile.prototype.getRealtimeError = function()
  1360. {
  1361. return (this.sync != null && this.sync.p2pCollab != null) ?
  1362. this.sync.p2pCollab.getLastError() : null;
  1363. };
  1364. /**
  1365. * Returns true if the notification to update should be sent
  1366. * together with the save request.
  1367. */
  1368. DrawioFile.prototype.isOptimisticSync = function()
  1369. {
  1370. return false;
  1371. };
  1372. /**
  1373. * Hook for subclassers.
  1374. */
  1375. DrawioFile.prototype.isRevisionHistorySupported = function()
  1376. {
  1377. return false;
  1378. };
  1379. /**
  1380. * Hook for subclassers.
  1381. */
  1382. DrawioFile.prototype.getRevisions = function(success, error)
  1383. {
  1384. success(null);
  1385. };
  1386. /**
  1387. * Hook for subclassers to get the latest descriptor of this file
  1388. * and return it in the success handler.
  1389. */
  1390. DrawioFile.prototype.loadDescriptor = function(success, error)
  1391. {
  1392. success(null);
  1393. };
  1394. /**
  1395. * Hook for subclassers to get the latest etag of this file
  1396. * and return it in the success handler.
  1397. */
  1398. DrawioFile.prototype.loadPatchDescriptor = function(success, error)
  1399. {
  1400. this.loadDescriptor(mxUtils.bind(this, function(desc)
  1401. {
  1402. success(desc);
  1403. }), error);
  1404. };
  1405. /**
  1406. * Adds the listener for automatically saving the diagram for local changes.
  1407. */
  1408. DrawioFile.prototype.patchDescriptor = function(desc, patch)
  1409. {
  1410. this.setDescriptorEtag(desc, this.getDescriptorEtag(patch));
  1411. this.descriptorChanged();
  1412. };
  1413. /**
  1414. * Creates a starts the synchronization.
  1415. */
  1416. DrawioFile.prototype.startSync = function()
  1417. {
  1418. if (((DrawioFile.SYNC == 'auto' || DrawioFile.SYNC == 'fast') &&
  1419. urlParams['stealth'] != '1') && (urlParams['rt'] == '1' ||
  1420. !this.ui.editor.chromeless || this.ui.editor.editable))
  1421. {
  1422. if (this.sync == null)
  1423. {
  1424. this.sync = new DrawioFileSync(this);
  1425. }
  1426. this.addListener('realtimeStateChanged', mxUtils.bind(this, function()
  1427. {
  1428. this.ui.fireEvent(new mxEventObject('realtimeStateChanged'));
  1429. }));
  1430. this.sync.start();
  1431. }
  1432. };
  1433. /**
  1434. * Hook for subclassers to check if an error is a conflict.
  1435. */
  1436. DrawioFile.prototype.isConflict = function()
  1437. {
  1438. return false;
  1439. };
  1440. /**
  1441. * Gets the channel ID for sync messages.
  1442. */
  1443. DrawioFile.prototype.getChannelId = function()
  1444. {
  1445. // Slash, space and plus replaced with underscore
  1446. return Graph.compress(this.getHash()).replace(/[\/ +]/g, '_');
  1447. };
  1448. /**
  1449. * Gets the channel ID from the given descriptor.
  1450. */
  1451. DrawioFile.prototype.getChannelKey = function(desc)
  1452. {
  1453. return null;
  1454. };
  1455. /**
  1456. * Returns the current etag.
  1457. */
  1458. DrawioFile.prototype.getCurrentUser = function()
  1459. {
  1460. return null;
  1461. };
  1462. /**
  1463. * Hook for subclassers to get the latest version of this file
  1464. * and return it in the success handler.
  1465. */
  1466. DrawioFile.prototype.getLatestVersion = function(success, error)
  1467. {
  1468. success(null);
  1469. };
  1470. /**
  1471. * Hook for subclassers to get the latest version ID of this file
  1472. * and return it in the success handler.
  1473. */
  1474. DrawioFile.prototype.getLatestVersionId = function(success, error)
  1475. {
  1476. success(-1);
  1477. };
  1478. /**
  1479. * Returns the last modified date of this file.
  1480. */
  1481. DrawioFile.prototype.getLastModifiedDate = function()
  1482. {
  1483. return new Date();
  1484. };
  1485. /**
  1486. * Sets the current revision ID.
  1487. */
  1488. DrawioFile.prototype.setCurrentRevisionId = function(id)
  1489. {
  1490. this.setDescriptorRevisionId(this.getDescriptor(), id);
  1491. };
  1492. /**
  1493. * Returns the current revision ID.
  1494. */
  1495. DrawioFile.prototype.getCurrentRevisionId = function()
  1496. {
  1497. return this.getDescriptorRevisionId(this.getDescriptor());
  1498. };
  1499. /**
  1500. * Sets the current etag.
  1501. */
  1502. DrawioFile.prototype.setCurrentEtag = function(etag)
  1503. {
  1504. this.setDescriptorEtag(this.getDescriptor(), etag);
  1505. };
  1506. /**
  1507. * Returns the current etag.
  1508. */
  1509. DrawioFile.prototype.getCurrentEtag = function()
  1510. {
  1511. return this.getDescriptorEtag(this.getDescriptor());
  1512. };
  1513. /**
  1514. * Returns the descriptor from this file.
  1515. */
  1516. DrawioFile.prototype.getDescriptor = function()
  1517. {
  1518. return null;
  1519. };
  1520. /**
  1521. * Sets the descriptor for this file.
  1522. */
  1523. DrawioFile.prototype.setDescriptor = function() { };
  1524. /**
  1525. * Updates the revision ID on the given descriptor.
  1526. */
  1527. DrawioFile.prototype.setDescriptorRevisionId = function(desc, id)
  1528. {
  1529. this.setDescriptorEtag(desc, id);
  1530. };
  1531. /**
  1532. * Returns the revision ID from the given descriptor.
  1533. */
  1534. DrawioFile.prototype.getDescriptorRevisionId = function(desc)
  1535. {
  1536. return this.getDescriptorEtag(desc);
  1537. };
  1538. /**
  1539. * Updates the etag on the given descriptor.
  1540. */
  1541. DrawioFile.prototype.setDescriptorEtag = function(desc, etag) { };
  1542. /**
  1543. * Returns the etag from the given descriptor.
  1544. */
  1545. DrawioFile.prototype.getDescriptorEtag = function(desc)
  1546. {
  1547. return null;
  1548. };
  1549. /**
  1550. * Returns the secret from the given descriptor. This must be stored
  1551. * in a custom property and generated by the saving client so that a
  1552. * token can be obtained from the cache for writing the patch after
  1553. * saving the file. If this cannot be saved in a custom property then
  1554. * null must be returned so that no deltas are used for updating the
  1555. * file (the file is reloaded every time instead). This is needed to
  1556. * make sure nobody with read-only permissions can write a patch to
  1557. * the cache before the saving client wrote the patch and inject
  1558. * data into the file via other clients merging that data.
  1559. */
  1560. DrawioFile.prototype.getDescriptorSecret = function(desc)
  1561. {
  1562. return null;
  1563. };
  1564. /**
  1565. * Returns the checksum from the given descriptor. This must be stored
  1566. * in a custom property and generated by the saving client so that
  1567. * the current state of the editor can be compared with the state.
  1568. */
  1569. DrawioFile.prototype.getDescriptorChecksum = function(desc)
  1570. {
  1571. return null;
  1572. };
  1573. /**
  1574. * Installs the change listener.
  1575. */
  1576. DrawioFile.prototype.installListeners = function()
  1577. {
  1578. if (this.changeListener == null)
  1579. {
  1580. this.changeListener = mxUtils.bind(this, function(sender, eventObject)
  1581. {
  1582. var edit = (eventObject != null) ? eventObject.getProperty('edit') : null;
  1583. if (this.changeListenerEnabled && this.isEditable() && (edit == null || !edit.ignoreEdit))
  1584. {
  1585. this.fileChanged();
  1586. }
  1587. });
  1588. this.ui.editor.graph.model.addListener(mxEvent.CHANGE, this.changeListener);
  1589. // Some options trigger autosave
  1590. this.ui.editor.graph.addListener('gridSizeChanged', this.changeListener);
  1591. this.ui.editor.graph.addListener('shadowVisibleChanged', this.changeListener);
  1592. this.ui.addListener('pageFormatChanged', this.changeListener);
  1593. this.ui.addListener('pageScaleChanged', this.changeListener);
  1594. this.ui.addListener('backgroundColorChanged', this.changeListener);
  1595. this.ui.addListener('backgroundImageChanged', this.changeListener);
  1596. this.ui.addListener('foldingEnabledChanged', this.changeListener);
  1597. this.ui.addListener('mathEnabledChanged', this.changeListener);
  1598. this.ui.addListener('gridEnabledChanged', this.changeListener);
  1599. this.ui.addListener('guidesEnabledChanged', this.changeListener);
  1600. this.ui.addListener('tooltipsEnabledChanged', this.changeListener);
  1601. this.ui.addListener('pageViewChanged', this.changeListener);
  1602. this.ui.addListener('connectionPointsChanged', this.changeListener);
  1603. this.ui.addListener('connectionArrowsChanged', this.changeListener);
  1604. }
  1605. };
  1606. /**
  1607. * Returns the location as a new object.
  1608. * @type mx.Point
  1609. */
  1610. DrawioFile.prototype.addAllSavedStatus = function(status)
  1611. {
  1612. if (this.ui.statusContainer != null && this.ui.getCurrentFile() == this)
  1613. {
  1614. status = (status != null) ? status : mxUtils.htmlEntities(mxResources.get(this.allChangesSavedKey));
  1615. var rev = (this.isRevisionHistorySupported() && status != mxUtils.htmlEntities(
  1616. mxResources.get(this.savingStatusKey)) + '...') ? 'data-action="revisionHistory" ' : '';
  1617. this.ui.editor.setStatus('<div ' + rev + 'title="'+ status + '">' + status +
  1618. (this.isLocked() ? ' <img class="geToolbarButton geAdaptiveAsset" data-action="properties" ' +
  1619. 'style="margin-left:4px;flex-shrink:0;" src="' + Editor.lockedImage + '"/>' : '') + '</div>');
  1620. }
  1621. };
  1622. /**
  1623. * Adds the listener for automatically saving the diagram for local changes.
  1624. */
  1625. DrawioFile.prototype.saveDraft = function(data)
  1626. {
  1627. try
  1628. {
  1629. if (this.draftId == null)
  1630. {
  1631. if (this.usedDraftId != null)
  1632. {
  1633. this.draftId = this.usedDraftId;
  1634. }
  1635. else
  1636. {
  1637. this.draftId = Editor.guid();
  1638. }
  1639. }
  1640. var draft = {type: 'draft',
  1641. created: this.created,
  1642. modified: new Date().getTime(),
  1643. data: (data != null) ? data : this.ui.getFileData(),
  1644. title: this.getTitle(),
  1645. fileObject: this.fileObject,
  1646. aliveCheck: this.ui.draftAliveCheck};
  1647. this.ui.setDatabaseItem('.draft_' + this.draftId,
  1648. JSON.stringify(draft));
  1649. EditorUi.debug('DrawioFile.saveDraft', [this],
  1650. 'draftId', this.draftId, [draft]);
  1651. }
  1652. catch (e)
  1653. {
  1654. // Removes any stored draft
  1655. this.removeDraft();
  1656. }
  1657. };
  1658. /**
  1659. * Adds the listener for automatically saving the diagram for local changes.
  1660. */
  1661. DrawioFile.prototype.removeDraft = function()
  1662. {
  1663. try
  1664. {
  1665. if (this.draftId != null)
  1666. {
  1667. EditorUi.debug('DrawioFile.removeDraft',
  1668. [this], 'draftId', this.draftId);
  1669. this.ui.removeDatabaseItem('.draft_' + this.draftId);
  1670. this.usedDraftId = this.draftId;
  1671. this.draftId = null;
  1672. }
  1673. }
  1674. catch (e)
  1675. {
  1676. // ignore
  1677. }
  1678. };
  1679. /**
  1680. * Adds the listener for automatically saving the diagram for local changes.
  1681. */
  1682. DrawioFile.prototype.addUnsavedStatus = function(err)
  1683. {
  1684. if (!this.inConflictState && this.ui.statusContainer != null && this.ui.getCurrentFile() == this)
  1685. {
  1686. if (err instanceof Error && err.message != null && err.message != '')
  1687. {
  1688. var status = mxUtils.htmlEntities(mxResources.get('unsavedChanges'));
  1689. this.ui.editor.setStatus('<div title="'+ status + '" data-title="' +
  1690. mxUtils.htmlEntities(mxResources.get('unsavedChanges')) +
  1691. '" data-message="' + mxUtils.htmlEntities(err.message) +
  1692. '" class="geStatusAlert">' + status + ' (' +
  1693. mxUtils.htmlEntities(err.message) + ')</div>');
  1694. }
  1695. else
  1696. {
  1697. var msg = this.getErrorMessage(err);
  1698. if (msg == null && this.lastSaved != null)
  1699. {
  1700. var str = this.ui.timeSince(new Date(this.lastSaved));
  1701. // Only show if more than a minute ago
  1702. if (str != null)
  1703. {
  1704. msg = mxResources.get('lastSaved', [str]);
  1705. }
  1706. }
  1707. if (msg != null && msg.length > 60)
  1708. {
  1709. msg = msg.substring(0, 60) + '...';
  1710. }
  1711. var status = mxUtils.htmlEntities(mxResources.get('unsavedChangesClickHereToSave')) +
  1712. ((msg != null && msg != '') ? ' (' + mxUtils.htmlEntities(msg) + ')' : '');
  1713. var action = 'data-action="' + ((this.ui.mode == null || !this.isEditable()) ?
  1714. 'saveAs' : 'save') + '"';
  1715. this.ui.editor.setStatus('<div ' + action + ' title="' +
  1716. status + '" class="geStatusAlert">' + status +
  1717. ' <img class="geAdaptiveAsset" src="' + Editor.saveImage + '"/></div>');
  1718. if (EditorUi.enableDrafts && (this.getMode() == null || EditorUi.isElectronApp))
  1719. {
  1720. this.lastDraftSave = this.lastDraftSave || Date.now();
  1721. if (this.saveDraftThread != null)
  1722. {
  1723. window.clearTimeout(this.saveDraftThread);
  1724. this.saveDraftThread = null;
  1725. // Max delay without saving is double the delay for autosave or 30 sec
  1726. if (Date.now() - this.lastDraftSave > Math.max(2 * EditorUi.draftSaveDelay, 30000))
  1727. {
  1728. this.lastDraftSave = Date.now();
  1729. this.saveDraft();
  1730. }
  1731. }
  1732. this.saveDraftThread = window.setTimeout(mxUtils.bind(this, function()
  1733. {
  1734. this.lastDraftSave = Date.now();
  1735. this.saveDraftThread = null;
  1736. this.saveDraft();
  1737. }), EditorUi.draftSaveDelay || 0);
  1738. }
  1739. }
  1740. }
  1741. };
  1742. /**
  1743. * Halts all timers and shows a conflict status message. The optional error
  1744. * handler is invoked first.
  1745. */
  1746. DrawioFile.prototype.addConflictStatus = function(message, fn)
  1747. {
  1748. if (this.invalidChecksum && message == null)
  1749. {
  1750. message = mxResources.get('checksum');
  1751. }
  1752. this.setConflictStatus(mxUtils.htmlEntities(mxResources.get('fileChangedSync')) +
  1753. ((message != null && message != '') ? ' (' +
  1754. mxUtils.htmlEntities(message) + ')' : ''), fn);
  1755. this.ui.spinner.stop();
  1756. this.clearAutosave();
  1757. };
  1758. /**
  1759. * Halts all timers and shows a conflict status message. The optional error
  1760. * handler is invoked first.
  1761. */
  1762. DrawioFile.prototype.setConflictStatus = function(message, fn)
  1763. {
  1764. this.ui.editor.setStatus('<div title="'+ message + '" ' + ((fn != null) ?
  1765. 'data-action="statusFunction"' : '') + ' class="geStatusAlert">' + message +
  1766. '<img data-link="https://www.drawio.com/doc/faq/synchronize" src="' +
  1767. Editor.helpImage + '" style="margin-left:2px;cursor:help;"/></div>', fn);
  1768. };
  1769. /**
  1770. * Shows a conflict dialog to the user.
  1771. */
  1772. DrawioFile.prototype.showRefreshDialog = function(success, error, message)
  1773. {
  1774. if (message == null)
  1775. {
  1776. message = mxResources.get('checksum');
  1777. }
  1778. if (this.ui.editor.isChromelessView() && !this.ui.editor.editable)
  1779. {
  1780. this.ui.alert(mxResources.get('fileChangedSync'), mxUtils.bind(this, function()
  1781. {
  1782. this.reloadFile(success, error);
  1783. }));
  1784. }
  1785. else
  1786. {
  1787. // Allows for escape key to be pressed while dialog is showing
  1788. this.addConflictStatus(message, mxUtils.bind(this, function()
  1789. {
  1790. this.showRefreshDialog(success, error);
  1791. }));
  1792. this.ui.showError(mxResources.get('warning') + ' (' + message + ')',
  1793. mxResources.get('fileChangedSyncDialog'),
  1794. mxResources.get('makeCopy'), mxUtils.bind(this, function()
  1795. {
  1796. this.copyFile(mxUtils.bind(this, function()
  1797. {
  1798. if (success != null)
  1799. {
  1800. success();
  1801. }
  1802. this.ui.alert(mxResources.get('copyCreated'));
  1803. }), error);
  1804. }), null, mxResources.get('merge'), mxUtils.bind(this, function()
  1805. {
  1806. if (this.ui.spinner.spin(document.body, mxResources.get('updatingDocument')))
  1807. {
  1808. this.reloadFile(mxUtils.bind(this, function()
  1809. {
  1810. this.ui.spinner.stop();
  1811. if (success != null)
  1812. {
  1813. success();
  1814. }
  1815. }), mxUtils.bind(this, function()
  1816. {
  1817. this.ui.spinner.stop();
  1818. if (error != null)
  1819. {
  1820. error();
  1821. }
  1822. }));
  1823. }
  1824. }), mxResources.get('cancel'), mxUtils.bind(this, function()
  1825. {
  1826. this.ui.hideDialog();
  1827. }), 380, 130);
  1828. }
  1829. };
  1830. /**
  1831. * Shows a dialog with no synchronize option.
  1832. */
  1833. DrawioFile.prototype.showCopyDialog = function(success, error, overwrite)
  1834. {
  1835. this.inConflictState = false;
  1836. this.invalidChecksum = false;
  1837. this.addUnsavedStatus();
  1838. this.ui.showError(mxResources.get('externalChanges'),
  1839. mxResources.get('fileChangedOverwriteDialog'),
  1840. mxResources.get('makeCopy'), mxUtils.bind(this, function()
  1841. {
  1842. this.copyFile(success, error);
  1843. }), null, mxResources.get('overwrite'), overwrite,
  1844. mxResources.get('cancel'), mxUtils.bind(this, function()
  1845. {
  1846. this.ui.hideDialog();
  1847. }), 380, 150);
  1848. };
  1849. /**
  1850. * Shows a conflict dialog to the user.
  1851. */
  1852. DrawioFile.prototype.showConflictDialog = function(overwrite, synchronize)
  1853. {
  1854. this.ui.showError(mxResources.get('externalChanges'),
  1855. mxResources.get('fileChangedSyncDialog'),
  1856. mxResources.get('overwrite'), overwrite, null,
  1857. mxResources.get('merge'), synchronize,
  1858. mxResources.get('cancel'), mxUtils.bind(this, function()
  1859. {
  1860. this.ui.hideDialog();
  1861. this.handleFileError(null, false);
  1862. }), 380, 130);
  1863. };
  1864. /**
  1865. * Checks if the client is authorized and calls the next step.
  1866. */
  1867. DrawioFile.prototype.redirectToNewApp = function(error, details)
  1868. {
  1869. this.ui.spinner.stop();
  1870. if (!this.redirectDialogShowing)
  1871. {
  1872. this.redirectDialogShowing = true;
  1873. var url = window.location.protocol + '//' + window.location.host + '/' + this.ui.getSearch(
  1874. ['create', 'title', 'mode', 'url', 'drive', 'splash', 'state']) + '#' + this.getHash();
  1875. var msg = mxResources.get('redirectToNewApp');
  1876. if (details != null)
  1877. {
  1878. msg += ' (' + details + ')';
  1879. }
  1880. var redirect = mxUtils.bind(this, function()
  1881. {
  1882. var fn = mxUtils.bind(this, function()
  1883. {
  1884. this.redirectDialogShowing = false;
  1885. if (window.location.href == url)
  1886. {
  1887. window.location.reload();
  1888. }
  1889. else
  1890. {
  1891. window.location.href = url;
  1892. }
  1893. });
  1894. if (error == null && this.isModified())
  1895. {
  1896. this.ui.confirm(mxResources.get('allChangesLost'), mxUtils.bind(this, function()
  1897. {
  1898. this.redirectDialogShowing = false;
  1899. }), fn, mxResources.get('cancel'), mxResources.get('discardChanges'));
  1900. }
  1901. else
  1902. {
  1903. fn();
  1904. }
  1905. });
  1906. if (error != null)
  1907. {
  1908. if (this.isModified())
  1909. {
  1910. this.ui.confirm(msg, mxUtils.bind(this, function()
  1911. {
  1912. this.redirectDialogShowing = false;
  1913. error();
  1914. }), redirect, mxResources.get('cancel'), mxResources.get('discardChanges'));
  1915. }
  1916. else
  1917. {
  1918. this.ui.confirm(msg, redirect, mxUtils.bind(this, function()
  1919. {
  1920. this.redirectDialogShowing = false;
  1921. error();
  1922. }));
  1923. }
  1924. }
  1925. else
  1926. {
  1927. this.ui.alert(mxResources.get('redirectToNewApp'), redirect);
  1928. }
  1929. }
  1930. };
  1931. /**
  1932. * Adds the listener for automatically saving the diagram for local changes.
  1933. */
  1934. DrawioFile.prototype.handleFileSuccess = function(saved)
  1935. {
  1936. this.ui.spinner.stop();
  1937. if (this.ui.getCurrentFile() == this)
  1938. {
  1939. EditorUi.debug('DrawioFile.handleFileSuccess', [this],
  1940. 'saved', saved, 'modified', this.isModified(),
  1941. 'remoteFileChanged', (this.sync == null) ?
  1942. 'n/a' : this.sync.remoteFileChanged);
  1943. if (this.isModified())
  1944. {
  1945. this.fileChanged();
  1946. }
  1947. else if (saved)
  1948. {
  1949. if (this.isTrashed())
  1950. {
  1951. this.addAllSavedStatus(mxUtils.htmlEntities(mxResources.get(this.allChangesSavedKey)) + ' (' +
  1952. mxUtils.htmlEntities(mxResources.get('fileMovedToTrash')) + ')');
  1953. }
  1954. else
  1955. {
  1956. this.addAllSavedStatus();
  1957. }
  1958. if (this.sync != null)
  1959. {
  1960. this.sync.resetUpdateStatusThread();
  1961. if (this.sync.remoteFileChanged)
  1962. {
  1963. this.sync.remoteFileChanged = false;
  1964. this.sync.fileChangedNotify();
  1965. }
  1966. }
  1967. }
  1968. else
  1969. {
  1970. this.ui.editor.setStatus('');
  1971. }
  1972. }
  1973. };
  1974. /**
  1975. * Adds the listener for automatically saving the diagram for local changes.
  1976. */
  1977. DrawioFile.prototype.handleFileError = function(err, manual)
  1978. {
  1979. this.ui.spinner.stop();
  1980. if (this.ui.getCurrentFile() == this)
  1981. {
  1982. if (this.inConflictState)
  1983. {
  1984. this.handleConflictError(err, manual);
  1985. }
  1986. else
  1987. {
  1988. if (this.isModified())
  1989. {
  1990. this.addUnsavedStatus(err);
  1991. }
  1992. if (manual)
  1993. {
  1994. this.ui.handleError(err, (err != null) ? mxResources.get('errorSavingFile') : null);
  1995. }
  1996. else if (!this.isModified())
  1997. {
  1998. var msg = this.getErrorMessage(err);
  1999. if (msg != null && msg.length > 60)
  2000. {
  2001. msg = msg.substring(0, 60) + '...';
  2002. }
  2003. this.ui.editor.setStatus('<div class="geStatusAlert">' +
  2004. mxUtils.htmlEntities(mxResources.get('error')) + ((msg != null) ?
  2005. ' (' + mxUtils.htmlEntities(msg) + ')' : '') + '</div>');
  2006. }
  2007. }
  2008. }
  2009. };
  2010. /**
  2011. * Adds the listener for automatically saving the diagram for local changes.
  2012. */
  2013. DrawioFile.prototype.handleConflictError = function(err, manual)
  2014. {
  2015. var success = mxUtils.bind(this, function()
  2016. {
  2017. this.handleFileSuccess(true);
  2018. });
  2019. var error = mxUtils.bind(this, function(err2)
  2020. {
  2021. this.handleFileError(err2, true);
  2022. });
  2023. var overwrite = mxUtils.bind(this, function()
  2024. {
  2025. if (this.ui.spinner.spin(document.body, mxResources.get(this.savingSpinnerKey)))
  2026. {
  2027. this.ui.editor.setStatus('');
  2028. var isRepoFile = (this.constructor == GitHubFile) || (this.constructor == GitLabFile);
  2029. this.save(true, success, error, null, true, (isRepoFile &&
  2030. err != null) ? err.commitMessage : null);
  2031. }
  2032. });
  2033. var synchronize = mxUtils.bind(this, function()
  2034. {
  2035. if (this.ui.spinner.spin(document.body, mxResources.get('updatingDocument')))
  2036. {
  2037. this.synchronizeFile(mxUtils.bind(this, function()
  2038. {
  2039. this.ui.spinner.stop();
  2040. if (this.ui.spinner.spin(document.body, mxResources.get(this.savingSpinnerKey)))
  2041. {
  2042. var isRepoFile = (this.constructor == GitHubFile) || (this.constructor == GitLabFile);
  2043. this.save(true, success, error, null, null, (isRepoFile &&
  2044. err != null) ? err.commitMessage : null);
  2045. }
  2046. }), error);
  2047. }
  2048. })
  2049. if (DrawioFile.SYNC == 'none')
  2050. {
  2051. this.showCopyDialog(success, error, overwrite);
  2052. }
  2053. else if (this.invalidChecksum && manual)
  2054. {
  2055. this.showRefreshDialog(success, error, this.getErrorMessage(err));
  2056. }
  2057. else if (manual)
  2058. {
  2059. this.showConflictDialog(overwrite, synchronize);
  2060. }
  2061. else
  2062. {
  2063. this.addConflictStatus(this.getErrorMessage(err), mxUtils.bind(this, function()
  2064. {
  2065. this.ui.editor.setStatus(mxUtils.htmlEntities(
  2066. mxResources.get('updatingDocument')));
  2067. this.synchronizeFile(success, error);
  2068. }));
  2069. }
  2070. };
  2071. /**
  2072. * Adds the listener for automatically saving the diagram for local changes.
  2073. */
  2074. DrawioFile.prototype.getErrorMessage = function(err)
  2075. {
  2076. var msg = (err != null) ? ((err.error != null) ? err.error.message : err.message) : null;
  2077. if (msg == null && err != null && err.code == App.ERROR_TIMEOUT)
  2078. {
  2079. msg = mxResources.get('timeout');
  2080. }
  2081. // XHR blocked by CORS or response has no CORS headers
  2082. else if (msg == '0')
  2083. {
  2084. msg = mxResources.get('noResponse');
  2085. }
  2086. return msg;
  2087. };
  2088. /**
  2089. * Returns true if the oldest unsaved change is older than <EditorUi.warnInterval>.
  2090. */
  2091. DrawioFile.prototype.isOverdue = function()
  2092. {
  2093. return this.ageStart != null && (Date.now() - this.ageStart.getTime()) >= this.ui.warnInterval;
  2094. };
  2095. /**
  2096. * Invoked when the compression has changed.
  2097. */
  2098. DrawioFile.prototype.compressionChanged = function(compressed)
  2099. {
  2100. // Changes the internal compressed data in the pages to the current state
  2101. var pages = (this.ownPages != null) ? this.ownPages : this.ui.pages;
  2102. if (pages != null)
  2103. {
  2104. for (var i = 0; i < pages.length; i++)
  2105. {
  2106. var pageNode = pages[i].node;
  2107. if (pageNode != null && (this.ui.currentPage == null ||
  2108. this.ui.currentPage.getId() != pages[i].getId()))
  2109. {
  2110. var models = pageNode.getElementsByTagName('mxGraphModel');
  2111. var modelNode = (models.length > 0) ? models[0] : null;
  2112. var xml = Graph.decompress(mxUtils.getNodeValue(pageNode));
  2113. if (compressed)
  2114. {
  2115. if (xml.length == 0 && modelNode != null)
  2116. {
  2117. EditorUi.removeChildNodes(pageNode);
  2118. mxUtils.setTextContent(pageNode, Graph.compressNode(modelNode));
  2119. EditorUi.debug('DrawioFile.compressionChanged',
  2120. [this], 'Page ' + i + ' compressed');
  2121. }
  2122. }
  2123. else
  2124. {
  2125. if (xml.length > 0 && modelNode == null)
  2126. {
  2127. EditorUi.removeChildNodes(pageNode);
  2128. pageNode.appendChild(mxUtils.parseXml(xml).documentElement);
  2129. EditorUi.debug('DrawioFile.compressionChanged',
  2130. [this], 'Page ' + i + ' decompressed');
  2131. }
  2132. }
  2133. }
  2134. }
  2135. }
  2136. };
  2137. /**
  2138. * Adds the listener for automatically saving the diagram for local changes.
  2139. */
  2140. DrawioFile.prototype.fileReplaced = function(patches)
  2141. {
  2142. this.invalidChecksum = false;
  2143. this.inConflictState = false;
  2144. if (patches != null)
  2145. {
  2146. this.patch(patches);
  2147. }
  2148. if (this.sync != null)
  2149. {
  2150. this.sync.initRealtime();
  2151. }
  2152. EditorUi.debug('DrawioFile.fileReplaced', [this], 'patches', patches);
  2153. };
  2154. /**
  2155. * Adds the listener for automatically saving the diagram for local changes.
  2156. */
  2157. DrawioFile.prototype.fileChanged = function(sync)
  2158. {
  2159. sync = (sync != null) ? sync : true;
  2160. this.lastChanged = new Date();
  2161. this.setModified(true);
  2162. EditorUi.debug('DrawioFile.fileChanged', [this],
  2163. 'autosaveDelay', this.autosaveDelay,
  2164. 'autosave', this.isAutosave(),
  2165. 'saving', this.savingFile);
  2166. if (this.isAutosave())
  2167. {
  2168. if (this.savingStatusKey != null)
  2169. {
  2170. this.addAllSavedStatus(mxUtils.htmlEntities(mxResources.get(this.savingStatusKey)) + '...');
  2171. }
  2172. this.ui.scheduleSanityCheck();
  2173. if (this.ageStart == null)
  2174. {
  2175. this.ageStart = new Date();
  2176. }
  2177. this.autosave(this.autosaveDelay, this.maxAutosaveDelay, mxUtils.bind(this, function(resp)
  2178. {
  2179. this.ui.stopSanityCheck();
  2180. // Does not update status if another autosave was scheduled
  2181. if (this.autosaveThread == null)
  2182. {
  2183. this.handleFileSuccess(true);
  2184. this.ageStart = null;
  2185. }
  2186. else if (this.isModified())
  2187. {
  2188. this.ui.scheduleSanityCheck();
  2189. this.ageStart = this.lastChanged;
  2190. }
  2191. }), mxUtils.bind(this, function(err)
  2192. {
  2193. this.handleFileError(err);
  2194. }));
  2195. }
  2196. else
  2197. {
  2198. this.ageStart = null;
  2199. if ((!this.isAutosaveOptional() || !this.ui.editor.autosave) &&
  2200. !this.inConflictState)
  2201. {
  2202. this.addUnsavedStatus();
  2203. }
  2204. }
  2205. if (this.sync != null && sync)
  2206. {
  2207. this.sync.localFileChanged();
  2208. }
  2209. };
  2210. /**
  2211. * Creates a secret and token pair for writing a patch to the cache.
  2212. */
  2213. DrawioFile.prototype.createSecret = function(success)
  2214. {
  2215. var secret = Editor.guid(32);
  2216. if (Editor.enableRealtimeCache && this.sync != null &&
  2217. !this.isOptimisticSync())
  2218. {
  2219. this.sync.createToken(secret,
  2220. mxUtils.bind(this, function(token)
  2221. {
  2222. EditorUi.debug('DrawioFile.createSecret', [this],
  2223. 'secret', secret, 'token', token);
  2224. success(secret, token);
  2225. }), mxUtils.bind(this, function()
  2226. {
  2227. success(secret);
  2228. }));
  2229. }
  2230. else
  2231. {
  2232. success(secret);
  2233. }
  2234. };
  2235. /**
  2236. * Invokes sync and updates shadow document.
  2237. */
  2238. DrawioFile.prototype.fileSaving = function()
  2239. {
  2240. if (this.sync != null)
  2241. {
  2242. this.sync.fileSaving();
  2243. }
  2244. };
  2245. /**
  2246. * Invokes sync and updates shadow document.
  2247. */
  2248. DrawioFile.prototype.fileSaved = function(savedData, lastDesc, success, error, token, pages, checksum)
  2249. {
  2250. this.lastSaved = new Date();
  2251. this.ageStart = null;
  2252. this.stats.saved++;
  2253. try
  2254. {
  2255. this.inConflictState = false;
  2256. this.invalidChecksum = false;
  2257. pages = (pages != null) ? pages : this.ui.getPagesForXml(savedData);
  2258. try
  2259. {
  2260. if (this.sync == null || this.isOptimisticSync())
  2261. {
  2262. this.setShadowPages(pages);
  2263. if (this.sync != null)
  2264. {
  2265. this.sync.lastModified = this.getLastModifiedDate();
  2266. this.sync.resetUpdateStatusThread();
  2267. if (this.isRealtime())
  2268. {
  2269. this.sync.scheduleCleanup();
  2270. }
  2271. }
  2272. if (success != null)
  2273. {
  2274. success();
  2275. }
  2276. }
  2277. else
  2278. {
  2279. this.sync.fileSaved(pages, lastDesc,
  2280. success, error, token, checksum);
  2281. }
  2282. }
  2283. catch (e)
  2284. {
  2285. this.inConflictState = true;
  2286. this.invalidChecksum = true;
  2287. this.descriptorChanged();
  2288. if (error != null)
  2289. {
  2290. error(e);
  2291. }
  2292. try
  2293. {
  2294. var user = this.getCurrentUser();
  2295. var uid = (user != null) ? user.id : 'unknown';
  2296. EditorUi.logError('Error in fileSaved', null,
  2297. this.getMode() + '.' + this.getId(),
  2298. uid, e);
  2299. }
  2300. catch (e2)
  2301. {
  2302. // ignore
  2303. }
  2304. }
  2305. EditorUi.debug('DrawioFile.fileSaved', [this],
  2306. 'savedData', [savedData], 'desc', [lastDesc],
  2307. 'inConflictState', this.inConflictState,
  2308. 'invalidChecksum', this.invalidChecksum);
  2309. }
  2310. catch (e)
  2311. {
  2312. this.descriptorChanged();
  2313. if (error != null)
  2314. {
  2315. error(e);
  2316. }
  2317. }
  2318. };
  2319. /**
  2320. * Adds the listener for automatically saving the diagram for local changes.
  2321. */
  2322. DrawioFile.prototype.autosave = function(delay, maxDelay, success, error)
  2323. {
  2324. if (this.lastAutosave == null)
  2325. {
  2326. this.lastAutosave = Date.now();
  2327. }
  2328. var tmp = (Date.now() - this.lastAutosave < maxDelay) ? delay : 0;
  2329. this.clearAutosave();
  2330. // Starts new timer or executes immediately if not unsaved for maxDelay
  2331. var thread = window.setTimeout(mxUtils.bind(this, function()
  2332. {
  2333. try
  2334. {
  2335. this.lastAutosave = null;
  2336. if (this.autosaveThread == thread)
  2337. {
  2338. this.autosaveThread = null;
  2339. }
  2340. EditorUi.debug('DrawioFile.autosave', [this], 'thread', thread,
  2341. 'modified', this.isModified(), 'now', this.isAutosaveNow(),
  2342. 'saving', this.savingFile);
  2343. // Workaround for duplicate save if UI is blocking
  2344. // after save while pending autosave triggers
  2345. if (this.isModified() && this.isAutosaveNow())
  2346. {
  2347. var rev = this.isAutosaveRevision();
  2348. if (rev)
  2349. {
  2350. this.lastAutosaveRevision = new Date().getTime();
  2351. }
  2352. this.save(rev, mxUtils.bind(this, function(resp)
  2353. {
  2354. this.autosaveCompleted();
  2355. if (success != null)
  2356. {
  2357. success(resp);
  2358. }
  2359. }), mxUtils.bind(this, function(resp)
  2360. {
  2361. if (error != null)
  2362. {
  2363. error(resp);
  2364. }
  2365. }));
  2366. }
  2367. else
  2368. {
  2369. if (!this.isModified())
  2370. {
  2371. this.ui.editor.setStatus('');
  2372. }
  2373. if (success != null)
  2374. {
  2375. success(null);
  2376. }
  2377. }
  2378. }
  2379. catch (e)
  2380. {
  2381. if (error != null)
  2382. {
  2383. error(e);
  2384. }
  2385. }
  2386. }), tmp);
  2387. this.autosaveThread = thread;
  2388. EditorUi.debug('DrawioFile.autosave', [this], 'thread', thread,
  2389. 'delay', delay, 'maxDelay', maxDelay, 'actualDelay', tmp,
  2390. 'lastAutosave', this.lastAutosave, 'saving', this.savingFile);
  2391. };
  2392. /**
  2393. * Returns true if an autosave is required at the time of execution.
  2394. * This implementation returns true.
  2395. */
  2396. DrawioFile.prototype.isAutosaveNow = function()
  2397. {
  2398. return true;
  2399. };
  2400. /**
  2401. * Hooks for subclassers after the autosave has completed.
  2402. */
  2403. DrawioFile.prototype.autosaveCompleted = function() { };
  2404. /**
  2405. * Adds the listener for automatically saving the diagram for local changes.
  2406. */
  2407. DrawioFile.prototype.clearAutosave = function()
  2408. {
  2409. if (this.autosaveThread != null)
  2410. {
  2411. window.clearTimeout(this.autosaveThread);
  2412. this.autosaveThread = null;
  2413. }
  2414. };
  2415. /**
  2416. * Returns the location as a new object.
  2417. * @type mx.Point
  2418. */
  2419. DrawioFile.prototype.isAutosaveRevision = function()
  2420. {
  2421. var now = new Date().getTime();
  2422. return (this.lastAutosaveRevision == null) || (now - this.lastAutosaveRevision) > this.maxAutosaveRevisionDelay;
  2423. };
  2424. /**
  2425. * Translates this point by the given vector.
  2426. *
  2427. * @param {number} dx X-coordinate of the translation.
  2428. * @param {number} dy Y-coordinate of the translation.
  2429. */
  2430. DrawioFile.prototype.descriptorChanged = function()
  2431. {
  2432. this.fireEvent(new mxEventObject('descriptorChanged'));
  2433. };
  2434. /**
  2435. * Translates this point by the given vector.
  2436. *
  2437. * @param {number} dx X-coordinate of the translation.
  2438. * @param {number} dy Y-coordinate of the translation.
  2439. */
  2440. DrawioFile.prototype.contentChanged = function()
  2441. {
  2442. this.fireEvent(new mxEventObject('contentChanged'));
  2443. };
  2444. /**
  2445. * Returns the location as a new object.
  2446. */
  2447. DrawioFile.prototype.close = function(unloading)
  2448. {
  2449. try
  2450. {
  2451. if (this.isAutosave() && this.isModified())
  2452. {
  2453. this.updateFileData();
  2454. this.save(this.isAutosaveRevision(), null, null, unloading);
  2455. }
  2456. }
  2457. catch (e)
  2458. {
  2459. // ignore
  2460. }
  2461. this.stats.closed++;
  2462. this.destroy();
  2463. };
  2464. /**
  2465. * Returns the location as a new object.
  2466. */
  2467. DrawioFile.prototype.hasSameExtension = function(title, newTitle)
  2468. {
  2469. if (title != null && newTitle != null)
  2470. {
  2471. var dot = title.lastIndexOf('.');
  2472. var ext = (dot > 0) ? title.substring(dot) : '';
  2473. dot = newTitle.lastIndexOf('.');
  2474. return ext === ((dot > 0) ? newTitle.substring(dot) : '');
  2475. }
  2476. return title == newTitle;
  2477. };
  2478. /**
  2479. * Removes the change listener.
  2480. */
  2481. DrawioFile.prototype.removeListeners = function()
  2482. {
  2483. if (this.changeListener != null)
  2484. {
  2485. this.ui.editor.graph.model.removeListener(this.changeListener);
  2486. this.ui.editor.graph.removeListener(this.changeListener);
  2487. this.ui.removeListener(this.changeListener);
  2488. this.changeListener = null;
  2489. }
  2490. };
  2491. /**
  2492. * Stops any pending autosaves and removes all listeners.
  2493. */
  2494. DrawioFile.prototype.destroy = function()
  2495. {
  2496. this.clearAutosave();
  2497. this.removeListeners();
  2498. this.stats.destroyed++;
  2499. if (this.sync != null)
  2500. {
  2501. this.sync.destroy();
  2502. this.sync = null;
  2503. }
  2504. };
  2505. /**
  2506. * Are comments supported
  2507. */
  2508. DrawioFile.prototype.commentsSupported = function()
  2509. {
  2510. return false; //The default is false and files that support it must explicitly state that
  2511. };
  2512. /**
  2513. * Show refresh button?
  2514. */
  2515. DrawioFile.prototype.commentsRefreshNeeded = function()
  2516. {
  2517. return true;
  2518. };
  2519. /**
  2520. * Show save button?
  2521. */
  2522. DrawioFile.prototype.commentsSaveNeeded = function()
  2523. {
  2524. return false;
  2525. };
  2526. /**
  2527. * Get comments of the file
  2528. */
  2529. DrawioFile.prototype.getComments = function(success, error)
  2530. {
  2531. success([]); //placeholder
  2532. };
  2533. /**
  2534. * Add a comment to the file
  2535. */
  2536. DrawioFile.prototype.addComment = function(comment, success, error)
  2537. {
  2538. success(Date.now()); //placeholder
  2539. };
  2540. /**
  2541. * Can add a reply to a reply
  2542. */
  2543. DrawioFile.prototype.canReplyToReplies = function()
  2544. {
  2545. return true;
  2546. };
  2547. /**
  2548. * Can add comments (The permission to comment to this file)
  2549. */
  2550. DrawioFile.prototype.canComment = function()
  2551. {
  2552. return true;
  2553. };
  2554. /**
  2555. * Get a new comment object
  2556. */
  2557. DrawioFile.prototype.newComment = function(content, user)
  2558. {
  2559. return new DrawioComment(this, null, content, Date.now(), Date.now(), false, user);
  2560. };