Skip to content

draw.io is a JavaScript, client-side editor for general diagramming.

250 KB
Raw Blame
/**
 * Copyright (c) 2006-2020, JGraph Holdings Ltd
 * Copyright (c) 2006-2020, draw.io AG
 */

/**
 * Constructs a new application for the given editor in the given container.
 * If lightbox is null, it is derived from the URL parameters.
 */
App = function(editor, container, lightbox)
{
	EditorUi.call(this, editor, container, (lightbox != null) ? lightbox :
		(urlParams['lightbox'] == '1' || (uiTheme == 'min' &&
		urlParams['chrome'] != '0')));
	
	// Logs changes to autosave
	this.editor.addListener('autosaveChanged', mxUtils.bind(this, function()
	{
		var file = this.getCurrentFile();

		if (file != null)
		{
			EditorUi.logEvent({category: ((this.editor.autosave) ? 'ON' : 'OFF') +
				'-AUTOSAVE-FILE-' + EditorUi.getLogHash(file.getHash()), action: 'changed',
				label: 'autosave_' + ((this.editor.autosave) ? 'on' : 'off')});
		}
	}));

	// Counts this browser for the version dashboard once per day, and
	// again every hour so tabs that stay open for days are counted too
	if (!App.versionPingStarted)
	{
		App.versionPingStarted = true;
		App.pingVersion();
		window.setInterval(App.pingVersion, 3600000);
	}

	// Reloads this tab when a release channel switch (flagged by
	// switchReleaseChannel in any tab) activates the other channel's
	// service worker, so no tab keeps running one channel's shell against
	// the other channel's cache. Only with no unsaved changes.
	if (Editor.enableServiceWorker && ('serviceWorker' in navigator))
	{
		try
		{
			navigator.serviceWorker.addEventListener('controllerchange',
				mxUtils.bind(this, function()
			{
				try
				{
					var ts = parseInt(localStorage.getItem(
						'.drawio-channel-switch-ts'), 10);
					var elapsed = Date.now() - ts;

					if (!isNaN(elapsed) && elapsed >= 0 && elapsed < 600000 &&
						(this.getCurrentFile() == null ||
						!this.getCurrentFile().isModified()))
					{
						window.location.reload();
					}
				}
				catch (e)
				{
					// ignore
				}
			}));
		}
		catch (e)
		{
			// ignore
		}
	}
	
	// Pre-fetches images
	if (mxClient.IS_SVG)
	{
		mxGraph.prototype.warningImage.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAE7SURBVHjaYvz//z8DJQAggBjwGXDuHMP/tWuD/uPTCxBAOA0AaQRK/f/+XeJ/cbHlf1wGAAQQTgPu3QNLgfHSpZo4DQAIIKwGwGyH4e/fFbG6AiQJEEAs2Ew2NFzH8OOHBMO6dT/A/KCg7wxGRh+wuhQggDBcALMdFIAcHBxgDGJjcwVIIUAAYbhAUXEdVos4OO4DXcGBIQ4QQCguQPY7sgtgAYruCpAgQACx4LJdU1OCwctLEcyWlLwPJF+AXQE0EMUBAAEEdwF6yMOiD4RRY0QT7gqQAEAAseDzu6XldYYPH9DD4joQa8L5AAEENgWb7SBcXa0JDQMBrK4AcQACiAlfyOMCEFdAnAYQQEz4FLa0XGf4/v0H0IIPONUABBAjyBmMjIwMS5cK/L927QORbtBkaG29DtYLEGAAH6f7oq3Zc+kAAAAASUVORK5CYII=';
	}
	else
	{
		var img = new Image();
		img.src = mxGraph.prototype.warningImage.src;
	}
	
	// Global helper method to deal with popup blockers
	window.geOpenWindow = mxUtils.bind(this, function(url, pre, fallback)
	{
		if (urlParams['openInSameWin'] == '1' || navigator.standalone)
		{
			if (fallback != null)
			{
				fallback();
			}
		}
		else
		{
			var wnd = null;
			
			try
			{
				wnd = window.open(url);
			}
			catch (e)
			{
				// ignore
			}
			
			if (wnd == null || wnd === undefined)
			{
				this.showDialog(new PopupDialog(this, url,pre, fallback).
					container, 340, 140, true, true);
			}
			else if (pre != null)
			{
				pre();
			}
		}
	});

	// Initial state for toolbar items is disabled
	this.updateDocumentTitle();
	this.updateUi();

	// Global helper method to display error messages
	window.showOpenAlert = mxUtils.bind(this, function(message)
	{
		// Cancel must be called before showing error message
		if (window.openFile != null)
		{
			window.openFile.cancel(true);
		}
		
		this.handleError(message);
	});

	// Handles opening files via drag and drop
	if (!this.editor.chromeless || this.editor.editable)
	{
		this.addFileDropHandler([document]);
	}
	
	// Process the queue for waiting plugins
	if (App.DrawPlugins != null)
	{
		for (var i = 0; i < App.DrawPlugins.length; i++)
		{
			try
			{
				App.DrawPlugins[i](this);
			}
			catch (e)
			{
				if (window.console != null)
				{
					console.log('Plugin Error:', e, App.DrawPlugins[i]);
				}
			}
			finally
			{
				App.embedModePluginsCount--;
				this.initializeEmbedMode();
			}
		}
		
		// Installs global callback for plugins
		window.Draw.loadPlugin = mxUtils.bind(this, function(callback)
		{
			try
			{
				callback(this);
			}
			finally
			{
				App.embedModePluginsCount--;
				this.initializeEmbedMode();
			}
		});
		
		//Set a timeout in case a plugin doesn't load quickly or doesn't load at all
		setTimeout(mxUtils.bind(this, function()
		{
			//Force finish loading if its not yet called
			if (App.embedModePluginsCount > 0)
			{
				App.embedModePluginsCount = 0;
				this.initializeEmbedMode();
			}
		}), 5000); //5 sec timeout
	}

	this.load();
};

/**
 * Timeout error
 */
App.ERROR_TIMEOUT = 'timeout';

/**
 * Busy error
 */
App.ERROR_BUSY = 'busy';

/**
 * Unknown error
 */
App.ERROR_UNKNOWN = 'unknown';

/**
 * Google drive mode
 */
App.MODE_GOOGLE = 'google';

/**
 * OneDrive Mode
 */
App.MODE_ONEDRIVE = 'onedrive';

/**
 * M365 Mode
 */
App.MODE_M365 = 'm365';

/**
 * Github Mode
 */
App.MODE_GITHUB = 'github';

/**
 * Gitlab mode
 */
App.MODE_GITLAB = 'gitlab';

/**
 * Device Mode
 */
App.MODE_DEVICE = 'device';

/**
 * Browser Mode
 */
App.MODE_BROWSER = 'browser';

/**
 * Trello App Mode
 */
App.MODE_TRELLO = 'trello';

/**
 * Embed App Mode
 */
App.MODE_EMBED = 'embed';

/**
 * Atlas App Mode
 */
App.MODE_ATLAS = 'atlas';

/**
 * Storages by mode: the property of the client in the App (client), the
 * resource key of the name (title), the first character of the hash of
 * files (char), the logo in IMAGE_PATH (logo), the logo of the app icon
 * on hover and its size (iconLogo, iconLogoSize) and the start page (url).
 * Has no prototype, as modes come from URLs and storage.
 */
App.storages = Object.create(null);

App.storages[App.MODE_GOOGLE] = {client: 'drive', title: 'googleDrive', char: 'G',
	logo: 'google-drive-logo.svg', iconLogo: 'google-drive-logo-white.svg',
	url: 'https://drive.google.com/?authuser=0'};
App.storages[App.MODE_ONEDRIVE] = {client: 'oneDrive', title: 'oneDrive', char: 'W',
	logo: 'onedrive-logo.svg', iconLogo: 'onedrive-logo-white.svg',
	url: 'https://onedrive.live.com/'};
App.storages[App.MODE_M365] = {client: 'm365', title: 'm365', char: 'M',
	logo: 'onedrive-logo.svg'};
App.storages[App.MODE_GITHUB] = {client: 'gitHub', title: 'github', char: 'H',
	logo: 'github-logo.svg', iconLogo: 'github-logo-white.svg',
	url: 'https://github.com/'};
App.storages[App.MODE_GITLAB] = {client: 'gitLab', title: 'gitlab', char: 'A',
	logo: 'gitlab-logo.svg', iconLogo: 'gitlab-logo-white.svg', iconLogoSize: '90%',
	// Configurable (see Init.js)
	get url() { return window.DRAWIO_GITLAB_URL; }};
App.storages[App.MODE_TRELLO] = {client: 'trello', title: 'trello', char: 'T',
	logo: 'trello-logo.svg', iconLogo: 'trello-logo-white-orange.svg',
	url: 'https://trello.com/'};
App.storages[App.MODE_DEVICE] = {title: 'device', logo: 'osa_drive-harddisk.png',
	url: 'https://get.draw.io/'};
App.storages[App.MODE_BROWSER] = {title: 'browser', logo: 'osa_database.png'};

/**
 * OneDrive Client JS (file/folder picker). This is a slightly modified version to allow using accessTokens.
 */
App.ONEDRIVE_URL = 'js/onedrive/OneDrive.js';

/**
 * Trello URL
 */
App.TRELLO_URL = 'https://api.trello.com/1/client.js';

/**
 * Trello JQuery dependency
 */
App.TRELLO_JQUERY_URL = 'js/jquery/jquery-3.6.0.min.js';

/**
 * SimplePeer library 
 */
App.SIMPLE_PEER_URL = 'js/simplepeer/simplepeer9.10.0.min.js';

/**
 * Google APIs to load. The realtime API is needed to notify collaborators of conversion
 * of the realtime files, but after Dec 11 it's read-only and hence no longer needed.
 */
App.GOOGLE_APIS = 'drive-share'; 

/**
 * Function: authorize
 * 
 * Authorizes the client, gets the userId and calls <open>.
 */
App.startTime = new Date();

/**
 * Defines plugin IDs for loading via p URL parameter. Update the table at
 * https://www.drawio.com/doc/faq/supported-url-parameters
 */
App.pluginRegistry = {'ex': 'plugins/explore.js',
	'ac': 'plugins/connect.js', 'acj': 'plugins/connectJira.js',
	'ac148': 'plugins/cConf-1-4-8.js', 'ac148cmnt': 'plugins/cConf-comments.js', 
	'nxtcld': 'plugins/nextcloud.js',
	'monday': 'plugins/monday.js',
	'svgdata': 'plugins/svgdata.js',
	'number': 'plugins/number.js',
	'props': 'plugins/props.js', 'text': 'plugins/text.js',
	'update': 'plugins/update.js',
	'trees': 'plugins/trees/trees.js',
	'replay': 'plugins/replay.js', 'anon': 'plugins/anonymize.js',
	'tr': 'plugins/trello.js',
	'rnd': 'plugins/random.js',
	'tags': 'plugins/tags.js'};

App.publicPlugin = [
	'ex',
	'svgdata',
	'number',
	'props',
	'text',
	'update',
	'trees',
	'replay',
	'anon',
//	'rnd',
	'tags'
];

/**
 * Loads all given scripts and invokes onload after
 * all scripts have finished loading.
 */
App.loadScripts = function(scripts, onload, onerror)
{
	var n = scripts.length;
	var failed = false;
	
	for (var i = 0; i < scripts.length; i++)
	{
		mxscript(scripts[i], function()
		{
			if (--n == 0 && !failed && onload != null)
			{
				onload();
			}
		}, null, null, null, function(message, e)
		{
			failed = true;

			if (onerror != null)
			{
				onerror(new Error(message));
			}

			console.error('Error loading script', message, e, e.stack);
		});
	}
};

/**
 * Function: getStoredMode
 * 
 * Returns the current mode.
 */
App.getStoredMode = function()
{
	var mode = null;
	
	if (mode == null && isLocalStorage)
	{
		mode = localStorage.getItem('.mode');
	}
	
	if (mode == null && typeof(Storage) != 'undefined')
	{
		try
		{
			var cookies = document.cookie.split(";");
			
			for (var i = 0; i < cookies.length; i++)
			{
				// Removes spaces around cookie
				var cookie = mxUtils.trim(cookies[i]);
				
				if (cookie.substring(0, 5) == 'MODE=')
				{
					mode = cookie.substring(5);
					break;
				}
			}
			
			if (mode != null && isLocalStorage)
			{
				// Moves to local storage
				var expiry = new Date();
				expiry.setYear(expiry.getFullYear() - 1);
				document.cookie = 'MODE=; expires=' + expiry.toUTCString();
				localStorage.setItem('.mode', mode);
			}
		}
		catch (e)
		{
			// ignore
		}
	}
	
	return mode;
};

/**
 * Function: isKnownMode
 *
 * Returns true if the given mode has a storage or is embed or atlas. Stored
 * and requested modes may be for a storage that has been removed (eg.
 * dropbox).
 */
App.isKnownMode = function(mode)
{
	return App.storages[mode] != null ||
		mode == App.MODE_EMBED || mode == App.MODE_ATLAS;
};

/**
 * Static Application initializer executed at load-time.
 */
(function()
{
	if (!mxClient.IS_CHROMEAPP)
	{
		if (urlParams['offline'] != '1')
		{
			App.mode = urlParams['mode'];
		}
		
		if (App.mode == null && urlParams['embed'] != '1')
		{
			// Stored mode overrides preferred mode
			App.mode = App.getStoredMode();
		}
		
		/**
		 * Lazy loading backends.
		 */
		if (window.mxscript != null)
		{
			// Loads gapi for all browsers but IE8 and below if not disabled or if enabled and in embed mode
			if (urlParams['embed'] != '1')
			{
				if (typeof window.DriveClient === 'function')
				{
					if (urlParams['gapi'] != '0' && isSvgBrowser &&
						(document.documentMode == null || document.documentMode >= 10))
					{
						// Immediately loads client
						if (App.mode == App.MODE_GOOGLE || (urlParams['state'] != null &&
							window.location.hash == '') || (window.location.hash != null &&
							window.location.hash.substring(0, 2) == '#G'))
						{
							mxscript('https://apis.google.com/js/api.js');
						}
						// Keeps lazy loading for fallback to authenticated Google file if not public in loadFile
						else if (urlParams['chrome'] == '0' && (window.location.hash == null ||
							window.location.hash.substring(0, 45) !== '#Uhttps%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D'))
						{
							// Disables loading of client
							window.DriveClient = null;
						}
					}
					else
					{
						// Disables loading of client
						window.DriveClient = null;
					}
				}
	
				// Enables OneDrive for all browsers but IE6/IOS if not disabled or if enabled and in embed mode
				if (typeof window.OneDriveClient === 'function')
				{
					if (urlParams['od'] != '0' && (navigator.userAgent == null ||
						navigator.userAgent.indexOf('MSIE') < 0 || document.documentMode >= 10))
					{
						// Disables the client in chromeless mode unless a OneDrive file is opened
						if (urlParams['chrome'] == '0' && App.mode != App.MODE_ONEDRIVE && App.mode != App.MODE_M365 &&
							(window.location.hash == null || (window.location.hash.substring(0, 2) != '#W' &&
							window.location.hash.substring(0, 2) != '#M')))
						{
							window.OneDriveClient = null;
						}
					}
					else
					{
						// Disables loading of client
						window.OneDriveClient = null;
					}
				}
				
				// Loads Trello if not disabled or if enabled and in embed mode
				if (typeof window.TrelloClient === 'function')
				{
					if (urlParams['tr'] == '1' && isSvgBrowser)
					{
						// Immediately loads client
						if (App.mode == App.MODE_TRELLO || (window.location.hash != null &&
							window.location.hash.substring(0, 2) == '#T'))
						{
							mxscript(App.TRELLO_JQUERY_URL, function()
							{
								mxscript(App.TRELLO_URL);
							});
						}
						else if (urlParams['chrome'] == '0')
						{
							window.TrelloClient = null;
						}
					}
					else
					{
						// Disables loading of client
						window.TrelloClient = null;
					}
				}
			}
		}
	}
})();

/**
 * Clears the PWA cache.
 */
App.clearServiceWorker = function(success, error)
{
	try
	{
		// A cleared PWA cache also resets the release channel state.
		localStorage.removeItem('.drawio-channel');
		localStorage.removeItem('.drawio-channel-ts');
		localStorage.removeItem('.drawio-channel-swerr-ts');
		localStorage.removeItem('.drawio-channel-swfail');
		localStorage.removeItem('.drawio-channel-switch-ts');
	}
	catch (e)
	{
		// ignore
	}

	navigator.serviceWorker.getRegistration().then(function(reg)
	{
		if (reg != null)
		{
			return reg.unregister().then(function()
			{
				if (success != null)
				{
					success();
					success = null;
				}
			});
		}
		else if (success != null)
		{
			success();
			success = null;
		}
	})['catch'](function()
	{
		if (error != null)
		{
			error();
		}
	});
};

/**
 * Checks for an updated service worker and invokes done once the new
 * worker is activated, at once when no update is installing, or after
 * the timeout (default 15s). Used before a forced reload: the reload is
 * then served from the new precache in one load instead of the usual
 * two (a plain reload is served by the old worker and only triggers the
 * update in the background). Deleting the cache would not help - the
 * old worker refetches the revisions of its own manifest on a miss.
 */
App.updateServiceWorker = function(done, timeout)
{
	var finished = false;
	var thread = null;

	var finish = function()
	{
		if (!finished)
		{
			finished = true;
			window.clearTimeout(thread);
			done();
		}
	};

	thread = window.setTimeout(finish, (timeout != null) ? timeout : 15000);

	try
	{
		if (Editor.enableServiceWorker && ('serviceWorker' in navigator) &&
			navigator.serviceWorker.controller != null)
		{
			navigator.serviceWorker.getRegistration().then(function(reg)
			{
				if (reg == null)
				{
					finish();
				}
				else
				{
					reg.update().then(function(updated)
					{
						var current = (updated != null) ? updated : reg;
						var sw = current.installing || current.waiting;

						if (sw != null)
						{
							// The worker calls skipWaiting, so activated
							// follows the install directly; redundant is a
							// failed install
							var check = function()
							{
								if (sw.state == 'activated' || sw.state == 'redundant')
								{
									finish();
								}
							};

							sw.addEventListener('statechange', check);
							check();
						}
						else
						{
							finish();
						}
					})['catch'](finish);
				}
			})['catch'](finish);
		}
		else
		{
			finish();
		}
	}
	catch (e)
	{
		finish();
	}
};

/**
 * Returns 'stable' if this browser is pinned to the stable release channel,
 * or null for the default (beta) channel.
 */
App.getReleaseChannel = function()
{
	try
	{
		return (isLocalStorage && localStorage.getItem('.drawio-channel') ==
			'stable') ? 'stable' : null;
	}
	catch (e)
	{
		return null;
	}
};

/**
 * Stores the release channel ('stable' or null for beta).
 */
App.setReleaseChannel = function(channel)
{
	try
	{
		if (channel == 'stable')
		{
			localStorage.setItem('.drawio-channel', 'stable');
		}
		else
		{
			localStorage.removeItem('.drawio-channel');
		}
	}
	catch (e)
	{
		// ignore
	}
};

/**
 * Counts this browser once per UTC day for each app version it runs, for
 * the version dashboard (release-monitor /versions). The stamps stay in
 * localStorage, so the request carries no cookie or ID: only the version,
 * the hostname, whether the stable channel's service worker serves the
 * page, and whether this is the browser's first ping of the day (d), of
 * the week starting on Monday (w) and of the month (m), which give the
 * daily, weekly and monthly actives. Without localStorage each page load
 * counts once a day.
 */
App.pingVersion = function()
{
	var now = new Date();
	var day = now.toISOString().substring(0, 10);

	if (EditorUi.enableLogging && urlParams['dev'] != '1' &&
		App.lastVersionPing != day)
	{
		var week = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(),
			now.getUTCDate() - (now.getUTCDay() + 6) % 7)).toISOString().substring(0, 10);
		var month = day.substring(0, 7);
		var key = '.drawio-version-ping';
		var stamp = null;
		App.lastVersionPing = day;

		try
		{
			stamp = (isLocalStorage) ? JSON.parse(localStorage.getItem(key)) : null;
		}
		catch (e)
		{
			// ignore
		}

		stamp = (stamp != null && typeof stamp === 'object') ? stamp : {};
		var versions = (stamp.d == day && Array.isArray(stamp.v)) ? stamp.v : [];

		if (mxUtils.indexOf(versions, EditorUi.VERSION) < 0)
		{
			var stable = false;

			try
			{
				var sw = ('serviceWorker' in navigator) ?
					navigator.serviceWorker.controller : null;
				stable = sw != null && sw.scriptURL.indexOf('/stable/') >= 0;
			}
			catch (e)
			{
				// ignore
			}

			try
			{
				var img = new Image();
				img.src = window.DRAWIO_LOG_URL + '/log?ping=1' +
					'&v=' + encodeURIComponent(EditorUi.VERSION) +
					'&host=' + encodeURIComponent(window.location.hostname) +
					((stable) ? '&channel=stable' : '') +
					((versions.length == 0) ? '&d=1' : '') +
					((stamp.w != week) ? '&w=1' : '') +
					((stamp.m != month) ? '&m=1' : '');
				versions.push(EditorUi.VERSION);

				if (isLocalStorage)
				{
					localStorage.setItem(key, JSON.stringify({d: day,
						v: versions, w: week, m: month}));
				}
			}
			catch (e)
			{
				// ignore
			}
		}
	}
};

/**
 * Rate-limited (one report per day) logging for service worker failures,
 * plus a distinct-day failure counter for the stable channel that drives
 * the automatic fallback to beta in App.main.
 */
App.logServiceWorkerError = function(swUrl, e)
{
	try
	{
		EditorUi.debug('App.logServiceWorkerError', swUrl, e);

		var now = Date.now();
		var ts = parseInt(localStorage.getItem('.drawio-channel-swerr-ts'), 10);
		var elapsed = now - ts;

		if (isNaN(elapsed) || elapsed < 0 || elapsed >= 86400000)
		{
			localStorage.setItem('.drawio-channel-swerr-ts', String(now));

			if (App.getReleaseChannel() == 'stable')
			{
				localStorage.setItem('.drawio-channel-swfail',
					String(App.getServiceWorkerFailures() + 1));
			}

			EditorUi.logError('Service worker error: ' + swUrl,
				null, null, null, e);
		}
	}
	catch (e2)
	{
		// ignore
	}
};

/**
 * Returns the number of distinct days with stable channel failures.
 */
App.getServiceWorkerFailures = function()
{
	try
	{
		return parseInt(localStorage.getItem('.drawio-channel-swfail'), 10) || 0;
	}
	catch (e)
	{
		return 0;
	}
};

/**
 * Resets the service worker failure counter and report timestamp.
 */
App.resetServiceWorkerFailures = function()
{
	try
	{
		localStorage.removeItem('.drawio-channel-swfail');
		localStorage.removeItem('.drawio-channel-swerr-ts');
	}
	catch (e)
	{
		// ignore
	}
};

/**
 * Returns true if the given link is on the same domain as this app.
 */
App.isSameDomain = function(link)
{
	var a = document.createElement('a');
	a.href = link;

	return a.protocol === window.location.protocol &&
		a.host === window.location.host;
};

/**
 * Returns true if the given relative path is a built-in plugin. Accepts the
 * path as stored in App.pluginRegistry and the leading slash form used before
 * the registry was made relative, as resolved against PLUGINS_BASE_PATH by
 * the caller. Both forms are built from the registry so that the given path
 * is only ever compared, never rewritten.
 */
App.isBuiltInPlugin = function(path)
{
	for (var key in App.pluginRegistry)
	{
		var plugin = App.pluginRegistry[key];

		if (plugin === path || PLUGINS_BASE_PATH + '/' + plugin === path)
		{
			return true;
		}
	}

	return false;
};

/**
 * Maps removed plugins to the built-in feature that replaced them. Keys are
 * the ID for the p URL parameter and the path as stored in the plugins
 * setting, with and without the leading slash used before the registry was
 * made relative, so existing URLs and installs keep working.
 */
App.retiredPlugins = {'tips': 'tooltipIcons',
	'plugins/tooltips.js': 'tooltipIcons',
	'/plugins/tooltips.js': 'tooltipIcons'};

/**
 * Enables the built-in replacement for the given removed plugin and returns
 * true if it was retired and must not be loaded. Called before Editor.configure
 * so an explicit setting for the replacement still takes precedence.
 */
App.applyRetiredPlugin = function(idOrPath)
{
	// Own property only so an ID like constructor cannot match Object.prototype
	var replacement = (idOrPath != null && Object.prototype.hasOwnProperty.call(
		App.retiredPlugins, idOrPath)) ? App.retiredPlugins[idOrPath] : null;

	// plugins/tooltips.js drew its own icon on cells with a tooltip
	if (replacement == 'tooltipIcons')
	{
		Editor.showTooltipIcons = true;
	}

	if (replacement != null && window.console != null)
	{
		console.log('Retired plugin:', idOrPath, 'replaced by', replacement);
	}

	return replacement != null;
};

/**
 * 
 */
App.isSimpleThemePreferred = function()
{
	var iw = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
	var userAgent = navigator.userAgent || navigator.vendor || window.opera;
	
	return (iw <= 1024 ||  /android/i.test(userAgent) || (/iPad|iPhone|iPod/.test(userAgent) &&
		!window.MSStream) || (navigator.userAgent.match(/Mac/) &&
		navigator.maxTouchPoints && navigator.maxTouchPoints > 2));
};

/**
 * Program flow starts here.
 * 
 * Optional callback is called with the app instance.
 */
App.main = function(callback, createUi)
{
	try
	{
		// This function is called only once, so we can set the flag here
		// Safari calls window.load event when the location hash is set (e.g, on descriptor change) resulting in calling main twice
		if (App.isMainCalled) 
		{
			return;
		}

		// Checks if electron is defined in Electron app
		if (mxIsElectron && typeof electron === 'undefined')
		{
			alert('Runtime Environment not found.');
			document.body.innerHTML = '<div style="grid-column:1 / -1;grid-row:1 / -1;margin-top:10%;text-align:center;">' +
				'<img src="mxgraph/images/warning.png" align="top" style="padding-right:6px;"/>' +
				'Runtime Environment not found.</div>';
			
			return;
		}

		// Replaces light-dark color functions with light colors for older browsers
		Editor.loadCompatibleCss();

		App.isMainCalled = true;

		// Declares the language of the user interface for screen readers, which
		// is the default language if there are no resources for mxLanguage
		document.documentElement.setAttribute('lang', (mxLanguage != null &&
			mxResources.isLanguageSupported(mxLanguage)) ? mxLanguage :
			mxClient.defaultLanguage);

		// Detects Android tablets using Chrome's "Request Desktop Site"
		// mode where the user agent shows Linux instead of Android.
		// Use android=1 to force or android=0 to suppress detection.
		if (urlParams['android'] == '1' || (urlParams['android'] != '0' &&
			!mxClient.IS_ANDROID && mxClient.IS_LINUX && mxClient.IS_GC &&
			navigator.maxTouchPoints > 1))
		{
			mxClient.IS_ANDROID = true;
		}

		// Handles uncaught errors before the app is loaded
		window.onerror = function(message, url, linenumber, colno, err)
		{
			// Ignores errors of foreign scripts which carry no information
			if (EditorUi.isOpaqueScriptError(message, linenumber))
			{
				return;
			}

			EditorUi.logError('Global: ' + ((message != null) ? message : ''),
				url, linenumber, colno, err, null, true);
			
			if (window.console != null && !EditorUi.isElectronApp)
			{
				console.error('Message:', message, '\nURL:', url, '\nLine:',
					linenumber, '\nColumn:', colno, '\nError:', err);
			}
			else
			{
				mxLog.show();
				mxLog.debug('Message:', message, '\nURL:', url, '\nLine:',
					linenumber, '\nColumn:', colno, '\nError:', err);
			}

			// Waits for page and console output to appear
			window.setTimeout(function()
			{
				alert('Error: ' + ((message != null) ? message : ''));
			}, 100);
		};

		// Blocks stand-alone mode for certain subdomains
		if (window.top == window.self &&
			('import.diagrams.net' === window.location.hostname ||
			'ac.draw.io' === window.location.hostname ||
			'aj.draw.io' === window.location.hostname))
		{
			document.body.innerHTML = '<div style="grid-column:1 / -1;grid-row:1 / -1;margin-top:10%;text-align:center;">Stand-alone mode not allowed for this domain.</div>';
			
			return;
		}
		
		// Removes info text in embed mode
		if (urlParams['embed'] == '1' || urlParams['lightbox'] == '1')
		{
			var geInfo = document.getElementById('geInfo');
			
			if (geInfo != null)
			{
				geInfo.parentNode.removeChild(geInfo);
			}
		}

		// Adds embed CSS class
		if (urlParams['embed'] == '1')
		{
			document.body.classList.add('geEmbed');
		}
		
		// Redirects to the latest AWS icons
		if (document.referrer != null && urlParams['libs'] == 'aws3' &&
			document.referrer.substring(0, 42) == 'https://aws.amazon.com/architecture/icons/')
		{
			urlParams['libs'] = 'aws4';
		}
		
		if (window.mxscript != null)
		{
			try
			{
				// Removes PWA cache on www.draw.io to force use of new domain via redirect
				if (Editor.enableServiceWorker && (urlParams['offline'] == '0' ||
					/www\.draw\.io$/.test(window.location.hostname) ||
					(urlParams['offline'] != '1' && urlParams['enableSW'] != '1' &&
						urlParams['dev'] == '1')))
				{
					EditorUi.debug('App.main', 'Uninstalling service worker');

					App.clearServiceWorker(function()
					{
						if (urlParams['offline'] == '0')
						{
							alert('Cache cleared');
						}
					});
				}
				else if (Editor.enableServiceWorker)
				{
					navigator.serviceWorker.getRegistration().then(function(reg)
					{
						// The registration URL is the release channel: the stable
						// script is served via the edge route to the pinned build
						// and needs scope '/' (Service-Worker-Allowed header).
						var stable = App.getReleaseChannel() == 'stable';

						// Frozen-but-working must not become permanent: after
						// two weeks of distinct-day stable service worker
						// failures, fall back to the default channel.
						if (stable && App.getServiceWorkerFailures() >= 14)
						{
							EditorUi.debug('App.main',
								'Stable channel failing, reverting to beta');
							App.setReleaseChannel(null);
							App.resetServiceWorkerFailures();
							stable = false;
						}

						var swUrl = (stable) ? 'stable/service-worker.js' :
							'service-worker.js';
						var current = (reg != null) ? (reg.active || reg.waiting ||
							reg.installing) : null;

						if (current != null && stable ==
							/\/stable\/service-worker\.js$/.test(current.scriptURL))
						{
							EditorUi.debug('App.main', 'Updating service worker');
							reg.update().then(function()
							{
								App.resetServiceWorkerFailures();
							})['catch'](function(e)
							{
								App.logServiceWorkerError(swUrl, e);
							});
						}
						// Skips service worker install on first load unless the
						// channel was pinned (eg. via the ?channel= link) or the
						// installed worker is on the wrong channel
						else if (current != null || App.getReleaseChannel() != null ||
							!Editor.isSettingsEnabled() || (mxSettings.settings != null &&
							!mxSettings.settings.isNew) || urlParams['enableSW'] == '1')
						{
							EditorUi.debug('App.main', 'Installing service worker', swUrl);
							navigator.serviceWorker.register(swUrl, {scope: './'}).then(function()
							{
								App.resetServiceWorkerFailures();
							})['catch'](function(e)
							{
								App.logServiceWorkerError(swUrl, e);
							});
						}
						else
						{
							EditorUi.debug('App.main', 'Skipping service worker (first load)');
						}
					});
				}
			}
			catch (e)
			{
				// ignore
			}
			
			// Loads SimplePeer for WebRTC between collaborators (fast-sync=1)
			if (urlParams['fast-sync'] == '1' && ('ArrayBuffer' in window) &&
				!mxClient.IS_CHROMEAPP && !EditorUi.isElectronApp &&
				DrawioFile.SYNC == 'auto' && (urlParams['embed'] != '1' ||
				urlParams['embedRT'] == '1') && urlParams['lockdown'] != '1' &&
				urlParams['local'] != '1' &&
				(urlParams['chrome'] != '0' || urlParams['rt'] == '1') &&
				urlParams['stealth'] != '1' && urlParams['offline'] != '1')
			{
				mxscript(App.SIMPLE_PEER_URL);
			}
			
			// Loads plugins
			if (urlParams['plugins'] != '0' && urlParams['offline'] != '1')
			{
				// mxSettings is not yet initialized in configure mode, redirect parameter
				// to p URL parameter in caller for plugins in embed mode
				var plugins = (mxSettings.settings != null) ? mxSettings.getPlugins() : null;
				
				// Configured plugins in embed mode with configure=1 URL should be loaded so we
				// look ahead here and parse the config to fetch the list of custom plugins
				if (mxSettings.settings == null && isLocalStorage && typeof(JSON) !== 'undefined')
				{
					try
					{
						var temp = JSON.parse(localStorage.getItem(mxSettings.key));
						
						if (temp != null)
						{
							plugins = temp.plugins;
						}
					}
					catch (e)
					{
						// ignore
					}
				}

				var temp = urlParams['p'];
				App.initPluginCallback();

				if (temp != null)
				{
					// Mapping from key to URL in App.plugins
					App.loadPlugins(temp.split(';'));
				}
				
				if (plugins != null && plugins.length > 0 && urlParams['plugins'] != '0')
				{
					for (var i = 0; i < plugins.length; i++)
					{
						try
						{
							if (App.applyRetiredPlugin(plugins[i]))
							{
								continue;
							}

							if (plugins[i].charAt(0) == '/')
							{
								plugins[i] = PLUGINS_BASE_PATH + plugins[i];
							}

							if (!App.isSameDomain(plugins[i]))
							{
								if (window.console != null)
								{
									console.log('Blocked plugin:', plugins[i]);
								}
							}
							else if (!ALLOW_CUSTOM_PLUGINS && !App.isBuiltInPlugin(plugins[i]))
							{
								if (window.console != null)
								{
									console.log('Unknown plugin:', plugins[i]);
								}
							}
							else if (App.pluginsLoaded[plugins[i]] == null)
							{
								App.pluginsLoaded[plugins[i]] = true;
								App.embedModePluginsCount++;
								mxscript(plugins[i]);
							}
						}
						catch (e)
						{
							// ignore
						}
					}
				}
			}
			
			// Loads gapi for all browsers but IE8 and below if not disabled or if enabled and in embed mode
			// Special case: Cannot load in asynchronous code below
			if (typeof window.DriveClient === 'function' &&
				(typeof gapi === 'undefined' && (((urlParams['embed'] != '1' && urlParams['gapi'] != '0') ||
				(urlParams['embed'] == '1' && urlParams['gapi'] == '1')) && isSvgBrowser &&
				isLocalStorage && (document.documentMode == null || document.documentMode >= 10))))
			{
				mxscript('https://apis.google.com/js/api.js?onload=DrawGapiClientCallback', null, null, null, mxClient.IS_SVG);
			}
			// Disables client
			else if (typeof window.gapi === 'undefined')
			{
				window.DriveClient = null;
			}
		}
		
		/**
		 * Asynchronous MathJax extension.
		 */
		if (urlParams['math'] != '0')
		{
			Editor.initMath();
		}

		function doLoad(bundle)
		{
			// Prefetches asynchronous requests so that below code runs synchronous
			// Loading the correct bundle (one file) via the fallback system in mxResources. The stylesheet
			// is compiled into JS in the build process and is only needed for local development.
			mxUtils.getAll((urlParams['dev'] != '1') ? [bundle] : [bundle,
				STYLE_PATH + '/default.xml'], function(xhr)
			{
				// Adds bundle text to resources
				mxResources.parse(xhr[0].getText());
				
				// Adds the bundle to the offline cache: language files are
				// cached on first use instead of being precached, and on the
				// very first visit this page is not yet controlled by the
				// service worker, so the request above bypassed it. In dev
				// mode also fills the missing dev sources - an offline dev
				// reload needs the complete set, not just the files this
				// session finished caching (see GenerateServiceWorker)
				try
				{
					if ('serviceWorker' in navigator)
					{
						navigator.serviceWorker.ready.then(function(reg)
						{
							if (reg.active != null)
							{
								reg.active.postMessage({warmLazy: bundle,
									warmDev: urlParams['dev'] == '1'});

								// Languages configured as installed by
								// default - each code is validated against
								// the lazy manifest by the service worker
								if (Editor.defaultLanguages != null)
								{
									for (var i = 0; i < Editor.defaultLanguages.length; i++)
									{
										var lang = Editor.defaultLanguages[i];

										if (typeof lang === 'string' &&
											/^[a-z0-9-]+$/.test(lang))
										{
											reg.active.postMessage({warmLazy:
												'resources/dia_' + lang + '.txt'});
										}
									}
								}
							}
						});
					}
				}
				catch (e)
				{
					// ignore
				}

				// Configuration mode
				if (isLocalStorage && localStorage != null && window.location.hash != null &&
					window.location.hash.substring(0, 9) == '#_CONFIG_')
				{
					try
					{
						var value = JSON.parse(Graph.decompress(window.location.hash.substring(9)));

						if (value != null)
						{
							EditorUi.debug('Setting configuration', JSON.stringify(value));
							
							if (value.merge != null)
							{
								var temp = localStorage.getItem(Editor.configurationKey);
								
								if (temp != null)
								{
									try
									{
										var config = JSON.parse(temp);
										
										for (var key in value.merge)
										{
											config[key] = value.merge[key];
										}
										
										value = config;
									}
									catch (e)
									{
										window.location.hash = '';
										alert(e);
									}
								}
								else
								{
									value = value.merge;
								}
							}
							
							if (confirm(mxResources.get('configLinkWarn')) &&
								confirm(mxResources.get('configLinkConfirm')))
							{
								localStorage.setItem(Editor.configurationKey, JSON.stringify(value));
								window.location.hash = '';
								window.location.reload();
							}
						}

						window.location.hash = '';
					}
					catch (e)
					{
						window.location.hash = '';
						alert(e);
					}
				}
				
				// Prepares themes with mapping from old default-style to old XML file
				if (xhr.length > 1)
				{
					Graph.prototype.defaultThemes['default-style2'] = xhr[1].getDocumentElement();
					Graph.prototype.defaultThemes['darkTheme'] = xhr[1].getDocumentElement();
				}
				
				// Main
				function realMain()
				{
					try
					{
						// Uses simple theme on small screens in own domain standalone app
						try
						{
							if ((Editor.currentTheme == null && urlParams['embed'] != '1' &&
								(urlParams['dev'] == 1 || urlParams['test'] == 1 ||
								window.location.hostname === 'test.draw.io' ||
								window.location.hostname === 'www.draw.io' ||
								window.location.hostname === 'preprod.diagrams.net' ||
								window.location.hostname === 'app.diagrams.net' ||
								window.location.hostname === 'jgraph.github.io' ||
								(/drawio-dev\.pages\.dev$/.test(window.location.hostname)))) &&
								App.isSimpleThemePreferred())
							{
								Editor.currentTheme = 'simple';
							}
						}
						catch (e)
						{
							// ignore
						}

						// Checks theme support
						if (Editor.currentTheme != 'kennedy' &&
							mxUtils.indexOf(Editor.themes, Editor.currentTheme) < 0)
						{
							Editor.currentTheme = 'kennedy';
						}

						// Adds transparent background
						if (urlParams['transparent'] == '1')
						{
							document.body.style.background = 'transparent';
						}
						
						var ui = (createUi != null) ? createUi() : new App(new Editor(
								urlParams['chrome'] == '0' || uiTheme == 'min',
								null, null, null, urlParams['chrome'] != '0'));

						// Opens files passed by the OS via the file_handlers
						// registration in images/manifest.json (installed PWA)
						if ('launchQueue' in window && urlParams['embed'] != '1')
						{
							window.launchQueue.setConsumer(function(launchParams)
							{
								if (launchParams.files != null && launchParams.files.length > 0)
								{
									ui.loadFileSystemEntry(launchParams.files[0]);
								}
							});
						}

						if (window.mxscript != null)
						{
							// Disables the OneDrive client if the UI did not create one
							if (ui.oneDrive == null)
							{
								window.OneDriveClient = null;
							}
							
							// Loads Trello if not disabled or if enabled and in embed mode
							if (typeof window.TrelloClient === 'function' &&
								typeof window.Trello === 'undefined' && window.DrawTrelloClientCallback != null &&
								urlParams['tr'] == '1')
							{
								mxscript(App.TRELLO_JQUERY_URL, function()
								{
									// Must load this after jQuery since the Trello client needs it
									mxscript(App.TRELLO_URL, function()
									{
										DrawTrelloClientCallback();
									});
								});
							}
							// Disables client
							else if (typeof window.Trello === 'undefined')
							{
								window.TrelloClient = null;
							}
						}
						
						if (callback != null)
						{
							callback(ui);
						}
						
						/**
						 * For developers only
						 */
						if (urlParams['chrome'] != '0' && urlParams['test'] == '1')
						{
							EditorUi.debug('App.start', ['v' + EditorUi.VERSION, ui, (new Date().getTime() - t0.getTime()) + 'ms']);
							EditorUi.debug('Export:', EXPORT_URL);
						}
					}
					catch (e)
					{
						if (EditorUi.isElectronApp)
						{
							mxLog.show();
							mxLog.debug(e.stack);
						}
						else
						{
							EditorUi.logError(e.message, null, null, null, e);

							window.setTimeout(function()
							{
								alert(e.message);
							}, 1);
						}
					}
				};
				
				if (urlParams['dev'] == '1' || EditorUi.isElectronApp) //TODO check if we can remove these scripts loading from index.html
				{
					realMain();
				}
				else
				{
					// Note: Lazy loading stencils.min.js in viewer.diagrams.net
					// has no impact as stencils.min.js is pre-cached in PWA
					mxStencilRegistry.allowEval = false;
					App.loadScripts(['js/shapes-14-6-5.min.js', 'js/stencils.min.js',
						'js/extensions.min.js'], realMain, function(e)
						{
							document.body.innerHTML = '';
							var pre = document.createElement('pre');
							mxUtils.write(pre, e.stack);
							document.body.appendChild(pre);
						});
				}
			}, function(xhr)
			{
				var st = document.getElementById('geStatus');
				
				if (st != null)
				{
					st.innerHTML = 'Error loading page. <a>Please try refreshing.</a>';
					
					// Tries reload with default resources in case any language resources were not available
					st.getElementsByTagName('a')[0].onclick = function()
					{
						mxLanguage = 'en';
						doLoad(mxResources.getDefaultBundle(RESOURCE_BASE, mxLanguage) ||
							mxResources.getSpecialBundle(RESOURCE_BASE, mxLanguage));
					};
				}
			});
		};

		function doMain()
		{
			// Optional override for autosaveDelay and defaultEdgeLength
			try
			{
				if (mxSettings.settings != null)
				{
					if (mxSettings.settings.autosaveDelay != null)
					{
						var val = parseInt(mxSettings.settings.autosaveDelay);
						
						if (!isNaN(val) && val > 0)
						{
							DrawioFile.prototype.autosaveDelay = val;
							EditorUi.debug('Setting autosaveDelay', val);
						}
						else
						{
							EditorUi.debug('Invalid autosaveDelay', val);
						}
					}
					
					if (mxSettings.settings.defaultEdgeLength != null)
					{
						var val = parseInt(mxSettings.settings.defaultEdgeLength);
						
						if (!isNaN(val) && val > 0)
						{
							Graph.prototype.defaultEdgeLength = val;
							EditorUi.debug('Using defaultEdgeLength', val);
						}
						else
						{
							EditorUi.debug('Invalid defaultEdgeLength', val);
						}
					}
				}
			}
			catch (e)
			{
				if (window.console != null && !EditorUi.isElectronApp)
				{
					console.error(e);
				}
				else
				{
					mxLog.show();
					mxLog.debug(e.stack);
				}
			}

			try
			{
				// Prefetches default fonts with URLs
				if (Menus.prototype.defaultFonts != null)
				{
					for (var i = 0; i < Menus.prototype.defaultFonts.length; i++)
					{
						var value = Menus.prototype.defaultFonts[i];
						
						if (typeof value !== 'string' &&
							value.fontFamily != null &&
							value.fontUrl != null)
						{
							Graph.addFont(value.fontFamily, value.fontUrl);
						}
					}
				}
				
				// Adds required resources (disables loading of fallback properties, this can only
				// be used if we know that all keys are defined in the language specific file)
				mxResources.loadDefaultBundle = false;
				doLoad(mxResources.getDefaultBundle(RESOURCE_BASE, mxLanguage) ||
					mxResources.getSpecialBundle(RESOURCE_BASE, mxLanguage));
			}
			catch (e)
			{
				document.body.innerHTML = '';
				var pre = document.createElement('pre');
				mxUtils.write(pre, e.stack);
				document.body.appendChild(pre);
			}
		};

		// Sends load event if configuration is requested and waits for configure message
		if (urlParams['configure'] == '1')
		{
			var op = window.opener || window.parent;
			
			var configHandler = function(evt)
			{
				if (evt.source == op)
				{
					try
					{
						var data = JSON.parse(evt.data);
						
						if (data != null && data.action == 'configure')
						{
							mxEvent.removeListener(window, 'message', configHandler);
							Editor.configure(data.config);

							// A popup shares the storage of the app, so the settings of each
							// opener are kept apart from those of the app (frames have their
							// own storage per site, see storage partitioning)
							if (op == window.opener)
							{
								Editor.configurationKey += '@' + evt.origin;
								Editor.settingsKey += '@' + evt.origin;
								mxSettings.key = Editor.settingsKey;
							}

							mxSettings.load();

							if (data.config.darkColor != null)
							{
								document.body.style.setProperty(
									'--dark-color', data.config.darkColor);
							}

							//To enable transparent iframe in dark mode (e.g, in gitlab)
							if (data.colorSchemeMeta)
							{
								mxmeta('color-scheme', 'dark light');
							}

							doMain();
						}
					}
					catch (e)
					{
						if (window.console != null)
						{
							console.log('Error in configure message: ' + e, evt.data);
						}
					}
				}
			};
			
			// Receives XML message from opener and puts it into the graph
			mxEvent.addListener(window, 'message', configHandler);
			op.postMessage(JSON.stringify({event: 'configure'}), '*');
		}
		else
		{
			if (Editor.config == null)
			{
				// Loads configuration from global scope or local storage
				if (window.DRAWIO_CONFIG != null)
				{
					try
					{
						EditorUi.debug('Using global configuration', window.DRAWIO_CONFIG);
						Editor.configure(window.DRAWIO_CONFIG);
						mxSettings.load();
					}
					catch (e)
					{
						if (window.console != null && !EditorUi.isElectronApp)
						{
							console.error(e);
						}
						else
						{
							mxLog.show();
							mxLog.debug(e.stack);
						}
					}
				}
		
				// Loads configuration from local storage, on top of the cached
				// settings of the user's organization (App.updateOrgSettings)
				if (isLocalStorage && localStorage != null && urlParams['embed'] != '1')
				{
					var configData = localStorage.getItem(Editor.configurationKey);
					var orgData = (typeof OrgSettings !== 'undefined') ?
						localStorage.getItem(OrgSettings.cacheKey) : null;
		
					if (configData != null || orgData != null)
					{
						try
						{
							configData = (configData != null) ? JSON.parse(configData) : null;

							// A broken cache must not stop the user's own configuration
							try
							{
								if (orgData != null)
								{
									configData = OrgSettings.merge(JSON.parse(orgData), configData);
								}
							}
							catch (e)
							{
								// ignore
							}
							
							if (configData != null)
							{
								EditorUi.debug('Using local configuration', configData);
								Editor.configure(configData);
								mxSettings.load();
							}
						}
						catch (e)
						{
							if (window.console != null && !EditorUi.isElectronApp)
							{
								console.error(e);
							}
							else
							{
								mxLog.show();
								mxLog.debug(e.stack);
							}
						}
					}
				}
			}
			
			doMain();
		}
	}
	catch (e)
	{
		document.body.innerHTML = '';
		var pre = document.createElement('pre');
		mxUtils.write(pre, e.stack);
		document.body.appendChild(pre);
	}
};

//Extends EditorUi
mxUtils.extend(App, EditorUi);

/**
 * Interval to show dialog for unsaved data if autosave is on.
 * Default is 300000 (5 minutes).
 */
App.prototype.warnInterval = 300000;

/**
 *
 */
App.prototype.compactMode = false;

/**
 *
 */
App.prototype.fullscreenMode = false;

/**
 * Queue for loading plugins and wait for UI instance
 */
App.initPluginCallback = function()
{
	if (App.DrawPlugins == null)
	{
		// Workaround for need to load plugins now but wait for UI instance
		App.DrawPlugins = [];
		
		// Global entry point for plugins is Draw.loadPlugin. This is the only
		// long-term supported solution for access to the EditorUi instance.
		window.Draw = new Object();
		window.Draw.loadPlugin = function(callback)
		{
			App.DrawPlugins.push(callback);
		};
	}
};

/**
 * 
 */
App.pluginsLoaded = {};
App.embedModePluginsCount = 0;

/**
 * Queue for loading plugins and wait for UI instance
 */
App.loadPlugins = function(plugins, useInclude)
{
	EditorUi.debug('Loading plugins', plugins);

	for (var i = 0; i < plugins.length; i++)
	{
		if (plugins[i] != null && plugins[i].length > 0)
		{
			try
			{
				if (App.applyRetiredPlugin(plugins[i]))
				{
					// Removed plugin, built-in replacement enabled above
				}
				else if (App.pluginRegistry[plugins[i]] != null)
				{
					var url = PLUGINS_BASE_PATH + App.pluginRegistry[plugins[i]];
					
					if (App.pluginsLoaded[url] == null)
					{
						App.pluginsLoaded[url] = true;
						App.embedModePluginsCount++;
						
						if (typeof window.drawDevUrl === 'undefined')
						{
							if (useInclude)
							{
								mxinclude(url);
							}
							else
							{
								mxscript(url);
							}
						}
						else
						{
							if (useInclude)
							{
								mxinclude(url);
							}
							else
							{
								mxscript(drawDevUrl + url);
							}
						}
					}
				}
				else if (window.console != null)
				{
					console.log('Unknown plugin:', plugins[i]);
				}
			}
			catch (e)
			{
				if (window.console != null)
				{
					console.log('Error loading plugin:', plugins[i], e);
				}
			}
		}
	}
};

/**
 * Delay embed mode initialization until all plugins are loaded
 */
App.prototype.initializeEmbedMode = function()
{
	if (urlParams['embed'] == '1')
	{
		if (window.location.hostname == 'app.diagrams.net')
		{
			this.showBanner('EmbedDeprecationFooter', 'app.diagrams.net will stop working for embed mode. Please use embed.diagrams.net.');
		}
		
		if (App.embedModePluginsCount > 0 || this.initEmbedDone)
		{
			return; //Wait for plugins to load, or this is a duplicate call due to timeout
		}
		else
		{
			this.initEmbedDone = true;
		}
		
		EditorUi.prototype.initializeEmbedMode.apply(this, arguments);
	}
};

/**
 * TODO: Define viewer protocol and implement new viewer style toolbar
 */
App.prototype.initializeViewerMode = function()
{
	var parent = window.opener || window.parent;

	if (parent != null)
	{
		this.editor.graph.addListener(mxEvent.SIZE, mxUtils.bind(this, function()
		{
			parent.postMessage(JSON.stringify(this.createLoadMessage('size')), '*');
		}));
	}
};

/**
 * Initializes the UI and creates the clients for the enabled storage
 * services. Does nothing if the app runs in a blocked frame.
 */
App.prototype.init = function()
{
	if (App.blockedAncestorFrames())
	{
		return;
	}

	// Button container is used in UI init
	this.buttonContainer = this.createButtonContainer();

	EditorUi.prototype.init.apply(this, arguments);
	
	/**
	 * Holds the listener for description changes.
	 */	
	this.descriptorChangedListener = mxUtils.bind(this, this.descriptorChanged);

	this.addListener('currentThemeChanged', mxUtils.bind(this, function()
	{
		if (this.compactMode && this.isDefaultTheme(Editor.currentTheme))
		{
			this.setCompactMode(true);
		}
	}));

	// Restores compact mode from settings
	if (Editor.isSettingsEnabled() && mxSettings.settings.compactMode != null &&
		this.isDefaultTheme(Editor.currentTheme))
	{
		this.setCompactMode(mxSettings.settings.compactMode);
	}

	// Restores collaboration cursor preferences from settings (an absent key
	// means no user choice, keeping the default or configured value)
	if (Editor.isSettingsEnabled())
	{
		if (mxSettings.settings.shareCursorPosition != null)
		{
			this.shareCursorPosition = mxSettings.settings.shareCursorPosition;
		}

		if (mxSettings.settings.showRemoteCursors != null)
		{
			this.showRemoteCursors = mxSettings.settings.showRemoteCursors;
		}
	}

	/**
	 * Creates github client.
	 */
	try
	{
		this.gitHub = (urlParams['gh'] != '0' && (urlParams['embed'] != '1' ||
				urlParams['gh'] == '1')) ? new GitHubClient(this) : null;
		
		if (this.gitHub != null)
		{
			this.gitHub.addListener('userChanged', mxUtils.bind(this, function()
			{
				this.updateButtonContainer();
				this.restoreLibraries();
			}));
		}
	}
	catch (e)
	{
		if (window.console != null)
		{
			console.log('GitHubClient disabled: ' + e.message);
		}
	}

	/**
	 * Creates gitlab client.
	 */
	try
	{
		this.gitLab = (urlParams['gl'] != '0' && (urlParams['embed'] != '1' ||
			urlParams['gl'] == '1')) ? new GitLabClient(this) : null;

		if (this.gitLab != null)
		{
			this.gitLab.addListener('userChanged', mxUtils.bind(this, function()
			{
				this.updateButtonContainer();
				this.restoreLibraries();
			}));
		}
	}
	catch (e)
	{
		if (window.console != null)
		{
			console.log('GitLabClient disabled: ' + e.message);
		}
	}

	/**
	 * Creates the OneDrive client. The OneDrive SDK is only loaded for the
	 * picker that is not inline (see Editor.oneDriveInlinePicker).
	 */
	if (typeof window.OneDriveClient === 'function' &&
		(urlParams['embed'] != '1' || urlParams['od'] == '1'))
	{
		try
		{
			this.oneDrive = new OneDriveClient(this);

			if (!this.oneDrive.inlinePicker && typeof window.OneDrive === 'undefined' &&
				window.mxscript != null)
			{
				mxscript(App.ONEDRIVE_URL, null, null, null, true);
			}

			this.oneDrive.addListener('userChanged', mxUtils.bind(this, function()
			{
				this.updateButtonContainer();
				this.restoreLibraries();
				this.checkReleaseChannel(this.oneDrive);
			}));

			// Notifies listeners of new client
			this.fireEvent(new mxEventObject('clientLoaded', 'client', this.oneDrive));
		}
		catch (e)
		{
			if (window.console != null)
			{
				console.log('OneDriveClient disabled: ' + e.message);
			}
		}
	}

	if (urlParams['ms365'] != '0' && !EditorUi.isElectronApp &&
		(urlParams['embed'] != '1' || urlParams['ms365'] == '1'))
	{
		try
		{
			this.m365 = new OneDriveClient(this, false, false, false, true);

			this.m365.addListener('userChanged', mxUtils.bind(this, function()
			{
				this.updateButtonContainer();
				this.restoreLibraries();
				this.checkReleaseChannel(this.m365);
			}));

			// Notifies listeners of new client
			this.fireEvent(new mxEventObject('clientLoaded', 'client', this.m365));
		}
		catch (e)
		{
			if (window.console != null)
			{
				console.log('M365Client disabled: ' + e.message);
			}
		}
	}

	/**
	 * Lazy-loading for Trello
	 */
	if (urlParams['embed'] != '1' || urlParams['tr'] == '1')
	{
		/**
		 * Creates Trello client if all required libraries are available.
		 */
		var initTrelloClient = mxUtils.bind(this, function()
		{
			if (typeof window.Trello !== 'undefined')
			{
				try
				{
					this.trello = new TrelloClient(this);
					
					//TODO we have no user info from Trello so we don't set a user
					this.trello.addListener('userChanged', mxUtils.bind(this, function()
					{
						this.updateButtonContainer();
						this.restoreLibraries();
					}));
					
					// Notifies listeners of new client
					this.fireEvent(new mxEventObject('clientLoaded', 'client', this.trello));
				}
				catch (e)
				{
					if (window.console != null)
					{
						console.log('TrelloClient disabled: ' + e.message);
					}
				}
			}
			else if (window.DrawTrelloClientCallback == null)
			{
				window.DrawTrelloClientCallback = initTrelloClient;
			}
		});

		initTrelloClient();
	}

	/**
	 * Creates drive client with all required libraries are available.
	 */
	if (urlParams['embed'] != '1' || urlParams['gapi'] == '1')
	{
		var initDriveClient = mxUtils.bind(this, function()
		{
			/**
			 * Creates google drive client if all required libraries are available.
			 */
			if (typeof gapi !== 'undefined')
			{
				var doInit = mxUtils.bind(this, function()
				{
					try
					{
						this.drive = new DriveClient(this);
						
						this.drive.addListener('userChanged', mxUtils.bind(this, function()
						{
							this.updateButtonContainer();
							this.restoreLibraries();
							this.updateOrgSettings();
							this.checkReleaseChannel(this.drive);
							this.recordTermsInDrive();
						}))
						
						// Notifies listeners of new client
						this.fireEvent(new mxEventObject('clientLoaded', 'client', this.drive));
					}
					catch (e)
					{
						if (window.console != null)
						{
							console.log('DriveClient disabled: ' + e.message);
						}
					}
				});
				
				if (window.DrawGapiClientCallback != null)
				{
					gapi.load(((urlParams['picker'] != '0') ? 'picker,': '') + App.GOOGLE_APIS, doInit);
					
					/**
					 * Clears any callbacks.
					 */
					window.DrawGapiClientCallback = null;
				}
				else
				{
					doInit();
				}
			}
			else if (window.DrawGapiClientCallback == null)
			{
				window.DrawGapiClientCallback = initDriveClient;
			}
		});
		
		initDriveClient();
	}

	if (urlParams['embed'] != '1')
	{
		this.setGraphEnabled(false);
		
		// Sets the initial mode
		if (urlParams['local'] == '1')
		{
			this.setMode(App.MODE_DEVICE);
		}
		else
		{
			this.mode = App.mode;

			// Ignores a stored or requested mode for a storage that has been
			// removed (eg. dropbox) and forgets it if it was stored, so that
			// the start shows the storage and draft dialogs as before
			if (this.mode != null && !App.isKnownMode(this.mode))
			{
				if (this.mode == App.getStoredMode())
				{
					this.clearMode();
				}

				this.mode = null;
			}
			// Ignores a stored or requested mode for a storage whose support has
			// ended unless it was enabled explicitly (tr=1), so that the
			// storage can be changed instead of opening a picker that is missing
			else if (this.mode == App.MODE_TRELLO && !this.isModeEnabled(this.mode))
			{
				this.mode = null;
			}
		}

		// Add to Home Screen dialog for mobile devices
		if ('serviceWorker' in navigator && !this.editor.isChromelessView() &&
			(mxClient.IS_ANDROID || mxClient.IS_IOS))
		{
			window.addEventListener('beforeinstallprompt', mxUtils.bind(this, function(e)
			{
				this.showBanner('AddToHomeScreenFooter', mxResources.get('installApp'), mxUtils.bind(this, function()
				{
					e.prompt();
				}), true, true);
			}));
		}
		
		if (this.isOwnGDriveDomain() && (!this.editor.chromeless || this.editor.editable))
		{
			this.editor.addListener('fileLoaded', mxUtils.bind(this, function()
			{
				var file = this.getCurrentFile();
				var mode = (file != null) ? file.getMode() : null;
				
				if (!mxClient.IS_CHROMEAPP && !mxClient.IS_ANDROID && !mxClient.IS_IOS &&
					!EditorUi.isElectronApp && !this.isOffline() && urlParams['open'] == null &&
					urlParams['extAuth'] != '1' && (mode == App.MODE_DEVICE || mode == App.MODE_BROWSER))
				{
					this.showDownloadDesktopBanner();
				}
			}));
		}

		// Checks if the cache is alive (also runs when the first file
		// starts to sync, eg. in embed mode, see DrawioFileSync.start)
		DrawioFileSync.checkCacheAlive(this);
	}

	// Fits the diagram after fileLoaded as the page fit in pageSelected is
	// skipped while the file is opening (embed mode fits after setFileData)
	if (!this.editor.chromeless || this.editor.editable)
	{
		this.editor.addListener('fileLoaded', mxUtils.bind(this, function()
		{
			if (Editor.fitDiagramOnLoad)
			{
				this.fitInitialView();
			}
		}));
	}

	this.updateHeader();

	if (this.menubar != null)
	{
		if (Editor.currentTheme != 'sketch' &&
			(Editor.currentTheme != 'simple' ||
			urlParams['embed'] != '1'))
		{
			var insertButtonContainer = mxUtils.bind(this, function()
			{
				if (urlParams['embed'] != '1')
				{
					this.menubar.container.appendChild(this.buttonContainer);
				}
				else
				{
					this.toolbarContainer.appendChild(this.buttonContainer);
				}
			});

			this.addListener('languageChanged', insertButtonContainer);
			this.addListener('currentThemeChanged', insertButtonContainer);
			insertButtonContainer();
		}

		if ((Editor.currentTheme == 'kennedy' && urlParams['embed'] == '1') ||
			(Editor.currentTheme == 'atlas' && urlParams['embed'] != '1'))
		{
			this.setCompactMode(true);
		}

		if (Editor.currentTheme == 'atlas' || urlParams['atlas'] == '1')
		{	
			this.icon = document.createElement('img');
			this.icon.setAttribute('src', IMAGE_PATH + '/logo-flat-small.png');
			this.icon.setAttribute('title', mxResources.get('draw.io'));
			this.icon.className = 'geSmallAppIcon';
			// this.icon.style.padding = '0 4px 0 0';

			if (urlParams['embed'] != '1')
			{
				this.icon.style.cursor = 'pointer';
				
				mxEvent.addListener(this.icon, 'click', mxUtils.bind(this, function(evt)
				{
					this.appIconClicked(evt);
				}));

				this.initKeyboardButton(this.icon);
			}
			
			this.menubar.container.insertBefore(this.icon, this.menubar.container.firstChild);
		}
	}
	
	if (this.editor.graph.isViewer())
	{
		this.initializeViewerMode();
	}
};

App.blockedAncestorFrames = function()
{
	try
	{
		if (window.location.ancestorOrigins && window.location.hostname &&
			window.location.ancestorOrigins.length && window.location.ancestorOrigins.length > 0)
		{
			var hostname = window.location.hostname;

			if (hostname && hostname.length > 1 && hostname.charAt(hostname.length - 1) == '/')
			{
				hostname = hostname.substring(0, hostname.length - 1)
			}

			var message = '';

			for (var i = 0; i < window.location.ancestorOrigins.length; i++)
			{
				message += ' -> ' + window.location.ancestorOrigins[i];

				// Running commercial, competing services using our infrastructure isn't allowed.
				if (message.endsWith('dan6v7pm1f1a1.cloudfront.net') || message.endsWith('confluence-cloud-excalidraw-2-ll3likebca-uc.a.run.app'))
				{
					return true;
				}
			}

			// if (hostname.endsWith('embed.diagrams.net') && window.location.ancestorOrigins.length > 0)
			// {
			// 	var img = new Image();
			// 	img.src = 'https://log.diagrams.net/images/1x1.png?src=EditorEmbedAncestorFrames' +
			// 		'&v=' + encodeURIComponent(EditorUi.VERSION) + '&data=' + encodeURIComponent(message);
			// }
		}
	}
	catch (e)
	{
		// ignore
	}

	return false;
};

/**
 * Schedules a sanity check.
 */
App.prototype.scheduleSanityCheck = function()
{
	if (!mxClient.IS_CHROMEAPP && !EditorUi.isElectronApp &&
		this.sanityCheckThread == null)
	{
		this.sanityCheckThread = window.setTimeout(mxUtils.bind(this, function()
		{
			this.sanityCheckThread = null;
			this.sanityCheck();
		}), this.warnInterval);
	}
};

/**
 * Stops sanity checks.
 */
App.prototype.stopSanityCheck = function()
{
	if (this.sanityCheckThread != null)
	{
		window.clearTimeout(this.sanityCheckThread);
		this.sanityCheckThread = null;
	}
};

/**
 * Shows a warning after some time with unsaved changes and autosave.
 */
App.prototype.sanityCheck = function()
{
	var file = this.getCurrentFile();

	if (file != null && file.isModified() && file.isAutosave() && file.isOverdue())
	{
		var evt = {category: 'WARN-FILE-' + file.getHash(),
			action: ((file.savingFile) ? 'saving' : '') +
			((file.savingFile && file.savingFileTime != null) ? '_' +
				Math.round((Date.now() - file.savingFileTime.getTime()) / 1000) : '') +
			((file.saveLevel != null) ? ('-sl_' + file.saveLevel) : '') +
			'-age_' + ((file.ageStart != null) ? Math.round((Date.now() - file.ageStart.getTime()) / 1000) : 'x') +
			((this.editor.autosave) ? '' : '-nosave') +
			((file.isAutosave()) ? '' : '-noauto') +
			'-open_' + ((file.opened != null) ? Math.round((Date.now() - file.opened.getTime()) / 1000) : 'x') +
			'-save_' + ((file.lastSaved != null) ? Math.round((Date.now() - file.lastSaved.getTime()) / 1000) : 'x') +
			'-change_' + ((file.lastChanged != null) ? Math.round((Date.now() - file.lastChanged.getTime()) / 1000) : 'x')+
			'-alive_' + Math.round((Date.now() - App.startTime.getTime()) / 1000),
			label: (file.sync != null) ? ('client_' + file.sync.clientId) : 'nosync'};
			
		if (file.constructor == DriveFile && file.desc != null && this.drive != null)
		{
			evt.label += ((this.drive.user != null) ? ('-user_' + this.drive.user.id) : '-nouser') + '-rev_' +
				file.desc.headRevisionId + '-mod_' + file.desc.modifiedDate + '-size_' + file.getSize() +
				'-mime_' + file.desc.mimeType;
		}
			
		// EditorUi.logEvent(evt);

		var msg = mxResources.get('ensureDataSaved');
		
		if (file.lastSaved != null)
		{
			var str = this.timeSince(file.lastSaved);
			
			if (str == null)
			{
				str = mxResources.get('lessThanAMinute');
			}

			msg = mxResources.get('lastSaved', [str]);
		}
		
		// Resets possible stale state
		this.spinner.stop();

		this.showError(mxResources.get('unsavedChanges'), msg, mxResources.get('ignore'),
			mxUtils.bind(this, function()
			{
				this.hideDialog();
			}), null, mxResources.get('save'), mxUtils.bind(this, function()
			{
				this.stopSanityCheck();
				this.actions.get((this.mode == null || !file.isEditable()) ?
					'saveAs' : 'save').funct();
			}), null, null, 360, 140, null, mxUtils.bind(this, function()
			{
				this.scheduleSanityCheck();
			}));
	}
};

/**
 * Returns true if the current domain is valid for using Google Drive
 */
App.prototype.isOwnGDriveDomain = function()
{
	return window.location.hostname == 'test.draw.io' ||
		window.location.hostname == 'preprod.diagrams.net' ||
		window.location.hostname == 'app.diagrams.net' ||
		(/drawio-dev\.pages\.dev$/.test(window.location.hostname));
};

/**
 * Returns true if the current domain is for the new drive app.
 */
App.prototype.isDriveDomain = function()
{
	return urlParams['drive'] != '0' && this.isOwnGDriveDomain();
};

/**
 * Pads the diagram of the lightbox and chrome=0 only if they are not in a
 * frame, eg. an iframe of Embed > IFrame, where the padding would always show
 * scrollbars and the mouse wheel would move the diagram out of view.
 * Presentation mode and the lightbox of the viewer are padded, as they are
 * EditorUi instances.
 */
App.prototype.isChromelessDiagramPadded = function()
{
	return window.self === window.top &&
		EditorUi.prototype.isChromelessDiagramPadded.apply(this, arguments);
};

/**
 * Shows a footer to download the desktop version once per session.
 */
App.prototype.searchHelp = function(prompt)
{
	var link = 'https://www.drawio.com/search?src=' +
		(EditorUi.isElectronApp ? 'DESKTOP' : encodeURIComponent(location.host)) + 
			'&search=' + encodeURIComponent(prompt);
	this.openLink(link);
	
	if (prompt.length > 0)
	{
		EditorUi.logEvent({category: 'SEARCH-HELP', action: 'search', label: prompt});
	}
};

/**
 * Shows a footer to download the desktop version once per session.
 */
App.prototype.showNameConfBanner = function()
{
	this.showBanner('ConfFooter', 'Try draw.io for Confluence', mxUtils.bind(this, function()
	{
		this.openLink('https://marketplace.atlassian.com/apps/1210933/draw-io-diagrams-for-confluence');
	}), true);
};

/**
 * Shows a footer to download the desktop version once per session.
 */
App.prototype.showDownloadDesktopBanner = function()
{
	this.showBanner('DesktopFooter', mxResources.get('downloadDesktop'), mxUtils.bind(this, function()
	{
		this.openLink('https://get.diagrams.net/');
	}), true, true);
};

/**
 * Shows a footer to download the desktop version once per session.
 */
App.prototype.showRatingBanner = function()
{
	if (!this.bannerShowing && !this['hideBanner' + 'ratingFooter'] &&
		(!isLocalStorage || mxSettings.settings == null ||
		mxSettings.settings['close' + 'ratingFooter'] == null))
	{
		var banner = document.createElement('div');
		banner.style.cssText = 'position:absolute;bottom:10px;left:50%;max-width:90%;padding:18px 34px 12px 20px;' +
			'font-size:16px;font-weight:bold;white-space:nowrap;cursor:pointer;z-index:' + mxPopupMenu.prototype.zIndex + ';';
		mxUtils.setPrefixedStyle(banner.style, 'box-shadow', '1px 1px 2px 0px #ddd');
		mxUtils.setPrefixedStyle(banner.style, 'transform', 'translate(-50%,120%)');
		mxUtils.setPrefixedStyle(banner.style, 'transition', 'all 1s ease');
		banner.className = 'geBtn gePrimaryBtn';

		var img = document.createElement('img');
		img.setAttribute('src', Dialog.prototype.closeImage);
		img.setAttribute('title', mxResources.get('close'));
		img.setAttribute('border', '0');
		img.style.cssText = 'position:absolute;right:10px;top:12px;filter:invert(1);padding:6px;margin:-6px;cursor:default;';
		banner.appendChild(img);
		
		var star = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZ' +
			'XdvcmtzIENTM5jWRgMAAAQRdEVYdFhNTDpjb20uYWRvYmUueG1wADw/eHBhY2tldCBiZWdpbj0iICAgIiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+Cjx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8i' +
			'IHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDQuMS1jMDM0IDQ2LjI3Mjk3NiwgU2F0IEphbiAyNyAyMDA3IDIyOjExOjQxICAgICAgICAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDI' +
			'vMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczp4YXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iPgogICAgICAgICA8eGFwOkNyZW' +
			'F0b3JUb29sPkFkb2JlIEZpcmV3b3JrcyBDUzM8L3hhcDpDcmVhdG9yVG9vbD4KICAgICAgICAgPHhhcDpDcmVhdGVEYXRlPjIwMDgtMDItMTdUMDI6MzY6NDVaPC94YXA6Q3JlYXRlRGF0ZT4KICAgICAgICAgPHhhcDpNb2RpZ' +
			'nlEYXRlPjIwMDktMDMtMTdUMTQ6MTI6MDJaPC94YXA6TW9kaWZ5RGF0ZT4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgICAgIDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiCiAgICAgICAgICAgIHhtbG5zOmRjPSJo' +
			'dHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyI+CiAgICAgICAgIDxkYzpmb3JtYXQ+aW1hZ2UvcG5nPC9kYzpmb3JtYXQ+CiAgICAgIDwvcmRmOkRlc2NyaXB0aW9uPgogICA8L3JkZjpSREY+CjwveDp4bXBtZXRhPgo' +
			'gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgIC' +
			'AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI' +
			'CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIIImu8AAAAAVdEVYdENyZWF0aW9uIFRpbWUAMi8xNy8wOCCcqlgAAAHuSURBVDiNlZJBi1JRGIbfk+fc0ZuMXorJe4XujWoMdREaA23HICj6AQeLINr0C4I27ab2' +
			'7VqOI9+q/sH8gMDceG1RkIwgClEXFMbRc5zTZgZURmG+5fu9PN/7Hg6wZohoh4h21nn4uqXW+q0xZgzg+SrPlTXX73uet+26bp6ICpcGaK1fua57M5vN3tZav7gUgIiSqVTqcRAEm0EQbCaTyQoRXb3Iy4hoG8CT6XSaY4xtMMa' +
			'SQohMPp8v+r7vAEC3243CMGwqpfoApsaYE8uyfgM45ABOjDEvXdfNlMvlzFINAIDneY7neZVzvdlsDgaDQYtzfsjOIjtKqU+e5+0Wi0V3VV8ACMOw3+/3v3HOX0sp/7K53te11h/S6fRuoVAIhBAL76OUOm2320dRFH0VQuxJKf' +
			'8BAFu+UKvVvpRKpWe2bYt5fTweq0ajQUKIN1LK43N94SMR0Y1YLLYlhBBKqQUw51wkEol7WmuzoC8FuJtIJLaUUoii6Ljb7f4yxpz6vp9zHMe2bfvacDi8BeDHKkBuNps5rVbr52QyaVuW9ZExttHpdN73ej0/Ho+nADxYCdBaV' +
			'0aj0RGAz5ZlHUgpx2erR/V6/d1wOHwK4CGA/QsBnPN9AN+llH+WkqFare4R0QGAO/M6M8Ysey81/wGqa8MlVvHPNAAAAABJRU5ErkJggg==';

		mxUtils.write(banner, 'Please rate us');
		document.body.appendChild(banner);

		var star1 = document.createElement('img');
		star1.setAttribute('border', '0');
		star1.setAttribute('align', 'absmiddle');
		star1.setAttribute('title', '1 star');
		star1.setAttribute('style', 'margin-top:-6px;cursor:pointer;margin-left:8px;');
		star1.setAttribute('src', star);
		banner.appendChild(star1);
		
		var star2 = document.createElement('img');
		star2.setAttribute('border', '0');
		star2.setAttribute('align', 'absmiddle');
		star2.setAttribute('title', '2 star');
		star2.setAttribute('style', 'margin-top:-6px;margin-left:3px;cursor:pointer;');
		star2.setAttribute('src', star);
		banner.appendChild(star2);
		
		var star3 = document.createElement('img');
		star3.setAttribute('border', '0');
		star3.setAttribute('align', 'absmiddle');
		star3.setAttribute('title', '3 star');
		star3.setAttribute('style', 'margin-top:-6px;margin-left:3px;cursor:pointer;');
		star3.setAttribute('src', star);
		banner.appendChild(star3);
		
		var star4 = document.createElement('img');
		star4.setAttribute('border', '0');
		star4.setAttribute('align', 'absmiddle');
		star4.setAttribute('title', '4 star');
		star4.setAttribute('style', 'margin-top:-6px;margin-left:3px;cursor:pointer;');
		star4.setAttribute('src', star);
		banner.appendChild(star4);
		
		this.bannerShowing = true;
		
		var onclose = mxUtils.bind(this, function()
		{
			if (banner.parentNode != null)
			{
				banner.parentNode.removeChild(banner);
				this.bannerShowing = false;
				
				this['hideBanner' + 'ratingFooter'] = true;

				if (isLocalStorage && mxSettings.settings != null)
				{
					mxSettings.settings['close' + 'ratingFooter'] = Date.now();
					mxSettings.save();
				}
			}
		});
		
		mxEvent.addListener(img, 'click', mxUtils.bind(this, function(e)
		{
			mxEvent.consume(e);
			onclose();
		}));
		mxEvent.addListener(star1, 'click', mxUtils.bind(this, function(e)
		{
			mxEvent.consume(e);
			onclose();
		}));
		mxEvent.addListener(star2, 'click', mxUtils.bind(this, function(e)
		{
			mxEvent.consume(e);
			onclose();
		}));
		mxEvent.addListener(star3, 'click', mxUtils.bind(this, function(e)
		{
			mxEvent.consume(e);
			onclose();
		}));
		mxEvent.addListener(star4, 'click', mxUtils.bind(this, function(e)
		{
			mxEvent.consume(e);
			window.open('https://marketplace.atlassian.com/apps/1210933/draw-io-diagrams-for-confluence?hosting=datacenter&tab=reviews');
			onclose();
		}));

		var hide = mxUtils.bind(this, function()
		{
			mxUtils.setPrefixedStyle(banner.style, 'transform', 'translate(-50%,120%)');
			
			window.setTimeout(mxUtils.bind(this, function()
			{
				onclose();
			}), 1000);
		});
		
		window.setTimeout(mxUtils.bind(this, function()
		{
			mxUtils.setPrefixedStyle(banner.style, 'transform', 'translate(-50%,0%)');
		}), 500);
		
		window.setTimeout(hide, 60000);
	}
};

/**
 * Looks up the release channel for the signed-in account's email domain and
 * switches this browser when it changed. Only the email domain is
 * transmitted (no personal information), at most once per day.
 */
App.prototype.checkReleaseChannel = function(client)
{
	try
	{
		var user = (client != null) ? client.getUser() : null;
		var email = (user != null) ? user.email : null;
		var at = (email != null) ? email.lastIndexOf('@') : -1;

		// The explicit ?channel= override wins for this session.
		if (at < 0 || !isLocalStorage || !Editor.enableServiceWorker ||
			!('serviceWorker' in navigator) || urlParams['channel'] != null)
		{
			return;
		}

		var ts = parseInt(localStorage.getItem('.drawio-channel-ts'), 10);
		var elapsed = Date.now() - ts;

		// A future timestamp (corrected clock) must expire, never freeze.
		if (!isNaN(ts) && elapsed >= 0 && elapsed < 86400000)
		{
			return;
		}

		localStorage.setItem('.drawio-channel-ts', String(Date.now()));

		var xhr = new XMLHttpRequest();
		xhr.open('POST', 'channel');
		xhr.setRequestHeader('Content-Type', 'application/json');

		xhr.onload = mxUtils.bind(this, function()
		{
			try
			{
				var verdict = null;

				if (xhr.status == 404 || xhr.status == 405)
				{
					// The endpoint is definitively gone (the zone origin
					// answered in its place): the channel infrastructure was
					// decommissioned, converge to the default channel.
					verdict = 'beta';
				}
				else if (xhr.status >= 200 && xhr.status <= 299)
				{
					var result = JSON.parse(xhr.responseText);

					// Only an explicit verdict changes the channel - a buggy
					// 200 without one must not mass-demote pinned browsers.
					// Transient errors (5xx, network) change nothing.
					if (result != null && (result.channel == 'stable' ||
						result.channel == 'beta'))
					{
						verdict = result.channel;
					}
				}

				if (verdict != null)
				{
					var channel = (verdict == 'stable') ? 'stable' : null;

					if (channel != App.getReleaseChannel())
					{
						EditorUi.debug('App.checkReleaseChannel',
							'Switching channel', verdict);
						App.setReleaseChannel(channel);
						this.switchReleaseChannel();
					}
				}
			}
			catch (e)
			{
				// ignore
			}
		});

		xhr.send(JSON.stringify({domain: email.substring(at + 1)}));
	}
	catch (e)
	{
		// ignore
	}
};

/**
 * Registers the service worker for the stored release channel. The new
 * worker precaches the full channel before it activates; the page reloads
 * only then, and only without unsaved changes (else the next start uses
 * the new channel).
 */
App.prototype.switchReleaseChannel = function()
{
	try
	{
		var swUrl = (App.getReleaseChannel() == 'stable') ?
			'stable/service-worker.js' : 'service-worker.js';

		// Lets other open tabs reload (when clean) via controllerchange -
		// normal release updates set no flag and never force reloads.
		localStorage.setItem('.drawio-channel-switch-ts', String(Date.now()));

		navigator.serviceWorker.register(swUrl, {scope: './'}).then(
			mxUtils.bind(this, function(reg)
		{
			var track = mxUtils.bind(this, function(sw)
			{
				if (sw != null)
				{
					sw.addEventListener('statechange', mxUtils.bind(this, function()
					{
						if (sw.state == 'activated' && (this.getCurrentFile() == null ||
							!this.getCurrentFile().isModified()))
						{
							window.location.reload();
						}
					}));
				}
			});

			if (reg.installing != null)
			{
				track(reg.installing);
			}
			else
			{
				reg.addEventListener('updatefound', function()
				{
					track(reg.installing);
				});
			}
		}), function(e)
		{
			// ignore
		});
	}
	catch (e)
	{
		// ignore
	}
};

/**
 * Hook for subclassers to handle the licence of the user's domain, which
 * App.reportDriveUse gets from the ws worker.
 */
App.prototype.handleLicense = function(lic, domain)
{
	// Hook for subclassers to handle license response
};

/**
 * Hosts where the app reports Google Drive views and edits to the ws worker
 * (App.reportDriveUse), and where it reads the organization's settings. Only
 * hosts whose /ws/* goes to the worker (its README): elsewhere the requests
 * would go to the App Engine origin.
 */
App.driveUsageHosts = ['app.diagrams.net', 'preprod.diagrams.net'];

/**
 * Hosts where the steps that start using draw.io (the storage choice, the
 * authorization of a storage) say that continuing accepts the draw.io Terms
 * of Use (App.prototype.createTermsNotice): draw.io's own. Never a copy that
 * someone else hosts, the desktop app, or the apps for Confluence and Jira,
 * which have a licence agreement of their own.
 */
App.termsHosts = ['app.diagrams.net', 'preprod.diagrams.net'];

/**
 * The version of the Terms of Use, the number at the end of the page
 * (App.termsUrl), the same as the ws worker's TERMS_VERSION.
 */
App.termsVersion = '1.3';

/**
 * The pages the Terms of Use notice links to.
 */
App.termsUrl = 'https://www.drawio.com/trust/terms-of-use';
App.privacyUrl = 'https://www.drawio.com/trust/';

/**
 * Key of the record of the Terms of Use accepted in this browser:
 * {version, accepted}, the version and when.
 */
App.termsKey = '.drawio-terms';

/**
 * Mail providers of personal Google accounts, whose users don't see Extras >
 * Organization Admin. The same list as PERSONAL_DOMAINS in the ws worker's
 * lib.js (its tests compare them), which never admits or counts them.
 */
App.personalMailDomains = ['gmail.com', 'googlemail.com',
	'outlook.com', 'hotmail.com', 'live.com', 'msn.com', 'hotmail.co.uk',
	'hotmail.fr', 'hotmail.de', 'hotmail.it', 'hotmail.es', 'live.co.uk',
	'live.fr', 'live.de', 'live.nl', 'live.it', 'live.ca', 'live.com.au',
	'outlook.fr', 'outlook.de', 'outlook.es', 'outlook.it', 'outlook.jp',
	'yahoo.com', 'ymail.com', 'rocketmail.com', 'yahoo.co.uk', 'yahoo.fr',
	'yahoo.de', 'yahoo.it', 'yahoo.es', 'yahoo.ca', 'yahoo.com.au',
	'yahoo.co.in', 'yahoo.co.jp', 'yahoo.com.br', 'aol.com', 'icloud.com',
	'me.com', 'mac.com', 'proton.me', 'protonmail.com', 'pm.me',
	'tutanota.com', 'gmx.com', 'gmx.de', 'gmx.net', 'gmx.at', 'gmx.ch',
	'web.de', 't-online.de', 'mail.com', 'yandex.ru', 'yandex.com',
	'mail.ru', 'qq.com', '163.com', '126.com', 'sina.com', 'naver.com',
	'daum.net', 'hanmail.net', 'orange.fr', 'free.fr', 'laposte.net',
	'libero.it', 'comcast.net', 'verizon.net', 'att.net', 'sbcglobal.net',
	'btinternet.com', 'rediffmail.com'];

/**
 * The admin console's own host for each app host (AdminPage.js sends the
 * browser there too). Elsewhere, such as preprod, the console is admin.html
 * next to the app.
 */
App.adminConsoleUrls = {'app.diagrams.net': 'https://admin.diagrams.net/'};

/**
 * Returns the address of the admin console (Extras > Organization Admin).
 */
App.getAdminConsoleUrl = function()
{
	return (Object.prototype.hasOwnProperty.call(App.adminConsoleUrls, window.location.hostname)) ?
		App.adminConsoleUrls[window.location.hostname] : new URL('admin.html', window.location.href).href;
};

/**
 * Returns true if Extras > Organization Admin is shown: Google Drive users
 * with a company address (not App.personalMailDomains) on the hosts of the ws
 * worker, which checks every request anyway (ADMIN_DOMAINS).
 */
App.prototype.isOrganizationAdminVisible = function()
{
	var user = (this.drive != null) ? this.drive.getUser() : null;
	var email = (user != null && typeof user.email === 'string') ? user.email.toLowerCase() : '';
	var at = email.lastIndexOf('@');
	var domain = (at > 0) ? email.substring(at + 1) : '';

	return urlParams['embed'] != '1' && !this.isOfflineApp() &&
		App.driveUsageHosts.indexOf(window.location.hostname) >= 0 &&
		domain.indexOf('.') > 0 && App.personalMailDomains.indexOf(domain) < 0;
};

/**
 * Gets the settings of the Drive user's organization once per page load and
 * caches them (OrgSettings.cacheKey), or removes the cache if there are none.
 * The app applies the cache on its next start, below the user's own
 * configuration (App.main), so start-up never waits for this request.
 */
App.prototype.updateOrgSettings = function()
{
	if (typeof OrgSettings !== 'undefined' && isLocalStorage && this.drive != null &&
		!this.orgSettingsRequested && !this.isOffline() && urlParams['embed'] != '1' &&
		App.driveUsageHosts.indexOf(window.location.hostname) >= 0)
	{
		this.orgSettingsRequested = this.drive.getOrgSettings(function(result)
		{
			try
			{
				var settings = (result.rev > 0) ? OrgSettings.filter(result.settings) : {};

				if (Object.keys(settings).length > 0)
				{
					localStorage.setItem(OrgSettings.cacheKey, JSON.stringify(
						{rev: result.rev, settings: settings}));
				}
				else
				{
					localStorage.removeItem(OrgSettings.cacheKey);
				}
			}
			catch (e)
			{
				// ignore
			}
		}, function()
		{
			// Keeps the cache
		});
	}
};

/**
 * Reports to the licence endpoint (DriveClient.checkLicense) the first time
 * each month that the user opens (usage is 'view') or saves (usage is 'edit')
 * a Google Drive diagram. The endpoint adds the user to the viewers or
 * editors of their domain this month and stores nothing about the user (its
 * sketches ignore a user sent again, but each request is a write), so
 * the user's own Drive remembers that they were counted: the usage marker in
 * draw.io's app data folder (DriveClient.getUsageMarker), read before and
 * written after each count, and cached in this browser. A first edit counts
 * as a view too if the month has none yet. Users without the email or
 * drive.appdata scope aren't counted and are asked again the next day.
 * Reports run one at a time, once per page load and usage at most, and
 * opening and editing never wait for them or depend on them.
 */
App.prototype.reportDriveUse = function(usage)
{
	var user = (this.drive != null) ? this.drive.getUser() : null;

	if ((usage == 'view' || usage == 'edit') && user != null && user.id != null &&
		!this.isOffline() && urlParams['dev'] != '1' && this.drive.hasIdToken() &&
		App.driveUsageHosts.indexOf(window.location.hostname) >= 0)
	{
		var id = usage + '-' + user.id;
		this.driveUsageReported = this.driveUsageReported || {};

		if (!this.driveUsageReported[id] && !this.isDriveUseCounted(user, usage))
		{
			this.driveUsageReported[id] = true;
			this.driveUsageQueue = this.driveUsageQueue || [];
			this.driveUsageQueue.push({user: user, usage: usage});

			if (!this.driveUsageBusy)
			{
				this.nextDriveUse();
			}
		}
	}
};

/**
 * Returns the key of the browser's cache of the usage marker of the user.
 */
App.prototype.getDriveUseKey = function(user)
{
	return '.drive-usage-' + Editor.crc32(user.id);
};

/**
 * Returns the browser's cache of the usage marker of the user: {view, edit,
 * wait}, the months the user was counted and the day not to ask before.
 */
App.prototype.getDriveUseCache = function(user)
{
	var cache = null;

	try
	{
		cache = (isLocalStorage) ? JSON.parse(localStorage.getItem(this.getDriveUseKey(user))) : null;
	}
	catch (e)
	{
		// ignore
	}

	return {view: (cache != null && typeof cache.view === 'string') ? cache.view : null,
		edit: (cache != null && typeof cache.edit === 'string') ? cache.edit : null,
		wait: (cache != null && typeof cache.wait === 'string') ? cache.wait : null};
};

/**
 * Stores the browser's cache of the usage marker of the user.
 */
App.prototype.setDriveUseCache = function(user, cache)
{
	try
	{
		if (isLocalStorage)
		{
			localStorage.setItem(this.getDriveUseKey(user), JSON.stringify(
				{view: cache.view, edit: cache.edit, wait: cache.wait}));
		}
	}
	catch (e)
	{
		// ignore
	}
};

/**
 * Returns true if this browser knows that the user was counted for the usage
 * this month, or must not ask before tomorrow.
 */
App.prototype.isDriveUseCounted = function(user, usage)
{
	var today = new Date().toISOString().substring(0, 10);
	var cache = this.getDriveUseCache(user);

	return cache[usage] == today.substring(0, 7) || cache.wait == today;
};

/**
 * Runs the next report of reportDriveUse: reads the usage marker, sends what
 * it hasn't counted this month, then writes it. Fails open.
 */
App.prototype.nextDriveUse = function()
{
	var next = (this.driveUsageQueue != null) ? this.driveUsageQueue.shift() : null;
	this.driveUsageBusy = next != null;

	if (next == null || this.drive == null || this.isDriveUseCounted(next.user, next.usage))
	{
		if (next != null)
		{
			this.nextDriveUse();
		}

		return;
	}

	var user = next.user;
	var today = new Date().toISOString().substring(0, 10);
	var month = today.substring(0, 7);
	var done = mxUtils.bind(this, function()
	{
		this.nextDriveUse();
	});

	this.drive.getUsageMarker(mxUtils.bind(this, function(marker)
	{
		// The drive could be another user's by now
		if (this.drive == null || this.drive.getUser() == null || this.drive.getUser().id != user.id)
		{
			done();

			return;
		}

		// What this browser knows was counted is, even if the marker missed it
		var cache = this.getDriveUseCache(user);
		marker.view = (cache.view == month) ? month : marker.view;
		marker.edit = (cache.edit == month) ? month : marker.edit;

		var counts = {};
		counts[next.usage] = marker[next.usage] != month;
		counts.view = counts.view || (counts.edit && marker.view != month);

		if (!counts.view && !counts.edit)
		{
			this.setDriveUseCache(user, {view: marker.view, edit: marker.edit});
			done();
		}
		else if (!this.drive.checkLicense(counts, mxUtils.bind(this, function(lic)
		{
			// Not counted without the email scope: asks again tomorrow
			if (lic.reason == 'unknown')
			{
				this.setDriveUseCache(user, {view: marker.view, edit: marker.edit, wait: today});
				done();
			}
			// Personal accounts are never counted: doesn't ask again this month
			else if (lic.reason == 'personal')
			{
				this.setDriveUseCache(user, {view: month, edit: month});
				done();
			}
			else
			{
				marker.view = (counts.view) ? month : marker.view;
				marker.edit = (counts.edit) ? month : marker.edit;
				this.setDriveUseCache(user, marker);

				// Only into the Drive of the user who was counted
				if (this.drive != null && this.drive.getUser() != null &&
					this.drive.getUser().id == user.id)
				{
					this.drive.setUsageMarker(marker, done, done);
					this.handleLicense(lic, null);
				}
				else
				{
					done();
				}
			}
		}), done))
		{
			done();
		}
	}), mxUtils.bind(this, function(err)
	{
		// Without the drive.appdata scope the user can't be counted only once
		// a month, so isn't counted, and is asked again tomorrow
		if (err != null && (err.status == 401 || err.status == 403))
		{
			var cache = this.getDriveUseCache(user);
			cache.wait = today;
			this.setDriveUseCache(user, cache);
		}

		done();
	}));
};

/**
 * Reports the user's first save of a Google Drive diagram this month
 * (App.reportDriveUse), called by DriveFile after each save.
 */
App.prototype.reportDriveEdit = function()
{
	this.reportDriveUse('edit');
};

/**
 * Returns true if the steps that start using draw.io ask for the Terms of
 * Use: on draw.io's own hosts (App.termsHosts), not in development mode
 * (dev=1) or embed mode, which has no such steps.
 */
App.prototype.isTermsAsked = function()
{
	return urlParams['dev'] != '1' && urlParams['embed'] != '1' &&
		App.termsHosts.indexOf(window.location.hostname) >= 0;
};

/**
 * Returns the line next to the button of a step that starts using draw.io
 * (StorageDialog, AuthDialog), whose click accepts the Terms of Use
 * (acceptTerms): "By continuing you agree to the Terms of Use and have read
 * the Privacy Policy", with links. The Privacy Policy is a notice, never
 * agreed to. Null where the Terms aren't asked for (isTermsAsked). Text and
 * links only, written as text.
 */
App.prototype.createTermsNotice = function()
{
	if (!this.isTermsAsked())
	{
		return null;
	}

	var link = mxUtils.bind(this, function(url, label)
	{
		var a = document.createElement('a');
		a.setAttribute('href', url);
		a.setAttribute('target', '_blank');
		a.setAttribute('rel', 'noopener noreferrer');
		mxUtils.write(a, label);

		mxEvent.addListener(a, 'click', mxUtils.bind(this, function(evt)
		{
			this.openLink(url);
			mxEvent.consume(evt);
		}));

		return a;
	});

	var links = {'{1}': link(App.termsUrl, mxResources.get('termsOfUse', null, 'Terms of Use')),
		'{2}': link(App.privacyUrl, mxResources.get('privacyPolicy', null, 'Privacy Policy'))};
	var parts = mxResources.get('termsNotice', null, 'By continuing you agree to the {1} and ' +
		'have read the {2}.').split(/(\{[12]\})/);
	var notice = document.createElement('p');
	notice.className = 'geDialogHint';
	notice.style.whiteSpace = 'normal';
	notice.style.lineHeight = '1.2em';

	for (var i = 0; i < parts.length; i++)
	{
		if (Object.prototype.hasOwnProperty.call(links, parts[i]))
		{
			notice.appendChild(links[parts[i]]);
		}
		else
		{
			mxUtils.write(notice, parts[i]);
		}
	}

	return notice;
};

/**
 * Records that the user accepted the Terms of Use with the button of a step
 * that showed the notice (createTermsNotice): the version and when, in this
 * browser and, if the step was for Google Drive (peer), in the user's own
 * Drive once they are signed in (recordTermsInDrive). Nothing goes to
 * draw.io's servers.
 */
App.prototype.acceptTerms = function(peer)
{
	if (this.isTermsAsked())
	{
		var record = this.getTermsRecord();

		if (record == null || record.version !== App.termsVersion)
		{
			this.setTermsRecord({version: App.termsVersion, accepted: new Date().toISOString()});
		}

		if (peer != null && peer == this.drive)
		{
			this.termsDrivePending = true;
			this.recordTermsInDrive();
		}
	}
};

/**
 * Writes the Terms of Use the user accepted at a step for Google Drive
 * (acceptTerms) to draw.io's app data folder of their Drive, once they are
 * signed in, unless it holds the current version. Fails quietly: without
 * the drive.appdata scope (403) the browser's record stays; an expired
 * token or no network tries again at the next sign-in.
 */
App.prototype.recordTermsInDrive = function()
{
	var user = (this.drive != null) ? this.drive.getUser() : null;
	var record = this.getTermsRecord();

	if (this.termsDrivePending && user != null && !this.isOffline() &&
		record != null && record.version === App.termsVersion)
	{
		this.termsDrivePending = false;

		var retry = mxUtils.bind(this, function(err)
		{
			this.termsDrivePending = err == null || err.status != 403;
		});

		this.drive.getTermsRecord(App.termsVersion, mxUtils.bind(this, function(stored)
		{
			if (stored.version !== App.termsVersion && this.drive != null && this.drive.getUser() != null &&
				this.drive.getUser().id == user.id)
			{
				this.drive.setTermsRecord({id: stored.id, version: record.version,
					accepted: record.accepted}, function()
				{
					// Done
				}, retry);
			}
		}), retry);
	}
};

/**
 * Returns the record of the Terms of Use accepted in this browser,
 * {version, accepted}, or null.
 */
App.prototype.getTermsRecord = function()
{
	var record = null;

	try
	{
		record = (isLocalStorage) ? JSON.parse(localStorage.getItem(App.termsKey)) : null;
	}
	catch (e)
	{
		// ignore
	}

	return (record != null && typeof record.version === 'string') ? {version: record.version,
		accepted: (typeof record.accepted === 'string') ? record.accepted : null} : null;
};

/**
 * Stores the record of the Terms of Use accepted in this browser.
 */
App.prototype.setTermsRecord = function(record)
{
	try
	{
		if (isLocalStorage)
		{
			localStorage.setItem(App.termsKey, JSON.stringify({version: record.version,
				accepted: record.accepted}));
		}
	}
	catch (e)
	{
		// ignore
	}
};

/**
 * 
 */
App.prototype.getEditBlankXml = function()
{
	var file = this.getCurrentFile();
	
	if (file != null && this.editor.isChromelessView() && this.editor.graph.isLightboxView())
	{
		return file.getData();
	}
	else
	{
		return this.getFileData(true);
	}
};

/**
 * Updates action states depending on the selection.
 */
App.prototype.updateActionStates = function()
{
	EditorUi.prototype.updateActionStates.apply(this, arguments);

	this.actions.get('revisionHistory').setEnabled(this.isRevisionHistoryEnabled());
};

/**
 * Adds the specified entry to the recent file list in local storage
 */
App.prototype.addRecent = function(entry, type, max)
{
	if (isLocalStorage && localStorage != null)
	{
		type = (type != null) ? type : '';	
		var recent = this.getRecent(type);
		
		if (recent == null)
		{
			recent = [];
		}
		else
		{
			for (var i = 0; i < recent.length; i++)
			{
				if (recent[i].mode == entry.mode &&
					recent[i].id == entry.id)
				{
					recent.splice(i, 1);
				}
			}
		}
		
		if (recent != null)
		{
			max = (max != null) ? max : 10;
			recent.unshift(entry);
			recent = recent.slice(0, max);
			localStorage.setItem('.recent' + type, JSON.stringify(recent));
		}
	}
};

/**
 * Returns the recent file list from local storage
 */
App.prototype.getRecent = function(type)
{
	if (isLocalStorage && localStorage != null)
	{
		type = (type != null) ? type : '';

		try
		{
			var recent = localStorage.getItem('.recent' + type);
			
			if (recent != null)
			{
				return JSON.parse(recent);
			}
		}
		catch (e)
		{
			// ignore
		}
		
		return null;
	}
};

/**
 * Clears the recent file list in local storage
 */
App.prototype.resetRecent = function(type)
{
	if (isLocalStorage && localStorage != null)
	{
		type = (type != null) ? type : '';

		try
		{
			localStorage.removeItem('.recent' + type);
		}
		catch (e)
		{
			// ignore
		}
	}
};

/**
 * Sets the onbeforeunload for the application
 */
App.prototype.onBeforeUnload = function()
{
	if (urlParams['embed'] == '1' && this.editor.modified)
	{
		return mxResources.get('allChangesLost');
	}
	else
	{
		this.unloading = true;
		var file = this.getCurrentFile();
		
		if (file != null)
		{
			// KNOWN: Message is ignored by most browsers
			if (file.constructor == LocalFile && file.getHash() == '' && !file.isModified() &&
				urlParams['nowarn'] != '1' && !this.isDiagramEmpty() && urlParams['url'] == null &&
				!this.editor.isChromelessView() && file.fileHandle == null)
			{
				return mxResources.get('ensureDataSaved');
			}
			else if (file.isModified())
			{
				this.logIfModified(file);

				return mxResources.get('allChangesLost');
			}
			else
			{
				file.close(true);
			}
		}
	}
};

/**
 * Updates the document title with the title of the current file and the app
 * name, or the name of the current page in lightbox view and the simple
 * theme.
 */
App.prototype.updateDocumentTitle = function()
{
	var title = this.editor.appName;
	var file = this.getCurrentFile();

	if (file != null && (this.editor.graph.isLightboxView() ||
		Editor.currentTheme == 'simple') &&
		this.pages != null && this.currentPage != null)
	{
		title = this.getShortPageName(this.currentPage);
	}
	else if (this.isOfflineApp())
	{
		title += ' app';
	}
	
	if (file != null)
	{
		var filename = (file.getTitle() != null) ? file.getTitle() : this.defaultFilename;
		title = filename + ' - ' + title;
	}
	
	if (document.title != title)
	{
		document.title = title;
	}
};

/**
 * Returns a thumbnail of the current file.
 */
App.prototype.getThumbnail = function(width, fn, border)
{
	border = (border != null) ? border : 0;
	var result = false;
	
	try
	{
		var acceptResponse = true;
		
		var timeoutThread = window.setTimeout(mxUtils.bind(this, function()
		{
			acceptResponse = false;
			fn(null);
		}), this.timeout);
		
		var success = mxUtils.bind(this, function(canvas)
		{
			window.clearTimeout(timeoutThread);
			
			if (acceptResponse)
			{
				fn(canvas);
			}
		});
		
		if (this.thumbImageCache == null)
		{
			this.thumbImageCache = new Object();
		}
		
		var graph = this.editor.graph;
		var bgImg = graph.backgroundImage;
		
		// Exports PNG for first page while other page is visible by creating a graph
		// LATER: Add caching for the graph or SVG while not on first page
		// To avoid refresh during save dark theme uses separate graph instance
		if (this.pages != null && this.currentPage != this.pages[0])
		{
			var graphGetGlobalVariable = graph.getGlobalVariable;
			graph = this.createTemporaryGraph(graph.getStylesheet());
			graph.setBackgroundImage = this.editor.graph.setBackgroundImage;
			var page = this.pages[0];

			if (this.currentPage == page)
			{
				graph.mathEnabled = this.editor.graph.mathEnabled;
				graph.setBackgroundImage(bgImg);
			}
			else if (page.viewState != null && page.viewState != null)
			{
				graph.mathEnabled = page.viewState.mathEnabled;
				bgImg = page.viewState.backgroundImage;
				graph.setBackgroundImage(bgImg);
				graph.setMeasureScale(page.viewState.measureScale);
			}

			graph.getGlobalVariable = function(name)
			{
				if (name == 'page')
				{
					return page.getName();
				}
				else if (name == 'pagenumber')
				{
					return 1;
				}
				
				return graphGetGlobalVariable.apply(this, arguments);
			};
			
			graph.getGlobalVariable = graphGetGlobalVariable;
			document.body.appendChild(graph.container);
			graph.model.setRoot(page.root);
		}
		
		// Uses client-side canvas export
		if (mxClient.IS_CHROMEAPP || Editor.useCanvasForExport)
		{
		   	this.editor.exportToCanvas(mxUtils.bind(this, function(canvas)
		   	{
		   		try
		   		{
			   		// Removes temporary graph from DOM
	   	   	    	if (graph != this.editor.graph && graph.container.parentNode != null)
					{
						graph.container.parentNode.removeChild(graph.container);
					}
				}
				catch (e)
				{
					canvas = null;
				}
				
		   		success(canvas);
		   	}), width, this.thumbImageCache, '#ffffff', function()
		   	{
		   		// Continues with null in error case
		   		success();
		   	}, null, null, null, null, null, null, graph, border, null, null,
			   null, 'diagram', null);
		   	
		   	result = true;
		}
		else if (Editor.canvasSupported && this.getCurrentFile() != null)
		{
			var canvas = document.createElement('canvas');
			var bounds = graph.getGraphBounds();
			var t = graph.view.translate;
			var s = graph.view.scale;

			if (bgImg != null)
			{
				bounds = mxRectangle.fromRectangle(bounds);
				bounds.add(new mxRectangle(
					(t.x + bgImg.x) * s, (t.y + bgImg.y) * s,
					bgImg.width * s, bgImg.height * s));
			}

			var scale = width / bounds.width;

			// Limits scale to 1 or 2 * width / height
			scale = Math.min(1, Math.min((width * 3) / (bounds.height * 4), scale));
			
			var x0 = Math.floor(bounds.x);
			var y0 = Math.floor(bounds.y);
			
			canvas.setAttribute('width', Math.ceil(scale * (bounds.width + 4)));
			canvas.setAttribute('height', Math.ceil(scale * (bounds.height + 4)));
			
			var ctx = canvas.getContext('2d');
			
			// Configures the canvas
			ctx.scale(scale, scale);
			ctx.translate(-x0, -y0);
			
			// Paint white background instead of transparent
			var bg = graph.background;
			
			if (bg == null || bg == '' || bg == mxConstants.NONE)
			{
				bg = '#ffffff';
			}
	
			// Paints background
			ctx.save();
			ctx.fillStyle = bg;
			ctx.fillRect(x0, y0, Math.ceil(bounds.width + 4), Math.ceil(bounds.height + 4));
			ctx.restore();
			
			// Paints background image
			if (bgImg != null)
			{
				var img = new Image();
				img.src = bgImg.src;

				ctx.drawImage(img, bgImg.x * scale, bgImg.y * scale,
					bgImg.width * scale, bgImg.height * scale);
			}
			
			var htmlCanvas = new mxJsCanvas(canvas);
			
			// NOTE: htmlCanvas passed into async canvas is only used for image
			// and canvas caching (canvas caching not used in this case as we do
			// not render text). To reuse that cache via the thumbImageCache we
			// pass that into the async canvas and override the image cache in
			// the newly created html canvas with that of the thumbImageCache.
			// LATER: Is clear thumbImageCache needed if file changes?
			var asynCanvas = new mxAsyncCanvas(this.thumbImageCache);
			htmlCanvas.images = this.thumbImageCache.images;
			
			// Render graph
			var imgExport = new mxImageExport();

			imgExport.drawShape = function(state, canvas)
			{
				if (state.shape instanceof mxShape && state.shape.checkBounds())
				{
					canvas.save();
					canvas.translate(0.5, 0.5);
					state.shape.paint(canvas);
					canvas.translate(-0.5, -0.5);
					canvas.restore();
				}
			};
			
			imgExport.drawText = function(state, canvas)
			{
				// No text output for thumbnails
			};
	
			imgExport.drawState(graph.getView().getState(graph.model.root), asynCanvas);
	
			asynCanvas.finish(mxUtils.bind(this, function()
			{
				try
				{
					imgExport.drawState(graph.getView().getState(graph.model.root), htmlCanvas);
					
			   		// Removes temporary graph from DOM
	   	   	    	if (graph != this.editor.graph && graph.container.parentNode != null)
					{
						graph.container.parentNode.removeChild(graph.container);
					}
				}
				catch (e)
				{
					canvas = null;
				}

				success(canvas);
			}));
			
			result = true;
		}
	}
	catch (e)
	{
		result = false;
		
		// Removes temporary graph from DOM
  	    if (graph != null && graph != this.editor.graph && graph.container.parentNode != null)
		{
			graph.container.parentNode.removeChild(graph.container);
		}
	}
	
	if (!result)
	{
		window.clearTimeout(timeoutThread);
	}
	
	return result;
};

/**
 * Overrides setMode to update Editor.useLocalStorage and the tooltip of the
 * app icon, and to store the mode if remember is true.
 */
(function()
{
	var editorUiSetMode = EditorUi.prototype.setMode;
	
	App.prototype.setMode = function(mode, remember)
	{
		editorUiSetMode.apply(this, arguments);
		
		// Note: UseLocalStorage affects the file dialogs
		// and should not be modified if mode is undefined
		if (this.mode != null)
		{
			Editor.useLocalStorage = this.mode == App.MODE_BROWSER;
		}

		if (this.appIcon != null)
		{
			var file = this.getCurrentFile();
			mode = (file != null) ? file.getMode() : mode;

			if (this.updateTitleListener == null)
			{
				this.updateTitleListener = mxUtils.bind(this, function()
				{
					if (mode == App.MODE_GOOGLE)
					{
						this.appIcon.setAttribute('title', mxResources.get('openIt', [mxResources.get('googleDrive')]));
					}
					else if (mode == App.MODE_ONEDRIVE)
					{
						this.appIcon.setAttribute('title', mxResources.get('openIt', [mxResources.get('oneDrive')]));
					}
					else
					{
						this.appIcon.removeAttribute('title');
					}
				});
				
				this.addListener('languageChanged', mxUtils.bind(this, function()
				{
					this.updateTitleListener();
				}));
			}

			this.updateTitleListener();
		}
		
		if (remember)
		{
			try
			{
				if (isLocalStorage)
				{
					localStorage.setItem('.mode', mode);
				}
				else if (typeof(Storage) != 'undefined')
				{
					var expiry = new Date();
					expiry.setYear(expiry.getFullYear() + 1);
					document.cookie = 'MODE=' + mode + '; expires=' + expiry.toUTCString();
				}
			}
			catch (e)
			{
				// ignore possible access denied
			}
		}
	};
})();

/**
 * Opens the URL of the current file, or of its folder if Alt is pressed, or
 * the start page of the storage of the current file.
 */
App.prototype.appIconClicked = function(evt)
{
	var file = this.getCurrentFile();
	var mode = (file != null) ? file.getMode() : null;
	var url = (file != null) ? (mxEvent.isAltDown(evt) ?
		file.getFolderUrl() : file.getFileUrl()) : null;

	var storage = (mode != null) ? App.storages[mode] : null;

	if (url == null)
	{
		url = (storage != null && storage.url != null) ? storage.url : 'https://www.drawio.com/';
	}

	this.openLink(url);
	mxEvent.consume(evt);
};

/**
 * Function: authorize
 * 
 * Authorizes the client, gets the userId and calls <open>.
 */
App.prototype.clearMode = function()
{
	if (isLocalStorage)
	{
		localStorage.removeItem('.mode');
	}
	else if (typeof(Storage) != 'undefined')
	{
		var expiry = new Date();
		expiry.setYear(expiry.getFullYear() - 1);
		document.cookie = 'MODE=; expires=' + expiry.toUTCString();
	}
};

/**
 * Opens any file specified in the URL parameters.
 */
App.prototype.open = function()
{
	// Cross-domain window access is not allowed in FF, so if we
	// were opened from another domain then this will fail.
	try
	{
		// If the create URL param is used in embed mode then
		// we try to open the XML from window.opener[value].
		// Use this for embedding via tab to bypass the timing
		// issues when passing messages without onload event.
		if (window.opener != null)
		{
			var value = urlParams['create'];
			
			if (value != null)
			{
				value = decodeURIComponent(value);
			}
			
			if (value != null && value.length > 0 && value.substring(0, 7) != 'http://' &&
				value.substring(0, 8) != 'https://')
			{
				var doc = mxUtils.parseXml(window.opener[value]);
				this.editor.setGraphXml(doc.documentElement);
			}
			else if (window.opener.openFile != null)
			{
				window.opener.openFile.setConsumer(mxUtils.bind(this, function(xml, filename, temp)
				{
					this.spinner.stop();
					
					if (filename == null)
					{
						var title = urlParams['title'];
						temp = true;
						
						if (title != null)
						{
							filename = decodeURIComponent(title);
						}
						else
						{
							filename = this.defaultFilename;
						}
					}
					
					// Replaces PNG with XML extension
					var dot = (!Editor.useCanvasForExport) ? filename.substring(filename.length - 4) == '.png' : -1;
					
					if (dot > 0)
					{
						filename = filename.substring(0, filename.length - 4) + '.drawio';
					}
					
					this.fileLoaded((mxClient.IS_IOS) ?
						new StorageFile(this, xml, filename) :
						new LocalFile(this, xml, filename, temp));
					
					// Marks temp files as changed to trigger draft save
					var file = this.getCurrentFile();

					if (temp && file != null)
					{
						file.fileChanged();
					}
				}));
			}
		}
	}
	catch(e)
	{
		// ignore
	}
};

App.prototype.loadGapi = function(then)
{
	if (typeof gapi !== 'undefined')
	{
		gapi.load(((urlParams['picker'] != '0') ? 'picker,': '') + App.GOOGLE_APIS, then);
	}
};

/**
 * Main function. Program starts here.
 * 
 * @param {number} dx X-coordinate of the translation.
 * @param {number} dy Y-coordinate of the translation.
 */
App.prototype.load = function()
{
	try
	{
		// Checks if we're running in embedded mode
		if (urlParams['embed'] != '1')
		{
			try
			{
				if (this.spinner.spin(document.body, mxResources.get('starting')))
				{
					try
					{
						this.stateArg = (urlParams['state'] != null && this.drive != null) ?
							JSON.parse(decodeURIComponent(urlParams['state'])) : null;
					}
					catch (e)
					{
						// ignores invalid state args
					}
					
					this.editor.graph.setEnabled(this.getCurrentFile() != null);
					
					// Passes the userId from the state parameter to the client
					if ((window.location.hash == null || window.location.hash.length == 0) &&
						this.drive != null && this.stateArg != null && this.stateArg.userId != null)
					{
						this.drive.setUserId(this.stateArg.userId);
					}

					// Legacy support for fileId parameter which is moved to the hash tag
					if (urlParams['fileId'] != null)
					{
						window.location.hash = 'G' + urlParams['fileId'];
						window.location.search = this.getSearch(['fileId']);
					}
					else
					{
						// Asynchronous or disabled loading of client
						if (this.drive == null)
						{
							if (this.mode == App.MODE_GOOGLE)
							{
								this.mode = null;
							}
							
							this.start();
						}
						else
						{
							this.loadGapi(mxUtils.bind(this, function()
							{
								this.start();
							}));
						}
					}
				}
			}
			catch (e)
			{
				this.handleError(e);
			}
		}
		else
		{
			this.restoreLibraries();
			
			if (urlParams['gapi'] == '1')
			{
				this.loadGapi(function() {});
			}
		}
	}
	catch (e)
	{
		if (EditorUi.isElectronApp)
		{
			mxLog.show();
			mxLog.debug(e.stack);
		}
		else
		{
			EditorUi.logError(e.message, null, null, null, e);
			alert(e.message);
		}
	}
};

/**
 * Adds the listener for automatically saving the diagram for local changes.
 */
App.prototype.showRefreshDialog = function(title, message)
{
	if (!this.showingRefreshDialog)
	{
		this.showingRefreshDialog = true;

		this.showError(title || mxResources.get('externalChanges'),
			message || mxResources.get('redirectToNewApp'),
			mxResources.get('refresh'), mxUtils.bind(this, function()
		{
			var file = this.getCurrentFile();
			
			if (file != null)
			{
				file.setModified(false);
			}
				
			this.spinner.spin(document.body, mxResources.get('connecting'));
			this.editor.graph.setEnabled(false);
			window.location.reload();
		}), null, null, null, null, null, 340, 180);
		
		// Adds important notice to dialog
		if (this.dialog != null && this.dialog.container != null)
		{
			var alert = this.createRealtimeNotice();
			alert.style.left = '0';
			alert.style.right = '0';
			alert.style.borderRadius = '0';
			alert.style.borderLeftStyle = 'none';
			alert.style.borderRightStyle = 'none';
			alert.style.marginBottom = '26px';
			alert.style.padding = '8px 0 8px 0';

			this.dialog.container.appendChild(alert);
		}
	}
};

/**
 * Shows the given message in a closable alert that hides itself after a
 * delay.
 */
App.prototype.showAlert = function(message)
{
	if (message != null && message.length > 0)
	{
		var div = document.createElement('div');
		div.className = 'geAlert';
		div.setAttribute('role', 'alert');
		div.style.zIndex = 2e9; 
		div.style.left = '50%';
		div.style.top = '-100%';
		//Limit width to 80% max with word wrapping
		div.style.maxWidth = '80%';
		div.style.width = 'max-content';
		div.style.whiteSpace = 'pre-wrap';
		mxUtils.setPrefixedStyle(div.style, 'transform', 'translate(-50%,0%)');
		mxUtils.setPrefixedStyle(div.style, 'transition', 'all 1s ease');
		
		div.innerHTML = message;
		
		var close = document.createElement('a');
		close.className = 'geAlertLink';
		close.style.textAlign = 'right';
		close.style.marginTop = '20px';
		close.style.display = 'block';
		close.setAttribute('title', mxResources.get('close'));
		close.innerHTML = mxResources.get('close');
		Editor.initKeyboardButton(close);
		div.appendChild(close);
		
		mxEvent.addListener(close, 'click', function(evt)
		{
			if (div.parentNode != null)
			{
				div.parentNode.removeChild(div);
				mxEvent.consume(evt);
			}
		});
		
		document.body.appendChild(div);
		
		// Delayed to get smoother animation after DOM rendering
		window.setTimeout(function()
		{
			div.style.top = '30px';
		}, 10);
		
		// Fades out the alert after 15 secs
		window.setTimeout(function()
		{
			mxUtils.setPrefixedStyle(div.style, 'transition', 'all 2s ease');
			div.style.opacity = '0';
			
			window.setTimeout(function()
			{
				if (div.parentNode != null)
				{
					div.parentNode.removeChild(div);
				}
			}, 2000);
		}, 15000);
	}
};

/**
 * Starts the app after initialization. Restores the libraries, installs the
 * global error and hash change handlers and opens the diagram specified in
 * the URL, or shows the splash screen.
 */
App.prototype.start = function()
{
	try
	{
		// Handles all errors
		this.restoreLibraries();
		this.spinner.stop();
		var ui = this;

		window.onerror = function(message, url, linenumber, colno, err)
		{
			// Ignores Grammarly error [1344] and errors of foreign scripts, eg.
			// in-app browsers, which carry no information (the app keeps working)
			if (message != 'ResizeObserver loop limit exceeded' &&
				!EditorUi.isOpaqueScriptError(message, linenumber))
			{
				// "Invalid or unexpected token" is a JS engine parse error that can only
				// come from eval() or new Function(). All eval() calls in the codebase are
				// wrapped in try/catch, so this reaching window.onerror indicates external
				// interference (browser extensions, corrupted cache, proxy injection).
				if (message == null || message.indexOf('Invalid or unexpected token') < 0)
				{
					EditorUi.logError('Uncaught: ' + ((message != null) ? message : ''),
						url, linenumber, colno, err, null, true);
				}

				ui.handleError({message: message}, mxResources.get('unknownError'),
					null, null, null, null, true);
			}
		};
		
		// Listens to changes of the hash if not in embed or client mode
		if (urlParams['client'] != '1' && urlParams['embed'] != '1')
		{
			// Installs listener to claim current draft if there is one
			try
			{
				if (isLocalStorage)
				{
					window.addEventListener('storage', mxUtils.bind(this, function(evt)
					{
						var file = this.getCurrentFile();
						EditorUi.debug('storage event', [evt], [file]);
	
						if (file != null && evt.key == '.draft-alive-check' &&
							evt.newValue != null && file.draftId != null)
						{
							this.draftAliveCheck = evt.newValue;
							file.saveDraft();
						}
					}));
				}
			}
			catch (e)
			{
				// ignore
			}

			// Handles changes of the file ID in the hash
			var lastId = this.getDiagramId();
			
			mxEvent.addListener(window, 'hashchange', mxUtils.bind(this, function(evt)
			{
				try
				{
					var id = this.getDiagramId();

					if (id != lastId)
					{
						lastId = id;
						var file = this.getCurrentFile();

						// A file created from a #create link is also the file of
						// the hash it was rewritten to (see executeCreateObject)
						if (file == null || (file.getHash() != id &&
							file.createdHash != id))
						{
							this.loadFile(id, true);
						}
					}
					else
					{
						var obj = this.getHashObject();

						if (obj != null && obj.pageId != null && this.currentPage != null &&
							obj.pageId != this.currentPage.getId())
						{
							var page = this.getPageById(obj.pageId);

							if (page != null)
							{
								this.selectPage(page);
							}
						}
					}
				}
				catch (e)
				{
					// Workaround for possible scrollWidth of null in Dialog ctor
					if (document.body != null)
					{
						this.handleError(e, mxResources.get('errorLoadingFile'), mxUtils.bind(this, function()
						{
							var file = this.getCurrentFile();
							window.location.hash = (file != null) ? file.getHash() : '';
						}));
					}
				}
			}));
		}
		
		// Descriptor for CSV import
		if ((window.location.hash == null || window.location.hash.length <= 1) && urlParams['desc'] != null)
		{
			try
			{
				this.loadDescriptor(JSON.parse(Graph.decompress(urlParams['desc'])),
					null, mxUtils.bind(this, function(e)
				{
					this.handleError(e, mxResources.get('errorLoadingFile'));
				}));
			}
			catch (e)
			{
				this.handleError(e, mxResources.get('errorLoadingFile'));
			}
		}
		// Redirects old url URL parameter to new #U format
		else if ((window.location.hash == null || window.location.hash.length <= 1) && urlParams['url'] != null)
		{
			this.loadFile('U' + urlParams['url'], true);
		}
		else if (this.getCurrentFile() == null)
		{
			var done = mxUtils.bind(this, function()
			{
				// Starts in client mode and waits for data
				if (urlParams['client'] == '1' && (window.location.hash == null ||
					window.location.hash.length == 0 || window.location.hash.substring(0, 2) == '#P'))
				{
					var doLoadFile = mxUtils.bind(this, function(xml)
					{
						// Extracts graph model from PNG
						if (Editor.isPngDataUrl(xml))
						{
							xml = Editor.extractGraphModelFromPng(xml);
						}
						
						var title = urlParams['title'];
						
						if (title != null)
						{
							title = decodeURIComponent(title);
						}
						else
						{
							title = this.defaultFilename;
						}
						
						var file = new LocalFile(this, xml, title, true);
						this.fileLoaded(file);

						// Clears parameters hash property in client mode
						if (window.location.hash != null &&
							window.location.hash.substring(0, 2) == '#P')
						{
							window.location.hash = '';
						}
						
						if (!this.editor.chromeless)
						{
							// Handles possible copy of modified file
							file.fileChanged();

							window.setTimeout(mxUtils.bind(this, function()
							{
								this.actions.get('resetView').funct();
							}), 0);
						}
					});

					var parent = window.opener || window.parent;
					
					if (parent != window)
					{
						var value = urlParams['create'];
						
						if (value != null)
						{
							doLoadFile(parent[decodeURIComponent(value)]);
						}
						else
						{
							value = urlParams['data'];
							
							if (value != null)
							{
								doLoadFile(decodeURIComponent(value));
							}
							else if (this.spinner.spin(document.body, mxResources.get('loading')))
							{
								this.createTimeout(2000, mxUtils.bind(this, function(timeout)
								{
									this.installMessageHandler(mxUtils.bind(this, function(xml, evt)
									{
										// Ignores messages from other windows
										if (evt.source == parent && timeout.clear())
										{
											this.spinner.stop();
											doLoadFile(xml);
										}
									}));
								}), mxUtils.bind(this, function(err)
								{
									this.handleError(err);
								}));
							}
						}
					}
				}
				// Checks if no earlier loading errors are showing
				else if (this.dialog == null)
				{
					if (urlParams['demo'] == '1')
					{
						var prev = Editor.useLocalStorage;
						this.createFile(this.defaultFilename, null,
							null, null, null, null, null, true);
						Editor.useLocalStorage = prev;
					}
					else
					{
						var waiting = false;
						
						// Checks if we're waiting for some asynchronous file to be loaded
						// Cross-domain window access is not allowed in FF, so if we
						// were opened from another domain then this will fail.
						try
						{
							waiting = window.opener != null && window.opener.openFile != null;
						}
						catch(e)
						{
							// ignore
						}
						
						if (waiting)
						{
							// Spinner is stopped in App.open
							this.spinner.spin(document.body, mxResources.get('loading'))
						}
						else
						{
							var id = this.getDiagramId();
							
							if (EditorUi.enableDrafts && urlParams['mode'] == null &&
								this.getServiceName() == 'draw.io' && (id == null || id.length == 0) &&
								!this.editor.isChromelessView())
							{
								this.checkDrafts();
							}
							else if (id != null && id.length > 0)
							{
								this.loadFile(id, null, null, mxUtils.bind(this, function()
								{
									// Same object as the embed protocol's viewbox
									// option, see EditorUi.parseViewBox
									var bounds = EditorUi.getViewBoxParam();

									if (bounds != null)
									{
										this.applyViewBox(bounds);
									}
								}));
							}
							else if (urlParams['splash'] != '0' || (urlParams['mode'] != null && !EditorUi.isElectronApp))
							{
								this.loadFile();
							}
							else
							{
								this.createFile(this.defaultFilename, this.getFileData(),
									null, null, null, null, null, true);
							}
						}
					}
				}
			});
	
			var value = decodeURIComponent(urlParams['create'] || '');

			if (window.location.hash != null && window.location.hash.substring(0, 8) == '#create=')
			{
				value = decodeURIComponent(window.location.hash.substring(8));
			}
			
			if (urlParams['smart-template'] != null && (window.location.hash == null ||
				window.location.hash.length <= 1))
			{
				value = JSON.stringify({
					type: 'generate', data: decodeURIComponent(urlParams['smart-template'])
				});
			}
			
			if ((window.location.hash == null || window.location.hash.length <= 1) &&
				value.length > 0 && this.spinner.spin(document.body, mxResources.get('loading')))
			{
				var reconnect = mxUtils.bind(this, function()
				{
					// Removes URL parameter and reloads the page
					if (this.spinner.spin(document.body, mxResources.get('reconnecting')))
					{
						window.location.search = this.getSearch(['create', 'title']);
					};
				});
	
				var showCreateDialog = mxUtils.bind(this, function(xml)
				{
					this.spinner.stop();
	
					// Resets mode for dialog - local file is only for preview
					if (urlParams['splash'] != '0')
					{
						this.fileLoaded(new LocalFile(this, xml, null));
						
						this.editor.graph.setEnabled(false);
						var mode = urlParams['mode'];

						// Ignores a requested mode for a storage that has been removed
						// or that is not enabled (trello without tr=1), as in init
						this.mode = (mode != null && App.isKnownMode(mode) &&
							(mode != App.MODE_TRELLO || this.isModeEnabled(mode))) ?
							mode : null;
						var title = urlParams['title'];
		
						if (title != null)
						{
							title = decodeURIComponent(title);
						}
						else
						{
							title = this.defaultFilename;
						}
						
						var serviceCount = this.getServiceCount(true);
						
						if (isLocalStorage)
						{
							serviceCount++;
						}
						
						var rowLimit = (serviceCount <= 4) ? 2 : (serviceCount > 6 ? 4 : 3);
						
						var dlg = new CreateDialog(this, title, mxUtils.bind(this, function(filename, mode)
						{
							try
							{
								if (mode == null)
								{
									this.hideDialog();
									var prev = Editor.useLocalStorage;
									this.createFile((filename.length > 0) ? filename : this.defaultFilename,
										this.getFileData(), null, null, null, true, null, true);
									Editor.useLocalStorage = prev;
								}
								else
								{
									this.pickFolder(mode, mxUtils.bind(this, function(folderId)
									{
										try
										{
											this.createFile(filename, this.getFileData(true),
												null, mode, null, true, folderId);
										}
										catch (e)
										{
											this.handleError(e);
										}
									}));
								}
							}
							catch (e)
							{
								this.handleError(e);
							}
						}), null, null, null, null, urlParams['browser'] == '1',
							null, null, true, rowLimit, null, null, null,
							this.editor.fileExtensions);
						this.showDialog(dlg.container, 420, (serviceCount > rowLimit) ? 390 : 280,
							true, false, mxUtils.bind(this, function(cancel)
						{
							if (cancel && this.getCurrentFile() == null)
							{
								this.showSplash();
							}
						}));
						dlg.init();
					}
				});
				
				if (value.substring(0, 7) != 'http://' && value.substring(0, 8) != 'https://')
				{
					try
					{
						if (value.charAt(0) == '{')
						{
							this.executeCreateObject(JSON.parse(decodeURIComponent(value)),
								mxUtils.bind(this, function()
								{
									window.history.replaceState(null, null,
										window.location.pathname +
										this.getSearch(['create']));
								}));
						}
						else
						{
							// Cross-domain window access is not allowed in FF, so if we
							// were opened from another domain then this will fail.
							if (window.opener != null && window.opener[value] != null)
							{
								showCreateDialog(window.opener[value]);
							}
							else
							{
								throw new Error(mxResources.get('invalidCallFnNotFound', ['window.opener.' + value]));
							}
						}
					}
					catch (e)
					{
						this.handleError(e, mxResources.get('errorLoadingFile'));
					}
				}
				else
				{
					this.loadTemplate(value, function(text)
					{
						showCreateDialog(text);
					}, mxUtils.bind(this, function(e)
					{
						this.handleError(e, mxResources.get('errorLoadingFile'), reconnect);
					}));
				}
			}
			else
			{
				// Passes the fileId from the state parameter to the hash tag and reloads
				// the page without the state parameter
				if ((window.location.hash == null || window.location.hash.length <= 1) &&
					urlParams['state'] != null && this.stateArg != null && this.stateArg.action == 'open')
				{
					if (this.stateArg.ids != null)
					{
						if (window.history && window.history.replaceState)
						{
							// Removes state URL parameter without reloading the page
							window.history.replaceState(null, null, window.location.pathname +
								this.getSearch(['state', 'splash']));
						}
						
						window.location.hash = 'G' + this.stateArg.ids[0];
					}
				}
				else if ((window.location.hash == null || window.location.hash.length <= 1) &&
					this.drive != null && this.stateArg != null && this.stateArg.action == 'create')
				{
					if (window.history && window.history.replaceState)
					{
						// Removes state URL parameter without reloading the page
						window.history.replaceState(null, null, window.location.pathname +
							this.getSearch(['state']));
					}
					
					this.setMode(App.MODE_GOOGLE);

					if (urlParams['splash'] == '0')
					{
						this.createFile((urlParams['title'] != null) ?
							decodeURIComponent(urlParams['title']) :
							this.defaultFilename);
					}
					else
					{
						this.actions.get('new').funct();
					}
				}
				else
				{
					// Removes open URL parameter. Hash is also updated in Init to load client.
					if (urlParams['open'] != null && window.history && window.history.replaceState)
					{
						window.history.replaceState(null, null, window.location.pathname +
							this.getSearch(['open', 'sketch']));
						window.location.hash = urlParams['open'];
					}
					
					done();
				}
			}
		}
	}
	catch (e)
	{
		this.handleError(e);
	}
};

/**
 * Creates a new diagram from the given create object, whose data can be
 * XML, CSV, Mermaid or a prompt for generating a diagram, or is loaded from
 * its url, and invokes done. Applies the optional layouts and stores the
 * resulting XML in the URL hash.
 */
App.prototype.executeCreateObject = function(value, done)
{
	try
	{
		EditorUi.debug('App.executeCreateObject',
			[this], 'value', [value]);
		
		var createDiagram = mxUtils.bind(this, function(xml)
		{
			this.spinner.stop();

			this.createFile((value.filename != null) ?
				value.filename : this.defaultFilename,
				xml, null, null, mxUtils.bind(this, function()
				{
					var file = this.getCurrentFile();

					if (urlParams['pv'] != null)
					{
						this.setPageVisible(urlParams['pv'] == '1');
					}

					if (urlParams['grid'] != null)
					{
						this.editor.graph.setGridEnabled(
							urlParams['grid'] == '1');
					}

					var finish = mxUtils.bind(this, function()
					{
						// Fits diagram to window
						this.initialFitDiagram(1.2);

						// Easter egg: pop effect animates all cells on load
						if (value.effect == 'pop')
						{
							var graph = this.editor.graph;
							var cells = graph.model.getDescendants(
								graph.model.getRoot());
							var nodes = graph.getNodesForCells(cells);
							Graph.setOpacityForNodes(nodes, 0);

							window.setTimeout(mxUtils.bind(this, function()
							{
								var animations = graph.createPopAnimations(
									cells, true);
								graph.executeAnimations(animations);
							}), 200);
						}

						// Needs to go before upate of hash if
						// it replaces the history state
						if (done != null)
						{
							done();
						}

						// Sets create value with compressed XML. When a layout
						// was applied, store the laid-out XML and drop the
						// layout options so a reload reproduces the result
						// without re-running them.
						value.type = 'xml';
						value.compressed = true;
						var data = xml;

						if (value.layout != null || value.applyLayouts)
						{
							// Keeps the Alt Text of the page (see createMermaidPageXml)
							data = mxUtils.getXml((this.currentPage != null &&
								this.currentPage.getAlt() != null) ?
								this.getXmlFileData(null, null, true) :
								this.editor.getGraphXml());
						}

						value.data = Graph.compress(data);
						delete value.layout;
						delete value.applyLayouts;
						var hash = 'create=' + encodeURIComponent(JSON.stringify(value));

						// fileLoaded has cleared the hash for the new file, and
						// the hashchange handler compares the result with the
						// hash from before the load. Any rewrite that differs
						// from the link (Mermaid, CSV, another encoder, a host
						// that re-encodes the link) would load the link again
						// and ask to discard the changes. Skipped if another
						// file was opened while a layout ran.
						if (file != null && file == this.getCurrentFile())
						{
							file.createdHash = hash;
							window.location.hash = hash;
						}

						// explore: opens the explorer for a cell of a page with
						// a number of levels (see EditorUi.openExplorer)
						if (value.explore != null)
						{
							this.openExplorer(value.explore);
						}
					});

					// layout: run the requested layout (a preset name or
					// custom-layout JSON, the same format as the desktop
					// --layout flag and the embed "layout" action) before
					// fitting so the view reflects the new positions.
					var runLayout = mxUtils.bind(this, function()
					{
						if (value.layout != null)
						{
							this.executeLayoutSpec(value.layout, finish);
						}
						else
						{
							finish();
						}
					});

					// applyLayouts: run the layouts defined in the diagram's
					// childLayout styles (nested children before their parents)
					// first, so a one-shot layout given via the layout option
					// sees the containers at their final size.
					if (value.applyLayouts)
					{
						this.applyChildLayouts(runLayout);
					}
					else
					{
						runLayout();
					}
				}), true, null, true);
		});

		// url: loads the data from the given URL like a template, via the
		// proxy where CORS isn't enabled. For the xml type (the default) the
		// diagram is taken from the file: a .drawio or .xml file, an editable
		// SVG or PNG, or a Visio, Gliffy or Lucidchart file. Other types use
		// the text of the file. The hash written after the diagram was created
		// carries the data, so a reload doesn't load the URL again.
		if (value.url != null && value.data == null)
		{
			var url = String(value.url);
			delete value.url;
			this.spinner.spin(document.body, mxResources.get('loading'));

			this.loadTemplate(url, mxUtils.bind(this, function(text)
			{
				// Each type starts its own spinner as without a URL, and the
				// generate type only runs if it can start it
				this.spinner.stop();

				try
				{
					if (value.type == null || value.type == 'xml')
					{
						var node = (text != null) ? this.editor.extractGraphModel(
							mxUtils.parseXml(text).documentElement, true) : null;

						if (node == null)
						{
							throw new Error(mxResources.get('invalidOrMissingFile'));
						}

						value.type = 'xml';
						value.data = mxUtils.getXml(node);
					}
					else
					{
						value.data = text;
					}

					delete value.compressed;
					this.executeCreateObject(value, done);
				}
				catch (e)
				{
					this.handleError(e, mxResources.get('errorLoadingFile'));
				}
			}), mxUtils.bind(this, function(e)
			{
				this.spinner.stop();
				this.handleError(e, mxResources.get('errorLoadingFile'));
			}));

			return;
		}

		var data = value.data;

		if (value.compressed)
		{
			data = Graph.decompress(data);
		}

		if (value.type == 'mermaid')
		{
			if (EditorUi.isMermaidSupported())
			{
				var onMermaidError = mxUtils.bind(this, function(e)
				{
					this.handleError(e);
				});

				// A created diagram is new, so it gets the defaults version of
				// new diagrams unless the link names one (eg. to match a preview
				// that was rendered with another version)
				var version = (value.version != null) ? String(value.version) :
					EditorUi.getInsertMermaidVersion();

				if (value.image)
				{
					// image:true creates the diagram as a static SVG image cell
					// (carrying the mermaid source for re-editing), matching the
					// legacy image insert. New images follow the configured Mermaid
					// config, or keep the legacy look when unset (parseMermaidImage).
					// The diagram is the page, so its text alternative becomes
					// the Alt Text of the page (see createMermaidPageXml)
					this.parseMermaidImage(data, mxUtils.bind(this, function(xml)
					{
						createDiagram(this.createMermaidPageXml(xml));
					}), onMermaidError, version);
				}
				else
				{
					this.parseMermaidDiagram(data, null, mxUtils.bind(this, function(xml)
					{
						createDiagram(this.createMermaidPageXml(mxMermaidToDrawio.wrapGroup(
							xml, data, EditorUi.getInsertMermaidConfig(),
							(version != null) ? {version: version} : null)));
					}), onMermaidError, null, version);
				}
			}
			else
			{
				throw new Error(mxResources.get('serviceUnavailableOrBlocked'));
			}
		}
		else if (value.type == 'generate' && this.spinner.spin(
			document.body, mxResources.get('generate') +
			' \''+ data + '\''))
		{
			this.generateOpenAiMermaidDiagram(data, function(xml)
			{
				createDiagram(xml);
			}, mxUtils.bind(this, function(e)
			{
				this.handleError(e, mxResources.get('errorLoadingFile'));
			}), {complexity: 'high'});
		}
		else if (value.type == 'csv')
		{
			var graph = this.createTemporaryGraph(this.editor.graph.getStylesheet());
			
			this.importCsv(data, mxUtils.bind(this, function()
			{
				var codec = new mxCodec();
				createDiagram(mxUtils.getXml(
					codec.encode(graph.getModel())));
			}), graph, true);
		}
		else if (value.type == 'xml')
		{
			createDiagram(data);
		}
		else
		{
			throw new Error(mxResources.get('invalidCallFnNotFound', [value.type]));
		}
	}
	catch (e)
	{
		this.handleError(e, mxResources.get('errorLoadingFile'));
	}
};

/**
 * 
 */
App.prototype.openGenerateDialog = function(prompt)
{
	if (this.chatWindow == null)
	{
		var saved = mxSettings.getWindowState('chat');
		var cx = (saved != null && saved.x != null) ? saved.x : 224;
		var cy = (saved != null && saved.y != null) ? saved.y : 104;
		var cw = (saved != null && saved.w != null) ? saved.w : 440;
		var ch = (saved != null && saved.h != null) ? saved.h : 440;

		this.chatWindow = new ChatWindow(this, cx, cy, cw, ch);
		this.chatWindow.window.addListener('show', mxUtils.bind(this, function()
		{
			this.fireEvent(new mxEventObject('chat'));
		}));
		this.chatWindow.window.addListener('hide', function()
		{
			this.fireEvent(new mxEventObject('chat'));
		});

		this.installWindowPersistence('chat', this.chatWindow);

		if (saved != null && prompt == null)
		{
			this.restoreWindowState('chat', this.chatWindow);
		}
		else
		{
			this.chatWindow.window.setVisible(true);
		}

		this.fireEvent(new mxEventObject('chat'));
	}
	else
	{
		this.chatWindow.window.setVisible(true);
	}

	if (prompt != null)
	{
		this.chatWindow.generate(prompt);
	}
};

/**
 * Returns true if templates can be inserted (see Insert, Template).
 */
App.prototype.isTemplateSearchSupported = function()
{
	return this.insertTemplateEnabled && !this.isOffline() &&
		this.editor.graph.isEnabled();
};

/**
 * Opens the templates dialog with the given search terms.
 */
App.prototype.searchTemplates = function(terms)
{
	this.openTemplateDialog(null, terms);
};

/**
 * Opens the templates dialog for inserting a template with the optional
 * prompt for generating a diagram and the optional search terms.
 */
App.prototype.openTemplateDialog = function(generatePrompt, searchTerms)
{
	var graph = this.editor.graph;
	
	if (graph.isEnabled() && !graph.isCellLocked(graph.getDefaultParent()))
	{
		var dlg = new NewDialog(this, null, false, mxUtils.bind(this, function(xml)
		{
			this.hideDialog();
			
			if (xml != null)
			{
				var insertPoint = this.editor.graph.getFreeInsertPoint(true);
				graph.setSelectionCells(this.importXml(xml,
					Math.max(insertPoint.x, 20),
					Math.max(insertPoint.y, 20),
					true, null, null, true));
				graph.scrollCellToVisible(graph.getSelectionCell());
			}
		}), null, null, null, null, null, null, null, null, null, null,
			false, mxResources.get('insert'), null, null, generatePrompt,
			null, true);

		this.showDialog(dlg.container, 620, 460, true, true, mxUtils.bind(this, function()
		{
			this.sidebar.hideTooltip();
		}));
		
		dlg.init();

		if (searchTerms != null && searchTerms.length > 0)
		{
			dlg.searchTemplates(searchTerms);
		}
	}
};

/**
 * Checks for orphaned drafts.
 */
App.prototype.loadDraft = function(xml, success)
{
	this.createFile(this.defaultFilename, xml, null, null, mxUtils.bind(this, function()
	{
		window.setTimeout(mxUtils.bind(this, function()
		{
			var file = this.getCurrentFile();
			
			if (file != null)
			{
				file.fileChanged();
				
				if (success != null)
				{
					success();
				}
			}
		}), 0);
	}), null, null, true);
};

/**
 * Checks for orphaned drafts.
 */
App.prototype.filterDrafts = function(filePath, guid, callback)
{
	var drafts = [];

	function result()
	{
		callback(drafts);
	};

	try
	{
		this.getDatabaseItems(mxUtils.bind(this, function(items)
		{
			EditorUi.debug('App.filterDrafts',
				[this], 'items', items);

			// Collects orphaned drafts
			for (var i = 0; i < items.length; i++)
			{
				try
				{
					var key = items[i].key;
					
					if (key != null && key.substring(0, 7) == '.draft_')
					{
						var obj = JSON.parse(items[i].data);

						if (obj != null && obj.type == 'draft' && obj.aliveCheck != guid &&
							((filePath == null && obj.fileObject == null) ||
								(obj.fileObject != null && obj.fileObject.path == filePath)))
						{
							// Drop drafts whose payload has no user-added cells.
							// These get created when a recovery draft is saved
							// for a file the user then emptied; surfacing them
							// in the draft picker only confuses the user.
							if (this.isDiagramDataEmpty(obj.data))
							{
								this.removeDatabaseItem(key);
							}
							else
							{
								obj.key = key;
								drafts.push(obj);
							}
						}
					}
				}
				catch (e)
				{
					// ignore
				}
			}

			result();
		}), result);
	}
	catch (e)
	{
		result();
	}
};

/**
 * Checks for orphaned drafts.
 */
App.prototype.checkDrafts = function()
{
	try
	{
		// Triggers storage event for other windows to mark active drafts
		var guid = Editor.guid();
		localStorage.setItem('.draft-alive-check', guid);
		
		window.setTimeout(mxUtils.bind(this, function()
		{
			localStorage.removeItem('.draft-alive-check');

			this.filterDrafts(null, guid, mxUtils.bind(this, function(drafts)
			{
				if (drafts.length == 1)
				{
					this.loadDraft(drafts[0].data, mxUtils.bind(this, function()
					{
						this.removeDatabaseItem(drafts[0].key);
					}));
				}
				else if (drafts.length > 1)
				{
					var ts = new Date(drafts[0].modified);
					
					var dlg = new DraftDialog(this, (drafts.length > 1) ? mxResources.get('selectDraft') :
						mxResources.get('draftFound', [ts.toLocaleDateString() + ' ' + ts.toLocaleTimeString()]),
						(drafts.length > 1) ? null : drafts[0].data, mxUtils.bind(this, function(index)
					{
						this.hideDialog();
						index = (index != '' && drafts[index] != null) ? index : 0;
						
						this.loadDraft(drafts[index].data, mxUtils.bind(this, function()
						{
							this.removeDatabaseItem(drafts[index].key);
						}));
					}), mxUtils.bind(this, function(index, success)
					{
						index = (index != '') ? index : 0;
						this.removeDatabaseItem(drafts[index].key);
						
						if (success != null)
						{
							success();
						}
					}), null, null, null, (drafts.length > 1) ? drafts : null);
					this.showDialog(dlg.container, 640, 480, true, false, mxUtils.bind(this, function(cancel)
					{
						if (cancel)
						{
							if (urlParams['splash'] != '0')
							{
								this.loadFile();
							}
							else
							{
								try
								{
									this.createFile(this.defaultFilename, this.getFileData(),
										null, null, null, null, null, true);
								}
								catch (e)
								{
									this.handleError(e);
								}
							}
						}
					}));
					dlg.init();
				}
				else if (urlParams['splash'] != '0')
				{
					this.loadFile();
				}
				else
				{
					try
					{
						this.createFile(this.defaultFilename, this.getFileData(),
							null, null, null, null, null, true);
					}
					catch (e)
					{
						// ignore
					}
				}
			}));
		}), 0);
	}
	catch (e)
	{
		// ignore
	}
};

/**
 * Returns true if the Home screen (HomeDialog) can be shown: the full app
 * with Google Drive, never with ?home=0. HomeDialog.js is only bundled next
 * to DriveClient.js (app.min.js).
 */
App.prototype.isHomeAvailable = function()
{
	return this.drive != null && typeof HomeDialog === 'function' &&
		urlParams['home'] != '0' && !this.editor.chromeless &&
		urlParams['embed'] != '1' && urlParams['noFileMenu'] != '1' &&
		!mxClient.IS_CHROMEAPP && !EditorUi.isElectronApp;
};

/**
 * Returns true if the Home screen replaces the splash dialog: in Google Drive
 * mode.
 */
App.prototype.isHomeEnabled = function()
{
	return this.mode == App.MODE_GOOGLE && this.isHomeAvailable();
};

/**
 * Returns true if File > My Diagrams opens the Home screen: in Google Drive
 * mode, or whenever the user is signed in to Google Drive, whatever the
 * storage of the current diagram.
 */
App.prototype.isMyDiagramsEnabled = function()
{
	return this.isHomeAvailable() && (this.mode == App.MODE_GOOGLE ||
		this.drive.getUser() != null || this.drive.userId != null);
};

/**
 * Shows the Home screen. Opened with no file (at startup, or after the new
 * diagram dialog is cancelled), closing it creates a blank diagram, like the
 * splash dialog. Background clicks don't close it, since that would create
 * that diagram by accident.
 */
App.prototype.showHome = function()
{
	if (!this.isMyDiagramsEnabled())
	{
		return;
	}

	var startup = this.getCurrentFile() == null;
	var dlg = new HomeDialog(this, startup);
	var w = Math.max(280, Math.min(960, window.innerWidth - 96));
	var h = Math.max(320, Math.min(640, window.innerHeight - 96));

	this.showDialog(dlg.container, w, h, true, true, mxUtils.bind(this, function(cancel, isEsc)
	{
		dlg.destroy();

		if ((cancel || isEsc) && startup && this.getCurrentFile() == null)
		{
			var prev = Editor.useLocalStorage;
			this.createFile(this.defaultFilename, null, null, null, null, null, null,
				urlParams['local'] != '1');
			Editor.useLocalStorage = prev;
		}
	}), null, null, null, true);

	dlg.init();
};

/**
 * Returns true if a Google Drive file that returned 404 asks for access
 * (showDriveAccessDialog) instead of showing an error: where the Home screen
 * can show, and in the lightbox and viewer of published links, which only
 * open Drive files each user opened with draw.io before. Not in a frame,
 * where the Picker would need the origin of the top page.
 */
App.prototype.isDriveAccessAvailable = function()
{
	return this.isHomeAvailable() || (this.drive != null &&
		this.editor.isChromelessView() && urlParams['embed'] != '1' &&
		window.self === window.top);
};

/**
 * Asks for access to a Google Drive file that returned 404 (drive.file only
 * sees files the user created or picked with draw.io). Allow access opens
 * the Google Picker limited to that file, and picking it grants the file and
 * loads it. Returns false if the Picker isn't available.
 */
App.prototype.showDriveAccessDialog = function(id, changeUserFn, cancelFn)
{
	if (this.drive == null || !DriveClient.isFileId(id) ||
		typeof google === 'undefined' || google.picker == null)
	{
		return false;
	}

	var div = document.createElement('div');
	div.className = 'geHomeAccess';

	var hd = document.createElement('h3');
	mxUtils.write(hd, mxResources.get('allowAccessTitle', null, 'Allow access to this diagram'));
	div.appendChild(hd);

	var user = this.drive.getUser();
	var msg = document.createElement('div');
	msg.style.lineHeight = 'normal';
	mxUtils.write(msg, mxResources.get('allowAccessMessage', [(user != null && user.email != null) ?
		user.email : mxResources.get('googleDrive')], 'draw.io can only open the Google Drive files ' +
		'you choose. Select this diagram in the Google file picker to open it. If it isn\'t listed, ' +
		'it doesn\'t exist or isn\'t shared with {1}.'));
	div.appendChild(msg);

	// Secondary actions as links, so the buttons are only Cancel and Allow access
	var links = document.createElement('div');
	links.className = 'geHomeLinks';

	var openInDrive = mxUtils.button(mxResources.get('openInGoogleDrive', null,
		'Open in Google Drive'), mxUtils.bind(this, function()
	{
		// The file viewer shows Drive's own page for missing or inaccessible
		// files, where /open?id= shows a generic 404 page
		this.openLink('https://drive.google.com/file/d/' + encodeURIComponent(id) + '/view');
	}));
	openInDrive.className = 'geHomeLink';
	links.appendChild(openInDrive);

	if (changeUserFn != null)
	{
		var changeUser = mxUtils.button(mxResources.get('changeUser'), mxUtils.bind(this, function()
		{
			this.hideDialog();
			changeUserFn();
		}));
		changeUser.className = 'geHomeLink';
		links.appendChild(changeUser);
	}

	div.appendChild(links);

	var dlg = new CustomDialog(this, div, mxUtils.bind(this, function()
	{
		this.drive.pickDiagrams({fileIds: [id], title: mxResources.get('allowAccessTitle', null,
			'Allow access to this diagram')}, mxUtils.bind(this, function(docs)
		{
			if (docs.length > 0)
			{
				this.loadFile('G' + docs[0].id, true);
			}
			else if (cancelFn != null)
			{
				cancelFn();
			}
		}), cancelFn);
	}), cancelFn, mxResources.get('allowAccess', null, 'Allow access'));

	// Escape closes the dialog without the Cancel button
	this.showDialog(dlg.container, 420, null, true, false, function(cancel, isEsc)
	{
		if (isEsc && cancelFn != null)
		{
			cancelFn();
		}
	});

	return true;
};

/**
 * Shows the dialog for selecting the storage if no mode is set or force is
 * true, followed by the splash dialog or the home screen. Closing the splash
 * dialog creates a blank diagram.
 */
App.prototype.showSplash = function(force)
{
	//Splash dialog shouldn't be shownn when running without a file menu
	if (urlParams['noFileMenu'] == '1')
	{
		return;	
	}
	
	var serviceCount = this.getServiceCount(true);
	
	var showSecondDialog = mxUtils.bind(this, function()
	{
		if (this.isHomeEnabled())
		{
			this.showHome();

			return;
		}

		var dlg = new SplashDialog(this);
		
		this.showDialog(dlg.container, 340, (mxClient.IS_CHROMEAPP ||
			EditorUi.isElectronApp) ? 200 : 230, true, true,
			mxUtils.bind(this, function(cancel, isEsc)
			{
				// Creates a blank diagram if the dialog is closed
				if ((cancel || isEsc) && !mxClient.IS_CHROMEAPP)
				{
					var prev = Editor.useLocalStorage;
					this.createFile(this.defaultFilename + (EditorUi.isElectronApp? '.drawio' : ''),
						null, null, null, null, null, null, urlParams['local'] != '1');
					Editor.useLocalStorage = prev;
				}
			}), true);
	});
	
	if (this.editor.isChromelessView())
	{
		this.handleError({message: mxResources.get('noFileSelected')},
			mxResources.get('errorLoadingFile'), mxUtils.bind(this, function()
		{
			this.showSplash();
		}));
	}
	else if (!mxClient.IS_CHROMEAPP && !EditorUi.isElectronApp &&
		(this.mode == null || force))
	{
		var rowLimit = (serviceCount == 4) ? 2 : 3;
		
		var dlg = new StorageDialog(this, mxUtils.bind(this, function()
		{
			this.hideDialog();
			showSecondDialog();
		}), rowLimit);
		
		// With the Terms of Use notice, the height of the content
		this.showDialog(dlg.container, (rowLimit < 3) ? 200 : 300, (dlg.notice != null) ? null :
			((serviceCount > 3) ? 320 : 210), true, false);
	}
	else if (urlParams['create'] == null)
	{
		showSecondDialog();
	}
};

/**
 * Adds a globe icon with an optional label for the language menu to the
 * given element and returns the icon.
 */
App.prototype.addLanguageMenu = function(elt, addLabel, right)
{
	var img = null;
	var langMenu = this.menus.get('language');
	
	if (langMenu != null)
	{
		img = document.createElement('div');
		this.setElementTitle(img, 'language');

		img.className = 'geAdaptiveAsset';
		img.style.backgroundImage = 'url(' + Editor.globeImage + ')';
		img.style.backgroundPosition = 'right center';
		img.style.backgroundRepeat = 'no-repeat';
		img.style.backgroundSize = '19px 19px';
		img.style.width = '19px';
		img.style.height = '19px';
		mxUtils.setOpacity(img, 40);

		img.style.position = 'absolute';
		img.style.cursor = 'pointer';
		img.style.bottom = '20px';
		img.style.right = (right != null) ? right : '22px';
		
		if (addLabel)
		{
			img.style.direction = 'rtl';
			img.style.textAlign = 'right';
			img.style.right = (right != null) ? right : '24px';

			var label = document.createElement('span');
			label.style.display = 'inline-block';
			label.style.fontSize = '12px';
			label.style.margin = '2px 24px 0 0';
			label.style.userSelect = 'none';
			
			mxUtils.write(label, mxResources.get('language'));
			img.appendChild(label);

			label.className = 'geAdaptiveAsset';
		}
		
		mxEvent.addListener(img, 'click', mxUtils.bind(this, function(evt)
		{
			this.editor.graph.popupMenuHandler.hideMenu();
			var menu = new mxPopupMenu(this.menus.get('language').funct);
			menu.smartSeparators = true;
			menu.showDisabled = true;
			menu.autoExpand = true;
			
			// Disables autoexpand and destroys menu when hidden
			menu.hideMenu = mxUtils.bind(this, function()
			{
				mxPopupMenu.prototype.hideMenu.apply(menu, arguments);
				menu.destroy();
			});
	
			var offset = mxUtils.getOffset(img);
			menu.popup(offset.x, offset.y + img.offsetHeight, null, evt);
			
			// Allows hiding by clicking on document
			this.setCurrentMenu(menu);
		}));
	
		elt.appendChild(img);
	}
	
	return img;
};

/**
 * Loads the given file handle as a local file.
 */
App.prototype.loadFileSystemEntry = function(fileHandle, success, error)
{
	error = (error != null) ? error : mxUtils.bind(this, function(e)
	{
		this.handleError(e);
	});
	
	try
	{
		fileHandle.getFile().then(mxUtils.bind(this, function(file)
		{
			var reader = new FileReader();
					
			reader.onload = mxUtils.bind(this, function(e)
			{
				var doSuccess = mxUtils.bind(this, function(editable)
				{
					try
					{
						if (success != null)
						{
							var data = e.target.result;
							
							if (file.type == 'image/png')
							{
								data = this.extractGraphModelFromPng(data);
							}
							
							success(new LocalFile(this, data, file.name, null, fileHandle, file, editable));
						}
						else
						{
							this.openFileHandle(e.target.result, file.name, file, false, fileHandle, editable);
						}
					}
					catch(e)
					{
						error(e);
					}
				});
				
				if (fileHandle.queryPermission)
				{
					fileHandle.queryPermission({mode: 'readwrite'}).then(mxUtils.bind(this, function(permission)
					{
						doSuccess(permission !== 'denied');
					}));
				}
				else if (typeof fileHandle.createWritable === 'function')
				{
					fileHandle.createWritable().then(mxUtils.bind(this, function()
					{
						doSuccess(true);
					}), mxUtils.bind(this, function(e)
					{
						doSuccess(false);
					}));
				}
				else
				{
					// Handle without permission and writable APIs opens read-only
					doSuccess(false);
				}
			});
			
			reader.onerror = error;
			
			if ((file.type.substring(0, 5) === 'image' ||
				file.type === 'application/pdf') &&
				file.type.substring(0, 9) !== 'image/svg')
			{
				reader.readAsDataURL(file);
			}
			else
			{
				reader.readAsText(file);
			}
		}), error);
	}
	catch (e)
	{
		error(e);
	}
};

/**
 * Loads the given file handle as a local file.
 */
App.prototype.createFileSystemOptions = function(name)
{
	var ext = [];
	var temp = null;
		
	if (name != null)
	{
		var idx = name.lastIndexOf('.');
		
		if (idx > 0)
		{
			temp = name.substring(idx + 1);
		}
	}
	
	for (var i = 0; i < this.editor.diagramFileTypes.length; i++)
	{
		var obj = {description: mxResources.get(this.editor.diagramFileTypes[i].description) +
			((mxClient.IS_MAC) ? ' (.' + this.editor.diagramFileTypes[i].extension + ')' : ''),
			accept: {}};
		obj.accept[this.editor.diagramFileTypes[i].mimeType] = ['.' + this.editor.diagramFileTypes[i].extension];
		
		if (this.editor.diagramFileTypes[i].extension == temp)
		{
			ext.splice(0, 0, obj);
		}
		else
		{
			if (this.editor.diagramFileTypes[i].extension == temp)
			{
				ext.splice(0, 0, obj);
			}
			else
			{
				ext.push(obj);
			}
		}
	}
	
	return {types: ext, suggestedName: name};
};

/**
 * Shows the save file picker with the given options and passes the file
 * handle and its File object to success.
 */
App.prototype.showSaveFilePicker = function(success, error, opts)
{
	error = (error != null) ? error : mxUtils.bind(this, function(e)
	{
		if (e.name != 'AbortError')
		{
			this.handleError(e);
		}
	});
	
	opts = (opts != null) ? opts : this.createFileSystemOptions();
	
	window.showSaveFilePicker(opts).then(mxUtils.bind(this, function(fileHandle)
	{
		if (fileHandle != null)
		{
			fileHandle.getFile().then(mxUtils.bind(this, function(desc)
			{
				success(fileHandle, desc);
			}), error);
		}
	}), error);
};

/**
 * Shows the file picker for opening a file in the given or current storage
 * mode.
 */
App.prototype.pickFile = function(mode)
{
	try
	{
		mode = (mode != null) ? mode : this.mode;
		
		if (mode == App.MODE_GOOGLE)
		{
			if (this.drive != null && typeof(google) != 'undefined' && typeof(google.picker) != 'undefined')
			{
				this.drive.pickFile();
			}
			else
			{
				this.openLink('https://drive.google.com');
			}
		}
		else
		{
			var peer = this.getServiceForName(mode);
			
			if (peer != null)
			{
				peer.pickFile();
			}
			else if (mode == App.MODE_DEVICE && EditorUi.nativeFileSupport)
			{
				window.showOpenFilePicker().then(mxUtils.bind(this, function(fileHandles)
				{
					if (fileHandles != null && fileHandles.length > 0 &&
						this.spinner.spin(document.body, mxResources.get('loading')))
					{
						this.loadFileSystemEntry(fileHandles[0]);
					}
				}), mxUtils.bind(this, function(e)
				{
					if (e.name != 'AbortError')
					{
						this.handleError(e);
					}
				}));
			}
			else if (mode == App.MODE_DEVICE && Graph.fileSupport)
			{
				if (this.openFileInputElt == null) 
				{
					var input = document.createElement('input');
					input.setAttribute('type', 'file');
					
					mxEvent.addListener(input, 'change', mxUtils.bind(this, function()
					{
						if (input.files != null)
						{
							this.openFiles(input.files);
							
				    		// Resets input to force change event for
							// same file (type reset required for IE)
							input.type = '';
							input.type = 'file';
				    		input.value = '';
						}
					}));
					
					input.style.display = 'none';
					document.body.appendChild(input);
					this.openFileInputElt = input;
				}
				
				this.openFileInputElt.click();
			}
			else
			{
				this.hideDialog();
				window.openNew = this.getCurrentFile() != null && !this.isDiagramEmpty();
				window.baseUrl = this.getUrl();
				window.openKey = 'open';
				
				window.listBrowserFiles = mxUtils.bind(this, function(success, error) 
				{
					StorageFile.listFiles(this, 'F', success, error);
				});
				
				window.openBrowserFile = mxUtils.bind(this, function(title, success, error)
				{
					StorageFile.getFileContent(this, title, success, error);
				});
				
				window.deleteBrowserFile = mxUtils.bind(this, function(title, success, error)
				{
					StorageFile.deleteFile(this, title, success, error);
				});
				
				var prevValue = Editor.useLocalStorage;
				Editor.useLocalStorage = (mode == App.MODE_BROWSER);
				this.openFile();
				
				// Installs local handler for opened files in same window
				window.openFile.setConsumer(mxUtils.bind(this, function(xml, filename, temp)
				{
					var doOpenFile = mxUtils.bind(this, function()
					{
						// Replaces PNG with XML extension
						var dot = !Editor.useCanvasForExport && filename.substring(filename.length - 4) == '.png';

						if (dot)
						{
							filename = filename.substring(0, filename.length - 4) + '.drawio';
						}

						this.fileLoaded((mode == App.MODE_BROWSER) ?
							new StorageFile(this, xml, filename) :
							new LocalFile(this, xml, filename, temp));

						// Marks temp files as changed to trigger draft save
						var file = this.getCurrentFile();

						if (temp && file != null)
						{
							file.fileChanged();
						}
					});
					
					var currentFile = this.getCurrentFile();
					
					if (currentFile == null || !currentFile.isModified())
					{
						doOpenFile();
					}
					else
					{
						this.confirm(mxResources.get('allChangesLost'), null, doOpenFile,
							mxResources.get('cancel'), mxResources.get('discardChanges'));
					}
				}));
				
				// Extends dialog close to show splash screen
				var dlg = this.dialog;
				var dlgClose = dlg.close;
				
				this.dialog.close = mxUtils.bind(this, function(cancel)
				{
					Editor.useLocalStorage = prevValue;
					dlgClose.apply(dlg, arguments);
		
					if (this.getCurrentFile() == null)
					{
						this.showSplash();
					}
				});
			}
		}
	}
	catch (e)
	{
		this.handleError(e);
	}
};

/**
 * Shows the file picker for opening a library in the given or current
 * storage mode and adds the picked library to the sidebar.
 */
App.prototype.pickLibrary = function(mode)
{
	mode = (mode != null) ? mode : this.mode;

	var doLoadLibary = mxUtils.bind(this, function(file)
	{
		try
		{
			this.loadLibrary(file);
			this.showSidebar();

			try
			{
				this.sidebar.palettes[file.getHash()][0].
					scrollIntoView({behavior: 'smooth'});
			}
			catch (e)
			{
				// ignore
			}
		}
		catch (e)
		{
			this.handleError(e, mxResources.get('errorLoadingFile'));
		}
	});
	
	if (mode == App.MODE_GOOGLE || mode == App.MODE_ONEDRIVE ||
		mode == App.MODE_GITHUB || mode == App.MODE_GITLAB || mode == App.MODE_TRELLO)
	{
		var peer = (mode == App.MODE_GOOGLE) ? this.drive :
			((mode == App.MODE_ONEDRIVE) ? this.oneDrive :
			((mode == App.MODE_GITHUB) ? this.gitHub :
			((mode == App.MODE_GITLAB) ? this.gitLab :
			this.trello)));
		
		if (peer != null)
		{
			peer.pickLibrary(mxUtils.bind(this, function(id, optionalFile)
			{
				if (optionalFile != null)
				{
					doLoadLibary(optionalFile);
				}
				else
				{
					if (this.spinner.spin(document.body, mxResources.get('loading')))
					{
						peer.getLibrary(id, mxUtils.bind(this, function(file)
						{
							this.spinner.stop();
							doLoadLibary(file);
						}), mxUtils.bind(this, function(resp)
						{
							this.handleError(resp, (resp != null) ? mxResources.get('errorLoadingFile') : null);
						}));
					}
				}
			}));
		}
	}
	else if (mode == App.MODE_DEVICE && Graph.fileSupport)
	{
		if (this.libFileInputElt == null) 
		{
			var input = document.createElement('input');
			input.setAttribute('type', 'file');
			
			mxEvent.addListener(input, 'change', mxUtils.bind(this, function()
			{
				if (input.files != null)
				{
					for (var i = 0; i < input.files.length; i++)
					{
						(mxUtils.bind(this, function(file)
						{
							var reader = new FileReader();
						
							reader.onload = mxUtils.bind(this, function(e)
							{
								doLoadLibary(new LocalLibrary(this,
									e.target.result, file.name));
							});
	
							reader.readAsText(file);
						}))(input.files[i]);
					}
					
		    		// Resets input to force change event for same file (type reset required for IE)
					input.type = '';
					input.type = 'file';
		    		input.value = '';
				}
			}));
			
			input.style.display = 'none';
			document.body.appendChild(input);
			this.libFileInputElt = input;
		}
		
		this.libFileInputElt.click();
	}
	else
	{
		window.openNew = false;
		window.openKey = 'open';
		
		window.listBrowserFiles = mxUtils.bind(this, function(success, error) 
		{
			StorageFile.listFiles(this, 'L', success, error);
		});
		
		window.openBrowserFile = mxUtils.bind(this, function(title, success, error)
		{
			StorageFile.getFileContent(this, title, success, error);
		});
		
		window.deleteBrowserFile = mxUtils.bind(this, function(title, success, error)
		{
			StorageFile.deleteFile(this, title, success, error);
		});
		
		var prevValue = Editor.useLocalStorage;
		Editor.useLocalStorage = mode == App.MODE_BROWSER;
		
		// Closes dialog after open
		window.openFile = new OpenFile(mxUtils.bind(this, function(cancel)
		{
			this.hideDialog(cancel);
		}));
		
		window.openFile.setConsumer(mxUtils.bind(this, function(xml, filename)
		{
			doLoadLibary((mode == App.MODE_BROWSER) ?
				new StorageLibrary(this, xml, filename) :
				new LocalLibrary(this, xml, filename));
		}));

		// Removes openFile if dialog is closed
		this.showDialog(new OpenDialog(this).container, (Editor.useLocalStorage) ? 640 : 360,
			(Editor.useLocalStorage) ? 480 : 220, true, true, function()
		{
			Editor.useLocalStorage = prevValue;
			window.openFile = null;
		});
	}
};

/**
 * Saves the given images as a library with the given name. If file is null,
 * a new library is created in a folder picked for the given or current
 * storage mode, otherwise the given library is renamed if needed and saved.
 * Invokes fn after saving or on error.
 */
App.prototype.saveLibrary = function(name, images, file, mode, noSpin, noReload, fn)
{
	try
	{
		mode = (mode != null) ? mode : this.mode;
		noSpin = (noSpin != null) ? noSpin : false;
		noReload = (noReload != null) ? noReload : false;
		var xml = this.createLibraryDataFromImages(images);
		
		var error = mxUtils.bind(this, function(resp)
		{
			this.spinner.stop();
			
			if (fn != null)
			{
				fn();
			}
			
			this.handleError(resp, (resp != null) ? mxResources.get('errorSavingFile') : null);
		});
	
		// Handles special case for local libraries
		if (file == null && mode == App.MODE_DEVICE)
		{
			file = new LocalLibrary(this, xml, name);
		}
		
		if (file == null)
		{
			this.pickFolder(mode, mxUtils.bind(this, function(folderId)
			{
				if (mode == App.MODE_GOOGLE && this.drive != null && this.spinner.spin(document.body, mxResources.get('inserting')))
				{
					this.drive.insertFile(name, xml, folderId, mxUtils.bind(this, function(newFile)
					{
						this.spinner.stop();
						this.hideDialog(true);
						this.libraryLoaded(newFile, images);
					}), error, this.drive.libraryMimeType);
				}
				else if (mode == App.MODE_GITHUB && this.gitHub != null && this.spinner.spin(document.body, mxResources.get('inserting')))
				{
					this.gitHub.insertLibrary(name, xml, mxUtils.bind(this, function(newFile)
					{
						this.spinner.stop();
						this.hideDialog(true);
						this.libraryLoaded(newFile, images);
					}), error, folderId);
				}
				else if (mode == App.MODE_GITLAB && this.gitLab != null && this.spinner.spin(document.body, mxResources.get('inserting')))
				{
					this.gitLab.insertLibrary(name, xml, mxUtils.bind(this, function(newFile)
					{
						this.spinner.stop();
						this.hideDialog(true);
						this.libraryLoaded(newFile, images);
					}), error, folderId);
				}
				else if (mode == App.MODE_TRELLO && this.trello != null && this.spinner.spin(document.body, mxResources.get('inserting')))
				{
					this.trello.insertLibrary(name, xml, mxUtils.bind(this, function(newFile)
					{
						this.spinner.stop();
						this.hideDialog(true);
						this.libraryLoaded(newFile, images);
					}), error, folderId);
				}
				else if (mode == App.MODE_ONEDRIVE && this.oneDrive != null && this.spinner.spin(document.body, mxResources.get('inserting')))
				{
					this.oneDrive.insertLibrary(name, xml, mxUtils.bind(this, function(newFile)
					{
						this.spinner.stop();
						this.hideDialog(true);
						this.libraryLoaded(newFile, images);
					}), error, folderId);
				}
				else if (mode == App.MODE_BROWSER)
				{
					StorageFile.doInsertFile(new StorageLibrary(this, xml, name),
						mxUtils.bind(this, function(file)
						{
							this.hideDialog(true);
							this.libraryLoaded(file, images);
						}), error)
				}
				else
				{
					this.handleError({message: mxResources.get('serviceUnavailableOrBlocked')});
				}
			}));
		}
		else if (noSpin || this.spinner.spin(document.body, mxResources.get('saving')))
		{
			file.setData(xml);
			
			var doSave = mxUtils.bind(this, function()
			{
				file.save(true, mxUtils.bind(this, function(resp)
				{
					this.spinner.stop();
					this.hideDialog(true);
					
					if (!noReload)
					{
						this.libraryLoaded(file, images);
					}
					
					if (fn != null)
					{
						fn();
					}
				}), error);
			});
			
			if (name != file.getTitle())
			{
				var oldHash = file.getHash();
				
				file.rename(name, mxUtils.bind(this, function(resp)
				{
					// Change hash in stored settings
					if (file.constructor != LocalLibrary && oldHash != file.getHash())
					{
						mxSettings.removeCustomLibrary(oldHash);
						mxSettings.addCustomLibrary(file.getHash());
					}
	
					// Workaround for library files changing hash so
					// the old library cannot be removed from the
					// sidebar using the updated file in libraryLoaded
					this.removeLibrarySidebar(oldHash);
	
					doSave();
				}), error)
			}
			else
			{
				doSave();
			}
		}
	}
	catch (e)
	{
		this.handleError(e);
	}
};

/**
 * Saves the current file under its title. Shows a dialog for the filename
 * and location instead if forceDialog is true, if the file has no title or
 * valid file handle, or if no storage mode is set. Invokes success after
 * saving.
 */
App.prototype.saveFile = function(forceDialog, success)
{
	var file = this.getCurrentFile();
	var prev = this.mode;
	
	if (file != null)
	{
		// FIXME: Invoke for local files
		var done = mxUtils.bind(this, function()
		{
			if (EditorUi.enableDrafts)
			{
				file.removeDraft();
			}
			
			if (this.getCurrentFile() != file && !file.isModified())
			{
				// Workaround for possible status update while save as dialog is showing
				// is to show no saved status for device files
				if (file.getMode() != App.MODE_DEVICE)
				{
					this.updateStatus(mxUtils.bind(this, function()
					{
						this.editor.setStatus(mxUtils.htmlEntities(
							mxResources.get('allChangesSaved')));
					}));
				}
				else
				{
					this.clearStatus();
				}
			}
			
			if (success != null)
			{
				success();
			}
		});
		
		if (!forceDialog && file.getTitle() != null && file.invalidFileHandle == null && this.mode != null)
		{
			this.save(file.getTitle(), done);
		}
		else if (file != null && file.constructor == LocalFile && file.fileHandle != null &&
			typeof window.showSaveFilePicker === 'function')
		{
			this.showSaveFilePicker(mxUtils.bind(this, function(fileHandle, desc)
			{
				file.invalidFileHandle = null;
				file.fileHandle = fileHandle;
				file.title = desc.name;
				file.desc = desc;
				file.editable = null;
				this.save(desc.name, done);
			}), null, this.createFileSystemOptions(file.getTitle()));
		}
		else
		{
			var filename = (file.getTitle() != null) ? file.getTitle() : this.defaultFilename;

			var saveFunction = mxUtils.bind(this, function(name, mode, input, folderId)
			{
				if (name != null && name.length > 0)
				{
					// Handles special case where PDF export is detected
					if (/(\.pdf)$/i.test(name))
					{
						this.confirm(mxResources.get('didYouMeanToExportToPdf'), mxUtils.bind(this, function()
						{
							this.hideDialog();
							this.actions.get('exportPdf').funct();
						}), mxUtils.bind(this, function()
						{
							input.value = name.split('.').slice(0, -1).join('.');
							input.focus();
							
							if (mxClient.IS_GC || mxClient.IS_FF || document.documentMode >= 5)
							{
								input.select();
							}
							else
							{
								document.execCommand('selectAll', false, null);
							}
						}), mxResources.get('yes'), mxResources.get('no'));
					}
					else
					{
						this.hideDialog();
						
						if (prev == null && mode == App.MODE_DEVICE)
						{
							if (file != null && EditorUi.nativeFileSupport)
							{
								this.showSaveFilePicker(mxUtils.bind(this, function(fileHandle, desc)
								{
									file.fileHandle = fileHandle;
									file.mode = App.MODE_DEVICE;
									file.title = desc.name;
									file.desc = desc;

									this.setMode(App.MODE_DEVICE);
									this.save(desc.name, done);
								}), mxUtils.bind(this, function(e)
								{
									if (e.name != 'AbortError')
									{
										this.handleError(e);
									}
								}), this.createFileSystemOptions(name));
							}
							else
							{
								this.setMode(App.MODE_DEVICE);
								this.save(name, done);
							}
						}
						else if (mode == 'download')
						{
							var tmp = new LocalFile(this, null, name);
							tmp.save();
						}
						else if (mode == '_blank')
						{
							window.openFile = new OpenFile(function()
							{
								window.openFile = null;
							});
							
							// Do not use a filename to use undefined mode
							window.openFile.setData(this.getFileData(true));
							this.openLink(this.getUrl(window.location.pathname), null, true);
						}
						else if (forceDialog || prev != mode) // create a new file also with saveAs even if mode is the same as current
						{
							var createFile = mxUtils.bind(this, function(folderId)
							{
								try
								{
									var graph = this.editor.graph;
									var selection = graph.getSelectionCells();
									var viewState = graph.getViewState();
									var page = this.currentPage;

									// Opens new window if not temporary file
									var currentFile = this.getCurrentFile();
									var replace = this.mode == null || (currentFile == null ||
											currentFile.mode == null);

									this.createFile(name, this.getFileData(/(\.xml)$/i.test(name) ||
										name.indexOf('.') < 0 || /(\.drawio)$/i.test(name),
										/(\.svg)$/i.test(name), /(\.html)$/i.test(name)), null,
										mode, done, replace, folderId, null, null,
										mxUtils.bind(this, function()
										{
											this.restoreViewState(page, viewState, selection);
										}));
								}
								catch (e)
								{
									this.handleError(e);
								}
							});

							if (folderId != null)
							{
								createFile(folderId);
							}
							else
							{
								this.pickFolder(mode, createFile);
							}
						}
						else if (mode != null)
						{
							this.save(name, done);
						}
					}
				}
			});
			
			var allowTab = !mxClient.IS_IOS || !navigator.standalone;

			var dlg = new SaveDialog(this, filename, mxUtils.bind(this, function(input, mode, folderId)
			{
				try
				{
					saveFunction(input.value, mode, input, folderId);
					this.hideDialog();
				}
				catch (e)
				{
					this.handleError(e);
				}
			}), (allowTab) ? null : ['_blank']);

			this.showDialog(dlg.container, 420, 162, true, false, mxUtils.bind(this, function()
			{
				this.hideDialog();
			}));
			dlg.init();
		}
	}
};

/**
 * Loads the template from the given URL, via the proxy if CORS is not
 * enabled, and passes its diagram data to onload. Visio, Gliffy, Lucidchart
 * and PNG files are converted.
 */
App.prototype.loadTemplate = function(url, onload, onerror, templateFilename, asLibrary)
{
	var base64 = false;
	var realUrl = url;
	var filterFn = (templateFilename != null) ? templateFilename : url;
	var binary = /\.png$/i.test(filterFn) || /\.pdf$/i.test(filterFn);
	var isVisioFilename = EditorUi.isVisioFilename(filterFn);
	
	if (!this.editor.isCorsEnabledForUrl(realUrl))
	{
		base64 = binary || isVisioFilename;
		var nocache = 't=' + new Date().getTime();
		realUrl = PROXY_URL + '?url=' + encodeURIComponent(url) +
			'&' + nocache + ((base64) ? '&base64=1' : '');
	}

	this.editor.loadUrl(realUrl, mxUtils.bind(this, function(responseData)
	{
		try
		{
			var data = (!base64) ? responseData : ((window.atob) ?
				atob(responseData) : Base64.decode(responseData));
			
			if (isVisioFilename || this.isVisioData(data))
			{
				// Adds filename to control converter code
				if (!isVisioFilename)
				{
					if (asLibrary)
					{
						filterFn = this.isRemoteVisioData(data) ? 'raw.vss' : 'raw.vssx';
					}
					else
					{
						filterFn = this.isRemoteVisioData(data) ? 'raw.vsd' : 'raw.vsdx';
					}
				}
				
				this.importVisio(this.base64ToBlob(responseData.substring(responseData.indexOf(',') + 1)), function(xml)
				{
					onload(xml);
				}, onerror, filterFn);
			}
			else if (this.isGliffyData(data, filterFn))
			{
				this.importGliffy(data, mxUtils.bind(this, function(xml)
				{
					if (xml.substring(0, 13) == '<mxGraphModel')
					{
						onload(xml);
					}
					else
					{
						onerror();
					}
				}), onerror, url);
			}
			else if (this.isLucidChartData(data))
			{
				this.convertLucidChart(data, mxUtils.bind(this, function(xml)
				{
					onload(xml);
				}), mxUtils.bind(this, function(e)
				{
					onerror(e);
				}));
			}
			else
			{
				if (/(\.png)($|\?)/i.test(filterFn) || Editor.isPngData(data))
				{
					data = Editor.extractGraphModelFromPng(responseData);
				}
				
				onload(data);
			}
		}
		catch (e)
		{
			onerror(e);
		}
	}), onerror, /(\.png)($|\?)/i.test(filterFn) || isVisioFilename, null, null, base64);
};

/**
 * 
 */
App.prototype.getModeForChar = function(char)
{
	if (char != null)
	{
		for (var mode in App.storages)
		{
			if (App.storages[mode].char == char)
			{
				return mode;
			}
		}
	}

	return null;
};

/**
 * Returns true if the storage for the given mode is available and enabled.
 */
App.prototype.isModeEnabled = function(mode)
{
	if (mode == App.MODE_GOOGLE)
	{
		return typeof window.DriveClient === 'function' &&
			((urlParams['embed'] != '1' && urlParams['gapi'] != '0') ||
			(urlParams['embed'] == '1' && urlParams['gapi'] == '1')) &&
			mxClient.IS_SVG && isLocalStorage && (document.documentMode == null ||
				document.documentMode >= 10);
	}
	else if (mode == App.MODE_GITHUB)
	{
		return this.gitHub != null;
	}
	else if (mode == App.MODE_GITLAB)
	{
		return this.gitLab != null;
	}
	else if (mode == App.MODE_ONEDRIVE)
	{
		return typeof window.OneDriveClient === 'function' &&
			(window.location.hostname == 'www.draw.io' ||
			window.location.hostname == 'test.draw.io' ||
			window.location.hostname == 'drive.draw.io' ||
			window.location.hostname == 'app.diagrams.net') &&
			(((urlParams['embed'] != '1' && urlParams['od'] != '0') ||
				(urlParams['embed'] == '1' && urlParams['od'] == '1')) &&
			!mxClient.IS_IOS && (navigator.userAgent.indexOf('MSIE') < 0 ||
				document.documentMode >= 10));
	}
	else if (mode == App.MODE_TRELLO)
	{
		return typeof window.TrelloClient === 'function' && urlParams['tr'] == '1' &&
			mxClient.IS_SVG && (document.documentMode == null ||
				document.documentMode > 9);
	}
	else if (mode == App.MODE_M365)
	{
		return this.m365 != null;
	}
	else
	{
		return false;
	}
};

/**
 * Returns true if the peer for the given mode has been loaded.
 */
App.prototype.isModeReady = function(mode)
{
	return this.getServiceForName(mode) != null;
};

/**
 * Returns the given file data with the compressed diagrams replaced by their
 * XML. Returns the data unchanged if it cannot be parsed.
 */
App.prototype.uncompressPages = function(data)
{
	if (data != null)
	{
		try
		{
			var doc = mxUtils.parseXml(data);

			if (doc.documentElement.nodeName == 'mxfile')
			{
				var diagrams = doc.documentElement.getElementsByTagName('diagram');

				for (var i = 0; i < diagrams.length; i++)
				{
					var node = Editor.parseDiagramNode(diagrams[i], true);

					// Replaces text content with XML
					if (node != null)
					{
						mxUtils.setTextContent(diagrams[i], '');
						diagrams[i].appendChild(node);
					}
				}

				data = mxUtils.getPrettyXml(doc.documentElement);
			}
		}
		catch (e)
		{
			// fallback to input data in case of error
		}
	}

	return data;
};

/**
 * Creates a new file with the given title and data, or an empty diagram, in
 * the given or current storage mode and passes it to fileCreated. Temporary
 * files are created as local files without a storage mode.
 */
App.prototype.createFile = function(title, data, libs, mode, done, replace, folderId, tempFile, clibs, success)
{
	EditorUi.debug('App.createFile', [this],
		'title', [title], 'data', [data],
		'libs', [libs], 'mode', [mode]);
	mode = (tempFile) ? null : ((mode != null) ? mode : this.mode);

	if (title != null && this.spinner.spin(document.body, mxResources.get('inserting')))
	{
		data = (data != null) ? data : this.emptyDiagramXml;

		// Decompresses existing content
		if (data != null && !Editor.defaultCompressed)
		{
			data = this.uncompressPages(data);
		}

		var complete = mxUtils.bind(this, function()
		{
			this.spinner.stop();
		});
		
		var error = mxUtils.bind(this, function(resp)
		{
			complete();
			
			if (resp == null && this.getCurrentFile() == null && this.dialog == null)
			{
				this.showSplash();
			}
			else if (resp != null)
			{
				this.handleError(resp);
			}
		});
		
		try
		{
			var fileCreated = mxUtils.bind(this, function(file)
			{
				complete();
				this.fileCreated(file, libs, replace, done, clibs, success);
			});

			if (mode == App.MODE_GOOGLE && this.drive != null)
			{
				if (folderId == null && this.stateArg != null && this.stateArg.folderId != null)
				{
					folderId = this.stateArg.folderId;
				}
	
				this.drive.insertFile(title, data, folderId, fileCreated, error);
			}
			else if (mode == App.MODE_GITHUB && this.gitHub != null)
			{
				this.gitHub.insertFile(title, data, fileCreated, error, false, folderId);
			}
			else if (mode == App.MODE_GITLAB && this.gitLab != null)
			{
				this.gitLab.insertFile(title, data, fileCreated, error, false, folderId);
			}
			else if (mode == App.MODE_TRELLO && this.trello != null)
			{
				this.trello.insertFile(title, data, fileCreated, error, false, folderId);
			}
			else if (mode == App.MODE_ONEDRIVE && this.oneDrive != null)
			{
				this.oneDrive.insertFile(title, data, fileCreated, error, false, folderId);
			}
			else if (mode == App.MODE_M365 && this.m365 != null)
			{
				this.m365.insertFile(title, data, fileCreated, error, false, folderId);
			}
			else if (mode == App.MODE_BROWSER)
			{
				StorageFile.insertFile(this, title, data, fileCreated, error);
			}
			else if (!tempFile && mode == App.MODE_DEVICE && EditorUi.nativeFileSupport)
			{
				complete();
				
				this.showSaveFilePicker(mxUtils.bind(this, function(fileHandle, desc)
				{
					// File is written in fileCreated to use the format of the file name
					this.fileCreated(new LocalFile(this, data, desc.name, null, fileHandle, desc),
						libs, replace, done, clibs, success);
				}), mxUtils.bind(this, function(e)
				{
					if (e.name != 'AbortError')
					{
						error(e);
					}
				}), this.createFileSystemOptions(title));
			}
			else
			{
				complete();
				this.fileCreated(new LocalFile(this, data, title, mode == null),
					libs, replace, done, clibs, success);
			}
		}
		catch (e)
		{
			complete();
			this.handleError(e);
		}
	}
};

/**
 * Saves the data of the given new file, which needs the ID of the file for
 * the redirect, and opens the file in a new window if replace is false or in
 * this window otherwise. The given libraries are loaded after opening.
 */
App.prototype.fileCreated = function(file, libs, replace, done, clibs, success)
{
	EditorUi.debug('App.fileCreated', [this], 'file', [file],
		'libs', [libs], 'replace', [replace]);
	var url = window.location.pathname;
	
	if (libs != null && libs.length > 0)
	{
		url += '?libs=' + libs;
	}

	if (clibs != null && clibs.length > 0)
	{
		url += '?clibs=' + clibs;
	}
	
	url = this.getUrl(url);

	// Always opens a new tab for local files to avoid losing changes
	if (file.getMode() != App.MODE_DEVICE)
	{
		url += '#' + file.getHash();
	}

	// Makes sure to produce consistent output with finalized files via createFileData this needs
	// to save the file again since it needs the newly created file ID for redirecting in HTML
	if (this.spinner.spin(document.body, mxResources.get('inserting')))
	{
		var data = file.getData();
		var dataNode = (data.length > 0) ? this.editor.extractGraphModel(
			mxUtils.parseXml(data).documentElement, true) : null;
		var redirect = window.location.protocol + '//' + window.location.hostname + url;
		var node = dataNode;
		var graph = null;
		
		// Handles special case where SVG files need a rendered graph to be saved
		if (dataNode != null && /\.svg$/i.test(file.getTitle()))
		{
			graph = this.createTemporaryGraph(this.editor.graph.getStylesheet());
			document.body.appendChild(graph.container);
			node = this.decodeNodeIntoGraph(node, graph);
		}
		
		file.setData(this.createFileData(dataNode, graph, file, redirect));

		if (graph != null)
		{
			graph.container.parentNode.removeChild(graph.container);
		}

		var complete = mxUtils.bind(this, function()
		{
			this.spinner.stop();
		});
		
		var fn = mxUtils.bind(this, function()
		{
			complete();
			
			var currentFile = this.getCurrentFile();
			
			if (replace == null && currentFile != null)
			{
				replace = !currentFile.isModified() &&
					(currentFile.getMode() == null ||
					EditorUi.isElectronApp);
			}
			
			var fn3 = mxUtils.bind(this, function()
			{
				window.openFile = null;
				this.fileLoaded(file, null, success);
				
				if (replace)
				{
					this.updateStatus(mxUtils.bind(this, function()
					{
						file.addAllSavedStatus();
					}));
				}
				
				if (libs != null)
				{
					this.sidebar.showEntries(libs);
				}
				
				if (clibs != null)
				{
					var temp = [];
					var tokens = clibs.split(';');
					
					for (var i = 0; i < tokens.length; i++)
					{
						temp.push(decodeURIComponent(tokens[i]));
					}
					
					this.loadLibraries(temp);
				}

				if (done != null)
				{
					done();
				}
			});

			var fn2 = mxUtils.bind(this, function()
			{
				if (replace || currentFile == null || !currentFile.isModified())
				{
					fn3();
				}
				else
				{
					this.confirm(mxResources.get('allChangesLost'), null, fn3,
						mxResources.get('cancel'), mxResources.get('discardChanges'));
				}
			});

			// Opens the file in a new window
			if (replace != null && !replace)
			{
				// Opens local file in a new window
				if (file.constructor == LocalFile)
				{
					window.openFile = new OpenFile(function()
					{
						window.openFile = null;
					});
						
					window.openFile.setData(file.getData(), file.getTitle(), file.getMode() == null);
				}

				window.geOpenWindow(url, null, fn2);
			}
			else
			{
				fn2();
			}
		});

		// Updates data in memory for local files without a file handle
		if (file.constructor == LocalFile && file.fileHandle == null)
		{
			fn();
		}
		else
		{
			var saveError = mxUtils.bind(this, function(resp)
			{
				complete();

				if (resp == null || resp.name != 'AbortError')
				{
					this.handleError(resp);
				}
			});

			// Writes the data created above for new local files with a file handle
			if (file.constructor == LocalFile)
			{
				file.saveFile(file.getTitle(), false, fn, saveError, true);
			}
			else
			{
				file.saveFile(file.getTitle(), false, mxUtils.bind(this, function()
				{
					fn();
				}), saveError);
			}
		}
	}
};

/**
 * Loads the file with the given ID, or the given file if it is already
 * loaded. If a file is open and sameWindow is false, a dialog offers to open
 * the file in a new window. Asks before discarding changes unless force is
 * true.
 */
App.prototype.loadFile = function(id, sameWindow, file, success, force)
{
	if (urlParams['openInSameWin'] == '1' || navigator.standalone)
	{
		sameWindow = true;
	}
	
	this.hideDialog();
	
	var fn2 = mxUtils.bind(this, function()
	{
		if (id == null || id.length == 0)
		{
			this.clearStatus();
			this.fileLoaded(null);
		}
		else if (this.spinner.spin(document.body, mxResources.get('loading')))
		{
			// Handles files from localStorage
			if (id.charAt(0) == 'L')
			{
				this.spinner.stop();

				if (!isLocalStorage)
				{
					this.handleError({message: mxResources.get('serviceUnavailableOrBlocked')},
						mxResources.get('errorLoadingFile'), mxUtils.bind(this, function()
					{
						var tempFile = this.getCurrentFile();
						window.location.hash = (tempFile != null) ? tempFile.getHash() : '';
					}));
				}
				else
				{
					var error = mxUtils.bind(this, function (e)
					{
						this.handleError(e, mxResources.get('errorLoadingFile'),
							mxUtils.bind(this, function()
						{
							var tempFile = this.getCurrentFile();
							window.location.hash = (tempFile != null) ? tempFile.getHash() : '';
						}));
					});
					
					id = decodeURIComponent(id.substring(1));
					
					StorageFile.getFileContent(this, id, mxUtils.bind(this, function(data)
					{
						if (data != null)
						{
							this.fileLoaded(new StorageFile(this, data, id));

							if (success != null)
							{
								success();
							}
						}
						else
						{
							error({message: mxResources.get('fileNotFound')});
						}
					}), error);
				}
			}
			else if (file != null)
			{
				// File already loaded
				this.spinner.stop();
				this.fileLoaded(file);

				if (success != null)
				{
					success();
				}
			}
			else if (id.charAt(0) == 'S')
			{
				this.spinner.stop();
				
				this.alert('[Deprecation] #S is no longer supported, go to https://app.diagrams.net/?desc=' + id.substring(1).substring(0, 10), mxUtils.bind(this, function()
				{
					window.location.href = 'https://app.diagrams.net/?desc=' + id.substring(1);
				}));
			}
			else if (id.substring(0, 7) == 'create=')
			{
				try
				{
					var obj = JSON.parse(decodeURIComponent(id.substring(7)));

					if (obj.type == 'message')
					{
						var sourceWindow = window.opener || window.parent;;

						var createMessageHandler = mxUtils.bind(this, function(evt)
						{
							EditorUi.debug('EditorUi.createMessageHandler',
								[this], 'evt', [evt]);

							if (evt.source != sourceWindow)
							{
								return;
							}

							try
							{
								if (evt.data.action == 'create' && evt.data.data != null)
								{
									mxEvent.removeListener(window, 'message', createMessageHandler);
									this.executeCreateObject(evt.data.data);
								}
							}
							catch (e)
							{
								data = null;
							}
						});

						// Sends ready message to source window to trigger sending of create message with data
						mxEvent.addListener(window, 'message', createMessageHandler);
						sourceWindow.postMessage(JSON.stringify({event: 'ready'}), '*');
					}
					else
					{
						this.executeCreateObject(obj);
					}
				}
				catch (e)
				{
					this.handleError(e, mxResources.get('errorLoadingFile'));
				}
			}
			else if (id.charAt(0) == 'R')
			{
				// Raw file encoded into URL
				this.spinner.stop();

				try
				{
					var data = decodeURIComponent(id.substring(1));
					
					if (data.charAt(0) != '<')
					{
						data = Graph.decompress(data);
					}
					
					var tempFile = new LocalFile(this, data, (urlParams['title'] != null) ?
						decodeURIComponent(urlParams['title']) : this.defaultFilename, true);
					tempFile.getHash = function()
					{
						return id;
					};
					this.fileLoaded(tempFile);

					if (success != null)
					{
						success();
					}
				}
				catch (e)
				{
					// Truncated or altered links fail in decodeURIComponent or in
					// atob inside Graph.decompress; falls back to the current file
					this.handleError(e, mxResources.get('errorLoadingFile'),
						mxUtils.bind(this, function()
					{
						var tempFile = this.getCurrentFile();
						window.location.hash = (tempFile != null) ? tempFile.getHash() : '';
					}));
				}
			}
			else if (id.charAt(0) == 'E') // Embed file
			{
				//Currently we only reload current file. Id is not used!
				var currentFile = this.getCurrentFile();
				
				if (currentFile == null)
				{
					this.handleError({message: mxResources.get('serviceUnavailableOrBlocked')}, mxResources.get('errorLoadingFile'));
				}
				else
				{
					this.remoteInvoke('getDraftFileContent', null, null, mxUtils.bind(this, function(data, desc)
					{
						this.spinner.stop();
						this.fileLoaded(new EmbedFile(this, data, desc));
						
						if (success != null)
						{
							success();
						}
					}), mxUtils.bind(this, function()
					{
						this.handleError({message: mxResources.get('serviceUnavailableOrBlocked')}, mxResources.get('errorLoadingFile'));
					}));
				}
			}
			else if (id.charAt(0) == 'U')
			{
				var url = decodeURIComponent(id.substring(1));
				
				var doFallback = mxUtils.bind(this, function()
				{
					// Fallback for non-public Google Drive files
					if (url.substring(0, 31) == 'https://drive.google.com/uc?id=' &&
						(this.drive != null || typeof window.DriveClient === 'function'))
					{
						this.hideDialog();
						
						var fallback = mxUtils.bind(this, function()
						{
							this.spinner.stop();
							
							if (this.drive != null)
							{
								var tempId = url.substring(31, url.lastIndexOf('&ex'));
								
								this.loadFile('G' + tempId, sameWindow, null, mxUtils.bind(this, function()
								{
									var currentFile = this.getCurrentFile();
									
									if (currentFile != null && this.editor.chromeless && !this.editor.editable)
									{
										currentFile.getHash = function()
										{
											return 'G' + tempId;
										};
										
										window.location.hash = '#' + currentFile.getHash();
									}
									
									if (success != null)
									{
										success();
									}
								}));
								
								return true;
							}
							else
							{
								return false;
							}
						});
						
						if (!fallback() && this.spinner.spin(document.body, mxResources.get('loading')))
						{
							this.addListener('clientLoaded', fallback);
						}
						
						return true;
					}
					else
					{
						return false;
					}
				});
				
				this.loadTemplate(url, mxUtils.bind(this, function(text)
				{
					this.spinner.stop();
					
					if (text != null && text.length > 0)
					{
						var filename = this.defaultFilename;
						
						// Tries to find name from URL with valid extensions
						if (urlParams['title'] == null && urlParams['notitle'] != '1')
						{
							var tmp = url;
							var dot = url.lastIndexOf('.');
							var slash = tmp.lastIndexOf('/');
							
							if (dot > slash && slash > 0)
							{
								tmp = tmp.substring(slash + 1, dot);
								var ext = url.substring(dot);
								
								if (!Editor.useCanvasForExport && ext == '.png')
								{
									ext = '.drawio';
								}

								if (ext === '.svg' || ext === '.xml' ||
									ext === '.html' || ext === '.png'  ||
									ext === '.drawio')
								{
									filename = tmp + ext;
								}
							}
						}
						
						var tempFile = new LocalFile(this, text, (urlParams['title'] != null) ?
							decodeURIComponent(urlParams['title']) : filename, true);
						tempFile.getHash = function()
						{
							return id;
						};
						
						if (this.fileLoaded(tempFile, true))
						{
							if (success != null)
							{
								success();
							}
						}
						else if (!doFallback())
						{
							this.handleError({message: mxResources.get('fileNotFound')},
								mxResources.get('errorLoadingFile'));
						}
					}
					else if (!doFallback())
					{
						this.handleError({message: mxResources.get('fileNotFound')},
							mxResources.get('errorLoadingFile'));
					}
				}), mxUtils.bind(this, function()
				{
					if (!doFallback())
					{
						this.spinner.stop();
						this.handleError({message: mxResources.get('fileNotFound')},
							mxResources.get('errorLoadingFile'));
					}
				}), (urlParams['template-filename'] != null) ?
					decodeURIComponent(urlParams['template-filename']) : null);
			}
			else
			{
				var mode = this.getModeForChar(id.charAt(0));

				var doLoadFile = mxUtils.bind(this, function()
				{
					var peer = this.getServiceForName(mode);

					if (peer == null)
					{
						this.handleError({message: mxResources.get('serviceUnavailableOrBlocked')},
							mxResources.get('errorLoadingFile'), mxUtils.bind(this, function()
						{
							var currentFile = this.getCurrentFile();
							window.location.hash = (currentFile != null) ? currentFile.getHash() : '';
						}));
					}
					else
					{
						var peerChar = id.charAt(0);
						// Malformed hashes are passed on as-is so that the service reports the error
						id = mxUtils.safeDecodeURIComponent(id.substring(1));

						peer.getFile(id, mxUtils.bind(this, function(file)
						{
							this.spinner.stop();
							this.fileLoaded(file);
							var currentFile = this.getCurrentFile();

							// Counts the user as a viewer of the month. Must never
							// stop a diagram from opening.
							if (mode == App.MODE_GOOGLE && currentFile != null && currentFile == file)
							{
								try
								{
									this.reportDriveUse('view');
								}
								catch (e)
								{
									// ignore
								}
							}
							
							if (currentFile == null)
							{
								window.location.hash = '';
								this.showSplash();
							}
							else if (this.editor.chromeless && !this.editor.editable)
							{
								// Keeps ID even for converted files in chromeless mode for refresh to work
								currentFile.getHash = function()
								{
									return peerChar + id;
								};

								var hash = '#' + currentFile.getHash();

								try
								{
									var obj = this.getHashObject();

									if (obj != null && !mxUtils.isEmptyObject(obj))
									{
										hash = hash + '#' + encodeURIComponent(JSON.stringify(obj));
									}
								}
								catch (e)
								{
									// ignore
								}

								window.location.replace(hash);
							}
							else if (file == currentFile && file.getMode() == null)
							{
								// Shows a warning if a copy was opened which happens
								// eg. for .png files in IE as they cannot be written
								this.updateStatus(mxUtils.bind(this, function()
								{
									var status = mxResources.get('copyCreated');
									this.editor.setStatus('<div title="'+ status +
										'" class="geStatusAlert">' + status + '</div>');
								}));								
							}
							
							if (success != null)
							{
								success();
							}
						}), mxUtils.bind(this, function(resp)
						{
							// Makes sure the file does not save the invalid UI model and overwrites anything important
							if (window.console != null && resp != null)
							{
								console.log('error in loadFile:', id, resp);
							}

							var fn = mxUtils.bind(this, function()
							{
								var currentFile = this.getCurrentFile();
								
								if (currentFile == null)
								{
									window.location.hash = '';
									this.showSplash();
								}
								else
								{
									window.location.hash = '#' + currentFile.getHash();
								}
							});

							if (resp == null || resp.name != 'AbortError')
							{
								this.handleError(resp, (resp != null) ? mxResources.get('errorLoadingFile') : null,
									fn, null, null, '#' + peerChar + id);
							}
							else
							{
								fn();
							}
						}));
					}
				});

				// Dropbox support has ended and there is no mode for its hashes
				// any more, so explain where the files are instead of showing a
				// generic service error (old #D links stay around for years).
				if (id.charAt(0) == 'D')
				{
					this.spinner.stop();

					this.alert('Dropbox support has ended. Your diagrams are unchanged in ' +
						'the Apps/drawio folder on dropbox.com.', mxUtils.bind(this, function()
					{
						var currentFile = this.getCurrentFile();
						window.location.hash = (currentFile != null) ? currentFile.getHash() : '';
					}));
				}
				else
				{
					doLoadFile();
				}
			}
		}
	});
	
	var currentFile = this.getCurrentFile();
	
	var fn = mxUtils.bind(this, function()
	{
		if (force || currentFile == null || !currentFile.isModified())
		{
			fn2();
		}
		else
		{
			this.confirm(mxResources.get('allChangesLost'), mxUtils.bind(this, function()
			{
				if (currentFile != null)
				{
					window.location.hash = currentFile.getHash();
				}
			}), fn2, mxResources.get('cancel'), mxResources.get('discardChanges'));
		}
	});

	if (id == null || id.length == 0 || (sameWindow == null &&
		currentFile != null && !currentFile.isModified() &&
		this.isBlankFile()))
	{
		fn();
	}
	else if (currentFile != null && !sameWindow)
	{
		this.showDialog(new PopupDialog(this, this.getUrl() + '#' + id,
			null, fn).container, 340, 140, true, true);
	}
	else
	{
		fn();
	}
};

/**
 * Returns the tooltip for the given library, which contains its title, hash
 * and storage name.
 */
App.prototype.getLibraryStorageHint = function(file)
{
	var tip = file.getTitle();
	
	if (file.constructor != LocalLibrary)
	{
		tip += '\n' + file.getHash();
	}
	
	if (file.constructor == DriveLibrary)
	{
		tip += ' (' + mxResources.get('googleDrive') + ')';
	}
	else if (file.constructor == GitHubLibrary)
	{
		tip += ' (' + mxResources.get('github') + ')';
	}
	else if (file.constructor == TrelloLibrary)
	{
		tip += ' (' + mxResources.get('trello') + ')';
	}
	else if (file.constructor == OneDriveLibrary)
	{
		tip += ' (' + mxResources.get('oneDrive') + ')';
	}
	else if (file.constructor == StorageLibrary)
	{
		tip += ' (' + mxResources.get('browser') + ')';
	}
	else if (file.constructor == LocalLibrary)
	{
		tip += ' (' + mxResources.get('device') + ')';
	}

	return tip;
};

/**
 * Loads the custom libraries from the settings and the clibs URL parameter.
 */
App.prototype.restoreLibraries = function()
{
	var checked = [];

	function addLibs(libs)
	{
		for (var i = 0; i < libs.length; i++)
		{
			if (libs[i] != '' && mxUtils.indexOf(
				checked, libs[i]) < 0)
			{
				checked.push(libs[i]);
			}
		}
	};

	addLibs(mxSettings.getCustomLibraries());
	addLibs((urlParams['clibs'] || '').split(';'));
	this.loadLibraries(checked);
};

/**
 * Loads the libraries with the given IDs into the sidebar and invokes done
 * when all libraries are loaded.
 */
App.prototype.loadLibraries = function(libs, done)
{
	if (this.sidebar != null)
	{
		if (this.loadedLibraries == null)
		{
			this.loadedLibraries = new Object();
		}
		
		// Ignores this library next time
		var ignore = mxUtils.bind(this, function(id, keep)
		{
			if (!keep)
			{
				mxSettings.removeCustomLibrary(id);
			}

			delete this.loadedLibraries[id];
		});

		var waiting = 0;
		var files = [];
		var idx = (libs.length > 0 && libs[0] == 'L.scratchpad') ? 1 : 0;

		// Loads in order of libs array
		var checkDone = mxUtils.bind(this, function()
		{
			if (waiting == 0)
			{
				if (libs != null)
				{
					// Entries are prepended in the sidebar so they must be
					// loaded in reverse, or in-order if they are appended
					var append = this.sidebar.appendCustomLibraries;

					for (var j = 0; j < libs.length; j++)
					{
						var i = (append) ? j : libs.length - 1 - j;

						if (files[i] != null)
						{
							try
							{
								this.loadLibrary(files[i], i <= idx);
							}
							catch (e)
							{
								// ignore
							}
						}
					}
				}
				
				if (done != null)
				{
					done();
				}
			}
		});
		
		if (libs != null)
		{
			for (var i = 0; i < libs.length; i++)
			{
				var name = encodeURIComponent(decodeURIComponent(libs[i]));
				
				(mxUtils.bind(this, function(id, index)
				{
					if (id != null && id.length > 0 && this.loadedLibraries[id] == null &&
						this.sidebar.palettes[id] == null)
					{
						// Waits for all libraries to load
						this.loadedLibraries[id] = true;
						waiting++;
						
						var onload = mxUtils.bind(this, function(file)
						{
							files[index] = file;
							waiting--;
							checkDone();
						});
						
						var onerror = mxUtils.bind(this, function(keep)
						{
							ignore(id, keep);
							waiting--;
							checkDone();
						});
						
						var service = id.substring(0, 1);
						
						if (service == 'L')
						{
							if (isLocalStorage || mxClient.IS_CHROMEAPP)
							{
								// Make asynchronous for barrier to work
								window.setTimeout(mxUtils.bind(this, function()
								{
									try
									{
										var name = decodeURIComponent(id.substring(1));
										
										StorageFile.getFileContent(this, name, mxUtils.bind(this, function(xml)
										{
											if (name == '.scratchpad' && (xml == null || xml.substring(0, 7) == '<mxfile'))
											{
												xml = this.emptyLibraryXml;
											}
											
											if (xml != null)
											{
												onload(new StorageLibrary(this, xml, name));
											}
											else
											{
												onerror();
											}
										}), onerror);
									}
									catch (e)
									{
										onerror();
									}
								}), 0);
							}
						}
						else if (service == 'U')
						{
							var url = decodeURIComponent(id.substring(1));
							
							if (!this.isOffline())
							{
								this.loadTemplate(url, mxUtils.bind(this, function(text)
								{
									if (text != null && text.length > 0)
									{
										// LATER: Convert mxfile to mxlibrary using code from libraryLoaded
										onload(new UrlLibrary(this, text, url));
									}
									else
									{
										onerror();
									}
								}), function()
								{
									onerror();
								}, null, true);
							}
							else
							{
								onerror(true);
							}
						}
						else if (service == 'R')
						{
							var libDesc = decodeURIComponent(id.substring(1));
							
							try
							{
								libDesc = JSON.parse(libDesc);
								var libObj = {
									id: libDesc[0], 
			               			title: libDesc[1], 
			               			downloadUrl: libDesc[2]
								}
								
								this.remoteInvoke('getFileContent', [libObj.downloadUrl], null, mxUtils.bind(this, function(libContent)
								{
									try
									{
										onload(new RemoteLibrary(this, libContent, libObj));
									}
									catch (e)
									{
										onerror();
									}
								}), function()
								{
									onerror();
								});
							}
							catch (e)
							{
								onerror();
							}
						}
						else if (service == 'S' && this.loadDesktopLib != null)
						{
							try
							{
								this.loadDesktopLib(decodeURIComponent(id.substring(1)), function(desktopLib)
								{
									onload(desktopLib);
								}, onerror);
							}
							catch (e)
							{
								onerror();
							}
						}
						else
						{
							var peer = null;
							
							if (service == 'G')
							{
								if (this.drive != null && this.drive.user != null)
								{
									peer = this.drive;
								}
							}
							else if (service == 'H')
							{
								if (this.gitHub != null && this.gitHub.getUser() != null)
								{
									peer = this.gitHub;
								}
							}
							else if (service == 'T')
							{
								if (this.trello != null && this.trello.isAuthorized())
								{
									peer = this.trello;
								}
							}
							else if (service == 'W')
							{
								if (this.oneDrive != null && this.oneDrive.getUser() != null)
								{
									peer = this.oneDrive;
								}
							}
							
							if (peer != null)
							{
								peer.getLibrary(decodeURIComponent(id.substring(1)), mxUtils.bind(this, function(file)
								{
									try
									{
										onload(file);
									}
									catch (e)
									{
										onerror();
									}
								}), function(resp)
								{
									onerror();
								});
							}
							else
							{
								onerror(true);
							}
						}
					}
				}))(name, i);
			}
			
			checkDone();
		}
		else
		{
			checkDone();
		}
	}
};

/**
 * Updates the notification, comment, share and user buttons for the current
 * file and theme. Notifications are not fetched if skipNotifications is
 * true.
 */
App.prototype.updateButtonContainer = function(skipNotifications)
{
	if (this.buttonContainer != null)
	{
		// Fetch notifications
		if (!EditorUi.isElectronApp && !this.isOffline() && !skipNotifications)
		{
			if (urlParams['notif'] != null) //Notif for embed mode
			{
				this.fetchAndShowNotification(urlParams['notif']);
			}
			else if (urlParams['extAuth'] != '1' && 
				Editor.currentTheme != 'atlas') //Disable notification with external auth (e.g, Teams app)
			{
				this.fetchAndShowNotification('online', this.mode);
			}
		}

		if (this.isStandaloneApp() ||
			(Editor.currentTheme == 'simple' &&
			urlParams['embed'] != '1'))
		{
			this.buttonContainer.style.display = 'none';

			if (this.notificationBtn != null &&
				this.notificationBtn.parentNode != this.sketchMenubarElt)
			{
				this.sketchMenubarElt.appendChild(this.notificationBtn);
			}
		}
		else
		{
			this.buttonContainer.style.display = '';
			var file = this.getCurrentFile();

			if (this.notificationBtn != null &&
				this.notificationBtn.parentNode != this.buttonContainer)
			{
				this.buttonContainer.appendChild(this.notificationBtn);
			}

			// Comment
			if (Editor.currentTheme != 'sketch' &&
				Editor.currentTheme != 'simple')
			{
				if (this.commentButton == null)
				{
					this.commentButton = document.createElement('a');
					this.setElementTitle(this.commentButton, 'comments');
					this.commentButton.className = 'geButton geRoundButton';
					this.commentButton.style.backgroundImage = 'url(' + Editor.commentImage + ')';

					mxEvent.addListener(this.commentButton, 'click', mxUtils.bind(this, function()
					{
						this.actions.get('comments').funct();
					}));

					this.buttonContainer.appendChild(this.commentButton);

					// Shows the number of unresolved comments of the file
					this.addCommentsBadge(this.commentButton);

					// Dragging the button to the canvas starts a comment
					// on the shape or point it is dropped on
					this.installCommentDragSource(this.commentButton);
				}

				this.commentButton.style.display = (this.commentsSupported()) ? '' : 'none';
			}

			// Share
			if (this.shareButton == null)
			{
				this.shareButton = document.createElement('button');
				this.shareButton.className = 'geBtn gePrimaryBtn';

				var label = document.createElement('div');
				label.className = 'geButton';
				label.style.backgroundImage = 'url(' + Editor.groupImage + ')';
				this.shareButton.appendChild(label);

				this.dependsOnLanguage(mxUtils.bind(this, function()
				{
					label.innerHTML = '';
					mxUtils.write(label, mxResources.get('share'));
					this.shareButton.setAttribute('title', mxResources.get('share'));
				}));
				
				mxEvent.addListener(this.shareButton, 'click', mxUtils.bind(this, function()
				{
					this.actions.get('share').funct();
				}));
				
				this.buttonContainer.appendChild(this.shareButton);
			}

			this.shareButton.style.display = (file != null &&
				Editor.currentTheme == 'kennedy' &&
				urlParams['embed'] != '1') ? '' : 'none';
			
			// User
			if (Editor.currentTheme != 'simple')
			{
				if (this.userButton == null)
				{
					this.userButton = document.createElement('a');
					this.userButton.className = 'geButton geRoundButton';

					// User avatar (a div using a background-image rather than an
					// <img> so the default account icon adapts in dark mode via the
					// same geAdaptiveAsset pattern as other toolbar icons — see #5364)
					var userImg = document.createElement('div');
					userImg.className = 'geUserAvatar';
					this.userButton.appendChild(userImg);

					mxEvent.addListener(this.userButton, 'click', mxUtils.bind(this, function(evt)
					{
						this.toggleUserPanel();

						var bounds = this.userButton.getBoundingClientRect();
						var ww = window.innerWidth ||
							document.documentElement.clientWidth;
						this.userPanel.style.top = (bounds.bottom) + 'px';
						this.userPanel.style.right = (ww - bounds.right) + 'px';
				
						mxEvent.consume(evt);
					}));

					// Real-time collaboration status
					var syncImg = document.createElement('img');
					syncImg.style.position = 'absolute';
					syncImg.style.width = '10px';
					this.userButton.appendChild(syncImg);
					this.buttonContainer.appendChild(this.userButton);
				}

				// Updates user image
				var userImg = this.userButton.getElementsByClassName('geUserAvatar')[0];
				var syncImg = this.userButton.getElementsByTagName('img')[0];

				// Workaround for invalid images when page is unloading and for
				// images that were removed outside of the app
				if (!this.unloading && userImg != null && syncImg != null)
				{
					var title = mxResources.get('changeUser');
					var user = this.getMainUser();

					if (user != null && user.displayName != null)
					{
						title = user.displayName;
					}

					if (user != null && user.pictureUrl != null)
					{
						userImg.classList.remove('geAdaptiveAsset');
						userImg.classList.add('geUserPhoto');
						userImg.style.backgroundImage = 'url(' + user.pictureUrl + ')';
						syncImg.style.top = '3px';
						syncImg.style.right = '0';
					}
					else
					{
						userImg.classList.remove('geUserPhoto');
						userImg.classList.add('geAdaptiveAsset');
						userImg.style.backgroundImage = 'url(' + Editor.userImage + ')';
						syncImg.style.top = '6px';
						syncImg.style.right = '4px';
					}

					// Updates sync icon
					if (file != null && file.isRealtimeEnabled() && file.isRealtimeSupported())
					{
						syncImg.style.display = '';

						var err = file.getRealtimeError();
						var state = file.getRealtimeState();
						title += ' (';

						if (state == 1)
						{
							syncImg.src = Editor.syncImage;
							title += mxResources.get('online');
						}
						else
						{
							syncImg.src = Editor.syncProblemImage;

							if (err != null && err.message != null)
							{
								title += err.message;
							}
							else
							{
								title += mxResources.get('disconnected');
							}
						}
						
						title += ')';
					}
					else
					{
						syncImg.style.display = 'none';
						syncImg.src = Editor.cloudImage;
					}
					
					this.userButton.setAttribute('title', title);
					this.userButton.style.display = (this.getServiceName() == 'draw.io' && user != null &&
						urlParams['embed'] != '1' && !this.isStandaloneApp() && file != null) ?
						'' : 'none';
				}
			}
		}
	}
};

/**
 * For testing use notifs = [{timestamp: Date.now(), content: 'Test'}]
 */
App.prototype.fetchAndShowNotification = function(target, subtarget)
{
	// Plugins call this directly (eg. Confluence Cloud), so the offline
	// check of updateButtonContainer (which includes lockdown) is repeated
	if (this.fetchingNotif || NOTIFICATIONS_URL == null || this.isOffline())
	{
		return;	
	}
	
	target = target || 'online';
	var cachedNotifKey = '.notifCache';
	var cachedNotif = null;
	
	var processNotif = mxUtils.bind(this, function(notifs)
	{
		notifs = notifs.filter(function(notif)
		{
			return !notif.targets || notif.targets.indexOf(target) > -1 || 
						(subtarget != null && notif.targets.indexOf(subtarget) > -1);
		});
		
		var lsReadFlag = target + 'NotifReadTS';
		var lastRead = isLocalStorage ? parseInt(localStorage.getItem(lsReadFlag)) : true;
				
		for (var i = 0; i < notifs.length; i++)
		{
			notifs[i].isNew = (!lastRead || notifs[i].timestamp > lastRead);
		}
		
		this.showNotification(notifs, lsReadFlag);
	});
	
	try
	{
		if (isLocalStorage)
		{
			cachedNotif = JSON.parse(localStorage.getItem(cachedNotifKey));
		}
	}
	catch(e) {} //Ignore
	
	// Cache for one day. A cache without a timestamp or a list of notifications
	// is fetched again (NaN < Date.now() is false and would use it forever).
	if (cachedNotif == null || typeof cachedNotif.ts !== 'number' ||
		!Array.isArray(cachedNotif.notifs) ||
		cachedNotif.ts + 24 * 60 * 60 * 1000 < Date.now())
	{
		this.fetchingNotif = true;
		//Fetch all notifications and store them, then filter client-side
		mxUtils.get(NOTIFICATIONS_URL, mxUtils.bind(this, function(req)
		{
			if (req.getStatus() >= 200 && req.getStatus() <= 299)
			{
				try
				{
					var notifs = JSON.parse(req.getText());
					
					//Process and sort
					notifs.sort(function(a, b)
					{
						return mxUtils.compareNumbers(b.timestamp, a.timestamp);
					});

					if (isLocalStorage)
					{
						localStorage.setItem(cachedNotifKey, JSON.stringify({ts: Date.now(), notifs: notifs}));
					}
					
					this.fetchingNotif = false;	
					processNotif(notifs);
				}
				catch(e)
				{
					// ignore
				}
			}
		}));
	}
	else
	{
		processNotif(cachedNotif.notifs);
	}
};

App.prototype.showNotification = function(notifs, lsReadFlag)
{
	var newCount = notifs.length;

	if (Editor.currentTheme == 'min' || Editor.currentTheme == 'simple')
	{
		newCount = 0;

		for (var i = 0; i < notifs.length; i++)
		{
			if (notifs[i].isNew)
			{
				newCount++;
			}
		}
	}
	
	if (newCount == 0)
	{
		if (this.notificationBtn != null)
		{
			this.notificationBtn.style.display = 'none';
			this.editor.fireEvent(new mxEventObject('statusChanged'));
		}
		
		return;
	}
	
	function shouldAnimate(newNotif)
	{
		var countEl = document.querySelector('.geNotification-count');
		
		if (countEl == null)
		{
			return;
		}
		
		countEl.innerHTML = newNotif;
		countEl.style.display = newNotif == 0? 'none' : '';
		var notifBell = document.querySelector('.geNotification-bell');
		notifBell.style.animation = newNotif == 0? 'none' : '';
		notifBell.className = 'geNotification-bell' + (newNotif == 0? ' geNotification-bellOff' : '');
		document.querySelector('.geBell-rad').style.animation = newNotif == 0? 'none' : '';
	}
	
	var markAllAsRead = mxUtils.bind(this, function()
	{
		this.notificationWin.style.display = 'none';
		var unread = this.notificationWin.querySelectorAll('.circle.active');
		
		for (var i = 0; i < unread.length; i++)
		{
			unread[i].className = 'circle';
		}
		
		if (isLocalStorage && notifs[0])
		{
			localStorage.setItem(lsReadFlag, notifs[0].timestamp);
		}
	});
	
	if (this.notificationBtn == null)
	{
		this.notificationBtn = document.createElement('div');
		this.notificationBtn.className = 'geNotification-box';

		var notifCount = document.createElement('span');
		notifCount.className = 'geNotification-count';
		this.notificationBtn.appendChild(notifCount);
		this.notifCount = notifCount;
		
		var notifBell = document.createElement('div');
		notifBell.className = 'geNotification-bell';
		var bellPart = document.createElement('span');
		bellPart.className = 'geBell-top';
		notifBell.appendChild(bellPart);
		var bellPart = document.createElement('span');
		bellPart.className = 'geBell-middle';
		notifBell.appendChild(bellPart);
		var bellPart = document.createElement('span');
		bellPart.className = 'geBell-bottom';
		notifBell.appendChild(bellPart);
		var bellPart = document.createElement('span');
		bellPart.className = 'geBell-rad';
		notifBell.appendChild(bellPart);
		this.notificationBtn.appendChild(notifBell);
		
		// Add as first child such that it is the left-most one
		this.notificationWin = document.createElement('div');
		this.notificationWin.className = 'geNotifPanel';
		this.notificationWin.style.display = 'none';
		document.body.appendChild(this.notificationWin);
		
		var winHeader = document.createElement('div');
		winHeader.className = 'header';
		var winTitle = document.createElement('span');
		winTitle.className = 'title';
		winTitle.textContent = mxResources.get('notifications');
		winHeader.appendChild(winTitle);
		var winClose = document.createElement('span');
		winClose.className = 'closeBtn';
		winClose.textContent = 'x';
		winHeader.appendChild(winClose);
		this.notificationWin.appendChild(winHeader);
		
		var winBody = document.createElement('div');
		winBody.className = 'notifications clearfix';
		var notifList = document.createElement('div');
		notifList.setAttribute('id', 'geNotifList');
		notifList.style.position = 'relative';
		winBody.appendChild(notifList);
		this.notificationWin.appendChild(winBody);
		
		mxEvent.addListener(this.notificationBtn, 'click', mxUtils.bind(this, function()
		{
			if (this.notificationWin.style.display == 'none')
			{
				this.notificationWin.style.display = '';
				document.querySelector('.notifications').scrollTop = 0;
				var r = this.notificationBtn.getBoundingClientRect();
				this.notificationWin.style.top = (r.top + this.notificationBtn.clientHeight) + 'px';
				this.notificationWin.style.left = (r.right - this.notificationWin.clientWidth) + 'px';
				shouldAnimate(0); //Stop animation once notifications are open
			}
			else
			{
				markAllAsRead();
			}
		}));
		
		mxEvent.addListener(winClose, 'click', markAllAsRead);
	}
	else
	{
		this.notificationBtn.style.display = ''; //In case it was hidden
	}
		
	var newNotif = 0;
	var notifListEl = document.getElementById('geNotifList');
	
	if (notifListEl == null)
	{
		return; //This shouldn't happen and no meaning of continuing
	}
	else
	{
		notifListEl.innerHTML = '<div class="line"></div>';
		
		for (var i = 0; i < notifs.length; i++)
		{
			(function(editorUi, notif)
			{
				if (notif.isNew)
				{
					newNotif++;
				}
				
				var notifEl = document.createElement('div');
				notifEl.className = 'notification';
				var ts = new Date(notif.timestamp);
				var str = editorUi.timeSince(ts);
		
				if (str == null)
				{
					str = mxResources.get('lessThanAMinute');
				}
				
				notifEl.innerHTML = '<div class="circle' + (notif.isNew? ' active' : '') + '"></div><span class="time">' + 
										mxUtils.htmlEntities(mxResources.get('timeAgo', [str], '{1} ago')) + '</span>' + 
										'<p>' + mxUtils.htmlEntities(notif.content) + '</p>';
				if (notif.link)
				{
					mxEvent.addListener(notifEl, 'click', function()
					{
						window.open(notif.link, 'notifWin');
					});
				}
				
				notifListEl.appendChild(notifEl);
			})(this, notifs[i]);
		}
	}
	
	shouldAnimate(newNotif);
};

/**
 * Saves the current file, or saves it with the given name if the name
 * differs from its title, and invokes done after a successful save. Failed
 * saves can be retried.
 */
App.prototype.save = function(name, done)
{
	var file = this.getCurrentFile();
	var acceptResponse = true;
	var saveFile = null;

	var success = mxUtils.bind(this, function()
	{
		if (acceptResponse)
		{
			acceptResponse = false;
			file.handleFileSuccess(true);

			if (done != null)
			{
				done();
			}
		}
	});

	var error = mxUtils.bind(this, function(err)
	{
		// Waits for a save operation in progress, eg. an autosave, and saves
		// again with the spinner still active instead of showing the busy
		// error (the spinner timeout ends the wait with a timeout error)
		if (acceptResponse && err != null && err.code == App.ERROR_BUSY &&
			file.savingFile && saveFile != null)
		{
			file.afterSave(mxUtils.bind(this, function()
			{
				if (acceptResponse)
				{
					if (this.getCurrentFile() != file)
					{
						acceptResponse = false;
						this.spinner.stop();
					}
					else if (file.isModified())
					{
						saveFile();
					}
					else
					{
						// Changes were saved by the save in progress
						success();
					}
				}
			}));
		}
		else if (acceptResponse)
		{
			acceptResponse = false;

			Editor.addRetryToError(err, mxUtils.bind(this, function()
			{
				this.save(name, done);
			}));

			// Resets acceptResponse state for retry or
			// invokes success if no longer modified
			if (err != null && err.retry != null)
			{
				var retry = err.retry;

				err.retry = function()
				{
					acceptResponse = true;

					try
					{
						if (file.isModified())
						{
							retry();
						}
						else
						{
							success();
						}
					}
					catch (e)
					{
						error(e);
					}
				};
			}

			file.handleFileError(err, err == null ||
				err.name != 'AbortError');
		}
	});

	if (file != null && this.spinner.spin(document.body,
		mxResources.get('saving'), error, 3 * this.timeout))
	{
		saveFile = mxUtils.bind(this, function()
		{
			try
			{
				if (name == file.getTitle())
				{
					file.save(true, success, error);
				}
				else
				{
					file.saveAs(name, success, error)
				}
			}
			catch (err)
			{
				error(err);
			}
		});

		try
		{
			this.clearStatus();

			if (this.editor.graph.isEditing())
			{
				this.editor.graph.stopEditing();
			}

			saveFile();
		}
		catch (err)
		{
			error(err);
		}
	}
};

/**
 * Hook for subclassers.
 */
App.prototype.getExtensionForService = function(name)
{
	var service = this.getServiceForName(name);

	return service != null ? service.extension : '.drawio';
};

/**
 * Hook for subclassers.
 */
App.prototype.getServiceForName = function(name)
{
	var storage = (name != null) ? App.storages[name] : null;

	return (storage != null && storage.client != null) ? this[storage.client] : null;
};

/**
 * Hook for subclassers.
 */
App.prototype.getTitleForService = function(name)
{
	var storage = (name != null) ? App.storages[name] : null;

	if (storage != null)
	{
		return mxResources.get(storage.title);
	}
	else
	{
		return EditorUi.prototype.getTitleForService.apply(this, arguments);
	}
};

/**
 * Invokes callback with null if mode does not support folder or not null
 * if a valid folder was chosen for a mode that supports it. No callback
 * is made if no folder was chosen for a mode that supports it.
 */
App.prototype.pickFolder = function(mode, fn, enabled, direct, force, returnPickerValue)
{
	enabled = (enabled != null) ? enabled : true;
	this.spinner = (this.spinner != null) ? this.spinner :
		this.createSpinner(null, null, 24);
	var resume = this.spinner.pause();
	
	if (enabled && mode == App.MODE_GOOGLE && this.drive != null)
	{
		// Shows a save dialog
		this.drive.pickFolder(mxUtils.bind(this, function(evt)
		{
			resume();
			
			// Value of google.picker.Action.PICKED, which is not defined if
			// the root folder was picked without loading the Picker API
			if (evt.action == 'picked')
			{
				var folderId = null;
				
				if (evt.docs != null && evt.docs.length > 0 && evt.docs[0].type == 'folder')
				{
					folderId = evt.docs[0].id;
				}
				
				fn((returnPickerValue) ? evt : folderId);
			}
		}), force);
	}
	else if (enabled && mode == App.MODE_ONEDRIVE && this.oneDrive != null)
	{
		this.oneDrive.pickFolder(mxUtils.bind(this, function(files)
		{
			var folderId = null;
			resume();
			
			if (files != null && files.value != null && files.value.length > 0)
			{
				folderId = OneDriveFile.prototype.getIdOf(files.value[0]);
        		fn((returnPickerValue) ? files : folderId);
			}
		}), direct);
	}
	else if (enabled && mode == App.MODE_M365 && this.m365 != null)
	{
		this.m365.pickFolder(mxUtils.bind(this, function (files)
		{
			var folderId = null;
			resume();

			if (files != null && files.value != null && files.value.length > 0)
			{
				folderId = OneDriveFile.prototype.getIdOf(files.value[0]);
				fn((returnPickerValue) ? files : folderId);
			}
		}), direct);
	}
	else if (enabled && mode == App.MODE_GITHUB && this.gitHub != null)
	{
		this.gitHub.pickFolder(mxUtils.bind(this, function(folderPath)
		{
			resume();
			fn(folderPath);
		}));
	}
	else if (enabled && mode == App.MODE_GITLAB && this.gitLab != null)
	{
		this.gitLab.pickFolder(mxUtils.bind(this, function(folderPath)
		{
			resume();
			fn(folderPath);
		}));
	}
	else if (enabled && mode == App.MODE_TRELLO && this.trello != null)
	{
		this.trello.pickFolder(mxUtils.bind(this, function(cardId)
		{
			resume();
			fn(cardId);
		}));
	}
	else
	{
		EditorUi.prototype.pickFolder.apply(this, arguments);
	}
};

/**
 * 
 */
App.prototype.exportFile = function(data, filename, mimeType, base64Encoded, mode, folderId)
{
	if (mode == App.MODE_GOOGLE)
	{
		if (this.drive != null && this.spinner.spin(document.body, mxResources.get('saving')))
		{
			this.drive.insertFile(filename, data, folderId, mxUtils.bind(this, function(resp)
			{
				this.spinner.stop();
			}), mxUtils.bind(this, function(resp)
			{
				this.spinner.stop();
				this.handleError(resp);
			}), mimeType, base64Encoded);
		}
	}
	else if (mode == App.MODE_ONEDRIVE)
	{
		if (this.oneDrive != null && this.spinner.spin(document.body, mxResources.get('saving')))
		{
			// KNOWN: OneDrive does not show .svg extension
			this.oneDrive.insertFile(filename, (base64Encoded) ? this.base64ToBlob(data, mimeType) :
				data, mxUtils.bind(this, function()
			{
				this.spinner.stop();
			}), mxUtils.bind(this, function(resp)
			{
				this.spinner.stop();
				this.handleError(resp);
			}), false, folderId);
		}
	}
	else if (mode == App.MODE_GITHUB)
	{
		if (this.gitHub != null && this.spinner.spin(document.body, mxResources.get('saving')))
		{
			// Must insert file as library to force the file to be written
			this.gitHub.insertFile(filename, data, mxUtils.bind(this, function()
			{
				this.spinner.stop();
			}), mxUtils.bind(this, function(resp)
			{
				this.spinner.stop();
				this.handleError(resp);
			}), true, folderId, base64Encoded);
		}
	}
	else if (mode == App.MODE_GITLAB)
	{
		if (this.gitHub != null && this.spinner.spin(document.body, mxResources.get('saving')))
		{
			// Must insert file as library to force the file to be written
			this.gitLab.insertFile(filename, data, mxUtils.bind(this, function()
			{
				this.spinner.stop();
			}), mxUtils.bind(this, function(resp)
			{
				this.spinner.stop();
				this.handleError(resp);
			}), true, folderId, base64Encoded);
		}
	}
	else if (mode == App.MODE_TRELLO)
	{
		if (this.trello != null && this.spinner.spin(document.body, mxResources.get('saving')))
		{
			this.trello.insertFile(filename, (base64Encoded) ? this.base64ToBlob(data, mimeType) :
				data, mxUtils.bind(this, function()
			{
				this.spinner.stop();
			}), mxUtils.bind(this, function(resp)
			{
				this.spinner.stop();
				this.handleError(resp);
			}), false, folderId);
		}
	}
	else if (mode == App.MODE_BROWSER)
	{
		if (window.StorageFile != null && !base64Encoded &&
			this.spinner.spin(document.body, mxResources.get('saving')))
		{
			var file = data.substring(0, 10) == '<mxlibrary' ?
				new StorageLibrary(this, data, filename) :
				new StorageFile(this, data, filename)

			StorageFile.doInsertFile(file,
				mxUtils.bind(this, function()
				{
					this.spinner.stop();
				}), mxUtils.bind(this, function(resp)
				{
					this.spinner.stop();
					this.handleError(resp);
				}));
		}
		else
		{
			var fn = mxUtils.bind(this, function()
			{
				localStorage.setItem(filename, data);
			});
			
			if (localStorage.getItem(filename) == null)
			{
				fn();
			}
			else
			{
				this.confirm(mxResources.get('replaceIt', [filename]), fn);
			}
		}
	}
};

/**
 * Updates the filename, the editable state, the document title and the URL
 * hash for the current file and fires a fileDescriptorChanged event.
 */
App.prototype.descriptorChanged = function()
{
	var file = this.getCurrentFile();
	
	if (file != null)
	{
		if (this.fname != null)
		{
			this.fname.innerText = '';
			var filename = (file.getTitle() != null) ? file.getTitle() : this.defaultFilename;
			mxUtils.write(this.fname, filename);
		}
		
		var graph = this.editor.graph;
		var editable = file.isEditable();
		
		if (graph.isEnabled() && !editable)
		{
			graph.reset();
		}
		
		graph.setEnabled(editable);
		
		// Ignores title and hash for revisions
		if (urlParams['rev'] == null)
		{
			this.updateDocumentTitle();
			var newHash = file.getHash();
			
			if (newHash.length > 0)
			{
				if (newHash != this.getDiagramId())
				{
					window.location.hash = newHash;
				}

				this.updateHashObject();
			}
			else if (window.location.hash.length > 0)
			{
				window.location.hash = '';
			}
		}
	}
	
	this.updateUi();
	
	// Refresh if editable state has changed
	if (this.format != null && (file == null ||
		this.fileEditable != file.isEditable()) &&
		this.editor.graph.isSelectionEmpty())
	{
		this.format.refresh();
		this.fileEditable = (file != null) ? file.isEditable() : null;
	}
	
	this.fireEvent(new mxEventObject('fileDescriptorChanged', 'file', file));
};

/**
 * Shows the authorization dialog for the given storage peer. Invokes fn with
 * the remember option and a function that closes the dialog.
 */
App.prototype.showAuthDialog = function(peer, showRememberOption, fn, closeFn)
{
	var resume = this.spinner.pause();
	var dlg = new AuthDialog(this, peer, showRememberOption, mxUtils.bind(this, function(remember)
	{
		try
		{
			if (fn != null)
			{
				fn(remember, mxUtils.bind(this, function()
				{
					this.hideDialog();
					resume();
				}));
			}
		}
		catch (e)
		{
			this.updateStatus(mxUtils.bind(this, function()
			{
				this.editor.setStatus(mxUtils.htmlEntities(e.message));
			}));
		}
	}));

	// Room for three lines of the Terms of Use notice (the logo loads later,
	// so the content can't be measured)
	this.showDialog(dlg.container, 300, ((showRememberOption) ? 180 : 140) + ((dlg.notice != null) ? 70 : 0),
		true, true, mxUtils.bind(this, function(cancel)
	{
		if (closeFn != null)
		{
			closeFn(cancel);
		}
		
		if (cancel && this.getCurrentFile() == null && this.dialog == null)
		{
			this.showSplash();
		}
	}));
};

/**
 * Checks if the client is authorized and calls the next step. The optional
 * readXml argument is used for import. Default is false. The optional
 * readLibrary argument is used for reading libraries. Default is false.
 */
App.prototype.convertFile = function(url, filename, mimeType, extension, success, error, executeRequest, headers)
{
	var name = filename;
	
	// SVG file extensions are valid and needed for image import
	if (!/\.svg$/i.test(name))
	{
		name = name.substring(0, filename.lastIndexOf('.')) + extension;
	}
	
	var gitHubUrl = false;
	
	if (this.gitHub != null && url.substring(0, this.gitHub.baseUrl.length) == this.gitHub.baseUrl)
	{
		gitHubUrl = true;
	}
	
	// Workaround for wrong binary response with VSD(X) & VDX files
	if (/\.v(dx|sdx?)$/i.test(filename) && Graph.fileSupport && new XMLHttpRequest().upload &&
		typeof new XMLHttpRequest().responseType === 'string')
	{
		var req = new XMLHttpRequest();
		req.open('GET', url, true);
		
		if (!gitHubUrl)
		{
			req.responseType = 'blob';
		}
		
		if (headers)
		{
			for (var key in headers)
			{
				req.setRequestHeader(key, headers[key]);
			}
		}
		
		req.onload = mxUtils.bind(this, function()
		{
			if (req.status >= 200 && req.status <= 299)
			{
				var blob = null;
				
				if (gitHubUrl)
				{
					var file = JSON.parse(req.responseText);
					blob = this.base64ToBlob(file.content, 'application/octet-stream');
				}
				else
				{
					blob = new Blob([req.response], {type: 'application/octet-stream'});
				}
				
				this.importVisio(blob, mxUtils.bind(this, function(xml)
				{
					success(new LocalFile(this, xml, name, true));
				}), error, filename)
			}
			else if (error != null)
			{
				error({message: mxResources.get('errorLoadingFile')});
			}
		});

		req.onerror = error;
		req.send();
	}
	else
	{
		var handleData = mxUtils.bind(this, function(data)
		{
			try
			{
				if (/\.pdf$/i.test(filename))
				{
					var temp = Editor.extractGraphModelFromPdf(data);
						
					if (temp != null && temp.length > 0)
					{
						success(new LocalFile(this, temp, name, true));
					}
				}
				else if (/\.png$/i.test(filename))
				{
					var temp = this.extractGraphModelFromPng(data);
					
					if (temp != null)
					{
						success(new LocalFile(this, temp, name, true));
					}
					else
					{
						success(new LocalFile(this, data, filename, true));
					}
				}
				else if (Graph.fileSupport && this.isGliffyData(data, url))
				{
					this.importGliffy(data, mxUtils.bind(this, function(xml)
					{
						success(new LocalFile(this, xml, name, true));
					}), mxUtils.bind(this, function(err)
					{
						if (error != null)
						{
							error({message: mxResources.get('errorLoadingFile')});
						}
					}), filename);
				}
				else
				{
					success(new LocalFile(this, data, name, true));
				}
			}
			catch (e)
			{
				if (error != null)
				{
					error(e);
				}
			}
		});

		var binary = /\.png$/i.test(filename) || /\.jpe?g$/i.test(filename) ||
		 	/\.pdf$/i.test(filename) || (mimeType != null &&
		 	mimeType.substring(0, 6) == 'image/');
		
		// NOTE: Cannot force non-binary request via loadUrl so needs separate
		// code as decoding twice on content with binary data did not work
		if (gitHubUrl)
		{
			mxUtils.get(url, mxUtils.bind(this, function(req)
			{
				if (req.getStatus() >= 200 && req.getStatus() <= 299)
				{
			    	if (success != null)
			    	{
				    	var file = JSON.parse(req.getText());
				    	var data = file.content;
				    	
				    	if (file.encoding === 'base64')
				    	{
				    		if (/\.png$/i.test(filename))
					    	{
					    		data = 'data:image/png;base64,' + data;	
					    	}
				    		else if (/\.pdf$/i.test(filename))
					    	{
					    		data = 'data:application/pdf;base64,' + data;	
					    	}
				    		else
					    	{
					    		// Workaround for character encoding issues in IE10/11
					    		data = (window.atob) ? atob(data) : Base64.decode(data);
					    	}
				    	}
				    	
				    	handleData(data);
			    	}
				}
				else if (error != null)
		    	{
		    		error({code: App.ERROR_UNKNOWN});
		    	}
			}), function()
			{
		    	if (error != null)
		    	{
		    		error({code: App.ERROR_UNKNOWN});
		    	}
			}, false, this.timeout, mxUtils.bind(this, function()
		    {
		    	if (error != null)
				{
					error({code: App.ERROR_TIMEOUT, retry: mxUtils.bind(this, function()
					{
						this.convertFile(url, filename, mimeType, extension,
							success, error, executeRequest, headers);
					})});
				}
		    }), headers);
		}
		else if (executeRequest != null)
		{
			executeRequest(url, handleData, error, binary);
		}
		else
		{
			this.editor.loadUrl(url, handleData, error, binary, null, null, null, headers);
		}
	}
};

/**
 * Adds the listener for automatically saving the diagram for local changes.
 */ 
App.prototype.updateHeader = function()
{
	if (this.menubar != null)
	{
		var logo = 'url(' + Editor.logoImage + ')';
		this.appIcon = document.createElement('a');
		this.appIcon.className = 'geAppIcon';
		this.appIcon.style.backgroundImage = logo;

		mxEvent.disableContextMenu(this.appIcon);
		
		mxEvent.addListener(this.appIcon, 'click', mxUtils.bind(this, function(evt)
		{
			this.appIconClicked(evt);
		}));

		this.initKeyboardButton(this.appIcon);
		this.appIcon.setAttribute('aria-label', mxResources.get('draw.io'));

		mxEvent.addListener(this.appIcon, 'mouseover', mxUtils.bind(this, function()
		{
			var file = this.getCurrentFile();
			
			if (file != null)
			{
				var mode = file.getMode();
				var storage = (mode != null) ? App.storages[mode] : null;
				
				if (storage != null && storage.iconLogo != null)
				{
					this.appIcon.style.backgroundImage = 'url(' + IMAGE_PATH + '/' + storage.iconLogo + ')';
					this.appIcon.style.backgroundSize = (storage.iconLogoSize != null) ? storage.iconLogoSize : '70%';
				}
			}
		}));
		
		mxEvent.addListener(this.appIcon, 'mouseout', mxUtils.bind(this, function()
		{
			this.appIcon.style.backgroundImage = logo;
			this.appIcon.style.backgroundSize = ''
		}));
		
		if (urlParams['embed'] != '1')
		{
			this.menubarContainer.appendChild(this.appIcon);
		}
	
		this.fnameWrapper = document.createElement('div');
		this.fname = document.createElement('a');
		this.fnameWrapper.className = 'geFilenameContainer';
		this.fname.className = 'geFilename';

		mxEvent.addListener(this.fname, 'click', mxUtils.bind(this, function(evt)
		{
			var file = this.getCurrentFile();
			
			if (file != null && file.isRenamable())
			{
				if (this.editor.graph.isEditing())
				{
					this.editor.graph.stopEditing();
				}

				this.actions.get('rename').funct();
			}
			
			mxEvent.consume(evt);
		}));

		mxEvent.preventDefault(this.fname);
		this.fnameWrapper.appendChild(this.fname);
		
		if (urlParams['embed'] != '1')
		{
			this.menubarContainer.appendChild(this.fnameWrapper);
		}

		var wrapper = document.createElement('div');
		wrapper.className = 'geToolbar geToolbarEnd';
		this.toolbarContainer.appendChild(wrapper);

		// Fullscreen toggle
		this.fullscreenElement = document.createElement('a');
		this.fullscreenElement.style.backgroundImage = 'url(\'' + Editor.fullscreenImage + '\')';
		this.fullscreenElement.className = 'geButton';
		wrapper.appendChild(this.fullscreenElement);

		mxEvent.addListener(this.fullscreenElement, 'click', mxUtils.bind(this, function(evt)
		{
			var active = this.fullscreenMode;

			if (Editor.currentTheme != 'atlas' && urlParams['embed'] != '1')
			{
				this.setCompactMode(!active, null, Editor.transitionDelay);
			}

			this.toggleShapesPanel(active);
			this.toggleFormatPanel(active);
			this.fullscreenMode = !active;

			this.fullscreenElement.style.backgroundImage = 'url(\'' + ((this.fullscreenMode) ?
				Editor.fullscreenExitImage : Editor.fullscreenImage) + '\')';

			mxEvent.consume(evt);
		}));

		this.initKeyboardButton(this.fullscreenElement);

		this.addListener('formatWidthChanged', mxUtils.bind(this, function()
		{
			this.updateFullscreenState();
		}));

		this.addListener('shapesPanelChanged', mxUtils.bind(this, function()
		{
			this.updateFullscreenState();
		}));
		
		// Format panel toggle
		var toggleFormatElement = document.createElement('a');
		toggleFormatElement.className = 'geButton';
		wrapper.appendChild(toggleFormatElement);
		
		mxEvent.addListener(toggleFormatElement, 'click', mxUtils.bind(this, function(evt)
		{
			this.actions.get('format').funct();
			mxEvent.consume(evt);
		}));

		this.initKeyboardButton(toggleFormatElement);

		var toggleFormatPanel = mxUtils.bind(this, function()
		{
			if (this.formatWidth > 0)
			{
				toggleFormatElement.style.backgroundImage = 'url(\'' + Editor.rightPanelCloseImage + '\')';
			}
			else
			{
				toggleFormatElement.style.backgroundImage = 'url(\'' + Editor.rightPanelOpenImage + '\')';
			}
		});
		
		this.addListener('formatWidthChanged', toggleFormatPanel);
		toggleFormatPanel();

		var toggleElement = document.createElement('a');
		toggleElement.style.backgroundImage = 'url(\'' + ((this.compactMode) ?
			Editor.chevronDownImage : Editor.chevronUpImage) + '\')';
		toggleElement.className = 'geButton';
		
		// Compact UI toggle
		if (urlParams['embed'] != '1' && Editor.currentTheme != 'atlas')
		{
			wrapper.appendChild(toggleElement);
			
			// Toggles compact mode
			mxEvent.addListener(toggleElement, 'click', mxUtils.bind(this, function(evt)
			{
				this.setCompactMode(!this.compactMode, true, Editor.transitionDelay);
				mxEvent.consume(evt);
			}));

			this.initKeyboardButton(toggleElement);
			
			// Enable compact mode for small screens except for Firefox where the height is wrong
			if (!mxClient.IS_FF && screen.height <= 740 && typeof toggleElement.click !== 'undefined')
			{
				window.setTimeout(mxUtils.bind(this, function()
				{
					toggleElement.click();
				}), 0);
			}

			this.addListener('compactModeChanged', mxUtils.bind(this, function()
			{
				toggleElement.style.backgroundImage = 'url(\'' + ((this.compactMode) ?
					Editor.chevronDownImage : Editor.chevronUpImage) + '\')';
			}));
		}
		
		this.dependsOnLanguage(mxUtils.bind(this, function()
		{
			this.fname.setAttribute('title', mxResources.get('rename'));
			this.fullscreenElement.setAttribute('title', mxResources.get('fullscreen'));
			toggleElement.setAttribute('title', mxResources.get('collapseExpand'));
			toggleFormatElement.setAttribute('title', mxResources.get('format') + ' (' + Editor.ctrlKey + '+' + Editor.shiftKey + '+P)');
		}));
	}

	this.updateFullscreenState();
};

/**
 * Adds the listener for automatically saving the diagram for local changes.
 */
App.prototype.setCompactMode = function(active, remember, delay)
{
	var node = (mxUtils.isAncestorNode(document.body, this.container) ||
		this.editor == null) ? this.container : this.editor.graph.container;
	delay = (delay != null) ? delay : 0;
	
	window.setTimeout(mxUtils.bind(this, function()
	{
		mxUtils.setPrefixedStyle(this.menubarContainer.style, 'transition', 'all ' + delay + 's ease-in-out');
		mxUtils.setPrefixedStyle(this.toolbarContainer.style, 'transition', 'all ' + delay + 's ease-in-out');
		
		if (active)
		{
			node.classList.add('geCompactMode');
		}
		else
		{
			node.classList.remove('geCompactMode');
		}

		window.setTimeout(mxUtils.bind(this, function()
		{
			mxUtils.setPrefixedStyle(this.menubarContainer.style, 'transition', null);
			mxUtils.setPrefixedStyle(this.toolbarContainer.style, 'transition', null);
			this.compactMode = active;
			this.refresh(true);
			this.fireEvent(new mxEventObject('compactModeChanged'));

			if (isLocalStorage && remember)
			{
				mxSettings.settings.compactMode = this.compactMode;
				mxSettings.save();
			}
		}), delay * 1000);
	}), 0);
};

/**
 * Updates the fullscreen button state based on actual panel visibility.
 */
App.prototype.updateFullscreenState = function()
{
	if (this.fullscreenElement != null)
	{
		var shouldBeFullscreen = !this.isShapesPanelVisible() && !this.isFormatPanelVisible();

		if (this.fullscreenMode != shouldBeFullscreen)
		{
			this.fullscreenMode = shouldBeFullscreen;
			this.fullscreenElement.style.backgroundImage = 'url(\'' + ((this.fullscreenMode) ?
				Editor.fullscreenExitImage : Editor.fullscreenImage) + '\')';
		}
	}
};

/**
 * Returns the user of the first client in the given list that has a user.
 */
App.prototype.getFirstClientUser = function(clients)
{
	for (var i = 0; i < clients.length; i++)
	{
		if (clients[i] != null && clients[i].getUser() != null)
		{
			return clients[i].getUser();
		}
	}

	return null;
};

/**
 * Returns the user for the user button and accounts menu.
 */
App.prototype.getMainUser = function()
{
	// LATER: Trello no user issue
	return this.getFirstClientUser([this.drive, this.oneDrive,
		this.m365, this.gitHub, this.gitLab]);
};

/**
 * Adds the listener for automatically saving the diagram for local changes.
 */
App.prototype.hideUserPanel = function()
{
	if (this.userPanel != null && this.userPanel.parentNode != null)
	{
		this.userPanel.parentNode.removeChild(this.userPanel);
	}
};

/**
 * Adds the listener for automatically saving the diagram for local changes.
 */
App.prototype.toggleUserPanel = function()
{
	if (this.userPanel == null)
	{
		var div = document.createElement('div');
		div.className = 'geDialog geInlineDialog';
		div.style.minWidth = '300px';
		this.userPanel = div;

		mxEvent.addListener(document.body, 'click', mxUtils.bind(this, function(evt)
		{
			if (!mxEvent.isConsumed(evt))
			{
				this.hideUserPanel();
			}
		}));
	}
	
	if (this.userPanel.parentNode != null)
	{
		this.userPanel.parentNode.removeChild(this.userPanel);
	}
	else
	{
		var connected = false;
		this.userPanel.innerText = '';
		
		var closeImg = document.createElement('div');
		closeImg.className = 'geButton';
		closeImg.setAttribute('title', mxResources.get('close'));
		closeImg.style.backgroundImage = 'url(' + Editor.crossImage + ')';
		closeImg.style.position = 'absolute';
		closeImg.style.right = '0px';
		
		mxEvent.addListener(closeImg, 'click', mxUtils.bind(this, function()
		{
			this.hideUserPanel();
		}));
		
		this.userPanel.appendChild(closeImg);
							
		if (this.drive != null)
		{
			var driveUsers = this.drive.getUsersList();
			
			if (driveUsers.length > 0)
			{
				// LATER: Cannot change user while file is open since close will not work with new
				// credentials and closing the file using fileLoaded(null) will show splash dialog.
				var closeFile = mxUtils.bind(this, function(callback, spinnerMsg)
				{
					var file = this.getCurrentFile();

					if (file != null && file.constructor == DriveFile)
					{
						this.spinner.spin(document.body, spinnerMsg);
						this.fileLoaded(null);

						// LATER: Use callback to wait for thumbnail update
						window.setTimeout(mxUtils.bind(this, function()
						{
							this.spinner.stop();
							callback();
						}), 2000);
					}
					else
					{
						callback();
					}
				});
				
				var createUserRow = mxUtils.bind(this, function (user)
				{
					var tr = document.createElement('tr');
					var td = document.createElement('td');
					td.setAttribute('valig', 'middle');
					td.style.height = '59px';
					td.style.width = '66px';

					var img = document.createElement('img');
					img.setAttribute('width', '50');
					img.setAttribute('height', '50');
					img.setAttribute('border', '0');
					img.setAttribute('src', (user.pictureUrl != null) ?
						user.pictureUrl : Editor.userImage);
					img.style.borderRadius = '50%';
					img.style.margin = '4px 8px 0 8px';
					td.appendChild(img);
					tr.appendChild(td);

					var td = document.createElement('td');
					td.setAttribute('valign', 'middle');
					td.style.whiteSpace = 'nowrap';
					td.style.paddingTop = '4px';
					td.style.maxWidth = '0';
					td.style.overflow = 'hidden';
					td.style.textOverflow = 'ellipsis';
					mxUtils.write(td, user.displayName +
						((user.isCurrent && driveUsers.length > 1) ?
						' (' + mxResources.get('default') + ')' : ''));

					if (user.email != null)
					{
						mxUtils.br(td);

						var small = document.createElement('small');
						small.style.color = 'gray';
						mxUtils.write(small, user.email);
						td.appendChild(small);
					}

					var div = document.createElement('div');
					div.style.marginTop = '4px';

					var i = document.createElement('i');
					mxUtils.write(i, mxResources.get('googleDrive'));
					div.appendChild(i);
					td.appendChild(div);
					tr.appendChild(td);

					if (user.isCurrent)
					{
						tr.setAttribute('title', 'User ID: ' + user.id);
					}
					else
					{
						tr.setAttribute('title', mxResources.get('login') +
							' (' + 'User ID: ' + user.id + ')');
						tr.style.cursor = 'pointer';
						tr.style.opacity = '0.3';

						mxEvent.addListener(tr, 'mouseenter', mxUtils.bind(this, function()
						{
							tr.style.opacity = '1';
						}));

						mxEvent.addListener(tr, 'mouseleave', mxUtils.bind(this, function()
						{
							tr.style.opacity = '0.3';
						}));

						mxEvent.addListener(tr, 'click', mxUtils.bind(this, function(evt)
						{
							this.hideUserPanel();

							closeFile(mxUtils.bind(this, function()
							{
								this.stateArg = null;
								this.drive.setUser(user);
								
								this.drive.authorize(true, mxUtils.bind(this, function()
								{
									this.setMode(App.MODE_GOOGLE);
									this.hideDialog();
									this.showSplash();
								}), mxUtils.bind(this, function(resp)
								{
									this.handleError(resp);
								}), true); //Remember is true since add account imply keeping that account
							}), mxResources.get('changeUser') + '...');
							
							mxEvent.consume(evt);
						}));
					}
				
					return tr;
				});
				
				connected = true;
				
				var driveUserTable = document.createElement('table');
				driveUserTable.style.borderSpacing = '0';
				driveUserTable.style.fontSize = '10pt';
				driveUserTable.style.width = '100%';
				driveUserTable.style.padding = '10px';

				for (var i = 0; i < driveUsers.length; i++)
				{
					driveUserTable.appendChild(createUserRow(driveUsers[i]));
				}
				
				this.userPanel.appendChild(driveUserTable);
				
				var div = document.createElement('div');
				div.style.textAlign = 'left';
				div.style.padding = '10px';
				div.style.whiteSpace = 'nowrap';
				div.style.borderTopStyle = 'solid';
				div.style.borderTopWidth = '1px';

				var btn = mxUtils.button(mxResources.get('signOut'), mxUtils.bind(this, function()
				{
					this.confirm(mxResources.get('areYouSure'), mxUtils.bind(this, function()
					{
						closeFile(mxUtils.bind(this, function()
						{
							this.stateArg = null;
							this.drive.logout();
							this.setMode(App.MODE_GOOGLE);
							this.hideDialog();
							this.showSplash();
						}), mxResources.get('signOut'));
					}));
				}));
				btn.className = 'geBtn';
				btn.style.float = 'right';
				div.appendChild(btn);
				
				var btn = mxUtils.button(mxResources.get('addAccount'), mxUtils.bind(this, function()
				{
					var authWin = this.drive.createAuthWin();
					//FIXME This doean't work to set focus back to main window until closing the file is done
					authWin.blur();
					window.focus();
					
					closeFile(mxUtils.bind(this, function()
					{
						this.stateArg = null;
						
						this.drive.authorize(false, mxUtils.bind(this, function()
						{
							this.setMode(App.MODE_GOOGLE);
							this.hideDialog();
							this.showSplash();
						}), mxUtils.bind(this, function(resp)
						{
							this.handleError(resp);
						}), true, authWin); //Remember is true since add account imply keeping that account
					}), mxResources.get('closingFile') + '...');
				}));

				btn.className = 'geBtn';
				btn.style.margin = '0px';
				div.appendChild(btn);
				this.userPanel.appendChild(div);
			}
		}
		
		var addUser = mxUtils.bind(this, function(user, logo, logout, label)
		{
			if (user != null)
			{
				if (connected)
				{
					this.userPanel.appendChild(document.createElement('hr'));
				}
				
				connected = true;
				var userTable = document.createElement('table');
				userTable.style.borderSpacing = '0';
				userTable.style.fontSize = '10pt';
				userTable.style.width = '100%';
				userTable.style.padding = '10px';

				var tbody = document.createElement('tbody');
				var row = document.createElement('tr');
				var td = document.createElement('td');
				td.setAttribute('valig', 'top');
				td.style.width = '40px';

				if (logo != null)
				{
					var img = document.createElement('img');
					img.setAttribute('width', '40');
					img.setAttribute('height', '40');
					img.setAttribute('border', '0');
					img.setAttribute('src', logo);
					img.style.marginRight = '6px';

					td.appendChild(img);
				}

				row.appendChild(td);

				var td = document.createElement('td');
				td.setAttribute('valign', 'middle');
				td.style.whiteSpace = 'nowrap';
				td.style.maxWidth = '0';
				td.style.overflow = 'hidden';
				td.style.textOverflow = 'ellipsis';

				mxUtils.write(td, user.displayName);

				if (user.email != null)
				{
					mxUtils.br(td);

					var small = document.createElement('small');
					small.style.color = 'gray';
					mxUtils.write(small, user.email);
					td.appendChild(small);
				}

				if (label != null)
				{
					var div = document.createElement('div');
					div.style.marginTop = '4px';

					var i = document.createElement('i');
					mxUtils.write(i, label);
					div.appendChild(i);
					td.appendChild(div);
				}

				row.appendChild(td);
				tbody.appendChild(row);
				userTable.appendChild(tbody);

				this.userPanel.appendChild(userTable);
				var div = document.createElement('div');
				div.style.textAlign = 'center';
				div.style.padding = '10px';
				div.style.whiteSpace = 'nowrap';
				
				if (logout != null)
				{
					var btn = mxUtils.button(mxResources.get('signOut'), logout);
					btn.className = 'geBtn';
					div.appendChild(btn);
				}
				
				this.userPanel.appendChild(div);
			}
		});
		
		if (this.oneDrive != null)
		{
			addUser(this.oneDrive.getUser(), IMAGE_PATH + '/onedrive-logo.svg', this.oneDrive.noLogout? null : mxUtils.bind(this, function()
			{
				var file = this.getCurrentFile();

				if (file != null && file.constructor == OneDriveFile && !file.isSP)
				{
					var doLogout = mxUtils.bind(this, function()
					{
						this.oneDrive.logout();
						window.location.hash = '';
					});

					if (!file.isModified())
					{
						doLogout();
					}
					else
					{
						this.confirm(mxResources.get('allChangesLost'), null, doLogout,
							mxResources.get('cancel'), mxResources.get('discardChanges'));
					}
				}
				else
				{
					this.oneDrive.logout();
				}
			}), mxResources.get('oneDrive'));
		}

		if (this.m365 != null)
		{
			addUser(this.m365.getUser(), IMAGE_PATH + '/onedrive-logo.svg', this.m365.noLogout? null : mxUtils.bind(this, function()
			{
				var file = this.getCurrentFile();

				if (file != null && file.constructor == OneDriveFile && file.isSP)
				{
					var doLogout = mxUtils.bind(this, function()
					{
						this.m365.logout();
						window.location.hash = '';
					});

					if (!file.isModified())
					{
						doLogout();
					}
					else
					{
						this.confirm(mxResources.get('allChangesLost'), null, doLogout,
							mxResources.get('cancel'), mxResources.get('discardChanges'));
					}
				}
				else
				{
					this.m365.logout();
				}
			}), mxResources.get('m365'));
		}

		if (this.gitHub != null)
		{
			addUser(this.gitHub.getUser(), IMAGE_PATH + '/github-logo.svg', mxUtils.bind(this, function()
			{
				var file = this.getCurrentFile();

				if (file != null && file.constructor == GitHubFile)
				{
					var doLogout = mxUtils.bind(this, function()
					{
						this.gitHub.logout();
						window.location.hash = '';
					});
					
					if (!file.isModified())
					{
						doLogout();
					}
					else
					{
						this.confirm(mxResources.get('allChangesLost'), null, doLogout,
							mxResources.get('cancel'), mxResources.get('discardChanges'));
					}
				}
				else
				{
					this.gitHub.logout();
				}
			}), mxResources.get('github'));
		}
		
		if (this.gitLab != null)
		{
			addUser(this.gitLab.getUser(), IMAGE_PATH + '/gitlab-logo.svg', mxUtils.bind(this, function()
			{
				var file = this.getCurrentFile();

				if (file != null && file.constructor == GitLabFile)
				{
					var doLogout = mxUtils.bind(this, function()
					{
						this.gitLab.logout();
						window.location.hash = '';
					});

					if (!file.isModified())
					{
						doLogout();
					}
					else
					{
						this.confirm(mxResources.get('allChangesLost'), null, doLogout,
							mxResources.get('cancel'), mxResources.get('discardChanges'));
					}
				}
				else
				{
					this.gitLab.logout();
				}
			}), mxResources.get('gitlab'));
		}

		//TODO We have no user info from Trello, how we can create a user?
		if (this.trello != null)
		{
			addUser(this.trello.getUser(), IMAGE_PATH + '/trello-logo.svg', mxUtils.bind(this, function()
			{
				var file = this.getCurrentFile();

				if (file != null && file.constructor == TrelloFile)
				{
					var doLogout = mxUtils.bind(this, function()
					{
						this.trello.logout();
						window.location.hash = '';
					});
					
					if (!file.isModified())
					{
						doLogout();
					}
					else
					{
						this.confirm(mxResources.get('allChangesLost'), null, doLogout,
							mxResources.get('cancel'), mxResources.get('discardChanges'));
					}
				}
				else
				{
					this.trello.logout();
				}
			}), mxResources.get('trello'));
		}
		
		if (uiTheme == 'min')
		{
			var file = this.getCurrentFile();

			if (file != null && file.isRealtimeEnabled() && file.isRealtimeSupported())
			{
				var div = document.createElement('div');
				div.style.padding = '10px';
				div.style.whiteSpace = 'nowrap';
				div.style.borderTop = '1px solid rgb(224, 224, 224)';
				div.style.marginTop = '4px';
				div.style.textAlign = 'center';
				div.style.padding = '10px';
				div.style.fontSize = '9pt';
				var err = file.getRealtimeError();
				var state = file.getRealtimeState();

				if (state != 1)
				{
					mxUtils.write(div, mxResources.get('realtimeCollaboration') + ': ' +
						((err != null && err.message != null) ?
						err.message : mxResources.get('disconnected')));
					this.userPanel.appendChild(div);
				}
			}
		}

		document.body.appendChild(this.userPanel);
	}
};

//TODO Use this function to get the currently logged in user
App.prototype.getCurrentUser = function()
{
	//TODO Trello no user issue
	return this.getFirstClientUser([this.drive, this.oneDrive,
		this.m365, this.gitHub]);
};

/**
 * Override depends on mxSettings which is not defined in the minified viewer.
 */
var editorResetGraph = Editor.prototype.resetGraph;	
Editor.prototype.resetGraph = function()
{
	editorResetGraph.apply(this, arguments);
	
	// Overrides default with persisted value
	if (this.graph.defaultPageFormat == null)
	{
		this.graph.pageFormat = mxSettings.getPageFormat();
	}
};