diff --git a/customize.dist/pages/features.js b/customize.dist/pages/features.js index 1dfd2417f..640d97ad8 100644 --- a/customize.dist/pages/features.js +++ b/customize.dist/pages/features.js @@ -7,12 +7,16 @@ define([ '/customize/pages.js', '/api/config', '/common/common-ui-elements.js', -], function ($, h, Msg, AppConfig, LocalStore, Pages, Config, UIElements) { + '/common/common-constants.js', +], function ($, h, Msg, AppConfig, LocalStore, Pages, Config, UIElements, Constants) { var accounts = Pages.accounts; return function () { Msg.features_f_apps_note = AppConfig.availablePadTypes.map(function (app) { if (AppConfig.registeredOnlyTypes.indexOf(app) !== -1) { return; } + if (AppConfig.premiumTypes && AppConfig.premiumTypes.includes(app)) { return; } + if (Constants.earlyAccessApps && Constants.earlyAccessApps.includes(app) && + AppConfig.enableEarlyAccess) { return; } return Msg.type[app]; }).filter(function (x) { return x; }).join(', '); var premiumButton = h('a', { diff --git a/customize.dist/pages/index.js b/customize.dist/pages/index.js index ac37ac104..1f1efd4dc 100644 --- a/customize.dist/pages/index.js +++ b/customize.dist/pages/index.js @@ -5,12 +5,14 @@ define([ '/common/common-feedback.js', '/common/common-interface.js', '/common/common-hash.js', + '/common/common-constants.js', + '/common/common-util.js', '/lib/textFit.min.js', '/customize/messages.js', '/customize/application_config.js', '/common/outer/local-store.js', '/customize/pages.js' -], function ($, Config, h, Feedback, UI, Hash, TextFit, Msg, AppConfig, LocalStore, Pages) { +], function ($, Config, h, Feedback, UI, Hash, Constants, Util, TextFit, Msg, AppConfig, LocalStore, Pages) { var urlArgs = Config.requireConf.urlArgs; var isAvailableType = function (x) { @@ -18,6 +20,17 @@ define([ return AppConfig.availablePadTypes.indexOf(x) !== -1; }; + + // XXX PREMIUM + var checkEarlyAccess = function (x) { + // Check if this is an early access app and if they are allowed. + // Check if this is a premium app and if you're premium + // Returns false if the app should be hidden + var earlyTypes = Constants.earlyAccessApps; + var ea = Util.checkRestrictedApp(x, AppConfig, earlyTypes, + LocalStore.getPremium(), LocalStore.isLoggedIn()); + return ea > 0; + }; var checkRegisteredType = function (x) { // Return true if we're registered or if the app is not registeredOnly if (LocalStore.isLoggedIn()) { return true; } @@ -27,20 +40,24 @@ define([ return function () { var icons = [ + [ 'sheet', Msg.type.sheet], + [ 'doc', Msg.type.doc], + [ 'presentation', Msg.type.presentation], [ 'pad', Msg.type.pad], [ 'code', Msg.type.code], - [ 'slide', Msg.type.slide], - [ 'sheet', Msg.type.sheet], [ 'form', Msg.type.form], [ 'kanban', Msg.type.kanban], [ 'whiteboard', Msg.type.whiteboard], + [ 'slide', Msg.type.slide], [ 'drive', Msg.type.drive] ].filter(function (x) { return isAvailableType(x[0]); }) .map(function (x) { var s = 'div.bs-callout.cp-callout-' + x[0]; + var cls = ''; var isEnabled = checkRegisteredType(x[0]); + var isEAEnabled = checkEarlyAccess(x[0]); //if (i > 2) { s += '.cp-more.cp-hidden'; } var icon = AppConfig.applicationsIcon[x[0]]; var font = icon.indexOf('cptools') === 0 ? 'cptools' : 'fa'; @@ -52,11 +69,14 @@ define([ window.location.href = url; } }; + if (!isEAEnabled) { + cls += '.cp-app-hidden'; + } if (!isEnabled) { - s += '.cp-app-disabled'; + cls += '.cp-app-disabled'; attr.title = Msg.mustLogin; } - return h('a', [ + return h('a.cp-index-appitem' + cls, [ attr, h(s, [ h('i.' + font + '.' + icon, {'aria-hidden': 'true'}), diff --git a/customize.dist/src/less2/include/contextmenu.less b/customize.dist/src/less2/include/contextmenu.less index 09b26dda9..2bd587e9e 100644 --- a/customize.dist/src/less2/include/contextmenu.less +++ b/customize.dist/src/less2/include/contextmenu.less @@ -55,10 +55,20 @@ color: @cp_context-fg; } .fa, .cptools { - margin-right: 10px; + &:first-child { + margin-right: 10px; + } + &.cptools:not(:first-child) { + vertical-align: middle; + } color: @cp_context-icon; width: 16px; } + // XXX PREMIUM + &.cp-app-disabled { + cursor: not-allowed !important; + opacity: 0.5; + } } } .cp-app-drive-context-noAction { diff --git a/customize.dist/src/less2/include/drive.less b/customize.dist/src/less2/include/drive.less index d287951b5..304816f49 100644 --- a/customize.dist/src/less2/include/drive.less +++ b/customize.dist/src/less2/include/drive.less @@ -80,6 +80,16 @@ display: none; } } + + // XXX PREMIUM + &.cp-app-hidden { + display: none !important; + } + &.cp-app-disabled { + cursor: not-allowed !important; + .fa, .cptools { cursor: not-allowed !important; } + opacity: 0.5; + } } } @@ -286,7 +296,9 @@ display: none; } input { - width: ~"calc(100% - 30px)"; + //width: ~"calc(100% - 30px)"; + flex: 1; + min-width: 0; padding: 0 10px; border: 0; height: auto; @@ -298,8 +310,9 @@ .leftside-menu-category_main(); width: ~"calc(100% + 5px)"; margin: 0; - margin-bottom: -6px; - display: inline-block; + //margin-bottom: -6px; + display: flex; + align-items: center; cursor: pointer; margin-left: -5px; padding-left: 5px; @@ -309,6 +322,12 @@ width: 25px; margin-right: 0px; } + .cp-app-drive-element { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + } } } } diff --git a/customize.dist/src/less2/include/dropdown.less b/customize.dist/src/less2/include/dropdown.less index ddba87cd7..a7c810692 100644 --- a/customize.dist/src/less2/include/dropdown.less +++ b/customize.dist/src/less2/include/dropdown.less @@ -120,6 +120,15 @@ background-color: @cp_dropdown-bg-active; color: @cp_dropdown-fg; } + + // XXX PREMIUM + &.cp-app-hidden { + display: none; + } + &.cp-app-disabled { + cursor: not-allowed !important; + opacity: 0.5; + } } &> span { box-sizing: border-box; diff --git a/customize.dist/src/less2/include/forms.less b/customize.dist/src/less2/include/forms.less index 2eace9f29..30c2e9197 100644 --- a/customize.dist/src/less2/include/forms.less +++ b/customize.dist/src/less2/include/forms.less @@ -117,9 +117,6 @@ margin-right: 5px; } } - .cptools { - vertical-align: middle; - } color: @cp_buttons-fg; border: 1px solid @cp_buttons-fg; diff --git a/customize.dist/src/less2/include/icons.less b/customize.dist/src/less2/include/icons.less index 6c05803c7..4ea81ca71 100644 --- a/customize.dist/src/less2/include/icons.less +++ b/customize.dist/src/less2/include/icons.less @@ -38,5 +38,15 @@ display: none; } } + + // XXX PREMIUM + &.cp-app-hidden { + display: none !important; + } + &.cp-app-disabled { + cursor: not-allowed !important; + .fa, .cptools { cursor: not-allowed !important; } + opacity: 0.5; + } } } diff --git a/customize.dist/src/less2/pages/page-index.less b/customize.dist/src/less2/pages/page-index.less index 8c5fdc164..41a3014c7 100644 --- a/customize.dist/src/less2/pages/page-index.less +++ b/customize.dist/src/less2/pages/page-index.less @@ -118,15 +118,23 @@ padding: 10px 10px 0px 10px; //height: @icons-size - @icons-text-size; } - &.cp-app-disabled { - cursor: not-allowed !important; - opacity: 0.5; - } .pad-button-text { color: @cryptpad_text_col; padding: 5px; } } + .cp-index-appitem { + // XXX PREMIUM + &.cp-app-hidden { + display: none; + } + &.cp-app-disabled { + div { + cursor: not-allowed !important; + } + opacity: 0.5; + } + } h4 { margin: 0; } diff --git a/www/calendar/inner.js b/www/calendar/inner.js index fbc910bdb..80b5606f2 100644 --- a/www/calendar/inner.js +++ b/www/calendar/inner.js @@ -513,7 +513,8 @@ define([ options: types, // Entries displayed in the menu isSelect: true, initialValue: '.ics', - common: common + common: common, + buttonCls: 'btn', }; var $select = UIElements.createDropdown(dropdownConfig); UI.prompt(Messages.exportPrompt, diff --git a/www/common/application_config_internal.js b/www/common/application_config_internal.js index 4a58085ab..d9e4c230d 100644 --- a/www/common/application_config_internal.js +++ b/www/common/application_config_internal.js @@ -11,8 +11,8 @@ define(function() { * redirected to the drive. * You should never remove the drive from this list. */ - AppConfig.availablePadTypes = ['drive', 'teams', 'pad', 'sheet', 'code', 'slide', 'poll', 'kanban', 'whiteboard', - /*'doc', 'presentation',*/ 'file', /*'todo',*/ 'contacts', 'form', 'convert']; + AppConfig.availablePadTypes = ['drive', 'teams', 'sheet', 'doc', 'presentation', 'pad', 'code', 'slide', 'poll', 'kanban', 'whiteboard', + 'file', 'contacts', 'form', 'convert']; /* The registered only types are apps restricted to registered users. * You should never remove apps from this list unless you know what you're doing. The apps * listed here by default can't work without a user account. @@ -22,6 +22,13 @@ define(function() { */ AppConfig.registeredOnlyTypes = ['file', 'contacts', 'notifications', 'support']; + /* New application may be introduced in an "early access" state which can contain + * bugs and can cause loss of user content. You can enable these applications on your + * CryptPad instance to test them and report bugs to the developers or keep them + * disable until they are officialy considered safe. + */ + AppConfig.enableEarlyAccess = false; + // to prevent apps that aren't officially supported from showing up // in the document creation modal AppConfig.hiddenTypes = ['drive', 'teams', 'contacts', 'todo', 'file', 'accounts', 'calendar', 'poll', 'convert', diff --git a/www/common/common-constants.js b/www/common/common-constants.js index fd4d1474b..6be5d7552 100644 --- a/www/common/common-constants.js +++ b/www/common/common-constants.js @@ -11,11 +11,13 @@ define(['/customize/application_config.js'], function (AppConfig) { storageKey: 'filesData', tokenKey: 'loginToken', prefersDriveRedirectKey: 'prefersDriveRedirect', + isPremiumKey: 'isPremiumUser', displayPadCreationScreen: 'displayPadCreationScreen', deprecatedKey: 'deprecated', MAX_TEAMS_SLOTS: AppConfig.maxTeamsSlots || 5, MAX_TEAMS_OWNED: AppConfig.maxOwnedTeams || 5, // Apps - criticalApps: ['profile', 'settings', 'debug', 'admin', 'support', 'notifications', 'calendar'] + criticalApps: ['profile', 'settings', 'debug', 'admin', 'support', 'notifications', 'calendar'], + earlyAccessApps: ['doc', 'presentation'] }; }); diff --git a/www/common/common-ui-elements.js b/www/common/common-ui-elements.js index 08e0bcf07..0910a5d59 100644 --- a/www/common/common-ui-elements.js +++ b/www/common/common-ui-elements.js @@ -2087,6 +2087,7 @@ define([ }; + UIElements.createNewPadModal = function (common) { // if in drive, show new pad modal instead if ($(".cp-app-drive-element-row.cp-app-drive-new-ghost").length !== 0) { @@ -2113,6 +2114,7 @@ define([ AppConfig.registeredOnlyTypes.indexOf(p) !== -1) { return; } return true; }); + types.forEach(function (p) { var $element = $('
  • ', { 'class': 'cp-icons-element', @@ -2125,6 +2127,13 @@ define([ $modal.hide(); common.openURL('/' + p + '/'); }); + // XXX PREMIUM + var premium = common.checkRestrictedApp(p); + if (premium < 0) { + $element.addClass('cp-app-hidden cp-app-disabled'); + } else if (premium === 0) { + $element.addClass('cp-app-disabled'); + } }); var selected = -1; @@ -2268,6 +2277,7 @@ define([ var type = metadataMgr.getMetadataLazy().type || privateData.app; var fromFileData = privateData.fromFileData; + var fromContent = privateData.fromContent; var $body = $('body'); var $creationContainer = $('
    ', { id: 'cp-creation-container' }).appendTo($body); @@ -2524,6 +2534,14 @@ define([ todo(res.data); }); } + else if (fromContent) { + allData = [{ + name: fromContent.title, + id: 0, + icon: h('span.cptools.cptools-poll'), + }]; + redraw(0); + } else { redraw(0); } diff --git a/www/common/common-util.js b/www/common/common-util.js index bec6cb125..efcb46227 100644 --- a/www/common/common-util.js +++ b/www/common/common-util.js @@ -575,6 +575,26 @@ return false; }; + // Tell if a file is spreadsheet from its metadata={title, fileType} + Util.isSpreadsheet = function (type, name) { + return (type && + (type === 'application/vnd.oasis.opendocument.spreadsheet' || + type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')) + || (name && (name.endsWith('.xlsx') || name.endsWith('.ods'))); + }; + Util.isOfficeDoc = function (type, name) { + return (type && + (type === 'application/vnd.oasis.opendocument.text' || + type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')) + || (name && (name.endsWith('.docx') || name.endsWith('.odt'))); + }; + Util.isPresentation = function (type, name) { + return (type && + (type === 'application/vnd.oasis.opendocument.presentation' || + type === 'application/vnd.openxmlformats-officedocument.presentationml.presentation')) + || (name && (name.endsWith('.pptx') || name.endsWith('.odp'))); + }; + Util.isValidURL = function (str) { var pattern = new RegExp('^(https?:\\/\\/)'+ // protocol '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name @@ -618,6 +638,49 @@ getColor().toString(16); }; + Util.checkRestrictedApp = function (app, AppConfig, earlyTypes, plan, loggedIn) { + // If this is an early access app, make sure this instance allows them + if (Array.isArray(earlyTypes) && earlyTypes.includes(app) && !AppConfig.enableEarlyAccess) { + return -2; + } + + var premiumTypes = AppConfig.premiumTypes; + // If this is not a premium app, don't disable it + if (!Array.isArray(premiumTypes) || !premiumTypes.includes(app)) { return 2; } + // This is a premium app + // if you're not logged in, disable it + if (!loggedIn) { return -1; } + // if you're logged in, enable it only if you're a premium user + return plan ? 1 : 0; + + }; + + /* Chrome 92 dropped support for SharedArrayBuffer in cross-origin contexts + where window.crossOriginIsolated is false. + + Their blog (https://blog.chromium.org/2021/02/restriction-on-sharedarraybuffers.html) + isn't clear about why they're doing this, but since it's related to site-isolation + it seems they're trying to do vague security things. + + In any case, there seems to be a workaround where you can still create them + by using `new WebAssembly.Memory({shared: true, ...})` instead of `new SharedArrayBuffer`. + + This seems unreliable, but it's better than not being able to export, since + we actively rely on postMessage between iframes and therefore can't afford + to opt for full isolation. + */ + var supportsSharedArrayBuffers = function () { + try { + return Object.prototype.toString.call(new window.WebAssembly.Memory({shared: true, initial: 0, maximum: 0}).buffer) === '[object SharedArrayBuffer]'; + } catch (err) { + console.error(err); + } + return false; + }; + Util.supportsWasm = function () { + return !(typeof(Atomics) === "undefined" || !supportsSharedArrayBuffers() || typeof(WebAssembly) === 'undefined'); + }; + if (typeof(module) !== 'undefined' && module.exports) { module.exports = Util; } else if ((typeof(define) !== 'undefined' && define !== null) && (define.amd !== null)) { diff --git a/www/common/drive-ui.js b/www/common/drive-ui.js index d2f76ef8d..f4afde7b0 100644 --- a/www/common/drive-ui.js +++ b/www/common/drive-ui.js @@ -89,7 +89,6 @@ define([ var faShared = 'fa-shhare-alt'; var faReadOnly = 'fa-eye'; var faPreview = 'fa-eye'; - var faOpenInCode = 'cptools-code'; var faRename = 'fa-pencil'; var faColor = 'cptools-palette'; var faTrash = 'fa-trash'; @@ -332,7 +331,26 @@ define([ }; - var createContextMenu = function () { + Messages.fc_openIn = "Open in {0}"; // XXX + // delete fc_openInCode // XXX + var createContextMenu = function (common) { + // XXX PREMIUM + // XXX "Edit in Document" and "New Document" (and presentation) + var premiumP = common.checkRestrictedApp('presentation'); + var premiumD = common.checkRestrictedApp('doc'); + var getOpenIn = function (app) { + var icon = AppConfig.applicationsIcon[app]; + var cls = icon.indexOf('cptools') === 0 ? 'cptools '+icon : 'fa '+icon; + var html = '' + Messages.type[app]; + return Messages._getKey('fc_openIn', [html]); + }; + var isAppEnabled = function (app) { + if (!Array.isArray(AppConfig.availablePadTypes)) { return true; } + var registered = common.isLoggedIn() || !(AppConfig.registeredOnlyTypes || []).includes(app); + var restricted = common.checkRestrictedApp(app) < 0; + if (restricted === 0) { return 0; } + return AppConfig.availablePadTypes.includes(app) && registered && !restricted; + }; var menu = h('div.cp-contextmenu.dropdown.cp-unselectable', [ h('ul.dropdown-menu', { 'role': 'menu', @@ -352,10 +370,22 @@ define([ 'tabindex': '-1', 'data-icon': faReadOnly, }, h('span.cp-text', Messages.fc_open_ro))), - h('li', h('a.cp-app-drive-context-openincode.dropdown-item', { + isAppEnabled('code') ? h('li', UI.setHTML(h('a.cp-app-drive-context-openincode.dropdown-item', { + 'tabindex': '-1', + 'data-icon': 'fa-arrows', + }), getOpenIn('code'))) : undefined, + isAppEnabled('sheet') ? h('li', UI.setHTML(h('a.cp-app-drive-context-openinsheet.dropdown-item', { 'tabindex': '-1', - 'data-icon': faOpenInCode, - }, Messages.fc_openInCode)), + 'data-icon': 'fa-arrows', + }), getOpenIn('sheet'))) : undefined, + isAppEnabled('doc') ? h('li', UI.setHTML(h('a.cp-app-drive-context-openindoc.dropdown-item' + (premiumD === 0 ? '.cp-app-disabled' : ''), { + 'tabindex': '-1', + 'data-icon': 'fa-arrows', + }), getOpenIn('doc'))) : undefined, + isAppEnabled('presentation') ? h('li', UI.setHTML(h('a.cp-app-drive-context-openinpresentation.dropdown-item' + (premiumP === 0 ? '.cp-app-disabled' : ''), { + 'tabindex': '-1', + 'data-icon': 'fa-arrows', + }), getOpenIn('presentation'))) : undefined, h('li', h('a.cp-app-drive-context-savelocal.dropdown-item', { 'tabindex': '-1', 'data-icon': 'fa-cloud-upload', @@ -402,47 +432,57 @@ define([ 'data-icon': faUploadFolder, }, Messages.uploadFolderButton)), $separator.clone()[0], - h('li', h('a.cp-app-drive-context-newdoc.dropdown-item.cp-app-drive-context-editable', { + isAppEnabled('pad') ? h('li', h('a.cp-app-drive-context-newdoc.dropdown-item.cp-app-drive-context-editable', { 'tabindex': '-1', 'data-icon': AppConfig.applicationsIcon.pad, 'data-type': 'pad' - }, Messages.button_newpad)), - h('li', h('a.cp-app-drive-context-newdoc.dropdown-item.cp-app-drive-context-editable', { + }, Messages.button_newpad)) : undefined, + isAppEnabled('code') ? h('li', h('a.cp-app-drive-context-newdoc.dropdown-item.cp-app-drive-context-editable', { 'tabindex': '-1', 'data-icon': AppConfig.applicationsIcon.code, 'data-type': 'code' - }, Messages.button_newcode)), - h('li', h('a.cp-app-drive-context-newdoc.dropdown-item.cp-app-drive-context-editable', { + }, Messages.button_newcode)) : undefined, + isAppEnabled('sheet') ? h('li', h('a.cp-app-drive-context-newdoc.dropdown-item.cp-app-drive-context-editable', { 'tabindex': '-1', - 'data-icon': AppConfig.applicationsIcon.slide, - 'data-type': 'slide' - }, Messages.button_newslide)), + 'data-icon': AppConfig.applicationsIcon.sheet, + 'data-type': 'sheet' + }, Messages.button_newsheet)) : undefined, h('li.dropdown-submenu', [ h('a.cp-app-drive-context-newdocmenu.dropdown-item', { 'tabindex': '-1', 'data-icon': "fa-plus", }, Messages.fm_morePads), h("ul.dropdown-menu", [ - h('li', h('a.cp-app-drive-context-newdoc.dropdown-item.cp-app-drive-context-editable', { + isAppEnabled('doc') ? h('li', h('a.cp-app-drive-context-newdoc.dropdown-item.cp-app-drive-context-editable' + (premiumD === 0 ? '.cp-app-disabled' : ''), { 'tabindex': '-1', - 'data-icon': AppConfig.applicationsIcon.sheet, - 'data-type': 'sheet' - }, Messages.button_newsheet)), - h('li', h('a.cp-app-drive-context-newdoc.dropdown-item.cp-app-drive-context-editable', { + 'data-icon': AppConfig.applicationsIcon.doc, + 'data-type': 'doc' + }, Messages.button_newdoc)) : undefined, + isAppEnabled('presentation') ? h('li', h('a.cp-app-drive-context-newdoc.dropdown-item.cp-app-drive-context-editable' + (premiumP === 0 ? '.cp-app-disabled' : ''), { + 'tabindex': '-1', + 'data-icon': AppConfig.applicationsIcon.presentation, + 'data-type': 'presentation' + }, Messages.button_newpresentation)) : undefined, + isAppEnabled('whiteboard') ? h('li', h('a.cp-app-drive-context-newdoc.dropdown-item.cp-app-drive-context-editable', { 'tabindex': '-1', 'data-icon': AppConfig.applicationsIcon.whiteboard, 'data-type': 'whiteboard' - }, Messages.button_newwhiteboard)), - h('li', h('a.cp-app-drive-context-newdoc.dropdown-item.cp-app-drive-context-editable', { + }, Messages.button_newwhiteboard)) : undefined, + isAppEnabled('kanban') ? h('li', h('a.cp-app-drive-context-newdoc.dropdown-item.cp-app-drive-context-editable', { 'tabindex': '-1', 'data-icon': AppConfig.applicationsIcon.kanban, 'data-type': 'kanban' - }, Messages.button_newkanban)), - h('li', h('a.cp-app-drive-context-newdoc.dropdown-item.cp-app-drive-context-editable', { + }, Messages.button_newkanban)) : undefined, + isAppEnabled('form') ? h('li', h('a.cp-app-drive-context-newdoc.dropdown-item.cp-app-drive-context-editable', { + 'tabindex': '-1', + 'data-icon': AppConfig.applicationsIcon.form, + 'data-type': 'form' + }, Messages.button_newform)) : undefined, + isAppEnabled('slide') ? h('li', h('a.cp-app-drive-context-newdoc.dropdown-item.cp-app-drive-context-editable', { 'tabindex': '-1', - 'data-icon': AppConfig.applicationsIcon.poll, - 'data-type': 'poll' - }, Messages.button_newpoll)), + 'data-icon': AppConfig.applicationsIcon.slide, + 'data-type': 'slide' + }, Messages.button_newslide)) : undefined, h('li', h('a.cp-app-drive-context-newdoc.dropdown-item.cp-app-drive-context-editable', { 'tabindex': '-1', 'data-icon': AppConfig.applicationsIcon.link, @@ -613,7 +653,7 @@ define([ var $content = APP.$content = $("#cp-app-drive-content"); var $appContainer = $(".cp-app-drive-container"); var $driveToolbar = APP.toolbar.$bottom; - var $contextMenu = createContextMenu().appendTo($appContainer); + var $contextMenu = createContextMenu(common).appendTo($appContainer); var $contentContextMenu = $("#cp-app-drive-context-content"); var $defaultContextMenu = $("#cp-app-drive-context-default"); @@ -625,7 +665,7 @@ define([ // DRIVE var currentPath = APP.currentPath = LS.getLastOpenedFolder(); if (APP.newSharedFolder) { - var newSFPaths = manager.findFile(APP.newSharedFolder); + var newSFPaths = manager.findFile(Number(APP.newSharedFolder)); if (newSFPaths.length) { currentPath = newSFPaths[0]; } @@ -654,6 +694,8 @@ define([ displayedCategories = [FILES_DATA]; currentPath = [FILES_DATA]; } + } else if (priv.isEmbed && APP.newSharedFolder) { + displayedCategories = [ROOT, TRASH]; } APP.editable = !APP.readOnly; @@ -1275,7 +1317,7 @@ define([ hide.push('preview'); } if ($element.is('.cp-border-color-sheet')) { - hide.push('download'); + //hide.push('download'); // XXX if we don't want to enable this feature yet } if ($element.is('.cp-app-drive-static')) { hide.push('access', 'hashtag', 'properties', 'download'); @@ -1293,6 +1335,18 @@ define([ if (!metadata || !Util.isPlainTextFile(metadata.fileType, metadata.title)) { hide.push('openincode'); } + if (!metadata || !Util.isSpreadsheet(metadata.fileType, metadata.title) + || !priv.supportsWasm) { + hide.push('openinsheet'); + } + if (!metadata || !Util.isOfficeDoc(metadata.fileType, metadata.title) + || !priv.supportsWasm) { + hide.push('openindoc'); + } + if (!metadata || !Util.isPresentation(metadata.fileType, metadata.title) + || !priv.supportsWasm) { + hide.push('openinpresentation'); + } if (metadata.channel && metadata.channel.length < 48) { hide.push('preview'); } @@ -1309,6 +1363,9 @@ define([ containsFolder = true; hide.push('openro'); hide.push('openincode'); + hide.push('openinsheet'); + hide.push('openindoc'); + hide.push('openinpresentation'); hide.push('hashtag'); //hide.push('delete'); hide.push('makeacopy'); @@ -1324,6 +1381,9 @@ define([ hide.push('savelocal'); hide.push('openro'); hide.push('openincode'); + hide.push('openinsheet'); + hide.push('openindoc'); + hide.push('openinpresentation'); hide.push('properties', 'access'); hide.push('hashtag'); hide.push('makeacopy'); @@ -1355,7 +1415,8 @@ define([ hide.push('download'); hide.push('share'); hide.push('savelocal'); - hide.push('openincode'); // can't because of race condition + //hide.push('openincode'); // can't because of race condition + //hide.push('openinsheet'); // can't because of race condition hide.push('makeacopy'); hide.push('preview'); } @@ -1367,6 +1428,9 @@ define([ if (!APP.loggedIn) { hide.push('openparent'); hide.push('rename'); + hide.push('openinsheet'); + hide.push('openindoc'); + hide.push('openinpresentation'); } filter = function ($el, className) { @@ -1380,11 +1444,12 @@ define([ break; case 'tree': show = ['open', 'openro', 'preview', 'openincode', 'expandall', 'collapseall', - 'color', 'download', 'share', 'savelocal', 'rename', 'delete', 'makeacopy', + 'color', 'download', 'share', 'savelocal', 'rename', 'delete', + 'makeacopy', 'openinsheet', 'openindoc', 'openinpresentation', 'deleteowned', 'removesf', 'access', 'properties', 'hashtag']; break; case 'default': - show = ['open', 'openro', 'preview', 'openincode', 'share', 'download', 'openparent', 'delete', 'deleteowned', 'properties', 'access', 'hashtag', 'makeacopy', 'savelocal', 'rename']; + show = ['open', 'openro', 'preview', 'openincode', 'openinsheet', 'openindoc', 'openinpresentation', 'share', 'download', 'openparent', 'delete', 'deleteowned', 'properties', 'access', 'hashtag', 'makeacopy', 'savelocal', 'rename']; break; case 'trashtree': { show = ['empty']; @@ -2354,6 +2419,7 @@ define([ path.forEach(function (p, idx) { if (isTrash && [2,3].indexOf(idx) !== -1) { return; } if (skipNext) { skipNext = false; return; } + if (APP.newSharedFolder && priv.isEmbed && p === ROOT && !idx) { return; } var name = p; if (manager.isFile(el) && isInTrashRoot && idx === 1) { @@ -2394,7 +2460,7 @@ define([ addDragAndDropHandlers($span, path.slice(0, idx), true, true); if (idx === 0) { name = p === SHARED_FOLDER ? name : getPrettyName(p); } - else { + else if (!(APP.newSharedFolder && priv.isEmbed && idx === 1)) { var $span2 = $('', { 'class': 'cp-app-drive-path-element cp-app-drive-path-separator' }).text(' / '); @@ -2885,6 +2951,15 @@ define([ 'data-type': type, 'href': '#' }; + + // XXX PREMIUM + var premium = common.checkRestrictedApp(type); + if (premium < 0) { + attributes.class += ' cp-app-hidden cp-app-disabled'; + } else if (premium === 0) { + attributes.class += ' cp-app-disabled'; + } + options.push({ tag: 'a', attributes: attributes, @@ -3211,6 +3286,14 @@ define([ $element.append($('', {'class': 'cp-app-drive-new-name'}) .text(Messages.type[type])); $element.attr('data-type', type); + + // XXX PREMIUM + var premium = common.checkRestrictedApp(type); + if (premium < 0) { + $element.addClass('cp-app-hidden cp-app-disabled'); + } else if (premium === 0) { + $element.addClass('cp-app-disabled'); + } }); $container.find('.cp-app-drive-element-row').click(function () { @@ -4062,17 +4145,28 @@ define([ var createTree = function ($container, path) { var root = manager.find(path); + var isRoot = manager.comparePath([ROOT], path); + var rootName = ROOT_NAME; + if (APP.newSharedFolder && priv.isEmbed && isRoot) { + var newSFPaths = manager.findFile(Number(APP.newSharedFolder)); + if (newSFPaths.length) { + path = newSFPaths[0]; + path.push(ROOT); + root = manager.find(path); + rootName = manager.getSharedFolderData(APP.newSharedFolder).title; + } + } + // don't try to display what doesn't exist if (!root) { return; } // Display the root element in the tree - var displayingRoot = manager.comparePath([ROOT], path); - if (displayingRoot) { - var isRootOpened = manager.comparePath([ROOT], currentPath); + if (isRoot) { + var isRootOpened = manager.comparePath(path.slice(), currentPath); var $rootIcon = manager.isFolderEmpty(files[ROOT]) ? (isRootOpened ? $folderOpenedEmptyIcon : $folderEmptyIcon) : (isRootOpened ? $folderOpenedIcon : $folderIcon); - var $rootElement = createTreeElement(ROOT_NAME, $rootIcon.clone(), [ROOT], false, true, true, isRootOpened); + var $rootElement = createTreeElement(rootName, $rootIcon.clone(), path.slice(), false, true, true, isRootOpened); if (!manager.hasSubfolder(root)) { $rootElement.find('.cp-app-drive-icon-expcol').css('visibility', 'hidden'); } @@ -4349,6 +4443,21 @@ define([ }); }; + var openInApp = function (paths, app) { + var p = paths[0]; + var el = manager.find(p.path); + var path = currentPath; + if (path[0] !== ROOT) { path = [ROOT]; } + var _metadata = manager.getFileData(el); + var _simpleData = { + title: _metadata.filename || _metadata.title, + href: _metadata.href || _metadata.roHref, + fileType: _metadata.fileType, + password: _metadata.password, + channel: _metadata.channel, + }; + openIn(app, path, APP.team, _simpleData); + }; $contextMenu.on("click", "a", function(e) { e.stopPropagation(); @@ -4436,20 +4545,19 @@ define([ } else if ($this.hasClass('cp-app-drive-context-openincode')) { if (paths.length !== 1) { return; } - var p = paths[0]; - el = manager.find(p.path); - (function () { - var path = currentPath; - if (path[0] !== ROOT) { path = [ROOT]; } - var _metadata = manager.getFileData(el); - var _simpleData = { - title: _metadata.filename || _metadata.title, - href: _metadata.href || _metadata.roHref, - password: _metadata.password, - channel: _metadata.channel, - }; - openIn('code', path, APP.team, _simpleData); - })(); + openInApp(paths, 'code'); + } + else if ($this.hasClass('cp-app-drive-context-openinsheet')) { + if (paths.length !== 1) { return; } + openInApp(paths, 'sheet'); + } + else if ($this.hasClass('cp-app-drive-context-openindoc')) { + if (paths.length !== 1) { return; } + openInApp(paths, 'doc'); + } + else if ($this.hasClass('cp-app-drive-context-openinpresentation')) { + if (paths.length !== 1) { return; } + openInApp(paths, 'presentation'); } else if ($this.hasClass('cp-app-drive-context-expandall') || $this.hasClass('cp-app-drive-context-collapseall')) { diff --git a/www/common/make-backup.js b/www/common/make-backup.js index 3f66c1310..a80663677 100644 --- a/www/common/make-backup.js +++ b/www/common/make-backup.js @@ -28,7 +28,7 @@ define([ return n; }; - var transform = function (ctx, type, sjson, cb) { + var transform = function (ctx, type, sjson, cb, padData) { var result = { data: sjson, ext: '.json', @@ -41,11 +41,11 @@ define([ } var path = '/' + type + '/export.js'; require([path], function (Exporter) { - Exporter.main(json, function (data) { - result.ext = Exporter.ext || ''; + Exporter.main(json, function (data, _ext) { + result.ext = _ext || Exporter.ext || ''; result.data = data; cb(result); - }); + }, null, ctx.sframeChan, padData); }, function () { cb(result); }); @@ -117,12 +117,16 @@ define([ var opts = { password: pData.password }; + var padData = { + hash: parsed.hash, + password: pData.password + }; var handler = ctx.sframeChan.on("EV_CRYPTGET_PROGRESS", function (data) { if (data.hash !== parsed.hash) { return; } updateProgress.progress(data.progress); if (data.progress === 1) { handler.stop(); - updateProgress.progress2(1); + updateProgress.progress2(2); } }); ctx.get({ @@ -136,14 +140,15 @@ define([ if (cancelled) { return; } if (!res.data) { return; } var dl = function () { - saveAs(res.data, Util.fixFileName(name)); + saveAs(res.data, Util.fixFileName(name)+(res.ext || '')); }; + updateProgress.progress2(1); cb(null, { metadata: res.metadata, content: res.data, download: dl }); - }); + }, padData); }); return { cancel: cancel @@ -195,9 +200,16 @@ define([ }); }; + var timeout = 60000; + // OO pads can only be converted one at a time so we have to give them a + // bigger timeout value in case there are 5 of them in the current queue + if (['sheet', 'doc', 'presentation'].indexOf(parsed.type) !== -1) { + timeout = 180000; + } + to = setTimeout(function () { error('TIMEOUT'); - }, 60000); + }, timeout); setTimeout(function () { if (ctx.stop) { return; } @@ -228,6 +240,9 @@ define([ zip.file(fileName, res.data, opts); console.log('DONE ---- ' + fileName); setTimeout(done, 500); + }, { + hash: parsed.hash, + password: fData.password }); }); }; @@ -292,7 +307,7 @@ define([ }; // Main function. Create the empty zip and fill it starting from drive.root - var create = function (data, getPad, fileHost, cb, progress, cache) { + var create = function (data, getPad, fileHost, cb, progress, cache, sframeChan) { if (!data || !data.uo || !data.uo.drive) { return void cb('EEMPTY'); } var sem = Saferphore.create(5); var ctx = { @@ -307,7 +322,8 @@ define([ updateProgress: progress, max: 0, done: 0, - cache: cache + cache: cache, + sframeChan: sframeChan }; var filesData = data.sharedFolderId && ctx.sf[data.sharedFolderId] ? ctx.sf[data.sharedFolderId].filesData : ctx.data.filesData; progress('reading', -1); // Msg.settings_export_reading @@ -358,7 +374,7 @@ define([ else if (state === "done") { updateProgress.folderProgress(3); } - }, ctx.cache); + }, ctx.cache, ctx.sframeChan); }; var createExportUI = function (origin) { diff --git a/www/common/onlyoffice/history.js b/www/common/onlyoffice/history.js index b8ae4b77d..c0126023c 100644 --- a/www/common/onlyoffice/history.js +++ b/www/common/onlyoffice/history.js @@ -119,7 +119,7 @@ define([ // The first "cp" in history is the empty doc. It doesn't include the first patch // of the history - var initialCp = cpIndex === sortedCp.length; + var initialCp = cpIndex === sortedCp.length || !cp.hash; var messages = (data.messages || []).slice(initialCp ? 0 : 1); diff --git a/www/common/onlyoffice/inner.js b/www/common/onlyoffice/inner.js index 195991db9..0454b4bc5 100644 --- a/www/common/onlyoffice/inner.js +++ b/www/common/onlyoffice/inner.js @@ -20,6 +20,7 @@ define([ '/common/onlyoffice/oodoc_base.js', '/common/onlyoffice/ooslide_base.js', '/common/outer/worker-channel.js', + '/common/outer/x2t.js', '/bower_components/file-saver/FileSaver.min.js', @@ -47,7 +48,8 @@ define([ EmptyCell, EmptyDoc, EmptySlide, - Channel) + Channel, + X2T) { var saveAs = window.saveAs; var Nacl = window.nacl; @@ -56,11 +58,13 @@ define([ urlArgs: Util.find(ApiConfig, ['requireConf', 'urlArgs']) }; - var CHECKPOINT_INTERVAL = 100; + var CHECKPOINT_INTERVAL = 20; // XXX + var FORCE_CHECKPOINT_INTERVAL = 50; // XXX var DISPLAY_RESTORE_BUTTON = false; - var NEW_VERSION = 4; + var NEW_VERSION = 4; // version of the .bin, patches and ChainPad formats var PENDING_TIMEOUT = 30000; - var CURRENT_VERSION = 'v4'; + var CURRENT_VERSION = X2T.CURRENT_VERSION; + //var READONLY_REFRESH_TO = 15000; var debug = function (x, type) { @@ -72,34 +76,6 @@ define([ return JSONSortify(obj); }; - /* Chrome 92 dropped support for SharedArrayBuffer in cross-origin contexts - where window.crossOriginIsolated is false. - - Their blog (https://blog.chromium.org/2021/02/restriction-on-sharedarraybuffers.html) - isn't clear about why they're doing this, but since it's related to site-isolation - it seems they're trying to do vague security things. - - In any case, there seems to be a workaround where you can still create them - by using `new WebAssembly.Memory({shared: true, ...})` instead of `new SharedArrayBuffer`. - - This seems unreliable, but it's better than not being able to export, since - we actively rely on postMessage between iframes and therefore can't afford - to opt for full isolation. - */ - var supportsSharedArrayBuffers = function () { - try { - return Object.prototype.toString.call(new window.WebAssembly.Memory({shared: true, initial: 0, maximum: 0}).buffer) === '[object SharedArrayBuffer]'; - } catch (err) { - console.error(err); - } - return false; - }; - - var supportsXLSX = function () { - return !(typeof(Atomics) === "undefined" || !supportsSharedArrayBuffers() /* || typeof (SharedArrayBuffer) === "undefined" */ || typeof(WebAssembly) === 'undefined'); - }; - - var toolbar; var cursor; @@ -136,6 +112,10 @@ define([ var startOO = function () {}; + var supportsXLSX = function () { + return privateData.supportsWasm; + }; + var getMediasSources = APP.getMediasSources = function() { content.mediasSources = content.mediasSources || {}; return content.mediasSources; @@ -145,9 +125,13 @@ define([ return metadataMgr.getNetfluxId() + '-' + privateData.clientId; }; + var getWindow = function () { + return window.frames && window.frames[0]; + }; var getEditor = function () { - if (!window.frames || !window.frames[0]) { return; } - return window.frames[0].editor || window.frames[0].editorCell; + var w = getWindow(); + if (!w) { return; } + return w.editor || w.editorCell; }; var setEditable = function (state, force) { @@ -252,6 +236,10 @@ define([ var getFileType = function () { var type = common.getMetadataMgr().getPrivateData().ooType; var title = common.getMetadataMgr().getMetadataLazy().title; + if (APP.downloadType) { + type = APP.downloadType; + title = "download"; + } var file = {}; switch(type) { case 'doc': @@ -478,6 +466,9 @@ define([ delete APP.refreshPopup; clearTimeout(APP.refreshRoTo); + // Don't create the initial checkpoint indefinitely in a loop + delete APP.initCheckpoint; + if (!isLockedModal.modal) { isLockedModal.modal = UI.openCustomModal(isLockedModal.content); } @@ -495,10 +486,10 @@ define([ startOO(blob, type, true); }; - var saveToServer = function () { + var saveToServer = function (blob, title) { if (APP.cantCheckpoint) { return; } // TOO_LARGE var text = getContent(); - if (!text) { + if (!text && !blob) { setEditable(false, true); sframeChan.query('Q_CLEAR_CACHE_CHANNELS', [ 'chainpad', @@ -509,9 +500,9 @@ define([ }); return; } - var blob = new Blob([text], {type: 'plain/text'}); + blob = blob || new Blob([text], {type: 'plain/text'}); var file = getFileType(); - blob.name = (metadataMgr.getMetadataLazy().title || file.doc) + '.' + file.type; + blob.name = title || (metadataMgr.getMetadataLazy().title || file.doc) + '.' + file.type; var data = { hash: (APP.history || APP.template) ? ooChannel.historyLastHash : ooChannel.lastHash, index: (APP.history || APP.template) ? ooChannel.currentIndex : ooChannel.cpIndex @@ -539,8 +530,9 @@ define([ var locked = content.saveLock; var lastCp = getLastCp(); - var needCp = force || ooChannel.cpIndex % CHECKPOINT_INTERVAL === 0 || - (ooChannel.cpIndex - (lastCp.index || 0)) > CHECKPOINT_INTERVAL; + var currentIdx = ooChannel.cpIndex; + var needCp = force || (currentIdx - (lastCp.index || 0)) > FORCE_CHECKPOINT_INTERVAL; + if (!needCp) { return; } if (!locked || !isUserOnline(locked) || force) { @@ -725,6 +717,7 @@ define([ var cp = hashes[cpId] || {}; var minor = Number(s[1]) + 1; + if (APP.isDownload) { minor = undefined; } var toHash = cp.hash || 'NONE'; var fromHash = nextCpId ? hashes[nextCpId].hash : 'NONE'; @@ -733,6 +726,7 @@ define([ channel: content.channel, lastKnownHash: fromHash, toHash: toHash, + isDownload: APP.isDownload }, function (err, data) { if (err) { console.error(err); return void UI.errorLoadingScreen(Messages.error); } if (!Array.isArray(data.messages)) { @@ -742,7 +736,7 @@ define([ // The first "cp" in history is the empty doc. It doesn't include the first patch // of the history - var initialCp = major === 0; + var initialCp = major === 0 || !cp.hash; var messages = (data.messages || []).slice(initialCp ? 0 : 1, minor); messages.forEach(function (obj) { @@ -784,6 +778,7 @@ define([ } var file = getFileType(); var type = common.getMetadataMgr().getPrivateData().ooType; + if (APP.downloadType) { type = APP.downloadType; } var blob = loadInitDocument(type, true); ooChannel.queue = messages; resetData(blob, file); @@ -1077,17 +1072,31 @@ define([ return; } var type = common.getMetadataMgr().getPrivateData().ooType; - - content.locks = content.locks || {}; - // Send the lock to other users + var b = obj.block && obj.block[0]; var msg = { time: now(), user: myUniqueOOId, - block: obj.block && obj.block[0], + block: b }; + + var editor = getEditor(); + if (type === "presentation" && (APP.themeChanged || APP.themeRemote) && b && + b.guid === editor.GetPresentation().Presentation.themeLock.Id) { + APP.themeLocked = APP.themeChanged; + APP.themeChanged = undefined; + var fakeLocks = getLock(); + fakeLocks[Util.uid()] = msg; + send({ + type: "getLock", + locks: fakeLocks + }); + return; + } + + content.locks = content.locks || {}; + // Send the lock to other users var myId = getId(); content.locks[myId] = content.locks[myId] || {}; - var b = obj.block && obj.block[0]; if (type === "sheet" || typeof(b) !== "string") { var uid = Util.uid(); content.locks[myId][uid] = msg; @@ -1097,6 +1106,7 @@ define([ oldLocks = JSON.parse(JSON.stringify(content.locks)); // Remove old locks deleteOfflineLocks(); + // Prepare callback if (cpNfInner) { var waitLock = APP.waitLock = Util.mkEvent(true); @@ -1138,7 +1148,7 @@ define([ APP.realtime.sync(); }; - var parseChanges = function (changes) { + var parseChanges = function (changes, isObj) { try { changes = JSON.parse(changes); } catch (e) { @@ -1147,7 +1157,7 @@ define([ return changes.map(function (change) { return { docid: "fresh", - change: '"' + change + '"', + change: isObj ? change : '"' + change + '"', time: now(), user: myUniqueOOId, useridoriginal: String(myOOId) @@ -1186,11 +1196,16 @@ define([ return; } + var changes = obj.changes; + if (obj.type === "cp_theme") { + changes = JSON.stringify([JSON.stringify(obj)]); + } + // Send the changes content.locks = content.locks || {}; rtChannel.sendMsg({ type: "saveChanges", - changes: parseChanges(obj.changes), + changes: parseChanges(changes, obj.type === "cp_theme"), changesIndex: ooChannel.cpIndex || 0, locks: getUserLock(getId(), true), excelAdditionalInfo: obj.excelAdditionalInfo @@ -1224,6 +1239,73 @@ define([ }); }; + APP.testArr = [ + ['a','b',1,'d'], + ['e',undefined,'g','h'] + ]; + var makePatch = APP.makePatch = function (arr) { + var w = getWindow(); + if (!w) { return; } + // Define OO classes + var AscCommonExcel = w.AscCommonExcel; + var CellValueData = AscCommonExcel.UndoRedoData_CellValueData; + var CCellValue = AscCommonExcel.CCellValue; + //var History = w.AscCommon.History; + var AscCH = w.AscCH; + var Asc = w.Asc; + var UndoRedoData_CellSimpleData = AscCommonExcel.UndoRedoData_CellSimpleData; + var editor = getEditor(); + + var Id = editor.GetSheet(0).worksheet.Id; + //History.Create_NewPoint(); + var patches = []; + arr.forEach(function (arr2, i) { + arr2.forEach(function (v, j) { + var obj = {}; + if (typeof(v) === "string") { obj.text = v; obj.type = 1; } + else if (typeof(v) === "number") { obj.number = v; obj.type = 0; } + else { return; } + var newValue = new CellValueData(undefined, new CCellValue(obj)); + var nCol = j; + var nRow = i; + var patch = new AscCommonExcel.UndoRedoItemSerializable(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ChangeValue, Id, + new Asc.Range(nCol, nRow, nCol, nRow), + new UndoRedoData_CellSimpleData(nRow, nCol, undefined, newValue), undefined); + patches.push(patch); + /* + History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ChangeValue, Id, + new Asc.Range(nCol, nRow, nCol, nRow), + new UndoRedoData_CellSimpleData(nRow, nCol, undefined, newValue), undefined, true); + */ + }); + }); + var oMemory = new w.AscCommon.CMemory(); + var aRes = []; + patches.forEach(function (item) { + editor.GetSheet(0).worksheet.workbook._SerializeHistoryBase64(oMemory, item, aRes); + }); + + // Make the patch + var msg = { + type: "saveChanges", + changes: parseChanges(JSON.stringify(aRes)), + changesIndex: ooChannel.cpIndex || 0, + locks: getUserLock(getId(), true), + excelAdditionalInfo: null + }; + + // Send the patch + rtChannel.sendMsg(msg, null, function (err, hash) { + if (err) { + return void console.error(err); + } + // Apply it on our side + ooChannel.send(msg); + ooChannel.lastHash = hash; + ooChannel.cpIndex++; + }); + }; + var makeChannel = function () { var msgEv = Util.mkEvent(); @@ -1244,6 +1326,11 @@ define([ if (APP.onStrictSaveChanges && !force) { return; } // We only need to release locks for sheets if (type !== "sheet" && obj.type === "releaseLock") { return; } + if (type === "presentation" && obj.type === "cp_theme") { + // XXX + console.error(obj); + return; + } debug(obj, 'toOO'); chan.event('CMD', obj); @@ -1306,6 +1393,24 @@ define([ APP.onStrictSaveChanges(); return; } + var AscCommon = window.frames[0] && window.frames[0].AscCommon; + if (Util.find(AscCommon, ['CollaborativeEditing','m_bFast']) + && APP.themeLocked) { + obj = APP.themeLocked; + APP.themeLocked = undefined; + obj.type = "cp_theme"; + console.error(obj); + } + if (APP.themeRemote) { + delete APP.themeRemote; + send({ + type: "unSaveLock", + index: ooChannel.cpIndex, + time: +new Date() + }); + return; + } + // We're sending our changes to netflux handleChanges(obj, send); // If we're alone, clean up the medias @@ -1351,15 +1456,64 @@ define([ }); }; + var x2tConvertData = function (data, fileName, format, cb) { + var sframeChan = common.getSframeChannel(); + var e = getEditor(); + var fonts = e && e.FontLoader.fontInfos; + var files = e && e.FontLoader.fontFiles.map(function (f) { + return { 'Id': f.Id, }; + }); + var type = common.getMetadataMgr().getPrivateData().ooType; + var images = (e && window.frames[0].AscCommon.g_oDocumentUrls.urls) || {}; + var theme = e && window.frames[0].AscCommon.g_image_loader.map_image_index; + if (theme) { + Object.keys(theme).forEach(function (url) { + if (!/^(\/|blob:|data:)/.test(url)) { + images[url] = url; + } + }); + } + sframeChan.query('Q_OO_CONVERT', { + data: data, + type: type, + fileName: fileName, + outputFormat: format, + images: (e && window.frames[0].AscCommon.g_oDocumentUrls.urls) || {}, + fonts: fonts, + fonts_files: files, + mediasSources: getMediasSources(), + mediasData: mediasData + }, function (err, obj) { + if (err || !obj || !obj.data) { + UI.warn(Messages.error); + return void cb(); + } + cb(obj.data, obj.images); + }, { + raw: true + }); + }; + + // When download a sheet from the drive, we must wait for all the images + // to be downloaded and decrypted before converting to xlsx + var downloadImages = {}; + + var firstOO = true; startOO = function (blob, file, force) { if (APP.ooconfig && !force) { return void console.error('already started'); } var url = URL.createObjectURL(blob); var lock = !APP.history && (APP.migrate); + var fromContent = metadataMgr.getPrivateData().fromContent; + if (!firstOO) { fromContent = undefined; } + firstOO = false; + // Starting from version 3, we can use the view mode again // defined but never used //var mode = (content && content.version > 2 && lock) ? "view" : "edit"; + var lang = (window.cryptpadLanguage || navigator.language || navigator.userLanguage || '').slice(0,2); + // Config APP.ooconfig = { "document": { @@ -1386,7 +1540,7 @@ define([ "name": metadataMgr.getUserData().name || Messages.anonymous, }, "mode": "edit", - "lang": (window.cryptpadLanguage || navigator.language || navigator.userLanguage || '').slice(0,2) + "lang": lang }, "events": { "onAppReady": function(/*evt*/) { @@ -1431,6 +1585,13 @@ define([ }); } }, + "onError": function () { + console.error(arguments); + if (APP.isDownload) { + var sframeChan = common.getSframeChannel(); + sframeChan.event('EV_OOIFRAME_DONE', ''); + } + }, "onDocumentReady": function () { evOnSync.fire(); var onMigrateRdy = Util.mkEvent(); @@ -1508,7 +1669,38 @@ define([ ooChannel.lastHash = hash; }); } + + if (APP.startNew) { + var w = getWindow(); + if (lang === "fr") { lang = 'fr-fr'; } + var l = w.Common.util.LanguageInfo.getLocalLanguageCode(lang); + getEditor().asc_setDefaultLanguage(l); + } } + delete APP.startNew; + + if (fromContent && !lock && Array.isArray(fromContent.content)) { + makePatch(fromContent.content); + } + + if (APP.isDownload) { + var bin = getContent(); + if (!supportsXLSX()) { + return void sframeChan.event('EV_OOIFRAME_DONE', bin, {raw: true}); + } + nThen(function (waitFor) { + // wait for all the images to be loaded before converting + Object.keys(downloadImages).forEach(function (name) { + downloadImages[name].reg(waitFor()); + }); + }).nThen(function () { + x2tConvertData(bin, 'filename.bin', file.type, function (xlsData) { + sframeChan.event('EV_OOIFRAME_DONE', xlsData, {raw: true}); + }); + }); + return; + } + if (isLockedModal.modal && force) { isLockedModal.modal.closeModal(); @@ -1534,10 +1726,15 @@ define([ } catch (e) {} } - if (lock && !readOnly) { + if (lock && !readOnly) { // Lock = !history && migrate onMigrateRdy.fire(); } + if (APP.initCheckpoint) { + getEditor().asc_setRestriction(true); + makeCheckpoint(true); + } + // Check if history can/should be trimmed var cp = getLastCp(); if (cp && cp.file && cp.hash) { @@ -1637,6 +1834,25 @@ define([ }); }; + APP.remoteTheme = function () { + /* + APP.themeRemote = true; + */ + }; + APP.changeTheme = function (id) { + /* + // XXX disabled: +Uncaught TypeError: Cannot read property 'calculatedType' of null + at CPresentation.changeTheme (sdk-all.js?ver=4.11.0-1633612942653-1633619288217:15927) + */ + + id = id; + /* + APP.themeChanged = { + id: id + }; + */ + }; APP.openURL = function (url) { common.openUnsafeURL(url); }; @@ -1649,13 +1865,28 @@ define([ var mediasSources = getMediasSources(); var data = mediasSources[name]; + downloadImages[name] = Util.mkEvent(true); if (typeof data === 'undefined') { + if (/^http/.test(name) && /slide\/themes\/theme/.test(name)) { + Util.fetch(name, function (err, u8) { + if (err) { return; } + mediasData[name] = { + blobUrl: name, + content: u8, + name: name + }; + var b = new Blob([u8], {type: "image/jpeg"}); + var blobUrl = URL.createObjectURL(b); + return void callback(blobUrl); + }); + return; + } debug("CryptPad - could not find matching media for " + name); return void callback(""); } - var blobUrl = (typeof mediasData[data.src] === 'undefined') ? "" : mediasData[data.src].src; + var blobUrl = (typeof mediasData[data.src] === 'undefined') ? "" : mediasData[data.src].blobUrl; if (blobUrl) { debug("CryptPad Image already loaded " + blobUrl); return void callback(blobUrl); @@ -1680,12 +1911,17 @@ define([ try { var blobUrl = URL.createObjectURL(res.content); // store media blobUrl and content for cache and export - var mediaData = { blobUrl : blobUrl, content : "" }; + var mediaData = { + blobUrl : blobUrl, + content : "", + name: name + }; mediasData[data.src] = mediaData; var reader = new FileReader(); reader.onloadend = function () { debug("MediaData set"); mediaData.content = reader.result; + downloadImages[name].fire(); }; reader.readAsArrayBuffer(res.content); debug("Adding CryptPad Image " + data.name + ": " + blobUrl); @@ -1707,239 +1943,55 @@ define([ makeChannel(); }; - var x2tReady = Util.mkEvent(true); - var fetchFonts = function (x2t) { - var path = '/common/onlyoffice/'+CURRENT_VERSION+'/fonts/'; - var e = getEditor(); - var fonts = e.FontLoader.fontInfos; - var files = e.FontLoader.fontFiles; - var suffixes = { - indexR: '', - indexB: '_Bold', - indexBI: '_Bold_Italic', - indexI: '_Italic', - }; - nThen(function (waitFor) { - fonts.forEach(function (font) { - // Check if the font is already loaded - if (!font.NeedStyles) { return; } - // Pick the variants we need (regular, bold, italic) - ['indexR', 'indexB', 'indexI', 'indexBI'].forEach(function (k) { - if (typeof(font[k]) !== "number" || font[k] === -1) { return; } // No matching file - var file = files[font[k]]; - - var name = font.Name + suffixes[k] + '.ttf'; - Util.fetch(path + file.Id, waitFor(function (err, buffer) { - if (buffer) { - x2t.FS.writeFile('/working/fonts/' + name, buffer); - } - })); - }); - }); - }).nThen(function () { - x2tReady.fire(); - }); - }; - - var x2tInitialized = false; - var x2tInit = function(x2t) { - debug("x2t mount"); - // x2t.FS.mount(x2t.MEMFS, {} , '/'); - x2t.FS.mkdir('/working'); - x2t.FS.mkdir('/working/media'); - x2t.FS.mkdir('/working/fonts'); - x2tInitialized = true; - fetchFonts(x2t); - debug("x2t mount done"); - }; - var getX2T = function (cb) { - // Perform the x2t conversion - require(['/common/onlyoffice/x2t/x2t.js'], function() { // FIXME why does this fail without an access-control-allow-origin header? - var x2t = window.Module; - x2t.run(); - if (x2tInitialized) { - debug("x2t runtime already initialized"); - return void x2tReady.reg(function () { - cb(x2t); - }); - } - - x2t.onRuntimeInitialized = function() { - debug("x2t in runtime initialized"); - // Init x2t js module - x2tInit(x2t); - x2tReady.reg(function () { - cb(x2t); - }); - }; - }); - }; - - - /* - Converting Data - - This function converts a data in a specific format to the outputformat - The filename extension needs to represent the input format - Example: fileName=cryptpad.bin outputFormat=xlsx - */ - var getFormatId = function (ext) { - // Sheets - if (ext === 'xlsx') { return 257; } - if (ext === 'xls') { return 258; } - if (ext === 'ods') { return 259; } - if (ext === 'csv') { return 260; } - if (ext === 'pdf') { return 513; } - return; - }; - var getFromId = function (ext) { - var id = getFormatId(ext); - if (!id) { return ''; } - return ''+id+''; - }; - var getToId = function (ext) { - var id = getFormatId(ext); - if (!id) { return ''; } - return ''+id+''; - }; - var x2tConvertDataInternal = function(x2t, data, fileName, outputFormat) { - debug("Converting Data for " + fileName + " to " + outputFormat); - - // PDF - var pdfData = ''; - if (outputFormat === "pdf" && typeof(data) === "object" && data.bin && data.buffer) { - // Add conversion rules - pdfData = "false" + - "/working/fonts/"; - // writing file to mounted working disk (in memory) - x2t.FS.writeFile('/working/' + fileName, data.bin); - x2t.FS.writeFile('/working/pdf.bin', data.buffer); - } else { - // writing file to mounted working disk (in memory) - x2t.FS.writeFile('/working/' + fileName, data); - } - - // Adding images - Object.keys(window.frames[0].AscCommon.g_oDocumentUrls.urls || {}).forEach(function (_mediaFileName) { - var mediaFileName = _mediaFileName.substring(6); - var mediasSources = getMediasSources(); - var mediaSource = mediasSources[mediaFileName]; - var mediaData = mediaSource ? mediasData[mediaSource.src] : undefined; - if (mediaData) { - debug("Writing media data " + mediaFileName); - debug("Data"); - var fileData = mediaData.content; - x2t.FS.writeFile('/working/media/' + mediaFileName, new Uint8Array(fileData)); - } else { - debug("Could not find media content for " + mediaFileName); - } - }); - - - var inputFormat = fileName.split('.').pop(); - - var params = "" - + "" - + "/working/" + fileName + "" - + "/working/" + fileName + "." + outputFormat + "" - + pdfData - + getFromId(inputFormat) - + getToId(outputFormat) - + "false" - + ""; - // writing params file to mounted working disk (in memory) - x2t.FS.writeFile('/working/params.xml', params); - // running conversion - x2t.ccall("runX2T", ["number"], ["string"], ["/working/params.xml"]); - // reading output file from working disk (in memory) - var result; - try { - result = x2t.FS.readFile('/working/' + fileName + "." + outputFormat); - } catch (e) { - debug("Failed reading converted file"); - UI.removeModals(); - UI.warn(Messages.error); - return ""; - } - return result; - }; - APP.printPdf = function (obj, cb) { - getX2T(function (x2t) { - //var e = getEditor(); - //var d = e.asc_nativePrint(undefined, undefined, 0x100 + opts.printType).ImData; - var bin = getContent(); - var xlsData = x2tConvertDataInternal(x2t, { - buffer: obj.data, - bin: bin - }, 'output.bin', 'pdf'); - if (xlsData) { - var md = common.getMetadataMgr().getMetadataLazy(); - var type = common.getMetadataMgr().getPrivateData().ooType; - var title = md.title || md.defaultTitle || type; - var blob = new Blob([xlsData], {type: "application/pdf"}); - //var url = URL.createObjectURL(blob, { type: "application/pdf" }); - saveAs(blob, title+'.pdf'); - //window.open(url); - cb({ - "type":"save", - "status":"ok", - //"data":url + "?disposition=inline&ooname=output.pdf" - }); - /* - ooChannel.send({ - "type":"documentOpen", - "data": { - "type":"save", - "status":"ok", - "data":url + "?disposition=inline&ooname=output.pdf" - } - }); - */ - } + var bin = getContent(); + x2tConvertData({ + buffer: obj.data, + bin: bin + }, 'output.bin', 'pdf', function (xlsData) { + if (!xlsData) { return; } + var md = common.getMetadataMgr().getMetadataLazy(); + var type = common.getMetadataMgr().getPrivateData().ooType; + var title = md.title || md.defaultTitle || type; + var blob = new Blob([xlsData], {type: "application/pdf"}); + UI.removeModals(); + cb(); + saveAs(blob, APP.exportPdfName || title+'.pdf'); + delete APP.exportPdfName; }); }; - var x2tSaveAndConvertDataInternal = function(x2t, data, filename, extension, finalFilename) { + var x2tSaveAndConvertData = function(data, filename, extension, finalFilename) { var type = common.getMetadataMgr().getPrivateData().ooType; - var xlsData; + var e = getEditor(); // PDF if (type === "sheet" && extension === "pdf") { - var e = getEditor(); var d = e.asc_nativePrint(undefined, undefined, 0x101).ImData; - xlsData = x2tConvertDataInternal(x2t, { + x2tConvertData({ buffer: d.data, bin: data - }, filename, extension); - if (xlsData) { - var _blob = new Blob([xlsData], {type: "application/bin;charset=utf-8"}); - UI.removeModals(); - saveAs(_blob, finalFilename); - } + }, filename, extension, function (res) { + if (res) { + var _blob = new Blob([res], {type: "application/pdf;charset=utf-8"}); + UI.removeModals(); + saveAs(_blob, finalFilename); + } + }); return; } - if (type === "sheet" && extension !== 'xlsx') { - xlsData = x2tConvertDataInternal(x2t, data, filename, 'xlsx'); - filename += '.xlsx'; - } else if (type === "presentation" && extension !== "pptx") { - xlsData = x2tConvertDataInternal(x2t, data, filename, 'pptx'); - filename += '.pptx'; - } else if (type === "doc" && extension !== "docx") { - xlsData = x2tConvertDataInternal(x2t, data, filename, 'docx'); - filename += '.docx'; - } - xlsData = x2tConvertDataInternal(x2t, data, filename, extension); - if (xlsData) { - var blob = new Blob([xlsData], {type: "application/bin;charset=utf-8"}); - UI.removeModals(); - saveAs(blob, finalFilename); + if (extension === "pdf") { + APP.exportPdfName = finalFilename; + return void e.asc_Print({}); } - }; - - var x2tSaveAndConvertData = function(data, filename, extension, finalName) { - getX2T(function (x2t) { - x2tSaveAndConvertDataInternal(x2t, data, filename, extension, finalName); + x2tConvertData(data, filename, extension, function (xlsData) { + if (xlsData) { + var blob = new Blob([xlsData], {type: "application/bin;charset=utf-8"}); + UI.removeModals(); + saveAs(blob, finalFilename); + return; + } + UI.warn(Messages.error); }); }; @@ -1952,9 +2004,9 @@ define([ var type = common.getMetadataMgr().getPrivateData().ooType; var warning = ''; if (type==="presentation") { - ext = ['.pptx', /*'.odp',*/ '.bin']; + ext = ['.pptx', '.odp', '.bin', '.pdf']; } else if (type==="doc") { - ext = ['.docx', /*'.odt',*/ '.bin']; + ext = ['.docx', '.odt', '.bin', '.pdf']; } if (!supportsXLSX()) { @@ -2012,32 +2064,29 @@ define([ $select.find('button').addClass('btn'); }; - var x2tImportImagesInternal = function(x2t, images, i, callback) { + var x2tImportImagesInternal = function(images, i, callback) { if (i >= images.length) { callback(); } else { debug("Import image " + i); var handleFileData = { - name: images[i], + name: images[i].name, mediasSources: getMediasSources(), callback: function() { debug("next image"); - x2tImportImagesInternal(x2t, images, i+1, callback); + x2tImportImagesInternal(images, i+1, callback); }, }; - var filePath = "/working/media/" + images[i]; - debug("Import filename " + filePath); - var fileData = x2t.FS.readFile("/working/media/" + images[i], { encoding : "binary" }); - debug("Importing data"); + var fileData = images[i].data; debug("Buffer"); debug(fileData.buffer); var blob = new Blob([fileData.buffer], {type: 'image/png'}); - blob.name = images[i]; + blob.name = images[i].name; APP.FMImages.handleFile(blob, handleFileData); } }; - var x2tImportImages = function (x2t, callback) { + var x2tImportImages = function (images, callback) { if (!APP.FMImages) { var fmConfigImages = { noHandlers: true, @@ -2063,14 +2112,8 @@ define([ // Import Images debug("Import Images"); - var files = x2t.FS.readdir("/working/media/"); - var images = []; - files.forEach(function (file) { - if (file !== "." && file !== "..") { - images.push(file); - } - }); - x2tImportImagesInternal(x2t, images, 0, function() { + debug(images); + x2tImportImagesInternal(images, 0, function() { debug("Sync media sources elements"); debug(getMediasSources()); APP.onLocal(); @@ -2080,26 +2123,12 @@ define([ }; - var x2tConvertData = function (x2t, data, filename, extension, callback) { - var convertedContent; - // Convert from ODF format: - // first convert to Office format then to the selected extension - if (filename.endsWith(".ods")) { - console.log(x2t, data, filename, extension); - convertedContent = x2tConvertDataInternal(x2t, new Uint8Array(data), filename, "xlsx"); - console.log(convertedContent); - convertedContent = x2tConvertDataInternal(x2t, convertedContent, filename + ".xlsx", extension); - } else if (filename.endsWith(".odt")) { - convertedContent = x2tConvertDataInternal(x2t, new Uint8Array(data), filename, "docx"); - convertedContent = x2tConvertDataInternal(x2t, convertedContent, filename + ".docx", extension); - } else if (filename.endsWith(".odp")) { - convertedContent = x2tConvertDataInternal(x2t, new Uint8Array(data), filename, "pptx"); - convertedContent = x2tConvertDataInternal(x2t, convertedContent, filename + ".pptx", extension); - } else { - convertedContent = x2tConvertDataInternal(x2t, new Uint8Array(data), filename, extension); - } - x2tImportImages(x2t, function() { - callback(convertedContent); + var x2tImportData = function (data, filename, extension, callback) { + x2tConvertData(new Uint8Array(data), filename, extension, function (binData, images) { + if (!binData) { return void callback(); } + x2tImportImages(images, function() { + callback(binData); + }); }); }; @@ -2153,10 +2182,12 @@ define([ ]); UI.openCustomModal(UI.dialog.customModal(div, {buttons: []})); setTimeout(function () { - getX2T(function (x2t) { - x2tConvertData(x2t, new Uint8Array(content), filename.name, "bin", function(c) { - importFile(c); - }); + x2tImportData(new Uint8Array(content), filename.name, "bin", function(c) { + if (!c) { + UI.removeModals(); + return void UI.warn(Messages.error); + } + importFile(c); }); }, 100); }; @@ -2382,6 +2413,40 @@ define([ }); }; + sframeChan.on('EV_OOIFRAME_REFRESH', function (data) { + // We want to get the "bin" content of a sheet from its json in order to download + // something useful from a non-onlyoffice app (download from drive or settings). + // We don't want to initialize a full pad in async-store because we only need a + // static version, so we can use "openVersionHash" which is based on GET_HISTORY_RANGE + APP.isDownload = data.downloadId; + APP.downloadType = data.type; + downloadImages = {}; + var json = data && data.json; + if (!json || !json.content) { + return void sframeChan.event('EV_OOIFRAME_DONE', ''); + } + content = json.content; + readOnly = true; + var version = (!content.version || content.version === 1) ? 'v1/' : + (content.version <= 3 ? 'v2b/' : CURRENT_VERSION+'/'); + var s = h('script', { + type:'text/javascript', + src: '/common/onlyoffice/'+version+'web-apps/apps/api/documents/api.js' + }); + $('#cp-app-oo-editor').append(s); + + var hashes = content.hashes || {}; + var idx = sortCpIndex(hashes); + var lastIndex = idx[idx.length - 1]; + + // We're going to open using "openVersionHash" to avoid reimplementing existing code. + // To do so, we're using a version corresponding to the latest checkpoint with a + // minor version of 0. "openVersionHash" knows that it needs to give us the latest + // version when "APP.isDownload" is true. + var sheetVersion = lastIndex + '.0'; + openVersionHash(sheetVersion); + }); + config.onInit = function (info) { var privateData = metadataMgr.getPrivateData(); metadataMgr.setDegraded(false); // FIXME degraded moded unsupported (no cursor channel) @@ -2414,6 +2479,26 @@ define([ makeCheckpoint(true); }); $save.appendTo(toolbar.$bottomM); + + var $dlMedias = common.createButton('', true, { + name: 'dlmedias', + icon: 'fa-download', + }, function () { + require(['/bower_components/jszip/dist/jszip.min.js'], function (JsZip) { + var zip = new JsZip(); + Object.keys(mediasData || {}).forEach(function (url) { + var obj = mediasData[url]; + var b = new Blob([obj.content]); + zip.file(obj.name, b, {binary: true}); + }); + setTimeout(function () { + zip.generateAsync({type: 'blob'}).then(function (content) { + saveAs(content, 'media.zip'); + }); + }, 100); + }); + }).attr('title', "Download medias"); + $dlMedias.appendTo(toolbar.$bottomM); } if (!privateData.ooVersionHash) { @@ -2655,6 +2740,8 @@ define([ Title.updateTitle(Title.defaultTitle); } + APP.startNew = isNew; + var version = CURRENT_VERSION + '/'; var msg; // Old version detected: use the old OO and start the migration if we can @@ -2695,6 +2782,7 @@ define([ readOnly = true; } } + // NOTE: don't forget to also update the version in 'EV_OOIFRAME_REFRESH' // If the sheet is locked by an offline user, remove it if (content && content.saveLock && !isUserOnline(content.saveLock)) { @@ -2737,6 +2825,18 @@ define([ oldHashes = JSON.parse(JSON.stringify(content.hashes)); initializing = false; + // If we have more than CHECKPOINT_INTERVAL patches in the initial history + // and we're the only editor in the pad, make a checkpoint + var v = metadataMgr.getViewers(); + var m = metadataMgr.getChannelMembers().filter(function (str) { + return str.length === 32; + }).length; + if ((m - v) === 1 && !readOnly) { + var needCp = ooChannel.queue.length > CHECKPOINT_INTERVAL; + APP.initCheckpoint = needCp; + } + + common.openPadChat(APP.onLocal); if (!readOnly) { @@ -2782,9 +2882,102 @@ define([ return; } - loadDocument(newDoc, useNewDefault); - setEditable(!readOnly); - UI.removeLoadingScreen(); + var next = function () { + loadDocument(newDoc, useNewDefault); + setEditable(!readOnly); + UI.removeLoadingScreen(); + }; + + if (privateData.isNewFile && privateData.fromFileData) { + try { + (function () { + var data = privateData.fromFileData; + + var type = data.fileType; + var title = data.title; + // Fix extension if the file was renamed + if (Util.isSpreadsheet(type) && !Util.isSpreadsheet(data.title)) { + if (type === 'application/vnd.oasis.opendocument.spreadsheet') { + data.title += '.ods'; + } + if (type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') { + data.title += '.xlsx'; + } + } + if (Util.isOfficeDoc(type) && !Util.isOfficeDoc(data.title)) { + if (type === 'application/vnd.oasis.opendocument.text') { + data.title += '.odt'; + } + if (type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') { + data.title += '.docx'; + } + } + if (Util.isPresentation(type) && !Util.isPresentation(data.title)) { + if (type === 'application/vnd.oasis.opendocument.presentation') { + data.title += '.odp'; + } + if (type === 'application/vnd.openxmlformats-officedocument.presentationml.presentation') { + data.title += '.pptx'; + } + } + + var href = data.href; + var password = data.password; + var parsed = Hash.parsePadUrl(href); + var secret = Hash.getSecrets('file', parsed.hash, password); + var hexFileName = secret.channel; + var fileHost = privateData.fileHost || privateData.origin; + var src = fileHost + Hash.getBlobPathFromHex(hexFileName); + var key = secret.keys && secret.keys.cryptKey; + var xhr = new XMLHttpRequest(); + xhr.open('GET', src, true); + xhr.responseType = 'arraybuffer'; + xhr.onload = function () { + if (/^4/.test('' + this.status)) { + // fallback to empty sheet + console.error(this.status); + return void next(); + } + var arrayBuffer = xhr.response; + if (arrayBuffer) { + var u8 = new Uint8Array(arrayBuffer); + FileCrypto.decrypt(u8, key, function (err, decrypted) { + if (err) { + // fallback to empty sheet + console.error(err); + return void next(); + } + var blobXlsx = decrypted.content; + new Response(blobXlsx).arrayBuffer().then(function (buffer) { + var u8Xlsx = new Uint8Array(buffer); + x2tImportData(u8Xlsx, data.title, 'bin', function (bin) { + if (!bin) { + return void UI.errorLoadingScreen(Messages.error); + } + var blob = new Blob([bin], {type: 'text/plain'}); + saveToServer(blob, data.title); + Title.updateTitle(title); + UI.removeLoadingScreen(); + }); + }); + }); + } + }; + xhr.onerror = function (err) { + // fallback to empty sheet + console.error(err); + next(); + }; + xhr.send(null); + })(); + } catch (e) { + console.error(e); + next(); + } + return; + } + + next(); }); }; diff --git a/www/common/onlyoffice/main.js b/www/common/onlyoffice/main.js index b7626a589..8b79474ae 100644 --- a/www/common/onlyoffice/main.js +++ b/www/common/onlyoffice/main.js @@ -143,6 +143,22 @@ define([ } sframeChan.event('EV_OO_EVENT', obj); }); + + // X2T + var x2t; + var onConvert = function (obj, cb) { + x2t.convert(obj, cb); + }; + sframeChan.on('Q_OO_CONVERT', function (obj, cb) { + if (x2t) { return void onConvert(obj, cb); } + require(['/common/outer/x2t.js'], function (X2T) { + x2t = X2T.start(); + onConvert(obj, cb); + }); + }); + + + }; SFCommonO.start({ hash: hash, diff --git a/www/common/onlyoffice/ooiframe.js b/www/common/onlyoffice/ooiframe.js new file mode 100644 index 000000000..097d21e5e --- /dev/null +++ b/www/common/onlyoffice/ooiframe.js @@ -0,0 +1,176 @@ +// Load #1, load as little as possible because we are in a race to get the loading screen up. +define([ + '/bower_components/nthen/index.js', + '/api/config', + 'jquery', + '/common/requireconfig.js', + '/customize/messages.js', +], function (nThen, ApiConfig, $, RequireConfig, Messages) { + var requireConfig = RequireConfig(); + + var ready = false; + var currentCb; + var queue = []; + + var create = function (config) { + // Loaded in load #2 + var sframeChan; + var refresh = function (data, cb) { + if (currentCb) { + queue.push({data: data, cb: cb}); + return; + } + if (!ready) { + ready = function () { + refresh(data, cb); + }; + return; + } + currentCb = cb; + sframeChan.event('EV_OOIFRAME_REFRESH', data); + }; + nThen(function (waitFor) { + $(waitFor()); + }).nThen(function (waitFor) { + var lang = Messages._languageUsed; + var themeKey = 'CRYPTPAD_STORE|colortheme'; + var req = { + cfg: requireConfig, + req: [ '/common/loading.js' ], + pfx: window.location.origin, + theme: localStorage[themeKey], + themeOS: localStorage[themeKey+'_default'], + lang: lang + }; + window.rc = requireConfig; + window.apiconf = ApiConfig; + $('#sbox-oo-iframe').attr('src', + ApiConfig.httpSafeOrigin + '/sheet/inner.html?' + requireConfig.urlArgs + + '#' + encodeURIComponent(JSON.stringify(req))); + + // This is a cheap trick to avoid loading sframe-channel in parallel with the + // loading screen setup. + var done = waitFor(); + var onMsg = function (msg) { + var data = typeof(msg.data) === "object" ? msg.data : JSON.parse(msg.data); + if (data.q !== 'READY') { return; } + window.removeEventListener('message', onMsg); + var _done = done; + done = function () { }; + _done(); + }; + window.addEventListener('message', onMsg); + }).nThen(function (/*waitFor*/) { + var Cryptpad = config.modules.Cryptpad; + var Utils = config.modules.Utils; + + nThen(function (waitFor) { + // The inner iframe tries to get some data from us every ms (cache, store...). + // It will send a "READY" message and wait for our answer with the correct txid. + // First, we have to answer to this message, otherwise we're going to block + // sframe-boot.js. Then we can start the channel. + var msgEv = Utils.Util.mkEvent(); + var iframe = $('#sbox-oo-iframe')[0].contentWindow; + var postMsg = function (data) { + iframe.postMessage(data, '*'); + }; + var w = waitFor(); + var whenReady = function (msg) { + if (msg.source !== iframe) { return; } + var data = JSON.parse(msg.data); + if (!data.txid) { return; } + // Remove the listener once we've received the READY message + window.removeEventListener('message', whenReady); + // Answer with the requested data + postMsg(JSON.stringify({ txid: data.txid, language: Cryptpad.getLanguage(), localStore: window.localStore, cache: window.cpCache })); + + // Then start the channel + window.addEventListener('message', function (msg) { + if (msg.source !== iframe) { return; } + msgEv.fire(msg); + }); + config.modules.SFrameChannel.create(msgEv, postMsg, waitFor(function (sfc) { + sframeChan = sfc; + })); + w(); + }; + window.addEventListener('message', whenReady); + }).nThen(function () { + var updateMeta = function () { + //console.log('EV_METADATA_UPDATE'); + var metaObj; + nThen(function (waitFor) { + Cryptpad.getMetadata(waitFor(function (err, n) { + if (err) { + waitFor.abort(); + return void console.log(err); + } + metaObj = n; + })); + }).nThen(function (/*waitFor*/) { + metaObj.doc = {}; + var additionalPriv = { + fileHost: ApiConfig.fileHost, + loggedIn: Utils.LocalStore.isLoggedIn(), + origin: window.location.origin, + pathname: window.location.pathname, + feedbackAllowed: Utils.Feedback.state, + secureIframe: true, + supportsWasm: Utils.Util.supportsWasm() + }; + for (var k in additionalPriv) { metaObj.priv[k] = additionalPriv[k]; } + + sframeChan.event('EV_METADATA_UPDATE', metaObj); + }); + }; + Cryptpad.onMetadataChanged(updateMeta); + sframeChan.onReg('EV_METADATA_UPDATE', updateMeta); + + config.addCommonRpc(sframeChan, true); + + Cryptpad.padRpc.onMetadataEvent.reg(function (data) { + sframeChan.event('EV_RT_METADATA', data); + }); + + sframeChan.on('EV_OOIFRAME_DONE', function (data) { + if (queue.length) { + setTimeout(function () { + var first = queue.shift(); + refresh(first.data, first.cb); + }); + } + if (!currentCb) { return; } + currentCb(data); + currentCb = undefined; + }); + + // X2T + var x2t; + var onConvert = function (obj, cb) { + x2t.convert(obj, cb); + }; + sframeChan.on('Q_OO_CONVERT', function (obj, cb) { + if (x2t) { return void onConvert(obj, cb); } + require(['/common/outer/x2t.js'], function (X2T) { + x2t = X2T.start(); + onConvert(obj, cb); + }); + }); + + sframeChan.onReady(function () { + if (ready === true) { return; } + if (typeof ready === "function") { + ready(); + } + ready = true; + }); + }); + }); + return { + refresh: refresh + }; + }; + return { + create: create + }; +}); diff --git a/www/common/onlyoffice/v4/sdkjs/cell/sdk-all-min.js b/www/common/onlyoffice/v4/sdkjs/cell/sdk-all-min.js index d54170dd3..8eb557699 100644 --- a/www/common/onlyoffice/v4/sdkjs/cell/sdk-all-min.js +++ b/www/common/onlyoffice/v4/sdkjs/cell/sdk-all-min.js @@ -268,13 +268,13 @@ editorType;this._isExcel=c_oEditorId.Spreadsheet===editorType;this._isPresentati docid;this.sockjs_url=AscCommon.getBaseUrl()+"../../../../doc/"+docid+"/c"};DocsCoApi.prototype.auth=function(isViewer,opt_openCmd,opt_isIdle){this._isViewer=isViewer;if(this._locks){this.ownedLockBlocks=[];for(var block in this._locks)if(this._locks.hasOwnProperty(block)){var lock=this._locks[block];if(lock["state"]===2)this.ownedLockBlocks.push(lock["blockValue"])}this._locks={}}this._send({"type":"auth","docid":this._docid,"documentCallbackUrl":this._documentCallbackUrl,"token":this._token,"user":{"id":this._user.asc_getId(), "username":this._user.asc_getUserName(),"firstname":this._user.asc_getFirstName(),"lastname":this._user.asc_getLastName(),"indexUser":this._indexUser},"editorType":this.editorType,"lastOtherSaveTime":this.lastOtherSaveTime,"block":this.ownedLockBlocks,"sessionId":this._id,"sessionTimeConnect":this._sessionTimeConnect,"sessionTimeIdle":opt_isIdle>=0?opt_isIdle:0,"documentFormatSave":this._documentFormatSave,"view":this._isViewer,"isCloseCoAuthoring":this.isCloseCoAuthoring,"openCmd":opt_openCmd,"lang":this.lang, "mode":this.mode,"permissions":this.permissions,"encrypted":this.encrypted,"jwtOpen":this.jwtOpen,"jwtSession":this.jwtSession})};DocsCoApi.prototype._initSocksJs=function(){var t=this;var sockjs;sockjs=this.sockjs={};var send=function(data){setTimeout(function(){sockjs.onmessage({data:JSON.stringify(data)})})};var license={type:"license",license:{type:3,mode:0,rights:1,buildVersion:"5.2.6",buildNumber:2}};var channel;require(["/common/outer/worker-channel.js","/common/common-util.js"],function(Channel, -Util){var msgEv=Util.mkEvent();var p=window.parent;window.addEventListener("message",function(msg){if(msg.source!==p)return;msgEv.fire(msg)});var postMsg=function(data){p.postMessage(data,"*")};Channel.create(msgEv,postMsg,function(chan){channel=chan;send(license);chan.on("CMD",function(obj){send(obj)})})});sockjs.onopen=function(){t._state=ConnectionState.WaitAuth;t.onFirstConnect()};sockjs.onopen();sockjs.close=function(){console.error("Close realtime")};sockjs.send=function(data){try{var obj=JSON.parse(data)}catch(e){console.error(e); -return}if(channel)channel.event("CMD",obj)};sockjs.onmessage=function(e){t._onServerMessage(e.data)};return sockjs};DocsCoApi.prototype._onServerOpen=function(){if(this.reconnectTimeout){clearTimeout(this.reconnectTimeout);this.reconnectTimeout=null;this.attemptCount=0}this._state=ConnectionState.WaitAuth;this.onFirstConnect()};DocsCoApi.prototype._onServerMessage=function(data){var dataObject=JSON.parse(data);switch(dataObject["type"]){case "auth":this._onAuth(dataObject);break;case "message":this._onMessages(dataObject, -false);break;case "cursor":this._onCursor(dataObject);break;case "meta":this._onMeta(dataObject);break;case "getLock":this._onGetLock(dataObject);break;case "releaseLock":this._onReleaseLock(dataObject);break;case "connectState":this._onConnectionStateChanged(dataObject);break;case "saveChanges":this._onSaveChanges(dataObject);break;case "authChanges":this._onAuthChanges(dataObject);break;case "saveLock":this._onSaveLock(dataObject);break;case "unSaveLock":this._onUnSaveLock(dataObject);break;case "savePartChanges":this._onSavePartChanges(dataObject); -break;case "drop":this._onDrop(dataObject);break;case "waitAuth":break;case "error":this._onDrop(dataObject);break;case "documentOpen":this._documentOpen(dataObject);break;case "warning":this._onWarning(dataObject);break;case "license":this._onLicense(dataObject);break;case "session":this._onSession(dataObject);break;case "refreshToken":this._onRefreshToken(dataObject["messages"]);break;case "expiredToken":this._onExpiredToken(dataObject);break;case "forceSaveStart":this._onForceSaveStart(dataObject["messages"]); -break;case "forceSave":this._onForceSave(dataObject["messages"]);break}};DocsCoApi.prototype._onServerClose=function(evt){if(ConnectionState.SaveChanges===this._state){this._isReSaveAfterAuth=true;if(null!==this.saveCallbackErrorTimeOutId){clearTimeout(this.saveCallbackErrorTimeOutId);this.saveCallbackErrorTimeOutId=null}}this._state=ConnectionState.Reconnect;var bIsDisconnectAtAll=c_oCloseCode.serverShutdown<=evt.code&&evt.code<=c_oCloseCode.drop||this.attemptCount>=this.maxAttemptCount;var code= -null;if(bIsDisconnectAtAll){this._state=ConnectionState.ClosedAll;code=evt.code}if(this.onDisconnect)this.onDisconnect(evt.reason,code);if(!bIsDisconnectAtAll)this._tryReconnect()};DocsCoApi.prototype._reconnect=function(){delete this.sockjs;this._initSocksJs()};DocsCoApi.prototype._tryReconnect=function(){var t=this;if(this.reconnectTimeout){clearTimeout(this.reconnectTimeout);t.reconnectTimeout=null}++this.attemptCount;this.reconnectTimeout=setTimeout(function(){t._reconnect()},this.reconnectInterval)}; -window["AscCommon"]=window["AscCommon"]||{};window["AscCommon"].CDocsCoApi=CDocsCoApi})(window);"use strict"; +Util){var msgEv=Util.mkEvent();var p=window.parent;if(editor&&editor.isReporterMode){p=window.opener;window.parent=p}else window.APP=p&&p.APP;window.addEventListener("message",function(msg){if(msg.source!==p)return;msgEv.fire(msg)});var postMsg=function(data){p.postMessage(data,"*")};Channel.create(msgEv,postMsg,function(chan){channel=chan;send(license);chan.on("CMD",function(obj){send(obj)})})});sockjs.onopen=function(){t._state=ConnectionState.WaitAuth;t.onFirstConnect()};sockjs.onopen();sockjs.close= +function(){console.error("Close realtime")};sockjs.send=function(data){try{var obj=JSON.parse(data)}catch(e){console.error(e);return}if(channel)channel.event("CMD",obj)};sockjs.onmessage=function(e){t._onServerMessage(e.data)};return sockjs};DocsCoApi.prototype._onServerOpen=function(){if(this.reconnectTimeout){clearTimeout(this.reconnectTimeout);this.reconnectTimeout=null;this.attemptCount=0}this._state=ConnectionState.WaitAuth;this.onFirstConnect()};DocsCoApi.prototype._onServerMessage=function(data){var dataObject= +JSON.parse(data);switch(dataObject["type"]){case "auth":this._onAuth(dataObject);break;case "message":this._onMessages(dataObject,false);break;case "cursor":this._onCursor(dataObject);break;case "meta":this._onMeta(dataObject);break;case "getLock":this._onGetLock(dataObject);break;case "releaseLock":this._onReleaseLock(dataObject);break;case "connectState":this._onConnectionStateChanged(dataObject);break;case "saveChanges":this._onSaveChanges(dataObject);break;case "authChanges":this._onAuthChanges(dataObject); +break;case "saveLock":this._onSaveLock(dataObject);break;case "unSaveLock":this._onUnSaveLock(dataObject);break;case "savePartChanges":this._onSavePartChanges(dataObject);break;case "drop":this._onDrop(dataObject);break;case "waitAuth":break;case "error":this._onDrop(dataObject);break;case "documentOpen":this._documentOpen(dataObject);break;case "warning":this._onWarning(dataObject);break;case "license":this._onLicense(dataObject);break;case "session":this._onSession(dataObject);break;case "refreshToken":this._onRefreshToken(dataObject["messages"]); +break;case "expiredToken":this._onExpiredToken(dataObject);break;case "forceSaveStart":this._onForceSaveStart(dataObject["messages"]);break;case "forceSave":this._onForceSave(dataObject["messages"]);break}};DocsCoApi.prototype._onServerClose=function(evt){if(ConnectionState.SaveChanges===this._state){this._isReSaveAfterAuth=true;if(null!==this.saveCallbackErrorTimeOutId){clearTimeout(this.saveCallbackErrorTimeOutId);this.saveCallbackErrorTimeOutId=null}}this._state=ConnectionState.Reconnect;var bIsDisconnectAtAll= +c_oCloseCode.serverShutdown<=evt.code&&evt.code<=c_oCloseCode.drop||this.attemptCount>=this.maxAttemptCount;var code=null;if(bIsDisconnectAtAll){this._state=ConnectionState.ClosedAll;code=evt.code}if(this.onDisconnect)this.onDisconnect(evt.reason,code);if(!bIsDisconnectAtAll)this._tryReconnect()};DocsCoApi.prototype._reconnect=function(){delete this.sockjs;this._initSocksJs()};DocsCoApi.prototype._tryReconnect=function(){var t=this;if(this.reconnectTimeout){clearTimeout(this.reconnectTimeout);t.reconnectTimeout= +null}++this.attemptCount;this.reconnectTimeout=setTimeout(function(){t._reconnect()},this.reconnectInterval)};window["AscCommon"]=window["AscCommon"]||{};window["AscCommon"].CDocsCoApi=CDocsCoApi})(window);"use strict"; (function(window){var CSpellCheckApi=function(){this._SpellCheckApi=new SpellCheckApi;this._onlineWork=false;this.onDisconnect=null;this.onSpellCheck=null};CSpellCheckApi.prototype.init=function(docid){if(this._SpellCheckApi&&this._SpellCheckApi.isRightURL()){var t=this;this._SpellCheckApi.onDisconnect=function(e,isDisconnectAtAll,isCloseCoAuthoring){t.callback_OnDisconnect(e,isDisconnectAtAll,isCloseCoAuthoring)};this._SpellCheckApi.onSpellCheck=function(e){t.callback_OnSpellCheck(e)};this._SpellCheckApi.onInit= function(e){t.callback_OnInit(e)};this._SpellCheckApi.init(docid);this._onlineWork=true}};CSpellCheckApi.prototype.set_url=function(url){if(this._SpellCheckApi)this._SpellCheckApi.set_url(url)};CSpellCheckApi.prototype.get_state=function(){if(this._SpellCheckApi)return this._SpellCheckApi.get_state();return 0};CSpellCheckApi.prototype.disconnect=function(){if(this._SpellCheckApi&&this._onlineWork)this._SpellCheckApi.disconnect()};CSpellCheckApi.prototype.spellCheck=function(spellCheckData){if(this._SpellCheckApi&& this._onlineWork)this._SpellCheckApi.spellCheck(spellCheckData)};CSpellCheckApi.prototype.checkDictionary=function(lang){if(this._SpellCheckApi&&this._onlineWork)return this._SpellCheckApi.checkDictionary(lang);return true};CSpellCheckApi.prototype.callback_OnSpellCheck=function(e){if(this.onSpellCheck)return this.onSpellCheck(e)};CSpellCheckApi.prototype.callback_OnInit=function(e){if(this.onInit)return this.onInit(e)};CSpellCheckApi.prototype.callback_OnDisconnect=function(e,isDisconnectAtAll,isCloseCoAuthoring){if(this.onDisconnect)return this.onDisconnect(e, @@ -1657,39 +1657,39 @@ function(){};baseEditorsApi.prototype._downloadAs=function(){};baseEditorsApi.pr actionType===c_oAscAsyncAction.Print?DownloadType.Print:DownloadType.Download;else downloadType=DownloadType.None;var isNoBase64=typeof ArrayBuffer!=="undefined"&&!isCloudCrypto;var dataContainer={data:null,part:null,index:0,count:0};var oAdditionalData={};oAdditionalData["c"]="save";oAdditionalData["id"]=this.documentId;oAdditionalData["userid"]=this.documentUserId;oAdditionalData["tokenSession"]=this.CoAuthoringApi.get_jwt();oAdditionalData["outputformat"]=options.fileType;oAdditionalData["title"]= AscCommon.changeFileExtention(this.documentTitle,AscCommon.getExtentionByFormat(options.fileType),Asc.c_nMaxDownloadTitleLen);oAdditionalData["nobase64"]=isNoBase64;if(DownloadType.Print===downloadType)oAdditionalData["inline"]=1;if(this._downloadAs(actionType,options,oAdditionalData,dataContainer))return;var t=this;this.fCurCallback=null;if(!options.callback)this.fCurCallback=function(input,status){var error=403===status?c_oAscError.ID.AccessDeny:c_oAscError.ID.Unknown;if(null!=input&&oAdditionalData["c"]=== input["type"])if("ok"===input["status"]){var url=input["data"];if(url){error=c_oAscError.ID.No;t.processSavedFile(url,downloadType)}}else error=AscCommon.mapAscServerErrorToAscError(parseInt(input["data"]),AscCommon.c_oAscAdvancedOptionsAction.Save);if(c_oAscError.ID.No!==error){t.endInsertDocumentUrls();t.sendEvent("asc_onError",options.errorDirect||error,c_oAscError.Level.NoCritical)}if(actionType)t.sync_EndAction(c_oAscAsyncActionType.BlockInteraction,actionType)};if(window.parent.APP.printPdf&& -(DownloadType.Print===downloadType||!downloadType)){window.parent.APP.printPdf(dataContainer,options.callback||this.fCurCallback);return}AscCommon.saveWithParts(function(fCallback1,oAdditionalData1,dataContainer1){AscCommon.sendCommand(t,fCallback1,oAdditionalData1,dataContainer1)},this.fCurCallback,options.callback,oAdditionalData,dataContainer)};baseEditorsApi.prototype.asc_getChartPreviews=function(chartType){return this.chartPreviewManager.getChartPreviews(chartType)};baseEditorsApi.prototype.asc_getTextArtPreviews= -function(){return this.textArtPreviewManager.getWordArtStyles()};baseEditorsApi.prototype.asc_onOpenChartFrame=function(){if(this.isMobileVersion)return;this.isOpenedChartFrame=true};baseEditorsApi.prototype.asc_onCloseChartFrame=function(){this.isOpenedChartFrame=false};baseEditorsApi.prototype.asc_setInterfaceDrawImagePlaceShape=function(elementId){this.shapeElementId=elementId};baseEditorsApi.prototype.asc_getPropertyEditorShapes=function(){return[AscCommon.g_oAutoShapesGroups,AscCommon.g_oAutoShapesTypes]}; -baseEditorsApi.prototype.asc_getPropertyEditorTextArts=function(){return[AscCommon.g_oPresetTxWarpGroups,AscCommon.g_PresetTxWarpTypes]};baseEditorsApi.prototype._addImageUrl=function(){};baseEditorsApi.prototype.asc_addImageCallback=function(res){};baseEditorsApi.prototype.asc_addImage=function(obj){var t=this;window.parent.APP.AddImage(function(res){console.log("AddImageCallback");t.asc_addImageCallback(res);t._addImageUrl([res.url])},function(){t.sendEvent("asc_onError",error,c_oAscError.Level.NoCritical)}); -return;var t=this;if(this.WordControl)this.WordControl.m_bIsMouseLock=false;AscCommon.ShowImageFileDialog(this.documentId,this.documentUserId,this.CoAuthoringApi.get_jwt(),function(error,files){t._uploadCallback(error,files,obj)},function(error){if(c_oAscError.ID.No!==error)t.sendEvent("asc_onError",error,c_oAscError.Level.NoCritical);t.sync_StartAction(c_oAscAsyncActionType.BlockInteraction,c_oAscAsyncAction.UploadImage)})};baseEditorsApi.prototype._uploadCallback=function(error,files,obj){var t= -this;if(c_oAscError.ID.No!==error)this.sendEvent("asc_onError",error,c_oAscError.Level.NoCritical);else{this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction,c_oAscAsyncAction.UploadImage);AscCommon.UploadImageFiles(files,this.documentId,this.documentUserId,this.CoAuthoringApi.get_jwt(),function(error,urls){if(c_oAscError.ID.No!==error)t.sendEvent("asc_onError",error,c_oAscError.Level.NoCritical);else t._addImageUrl(urls,obj);t.sync_EndAction(c_oAscAsyncActionType.BlockInteraction,c_oAscAsyncAction.UploadImage)})}}; -baseEditorsApi.prototype.asc_replaceLoadImageCallback=function(fCallback){};baseEditorsApi.prototype.asc_loadLocalImageAndAction=function(sLocalImage,fCallback){var _loadedUrl=this.ImageLoader.LoadImage(AscCommon.getFullImageSrc2(sLocalImage),1);if(_loadedUrl!=null)fCallback(_loadedUrl);else this.asc_replaceLoadImageCallback(fCallback)};baseEditorsApi.prototype.asc_checkImageUrlAndAction=function(sImageUrl,fCallback){var oThis=this;this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction,c_oAscAsyncAction.UploadImage); -var fCallback2=function(){oThis.sync_EndAction(c_oAscAsyncActionType.BlockInteraction,c_oAscAsyncAction.UploadImage);fCallback.apply(oThis,arguments)};var sLocalImage=AscCommon.g_oDocumentUrls.getImageLocal(sImageUrl);if(sLocalImage){this.asc_loadLocalImageAndAction(sLocalImage,fCallback2);return}AscCommon.sendImgUrls(oThis,[sImageUrl],function(data){if(data[0]&&data[0].path!=null&&data[0].url!=="error")oThis.asc_loadLocalImageAndAction(AscCommon.g_oDocumentUrls.imagePath2Local(data[0].path),fCallback2)}, -this.editorId===c_oEditorId.Spreadsheet)};baseEditorsApi.prototype.asc_addOleObject=function(oPluginData){if(this.isViewMode)return;var oThis=this;var sImgSrc=oPluginData["imgSrc"];var nWidthPix=oPluginData["widthPix"];var nHeightPix=oPluginData["heightPix"];var fWidth=oPluginData["width"];var fHeight=oPluginData["height"];var sData=oPluginData["data"];var sGuid=oPluginData["guid"];if(typeof sImgSrc==="string"&&sImgSrc.length>0&&typeof sData==="string"&&typeof sGuid==="string"&&sGuid.length>0&&AscFormat.isRealNumber(nWidthPix)&& -AscFormat.isRealNumber(nHeightPix)&&AscFormat.isRealNumber(fWidth)&&AscFormat.isRealNumber(fHeight))this.asc_checkImageUrlAndAction(sImgSrc,function(oImage){oThis.asc_addOleObjectAction(AscCommon.g_oDocumentUrls.getImageLocal(oImage.src),sData,sGuid,fWidth,fHeight,nWidthPix,nHeightPix)})};baseEditorsApi.prototype.asc_editOleObject=function(oPluginData){if(this.isViewMode)return;var oThis=this;var bResize=oPluginData["resize"];var sImgSrc=oPluginData["imgSrc"];var oOleObject=AscCommon.g_oTableId.Get_ById(oPluginData["objectId"]); -var nWidthPix=oPluginData["widthPix"];var nHeightPix=oPluginData["heightPix"];var sData=oPluginData["data"];if(typeof sImgSrc==="string"&&sImgSrc.length>0&&typeof sData==="string"&&oOleObject&&AscFormat.isRealNumber(nWidthPix)&&AscFormat.isRealNumber(nHeightPix))this.asc_checkImageUrlAndAction(sImgSrc,function(oImage){oThis.asc_editOleObjectAction(bResize,oOleObject,AscCommon.g_oDocumentUrls.getImageLocal(oImage.src),sData,nWidthPix,nHeightPix)})};baseEditorsApi.prototype.asc_addOleObjectAction=function(sLocalUrl, -sData,sApplicationId,fWidth,fHeight){};baseEditorsApi.prototype.asc_editOleObjectAction=function(bResize,oOleObject,sImageUrl,sData,nPixWidth,nPixHeight){};baseEditorsApi.prototype.asc_selectSearchingResults=function(value){if(this.selectSearchingResults===value)return;this.selectSearchingResults=value;this._selectSearchingResults(value)};baseEditorsApi.prototype.asc_startEditCurrentOleObject=function(){};baseEditorsApi.prototype.asc_canEditCrop=function(){};baseEditorsApi.prototype.asc_startEditCrop= -function(){};baseEditorsApi.prototype.asc_endEditCrop=function(){};baseEditorsApi.prototype.asc_cropFit=function(){};baseEditorsApi.prototype.asc_cropFill=function(){};baseEditorsApi.prototype.asc_RemoveAllComments=function(isMine,isCurrent){};baseEditorsApi.prototype.asc_showRevision=function(newObj){if(!newObj.docId)return;if(this.isCoAuthoringEnable)this.asc_coAuthoringDisconnect();var bUpdate=true;if(null===this.VersionHistory)this.VersionHistory=new window["Asc"].asc_CVersionHistory(newObj); -else bUpdate=this.VersionHistory.update(newObj);if(bUpdate){this.asc_CloseFile();this.DocInfo.put_Id(this.VersionHistory.docId);this.DocInfo.put_Url(this.VersionHistory.url);this.documentUrlChanges=this.VersionHistory.urlChanges;this.asc_setDocInfo(this.DocInfo);this.asc_LoadDocument(this.VersionHistory)}else if(this.VersionHistory.currentChangeIdb.name)return 1;if(a.name=0&&manager.SlideNum>0;var _zoom=_w/(_w_mm*AscCommon.g_dKoef_mm_to_pix);if(!transform)window["AscDesktopEditor"]["MediaStart"](sMediaName,_x,transition.Rect.y,extX,extY,_zoom);else window["AscDesktopEditor"]["MediaStart"](sMediaName,_x,transition.Rect.y, -extX,extY,_zoom,transform.sx,transform.shy,transform.shx,transform.sy,transform.tx,transform.ty)}}break}case c_oEditorId.Spreadsheet:{break}}};baseEditorsApi.prototype.hideVideoControl=function(){if(!window["AscDesktopEditor"]||!window["AscDesktopEditor"]["MediaEnd"])return;window["AscDesktopEditor"]["MediaEnd"]()};baseEditorsApi.prototype._checkLicenseApiFunctions=function(){return this.licenseResult&&true===this.licenseResult["plugins"]};baseEditorsApi.prototype.asc_pluginsRegister=function(basePath, -plugins){this.sendEvent("asc_LoadPluginsOrDocument");if(null!=this.pluginsManager){this.pluginsManager.register(basePath,plugins);if(this.pluginsManager.countEventDocContOrPluginsReady==2)this.pluginsManager.onPluginEvent("onDocumentContentReady")}};baseEditorsApi.prototype.asc_pluginRun=function(guid,variation,pluginData){if(null!=this.pluginsManager)this.pluginsManager.run(guid,variation,pluginData)};baseEditorsApi.prototype.asc_pluginStop=function(guid){if(null!=this.pluginsManager)this.pluginsManager.close(guid)}; -baseEditorsApi.prototype.asc_pluginResize=function(pluginData){if(null!=this.pluginsManager)this.pluginsManager.runResize(pluginData)};baseEditorsApi.prototype.asc_pluginButtonClick=function(id){if(null!=this.pluginsManager)this.pluginsManager.buttonClick(id)};baseEditorsApi.prototype.asc_pluginEnableMouseEvents=function(isEnable){if(!this.pluginsManager)return;this.pluginsManager.onEnableMouseEvents(isEnable)};baseEditorsApi.prototype.isEnabledDropTarget=function(){return true};baseEditorsApi.prototype.beginInlineDropTarget= -function(e){};baseEditorsApi.prototype.endInlineDropTarget=function(e){};baseEditorsApi.prototype["asc_insertSymbol"]=function(familyName,code,pr){var arrCharCodes=[code];AscFonts.FontPickerByCharacter.checkTextLight(arrCharCodes,true);var fonts=[new AscFonts.CFont(AscFonts.g_fontApplication.GetFontInfoName(familyName),0,"",0,null)];AscFonts.FontPickerByCharacter.extendFonts(fonts);this.asyncMethodCallback=function(){switch(this.editorId){case c_oEditorId.Word:case c_oEditorId.Presentation:{if(pr&& -c_oEditorId.Word===this.editorId)this.WordControl.m_oLogicDocument.AddSpecialSymbol(pr);else{var textPr=new AscCommonWord.CTextPr;textPr.SetFontFamily(familyName);this.WordControl.m_oLogicDocument.AddTextWithPr(new AscCommon.CUnicodeStringEmulator(arrCharCodes),textPr,true)}break}case c_oEditorId.Spreadsheet:{this.AddTextWithPr(familyName,arrCharCodes);break}}};if(false===AscCommon.g_font_loader.CheckFontsNeedLoading(fonts)){this.asyncMethodCallback();this.asyncMethodCallback=undefined;return}AscCommon.g_font_loader.LoadDocumentFonts2(fonts)}; -baseEditorsApi.prototype["asc_registerPlaceholderCallback"]=function(type,callback){if(this.WordControl&&this.WordControl.m_oDrawingDocument&&this.WordControl.m_oDrawingDocument.placeholders)this.WordControl.m_oDrawingDocument.placeholders.registerCallback(type,callback)};baseEditorsApi.prototype["asc_uncheckPlaceholders"]=function(){if(this.WordControl&&this.WordControl.m_oDrawingDocument&&this.WordControl.m_oDrawingDocument.placeholders)this.WordControl.m_oDrawingDocument.placeholders.closeAllActive()}; +(DownloadType.Print===downloadType||!downloadType)){var _cb=options.callback||this.fCurCallback;window.parent.APP.printPdf(dataContainer,function(obj){if(!obj){t.sync_EndAction(c_oAscAsyncActionType.BlockInteraction,actionType);return}_cb(obj)});return}AscCommon.saveWithParts(function(fCallback1,oAdditionalData1,dataContainer1){AscCommon.sendCommand(t,fCallback1,oAdditionalData1,dataContainer1)},this.fCurCallback,options.callback,oAdditionalData,dataContainer)};baseEditorsApi.prototype.asc_getChartPreviews= +function(chartType){return this.chartPreviewManager.getChartPreviews(chartType)};baseEditorsApi.prototype.asc_getTextArtPreviews=function(){return this.textArtPreviewManager.getWordArtStyles()};baseEditorsApi.prototype.asc_onOpenChartFrame=function(){if(this.isMobileVersion)return;this.isOpenedChartFrame=true};baseEditorsApi.prototype.asc_onCloseChartFrame=function(){this.isOpenedChartFrame=false};baseEditorsApi.prototype.asc_setInterfaceDrawImagePlaceShape=function(elementId){this.shapeElementId= +elementId};baseEditorsApi.prototype.asc_getPropertyEditorShapes=function(){return[AscCommon.g_oAutoShapesGroups,AscCommon.g_oAutoShapesTypes]};baseEditorsApi.prototype.asc_getPropertyEditorTextArts=function(){return[AscCommon.g_oPresetTxWarpGroups,AscCommon.g_PresetTxWarpTypes]};baseEditorsApi.prototype._addImageUrl=function(){};baseEditorsApi.prototype.asc_addImageCallback=function(res){};baseEditorsApi.prototype.asc_addImage=function(obj){var t=this;window.parent.APP.AddImage(function(res){console.log("AddImageCallback"); +t.asc_addImageCallback(res);t._addImageUrl([res.url])},function(){t.sendEvent("asc_onError",error,c_oAscError.Level.NoCritical)});return;var t=this;if(this.WordControl)this.WordControl.m_bIsMouseLock=false;AscCommon.ShowImageFileDialog(this.documentId,this.documentUserId,this.CoAuthoringApi.get_jwt(),function(error,files){t._uploadCallback(error,files,obj)},function(error){if(c_oAscError.ID.No!==error)t.sendEvent("asc_onError",error,c_oAscError.Level.NoCritical);t.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, +c_oAscAsyncAction.UploadImage)})};baseEditorsApi.prototype._uploadCallback=function(error,files,obj){var t=this;if(c_oAscError.ID.No!==error)this.sendEvent("asc_onError",error,c_oAscError.Level.NoCritical);else{this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction,c_oAscAsyncAction.UploadImage);AscCommon.UploadImageFiles(files,this.documentId,this.documentUserId,this.CoAuthoringApi.get_jwt(),function(error,urls){if(c_oAscError.ID.No!==error)t.sendEvent("asc_onError",error,c_oAscError.Level.NoCritical); +else t._addImageUrl(urls,obj);t.sync_EndAction(c_oAscAsyncActionType.BlockInteraction,c_oAscAsyncAction.UploadImage)})}};baseEditorsApi.prototype.asc_replaceLoadImageCallback=function(fCallback){};baseEditorsApi.prototype.asc_loadLocalImageAndAction=function(sLocalImage,fCallback){var _loadedUrl=this.ImageLoader.LoadImage(AscCommon.getFullImageSrc2(sLocalImage),1);if(_loadedUrl!=null)fCallback(_loadedUrl);else this.asc_replaceLoadImageCallback(fCallback)};baseEditorsApi.prototype.asc_checkImageUrlAndAction= +function(sImageUrl,fCallback){var oThis=this;this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction,c_oAscAsyncAction.UploadImage);var fCallback2=function(){oThis.sync_EndAction(c_oAscAsyncActionType.BlockInteraction,c_oAscAsyncAction.UploadImage);fCallback.apply(oThis,arguments)};var sLocalImage=AscCommon.g_oDocumentUrls.getImageLocal(sImageUrl);if(sLocalImage){this.asc_loadLocalImageAndAction(sLocalImage,fCallback2);return}AscCommon.sendImgUrls(oThis,[sImageUrl],function(data){if(data[0]&& +data[0].path!=null&&data[0].url!=="error")oThis.asc_loadLocalImageAndAction(AscCommon.g_oDocumentUrls.imagePath2Local(data[0].path),fCallback2)},this.editorId===c_oEditorId.Spreadsheet)};baseEditorsApi.prototype.asc_addOleObject=function(oPluginData){if(this.isViewMode)return;var oThis=this;var sImgSrc=oPluginData["imgSrc"];var nWidthPix=oPluginData["widthPix"];var nHeightPix=oPluginData["heightPix"];var fWidth=oPluginData["width"];var fHeight=oPluginData["height"];var sData=oPluginData["data"];var sGuid= +oPluginData["guid"];if(typeof sImgSrc==="string"&&sImgSrc.length>0&&typeof sData==="string"&&typeof sGuid==="string"&&sGuid.length>0&&AscFormat.isRealNumber(nWidthPix)&&AscFormat.isRealNumber(nHeightPix)&&AscFormat.isRealNumber(fWidth)&&AscFormat.isRealNumber(fHeight))this.asc_checkImageUrlAndAction(sImgSrc,function(oImage){oThis.asc_addOleObjectAction(AscCommon.g_oDocumentUrls.getImageLocal(oImage.src),sData,sGuid,fWidth,fHeight,nWidthPix,nHeightPix)})};baseEditorsApi.prototype.asc_editOleObject= +function(oPluginData){if(this.isViewMode)return;var oThis=this;var bResize=oPluginData["resize"];var sImgSrc=oPluginData["imgSrc"];var oOleObject=AscCommon.g_oTableId.Get_ById(oPluginData["objectId"]);var nWidthPix=oPluginData["widthPix"];var nHeightPix=oPluginData["heightPix"];var sData=oPluginData["data"];if(typeof sImgSrc==="string"&&sImgSrc.length>0&&typeof sData==="string"&&oOleObject&&AscFormat.isRealNumber(nWidthPix)&&AscFormat.isRealNumber(nHeightPix))this.asc_checkImageUrlAndAction(sImgSrc, +function(oImage){oThis.asc_editOleObjectAction(bResize,oOleObject,AscCommon.g_oDocumentUrls.getImageLocal(oImage.src),sData,nWidthPix,nHeightPix)})};baseEditorsApi.prototype.asc_addOleObjectAction=function(sLocalUrl,sData,sApplicationId,fWidth,fHeight){};baseEditorsApi.prototype.asc_editOleObjectAction=function(bResize,oOleObject,sImageUrl,sData,nPixWidth,nPixHeight){};baseEditorsApi.prototype.asc_selectSearchingResults=function(value){if(this.selectSearchingResults===value)return;this.selectSearchingResults= +value;this._selectSearchingResults(value)};baseEditorsApi.prototype.asc_startEditCurrentOleObject=function(){};baseEditorsApi.prototype.asc_canEditCrop=function(){};baseEditorsApi.prototype.asc_startEditCrop=function(){};baseEditorsApi.prototype.asc_endEditCrop=function(){};baseEditorsApi.prototype.asc_cropFit=function(){};baseEditorsApi.prototype.asc_cropFill=function(){};baseEditorsApi.prototype.asc_RemoveAllComments=function(isMine,isCurrent){};baseEditorsApi.prototype.asc_showRevision=function(newObj){if(!newObj.docId)return; +if(this.isCoAuthoringEnable)this.asc_coAuthoringDisconnect();var bUpdate=true;if(null===this.VersionHistory)this.VersionHistory=new window["Asc"].asc_CVersionHistory(newObj);else bUpdate=this.VersionHistory.update(newObj);if(bUpdate){this.asc_CloseFile();this.DocInfo.put_Id(this.VersionHistory.docId);this.DocInfo.put_Url(this.VersionHistory.url);this.documentUrlChanges=this.VersionHistory.urlChanges;this.asc_setDocInfo(this.DocInfo);this.asc_LoadDocument(this.VersionHistory)}else if(this.VersionHistory.currentChangeId< +newObj.currentChangeId){AscCommon.CollaborativeEditing.Clear_CollaborativeMarks();editor.VersionHistory.applyChanges(editor);AscCommon.CollaborativeEditing.Apply_Changes()}};baseEditorsApi.prototype.asc_undoAllChanges=function(){};baseEditorsApi.prototype.asc_getAdvancedOptions=function(){var cp={"codepage":AscCommon.c_oAscCodePageUtf8,"encodings":AscCommon.getEncodingParams()};return new AscCommon.asc_CAdvancedOptions(cp)};baseEditorsApi.prototype.asc_Print=function(options){if(window["AscDesktopEditor"]&& +this._printDesktop(options))return;if(!options)options=new Asc.asc_CDownloadOptions;options.fileType=Asc.c_oAscFileType.PDF;this.downloadAs(c_oAscAsyncAction.Print,options)};baseEditorsApi.prototype.asc_Save=function(isAutoSave,isIdle){var t=this;var res=false;if(this.canSave&&this._saveCheck()){this.IsUserSave=!isAutoSave;if(this.asc_isDocumentCanSave()||AscCommon.History.Have_Changes()||this._haveOtherChanges()||this.canUnlockDocument||this.forceSaveUndoRequest){if(this._prepareSave(isIdle)){this.canSave= +false;this.CoAuthoringApi.askSaveChanges(function(e){t._onSaveCallback(e)});res=true}}else if(this.isForceSaveOnUserSave&&this.IsUserSave)this.forceSave()}return res};baseEditorsApi.prototype.asc_isDocumentCanSave=function(){return this.isDocumentCanSave};baseEditorsApi.prototype.asc_getCanUndo=function(){return AscCommon.History.Can_Undo()};baseEditorsApi.prototype.asc_getCanRedo=function(){return AscCommon.History.Can_Redo()};baseEditorsApi.prototype.asc_isOffline=function(){return window.location.protocol.indexOf("file")== +0?true:false};baseEditorsApi.prototype.asc_getUrlType=function(url){return AscCommon.getUrlType(url)};baseEditorsApi.prototype.openDocument=function(file){};baseEditorsApi.prototype.openDocumentFromZip=function(){};baseEditorsApi.prototype.onEndLoadDocInfo=function(){if(this.isLoadFullApi&&this.DocInfo){if(this.DocInfo.get_OfflineApp())this._openChartOrLocalDocument();this.onEndLoadFile(null)}};baseEditorsApi.prototype.onEndLoadFile=function(result){if(result)this.openResult=result;if(this.isLoadFullApi&& +this.DocInfo&&this.openResult&&this.isLoadFonts){this.openDocument(this.openResult);this.openResult=null}};baseEditorsApi.prototype._onEndLoadSdk=function(){AscCommon.g_oTableId.init();var t=this;AscCommon.InitDragAndDrop(this.HtmlElement,function(error,files){t._uploadCallback(error,files)});AscFonts.g_fontApplication.Init();this.FontLoader=AscCommon.g_font_loader;this.ImageLoader=AscCommon.g_image_loader;this.FontLoader.put_Api(this);this.ImageLoader.put_Api(this);this.FontLoader.SetStandartFonts(); +this.chartPreviewManager=new AscCommon.ChartPreviewManager;this.textArtPreviewManager=new AscCommon.TextArtPreviewManager;AscFormat.initStyleManager();if(null!==this.tmpFocus)this.asc_enableKeyEvents(this.tmpFocus);this.pluginsManager=Asc.createPluginsManager(this);this.macros=new AscCommon.CDocumentMacros;this._loadSdkImages();if(AscFonts.FontPickerByCharacter&&this.documentTitle)AscFonts.FontPickerByCharacter.getFontsByString(this.documentTitle)};baseEditorsApi.prototype._loadSdkImages=function(){}; +baseEditorsApi.prototype.sendStandartTextures=function(){if(this.isSendStandartTextures)return;this.isSendStandartTextures=true;var _count=AscCommon.g_oUserTexturePresets.length;var arr=new Array(_count);var arrToDownload=[];for(var i=0;i<_count;++i){arr[i]=new AscCommon.asc_CTexture;arr[i].Id=i;arr[i].Image=AscCommon.g_oUserTexturePresets[i];arrToDownload.push(AscCommon.g_oUserTexturePresets[i])}if(this.editorId===c_oEditorId.Word)arrToDownload.push(AscCommon.g_sWordPlaceholderImage);this.ImageLoader.LoadImagesWithCallback(arrToDownload, +function(){},0);this.sendEvent("asc_onInitStandartTextures",arr)};baseEditorsApi.prototype.sendMathToMenu=function(){if(this.MathMenuLoad)return;var _MathPainter=new AscFormat.CMathPainter(this);_MathPainter.Generate();this.MathMenuLoad=true};baseEditorsApi.prototype.sendMathTypesToMenu=function(_math){this.sendEvent("asc_onMathTypes",_math)};baseEditorsApi.prototype.asyncFontEndLoaded_MathDraw=function(Obj){this.sync_EndAction(c_oAscAsyncActionType.Information,c_oAscAsyncAction.LoadFont);Obj.Generate2()}; +baseEditorsApi.prototype.getCurrentColorScheme=function(){var oTheme=this.getCurrentTheme();return oTheme&&oTheme.themeElements&&oTheme.themeElements.clrScheme};baseEditorsApi.prototype.asc_GetCurrentColorSchemeName=function(){var oClrScheme=this.getCurrentColorScheme();if(oClrScheme&&typeof oClrScheme.name==="string")return oClrScheme.name;return""};baseEditorsApi.prototype.asc_GetCurrentColorSchemeIndex=function(){var oTheme=this.getCurrentTheme();if(!oTheme)return-1;return this.getColorSchemes(oTheme).index}; +baseEditorsApi.prototype.getCurrentTheme=function(){return null};baseEditorsApi.prototype.getColorSchemes=function(theme){var result=AscCommon.g_oUserColorScheme.slice();var asc_color_scheme,_scheme,i;var aCustomSchemes=theme.getExtraAscColorSchemes();_scheme=theme.themeElements&&theme.themeElements.clrScheme;var nIndex=-1;if(_scheme){asc_color_scheme=AscCommon.getAscColorScheme(_scheme,theme);nIndex=AscCommon.getIndexColorSchemeInArray(result,asc_color_scheme);if(nIndex===-1)aCustomSchemes.push(asc_color_scheme); +aCustomSchemes.sort(function(a,b){if(a.name===""||a.name===null)return-1;if(b.name===""||b.name===null)return 1;if(a.name>b.name)return 1;if(a.name=0&&manager.SlideNum>0;var _zoom=_w/(_w_mm*AscCommon.g_dKoef_mm_to_pix);if(!transform)window["AscDesktopEditor"]["MediaStart"](sMediaName, +_x,transition.Rect.y,extX,extY,_zoom);else window["AscDesktopEditor"]["MediaStart"](sMediaName,_x,transition.Rect.y,extX,extY,_zoom,transform.sx,transform.shy,transform.shx,transform.sy,transform.tx,transform.ty)}}break}case c_oEditorId.Spreadsheet:{break}}};baseEditorsApi.prototype.hideVideoControl=function(){if(!window["AscDesktopEditor"]||!window["AscDesktopEditor"]["MediaEnd"])return;window["AscDesktopEditor"]["MediaEnd"]()};baseEditorsApi.prototype._checkLicenseApiFunctions=function(){return this.licenseResult&& +true===this.licenseResult["plugins"]};baseEditorsApi.prototype.asc_pluginsRegister=function(basePath,plugins){this.sendEvent("asc_LoadPluginsOrDocument");if(null!=this.pluginsManager){this.pluginsManager.register(basePath,plugins);if(this.pluginsManager.countEventDocContOrPluginsReady==2)this.pluginsManager.onPluginEvent("onDocumentContentReady")}};baseEditorsApi.prototype.asc_pluginRun=function(guid,variation,pluginData){if(null!=this.pluginsManager)this.pluginsManager.run(guid,variation,pluginData)}; +baseEditorsApi.prototype.asc_pluginStop=function(guid){if(null!=this.pluginsManager)this.pluginsManager.close(guid)};baseEditorsApi.prototype.asc_pluginResize=function(pluginData){if(null!=this.pluginsManager)this.pluginsManager.runResize(pluginData)};baseEditorsApi.prototype.asc_pluginButtonClick=function(id){if(null!=this.pluginsManager)this.pluginsManager.buttonClick(id)};baseEditorsApi.prototype.asc_pluginEnableMouseEvents=function(isEnable){if(!this.pluginsManager)return;this.pluginsManager.onEnableMouseEvents(isEnable)}; +baseEditorsApi.prototype.isEnabledDropTarget=function(){return true};baseEditorsApi.prototype.beginInlineDropTarget=function(e){};baseEditorsApi.prototype.endInlineDropTarget=function(e){};baseEditorsApi.prototype["asc_insertSymbol"]=function(familyName,code,pr){var arrCharCodes=[code];AscFonts.FontPickerByCharacter.checkTextLight(arrCharCodes,true);var fonts=[new AscFonts.CFont(AscFonts.g_fontApplication.GetFontInfoName(familyName),0,"",0,null)];AscFonts.FontPickerByCharacter.extendFonts(fonts); +this.asyncMethodCallback=function(){switch(this.editorId){case c_oEditorId.Word:case c_oEditorId.Presentation:{if(pr&&c_oEditorId.Word===this.editorId)this.WordControl.m_oLogicDocument.AddSpecialSymbol(pr);else{var textPr=new AscCommonWord.CTextPr;textPr.SetFontFamily(familyName);this.WordControl.m_oLogicDocument.AddTextWithPr(new AscCommon.CUnicodeStringEmulator(arrCharCodes),textPr,true)}break}case c_oEditorId.Spreadsheet:{this.AddTextWithPr(familyName,arrCharCodes);break}}};if(false===AscCommon.g_font_loader.CheckFontsNeedLoading(fonts)){this.asyncMethodCallback(); +this.asyncMethodCallback=undefined;return}AscCommon.g_font_loader.LoadDocumentFonts2(fonts)};baseEditorsApi.prototype["asc_registerPlaceholderCallback"]=function(type,callback){if(this.WordControl&&this.WordControl.m_oDrawingDocument&&this.WordControl.m_oDrawingDocument.placeholders)this.WordControl.m_oDrawingDocument.placeholders.registerCallback(type,callback)};baseEditorsApi.prototype["asc_uncheckPlaceholders"]=function(){if(this.WordControl&&this.WordControl.m_oDrawingDocument&&this.WordControl.m_oDrawingDocument.placeholders)this.WordControl.m_oDrawingDocument.placeholders.closeAllActive()}; baseEditorsApi.prototype.asc_nativeInitBuilder=function(){AscCommon.History.TurnOff();this.asc_setDocInfo(new Asc.asc_CDocInfo)};baseEditorsApi.prototype.asc_SetSilentMode=function(){};baseEditorsApi.prototype.asc_canPaste=function(){return false};baseEditorsApi.prototype.asc_Recalculate=function(){};baseEditorsApi.prototype["asc_nativeCheckPdfRenderer"]=function(_memory1,_memory2){if(true){_memory1.Copy=_memory1["Copy"];_memory1.ClearNoAttack=_memory1["ClearNoAttack"];_memory1.WriteByte=_memory1["WriteByte"]; _memory1.WriteBool=_memory1["WriteBool"];_memory1.WriteLong=_memory1["WriteLong"];_memory1.WriteDouble=_memory1["WriteDouble"];_memory1.WriteString=_memory1["WriteString"];_memory1.WriteString2=_memory1["WriteString2"];_memory2.Copy=_memory1["Copy"];_memory2.ClearNoAttack=_memory1["ClearNoAttack"];_memory2.WriteByte=_memory1["WriteByte"];_memory2.WriteBool=_memory1["WriteBool"];_memory2.WriteLong=_memory1["WriteLong"];_memory2.WriteDouble=_memory1["WriteDouble"];_memory2.WriteString=_memory1["WriteString"]; _memory2.WriteString2=_memory1["WriteString2"]}var _printer=new AscCommon.CDocumentRenderer;_printer.Memory=_memory1;_printer.VectorMemoryForPrint=_memory2;return _printer};baseEditorsApi.prototype.Begin_CompositeInput=function(){};baseEditorsApi.prototype.Add_CompositeText=function(nCharCode){};baseEditorsApi.prototype.Remove_CompositeText=function(nCount){};baseEditorsApi.prototype.Replace_CompositeText=function(arrCharCodes){};baseEditorsApi.prototype.Set_CursorPosInCompositeText=function(nPos){}; diff --git a/www/common/onlyoffice/v4/sdkjs/cell/sdk-all.js b/www/common/onlyoffice/v4/sdkjs/cell/sdk-all.js index cdefc6082..bd569223c 100644 --- a/www/common/onlyoffice/v4/sdkjs/cell/sdk-all.js +++ b/www/common/onlyoffice/v4/sdkjs/cell/sdk-all.js @@ -8425,87 +8425,88 @@ oThis.loadImageCallBackCounterMax)oThis.LoadImagesWithCallbackEnd()};oImage.Imag this.loadImageCallBackArgs);this.loadImageCallBack=null;this.loadImageCallBackArgs=null;this.loadImageCallBackCounterMax=0;this.loadImageCallBackCounter=0}}var g_flow_anchor=new Image;g_flow_anchor.asc_complete=false;g_flow_anchor.onload=function(){g_flow_anchor.asc_complete=true};g_flow_anchor.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAPBAMAAADNDVhEAAAAIVBMVEUAAAANDQ0NDQ0NDQ0NDQ0NDQ0AAAANDQ0NDQ0NDQ0NDQ1jk7YPAAAACnRSTlMAGkD4mb9c5s9TDghpXQAAAFZJREFUCNdjYGBgW8YABlxcIBLBZ1gAEfZa5QWiGRkWMAIpAaA4iHQE0YwODEtANMsChkIwv4BBWQBICyswMC1iWADEDAzKoUuDFUAGNC9uABvIaQkkABpxD6lFb9lRAAAAAElFTkSuQmCC"; var g_flow_anchor2=new Image;g_flow_anchor2.asc_complete=false;g_flow_anchor2.onload=function(){g_flow_anchor2.asc_complete=true};g_flow_anchor2.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAeCAMAAAAFBf7qAAAAOVBMVEUAAAAAAAAAAAAAAAAJCQkAAAAJCQkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJCQknI0ZQAAAAEnRSTlMAx9ITlAfyPHxn68yecTAl5qt6y0BvAAAAt0lEQVQoz8WS0QrDIAxFk0ajtlXb+/8fuzAprltg7Gnn4aIcvAgJTSSoBiGPoIAGV60qoquvIIL110IJgPONmKIlMI73MiwGRoZvahbKVSizcDKU8QeVPDXEIr6ShVB9VUEn2FOMkwL8VwjUtuypvDWiHeVTFeyWkZHfVQZHGm4XMhKQyJB9GKMxuHQSBlioF7u2q7kzgO2AcWwW3F8mWRmGKgyu91mK1Tzh4ixVVkBzJI/EnGjyACbfCaO3eIWRAAAAAElFTkSuQmCC"; window["AscCommon"]=window["AscCommon"]||{};window["AscCommon"].g_font_loader=new CGlobalFontLoader;window["AscCommon"].g_image_loader=new CGlobalImageLoader;window["AscCommon"].g_flow_anchor=g_flow_anchor;window["AscCommon"].g_flow_anchor2=g_flow_anchor2})(window,window.document);"use strict";(function(window,undefined){var FOREIGN_CURSOR_LABEL_HIDETIME=1500;function CCollaborativeChanges(){this.m_pData=null;this.m_oColor=null}CCollaborativeChanges.prototype.Set_Data=function(pData){this.m_pData= -pData};CCollaborativeChanges.prototype.Set_Color=function(oColor){this.m_oColor=oColor};CCollaborativeChanges.prototype.Set_FromUndoRedo=function(Class,Data,Binary){if(!Class.Get_Id)return false;this.m_pData=this.private_SaveData(Binary);return true};CCollaborativeChanges.prototype.Apply_Data=function(){var CollaborativeEditing=AscCommon.CollaborativeEditing;var Reader=this.private_LoadData(this.m_pData);var ClassId=Reader.GetString2();var Class=AscCommon.g_oTableId.Get_ById(ClassId);if(!Class)return false; -var nReaderPos=Reader.GetCurPos();var nChangesType=Reader.GetLong();var fChangesClass=AscDFH.changesFactory[nChangesType];if(fChangesClass){var oChange=new fChangesClass(Class);oChange.ReadFromBinary(Reader);if(true===CollaborativeEditing.private_AddOverallChange(oChange))oChange.Load(this.m_oColor);return true}else{CollaborativeEditing.private_AddOverallChange(this.m_pData);Reader.Seek2(nReaderPos);if(!Class.Load_Changes)return false;return Class.Load_Changes(Reader,null,this.m_oColor)}};CCollaborativeChanges.prototype.private_LoadData= -function(szSrc){return this.GetStream(szSrc,0,szSrc.length)};CCollaborativeChanges.prototype.GetStream=function(szSrc,offset,srcLen){var nWritten=0;var index=-1+offset;var dst_len="";while(true){index++;var _c=szSrc.charCodeAt(index);if(_c==";".charCodeAt(0)){index++;break}dst_len+=String.fromCharCode(_c)}var dstLen=parseInt(dst_len);var pointer=AscFonts.g_memory.Alloc(dstLen);var stream=new AscCommon.FT_Stream2(pointer.data,dstLen);stream.obj=pointer.obj;var dstPx=stream.data;if(window.chrome)while(index< -srcLen){var dwCurr=0;var i;var nBits=0;for(i=0;i<4;i++){if(index>=srcLen)break;var nCh=AscFonts.DecodeBase64Char(szSrc.charCodeAt(index++));if(nCh==-1){i--;continue}dwCurr<<=6;dwCurr|=nCh;nBits+=6}dwCurr<<=24-nBits;for(i=0;i>>16;dwCurr<<=8}}else{var p=AscFonts.b64_decode;while(index=srcLen)break;var nCh=p[szSrc.charCodeAt(index++)];if(nCh==undefined){i--;continue}dwCurr<<=6;dwCurr|= -nCh;nBits+=6}dwCurr<<=24-nBits;for(i=0;i>>16;dwCurr<<=8}}}return stream};CCollaborativeChanges.prototype.private_SaveData=function(Binary){var Writer=AscCommon.History.BinaryWriter;var Pos=Binary.Pos;var Len=Binary.Len;return Len+";"+Writer.GetBase64Memory2(Pos,Len)};function CCollaborativeEditingBase(){this.m_nUseType=1;this.m_aUsers=[];this.m_aChanges=[];this.m_aNeedUnlock=[];this.m_aNeedUnlock2=[];this.m_aNeedLock=[];this.m_aLinkData=[];this.m_aEndActions= -[];this.m_bGlobalLock=0;this.m_bGlobalLockSelection=0;this.m_aCheckLocks=[];this.m_aCheckLocksInstance=[];this.m_aNewObjects=[];this.m_aNewImages=[];this.m_aDC={};this.m_aChangedClasses={};this.m_oMemory=null;this.m_aCursorsToUpdate={};this.m_aCursorsToUpdateShortId={};this.m_bFast=false;this.m_oLogicDocument=null;this.m_aDocumentPositions=new CDocumentPositionsManager;this.m_aForeignCursorsPos=new CDocumentPositionsManager;this.m_aForeignCursors={};this.m_aForeignCursorsId={};this.m_nAllChangesSavedIndex= -0;this.m_aAllChanges=[];this.m_aOwnChangesIndexes=[];this.m_oOwnChanges=[]}CCollaborativeEditingBase.prototype.Clear=function(){this.m_nUseType=1;this.m_aUsers=[];this.m_aChanges=[];this.m_aNeedUnlock=[];this.m_aNeedUnlock2=[];this.m_aNeedLock=[];this.m_aLinkData=[];this.m_aEndActions=[];this.m_aCheckLocks=[];this.m_aCheckLocksInstance=[];this.m_aNewObjects=[];this.m_aNewImages=[]};CCollaborativeEditingBase.prototype.Set_Fast=function(bFast){this.m_bFast=bFast;if(false===bFast){this.Remove_AllForeignCursors(); -this.RemoveMyCursorFromOthers()}};CCollaborativeEditingBase.prototype.Is_Fast=function(){return this.m_bFast};CCollaborativeEditingBase.prototype.Is_SingleUser=function(){return 1===this.m_nUseType};CCollaborativeEditingBase.prototype.getCollaborativeEditing=function(){return!this.Is_SingleUser()};CCollaborativeEditingBase.prototype.Start_CollaborationEditing=function(){this.m_nUseType=-1};CCollaborativeEditingBase.prototype.End_CollaborationEditing=function(){if(this.m_nUseType<=0)this.m_nUseType= -0};CCollaborativeEditingBase.prototype.Add_User=function(UserId){if(-1===this.Find_User(UserId))this.m_aUsers.push(UserId)};CCollaborativeEditingBase.prototype.Find_User=function(UserId){var Len=this.m_aUsers.length;for(var Index=0;Index0;if(true===OtherChanges){AscFonts.IsCheckSymbols=true;editor.WordControl.m_oLogicDocument.StopRecalculate(); -editor.WordControl.m_oLogicDocument.EndPreview_MailMergeResult();editor.sync_StartAction(Asc.c_oAscAsyncActionType.BlockInteraction,Asc.c_oAscAsyncAction.ApplyChanges);var DocState=this.private_SaveDocumentState();this.Clear_NewImages();this.Apply_OtherChanges();this.Lock_NeedLock();this.private_RestoreDocumentState(DocState);this.OnStart_Load_Objects();AscFonts.IsCheckSymbols=false}};CCollaborativeEditingBase.prototype.Apply_OtherChanges=function(){AscCommon.g_oIdCounter.Set_Load(true);if(this.m_aChanges.length> -0)this.private_CollectOwnChanges();var _count=this.m_aChanges.length;for(var i=0;i<_count;i++){if(window["NATIVE_EDITOR_ENJINE"]===true&&window["native"]["CheckNextChange"])if(!window["native"]["CheckNextChange"]())break;var Changes=this.m_aChanges[i];Changes.Apply_Data()}this.private_ClearChanges();this.Apply_LinkData();this.Check_MergeData();this.OnEnd_ReadForeignChanges();AscCommon.g_oIdCounter.Set_Load(false)};CCollaborativeEditingBase.prototype.getOwnLocksLength=function(){return this.m_aNeedUnlock2.length}; -CCollaborativeEditingBase.prototype.Send_Changes=function(){};CCollaborativeEditingBase.prototype.Release_Locks=function(){};CCollaborativeEditingBase.prototype.CheckWaitingImages=function(aImages){};CCollaborativeEditingBase.prototype.SendImagesUrlsFromChanges=function(aImages){var rData={},oApi=editor||Asc["editor"],i;if(!oApi)return;rData["c"]="pathurls";rData["data"]=[];for(i=0;i0)this.SendImagesUrlsFromChanges(aImages);else{this.SendImagesCallback([].concat(this.m_aNewImages)); -this.m_aNewImages.length=0}};CCollaborativeEditingBase.prototype.OnEnd_Load_Objects=function(){};CCollaborativeEditingBase.prototype.Clear_LinkData=function(){this.m_aLinkData.length=0};CCollaborativeEditingBase.prototype.Add_LinkData=function(Class,LinkData){this.m_aLinkData.push({Class:Class,LinkData:LinkData})};CCollaborativeEditingBase.prototype.Apply_LinkData=function(){var Count=this.m_aLinkData.length;for(var Index=0;Index0){this.m_aOwnChangesIndexes.push({Position:this.m_aAllChanges.length,Count:arrChanges.length});this.m_aAllChanges= -this.m_aAllChanges.concat(arrChanges)}};CCollaborativeEditingBase.prototype.Undo=function(){if(true===this.Get_GlobalLock())return;if(this.m_aOwnChangesIndexes.length<=0)return false;var arrChanges=[];var oIndexes=this.m_aOwnChangesIndexes[this.m_aOwnChangesIndexes.length-1];var nPosition=oIndexes.Position;var nCount=oIndexes.Count;for(var nIndex=nCount-1;nIndex>=0;--nIndex){var oChange=this.m_aAllChanges[nPosition+nIndex];if(!oChange)continue;var oClass=oChange.GetClass();if(oChange.IsContentChange()){var _oChange= -oChange.Copy();if(this.private_CommutateContentChanges(_oChange,nPosition+nCount))arrChanges.push(_oChange);oChange.SetReverted(true)}else{var _oChange=oChange;if(this.private_CommutatePropertyChanges(oClass,_oChange,nPosition+nCount))arrChanges.push(_oChange)}}this.m_aOwnChangesIndexes.length=this.m_aOwnChangesIndexes.length-1;var arrReverseChanges=[];for(var nIndex=0,nCount=arrChanges.length;nIndex-1;--i)if(mapAddedSlides[oLogicDocument.Slides[i].Get_Id()]&&!oLogicDocument.Slides[i].Layout)oLogicDocument.removeSlide(i);for(var sId in mapSlides)if(mapSlides.hasOwnProperty(sId))mapSlides[sId].correctContent();if(bChangedLayout)for(var i=oLogicDocument.Slides.length-1;i>-1;--i){var Layout=oLogicDocument.Slides[i].Layout;if(!Layout||mapLayouts[Layout.Get_Id()])if(!oLogicDocument.Slides[i].CheckLayout())oLogicDocument.removeSlide(i)}for(var sId in mapGrObjects){var oShape= -mapGrObjects[sId];if(!oShape.checkCorrect()){oShape.setBDeleted(true);if(oShape.group)oShape.group.removeFromSpTree(oShape.Get_Id());else if(AscFormat.Slide&&oShape.parent instanceof AscFormat.Slide)oShape.parent.removeFromSpTreeById(oShape.Get_Id());else if(AscCommonWord.ParaDrawing&&oShape.parent instanceof AscCommonWord.ParaDrawing)mapDrawings[oShape.parent.Get_Id()]=oShape.parent}else if(oShape.resetGroups)oShape.resetGroups()}var oDrawing;for(var sId in mapDrawings)if(mapDrawings.hasOwnProperty(sId)){oDrawing= -mapDrawings[sId];if(!oDrawing.CheckCorrect()){var oParentParagraph=oDrawing.Get_ParentParagraph();oDrawing.PreDelete();oDrawing.Remove_FromDocument(false);if(oParentParagraph)mapParagraphs[oParentParagraph.Get_Id()]=oParentParagraph}}for(var sId in mapRuns)if(mapRuns.hasOwnProperty(sId)){var oRun=mapRuns[sId];for(var nIndex=oRun.Content.length-1;nIndex>-1;--nIndex)if(oRun.Content[nIndex]instanceof AscCommonWord.ParaDrawing)if(!oRun.Content[nIndex].CheckCorrect()){oRun.Remove_FromContent(nIndex,1, -false);if(oRun.Paragraph)mapParagraphs[oRun.Paragraph.Get_Id()]=oRun.Paragraph}}for(var sId in mapTables){var oTable=mapTables[sId];for(var nCurRow=oTable.Content.length-1;nCurRow>=0;--nCurRow){var oRow=oTable.Get_Row(nCurRow);if(oRow.Get_CellsCount()<=0)oTable.private_RemoveRow(nCurRow)}if(oTable.Parent instanceof AscCommonWord.CDocument||oTable.Parent instanceof AscCommonWord.CDocumentContent)mapDocumentContents[oTable.Parent.Get_Id()]=oTable.Parent}for(var sId in mapDocumentContents){var oDocumentContent= -mapDocumentContents[sId];var nContentLen=oDocumentContent.Content.length;for(var nIndex=nContentLen-1;nIndex>=0;--nIndex){var oElement=oDocumentContent.Content[nIndex];if((AscCommonWord.type_Paragraph===oElement.GetType()||AscCommonWord.type_Table===oElement.GetType())&&oElement.Content.length<=0)oDocumentContent.Remove_FromContent(nIndex,1)}nContentLen=oDocumentContent.Content.length;if(nContentLen<=0||AscCommonWord.type_Paragraph!==oDocumentContent.Content[nContentLen-1].GetType()){var oNewParagraph= -new AscCommonWord.Paragraph(oLogicDocument.Get_DrawingDocument(),oDocumentContent,0,0,0,0,0,false);oDocumentContent.Add_ToContent(nContentLen,oNewParagraph)}}for(var sId in mapParagraphs){var oParagraph=mapParagraphs[sId];oParagraph.CheckParaEnd();oParagraph.Correct_Content(null,null,true)}var oBinaryWriter=AscCommon.History.BinaryWriter;var aSendingChanges=[];for(var nIndex=0,nCount=arrReverseChanges.length;nIndex=0;--nActionIndex){var oAction=arrActions[nActionIndex];var oResult=oAction;for(var nIndex=nStartPosition,nOverallCount=this.m_aAllChanges.length;nIndex0)oChange.ConvertFromSimpleActions(arrCommutateActions);else return false;return true};CCollaborativeEditingBase.prototype.private_Commutate= -function(oActionL,oActionR){if(oActionL.Add)if(oActionR.Add)if(oActionL.Pos>=oActionR.Pos)oActionL.Pos++;else oActionR.Pos--;else if(oActionL.Pos>oActionR.Pos)oActionL.Pos--;else if(oActionL.Pos===oActionR.Pos)return false;else oActionR.Pos--;else if(oActionR.Add)if(oActionL.Pos>=oActionR.Pos)oActionL.Pos++;else oActionR.Pos++;else if(oActionL.Pos>oActionR.Pos)oActionL.Pos--;else oActionR.Pos++;return true};CCollaborativeEditingBase.prototype.private_CommutatePropertyChanges=function(oClass,oChange, -nStartPosition){if(oChange.CheckCorrect&&!oChange.CheckCorrect())return false;return true};CCollaborativeEditingBase.prototype.private_RecalculateDocument=function(oRecalcData){};function CDocumentPositionsManager(){this.m_aDocumentPositions=[];this.m_aDocumentPositionsSplit=[];this.m_aDocumentPositionsMap=[]}CDocumentPositionsManager.prototype.Clear_DocumentPositions=function(){this.m_aDocumentPositions=[];this.m_aDocumentPositionsSplit=[];this.m_aDocumentPositionsMap=[]};CDocumentPositionsManager.prototype.Add_DocumentPosition= -function(Position){this.m_aDocumentPositions.push(Position)};CDocumentPositionsManager.prototype.Update_DocumentPositionsOnAdd=function(Class,Pos){for(var PosIndex=0,PosCount=this.m_aDocumentPositions.length;PosIndexPos||_Pos.Position===Pos&&!(Class instanceof AscCommonWord.ParaRun))){_Pos.Position++; -break}}}};CDocumentPositionsManager.prototype.Update_DocumentPositionsOnRemove=function(Class,Pos,Count){for(var PosIndex=0,PosCount=this.m_aDocumentPositions.length;PosIndexPos+Count)_Pos.Position-=Count;else if(_Pos.Position>=Pos){_Pos.Position=Pos;_Pos.Deleted=true}break}}}}; -CDocumentPositionsManager.prototype.OnStart_SplitRun=function(SplitRun,SplitPos){this.m_aDocumentPositionsSplit=[];for(var PosIndex=0,PosCount=this.m_aDocumentPositions.length;PosIndex=SplitPos)this.m_aDocumentPositionsSplit.push({DocPos:DocPos,NewRunPos:_Pos.Position-SplitPos})}}}; -CDocumentPositionsManager.prototype.OnEnd_SplitRun=function(NewRun){if(!NewRun)return;for(var PosIndex=0,PosCount=this.m_aDocumentPositionsSplit.length;PosIndex0&&DocPos[DocPos.length-1].Class instanceof AscCommonWord.ParaRun){var Run=DocPos[DocPos.length-1].Class;var RunPos=DocPos[DocPos.length-1].Position;var Para=Run.GetParagraph();if(AscCommonWord.CanUpdatePosition(Para,Run)){DocPos.length=0;Run.GetDocumentPositionFromObject(DocPos);DocPos.push({Class:Run,Position:RunPos})}}};CDocumentPositionsManager.prototype.Remove_DocumentPosition=function(DocPos){for(var Pos=0,Count= -this.m_aDocumentPositions.length;Pos>0)+"px";this.HtmlElement.style.top=(_y*g_dKoef_mm_to_pix+.5>>0)+"px";this.HtmlElement.style.width=((_r-_x)*g_dKoef_mm_to_pix+.5>>0)+"px";this.HtmlElement.style.height=((_b-_y)*g_dKoef_mm_to_pix+.5>>0)+"px";if(api!==undefined&&api.CheckRetinaElement&&api.CheckRetinaElement(this.HtmlElement)){var _W=(_r-_x)*g_dKoef_mm_to_pix+.5>>0;var _H=(_b-_y)*g_dKoef_mm_to_pix+.5>>0;this.HtmlElement.width=AscCommon.AscBrowser.convertToRetinaValue(_W,true);this.HtmlElement.height= -AscCommon.AscBrowser.convertToRetinaValue(_H,true)}else{this.HtmlElement.width=(_r-_x)*g_dKoef_mm_to_pix+.5>>0;this.HtmlElement.height=(_b-_y)*g_dKoef_mm_to_pix+.5>>0}};this.GetCSS_width=function(){return(this.AbsolutePosition.R-this.AbsolutePosition.L)*g_dKoef_mm_to_pix+.5>>0};this.GetCSS_height=function(){return(this.AbsolutePosition.B-this.AbsolutePosition.T)*g_dKoef_mm_to_pix+.5>>0}}function CControlContainer(){this.Bounds=new CBounds;this.Anchor=g_anchor_left|g_anchor_top;this.Name=null;this.Parent= -null;this.TabIndex=null;this.HtmlElement=null;this.AbsolutePosition=new CBounds;this.Controls=[];this.AddControl=function(ctrl){ctrl.Parent=this;this.Controls[this.Controls.length]=ctrl};this.Resize=function(_width,_height,api){if(null==this.Parent){this.AbsolutePosition.L=0;this.AbsolutePosition.T=0;this.AbsolutePosition.R=_width;this.AbsolutePosition.B=_height;if(null!=this.HtmlElement){var lCount=this.Controls.length;for(var i=0;i>0)+"px";this.HtmlElement.style.top=(_y*g_dKoef_mm_to_pix+.5>>0)+"px";this.HtmlElement.style.width=((_r-_x)*g_dKoef_mm_to_pix+.5>>0)+"px";this.HtmlElement.style.height=((_b-_y)*g_dKoef_mm_to_pix+.5>>0)+"px";var lCount=this.Controls.length;for(var i=0;i>0};this.GetCSS_height=function(){return(this.AbsolutePosition.B-this.AbsolutePosition.T)*g_dKoef_mm_to_pix+.5>>0}}function CreateControlContainer(name){var ctrl=new CControlContainer;ctrl.Name=name;ctrl.HtmlElement=document.getElementById(name);return ctrl}function CreateControl(name){var ctrl=new CControl;ctrl.Name=name;ctrl.HtmlElement=document.getElementById(name);return ctrl}window["AscCommon"]=window["AscCommon"]|| -{};window["AscCommon"].g_anchor_left=g_anchor_left;window["AscCommon"].g_anchor_top=g_anchor_top;window["AscCommon"].g_anchor_right=g_anchor_right;window["AscCommon"].g_anchor_bottom=g_anchor_bottom;window["AscCommon"].CreateControlContainer=CreateControlContainer;window["AscCommon"].CreateControl=CreateControl})(window);"use strict";(function(window,undefined){var AscBrowser=AscCommon.AscBrowser;var TRACK_CIRCLE_RADIUS=5;var TRACK_RECT_SIZE2=4;var TRACK_RECT_SIZE=8;var TRACK_RECT_SIZE_CT=6;var TRACK_DISTANCE_ROTATE= -25;var TRACK_DISTANCE_ROTATE2=25;var TRACK_ADJUSTMENT_SIZE=10;var TRACK_WRAPPOINTS_SIZE=6;var IMAGE_ROTATE_TRACK_W=21;var bIsUseImageRotateTrack=true;if(bIsUseImageRotateTrack){window.g_track_rotate_marker=new Image;window.g_track_rotate_marker;window.g_track_rotate_marker.asc_complete=false;window.g_track_rotate_marker.onload=function(){window.g_track_rotate_marker.asc_complete=true};window.g_track_rotate_marker.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAMAAACeyVWkAAAAVFBMVEUAAAD///////////////////////////////////////////////////////98fHy2trb09PTT09OysrKqqqqJiYng4ODr6+uamprGxsbi4uKGhoYjgM0eAAAADnRSTlMAy00k7/z0jbeuMzDljsugwZgAAACpSURBVBjTdZHbEoMgDESDAl6bgIqX9v//s67UYpm6D0xyYMImoaiuUr3pVdVRUtnwqaY8YaE5SRcfaPgqc+DSIh7WIGGaEVoUqRGN4oZlcDIiqYlaPjQz5CNu6cFJwLiuSO3nlLBDrKhn3l4rcnH4NcAdGd5EZMfCsoMFBxM6CD57G+u6vC48PMVnHtrYhP/x+7+3cw7zdJnD3cyA7QXa4nYXaW+a9Xdvb6zqE5Jb7LmzAAAAAElFTkSuQmCC"; +pData};CCollaborativeChanges.prototype.Set_Color=function(oColor){this.m_oColor=oColor};CCollaborativeChanges.prototype.Set_FromUndoRedo=function(Class,Data,Binary){if(!Class.Get_Id)return false;this.m_pData=this.private_SaveData(Binary);return true};CCollaborativeChanges.prototype.Apply_Data=function(){var CollaborativeEditing=AscCommon.CollaborativeEditing;if(this.m_pData&&this.m_pData.type==="cp_theme"){clearTimeout(window.CP_theme_to);var data=this.m_pData;window.CP_theme_to=setTimeout(function(){window.parent.APP.remoteTheme(); +window.editor.ChangeTheme(data.id,null,true)});return true}var Reader=this.private_LoadData(this.m_pData);var ClassId=Reader.GetString2();var Class=AscCommon.g_oTableId.Get_ById(ClassId);if(!Class)return false;var nReaderPos=Reader.GetCurPos();var nChangesType=Reader.GetLong();var fChangesClass=AscDFH.changesFactory[nChangesType];if(fChangesClass){var oChange=new fChangesClass(Class);oChange.ReadFromBinary(Reader);if(true===CollaborativeEditing.private_AddOverallChange(oChange))oChange.Load(this.m_oColor); +return true}else{CollaborativeEditing.private_AddOverallChange(this.m_pData);Reader.Seek2(nReaderPos);if(!Class.Load_Changes)return false;return Class.Load_Changes(Reader,null,this.m_oColor)}};CCollaborativeChanges.prototype.private_LoadData=function(szSrc){return this.GetStream(szSrc,0,szSrc.length)};CCollaborativeChanges.prototype.GetStream=function(szSrc,offset,srcLen){var nWritten=0;var index=-1+offset;var dst_len="";while(true){index++;var _c=szSrc.charCodeAt(index);if(_c==";".charCodeAt(0)){index++; +break}dst_len+=String.fromCharCode(_c)}var dstLen=parseInt(dst_len);var pointer=AscFonts.g_memory.Alloc(dstLen);var stream=new AscCommon.FT_Stream2(pointer.data,dstLen);stream.obj=pointer.obj;var dstPx=stream.data;if(window.chrome)while(index=srcLen)break;var nCh=AscFonts.DecodeBase64Char(szSrc.charCodeAt(index++));if(nCh==-1){i--;continue}dwCurr<<=6;dwCurr|=nCh;nBits+=6}dwCurr<<=24-nBits;for(i=0;i>>16;dwCurr<<=8}}else{var p=AscFonts.b64_decode;while(index=srcLen)break;var nCh=p[szSrc.charCodeAt(index++)];if(nCh==undefined){i--;continue}dwCurr<<=6;dwCurr|=nCh;nBits+=6}dwCurr<<=24-nBits;for(i=0;i>>16;dwCurr<<=8}}}return stream};CCollaborativeChanges.prototype.private_SaveData=function(Binary){var Writer=AscCommon.History.BinaryWriter;var Pos=Binary.Pos;var Len=Binary.Len; +return Len+";"+Writer.GetBase64Memory2(Pos,Len)};function CCollaborativeEditingBase(){this.m_nUseType=1;this.m_aUsers=[];this.m_aChanges=[];this.m_aNeedUnlock=[];this.m_aNeedUnlock2=[];this.m_aNeedLock=[];this.m_aLinkData=[];this.m_aEndActions=[];this.m_bGlobalLock=0;this.m_bGlobalLockSelection=0;this.m_aCheckLocks=[];this.m_aCheckLocksInstance=[];this.m_aNewObjects=[];this.m_aNewImages=[];this.m_aDC={};this.m_aChangedClasses={};this.m_oMemory=null;this.m_aCursorsToUpdate={};this.m_aCursorsToUpdateShortId= +{};this.m_bFast=false;this.m_oLogicDocument=null;this.m_aDocumentPositions=new CDocumentPositionsManager;this.m_aForeignCursorsPos=new CDocumentPositionsManager;this.m_aForeignCursors={};this.m_aForeignCursorsId={};this.m_nAllChangesSavedIndex=0;this.m_aAllChanges=[];this.m_aOwnChangesIndexes=[];this.m_oOwnChanges=[]}CCollaborativeEditingBase.prototype.Clear=function(){this.m_nUseType=1;this.m_aUsers=[];this.m_aChanges=[];this.m_aNeedUnlock=[];this.m_aNeedUnlock2=[];this.m_aNeedLock=[];this.m_aLinkData= +[];this.m_aEndActions=[];this.m_aCheckLocks=[];this.m_aCheckLocksInstance=[];this.m_aNewObjects=[];this.m_aNewImages=[]};CCollaborativeEditingBase.prototype.Set_Fast=function(bFast){this.m_bFast=bFast;if(false===bFast){this.Remove_AllForeignCursors();this.RemoveMyCursorFromOthers()}};CCollaborativeEditingBase.prototype.Is_Fast=function(){return this.m_bFast};CCollaborativeEditingBase.prototype.Is_SingleUser=function(){return 1===this.m_nUseType};CCollaborativeEditingBase.prototype.getCollaborativeEditing= +function(){return!this.Is_SingleUser()};CCollaborativeEditingBase.prototype.Start_CollaborationEditing=function(){this.m_nUseType=-1};CCollaborativeEditingBase.prototype.End_CollaborationEditing=function(){if(this.m_nUseType<=0)this.m_nUseType=0};CCollaborativeEditingBase.prototype.Add_User=function(UserId){if(-1===this.Find_User(UserId))this.m_aUsers.push(UserId)};CCollaborativeEditingBase.prototype.Find_User=function(UserId){var Len=this.m_aUsers.length;for(var Index=0;Index0;if(true===OtherChanges){AscFonts.IsCheckSymbols=true;editor.WordControl.m_oLogicDocument.StopRecalculate();editor.WordControl.m_oLogicDocument.EndPreview_MailMergeResult();editor.sync_StartAction(Asc.c_oAscAsyncActionType.BlockInteraction,Asc.c_oAscAsyncAction.ApplyChanges);var DocState=this.private_SaveDocumentState();this.Clear_NewImages();this.Apply_OtherChanges(); +this.Lock_NeedLock();this.private_RestoreDocumentState(DocState);this.OnStart_Load_Objects();AscFonts.IsCheckSymbols=false}};CCollaborativeEditingBase.prototype.Apply_OtherChanges=function(){AscCommon.g_oIdCounter.Set_Load(true);if(this.m_aChanges.length>0)this.private_CollectOwnChanges();var _count=this.m_aChanges.length;for(var i=0;i<_count;i++){if(window["NATIVE_EDITOR_ENJINE"]===true&&window["native"]["CheckNextChange"])if(!window["native"]["CheckNextChange"]())break;var Changes=this.m_aChanges[i]; +Changes.Apply_Data()}this.private_ClearChanges();this.Apply_LinkData();this.Check_MergeData();this.OnEnd_ReadForeignChanges();AscCommon.g_oIdCounter.Set_Load(false)};CCollaborativeEditingBase.prototype.getOwnLocksLength=function(){return this.m_aNeedUnlock2.length};CCollaborativeEditingBase.prototype.Send_Changes=function(){};CCollaborativeEditingBase.prototype.Release_Locks=function(){};CCollaborativeEditingBase.prototype.CheckWaitingImages=function(aImages){};CCollaborativeEditingBase.prototype.SendImagesUrlsFromChanges= +function(aImages){var rData={},oApi=editor||Asc["editor"],i;if(!oApi)return;rData["c"]="pathurls";rData["data"]=[];for(i=0;i0)this.SendImagesUrlsFromChanges(aImages);else{this.SendImagesCallback([].concat(this.m_aNewImages));this.m_aNewImages.length=0}};CCollaborativeEditingBase.prototype.OnEnd_Load_Objects=function(){};CCollaborativeEditingBase.prototype.Clear_LinkData=function(){this.m_aLinkData.length=0};CCollaborativeEditingBase.prototype.Add_LinkData=function(Class,LinkData){this.m_aLinkData.push({Class:Class,LinkData:LinkData})}; +CCollaborativeEditingBase.prototype.Apply_LinkData=function(){var Count=this.m_aLinkData.length;for(var Index=0;Index +0){this.m_aOwnChangesIndexes.push({Position:this.m_aAllChanges.length,Count:arrChanges.length});this.m_aAllChanges=this.m_aAllChanges.concat(arrChanges)}};CCollaborativeEditingBase.prototype.Undo=function(){if(true===this.Get_GlobalLock())return;if(this.m_aOwnChangesIndexes.length<=0)return false;var arrChanges=[];var oIndexes=this.m_aOwnChangesIndexes[this.m_aOwnChangesIndexes.length-1];var nPosition=oIndexes.Position;var nCount=oIndexes.Count;for(var nIndex=nCount-1;nIndex>=0;--nIndex){var oChange= +this.m_aAllChanges[nPosition+nIndex];if(!oChange)continue;var oClass=oChange.GetClass();if(oChange.IsContentChange()){var _oChange=oChange.Copy();if(this.private_CommutateContentChanges(_oChange,nPosition+nCount))arrChanges.push(_oChange);oChange.SetReverted(true)}else{var _oChange=oChange;if(this.private_CommutatePropertyChanges(oClass,_oChange,nPosition+nCount))arrChanges.push(_oChange)}}this.m_aOwnChangesIndexes.length=this.m_aOwnChangesIndexes.length-1;var arrReverseChanges=[];for(var nIndex= +0,nCount=arrChanges.length;nIndex-1;--i)if(mapAddedSlides[oLogicDocument.Slides[i].Get_Id()]&&!oLogicDocument.Slides[i].Layout)oLogicDocument.removeSlide(i);for(var sId in mapSlides)if(mapSlides.hasOwnProperty(sId))mapSlides[sId].correctContent();if(bChangedLayout)for(var i=oLogicDocument.Slides.length-1;i>-1;--i){var Layout= +oLogicDocument.Slides[i].Layout;if(!Layout||mapLayouts[Layout.Get_Id()])if(!oLogicDocument.Slides[i].CheckLayout())oLogicDocument.removeSlide(i)}for(var sId in mapGrObjects){var oShape=mapGrObjects[sId];if(!oShape.checkCorrect()){oShape.setBDeleted(true);if(oShape.group)oShape.group.removeFromSpTree(oShape.Get_Id());else if(AscFormat.Slide&&oShape.parent instanceof AscFormat.Slide)oShape.parent.removeFromSpTreeById(oShape.Get_Id());else if(AscCommonWord.ParaDrawing&&oShape.parent instanceof AscCommonWord.ParaDrawing)mapDrawings[oShape.parent.Get_Id()]= +oShape.parent}else if(oShape.resetGroups)oShape.resetGroups()}var oDrawing;for(var sId in mapDrawings)if(mapDrawings.hasOwnProperty(sId)){oDrawing=mapDrawings[sId];if(!oDrawing.CheckCorrect()){var oParentParagraph=oDrawing.Get_ParentParagraph();oDrawing.PreDelete();oDrawing.Remove_FromDocument(false);if(oParentParagraph)mapParagraphs[oParentParagraph.Get_Id()]=oParentParagraph}}for(var sId in mapRuns)if(mapRuns.hasOwnProperty(sId)){var oRun=mapRuns[sId];for(var nIndex=oRun.Content.length-1;nIndex> +-1;--nIndex)if(oRun.Content[nIndex]instanceof AscCommonWord.ParaDrawing)if(!oRun.Content[nIndex].CheckCorrect()){oRun.Remove_FromContent(nIndex,1,false);if(oRun.Paragraph)mapParagraphs[oRun.Paragraph.Get_Id()]=oRun.Paragraph}}for(var sId in mapTables){var oTable=mapTables[sId];for(var nCurRow=oTable.Content.length-1;nCurRow>=0;--nCurRow){var oRow=oTable.Get_Row(nCurRow);if(oRow.Get_CellsCount()<=0)oTable.private_RemoveRow(nCurRow)}if(oTable.Parent instanceof AscCommonWord.CDocument||oTable.Parent instanceof +AscCommonWord.CDocumentContent)mapDocumentContents[oTable.Parent.Get_Id()]=oTable.Parent}for(var sId in mapDocumentContents){var oDocumentContent=mapDocumentContents[sId];var nContentLen=oDocumentContent.Content.length;for(var nIndex=nContentLen-1;nIndex>=0;--nIndex){var oElement=oDocumentContent.Content[nIndex];if((AscCommonWord.type_Paragraph===oElement.GetType()||AscCommonWord.type_Table===oElement.GetType())&&oElement.Content.length<=0)oDocumentContent.Remove_FromContent(nIndex,1)}nContentLen= +oDocumentContent.Content.length;if(nContentLen<=0||AscCommonWord.type_Paragraph!==oDocumentContent.Content[nContentLen-1].GetType()){var oNewParagraph=new AscCommonWord.Paragraph(oLogicDocument.Get_DrawingDocument(),oDocumentContent,0,0,0,0,0,false);oDocumentContent.Add_ToContent(nContentLen,oNewParagraph)}}for(var sId in mapParagraphs){var oParagraph=mapParagraphs[sId];oParagraph.CheckParaEnd();oParagraph.Correct_Content(null,null,true)}var oBinaryWriter=AscCommon.History.BinaryWriter;var aSendingChanges= +[];for(var nIndex=0,nCount=arrReverseChanges.length;nIndex=0;--nActionIndex){var oAction=arrActions[nActionIndex];var oResult=oAction;for(var nIndex=nStartPosition,nOverallCount=this.m_aAllChanges.length;nIndex0)oChange.ConvertFromSimpleActions(arrCommutateActions);else return false;return true};CCollaborativeEditingBase.prototype.private_Commutate=function(oActionL,oActionR){if(oActionL.Add)if(oActionR.Add)if(oActionL.Pos>=oActionR.Pos)oActionL.Pos++;else oActionR.Pos--;else if(oActionL.Pos>oActionR.Pos)oActionL.Pos--;else if(oActionL.Pos===oActionR.Pos)return false;else oActionR.Pos--;else if(oActionR.Add)if(oActionL.Pos>=oActionR.Pos)oActionL.Pos++; +else oActionR.Pos++;else if(oActionL.Pos>oActionR.Pos)oActionL.Pos--;else oActionR.Pos++;return true};CCollaborativeEditingBase.prototype.private_CommutatePropertyChanges=function(oClass,oChange,nStartPosition){if(oChange.CheckCorrect&&!oChange.CheckCorrect())return false;return true};CCollaborativeEditingBase.prototype.private_RecalculateDocument=function(oRecalcData){};function CDocumentPositionsManager(){this.m_aDocumentPositions=[];this.m_aDocumentPositionsSplit=[];this.m_aDocumentPositionsMap= +[]}CDocumentPositionsManager.prototype.Clear_DocumentPositions=function(){this.m_aDocumentPositions=[];this.m_aDocumentPositionsSplit=[];this.m_aDocumentPositionsMap=[]};CDocumentPositionsManager.prototype.Add_DocumentPosition=function(Position){this.m_aDocumentPositions.push(Position)};CDocumentPositionsManager.prototype.Update_DocumentPositionsOnAdd=function(Class,Pos){for(var PosIndex=0,PosCount=this.m_aDocumentPositions.length;PosIndexPos||_Pos.Position===Pos&&!(Class instanceof AscCommonWord.ParaRun))){_Pos.Position++;break}}}};CDocumentPositionsManager.prototype.Update_DocumentPositionsOnRemove=function(Class,Pos,Count){for(var PosIndex=0,PosCount=this.m_aDocumentPositions.length;PosIndexPos+Count)_Pos.Position-=Count;else if(_Pos.Position>=Pos){_Pos.Position=Pos;_Pos.Deleted=true}break}}}};CDocumentPositionsManager.prototype.OnStart_SplitRun=function(SplitRun,SplitPos){this.m_aDocumentPositionsSplit=[];for(var PosIndex=0,PosCount=this.m_aDocumentPositions.length;PosIndex=SplitPos)this.m_aDocumentPositionsSplit.push({DocPos:DocPos,NewRunPos:_Pos.Position-SplitPos})}}};CDocumentPositionsManager.prototype.OnEnd_SplitRun=function(NewRun){if(!NewRun)return;for(var PosIndex=0,PosCount=this.m_aDocumentPositionsSplit.length;PosIndex0&&DocPos[DocPos.length-1].Class instanceof AscCommonWord.ParaRun){var Run=DocPos[DocPos.length-1].Class;var RunPos=DocPos[DocPos.length-1].Position;var Para=Run.GetParagraph();if(AscCommonWord.CanUpdatePosition(Para, +Run)){DocPos.length=0;Run.GetDocumentPositionFromObject(DocPos);DocPos.push({Class:Run,Position:RunPos})}}};CDocumentPositionsManager.prototype.Remove_DocumentPosition=function(DocPos){for(var Pos=0,Count=this.m_aDocumentPositions.length;Pos>0)+"px";this.HtmlElement.style.top=(_y*g_dKoef_mm_to_pix+.5>>0)+"px";this.HtmlElement.style.width=((_r-_x)*g_dKoef_mm_to_pix+.5>>0)+"px";this.HtmlElement.style.height=((_b-_y)*g_dKoef_mm_to_pix+.5>>0)+"px";if(api!==undefined&&api.CheckRetinaElement&& +api.CheckRetinaElement(this.HtmlElement)){var _W=(_r-_x)*g_dKoef_mm_to_pix+.5>>0;var _H=(_b-_y)*g_dKoef_mm_to_pix+.5>>0;this.HtmlElement.width=AscCommon.AscBrowser.convertToRetinaValue(_W,true);this.HtmlElement.height=AscCommon.AscBrowser.convertToRetinaValue(_H,true)}else{this.HtmlElement.width=(_r-_x)*g_dKoef_mm_to_pix+.5>>0;this.HtmlElement.height=(_b-_y)*g_dKoef_mm_to_pix+.5>>0}};this.GetCSS_width=function(){return(this.AbsolutePosition.R-this.AbsolutePosition.L)*g_dKoef_mm_to_pix+.5>>0};this.GetCSS_height= +function(){return(this.AbsolutePosition.B-this.AbsolutePosition.T)*g_dKoef_mm_to_pix+.5>>0}}function CControlContainer(){this.Bounds=new CBounds;this.Anchor=g_anchor_left|g_anchor_top;this.Name=null;this.Parent=null;this.TabIndex=null;this.HtmlElement=null;this.AbsolutePosition=new CBounds;this.Controls=[];this.AddControl=function(ctrl){ctrl.Parent=this;this.Controls[this.Controls.length]=ctrl};this.Resize=function(_width,_height,api){if(null==this.Parent){this.AbsolutePosition.L=0;this.AbsolutePosition.T= +0;this.AbsolutePosition.R=_width;this.AbsolutePosition.B=_height;if(null!=this.HtmlElement){var lCount=this.Controls.length;for(var i=0;i>0)+"px";this.HtmlElement.style.top=(_y*g_dKoef_mm_to_pix+.5>>0)+"px";this.HtmlElement.style.width=((_r-_x)* +g_dKoef_mm_to_pix+.5>>0)+"px";this.HtmlElement.style.height=((_b-_y)*g_dKoef_mm_to_pix+.5>>0)+"px";var lCount=this.Controls.length;for(var i=0;i>0};this.GetCSS_height=function(){return(this.AbsolutePosition.B-this.AbsolutePosition.T)*g_dKoef_mm_to_pix+.5>>0}}function CreateControlContainer(name){var ctrl=new CControlContainer;ctrl.Name=name; +ctrl.HtmlElement=document.getElementById(name);return ctrl}function CreateControl(name){var ctrl=new CControl;ctrl.Name=name;ctrl.HtmlElement=document.getElementById(name);return ctrl}window["AscCommon"]=window["AscCommon"]||{};window["AscCommon"].g_anchor_left=g_anchor_left;window["AscCommon"].g_anchor_top=g_anchor_top;window["AscCommon"].g_anchor_right=g_anchor_right;window["AscCommon"].g_anchor_bottom=g_anchor_bottom;window["AscCommon"].CreateControlContainer=CreateControlContainer;window["AscCommon"].CreateControl= +CreateControl})(window);"use strict";(function(window,undefined){var AscBrowser=AscCommon.AscBrowser;var TRACK_CIRCLE_RADIUS=5;var TRACK_RECT_SIZE2=4;var TRACK_RECT_SIZE=8;var TRACK_RECT_SIZE_CT=6;var TRACK_DISTANCE_ROTATE=25;var TRACK_DISTANCE_ROTATE2=25;var TRACK_ADJUSTMENT_SIZE=10;var TRACK_WRAPPOINTS_SIZE=6;var IMAGE_ROTATE_TRACK_W=21;var bIsUseImageRotateTrack=true;if(bIsUseImageRotateTrack){window.g_track_rotate_marker=new Image;window.g_track_rotate_marker;window.g_track_rotate_marker.asc_complete= +false;window.g_track_rotate_marker.onload=function(){window.g_track_rotate_marker.asc_complete=true};window.g_track_rotate_marker.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAMAAACeyVWkAAAAVFBMVEUAAAD///////////////////////////////////////////////////////98fHy2trb09PTT09OysrKqqqqJiYng4ODr6+uamprGxsbi4uKGhoYjgM0eAAAADnRSTlMAy00k7/z0jbeuMzDljsugwZgAAACpSURBVBjTdZHbEoMgDESDAl6bgIqX9v//s67UYpm6D0xyYMImoaiuUr3pVdVRUtnwqaY8YaE5SRcfaPgqc+DSIh7WIGGaEVoUqRGN4oZlcDIiqYlaPjQz5CNu6cFJwLiuSO3nlLBDrKhn3l4rcnH4NcAdGd5EZMfCsoMFBxM6CD57G+u6vC48PMVnHtrYhP/x+7+3cw7zdJnD3cyA7QXa4nYXaW+a9Xdvb6zqE5Jb7LmzAAAAAElFTkSuQmCC"; window.g_track_rotate_marker2=new Image;window.g_track_rotate_marker2;window.g_track_rotate_marker2.asc_complete=false;window.g_track_rotate_marker2.onload=function(){window.g_track_rotate_marker2.asc_complete=true};window.g_track_rotate_marker2.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAMAAAC7IEhfAAAAeFBMVEUAAAD///////////////////////////////////////////////////////////////////////////+Tk5Obm5v8/PzAwMD5+fmWlpbt7e3k5OSfn5/z8/PLy8vn5+fExMSsrKyqqqrf39+vr6+9vb2urq7c3NxSmuRpAAAAE3RSTlMA+u2XA+PTrId4WBwTN7EKtLY4iqQP6AAAAWhJREFUOMudVe2SgjAMLN+goN51CxTLp3r3/m943BAqIJTR/RU6O02yTRY2g5tEgW9blu0HUeKyLRxDj0/ghcdVWuxYfAHLiV95B5uvwD4saK7DN+DMSj1f+CYu58l9J27A6XnnJG9R3ZWU6l4Vk+y6D310baHRXvUxdRSP/aYZILJbmebFLRNAlo69x7PEeQdZ5Xz8qiS6fJr8aOnEquATFApdSsr/v1HINUo+Q6nwoDDspfH4JmoJ6shzWcINaNBSlLCI6uvLfyXmAlR2xIKBB/A1ZKiGIGA+8QCtphBawRt+hsBnNvE0M0OPZmwcijRnFvE0U6CuIcbrIUlJRnJL9L0YifTQCgU3p/aH4I7fnWaCIajwMMszCl5A7Aj+TWctGuMT6qG4QtbGodBj9oAyjpke3LSDYXCXq9A8V6GZrsLGcqXlcrneW9elAQgpxdwA3rcUdv4ymdQHtrdvpPvW/LHZ7/8+/gBTWGFPbAkGiAAAAABJRU5ErkJggg=="; TRACK_DISTANCE_ROTATE2=18}function COverlay(){this.m_oControl=null;this.m_oContext=null;this.min_x=65535;this.min_y=65535;this.max_x=-65535;this.max_y=-65535;this.m_bIsShow=false;this.m_bIsAlwaysUpdateOverlay=false;this.m_oHtmlPage=null;this.DashLineColor="#000000";this.ClearAll=false;this.IsRetina=false;this.IsCellEditor=false}COverlay.prototype={init:function(context,controlName,x,y,w_pix,h_pix,w_mm,h_mm){this.m_oContext=context;this.m_oControl=AscCommon.CreateControl(controlName);this.m_oHtmlPage= new AscCommon.CHtmlPage;this.m_oHtmlPage.init(x,y,w_pix,h_pix,w_mm,h_mm)},Clear:function(){if(null==this.m_oContext){this.m_oContext=this.m_oControl.HtmlElement.getContext("2d");this.m_oContext.imageSmoothingEnabled=false;this.m_oContext.mozImageSmoothingEnabled=false;this.m_oContext.oImageSmoothingEnabled=false;this.m_oContext.webkitImageSmoothingEnabled=false}this.SetBaseTransform();this.m_oContext.beginPath();if(this.max_x!=-65535&&this.max_y!=-65535)if(this.ClearAll===true){this.m_oContext.clearRect(0, diff --git a/www/common/onlyoffice/v4/sdkjs/slide/sdk-all-min.js b/www/common/onlyoffice/v4/sdkjs/slide/sdk-all-min.js index c2762ee40..738dacf5c 100644 --- a/www/common/onlyoffice/v4/sdkjs/slide/sdk-all-min.js +++ b/www/common/onlyoffice/v4/sdkjs/slide/sdk-all-min.js @@ -266,13 +266,13 @@ editorType;this._isExcel=c_oEditorId.Spreadsheet===editorType;this._isPresentati docid;this.sockjs_url=AscCommon.getBaseUrl()+"../../../../doc/"+docid+"/c"};DocsCoApi.prototype.auth=function(isViewer,opt_openCmd,opt_isIdle){this._isViewer=isViewer;if(this._locks){this.ownedLockBlocks=[];for(var block in this._locks)if(this._locks.hasOwnProperty(block)){var lock=this._locks[block];if(lock["state"]===2)this.ownedLockBlocks.push(lock["blockValue"])}this._locks={}}this._send({"type":"auth","docid":this._docid,"documentCallbackUrl":this._documentCallbackUrl,"token":this._token,"user":{"id":this._user.asc_getId(), "username":this._user.asc_getUserName(),"firstname":this._user.asc_getFirstName(),"lastname":this._user.asc_getLastName(),"indexUser":this._indexUser},"editorType":this.editorType,"lastOtherSaveTime":this.lastOtherSaveTime,"block":this.ownedLockBlocks,"sessionId":this._id,"sessionTimeConnect":this._sessionTimeConnect,"sessionTimeIdle":opt_isIdle>=0?opt_isIdle:0,"documentFormatSave":this._documentFormatSave,"view":this._isViewer,"isCloseCoAuthoring":this.isCloseCoAuthoring,"openCmd":opt_openCmd,"lang":this.lang, "mode":this.mode,"permissions":this.permissions,"encrypted":this.encrypted,"jwtOpen":this.jwtOpen,"jwtSession":this.jwtSession})};DocsCoApi.prototype._initSocksJs=function(){var t=this;var sockjs;sockjs=this.sockjs={};var send=function(data){setTimeout(function(){sockjs.onmessage({data:JSON.stringify(data)})})};var license={type:"license",license:{type:3,mode:0,rights:1,buildVersion:"5.2.6",buildNumber:2}};var channel;require(["/common/outer/worker-channel.js","/common/common-util.js"],function(Channel, -Util){var msgEv=Util.mkEvent();var p=window.parent;window.addEventListener("message",function(msg){if(msg.source!==p)return;msgEv.fire(msg)});var postMsg=function(data){p.postMessage(data,"*")};Channel.create(msgEv,postMsg,function(chan){channel=chan;send(license);chan.on("CMD",function(obj){send(obj)})})});sockjs.onopen=function(){t._state=ConnectionState.WaitAuth;t.onFirstConnect()};sockjs.onopen();sockjs.close=function(){console.error("Close realtime")};sockjs.send=function(data){try{var obj=JSON.parse(data)}catch(e){console.error(e); -return}if(channel)channel.event("CMD",obj)};sockjs.onmessage=function(e){t._onServerMessage(e.data)};return sockjs};DocsCoApi.prototype._onServerOpen=function(){if(this.reconnectTimeout){clearTimeout(this.reconnectTimeout);this.reconnectTimeout=null;this.attemptCount=0}this._state=ConnectionState.WaitAuth;this.onFirstConnect()};DocsCoApi.prototype._onServerMessage=function(data){var dataObject=JSON.parse(data);switch(dataObject["type"]){case "auth":this._onAuth(dataObject);break;case "message":this._onMessages(dataObject, -false);break;case "cursor":this._onCursor(dataObject);break;case "meta":this._onMeta(dataObject);break;case "getLock":this._onGetLock(dataObject);break;case "releaseLock":this._onReleaseLock(dataObject);break;case "connectState":this._onConnectionStateChanged(dataObject);break;case "saveChanges":this._onSaveChanges(dataObject);break;case "authChanges":this._onAuthChanges(dataObject);break;case "saveLock":this._onSaveLock(dataObject);break;case "unSaveLock":this._onUnSaveLock(dataObject);break;case "savePartChanges":this._onSavePartChanges(dataObject); -break;case "drop":this._onDrop(dataObject);break;case "waitAuth":break;case "error":this._onDrop(dataObject);break;case "documentOpen":this._documentOpen(dataObject);break;case "warning":this._onWarning(dataObject);break;case "license":this._onLicense(dataObject);break;case "session":this._onSession(dataObject);break;case "refreshToken":this._onRefreshToken(dataObject["messages"]);break;case "expiredToken":this._onExpiredToken(dataObject);break;case "forceSaveStart":this._onForceSaveStart(dataObject["messages"]); -break;case "forceSave":this._onForceSave(dataObject["messages"]);break}};DocsCoApi.prototype._onServerClose=function(evt){if(ConnectionState.SaveChanges===this._state){this._isReSaveAfterAuth=true;if(null!==this.saveCallbackErrorTimeOutId){clearTimeout(this.saveCallbackErrorTimeOutId);this.saveCallbackErrorTimeOutId=null}}this._state=ConnectionState.Reconnect;var bIsDisconnectAtAll=c_oCloseCode.serverShutdown<=evt.code&&evt.code<=c_oCloseCode.drop||this.attemptCount>=this.maxAttemptCount;var code= -null;if(bIsDisconnectAtAll){this._state=ConnectionState.ClosedAll;code=evt.code}if(this.onDisconnect)this.onDisconnect(evt.reason,code);if(!bIsDisconnectAtAll)this._tryReconnect()};DocsCoApi.prototype._reconnect=function(){delete this.sockjs;this._initSocksJs()};DocsCoApi.prototype._tryReconnect=function(){var t=this;if(this.reconnectTimeout){clearTimeout(this.reconnectTimeout);t.reconnectTimeout=null}++this.attemptCount;this.reconnectTimeout=setTimeout(function(){t._reconnect()},this.reconnectInterval)}; -window["AscCommon"]=window["AscCommon"]||{};window["AscCommon"].CDocsCoApi=CDocsCoApi})(window);"use strict"; +Util){var msgEv=Util.mkEvent();var p=window.parent;if(editor&&editor.isReporterMode){p=window.opener;window.parent=p}else window.APP=p&&p.APP;window.addEventListener("message",function(msg){if(msg.source!==p)return;msgEv.fire(msg)});var postMsg=function(data){p.postMessage(data,"*")};Channel.create(msgEv,postMsg,function(chan){channel=chan;send(license);chan.on("CMD",function(obj){send(obj)})})});sockjs.onopen=function(){t._state=ConnectionState.WaitAuth;t.onFirstConnect()};sockjs.onopen();sockjs.close= +function(){console.error("Close realtime")};sockjs.send=function(data){try{var obj=JSON.parse(data)}catch(e){console.error(e);return}if(channel)channel.event("CMD",obj)};sockjs.onmessage=function(e){t._onServerMessage(e.data)};return sockjs};DocsCoApi.prototype._onServerOpen=function(){if(this.reconnectTimeout){clearTimeout(this.reconnectTimeout);this.reconnectTimeout=null;this.attemptCount=0}this._state=ConnectionState.WaitAuth;this.onFirstConnect()};DocsCoApi.prototype._onServerMessage=function(data){var dataObject= +JSON.parse(data);switch(dataObject["type"]){case "auth":this._onAuth(dataObject);break;case "message":this._onMessages(dataObject,false);break;case "cursor":this._onCursor(dataObject);break;case "meta":this._onMeta(dataObject);break;case "getLock":this._onGetLock(dataObject);break;case "releaseLock":this._onReleaseLock(dataObject);break;case "connectState":this._onConnectionStateChanged(dataObject);break;case "saveChanges":this._onSaveChanges(dataObject);break;case "authChanges":this._onAuthChanges(dataObject); +break;case "saveLock":this._onSaveLock(dataObject);break;case "unSaveLock":this._onUnSaveLock(dataObject);break;case "savePartChanges":this._onSavePartChanges(dataObject);break;case "drop":this._onDrop(dataObject);break;case "waitAuth":break;case "error":this._onDrop(dataObject);break;case "documentOpen":this._documentOpen(dataObject);break;case "warning":this._onWarning(dataObject);break;case "license":this._onLicense(dataObject);break;case "session":this._onSession(dataObject);break;case "refreshToken":this._onRefreshToken(dataObject["messages"]); +break;case "expiredToken":this._onExpiredToken(dataObject);break;case "forceSaveStart":this._onForceSaveStart(dataObject["messages"]);break;case "forceSave":this._onForceSave(dataObject["messages"]);break}};DocsCoApi.prototype._onServerClose=function(evt){if(ConnectionState.SaveChanges===this._state){this._isReSaveAfterAuth=true;if(null!==this.saveCallbackErrorTimeOutId){clearTimeout(this.saveCallbackErrorTimeOutId);this.saveCallbackErrorTimeOutId=null}}this._state=ConnectionState.Reconnect;var bIsDisconnectAtAll= +c_oCloseCode.serverShutdown<=evt.code&&evt.code<=c_oCloseCode.drop||this.attemptCount>=this.maxAttemptCount;var code=null;if(bIsDisconnectAtAll){this._state=ConnectionState.ClosedAll;code=evt.code}if(this.onDisconnect)this.onDisconnect(evt.reason,code);if(!bIsDisconnectAtAll)this._tryReconnect()};DocsCoApi.prototype._reconnect=function(){delete this.sockjs;this._initSocksJs()};DocsCoApi.prototype._tryReconnect=function(){var t=this;if(this.reconnectTimeout){clearTimeout(this.reconnectTimeout);t.reconnectTimeout= +null}++this.attemptCount;this.reconnectTimeout=setTimeout(function(){t._reconnect()},this.reconnectInterval)};window["AscCommon"]=window["AscCommon"]||{};window["AscCommon"].CDocsCoApi=CDocsCoApi})(window);"use strict"; (function(window){var CSpellCheckApi=function(){this._SpellCheckApi=new SpellCheckApi;this._onlineWork=false;this.onDisconnect=null;this.onSpellCheck=null};CSpellCheckApi.prototype.init=function(docid){if(this._SpellCheckApi&&this._SpellCheckApi.isRightURL()){var t=this;this._SpellCheckApi.onDisconnect=function(e,isDisconnectAtAll,isCloseCoAuthoring){t.callback_OnDisconnect(e,isDisconnectAtAll,isCloseCoAuthoring)};this._SpellCheckApi.onSpellCheck=function(e){t.callback_OnSpellCheck(e)};this._SpellCheckApi.onInit= function(e){t.callback_OnInit(e)};this._SpellCheckApi.init(docid);this._onlineWork=true}};CSpellCheckApi.prototype.set_url=function(url){if(this._SpellCheckApi)this._SpellCheckApi.set_url(url)};CSpellCheckApi.prototype.get_state=function(){if(this._SpellCheckApi)return this._SpellCheckApi.get_state();return 0};CSpellCheckApi.prototype.disconnect=function(){if(this._SpellCheckApi&&this._onlineWork)this._SpellCheckApi.disconnect()};CSpellCheckApi.prototype.spellCheck=function(spellCheckData){if(this._SpellCheckApi&& this._onlineWork)this._SpellCheckApi.spellCheck(spellCheckData)};CSpellCheckApi.prototype.checkDictionary=function(lang){if(this._SpellCheckApi&&this._onlineWork)return this._SpellCheckApi.checkDictionary(lang);return true};CSpellCheckApi.prototype.callback_OnSpellCheck=function(e){if(this.onSpellCheck)return this.onSpellCheck(e)};CSpellCheckApi.prototype.callback_OnInit=function(e){if(this.onInit)return this.onInit(e)};CSpellCheckApi.prototype.callback_OnDisconnect=function(e,isDisconnectAtAll,isCloseCoAuthoring){if(this.onDisconnect)return this.onDisconnect(e, @@ -1356,62 +1356,62 @@ prot["Clock_Clockwise"]=c_oAscSlideTransitionParams.Clock_Clockwise;prot["Clock_ prot["EditSelectAll"]=c_oAscPresentationShortcutType.EditSelectAll;prot["EditUndo"]=c_oAscPresentationShortcutType.EditUndo;prot["EditRedo"]=c_oAscPresentationShortcutType.EditRedo;prot["Cut"]=c_oAscPresentationShortcutType.Cut;prot["Copy"]=c_oAscPresentationShortcutType.Copy;prot["Paste"]=c_oAscPresentationShortcutType.Paste;prot["Duplicate"]=c_oAscPresentationShortcutType.Duplicate;prot["Print"]=c_oAscPresentationShortcutType.Print;prot["Save"]=c_oAscPresentationShortcutType.Save; prot["ShowContextMenu"]=c_oAscPresentationShortcutType.ShowContextMenu;window["AscCommon"]=window["AscCommon"]||{};window["AscCommon"].c_oSerFormat=c_oSerFormat;window["AscCommon"].CurFileVersion=c_oSerFormat.Version;"use strict"; (function(window,undefined){var FOREIGN_CURSOR_LABEL_HIDETIME=1500;function CCollaborativeChanges(){this.m_pData=null;this.m_oColor=null}CCollaborativeChanges.prototype.Set_Data=function(pData){this.m_pData=pData};CCollaborativeChanges.prototype.Set_Color=function(oColor){this.m_oColor=oColor};CCollaborativeChanges.prototype.Set_FromUndoRedo=function(Class,Data,Binary){if(!Class.Get_Id)return false;this.m_pData=this.private_SaveData(Binary);return true};CCollaborativeChanges.prototype.Apply_Data= -function(){var CollaborativeEditing=AscCommon.CollaborativeEditing;var Reader=this.private_LoadData(this.m_pData);var ClassId=Reader.GetString2();var Class=AscCommon.g_oTableId.Get_ById(ClassId);if(!Class)return false;var nReaderPos=Reader.GetCurPos();var nChangesType=Reader.GetLong();var fChangesClass=AscDFH.changesFactory[nChangesType];if(fChangesClass){var oChange=new fChangesClass(Class);oChange.ReadFromBinary(Reader);if(true===CollaborativeEditing.private_AddOverallChange(oChange))oChange.Load(this.m_oColor); -return true}else{CollaborativeEditing.private_AddOverallChange(this.m_pData);Reader.Seek2(nReaderPos);if(!Class.Load_Changes)return false;return Class.Load_Changes(Reader,null,this.m_oColor)}};CCollaborativeChanges.prototype.private_LoadData=function(szSrc){return this.GetStream(szSrc,0,szSrc.length)};CCollaborativeChanges.prototype.GetStream=function(szSrc,offset,srcLen){var nWritten=0;var index=-1+offset;var dst_len="";while(true){index++;var _c=szSrc.charCodeAt(index);if(_c==";".charCodeAt(0)){index++; -break}dst_len+=String.fromCharCode(_c)}var dstLen=parseInt(dst_len);var pointer=AscFonts.g_memory.Alloc(dstLen);var stream=new AscCommon.FT_Stream2(pointer.data,dstLen);stream.obj=pointer.obj;var dstPx=stream.data;if(window.chrome)while(index=srcLen)break;var nCh=AscFonts.DecodeBase64Char(szSrc.charCodeAt(index++));if(nCh==-1){i--;continue}dwCurr<<=6;dwCurr|=nCh;nBits+=6}dwCurr<<=24-nBits;for(i=0;i>>16;dwCurr<<=8}}else{var p=AscFonts.b64_decode;while(index=srcLen)break;var nCh=p[szSrc.charCodeAt(index++)];if(nCh==undefined){i--;continue}dwCurr<<=6;dwCurr|=nCh;nBits+=6}dwCurr<<=24-nBits;for(i=0;i>>16;dwCurr<<=8}}}return stream};CCollaborativeChanges.prototype.private_SaveData=function(Binary){var Writer=AscCommon.History.BinaryWriter;var Pos=Binary.Pos;var Len=Binary.Len; -return Len+";"+Writer.GetBase64Memory2(Pos,Len)};function CCollaborativeEditingBase(){this.m_nUseType=1;this.m_aUsers=[];this.m_aChanges=[];this.m_aNeedUnlock=[];this.m_aNeedUnlock2=[];this.m_aNeedLock=[];this.m_aLinkData=[];this.m_aEndActions=[];this.m_bGlobalLock=0;this.m_bGlobalLockSelection=0;this.m_aCheckLocks=[];this.m_aCheckLocksInstance=[];this.m_aNewObjects=[];this.m_aNewImages=[];this.m_aDC={};this.m_aChangedClasses={};this.m_oMemory=null;this.m_aCursorsToUpdate={};this.m_aCursorsToUpdateShortId= -{};this.m_bFast=false;this.m_oLogicDocument=null;this.m_aDocumentPositions=new CDocumentPositionsManager;this.m_aForeignCursorsPos=new CDocumentPositionsManager;this.m_aForeignCursors={};this.m_aForeignCursorsId={};this.m_nAllChangesSavedIndex=0;this.m_aAllChanges=[];this.m_aOwnChangesIndexes=[];this.m_oOwnChanges=[]}CCollaborativeEditingBase.prototype.Clear=function(){this.m_nUseType=1;this.m_aUsers=[];this.m_aChanges=[];this.m_aNeedUnlock=[];this.m_aNeedUnlock2=[];this.m_aNeedLock=[];this.m_aLinkData= -[];this.m_aEndActions=[];this.m_aCheckLocks=[];this.m_aCheckLocksInstance=[];this.m_aNewObjects=[];this.m_aNewImages=[]};CCollaborativeEditingBase.prototype.Set_Fast=function(bFast){this.m_bFast=bFast;if(false===bFast){this.Remove_AllForeignCursors();this.RemoveMyCursorFromOthers()}};CCollaborativeEditingBase.prototype.Is_Fast=function(){return this.m_bFast};CCollaborativeEditingBase.prototype.Is_SingleUser=function(){return 1===this.m_nUseType};CCollaborativeEditingBase.prototype.getCollaborativeEditing= -function(){return!this.Is_SingleUser()};CCollaborativeEditingBase.prototype.Start_CollaborationEditing=function(){this.m_nUseType=-1};CCollaborativeEditingBase.prototype.End_CollaborationEditing=function(){if(this.m_nUseType<=0)this.m_nUseType=0};CCollaborativeEditingBase.prototype.Add_User=function(UserId){if(-1===this.Find_User(UserId))this.m_aUsers.push(UserId)};CCollaborativeEditingBase.prototype.Find_User=function(UserId){var Len=this.m_aUsers.length;for(var Index=0;Index0;if(true===OtherChanges){AscFonts.IsCheckSymbols=true;editor.WordControl.m_oLogicDocument.StopRecalculate();editor.WordControl.m_oLogicDocument.EndPreview_MailMergeResult();editor.sync_StartAction(Asc.c_oAscAsyncActionType.BlockInteraction,Asc.c_oAscAsyncAction.ApplyChanges);var DocState=this.private_SaveDocumentState();this.Clear_NewImages();this.Apply_OtherChanges(); -this.Lock_NeedLock();this.private_RestoreDocumentState(DocState);this.OnStart_Load_Objects();AscFonts.IsCheckSymbols=false}};CCollaborativeEditingBase.prototype.Apply_OtherChanges=function(){AscCommon.g_oIdCounter.Set_Load(true);if(this.m_aChanges.length>0)this.private_CollectOwnChanges();var _count=this.m_aChanges.length;for(var i=0;i<_count;i++){if(window["NATIVE_EDITOR_ENJINE"]===true&&window["native"]["CheckNextChange"])if(!window["native"]["CheckNextChange"]())break;var Changes=this.m_aChanges[i]; -Changes.Apply_Data()}this.private_ClearChanges();this.Apply_LinkData();this.Check_MergeData();this.OnEnd_ReadForeignChanges();AscCommon.g_oIdCounter.Set_Load(false)};CCollaborativeEditingBase.prototype.getOwnLocksLength=function(){return this.m_aNeedUnlock2.length};CCollaborativeEditingBase.prototype.Send_Changes=function(){};CCollaborativeEditingBase.prototype.Release_Locks=function(){};CCollaborativeEditingBase.prototype.CheckWaitingImages=function(aImages){};CCollaborativeEditingBase.prototype.SendImagesUrlsFromChanges= -function(aImages){var rData={},oApi=editor||Asc["editor"],i;if(!oApi)return;rData["c"]="pathurls";rData["data"]=[];for(i=0;i0)this.SendImagesUrlsFromChanges(aImages);else{this.SendImagesCallback([].concat(this.m_aNewImages));this.m_aNewImages.length=0}};CCollaborativeEditingBase.prototype.OnEnd_Load_Objects=function(){};CCollaborativeEditingBase.prototype.Clear_LinkData=function(){this.m_aLinkData.length=0};CCollaborativeEditingBase.prototype.Add_LinkData=function(Class,LinkData){this.m_aLinkData.push({Class:Class,LinkData:LinkData})}; -CCollaborativeEditingBase.prototype.Apply_LinkData=function(){var Count=this.m_aLinkData.length;for(var Index=0;Index -0){this.m_aOwnChangesIndexes.push({Position:this.m_aAllChanges.length,Count:arrChanges.length});this.m_aAllChanges=this.m_aAllChanges.concat(arrChanges)}};CCollaborativeEditingBase.prototype.Undo=function(){if(true===this.Get_GlobalLock())return;if(this.m_aOwnChangesIndexes.length<=0)return false;var arrChanges=[];var oIndexes=this.m_aOwnChangesIndexes[this.m_aOwnChangesIndexes.length-1];var nPosition=oIndexes.Position;var nCount=oIndexes.Count;for(var nIndex=nCount-1;nIndex>=0;--nIndex){var oChange= -this.m_aAllChanges[nPosition+nIndex];if(!oChange)continue;var oClass=oChange.GetClass();if(oChange.IsContentChange()){var _oChange=oChange.Copy();if(this.private_CommutateContentChanges(_oChange,nPosition+nCount))arrChanges.push(_oChange);oChange.SetReverted(true)}else{var _oChange=oChange;if(this.private_CommutatePropertyChanges(oClass,_oChange,nPosition+nCount))arrChanges.push(_oChange)}}this.m_aOwnChangesIndexes.length=this.m_aOwnChangesIndexes.length-1;var arrReverseChanges=[];for(var nIndex= -0,nCount=arrChanges.length;nIndex-1;--i)if(mapAddedSlides[oLogicDocument.Slides[i].Get_Id()]&&!oLogicDocument.Slides[i].Layout)oLogicDocument.removeSlide(i);for(var sId in mapSlides)if(mapSlides.hasOwnProperty(sId))mapSlides[sId].correctContent();if(bChangedLayout)for(var i=oLogicDocument.Slides.length-1;i>-1;--i){var Layout= -oLogicDocument.Slides[i].Layout;if(!Layout||mapLayouts[Layout.Get_Id()])if(!oLogicDocument.Slides[i].CheckLayout())oLogicDocument.removeSlide(i)}for(var sId in mapGrObjects){var oShape=mapGrObjects[sId];if(!oShape.checkCorrect()){oShape.setBDeleted(true);if(oShape.group)oShape.group.removeFromSpTree(oShape.Get_Id());else if(AscFormat.Slide&&oShape.parent instanceof AscFormat.Slide)oShape.parent.removeFromSpTreeById(oShape.Get_Id());else if(AscCommonWord.ParaDrawing&&oShape.parent instanceof AscCommonWord.ParaDrawing)mapDrawings[oShape.parent.Get_Id()]= -oShape.parent}else if(oShape.resetGroups)oShape.resetGroups()}var oDrawing;for(var sId in mapDrawings)if(mapDrawings.hasOwnProperty(sId)){oDrawing=mapDrawings[sId];if(!oDrawing.CheckCorrect()){var oParentParagraph=oDrawing.Get_ParentParagraph();oDrawing.PreDelete();oDrawing.Remove_FromDocument(false);if(oParentParagraph)mapParagraphs[oParentParagraph.Get_Id()]=oParentParagraph}}for(var sId in mapRuns)if(mapRuns.hasOwnProperty(sId)){var oRun=mapRuns[sId];for(var nIndex=oRun.Content.length-1;nIndex> --1;--nIndex)if(oRun.Content[nIndex]instanceof AscCommonWord.ParaDrawing)if(!oRun.Content[nIndex].CheckCorrect()){oRun.Remove_FromContent(nIndex,1,false);if(oRun.Paragraph)mapParagraphs[oRun.Paragraph.Get_Id()]=oRun.Paragraph}}for(var sId in mapTables){var oTable=mapTables[sId];for(var nCurRow=oTable.Content.length-1;nCurRow>=0;--nCurRow){var oRow=oTable.Get_Row(nCurRow);if(oRow.Get_CellsCount()<=0)oTable.private_RemoveRow(nCurRow)}if(oTable.Parent instanceof AscCommonWord.CDocument||oTable.Parent instanceof -AscCommonWord.CDocumentContent)mapDocumentContents[oTable.Parent.Get_Id()]=oTable.Parent}for(var sId in mapDocumentContents){var oDocumentContent=mapDocumentContents[sId];var nContentLen=oDocumentContent.Content.length;for(var nIndex=nContentLen-1;nIndex>=0;--nIndex){var oElement=oDocumentContent.Content[nIndex];if((AscCommonWord.type_Paragraph===oElement.GetType()||AscCommonWord.type_Table===oElement.GetType())&&oElement.Content.length<=0)oDocumentContent.Remove_FromContent(nIndex,1)}nContentLen= -oDocumentContent.Content.length;if(nContentLen<=0||AscCommonWord.type_Paragraph!==oDocumentContent.Content[nContentLen-1].GetType()){var oNewParagraph=new AscCommonWord.Paragraph(oLogicDocument.Get_DrawingDocument(),oDocumentContent,0,0,0,0,0,false);oDocumentContent.Add_ToContent(nContentLen,oNewParagraph)}}for(var sId in mapParagraphs){var oParagraph=mapParagraphs[sId];oParagraph.CheckParaEnd();oParagraph.Correct_Content(null,null,true)}var oBinaryWriter=AscCommon.History.BinaryWriter;var aSendingChanges= -[];for(var nIndex=0,nCount=arrReverseChanges.length;nIndex=0;--nActionIndex){var oAction=arrActions[nActionIndex];var oResult=oAction;for(var nIndex=nStartPosition,nOverallCount=this.m_aAllChanges.length;nIndex=srcLen)break;var nCh=AscFonts.DecodeBase64Char(szSrc.charCodeAt(index++));if(nCh==-1){i--;continue}dwCurr<<=6;dwCurr|=nCh;nBits+=6}dwCurr<<=24-nBits;for(i=0;i>>16;dwCurr<<=8}}else{var p=AscFonts.b64_decode;while(index=srcLen)break;var nCh=p[szSrc.charCodeAt(index++)];if(nCh==undefined){i--;continue}dwCurr<<=6;dwCurr|=nCh;nBits+=6}dwCurr<<=24-nBits;for(i= +0;i>>16;dwCurr<<=8}}}return stream};CCollaborativeChanges.prototype.private_SaveData=function(Binary){var Writer=AscCommon.History.BinaryWriter;var Pos=Binary.Pos;var Len=Binary.Len;return Len+";"+Writer.GetBase64Memory2(Pos,Len)};function CCollaborativeEditingBase(){this.m_nUseType=1;this.m_aUsers=[];this.m_aChanges=[];this.m_aNeedUnlock=[];this.m_aNeedUnlock2=[];this.m_aNeedLock=[];this.m_aLinkData=[];this.m_aEndActions=[];this.m_bGlobalLock=0;this.m_bGlobalLockSelection= +0;this.m_aCheckLocks=[];this.m_aCheckLocksInstance=[];this.m_aNewObjects=[];this.m_aNewImages=[];this.m_aDC={};this.m_aChangedClasses={};this.m_oMemory=null;this.m_aCursorsToUpdate={};this.m_aCursorsToUpdateShortId={};this.m_bFast=false;this.m_oLogicDocument=null;this.m_aDocumentPositions=new CDocumentPositionsManager;this.m_aForeignCursorsPos=new CDocumentPositionsManager;this.m_aForeignCursors={};this.m_aForeignCursorsId={};this.m_nAllChangesSavedIndex=0;this.m_aAllChanges=[];this.m_aOwnChangesIndexes= +[];this.m_oOwnChanges=[]}CCollaborativeEditingBase.prototype.Clear=function(){this.m_nUseType=1;this.m_aUsers=[];this.m_aChanges=[];this.m_aNeedUnlock=[];this.m_aNeedUnlock2=[];this.m_aNeedLock=[];this.m_aLinkData=[];this.m_aEndActions=[];this.m_aCheckLocks=[];this.m_aCheckLocksInstance=[];this.m_aNewObjects=[];this.m_aNewImages=[]};CCollaborativeEditingBase.prototype.Set_Fast=function(bFast){this.m_bFast=bFast;if(false===bFast){this.Remove_AllForeignCursors();this.RemoveMyCursorFromOthers()}};CCollaborativeEditingBase.prototype.Is_Fast= +function(){return this.m_bFast};CCollaborativeEditingBase.prototype.Is_SingleUser=function(){return 1===this.m_nUseType};CCollaborativeEditingBase.prototype.getCollaborativeEditing=function(){return!this.Is_SingleUser()};CCollaborativeEditingBase.prototype.Start_CollaborationEditing=function(){this.m_nUseType=-1};CCollaborativeEditingBase.prototype.End_CollaborationEditing=function(){if(this.m_nUseType<=0)this.m_nUseType=0};CCollaborativeEditingBase.prototype.Add_User=function(UserId){if(-1===this.Find_User(UserId))this.m_aUsers.push(UserId)}; +CCollaborativeEditingBase.prototype.Find_User=function(UserId){var Len=this.m_aUsers.length;for(var Index=0;Index0;if(true===OtherChanges){AscFonts.IsCheckSymbols=true;editor.WordControl.m_oLogicDocument.StopRecalculate();editor.WordControl.m_oLogicDocument.EndPreview_MailMergeResult(); +editor.sync_StartAction(Asc.c_oAscAsyncActionType.BlockInteraction,Asc.c_oAscAsyncAction.ApplyChanges);var DocState=this.private_SaveDocumentState();this.Clear_NewImages();this.Apply_OtherChanges();this.Lock_NeedLock();this.private_RestoreDocumentState(DocState);this.OnStart_Load_Objects();AscFonts.IsCheckSymbols=false}};CCollaborativeEditingBase.prototype.Apply_OtherChanges=function(){AscCommon.g_oIdCounter.Set_Load(true);if(this.m_aChanges.length>0)this.private_CollectOwnChanges();var _count=this.m_aChanges.length; +for(var i=0;i<_count;i++){if(window["NATIVE_EDITOR_ENJINE"]===true&&window["native"]["CheckNextChange"])if(!window["native"]["CheckNextChange"]())break;var Changes=this.m_aChanges[i];Changes.Apply_Data()}this.private_ClearChanges();this.Apply_LinkData();this.Check_MergeData();this.OnEnd_ReadForeignChanges();AscCommon.g_oIdCounter.Set_Load(false)};CCollaborativeEditingBase.prototype.getOwnLocksLength=function(){return this.m_aNeedUnlock2.length};CCollaborativeEditingBase.prototype.Send_Changes=function(){}; +CCollaborativeEditingBase.prototype.Release_Locks=function(){};CCollaborativeEditingBase.prototype.CheckWaitingImages=function(aImages){};CCollaborativeEditingBase.prototype.SendImagesUrlsFromChanges=function(aImages){var rData={},oApi=editor||Asc["editor"],i;if(!oApi)return;rData["c"]="pathurls";rData["data"]=[];for(i=0;i0)this.SendImagesUrlsFromChanges(aImages);else{this.SendImagesCallback([].concat(this.m_aNewImages));this.m_aNewImages.length=0}};CCollaborativeEditingBase.prototype.OnEnd_Load_Objects=function(){};CCollaborativeEditingBase.prototype.Clear_LinkData=function(){this.m_aLinkData.length=0};CCollaborativeEditingBase.prototype.Add_LinkData= +function(Class,LinkData){this.m_aLinkData.push({Class:Class,LinkData:LinkData})};CCollaborativeEditingBase.prototype.Apply_LinkData=function(){var Count=this.m_aLinkData.length;for(var Index=0;Index0){this.m_aOwnChangesIndexes.push({Position:this.m_aAllChanges.length,Count:arrChanges.length});this.m_aAllChanges=this.m_aAllChanges.concat(arrChanges)}};CCollaborativeEditingBase.prototype.Undo=function(){if(true===this.Get_GlobalLock())return;if(this.m_aOwnChangesIndexes.length<=0)return false;var arrChanges=[];var oIndexes=this.m_aOwnChangesIndexes[this.m_aOwnChangesIndexes.length- +1];var nPosition=oIndexes.Position;var nCount=oIndexes.Count;for(var nIndex=nCount-1;nIndex>=0;--nIndex){var oChange=this.m_aAllChanges[nPosition+nIndex];if(!oChange)continue;var oClass=oChange.GetClass();if(oChange.IsContentChange()){var _oChange=oChange.Copy();if(this.private_CommutateContentChanges(_oChange,nPosition+nCount))arrChanges.push(_oChange);oChange.SetReverted(true)}else{var _oChange=oChange;if(this.private_CommutatePropertyChanges(oClass,_oChange,nPosition+nCount))arrChanges.push(_oChange)}}this.m_aOwnChangesIndexes.length= +this.m_aOwnChangesIndexes.length-1;var arrReverseChanges=[];for(var nIndex=0,nCount=arrChanges.length;nIndex-1;--i)if(mapAddedSlides[oLogicDocument.Slides[i].Get_Id()]&&!oLogicDocument.Slides[i].Layout)oLogicDocument.removeSlide(i);for(var sId in mapSlides)if(mapSlides.hasOwnProperty(sId))mapSlides[sId].correctContent(); +if(bChangedLayout)for(var i=oLogicDocument.Slides.length-1;i>-1;--i){var Layout=oLogicDocument.Slides[i].Layout;if(!Layout||mapLayouts[Layout.Get_Id()])if(!oLogicDocument.Slides[i].CheckLayout())oLogicDocument.removeSlide(i)}for(var sId in mapGrObjects){var oShape=mapGrObjects[sId];if(!oShape.checkCorrect()){oShape.setBDeleted(true);if(oShape.group)oShape.group.removeFromSpTree(oShape.Get_Id());else if(AscFormat.Slide&&oShape.parent instanceof AscFormat.Slide)oShape.parent.removeFromSpTreeById(oShape.Get_Id()); +else if(AscCommonWord.ParaDrawing&&oShape.parent instanceof AscCommonWord.ParaDrawing)mapDrawings[oShape.parent.Get_Id()]=oShape.parent}else if(oShape.resetGroups)oShape.resetGroups()}var oDrawing;for(var sId in mapDrawings)if(mapDrawings.hasOwnProperty(sId)){oDrawing=mapDrawings[sId];if(!oDrawing.CheckCorrect()){var oParentParagraph=oDrawing.Get_ParentParagraph();oDrawing.PreDelete();oDrawing.Remove_FromDocument(false);if(oParentParagraph)mapParagraphs[oParentParagraph.Get_Id()]=oParentParagraph}}for(var sId in mapRuns)if(mapRuns.hasOwnProperty(sId)){var oRun= +mapRuns[sId];for(var nIndex=oRun.Content.length-1;nIndex>-1;--nIndex)if(oRun.Content[nIndex]instanceof AscCommonWord.ParaDrawing)if(!oRun.Content[nIndex].CheckCorrect()){oRun.Remove_FromContent(nIndex,1,false);if(oRun.Paragraph)mapParagraphs[oRun.Paragraph.Get_Id()]=oRun.Paragraph}}for(var sId in mapTables){var oTable=mapTables[sId];for(var nCurRow=oTable.Content.length-1;nCurRow>=0;--nCurRow){var oRow=oTable.Get_Row(nCurRow);if(oRow.Get_CellsCount()<=0)oTable.private_RemoveRow(nCurRow)}if(oTable.Parent instanceof +AscCommonWord.CDocument||oTable.Parent instanceof AscCommonWord.CDocumentContent)mapDocumentContents[oTable.Parent.Get_Id()]=oTable.Parent}for(var sId in mapDocumentContents){var oDocumentContent=mapDocumentContents[sId];var nContentLen=oDocumentContent.Content.length;for(var nIndex=nContentLen-1;nIndex>=0;--nIndex){var oElement=oDocumentContent.Content[nIndex];if((AscCommonWord.type_Paragraph===oElement.GetType()||AscCommonWord.type_Table===oElement.GetType())&&oElement.Content.length<=0)oDocumentContent.Remove_FromContent(nIndex, +1)}nContentLen=oDocumentContent.Content.length;if(nContentLen<=0||AscCommonWord.type_Paragraph!==oDocumentContent.Content[nContentLen-1].GetType()){var oNewParagraph=new AscCommonWord.Paragraph(oLogicDocument.Get_DrawingDocument(),oDocumentContent,0,0,0,0,0,false);oDocumentContent.Add_ToContent(nContentLen,oNewParagraph)}}for(var sId in mapParagraphs){var oParagraph=mapParagraphs[sId];oParagraph.CheckParaEnd();oParagraph.Correct_Content(null,null,true)}var oBinaryWriter=AscCommon.History.BinaryWriter; +var aSendingChanges=[];for(var nIndex=0,nCount=arrReverseChanges.length;nIndex=0;--nActionIndex){var oAction=arrActions[nActionIndex];var oResult=oAction;for(var nIndex=nStartPosition,nOverallCount= +this.m_aAllChanges.length;nIndex0)oChange.ConvertFromSimpleActions(arrCommutateActions);else return false;return true};CCollaborativeEditingBase.prototype.private_Commutate=function(oActionL,oActionR){if(oActionL.Add)if(oActionR.Add)if(oActionL.Pos>=oActionR.Pos)oActionL.Pos++;else oActionR.Pos--;else if(oActionL.Pos>oActionR.Pos)oActionL.Pos--;else if(oActionL.Pos===oActionR.Pos)return false;else oActionR.Pos--;else if(oActionR.Add)if(oActionL.Pos>=oActionR.Pos)oActionL.Pos++; else oActionR.Pos++;else if(oActionL.Pos>oActionR.Pos)oActionL.Pos--;else oActionR.Pos++;return true};CCollaborativeEditingBase.prototype.private_CommutatePropertyChanges=function(oClass,oChange,nStartPosition){if(oChange.CheckCorrect&&!oChange.CheckCorrect())return false;return true};CCollaborativeEditingBase.prototype.private_RecalculateDocument=function(oRecalcData){};function CDocumentPositionsManager(){this.m_aDocumentPositions=[];this.m_aDocumentPositionsSplit=[];this.m_aDocumentPositionsMap= []}CDocumentPositionsManager.prototype.Clear_DocumentPositions=function(){this.m_aDocumentPositions=[];this.m_aDocumentPositionsSplit=[];this.m_aDocumentPositionsMap=[]};CDocumentPositionsManager.prototype.Add_DocumentPosition=function(Position){this.m_aDocumentPositions.push(Position)};CDocumentPositionsManager.prototype.Update_DocumentPositionsOnAdd=function(Class,Pos){for(var PosIndex=0,PosCount=this.m_aDocumentPositions.length;PosIndex0&&typeof sData==="string"&&typeof sGuid==="string"&&sGuid.length>0&&AscFormat.isRealNumber(nWidthPix)&& -AscFormat.isRealNumber(nHeightPix)&&AscFormat.isRealNumber(fWidth)&&AscFormat.isRealNumber(fHeight))this.asc_checkImageUrlAndAction(sImgSrc,function(oImage){oThis.asc_addOleObjectAction(AscCommon.g_oDocumentUrls.getImageLocal(oImage.src),sData,sGuid,fWidth,fHeight,nWidthPix,nHeightPix)})};baseEditorsApi.prototype.asc_editOleObject=function(oPluginData){if(this.isViewMode)return;var oThis=this;var bResize=oPluginData["resize"];var sImgSrc=oPluginData["imgSrc"];var oOleObject=AscCommon.g_oTableId.Get_ById(oPluginData["objectId"]); -var nWidthPix=oPluginData["widthPix"];var nHeightPix=oPluginData["heightPix"];var sData=oPluginData["data"];if(typeof sImgSrc==="string"&&sImgSrc.length>0&&typeof sData==="string"&&oOleObject&&AscFormat.isRealNumber(nWidthPix)&&AscFormat.isRealNumber(nHeightPix))this.asc_checkImageUrlAndAction(sImgSrc,function(oImage){oThis.asc_editOleObjectAction(bResize,oOleObject,AscCommon.g_oDocumentUrls.getImageLocal(oImage.src),sData,nWidthPix,nHeightPix)})};baseEditorsApi.prototype.asc_addOleObjectAction=function(sLocalUrl, -sData,sApplicationId,fWidth,fHeight){};baseEditorsApi.prototype.asc_editOleObjectAction=function(bResize,oOleObject,sImageUrl,sData,nPixWidth,nPixHeight){};baseEditorsApi.prototype.asc_selectSearchingResults=function(value){if(this.selectSearchingResults===value)return;this.selectSearchingResults=value;this._selectSearchingResults(value)};baseEditorsApi.prototype.asc_startEditCurrentOleObject=function(){};baseEditorsApi.prototype.asc_canEditCrop=function(){};baseEditorsApi.prototype.asc_startEditCrop= -function(){};baseEditorsApi.prototype.asc_endEditCrop=function(){};baseEditorsApi.prototype.asc_cropFit=function(){};baseEditorsApi.prototype.asc_cropFill=function(){};baseEditorsApi.prototype.asc_RemoveAllComments=function(isMine,isCurrent){};baseEditorsApi.prototype.asc_showRevision=function(newObj){if(!newObj.docId)return;if(this.isCoAuthoringEnable)this.asc_coAuthoringDisconnect();var bUpdate=true;if(null===this.VersionHistory)this.VersionHistory=new window["Asc"].asc_CVersionHistory(newObj); -else bUpdate=this.VersionHistory.update(newObj);if(bUpdate){this.asc_CloseFile();this.DocInfo.put_Id(this.VersionHistory.docId);this.DocInfo.put_Url(this.VersionHistory.url);this.documentUrlChanges=this.VersionHistory.urlChanges;this.asc_setDocInfo(this.DocInfo);this.asc_LoadDocument(this.VersionHistory)}else if(this.VersionHistory.currentChangeIdb.name)return 1;if(a.name=0&&manager.SlideNum>0;var _zoom=_w/(_w_mm*AscCommon.g_dKoef_mm_to_pix);if(!transform)window["AscDesktopEditor"]["MediaStart"](sMediaName,_x,transition.Rect.y,extX,extY,_zoom);else window["AscDesktopEditor"]["MediaStart"](sMediaName,_x,transition.Rect.y, -extX,extY,_zoom,transform.sx,transform.shy,transform.shx,transform.sy,transform.tx,transform.ty)}}break}case c_oEditorId.Spreadsheet:{break}}};baseEditorsApi.prototype.hideVideoControl=function(){if(!window["AscDesktopEditor"]||!window["AscDesktopEditor"]["MediaEnd"])return;window["AscDesktopEditor"]["MediaEnd"]()};baseEditorsApi.prototype._checkLicenseApiFunctions=function(){return this.licenseResult&&true===this.licenseResult["plugins"]};baseEditorsApi.prototype.asc_pluginsRegister=function(basePath, -plugins){this.sendEvent("asc_LoadPluginsOrDocument");if(null!=this.pluginsManager){this.pluginsManager.register(basePath,plugins);if(this.pluginsManager.countEventDocContOrPluginsReady==2)this.pluginsManager.onPluginEvent("onDocumentContentReady")}};baseEditorsApi.prototype.asc_pluginRun=function(guid,variation,pluginData){if(null!=this.pluginsManager)this.pluginsManager.run(guid,variation,pluginData)};baseEditorsApi.prototype.asc_pluginStop=function(guid){if(null!=this.pluginsManager)this.pluginsManager.close(guid)}; -baseEditorsApi.prototype.asc_pluginResize=function(pluginData){if(null!=this.pluginsManager)this.pluginsManager.runResize(pluginData)};baseEditorsApi.prototype.asc_pluginButtonClick=function(id){if(null!=this.pluginsManager)this.pluginsManager.buttonClick(id)};baseEditorsApi.prototype.asc_pluginEnableMouseEvents=function(isEnable){if(!this.pluginsManager)return;this.pluginsManager.onEnableMouseEvents(isEnable)};baseEditorsApi.prototype.isEnabledDropTarget=function(){return true};baseEditorsApi.prototype.beginInlineDropTarget= -function(e){};baseEditorsApi.prototype.endInlineDropTarget=function(e){};baseEditorsApi.prototype["asc_insertSymbol"]=function(familyName,code,pr){var arrCharCodes=[code];AscFonts.FontPickerByCharacter.checkTextLight(arrCharCodes,true);var fonts=[new AscFonts.CFont(AscFonts.g_fontApplication.GetFontInfoName(familyName),0,"",0,null)];AscFonts.FontPickerByCharacter.extendFonts(fonts);this.asyncMethodCallback=function(){switch(this.editorId){case c_oEditorId.Word:case c_oEditorId.Presentation:{if(pr&& -c_oEditorId.Word===this.editorId)this.WordControl.m_oLogicDocument.AddSpecialSymbol(pr);else{var textPr=new AscCommonWord.CTextPr;textPr.SetFontFamily(familyName);this.WordControl.m_oLogicDocument.AddTextWithPr(new AscCommon.CUnicodeStringEmulator(arrCharCodes),textPr,true)}break}case c_oEditorId.Spreadsheet:{this.AddTextWithPr(familyName,arrCharCodes);break}}};if(false===AscCommon.g_font_loader.CheckFontsNeedLoading(fonts)){this.asyncMethodCallback();this.asyncMethodCallback=undefined;return}AscCommon.g_font_loader.LoadDocumentFonts2(fonts)}; -baseEditorsApi.prototype["asc_registerPlaceholderCallback"]=function(type,callback){if(this.WordControl&&this.WordControl.m_oDrawingDocument&&this.WordControl.m_oDrawingDocument.placeholders)this.WordControl.m_oDrawingDocument.placeholders.registerCallback(type,callback)};baseEditorsApi.prototype["asc_uncheckPlaceholders"]=function(){if(this.WordControl&&this.WordControl.m_oDrawingDocument&&this.WordControl.m_oDrawingDocument.placeholders)this.WordControl.m_oDrawingDocument.placeholders.closeAllActive()}; +(DownloadType.Print===downloadType||!downloadType)){var _cb=options.callback||this.fCurCallback;window.parent.APP.printPdf(dataContainer,function(obj){if(!obj){t.sync_EndAction(c_oAscAsyncActionType.BlockInteraction,actionType);return}_cb(obj)});return}AscCommon.saveWithParts(function(fCallback1,oAdditionalData1,dataContainer1){AscCommon.sendCommand(t,fCallback1,oAdditionalData1,dataContainer1)},this.fCurCallback,options.callback,oAdditionalData,dataContainer)};baseEditorsApi.prototype.asc_getChartPreviews= +function(chartType){return this.chartPreviewManager.getChartPreviews(chartType)};baseEditorsApi.prototype.asc_getTextArtPreviews=function(){return this.textArtPreviewManager.getWordArtStyles()};baseEditorsApi.prototype.asc_onOpenChartFrame=function(){if(this.isMobileVersion)return;this.isOpenedChartFrame=true};baseEditorsApi.prototype.asc_onCloseChartFrame=function(){this.isOpenedChartFrame=false};baseEditorsApi.prototype.asc_setInterfaceDrawImagePlaceShape=function(elementId){this.shapeElementId= +elementId};baseEditorsApi.prototype.asc_getPropertyEditorShapes=function(){return[AscCommon.g_oAutoShapesGroups,AscCommon.g_oAutoShapesTypes]};baseEditorsApi.prototype.asc_getPropertyEditorTextArts=function(){return[AscCommon.g_oPresetTxWarpGroups,AscCommon.g_PresetTxWarpTypes]};baseEditorsApi.prototype._addImageUrl=function(){};baseEditorsApi.prototype.asc_addImageCallback=function(res){};baseEditorsApi.prototype.asc_addImage=function(obj){var t=this;window.parent.APP.AddImage(function(res){console.log("AddImageCallback"); +t.asc_addImageCallback(res);t._addImageUrl([res.url])},function(){t.sendEvent("asc_onError",error,c_oAscError.Level.NoCritical)});return;var t=this;if(this.WordControl)this.WordControl.m_bIsMouseLock=false;AscCommon.ShowImageFileDialog(this.documentId,this.documentUserId,this.CoAuthoringApi.get_jwt(),function(error,files){t._uploadCallback(error,files,obj)},function(error){if(c_oAscError.ID.No!==error)t.sendEvent("asc_onError",error,c_oAscError.Level.NoCritical);t.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, +c_oAscAsyncAction.UploadImage)})};baseEditorsApi.prototype._uploadCallback=function(error,files,obj){var t=this;if(c_oAscError.ID.No!==error)this.sendEvent("asc_onError",error,c_oAscError.Level.NoCritical);else{this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction,c_oAscAsyncAction.UploadImage);AscCommon.UploadImageFiles(files,this.documentId,this.documentUserId,this.CoAuthoringApi.get_jwt(),function(error,urls){if(c_oAscError.ID.No!==error)t.sendEvent("asc_onError",error,c_oAscError.Level.NoCritical); +else t._addImageUrl(urls,obj);t.sync_EndAction(c_oAscAsyncActionType.BlockInteraction,c_oAscAsyncAction.UploadImage)})}};baseEditorsApi.prototype.asc_replaceLoadImageCallback=function(fCallback){};baseEditorsApi.prototype.asc_loadLocalImageAndAction=function(sLocalImage,fCallback){var _loadedUrl=this.ImageLoader.LoadImage(AscCommon.getFullImageSrc2(sLocalImage),1);if(_loadedUrl!=null)fCallback(_loadedUrl);else this.asc_replaceLoadImageCallback(fCallback)};baseEditorsApi.prototype.asc_checkImageUrlAndAction= +function(sImageUrl,fCallback){var oThis=this;this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction,c_oAscAsyncAction.UploadImage);var fCallback2=function(){oThis.sync_EndAction(c_oAscAsyncActionType.BlockInteraction,c_oAscAsyncAction.UploadImage);fCallback.apply(oThis,arguments)};var sLocalImage=AscCommon.g_oDocumentUrls.getImageLocal(sImageUrl);if(sLocalImage){this.asc_loadLocalImageAndAction(sLocalImage,fCallback2);return}AscCommon.sendImgUrls(oThis,[sImageUrl],function(data){if(data[0]&& +data[0].path!=null&&data[0].url!=="error")oThis.asc_loadLocalImageAndAction(AscCommon.g_oDocumentUrls.imagePath2Local(data[0].path),fCallback2)},this.editorId===c_oEditorId.Spreadsheet)};baseEditorsApi.prototype.asc_addOleObject=function(oPluginData){if(this.isViewMode)return;var oThis=this;var sImgSrc=oPluginData["imgSrc"];var nWidthPix=oPluginData["widthPix"];var nHeightPix=oPluginData["heightPix"];var fWidth=oPluginData["width"];var fHeight=oPluginData["height"];var sData=oPluginData["data"];var sGuid= +oPluginData["guid"];if(typeof sImgSrc==="string"&&sImgSrc.length>0&&typeof sData==="string"&&typeof sGuid==="string"&&sGuid.length>0&&AscFormat.isRealNumber(nWidthPix)&&AscFormat.isRealNumber(nHeightPix)&&AscFormat.isRealNumber(fWidth)&&AscFormat.isRealNumber(fHeight))this.asc_checkImageUrlAndAction(sImgSrc,function(oImage){oThis.asc_addOleObjectAction(AscCommon.g_oDocumentUrls.getImageLocal(oImage.src),sData,sGuid,fWidth,fHeight,nWidthPix,nHeightPix)})};baseEditorsApi.prototype.asc_editOleObject= +function(oPluginData){if(this.isViewMode)return;var oThis=this;var bResize=oPluginData["resize"];var sImgSrc=oPluginData["imgSrc"];var oOleObject=AscCommon.g_oTableId.Get_ById(oPluginData["objectId"]);var nWidthPix=oPluginData["widthPix"];var nHeightPix=oPluginData["heightPix"];var sData=oPluginData["data"];if(typeof sImgSrc==="string"&&sImgSrc.length>0&&typeof sData==="string"&&oOleObject&&AscFormat.isRealNumber(nWidthPix)&&AscFormat.isRealNumber(nHeightPix))this.asc_checkImageUrlAndAction(sImgSrc, +function(oImage){oThis.asc_editOleObjectAction(bResize,oOleObject,AscCommon.g_oDocumentUrls.getImageLocal(oImage.src),sData,nWidthPix,nHeightPix)})};baseEditorsApi.prototype.asc_addOleObjectAction=function(sLocalUrl,sData,sApplicationId,fWidth,fHeight){};baseEditorsApi.prototype.asc_editOleObjectAction=function(bResize,oOleObject,sImageUrl,sData,nPixWidth,nPixHeight){};baseEditorsApi.prototype.asc_selectSearchingResults=function(value){if(this.selectSearchingResults===value)return;this.selectSearchingResults= +value;this._selectSearchingResults(value)};baseEditorsApi.prototype.asc_startEditCurrentOleObject=function(){};baseEditorsApi.prototype.asc_canEditCrop=function(){};baseEditorsApi.prototype.asc_startEditCrop=function(){};baseEditorsApi.prototype.asc_endEditCrop=function(){};baseEditorsApi.prototype.asc_cropFit=function(){};baseEditorsApi.prototype.asc_cropFill=function(){};baseEditorsApi.prototype.asc_RemoveAllComments=function(isMine,isCurrent){};baseEditorsApi.prototype.asc_showRevision=function(newObj){if(!newObj.docId)return; +if(this.isCoAuthoringEnable)this.asc_coAuthoringDisconnect();var bUpdate=true;if(null===this.VersionHistory)this.VersionHistory=new window["Asc"].asc_CVersionHistory(newObj);else bUpdate=this.VersionHistory.update(newObj);if(bUpdate){this.asc_CloseFile();this.DocInfo.put_Id(this.VersionHistory.docId);this.DocInfo.put_Url(this.VersionHistory.url);this.documentUrlChanges=this.VersionHistory.urlChanges;this.asc_setDocInfo(this.DocInfo);this.asc_LoadDocument(this.VersionHistory)}else if(this.VersionHistory.currentChangeId< +newObj.currentChangeId){AscCommon.CollaborativeEditing.Clear_CollaborativeMarks();editor.VersionHistory.applyChanges(editor);AscCommon.CollaborativeEditing.Apply_Changes()}};baseEditorsApi.prototype.asc_undoAllChanges=function(){};baseEditorsApi.prototype.asc_getAdvancedOptions=function(){var cp={"codepage":AscCommon.c_oAscCodePageUtf8,"encodings":AscCommon.getEncodingParams()};return new AscCommon.asc_CAdvancedOptions(cp)};baseEditorsApi.prototype.asc_Print=function(options){if(window["AscDesktopEditor"]&& +this._printDesktop(options))return;if(!options)options=new Asc.asc_CDownloadOptions;options.fileType=Asc.c_oAscFileType.PDF;this.downloadAs(c_oAscAsyncAction.Print,options)};baseEditorsApi.prototype.asc_Save=function(isAutoSave,isIdle){var t=this;var res=false;if(this.canSave&&this._saveCheck()){this.IsUserSave=!isAutoSave;if(this.asc_isDocumentCanSave()||AscCommon.History.Have_Changes()||this._haveOtherChanges()||this.canUnlockDocument||this.forceSaveUndoRequest){if(this._prepareSave(isIdle)){this.canSave= +false;this.CoAuthoringApi.askSaveChanges(function(e){t._onSaveCallback(e)});res=true}}else if(this.isForceSaveOnUserSave&&this.IsUserSave)this.forceSave()}return res};baseEditorsApi.prototype.asc_isDocumentCanSave=function(){return this.isDocumentCanSave};baseEditorsApi.prototype.asc_getCanUndo=function(){return AscCommon.History.Can_Undo()};baseEditorsApi.prototype.asc_getCanRedo=function(){return AscCommon.History.Can_Redo()};baseEditorsApi.prototype.asc_isOffline=function(){return window.location.protocol.indexOf("file")== +0?true:false};baseEditorsApi.prototype.asc_getUrlType=function(url){return AscCommon.getUrlType(url)};baseEditorsApi.prototype.openDocument=function(file){};baseEditorsApi.prototype.openDocumentFromZip=function(){};baseEditorsApi.prototype.onEndLoadDocInfo=function(){if(this.isLoadFullApi&&this.DocInfo){if(this.DocInfo.get_OfflineApp())this._openChartOrLocalDocument();this.onEndLoadFile(null)}};baseEditorsApi.prototype.onEndLoadFile=function(result){if(result)this.openResult=result;if(this.isLoadFullApi&& +this.DocInfo&&this.openResult&&this.isLoadFonts){this.openDocument(this.openResult);this.openResult=null}};baseEditorsApi.prototype._onEndLoadSdk=function(){AscCommon.g_oTableId.init();var t=this;AscCommon.InitDragAndDrop(this.HtmlElement,function(error,files){t._uploadCallback(error,files)});AscFonts.g_fontApplication.Init();this.FontLoader=AscCommon.g_font_loader;this.ImageLoader=AscCommon.g_image_loader;this.FontLoader.put_Api(this);this.ImageLoader.put_Api(this);this.FontLoader.SetStandartFonts(); +this.chartPreviewManager=new AscCommon.ChartPreviewManager;this.textArtPreviewManager=new AscCommon.TextArtPreviewManager;AscFormat.initStyleManager();if(null!==this.tmpFocus)this.asc_enableKeyEvents(this.tmpFocus);this.pluginsManager=Asc.createPluginsManager(this);this.macros=new AscCommon.CDocumentMacros;this._loadSdkImages();if(AscFonts.FontPickerByCharacter&&this.documentTitle)AscFonts.FontPickerByCharacter.getFontsByString(this.documentTitle)};baseEditorsApi.prototype._loadSdkImages=function(){}; +baseEditorsApi.prototype.sendStandartTextures=function(){if(this.isSendStandartTextures)return;this.isSendStandartTextures=true;var _count=AscCommon.g_oUserTexturePresets.length;var arr=new Array(_count);var arrToDownload=[];for(var i=0;i<_count;++i){arr[i]=new AscCommon.asc_CTexture;arr[i].Id=i;arr[i].Image=AscCommon.g_oUserTexturePresets[i];arrToDownload.push(AscCommon.g_oUserTexturePresets[i])}if(this.editorId===c_oEditorId.Word)arrToDownload.push(AscCommon.g_sWordPlaceholderImage);this.ImageLoader.LoadImagesWithCallback(arrToDownload, +function(){},0);this.sendEvent("asc_onInitStandartTextures",arr)};baseEditorsApi.prototype.sendMathToMenu=function(){if(this.MathMenuLoad)return;var _MathPainter=new AscFormat.CMathPainter(this);_MathPainter.Generate();this.MathMenuLoad=true};baseEditorsApi.prototype.sendMathTypesToMenu=function(_math){this.sendEvent("asc_onMathTypes",_math)};baseEditorsApi.prototype.asyncFontEndLoaded_MathDraw=function(Obj){this.sync_EndAction(c_oAscAsyncActionType.Information,c_oAscAsyncAction.LoadFont);Obj.Generate2()}; +baseEditorsApi.prototype.getCurrentColorScheme=function(){var oTheme=this.getCurrentTheme();return oTheme&&oTheme.themeElements&&oTheme.themeElements.clrScheme};baseEditorsApi.prototype.asc_GetCurrentColorSchemeName=function(){var oClrScheme=this.getCurrentColorScheme();if(oClrScheme&&typeof oClrScheme.name==="string")return oClrScheme.name;return""};baseEditorsApi.prototype.asc_GetCurrentColorSchemeIndex=function(){var oTheme=this.getCurrentTheme();if(!oTheme)return-1;return this.getColorSchemes(oTheme).index}; +baseEditorsApi.prototype.getCurrentTheme=function(){return null};baseEditorsApi.prototype.getColorSchemes=function(theme){var result=AscCommon.g_oUserColorScheme.slice();var asc_color_scheme,_scheme,i;var aCustomSchemes=theme.getExtraAscColorSchemes();_scheme=theme.themeElements&&theme.themeElements.clrScheme;var nIndex=-1;if(_scheme){asc_color_scheme=AscCommon.getAscColorScheme(_scheme,theme);nIndex=AscCommon.getIndexColorSchemeInArray(result,asc_color_scheme);if(nIndex===-1)aCustomSchemes.push(asc_color_scheme); +aCustomSchemes.sort(function(a,b){if(a.name===""||a.name===null)return-1;if(b.name===""||b.name===null)return 1;if(a.name>b.name)return 1;if(a.name=0&&manager.SlideNum>0;var _zoom=_w/(_w_mm*AscCommon.g_dKoef_mm_to_pix);if(!transform)window["AscDesktopEditor"]["MediaStart"](sMediaName, +_x,transition.Rect.y,extX,extY,_zoom);else window["AscDesktopEditor"]["MediaStart"](sMediaName,_x,transition.Rect.y,extX,extY,_zoom,transform.sx,transform.shy,transform.shx,transform.sy,transform.tx,transform.ty)}}break}case c_oEditorId.Spreadsheet:{break}}};baseEditorsApi.prototype.hideVideoControl=function(){if(!window["AscDesktopEditor"]||!window["AscDesktopEditor"]["MediaEnd"])return;window["AscDesktopEditor"]["MediaEnd"]()};baseEditorsApi.prototype._checkLicenseApiFunctions=function(){return this.licenseResult&& +true===this.licenseResult["plugins"]};baseEditorsApi.prototype.asc_pluginsRegister=function(basePath,plugins){this.sendEvent("asc_LoadPluginsOrDocument");if(null!=this.pluginsManager){this.pluginsManager.register(basePath,plugins);if(this.pluginsManager.countEventDocContOrPluginsReady==2)this.pluginsManager.onPluginEvent("onDocumentContentReady")}};baseEditorsApi.prototype.asc_pluginRun=function(guid,variation,pluginData){if(null!=this.pluginsManager)this.pluginsManager.run(guid,variation,pluginData)}; +baseEditorsApi.prototype.asc_pluginStop=function(guid){if(null!=this.pluginsManager)this.pluginsManager.close(guid)};baseEditorsApi.prototype.asc_pluginResize=function(pluginData){if(null!=this.pluginsManager)this.pluginsManager.runResize(pluginData)};baseEditorsApi.prototype.asc_pluginButtonClick=function(id){if(null!=this.pluginsManager)this.pluginsManager.buttonClick(id)};baseEditorsApi.prototype.asc_pluginEnableMouseEvents=function(isEnable){if(!this.pluginsManager)return;this.pluginsManager.onEnableMouseEvents(isEnable)}; +baseEditorsApi.prototype.isEnabledDropTarget=function(){return true};baseEditorsApi.prototype.beginInlineDropTarget=function(e){};baseEditorsApi.prototype.endInlineDropTarget=function(e){};baseEditorsApi.prototype["asc_insertSymbol"]=function(familyName,code,pr){var arrCharCodes=[code];AscFonts.FontPickerByCharacter.checkTextLight(arrCharCodes,true);var fonts=[new AscFonts.CFont(AscFonts.g_fontApplication.GetFontInfoName(familyName),0,"",0,null)];AscFonts.FontPickerByCharacter.extendFonts(fonts); +this.asyncMethodCallback=function(){switch(this.editorId){case c_oEditorId.Word:case c_oEditorId.Presentation:{if(pr&&c_oEditorId.Word===this.editorId)this.WordControl.m_oLogicDocument.AddSpecialSymbol(pr);else{var textPr=new AscCommonWord.CTextPr;textPr.SetFontFamily(familyName);this.WordControl.m_oLogicDocument.AddTextWithPr(new AscCommon.CUnicodeStringEmulator(arrCharCodes),textPr,true)}break}case c_oEditorId.Spreadsheet:{this.AddTextWithPr(familyName,arrCharCodes);break}}};if(false===AscCommon.g_font_loader.CheckFontsNeedLoading(fonts)){this.asyncMethodCallback(); +this.asyncMethodCallback=undefined;return}AscCommon.g_font_loader.LoadDocumentFonts2(fonts)};baseEditorsApi.prototype["asc_registerPlaceholderCallback"]=function(type,callback){if(this.WordControl&&this.WordControl.m_oDrawingDocument&&this.WordControl.m_oDrawingDocument.placeholders)this.WordControl.m_oDrawingDocument.placeholders.registerCallback(type,callback)};baseEditorsApi.prototype["asc_uncheckPlaceholders"]=function(){if(this.WordControl&&this.WordControl.m_oDrawingDocument&&this.WordControl.m_oDrawingDocument.placeholders)this.WordControl.m_oDrawingDocument.placeholders.closeAllActive()}; baseEditorsApi.prototype.asc_nativeInitBuilder=function(){AscCommon.History.TurnOff();this.asc_setDocInfo(new Asc.asc_CDocInfo)};baseEditorsApi.prototype.asc_SetSilentMode=function(){};baseEditorsApi.prototype.asc_canPaste=function(){return false};baseEditorsApi.prototype.asc_Recalculate=function(){};baseEditorsApi.prototype["asc_nativeCheckPdfRenderer"]=function(_memory1,_memory2){if(true){_memory1.Copy=_memory1["Copy"];_memory1.ClearNoAttack=_memory1["ClearNoAttack"];_memory1.WriteByte=_memory1["WriteByte"]; _memory1.WriteBool=_memory1["WriteBool"];_memory1.WriteLong=_memory1["WriteLong"];_memory1.WriteDouble=_memory1["WriteDouble"];_memory1.WriteString=_memory1["WriteString"];_memory1.WriteString2=_memory1["WriteString2"];_memory2.Copy=_memory1["Copy"];_memory2.ClearNoAttack=_memory1["ClearNoAttack"];_memory2.WriteByte=_memory1["WriteByte"];_memory2.WriteBool=_memory1["WriteBool"];_memory2.WriteLong=_memory1["WriteLong"];_memory2.WriteDouble=_memory1["WriteDouble"];_memory2.WriteString=_memory1["WriteString"]; _memory2.WriteString2=_memory1["WriteString2"]}var _printer=new AscCommon.CDocumentRenderer;_printer.Memory=_memory1;_printer.VectorMemoryForPrint=_memory2;return _printer};baseEditorsApi.prototype.Begin_CompositeInput=function(){};baseEditorsApi.prototype.Add_CompositeText=function(nCharCode){};baseEditorsApi.prototype.Remove_CompositeText=function(nCount){};baseEditorsApi.prototype.Replace_CompositeText=function(arrCharCodes){};baseEditorsApi.prototype.Set_CursorPosInCompositeText=function(nPos){}; @@ -1993,10 +1993,10 @@ true;var ret=editor.WordControl.onKeyDown(e);editor.WordControl.IsFocus=false;re if(null!=this.WordControl.m_oLogicDocument)this.WordControl.m_oLogicDocument.viewMode=true}else{this.WordControl.checkNeedRules();this.WordControl.m_oDrawingDocument.ClearCachePages();this.WordControl.OnResize(true);if(null!=this.WordControl.m_oLogicDocument)this.WordControl.m_oLogicDocument.viewMode=false}};asc_docs_api.prototype.sync_HyperlinkClickCallback=function(Url){var indAction=Url.indexOf("ppaction://hlink");if(0==indAction){if(Url=="ppaction://hlinkshowjump?jump=firstslide")this.WordControl.GoToPage(0); else if(Url=="ppaction://hlinkshowjump?jump=lastslide")this.WordControl.GoToPage(this.WordControl.m_oDrawingDocument.SlidesCount-1);else if(Url=="ppaction://hlinkshowjump?jump=nextslide")this.WordControl.onNextPage();else if(Url=="ppaction://hlinkshowjump?jump=previousslide")this.WordControl.onPrevPage();else{var mask="ppaction://hlinksldjumpslide";var indSlide=Url.indexOf(mask);if(0==indSlide){var slideNum=parseInt(Url.substring(mask.length));if(slideNum>=0&&slideNum=_count)return;var aSelectedSlides=this.WordControl.m_oLogicDocument.GetSelectedSlides();for(var i=0;i=_count)return;var aSelectedSlides=this.WordControl.m_oLogicDocument.GetSelectedSlides();for(var i=0;i=_count)return;var _curSlide=_slides[_cur];_curSlide.timing.makeDuplicate(this.WordControl.m_oLogicDocument.DefaultSlideTiming); var _default=this.WordControl.m_oLogicDocument.DefaultSlideTiming;for(var i=0;i<_count;i++){if(i==_cur)continue;_slides[i].applyTiming(_default)}}};asc_docs_api.prototype.SlideTransitionPlay=function(){var _count=this.WordControl.m_oDrawingDocument.SlidesCount;var _cur=this.WordControl.m_oDrawingDocument.SlideCurrent;if(_cur<0||_cur>=_count)return;var _timing=this.WordControl.m_oLogicDocument.Slides[_cur].timing;var _tr=this.WordControl.m_oDrawingDocument.TransitionSlide;_tr.Type=_timing.TransitionType; _tr.Param=_timing.TransitionOption;_tr.Duration=_timing.TransitionDuration;_tr.Start(true)};asc_docs_api.prototype.asc_HideSlides=function(isHide){this.WordControl.m_oLogicDocument.hideSlides(isHide)};asc_docs_api.prototype.sync_EndAddShape=function(){editor.sendEvent("asc_onEndAddShape");if(this.WordControl.m_oDrawingDocument.m_sLockedCursorType=="crosshair")this.WordControl.m_oDrawingDocument.UnlockCursorType()};asc_docs_api.prototype.asc_getChartObject=function(type){this.isChartEditor=true;if(!AscFormat.isRealNumber(type)){this.asc_onOpenChartFrame(); diff --git a/www/common/onlyoffice/v4/sdkjs/word/sdk-all-min.js b/www/common/onlyoffice/v4/sdkjs/word/sdk-all-min.js index e506201ae..e569b3a5e 100644 --- a/www/common/onlyoffice/v4/sdkjs/word/sdk-all-min.js +++ b/www/common/onlyoffice/v4/sdkjs/word/sdk-all-min.js @@ -266,13 +266,13 @@ editorType;this._isExcel=c_oEditorId.Spreadsheet===editorType;this._isPresentati docid;this.sockjs_url=AscCommon.getBaseUrl()+"../../../../doc/"+docid+"/c"};DocsCoApi.prototype.auth=function(isViewer,opt_openCmd,opt_isIdle){this._isViewer=isViewer;if(this._locks){this.ownedLockBlocks=[];for(var block in this._locks)if(this._locks.hasOwnProperty(block)){var lock=this._locks[block];if(lock["state"]===2)this.ownedLockBlocks.push(lock["blockValue"])}this._locks={}}this._send({"type":"auth","docid":this._docid,"documentCallbackUrl":this._documentCallbackUrl,"token":this._token,"user":{"id":this._user.asc_getId(), "username":this._user.asc_getUserName(),"firstname":this._user.asc_getFirstName(),"lastname":this._user.asc_getLastName(),"indexUser":this._indexUser},"editorType":this.editorType,"lastOtherSaveTime":this.lastOtherSaveTime,"block":this.ownedLockBlocks,"sessionId":this._id,"sessionTimeConnect":this._sessionTimeConnect,"sessionTimeIdle":opt_isIdle>=0?opt_isIdle:0,"documentFormatSave":this._documentFormatSave,"view":this._isViewer,"isCloseCoAuthoring":this.isCloseCoAuthoring,"openCmd":opt_openCmd,"lang":this.lang, "mode":this.mode,"permissions":this.permissions,"encrypted":this.encrypted,"jwtOpen":this.jwtOpen,"jwtSession":this.jwtSession})};DocsCoApi.prototype._initSocksJs=function(){var t=this;var sockjs;sockjs=this.sockjs={};var send=function(data){setTimeout(function(){sockjs.onmessage({data:JSON.stringify(data)})})};var license={type:"license",license:{type:3,mode:0,rights:1,buildVersion:"5.2.6",buildNumber:2}};var channel;require(["/common/outer/worker-channel.js","/common/common-util.js"],function(Channel, -Util){var msgEv=Util.mkEvent();var p=window.parent;window.addEventListener("message",function(msg){if(msg.source!==p)return;msgEv.fire(msg)});var postMsg=function(data){p.postMessage(data,"*")};Channel.create(msgEv,postMsg,function(chan){channel=chan;send(license);chan.on("CMD",function(obj){send(obj)})})});sockjs.onopen=function(){t._state=ConnectionState.WaitAuth;t.onFirstConnect()};sockjs.onopen();sockjs.close=function(){console.error("Close realtime")};sockjs.send=function(data){try{var obj=JSON.parse(data)}catch(e){console.error(e); -return}if(channel)channel.event("CMD",obj)};sockjs.onmessage=function(e){t._onServerMessage(e.data)};return sockjs};DocsCoApi.prototype._onServerOpen=function(){if(this.reconnectTimeout){clearTimeout(this.reconnectTimeout);this.reconnectTimeout=null;this.attemptCount=0}this._state=ConnectionState.WaitAuth;this.onFirstConnect()};DocsCoApi.prototype._onServerMessage=function(data){var dataObject=JSON.parse(data);switch(dataObject["type"]){case "auth":this._onAuth(dataObject);break;case "message":this._onMessages(dataObject, -false);break;case "cursor":this._onCursor(dataObject);break;case "meta":this._onMeta(dataObject);break;case "getLock":this._onGetLock(dataObject);break;case "releaseLock":this._onReleaseLock(dataObject);break;case "connectState":this._onConnectionStateChanged(dataObject);break;case "saveChanges":this._onSaveChanges(dataObject);break;case "authChanges":this._onAuthChanges(dataObject);break;case "saveLock":this._onSaveLock(dataObject);break;case "unSaveLock":this._onUnSaveLock(dataObject);break;case "savePartChanges":this._onSavePartChanges(dataObject); -break;case "drop":this._onDrop(dataObject);break;case "waitAuth":break;case "error":this._onDrop(dataObject);break;case "documentOpen":this._documentOpen(dataObject);break;case "warning":this._onWarning(dataObject);break;case "license":this._onLicense(dataObject);break;case "session":this._onSession(dataObject);break;case "refreshToken":this._onRefreshToken(dataObject["messages"]);break;case "expiredToken":this._onExpiredToken(dataObject);break;case "forceSaveStart":this._onForceSaveStart(dataObject["messages"]); -break;case "forceSave":this._onForceSave(dataObject["messages"]);break}};DocsCoApi.prototype._onServerClose=function(evt){if(ConnectionState.SaveChanges===this._state){this._isReSaveAfterAuth=true;if(null!==this.saveCallbackErrorTimeOutId){clearTimeout(this.saveCallbackErrorTimeOutId);this.saveCallbackErrorTimeOutId=null}}this._state=ConnectionState.Reconnect;var bIsDisconnectAtAll=c_oCloseCode.serverShutdown<=evt.code&&evt.code<=c_oCloseCode.drop||this.attemptCount>=this.maxAttemptCount;var code= -null;if(bIsDisconnectAtAll){this._state=ConnectionState.ClosedAll;code=evt.code}if(this.onDisconnect)this.onDisconnect(evt.reason,code);if(!bIsDisconnectAtAll)this._tryReconnect()};DocsCoApi.prototype._reconnect=function(){delete this.sockjs;this._initSocksJs()};DocsCoApi.prototype._tryReconnect=function(){var t=this;if(this.reconnectTimeout){clearTimeout(this.reconnectTimeout);t.reconnectTimeout=null}++this.attemptCount;this.reconnectTimeout=setTimeout(function(){t._reconnect()},this.reconnectInterval)}; -window["AscCommon"]=window["AscCommon"]||{};window["AscCommon"].CDocsCoApi=CDocsCoApi})(window);"use strict"; +Util){var msgEv=Util.mkEvent();var p=window.parent;if(editor&&editor.isReporterMode){p=window.opener;window.parent=p}else window.APP=p&&p.APP;window.addEventListener("message",function(msg){if(msg.source!==p)return;msgEv.fire(msg)});var postMsg=function(data){p.postMessage(data,"*")};Channel.create(msgEv,postMsg,function(chan){channel=chan;send(license);chan.on("CMD",function(obj){send(obj)})})});sockjs.onopen=function(){t._state=ConnectionState.WaitAuth;t.onFirstConnect()};sockjs.onopen();sockjs.close= +function(){console.error("Close realtime")};sockjs.send=function(data){try{var obj=JSON.parse(data)}catch(e){console.error(e);return}if(channel)channel.event("CMD",obj)};sockjs.onmessage=function(e){t._onServerMessage(e.data)};return sockjs};DocsCoApi.prototype._onServerOpen=function(){if(this.reconnectTimeout){clearTimeout(this.reconnectTimeout);this.reconnectTimeout=null;this.attemptCount=0}this._state=ConnectionState.WaitAuth;this.onFirstConnect()};DocsCoApi.prototype._onServerMessage=function(data){var dataObject= +JSON.parse(data);switch(dataObject["type"]){case "auth":this._onAuth(dataObject);break;case "message":this._onMessages(dataObject,false);break;case "cursor":this._onCursor(dataObject);break;case "meta":this._onMeta(dataObject);break;case "getLock":this._onGetLock(dataObject);break;case "releaseLock":this._onReleaseLock(dataObject);break;case "connectState":this._onConnectionStateChanged(dataObject);break;case "saveChanges":this._onSaveChanges(dataObject);break;case "authChanges":this._onAuthChanges(dataObject); +break;case "saveLock":this._onSaveLock(dataObject);break;case "unSaveLock":this._onUnSaveLock(dataObject);break;case "savePartChanges":this._onSavePartChanges(dataObject);break;case "drop":this._onDrop(dataObject);break;case "waitAuth":break;case "error":this._onDrop(dataObject);break;case "documentOpen":this._documentOpen(dataObject);break;case "warning":this._onWarning(dataObject);break;case "license":this._onLicense(dataObject);break;case "session":this._onSession(dataObject);break;case "refreshToken":this._onRefreshToken(dataObject["messages"]); +break;case "expiredToken":this._onExpiredToken(dataObject);break;case "forceSaveStart":this._onForceSaveStart(dataObject["messages"]);break;case "forceSave":this._onForceSave(dataObject["messages"]);break}};DocsCoApi.prototype._onServerClose=function(evt){if(ConnectionState.SaveChanges===this._state){this._isReSaveAfterAuth=true;if(null!==this.saveCallbackErrorTimeOutId){clearTimeout(this.saveCallbackErrorTimeOutId);this.saveCallbackErrorTimeOutId=null}}this._state=ConnectionState.Reconnect;var bIsDisconnectAtAll= +c_oCloseCode.serverShutdown<=evt.code&&evt.code<=c_oCloseCode.drop||this.attemptCount>=this.maxAttemptCount;var code=null;if(bIsDisconnectAtAll){this._state=ConnectionState.ClosedAll;code=evt.code}if(this.onDisconnect)this.onDisconnect(evt.reason,code);if(!bIsDisconnectAtAll)this._tryReconnect()};DocsCoApi.prototype._reconnect=function(){delete this.sockjs;this._initSocksJs()};DocsCoApi.prototype._tryReconnect=function(){var t=this;if(this.reconnectTimeout){clearTimeout(this.reconnectTimeout);t.reconnectTimeout= +null}++this.attemptCount;this.reconnectTimeout=setTimeout(function(){t._reconnect()},this.reconnectInterval)};window["AscCommon"]=window["AscCommon"]||{};window["AscCommon"].CDocsCoApi=CDocsCoApi})(window);"use strict"; (function(window){var CSpellCheckApi=function(){this._SpellCheckApi=new SpellCheckApi;this._onlineWork=false;this.onDisconnect=null;this.onSpellCheck=null};CSpellCheckApi.prototype.init=function(docid){if(this._SpellCheckApi&&this._SpellCheckApi.isRightURL()){var t=this;this._SpellCheckApi.onDisconnect=function(e,isDisconnectAtAll,isCloseCoAuthoring){t.callback_OnDisconnect(e,isDisconnectAtAll,isCloseCoAuthoring)};this._SpellCheckApi.onSpellCheck=function(e){t.callback_OnSpellCheck(e)};this._SpellCheckApi.onInit= function(e){t.callback_OnInit(e)};this._SpellCheckApi.init(docid);this._onlineWork=true}};CSpellCheckApi.prototype.set_url=function(url){if(this._SpellCheckApi)this._SpellCheckApi.set_url(url)};CSpellCheckApi.prototype.get_state=function(){if(this._SpellCheckApi)return this._SpellCheckApi.get_state();return 0};CSpellCheckApi.prototype.disconnect=function(){if(this._SpellCheckApi&&this._onlineWork)this._SpellCheckApi.disconnect()};CSpellCheckApi.prototype.spellCheck=function(spellCheckData){if(this._SpellCheckApi&& this._onlineWork)this._SpellCheckApi.spellCheck(spellCheckData)};CSpellCheckApi.prototype.checkDictionary=function(lang){if(this._SpellCheckApi&&this._onlineWork)return this._SpellCheckApi.checkDictionary(lang);return true};CSpellCheckApi.prototype.callback_OnSpellCheck=function(e){if(this.onSpellCheck)return this.onSpellCheck(e)};CSpellCheckApi.prototype.callback_OnInit=function(e){if(this.onInit)return this.onInit(e)};CSpellCheckApi.prototype.callback_OnDisconnect=function(e,isDisconnectAtAll,isCloseCoAuthoring){if(this.onDisconnect)return this.onDisconnect(e, @@ -1364,62 +1364,62 @@ prot["RegisteredSign"]=prot.RegisteredSign;prot["RightPara"]=prot.RightPara;prot prot["SoftHyphen"]=prot.SoftHyphen;prot["HorizontalEllipsis"]=prot.HorizontalEllipsis;prot["Subscript"]=prot.Subscript;prot["IncreaseFontSize"]=prot.IncreaseFontSize;prot["DecreaseFontSize"]=prot.DecreaseFontSize;prot=window["Asc"]["c_oAscDocumentRefenceToType"]=window["Asc"].c_oAscDocumentRefenceToType=c_oAscDocumentRefenceToType;prot["Text"]=prot.Text;prot["PageNum"]=prot.PageNum;prot["ParaNum"]=prot.ParaNum;prot["ParaNumNoContext"]=prot.ParaNumNoContext;prot["ParaNumFullContex"]=prot.ParaNumFullContex; prot["AboveBelow"]=prot.AboveBelow;prot["OnlyLabelAndNumber"]=prot.OnlyLabelAndNumber;prot["OnlyCaptionText"]=prot.OnlyCaptionText;prot["NoteNumber"]=prot.NoteNumber;prot["NoteNumberFormatted"]=prot.NoteNumberFormatted;"use strict"; (function(window,undefined){var FOREIGN_CURSOR_LABEL_HIDETIME=1500;function CCollaborativeChanges(){this.m_pData=null;this.m_oColor=null}CCollaborativeChanges.prototype.Set_Data=function(pData){this.m_pData=pData};CCollaborativeChanges.prototype.Set_Color=function(oColor){this.m_oColor=oColor};CCollaborativeChanges.prototype.Set_FromUndoRedo=function(Class,Data,Binary){if(!Class.Get_Id)return false;this.m_pData=this.private_SaveData(Binary);return true};CCollaborativeChanges.prototype.Apply_Data= -function(){var CollaborativeEditing=AscCommon.CollaborativeEditing;var Reader=this.private_LoadData(this.m_pData);var ClassId=Reader.GetString2();var Class=AscCommon.g_oTableId.Get_ById(ClassId);if(!Class)return false;var nReaderPos=Reader.GetCurPos();var nChangesType=Reader.GetLong();var fChangesClass=AscDFH.changesFactory[nChangesType];if(fChangesClass){var oChange=new fChangesClass(Class);oChange.ReadFromBinary(Reader);if(true===CollaborativeEditing.private_AddOverallChange(oChange))oChange.Load(this.m_oColor); -return true}else{CollaborativeEditing.private_AddOverallChange(this.m_pData);Reader.Seek2(nReaderPos);if(!Class.Load_Changes)return false;return Class.Load_Changes(Reader,null,this.m_oColor)}};CCollaborativeChanges.prototype.private_LoadData=function(szSrc){return this.GetStream(szSrc,0,szSrc.length)};CCollaborativeChanges.prototype.GetStream=function(szSrc,offset,srcLen){var nWritten=0;var index=-1+offset;var dst_len="";while(true){index++;var _c=szSrc.charCodeAt(index);if(_c==";".charCodeAt(0)){index++; -break}dst_len+=String.fromCharCode(_c)}var dstLen=parseInt(dst_len);var pointer=AscFonts.g_memory.Alloc(dstLen);var stream=new AscCommon.FT_Stream2(pointer.data,dstLen);stream.obj=pointer.obj;var dstPx=stream.data;if(window.chrome)while(index=srcLen)break;var nCh=AscFonts.DecodeBase64Char(szSrc.charCodeAt(index++));if(nCh==-1){i--;continue}dwCurr<<=6;dwCurr|=nCh;nBits+=6}dwCurr<<=24-nBits;for(i=0;i>>16;dwCurr<<=8}}else{var p=AscFonts.b64_decode;while(index=srcLen)break;var nCh=p[szSrc.charCodeAt(index++)];if(nCh==undefined){i--;continue}dwCurr<<=6;dwCurr|=nCh;nBits+=6}dwCurr<<=24-nBits;for(i=0;i>>16;dwCurr<<=8}}}return stream};CCollaborativeChanges.prototype.private_SaveData=function(Binary){var Writer=AscCommon.History.BinaryWriter;var Pos=Binary.Pos;var Len=Binary.Len; -return Len+";"+Writer.GetBase64Memory2(Pos,Len)};function CCollaborativeEditingBase(){this.m_nUseType=1;this.m_aUsers=[];this.m_aChanges=[];this.m_aNeedUnlock=[];this.m_aNeedUnlock2=[];this.m_aNeedLock=[];this.m_aLinkData=[];this.m_aEndActions=[];this.m_bGlobalLock=0;this.m_bGlobalLockSelection=0;this.m_aCheckLocks=[];this.m_aCheckLocksInstance=[];this.m_aNewObjects=[];this.m_aNewImages=[];this.m_aDC={};this.m_aChangedClasses={};this.m_oMemory=null;this.m_aCursorsToUpdate={};this.m_aCursorsToUpdateShortId= -{};this.m_bFast=false;this.m_oLogicDocument=null;this.m_aDocumentPositions=new CDocumentPositionsManager;this.m_aForeignCursorsPos=new CDocumentPositionsManager;this.m_aForeignCursors={};this.m_aForeignCursorsId={};this.m_nAllChangesSavedIndex=0;this.m_aAllChanges=[];this.m_aOwnChangesIndexes=[];this.m_oOwnChanges=[]}CCollaborativeEditingBase.prototype.Clear=function(){this.m_nUseType=1;this.m_aUsers=[];this.m_aChanges=[];this.m_aNeedUnlock=[];this.m_aNeedUnlock2=[];this.m_aNeedLock=[];this.m_aLinkData= -[];this.m_aEndActions=[];this.m_aCheckLocks=[];this.m_aCheckLocksInstance=[];this.m_aNewObjects=[];this.m_aNewImages=[]};CCollaborativeEditingBase.prototype.Set_Fast=function(bFast){this.m_bFast=bFast;if(false===bFast){this.Remove_AllForeignCursors();this.RemoveMyCursorFromOthers()}};CCollaborativeEditingBase.prototype.Is_Fast=function(){return this.m_bFast};CCollaborativeEditingBase.prototype.Is_SingleUser=function(){return 1===this.m_nUseType};CCollaborativeEditingBase.prototype.getCollaborativeEditing= -function(){return!this.Is_SingleUser()};CCollaborativeEditingBase.prototype.Start_CollaborationEditing=function(){this.m_nUseType=-1};CCollaborativeEditingBase.prototype.End_CollaborationEditing=function(){if(this.m_nUseType<=0)this.m_nUseType=0};CCollaborativeEditingBase.prototype.Add_User=function(UserId){if(-1===this.Find_User(UserId))this.m_aUsers.push(UserId)};CCollaborativeEditingBase.prototype.Find_User=function(UserId){var Len=this.m_aUsers.length;for(var Index=0;Index0;if(true===OtherChanges){AscFonts.IsCheckSymbols=true;editor.WordControl.m_oLogicDocument.StopRecalculate();editor.WordControl.m_oLogicDocument.EndPreview_MailMergeResult();editor.sync_StartAction(Asc.c_oAscAsyncActionType.BlockInteraction,Asc.c_oAscAsyncAction.ApplyChanges);var DocState=this.private_SaveDocumentState();this.Clear_NewImages();this.Apply_OtherChanges(); -this.Lock_NeedLock();this.private_RestoreDocumentState(DocState);this.OnStart_Load_Objects();AscFonts.IsCheckSymbols=false}};CCollaborativeEditingBase.prototype.Apply_OtherChanges=function(){AscCommon.g_oIdCounter.Set_Load(true);if(this.m_aChanges.length>0)this.private_CollectOwnChanges();var _count=this.m_aChanges.length;for(var i=0;i<_count;i++){if(window["NATIVE_EDITOR_ENJINE"]===true&&window["native"]["CheckNextChange"])if(!window["native"]["CheckNextChange"]())break;var Changes=this.m_aChanges[i]; -Changes.Apply_Data()}this.private_ClearChanges();this.Apply_LinkData();this.Check_MergeData();this.OnEnd_ReadForeignChanges();AscCommon.g_oIdCounter.Set_Load(false)};CCollaborativeEditingBase.prototype.getOwnLocksLength=function(){return this.m_aNeedUnlock2.length};CCollaborativeEditingBase.prototype.Send_Changes=function(){};CCollaborativeEditingBase.prototype.Release_Locks=function(){};CCollaborativeEditingBase.prototype.CheckWaitingImages=function(aImages){};CCollaborativeEditingBase.prototype.SendImagesUrlsFromChanges= -function(aImages){var rData={},oApi=editor||Asc["editor"],i;if(!oApi)return;rData["c"]="pathurls";rData["data"]=[];for(i=0;i0)this.SendImagesUrlsFromChanges(aImages);else{this.SendImagesCallback([].concat(this.m_aNewImages));this.m_aNewImages.length=0}};CCollaborativeEditingBase.prototype.OnEnd_Load_Objects=function(){};CCollaborativeEditingBase.prototype.Clear_LinkData=function(){this.m_aLinkData.length=0};CCollaborativeEditingBase.prototype.Add_LinkData=function(Class,LinkData){this.m_aLinkData.push({Class:Class,LinkData:LinkData})}; -CCollaborativeEditingBase.prototype.Apply_LinkData=function(){var Count=this.m_aLinkData.length;for(var Index=0;Index -0){this.m_aOwnChangesIndexes.push({Position:this.m_aAllChanges.length,Count:arrChanges.length});this.m_aAllChanges=this.m_aAllChanges.concat(arrChanges)}};CCollaborativeEditingBase.prototype.Undo=function(){if(true===this.Get_GlobalLock())return;if(this.m_aOwnChangesIndexes.length<=0)return false;var arrChanges=[];var oIndexes=this.m_aOwnChangesIndexes[this.m_aOwnChangesIndexes.length-1];var nPosition=oIndexes.Position;var nCount=oIndexes.Count;for(var nIndex=nCount-1;nIndex>=0;--nIndex){var oChange= -this.m_aAllChanges[nPosition+nIndex];if(!oChange)continue;var oClass=oChange.GetClass();if(oChange.IsContentChange()){var _oChange=oChange.Copy();if(this.private_CommutateContentChanges(_oChange,nPosition+nCount))arrChanges.push(_oChange);oChange.SetReverted(true)}else{var _oChange=oChange;if(this.private_CommutatePropertyChanges(oClass,_oChange,nPosition+nCount))arrChanges.push(_oChange)}}this.m_aOwnChangesIndexes.length=this.m_aOwnChangesIndexes.length-1;var arrReverseChanges=[];for(var nIndex= -0,nCount=arrChanges.length;nIndex-1;--i)if(mapAddedSlides[oLogicDocument.Slides[i].Get_Id()]&&!oLogicDocument.Slides[i].Layout)oLogicDocument.removeSlide(i);for(var sId in mapSlides)if(mapSlides.hasOwnProperty(sId))mapSlides[sId].correctContent();if(bChangedLayout)for(var i=oLogicDocument.Slides.length-1;i>-1;--i){var Layout= -oLogicDocument.Slides[i].Layout;if(!Layout||mapLayouts[Layout.Get_Id()])if(!oLogicDocument.Slides[i].CheckLayout())oLogicDocument.removeSlide(i)}for(var sId in mapGrObjects){var oShape=mapGrObjects[sId];if(!oShape.checkCorrect()){oShape.setBDeleted(true);if(oShape.group)oShape.group.removeFromSpTree(oShape.Get_Id());else if(AscFormat.Slide&&oShape.parent instanceof AscFormat.Slide)oShape.parent.removeFromSpTreeById(oShape.Get_Id());else if(AscCommonWord.ParaDrawing&&oShape.parent instanceof AscCommonWord.ParaDrawing)mapDrawings[oShape.parent.Get_Id()]= -oShape.parent}else if(oShape.resetGroups)oShape.resetGroups()}var oDrawing;for(var sId in mapDrawings)if(mapDrawings.hasOwnProperty(sId)){oDrawing=mapDrawings[sId];if(!oDrawing.CheckCorrect()){var oParentParagraph=oDrawing.Get_ParentParagraph();oDrawing.PreDelete();oDrawing.Remove_FromDocument(false);if(oParentParagraph)mapParagraphs[oParentParagraph.Get_Id()]=oParentParagraph}}for(var sId in mapRuns)if(mapRuns.hasOwnProperty(sId)){var oRun=mapRuns[sId];for(var nIndex=oRun.Content.length-1;nIndex> --1;--nIndex)if(oRun.Content[nIndex]instanceof AscCommonWord.ParaDrawing)if(!oRun.Content[nIndex].CheckCorrect()){oRun.Remove_FromContent(nIndex,1,false);if(oRun.Paragraph)mapParagraphs[oRun.Paragraph.Get_Id()]=oRun.Paragraph}}for(var sId in mapTables){var oTable=mapTables[sId];for(var nCurRow=oTable.Content.length-1;nCurRow>=0;--nCurRow){var oRow=oTable.Get_Row(nCurRow);if(oRow.Get_CellsCount()<=0)oTable.private_RemoveRow(nCurRow)}if(oTable.Parent instanceof AscCommonWord.CDocument||oTable.Parent instanceof -AscCommonWord.CDocumentContent)mapDocumentContents[oTable.Parent.Get_Id()]=oTable.Parent}for(var sId in mapDocumentContents){var oDocumentContent=mapDocumentContents[sId];var nContentLen=oDocumentContent.Content.length;for(var nIndex=nContentLen-1;nIndex>=0;--nIndex){var oElement=oDocumentContent.Content[nIndex];if((AscCommonWord.type_Paragraph===oElement.GetType()||AscCommonWord.type_Table===oElement.GetType())&&oElement.Content.length<=0)oDocumentContent.Remove_FromContent(nIndex,1)}nContentLen= -oDocumentContent.Content.length;if(nContentLen<=0||AscCommonWord.type_Paragraph!==oDocumentContent.Content[nContentLen-1].GetType()){var oNewParagraph=new AscCommonWord.Paragraph(oLogicDocument.Get_DrawingDocument(),oDocumentContent,0,0,0,0,0,false);oDocumentContent.Add_ToContent(nContentLen,oNewParagraph)}}for(var sId in mapParagraphs){var oParagraph=mapParagraphs[sId];oParagraph.CheckParaEnd();oParagraph.Correct_Content(null,null,true)}var oBinaryWriter=AscCommon.History.BinaryWriter;var aSendingChanges= -[];for(var nIndex=0,nCount=arrReverseChanges.length;nIndex=0;--nActionIndex){var oAction=arrActions[nActionIndex];var oResult=oAction;for(var nIndex=nStartPosition,nOverallCount=this.m_aAllChanges.length;nIndex=srcLen)break;var nCh=AscFonts.DecodeBase64Char(szSrc.charCodeAt(index++));if(nCh==-1){i--;continue}dwCurr<<=6;dwCurr|=nCh;nBits+=6}dwCurr<<=24-nBits;for(i=0;i>>16;dwCurr<<=8}}else{var p=AscFonts.b64_decode;while(index=srcLen)break;var nCh=p[szSrc.charCodeAt(index++)];if(nCh==undefined){i--;continue}dwCurr<<=6;dwCurr|=nCh;nBits+=6}dwCurr<<=24-nBits;for(i= +0;i>>16;dwCurr<<=8}}}return stream};CCollaborativeChanges.prototype.private_SaveData=function(Binary){var Writer=AscCommon.History.BinaryWriter;var Pos=Binary.Pos;var Len=Binary.Len;return Len+";"+Writer.GetBase64Memory2(Pos,Len)};function CCollaborativeEditingBase(){this.m_nUseType=1;this.m_aUsers=[];this.m_aChanges=[];this.m_aNeedUnlock=[];this.m_aNeedUnlock2=[];this.m_aNeedLock=[];this.m_aLinkData=[];this.m_aEndActions=[];this.m_bGlobalLock=0;this.m_bGlobalLockSelection= +0;this.m_aCheckLocks=[];this.m_aCheckLocksInstance=[];this.m_aNewObjects=[];this.m_aNewImages=[];this.m_aDC={};this.m_aChangedClasses={};this.m_oMemory=null;this.m_aCursorsToUpdate={};this.m_aCursorsToUpdateShortId={};this.m_bFast=false;this.m_oLogicDocument=null;this.m_aDocumentPositions=new CDocumentPositionsManager;this.m_aForeignCursorsPos=new CDocumentPositionsManager;this.m_aForeignCursors={};this.m_aForeignCursorsId={};this.m_nAllChangesSavedIndex=0;this.m_aAllChanges=[];this.m_aOwnChangesIndexes= +[];this.m_oOwnChanges=[]}CCollaborativeEditingBase.prototype.Clear=function(){this.m_nUseType=1;this.m_aUsers=[];this.m_aChanges=[];this.m_aNeedUnlock=[];this.m_aNeedUnlock2=[];this.m_aNeedLock=[];this.m_aLinkData=[];this.m_aEndActions=[];this.m_aCheckLocks=[];this.m_aCheckLocksInstance=[];this.m_aNewObjects=[];this.m_aNewImages=[]};CCollaborativeEditingBase.prototype.Set_Fast=function(bFast){this.m_bFast=bFast;if(false===bFast){this.Remove_AllForeignCursors();this.RemoveMyCursorFromOthers()}};CCollaborativeEditingBase.prototype.Is_Fast= +function(){return this.m_bFast};CCollaborativeEditingBase.prototype.Is_SingleUser=function(){return 1===this.m_nUseType};CCollaborativeEditingBase.prototype.getCollaborativeEditing=function(){return!this.Is_SingleUser()};CCollaborativeEditingBase.prototype.Start_CollaborationEditing=function(){this.m_nUseType=-1};CCollaborativeEditingBase.prototype.End_CollaborationEditing=function(){if(this.m_nUseType<=0)this.m_nUseType=0};CCollaborativeEditingBase.prototype.Add_User=function(UserId){if(-1===this.Find_User(UserId))this.m_aUsers.push(UserId)}; +CCollaborativeEditingBase.prototype.Find_User=function(UserId){var Len=this.m_aUsers.length;for(var Index=0;Index0;if(true===OtherChanges){AscFonts.IsCheckSymbols=true;editor.WordControl.m_oLogicDocument.StopRecalculate();editor.WordControl.m_oLogicDocument.EndPreview_MailMergeResult(); +editor.sync_StartAction(Asc.c_oAscAsyncActionType.BlockInteraction,Asc.c_oAscAsyncAction.ApplyChanges);var DocState=this.private_SaveDocumentState();this.Clear_NewImages();this.Apply_OtherChanges();this.Lock_NeedLock();this.private_RestoreDocumentState(DocState);this.OnStart_Load_Objects();AscFonts.IsCheckSymbols=false}};CCollaborativeEditingBase.prototype.Apply_OtherChanges=function(){AscCommon.g_oIdCounter.Set_Load(true);if(this.m_aChanges.length>0)this.private_CollectOwnChanges();var _count=this.m_aChanges.length; +for(var i=0;i<_count;i++){if(window["NATIVE_EDITOR_ENJINE"]===true&&window["native"]["CheckNextChange"])if(!window["native"]["CheckNextChange"]())break;var Changes=this.m_aChanges[i];Changes.Apply_Data()}this.private_ClearChanges();this.Apply_LinkData();this.Check_MergeData();this.OnEnd_ReadForeignChanges();AscCommon.g_oIdCounter.Set_Load(false)};CCollaborativeEditingBase.prototype.getOwnLocksLength=function(){return this.m_aNeedUnlock2.length};CCollaborativeEditingBase.prototype.Send_Changes=function(){}; +CCollaborativeEditingBase.prototype.Release_Locks=function(){};CCollaborativeEditingBase.prototype.CheckWaitingImages=function(aImages){};CCollaborativeEditingBase.prototype.SendImagesUrlsFromChanges=function(aImages){var rData={},oApi=editor||Asc["editor"],i;if(!oApi)return;rData["c"]="pathurls";rData["data"]=[];for(i=0;i0)this.SendImagesUrlsFromChanges(aImages);else{this.SendImagesCallback([].concat(this.m_aNewImages));this.m_aNewImages.length=0}};CCollaborativeEditingBase.prototype.OnEnd_Load_Objects=function(){};CCollaborativeEditingBase.prototype.Clear_LinkData=function(){this.m_aLinkData.length=0};CCollaborativeEditingBase.prototype.Add_LinkData= +function(Class,LinkData){this.m_aLinkData.push({Class:Class,LinkData:LinkData})};CCollaborativeEditingBase.prototype.Apply_LinkData=function(){var Count=this.m_aLinkData.length;for(var Index=0;Index0){this.m_aOwnChangesIndexes.push({Position:this.m_aAllChanges.length,Count:arrChanges.length});this.m_aAllChanges=this.m_aAllChanges.concat(arrChanges)}};CCollaborativeEditingBase.prototype.Undo=function(){if(true===this.Get_GlobalLock())return;if(this.m_aOwnChangesIndexes.length<=0)return false;var arrChanges=[];var oIndexes=this.m_aOwnChangesIndexes[this.m_aOwnChangesIndexes.length- +1];var nPosition=oIndexes.Position;var nCount=oIndexes.Count;for(var nIndex=nCount-1;nIndex>=0;--nIndex){var oChange=this.m_aAllChanges[nPosition+nIndex];if(!oChange)continue;var oClass=oChange.GetClass();if(oChange.IsContentChange()){var _oChange=oChange.Copy();if(this.private_CommutateContentChanges(_oChange,nPosition+nCount))arrChanges.push(_oChange);oChange.SetReverted(true)}else{var _oChange=oChange;if(this.private_CommutatePropertyChanges(oClass,_oChange,nPosition+nCount))arrChanges.push(_oChange)}}this.m_aOwnChangesIndexes.length= +this.m_aOwnChangesIndexes.length-1;var arrReverseChanges=[];for(var nIndex=0,nCount=arrChanges.length;nIndex-1;--i)if(mapAddedSlides[oLogicDocument.Slides[i].Get_Id()]&&!oLogicDocument.Slides[i].Layout)oLogicDocument.removeSlide(i);for(var sId in mapSlides)if(mapSlides.hasOwnProperty(sId))mapSlides[sId].correctContent(); +if(bChangedLayout)for(var i=oLogicDocument.Slides.length-1;i>-1;--i){var Layout=oLogicDocument.Slides[i].Layout;if(!Layout||mapLayouts[Layout.Get_Id()])if(!oLogicDocument.Slides[i].CheckLayout())oLogicDocument.removeSlide(i)}for(var sId in mapGrObjects){var oShape=mapGrObjects[sId];if(!oShape.checkCorrect()){oShape.setBDeleted(true);if(oShape.group)oShape.group.removeFromSpTree(oShape.Get_Id());else if(AscFormat.Slide&&oShape.parent instanceof AscFormat.Slide)oShape.parent.removeFromSpTreeById(oShape.Get_Id()); +else if(AscCommonWord.ParaDrawing&&oShape.parent instanceof AscCommonWord.ParaDrawing)mapDrawings[oShape.parent.Get_Id()]=oShape.parent}else if(oShape.resetGroups)oShape.resetGroups()}var oDrawing;for(var sId in mapDrawings)if(mapDrawings.hasOwnProperty(sId)){oDrawing=mapDrawings[sId];if(!oDrawing.CheckCorrect()){var oParentParagraph=oDrawing.Get_ParentParagraph();oDrawing.PreDelete();oDrawing.Remove_FromDocument(false);if(oParentParagraph)mapParagraphs[oParentParagraph.Get_Id()]=oParentParagraph}}for(var sId in mapRuns)if(mapRuns.hasOwnProperty(sId)){var oRun= +mapRuns[sId];for(var nIndex=oRun.Content.length-1;nIndex>-1;--nIndex)if(oRun.Content[nIndex]instanceof AscCommonWord.ParaDrawing)if(!oRun.Content[nIndex].CheckCorrect()){oRun.Remove_FromContent(nIndex,1,false);if(oRun.Paragraph)mapParagraphs[oRun.Paragraph.Get_Id()]=oRun.Paragraph}}for(var sId in mapTables){var oTable=mapTables[sId];for(var nCurRow=oTable.Content.length-1;nCurRow>=0;--nCurRow){var oRow=oTable.Get_Row(nCurRow);if(oRow.Get_CellsCount()<=0)oTable.private_RemoveRow(nCurRow)}if(oTable.Parent instanceof +AscCommonWord.CDocument||oTable.Parent instanceof AscCommonWord.CDocumentContent)mapDocumentContents[oTable.Parent.Get_Id()]=oTable.Parent}for(var sId in mapDocumentContents){var oDocumentContent=mapDocumentContents[sId];var nContentLen=oDocumentContent.Content.length;for(var nIndex=nContentLen-1;nIndex>=0;--nIndex){var oElement=oDocumentContent.Content[nIndex];if((AscCommonWord.type_Paragraph===oElement.GetType()||AscCommonWord.type_Table===oElement.GetType())&&oElement.Content.length<=0)oDocumentContent.Remove_FromContent(nIndex, +1)}nContentLen=oDocumentContent.Content.length;if(nContentLen<=0||AscCommonWord.type_Paragraph!==oDocumentContent.Content[nContentLen-1].GetType()){var oNewParagraph=new AscCommonWord.Paragraph(oLogicDocument.Get_DrawingDocument(),oDocumentContent,0,0,0,0,0,false);oDocumentContent.Add_ToContent(nContentLen,oNewParagraph)}}for(var sId in mapParagraphs){var oParagraph=mapParagraphs[sId];oParagraph.CheckParaEnd();oParagraph.Correct_Content(null,null,true)}var oBinaryWriter=AscCommon.History.BinaryWriter; +var aSendingChanges=[];for(var nIndex=0,nCount=arrReverseChanges.length;nIndex=0;--nActionIndex){var oAction=arrActions[nActionIndex];var oResult=oAction;for(var nIndex=nStartPosition,nOverallCount= +this.m_aAllChanges.length;nIndex0)oChange.ConvertFromSimpleActions(arrCommutateActions);else return false;return true};CCollaborativeEditingBase.prototype.private_Commutate=function(oActionL,oActionR){if(oActionL.Add)if(oActionR.Add)if(oActionL.Pos>=oActionR.Pos)oActionL.Pos++;else oActionR.Pos--;else if(oActionL.Pos>oActionR.Pos)oActionL.Pos--;else if(oActionL.Pos===oActionR.Pos)return false;else oActionR.Pos--;else if(oActionR.Add)if(oActionL.Pos>=oActionR.Pos)oActionL.Pos++; else oActionR.Pos++;else if(oActionL.Pos>oActionR.Pos)oActionL.Pos--;else oActionR.Pos++;return true};CCollaborativeEditingBase.prototype.private_CommutatePropertyChanges=function(oClass,oChange,nStartPosition){if(oChange.CheckCorrect&&!oChange.CheckCorrect())return false;return true};CCollaborativeEditingBase.prototype.private_RecalculateDocument=function(oRecalcData){};function CDocumentPositionsManager(){this.m_aDocumentPositions=[];this.m_aDocumentPositionsSplit=[];this.m_aDocumentPositionsMap= []}CDocumentPositionsManager.prototype.Clear_DocumentPositions=function(){this.m_aDocumentPositions=[];this.m_aDocumentPositionsSplit=[];this.m_aDocumentPositionsMap=[]};CDocumentPositionsManager.prototype.Add_DocumentPosition=function(Position){this.m_aDocumentPositions.push(Position)};CDocumentPositionsManager.prototype.Update_DocumentPositionsOnAdd=function(Class,Pos){for(var PosIndex=0,PosCount=this.m_aDocumentPositions.length;PosIndex0&&typeof sData==="string"&&typeof sGuid==="string"&&sGuid.length>0&&AscFormat.isRealNumber(nWidthPix)&& -AscFormat.isRealNumber(nHeightPix)&&AscFormat.isRealNumber(fWidth)&&AscFormat.isRealNumber(fHeight))this.asc_checkImageUrlAndAction(sImgSrc,function(oImage){oThis.asc_addOleObjectAction(AscCommon.g_oDocumentUrls.getImageLocal(oImage.src),sData,sGuid,fWidth,fHeight,nWidthPix,nHeightPix)})};baseEditorsApi.prototype.asc_editOleObject=function(oPluginData){if(this.isViewMode)return;var oThis=this;var bResize=oPluginData["resize"];var sImgSrc=oPluginData["imgSrc"];var oOleObject=AscCommon.g_oTableId.Get_ById(oPluginData["objectId"]); -var nWidthPix=oPluginData["widthPix"];var nHeightPix=oPluginData["heightPix"];var sData=oPluginData["data"];if(typeof sImgSrc==="string"&&sImgSrc.length>0&&typeof sData==="string"&&oOleObject&&AscFormat.isRealNumber(nWidthPix)&&AscFormat.isRealNumber(nHeightPix))this.asc_checkImageUrlAndAction(sImgSrc,function(oImage){oThis.asc_editOleObjectAction(bResize,oOleObject,AscCommon.g_oDocumentUrls.getImageLocal(oImage.src),sData,nWidthPix,nHeightPix)})};baseEditorsApi.prototype.asc_addOleObjectAction=function(sLocalUrl, -sData,sApplicationId,fWidth,fHeight){};baseEditorsApi.prototype.asc_editOleObjectAction=function(bResize,oOleObject,sImageUrl,sData,nPixWidth,nPixHeight){};baseEditorsApi.prototype.asc_selectSearchingResults=function(value){if(this.selectSearchingResults===value)return;this.selectSearchingResults=value;this._selectSearchingResults(value)};baseEditorsApi.prototype.asc_startEditCurrentOleObject=function(){};baseEditorsApi.prototype.asc_canEditCrop=function(){};baseEditorsApi.prototype.asc_startEditCrop= -function(){};baseEditorsApi.prototype.asc_endEditCrop=function(){};baseEditorsApi.prototype.asc_cropFit=function(){};baseEditorsApi.prototype.asc_cropFill=function(){};baseEditorsApi.prototype.asc_RemoveAllComments=function(isMine,isCurrent){};baseEditorsApi.prototype.asc_showRevision=function(newObj){if(!newObj.docId)return;if(this.isCoAuthoringEnable)this.asc_coAuthoringDisconnect();var bUpdate=true;if(null===this.VersionHistory)this.VersionHistory=new window["Asc"].asc_CVersionHistory(newObj); -else bUpdate=this.VersionHistory.update(newObj);if(bUpdate){this.asc_CloseFile();this.DocInfo.put_Id(this.VersionHistory.docId);this.DocInfo.put_Url(this.VersionHistory.url);this.documentUrlChanges=this.VersionHistory.urlChanges;this.asc_setDocInfo(this.DocInfo);this.asc_LoadDocument(this.VersionHistory)}else if(this.VersionHistory.currentChangeIdb.name)return 1;if(a.name=0&&manager.SlideNum>0;var _zoom=_w/(_w_mm*AscCommon.g_dKoef_mm_to_pix);if(!transform)window["AscDesktopEditor"]["MediaStart"](sMediaName,_x,transition.Rect.y,extX,extY,_zoom);else window["AscDesktopEditor"]["MediaStart"](sMediaName,_x,transition.Rect.y, -extX,extY,_zoom,transform.sx,transform.shy,transform.shx,transform.sy,transform.tx,transform.ty)}}break}case c_oEditorId.Spreadsheet:{break}}};baseEditorsApi.prototype.hideVideoControl=function(){if(!window["AscDesktopEditor"]||!window["AscDesktopEditor"]["MediaEnd"])return;window["AscDesktopEditor"]["MediaEnd"]()};baseEditorsApi.prototype._checkLicenseApiFunctions=function(){return this.licenseResult&&true===this.licenseResult["plugins"]};baseEditorsApi.prototype.asc_pluginsRegister=function(basePath, -plugins){this.sendEvent("asc_LoadPluginsOrDocument");if(null!=this.pluginsManager){this.pluginsManager.register(basePath,plugins);if(this.pluginsManager.countEventDocContOrPluginsReady==2)this.pluginsManager.onPluginEvent("onDocumentContentReady")}};baseEditorsApi.prototype.asc_pluginRun=function(guid,variation,pluginData){if(null!=this.pluginsManager)this.pluginsManager.run(guid,variation,pluginData)};baseEditorsApi.prototype.asc_pluginStop=function(guid){if(null!=this.pluginsManager)this.pluginsManager.close(guid)}; -baseEditorsApi.prototype.asc_pluginResize=function(pluginData){if(null!=this.pluginsManager)this.pluginsManager.runResize(pluginData)};baseEditorsApi.prototype.asc_pluginButtonClick=function(id){if(null!=this.pluginsManager)this.pluginsManager.buttonClick(id)};baseEditorsApi.prototype.asc_pluginEnableMouseEvents=function(isEnable){if(!this.pluginsManager)return;this.pluginsManager.onEnableMouseEvents(isEnable)};baseEditorsApi.prototype.isEnabledDropTarget=function(){return true};baseEditorsApi.prototype.beginInlineDropTarget= -function(e){};baseEditorsApi.prototype.endInlineDropTarget=function(e){};baseEditorsApi.prototype["asc_insertSymbol"]=function(familyName,code,pr){var arrCharCodes=[code];AscFonts.FontPickerByCharacter.checkTextLight(arrCharCodes,true);var fonts=[new AscFonts.CFont(AscFonts.g_fontApplication.GetFontInfoName(familyName),0,"",0,null)];AscFonts.FontPickerByCharacter.extendFonts(fonts);this.asyncMethodCallback=function(){switch(this.editorId){case c_oEditorId.Word:case c_oEditorId.Presentation:{if(pr&& -c_oEditorId.Word===this.editorId)this.WordControl.m_oLogicDocument.AddSpecialSymbol(pr);else{var textPr=new AscCommonWord.CTextPr;textPr.SetFontFamily(familyName);this.WordControl.m_oLogicDocument.AddTextWithPr(new AscCommon.CUnicodeStringEmulator(arrCharCodes),textPr,true)}break}case c_oEditorId.Spreadsheet:{this.AddTextWithPr(familyName,arrCharCodes);break}}};if(false===AscCommon.g_font_loader.CheckFontsNeedLoading(fonts)){this.asyncMethodCallback();this.asyncMethodCallback=undefined;return}AscCommon.g_font_loader.LoadDocumentFonts2(fonts)}; -baseEditorsApi.prototype["asc_registerPlaceholderCallback"]=function(type,callback){if(this.WordControl&&this.WordControl.m_oDrawingDocument&&this.WordControl.m_oDrawingDocument.placeholders)this.WordControl.m_oDrawingDocument.placeholders.registerCallback(type,callback)};baseEditorsApi.prototype["asc_uncheckPlaceholders"]=function(){if(this.WordControl&&this.WordControl.m_oDrawingDocument&&this.WordControl.m_oDrawingDocument.placeholders)this.WordControl.m_oDrawingDocument.placeholders.closeAllActive()}; +(DownloadType.Print===downloadType||!downloadType)){var _cb=options.callback||this.fCurCallback;window.parent.APP.printPdf(dataContainer,function(obj){if(!obj){t.sync_EndAction(c_oAscAsyncActionType.BlockInteraction,actionType);return}_cb(obj)});return}AscCommon.saveWithParts(function(fCallback1,oAdditionalData1,dataContainer1){AscCommon.sendCommand(t,fCallback1,oAdditionalData1,dataContainer1)},this.fCurCallback,options.callback,oAdditionalData,dataContainer)};baseEditorsApi.prototype.asc_getChartPreviews= +function(chartType){return this.chartPreviewManager.getChartPreviews(chartType)};baseEditorsApi.prototype.asc_getTextArtPreviews=function(){return this.textArtPreviewManager.getWordArtStyles()};baseEditorsApi.prototype.asc_onOpenChartFrame=function(){if(this.isMobileVersion)return;this.isOpenedChartFrame=true};baseEditorsApi.prototype.asc_onCloseChartFrame=function(){this.isOpenedChartFrame=false};baseEditorsApi.prototype.asc_setInterfaceDrawImagePlaceShape=function(elementId){this.shapeElementId= +elementId};baseEditorsApi.prototype.asc_getPropertyEditorShapes=function(){return[AscCommon.g_oAutoShapesGroups,AscCommon.g_oAutoShapesTypes]};baseEditorsApi.prototype.asc_getPropertyEditorTextArts=function(){return[AscCommon.g_oPresetTxWarpGroups,AscCommon.g_PresetTxWarpTypes]};baseEditorsApi.prototype._addImageUrl=function(){};baseEditorsApi.prototype.asc_addImageCallback=function(res){};baseEditorsApi.prototype.asc_addImage=function(obj){var t=this;window.parent.APP.AddImage(function(res){console.log("AddImageCallback"); +t.asc_addImageCallback(res);t._addImageUrl([res.url])},function(){t.sendEvent("asc_onError",error,c_oAscError.Level.NoCritical)});return;var t=this;if(this.WordControl)this.WordControl.m_bIsMouseLock=false;AscCommon.ShowImageFileDialog(this.documentId,this.documentUserId,this.CoAuthoringApi.get_jwt(),function(error,files){t._uploadCallback(error,files,obj)},function(error){if(c_oAscError.ID.No!==error)t.sendEvent("asc_onError",error,c_oAscError.Level.NoCritical);t.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, +c_oAscAsyncAction.UploadImage)})};baseEditorsApi.prototype._uploadCallback=function(error,files,obj){var t=this;if(c_oAscError.ID.No!==error)this.sendEvent("asc_onError",error,c_oAscError.Level.NoCritical);else{this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction,c_oAscAsyncAction.UploadImage);AscCommon.UploadImageFiles(files,this.documentId,this.documentUserId,this.CoAuthoringApi.get_jwt(),function(error,urls){if(c_oAscError.ID.No!==error)t.sendEvent("asc_onError",error,c_oAscError.Level.NoCritical); +else t._addImageUrl(urls,obj);t.sync_EndAction(c_oAscAsyncActionType.BlockInteraction,c_oAscAsyncAction.UploadImage)})}};baseEditorsApi.prototype.asc_replaceLoadImageCallback=function(fCallback){};baseEditorsApi.prototype.asc_loadLocalImageAndAction=function(sLocalImage,fCallback){var _loadedUrl=this.ImageLoader.LoadImage(AscCommon.getFullImageSrc2(sLocalImage),1);if(_loadedUrl!=null)fCallback(_loadedUrl);else this.asc_replaceLoadImageCallback(fCallback)};baseEditorsApi.prototype.asc_checkImageUrlAndAction= +function(sImageUrl,fCallback){var oThis=this;this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction,c_oAscAsyncAction.UploadImage);var fCallback2=function(){oThis.sync_EndAction(c_oAscAsyncActionType.BlockInteraction,c_oAscAsyncAction.UploadImage);fCallback.apply(oThis,arguments)};var sLocalImage=AscCommon.g_oDocumentUrls.getImageLocal(sImageUrl);if(sLocalImage){this.asc_loadLocalImageAndAction(sLocalImage,fCallback2);return}AscCommon.sendImgUrls(oThis,[sImageUrl],function(data){if(data[0]&& +data[0].path!=null&&data[0].url!=="error")oThis.asc_loadLocalImageAndAction(AscCommon.g_oDocumentUrls.imagePath2Local(data[0].path),fCallback2)},this.editorId===c_oEditorId.Spreadsheet)};baseEditorsApi.prototype.asc_addOleObject=function(oPluginData){if(this.isViewMode)return;var oThis=this;var sImgSrc=oPluginData["imgSrc"];var nWidthPix=oPluginData["widthPix"];var nHeightPix=oPluginData["heightPix"];var fWidth=oPluginData["width"];var fHeight=oPluginData["height"];var sData=oPluginData["data"];var sGuid= +oPluginData["guid"];if(typeof sImgSrc==="string"&&sImgSrc.length>0&&typeof sData==="string"&&typeof sGuid==="string"&&sGuid.length>0&&AscFormat.isRealNumber(nWidthPix)&&AscFormat.isRealNumber(nHeightPix)&&AscFormat.isRealNumber(fWidth)&&AscFormat.isRealNumber(fHeight))this.asc_checkImageUrlAndAction(sImgSrc,function(oImage){oThis.asc_addOleObjectAction(AscCommon.g_oDocumentUrls.getImageLocal(oImage.src),sData,sGuid,fWidth,fHeight,nWidthPix,nHeightPix)})};baseEditorsApi.prototype.asc_editOleObject= +function(oPluginData){if(this.isViewMode)return;var oThis=this;var bResize=oPluginData["resize"];var sImgSrc=oPluginData["imgSrc"];var oOleObject=AscCommon.g_oTableId.Get_ById(oPluginData["objectId"]);var nWidthPix=oPluginData["widthPix"];var nHeightPix=oPluginData["heightPix"];var sData=oPluginData["data"];if(typeof sImgSrc==="string"&&sImgSrc.length>0&&typeof sData==="string"&&oOleObject&&AscFormat.isRealNumber(nWidthPix)&&AscFormat.isRealNumber(nHeightPix))this.asc_checkImageUrlAndAction(sImgSrc, +function(oImage){oThis.asc_editOleObjectAction(bResize,oOleObject,AscCommon.g_oDocumentUrls.getImageLocal(oImage.src),sData,nWidthPix,nHeightPix)})};baseEditorsApi.prototype.asc_addOleObjectAction=function(sLocalUrl,sData,sApplicationId,fWidth,fHeight){};baseEditorsApi.prototype.asc_editOleObjectAction=function(bResize,oOleObject,sImageUrl,sData,nPixWidth,nPixHeight){};baseEditorsApi.prototype.asc_selectSearchingResults=function(value){if(this.selectSearchingResults===value)return;this.selectSearchingResults= +value;this._selectSearchingResults(value)};baseEditorsApi.prototype.asc_startEditCurrentOleObject=function(){};baseEditorsApi.prototype.asc_canEditCrop=function(){};baseEditorsApi.prototype.asc_startEditCrop=function(){};baseEditorsApi.prototype.asc_endEditCrop=function(){};baseEditorsApi.prototype.asc_cropFit=function(){};baseEditorsApi.prototype.asc_cropFill=function(){};baseEditorsApi.prototype.asc_RemoveAllComments=function(isMine,isCurrent){};baseEditorsApi.prototype.asc_showRevision=function(newObj){if(!newObj.docId)return; +if(this.isCoAuthoringEnable)this.asc_coAuthoringDisconnect();var bUpdate=true;if(null===this.VersionHistory)this.VersionHistory=new window["Asc"].asc_CVersionHistory(newObj);else bUpdate=this.VersionHistory.update(newObj);if(bUpdate){this.asc_CloseFile();this.DocInfo.put_Id(this.VersionHistory.docId);this.DocInfo.put_Url(this.VersionHistory.url);this.documentUrlChanges=this.VersionHistory.urlChanges;this.asc_setDocInfo(this.DocInfo);this.asc_LoadDocument(this.VersionHistory)}else if(this.VersionHistory.currentChangeId< +newObj.currentChangeId){AscCommon.CollaborativeEditing.Clear_CollaborativeMarks();editor.VersionHistory.applyChanges(editor);AscCommon.CollaborativeEditing.Apply_Changes()}};baseEditorsApi.prototype.asc_undoAllChanges=function(){};baseEditorsApi.prototype.asc_getAdvancedOptions=function(){var cp={"codepage":AscCommon.c_oAscCodePageUtf8,"encodings":AscCommon.getEncodingParams()};return new AscCommon.asc_CAdvancedOptions(cp)};baseEditorsApi.prototype.asc_Print=function(options){if(window["AscDesktopEditor"]&& +this._printDesktop(options))return;if(!options)options=new Asc.asc_CDownloadOptions;options.fileType=Asc.c_oAscFileType.PDF;this.downloadAs(c_oAscAsyncAction.Print,options)};baseEditorsApi.prototype.asc_Save=function(isAutoSave,isIdle){var t=this;var res=false;if(this.canSave&&this._saveCheck()){this.IsUserSave=!isAutoSave;if(this.asc_isDocumentCanSave()||AscCommon.History.Have_Changes()||this._haveOtherChanges()||this.canUnlockDocument||this.forceSaveUndoRequest){if(this._prepareSave(isIdle)){this.canSave= +false;this.CoAuthoringApi.askSaveChanges(function(e){t._onSaveCallback(e)});res=true}}else if(this.isForceSaveOnUserSave&&this.IsUserSave)this.forceSave()}return res};baseEditorsApi.prototype.asc_isDocumentCanSave=function(){return this.isDocumentCanSave};baseEditorsApi.prototype.asc_getCanUndo=function(){return AscCommon.History.Can_Undo()};baseEditorsApi.prototype.asc_getCanRedo=function(){return AscCommon.History.Can_Redo()};baseEditorsApi.prototype.asc_isOffline=function(){return window.location.protocol.indexOf("file")== +0?true:false};baseEditorsApi.prototype.asc_getUrlType=function(url){return AscCommon.getUrlType(url)};baseEditorsApi.prototype.openDocument=function(file){};baseEditorsApi.prototype.openDocumentFromZip=function(){};baseEditorsApi.prototype.onEndLoadDocInfo=function(){if(this.isLoadFullApi&&this.DocInfo){if(this.DocInfo.get_OfflineApp())this._openChartOrLocalDocument();this.onEndLoadFile(null)}};baseEditorsApi.prototype.onEndLoadFile=function(result){if(result)this.openResult=result;if(this.isLoadFullApi&& +this.DocInfo&&this.openResult&&this.isLoadFonts){this.openDocument(this.openResult);this.openResult=null}};baseEditorsApi.prototype._onEndLoadSdk=function(){AscCommon.g_oTableId.init();var t=this;AscCommon.InitDragAndDrop(this.HtmlElement,function(error,files){t._uploadCallback(error,files)});AscFonts.g_fontApplication.Init();this.FontLoader=AscCommon.g_font_loader;this.ImageLoader=AscCommon.g_image_loader;this.FontLoader.put_Api(this);this.ImageLoader.put_Api(this);this.FontLoader.SetStandartFonts(); +this.chartPreviewManager=new AscCommon.ChartPreviewManager;this.textArtPreviewManager=new AscCommon.TextArtPreviewManager;AscFormat.initStyleManager();if(null!==this.tmpFocus)this.asc_enableKeyEvents(this.tmpFocus);this.pluginsManager=Asc.createPluginsManager(this);this.macros=new AscCommon.CDocumentMacros;this._loadSdkImages();if(AscFonts.FontPickerByCharacter&&this.documentTitle)AscFonts.FontPickerByCharacter.getFontsByString(this.documentTitle)};baseEditorsApi.prototype._loadSdkImages=function(){}; +baseEditorsApi.prototype.sendStandartTextures=function(){if(this.isSendStandartTextures)return;this.isSendStandartTextures=true;var _count=AscCommon.g_oUserTexturePresets.length;var arr=new Array(_count);var arrToDownload=[];for(var i=0;i<_count;++i){arr[i]=new AscCommon.asc_CTexture;arr[i].Id=i;arr[i].Image=AscCommon.g_oUserTexturePresets[i];arrToDownload.push(AscCommon.g_oUserTexturePresets[i])}if(this.editorId===c_oEditorId.Word)arrToDownload.push(AscCommon.g_sWordPlaceholderImage);this.ImageLoader.LoadImagesWithCallback(arrToDownload, +function(){},0);this.sendEvent("asc_onInitStandartTextures",arr)};baseEditorsApi.prototype.sendMathToMenu=function(){if(this.MathMenuLoad)return;var _MathPainter=new AscFormat.CMathPainter(this);_MathPainter.Generate();this.MathMenuLoad=true};baseEditorsApi.prototype.sendMathTypesToMenu=function(_math){this.sendEvent("asc_onMathTypes",_math)};baseEditorsApi.prototype.asyncFontEndLoaded_MathDraw=function(Obj){this.sync_EndAction(c_oAscAsyncActionType.Information,c_oAscAsyncAction.LoadFont);Obj.Generate2()}; +baseEditorsApi.prototype.getCurrentColorScheme=function(){var oTheme=this.getCurrentTheme();return oTheme&&oTheme.themeElements&&oTheme.themeElements.clrScheme};baseEditorsApi.prototype.asc_GetCurrentColorSchemeName=function(){var oClrScheme=this.getCurrentColorScheme();if(oClrScheme&&typeof oClrScheme.name==="string")return oClrScheme.name;return""};baseEditorsApi.prototype.asc_GetCurrentColorSchemeIndex=function(){var oTheme=this.getCurrentTheme();if(!oTheme)return-1;return this.getColorSchemes(oTheme).index}; +baseEditorsApi.prototype.getCurrentTheme=function(){return null};baseEditorsApi.prototype.getColorSchemes=function(theme){var result=AscCommon.g_oUserColorScheme.slice();var asc_color_scheme,_scheme,i;var aCustomSchemes=theme.getExtraAscColorSchemes();_scheme=theme.themeElements&&theme.themeElements.clrScheme;var nIndex=-1;if(_scheme){asc_color_scheme=AscCommon.getAscColorScheme(_scheme,theme);nIndex=AscCommon.getIndexColorSchemeInArray(result,asc_color_scheme);if(nIndex===-1)aCustomSchemes.push(asc_color_scheme); +aCustomSchemes.sort(function(a,b){if(a.name===""||a.name===null)return-1;if(b.name===""||b.name===null)return 1;if(a.name>b.name)return 1;if(a.name=0&&manager.SlideNum>0;var _zoom=_w/(_w_mm*AscCommon.g_dKoef_mm_to_pix);if(!transform)window["AscDesktopEditor"]["MediaStart"](sMediaName, +_x,transition.Rect.y,extX,extY,_zoom);else window["AscDesktopEditor"]["MediaStart"](sMediaName,_x,transition.Rect.y,extX,extY,_zoom,transform.sx,transform.shy,transform.shx,transform.sy,transform.tx,transform.ty)}}break}case c_oEditorId.Spreadsheet:{break}}};baseEditorsApi.prototype.hideVideoControl=function(){if(!window["AscDesktopEditor"]||!window["AscDesktopEditor"]["MediaEnd"])return;window["AscDesktopEditor"]["MediaEnd"]()};baseEditorsApi.prototype._checkLicenseApiFunctions=function(){return this.licenseResult&& +true===this.licenseResult["plugins"]};baseEditorsApi.prototype.asc_pluginsRegister=function(basePath,plugins){this.sendEvent("asc_LoadPluginsOrDocument");if(null!=this.pluginsManager){this.pluginsManager.register(basePath,plugins);if(this.pluginsManager.countEventDocContOrPluginsReady==2)this.pluginsManager.onPluginEvent("onDocumentContentReady")}};baseEditorsApi.prototype.asc_pluginRun=function(guid,variation,pluginData){if(null!=this.pluginsManager)this.pluginsManager.run(guid,variation,pluginData)}; +baseEditorsApi.prototype.asc_pluginStop=function(guid){if(null!=this.pluginsManager)this.pluginsManager.close(guid)};baseEditorsApi.prototype.asc_pluginResize=function(pluginData){if(null!=this.pluginsManager)this.pluginsManager.runResize(pluginData)};baseEditorsApi.prototype.asc_pluginButtonClick=function(id){if(null!=this.pluginsManager)this.pluginsManager.buttonClick(id)};baseEditorsApi.prototype.asc_pluginEnableMouseEvents=function(isEnable){if(!this.pluginsManager)return;this.pluginsManager.onEnableMouseEvents(isEnable)}; +baseEditorsApi.prototype.isEnabledDropTarget=function(){return true};baseEditorsApi.prototype.beginInlineDropTarget=function(e){};baseEditorsApi.prototype.endInlineDropTarget=function(e){};baseEditorsApi.prototype["asc_insertSymbol"]=function(familyName,code,pr){var arrCharCodes=[code];AscFonts.FontPickerByCharacter.checkTextLight(arrCharCodes,true);var fonts=[new AscFonts.CFont(AscFonts.g_fontApplication.GetFontInfoName(familyName),0,"",0,null)];AscFonts.FontPickerByCharacter.extendFonts(fonts); +this.asyncMethodCallback=function(){switch(this.editorId){case c_oEditorId.Word:case c_oEditorId.Presentation:{if(pr&&c_oEditorId.Word===this.editorId)this.WordControl.m_oLogicDocument.AddSpecialSymbol(pr);else{var textPr=new AscCommonWord.CTextPr;textPr.SetFontFamily(familyName);this.WordControl.m_oLogicDocument.AddTextWithPr(new AscCommon.CUnicodeStringEmulator(arrCharCodes),textPr,true)}break}case c_oEditorId.Spreadsheet:{this.AddTextWithPr(familyName,arrCharCodes);break}}};if(false===AscCommon.g_font_loader.CheckFontsNeedLoading(fonts)){this.asyncMethodCallback(); +this.asyncMethodCallback=undefined;return}AscCommon.g_font_loader.LoadDocumentFonts2(fonts)};baseEditorsApi.prototype["asc_registerPlaceholderCallback"]=function(type,callback){if(this.WordControl&&this.WordControl.m_oDrawingDocument&&this.WordControl.m_oDrawingDocument.placeholders)this.WordControl.m_oDrawingDocument.placeholders.registerCallback(type,callback)};baseEditorsApi.prototype["asc_uncheckPlaceholders"]=function(){if(this.WordControl&&this.WordControl.m_oDrawingDocument&&this.WordControl.m_oDrawingDocument.placeholders)this.WordControl.m_oDrawingDocument.placeholders.closeAllActive()}; baseEditorsApi.prototype.asc_nativeInitBuilder=function(){AscCommon.History.TurnOff();this.asc_setDocInfo(new Asc.asc_CDocInfo)};baseEditorsApi.prototype.asc_SetSilentMode=function(){};baseEditorsApi.prototype.asc_canPaste=function(){return false};baseEditorsApi.prototype.asc_Recalculate=function(){};baseEditorsApi.prototype["asc_nativeCheckPdfRenderer"]=function(_memory1,_memory2){if(true){_memory1.Copy=_memory1["Copy"];_memory1.ClearNoAttack=_memory1["ClearNoAttack"];_memory1.WriteByte=_memory1["WriteByte"]; _memory1.WriteBool=_memory1["WriteBool"];_memory1.WriteLong=_memory1["WriteLong"];_memory1.WriteDouble=_memory1["WriteDouble"];_memory1.WriteString=_memory1["WriteString"];_memory1.WriteString2=_memory1["WriteString2"];_memory2.Copy=_memory1["Copy"];_memory2.ClearNoAttack=_memory1["ClearNoAttack"];_memory2.WriteByte=_memory1["WriteByte"];_memory2.WriteBool=_memory1["WriteBool"];_memory2.WriteLong=_memory1["WriteLong"];_memory2.WriteDouble=_memory1["WriteDouble"];_memory2.WriteString=_memory1["WriteString"]; _memory2.WriteString2=_memory1["WriteString2"]}var _printer=new AscCommon.CDocumentRenderer;_printer.Memory=_memory1;_printer.VectorMemoryForPrint=_memory2;return _printer};baseEditorsApi.prototype.Begin_CompositeInput=function(){};baseEditorsApi.prototype.Add_CompositeText=function(nCharCode){};baseEditorsApi.prototype.Remove_CompositeText=function(nCount){};baseEditorsApi.prototype.Replace_CompositeText=function(arrCharCodes){};baseEditorsApi.prototype.Set_CursorPosInCompositeText=function(nPos){}; diff --git a/www/common/onlyoffice/v4/web-apps/apps/spreadsheeteditor/main/app.js b/www/common/onlyoffice/v4/web-apps/apps/spreadsheeteditor/main/app.js index 4cb1f3ba0..8f3cebf17 100644 --- a/www/common/onlyoffice/v4/web-apps/apps/spreadsheeteditor/main/app.js +++ b/www/common/onlyoffice/v4/web-apps/apps/spreadsheeteditor/main/app.js @@ -27,7 +27,7 @@ this.api.asc_setDrawImagePlaceParagraph("paragraphadv-font-img",s)}},onSuperscri ;t=e.asc_getIsTop10Sum(),this.setTitle(this.txtValueTitle+" ("+n[0]+")"),n.shift();var s=[];n&&n.forEach(function(t,e){t&&s.push({value:e,displayValue:t})}),this.cmbFields.setData(s),this.cmbFields.setValue(0!==i?i-1:0)}var o=this.properties.asc_getFilterObj();if(o.asc_getType()==Asc.c_oAscAutoFilterTypes.Top10){var a=o.asc_getFilter(),l=a.asc_getTop(),r=a.asc_getPercent();this.cmbType.setValue(l||null===l),this.cmbItem.setValue(t?0:r||null===r),this.spnCount.setDefaultUnit(!r&&null!==r||t?"":"%"),this.spnCount.setValue(a.asc_getVal())}}},save:function(){if(this.api&&this.properties){var t=this.properties.asc_getFilterObj();t.asc_setFilter(new Asc.Top10),t.asc_setType(Asc.c_oAscAutoFilterTypes.Top10);var e=t.asc_getFilter();if(e.asc_setTop(this.cmbType.getValue()),e.asc_setPercent(!0===this.cmbItem.getValue()),e.asc_setVal(this.spnCount.getNumberValue()),"value"==this.type){var i=this.properties.asc_getPivotObj();i.asc_setIsTop10Sum(0===this.cmbItem.getValue()),i.asc_setDataFieldIndexFilter("value"==this.type?this.cmbFields.getValue()+1:0)}this.api.asc_applyAutoFilter(this.properties)}},onPrimary:function(){return this.save(),this.close(),!1},txtTitle:"Top 10 AutoFilter",textType:"Show",txtTop:"Top",txtBottom:"Bottom",txtItems:"Item",txtPercent:"Percent",txtValueTitle:"Top 10 Filter",txtSum:"Sum",txtBy:"by"},SSE.Views.Top10FilterDialog||{})),SSE.Views.PivotDigitalFilterDialog=Common.UI.Window.extend(_.extend({initialize:function(t){var e=this,i={};_.extend(i,{width:501,height:210,contentWidth:180,header:!0,cls:"filter-dlg",contentTemplate:"",title:"label"==t.type?e.txtTitleLabel:e.txtTitleValue,items:[]},t),this.api=t.api,this.handler=t.handler,this.type=t.type||"value",this.template=t.template||['
    ','
    ','",'
    ','
    ','
    ','
    ','",'
    ',"
    ",'
    ','",'","
    ","
    ","
    ",'
    ','"].join(""),i.tpl=_.template(this.template)(i),Common.UI.Window.prototype.initialize.call(this,i)},render:function(){Common.UI.Window.prototype.render.call(this),this.conditions=[{value:Asc.c_oAscCustomAutoFilter.equals,displayValue:this.capCondition1},{value:Asc.c_oAscCustomAutoFilter.doesNotEqual,displayValue:this.capCondition2},{value:Asc.c_oAscCustomAutoFilter.isGreaterThan,displayValue:this.capCondition3},{value:Asc.c_oAscCustomAutoFilter.isGreaterThanOrEqualTo,displayValue:this.capCondition4},{value:Asc.c_oAscCustomAutoFilter.isLessThan,displayValue:this.capCondition5},{value:Asc.c_oAscCustomAutoFilter.isLessThanOrEqualTo,displayValue:this.capCondition6},{value:-2,displayValue:this.capCondition13},{value:-3,displayValue:this.capCondition14}],"label"==this.type&&(this.conditions=this.conditions.concat([{value:Asc.c_oAscCustomAutoFilter.beginsWith,displayValue:this.capCondition7},{value:Asc.c_oAscCustomAutoFilter.doesNotBeginWith,displayValue:this.capCondition8},{value:Asc.c_oAscCustomAutoFilter.endsWith,displayValue:this.capCondition9},{value:Asc.c_oAscCustomAutoFilter.doesNotEndWith,displayValue:this.capCondition10},{value:Asc.c_oAscCustomAutoFilter.contains,displayValue:this.capCondition11},{value:Asc.c_oAscCustomAutoFilter.doesNotContain,displayValue:this.capCondition12}])),this.cmbCondition1=new Common.UI.ComboBox({el:$("#id-cond-digital-combo",this.$window),menuStyle:"min-width: 100%;max-height: 135px;",style:"width:100%;",cls:"input-group-nr",data:this.conditions,scrollAlwaysVisible:!0,editable:!1,takeFocusOnClose:!0}),this.cmbCondition1.setValue(Asc.c_oAscCustomAutoFilter.equals),this.cmbCondition1.on("selected",_.bind(function(t,e){var i=-2==e.value||-3==e.value;this.inputValue2.setVisible(i),this.lblAnd.toggleClass("hidden",!i),this.inputValue.$el.width(i?100:225);var n=this;_.defer(function(){n.inputValue&&n.inputValue.focus()},10)},this)),this.cmbFields=new Common.UI.ComboBox({el:$("#id-field-digital-combo",this.$window),menuStyle:"min-width: 100%;max-height: 135px;",style:"width:100%;",cls:"input-group-nr",data:[],scrollAlwaysVisible:!0,editable:!1,takeFocusOnClose:!0}),this.cmbFields.setVisible("value"==this.type),this.cmbFields.on("selected",_.bind(function(t,e){var i=this;_.defer(function(){i.inputValue&&i.inputValue.focus()},10)},this)),this.inputValue=new Common.UI.InputField({el:$("#id-input-digital-value1"),allowBlank:!1,style:"width: 100%;",validateOnBlur:!1}),this.inputValue2=new Common.UI.InputField({el:$("#id-input-digital-value2"),allowBlank:!1,style:"width: 100%;",validateOnBlur:!1}),this.lblAnd=this.$window.find("#id-label-digital-and"),this.$window.find(".dlg-btn").on("click",_.bind(this.onBtnClick,this)),this.loadDefaults()},getFocusedComponents:function(){return[this.cmbFields,this.cmbCondition1,this.inputValue,this.inputValue2]},getDefaultFocusableComponent:function(){return this.inputValue},close:function(){this.api&&this.api.asc_enableKeyEvents(!0),Common.UI.Window.prototype.close.call(this)},onBtnClick:function(t){t.currentTarget.attributes&&t.currentTarget.attributes.result&&("ok"===t.currentTarget.attributes.result.value&&this.save(),this.close())},setSettings:function(t){this.properties=t},loadDefaults:function(){if(this.properties&&this.cmbCondition1&&this.cmbFields&&this.inputValue){var t=this.properties.asc_getPivotObj(),e=t.asc_getDataFieldIndexFilter(),i=t.asc_getDataFields();if(this.setTitle(this.options.title+" ("+i[0]+")"),"value"==this.type){i.shift();var n=[];i&&i.forEach(function(t,e){t&&n.push({value:e,displayValue:t})}),this.cmbFields.setData(n),this.cmbFields.setValue(0!==e?e-1:0)}var s=this.properties.asc_getFilterObj();if(s.asc_getType()==Asc.c_oAscAutoFilterTypes.CustomFilters){var o=s.asc_getFilter(),a=o.asc_getCustomFilters(),l=a[0].asc_getOperator();if(a.length>1){var r=o.asc_getAnd(),c=a[0].asc_getOperator()==Asc.c_oAscCustomAutoFilter.isGreaterThanOrEqualTo&&a[1].asc_getOperator()==Asc.c_oAscCustomAutoFilter.isLessThanOrEqualTo,h=a[0].asc_getOperator()==Asc.c_oAscCustomAutoFilter.isLessThan&&a[1].asc_getOperator()==Asc.c_oAscCustomAutoFilter.isGreaterThan;r&&c?l=-2:!r&&h&&(l=-3)}this.cmbCondition1.setValue(l||Asc.c_oAscCustomAutoFilter.equals),this.inputValue.setValue(null===a[0].asc_getVal()?"":a[0].asc_getVal()),this.inputValue.$el.width(-2==l||-3==l?100:225),this.lblAnd.toggleClass("hidden",!(-2==l||-3==l)),this.inputValue2.setVisible(-2==l||-3==l),this.inputValue2.setValue(a.length>1?null===a[1].asc_getVal()?"":a[1].asc_getVal():"")}}},save:function(){if(this.api&&this.properties&&this.cmbCondition1&&this.cmbFields&&this.inputValue){var t=this.properties.asc_getFilterObj();t.asc_setFilter(new Asc.CustomFilters),t.asc_setType(Asc.c_oAscAutoFilterTypes.CustomFilters);var e=t.asc_getFilter(),i=this.cmbCondition1.getValue();if(-2==i){e.asc_setCustomFilters([new Asc.CustomFilter,new Asc.CustomFilter]),e.asc_setAnd(!0);var n=e.asc_getCustomFilters();n[0].asc_setOperator(Asc.c_oAscCustomAutoFilter.isGreaterThanOrEqualTo),n[0].asc_setVal(this.inputValue.getValue()),n[1].asc_setOperator(Asc.c_oAscCustomAutoFilter.isLessThanOrEqualTo),n[1].asc_setVal(this.inputValue2.getValue())}else if(-3==i){e.asc_setCustomFilters([new Asc.CustomFilter,new Asc.CustomFilter]),e.asc_setAnd(!1);var n=e.asc_getCustomFilters();n[0].asc_setOperator(Asc.c_oAscCustomAutoFilter.isLessThan),n[0].asc_setVal(this.inputValue.getValue()),n[1].asc_setOperator(Asc.c_oAscCustomAutoFilter.isGreaterThan),n[1].asc_setVal(this.inputValue2.getValue())}else{e.asc_setCustomFilters([new Asc.CustomFilter]),e.asc_setAnd(!0);var n=e.asc_getCustomFilters();n[0].asc_setOperator(this.cmbCondition1.getValue()),n[0].asc_setVal(this.inputValue.getValue())}this.properties.asc_getPivotObj().asc_setDataFieldIndexFilter("value"==this.type?this.cmbFields.getValue()+1:0),this.api.asc_applyAutoFilter(this.properties)}},onPrimary:function(){return this.save(),this.close(),!1},capCondition1:"equals",capCondition10:"does not end with",capCondition11:"contains",capCondition12:"does not contain",capCondition2:"does not equal",capCondition3:"is greater than",capCondition4:"is greater than or equal to",capCondition5:"is less than",capCondition6:"is less than or equal to",capCondition7:"begins with",capCondition8:"does not begin with",capCondition9:"ends with",textShowLabel:"Show items for which the label:",textShowValue:"Show items for which:",textUse1:"Use ? to present any single character",textUse2:"Use * to present any series of character",txtTitleValue:"Value Filter",txtTitleLabel:"Label Filter",capCondition13:"between",capCondition14:"not between",txtAnd:"and"},SSE.Views.PivotDigitalFilterDialog||{})),SSE.Views.SortFilterDialog=Common.UI.Window.extend(_.extend({initialize:function(t){var e=this,i={};this.type=t.type,_.extend(i,{width:250,height:215,contentWidth:180,header:!0,cls:"filter-dlg",contentTemplate:"",title:e.txtTitle,items:[],buttons:["ok","cancel"]},t),this.template=t.template||['
    ','
    ','
    ','
    ','
    ','
    ',"
    ","
    ",'
    '].join(""),this.api=t.api,this.handler=t.handler,i.tpl=_.template(this.template)(i),Common.UI.Window.prototype.initialize.call(this,i)},render:function(){Common.UI.Window.prototype.render.call(this),this.radioAsc=new Common.UI.RadioBox({el:$("#id-sort-filter-radio-asc"),labelText:this.textAsc,name:"asc-radio-sort",checked:!0}),this.radioAsc.on("change",_.bind(function(t,e){e&&this.cmbFieldsAsc.setDisabled(!1),e&&this.cmbFieldsDesc.setDisabled(!0)},this)),this.radioDesc=new Common.UI.RadioBox({el:$("#id-sort-filter-radio-desc"),labelText:this.textDesc,name:"asc-radio-sort"}),this.radioDesc.on("change",_.bind(function(t,e){e&&this.cmbFieldsAsc.setDisabled(!0),e&&this.cmbFieldsDesc.setDisabled(!1)},this)),this.cmbFieldsAsc=new Common.UI.ComboBox({el:$("#id-sort-filter-fields-asc",this.$window),menuStyle:"min-width: 100%;max-height: 135px;",style:"width:100%;",cls:"input-group-nr",data:[],scrollAlwaysVisible:!0,editable:!1}),this.cmbFieldsDesc=new Common.UI.ComboBox({el:$("#id-sort-filter-fields-desc",this.$window),menuStyle:"min-width: 100%;max-height: 135px;",style:"width:100%;",cls:"input-group-nr",data:[],scrollAlwaysVisible:!0,editable:!1,disabled:!0}),this.$window.find(".dlg-btn").on("click",_.bind(this.onBtnClick,this)),this.loadDefaults()},show:function(){Common.UI.Window.prototype.show.call(this)},close:function(){this.api&&this.api.asc_enableKeyEvents(!0),Common.UI.Window.prototype.close.call(this)},onBtnClick:function(t){t.currentTarget.attributes&&t.currentTarget.attributes.result&&("ok"===t.currentTarget.attributes.result.value&&this.save(),this.close())},setSettings:function(t){this.properties=t},loadDefaults:function(){if(this.properties){var t=this.properties.asc_getPivotObj(),e=t.asc_getDataFieldIndexSorting(),i=t.asc_getDataFields(),n=this.properties.asc_getSortState();this.setTitle(this.txtTitle+" ("+i[0]+")");var s=[];i&&i.forEach(function(t,e){t&&s.push({value:e,displayValue:t})}),this.cmbFieldsAsc.setData(s),this.cmbFieldsAsc.setValue(e>=0?e:0),this.cmbFieldsDesc.setData(s),this.cmbFieldsDesc.setValue(e>=0?e:0),this.radioDesc.setValue(n==Asc.c_oAscSortOptions.Descending,!0),this.cmbFieldsDesc.setDisabled(n!==Asc.c_oAscSortOptions.Descending)}},save:function(){if(this.api&&this.properties){var t=this.radioAsc.getValue()?this.cmbFieldsAsc:this.cmbFieldsDesc;this.properties.asc_getPivotObj().asc_setDataFieldIndexSorting(t.getValue()),this.properties.asc_setSortState(this.radioAsc.getValue()?Asc.c_oAscSortOptions.Ascending:Asc.c_oAscSortOptions.Descending),this.api.asc_applyAutoFilter(this.properties)}},onPrimary:function(){return this.save(),this.close(),!1},txtTitle:"Sort",textAsc:"Ascenging (A to Z) by",textDesc:"Descending (Z to A) by"},SSE.Views.SortFilterDialog||{})),SSE.Views.AutoFilterDialog=Common.UI.Window.extend(_.extend({initialize:function(t){var e=this,i={},n=450,s=void 0;Common.Utils.InternalSettings.get("sse-settings-size-filter-window")&&(n=Common.Utils.InternalSettings.get("sse-settings-size-filter-window")[0],s=Common.Utils.InternalSettings.get("sse-settings-size-filter-window")[1]),_.extend(i,{width:n||450,height:s||265,contentWidth:n-50||400,header:!1,cls:"filter-dlg",contentTemplate:"",title:e.txtTitle,modal:!1,animate:!1,items:[],resizable:!0,minwidth:450,minheight:265},t),this.template=t.template||['
    ','
    ','
    ','','
    ','
    ',"
    ","
    ",'","
    ",'","
    "].join(""),this.api=t.api,this.handler=t.handler,this.throughIndexes=[],this.filteredIndexes=[],this.curSize=null,i.tpl=_.template(this.template)(i),Common.UI.Window.prototype.initialize.call(this,i),this.on("resizing",_.bind(this.onWindowResizing,this)),this.on("resize",_.bind(this.onWindowResize,this))},render:function(){var t=this;Common.UI.Window.prototype.render.call(this);var e=this.$window.find(".resize-border");this.$window.find(".resize-border.left, .resize-border.top").css({cursor:"default"}),e.css({background:"none",border:"none"}),e.removeClass("left"),e.removeClass("top"),this.$window.find(".btn").on("click",_.bind(this.onBtnClick,this)),this.btnOk=new Common.UI.Button({cls:"btn normal dlg-btn primary",caption:this.okButtonText,enableToggle:!1,allowDepress:!1}),this.btnOk&&(this.btnOk.render($("#id-apply-filter",this.$window)),this.btnOk.on("click",_.bind(this.onApplyFilter,this))),this.miSortLow2High=new Common.UI.MenuItem({caption:this.txtSortLow2High,toggleGroup:"menufiltersort",checkable:!0,checked:!1}),this.miSortLow2High.on("click",_.bind(this.onSortType,this,Asc.c_oAscSortOptions.Ascending)),this.miSortHigh2Low=new Common.UI.MenuItem({caption:this.txtSortHigh2Low,toggleGroup:"menufiltersort",checkable:!0,checked:!1}),this.miSortHigh2Low.on("click",_.bind(this.onSortType,this,Asc.c_oAscSortOptions.Descending)),this.miSortOptions=new Common.UI.MenuItem({caption:this.txtSortOption}),this.miSortOptions.on("click",_.bind(this.onSortOptions,this)),this.miSortCellColor=new Common.UI.MenuItem({caption:this.txtSortCellColor,toggleGroup:"menufiltersort",checkable:!0,checked:!1,menu:new Common.UI.Menu({style:"min-width: inherit; padding: 0px;",menuAlign:"tl-tr",items:[{template:_.template('
    ')}]})}),this.miSortFontColor=new Common.UI.MenuItem({caption:this.txtSortFontColor,toggleGroup:"menufiltersort",checkable:!0,checked:!1,menu:new Common.UI.Menu({style:"min-width: inherit; padding: 0px;",menuAlign:"tl-tr",items:[{template:_.template('
    ')}]})}),this.miNumFilter=new Common.UI.MenuItem({caption:this.txtNumFilter,toggleGroup:"menufilterfilter",checkable:!0,checked:!1,menu:new Common.UI.Menu({menuAlign:"tl-tr",items:[{value:Asc.c_oAscCustomAutoFilter.equals,caption:this.txtEquals,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters},{value:Asc.c_oAscCustomAutoFilter.doesNotEqual,caption:this.txtNotEquals,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters},{value:Asc.c_oAscCustomAutoFilter.isGreaterThan,caption:this.txtGreater,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters},{value:Asc.c_oAscCustomAutoFilter.isGreaterThanOrEqualTo,caption:this.txtGreaterEquals,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters},{value:Asc.c_oAscCustomAutoFilter.isLessThan,caption:this.txtLess,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters},{value:Asc.c_oAscCustomAutoFilter.isLessThanOrEqualTo,caption:this.txtLessEquals,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters},{value:-2,caption:this.txtBetween,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters},{value:Asc.c_oAscCustomAutoFilter.top10,caption:this.txtTop10,checkable:!0,type:Asc.c_oAscAutoFilterTypes.Top10},{value:Asc.c_oAscDynamicAutoFilter.aboveAverage,caption:this.txtAboveAve,checkable:!0,type:Asc.c_oAscAutoFilterTypes.DynamicFilter},{value:Asc.c_oAscDynamicAutoFilter.belowAverage,caption:this.txtBelowAve,checkable:!0,type:Asc.c_oAscAutoFilterTypes.DynamicFilter},{value:-1,caption:this.btnCustomFilter+"...",checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters}]})});for(var i=this.miNumFilter.menu.items,n=0;n
    ')}]})}),this.miFilterFontColor=new Common.UI.MenuItem({caption:this.txtFilterFontColor,toggleGroup:"menufilterfilter",checkable:!0,checked:!1,menu:new Common.UI.Menu({style:"min-width: inherit; padding: 0px;",menuAlign:"tl-tr",items:[{template:_.template('
    ')}]})}),this.miClear=new Common.UI.MenuItem({caption:this.txtClear,checkable:!1}),this.miClear.on("click",_.bind(this.onClear,this)),this.miReapply=new Common.UI.MenuItem({caption:this.txtReapply,checkable:!1}),this.miReapply.on("click",_.bind(this.onReapply,this)),this.miReapplySeparator=new Common.UI.MenuItem({caption:"--"}),this.miValueFilter=new Common.UI.MenuItem({caption:this.txtValueFilter,toggleGroup:"menufilterfilter",checkable:!0,checked:!1,menu:new Common.UI.Menu({menuAlign:"tl-tr",items:[{value:Asc.c_oAscCustomAutoFilter.equals,caption:this.txtEquals,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters,pivottype:"value"},{value:Asc.c_oAscCustomAutoFilter.doesNotEqual,caption:this.txtNotEquals,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters,pivottype:"value"},{value:Asc.c_oAscCustomAutoFilter.isGreaterThan,caption:this.txtGreater,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters,pivottype:"value"},{value:Asc.c_oAscCustomAutoFilter.isGreaterThanOrEqualTo,caption:this.txtGreaterEquals,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters,pivottype:"value"},{value:Asc.c_oAscCustomAutoFilter.isLessThan,caption:this.txtLess,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters,pivottype:"value"},{value:Asc.c_oAscCustomAutoFilter.isLessThanOrEqualTo,caption:this.txtLessEquals,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters,pivottype:"value"},{value:-2,caption:this.txtBetween,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters,pivottype:"value"},{value:-3,caption:this.txtNotBetween,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters,pivottype:"value"},{value:Asc.c_oAscCustomAutoFilter.top10,caption:this.txtTop10,checkable:!0,type:Asc.c_oAscAutoFilterTypes.Top10,pivottype:"value"}]})}),this.miValueFilter.menu.on("item:click",_.bind(this.onValueFilterMenuClick,this)),this.miLabelFilter=new Common.UI.MenuItem({caption:this.txtLabelFilter,toggleGroup:"menufilterfilter",checkable:!0,checked:!1,menu:new Common.UI.Menu({menuAlign:"tl-tr",items:[{value:Asc.c_oAscCustomAutoFilter.equals,caption:this.txtEquals,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters,pivottype:"label"},{value:Asc.c_oAscCustomAutoFilter.doesNotEqual,caption:this.txtNotEquals,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters,pivottype:"label"},{value:Asc.c_oAscCustomAutoFilter.beginsWith,caption:this.txtBegins,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters,pivottype:"label"},{value:Asc.c_oAscCustomAutoFilter.doesNotBeginWith,caption:this.txtNotBegins,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters,pivottype:"label"},{value:Asc.c_oAscCustomAutoFilter.endsWith,caption:this.txtEnds,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters,pivottype:"label"},{value:Asc.c_oAscCustomAutoFilter.doesNotEndWith,caption:this.txtNotEnds,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters,pivottype:"label"},{value:Asc.c_oAscCustomAutoFilter.contains,caption:this.txtContains,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters,pivottype:"label"},{value:Asc.c_oAscCustomAutoFilter.doesNotContain,caption:this.txtNotContains,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters,pivottype:"label"},{caption:"--"},{value:Asc.c_oAscCustomAutoFilter.isGreaterThan,caption:this.txtGreater,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters,pivottype:"label"},{value:Asc.c_oAscCustomAutoFilter.isGreaterThanOrEqualTo,caption:this.txtGreaterEquals,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters,pivottype:"label"},{value:Asc.c_oAscCustomAutoFilter.isLessThan,caption:this.txtLess,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters,pivottype:"label"},{value:Asc.c_oAscCustomAutoFilter.isLessThanOrEqualTo,caption:this.txtLessEquals,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters,pivottype:"label"},{value:-2,caption:this.txtBetween,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters,pivottype:"label"},{value:-3,caption:this.txtNotBetween,checkable:!0,type:Asc.c_oAscAutoFilterTypes.CustomFilters,pivottype:"label"}]})}),this.miLabelFilter.menu.on("item:click",_.bind(this.onLabelFilterMenuClick,this)),this.filtersMenu=new Common.UI.Menu({items:[this.miSortLow2High,this.miSortHigh2Low,this.miSortOptions,this.miSortCellColor,this.miSortFontColor,{caption:"--"},this.miLabelFilter,this.miValueFilter,this.miNumFilter,this.miTextFilter,this.miFilterCellColor,this.miFilterFontColor,this.miClear,this.miReapplySeparator,this.miReapply]});var s=this.$window.find("#menu-container-filters");this.filtersMenu.render(s),this.filtersMenu.cmpEl.attr({tabindex:"-1"}),this.mnuSortColorCellsPicker=new Common.UI.ColorPaletteExt({el:$("#filter-dlg-sort-cells-color"),colors:[]}),this.mnuSortColorCellsPicker.on("select",_.bind(this.onSortColorSelect,this,Asc.c_oAscSortOptions.ByColorFill)),this.mnuSortColorFontPicker=new Common.UI.ColorPaletteExt({el:$("#filter-dlg-sort-font-color"),colors:[]}),this.mnuSortColorFontPicker.on("select",_.bind(this.onSortColorSelect,this,Asc.c_oAscSortOptions.ByColorFont)),this.mnuFilterColorCellsPicker=new Common.UI.ColorPaletteExt({el:$("#filter-dlg-filter-cells-color"),colors:[]}),this.mnuFilterColorCellsPicker.on("select",_.bind(this.onFilterColorSelect,this,!0)),this.mnuFilterColorFontPicker=new Common.UI.ColorPaletteExt({el:$("#filter-dlg-filter-font-color"),colors:[]}),this.mnuFilterColorFontPicker.on("select",_.bind(this.onFilterColorSelect,this,!1)),this.input=new Common.UI.InputField({el:$("#id-sd-cell-search",this.$window),allowBlank:!0,placeHolder:this.txtEmpty,validateOnChange:!0,validation:function(){return!0}}).on("changing",function(e,i){i.length?(i=i.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1"),t.filter=new RegExp(i,"ig")):t.filter=void 0,t.setupDataCells()}),this.cells=new Common.UI.DataViewStore,this.filterExcludeCells=new Common.UI.DataViewStore,this.cells&&(this.cellsList=new Common.UI.ListView({el:$("#id-dlg-filter-values",this.$window),store:this.cells,simpleAddMode:!0,template:_.template(['
    '].join("")),itemTemplate:_.template(["
    ",'",'
    ','
    <%= Common.Utils.String.htmlEncode(value) %>
    ','<% if (typeof count !=="undefined" && count) { %>','
    <%= count%>
    ',"<% } %>","
    ","
    "].join(""))}),this.cellsList.store.comparator=function(t,e){if("0"==t.get("groupid"))return-1;if("0"==e.get("groupid"))return 1;if("2"==t.get("groupid"))return-1;if("2"==e.get("groupid"))return 1;var i=t.get("intval"),n=e.get("intval"),s=void 0!==i;return s!==(void 0!==n)?s?-1:1:(!s&&(i=t.get("cellvalue").toLowerCase())&&(n=e.get("cellvalue").toLowerCase()),i==n?0:""==n||""!==i&&i1?r[1].asc_getOperator()||0:0,i=null===r[0].asc_getVal()?"":r[0].asc_getVal(),n=r.length>1?null===r[1].asc_getVal()?"":r[1].asc_getVal():""}if(-1!==t.value){var c=new Asc.CustomFilters;c.asc_setCustomFilters(-2==t.value||-3==t.value?[new Asc.CustomFilter,new Asc.CustomFilter]:[new Asc.CustomFilter]);var h=c.asc_getCustomFilters();if(h[0].asc_setOperator(-2==t.value?Asc.c_oAscCustomAutoFilter.isGreaterThanOrEqualTo:-3==t.value?Asc.c_oAscCustomAutoFilter.isLessThan:t.value),-2==t.value){var d=s==Asc.c_oAscCustomAutoFilter.isGreaterThanOrEqualTo&&o==Asc.c_oAscCustomAutoFilter.isLessThanOrEqualTo;c.asc_setAnd(!d||a),h[0].asc_setVal(d?i:""),h[1].asc_setOperator(Asc.c_oAscCustomAutoFilter.isLessThanOrEqualTo),h[1].asc_setVal(d?n:"")}else if(-3==t.value){var p=s==Asc.c_oAscCustomAutoFilter.isLessThan&&o==Asc.c_oAscCustomAutoFilter.isGreaterThan;c.asc_setAnd(!!p&&a),h[0].asc_setVal(p?i:""),h[1].asc_setOperator(Asc.c_oAscCustomAutoFilter.isGreaterThan),h[1].asc_setVal(p?n:"")}else c.asc_setAnd(!0),h[0].asc_setVal(t.value==s?i:"");e.asc_setFilter(c),e.asc_setType(Asc.c_oAscAutoFilterTypes.CustomFilters)}var m,u=this;m="label"==t.options.pivottype||"value"==t.options.pivottype?new SSE.Views.PivotDigitalFilterDialog({api:this.api,type:t.options.pivottype}).on({close:function(){u.close()}}):new SSE.Views.DigitalFilterDialog({api:this.api,type:"number"}).on({close:function(){u.close()}}),this.close(),m.setSettings(this.configTo),m.show()},onTextFilterMenuClick:function(t,e){var i=this.configTo.asc_getFilterObj(),n="",s=Asc.c_oAscCustomAutoFilter.equals;if(i.asc_getType()==Asc.c_oAscAutoFilterTypes.CustomFilters){var o=i.asc_getFilter(),a=o.asc_getCustomFilters();o.asc_getAnd(),s=a[0].asc_getOperator(),a.length>1?a[1].asc_getOperator()||0:0,n=null===a[0].asc_getVal()?"":a[0].asc_getVal(),a.length>1?null===a[1].asc_getVal()?"":a[1].asc_getVal():""}if(-1!==e.value){var l=new Asc.CustomFilters;l.asc_setCustomFilters([new Asc.CustomFilter]);var r=l.asc_getCustomFilters();l.asc_setAnd(!0),r[0].asc_setOperator(e.value),r[0].asc_setVal(e.value==s?n:""),i.asc_setFilter(l),i.asc_setType(Asc.c_oAscAutoFilterTypes.CustomFilters)}var c,h=this;c="label"==e.options.pivottype||"value"==e.options.pivottype?new SSE.Views.PivotDigitalFilterDialog({api:this.api,type:e.options.pivottype}).on({ close:function(){h.close()}}):new SSE.Views.DigitalFilterDialog({api:this.api,type:"text"}).on({close:function(){h.close()}}),this.close(),c.setSettings(this.configTo),c.show()},onNumDynamicFilterItemClick:function(t){var e=this.configTo.asc_getFilterObj();e.asc_getType()!==Asc.c_oAscAutoFilterTypes.DynamicFilter&&(e.asc_setFilter(new Asc.DynamicFilter),e.asc_setType(Asc.c_oAscAutoFilterTypes.DynamicFilter)),e.asc_getFilter().asc_setType(t.value),this.api.asc_applyAutoFilter(this.configTo),this.close()},onTop10FilterItemClick:function(t){var e=this,i=new SSE.Views.Top10FilterDialog({api:this.api,type:t.options.pivottype}).on({close:function(){e.close()}});this.close(),i.setSettings(this.configTo),i.show()},onLabelFilterMenuClick:function(t,e){e.value==Asc.c_oAscCustomAutoFilter.isGreaterThan||e.value==Asc.c_oAscCustomAutoFilter.isGreaterThanOrEqualTo||e.value==Asc.c_oAscCustomAutoFilter.isLessThan||e.value==Asc.c_oAscCustomAutoFilter.isLessThanOrEqualTo||-2==e.value||-3==e.value?this.onNumCustomFilterItemClick(e):this.onTextFilterMenuClick(t,e)},onValueFilterMenuClick:function(t,e){var i=this;this.configTo.asc_getPivotObj().asc_getDataFields().length<2?Common.UI.warning({title:this.textWarning,msg:this.warnFilterError,callback:function(){_.delay(function(){i.close()},10)}}):e.options.type==Asc.c_oAscAutoFilterTypes.CustomFilters?this.onNumCustomFilterItemClick(e):this.onTop10FilterItemClick(e)},onFilterColorSelect:function(t,e,i){var n=this.configTo.asc_getFilterObj();n.asc_getType()!==Asc.c_oAscAutoFilterTypes.ColorFilter&&(n.asc_setFilter(new Asc.ColorFilter),n.asc_setType(Asc.c_oAscAutoFilterTypes.ColorFilter));var s=n.asc_getFilter();s.asc_setCellColor(!!t&&null),s.asc_setCColor(t&&"transparent"==i||!t&&"#000000"==i?null:Common.Utils.ThemeColor.getRgbColor(i)),this.api.asc_applyAutoFilter(this.configTo),this.close()},onSortColorSelect:function(t,e,i){if(this.api&&this.configTo){var n=t==Asc.c_oAscSortOptions.ByColorFill;this.api.asc_sortColFilter(t,this.configTo.asc_getCellId(),this.configTo.asc_getDisplayName(),n&&"transparent"==i||!n&&"#000000"==i?null:Common.Utils.ThemeColor.getRgbColor(i))}this.close()},onCellCheck:function(t,e,i){if(!this.checkCellTrigerBlock){var n="",s=!1,o=null,a=window.event?window.event:window._event;if(a){if(n=$(a.currentTarget).find(".list-item"),n.length){o=n.get(0).getBoundingClientRect();var l=a.clientX*Common.Utils.zoom(),r=a.clientY*Common.Utils.zoom();o.left1&&(s[parseInt(t.get("throughIndex"))]=i))});else{e.set("check",i),s[parseInt(e.get("throughIndex"))]=i;for(var o=i,a=0;a0;if(this.miSortFontColor.setVisible(m),this.miFilterFontColor.setVisible(!i&&m),m){var u=[];h.forEach(function(t,e){t?u.push(Common.Utils.ThemeColor.getHexColor(t.get_r(),t.get_g(),t.get_b()).toLocaleUpperCase()):u.push("000000")}),this.mnuSortColorFontPicker.updateColors(u),this.mnuFilterColorFontPicker.updateColors(u),this.miFilterFontColor.setChecked(!1,!0),this.miSortFontColor.setChecked(d==Asc.c_oAscSortOptions.ByColorFont,!0),d==Asc.c_oAscSortOptions.ByColorFont&&this.mnuSortColorFontPicker.select(p||"000000",!0)}if(m=c&&c.length>0,this.miSortCellColor.setVisible(m),this.miFilterCellColor.setVisible(!i&&m),m){var u=[];c.forEach(function(t,e){t?u.push(Common.Utils.ThemeColor.getHexColor(t.get_r(),t.get_g(),t.get_b()).toLocaleUpperCase()):u.push("transparent")}),this.mnuSortColorCellsPicker.updateColors(u),this.mnuFilterColorCellsPicker.updateColors(u),this.miFilterCellColor.setChecked(!1,!0),this.miSortCellColor.setChecked(d==Asc.c_oAscSortOptions.ByColorFill,!0),d==Asc.c_oAscSortOptions.ByColorFill&&this.mnuSortColorCellsPicker.select(p||"transparent",!0)}if(o){var g=s.asc_getFilter(),b=g.asc_getCustomFilters(),f=(g.asc_getAnd(),b[0].asc_getOperator()),C=b.length>1?b[1].asc_getOperator()||0:0,v=i?n?this.miValueFilter.menu.items:this.miLabelFilter.menu.items:r?this.miTextFilter.menu.items:this.miNumFilter.menu.items,_=!0;1==b.length?v.forEach(function(t){var e=t.options.type==Asc.c_oAscAutoFilterTypes.CustomFilters&&t.value==f;t.setChecked(e,!0),e&&(_=!1)}):!i&&r||f!=Asc.c_oAscCustomAutoFilter.isGreaterThanOrEqualTo||C!=Asc.c_oAscCustomAutoFilter.isLessThanOrEqualTo?i&&f==Asc.c_oAscCustomAutoFilter.isLessThan&&C==Asc.c_oAscCustomAutoFilter.isGreaterThan&&(v[n?7:14].setChecked(!0,!0),_=!1):(v[i&&!n?13:6].setChecked(!0,!0),_=!1),_&&v[v.length-1].setChecked(!0,!0)}else if(this.initialFilterType===Asc.c_oAscAutoFilterTypes.ColorFilter){var y=s.asc_getFilter(),x=y.asc_getCColor();x&&(x=Common.Utils.ThemeColor.getHexColor(x.get_r(),x.get_g(),x.get_b()).toLocaleUpperCase()),null===y.asc_getCellColor()?(this.miFilterCellColor.setChecked(!0,!0),this.mnuFilterColorCellsPicker.select(x||"transparent",!0)):!1===y.asc_getCellColor()&&(this.miFilterFontColor.setChecked(!0,!0),this.mnuFilterColorFontPicker.select(x||"000000",!0))}else if(a||l){var w=a?s.asc_getFilter().asc_getType():null,v=i?this.miValueFilter.menu.items:this.miNumFilter.menu.items;v.forEach(function(t){t.setChecked(a&&t.options.type==Asc.c_oAscAutoFilterTypes.DynamicFilter&&t.value==w||l&&t.options.type==Asc.c_oAscAutoFilterTypes.Top10,!0)})}this.miClear.setDisabled(this.initialFilterType===Asc.c_oAscAutoFilterTypes.None),this.miReapply.setDisabled(this.initialFilterType===Asc.c_oAscAutoFilterTypes.None),this.btnOk.setDisabled(this.initialFilterType!==Asc.c_oAscAutoFilterTypes.Filters&&this.initialFilterType!==Asc.c_oAscAutoFilterTypes.None),this.menuPanelWidth=t.innerWidth();var S=this.getWidth();S-this.menuPanelWidth<260&&(S=Math.ceil(this.menuPanelWidth+260),this.setResizable(!0,[S,this.initConfig.minheight])),Common.Utils.InternalSettings.get("sse-settings-size-filter-window")&&(S=Common.Utils.InternalSettings.get("sse-settings-size-filter-window")[0]+this.menuPanelWidth),i&&e.asc_getIsPageFilter()&&(this.setResizable(!0,[this.initConfig.minwidth-this.menuPanelWidth,this.initConfig.minheight]),t.addClass("hidden"),S-=this.menuPanelWidth,this.menuPanelWidth=0),this.setSize(S,this.getHeight())},setupDataCells:function(){function t(t){return!isNaN(parseFloat(t))&&isFinite(t)}var e,i,n,s=this,o=0,a=2,l=!0,r=!1,c=0,h=[],d=[],p=s.filter?s.filteredIndexes:s.throughIndexes;this.configTo.asc_getValues().forEach(function(r){i=r.asc_getText(),e=t(i),l=!0,n=r.asc_getRepeats?r.asc_getRepeats():void 0,s.filter?(null===i.match(s.filter)&&(l=!1),p[a]=l):void 0==p[a]&&(p[a]=r.asc_getVisible()),l?(h.push(new Common.UI.DataViewModel({id:++o,selected:!1,allowSelected:!0,cellvalue:i,value:e?i:i.length>0?i:s.textEmptyItem,intval:e?parseFloat(i):void 0,strval:e?"":i,groupid:"1",check:p[a],throughIndex:a,count:n?n.toString():""})),p[a]&&c++):d.push(new Common.UI.DataViewModel({cellvalue:i})),++a}),c==h.length?r=!0:c>0&&(r="indeterminate"),(s.filter||void 0==p[0])&&(p[0]=!0),(!s.filter||h.length>0)&&h.unshift(new Common.UI.DataViewModel({id:++o,selected:!1,allowSelected:!0,value:s.filter?this.textSelectAllResults:this.textSelectAll,groupid:"0",check:p[0],throughIndex:0})),s.filter&&h.length>1&&(void 0==p[1]&&(p[1]=!1),h.splice(1,0,new Common.UI.DataViewModel({id:++o,selected:!1,allowSelected:!0,value:this.textAddSelection,groupid:"2",check:p[1],throughIndex:1}))),this.cells.reset(h),this.filterExcludeCells.reset(d),this.cells.length&&(this.checkCellTrigerBlock=!0,this.cells.at(0).set("check",r),this.checkCellTrigerBlock=void 0),this.btnOk.setDisabled(this.cells.length<1),this.cellsList.scroller.update({minScrollbarLength:40,alwaysVisibleY:!0,suppressScrollX:!0}),this.cellsList.cmpEl.toggleClass("scroll-padding",this.cellsList.scroller.isVisible())},testFilter:function(){var t=this,e=!1;return this.cells&&(this.filter&&this.filteredIndexes[1]?e=!0:this.cells.forEach(function(t){if("1"==t.get("groupid")&&t.get("check"))return e=!0,!0})),e||(t._skipCheckDocumentClick=!0,Common.UI.warning({title:this.textWarning,msg:this.warnNoSelected,callback:function(){t._skipCheckDocumentClick=!1,_.delay(function(){t.input.focus()},100,this)}})),e},save:function(){if(this.api&&this.configTo&&this.cells&&this.filterExcludeCells){var t=this.configTo.asc_getValues(),e=!1;if(this.filter&&this.filteredIndexes[1])this.initialFilterType===Asc.c_oAscAutoFilterTypes.CustomFilters&&t.forEach(function(t,e){t.asc_setVisible(!0)}),this.cells.each(function(e){"1"==e.get("groupid")&&t[parseInt(e.get("throughIndex"))-2].asc_setVisible(e.get("check"))}),t.forEach(function(t,i){if(t.asc_getVisible())return e=!0,!0});else{var i=this.filter?this.filteredIndexes:this.throughIndexes;t.forEach(function(t,e){t.asc_setVisible(i[e+2])}),e=!0}if(e){var n=this.configTo.asc_getPivotObj();n&&n.asc_getIsPageFilter()&&n.asc_setIsMultipleItemSelectionAllowed(!0),this.configTo.asc_getFilterObj().asc_setType(Asc.c_oAscAutoFilterTypes.Filters),this.api.asc_applyAutoFilter(this.configTo)}}},onPrimary:function(){return this.save(),this.close(),!1},onWindowResize:function(t){if(t&&"start"==t[1])this.curSize={resize:!1,height:this.getSize()[1]};else if(this.curSize.resize){var e=this.getSize();this.$window.find(".combo-values").css({height:e[1]-100+"px"}),this.cellsList.scroller.update({minScrollbarLength:40,alwaysVisibleY:!0,suppressScrollX:!0})}},onWindowResizing:function(){if(this.curSize){var t=this.getSize();t[1]!==this.curSize.height&&(this.curSize.resize||(this.curSize.resize=!0,this.cellsList.scroller.update({minScrollbarLength:40,alwaysVisibleY:!1,suppressScrollX:!0})),this.$window.find(".combo-values").css({height:t[1]-100+"px"}),this.curSize.height=t[1]),t[0]-=this.menuPanelWidth,Common.Utils.InternalSettings.set("sse-settings-size-filter-window",t)}},onItemChanged:function(t,e){var i=e.model.get("check");"indeterminate"==i?$("input[type=checkbox]",e.$el).prop("indeterminate",!0):$("input[type=checkbox]",e.$el).prop({checked:i,indeterminate:!1})},btnCustomFilter:"Custom Filter",textSelectAll:"Select All",txtTitle:"Filter",warnNoSelected:"You must choose at least one value",textWarning:"Warning",textEmptyItem:"{Blanks}",txtEmpty:"Enter cell's filter",txtSortLow2High:"Sort Lowest to Highest",txtSortHigh2Low:"Sort Highest to Lowest",txtSortCellColor:"Sort by cells color",txtSortFontColor:"Sort by font color",txtNumFilter:"Number filter",txtTextFilter:"Text filter",txtFilterCellColor:"Filter by cells color",txtFilterFontColor:"Filter by font color",txtClear:"Clear",txtReapply:"Reapply",txtEquals:"Equals...",txtNotEquals:"Does not equal...",txtGreater:"Greater than...",txtGreaterEquals:"Greater than or equal to...",txtLess:"Less than...",txtLessEquals:"Less than or equal to...",txtBetween:"Between...",txtTop10:"Top 10",txtAboveAve:"Above average",txtBelowAve:"Below average",txtBegins:"Begins with...",txtNotBegins:"Does not begin with...",txtEnds:"Ends with...",txtNotEnds:"Does not end with...",txtContains:"Contains...",txtNotContains:"Does not contain...",textSelectAllResults:"Select All Search Results",textAddSelection:"Add current selection to filter",txtValueFilter:"Value filter",txtLabelFilter:"Label filter",warnFilterError:"You need at least one field in the Values area in order to apply a value filter.",txtNotBetween:"Not between...",txtSortOption:"More sort options..."},SSE.Views.AutoFilterDialog||{}))}),define("spreadsheeteditor/main/app/view/SpecialPasteDialog",["common/main/lib/util/utils","common/main/lib/component/RadioBox","common/main/lib/component/CheckBox","common/main/lib/view/AdvancedSettingsWindow"],function(){"use strict";SSE.Views.SpecialPasteDialog=Common.Views.AdvancedSettingsWindow.extend(_.extend({options:{contentWidth:350,height:385},initialize:function(t){var e=this;_.extend(this.options,{title:this.textTitle,template:['
    ','
    ','
    ','',"",'","","",'",'","","",'",'","","",'",'","","",'",'","","",'",'","","",'",'","","",'","","",'",'","","",'",'","","",'",'","","",'","","",'",'","","
    ','","
    ','
    ',"
    ','
    ',"
    ','
    ',"
    ','
    ',"
    ','
    ',"
    ','
    ',"
    ','
    ',"
    ','
    ',"
    ','
    ',"
    ','
    ',"
    ','
    ',"
    ','
    ',"
    ','","
    ','
    ',"
    ','
    ',"
    ','
    ',"
    ','
    ',"
    ','
    ',"
    ',"
    ',"
    ','
    ',"
    ','
    ',"
    ","
    ","
    ","
    "].join("")},t),this.handler=t.handler,this.props=t.props,this._changedProps=null,this.isTable=!!t.isTable,Common.Views.AdvancedSettingsWindow.prototype.initialize.call(this,this.options)},render:function(){Common.Views.AdvancedSettingsWindow.prototype.render.call(this);this.propControls=[],this.radioAll=new Common.UI.RadioBox({el:$("#paste-radio-all"),name:"asc-radio-paste",labelText:this.textAll,value:Asc.c_oSpecialPasteProps.paste,disabled:!0}),this.radioAll.on("change",_.bind(this.onRadioPasteChange,this)),this.propControls[Asc.c_oSpecialPasteProps.paste]=this.radioAll,this.radioFormulas=new Common.UI.RadioBox({el:$("#paste-radio-formulas"),name:"asc-radio-paste",labelText:this.textFormulas,value:Asc.c_oSpecialPasteProps.pasteOnlyFormula,disabled:!0}),this.radioFormulas.on("change",_.bind(this.onRadioPasteChange,this)),this.propControls[Asc.c_oSpecialPasteProps.pasteOnlyFormula]=this.radioFormulas,this.radioValues=new Common.UI.RadioBox({el:$("#paste-radio-values"),name:"asc-radio-paste",labelText:this.textValues,value:Asc.c_oSpecialPasteProps.pasteOnlyValues,disabled:!0}),this.radioValues.on("change",_.bind(this.onRadioPasteChange,this)),this.propControls[Asc.c_oSpecialPasteProps.pasteOnlyValues]=this.radioValues,this.radioFormats=new Common.UI.RadioBox({el:$("#paste-radio-formats"),name:"asc-radio-paste",labelText:this.textFormats,value:Asc.c_oSpecialPasteProps.pasteOnlyFormating,disabled:!0}),this.radioFormats.on("change",_.bind(this.onRadioPasteChange,this)),this.propControls[Asc.c_oSpecialPasteProps.pasteOnlyFormating]=this.radioFormats,this.radioComments=new Common.UI.RadioBox({el:$("#paste-radio-comments"),name:"asc-radio-paste",labelText:this.textComments,value:Asc.c_oSpecialPasteProps.comments,disabled:!0}),this.radioComments.on("change",_.bind(this.onRadioPasteChange,this)),this.propControls[Asc.c_oSpecialPasteProps.comments]=this.radioComments,this.radioColWidth=new Common.UI.RadioBox({el:$("#paste-radio-col-width"),name:"asc-radio-paste",labelText:this.textColWidth,value:Asc.c_oSpecialPasteProps.columnWidth,disabled:!0}),this.radioColWidth.on("change",_.bind(this.onRadioPasteChange,this)),this.propControls[Asc.c_oSpecialPasteProps.columnWidth]=this.radioColWidth,this.radioWBorders=new Common.UI.RadioBox({el:$("#paste-radio-without-borders"),name:"asc-radio-paste",labelText:this.textWBorders,value:Asc.c_oSpecialPasteProps.formulaWithoutBorders,disabled:!0}),this.radioWBorders.on("change",_.bind(this.onRadioPasteChange,this)),this.propControls[Asc.c_oSpecialPasteProps.formulaWithoutBorders]=this.radioWBorders,this.radioFFormat=new Common.UI.RadioBox({el:$("#paste-radio-formula-formats"),name:"asc-radio-paste",labelText:this.textFFormat,value:Asc.c_oSpecialPasteProps.formulaAllFormatting,disabled:!0}),this.radioFFormat.on("change",_.bind(this.onRadioPasteChange,this)),this.propControls[Asc.c_oSpecialPasteProps.formulaAllFormatting]=this.radioFFormat,this.radioFWidth=new Common.UI.RadioBox({el:$("#paste-radio-formula-col-width"),name:"asc-radio-paste",labelText:this.textFWidth,value:Asc.c_oSpecialPasteProps.formulaColumnWidth,disabled:!0}),this.radioFWidth.on("change",_.bind(this.onRadioPasteChange,this)),this.propControls[Asc.c_oSpecialPasteProps.formulaColumnWidth]=this.radioFWidth,this.radioFNFormat=new Common.UI.RadioBox({el:$("#paste-radio-formula-num-format"),name:"asc-radio-paste",labelText:this.textFNFormat,value:Asc.c_oSpecialPasteProps.formulaNumberFormat,disabled:!0}),this.radioFNFormat.on("change",_.bind(this.onRadioPasteChange,this)),this.propControls[Asc.c_oSpecialPasteProps.formulaNumberFormat]=this.radioFNFormat,this.radioVNFormat=new Common.UI.RadioBox({el:$("#paste-radio-value-num-format"),name:"asc-radio-paste",labelText:this.textVNFormat,value:Asc.c_oSpecialPasteProps.valueNumberFormat,disabled:!0}),this.radioVNFormat.on("change",_.bind(this.onRadioPasteChange,this)),this.propControls[Asc.c_oSpecialPasteProps.valueNumberFormat]=this.radioVNFormat,this.radioVFormat=new Common.UI.RadioBox({el:$("#paste-radio-value-formats"),name:"asc-radio-paste",labelText:this.textVFormat,value:Asc.c_oSpecialPasteProps.valueAllFormating,disabled:!0}),this.radioVFormat.on("change",_.bind(this.onRadioPasteChange,this)),this.propControls[Asc.c_oSpecialPasteProps.valueAllFormating]=this.radioVFormat,this.radioNone=new Common.UI.RadioBox({el:$("#paste-radio-none"),name:"asc-radio-paste-operation",labelText:this.textNone,value:Asc.c_oSpecialPasteOperation.none,checked:!0}),this.radioNone.on("change",_.bind(this.onRadioOperationChange,this)),this.radioAdd=new Common.UI.RadioBox({el:$("#paste-radio-add"),name:"asc-radio-paste-operation",labelText:this.textAdd,value:Asc.c_oSpecialPasteOperation.add}),this.radioAdd.on("change",_.bind(this.onRadioOperationChange,this)),this.radioMult=new Common.UI.RadioBox({el:$("#paste-radio-mult"),name:"asc-radio-paste-operation",labelText:this.textMult,value:Asc.c_oSpecialPasteOperation.multiply}),this.radioMult.on("change",_.bind(this.onRadioOperationChange,this)),this.radioSub=new Common.UI.RadioBox({el:$("#paste-radio-sub"),name:"asc-radio-paste-operation",labelText:this.textSub,value:Asc.c_oSpecialPasteOperation.subtract}),this.radioSub.on("change",_.bind(this.onRadioOperationChange,this)),this.radioDiv=new Common.UI.RadioBox({el:$("#paste-radio-div"),name:"asc-radio-paste-operation",labelText:this.textDiv,value:Asc.c_oSpecialPasteOperation.divide}),this.radioDiv.on("change",_.bind(this.onRadioOperationChange,this)),this.chBlanks=new Common.UI.CheckBox({el:$("#paste-checkbox-blanks"),labelText:this.textBlanks}),this.chTranspose=new Common.UI.CheckBox({el:$("#paste-checkbox-transpose"),labelText:this.textTranspose}),this.afterRender()},afterRender:function(){this._setDefaults(this.props)},show:function(){Common.Views.AdvancedSettingsWindow.prototype.show.apply(this,arguments)},_setDefaults:function(t){var e=this;t&&_.each(t,function(t,i){e.propControls[t]&&e.propControls[t].setDisabled(!1)}),this._changedProps=new Asc.SpecialPasteProps,this._changedProps.asc_setProps(Asc.c_oSpecialPasteProps.paste),this._changedProps.asc_setOperation(Asc.c_oSpecialPasteOperation.none),this.radioAll.setValue(!0)},getSettings:function(){return this._changedProps&&(this._changedProps.asc_setTranspose("checked"==this.chTranspose.getValue()),this._changedProps.asc_setSkipBlanks("checked"==this.chBlanks.getValue())),this._changedProps},onDlgBtnClick:function(t){this._handleInput("object"==typeof t?t.currentTarget.attributes.result.value:t)},onPrimary:function(){return this._handleInput("ok"),!1},_handleInput:function(t){this.handler&&this.handler.call(this,t,"ok"==t?this.getSettings():void 0),this.close()},onRadioPasteChange:function(t,e,i){if(e&&this._changedProps){this._changedProps.asc_setProps(t.options.value);var n=t.options.value==Asc.c_oSpecialPasteProps.pasteOnlyFormating||t.options.value==Asc.c_oSpecialPasteProps.comments||t.options.value==Asc.c_oSpecialPasteProps.columnWidth,s=this.isTable&&!!this._changedProps.asc_getTableAllowed();this.radioNone.setDisabled(n||s),this.radioAdd.setDisabled(n||s),this.radioDiv.setDisabled(n||s),this.radioSub.setDisabled(n||s),this.radioMult.setDisabled(n||s),this.chBlanks.setDisabled(s),this.chTranspose.setDisabled(s)}},onRadioOperationChange:function(t,e,i){e&&this._changedProps&&this._changedProps.asc_setOperation(t.options.value)},textTitle:"Paste Special",textAll:"All",textFormulas:"Formulas",textValues:"Values",textFormats:"Formats",textComments:"Comments",textColWidth:"Column widths",textWBorders:"All except borders",textFFormat:"Formulas & formatting",textFWidth:"Formulas & column widths",textFNFormat:"Formulas & number formats",textVNFormat:"Values & number formats",textVFormat:"Values & formatting",textNone:"None",textAdd:"Add",textMult:"Multiply",textDiv:"Divide",textSub:"Subtract",textBlanks:"Skip blanks",textTranspose:"Transpose",textOperation:"Operation",textPaste:"Paste"},SSE.Views.SpecialPasteDialog||{}))}),define("text!spreadsheeteditor/main/app/template/SlicerSettingsAdvanced.template",[],function(){return'
    \n
    \n
    \n
    \n \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n \n
    \n
    \n
    \n
    \n \n
    \n
    \n
    \n
    \n
    \n
    \n \n
    \n
    \n
    \n \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n \x3c!--
    --\x3e\n
    \n
    \n
    \n
    \n
    \n
    \n
    \n \n \n
    \n
    \n \n \n
    \n
    \n \n
    \n
    \n
    \n
    \n
    \n
    \n \n \n \n \n \n \n \n \n \n \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n
    \n \n \n \n \n \n \n \n \n \n \n
    \n \n
    \n
    \n \n \n
    \n \n
    \n
    \n
    '}),void 0===Common)var Common={};define("common/main/lib/component/ComboDataView",["common/main/lib/component/BaseView","common/main/lib/component/DataView"],function(){"use strict";Common.UI.ComboDataView=Common.UI.BaseView.extend({options:{id:null,cls:"",style:"",hint:!1,itemWidth:80,itemHeight:40,menuMaxHeight:300,enableKeyEvents:!1,beforeOpenHandler:null,additionalMenuItems:null,showLast:!0,minWidth:-1},template:_.template(['
    ','
    ','
    ',"
    "].join("")),initialize:function(t){Common.UI.BaseView.prototype.initialize.call(this,t),this.id=this.options.id||Common.UI.getId(),this.cls=this.options.cls,this.style=this.options.style,this.hint=this.options.hint,this.store=this.options.store||new Common.UI.DataViewStore,this.itemWidth=this.options.itemWidth,this.itemHeight=this.options.itemHeight,this.menuMaxHeight=this.options.menuMaxHeight,this.beforeOpenHandler=this.options.beforeOpenHandler,this.showLast=this.options.showLast,this.rootWidth=0,this.rootHeight=0,this.rendered=!1,this.needFillComboView=!1,this.minWidth=this.options.minWidth,this.fieldPicker=new Common.UI.DataView({cls:"field-picker",allowScrollbar:!1,itemTemplate:_.template(['
    ','','<% if (typeof title !== "undefined") {%>','<%= title %>',"<% } %>","
    "].join(""))}),this.openButton=new Common.UI.Button({cls:"open-menu",menu:new Common.UI.Menu({menuAlign:"tl-tl",offset:[0,3],items:[{template:_.template('')}]})}),null!=this.options.additionalMenuItems&&(this.openButton.menu.items=this.openButton.menu.items.concat(this.options.additionalMenuItems)),this.menuPicker=new Common.UI.DataView({cls:"menu-picker",parentMenu:this.openButton.menu,restoreHeight:this.menuMaxHeight,style:"max-height: "+this.menuMaxHeight+"px;",enableKeyEvents:this.options.enableKeyEvents,store:this.store, itemTemplate:_.template(['
    ','','<% if (typeof title !== "undefined") {%>','<%= title %>',"<% } %>","
    "].join(""))}),setInterval(_.bind(this.checkSize,this),500),this.options.el&&this.render()},render:function(t){if(!this.rendered){var e=this;e.trigger("render:before",e),e.cmpEl=e.$el||$(e.el);var i=e.template({id:e.id,cls:e.cls,style:e.style});t?(e.setElement(t,!1),e.cmpEl=$(i),t.html(e.cmpEl)):e.cmpEl.html(i),e.rootWidth=e.cmpEl.width(),e.rootHeight=e.cmpEl.height(),e.fieldPicker.render($(".view",e.cmpEl)),e.openButton.render($(".button",e.cmpEl)),e.menuPicker.render($(".menu-picker-container",e.cmpEl)),e.openButton.menu.cmpEl&&e.openButton.menu.cmpEl&&(e.openButton.menu.menuAlignEl=e.cmpEl,e.openButton.menu.cmpEl.css("min-width",e.itemWidth),e.openButton.menu.on("show:before",_.bind(e.onBeforeShowMenu,e)),e.openButton.menu.on("show:after",_.bind(e.onAfterShowMenu,e)),e.openButton.cmpEl.on("hide.bs.dropdown",_.bind(e.onBeforeHideMenu,e)),e.openButton.cmpEl.on("hidden.bs.dropdown",_.bind(e.onAfterHideMenu,e))),e.options.hint&&(e.cmpEl.attr("data-toggle","tooltip"),e.cmpEl.tooltip({title:e.options.hint,placement:e.options.hintAnchor||"cursor"})),e.fieldPicker.on("item:select",_.bind(e.onFieldPickerSelect,e)),e.menuPicker.on("item:select",_.bind(e.onMenuPickerSelect,e)),e.fieldPicker.on("item:click",_.bind(e.onFieldPickerClick,e)),e.menuPicker.on("item:click",_.bind(e.onMenuPickerClick,e)),e.fieldPicker.on("item:contextmenu",_.bind(e.onPickerItemContextMenu,e)),e.menuPicker.on("item:contextmenu",_.bind(e.onPickerItemContextMenu,e)),e.fieldPicker.el.addEventListener("contextmenu",_.bind(e.onPickerComboContextMenu,e),!1),e.menuPicker.el.addEventListener("contextmenu",_.bind(e.onPickerComboContextMenu,e),!1),e.onResize(),e.rendered=!0,e.trigger("render:after",e)}return this},checkSize:function(){if(this.cmpEl&&this.cmpEl.is(":visible")){var t=this,e=this.cmpEl.width(),i=this.cmpEl.height();if(e div:not(.grouped-data):not(.ps-scrollbar-x-rail):not(.ps-scrollbar-y-rail)")[0]);a.length>0&&(n.itemMarginLeft=parseInt(a.css("margin-left")),n.itemMarginRight=parseInt(a.css("margin-right")),n.itemPaddingLeft=parseInt(a.css("padding-left")),n.itemPaddingRight=parseInt(a.css("padding-right")),n.itemBorderLeft=parseInt(a.css("border-left-width")),n.itemBorderRight=parseInt(a.css("border-right-width")))}var l=s.indexOf(t);if(l<0)return;var r=s.length,c=Math.floor(Math.max(o.width(),n.minWidth)/(n.itemWidth+(n.itemMarginLeft||0)+(n.itemMarginRight||0)+(n.itemPaddingLeft||0)+(n.itemPaddingRight||0)+(n.itemBorderLeft||0)+(n.itemBorderRight||0))),h=[];o.height()/n.itemHeight>2&&(c*=Math.floor(o.height()/n.itemHeight)),l=Math.floor(l/c)*c,r-l1?t/2:t)},setItemHeight:function(t){this.itemHeight!=t&&(this.itemHeight=window.devicePixelRatio>1?t/2:t)},removeTips:function(){var t=this.menuPicker;_.each(t.dataViewItems,function(t){var e=t.$el.data("bs.tooltip");e&&e.tip().remove()},t)}})}),define("spreadsheeteditor/main/app/view/SlicerSettingsAdvanced",["text!spreadsheeteditor/main/app/template/SlicerSettingsAdvanced.template","common/main/lib/view/AdvancedSettingsWindow","common/main/lib/component/MetricSpinner","common/main/lib/component/CheckBox","common/main/lib/component/RadioBox","common/main/lib/component/ComboDataView"],function(t){"use strict";SSE.Views.SlicerSettingsAdvanced=Common.Views.AdvancedSettingsWindow.extend(_.extend({options:{contentWidth:330,height:435,toggleGroup:"slicer-adv-settings-group",storageName:"sse-slicer-settings-adv-category"},initialize:function(e){_.extend(this.options,{title:this.textTitle,items:[{panelId:"id-adv-slicer-style",panelCaption:this.strStyleSize},{panelId:"id-adv-slicer-sorting",panelCaption:this.strSorting},{panelId:"id-adv-slicer-references",panelCaption:this.strReferences},{panelId:"id-adv-slicer-snap",panelCaption:this.textSnap},{panelId:"id-adv-slicer-alttext",panelCaption:this.textAlt}],contentTemplate:_.template(t)({scope:this})},e),this.options.handler=function(t,i){return"ok"==t&&!this.isNameValid()||void(e.handler&&e.handler.call(this,t,i))},Common.Views.AdvancedSettingsWindow.prototype.initialize.call(this,this.options),this._changedProps=null,this._noApply=!0,this.spinners=[],this._nRatio=1,this._originalProps=this.options.imageProps},render:function(){Common.Views.AdvancedSettingsWindow.prototype.render.call(this);var t=this;this.inputHeader=new Common.UI.InputField({el:$("#sliceradv-text-header"),allowBlank:!0,style:"width: 178px;"}).on("changed:after",function(){t.isCaptionChanged=!0}),this.chHeader=new Common.UI.CheckBox({el:$("#sliceradv-checkbox-header"),labelText:this.strShowHeader}),this.chHeader.on("change",_.bind(function(t,e,i,n){this._changedProps&&this._changedProps.asc_setShowCaption("checked"==t.getValue())},this)),this.btnSlicerStyle=new Common.UI.Button({parentEl:$("#sliceradv-btn-style"),cls:"btn-large-dataview sheet-template-slicer",iconCls:"icon-template-slicer",menu:new Common.UI.Menu({style:"width: 333px;",additionalAlign:this.menuAddAlign,items:[{template:_.template('')}]})}),this.mnuSlicerPicker=new Common.UI.DataView({el:$("#sliceradv-menu-style"),parentMenu:this.btnSlicerStyle.menu,restoreHeight:325,groups:new Common.UI.DataViewGroupStore,store:new Common.UI.DataViewStore,itemTemplate:_.template('
    '),style:"max-height: 325px;"}),this.mnuSlicerPicker.on("item:click",_.bind(this.onSelectSlicerStyle,this,this.btnSlicerStyle)),this.numWidth=new Common.UI.MetricSpinner({el:$("#sliceradv-spin-width"),step:.1,width:85,defaultUnit:"cm",defaultValue:0,value:"0 cm",maxValue:5963.9,minValue:0}),this.numWidth.on("change",_.bind(function(t,e,i,n){if(this.btnRatio.pressed){var s=t.getNumberValue(),o=s/this._nRatio;o>this.numHeight.options.maxValue&&(o=this.numHeight.options.maxValue,s=o*this._nRatio,this.numWidth.setValue(s,!0)),this.numHeight.setValue(o,!0)}this._originalProps&&(this._originalProps.put_Width(Common.Utils.Metric.fnRecalcToMM(t.getNumberValue())),this._originalProps.put_Height(Common.Utils.Metric.fnRecalcToMM(this.numHeight.getNumberValue())))},this)),this.spinners.push(this.numWidth),this.numHeight=new Common.UI.MetricSpinner({el:$("#sliceradv-spin-height"),step:.1,width:85,defaultUnit:"cm",defaultValue:0,value:"0 cm",maxValue:5963.9,minValue:0}),this.numHeight.on("change",_.bind(function(t,e,i,n){var s=t.getNumberValue(),o=null;this.btnRatio.pressed&&(o=s*this._nRatio,o>this.numWidth.options.maxValue&&(o=this.numWidth.options.maxValue,s=o/this._nRatio,this.numHeight.setValue(s,!0)),this.numWidth.setValue(o,!0)),this._originalProps&&(this._originalProps.put_Width(Common.Utils.Metric.fnRecalcToMM(this.numWidth.getNumberValue())),this._originalProps.put_Height(Common.Utils.Metric.fnRecalcToMM(t.getNumberValue())))},this)),this.spinners.push(this.numHeight),this.btnRatio=new Common.UI.Button({parentEl:$("#sliceradv-button-ratio"),cls:"btn-toolbar",iconCls:"toolbar__icon advanced-btn-ratio",style:"margin-bottom: 1px;",enableToggle:!0,hint:this.textKeepRatio}),this.btnRatio.on("click",_.bind(function(t,e){t.pressed&&this.numHeight.getNumberValue()>0&&(this._nRatio=this.numWidth.getNumberValue()/this.numHeight.getNumberValue()),this._originalProps&&this._originalProps.asc_putLockAspect(t.pressed)},this)),this.numColHeight=new Common.UI.MetricSpinner({el:$("#sliceradv-spin-col-height"),step:.1,width:85,defaultUnit:"cm",defaultValue:0,value:"0 cm",maxValue:5963.9,minValue:0}),this.numColHeight.on("change",_.bind(function(t,e,i,n){var s=t.getNumberValue();this._changedProps&&this._changedProps.asc_setRowHeight(36e3*Common.Utils.Metric.fnRecalcToMM(s))},this)),this.spinners.push(this.numColHeight),this.numCols=new Common.UI.MetricSpinner({el:$("#sliceradv-spin-columns"),step:1,width:85,defaultUnit:"",defaultValue:1,value:"1",allowDecimal:!1,maxValue:2e4,minValue:1}),this.numCols.on("change",_.bind(function(t,e,i,n){var s=t.getNumberValue();this._changedProps&&this._changedProps.asc_setColumnCount(s)},this)),this.radioAsc=new Common.UI.RadioBox({el:$("#sliceradv-radio-asc"),name:"asc-radio-sliceradv-sort",labelText:this.textAsc,checked:!0}),this.radioAsc.on("change",_.bind(function(t,e,i){e&&this._changedProps&&this._changedProps.asc_setSortOrder(Asc.ST_tabularSlicerCacheSortOrder.Ascending)},this)),this.radioDesc=new Common.UI.RadioBox({el:$("#sliceradv-radio-desc"),name:"asc-radio-sliceradv-sort",labelText:this.textDesc,checked:!1}),this.radioDesc.on("change",_.bind(function(t,e,i){e&&this._changedProps&&this._changedProps.asc_setSortOrder(Asc.ST_tabularSlicerCacheSortOrder.Descending)},this)),this.chHideNoData=new Common.UI.CheckBox({el:$("#sliceradv-check-hide-nodata"),labelText:this.strHideNoData}),this.chHideNoData.on("change",_.bind(function(t,e,i,n){var s="checked"==t.getValue();this.chIndNoData.setDisabled(s),this.chShowNoData.setDisabled(s||"checked"!=this.chIndNoData.getValue()),this.chShowDel.setDisabled(s),this._changedProps&&this._changedProps.asc_setHideItemsWithNoData(s)},this)),this.chIndNoData=new Common.UI.CheckBox({el:$("#sliceradv-check-indicate-nodata"),labelText:this.strIndNoData}),this.chIndNoData.on("change",_.bind(function(t,e,i,n){var s="checked"==t.getValue();this.chShowNoData.setDisabled(!s),this._changedProps&&this._changedProps.asc_setIndicateItemsWithNoData(s)},this)),this.chShowNoData=new Common.UI.CheckBox({el:$("#sliceradv-check-show-nodata-last"),disabled:!0,labelText:this.strShowNoData}),this.chShowNoData.on("change",_.bind(function(t,e,i,n){this._changedProps&&this._changedProps.asc_setShowItemsWithNoDataLast("checked"==t.getValue())},this)),this.chShowDel=new Common.UI.CheckBox({el:$("#sliceradv-check-show-deleted"),labelText:this.strShowDel}),this.chShowDel.on("change",_.bind(function(t,e,i,n){this._changedProps},this)),this.inputName=new Common.UI.InputField({el:$("#sliceradv-text-name"),allowBlank:!1,blankError:t.txtEmpty,style:"width: 178px;"}).on("changed:after",function(){t.isNameChanged=!0}),this.lblSource=$("#sliceradv-lbl-source"),this.lblFormula=$("#sliceradv-lbl-formula"),this.radioTwoCell=new Common.UI.RadioBox({el:$("#slicer-advanced-radio-twocell"),name:"asc-radio-snap",labelText:this.textTwoCell,value:AscCommon.c_oAscCellAnchorType.cellanchorTwoCell}),this.radioTwoCell.on("change",_.bind(this.onRadioSnapChange,this)),this.radioOneCell=new Common.UI.RadioBox({el:$("#slicer-advanced-radio-onecell"),name:"asc-radio-snap",labelText:this.textOneCell,value:AscCommon.c_oAscCellAnchorType.cellanchorOneCell}),this.radioOneCell.on("change",_.bind(this.onRadioSnapChange,this)),this.radioAbsolute=new Common.UI.RadioBox({el:$("#slicer-advanced-radio-absolute"),name:"asc-radio-snap",labelText:this.textAbsolute,value:AscCommon.c_oAscCellAnchorType.cellanchorAbsolute}),this.radioAbsolute.on("change",_.bind(this.onRadioSnapChange,this)),this.inputAltTitle=new Common.UI.InputField({el:$("#sliceradv-alt-title"),allowBlank:!0,validateOnBlur:!1,style:"width: 100%;"}).on("changed:after",function(){t.isAltTitleChanged=!0}),this.textareaAltDescription=this.$window.find("textarea"),this.textareaAltDescription.keydown(function(e){e.keyCode==Common.UI.Keys.RETURN&&e.stopPropagation(),t.isAltDescChanged=!0}),this.afterRender()},getFocusedComponents:function(){return[this.inputHeader,this.numWidth,this.numHeight,this.numCols,this.numColHeight,this.inputName,this.inputAltTitle,this.textareaAltDescription]},onCategoryClick:function(t,e){Common.Views.AdvancedSettingsWindow.prototype.onCategoryClick.call(this,t,e);var i=this;setTimeout(function(){switch(e){case 0:i.inputHeader.focus();break;case 2:i.inputName.focus();break;case 4:i.inputAltTitle.focus()}},10)},getSettings:function(){return this.isCaptionChanged&&this._changedProps.asc_setCaption(this.inputHeader.getValue()),this.isNameChanged&&this._changedProps.asc_setName(this.inputName.getValue()),this.isAltTitleChanged&&this._originalProps.asc_putTitle(this.inputAltTitle.getValue()),this.isAltDescChanged&&this._originalProps.asc_putDescription(this.textareaAltDescription.val()),{imageProps:this._originalProps}},_setDefaults:function(t){if(t){var e=t.asc_getWidth();switch(this.numWidth.setValue(null!==e?Common.Utils.Metric.fnRecalcFromMM(e).toFixed(2):"",!0),e=t.asc_getHeight(),this.numHeight.setValue(null!==e?Common.Utils.Metric.fnRecalcFromMM(e).toFixed(2):"",!0),t.asc_getHeight()>0&&(this._nRatio=t.asc_getWidth()/t.asc_getHeight()),e=t.asc_getLockAspect(),this.btnRatio.toggle(e),e=t.asc_getTitle(),this.inputAltTitle.setValue(e||""),e=t.asc_getDescription(),this.textareaAltDescription.val(e||""),e=t.asc_getAnchor()){case AscCommon.c_oAscCellAnchorType.cellanchorTwoCell:this.radioTwoCell.setValue(!0,!0);break;case AscCommon.c_oAscCellAnchorType.cellanchorOneCell:this.radioOneCell.setValue(!0,!0);break;case AscCommon.c_oAscCellAnchorType.cellanchorAbsolute:this.radioAbsolute.setValue(!0,!0)}var i=t.asc_getSlicerProperties();if(i){this._noApply=!0,this.numCols.setValue(i.asc_getColumnCount(),!0),this.numColHeight.setValue(Common.Utils.Metric.fnRecalcFromMM(i.asc_getRowHeight()/36e3).toFixed(2),!0),this.inputHeader.setValue(i.asc_getCaption(),!0);var n=i.asc_getShowCaption();this.chHeader.setValue(null!==n&&void 0!==n?n:"indeterminate",!0),this.radioAsc.setCaption(this.textAsc+" ("+this.textAZ+")"),this.radioDesc.setCaption(this.textDesc+" ("+this.textZA+")"),i.asc_getSortOrder()==Asc.ST_tabularSlicerCacheSortOrder.Ascending?this.radioAsc.setValue(!0,!0):this.radioDesc.setValue(!0,!0),n=i.asc_getIndicateItemsWithNoData(),this.chIndNoData.setValue(null!==n&&void 0!==n?n:"indeterminate",!0),n=i.asc_getShowItemsWithNoDataLast(),this.chShowNoData.setValue(null!==n&&void 0!==n?n:"indeterminate",!0),n=i.asc_getHideItemsWithNoData(),this.chHideNoData.setValue(null!==n&&void 0!==n?n:"indeterminate",!0),this.chIndNoData.setDisabled(n),this.chShowNoData.setDisabled(n||"checked"!=this.chIndNoData.getValue()),this.chShowDel.setDisabled(n),e=i.asc_getName(),this.inputName.setValue(null!==e&&void 0!==e?e:""),this.inputName.setDisabled(null===e||void 0===e),this.lblSource.text(i.asc_getSourceName()),this.lblFormula.text(i.asc_getNameInFormulas()),e=i.asc_getStyle();var s=this.mnuSlicerPicker.store.findWhere({type:e});!s&&this.mnuSlicerPicker.store.length>0&&(s=this.mnuSlicerPicker.store.at(0)),s?(this.btnSlicerStyle.suspendEvents(),this.mnuSlicerPicker.selectRecord(s,!0),this.btnSlicerStyle.resumeEvents(),this.$window.find(".icon-template-slicer").css({"background-image":"url("+s.get("imageUrl")+")",height:"49px",width:"36px","background-position":"center","background-size":"cover"})):this.$window.find(".icon-template-slicer").css({height:"49px",width:"36px","background-position":"center","background-size":"cover"}),this._noApply=!1,this._changedProps=i}}},updateMetricUnit:function(){if(this.spinners)for(var t=0;t0){n.asc_setFilter(new Asc.ColorFilter),n.asc_setType(Asc.c_oAscAutoFilterTypes.ColorFilter);var s=n.asc_getFilter();s.asc_setCellColor(1==e.value&&null),s.asc_setCColor(1==e.value?this.documentHolder.ssMenu.cellColor:this.documentHolder.ssMenu.fontColor)}else{n.asc_setFilter(new Asc.CustomFilters),n.asc_setType(Asc.c_oAscAutoFilterTypes.CustomFilters);var o=n.asc_getFilter();o.asc_setCustomFilters([new Asc.CustomFilter]),o.asc_setAnd(!0);o.asc_getCustomFilters()[0].asc_setOperator(Asc.c_oAscCustomAutoFilter.equals)}i.asc_setFilterObj(n),this.api.asc_applyAutoFilterByType(i),Common.NotificationCenter.trigger("edit:complete",this.documentHolder),Common.component.Analytics.trackEvent("DocumentHolder","Filter Cells")}},onReapply:function(){this.api.asc_reapplyAutoFilter(this.documentHolder.ssMenu.formatTableName)},onClear:function(t,e){this.api&&(this.api.asc_emptyCells(e.value),Common.NotificationCenter.trigger("edit:complete",this.documentHolder),Common.component.Analytics.trackEvent("DocumentHolder","Clear"))},onSelectTable:function(t,e){this.api&&this.documentHolder.ssMenu.formatTableName&&(this.api.asc_changeSelectionFormatTable(this.documentHolder.ssMenu.formatTableName,e.value),Common.NotificationCenter.trigger("edit:complete",this.documentHolder),Common.component.Analytics.trackEvent("DocumentHolder","Select Table"))},onInsertTable:function(t,e){this.api&&this.documentHolder.ssMenu.formatTableName&&(this.api.asc_insertCellsInTable(this.documentHolder.ssMenu.formatTableName,e.value),Common.NotificationCenter.trigger("edit:complete",this.documentHolder),Common.component.Analytics.trackEvent("DocumentHolder","Insert to Table"))},onDeleteTable:function(t,e){this.api&&this.documentHolder.ssMenu.formatTableName&&(this.api.asc_deleteCellsInTable(this.documentHolder.ssMenu.formatTableName,e.value),Common.NotificationCenter.trigger("edit:complete",this.documentHolder),Common.component.Analytics.trackEvent("DocumentHolder","Delete from Table"))},onInsFunction:function(t){var e=this.getApplication().getController("FormulaDialog");e&&this.api&&e.showDialog(void 0,t.value==Asc.ETotalsRowFunction.totalrowfunctionCustom)},onInsHyperlink:function(t){var e,i,n=this;if(n.api){for(var s=n.api.asc_getWorksheetsCount(),o=-1,a=[];++o-1&&e.value<6?(this.api.asc_setSelectedDrawingObjectAlign(e.value),Common.NotificationCenter.trigger("edit:complete",this.documentHolder),Common.component.Analytics.trackEvent("DocumentHolder","Objects Align")):6==e.value?(this.api.asc_DistributeSelectedDrawingObjectHor(),Common.NotificationCenter.trigger("edit:complete",this.documentHolder),Common.component.Analytics.trackEvent("DocumentHolder","Distribute")):7==e.value&&(this.api.asc_DistributeSelectedDrawingObjectVer(),Common.NotificationCenter.trigger("edit:complete",this.documentHolder),Common.component.Analytics.trackEvent("DocumentHolder","Distribute")))},onParagraphVAlign:function(t,e){if(this.api){var i=new Asc.asc_CImgProperty;i.asc_putVerticalTextAlign(e.value),this.api.asc_setGraphicObjectProps(i),Common.NotificationCenter.trigger("edit:complete",this.documentHolder),Common.component.Analytics.trackEvent("DocumentHolder","Paragraph Vertical Align")}},onParagraphDirection:function(t,e){if(this.api){var i=new Asc.asc_CImgProperty;i.asc_putVert(e.options.direction),this.api.asc_setGraphicObjectProps(i),Common.NotificationCenter.trigger("edit:complete",this.documentHolder),Common.component.Analytics.trackEvent("DocumentHolder","Text Direction")}},onSelectBulletMenu:function(t,e){if(this.api)if(-1==e.options.value)this.api.asc_setListType(0,e.options.value),Common.NotificationCenter.trigger("edit:complete",this.documentHolder),Common.component.Analytics.trackEvent("DocumentHolder","List Type");else if("settings"==e.options.value){for(var i,n=this,s=n.api.asc_getGraphicObjectProps(),o=0;o0;r--)switch(t[r-1].asc_getType()){case Asc.c_oAscMouseMoveType.Hyperlink:e=r;break;case Asc.c_oAscMouseMoveType.Comment:i=r;break;case Asc.c_oAscMouseMoveType.LockedObject:n=r;break;case Asc.c_oAscMouseMoveType.ResizeColumn:s=r;break;case Asc.c_oAscMouseMoveType.ResizeRow:o=r;break;case Asc.c_oAscMouseMoveType.Filter:a=r;break;case Asc.c_oAscMouseMoveType.Tooltip:l=r}var c=this,h=[0,0],d=c.tooltips.coauth,p=c.tooltips.comment,m=c.tooltips.hyperlink,u=c.tooltips.row_column,g=c.tooltips.filter,b=c.tooltips.slicer,f=[c.documentHolder.cmpEl.offset().left-$(window).scrollLeft(),c.documentHolder.cmpEl.offset().top-$(window).scrollTop()];if(e||c.hideHyperlinkTip(),void 0===s&&void 0===o&&!u.isHidden&&u.ref&&(u.ref.hide(),u.ref=void 0,u.text="",u.isHidden=!0),(c.permissions.isEdit||c.permissions.canViewComments)&&(!i||this.popupmenu)&&(p.moveCommentId=void 0,void 0!=p.viewCommentId)){p={};var C=this.getApplication().getController("Common.Controllers.Comments");C&&(this.permissions.canCoAuthoring&&this.permissions.canViewComments?setTimeout(function(){C.onApiHideComment(!0)},200):C.onApiHideComment(!0))}c.permissions.isEdit&&(n||c.hideCoAuthTips(),void 0===l&&!b.isHidden&&b.ref&&(b.ref.hide(),b.ref=void 0,b.text="",b.isHidden=!0)),(void 0===a||c.dlgFilter&&c.dlgFilter.isVisible()||c.currentMenu&&c.currentMenu.isVisible())&&!g.isHidden&&g.ref&&(g.ref.hide(),g.ref=void 0,g.text="",g.isHidden=!0);if(e){m.parentEl||(m.parentEl=$('
    '),c.documentHolder.cmpEl.append(m.parentEl));var v=t[e-1],_=v.asc_getHyperlink();if(_.asc_getType()==Asc.c_oAscHyperlinkType.WebLink){var y=_.asc_getTooltip();y=y?Common.Utils.String.htmlEncode(y)+"
    "+c.textCtrlClick+"":Common.Utils.String.htmlEncode(_.asc_getHyperlinkUrl())+"
    "+c.textCtrlClick+""}else y=Common.Utils.String.htmlEncode(_.asc_getTooltip()||_.asc_getLocation()),y+="
    "+c.textCtrlClick+"";if(m.ref&&m.ref.isVisible()&&m.text!=y&&(m.ref.hide(),m.ref=void 0,m.text="",m.isHidden=!0),!m.ref||!m.ref.isVisible()){m.text=y,m.ref=new Common.UI.Tooltip({owner:m.parentEl,html:!0,title:y}),m.ref.show([-1e4,-1e4]),m.isHidden=!1,h=[v.asc_getX(),v.asc_getY()],h[0]+=f[0]+6,h[1]+=f[1]-20,h[1]-=m.ref.getBSTip().$tip.height();var x=m.ref.getBSTip().$tip.width();h[0]+x>c.tooltips.coauth.bodyWidth&&(h[0]=c.tooltips.coauth.bodyWidth-x),m.ref.getBSTip().$tip.css({top:h[1]+"px",left:h[0]+"px"})}}if(void 0!==s||void 0!==o){u.parentEl||(u.parentEl=$('
    '),c.documentHolder.cmpEl.append(u.parentEl));var v=t[void 0!==s?s-1:o-1],w=Common.Utils.String.format(void 0!==s?this.textChangeColumnWidth:this.textChangeRowHeight,v.asc_getSizeCCOrPt().toFixed(2),v.asc_getSizePx().toFixed());if(u.ref&&u.ref.isVisible()&&u.text!=w&&(u.text=w,u.ref.setTitle(w),u.ref.updateTitle()),!u.ref||!u.ref.isVisible()){u.text=w,u.ref=new Common.UI.Tooltip({owner:u.parentEl,html:!0,title:w}),u.ref.show([-1e4,-1e4]),u.isHidden=!1,h=[v.asc_getX(),v.asc_getY()],h[0]+=f[0]+6,h[1]+=f[1]-20-u.ttHeight;var x=u.ref.getBSTip().$tip.width();h[0]+x>c.tooltips.coauth.bodyWidth&&(h[0]=c.tooltips.coauth.bodyWidth-x-20),u.ref.getBSTip().$tip.css({top:h[1]+"px",left:h[0]+"px"})}}if((c.permissions.isEdit||c.permissions.canViewComments)&&i&&!this.popupmenu&&(v=t[i-1],!p.editCommentId&&p.moveCommentId!=v.asc_getCommentIndexes()[0])){p.moveCommentId=v.asc_getCommentIndexes()[0],p.moveCommentTimer&&clearTimeout(p.moveCommentTimer);var S=v.asc_getCommentIndexes(),A=v.asc_getX(),k=v.asc_getY(),T=v.asc_getReverseX();p.moveCommentTimer=setTimeout(function(){if(p.moveCommentId&&!p.editCommentId){p.viewCommentId=p.moveCommentId;var t=c.getApplication().getController("Common.Controllers.Comments");t&&(t.isSelectedComment||t.onApiShowComment(S,A,k,T,!1,!0))}},400)}if(c.permissions.isEdit&&n&&(v=t[n-1],d.XY||c.onDocumentResize(),d.x_point!=v.asc_getX()||d.y_point!=v.asc_getY())){c.hideCoAuthTips(),d.x_point=v.asc_getX(),d.y_point=v.asc_getY();var I=$(document.createElement("div")),E=v.asc_getLockedObjectType()==Asc.c_oAscMouseMoveLockedObjectType.Sheet||v.asc_getLockedObjectType()==Asc.c_oAscMouseMoveLockedObjectType.TableProperties;d.ref=I,I.addClass("username-tip"),I.css({height:d.ttHeight+"px",position:"absolute",zIndex:"900",visibility:"visible"}),$(document.body).append(I),h=[E?d.x_point+d.rightMenuWidth:d.bodyWidth-(d.x_point+d.XY[0]),d.y_point+d.XY[1]],h[1]>=d.XY[1]&&h[1]+d.ttHeight'),c.documentHolder.cmpEl.append(g.parentEl));var v=t[a-1],w=c.makeFilterTip(v.asc_getFilter());if(g.ref&&g.ref.isVisible()&&g.text!=w&&(g.text=w,g.ref.setTitle(w),g.ref.updateTitle()),!g.ref||!g.ref.isVisible()){g.text=w,g.ref=new Common.UI.Tooltip({owner:g.parentEl,html:!1,title:w,cls:"auto-tooltip"}),g.ref.show([-1e4,-1e4]),g.isHidden=!1,h=[v.asc_getX()+f[0]-10,v.asc_getY()+f[1]+20];g.ref.getBSTip().$tip.width();h[1]+g.ttHeight>c.tooltips.coauth.bodyHeight&&(h[1]=c.tooltips.coauth.bodyHeight-g.ttHeight-5,h[0]+=20);var x=g.ref.getBSTip().$tip.width();h[0]+x>c.tooltips.coauth.bodyWidth&&(h[0]=c.tooltips.coauth.bodyWidth-x-20),g.ref.getBSTip().$tip.css({top:h[1]+"px",left:h[0]+"px"})}}if(void 0!==l&&c.permissions.isEdit){b.parentEl||(b.parentEl=$('
    '),c.documentHolder.cmpEl.append(b.parentEl));var v=t[l-1],w=v.asc_getTooltip();if(b.ref&&b.ref.isVisible()&&b.text!=w&&(b.text=w,b.ref.setTitle(w),b.ref.updateTitle()),!b.ref||!b.ref.isVisible()){b.text=w,b.ref=new Common.UI.Tooltip({owner:b.parentEl,html:!0,title:w}),b.ref.show([-1e4,-1e4]),b.isHidden=!1,h=[v.asc_getX(),v.asc_getY()],h[0]+=f[0]+6,h[1]+=f[1]-20-b.ttHeight;var x=b.ref.getBSTip().$tip.width();h[0]+x>c.tooltips.coauth.bodyWidth&&(h[0]=c.tooltips.coauth.bodyWidth-x-20),b.ref.getBSTip().$tip.css({top:h[1]+"px",left:h[0]+"px"})}}}},onApiHideComment:function(){this.tooltips.comment.viewCommentId=this.tooltips.comment.editCommentId=this.tooltips.comment.moveCommentId=void 0},onApiHyperlinkClick:function(t){if(!t)return void Common.UI.alert({msg:this.errorInvalidLink,title:this.notcriticalErrorTitle,iconCls:"warn",buttons:["ok"],callback:_.bind(function(t){Common.NotificationCenter.trigger("edit:complete",this.documentHolder)},this)});try{window.parent.APP.openURL(t)}catch(i){console.error(i);var e=window.open(t,"_blank");e&&e.focus()}},onApiAutofilter:function(t){var e=this;if(!e.tooltips.filter.isHidden&&e.tooltips.filter.ref&&(e.tooltips.filter.ref.hide(),e.tooltips.filter.ref=void 0,e.tooltips.filter.text="",e.tooltips.filter.isHidden=!0),e.permissions.isEdit)if(e.dlgFilter)e.dlgFilter.close();else{e.dlgFilter=new SSE.Views.AutoFilterDialog({api:this.api}).on({close:function(){e.api&&e.api.asc_enableKeyEvents(!0),e.dlgFilter=void 0}}),e.api&&e.api.asc_enableKeyEvents(!1),Common.UI.Menu.Manager.hideAll(),e.dlgFilter.setSettings(t);var i=e.documentHolder.cmpEl.offset(),n=t.asc_getCellCoord(),s=n.asc_getX()+n.asc_getWidth()+i.left,o=n.asc_getY()+n.asc_getHeight()+i.top,a=Common.Utils.innerWidth(),l=Common.Utils.innerHeight();s+e.dlgFilter.options.width>a&&(s=a-e.dlgFilter.options.width-5),o+e.dlgFilter.options.height>l&&(o=l-e.dlgFilter.options.height-5),e.dlgFilter.show(s,o)}},makeFilterTip:function(t){var e=t.asc_getFilterObj(),i=e.asc_getType(),n=(t.asc_getIsTextFilter(),t.asc_getColorsFill(),t.asc_getColorsFont(),"");if(i===Asc.c_oAscAutoFilterTypes.CustomFilters){var s=e.asc_getFilter(),o=s.asc_getCustomFilters();n=this.getFilterName(Asc.c_oAscAutoFilterTypes.CustomFilters,o[0].asc_getOperator())+' "'+o[0].asc_getVal()+'"',o.length>1&&(n=n+" "+(s.asc_getAnd()?this.txtAnd:this.txtOr),n=n+" "+this.getFilterName(Asc.c_oAscAutoFilterTypes.CustomFilters,o[1].asc_getOperator())+' "'+o[1].asc_getVal()+'"')}else if(i===Asc.c_oAscAutoFilterTypes.ColorFilter){var a=e.asc_getFilter();null===a.asc_getCellColor()?n=this.txtEqualsToCellColor:!1===a.asc_getCellColor()&&(n=this.txtEqualsToFontColor)}else if(i===Asc.c_oAscAutoFilterTypes.DynamicFilter)n=this.getFilterName(Asc.c_oAscAutoFilterTypes.DynamicFilter,e.asc_getFilter().asc_getType());else if(i===Asc.c_oAscAutoFilterTypes.Top10){var l=e.asc_getFilter(),r=l.asc_getPercent();n=this.getFilterName(Asc.c_oAscAutoFilterTypes.Top10,l.asc_getTop()),n+=" "+l.asc_getVal()+" "+(r||null===r?this.txtPercent:this.txtItems)}else if(i===Asc.c_oAscAutoFilterTypes.Filters){var c=0,h=0,d=void 0,p=t.asc_getValues();p.forEach(function(t){t.asc_getVisible()&&(h++,c<100&&t.asc_getText()&&(n+=t.asc_getText()+"; ",c=n.length)),t.asc_getText()||(d=t.asc_getVisible())}),h==p.length?n=this.txtAll:1==h&&d?n=this.txtEquals+' "'+this.txtBlanks+'"':h==p.length-1&&0==d?n=this.txtNotEquals+' "'+this.txtBlanks+'"':(d&&(n+=this.txtBlanks+"; "),n=this.txtEquals+' "'+n.substring(0,n.length-2)+'"')}else i===Asc.c_oAscAutoFilterTypes.None&&(n=this.txtAll);return n.length>100&&(n=n.substring(0,100)+"..."),n=""+(t.asc_getColumnName()||"("+this.txtColumn+" "+t.asc_getSheetColumnName()+")")+":
    "+n},getFilterName:function(t,e){var i="";if(t==Asc.c_oAscAutoFilterTypes.CustomFilters)switch(e){case Asc.c_oAscCustomAutoFilter.equals:i=this.txtEquals;break;case Asc.c_oAscCustomAutoFilter.isGreaterThan:i=this.txtGreater;break;case Asc.c_oAscCustomAutoFilter.isGreaterThanOrEqualTo:i=this.txtGreaterEquals;break;case Asc.c_oAscCustomAutoFilter.isLessThan:i=this.txtLess;break;case Asc.c_oAscCustomAutoFilter.isLessThanOrEqualTo:i=this.txtLessEquals;break;case Asc.c_oAscCustomAutoFilter.doesNotEqual:i=this.txtNotEquals;break;case Asc.c_oAscCustomAutoFilter.beginsWith:i=this.txtBegins;break;case Asc.c_oAscCustomAutoFilter.doesNotBeginWith:i=this.txtNotBegins;break;case Asc.c_oAscCustomAutoFilter.endsWith:i=this.txtEnds;break;case Asc.c_oAscCustomAutoFilter.doesNotEndWith:i=this.txtNotEnds;break;case Asc.c_oAscCustomAutoFilter.contains:i=this.txtContains;break;case Asc.c_oAscCustomAutoFilter.doesNotContain:i=this.txtNotContains}else if(t==Asc.c_oAscAutoFilterTypes.DynamicFilter)switch(e){case Asc.c_oAscDynamicAutoFilter.aboveAverage:i=this.txtAboveAve;break;case Asc.c_oAscDynamicAutoFilter.belowAverage:i=this.txtBelowAve}else t==Asc.c_oAscAutoFilterTypes.Top10&&(i=e||null===e?this.txtFilterTop:this.txtFilterBottom);return i},onUndo:function(){this.api&&(this.api.asc_Undo(),Common.NotificationCenter.trigger("edit:complete",this.documentHolder))},onApiContextMenu:function(t){var e=this;_.delay(function(){e.showObjectMenu.call(e,t)},10)},onAfterRender:function(t){},onDocumentResize:function(t){var e=this;e.documentHolder&&(e.tooltips.coauth.XY=[e.documentHolder.cmpEl.offset().left-$(window).scrollLeft(),e.documentHolder.cmpEl.offset().top-$(window).scrollTop()],e.tooltips.coauth.apiHeight=e.documentHolder.cmpEl.height(),e.tooltips.coauth.rightMenuWidth=$("#right-menu").width(),e.tooltips.coauth.bodyWidth=$(window).width(),e.tooltips.coauth.bodyHeight=$(window).height())},onDocumentWheel:function(t){if(this.api&&!this.isEditCell){var e=_.isUndefined(t.originalEvent)?t.wheelDelta:t.originalEvent.wheelDelta;if(_.isUndefined(e)&&(e=t.deltaY),(t.ctrlKey||t.metaKey)&&!t.altKey){var i=this.api.asc_getZoom();e<0?(i=Math.ceil(10*i)/10,(i-=.1)<.5||this.api.asc_setZoom(i)):e>0&&(i=Math.floor(10*i)/10,(i+=.1)>0&&!(i>2)&&this.api.asc_setZoom(i)),t.preventDefault(),t.stopPropagation()}}},onDocumentKeyDown:function(t){if(this.api){var e=t.keyCode;if(!t.ctrlKey&&!t.metaKey||t.shiftKey||t.altKey){if(e==Common.UI.Keys.F10&&t.shiftKey)return this.showObjectMenu(t),t.preventDefault(),t.stopPropagation(),!1}else if(e===Common.UI.Keys.NUM_PLUS||e===Common.UI.Keys.EQUALITY||Common.Utils.isGecko&&e===Common.UI.Keys.EQUALITY_FF||Common.Utils.isOpera&&43==e){if(!this.api.isCellEdited){var i=Math.floor(10*this.api.asc_getZoom())/10;return i+=.1,i>0&&!(i>2)&&this.api.asc_setZoom(i),t.preventDefault(),t.stopPropagation(),!1}}else if(e===Common.UI.Keys.NUM_MINUS||e===Common.UI.Keys.MINUS||Common.Utils.isGecko&&e===Common.UI.Keys.MINUS_FF||Common.Utils.isOpera&&45==e){if(!this.api.isCellEdited)return i=Math.ceil(10*this.api.asc_getZoom())/10,i-=.1,i<.5||this.api.asc_setZoom(i),t.preventDefault(),t.stopPropagation(),!1}else if((48===e||96===e)&&!this.api.isCellEdited)return this.api.asc_setZoom(1),t.preventDefault(),t.stopPropagation(),!1}},onDocumentRightDown:function(t){0==t.button&&(this.mouse.isLeftButtonDown=!0)},onDocumentRightUp:function(t){0==t.button&&(this.mouse.isLeftButtonDown=!1)},onProcessMouse:function(t){"mouseup"==t.type&&(this.mouse.isLeftButtonDown=!1)},onDragEndMouseUp:function(){this.mouse.isLeftButtonDown=!1},onDocumentMouseMove:function(t){"canvas"!==t.target.localName&&this.hideHyperlinkTip()},showObjectMenu:function(t){!this.api||this.mouse.isLeftButtonDown||this.rangeSelectionMode||(this.permissions.isEdit&&!this._isDisabled?this.fillMenuProps(this.api.asc_getCellInfo(),!0,t):this.fillViewMenuProps(this.api.asc_getCellInfo(),!0,t))},onSelectionChanged:function(t){!this.mouse.isLeftButtonDown&&!this.rangeSelectionMode&&this.currentMenu&&this.currentMenu.isVisible()&&(this.permissions.isEdit&&!this._isDisabled?this.fillMenuProps(t,!0):this.fillViewMenuProps(t,!0))},fillMenuProps:function(t,e,i){var n,s,o,a,l,r,c,h,d,p,m,u=this.documentHolder,g=t.asc_getSelectionType(),b=t.asc_getLocked(),f=!0===t.asc_getLockedTable(),C=!1,v=this.getApplication().getController("Common.Controllers.Comments"),y=this.permissions.isEditMailMerge||this.permissions.isEditDiagram,x=t.asc_getXfs();switch(g){case Asc.c_oAscSelectionType.RangeCells:n=!0;break;case Asc.c_oAscSelectionType.RangeRow:s=!0;break;case Asc.c_oAscSelectionType.RangeCol:o=!0;break;case Asc.c_oAscSelectionType.RangeMax:a=!0;break;case Asc.c_oAscSelectionType.RangeSlicer:case Asc.c_oAscSelectionType.RangeImage:r=!y;break;case Asc.c_oAscSelectionType.RangeShape:h=!y;break;case Asc.c_oAscSelectionType.RangeChart:l=!y;break;case Asc.c_oAscSelectionType.RangeChartText:d=!y;break;case Asc.c_oAscSelectionType.RangeShapeText:c=!y}if(this.api.asc_getHeaderFooterMode()){if(!u.copyPasteMenu||!e&&!u.copyPasteMenu.isVisible())return;e&&this.showPopupMenu(u.copyPasteMenu,{},i)}else if(r||h||l){if(!u.imgMenu||!e&&!u.imgMenu.isVisible())return;r=h=l=m=!1,u.mnuImgAdvanced.imageInfo=void 0;for(var w,S=!1,A=this.api.asc_getGraphicObjectProps(),k=0;k-1),u.menuImageArrange.setDisabled(C),u.menuImgRotate.setVisible(!(l||null!==P&&void 0!==P||m)),u.menuImgRotate.setDisabled(C),u.menuImgCrop.setVisible(this.api.asc_canEditCrop()),u.menuImgCrop.setDisabled(C);var V=!!w;u.menuSignatureEditSign.setVisible(V),u.menuSignatureEditSetup.setVisible(V),u.menuEditSignSeparator.setVisible(V),e&&this.showPopupMenu(u.imgMenu,{},i),u.mnuShapeSeparator.setVisible(u.mnuShapeAdvanced.isVisible()||u.mnuChartEdit.isVisible()||u.mnuImgAdvanced.isVisible()),u.mnuSlicerSeparator.setVisible(u.mnuSlicerAdvanced.isVisible()),V&&(u.menuSignatureEditSign.cmpEl.attr("data-value",w),u.menuSignatureEditSetup.cmpEl.attr("data-value",w))}else if(c||d){if(!u.textInShapeMenu||!e&&!u.textInShapeMenu.isVisible())return;u.pmiTextAdvanced.textInfo=void 0;for(var A=this.api.asc_getGraphicObjectProps(),M=!1,k=0;k0){n.asc_setFilter(new Asc.ColorFilter),n.asc_setType(Asc.c_oAscAutoFilterTypes.ColorFilter);var s=n.asc_getFilter();s.asc_setCellColor(1==e.value&&null),s.asc_setCColor(1==e.value?this.documentHolder.ssMenu.cellColor:this.documentHolder.ssMenu.fontColor)}else{n.asc_setFilter(new Asc.CustomFilters),n.asc_setType(Asc.c_oAscAutoFilterTypes.CustomFilters);var o=n.asc_getFilter();o.asc_setCustomFilters([new Asc.CustomFilter]),o.asc_setAnd(!0);o.asc_getCustomFilters()[0].asc_setOperator(Asc.c_oAscCustomAutoFilter.equals)}i.asc_setFilterObj(n),this.api.asc_applyAutoFilterByType(i),Common.NotificationCenter.trigger("edit:complete",this.documentHolder),Common.component.Analytics.trackEvent("DocumentHolder","Filter Cells")}},onReapply:function(){this.api.asc_reapplyAutoFilter(this.documentHolder.ssMenu.formatTableName)},onClear:function(t,e){this.api&&(this.api.asc_emptyCells(e.value),Common.NotificationCenter.trigger("edit:complete",this.documentHolder),Common.component.Analytics.trackEvent("DocumentHolder","Clear"))},onSelectTable:function(t,e){this.api&&this.documentHolder.ssMenu.formatTableName&&(this.api.asc_changeSelectionFormatTable(this.documentHolder.ssMenu.formatTableName,e.value),Common.NotificationCenter.trigger("edit:complete",this.documentHolder),Common.component.Analytics.trackEvent("DocumentHolder","Select Table"))},onInsertTable:function(t,e){this.api&&this.documentHolder.ssMenu.formatTableName&&(this.api.asc_insertCellsInTable(this.documentHolder.ssMenu.formatTableName,e.value),Common.NotificationCenter.trigger("edit:complete",this.documentHolder),Common.component.Analytics.trackEvent("DocumentHolder","Insert to Table"))},onDeleteTable:function(t,e){this.api&&this.documentHolder.ssMenu.formatTableName&&(this.api.asc_deleteCellsInTable(this.documentHolder.ssMenu.formatTableName,e.value),Common.NotificationCenter.trigger("edit:complete",this.documentHolder),Common.component.Analytics.trackEvent("DocumentHolder","Delete from Table"))},onInsFunction:function(t){var e=this.getApplication().getController("FormulaDialog");e&&this.api&&e.showDialog(void 0,t.value==Asc.ETotalsRowFunction.totalrowfunctionCustom)},onInsHyperlink:function(t){var e,i,n=this;if(n.api){for(var s=n.api.asc_getWorksheetsCount(),o=-1,a=[];++o-1&&e.value<6?(this.api.asc_setSelectedDrawingObjectAlign(e.value),Common.NotificationCenter.trigger("edit:complete",this.documentHolder),Common.component.Analytics.trackEvent("DocumentHolder","Objects Align")):6==e.value?(this.api.asc_DistributeSelectedDrawingObjectHor(),Common.NotificationCenter.trigger("edit:complete",this.documentHolder),Common.component.Analytics.trackEvent("DocumentHolder","Distribute")):7==e.value&&(this.api.asc_DistributeSelectedDrawingObjectVer(),Common.NotificationCenter.trigger("edit:complete",this.documentHolder),Common.component.Analytics.trackEvent("DocumentHolder","Distribute")))},onParagraphVAlign:function(t,e){if(this.api){var i=new Asc.asc_CImgProperty;i.asc_putVerticalTextAlign(e.value),this.api.asc_setGraphicObjectProps(i),Common.NotificationCenter.trigger("edit:complete",this.documentHolder),Common.component.Analytics.trackEvent("DocumentHolder","Paragraph Vertical Align")}},onParagraphDirection:function(t,e){if(this.api){var i=new Asc.asc_CImgProperty;i.asc_putVert(e.options.direction),this.api.asc_setGraphicObjectProps(i),Common.NotificationCenter.trigger("edit:complete",this.documentHolder),Common.component.Analytics.trackEvent("DocumentHolder","Text Direction")}},onSelectBulletMenu:function(t,e){if(this.api)if(-1==e.options.value)this.api.asc_setListType(0,e.options.value),Common.NotificationCenter.trigger("edit:complete",this.documentHolder),Common.component.Analytics.trackEvent("DocumentHolder","List Type");else if("settings"==e.options.value){for(var i,n=this,s=n.api.asc_getGraphicObjectProps(),o=0;o0;r--)switch(t[r-1].asc_getType()){case Asc.c_oAscMouseMoveType.Hyperlink:e=r;break;case Asc.c_oAscMouseMoveType.Comment:i=r;break;case Asc.c_oAscMouseMoveType.LockedObject:n=r;break;case Asc.c_oAscMouseMoveType.ResizeColumn:s=r;break;case Asc.c_oAscMouseMoveType.ResizeRow:o=r;break;case Asc.c_oAscMouseMoveType.Filter:a=r;break;case Asc.c_oAscMouseMoveType.Tooltip:l=r}var c=this,h=[0,0],d=c.tooltips.coauth,p=c.tooltips.comment,m=c.tooltips.hyperlink,u=c.tooltips.row_column,g=c.tooltips.filter,b=c.tooltips.slicer,f=[c.documentHolder.cmpEl.offset().left-$(window).scrollLeft(),c.documentHolder.cmpEl.offset().top-$(window).scrollTop()];if(e||c.hideHyperlinkTip(),void 0===s&&void 0===o&&!u.isHidden&&u.ref&&(u.ref.hide(),u.ref=void 0,u.text="",u.isHidden=!0),(c.permissions.isEdit||c.permissions.canViewComments)&&(!i||this.popupmenu)&&(p.moveCommentId=void 0,void 0!=p.viewCommentId)){p={};var C=this.getApplication().getController("Common.Controllers.Comments");C&&(this.permissions.canCoAuthoring&&this.permissions.canViewComments?setTimeout(function(){C.onApiHideComment(!0)},200):C.onApiHideComment(!0))}c.permissions.isEdit&&(n||c.hideCoAuthTips(),void 0===l&&!b.isHidden&&b.ref&&(b.ref.hide(),b.ref=void 0,b.text="",b.isHidden=!0)),(void 0===a||c.dlgFilter&&c.dlgFilter.isVisible()||c.currentMenu&&c.currentMenu.isVisible())&&!g.isHidden&&g.ref&&(g.ref.hide(),g.ref=void 0,g.text="",g.isHidden=!0);if(e){m.parentEl||(m.parentEl=$('
    '),c.documentHolder.cmpEl.append(m.parentEl));var v=t[e-1],_=v.asc_getHyperlink();if(_.asc_getType()==Asc.c_oAscHyperlinkType.WebLink){var y=_.asc_getTooltip();y=y?Common.Utils.String.htmlEncode(y)+"
    "+c.textCtrlClick+"":Common.Utils.String.htmlEncode(_.asc_getHyperlinkUrl())+"
    "+c.textCtrlClick+""}else y=Common.Utils.String.htmlEncode(_.asc_getTooltip()||_.asc_getLocation()),y+="
    "+c.textCtrlClick+"";if(m.ref&&m.ref.isVisible()&&m.text!=y&&(m.ref.hide(),m.ref=void 0,m.text="",m.isHidden=!0),!m.ref||!m.ref.isVisible()){m.text=y,m.ref=new Common.UI.Tooltip({owner:m.parentEl,html:!0,title:y}),m.ref.show([-1e4,-1e4]),m.isHidden=!1,h=[v.asc_getX(),v.asc_getY()],h[0]+=f[0]+6,h[1]+=f[1]-20,h[1]-=m.ref.getBSTip().$tip.height();var x=m.ref.getBSTip().$tip.width();h[0]+x>c.tooltips.coauth.bodyWidth&&(h[0]=c.tooltips.coauth.bodyWidth-x),m.ref.getBSTip().$tip.css({top:h[1]+"px",left:h[0]+"px"})}}if(void 0!==s||void 0!==o){u.parentEl||(u.parentEl=$('
    '),c.documentHolder.cmpEl.append(u.parentEl));var v=t[void 0!==s?s-1:o-1],w=Common.Utils.String.format(void 0!==s?this.textChangeColumnWidth:this.textChangeRowHeight,v.asc_getSizeCCOrPt().toFixed(2),v.asc_getSizePx().toFixed());if(u.ref&&u.ref.isVisible()&&u.text!=w&&(u.text=w,u.ref.setTitle(w),u.ref.updateTitle()),!u.ref||!u.ref.isVisible()){u.text=w,u.ref=new Common.UI.Tooltip({owner:u.parentEl,html:!0,title:w}),u.ref.show([-1e4,-1e4]),u.isHidden=!1,h=[v.asc_getX(),v.asc_getY()],h[0]+=f[0]+6,h[1]+=f[1]-20-u.ttHeight;var x=u.ref.getBSTip().$tip.width();h[0]+x>c.tooltips.coauth.bodyWidth&&(h[0]=c.tooltips.coauth.bodyWidth-x-20),u.ref.getBSTip().$tip.css({top:h[1]+"px",left:h[0]+"px"})}}if((c.permissions.isEdit||c.permissions.canViewComments)&&i&&!this.popupmenu&&(v=t[i-1],!p.editCommentId&&p.moveCommentId!=v.asc_getCommentIndexes()[0])){p.moveCommentId=v.asc_getCommentIndexes()[0],p.moveCommentTimer&&clearTimeout(p.moveCommentTimer);var S=v.asc_getCommentIndexes(),A=v.asc_getX(),k=v.asc_getY(),T=v.asc_getReverseX();p.moveCommentTimer=setTimeout(function(){if(p.moveCommentId&&!p.editCommentId){p.viewCommentId=p.moveCommentId;var t=c.getApplication().getController("Common.Controllers.Comments");t&&(t.isSelectedComment||t.onApiShowComment(S,A,k,T,!1,!0))}},400)}if(c.permissions.isEdit&&n&&(v=t[n-1],d.XY||c.onDocumentResize(),d.x_point!=v.asc_getX()||d.y_point!=v.asc_getY())){c.hideCoAuthTips(),d.x_point=v.asc_getX(),d.y_point=v.asc_getY();var I=$(document.createElement("div")),E=v.asc_getLockedObjectType()==Asc.c_oAscMouseMoveLockedObjectType.Sheet||v.asc_getLockedObjectType()==Asc.c_oAscMouseMoveLockedObjectType.TableProperties;d.ref=I,I.addClass("username-tip"),I.css({height:d.ttHeight+"px",position:"absolute",zIndex:"900",visibility:"visible"}),$(document.body).append(I),h=[E?d.x_point+d.rightMenuWidth:d.bodyWidth-(d.x_point+d.XY[0]),d.y_point+d.XY[1]],h[1]>=d.XY[1]&&h[1]+d.ttHeight'),c.documentHolder.cmpEl.append(g.parentEl));var v=t[a-1],w=c.makeFilterTip(v.asc_getFilter());if(g.ref&&g.ref.isVisible()&&g.text!=w&&(g.text=w,g.ref.setTitle(w),g.ref.updateTitle()),!g.ref||!g.ref.isVisible()){g.text=w,g.ref=new Common.UI.Tooltip({owner:g.parentEl,html:!0,title:w,cls:"auto-tooltip"}),g.ref.show([-1e4,-1e4]),g.isHidden=!1,h=[v.asc_getX()+f[0]-10,v.asc_getY()+f[1]+20];g.ref.getBSTip().$tip.width();h[1]+g.ttHeight>c.tooltips.coauth.bodyHeight&&(h[1]=c.tooltips.coauth.bodyHeight-g.ttHeight-5,h[0]+=20);var x=g.ref.getBSTip().$tip.width();h[0]+x>c.tooltips.coauth.bodyWidth&&(h[0]=c.tooltips.coauth.bodyWidth-x-20),g.ref.getBSTip().$tip.css({top:h[1]+"px",left:h[0]+"px"})}}if(void 0!==l&&c.permissions.isEdit){b.parentEl||(b.parentEl=$('
    '),c.documentHolder.cmpEl.append(b.parentEl));var v=t[l-1],w=v.asc_getTooltip();if(b.ref&&b.ref.isVisible()&&b.text!=w&&(b.text=w,b.ref.setTitle(w),b.ref.updateTitle()),!b.ref||!b.ref.isVisible()){b.text=w,b.ref=new Common.UI.Tooltip({owner:b.parentEl,html:!0,title:w}),b.ref.show([-1e4,-1e4]),b.isHidden=!1,h=[v.asc_getX(),v.asc_getY()],h[0]+=f[0]+6,h[1]+=f[1]-20-b.ttHeight;var x=b.ref.getBSTip().$tip.width();h[0]+x>c.tooltips.coauth.bodyWidth&&(h[0]=c.tooltips.coauth.bodyWidth-x-20),b.ref.getBSTip().$tip.css({top:h[1]+"px",left:h[0]+"px"})}}}},onApiHideComment:function(){this.tooltips.comment.viewCommentId=this.tooltips.comment.editCommentId=this.tooltips.comment.moveCommentId=void 0},onApiHyperlinkClick:function(t){if(!t)return void Common.UI.alert({msg:this.errorInvalidLink,title:this.notcriticalErrorTitle,iconCls:"warn",buttons:["ok"],callback:_.bind(function(t){Common.NotificationCenter.trigger("edit:complete",this.documentHolder)},this)});try{window.parent.APP.openURL(t)}catch(i){console.error(i);var e=window.open(t,"_blank");e&&e.focus()}},onApiAutofilter:function(t){var e=this;if(!e.tooltips.filter.isHidden&&e.tooltips.filter.ref&&(e.tooltips.filter.ref.hide(),e.tooltips.filter.ref=void 0,e.tooltips.filter.text="",e.tooltips.filter.isHidden=!0),e.permissions.isEdit)if(e.dlgFilter)e.dlgFilter.close();else{e.dlgFilter=new SSE.Views.AutoFilterDialog({api:this.api}).on({close:function(){e.api&&e.api.asc_enableKeyEvents(!0),e.dlgFilter=void 0}}),e.api&&e.api.asc_enableKeyEvents(!1),Common.UI.Menu.Manager.hideAll(),e.dlgFilter.setSettings(t);var i=e.documentHolder.cmpEl.offset(),n=t.asc_getCellCoord(),s=n.asc_getX()+n.asc_getWidth()+i.left,o=n.asc_getY()+n.asc_getHeight()+i.top,a=Common.Utils.innerWidth(),l=Common.Utils.innerHeight();s+e.dlgFilter.options.width>a&&(s=a-e.dlgFilter.options.width-5),o+e.dlgFilter.options.height>l&&(o=l-e.dlgFilter.options.height-5),e.dlgFilter.show(s,o)}},makeFilterTip:function(t){var e=t.asc_getFilterObj(),i=e.asc_getType(),n=(t.asc_getIsTextFilter(),t.asc_getColorsFill(),t.asc_getColorsFont(),"");if(i===Asc.c_oAscAutoFilterTypes.CustomFilters){var s=e.asc_getFilter(),o=s.asc_getCustomFilters();n=this.getFilterName(Asc.c_oAscAutoFilterTypes.CustomFilters,o[0].asc_getOperator())+' "'+o[0].asc_getVal()+'"',o.length>1&&(n=n+" "+(s.asc_getAnd()?this.txtAnd:this.txtOr),n=n+" "+this.getFilterName(Asc.c_oAscAutoFilterTypes.CustomFilters,o[1].asc_getOperator())+' "'+o[1].asc_getVal()+'"')}else if(i===Asc.c_oAscAutoFilterTypes.ColorFilter){var a=e.asc_getFilter();null===a.asc_getCellColor()?n=this.txtEqualsToCellColor:!1===a.asc_getCellColor()&&(n=this.txtEqualsToFontColor)}else if(i===Asc.c_oAscAutoFilterTypes.DynamicFilter)n=this.getFilterName(Asc.c_oAscAutoFilterTypes.DynamicFilter,e.asc_getFilter().asc_getType());else if(i===Asc.c_oAscAutoFilterTypes.Top10){var l=e.asc_getFilter(),r=l.asc_getPercent();n=this.getFilterName(Asc.c_oAscAutoFilterTypes.Top10,l.asc_getTop()),n+=" "+l.asc_getVal()+" "+(r||null===r?this.txtPercent:this.txtItems)}else if(i===Asc.c_oAscAutoFilterTypes.Filters){var c=0,h=0,d=void 0,p=t.asc_getValues();p.forEach(function(t){t.asc_getVisible()&&(h++,c<100&&t.asc_getText()&&(n+=t.asc_getText()+"; ",c=n.length)),t.asc_getText()||(d=t.asc_getVisible())}),h==p.length?n=this.txtAll:1==h&&d?n=this.txtEquals+' "'+this.txtBlanks+'"':h==p.length-1&&0==d?n=this.txtNotEquals+' "'+this.txtBlanks+'"':(d&&(n+=this.txtBlanks+"; "),n=this.txtEquals+' "'+n.substring(0,n.length-2)+'"')}else i===Asc.c_oAscAutoFilterTypes.None&&(n=this.txtAll);return n.length>100&&(n=n.substring(0,100)+"..."),n=""+(t.asc_getColumnName()||"("+this.txtColumn+" "+t.asc_getSheetColumnName()+")")+":
    "+n},getFilterName:function(t,e){var i="";if(t==Asc.c_oAscAutoFilterTypes.CustomFilters)switch(e){case Asc.c_oAscCustomAutoFilter.equals:i=this.txtEquals;break;case Asc.c_oAscCustomAutoFilter.isGreaterThan:i=this.txtGreater;break;case Asc.c_oAscCustomAutoFilter.isGreaterThanOrEqualTo:i=this.txtGreaterEquals;break;case Asc.c_oAscCustomAutoFilter.isLessThan:i=this.txtLess;break;case Asc.c_oAscCustomAutoFilter.isLessThanOrEqualTo:i=this.txtLessEquals;break;case Asc.c_oAscCustomAutoFilter.doesNotEqual:i=this.txtNotEquals;break;case Asc.c_oAscCustomAutoFilter.beginsWith:i=this.txtBegins;break;case Asc.c_oAscCustomAutoFilter.doesNotBeginWith:i=this.txtNotBegins;break;case Asc.c_oAscCustomAutoFilter.endsWith:i=this.txtEnds;break;case Asc.c_oAscCustomAutoFilter.doesNotEndWith:i=this.txtNotEnds;break;case Asc.c_oAscCustomAutoFilter.contains:i=this.txtContains;break;case Asc.c_oAscCustomAutoFilter.doesNotContain:i=this.txtNotContains}else if(t==Asc.c_oAscAutoFilterTypes.DynamicFilter)switch(e){case Asc.c_oAscDynamicAutoFilter.aboveAverage:i=this.txtAboveAve;break;case Asc.c_oAscDynamicAutoFilter.belowAverage:i=this.txtBelowAve}else t==Asc.c_oAscAutoFilterTypes.Top10&&(i=e||null===e?this.txtFilterTop:this.txtFilterBottom);return i},onUndo:function(){this.api&&(this.api.asc_Undo(),Common.NotificationCenter.trigger("edit:complete",this.documentHolder))},onApiContextMenu:function(t){var e=this;_.delay(function(){e.showObjectMenu.call(e,t)},10)},onAfterRender:function(t){},onDocumentResize:function(t){var e=this;e.documentHolder&&(e.tooltips.coauth.XY=[e.documentHolder.cmpEl.offset().left-$(window).scrollLeft(),e.documentHolder.cmpEl.offset().top-$(window).scrollTop()],e.tooltips.coauth.apiHeight=e.documentHolder.cmpEl.height(),e.tooltips.coauth.rightMenuWidth=$("#right-menu").width(),e.tooltips.coauth.bodyWidth=$(window).width(),e.tooltips.coauth.bodyHeight=$(window).height())},onDocumentWheel:function(t){if(this.api&&!this.isEditCell){var e=_.isUndefined(t.originalEvent)?t.wheelDelta:t.originalEvent.wheelDelta;if(_.isUndefined(e)&&(e=t.deltaY),(t.ctrlKey||t.metaKey)&&!t.altKey){var i=this.api.asc_getZoom();e<0?(i=Math.ceil(10*i)/10,(i-=.1)<.5||this.api.asc_setZoom(i)):e>0&&(i=Math.floor(10*i)/10,(i+=.1)>0&&!(i>2)&&this.api.asc_setZoom(i)),t.preventDefault(),t.stopPropagation()}}},onDocumentKeyDown:function(t){if(this.api){var e=t.keyCode;if(!t.ctrlKey&&!t.metaKey||t.shiftKey||t.altKey){if(e==Common.UI.Keys.F10&&t.shiftKey)return this.showObjectMenu(t),t.preventDefault(),t.stopPropagation(),!1}else if(e===Common.UI.Keys.NUM_PLUS||e===Common.UI.Keys.EQUALITY||Common.Utils.isGecko&&e===Common.UI.Keys.EQUALITY_FF||Common.Utils.isOpera&&43==e){if(!this.api.isCellEdited){var i=Math.floor(10*this.api.asc_getZoom())/10;return i+=.1,i>0&&!(i>2)&&this.api.asc_setZoom(i),t.preventDefault(),t.stopPropagation(),!1}}else if(e===Common.UI.Keys.NUM_MINUS||e===Common.UI.Keys.MINUS||Common.Utils.isGecko&&e===Common.UI.Keys.MINUS_FF||Common.Utils.isOpera&&45==e){if(!this.api.isCellEdited)return i=Math.ceil(10*this.api.asc_getZoom())/10,i-=.1,i<.5||this.api.asc_setZoom(i),t.preventDefault(),t.stopPropagation(),!1}else if((48===e||96===e)&&!this.api.isCellEdited)return this.api.asc_setZoom(1),t.preventDefault(),t.stopPropagation(),!1}},onDocumentRightDown:function(t){0==t.button&&(this.mouse.isLeftButtonDown=!0)},onDocumentRightUp:function(t){0==t.button&&(this.mouse.isLeftButtonDown=!1)},onProcessMouse:function(t){"mouseup"==t.type&&(this.mouse.isLeftButtonDown=!1)},onDragEndMouseUp:function(){this.mouse.isLeftButtonDown=!1},onDocumentMouseMove:function(t){"canvas"!==t.target.localName&&this.hideHyperlinkTip()},showObjectMenu:function(t){!this.api||this.mouse.isLeftButtonDown||this.rangeSelectionMode||(this.permissions.isEdit&&!this._isDisabled?this.fillMenuProps(this.api.asc_getCellInfo(),!0,t):this.fillViewMenuProps(this.api.asc_getCellInfo(),!0,t))},onSelectionChanged:function(t){!this.mouse.isLeftButtonDown&&!this.rangeSelectionMode&&this.currentMenu&&this.currentMenu.isVisible()&&(this.permissions.isEdit&&!this._isDisabled?this.fillMenuProps(t,!0):this.fillViewMenuProps(t,!0))},fillMenuProps:function(t,e,i){var n,s,o,a,l,r,c,h,d,p,m,u=this.documentHolder,g=t.asc_getSelectionType(),b=t.asc_getLocked(),f=!0===t.asc_getLockedTable(),C=!1,v=this.getApplication().getController("Common.Controllers.Comments"),y=this.permissions.isEditMailMerge||this.permissions.isEditDiagram,x=t.asc_getXfs();switch(g){case Asc.c_oAscSelectionType.RangeCells:n=!0;break;case Asc.c_oAscSelectionType.RangeRow:s=!0;break;case Asc.c_oAscSelectionType.RangeCol:o=!0;break;case Asc.c_oAscSelectionType.RangeMax:a=!0;break;case Asc.c_oAscSelectionType.RangeSlicer:case Asc.c_oAscSelectionType.RangeImage:r=!y;break;case Asc.c_oAscSelectionType.RangeShape:h=!y;break;case Asc.c_oAscSelectionType.RangeChart:l=!y;break;case Asc.c_oAscSelectionType.RangeChartText:d=!y;break;case Asc.c_oAscSelectionType.RangeShapeText:c=!y}if(this.api.asc_getHeaderFooterMode()){if(!u.copyPasteMenu||!e&&!u.copyPasteMenu.isVisible())return;e&&this.showPopupMenu(u.copyPasteMenu,{},i)}else if(r||h||l){if(!u.imgMenu||!e&&!u.imgMenu.isVisible())return;r=h=l=m=!1,u.mnuImgAdvanced.imageInfo=void 0;for(var w,S=!1,A=this.api.asc_getGraphicObjectProps(),k=0;k-1),u.menuImageArrange.setDisabled(C),u.menuImgRotate.setVisible(!(l||null!==P&&void 0!==P||m)),u.menuImgRotate.setDisabled(C),u.menuImgCrop.setVisible(this.api.asc_canEditCrop()),u.menuImgCrop.setDisabled(C);var V=!!w;u.menuSignatureEditSign.setVisible(V),u.menuSignatureEditSetup.setVisible(V),u.menuEditSignSeparator.setVisible(V),e&&this.showPopupMenu(u.imgMenu,{},i),u.mnuShapeSeparator.setVisible(u.mnuShapeAdvanced.isVisible()||u.mnuChartEdit.isVisible()||u.mnuImgAdvanced.isVisible()),u.mnuSlicerSeparator.setVisible(u.mnuSlicerAdvanced.isVisible()),V&&(u.menuSignatureEditSign.cmpEl.attr("data-value",w),u.menuSignatureEditSetup.cmpEl.attr("data-value",w))}else if(c||d){if(!u.textInShapeMenu||!e&&!u.textInShapeMenu.isVisible())return;u.pmiTextAdvanced.textInfo=void 0;for(var A=this.api.asc_getGraphicObjectProps(),M=!1,k=0;k',t.id)),s.cmpEl.append(a)),t.render(a),t.cmpEl.attr({tabindex:"-1"})),2!==i.button){var l=n.api.asc_getActiveCellCoord(),r={left:0,top:0};o[0]=l.asc_getX()+l.asc_getWidth()+r.left,o[1]=(l.asc_getY()<0?0:l.asc_getY())+l.asc_getHeight()+r.top}a.css({left:o[0],top:o[1]}),_.isFunction(t.options.initMenu)&&(t.options.initMenu(e),t.alignPosition()),_.delay(function(){t.cmpEl.focus()},10),t.show(),n.currentMenu=t}},onEntriesListMenu:function(t,e,i){if(e&&e.length>0){var n=this,s=n.documentHolder,o=s.entriesMenu,a=s.cmpEl.find(Common.Utils.String.format("#menu-container-{0}",o.id));if(t&&o.isVisible())return void o.hide();for(var l=0;l',o.id)),s.cmpEl.append(a)),o.render(a),o.cmpEl.attr({tabindex:"-1"}));var r=n.api.asc_getActiveCellCoord(),c={left:0,top:0},h=[r.asc_getX()+c.left,(r.asc_getY()<0?0:r.asc_getY())+r.asc_getHeight()+c.top];a.css({left:h[0],top:h[1]}),n._preventClick=t,t&&a.attr("data-value","prevent-canvas-click"),o.show(),o.alignPosition(),_.delay(function(){o.cmpEl.focus()},10)}else this.documentHolder.entriesMenu.hide(),!t&&Common.UI.warning({title:this.notcriticalErrorTitle,maxwidth:600,msg:this.txtNoChoices,callback:_.bind(function(t){Common.NotificationCenter.trigger("edit:complete",this.documentHolder)},this)})},onTableTotalMenu:function(t){if(void 0!==t){var e=this,i=e.documentHolder,n=i.tableTotalMenu,s=i.cmpEl.find(Common.Utils.String.format("#menu-container-{0}",n.id));if(n.isVisible())return void n.hide();Common.UI.Menu.Manager.hideAll(),n.rendered||(s.length<1&&(s=$(Common.Utils.String.format('',n.id)),i.cmpEl.append(s)),n.render(s),n.cmpEl.attr({tabindex:"-1"})),n.clearAll();var o=_.find(n.items,function(e){return e.value==t});o&&o.setChecked(!0,!0);var a=e.api.asc_getActiveCellCoord(),l={left:0,top:0},r=[a.asc_getX()+l.left,(a.asc_getY()<0?0:a.asc_getY())+a.asc_getHeight()+l.top];s.css({left:r[0],top:r[1]}),e._preventClick=!0,s.attr("data-value","prevent-canvas-click"),n.show(),n.alignPosition(),_.delay(function(){n.cmpEl.focus()},10)}else this.documentHolder.tableTotalMenu.hide()},onTotalMenuClick:function(t,e){e.value==Asc.ETotalsRowFunction.totalrowfunctionCustom?this.onInsFunction(e):this.api.asc_insertInCell(e.value,Asc.c_oAscPopUpSelectorType.TotalRowFunc),Common.NotificationCenter.trigger("edit:complete",this.documentHolder)},onFormulaCompleteMenu:function(t){if(this.documentHolder.funcMenu&&!Common.Utils.ModalWindow.isVisible()&&!this.rangeSelectionMode)if(t){for(var e=this,i=e.documentHolder,n=i.funcMenu,s=i.cmpEl.find("#menu-formula-selection"),o=e.getApplication().getController("FormulaDialog").getDescription(Common.Utils.InternalSettings.get("sse-settings-func-locale")),a=0;an?1:0}),_.each(t,function(t,i){var s=t.asc_getType(),a=t.asc_getName(!0),l=e.api.asc_getFormulaNameByLocale(a),r="btn-named-range";switch(s){case Asc.c_oAscPopUpSelectorType.Func:r="btn-function";break;case Asc.c_oAscPopUpSelectorType.Table:r="btn-menu-table";break;case Asc.c_oAscPopUpSelectorType.Slicer:r="btn-slicer"}var c=new Common.UI.MenuItem({iconCls:"menu__icon "+r,caption:a,hint:o&&o[l]?o[l].d:""}).on("click",function(t,i){setTimeout(function(){e.api.asc_insertInCell(t.caption,s,!1)},10)});n.addItem(c)}),n.rendered||(s.length<1&&(s=$(Common.Utils.String.format('')),i.cmpEl.append(s)),n.onAfterKeydownMenu=function(t){if(t.keyCode!=Common.UI.Keys.RETURN||!t.ctrlKey&&!t.altKey){var e;if(arguments.length>1&&arguments[1]instanceof KeyboardEvent&&(t=arguments[1]),s.hasClass("open"))if(t.keyCode==Common.UI.Keys.TAB||t.keyCode==Common.UI.Keys.RETURN&&!t.ctrlKey&&!t.altKey)e=s.find("a.focus").closest("li");else if(t.keyCode==Common.UI.Keys.UP||t.keyCode==Common.UI.Keys.DOWN){var i=n.cmpEl,o=i.offset().top,a=s.find("a.focus").closest("li"),l=a.offset().top;(lo+i.height())&&(n.scroller?n.scroller.scrollTop(i.scrollTop()+l-o,0):i.scrollTop(i.scrollTop()+l-o))}e&&(e.length>0&&e.click(),Common.UI.Menu.Manager.hideAll())}},n.on("hide:after",function(){for(var t=0;t'),this.documentHolder.cmpEl.append(e.parentEl));var i=this.getApplication().getController("FormulaDialog").getDescription(Common.Utils.InternalSettings.get("sse-settings-func-locale")),n=(i&&i[t]?this.api.asc_getFormulaLocaleName(t)+i[t].a:"").replace(/[,;]/g,this.api.asc_getFunctionArgumentSeparator());if(e.ref&&e.ref.isVisible()&&e.text!=n&&(e.ref.hide(),e.ref=void 0,e.text="",e.isHidden=!0),!n)return;e.ref&&e.ref.isVisible()||(e.text=n,e.ref=new Common.UI.Tooltip({owner:e.parentEl,html:!0,title:n,cls:"auto-tooltip"}),e.ref.show([-1e4,-1e4]),e.isHidden=!1);var s=[this.documentHolder.cmpEl.offset().left-$(window).scrollLeft(),this.documentHolder.cmpEl.offset().top-$(window).scrollTop()],o=this.api.asc_getActiveCellCoord(),a=[o.asc_getX()+s[0]-3,o.asc_getY()+s[1]-e.ref.getBSTip().$tip.height()-5],l=e.ref.getBSTip().$tip.width();a[0]+l>this.tooltips.coauth.bodyWidth&&(a[0]=this.tooltips.coauth.bodyWidth-l),e.ref.getBSTip().$tip.css({top:a[1]+"px",left:a[0]+"px"})}else!e.isHidden&&e.ref&&(e.ref.hide(),e.ref=void 0,e.text="",e.isHidden=!0)},onInputMessage:function(t,e){var i=this.tooltips.input_msg;if(e){i.parentEl||(i.parentEl=$('
    '),this.documentHolder.cmpEl.append(i.parentEl));var n=t?""+Common.Utils.String.htmlEncode(t||"")+"
    ":"";n+=Common.Utils.String.htmlEncode(e||""),i.ref&&i.ref.isVisible()&&i.text!=n&&(i.ref.hide(),i.ref=void 0,i.text="",i.isHidden=!0),i.ref&&i.ref.isVisible()||(i.text=n,i.ref=new Common.UI.Tooltip({owner:i.parentEl,html:!0,title:n}),i.ref.show([-1e4,-1e4]),i.isHidden=!1);var s=[this.documentHolder.cmpEl.offset().left-$(window).scrollLeft(),this.documentHolder.cmpEl.offset().top-$(window).scrollTop()],o=this.api.asc_getActiveCellCoord(),a=[o.asc_getX()+s[0]-3,o.asc_getY()+s[1]-i.ref.getBSTip().$tip.height()-5],l=i.ref.getBSTip().$tip.width();a[0]+l>this.tooltips.coauth.bodyWidth&&(a[0]=this.tooltips.coauth.bodyWidth-l),i.ref.getBSTip().$tip.css({top:a[1]+"px",left:a[0]+"px","z-index":900})}else!i.isHidden&&i.ref&&(i.ref.hide(),i.ref=void 0,i.text="",i.isHidden=!0)},onShowSpecialPasteOptions:function(t){var e=this,i=e.documentHolder,n=t.asc_getCellCoord(),s=i.cmpEl.find("#special-paste-container"),o=t.asc_getOptions(),a=!!t.asc_getContainTables();if(o){if(s.length<1&&(e._arrSpecialPaste=[],e._arrSpecialPaste[Asc.c_oSpecialPasteProps.paste]=[e.txtPaste,0],e._arrSpecialPaste[Asc.c_oSpecialPasteProps.pasteOnlyFormula]=[e.txtPasteFormulas,0],e._arrSpecialPaste[Asc.c_oSpecialPasteProps.formulaNumberFormat]=[e.txtPasteFormulaNumFormat,0],e._arrSpecialPaste[Asc.c_oSpecialPasteProps.formulaAllFormatting]=[e.txtPasteKeepSourceFormat,0],e._arrSpecialPaste[Asc.c_oSpecialPasteProps.formulaWithoutBorders]=[e.txtPasteBorders,0],e._arrSpecialPaste[Asc.c_oSpecialPasteProps.formulaColumnWidth]=[e.txtPasteColWidths,0],e._arrSpecialPaste[Asc.c_oSpecialPasteProps.mergeConditionalFormating]=[e.txtPasteMerge,0],e._arrSpecialPaste[Asc.c_oSpecialPasteProps.transpose]=[e.txtPasteTranspose,0],e._arrSpecialPaste[Asc.c_oSpecialPasteProps.pasteOnlyValues]=[e.txtPasteValues,1],e._arrSpecialPaste[Asc.c_oSpecialPasteProps.valueNumberFormat]=[e.txtPasteValNumFormat,1],e._arrSpecialPaste[Asc.c_oSpecialPasteProps.valueAllFormating]=[e.txtPasteValFormat,1],e._arrSpecialPaste[Asc.c_oSpecialPasteProps.pasteOnlyFormating]=[e.txtPasteFormat,2],e._arrSpecialPaste[Asc.c_oSpecialPasteProps.link]=[e.txtPasteLink,2],e._arrSpecialPaste[Asc.c_oSpecialPasteProps.picture]=[e.txtPastePicture,2],e._arrSpecialPaste[Asc.c_oSpecialPasteProps.linkedPicture]=[e.txtPasteLinkPicture,2],e._arrSpecialPaste[Asc.c_oSpecialPasteProps.sourceformatting]=[e.txtPasteSourceFormat,2],e._arrSpecialPaste[Asc.c_oSpecialPasteProps.destinationFormatting]=[e.txtPasteDestFormat,2],e._arrSpecialPaste[Asc.c_oSpecialPasteProps.keepTextOnly]=[e.txtKeepTextOnly,2],e._arrSpecialPaste[Asc.c_oSpecialPasteProps.useTextImport]=[e.txtUseTextImport,3],s=$('
    '),i.cmpEl.append(s),e.btnSpecialPaste=new Common.UI.Button({parentEl:$("#id-document-holder-btn-special-paste"),cls:"btn-toolbar",iconCls:"toolbar__icon btn-paste",menu:new Common.UI.Menu({items:[]})})),o.length>0){for(var l=e.btnSpecialPaste.menu,r=0;r0&&(l.addItem(new Common.UI.MenuItem({caption:"--"})),d=!1),_.each(c[r],function(t,e){l.addItem(t),d=!0});if(l.items.length>0&&l.items[0].setChecked(!0,!0),e._state.lastSpecPasteChecked=l.items.length>0?l.items[0]:null,h&&(l.addItem(new Common.UI.MenuItem({caption:"--"})),l.addItem(h)),l.items.length>0&&t.asc_getShowPasteSpecial()){l.addItem(new Common.UI.MenuItem({caption:"--"}));var p=new Common.UI.MenuItem({caption:e.textPasteSpecial,value:"special"}).on("click",function(t,i){new SSE.Views.SpecialPasteDialog({props:o,isTable:a,handler:function(t,i){"ok"==t&&(e._state.lastSpecPasteChecked&&e._state.lastSpecPasteChecked.setChecked(!1,!0),e._state.lastSpecPasteChecked=i&&e._arrSpecialPaste[i.asc_getProps()]?e._arrSpecialPaste[i.asc_getProps()][2]:null,e._state.lastSpecPasteChecked&&e._state.lastSpecPasteChecked.setChecked(!0,!0),e&&e.api&&e.api.asc_SpecialPaste(i))}}).show(),setTimeout(function(){l.hide()},100)});l.addItem(p)}}if(n[0].asc_getX()<0||n[0].asc_getY()<0)return void(s.is(":visible")&&s.hide());var m=n[0],u=n[1],g=e.tooltips.coauth.bodyWidth-e.tooltips.coauth.XY[0]-e.tooltips.coauth.rightMenuWidth-15,b=e.tooltips.coauth.apiHeight-15,f=[],C=[31,20],v=m.asc_getX()+m.asc_getWidth()+3+C[0],y=m.asc_getY()+m.asc_getHeight()+3+C[1];v>g?(f[0]=void 0!==u?u.asc_getX():g-C[0]-3,y>b&&(f[0]-=C[0]+3),f[0]<0&&(f[0]=g-3-C[0])):f[0]=v-C[0],f[1]=y>b?b-3-C[1]:y-C[1],s.css({left:f[0],top:f[1]}),s.show()}},onHideSpecialPasteOptions:function(){var t=this.documentHolder.cmpEl.find("#special-paste-container");t.is(":visible")&&t.hide()},onToggleAutoCorrectOptions:function(t){if(!t){var e=this.documentHolder.cmpEl.find("#autocorrect-paste-container");return void(e.is(":visible")&&e.hide())}var i=this,n=i.documentHolder,s=t.asc_getCellCoord(),e=n.cmpEl.find("#autocorrect-paste-container"),o=t.asc_getOptions();if(e.length<1&&(i._arrAutoCorrectPaste=[],i._arrAutoCorrectPaste[Asc.c_oAscAutoCorrectOptions.UndoTableAutoExpansion]={caption:i.txtUndoExpansion,icon:"menu__icon btn-undo"},i._arrAutoCorrectPaste[Asc.c_oAscAutoCorrectOptions.RedoTableAutoExpansion]={caption:i.txtRedoExpansion,icon:"menu__icon btn-redo"},e=$('
    '),n.cmpEl.append(e),i.btnAutoCorrectPaste=new Common.UI.Button({parentEl:$("#id-document-holder-btn-autocorrect-paste"),cls:"btn-toolbar",iconCls:"toolbar__icon btn-autocorrect",menu:new Common.UI.Menu({cls:"shifted-right",items:[]})}),i.btnAutoCorrectPaste.menu.on("show:after",_.bind(i.onAutoCorrectOpenAfter,i))),o.length>0){for(var a=i.btnAutoCorrectPaste.menu,l=0;lc||m>h||s.asc_getX()<0||s.asc_getY()<0?e.is(":visible")&&e.hide():(e.css({left:p-d[0],top:m-d[1]}),e.show())},onCellsRange:function(t){this.rangeSelectionMode=t!=Asc.c_oAscSelectionDialogType.None},onApiEditCell:function(t){this.isEditFormula=t==Asc.c_oAscCellEditorState.editFormula,this.isEditCell=t!=Asc.c_oAscCellEditorState.editEnd},onLockDefNameManager:function(t){this.namedrange_locked=t==Asc.c_oAscDefinedNameReason.LockDefNameManager},onChangeCropState:function(t){this.documentHolder.menuImgCrop.menu.items[0].setChecked(t,!0)},initEquationMenu:function(){if(this._currentMathObj){var t,e=this,i=e._currentMathObj.get_Type(),n=e._currentMathObj,s=[];switch(i){case Asc.c_oAscMathInterfaceType.Accent:t=new Common.UI.MenuItem({caption:e.txtRemoveAccentChar,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"remove_AccentCharacter"}}),s.push(t);break;case Asc.c_oAscMathInterfaceType.BorderBox:t=new Common.UI.MenuItem({caption:e.txtBorderProps,equation:!0,disabled:e._currentParaObjDisabled,menu:new Common.UI.Menu({cls:"shifted-right",menuAlign:"tl-tr",items:[{caption:n.get_HideTop()?e.txtAddTop:e.txtHideTop,equationProps:{type:i,callback:"put_HideTop",value:!n.get_HideTop()}},{caption:n.get_HideBottom()?e.txtAddBottom:e.txtHideBottom,equationProps:{type:i,callback:"put_HideBottom",value:!n.get_HideBottom()}},{caption:n.get_HideLeft()?e.txtAddLeft:e.txtHideLeft,equationProps:{type:i,callback:"put_HideLeft",value:!n.get_HideLeft()}},{caption:n.get_HideRight()?e.txtAddRight:e.txtHideRight,equationProps:{type:i,callback:"put_HideRight",value:!n.get_HideRight()}},{caption:n.get_HideHor()?e.txtAddHor:e.txtHideHor,equationProps:{type:i,callback:"put_HideHor",value:!n.get_HideHor()}},{caption:n.get_HideVer()?e.txtAddVer:e.txtHideVer,equationProps:{type:i,callback:"put_HideVer",value:!n.get_HideVer()}},{caption:n.get_HideTopLTR()?e.txtAddLT:e.txtHideLT,equationProps:{type:i,callback:"put_HideTopLTR",value:!n.get_HideTopLTR()}},{caption:n.get_HideTopRTL()?e.txtAddLB:e.txtHideLB,equationProps:{type:i,callback:"put_HideTopRTL",value:!n.get_HideTopRTL()}}]})}),s.push(t);break;case Asc.c_oAscMathInterfaceType.Bar:t=new Common.UI.MenuItem({caption:e.txtRemoveBar,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"remove_Bar"}}),s.push(t),t=new Common.UI.MenuItem({caption:n.get_Pos()==Asc.c_oAscMathInterfaceBarPos.Top?e.txtUnderbar:e.txtOverbar,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"put_Pos",value:n.get_Pos()==Asc.c_oAscMathInterfaceBarPos.Top?Asc.c_oAscMathInterfaceBarPos.Bottom:Asc.c_oAscMathInterfaceBarPos.Top}}),s.push(t);break;case Asc.c_oAscMathInterfaceType.Script:var o=n.get_ScriptType();o==Asc.c_oAscMathInterfaceScript.PreSubSup?(t=new Common.UI.MenuItem({caption:e.txtScriptsAfter,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"put_ScriptType",value:Asc.c_oAscMathInterfaceScript.SubSup}}),s.push(t),t=new Common.UI.MenuItem({caption:e.txtRemScripts,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"put_ScriptType",value:Asc.c_oAscMathInterfaceScript.None}}),s.push(t)):(o==Asc.c_oAscMathInterfaceScript.SubSup&&(t=new Common.UI.MenuItem({caption:e.txtScriptsBefore,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"put_ScriptType",value:Asc.c_oAscMathInterfaceScript.PreSubSup}}),s.push(t)),o!=Asc.c_oAscMathInterfaceScript.SubSup&&o!=Asc.c_oAscMathInterfaceScript.Sub||(t=new Common.UI.MenuItem({caption:e.txtRemSubscript,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"put_ScriptType",value:o==Asc.c_oAscMathInterfaceScript.SubSup?Asc.c_oAscMathInterfaceScript.Sup:Asc.c_oAscMathInterfaceScript.None}}),s.push(t)),o!=Asc.c_oAscMathInterfaceScript.SubSup&&o!=Asc.c_oAscMathInterfaceScript.Sup||(t=new Common.UI.MenuItem({caption:e.txtRemSuperscript,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"put_ScriptType",value:o==Asc.c_oAscMathInterfaceScript.SubSup?Asc.c_oAscMathInterfaceScript.Sub:Asc.c_oAscMathInterfaceScript.None}}),s.push(t)));break;case Asc.c_oAscMathInterfaceType.Fraction:var a=n.get_FractionType();a!=Asc.c_oAscMathInterfaceFraction.Skewed&&a!=Asc.c_oAscMathInterfaceFraction.Linear||(t=new Common.UI.MenuItem({caption:e.txtFractionStacked,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"put_FractionType",value:Asc.c_oAscMathInterfaceFraction.Bar}}),s.push(t)),a!=Asc.c_oAscMathInterfaceFraction.Bar&&a!=Asc.c_oAscMathInterfaceFraction.Linear||(t=new Common.UI.MenuItem({caption:e.txtFractionSkewed,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"put_FractionType",value:Asc.c_oAscMathInterfaceFraction.Skewed}}),s.push(t)),a!=Asc.c_oAscMathInterfaceFraction.Bar&&a!=Asc.c_oAscMathInterfaceFraction.Skewed||(t=new Common.UI.MenuItem({caption:e.txtFractionLinear,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"put_FractionType",value:Asc.c_oAscMathInterfaceFraction.Linear}}),s.push(t)),a!=Asc.c_oAscMathInterfaceFraction.Bar&&a!=Asc.c_oAscMathInterfaceFraction.NoBar||(t=new Common.UI.MenuItem({caption:a==Asc.c_oAscMathInterfaceFraction.Bar?e.txtRemFractionBar:e.txtAddFractionBar,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"put_FractionType",value:a==Asc.c_oAscMathInterfaceFraction.Bar?Asc.c_oAscMathInterfaceFraction.NoBar:Asc.c_oAscMathInterfaceFraction.Bar}}),s.push(t));break;case Asc.c_oAscMathInterfaceType.Limit:t=new Common.UI.MenuItem({caption:n.get_Pos()==Asc.c_oAscMathInterfaceLimitPos.Top?e.txtLimitUnder:e.txtLimitOver,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"put_Pos",value:n.get_Pos()==Asc.c_oAscMathInterfaceLimitPos.Top?Asc.c_oAscMathInterfaceLimitPos.Bottom:Asc.c_oAscMathInterfaceLimitPos.Top}}),s.push(t),t=new Common.UI.MenuItem({caption:e.txtRemLimit,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"put_Pos",value:Asc.c_oAscMathInterfaceLimitPos.None}}),s.push(t);break;case Asc.c_oAscMathInterfaceType.Matrix:t=new Common.UI.MenuItem({caption:n.get_HidePlaceholder()?e.txtShowPlaceholder:e.txtHidePlaceholder,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"put_HidePlaceholder",value:!n.get_HidePlaceholder()}}),s.push(t),t=new Common.UI.MenuItem({caption:e.insertText,equation:!0,disabled:e._currentParaObjDisabled,menu:new Common.UI.Menu({cls:"shifted-right",menuAlign:"tl-tr",items:[{caption:e.insertRowAboveText,equationProps:{type:i,callback:"insert_MatrixRow",value:!0}},{caption:e.insertRowBelowText,equationProps:{type:i,callback:"insert_MatrixRow",value:!1}},{caption:e.insertColumnLeftText,equationProps:{type:i,callback:"insert_MatrixColumn",value:!0}},{caption:e.insertColumnRightText,equationProps:{type:i,callback:"insert_MatrixColumn",value:!1}}]})}),s.push(t),t=new Common.UI.MenuItem({caption:e.deleteText,equation:!0,disabled:e._currentParaObjDisabled,menu:new Common.UI.Menu({cls:"shifted-right",menuAlign:"tl-tr",items:[{ caption:e.deleteRowText,equationProps:{type:i,callback:"delete_MatrixRow"}},{caption:e.deleteColumnText,equationProps:{type:i,callback:"delete_MatrixColumn"}}]})}),s.push(t),t=new Common.UI.MenuItem({caption:e.txtMatrixAlign,equation:!0,disabled:e._currentParaObjDisabled,menu:new Common.UI.Menu({cls:"shifted-right",menuAlign:"tl-tr",items:[{caption:e.txtTop,checkable:!0,checked:n.get_MatrixAlign()==Asc.c_oAscMathInterfaceMatrixMatrixAlign.Top,equationProps:{type:i,callback:"put_MatrixAlign",value:Asc.c_oAscMathInterfaceMatrixMatrixAlign.Top}},{caption:e.centerText,checkable:!0,checked:n.get_MatrixAlign()==Asc.c_oAscMathInterfaceMatrixMatrixAlign.Center,equationProps:{type:i,callback:"put_MatrixAlign",value:Asc.c_oAscMathInterfaceMatrixMatrixAlign.Center}},{caption:e.txtBottom,checkable:!0,checked:n.get_MatrixAlign()==Asc.c_oAscMathInterfaceMatrixMatrixAlign.Bottom,equationProps:{type:i,callback:"put_MatrixAlign",value:Asc.c_oAscMathInterfaceMatrixMatrixAlign.Bottom}}]})}),s.push(t),t=new Common.UI.MenuItem({caption:e.txtColumnAlign,equation:!0,disabled:e._currentParaObjDisabled,menu:new Common.UI.Menu({cls:"shifted-right",menuAlign:"tl-tr",items:[{caption:e.leftText,checkable:!0,checked:n.get_ColumnAlign()==Asc.c_oAscMathInterfaceMatrixColumnAlign.Left,equationProps:{type:i,callback:"put_ColumnAlign",value:Asc.c_oAscMathInterfaceMatrixColumnAlign.Left}},{caption:e.centerText,checkable:!0,checked:n.get_ColumnAlign()==Asc.c_oAscMathInterfaceMatrixColumnAlign.Center,equationProps:{type:i,callback:"put_ColumnAlign",value:Asc.c_oAscMathInterfaceMatrixColumnAlign.Center}},{caption:e.rightText,checkable:!0,checked:n.get_ColumnAlign()==Asc.c_oAscMathInterfaceMatrixColumnAlign.Right,equationProps:{type:i,callback:"put_ColumnAlign",value:Asc.c_oAscMathInterfaceMatrixColumnAlign.Right}}]})}),s.push(t);break;case Asc.c_oAscMathInterfaceType.EqArray:t=new Common.UI.MenuItem({caption:e.txtInsertEqBefore,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"insert_Equation",value:!0}}),s.push(t),t=new Common.UI.MenuItem({caption:e.txtInsertEqAfter,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"insert_Equation",value:!1}}),s.push(t),t=new Common.UI.MenuItem({caption:e.txtDeleteEq,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"delete_Equation"}}),s.push(t),t=new Common.UI.MenuItem({caption:e.alignmentText,equation:!0,disabled:e._currentParaObjDisabled,menu:new Common.UI.Menu({cls:"shifted-right",menuAlign:"tl-tr",items:[{caption:e.txtTop,checkable:!0,checked:n.get_Align()==Asc.c_oAscMathInterfaceEqArrayAlign.Top,equationProps:{type:i,callback:"put_Align",value:Asc.c_oAscMathInterfaceEqArrayAlign.Top}},{caption:e.centerText,checkable:!0,checked:n.get_Align()==Asc.c_oAscMathInterfaceEqArrayAlign.Center,equationProps:{type:i,callback:"put_Align",value:Asc.c_oAscMathInterfaceEqArrayAlign.Center}},{caption:e.txtBottom,checkable:!0,checked:n.get_Align()==Asc.c_oAscMathInterfaceEqArrayAlign.Bottom,equationProps:{type:i,callback:"put_Align",value:Asc.c_oAscMathInterfaceEqArrayAlign.Bottom}}]})}),s.push(t);break;case Asc.c_oAscMathInterfaceType.LargeOperator:t=new Common.UI.MenuItem({caption:e.txtLimitChange,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"put_LimitLocation",value:n.get_LimitLocation()==Asc.c_oAscMathInterfaceNaryLimitLocation.UndOvr?Asc.c_oAscMathInterfaceNaryLimitLocation.SubSup:Asc.c_oAscMathInterfaceNaryLimitLocation.UndOvr}}),s.push(t),void 0!==n.get_HideUpper()&&(t=new Common.UI.MenuItem({caption:n.get_HideUpper()?e.txtShowTopLimit:e.txtHideTopLimit,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"put_HideUpper",value:!n.get_HideUpper()}}),s.push(t)),void 0!==n.get_HideLower()&&(t=new Common.UI.MenuItem({caption:n.get_HideLower()?e.txtShowBottomLimit:e.txtHideBottomLimit,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"put_HideLower",value:!n.get_HideLower()}}),s.push(t));break;case Asc.c_oAscMathInterfaceType.Delimiter:t=new Common.UI.MenuItem({caption:e.txtInsertArgBefore,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"insert_DelimiterArgument",value:!0}}),s.push(t),t=new Common.UI.MenuItem({caption:e.txtInsertArgAfter,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"insert_DelimiterArgument",value:!1}}),s.push(t),n.can_DeleteArgument()&&(t=new Common.UI.MenuItem({caption:e.txtDeleteArg,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"delete_DelimiterArgument"}}),s.push(t)),t=new Common.UI.MenuItem({caption:n.has_Separators()?e.txtDeleteCharsAndSeparators:e.txtDeleteChars,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"remove_DelimiterCharacters"}}),s.push(t),t=new Common.UI.MenuItem({caption:n.get_HideOpeningBracket()?e.txtShowOpenBracket:e.txtHideOpenBracket,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"put_HideOpeningBracket",value:!n.get_HideOpeningBracket()}}),s.push(t),t=new Common.UI.MenuItem({caption:n.get_HideClosingBracket()?e.txtShowCloseBracket:e.txtHideCloseBracket,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"put_HideClosingBracket",value:!n.get_HideClosingBracket()}}),s.push(t),t=new Common.UI.MenuItem({caption:e.txtStretchBrackets,equation:!0,disabled:e._currentParaObjDisabled,checkable:!0,checked:n.get_StretchBrackets(),equationProps:{type:i,callback:"put_StretchBrackets",value:!n.get_StretchBrackets()}}),s.push(t),t=new Common.UI.MenuItem({caption:e.txtMatchBrackets,equation:!0,disabled:!n.get_StretchBrackets()||e._currentParaObjDisabled,checkable:!0,checked:n.get_StretchBrackets()&&n.get_MatchBrackets(),equationProps:{type:i,callback:"put_MatchBrackets",value:!n.get_MatchBrackets()}}),s.push(t);break;case Asc.c_oAscMathInterfaceType.GroupChar:n.can_ChangePos()&&(t=new Common.UI.MenuItem({caption:n.get_Pos()==Asc.c_oAscMathInterfaceGroupCharPos.Top?e.txtGroupCharUnder:e.txtGroupCharOver,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"put_Pos",value:n.get_Pos()==Asc.c_oAscMathInterfaceGroupCharPos.Top?Asc.c_oAscMathInterfaceGroupCharPos.Bottom:Asc.c_oAscMathInterfaceGroupCharPos.Top}}),s.push(t),t=new Common.UI.MenuItem({caption:e.txtDeleteGroupChar,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"put_Pos",value:Asc.c_oAscMathInterfaceGroupCharPos.None}}),s.push(t));break;case Asc.c_oAscMathInterfaceType.Radical:void 0!==n.get_HideDegree()&&(t=new Common.UI.MenuItem({caption:n.get_HideDegree()?e.txtShowDegree:e.txtHideDegree,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"put_HideDegree",value:!n.get_HideDegree()}}),s.push(t)),t=new Common.UI.MenuItem({caption:e.txtDeleteRadical,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"remove_Radical"}}),s.push(t)}return n.can_IncreaseArgumentSize()&&(t=new Common.UI.MenuItem({caption:e.txtIncreaseArg,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"increase_ArgumentSize"}}),s.push(t)),n.can_DecreaseArgumentSize()&&(t=new Common.UI.MenuItem({caption:e.txtDecreaseArg,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"decrease_ArgumentSize"}}),s.push(t)),n.can_InsertManualBreak()&&(t=new Common.UI.MenuItem({caption:e.txtInsertBreak,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"insert_ManualBreak"}}),s.push(t)),n.can_DeleteManualBreak()&&(t=new Common.UI.MenuItem({caption:e.txtDeleteBreak,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"delete_ManualBreak"}}),s.push(t)),n.can_AlignToCharacter()&&(t=new Common.UI.MenuItem({caption:e.txtAlignToChar,equation:!0,disabled:e._currentParaObjDisabled,equationProps:{type:i,callback:"align_ToCharacter"}}),s.push(t)),s}},addEquationMenu:function(t){var e=this;e.clearEquationMenu(t);var i=e.documentHolder.textInShapeMenu,n=e.initEquationMenu();return n.length>0&&_.each(n,function(n,s){n.menu?_.each(n.menu.items,function(t){t.on("click",_.bind(e.equationCallback,e,t.options.equationProps))}):n.on("click",_.bind(e.equationCallback,e,n.options.equationProps)),i.insertItem(t,n),t++}),n.length},clearEquationMenu:function(t){for(var e=this,i=e.documentHolder.textInShapeMenu,n=t;n')}),e.paraBulletsPicker.on("item:click",_.bind(this.onSelectBullets,this)),i&&e.paraBulletsPicker.selectRecord(i.rec,!0)},onSignatureClick:function(t){var e=t.cmpEl.attr("data-value");switch(t.value){case 0:Common.NotificationCenter.trigger("protect:sign",e);break;case 1:this.api.asc_ViewCertificate(e);break;case 2:Common.NotificationCenter.trigger("protect:signature","visible",this._isDisabled,e);break;case 3:this.api.asc_RemoveSignature(e)}},onOriginalSizeClick:function(t){if(this.api){var e=this.api.asc_getOriginalImageSize(),i=e.asc_getImageWidth(),n=e.asc_getImageHeight(),s=new Asc.asc_CImgProperty;s.asc_putWidth(i),s.asc_putHeight(n),s.put_ResetCrop(!0),this.api.asc_setGraphicObjectProps(s),Common.NotificationCenter.trigger("edit:complete",this.documentHolder),Common.component.Analytics.trackEvent("DocumentHolder","Set Image Original Size")}},onImgReplace:function(t,e){var i=this;this.api&&("file"==e.value?setTimeout(function(){i.api&&i.api.asc_changeImageFromFile(),Common.NotificationCenter.trigger("edit:complete",i.documentHolder)},10):"storage"==e.value?Common.NotificationCenter.trigger("storage:image-load","change"):new Common.Views.ImageFromUrlDialog({handler:function(t,e){if("ok"==t&&i.api){var n=e.replace(/ /g,"");if(!_.isEmpty(n)){var s=new Asc.asc_CImgProperty;s.asc_putImageUrl(n),i.api.asc_setGraphicObjectProps(s)}}Common.NotificationCenter.trigger("edit:complete",i.documentHolder)}}).show())},onNumberFormatSelect:function(t,e){void 0!==e.value&&"advanced"!==e.value&&this.api&&this.api.asc_setCellFormat(e.options.format),Common.NotificationCenter.trigger("edit:complete",this.documentHolder)},onCustomNumberFormat:function(t){var e=this,i=e.api.asc_getLocale();!i&&(i=e.permissions.lang?parseInt(Common.util.LanguageInfo.getLocalLanguageCode(e.permissions.lang)):1033),new SSE.Views.FormatSettingsDialog({api:e.api,handler:function(t,i){i&&e.api.asc_setCellFormat(i.format),Common.NotificationCenter.trigger("edit:complete",e.documentHolder)},props:{format:t.options.numformat,formatInfo:t.options.numformatinfo,langId:i}}).show(),Common.NotificationCenter.trigger("edit:complete",this.documentHolder)},onNumberFormatOpenAfter:function(t){if(this.api){var e=this,i=e.api.asc_getLocale();if(!i&&(i=e.permissions.lang?parseInt(Common.util.LanguageInfo.getLocalLanguageCode(e.permissions.lang)):1033),this._state.langId!==i){this._state.langId=i;var n=new Asc.asc_CFormatCellsInfo;n.asc_setType(Asc.c_oAscNumFormatType.None),n.asc_setSymbol(this._state.langId);for(var s=this.api.asc_getFormatCells(n),o=0;oOnly text values from the column can be selected for replacement.",txtExpandSort:"The data next to the selection will not be sorted. Do you want to expand the selection to include the adjacent data or continue with sorting the currently selected cells only?",txtExpand:"Expand and sort",txtSorting:"Sorting",txtSortSelected:"Sort selected",txtPaste:"Paste",txtPasteFormulas:"Formulas",txtPasteFormulaNumFormat:"Formulas & number formats",txtPasteKeepSourceFormat:"Formulas & formatting",txtPasteBorders:"All except borders",txtPasteColWidths:"Formulas & column widths",txtPasteMerge:"Merge conditional formatting",txtPasteTranspose:"Transpose",txtPasteValues:"Values",txtPasteValNumFormat:"Values & number formats",txtPasteValFormat:"Values & formatting",txtPasteFormat:"Paste only formatting",txtPasteLink:"Paste Link",txtPastePicture:"Picture",txtPasteLinkPicture:"Linked Picture",txtPasteSourceFormat:"Source formatting",txtPasteDestFormat:"Destination formatting",txtKeepTextOnly:"Keep text only",txtUseTextImport:"Use text import wizard",txtUndoExpansion:"Undo table autoexpansion",txtRedoExpansion:"Redo table autoexpansion",txtAnd:"and",txtOr:"or",txtEquals:"Equals",txtNotEquals:"Does not equal",txtGreater:"Greater than",txtGreaterEquals:"Greater than or equal to",txtLess:"Less than",txtLessEquals:"Less than or equal to",txtAboveAve:"Above average",txtBelowAve:"Below average",txtBegins:"Begins with",txtNotBegins:"Does not begin with",txtEnds:"Ends with",txtNotEnds:"Does not end with",txtContains:"Contains",txtNotContains:"Does not contain",txtFilterTop:"Top",txtFilterBottom:"Bottom",txtItems:"items",txtPercent:"percent",txtEqualsToCellColor:"Equals to cell color",txtEqualsToFontColor:"Equals to font color",txtAll:"(All)",txtBlanks:"(Blanks)",txtColumn:"Column",txtImportWizard:"Text Import Wizard",textPasteSpecial:"Paste special",textStopExpand:"Stop automatically expanding tables",textAutoCorrectSettings:"AutoCorrect options"},SSE.Controllers.DocumentHolder||{}))}),define("text!spreadsheeteditor/main/app/template/CellEditor.template",[],function(){return'
    \r\n \r\n
    \r\n \r\n
    \r\n
    \r\n \r\n
    \r\n
    \r\n \r\n
    \r\n'}),define("spreadsheeteditor/main/app/view/CellEditor",["text!spreadsheeteditor/main/app/template/CellEditor.template","common/main/lib/component/BaseView"],function(t){"use strict";SSE.Views.CellEditor=Common.UI.BaseView.extend(_.extend({template:_.template(t),initialize:function(t){Common.UI.BaseView.prototype.initialize.call(this,t)},render:function(){$(this.el).html(this.template()),this.btnNamedRanges=new Common.UI.Button({parentEl:$("#ce-cell-name-menu"),menu:new Common.UI.Menu({style:"min-width: 70px;max-width:400px;",maxHeight:250,items:[{caption:this.textManager,value:"manager"},{caption:"--"}]})}),this.btnNamedRanges.setVisible(!1),this.btnNamedRanges.menu.setOffset(-81),this.$cellname=$("#ce-cell-name",this.el),this.$btnexpand=$("#ce-btn-expand",this.el),this.$btnfunc=$("#ce-func-label",this.el);var t=this;return this.$cellname.on("focus",function(e){var i=t.$cellname[0];i.selectionStart=0,i.selectionEnd=i.value.length,i.scrollLeft=i.scrollWidth}),this.$btnfunc.addClass("disabled"),this.$btnfunc.tooltip({title:this.tipFormula,placement:"cursor"}),this},updateCellInfo:function(t){t&&this.$cellname.val("string"==typeof t?t:t.asc_getName())},cellNameDisabled:function(t){t?this.$cellname.attr("disabled","disabled"):this.$cellname.removeAttr("disabled"),this.btnNamedRanges.setDisabled(t)},tipFormula:"Insert Function",textManager:"Manager"},SSE.Views.CellEditor||{}))}),define("text!spreadsheeteditor/main/app/template/NameManagerDlg.template",[],function(){return'
    \r\n
    \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n
    \r\n \r\n
    \r\n
    \r\n
    \r\n
    \r\n
    \r\n
    \r\n
    \r\n
    \r\n \r\n
    \r\n
    \r\n
    \r\n \r\n \r\n \r\n \r\n
    \r\n
    \r\n
    '}),define("spreadsheeteditor/main/app/view/NameManagerDlg",["text!spreadsheeteditor/main/app/template/NameManagerDlg.template","common/main/lib/view/AdvancedSettingsWindow","common/main/lib/component/ComboBox","common/main/lib/component/ListView","common/main/lib/component/InputField"],function(t){"use strict";SSE.Views=SSE.Views||{},SSE.Views.NameManagerDlg=Common.Views.AdvancedSettingsWindow.extend(_.extend({options:{alias:"NameManagerDlg",contentWidth:525,height:353,buttons:null},initialize:function(e){_.extend(this.options,{title:this.txtTitle,template:['
    ','
    '+_.template(t)({scope:this})+"
    ","
    ",'
    ','"].join("")},e),this.api=e.api,this.handler=e.handler,this.sheets=e.sheets||[],this.sheetNames=e.sheetNames||[],this.ranges=e.ranges||[],this.props=e.props,this.sort=e.sort||{type:"name",direction:1},this.locked=e.locked||!1,this.userTooltip=!0,this.currentNamedRange=void 0,this.rangesStore=new Common.UI.DataViewStore,this.wrapEvents={onRefreshDefNameList:_.bind(this.onRefreshDefNameList,this),onLockDefNameManager:_.bind(this.onLockDefNameManager,this)},Common.Views.AdvancedSettingsWindow.prototype.initialize.call(this,this.options)},render:function(){Common.Views.AdvancedSettingsWindow.prototype.render.call(this);var t=this;this.cmbFilter=new Common.UI.ComboBox({el:$("#name-manager-combo-filter"),menuStyle:"min-width: 100%;",editable:!1,cls:"input-group-nr",data:[{value:0,displayValue:this.textFilterAll},{value:1,displayValue:this.textFilterDefNames},{value:2,displayValue:this.textFilterTableNames},{value:3,displayValue:this.textFilterSheet},{value:4,displayValue:this.textFilterWorkbook}],takeFocusOnClose:!0}).on("selected",function(e,i){t.refreshRangeList(null,0)}),this.cmbFilter.setValue(0),this.rangeList=new Common.UI.ListView({el:$("#name-manager-range-list",this.$window),store:new Common.UI.DataViewStore,simpleAddMode:!0,emptyText:this.textEmpty,template:_.template(['
    '].join("")),itemTemplate:_.template(['
    ','
    ">
    ','
    <%= name %>
    ','
    <%= scopeName %>
    ','
    <%= range %>
    ',"<% if (lock) { %>",'
    <%=lockuser%>
    ',"<% } %>","
    "].join("")),tabindex:1}),this.rangeList.store.comparator=function(e,i){var n=e.get(t.sort.type).toLowerCase(),s=i.get(t.sort.type).toLowerCase();return n==s?0:n0?this.textnoNames:this.textEmpty)}var l=this,r=this.rangeList.store,c=this.rangesStore.models,h=this.cmbFilter.getValue(),d=h<3?2==h:-1,p=h>2?4==h:-1;if(h>0&&(c=this.rangesStore.filter(function(t){return-1!==d?d===t.get("isTable"):-1!==p&&p===(null===t.get("scope"))})),r.reset(c,{silent:!1}),h=r.length,this.btnEditRange.setDisabled(!h),this.btnDeleteRange.setDisabled(!h),h>0){if(void 0!==e&&null!==e||(e=0),_.isNumber(e))e>h-1&&(e=h-1),this.rangeList.selectByIndex(e),setTimeout(function(){l.rangeList.scrollToRecord(r.at(e))},50);else if(e){var m=r.findWhere({name:e.asc_getName(!0),scope:e.asc_getScope()});m&&(this.rangeList.selectRecord(m),setTimeout(function(){l.rangeList.scrollToRecord(m)},50))}!0===this.userTooltip&&this.rangeList.cmpEl.find(".lock-user").length>0&&this.rangeList.cmpEl.on("mouseover",_.bind(l.onMouseOverLock,l)).on("mouseout",_.bind(l.onMouseOutLock,l))}_.delay(function(){l.rangeList.scroller.update({alwaysVisibleY:!0})},100,this)},onMouseOverLock:function(t,e,i){if(!0===this.userTooltip&&$(t.target).hasClass("lock-user")){var n=this,s=$(t.target).tooltip({title:this.tipIsLocked,trigger:"manual"}).data("bs.tooltip");this.userTooltip=s.tip(),this.userTooltip.css("z-index",parseInt(this.$window.css("z-index"))+10),s.show(),setTimeout(function(){n.userTipHide()},5e3)}},userTipHide:function(){"object"==typeof this.userTooltip&&(this.userTooltip.remove(),this.userTooltip=void 0,this.rangeList.cmpEl.off("mouseover").off("mouseout"))},onMouseOutLock:function(t,e,i){"object"==typeof this.userTooltip&&this.userTipHide()},onEditRange:function(t){if(this.locked)return void Common.NotificationCenter.trigger("namedrange:locked");var e=this,i=e.$window.offset(),n=this.rangeList.getSelectedRec(),s=(_.indexOf(this.rangeList.store.models,n),t&&n?new Asc.asc_CDefName(n.get("name"),n.get("range"),n.get("scope"),n.get("type"),void 0,void 0,void 0,!0):null),o=new SSE.Views.NamedRangeEditDlg({api:e.api,sheets:this.sheets,props:t?s:this.props,isEdit:t,handler:function(i,n){"ok"==i&&n&&(t?(e.currentNamedRange=n,e.api.asc_editDefinedNames(s,n)):(e.cmbFilter.setValue(0),e.currentNamedRange=n,e.api.asc_setDefinedNames(n)))}}).on("close",function(){e.show()});e.hide(),o.show(i.left+65,i.top+77)},onDeleteRange:function(){var t=this.rangeList.getSelectedRec();t&&(this.currentNamedRange=_.indexOf(this.rangeList.store.models,t),this.api.asc_delDefinedNames(new Asc.asc_CDefName(t.get("name"),t.get("range"),t.get("scope"),t.get("type"),void 0,void 0,void 0,!0)))},getSettings:function(){return this.sort},onPrimary:function(){return!0},onDlgBtnClick:function(t){this.handler&&this.handler.call(this,t.currentTarget.attributes.result.value),this.close()},onSortNames:function(t){t!==this.sort.type?(this.sort={type:t,direction:1},this.spanSortName.toggleClass("hidden"),this.spanSortScope.toggleClass("hidden")):this.sort.direction=-this.sort.direction;var e="name"==t?this.spanSortName:this.spanSortScope;this.sort.direction>0?e.removeClass("sort-desc"):e.addClass("sort-desc"),this.rangeList.store.sort(),this.rangeList.onResetItems(),this.rangeList.scroller.update({alwaysVisibleY:!0})},getUserName:function(t){var e=SSE.getCollection("Common.Collections.Users");if(e){var i=e.findUser(t);if(i)return Common.Utils.UserInfoParser.getParsedName(i.get("username"))}return this.guestText}, onSelectRangeItem:function(t,e,i){if(i){this.userTipHide();var n={};if(_.isFunction(i.toJSON)){if(!i.get("selected"))return;n=i.toJSON(),this.currentNamedRange=_.indexOf(this.rangeList.store.models,i),this.btnEditRange.setDisabled(n.lock),this.btnDeleteRange.setDisabled(n.lock||n.isTable||n.isSlicer)}}},hide:function(){this.userTipHide(),Common.UI.Window.prototype.hide.call(this)},close:function(){this.userTipHide(),this.api.asc_unregisterCallback("asc_onLockDefNameManager",this.wrapEvents.onLockDefNameManager),this.api.asc_unregisterCallback("asc_onRefreshDefNameList",this.wrapEvents.onRefreshDefNameList),Common.UI.Window.prototype.close.call(this)},onKeyDown:function(t,e,i){i.keyCode!=Common.UI.Keys.DELETE||this.btnDeleteRange.isDisabled()||this.onDeleteRange()},onDblClickItem:function(t,e,i){this.btnEditRange.isDisabled()||this.onEditRange(!0)},onLockDefNameManager:function(t){this.locked=t==Asc.c_oAscDefinedNameReason.LockDefNameManager},txtTitle:"Name Manager",closeButtonText:"Close",textDataRange:"Data Range",textNew:"New",textEdit:"Edit",textDelete:"Delete",textRanges:"Named Ranges",textScope:"Scope",textFilter:"Filter",textEmpty:"No named ranges have been created yet.
    Create at least one named range and it will appear in this field.",textnoNames:"No named ranges matching your filter could be found.",textFilterAll:"All",textFilterDefNames:"Defined names",textFilterTableNames:"Table names",textFilterSheet:"Names Scoped to Sheet",textFilterWorkbook:"Names Scoped to Workbook",textWorkbook:"Workbook",guestText:"Guest",tipIsLocked:"This element is being edited by another user."},SSE.Views.NameManagerDlg||{}))}),define("spreadsheeteditor/main/app/controller/CellEditor",["core","spreadsheeteditor/main/app/view/CellEditor","spreadsheeteditor/main/app/view/NameManagerDlg"],function(t){"use strict";SSE.Controllers.CellEditor=Backbone.Controller.extend({views:["CellEditor"],events:function(){return{"keyup input#ce-cell-name":_.bind(this.onCellName,this),"keyup textarea#ce-cell-content":_.bind(this.onKeyupCellEditor,this),"blur textarea#ce-cell-content":_.bind(this.onBlurCellEditor,this),"click button#ce-btn-expand":_.bind(this.expandEditorField,this),"click button#ce-func-label":_.bind(this.onInsertFunction,this)}},initialize:function(){this.addListeners({CellEditor:{},Viewport:{"layout:resizedrag":_.bind(this.onLayoutResize,this)},"Common.Views.Header":{"formulabar:hide":function(t){this.editor.setVisible(!t),Common.localStorage.setBool("sse-hidden-formula",t),Common.NotificationCenter.trigger("layout:changed","celleditor",t?"hidden":"showed")}.bind(this)}})},setApi:function(t){return this.api=t,this.api.isCEditorFocused=!1,this.api.asc_registerCallback("asc_onSelectionNameChanged",_.bind(this.onApiCellSelection,this)),this.api.asc_registerCallback("asc_onEditCell",_.bind(this.onApiEditCell,this)),this.api.asc_registerCallback("asc_onCoAuthoringDisconnect",_.bind(this.onApiDisconnect,this)),Common.NotificationCenter.on("api:disconnect",_.bind(this.onApiDisconnect,this)),Common.NotificationCenter.on("cells:range",_.bind(this.onCellsRange,this)),this.api.asc_registerCallback("asc_onLockDefNameManager",_.bind(this.onLockDefNameManager,this)),this.api.asc_registerCallback("asc_onInputKeyDown",_.bind(this.onInputKeyDown,this)),this},setMode:function(t){this.mode=t,this.editor.$btnfunc[this.mode.isEdit?"removeClass":"addClass"]("disabled"),this.editor.btnNamedRanges.setVisible(this.mode.isEdit&&!this.mode.isEditDiagram&&!this.mode.isEditMailMerge),this.mode.isEdit&&this.api.asc_registerCallback("asc_onSelectionChanged",_.bind(this.onApiSelectionChanged,this))},onInputKeyDown:function(t){if(Common.UI.Keys.UP===t.keyCode||Common.UI.Keys.DOWN===t.keyCode||Common.UI.Keys.TAB===t.keyCode||Common.UI.Keys.RETURN===t.keyCode||Common.UI.Keys.ESC===t.keyCode||Common.UI.Keys.LEFT===t.keyCode||Common.UI.Keys.RIGHT===t.keyCode){var e=$("#menu-formula-selection");e.hasClass("open")&&e.find(".dropdown-menu").trigger("keydown",t)}},onLaunch:function(){this.editor=this.getView("CellEditor"),this.bindViewEvents(this.editor,this.events),this.editor.$el.parent().find(".after").css({zIndex:"4"});var t=Common.localStorage.getItem("sse-celleditor-height");this.editor.keep_height=null!==t&&parseInt(t)>0?parseInt(t):74,Common.localStorage.getBool("sse-celleditor-expand")&&(this.editor.$el.height(this.editor.keep_height),this.onLayoutResize(void 0,"cell:edit")),this.editor.btnNamedRanges.menu.on("item:click",_.bind(this.onNamedRangesMenu,this)).on("show:before",_.bind(this.onNameBeforeShow,this)),this.namedrange_locked=!1},onApiEditCell:function(t){this.viewmode||(t==Asc.c_oAscCellEditorState.editStart?(this.api.isCellEdited=!0,this.editor.cellNameDisabled(!0)):t==Asc.c_oAscCellEditorState.editInCell?this.api.isCEditorFocused="clear":t==Asc.c_oAscCellEditorState.editEnd&&(this.api.isCellEdited=!1,this.api.isCEditorFocused=!1,this.editor.cellNameDisabled(!1)),this.editor.$btnfunc.toggleClass("disabled",t==Asc.c_oAscCellEditorState.editText))},onApiCellSelection:function(t){this.editor.updateCellInfo(t)},onApiSelectionChanged:function(t){if(!this.viewmode){var e=t.asc_getSelectionType(),i=!this.mode.isEditMailMerge&&!this.mode.isEditDiagram&&(!0===t.asc_getLocked()||!0===t.asc_getLockedTable()||!0===t.asc_getLockedPivotTable()),n=e==Asc.c_oAscSelectionType.RangeChartText,s=e==Asc.c_oAscSelectionType.RangeChart,o=e==Asc.c_oAscSelectionType.RangeShapeText,a=e==Asc.c_oAscSelectionType.RangeShape,l=e==Asc.c_oAscSelectionType.RangeImage||e==Asc.c_oAscSelectionType.RangeSlicer,r=o||a||n||s;this.editor.$btnfunc.toggleClass("disabled",l||r||i)}},onApiDisconnect:function(){this.mode.isEdit=!1;var t=this.getApplication().getController("FormulaDialog");t&&t.hideDialog(),this.mode.isEdit||($("#ce-func-label",this.editor.el).addClass("disabled"),this.editor.btnNamedRanges.setVisible(!1))},onCellsRange:function(t){this.editor.cellNameDisabled(t!=Asc.c_oAscSelectionDialogType.None),this.editor.$btnfunc.toggleClass("disabled",t!=Asc.c_oAscSelectionDialogType.None)},onLayoutResize:function(t,e){"cell:edit"==e&&(this.editor.$el.height()>19?(this.editor.$btnexpand.hasClass("btn-collapse")||this.editor.$btnexpand.addClass("btn-collapse"),t&&Common.localStorage.setItem("sse-celleditor-height",this.editor.$el.height()),t&&Common.localStorage.setBool("sse-celleditor-expand",!0)):(this.editor.$btnexpand.removeClass("btn-collapse"),t&&Common.localStorage.setBool("sse-celleditor-expand",!1)))},onCellName:function(t){if(t.keyCode==Common.UI.Keys.RETURN){var e=this.editor.$cellname.val();e&&e.length&&this.api.asc_findCell(e),Common.NotificationCenter.trigger("edit:complete",this.editor)}},onBlurCellEditor:function(){"clear"==this.api.isCEditorFocused?this.api.isCEditorFocused=void 0:this.api.isCellEdited&&(this.api.isCEditorFocused=!0)},onKeyupCellEditor:function(t){t.keyCode!=Common.UI.Keys.RETURN||t.altKey||(this.api.isCEditorFocused="clear")},expandEditorField:function(){this.editor.$el.height()>19?(this.editor.keep_height=this.editor.$el.height(),this.editor.$el.height(19),this.editor.$btnexpand.removeClass("btn-collapse"),Common.localStorage.setBool("sse-celleditor-expand",!1)):(this.editor.$el.height(this.editor.keep_height),this.editor.$btnexpand.addClass("btn-collapse"),Common.localStorage.setBool("sse-celleditor-expand",!0)),Common.NotificationCenter.trigger("layout:changed","celleditor"),Common.NotificationCenter.trigger("edit:complete",this.editor,{restorefocus:!0})},onInsertFunction:function(){if(!this.viewmode&&this.mode.isEdit&&!this.editor.$btnfunc.hasClass("disabled")){var t=this.getApplication().getController("FormulaDialog");t&&($("#ce-func-label",this.editor.el).blur(),t.showDialog())}},onNamedRangesMenu:function(t,e){var i=this;if("manager"==e.options.value){for(var n=this.api.asc_getWorksheetsCount(),s=-1,o=[],a=[];++s2)},onLockDefNameManager:function(t){this.namedrange_locked=t==Asc.c_oAscDefinedNameReason.LockDefNameManager},disableEditing:function(t){this.editor.$btnfunc[t?"addClass":"removeClass"]("disabled"),this.editor.btnNamedRanges.setVisible(!t)},setPreviewMode:function(t){this.viewmode!==t&&(this.viewmode=t,this.editor.$btnfunc[t?"addClass":"removeClass"]("disabled"),this.editor.cellNameDisabled(t))}})}),define("common/main/lib/view/ImageFromUrlDialog",["common/main/lib/component/Window"],function(){"use strict";Common.Views.ImageFromUrlDialog=Common.UI.Window.extend(_.extend({options:{width:330,header:!1,cls:"modal-dlg",buttons:["ok","cancel"]},initialize:function(t){_.extend(this.options,t||{}),this.template=['
    ','
    ',"","
    ",'
    ',"
    "].join(""),this.options.tpl=_.template(this.template)(this.options),Common.UI.Window.prototype.initialize.call(this,this.options)},render:function(){Common.UI.Window.prototype.render.call(this);var t=this;t.inputUrl=new Common.UI.InputField({el:$("#id-dlg-url"),allowBlank:!1,blankError:t.txtEmpty,style:"width: 100%;",validateOnBlur:!1,validation:function(e){return!!/((^https?)|(^ftp)):\/\/.+/i.test(e)||t.txtNotUrl}}),this.getChild().find(".btn").on("click",_.bind(this.onBtnClick,this))},show:function(){Common.UI.Window.prototype.show.apply(this,arguments);var t=this;_.delay(function(){t.getChild("input").focus()},100)},onPrimary:function(t){return this._handleInput("ok"),!1},onBtnClick:function(t){this._handleInput(t.currentTarget.attributes.result.value)},_handleInput:function(t){if(this.options.handler){if("ok"==t&&!0!==this.inputUrl.checkValidate())return void this.inputUrl.cmpEl.find("input").focus();this.options.handler.call(this,t,this.inputUrl.getValue())}this.close()},textUrl:"Paste an image URL:",txtEmpty:"This field is required",txtNotUrl:'This field should be a URL in the format "http://www.example.com"'},Common.Views.ImageFromUrlDialog||{}))}),void 0===Common)var Common={};if(define("common/main/lib/component/LoadMask",["common/main/lib/component/BaseView"],function(){"use strict";Common.UI.LoadMask=Common.UI.BaseView.extend(function(){return{options:{cls:"",style:"",title:"Loading...",owner:document.body},template:_.template(['"].join("")),initialize:function(t){Common.UI.BaseView.prototype.initialize.call(this,t),this.template=this.options.template||this.template,this.title=this.options.title,this.ownerEl=this.options.owner instanceof Common.UI.BaseView?$(this.options.owner.el):$(this.options.owner),this.loaderEl=$(this.template({id:this.id,cls:this.options.cls,style:this.options.style,title:this.title})),this.maskeEl=$('
    '),this.timerId=0},render:function(){return this},show:function(){var t=this.ownerEl,e=this.loaderEl,i=this.maskeEl;if(t.ismasked)return this;t.ismasked=!0;var n=this;return n.title!=n.options.title&&(n.options.title=n.title,$(".asc-loadmask-title",e).html(n.title)),n.timerId=setTimeout(function(){t.append(i),t.append(e),t&&0==t.closest(".asc-window.modal").length&&Common.util.Shortcuts.suspendEvents()},500),this},hide:function(){var t=this.ownerEl;this.timerId&&(clearTimeout(this.timerId),this.timerId=0),t&&t.ismasked&&(0!=t.closest(".asc-window.modal").length||Common.Utils.ModalWindow.isVisible()||Common.util.Shortcuts.resumeEvents(),this.maskeEl&&this.maskeEl.remove(),this.loaderEl&&this.loaderEl.remove()),delete t.ismasked},setTitle:function(t){this.title=t,this.ownerEl&&this.ownerEl.ismasked&&this.loaderEl&&$(".asc-loadmask-title",this.loaderEl).html(t)},isVisible:function(){return!!this.ownerEl.ismasked},updatePosition:function(){var t=this.ownerEl,e=this.loaderEl;t&&t.ismasked&&e&&(e.css({top:Math.round(t.height()/2-(e.height()+parseInt(e.css("padding-top"))+parseInt(e.css("padding-bottom")))/2)+"px",left:Math.round(t.width()/2-(e.width()+parseInt(e.css("padding-left"))+parseInt(e.css("padding-right")))/2)+"px"}),e.css({visibility:"visible"}))}}}())}),define("common/main/lib/view/SelectFileDlg",["common/main/lib/component/Window","common/main/lib/component/LoadMask"],function(){"use strict";Common.Views.SelectFileDlg=Common.UI.Window.extend(_.extend({initialize:function(t){var e={};_.extend(e,{title:this.textTitle,width:1024,height:621,header:!0},t),this.template=['
    '].join(""),e.tpl=_.template(this.template)(e),this.fileChoiceUrl=t.fileChoiceUrl||"",Common.UI.Window.prototype.initialize.call(this,e)},render:function(){Common.UI.Window.prototype.render.call(this),this.$window.find("> .body").css({height:"auto",overflow:"hidden"});var t=document.createElement("iframe");t.width="100%",t.height=585,t.align="top",t.frameBorder=0,t.scrolling="no",t.onload=_.bind(this._onLoad,this),$("#id-select-file-placeholder").append(t),this.loadMask=new Common.UI.LoadMask({owner:$("#id-select-file-placeholder")}),this.loadMask.setTitle(this.textLoading),this.loadMask.show(),t.src=this.fileChoiceUrl;var e=this;this._eventfunc=function(t){e._onWindowMessage(t)},this._bindWindowEvents.call(this),this.on("close",function(t){e._unbindWindowEvents()})},_bindWindowEvents:function(){window.addEventListener?window.addEventListener("message",this._eventfunc,!1):window.attachEvent&&window.attachEvent("onmessage",this._eventfunc)},_unbindWindowEvents:function(){window.removeEventListener?window.removeEventListener("message",this._eventfunc):window.detachEvent&&window.detachEvent("onmessage",this._eventfunc)},_onWindowMessage:function(t){if(t&&window.JSON)try{this._onMessage.call(this,window.JSON.parse(t.data))}catch(t){}},_onMessage:function(t){if(t&&"onlyoffice"==t.Referer&&void 0!==t.file){Common.NotificationCenter.trigger("window:close",this);var e=this;setTimeout(function(){_.isEmpty(t.file)||e.trigger("selectfile",e,t.file)},50)}},_onLoad:function(){this.loadMask&&this.loadMask.hide()},textTitle:"Select Data Source",textLoading:"Loading"},Common.Views.SelectFileDlg||{}))}),define("common/main/lib/view/OptionsDialog",["common/main/lib/component/Window","common/main/lib/component/RadioBox"],function(){"use strict";Common.Views.OptionsDialog=Common.UI.Window.extend(_.extend({options:{width:214,header:!0,style:"min-width: 214px;",cls:"modal-dlg",items:[],buttons:["ok","cancel"]},initialize:function(t){_.extend(this.options,t||{}),this.template=['
    ','<% if (typeof label !== "undefined" && label !=="") { %>','',"<% } %>","<% _.each(items, function(item, index) { %>","<% if (!item.id) item.id = Common.UI.getId(); %>",'
    ',"<% }) %>","
    "].join(""),this.options.tpl=_.template(this.template)(this.options),this.radio=[],Common.UI.Window.prototype.initialize.call(this,this.options)},render:function(){Common.UI.Window.prototype.render.call(this);var t=this,e=t.getChild(),i=this.options.items,n=!0,s=-1;if(i){for(var o=0;o=0&&this.radio[s].setValue(!0)}e.find(".dlg-btn").on("click",_.bind(this.onBtnClick,this))},_handleInput:function(t){this.options.handler&&this.options.handler.call(this,this,t),this.close()},onBtnClick:function(t){this._handleInput(t.currentTarget.attributes.result.value)},getSettings:function(){return this.currentCell},onPrimary:function(){return this._handleInput("ok"),!1}},Common.Views.OptionsDialog||{}))}),void 0===Common)var Common={};if(void 0===Common.define&&(Common.define={}),define("common/main/lib/util/define",[],function(){"use strict";Common.define.c_oAscMathMainType={Symbol:0,Fraction:1,Script:2,Radical:3,Integral:4,LargeOperator:5,Bracket:6,Function:7,Accent:8,LimitLog:9,Operator:10,Matrix:11},Common.define.c_oAscMathType={Symbol_pm:0,Symbol_infinity:1,Symbol_equals:2,Symbol_neq:3,Symbol_about:4,Symbol_times:5,Symbol_div:6,Symbol_factorial:7,Symbol_propto:8,Symbol_less:9,Symbol_ll:10,Symbol_greater:11,Symbol_gg:12,Symbol_leq:13,Symbol_geq:14,Symbol_mp:15,Symbol_cong:16,Symbol_approx:17,Symbol_equiv:18,Symbol_forall:19,Symbol_additional:20,Symbol_partial:21,Symbol_sqrt:22,Symbol_cbrt:23,Symbol_qdrt:24,Symbol_cup:25,Symbol_cap:26,Symbol_emptyset:27,Symbol_percent:28,Symbol_degree:29,Symbol_fahrenheit:30,Symbol_celsius:31,Symbol_inc:32,Symbol_nabla:33,Symbol_exists:34,Symbol_notexists:35,Symbol_in:36,Symbol_ni:37,Symbol_leftarrow:38,Symbol_uparrow:39,Symbol_rightarrow:40,Symbol_downarrow:41,Symbol_leftrightarrow:42,Symbol_therefore:43,Symbol_plus:44,Symbol_minus:45,Symbol_not:46,Symbol_ast:47,Symbol_bullet:48,Symbol_vdots:49,Symbol_cdots:50,Symbol_rddots:51,Symbol_ddots:52,Symbol_aleph:53,Symbol_beth:54,Symbol_QED:55,Symbol_alpha:65536,Symbol_beta:65537,Symbol_gamma:65538,Symbol_delta:65539,Symbol_varepsilon:65540,Symbol_epsilon:65541,Symbol_zeta:65542,Symbol_eta:65543,Symbol_theta:65544,Symbol_vartheta:65545,Symbol_iota:65546,Symbol_kappa:65547,Symbol_lambda:65548,Symbol_mu:65549,Symbol_nu:65550,Symbol_xsi:65551,Symbol_o:65552,Symbol_pi:65553,Symbol_varpi:65554,Symbol_rho:65555,Symbol_varrho:65556,Symbol_sigma:65557,Symbol_varsigma:65558,Symbol_tau:65559,Symbol_upsilon:65560,Symbol_varphi:65561,Symbol_phi:65562,Symbol_chi:65563,Symbol_psi:65564,Symbol_omega:65565,Symbol_Alpha:131072,Symbol_Beta:131073,Symbol_Gamma:131074,Symbol_Delta:131075,Symbol_Epsilon:131076,Symbol_Zeta:131077,Symbol_Eta:131078,Symbol_Theta:131079,Symbol_Iota:131080,Symbol_Kappa:131081,Symbol_Lambda:131082,Symbol_Mu:131083,Symbol_Nu:131084,Symbol_Xsi:131085,Symbol_O:131086,Symbol_Pi:131087,Symbol_Rho:131088,Symbol_Sigma:131089,Symbol_Tau:131090,Symbol_Upsilon:131091,Symbol_Phi:131092,Symbol_Chi:131093,Symbol_Psi:131094,Symbol_Omega:131095,FractionVertical:16777216,FractionDiagonal:16777217,FractionHorizontal:16777218,FractionSmall:16777219,FractionDifferential_1:16842752,FractionDifferential_2:16842753,FractionDifferential_3:16842754,FractionDifferential_4:16842755,FractionPi_2:16842756,ScriptSup:33554432,ScriptSub:33554433,ScriptSubSup:33554434,ScriptSubSupLeft:33554435,ScriptCustom_1:33619968,ScriptCustom_2:33619969,ScriptCustom_3:33619970,ScriptCustom_4:33619971,RadicalSqrt:50331648,RadicalRoot_n:50331649,RadicalRoot_2:50331650,RadicalRoot_3:50331651,RadicalCustom_1:50397184,RadicalCustom_2:50397185,Integral:67108864,IntegralSubSup:67108865,IntegralCenterSubSup:67108866,IntegralDouble:67108867,IntegralDoubleSubSup:67108868,IntegralDoubleCenterSubSup:67108869,IntegralTriple:67108870,IntegralTripleSubSup:67108871,IntegralTripleCenterSubSup:67108872,IntegralOriented:67174400,IntegralOrientedSubSup:67174401,IntegralOrientedCenterSubSup:67174402,IntegralOrientedDouble:67174403,IntegralOrientedDoubleSubSup:67174404,IntegralOrientedDoubleCenterSubSup:67174405,IntegralOrientedTriple:67174406,IntegralOrientedTripleSubSup:67174407,IntegralOrientedTripleCenterSubSup:67174408,Integral_dx:67239936,Integral_dy:67239937,Integral_dtheta:67239938,LargeOperator_Sum:83886080,LargeOperator_Sum_CenterSubSup:83886081,LargeOperator_Sum_SubSup:83886082,LargeOperator_Sum_CenterSub:83886083,LargeOperator_Sum_Sub:83886084,LargeOperator_Prod:83951616,LargeOperator_Prod_CenterSubSup:83951617,LargeOperator_Prod_SubSup:83951618,LargeOperator_Prod_CenterSub:83951619,LargeOperator_Prod_Sub:83951620,LargeOperator_CoProd:83951621,LargeOperator_CoProd_CenterSubSup:83951622,LargeOperator_CoProd_SubSup:83951623,LargeOperator_CoProd_CenterSub:83951624,LargeOperator_CoProd_Sub:83951625,LargeOperator_Union:84017152,LargeOperator_Union_CenterSubSup:84017153,LargeOperator_Union_SubSup:84017154,LargeOperator_Union_CenterSub:84017155,LargeOperator_Union_Sub:84017156,LargeOperator_Intersection:84017157,LargeOperator_Intersection_CenterSubSup:84017158,LargeOperator_Intersection_SubSup:84017159,LargeOperator_Intersection_CenterSub:84017160,LargeOperator_Intersection_Sub:84017161,LargeOperator_Disjunction:84082688,LargeOperator_Disjunction_CenterSubSup:84082689,LargeOperator_Disjunction_SubSup:84082690,LargeOperator_Disjunction_CenterSub:84082691,LargeOperator_Disjunction_Sub:84082692,LargeOperator_Conjunction:84082693,LargeOperator_Conjunction_CenterSubSup:84082694,LargeOperator_Conjunction_SubSup:84082695,LargeOperator_Conjunction_CenterSub:84082696,LargeOperator_Conjunction_Sub:84082697,LargeOperator_Custom_1:84148224,LargeOperator_Custom_2:84148225,LargeOperator_Custom_3:84148226,LargeOperator_Custom_4:84148227,LargeOperator_Custom_5:84148228,Bracket_Round:100663296,Bracket_Square:100663297,Bracket_Curve:100663298,Bracket_Angle:100663299,Bracket_LowLim:100663300,Bracket_UppLim:100663301,Bracket_Line:100663302,Bracket_LineDouble:100663303,Bracket_Square_OpenOpen:100663304,Bracket_Square_CloseClose:100663305,Bracket_Square_CloseOpen:100663306,Bracket_SquareDouble:100663307,Bracket_Round_Delimiter_2:100728832,Bracket_Curve_Delimiter_2:100728833,Bracket_Angle_Delimiter_2:100728834,Bracket_Angle_Delimiter_3:100728835,Bracket_Round_OpenNone:100794368,Bracket_Round_NoneOpen:100794369,Bracket_Square_OpenNone:100794370,Bracket_Square_NoneOpen:100794371,Bracket_Curve_OpenNone:100794372,Bracket_Curve_NoneOpen:100794373,Bracket_Angle_OpenNone:100794374,Bracket_Angle_NoneOpen:100794375,Bracket_LowLim_OpenNone:100794376,Bracket_LowLim_NoneNone:100794377,Bracket_UppLim_OpenNone:100794378,Bracket_UppLim_NoneOpen:100794379,Bracket_Line_OpenNone:100794380,Bracket_Line_NoneOpen:100794381,Bracket_LineDouble_OpenNone:100794382,Bracket_LineDouble_NoneOpen:100794383,Bracket_SquareDouble_OpenNone:100794384,Bracket_SquareDouble_NoneOpen:100794385,Bracket_Custom_1:100859904,Bracket_Custom_2:100859905,Bracket_Custom_3:100859906,Bracket_Custom_4:100859907,Bracket_Custom_5:100925440,Bracket_Custom_6:100925441,Bracket_Custom_7:100925442,Function_Sin:117440512,Function_Cos:117440513,Function_Tan:117440514,Function_Csc:117440515,Function_Sec:117440516,Function_Cot:117440517,Function_1_Sin:117506048,Function_1_Cos:117506049,Function_1_Tan:117506050,Function_1_Csc:117506051,Function_1_Sec:117506052,Function_1_Cot:117506053,Function_Sinh:117571584,Function_Cosh:117571585,Function_Tanh:117571586,Function_Csch:117571587,Function_Sech:117571588,Function_Coth:117571589,Function_1_Sinh:117637120,Function_1_Cosh:117637121,Function_1_Tanh:117637122,Function_1_Csch:117637123,Function_1_Sech:117637124,Function_1_Coth:117637125,Function_Custom_1:117702656,Function_Custom_2:117702657,Function_Custom_3:117702658,Accent_Dot:134217728,Accent_DDot:134217729,Accent_DDDot:134217730,Accent_Hat:134217731,Accent_Check:134217732,Accent_Accent:134217733,Accent_Grave:134217734,Accent_Smile:134217735,Accent_Tilde:134217736,Accent_Bar:134217737,Accent_DoubleBar:134217738,Accent_CurveBracketTop:134217739,Accent_CurveBracketBot:134217740,Accent_GroupTop:134217741,Accent_GroupBot:134217742,Accent_ArrowL:134217743,Accent_ArrowR:134217744,Accent_ArrowD:134217745,Accent_HarpoonL:134217746,Accent_HarpoonR:134217747,Accent_BorderBox:134283264,Accent_BorderBoxCustom:134283265,Accent_BarTop:134348800,Accent_BarBot:134348801,Accent_Custom_1:134414336,Accent_Custom_2:134414337,Accent_Custom_3:134414338,LimitLog_LogBase:150994944,LimitLog_Log:150994945,LimitLog_Lim:150994946,LimitLog_Min:150994947,LimitLog_Max:150994948,LimitLog_Ln:150994949,LimitLog_Custom_1:151060480,LimitLog_Custom_2:151060481,Operator_ColonEquals:167772160,Operator_EqualsEquals:167772161,Operator_PlusEquals:167772162,Operator_MinusEquals:167772163,Operator_Definition:167772164,Operator_UnitOfMeasure:167772165,Operator_DeltaEquals:167772166,Operator_ArrowL_Top:167837696,Operator_ArrowR_Top:167837697,Operator_ArrowL_Bot:167837698,Operator_ArrowR_Bot:167837699,Operator_DoubleArrowL_Top:167837700,Operator_DoubleArrowR_Top:167837701,Operator_DoubleArrowL_Bot:167837702,Operator_DoubleArrowR_Bot:167837703,Operator_ArrowD_Top:167837704,Operator_ArrowD_Bot:167837705,Operator_DoubleArrowD_Top:167837706,Operator_DoubleArrowD_Bot:167837707,Operator_Custom_1:167903232,Operator_Custom_2:167903233,Matrix_1_2:184549376,Matrix_2_1:184549377,Matrix_1_3:184549378,Matrix_3_1:184549379,Matrix_2_2:184549380,Matrix_2_3:184549381,Matrix_3_2:184549382,Matrix_3_3:184549383,Matrix_Dots_Center:184614912,Matrix_Dots_Baseline:184614913,Matrix_Dots_Vertical:184614914,Matrix_Dots_Diagonal:184614915,Matrix_Identity_2:184680448,Matrix_Identity_2_NoZeros:184680449,Matrix_Identity_3:184680450,Matrix_Identity_3_NoZeros:184680451,Matrix_2_2_RoundBracket:184745984,Matrix_2_2_SquareBracket:184745985,Matrix_2_2_LineBracket:184745986,Matrix_2_2_DLineBracket:184745987,Matrix_Flat_Round:184811520,Matrix_Flat_Square:184811521},Common.define.chartData=_.extend(new function(){return{textLine:"Line",textColumn:"Column",textBar:"Bar",textArea:"Area",textPie:"Pie",textPoint:"XY (Scatter)",textStock:"Stock",textSurface:"Surface",textCharts:"Charts",textSparks:"Sparklines",textLineSpark:"Line",textColumnSpark:"Column",textWinLossSpark:"Win/Loss",getChartGroupData:function(t){return[{id:"menu-chart-group-bar",caption:this.textColumn,headername:t?this.textCharts:void 0},{id:"menu-chart-group-line",caption:this.textLine},{id:"menu-chart-group-pie",caption:this.textPie},{id:"menu-chart-group-hbar",caption:this.textBar},{id:"menu-chart-group-area",caption:this.textArea,inline:!0},{id:"menu-chart-group-scatter",caption:this.textPoint,inline:!0},{id:"menu-chart-group-stock",caption:this.textStock,inline:!0}]},getChartData:function(){return[{group:"menu-chart-group-bar",type:Asc.c_oAscChartTypeSettings.barNormal,iconCls:"column-normal"},{group:"menu-chart-group-bar",type:Asc.c_oAscChartTypeSettings.barStacked,iconCls:"column-stack"},{group:"menu-chart-group-bar",type:Asc.c_oAscChartTypeSettings.barStackedPer,iconCls:"column-pstack"},{group:"menu-chart-group-bar",type:Asc.c_oAscChartTypeSettings.barNormal3d,iconCls:"column-3d-normal"},{group:"menu-chart-group-bar",type:Asc.c_oAscChartTypeSettings.barStacked3d,iconCls:"column-3d-stack"},{group:"menu-chart-group-bar",type:Asc.c_oAscChartTypeSettings.barStackedPer3d,iconCls:"column-3d-pstack"},{group:"menu-chart-group-bar",type:Asc.c_oAscChartTypeSettings.barNormal3dPerspective,iconCls:"column-3d-normal-per"},{group:"menu-chart-group-line",type:Asc.c_oAscChartTypeSettings.lineNormal,iconCls:"line-normal"},{group:"menu-chart-group-line",type:Asc.c_oAscChartTypeSettings.lineStacked,iconCls:"line-stack"},{group:"menu-chart-group-line",type:Asc.c_oAscChartTypeSettings.lineStackedPer,iconCls:"line-pstack"},{group:"menu-chart-group-line",type:Asc.c_oAscChartTypeSettings.line3d,iconCls:"line-3d"},{group:"menu-chart-group-pie",type:Asc.c_oAscChartTypeSettings.pie,iconCls:"pie-normal"},{group:"menu-chart-group-pie",type:Asc.c_oAscChartTypeSettings.doughnut,iconCls:"pie-doughnut"},{group:"menu-chart-group-pie",type:Asc.c_oAscChartTypeSettings.pie3d,iconCls:"pie-3d-normal"},{group:"menu-chart-group-hbar",type:Asc.c_oAscChartTypeSettings.hBarNormal,iconCls:"bar-normal"},{group:"menu-chart-group-hbar",type:Asc.c_oAscChartTypeSettings.hBarStacked,iconCls:"bar-stack"},{group:"menu-chart-group-hbar",type:Asc.c_oAscChartTypeSettings.hBarStackedPer,iconCls:"bar-pstack"},{group:"menu-chart-group-hbar",type:Asc.c_oAscChartTypeSettings.hBarNormal3d,iconCls:"bar-3d-normal"},{group:"menu-chart-group-hbar",type:Asc.c_oAscChartTypeSettings.hBarStacked3d,iconCls:"bar-3d-stack"},{group:"menu-chart-group-hbar",type:Asc.c_oAscChartTypeSettings.hBarStackedPer3d,iconCls:"bar-3d-pstack"},{group:"menu-chart-group-area",type:Asc.c_oAscChartTypeSettings.areaNormal,iconCls:"area-normal"},{group:"menu-chart-group-area",type:Asc.c_oAscChartTypeSettings.areaStacked,iconCls:"area-stack"},{group:"menu-chart-group-area",type:Asc.c_oAscChartTypeSettings.areaStackedPer,iconCls:"area-pstack"},{group:"menu-chart-group-scatter",type:Asc.c_oAscChartTypeSettings.scatter,iconCls:"point-normal"},{group:"menu-chart-group-stock",type:Asc.c_oAscChartTypeSettings.stock,iconCls:"stock-normal"}]},getSparkGroupData:function(t){return[{id:"menu-chart-group-sparkcolumn",inline:!0,headername:t?this.textSparks:void 0},{id:"menu-chart-group-sparkline",inline:!0},{id:"menu-chart-group-sparkwin",inline:!0}]},getSparkData:function(){return[{group:"menu-chart-group-sparkcolumn",type:Asc.c_oAscSparklineType.Column,allowSelected:!0,iconCls:"spark-column",tip:this.textColumnSpark},{group:"menu-chart-group-sparkline",type:Asc.c_oAscSparklineType.Line,allowSelected:!0,iconCls:"spark-line",tip:this.textLineSpark},{group:"menu-chart-group-sparkwin",type:Asc.c_oAscSparklineType.Stacked,allowSelected:!0,iconCls:"spark-win",tip:this.textWinLossSpark}]}}},Common.define.chartData||{})}),define("text!spreadsheeteditor/main/app/template/Toolbar.template",[],function(){ diff --git a/www/common/outer/local-store.js b/www/common/outer/local-store.js index 77d36645c..5d6f2e0ff 100644 --- a/www/common/outer/local-store.js +++ b/www/common/outer/local-store.js @@ -90,6 +90,15 @@ define([ localStorage.setItem(Constants.redirectToDriveKey, Boolean(bool)); }; + LocalStore.getPremium = function () { + try { + return JSON.parse(localStorage[Constants.isPremiumKey]); + } catch (err) { return; } + }; + LocalStore.setPremium = function (bool) { + localStorage.setItem(Constants.isPremiumKey, Boolean(bool)); + }; + LocalStore.login = function (hash, name, cb) { if (!hash) { throw new Error('expected a user hash'); } if (!name) { throw new Error('expected a user name'); } diff --git a/www/common/outer/x2t.js b/www/common/outer/x2t.js new file mode 100644 index 000000000..e712a9d96 --- /dev/null +++ b/www/common/outer/x2t.js @@ -0,0 +1,266 @@ +define([ + '/api/config', + '/bower_components/nthen/index.js', + '/common/common-util.js', +], function (ApiConfig, nThen, Util) { + var X2T = {}; + + var CURRENT_VERSION = X2T.CURRENT_VERSION = 'v4'; + var debug = function (str) { + if (localStorage.CryptPad_dev !== "1") { return; } + console.debug(str); + }; + + X2T.start = function () { + var x2tReady = Util.mkEvent(true); + var fetchFonts = function (x2t, obj, cb) { + if (!obj.fonts) { return void cb(); } + var path = ApiConfig.httpSafeOrigin + '/common/onlyoffice/'+CURRENT_VERSION+'/fonts/'; + var ver = '?' + ApiConfig.requireConf.urlArgs; + var fonts = obj.fonts; + var files = obj.fonts_files; + var suffixes = { + indexR: '', + indexB: '_Bold', + indexBI: '_Bold_Italic', + indexI: '_Italic', + }; + nThen(function (waitFor) { + fonts.forEach(function (font) { + // Check if the font is already loaded + if (!font.NeedStyles) { return; } + // Pick the variants we need (regular, bold, italic) + ['indexR', 'indexB', 'indexI', 'indexBI'].forEach(function (k) { + if (typeof(font[k]) !== "number" || font[k] === -1) { return; } // No matching file + var file = files[font[k]]; + + var name = font.Name + suffixes[k] + '.ttf'; + Util.fetch(path + file.Id + ver, waitFor(function (err, buffer) { + if (buffer) { + x2t.FS.writeFile('/working/fonts/' + name, buffer); + } + })); + }); + }); + }).nThen(function () { + cb(); + }); + }; + var x2tInitialized = false; + var x2tInit = function(x2t) { + debug("x2t mount"); + // x2t.FS.mount(x2t.MEMFS, {} , '/'); + x2t.FS.mkdir('/working'); + x2t.FS.mkdir('/working/media'); + x2t.FS.mkdir('/working/fonts'); + x2t.FS.mkdir('/working/themes'); + x2tInitialized = true; + x2tReady.fire(); + debug("x2t mount done"); + }; + var getX2T = function (cb) { + // Perform the x2t conversion + require(['/common/onlyoffice/x2t/x2t.js'], function() { // FIXME why does this fail without an access-control-allow-origin header? + var x2t = window.Module; + x2t.run(); + if (x2tInitialized) { + debug("x2t runtime already initialized"); + return void x2tReady.reg(function () { + cb(x2t); + }); + } + + x2t.onRuntimeInitialized = function() { + debug("x2t in runtime initialized"); + // Init x2t js module + x2tInit(x2t); + x2tReady.reg(function () { + cb(x2t); + }); + }; + }); + }; + + var getFormatId = function (ext) { + // Sheets + if (ext === 'xlsx') { return 257; } + if (ext === 'xls') { return 258; } + if (ext === 'ods') { return 259; } + if (ext === 'csv') { return 260; } + if (ext === 'pdf') { return 513; } + // Docs + if (ext === 'docx') { return 65; } + if (ext === 'doc') { return 66; } + if (ext === 'odt') { return 67; } + if (ext === 'txt') { return 69; } + if (ext === 'html') { return 70; } + + // Slides + if (ext === 'pptx') { return 129; } + if (ext === 'ppt') { return 130; } + if (ext === 'odp') { return 131; } + + return; + }; + var getFromId = function (ext) { + var id = getFormatId(ext); + if (!id) { return ''; } + return ''+id+''; + }; + var getToId = function (ext) { + var id = getFormatId(ext); + if (!id) { return ''; } + return ''+id+''; + }; + + var x2tConvertDataInternal = function(x2t, obj) { + var data = obj.data; + var fileName = obj.fileName; + var outputFormat = obj.outputFormat; + var images = obj.images; + debug("Converting Data for " + fileName + " to " + outputFormat); + + // PDF + var pdfData = ''; + if (outputFormat === "pdf" && typeof(data) === "object" && data.bin && data.buffer) { + // Add conversion rules + pdfData = "false" + + "/working/fonts/"; + // writing file to mounted working disk (in memory) + x2t.FS.writeFile('/working/' + fileName, data.bin); + x2t.FS.writeFile('/working/pdf.bin', data.buffer); + } else { + // writing file to mounted working disk (in memory) + x2t.FS.writeFile('/working/' + fileName, data); + } + + // Adding images + Object.keys(images || {}).forEach(function (_mediaFileName) { + if (/\.bin$/.test(_mediaFileName)) { return; } + var mediasSources = obj.mediasSources || {}; + var mediasData = obj.mediasData || {}; + var mediaData = mediasData[_mediaFileName]; + var mediaFileName; + if (mediaData) { // Theme image + var path = _mediaFileName.split('/'); + mediaFileName = path.pop(); + var theme = path[path.indexOf('themes') + 1]; + try { + x2t.FS.mkdir('/working/themes/'+theme); + x2t.FS.mkdir('/working/themes/'+theme+'/media'); + } catch (e) { + console.warn(e); + } + x2t.FS.writeFile('/working/themes/'+theme+'/media/' + mediaFileName, new Uint8Array(mediaData.content)); + debug("Writing media data " + mediaFileName + " at /working/themes/"+theme+"/media/"); + return; + } + // mediaData is undefined, check mediasSources + mediaFileName = _mediaFileName.substring(6); + var mediaSource = mediasSources[mediaFileName]; + mediaData = mediaSource ? mediasData[mediaSource.src] : undefined; + if (mediaData) { + debug("Writing media data " + mediaFileName); + debug("Data"); + var fileData = mediaData.content; + x2t.FS.writeFile('/working/media/' + mediaFileName, new Uint8Array(fileData)); + } else { + debug("Could not find media content for " + mediaFileName); + } + }); + + + var inputFormat = fileName.split('.').pop(); + + var params = "" + + "" + + "/working/" + fileName + "" + + "/working/themes" + + "/working/" + fileName + "." + outputFormat + "" + + pdfData + + getFromId(inputFormat) + + getToId(outputFormat) + + "false" + + ""; + // writing params file to mounted working disk (in memory) + x2t.FS.writeFile('/working/params.xml', params); + // running conversion + x2t.ccall("runX2T", ["number"], ["string"], ["/working/params.xml"]); + // reading output file from working disk (in memory) + var result; + try { + result = x2t.FS.readFile('/working/' + fileName + "." + outputFormat); + } catch (e) { + debug("Failed reading converted file"); + return ""; + } + return result; + }; + + var convert = function (obj, cb) { + console.error(obj); + getX2T(function (x2t) { + // Fonts + fetchFonts(x2t, obj, function () { + var o = obj.outputFormat; + + if (o !== 'pdf') { + // Add intermediary conversion to Microsoft Office format if needed + // (bin to pdf is allowed) + [ + // Import from Open Document + {source: '.ods', format: 'xlsx'}, + {source: '.odt', format: 'docx'}, + {source: '.odp', format: 'pptx'}, + // Export to non Microsoft Office + {source: '.bin', type: 'sheet', format: 'xlsx'}, + {source: '.bin', type: 'doc', format: 'docx'}, + {source: '.bin', type: 'presentation', format: 'pptx'}, + ].forEach(function (_step) { + if (obj.fileName.endsWith(_step.source) && obj.outputFormat !== _step.format && + (!_step.type || _step.type === obj.type)) { + obj.outputFormat = _step.format; + obj.data = x2tConvertDataInternal(x2t, obj); + obj.fileName += '.'+_step.format; + } + }); + obj.outputFormat = o; + } + + var data = x2tConvertDataInternal(x2t, obj); + + // Convert to bin -- Import + // We need to extract the images + var images; + if (o === 'bin') { + images = []; + var files = x2t.FS.readdir("/working/media/"); + files.forEach(function (file) { + if (file !== "." && file !== "..") { + var fileData = x2t.FS.readFile("/working/media/" + file, { + encoding : "binary" + }); + images.push({ + name: file, + data: fileData + }); + } + }); + + } + + cb({ + data: data, + images: images + }); + }); + }); + }; + + return { + convert: convert + }; + }; + + return X2T; +}); diff --git a/www/common/proxy-manager.js b/www/common/proxy-manager.js index d87572d7e..5cf44b467 100644 --- a/www/common/proxy-manager.js +++ b/www/common/proxy-manager.js @@ -548,6 +548,8 @@ define([ var secret = Hash.getSecrets('drive', parsed.hash, folderData.password); SF.upgrade(secret.channel, secret); Env.folders[folderId].userObject.setReadOnly(false, secret.keys.secondaryKey); + waitFor.abort(); + return void cb(folderId); } if (err) { waitFor.abort(); diff --git a/www/common/sframe-common-file.js b/www/common/sframe-common-file.js index 33d46caf6..e4f6c9260 100644 --- a/www/common/sframe-common-file.js +++ b/www/common/sframe-common-file.js @@ -660,6 +660,11 @@ define([ var updateDecryptProgress = function (progressValue) { var text = Math.round(progressValue * 100) + '%'; text += progressValue === 1 ? '' : ' (' + Messages.download_step2 + '...)'; + if (progressValue === 2) { + Messages.download_step3 = "Converting..."; // XXX + text = Messages.download_step3; + progressValue = 1; + } $pv.text(text); $pb.css({ width: (progressValue * 100) + '%' diff --git a/www/common/sframe-common-outer.js b/www/common/sframe-common-outer.js index 5223898d1..0053de3a6 100644 --- a/www/common/sframe-common-outer.js +++ b/www/common/sframe-common-outer.js @@ -72,6 +72,7 @@ define([ var SFrameChannel; var sframeChan; var SecureIframe; + var OOIframe; var Messaging; var Notifier; var Utils = { @@ -98,6 +99,7 @@ define([ '/common/cryptget.js', '/common/outer/worker-channel.js', '/secureiframe/main.js', + '/common/onlyoffice/ooiframe.js', '/common/common-messaging.js', '/common/common-notifier.js', '/common/common-hash.js', @@ -112,7 +114,7 @@ define([ '/common/test.js', '/common/userObject.js', ], waitFor(function (_CpNfOuter, _Cryptpad, _Crypto, _Cryptget, _SFrameChannel, - _SecureIframe, _Messaging, _Notifier, _Hash, _Util, _Realtime, _Notify, + _SecureIframe, _OOIframe, _Messaging, _Notifier, _Hash, _Util, _Realtime, _Notify, _Constants, _Feedback, _LocalStore, _Cache, _AppConfig, _Test, _UserObject) { CpNfOuter = _CpNfOuter; Cryptpad = _Cryptpad; @@ -120,6 +122,7 @@ define([ Cryptget = _Cryptget; SFrameChannel = _SFrameChannel; SecureIframe = _SecureIframe; + OOIframe = _OOIframe; Messaging = _Messaging; Notifier = _Notifier; Utils.Hash = _Hash; @@ -297,6 +300,13 @@ define([ })); }; + if (sessionStorage.CP_formExportSheet && parsed.type === 'sheet') { + try { + Cryptpad.fromContent = JSON.parse(sessionStorage.CP_formExportSheet); + } catch (e) { console.error(e); } + delete sessionStorage.CP_formExportSheet; + } + // New pad options var options = parsed.getOptions(); if (options.newPadOpts) { @@ -571,6 +581,8 @@ define([ var edPublic, curvePublic, notifications, isTemplate; var settings = {}; var isSafe = ['debug', 'profile', 'drive', 'teams', 'calendar', 'file'].indexOf(currentPad.app) !== -1; + var isOO = ['sheet', 'doc', 'presentation'].indexOf(parsed.type) !== -1; + var ooDownloadData = {}; var isDeleted = isNewFile && currentPad.hash.length > 0; if (isDeleted) { @@ -631,11 +643,13 @@ define([ channel: secret.channel, enableSF: localStorage.CryptPad_SF === "1", // TODO to remove when enabled by default devMode: localStorage.CryptPad_dev === "1", - fromFileData: Cryptpad.fromFileData ? { + fromFileData: Cryptpad.fromFileData ? (isOO ? Cryptpad.fromFileData : { title: Cryptpad.fromFileData.title - } : undefined, + }) : undefined, + fromContent: Cryptpad.fromContent, burnAfterReading: burnAfterReading, - storeInTeam: Cryptpad.initialTeam || (Cryptpad.initialPath ? -1 : undefined) + storeInTeam: Cryptpad.initialTeam || (Cryptpad.initialPath ? -1 : undefined), + supportsWasm: Utils.Util.supportsWasm() }; if (window.CryptPad_newSharedFolder) { additionalPriv.newSharedFolder = window.CryptPad_newSharedFolder; @@ -650,6 +664,17 @@ define([ additionalPriv.registeredOnly = true; } + // XXX PREMIUM + var priv = metaObj.priv; + var p = Utils.Util.checkRestrictedApp(parsed.type, AppConfig, + Utils.Constants.earlyAccessApps, priv.plan, additionalPriv.loggedIn); + if (p === 0 || p === -1) { + additionalPriv.premiumOnly = true; + } + if (p === -2) { + additionalPriv.earlyAccessBlocked = true; + } + if (isSafe) { additionalPriv.hashes = hashes; additionalPriv.password = password; @@ -661,6 +686,10 @@ define([ cfg.addData(metaObj.priv, Cryptpad, metaObj.user, Utils); } + if (metaObj && metaObj.priv && typeof(metaObj.priv.plan) === "string") { + Utils.LocalStore.setPremium(metaObj.priv.plan); + } + sframeChan.event('EV_METADATA_UPDATE', metaObj); }); }; @@ -1032,6 +1061,51 @@ define([ } }, cb); }); + sframeChan.on('Q_GET_HISTORY_RANGE', function (data, cb) { + var nSecret = secret; + if (cfg.isDrive) { + // Shared folder or user hash or fs hash + var hash = Utils.LocalStore.getUserHash() || Utils.LocalStore.getFSHash(); + if (data.sharedFolder) { hash = data.sharedFolder.hash; } + if (hash) { + var password = (data.sharedFolder && data.sharedFolder.password) || undefined; + nSecret = Utils.Hash.getSecrets('drive', hash, password); + } + } + if (data.href) { + var _parsed = Utils.Hash.parsePadUrl(data.href); + nSecret = Utils.Hash.getSecrets(_parsed.type, _parsed.hash, data.password); + } + if (data.isDownload && ooDownloadData[data.isDownload]) { + var ooData = ooDownloadData[data.isDownload]; + delete ooDownloadData[data.isDownload]; + nSecret = Utils.Hash.getSecrets('sheet', ooData.hash, ooData.password); + } + var channel = nSecret.channel; + var validate = nSecret.keys.validateKey; + var crypto = Crypto.createEncryptor(nSecret.keys); + Cryptpad.getHistoryRange({ + channel: data.channel || channel, + validateKey: validate, + toHash: data.toHash, + lastKnownHash: data.lastKnownHash + }, function (data) { + cb({ + isFull: data.isFull, + messages: data.messages.map(function (obj) { + // The 3rd parameter "true" means we're going to skip signature validation. + // We don't need it since the message is already validated serverside by hk + return { + msg: crypto.decrypt(obj.msg, true, true), + serverHash: obj.serverHash, + author: obj.author, + time: obj.time + }; + }), + lastKnownHash: data.lastKnownHash + }); + }); + }); }; addCommonRpc(sframeChan, isSafe); @@ -1273,46 +1347,6 @@ define([ }); }); }); - sframeChan.on('Q_GET_HISTORY_RANGE', function (data, cb) { - var nSecret = secret; - if (cfg.isDrive) { - // Shared folder or user hash or fs hash - var hash = Utils.LocalStore.getUserHash() || Utils.LocalStore.getFSHash(); - if (data.sharedFolder) { hash = data.sharedFolder.hash; } - if (hash) { - var password = (data.sharedFolder && data.sharedFolder.password) || undefined; - nSecret = Utils.Hash.getSecrets('drive', hash, password); - } - } - if (data.href) { - var _parsed = Utils.Hash.parsePadUrl(data.href); - nSecret = Utils.Hash.getSecrets(_parsed.type, _parsed.hash, data.password); - } - var channel = nSecret.channel; - var validate = nSecret.keys.validateKey; - var crypto = Crypto.createEncryptor(nSecret.keys); - Cryptpad.getHistoryRange({ - channel: data.channel || channel, - validateKey: validate, - toHash: data.toHash, - lastKnownHash: data.lastKnownHash - }, function (data) { - cb({ - isFull: data.isFull, - messages: data.messages.map(function (obj) { - // The 3rd parameter "true" means we're going to skip signature validation. - // We don't need it since the message is already validated serverside by hk - return { - msg: crypto.decrypt(obj.msg, true, true), - serverHash: obj.serverHash, - author: obj.author, - time: obj.time - }; - }), - lastKnownHash: data.lastKnownHash - }); - }); - }); // Store sframeChan.on('Q_DRIVE_GETDELETED', function (data, cb) { @@ -1462,6 +1496,38 @@ define([ initSecureModal('share', data || {}); }); + // OO iframe + var OOIframeObject = {}; + var initOOIframe = function (cfg, cb) { + if (!OOIframeObject.$iframe) { + var config = {}; + config.addCommonRpc = addCommonRpc; + config.modules = { + Cryptpad: Cryptpad, + SFrameChannel: SFrameChannel, + Utils: Utils + }; + OOIframeObject.$iframe = $('