api.js 144 KB
Newer Older
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1
/*
2
 * (c) Copyright Ascensio System SIA 2010-2017
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";
34

Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
35
var editor;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
36 37 38 39
(/**
 * @param {Window} window
 * @param {undefined} undefined
 */
40
  function(window, undefined) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
41 42
  var asc = window["Asc"];
  var prot;
43

44 45 46
  var c_oAscAdvancedOptionsAction = AscCommon.c_oAscAdvancedOptionsAction;
  var DownloadType = AscCommon.DownloadType;
  var c_oAscLockTypes = AscCommon.c_oAscLockTypes;
47
  var CColor = AscCommon.CColor;
48 49 50 51 52 53
  var g_oDocumentUrls = AscCommon.g_oDocumentUrls;
  var sendCommand = AscCommon.sendCommand;
  var mapAscServerErrorToAscError = AscCommon.mapAscServerErrorToAscError;
  var parserHelp = AscCommon.parserHelp;
  var g_oIdCounter = AscCommon.g_oIdCounter;
  var g_oTableId = AscCommon.g_oTableId;
54

55
  var c_oAscLockTypeElem = AscCommonExcel.c_oAscLockTypeElem;
56

57
  var c_oAscError = asc.c_oAscError;
58 59 60 61
  var c_oAscFileType = asc.c_oAscFileType;
  var c_oAscAsyncAction = asc.c_oAscAsyncAction;
  var c_oAscAdvancedOptionsID = asc.c_oAscAdvancedOptionsID;
  var c_oAscAsyncActionType = asc.c_oAscAsyncActionType;
62

63 64
  var History = null;

Alexander.Trofimov's avatar
Alexander.Trofimov committed
65

66 67
  /**
   *
Alexander.Trofimov's avatar
Alexander.Trofimov committed
68
   * @param config
69 70 71
   * @param eventsHandlers
   * @constructor
   * @returns {spreadsheet_api}
72
   * @extends {AscCommon.baseEditorsApi}
73
   */
Alexander.Trofimov's avatar
Alexander.Trofimov committed
74
  function spreadsheet_api(config) {
75
    AscCommon.baseEditorsApi.call(this, config, AscCommon.c_oEditorId.Spreadsheet);
76

Alexander.Trofimov's avatar
Alexander.Trofimov committed
77
    /************ private!!! **************/
Alexander.Trofimov's avatar
Alexander.Trofimov committed
78
    this.topLineEditorName = config['id-input'] || '';
Alexander.Trofimov's avatar
Alexander.Trofimov committed
79 80
    this.topLineEditorElement = null;

81
    this.controller = null;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
82

Alexander.Trofimov's avatar
Alexander.Trofimov committed
83
    this.handlers = new AscCommonExcel.asc_CHandlersList();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
84 85 86
    // Вид печати
    this.adjustPrint = null;

87
    this.fontRenderingMode = Asc.c_oAscFontRenderingModeType.hintingAndSubpixeling;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
88 89
    this.wb = null;
    this.wbModel = null;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
90
    this.tmpLocale = null;
91
    this.tmpLocalization = null;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113

    this.documentFormatSave = c_oAscFileType.XLSX;

    // объекты, нужные для отправки в тулбар (шрифты, стили)
    this._gui_control_colors = null;
    this.GuiControlColorsMap = null;
    this.IsSendStandartColors = false;

    this.asyncMethodCallback = undefined;

    // Переменная отвечает, загрузились ли фонты
    this.FontLoadWaitComplete = false;
    // Переменная отвечает, отрисовали ли мы все (иначе при рестарте, получится переинициализация)
    this.DocumentLoadComplete = false;
    // Переменная, которая отвечает, послали ли мы окончание открытия документа
    this.IsSendDocumentLoadCompleate = false;
    //текущий обьект куда записываются информация для update, когда принимаются изменения в native редакторе
    this.oRedoObjectParamNative = null;

    this.collaborativeEditing = null;

    // AutoSave
114
    this.autoSaveGapRealTime = 30;	  // Интервал быстрого автосохранения (когда выставлен флаг realtime) - 30 мс.
Alexander.Trofimov's avatar
Alexander.Trofimov committed
115 116 117 118 119 120 121 122 123

    // Shapes
    this.isStartAddShape = false;
    this.shapeElementId = null;
    this.textArtElementId = null;
    this.isImageChangeUrl = false;
    this.isShapeImageChangeUrl = false;
    this.isTextArtChangeUrl = false;

124 125 126 127

	  // Styles sizes
      this.styleThumbnailWidth = 112;
	  this.styleThumbnailHeight = 38;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
128 129 130 131 132 133

    this.formulasList = null;	// Список всех формул

    this._init();
    return this;
  }
134
  spreadsheet_api.prototype = Object.create(AscCommon.baseEditorsApi.prototype);
135
  spreadsheet_api.prototype.constructor = spreadsheet_api;
136 137 138 139
  spreadsheet_api.prototype.sendEvent = function() {
    this.handlers.trigger.apply(this.handlers, arguments);
  };

Alexander.Trofimov's avatar
Alexander.Trofimov committed
140
  spreadsheet_api.prototype._init = function() {
141
    AscCommon.baseEditorsApi.prototype._init.call(this);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
142
    this.topLineEditorElement = document.getElementById(this.topLineEditorName);
143 144
    // ToDo нужно ли это
    asc['editor'] = ( asc['editor'] || this );
145
    AscCommon.AscBrowser.checkZoom();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
146 147 148 149 150 151 152 153
  };

  spreadsheet_api.prototype.asc_CheckGuiControlColors = function() {
    // потом реализовать проверку на то, что нужно ли посылать

    var arr_colors = new Array(10);
    var _count = arr_colors.length;
    for (var i = 0; i < _count; ++i) {
154
      var color = AscCommonExcel.g_oColorManager.getThemeColor(i);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
      arr_colors[i] = new CColor(color.getR(), color.getG(), color.getB());
    }

    // теперь проверим
    var bIsSend = false;
    if (this.GuiControlColorsMap != null) {
      for (var i = 0; i < _count; ++i) {
        var _color1 = this.GuiControlColorsMap[i];
        var _color2 = arr_colors[i];

        if ((_color1.r !== _color2.r) || (_color1.g !== _color2.g) || (_color1.b !== _color2.b)) {
          bIsSend = true;
          break;
        }
      }
    } else {
      this.GuiControlColorsMap = new Array(_count);
      bIsSend = true;
    }
Oleg.Korshul's avatar
Oleg.Korshul committed
174

Alexander.Trofimov's avatar
Alexander.Trofimov committed
175 176 177 178
    if (bIsSend) {
      for (var i = 0; i < _count; ++i) {
        this.GuiControlColorsMap[i] = arr_colors[i];
      }
179

Alexander.Trofimov's avatar
Alexander.Trofimov committed
180 181 182
      this.asc_SendControlColors();
    }
  };
183

Alexander.Trofimov's avatar
Alexander.Trofimov committed
184 185 186
  spreadsheet_api.prototype.asc_SendControlColors = function() {
    var standart_colors = null;
    if (!this.IsSendStandartColors) {
187 188
      var standartColors = AscCommon.g_oStandartColors;
      var _c_s = standartColors.length;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
189
      standart_colors = new Array(_c_s);
190

Alexander.Trofimov's avatar
Alexander.Trofimov committed
191
      for (var i = 0; i < _c_s; ++i) {
192
        standart_colors[i] = new CColor(standartColors[i].R, standartColors[i].G, standartColors[i].B);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
193
      }
194

Alexander.Trofimov's avatar
Alexander.Trofimov committed
195 196
      this.IsSendStandartColors = true;
    }
197

Alexander.Trofimov's avatar
Alexander.Trofimov committed
198
    var _count = this.GuiControlColorsMap.length;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
199

Alexander.Trofimov's avatar
Alexander.Trofimov committed
200 201
    var _ret_array = new Array(_count * 6);
    var _cur_index = 0;
202

Alexander.Trofimov's avatar
Alexander.Trofimov committed
203
    for (var i = 0; i < _count; ++i) {
204 205
      var basecolor = AscCommonExcel.g_oColorManager.getThemeColor(i);
      var aTints = AscCommonExcel.g_oThemeColorsDefaultModsSpreadsheet[AscCommon.GetDefaultColorModsIndex(basecolor.getR(), basecolor.getG(), basecolor.getB())];
Alexander.Trofimov's avatar
Alexander.Trofimov committed
206 207
      for (var j = 0, length = aTints.length; j < length; ++j) {
        var tint = aTints[j];
208
        var color = AscCommonExcel.g_oColorManager.getThemeColor(i, tint);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
209 210 211 212
        _ret_array[_cur_index] = new CColor(color.getR(), color.getG(), color.getB());
        _cur_index++;
      }
    }
213

Alexander.Trofimov's avatar
Alexander.Trofimov committed
214 215
    this.asc_SendThemeColors(_ret_array, standart_colors);
  };
216

217
  spreadsheet_api.prototype.asc_getCurrencySymbols = function () {
218 219 220 221 222 223
		var result = {};
		for (var key in AscCommon.g_aCultureInfos) {
			result[key] = AscCommon.g_aCultureInfos[key].CurrencySymbol;
		}
		return result;
	};
224
	spreadsheet_api.prototype.asc_getLocaleExample = function(format, value, culture) {
225 226
		var cultureInfo = AscCommon.g_aCultureInfos[culture] || AscCommon.g_oDefaultCultureInfo;
		var numFormat = AscCommon.oNumFormatCache.get(format);
227 228 229 230 231 232 233 234 235 236 237 238 239 240
		var res;
		if (null == value) {
			var ws = this.wbModel.getActiveWs();
			var activeCell = ws.selectionRange.activeCell;
			var cell = ws._getCellNoEmpty(activeCell.row, activeCell.col);
			if (cell) {
				res = cell.getValueForExample(numFormat, cultureInfo);
			} else {
				res = '';
			}
		} else {
			res = numFormat.formatToChart(value, cultureInfo);
		}
		return res;
241
	};
242
	spreadsheet_api.prototype.asc_getFormatCells = function(info) {
243
		return AscCommon.getFormatCells(info);
244
	};
245
  spreadsheet_api.prototype.asc_getLocaleCurrency = function(val) {
246
    var cultureInfo = AscCommon.g_aCultureInfos[val];
247
    if (!cultureInfo) {
248
      cultureInfo = AscCommon.g_aCultureInfos[1033];
249
    }
250
    return AscCommonExcel.getCurrencyFormat(cultureInfo, 2, true, true);
251
  };
Alexander.Trofimov's avatar
Alexander.Trofimov committed
252
  spreadsheet_api.prototype.asc_setLocale = function(val) {
253 254 255 256
    if (!this.isLoadFullApi) {
      this.tmpLocale = val;
      return;
    }
Alexander.Trofimov's avatar
Alexander.Trofimov committed
257 258 259
    if (null === val) {
      return;
    }
260 261 262 263 264 265 266 267 268
    if (AscCommon.setCurrentCultureInfo(val)) {
      parserHelp.setDigitSeparator(AscCommon.g_oDefaultCultureInfo.NumberDecimalSeparator);
      if (this.wbModel) {
        AscCommon.oGeneralEditFormatCache.cleanCache();
        AscCommon.oNumFormatCache.cleanCache();
        this.wbModel.rebuildColors();
        if (this.IsSendDocumentLoadCompleate) {
          this._onUpdateAfterApplyChanges();
        }
Alexander.Trofimov's avatar
Alexander.Trofimov committed
269 270 271 272 273
      }
    }
  };

  spreadsheet_api.prototype.asc_LoadEmptyDocument = function() {
274
    this.CoAuthoringApi.auth(this.getViewMode());
Alexander.Trofimov's avatar
Alexander.Trofimov committed
275
    this.onEndLoadFile(true);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
276 277
  };

278
  spreadsheet_api.prototype._openDocument = function(data) {
279
    var wb = new AscCommonExcel.Workbook(this.handlers, this);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
280 281
    this.initGlobalObjects(wb);
    this.wbModel = wb;
282
    var oBinaryFileReader = new AscCommonExcel.BinaryFileReader();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
283 284 285 286 287 288 289
    oBinaryFileReader.Read(data, wb);
    g_oIdCounter.Set_Load(false);
    return wb;
  };

  spreadsheet_api.prototype.initGlobalObjects = function(wbModel) {
    // History & global counters
290
    History.init(wbModel);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
291

292
    g_oTableId.init();
293 294 295 296 297 298 299
    AscCommonExcel.g_oUndoRedoCell = new AscCommonExcel.UndoRedoCell(wbModel);
    AscCommonExcel.g_oUndoRedoWorksheet = new AscCommonExcel.UndoRedoWoorksheet(wbModel);
    AscCommonExcel.g_oUndoRedoWorkbook = new AscCommonExcel.UndoRedoWorkbook(wbModel);
    AscCommonExcel.g_oUndoRedoCol = new AscCommonExcel.UndoRedoRowCol(wbModel, false);
    AscCommonExcel.g_oUndoRedoRow = new AscCommonExcel.UndoRedoRowCol(wbModel, true);
    AscCommonExcel.g_oUndoRedoComment = new AscCommonExcel.UndoRedoComment(wbModel);
    AscCommonExcel.g_oUndoRedoAutoFilters = new AscCommonExcel.UndoRedoAutoFilters(wbModel);
300
    AscCommonExcel.g_oUndoRedoSparklines = new AscCommonExcel.UndoRedoSparklines(wbModel);
konovalovsergey's avatar
konovalovsergey committed
301
    AscCommonExcel.g_DefNameWorksheet = new AscCommonExcel.Woorksheet(wbModel, -1);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
302 303
  };

304
  spreadsheet_api.prototype.asc_DownloadAs = function(typeFile, bIsDownloadEvent) {//передаем число соответствующее своему формату. например  c_oAscFileType.XLSX
Alexander.Trofimov's avatar
Alexander.Trofimov committed
305 306 307 308
    if (!this.canSave || this.isChartEditor || c_oAscAdvancedOptionsAction.None !== this.advancedOptionsAction) {
      return;
    }

309
    if (c_oAscFileType.PDF === typeFile) {
310
      this.adjustPrint = new Asc.asc_CAdjustPrint();
311
    }
312
    this._asc_downloadAs(typeFile, c_oAscAsyncAction.DownloadAs, {downloadType: bIsDownloadEvent ? DownloadType.Download: DownloadType.None});
Alexander.Trofimov's avatar
Alexander.Trofimov committed
313
  };
314 315 316
	spreadsheet_api.prototype.saveCheck = function() {
		return !(!this.canSave || this.isChartEditor || c_oAscAdvancedOptionsAction.None !== this.advancedOptionsAction || this.isLongAction());
	};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
317
	spreadsheet_api.prototype.asc_Save = function (isAutoSave, isUndoRequest, isIdle) {
konovalovsergey's avatar
konovalovsergey committed
318
		this.IsUserSave = !isAutoSave;
319 320
		if (!this.saveCheck()) {
			return false;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
321 322 323
		}

		if (!(this.asc_isDocumentCanSave() || this.collaborativeEditing.haveOtherChanges() || this.canUnlockDocument)) {
konovalovsergey's avatar
konovalovsergey committed
324 325 326
			if (this.isForceSaveOnUserSave && this.IsUserSave) {
				this.forceSave();
			}
327
			return false;
328
		}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
329

Alexander.Trofimov's avatar
Alexander.Trofimov committed
330 331 332 333
		var tmpHandlers;
		if (isIdle) {
			tmpHandlers = this.wbModel.handlers.handlers['asc_onError'];
			this.wbModel.handlers.handlers['asc_onError'] = null;
334
		}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
335

336 337
      /* Нужно закрыть редактор (до выставления флага canSave, т.к. мы должны успеть отправить
       asc_onDocumentModifiedChanged для подписки на сборку) Баг http://bugzilla.onlyoffice.com/show_bug.cgi?id=28331 */
Alexander.Trofimov's avatar
Alexander.Trofimov committed
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
		if (!this.asc_closeCellEditor()) {
			if (isIdle) {
				this.asc_closeCellEditor(true);
			} else {
				return false;
			}
		}

		if (isIdle) {
			this.wbModel.handlers.handlers['asc_onError'] = tmpHandlers;
		}

		if (this.IsUserSave) {
			this.sync_StartAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.Save);
		}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
353

354 355
		// Не даем пользователю сохранять, пока не закончится сохранение
		this.canSave = false;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
356

357 358 359 360
		var t = this;
		this.CoAuthoringApi.askSaveChanges(function (e) {
			t.onSaveCallback(e);
		});
361
		return true;
362
	};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
363

364
  spreadsheet_api.prototype.asc_Print = function(adjustPrint, bIsDownloadEvent) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
365 366 367 368 369 370
    if (window["AscDesktopEditor"]) {
      window.AscDesktopEditor_PrintData = adjustPrint;
      window["AscDesktopEditor"]["Print"]();
      return;
    }

371
    this.adjustPrint = adjustPrint ? adjustPrint : new Asc.asc_CAdjustPrint();
372
    this._asc_downloadAs(c_oAscFileType.PDF, c_oAscAsyncAction.Print, {downloadType: bIsDownloadEvent ? DownloadType.Print: DownloadType.None});
Alexander.Trofimov's avatar
Alexander.Trofimov committed
373 374 375
  };

  spreadsheet_api.prototype.asc_Copy = function() {
Oleg Korshul's avatar
Oleg Korshul committed
376 377
    if (window["AscDesktopEditor"])
    {
378
      window["asc_desktop_copypaste"](this, "Copy");
Oleg Korshul's avatar
Oleg Korshul committed
379
      return true;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
380
    }
Oleg Korshul's avatar
Oleg Korshul committed
381
    return AscCommon.g_clipboardBase.Button_Copy();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
382 383 384
  };

  spreadsheet_api.prototype.asc_Paste = function() {
Oleg Korshul's avatar
Oleg Korshul committed
385 386
    if (window["AscDesktopEditor"])
    {
387
      window["asc_desktop_copypaste"](this, "Paste");
Oleg Korshul's avatar
Oleg Korshul committed
388
      return true;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
389
    }
Oleg Korshul's avatar
Oleg Korshul committed
390
    if (!AscCommon.g_clipboardBase.IsWorking()) {
Oleg Korshul's avatar
Oleg Korshul committed
391 392
      return AscCommon.g_clipboardBase.Button_Paste();
    }
Oleg Korshul's avatar
.  
Oleg Korshul committed
393
    return false;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
394
  };
395 396 397 398 399
  
  spreadsheet_api.prototype.asc_SpecialPaste = function(props) {
    return AscCommon.g_clipboardBase.Special_Paste(props);
  };
  
400
  spreadsheet_api.prototype.asc_SpecialPasteData = function(props) {
401
	if (!this.getViewMode()) {
402
      this.wb.specialPasteData(props);
403 404
    }
  };
Alexander.Trofimov's avatar
Alexander.Trofimov committed
405

406 407 408 409 410 411
  spreadsheet_api.prototype.asc_ShowSpecialPasteButton = function(props) {
      if (!this.getViewMode()) {
          this.wb.showSpecialPasteButton(props);
      }
  };

Alexander.Trofimov's avatar
Alexander.Trofimov committed
412
  spreadsheet_api.prototype.asc_Cut = function() {
Oleg Korshul's avatar
Oleg Korshul committed
413 414
    if (window["AscDesktopEditor"])
    {
415
      window["asc_desktop_copypaste"](this, "Cut");
Oleg Korshul's avatar
Oleg Korshul committed
416
      return true;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
417
    }
Oleg Korshul's avatar
Oleg Korshul committed
418
    return AscCommon.g_clipboardBase.Button_Cut();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
419 420
  };

GoshaZotov's avatar
GoshaZotov committed
421
  spreadsheet_api.prototype.asc_PasteData = function (_format, data1, data2, text_data) {
422
    if (!this.getViewMode()) {
GoshaZotov's avatar
GoshaZotov committed
423
      this.wb.pasteData(_format, data1, data2, text_data);
424
    }
425 426
  };

427 428
  spreadsheet_api.prototype.asc_CheckCopy = function (_clipboard /* CClipboardData */, _formats) {
    return this.wb.checkCopyToClipboard(_clipboard, _formats);
429
  };
GoshaZotov's avatar
GoshaZotov committed
430

431
  spreadsheet_api.prototype.asc_SelectionCut = function () {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
432 433 434
    if (!this.getViewMode()) {
      this.wb.selectionCut();
    }
GoshaZotov's avatar
GoshaZotov committed
435 436
  };

Alexander.Trofimov's avatar
Alexander.Trofimov committed
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
  spreadsheet_api.prototype.asc_bIsEmptyClipboard = function() {
    var result = this.wb.bIsEmptyClipboard();
    this.wb.restoreFocus();
    return result;
  };

  spreadsheet_api.prototype.asc_Undo = function() {
    this.wb.undo();
    this.wb.restoreFocus();
  };

  spreadsheet_api.prototype.asc_Redo = function() {
    this.wb.redo();
    this.wb.restoreFocus();
  };

453 454
  spreadsheet_api.prototype.asc_Resize = function () {
    AscCommon.AscBrowser.checkZoom();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
455 456
    if (this.wb) {
      this.wb.resize();
Oleg Korshul's avatar
Oleg Korshul committed
457

458
      if (AscCommon.g_inputContext) {
Oleg Korshul's avatar
Oleg Korshul committed
459
        AscCommon.g_inputContext.onResize("ws-canvas-outer");
460
      }
Alexander.Trofimov's avatar
Alexander.Trofimov committed
461 462 463 464 465 466 467 468 469 470 471 472 473
    }
  };

  spreadsheet_api.prototype.asc_addAutoFilter = function(styleName, addFormatTableOptionsObj) {
    var ws = this.wb.getWorksheet();
    return ws.addAutoFilter(styleName, addFormatTableOptionsObj);
  };

  spreadsheet_api.prototype.asc_changeAutoFilter = function(tableName, optionType, val) {
    var ws = this.wb.getWorksheet();
    return ws.changeAutoFilter(tableName, optionType, val);
  };

GoshaZotov's avatar
GoshaZotov committed
474
  spreadsheet_api.prototype.asc_applyAutoFilter = function(autoFilterObject) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
475
    var ws = this.wb.getWorksheet();
GoshaZotov's avatar
GoshaZotov committed
476
    ws.applyAutoFilter(autoFilterObject);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
477
  };
478 479 480 481 482
  
  spreadsheet_api.prototype.asc_applyAutoFilterByType = function(autoFilterObject) {
    var ws = this.wb.getWorksheet();
    ws.applyAutoFilterByType(autoFilterObject);
  };
483 484 485
  
  spreadsheet_api.prototype.asc_reapplyAutoFilter = function(displayName) {
    var ws = this.wb.getWorksheet();
GoshaZotov's avatar
GoshaZotov committed
486
    ws.reapplyAutoFilter(displayName);
487
  };
Alexander.Trofimov's avatar
Alexander.Trofimov committed
488

GoshaZotov's avatar
GoshaZotov committed
489
  spreadsheet_api.prototype.asc_sortColFilter = function(type, cellId, displayName, color, bIsExpandRange) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
490
    var ws = this.wb.getWorksheet();
GoshaZotov's avatar
GoshaZotov committed
491
    ws.sortRange(type, cellId, displayName, color, bIsExpandRange);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
492 493
  };

494
  spreadsheet_api.prototype.asc_getAddFormatTableOptions = function(range) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
495
    var ws = this.wb.getWorksheet();
496
    return ws.getAddFormatTableOptions(range);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
497 498 499 500 501 502
  };

  spreadsheet_api.prototype.asc_clearFilter = function() {
    var ws = this.wb.getWorksheet();
    return ws.clearFilter();
  };
503
  
504 505 506 507 508
  spreadsheet_api.prototype.asc_clearFilterColumn = function(cellId, displayName) {
    var ws = this.wb.getWorksheet();
    return ws.clearFilterColumn(cellId, displayName);
  };
  
509 510 511 512
  spreadsheet_api.prototype.asc_changeSelectionFormatTable = function(tableName, optionType) {
    var ws = this.wb.getWorksheet();
    return ws.af_changeSelectionFormatTable(tableName, optionType);
  };
513
  
514
  spreadsheet_api.prototype.asc_changeFormatTableInfo = function(tableName, optionType, val) {
515
    var ws = this.wb.getWorksheet();
516
    return ws.af_changeFormatTableInfo(tableName, optionType, val);
517
  };
518 519 520 521 522 523 524 525
  
  spreadsheet_api.prototype.asc_insertCellsInTable = function(tableName, optionType) {
    var ws = this.wb.getWorksheet();
    return ws.af_insertCellsInTable(tableName, optionType);
  };
  
  spreadsheet_api.prototype.asc_deleteCellsInTable = function(tableName, optionType) {
    var ws = this.wb.getWorksheet();
526
    return ws.af_deleteCellsInTable(tableName, optionType);
527
  };
528 529 530 531 532
  
  spreadsheet_api.prototype.asc_changeDisplayNameTable = function(tableName, newName) {
    var ws = this.wb.getWorksheet();
    return ws.af_changeDisplayNameTable(tableName, newName);
  };
533 534 535 536 537
  
  spreadsheet_api.prototype.asc_changeTableRange = function(tableName, range) {
    var ws = this.wb.getWorksheet();
    return ws.af_changeTableRange(tableName, range);
  };
538 539 540 541 542 543

  spreadsheet_api.prototype.asc_convertTableToRange = function(tableName) {
    var ws = this.wb.getWorksheet();
    return ws.af_convertTableToRange(tableName);
  };

544 545 546 547
  spreadsheet_api.prototype.asc_getTablePictures = function (props) 
  { 
	return this.wb.getTablePictures(props); 
  };
Alexander.Trofimov's avatar
Alexander.Trofimov committed
548

549
  spreadsheet_api.prototype.getViewMode = function() {
550
    return this.isViewMode;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
551 552
  };

553 554
  spreadsheet_api.prototype.asc_setViewMode = function (isViewMode) {
    this.isViewMode = !!isViewMode;
555
    if (!this.isLoadFullApi) {
556 557
      return;
    }
558
    this.controller.setViewerMode(isViewMode);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
559
    if (this.collaborativeEditing) {
560
      this.collaborativeEditing.setViewerMode(isViewMode);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
561 562
    }

563
    if (false === isViewMode) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
      // Отправка стилей
      this._sendWorkbookStyles();
      if (this.IsSendDocumentLoadCompleate && this.collaborativeEditing) {
        // Принимаем чужие изменения
        this.collaborativeEditing.applyChanges();
        // Пересылаем свои изменения
        this.collaborativeEditing.sendChanges();
      }
    }
  };

  /*
   idOption идентификатор дополнительного параметра, пока c_oAscAdvancedOptionsID.CSV.
   option - какие свойства применить, пока массив. для CSV объект asc_CCSVAdvancedOptions(codepage, delimiter)
   exp:	asc_setAdvancedOptions(c_oAscAdvancedOptionsID.CSV, new Asc.asc_CCSVAdvancedOptions(1200, c_oAscCsvDelimiter.Comma) );
   */
  spreadsheet_api.prototype.asc_setAdvancedOptions = function(idOption, option) {
    switch (idOption) {
      case c_oAscAdvancedOptionsID.CSV:
        // Проверяем тип состояния в данный момент
        if (this.advancedOptionsAction === c_oAscAdvancedOptionsAction.Open) {
          var v = {
            "id": this.documentId,
            "userid": this.documentUserId,
            "format": this.documentFormat,
            "c": "reopen",
            "url": this.documentUrl,
            "title": this.documentTitle,
            "delimiter": option.asc_getDelimiter(),
593
            "delimiterChar": option.asc_getDelimiterChar(),
Alexander.Trofimov's avatar
Alexander.Trofimov committed
594 595
            "codepage": option.asc_getCodePage()};

596
          sendCommand(this, null, v);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
597
        } else if (this.advancedOptionsAction === c_oAscAdvancedOptionsAction.Save) {
598 599 600
          var options = {CSVOptions: option, downloadType: this.downloadType};
          this.downloadType = DownloadType.None;
          this._asc_downloadAs(c_oAscFileType.CSV, c_oAscAsyncAction.DownloadAs, options);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
601 602
        }
        break;
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
      case c_oAscAdvancedOptionsID.DRM:
        // Проверяем тип состояния в данный момент
        if (this.advancedOptionsAction === c_oAscAdvancedOptionsAction.Open) {
          var v = {
            "id": this.documentId,
            "userid": this.documentUserId,
            "format": this.documentFormat,
            "c": "reopen",
            "url": this.documentUrl,
            "title": this.documentTitle,
            "password": option.asc_getPassword()
          };

          sendCommand(this, null, v);
        }
        break;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
619 620 621 622 623 624 625 626 627 628 629 630 631
    }
  };
  // Опции страницы (для печати)
  spreadsheet_api.prototype.asc_setPageOptions = function(options, index) {
    var sheetIndex = (undefined !== index && null !== index) ? index : this.wbModel.getActive();
    this.wbModel.getWorksheet(sheetIndex).PagePrintOptions = options;
  };

  spreadsheet_api.prototype.asc_getPageOptions = function(index) {
    var sheetIndex = (undefined !== index && null !== index) ? index : this.wbModel.getActive();
    return this.wbModel.getWorksheet(sheetIndex).PagePrintOptions;
  };

632
  spreadsheet_api.prototype._onNeedParams = function(data, opt_isPassword) {
633 634
    var t = this;
    // Проверяем, возможно нам пришли опции для CSV
635
    if (this.documentOpenOptions && !opt_isPassword) {
636 637 638
      var codePageCsv = AscCommon.c_oAscEncodingsMap[this.documentOpenOptions["codePage"]] || AscCommon.c_oAscCodePageUtf8, delimiterCsv = this.documentOpenOptions["delimiter"],
		  delimiterCharCsv = this.documentOpenOptions["delimiterChar"];
      if (null != codePageCsv && (null != delimiterCsv || null != delimiterCharCsv)) {
639 640 641 642
        this.asc_setAdvancedOptions(c_oAscAdvancedOptionsID.CSV, new asc.asc_CCSVAdvancedOptions(codePageCsv, delimiterCsv));
        return;
      }
    }
643 644 645
    if (opt_isPassword) {
      t.handlers.trigger("asc_onAdvancedOptions", new AscCommon.asc_CAdvancedOptions(c_oAscAdvancedOptionsID.DRM), this.advancedOptionsAction);
    } else if (data) {
646
      AscCommon.loadFileContent(data, function(result) {
647
        if (null === result) {
648
          t.handlers.trigger("asc_onError", c_oAscError.ID.Unknown, c_oAscError.Level.Critical);
649
          return;
650
        }
651
        var cp = JSON.parse(result);
652
        cp['encodings'] = AscCommon.getEncodingParams();
653
        t.handlers.trigger("asc_onAdvancedOptions", new AscCommon.asc_CAdvancedOptions(c_oAscAdvancedOptionsID.CSV, cp), t.advancedOptionsAction);
654 655
      });
    } else {
656
      t.handlers.trigger("asc_onError", c_oAscError.ID.Unknown, c_oAscError.Level.NoCritical);
657 658 659
    }
  };
  spreadsheet_api.prototype._onOpenCommand = function(data) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
660
    var t = this;
661
    AscCommon.openFileCommand(data, this.documentUrlChanges, AscCommon.c_oSerFormat.Signature, function(error, result) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
662
      if (error || !result.bSerFormat) {
663
        var oError = {returnCode: c_oAscError.Level.Critical, val: c_oAscError.ID.Unknown};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
664 665 666 667
        t.handlers.trigger("asc_onError", oError.val, oError.returnCode);
        return;
      }

668
      t.onEndLoadFile(result.data);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
669 670 671
    });
  };

672
  spreadsheet_api.prototype._OfflineAppDocumentEndLoad = function() {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
673 674
    var data = getTestWorkbook();
    var sData = data + "";
675 676
    if (AscCommon.c_oSerFormat.Signature === sData.substring(0, AscCommon.c_oSerFormat.Signature.length)) {
      this.openDocument(sData);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
677 678 679
    }
  };

680
  spreadsheet_api.prototype._asc_save2 = function () {
681
    var oBinaryFileWriter = new AscCommonExcel.BinaryFileWriter(this.wbModel);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
682 683
    var dataContainer = {data: null, part: null, index: 0, count: 0};
    dataContainer.data = oBinaryFileWriter.Write();
684
    var filetype = 0x1002;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
685 686 687 688
    var oAdditionalData = {};
    oAdditionalData["c"] = "sfct";
    oAdditionalData["id"] = this.documentId;
    oAdditionalData["userid"] = this.documentUserId;
konovalovsergey's avatar
konovalovsergey committed
689
    oAdditionalData["jwt"] = this.CoAuthoringApi.get_jwt();
690
    oAdditionalData["outputformat"] = filetype;
691 692
    oAdditionalData["title"] =
        AscCommon.changeFileExtention(this.documentTitle, AscCommon.getExtentionByFormat(filetype));
693
    oAdditionalData["savetype"] = AscCommon.c_oAscSaveTypes.CompleteAll;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
694
    var t = this;
695
    t.fCurCallback = function (incomeObject) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
696 697
      if (null != input && "save" == input["type"]) {
        if ('ok' == input["status"]) {
698
          var url = input["data"];
Alexander.Trofimov's avatar
Alexander.Trofimov committed
699
          if (url) {
700
            t.processSavedFile(url, false);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
701
          } else {
702
            t.handlers.trigger("asc_onError", c_oAscError.ID.Unknown, c_oAscError.Level.NoCritical);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
703 704
          }
        } else {
705 706 707
          t.handlers.trigger("asc_onError",
              mapAscServerErrorToAscError(parseInt(input["data"]), AscCommon.c_oAscAdvancedOptionsAction.Save),
              c_oAscError.Level.NoCritical);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
708 709
        }
      } else {
710
        t.handlers.trigger("asc_onError", c_oAscError.ID.Unknown, c_oAscError.Level.NoCritical);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
711 712
      }
    };
713
    AscCommon.saveWithParts(function (fCallback1, oAdditionalData1, dataContainer1) {
714
      sendCommand(t, fCallback1, oAdditionalData1, dataContainer1);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
715 716 717
    }, t.fCurCallback, null, oAdditionalData, dataContainer);
  };

718 719 720 721 722 723
  spreadsheet_api.prototype._asc_downloadAs = function(sFormat, actionType, options) { //fCallback({returnCode:"", ...})
    var t = this;
    if (!options) {
      options = {};
    }
    if (actionType) {
724
      this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, actionType);
725 726 727 728
    }
    // Меняем тип состояния (на сохранение)
    this.advancedOptionsAction = c_oAscAdvancedOptionsAction.Save;
    
Alexander.Trofimov's avatar
Alexander.Trofimov committed
729 730
    //sFormat: xlsx, xls, ods, csv, html
    var dataContainer = {data: null, part: null, index: 0, count: 0};
731
    var command = "save";
Alexander.Trofimov's avatar
Alexander.Trofimov committed
732
    var oAdditionalData = {};
733
    oAdditionalData["c"] = command;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
734 735
    oAdditionalData["id"] = this.documentId;
    oAdditionalData["userid"] = this.documentUserId;
konovalovsergey's avatar
konovalovsergey committed
736
    oAdditionalData["jwt"] = this.CoAuthoringApi.get_jwt();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
737
    oAdditionalData["outputformat"] = sFormat;
738
    oAdditionalData["title"] = AscCommon.changeFileExtention(this.documentTitle, AscCommon.getExtentionByFormat(sFormat), Asc.c_nMaxDownloadTitleLen);
739 740
    if (DownloadType.Print === options.downloadType) {
      oAdditionalData["inline"] = 1;
741
    }
Alexander.Trofimov's avatar
Alexander.Trofimov committed
742 743
    if (c_oAscFileType.PDF === sFormat) {
      var printPagesData = this.wb.calcPagesPrint(this.adjustPrint);
744
      var pdf_writer = new AscCommonExcel.CPdfPrinter();
745
      this.wb.printSheets(pdf_writer, printPagesData);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
746 747

      dataContainer.data = pdf_writer.DocumentRenderer.Memory.GetBase64Memory();
748
    } else if (c_oAscFileType.CSV === sFormat && !options.CSVOptions) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
749
      // Мы открывали команду, надо ее закрыть.
750
      if (actionType) {
751
        this.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, actionType);
752
      }
753
      var cp = {'delimiter': AscCommon.c_oAscCsvDelimiter.Comma, 'codepage': AscCommon.c_oAscCodePageUtf8, 'encodings': AscCommon.getEncodingParams()};
754
      this.downloadType = options.downloadType;
755
      this.handlers.trigger("asc_onAdvancedOptions", new AscCommon.asc_CAdvancedOptions(c_oAscAdvancedOptionsID.CSV, cp), this.advancedOptionsAction);
756
      return;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
757
    } else {
758
      var oBinaryFileWriter = new AscCommonExcel.BinaryFileWriter(this.wbModel);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
759
      if (c_oAscFileType.CSV === sFormat) {
760 761 762
        if (options.CSVOptions instanceof asc.asc_CCSVAdvancedOptions) {
          oAdditionalData["codepage"] = options.CSVOptions.asc_getCodePage();
          oAdditionalData["delimiter"] = options.CSVOptions.asc_getDelimiter();
763
          oAdditionalData["delimiterChar"] = options.CSVOptions.asc_getDelimiterChar();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
764 765 766 767
        }
      }
      dataContainer.data = oBinaryFileWriter.Write();
    }
768
    var fCallback = function(input) {
769
      var error = c_oAscError.ID.Unknown;
770 771 772 773
      if (null != input && command == input["type"]) {
        if ('ok' == input["status"]) {
          var url = input["data"];
          if (url) {
774
            error = c_oAscError.ID.No;
775
            t.processSavedFile(url, options.downloadType);
776 777
          }
        } else {
778
          error = mapAscServerErrorToAscError(parseInt(input["data"]), AscCommon.c_oAscAdvancedOptionsAction.Save);
779 780
        }
      }
781 782
      if (c_oAscError.ID.No != error) {
        t.handlers.trigger("asc_onError", error, c_oAscError.Level.NoCritical);
783 784 785 786
      }
      // Меняем тип состояния (на никакое)
      t.advancedOptionsAction = c_oAscAdvancedOptionsAction.None;
      if (actionType) {
787
        t.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, actionType);
788 789
      }
    };
Alexander.Trofimov's avatar
Alexander.Trofimov committed
790
    t.fCurCallback = fCallback;
791 792
    AscCommon.saveWithParts(function(fCallback1, oAdditionalData1, dataContainer1) {
      sendCommand(t, fCallback1, oAdditionalData1, dataContainer1);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
793 794 795 796 797 798 799
    }, fCallback, null, oAdditionalData, dataContainer);
  };

  spreadsheet_api.prototype.asc_isDocumentModified = function() {
    if (!this.canSave || this.asc_getCellEditMode()) {
      // Пока идет сохранение или редактирование ячейки, мы не закрываем документ
      return true;
800 801
    } else if (History && History.Have_Changes) {
      return History.Have_Changes();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
    }
    return false;
  };

  spreadsheet_api.prototype.asc_getCanUndo = function() {
    return History.Can_Undo();
  };
  spreadsheet_api.prototype.asc_getCanRedo = function() {
    return History.Can_Redo();
  };


  // Actions and callbacks interface

  /*
   * asc_onStartAction			(type, id)
   * asc_onEndAction				(type, id)
   * asc_onInitEditorFonts		(gui_fonts)
   * asc_onInitEditorStyles		(gui_styles)
821
   * asc_onOpenDocumentProgress	(AscCommon.COpenProgress)
Alexander.Trofimov's avatar
Alexander.Trofimov committed
822
   * asc_onAdvancedOptions		(asc_CAdvancedOptions, ascAdvancedOptionsAction)	- эвент на получение дополнительных опций (открытие/сохранение CSV)
823
   * asc_onError					(c_oAscError.ID, c_oAscError.Level)					- эвент об ошибке
824
   * asc_onEditCell				(Asc.c_oAscCellEditorState)								- эвент на редактирование ячейки с состоянием (переходами из формулы и обратно)
Alexander.Trofimov's avatar
Alexander.Trofimov committed
825 826 827
   * asc_onEditorSelectionChanged	(asc_CFont)											- эвент на смену информации о выделении в редакторе ячейки
   * asc_onSelectionChanged		(asc_CCellInfo)										- эвент на смену информации о выделении
   * asc_onSelectionNameChanged	(sName)												- эвент на смену имени выделения (Id-ячейки, число выделенных столбцов/строк, имя диаграммы и др.)
Alexey.Musinov's avatar
Alexey.Musinov committed
828 829 830
   * asc_onSelection
   *
   * Changed	(asc_CSelectionMathInfo)							- эвент на смену математической информации о выделении
Alexander.Trofimov's avatar
Alexander.Trofimov committed
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
   * asc_onZoomChanged			(zoom)
   * asc_onSheetsChanged			()													- эвент на обновление списка листов
   * asc_onActiveSheetChanged		(indexActiveSheet)									- эвент на обновление активного листа
   * asc_onCanUndoChanged			(bCanUndo)											- эвент на обновление возможности undo
   * asc_onCanRedoChanged			(bCanRedo)											- эвент на обновление возможности redo
   * asc_onSaveUrl				(sUrl, callback(hasError))							- эвент на сохранение файла на сервер по url
   * asc_onDocumentModifiedChanged(bIsModified)										- эвент на обновление статуса "изменен ли файл"
   * asc_onMouseMove				(asc_CMouseMoveData)								- эвент на наведение мышкой на гиперлинк или комментарий
   * asc_onHyperlinkClick			(sUrl)												- эвент на нажатие гиперлинка
   * asc_onCoAuthoringDisconnect	()													- эвент об отключении от сервера без попытки reconnect
   * asc_onSelectionRangeChanged	(selectRange)										- эвент о выборе диапазона для диаграммы (после нажатия кнопки выбора)
   * asc_onRenameCellTextEnd		(countCellsFind, countCellsReplace)					- эвент об окончании замены текста в ячейках (мы не можем сразу прислать ответ)
   * asc_onWorkbookLocked			(result)											- эвент залочена ли работа с листами или нет
   * asc_onWorksheetLocked		(index, result)										- эвент залочен ли лист или нет
   * asc_onGetEditorPermissions	(permission)										- эвент о правах редактора
   * asc_onStopFormatPainter		()													- эвент об окончании форматирования по образцу
   * asc_onUpdateSheetSettings	()													- эвент об обновлении свойств листа (закрепленная область, показывать сетку/заголовки)
   * asc_onUpdateTabColor			(index)												- эвент об обновлении цвета иконки листа
   * asc_onDocumentCanSaveChanged	(bIsCanSave)										- эвент об обновлении статуса "можно ли сохранять файл"
   * asc_onDocumentUpdateVersion	(callback)											- эвент о том, что файл собрался и не может больше редактироваться
   * asc_onContextMenu			(event)												- эвент на контекстное меню
852
   * asc_onDocumentContentReady ()                        - эвент об окончании загрузки документа
Alexander.Trofimov's avatar
Alexander.Trofimov committed
853
   * asc_onFilterInfo	        (countFilter, countRecords)								- send count filtered and all records
Alexander.Trofimov's avatar
Alexander.Trofimov committed
854 855 856 857
   */

  spreadsheet_api.prototype.asc_registerCallback = function(name, callback, replaceOldCallback) {
    this.handlers.add(name, callback, replaceOldCallback);
858
    return;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
859 860 861 862 863 864

    /*
     Не самая хорошая схема для отправки эвентов:
     проверяем, подписан ли кто-то на эвент? Если да, то отправляем и больше ничего не делаем.
     Если никто не подписан, то сохраняем у себя переменную и как только кто-то подписывается - отправляем ее
     */
865
    if (null !== this._gui_control_colors && "asc_onSendThemeColors" === name) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
      this.handlers.trigger("asc_onSendThemeColors", this._gui_control_colors.Colors, this._gui_control_colors.StandartColors);
      this._gui_control_colors = null;
    }
  };

  spreadsheet_api.prototype.asc_unregisterCallback = function(name, callback) {
    this.handlers.remove(name, callback);
  };

  spreadsheet_api.prototype.asc_getController = function() {
    return this.controller;
//				return null;
  };

  spreadsheet_api.prototype.asc_SetDocumentPlaceChangedEnabled = function(val) {
    this.wb.setDocumentPlaceChangedEnabled(val);
  };

884 885
  spreadsheet_api.prototype.asc_SetFastCollaborative = function(bFast) {
    if (this.collaborativeEditing) {
886
      AscCommon.CollaborativeEditing.Set_Fast(bFast);
887 888 889 890
      this.collaborativeEditing.setFast(bFast);
    }
  };

891 892 893 894 895
	spreadsheet_api.prototype.asc_setThumbnailStylesSizes = function (width, height) {
		this.styleThumbnailWidth = width;
		this.styleThumbnailHeight = height;
	};

Alexander.Trofimov's avatar
Alexander.Trofimov committed
896 897 898 899 900 901 902 903 904
  // Посылает эвент о том, что обновились листы
  spreadsheet_api.prototype.sheetsChanged = function() {
    this.handlers.trigger("asc_onSheetsChanged");
  };

  spreadsheet_api.prototype.asyncFontsDocumentStartLoaded = function() {
    this.OpenDocumentProgress.Type = c_oAscAsyncAction.LoadDocumentFonts;
    this.OpenDocumentProgress.FontsCount = this.FontLoader.fonts_loading.length;
    this.OpenDocumentProgress.CurrentFont = 0;
905
    this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.LoadDocumentFonts);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
906 907 908
  };

  spreadsheet_api.prototype.asyncFontsDocumentEndLoaded = function() {
909
    this.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.LoadDocumentFonts);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
910 911 912 913 914 915 916 917 918 919 920 921 922 923

    if (this.asyncMethodCallback !== undefined) {
      this.asyncMethodCallback();
      this.asyncMethodCallback = undefined;
    } else {
      // Шрифты загрузились, возможно стоит подождать совместное редактирование
      this.FontLoadWaitComplete = true;
      if (this.ServerIdWaitComplete) {
        this._openDocumentEndCallback();
      }
    }
  };

  spreadsheet_api.prototype.asyncFontEndLoaded = function(font) {
924
    this.sync_EndAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.LoadFont);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
925 926 927 928 929 930 931 932 933
  };

  spreadsheet_api.prototype._loadFonts = function(fonts, callback) {
    if (window["NATIVE_EDITOR_ENJINE"]) {
      return callback();
    }
    this.asyncMethodCallback = callback;
    var arrLoadFonts = [];
    for (var i in fonts)
934
      arrLoadFonts.push(new AscFonts.CFont(i, 0, "", 0));
Alexander.Trofimov's avatar
Alexander.Trofimov committed
935 936 937 938
    History.loadFonts(arrLoadFonts);
    this.FontLoader.LoadDocumentFonts2(arrLoadFonts);
  };

939
  spreadsheet_api.prototype.openDocument = function(sData) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
940 941 942 943 944 945 946 947 948 949
    if (true === sData) {
      // Empty Document
      sData = AscCommonExcel.getEmptyWorkbook() + "";
      if (sData.length && (AscCommon.c_oSerFormat.Signature === sData.substring(0, AscCommon.c_oSerFormat.Signature.length))) {
        this.isChartEditor = true;
      } else {
        return;
      }
    }

950
    this.wbModel = this._openDocument(sData);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
951 952 953 954 955

    this.FontLoader.LoadDocumentFonts(this.wbModel.generateFontMap2());

    // Какая-то непонятная заглушка, чтобы не падало в ipad
    if (this.isMobileVersion) {
956
      AscCommon.AscBrowser.isSafariMacOs = false;
957 958
      AscCommon.PasteElementsId.PASTE_ELEMENT_ID = "wrd_pastebin";
      AscCommon.PasteElementsId.ELEMENT_DISPAY_STYLE = "none";
Alexander.Trofimov's avatar
Alexander.Trofimov committed
959 960 961 962 963 964 965 966 967 968 969 970 971 972
    }
  };

  // Соединились с сервером
  spreadsheet_api.prototype.asyncServerIdEndLoaded = function() {
    // С сервером соединились, возможно стоит подождать загрузку шрифтов
    this.ServerIdWaitComplete = true;
    if (this.FontLoadWaitComplete) {
      this._openDocumentEndCallback();
    }
  };

  // Эвент о пришедщих изменениях
  spreadsheet_api.prototype.syncCollaborativeChanges = function() {
973 974 975 976
    // Для быстрого сохранения уведомлять не нужно.
    if (!this.collaborativeEditing.getFast()) {
      this.handlers.trigger("asc_onCollaborativeChanges");
    }
Alexander.Trofimov's avatar
Alexander.Trofimov committed
977 978 979 980 981 982 983 984 985 986 987 988
  };

  // Применение изменений документа, пришедших при открытии
  // Их нужно применять после того, как мы создали WorkbookView
  // т.к. автофильтры, диаграммы, изображения и комментарии завязаны на WorksheetView (ToDo переделать)
  spreadsheet_api.prototype._applyFirstLoadChanges = function() {
    if (this.IsSendDocumentLoadCompleate) {
      return;
    }
    if (this.collaborativeEditing.applyChanges()) {
      // Изменений не было
      this.IsSendDocumentLoadCompleate = true;
989
      this.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.Open);
990
      this.handlers.trigger('asc_onDocumentContentReady');
Alexander.Trofimov's avatar
Alexander.Trofimov committed
991 992 993 994 995 996
    }
  };

  /////////////////////////////////////////////////////////////////////////
  ///////////////////CoAuthoring and Chat api//////////////////////////////
  /////////////////////////////////////////////////////////////////////////
997
  spreadsheet_api.prototype._coAuthoringInitEnd = function() {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
998
    var t = this;
999
    this.collaborativeEditing = new AscCommonExcel.CCollaborativeEditing(/*handlers*/{
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
      "askLock": function() {
        t.CoAuthoringApi.askLock.apply(t.CoAuthoringApi, arguments);
      },
      "releaseLocks": function() {
        t.CoAuthoringApi.releaseLocks.apply(t.CoAuthoringApi, arguments);
      },
      "sendChanges": function() {
        t._onSaveChanges.apply(t, arguments);
      },
      "applyChanges": function() {
        t._onApplyChanges.apply(t, arguments);
      },
      "updateAfterApplyChanges": function() {
        t._onUpdateAfterApplyChanges.apply(t, arguments);
      },
      "drawSelection": function() {
        t._onDrawSelection.apply(t, arguments);
      },
      "drawFrozenPaneLines": function() {
        t._onDrawFrozenPaneLines.apply(t, arguments);
      },
      "updateAllSheetsLock": function() {
        t._onUpdateAllSheetsLock.apply(t, arguments);
      },
      "showDrawingObjects": function() {
        t._onShowDrawingObjects.apply(t, arguments);
      },
      "showComments": function() {
        t._onShowComments.apply(t, arguments);
      },
      "cleanSelection": function() {
        t._onCleanSelection.apply(t, arguments);
      },
      "updateDocumentCanSave": function() {
        t._onUpdateDocumentCanSave();
      },
      "checkCommentRemoveLock": function(lockElem) {
        return t._onCheckCommentRemoveLock(lockElem);
      },
      "unlockDefName": function() {
        t._onUnlockDefName.apply(t, arguments);
      },
      "checkDefNameLock": function(lockElem) {
        return t._onCheckDefNameLock(lockElem);
      }
1045
    }, this.getViewMode());
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1046 1047 1048 1049 1050

    this.CoAuthoringApi.onConnectionStateChanged = function(e) {
      t.handlers.trigger("asc_onConnectionStateChanged", e);
    };
    this.CoAuthoringApi.onLocksAcquired = function(e) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1051 1052 1053 1054 1055 1056
      if (!t.IsSendDocumentLoadCompleate) {
        // Пока документ еще не загружен, будем сохранять функцию и аргументы
        t.arrPreOpenLocksObjects.push(function(){t.CoAuthoringApi.onLocksAcquired(e);});
        return;
      }

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1057 1058 1059 1060
      if (2 != e["state"]) {
        var elementValue = e["blockValue"];
        var lockElem = t.collaborativeEditing.getLockByElem(elementValue, c_oAscLockTypes.kLockTypeOther);
        if (null === lockElem) {
1061
          lockElem = new AscCommonExcel.CLock(elementValue);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1062 1063
          t.collaborativeEditing.addUnlock(lockElem);
        }
1064

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1065 1066 1067 1068 1069 1070 1071
        var drawing, lockType = lockElem.Element["type"];
        var oldType = lockElem.getType();
        if (c_oAscLockTypes.kLockTypeOther2 === oldType || c_oAscLockTypes.kLockTypeOther3 === oldType) {
          lockElem.setType(c_oAscLockTypes.kLockTypeOther3, true);
        } else {
          lockElem.setType(c_oAscLockTypes.kLockTypeOther, true);
        }
1072

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1073 1074
        // Выставляем ID пользователя, залочившего данный элемент
        lockElem.setUserId(e["user"]);
1075

1076
        if (lockType === c_oAscLockTypeElem.Object) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1077 1078 1079 1080 1081
          drawing = g_oTableId.Get_ById(lockElem.Element["rangeOrObjectId"]);
          if (drawing) {
            drawing.lockType = lockElem.Type;
          }
        }
1082

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1083 1084
        if (t.wb) {
          // Шлем update для toolbar-а, т.к. когда select в lock ячейке нужно заблокировать toolbar
1085
          t.wb._onWSSelectionChanged();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1086 1087 1088 1089 1090 1091 1092 1093 1094

          // Шлем update для листов
          t._onUpdateSheetsLock(lockElem);

          t._onUpdateDefinedNames(lockElem);

          var ws = t.wb.getWorksheet();
          var lockSheetId = lockElem.Element["sheetId"];
          if (lockSheetId === ws.model.getId()) {
1095
            if (lockType === c_oAscLockTypeElem.Object) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1096 1097 1098 1099 1100 1101
              // Нужно ли обновлять закрепление областей
              if (t._onUpdateFrozenPane(lockElem)) {
                ws.draw();
              } else if (drawing && ws.model === drawing.worksheet) {
                if (ws.objectRender) {
                  ws.objectRender.showDrawingObjects(true);
1102
                }
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1103
              }
1104
            } else if (lockType === c_oAscLockTypeElem.Range || lockType === c_oAscLockTypeElem.Sheet) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1105
              ws.updateSelection();
1106
            }
1107
          } else if (-1 !== lockSheetId && 0 === lockSheetId.indexOf(AscCommonExcel.CCellCommentator.sStartCommentId)) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1108 1109 1110 1111 1112 1113 1114
            // Коммментарий
            t.handlers.trigger("asc_onLockComment", lockElem.Element["rangeOrObjectId"], e["user"]);
          }
        }
      }
    };
    this.CoAuthoringApi.onLocksReleased = function(e, bChanges) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1115 1116 1117 1118 1119 1120
      if (!t.IsSendDocumentLoadCompleate) {
        // Пока документ еще не загружен, будем сохранять функцию и аргументы
        t.arrPreOpenLocksObjects.push(function(){t.CoAuthoringApi.onLocksReleased(e, bChanges);});
        return;
      }

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
      var element = e["block"];
      var lockElem = t.collaborativeEditing.getLockByElem(element, c_oAscLockTypes.kLockTypeOther);
      if (null != lockElem) {
        var curType = lockElem.getType();

        var newType = c_oAscLockTypes.kLockTypeNone;
        if (curType === c_oAscLockTypes.kLockTypeOther) {
          if (true != bChanges) {
            newType = c_oAscLockTypes.kLockTypeNone;
          } else {
            newType = c_oAscLockTypes.kLockTypeOther2;
          }
        } else if (curType === c_oAscLockTypes.kLockTypeMine) {
          // Такого быть не должно
          newType = c_oAscLockTypes.kLockTypeMine;
        } else if (curType === c_oAscLockTypes.kLockTypeOther2 || curType === c_oAscLockTypes.kLockTypeOther3) {
          newType = c_oAscLockTypes.kLockTypeOther2;
        }

        if (t.wb) {
          t.wb.getWorksheet().cleanSelection();
        }
1143

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1144 1145 1146 1147 1148 1149 1150
        var drawing;
        if (c_oAscLockTypes.kLockTypeNone !== newType) {
          lockElem.setType(newType, true);
        } else {
          // Удаляем из lock-ов, тот, кто правил ушел и не сохранил
          t.collaborativeEditing.removeUnlock(lockElem);
          if (!t._onCheckCommentRemoveLock(lockElem.Element)) {
1151
            if (lockElem.Element["type"] === c_oAscLockTypeElem.Object) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
              drawing = g_oTableId.Get_ById(lockElem.Element["rangeOrObjectId"]);
              if (drawing) {
                drawing.lockType = c_oAscLockTypes.kLockTypeNone;
              }
            }
          }
        }
        if (t.wb) {
          // Шлем update для листов
          t._onUpdateSheetsLock(lockElem);
1162
          /*снимаем лок для DefName*/
1163
          t.handlers.trigger("asc_onLockDefNameManager",Asc.c_oAscDefinedNameReason.OK);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1164 1165 1166 1167
        }
      }
    };
    this.CoAuthoringApi.onLocksReleasedEnd = function() {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1168 1169 1170 1171 1172
      if (!t.IsSendDocumentLoadCompleate) {
        // Пока документ еще не загружен ничего не делаем
        return;
      }

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1173 1174
      if (t.wb) {
        // Шлем update для toolbar-а, т.к. когда select в lock ячейке нужно сбросить блокировку toolbar
1175
        t.wb._onWSSelectionChanged();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1176 1177

        var worksheet = t.wb.getWorksheet();
1178
        worksheet.cleanSelection();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
        worksheet._drawSelection();
        worksheet._drawFrozenPaneLines();
        if (worksheet.objectRender) {
          worksheet.objectRender.showDrawingObjects(true);
        }
      }
    };
    this.CoAuthoringApi.onSaveChanges = function(e, userId, bFirstLoad) {
      t.collaborativeEditing.addChanges(e);
      if (!bFirstLoad && t.IsSendDocumentLoadCompleate) {
        t.syncCollaborativeChanges();
      }
    };
    this.CoAuthoringApi.onRecalcLocks = function(excelAdditionalInfo) {
      if (!excelAdditionalInfo) {
        return;
      }

      var tmpAdditionalInfo = JSON.parse(excelAdditionalInfo);
      // Это мы получили recalcIndexColumns и recalcIndexRows
      var oRecalcIndexColumns = t.collaborativeEditing.addRecalcIndex('0', tmpAdditionalInfo['indexCols']);
      var oRecalcIndexRows = t.collaborativeEditing.addRecalcIndex('1', tmpAdditionalInfo['indexRows']);

      // Теперь нужно пересчитать индексы для lock-элементов
      if (null !== oRecalcIndexColumns || null !== oRecalcIndexRows) {
        t.collaborativeEditing._recalcLockArray(c_oAscLockTypes.kLockTypeMine, oRecalcIndexColumns, oRecalcIndexRows);
        t.collaborativeEditing._recalcLockArray(c_oAscLockTypes.kLockTypeOther, oRecalcIndexColumns, oRecalcIndexRows);
      }
    };
1208
	  this.CoAuthoringApi.onStartCoAuthoring = function (isStartEvent) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1209 1210 1211
		  if (t.isViewMode) {
			  return;
		  }
1212 1213 1214 1215 1216 1217 1218
		  // На старте не нужно ничего делать
		  if (isStartEvent) {
			  t.startCollaborationEditing();
		  } else {
			  // Когда документ еще не загружен, нужно отпустить lock (при быстром открытии 2-мя пользователями)
			  if (!t.IsSendDocumentLoadCompleate) {
				  t.startCollaborationEditing();
1219
				  t.CoAuthoringApi.unLockDocument(false, true);
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
			  } else {
				  // Сохранять теперь должны на таймере автосохранения. Иначе могли два раза запустить сохранение, не дожидаясь окончания
				  t.canUnlockDocument = true;
				  t.canStartCoAuthoring = true;
			  }
		  }
	  };
	  this.CoAuthoringApi.onEndCoAuthoring = function (isStartEvent) {
		  if (t.canUnlockDocument) {
			  t.canStartCoAuthoring = false;
		  } else {
			  t.endCollaborationEditing();
		  }
	  };
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
  };

  spreadsheet_api.prototype._onSaveChanges = function(recalcIndexColumns, recalcIndexRows) {
    if (this.IsSendDocumentLoadCompleate) {
      var arrChanges = this.wbModel.SerializeHistory();
      var deleteIndex = History.Get_DeleteIndex();
      var excelAdditionalInfo = null;
      if (this.collaborativeEditing.getCollaborativeEditing()) {
        // Пересчетные индексы добавляем только если мы не одни
        if (recalcIndexColumns || recalcIndexRows) {
          excelAdditionalInfo = {"indexCols": recalcIndexColumns, "indexRows": recalcIndexRows};
        }
      }
      if (0 < arrChanges.length || null !== deleteIndex || null !== excelAdditionalInfo) {
1248
        this.CoAuthoringApi.saveChanges(arrChanges, deleteIndex, excelAdditionalInfo, this.canUnlockDocument2);
1249
        History.CanNotAddChanges = true;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1250
      } else {
1251
        this.CoAuthoringApi.unLockDocument(true, this.canUnlockDocument2);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1252
      }
1253
      this.canUnlockDocument2 = false;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
    }
  };

  spreadsheet_api.prototype._onApplyChanges = function(changes, fCallback) {
    this.wbModel.DeserializeHistory(changes, fCallback);
  };

  spreadsheet_api.prototype._onUpdateAfterApplyChanges = function() {
    if (!this.IsSendDocumentLoadCompleate) {
      // При открытии после принятия изменений мы должны сбросить пересчетные индексы
      this.collaborativeEditing.clearRecalcIndex();
      this.IsSendDocumentLoadCompleate = true;
1266
      this.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.Open);
1267
      this.handlers.trigger('asc_onDocumentContentReady');
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1268 1269 1270
    } else if (this.wb && !window["NATIVE_EDITOR_ENJINE"]) {
      // Нужно послать 'обновить свойства' (иначе для удаления данных не обновится строка формул).
      // ToDo Возможно стоит обновлять только строку формул
1271
      AscCommon.CollaborativeEditing.Load_Images();
1272
      this.wb._onWSSelectionChanged();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1273
      History.TurnOff();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1274
      this.wb.getWorksheet().updateVisibleRange();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1275
      History.TurnOn();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
    }
  };

  spreadsheet_api.prototype._onCleanSelection = function() {
    if (this.wb) {
      this.wb.getWorksheet().cleanSelection();
    }
  };

  spreadsheet_api.prototype._onDrawSelection = function() {
    if (this.wb) {
      this.wb.getWorksheet()._drawSelection();
    }
  };

  spreadsheet_api.prototype._onDrawFrozenPaneLines = function() {
    if (this.wb) {
      this.wb.getWorksheet()._drawFrozenPaneLines();
    }
  };

  spreadsheet_api.prototype._onUpdateAllSheetsLock = function() {
    var t = this;
    if (t.wbModel) {
      // Шлем update для листов
      t.handlers.trigger("asc_onWorkbookLocked", t.asc_isWorkbookLocked());
      var i, length, wsModel, wsIndex;
      for (i = 0, length = t.wbModel.getWorksheetCount(); i < length; ++i) {
        wsModel = t.wbModel.getWorksheet(i);
        wsIndex = wsModel.getIndex();
        t.handlers.trigger("asc_onWorksheetLocked", wsIndex, t.asc_isWorksheetLockedOrDeleted(wsIndex));
      }
    }
  };

  spreadsheet_api.prototype._onShowDrawingObjects = function() {
    if (this.wb) {
      var ws = this.wb.getWorksheet();
      if (ws && ws.objectRender) {
        ws.objectRender.showDrawingObjects(true);
      }
    }
  };

  spreadsheet_api.prototype._onShowComments = function() {
    if (this.wb) {
      this.wb.getWorksheet().cellCommentator.drawCommentCells();
    }
  };

  spreadsheet_api.prototype._onUpdateSheetsLock = function(lockElem) {
    var t = this;
    // Шлем update для листов, т.к. нужно залочить лист
1329
    if (c_oAscLockTypeElem.Sheet === lockElem.Element["type"]) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
      t.handlers.trigger("asc_onWorkbookLocked", t.asc_isWorkbookLocked());
    }
    // Шлем update для листа
    var wsModel = t.wbModel.getWorksheetById(lockElem.Element["sheetId"]);
    if (wsModel) {
      var wsIndex = wsModel.getIndex();
      t.handlers.trigger("asc_onWorksheetLocked", wsIndex, t.asc_isWorksheetLockedOrDeleted(wsIndex));
    }
  };

  spreadsheet_api.prototype._onUpdateFrozenPane = function(lockElem) {
1341
    return (c_oAscLockTypeElem.Object === lockElem.Element["type"] && lockElem.Element["rangeOrObjectId"] === AscCommonExcel.c_oAscLockNameFrozenPane);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1342 1343
  };

1344 1345
	spreadsheet_api.prototype._sendWorkbookStyles = function () {
		if (this.wbModel) {
Alexey.Musinov's avatar
Alexey.Musinov committed
1346

1347 1348
			if (window["NATIVE_EDITOR_ENJINE"]) {
				// Для нативной версии (сборка и приложение) не генерируем стили
1349 1350
				return;
			}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1351

1352
			// Отправка стилей ячеек
1353 1354
			this.handlers.trigger("asc_onInitEditorStyles",
				this.wb.getCellStyles(this.styleThumbnailWidth, this.styleThumbnailHeight));
1355 1356
		}
	};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367

  spreadsheet_api.prototype.startCollaborationEditing = function() {
    // Начинаем совместное редактирование
    this.collaborativeEditing.startCollaborationEditing();
  };

  spreadsheet_api.prototype.endCollaborationEditing = function() {
    // Временно заканчиваем совместное редактирование
    this.collaborativeEditing.endCollaborationEditing();
  };

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1368 1369 1370 1371 1372 1373
	// End Load document
	spreadsheet_api.prototype._openDocumentEndCallback = function () {
		// Не инициализируем дважды
		if (this.DocumentLoadComplete) {
			return;
		}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1374

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1375 1376
		this.wb = new AscCommonExcel.WorkbookView(this.wbModel, this.controller, this.handlers, this.HtmlElement,
			this.topLineEditorElement, this, this.collaborativeEditing, this.fontRenderingMode);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1377

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1378 1379 1380 1381 1382 1383 1384 1385 1386
		if (this.isMobileVersion) {
			this.wb.defaults.worksheetView.halfSelection = true;
			this.wb.defaults.worksheetView.activeCellBorderColor = new CColor(79, 158, 79);
			var _container = document.getElementById(this.HtmlElementName);
			if (_container) {
				_container.style.overflow = "hidden";
			}
			this.wb.MobileTouchManager = new AscCommonExcel.CMobileTouchManager({eventsElement: "cell_mobile_element"});
			this.wb.MobileTouchManager.Init(this);
1387

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1388 1389 1390 1391
			// input context must be created!!!
			var _areaId = AscCommon.g_inputContext.HtmlArea.id;
			var _element = document.getElementById(_areaId);
			_element.parentNode.parentNode.style.zIndex = 10;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1392

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1393 1394
			this.wb.MobileTouchManager.initEvents(AscCommon.g_inputContext.HtmlArea.id);
		}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1395

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1396
		this.DocumentLoadComplete = true;
1397

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1398 1399 1400
		this.asc_CheckGuiControlColors();
		this.sendColorThemes(this.wbModel.theme);
		this.asc_ApplyColorScheme(false);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1401

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1402 1403
		this.sendStandartTextures();
		this.sendMathToMenu();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1404

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1405 1406 1407 1408 1409 1410 1411
		// Применяем пришедшие при открытии изменения
		this._applyFirstLoadChanges();
		// Применяем все lock-и (ToDo возможно стоит пересмотреть вообще Lock-и)
		for (var i = 0; i < this.arrPreOpenLocksObjects.length; ++i) {
			this.arrPreOpenLocksObjects[i]();
		}
		this.arrPreOpenLocksObjects = [];
1412

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1413 1414
		// Меняем тип состояния (на никакое)
		this.advancedOptionsAction = c_oAscAdvancedOptionsAction.None;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1415

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
		// Были ошибки при открытии, посылаем предупреждение
		if (0 < this.wbModel.openErrors.length) {
			this.sendEvent('asc_onError', c_oAscError.ID.OpenWarning, c_oAscError.Level.NoCritical);
		}

		//this.asc_Resize(); // Убрал, т.к. сверху приходит resize (http://bugzilla.onlyoffice.com/show_bug.cgi?id=14680)
	};

	// Переход на диапазон в листе
	spreadsheet_api.prototype._asc_setWorksheetRange = function (val) {
		// Получаем sheet по имени
		var ranges = null, ws;
        var sheet = val.asc_getSheet();
        if (!sheet) {
			ranges = AscCommonExcel.getRangeByRef(val.asc_getLocation(), this.wbModel.getActiveWs(), true);
			if (ranges = ranges[0]) {
				ws = ranges.worksheet;
            }
        } else {
			ws = this.wbModel.getWorksheetByName(sheet);
        }
		if (!ws) {
			this.handlers.trigger("asc_onHyperlinkClick", null);
			return;
		} else if (ws.getHidden()) {
			return;
		}
		// Индекс листа
		var sheetIndex = ws.getIndex();
		// Если не совпали индекс листа и индекс текущего, то нужно сменить
		if (this.asc_getActiveWorksheetIndex() !== sheetIndex) {
			// Меняем активный лист
			this.asc_showWorksheet(sheetIndex);
			// Посылаем эвент о смене активного листа
			this.handlers.trigger("asc_onActiveSheetChanged", sheetIndex);
		}
		var range;
		if (ranges) {
			range = ranges.bbox;
        } else {
			range = ws.getRange2(val.asc_getRange());
			if (range) {
				range = range.getBBox0();
            }
        }
		this.wb._onSetSelection(range, /*validRange*/ true);
	};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1463 1464 1465 1466 1467

  spreadsheet_api.prototype.onSaveCallback = function(e) {
    var t = this;
    var nState;
    if (false == e["saveLock"]) {
1468
      if (this.isLongAction()) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1469 1470 1471 1472
        // Мы не можем в этот момент сохранять, т.к. попали в ситуацию, когда мы залочили сохранение и успели нажать вставку до ответа
        // Нужно снять lock с сохранения
        this.CoAuthoringApi.onUnSaveLock = function() {
          t.canSave = true;
1473
          t.IsUserSave = false;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1474
          t.lastSaveTime = null;
1475
        };
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1476 1477 1478
        this.CoAuthoringApi.unSaveLock();
        return;
      }
1479

1480
      if (!this.IsUserSave) {
1481
        this.sync_StartAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.Save);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1482
      }
1483

1484 1485 1486 1487
      this.canUnlockDocument2 = this.canUnlockDocument;
      if (this.canUnlockDocument && this.canStartCoAuthoring) {
		  this.CoAuthoringApi.onStartCoAuthoring(true);
	  }
1488 1489
	  this.canStartCoAuthoring = false;
      this.canUnlockDocument = false;
1490

1491
      AscCommon.CollaborativeEditing.Clear_CollaborativeMarks();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1492 1493 1494 1495 1496
      // Принимаем чужие изменения
      this.collaborativeEditing.applyChanges();

      this.CoAuthoringApi.onUnSaveLock = function() {
        t.CoAuthoringApi.onUnSaveLock = null;
1497 1498 1499
        if (t.isForceSaveOnUserSave && t.IsUserSave) {
          t.forceSaveButtonContinue = t.forceSave();
        }
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1500 1501 1502

        if (t.collaborativeEditing.getCollaborativeEditing()) {
          // Шлем update для toolbar-а, т.к. когда select в lock ячейке нужно заблокировать toolbar
1503
          t.wb._onWSSelectionChanged();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1504 1505 1506
        }

        t.canSave = true;
1507
        t.IsUserSave = false;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1508 1509
        t.lastSaveTime = null;

1510 1511 1512
        if (!t.forceSaveButtonContinue) {
          t.sync_EndAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.Save);
        }
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1513
        // Обновляем состояние возможности сохранения документа
1514
        t.onUpdateDocumentModified(History.Have_Changes());
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1515 1516 1517 1518

        if (undefined !== window["AscDesktopEditor"]) {
          window["AscDesktopEditor"]["OnSave"]();
        }
1519 1520 1521 1522
        if (t.disconnectOnSave) {
          t.CoAuthoringApi.disconnect(t.disconnectOnSave.code, t.disconnectOnSave.reason);
          t.disconnectOnSave = null;
        }
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1523 1524
      };
      // Пересылаем свои изменения
1525
      this.collaborativeEditing.sendChanges(this.IsUserSave);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1526 1527
    } else {
      nState = t.CoAuthoringApi.get_state();
1528
      if (AscCommon.ConnectionState.ClosedCoAuth === nState || AscCommon.ConnectionState.ClosedAll === nState) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1529
        // Отключаемся от сохранения, соединение потеряно
1530
        if (this.IsUserSave) {
1531
          this.sync_EndAction(c_oAscAsyncActionType.Information, c_oAscAsyncAction.Save);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1532
        }
1533
        this.IsUserSave = false;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1534 1535 1536
        this.canSave = true;
      } else {
        // Если автосохранение, то не будем ждать ответа, а просто перезапустим таймер на немного
1537
        if (!this.IsUserSave) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
          this.canSave = true;
          return;
        }

        setTimeout(function() {
          t.CoAuthoringApi.askSaveChanges(function(event) {
            t.onSaveCallback(event);
          });
        }, 1000);
      }
    }
  };

  spreadsheet_api.prototype._getIsLockObjectSheet = function(lockInfo, callback) {
    if (false === this.collaborativeEditing.getCollaborativeEditing()) {
      // Пользователь редактирует один: не ждем ответа, а сразу продолжаем редактирование
1554
      AscCommonExcel.applyFunction(callback, true);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1555 1556 1557 1558
      callback = undefined;
    }
    if (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeMine, /*bCheckOnlyLockAll*/false)) {
      // Редактируем сами
1559
      AscCommonExcel.applyFunction(callback, true);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1560 1561 1562
      return;
    } else if (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/false)) {
      // Уже ячейку кто-то редактирует
1563
      AscCommonExcel.applyFunction(callback, false);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
      return;
    }

    this.collaborativeEditing.onStartCheckLock();
    this.collaborativeEditing.addCheckLock(lockInfo);
    this.collaborativeEditing.onEndCheckLock(callback);
  };
  // Залочена ли панель для закрепления
  spreadsheet_api.prototype._isLockedTabColor = function(index, callback) {
    var sheetId = this.wbModel.getWorksheet(index).getId();
1574
    var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Object, null, sheetId, AscCommonExcel.c_oAscLockNameTabColor);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1575 1576 1577

    if (false === this.collaborativeEditing.getCollaborativeEditing()) {
      // Пользователь редактирует один: не ждем ответа, а сразу продолжаем редактирование
1578
      AscCommonExcel.applyFunction(callback, true);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1579 1580 1581 1582
      callback = undefined;
    }
    if (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeMine, /*bCheckOnlyLockAll*/false)) {
      // Редактируем сами
1583
      AscCommonExcel.applyFunction(callback, true);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1584 1585 1586
      return;
    } else if (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/false)) {
      // Уже ячейку кто-то редактирует
1587
      AscCommonExcel.applyFunction(callback, false);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1588 1589 1590 1591 1592 1593 1594
      return;
    }

    this.collaborativeEditing.onStartCheckLock();
    this.collaborativeEditing.addCheckLock(lockInfo);
    this.collaborativeEditing.onEndCheckLock(callback);
  };
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
  spreadsheet_api.prototype._isLockedSparkline = function (id, callback) {
    var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Object, /*subType*/null,
        this.asc_getActiveWorksheetId(), id);
    if (false === this.collaborativeEditing.getCollaborativeEditing()) {
      // Пользователь редактирует один: не ждем ответа, а сразу продолжаем редактирование
      AscCommonExcel.applyFunction(callback, true);
      callback = undefined;
    }
    if (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeMine, false)) {
      // Редактируем сами
      AscCommonExcel.applyFunction(callback, true);
      return;
    } else if (false !==
        this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, false)) {
      // Уже ячейку кто-то редактирует
      AscCommonExcel.applyFunction(callback, false);
      return;
    }

    this.collaborativeEditing.onStartCheckLock();
    this.collaborativeEditing.addCheckLock(lockInfo);
    this.collaborativeEditing.onEndCheckLock(callback);
  };
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1618

1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
  spreadsheet_api.prototype._addWorksheet = function (name, i) {
    var t = this;
    var addWorksheetCallback = function(res) {
      if (res) {
        t.wbModel.createWorksheet(i, name);
        t.wb.spliceWorksheet(i, 0, null);
        t.asc_showWorksheet(i);
        // Посылаем callback об изменении списка листов
        t.sheetsChanged();
      }
    };

    var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Sheet, /*subType*/null,
      AscCommonExcel.c_oAscLockAddSheet, AscCommonExcel.c_oAscLockAddSheet);
    this._getIsLockObjectSheet(lockInfo, addWorksheetCallback);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
  };

  // Workbook interface

  spreadsheet_api.prototype.asc_getWorksheetsCount = function() {
    return this.wbModel.getWorksheetCount();
  };

  spreadsheet_api.prototype.asc_getWorksheetName = function(index) {
    return this.wbModel.getWorksheet(index).getName();
  };

  spreadsheet_api.prototype.asc_getWorksheetTabColor = function(index) {
    return this.wbModel.getWorksheet(index).getTabColor();
  };
  spreadsheet_api.prototype.asc_setWorksheetTabColor = function(index, color) {
    var t = this;
    var changeTabColorCallback = function(res) {
      if (res) {
1653
        color = AscCommonExcel.CorrectAscColor(color);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
        t.wbModel.getWorksheet(index).setTabColor(color);
      }
    };
    this._isLockedTabColor(index, changeTabColorCallback);
  };

  spreadsheet_api.prototype.asc_getActiveWorksheetIndex = function() {
    return this.wbModel.getActive();
  };

  spreadsheet_api.prototype.asc_getActiveWorksheetId = function() {
    var activeIndex = this.wbModel.getActive();
    return this.wbModel.getWorksheet(activeIndex).getId();
  };

  spreadsheet_api.prototype.asc_getWorksheetId = function(index) {
    return this.wbModel.getWorksheet(index).getId();
  };

  spreadsheet_api.prototype.asc_isWorksheetHidden = function(index) {
    return this.wbModel.getWorksheet(index).getHidden();
  };

  spreadsheet_api.prototype.asc_getDefinedNames = function(defNameListId) {
    return this.wb.getDefinedNames(defNameListId);
  };

  spreadsheet_api.prototype.asc_setDefinedNames = function(defName) {
//            return this.wb.setDefinedNames(defName);
    // Проверка глобального лока
    if (this.collaborativeEditing.getGlobalLock()) {
      return;
    }
    return this.wb.editDefinedNames(null, defName);
  };

  spreadsheet_api.prototype.asc_editDefinedNames = function(oldName, newName) {
    // Проверка глобального лока
    if (this.collaborativeEditing.getGlobalLock()) {
      return;
    }

    return this.wb.editDefinedNames(oldName, newName);
  };

  spreadsheet_api.prototype.asc_delDefinedNames = function(oldName) {
    // Проверка глобального лока
    if (this.collaborativeEditing.getGlobalLock()) {
      return;
    }
    return this.wb.delDefinedNames(oldName);
  };

  spreadsheet_api.prototype.asc_checkDefinedName = function(checkName, scope) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1708
    return this.wbModel.checkDefName(checkName, scope);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1709 1710 1711 1712 1713 1714 1715
  };

  spreadsheet_api.prototype.asc_getDefaultDefinedName = function() {
    return this.wb.getDefaultDefinedName();
  };

  spreadsheet_api.prototype._onUpdateDefinedNames = function(lockElem) {
1716
//      if( lockElem.Element["subType"] == AscCommonExcel.c_oAscLockTypeElemSubType.DefinedNames ){
1717
      if( lockElem.Element["sheetId"] == -1 && lockElem.Element["rangeOrObjectId"] != -1 && !this.collaborativeEditing.getFast() ){
konovalovsergey's avatar
konovalovsergey committed
1718
          var dN = this.wbModel.dependencyFormulas.getDefNameByNodeId(lockElem.Element["rangeOrObjectId"]);
1719
          if (dN) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1720
              dN.isLock = lockElem.UserId;
1721
              this.handlers.trigger("asc_onRefreshDefNameList",dN.getAscCDefName());
1722
          }
1723
          this.handlers.trigger("asc_onLockDefNameManager",Asc.c_oAscDefinedNameReason.LockDefNameManager);
1724
      }
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1725
  };
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1726 1727 1728

  spreadsheet_api.prototype._onUnlockDefName = function() {
    this.wb.unlockDefName();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1729
  };
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1730 1731 1732

  spreadsheet_api.prototype._onCheckDefNameLock = function() {
    return this.wb._onCheckDefNameLock();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1733
  };
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744

  // Залочена ли работа с листом
  spreadsheet_api.prototype.asc_isWorksheetLockedOrDeleted = function(index) {
    var ws = this.wbModel.getWorksheet(index);
    var sheetId = null;
    if (null === ws || undefined === ws) {
      sheetId = this.asc_getActiveWorksheetId();
    } else {
      sheetId = ws.getId();
    }

1745
    var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Sheet, /*subType*/null, sheetId, sheetId);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1746 1747 1748 1749 1750 1751
    // Проверим, редактирует ли кто-то лист
    return (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/false));
  };

  // Залочена ли работа с листами
  spreadsheet_api.prototype.asc_isWorkbookLocked = function() {
1752
    var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Sheet, /*subType*/null, null, null);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787
    // Проверим, редактирует ли кто-то лист
    return (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/false));
  };

  spreadsheet_api.prototype.asc_getHiddenWorksheets = function() {
    var model = this.wbModel;
    var len = model.getWorksheetCount();
    var i, ws, res = [];

    for (i = 0; i < len; ++i) {
      ws = model.getWorksheet(i);
      if (ws.getHidden()) {
        res.push({"index": i, "name": ws.getName()});
      }
    }
    return res;
  };

  spreadsheet_api.prototype.asc_showWorksheet = function(index) {
    if (typeof index === "number" && undefined !== index && null !== index) {
      var t = this;
      var ws = this.wbModel.getWorksheet(index);
      var isHidden = ws.getHidden();
      var showWorksheetCallback = function(res) {
        if (res) {
          t.wbModel.getWorksheet(index).setHidden(false);
          t.wb.showWorksheet(index);
          if (isHidden) {
            // Посылаем callback об изменении списка листов
            t.sheetsChanged();
          }
        }
      };
      if (isHidden) {
        var sheetId = this.wbModel.getWorksheet(index).getId();
1788
        var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Sheet, /*subType*/null, sheetId, sheetId);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815
        this._getIsLockObjectSheet(lockInfo, showWorksheetCallback);
      } else {
        showWorksheetCallback(true);
      }
    }
  };

  spreadsheet_api.prototype.asc_showActiveWorksheet = function() {
    this.wb.showWorksheet(this.wbModel.getActive());
  };

  spreadsheet_api.prototype.asc_hideWorksheet = function() {
    var t = this;
    // Колличество листов
    var countWorksheets = this.asc_getWorksheetsCount();
    // Колличество скрытых листов
    var arrHideWorksheets = this.asc_getHiddenWorksheets();
    var countHideWorksheets = arrHideWorksheets.length;
    // Вдруг остался один лист
    if (countWorksheets <= countHideWorksheets + 1) {
      return false;
    }

    var model = this.wbModel;
    // Активный лист
    var activeWorksheet = model.getActive();
    var sheetId = this.wbModel.getWorksheet(activeWorksheet).getId();
1816
    var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Sheet, /*subType*/null, sheetId, sheetId);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835

    var hideWorksheetCallback = function(res) {
      if (res) {
        t.wbModel.getWorksheet(activeWorksheet).setHidden(true);
      }
    };

    this._getIsLockObjectSheet(lockInfo, hideWorksheetCallback);
    return true;
  };

  spreadsheet_api.prototype.asc_renameWorksheet = function(name) {
    // Проверка глобального лока
    if (this.collaborativeEditing.getGlobalLock()) {
      return false;
    }

    var i = this.wbModel.getActive();
    var sheetId = this.wbModel.getWorksheet(i).getId();
1836
    var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Sheet, /*subType*/null, sheetId, sheetId);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1837 1838 1839 1840 1841

    var t = this;
    var renameCallback = function(res) {
      if (res) {
        t.wbModel.getWorksheet(i).setName(name);
1842
        t.sheetsChanged();
1843
      } else {
1844
        t.handlers.trigger("asc_onError", c_oAscError.ID.LockedWorksheetRename, c_oAscError.Level.NoCritical);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872
      }
    };

    this._getIsLockObjectSheet(lockInfo, renameCallback);
    return true;
  };

  spreadsheet_api.prototype.asc_addWorksheet = function(name) {
    var i = this.wbModel.getActive();
    this._addWorksheet(name, i + 1);
  };

  spreadsheet_api.prototype.asc_insertWorksheet = function(name) {
    var i = this.wbModel.getActive();
    this._addWorksheet(name, i);
  };

  // Удаление листа
  spreadsheet_api.prototype.asc_deleteWorksheet = function() {
    // Проверка глобального лока
    if (this.collaborativeEditing.getGlobalLock()) {
      return false;
    }

    var i = this.wbModel.getActive();
    var activeSheet = this.wbModel.getWorksheet(i);
    var activeName = activeSheet.sName;
    var sheetId = activeSheet.getId();
1873
    var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Sheet, /*subType*/null, sheetId, sheetId);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1874 1875 1876 1877 1878 1879 1880

    var t = this;
    var deleteCallback = function(res) {
      if (res) {

        History.Create_NewPoint();
        History.StartTransaction();
1881
        t.wbModel.dependencyFormulas.lockRecal();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
        // Нужно проверить все диаграммы, ссылающиеся на удаляемый лист
        for (var key in t.wb.model.aWorksheets) {
          var wsModel = t.wb.model.aWorksheets[key];
          if (wsModel) {
            History.TurnOff();
            var ws = t.wb.getWorksheet(wsModel.index);
            History.TurnOn();
            wsModel.oDrawingOjectsManager.updateChartReferencesWidthHistory(parserHelp.getEscapeSheetName(activeName), parserHelp.getEscapeSheetName(wsModel.sName));
            if (ws && ws.objectRender && ws.objectRender.controller) {
              ws.objectRender.controller.recalculate2(true);
1892
            }
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1893 1894
          }
        }
1895

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1896 1897 1898 1899 1900 1901 1902 1903
        // Удаляем Worksheet и получаем новый активный индекс (-1 означает, что ничего не удалилось)
        var activeNow = t.wbModel.removeWorksheet(i);
        if (-1 !== activeNow) {
          t.wb.removeWorksheet(i);
          t.asc_showWorksheet(activeNow);
          // Посылаем callback об изменении списка листов
          t.sheetsChanged();
        }
1904
        t.wbModel.dependencyFormulas.unlockRecal();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919
        History.EndTransaction();
      }
    };

    this._getIsLockObjectSheet(lockInfo, deleteCallback);
    return true;
  };

  spreadsheet_api.prototype.asc_moveWorksheet = function(where) {
    var i = this.wbModel.getActive();
    var d = i < where ? +1 : -1;
    // Мы должны поместить слева от заданного значения, поэтому если идем вправо, то вычтем 1
    if (1 === d) {
      where -= 1;
    }
1920
    History.Create_NewPoint();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935
    this.wb.replaceWorksheet(i, where);
    this.wbModel.replaceWorksheet(i, where);

    // Обновим текущий номер
    this.asc_showWorksheet(where);
    // Посылаем callback об изменении списка листов
    this.sheetsChanged();
  };

  spreadsheet_api.prototype.asc_copyWorksheet = function(where, newName) {
    var scale = this.asc_getZoom();
    var i = this.wbModel.getActive();

    // ToDo уйти от lock для листа при копировании
    var sheetId = this.wbModel.getWorksheet(i).getId();
1936
    var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Sheet, /*subType*/null, sheetId, sheetId);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1937 1938 1939
    var t = this;
    var copyWorksheet = function(res) {
      if (res) {
1940 1941
        // ToDo перейти от wsViews на wsViewsId (сейчас вызываем раньше, чем в модели, т.к. там будет sortDependency
        // и cleanCellCache, который создаст уже скопированный лист(и splice сработает неправильно))
1942
        History.Create_NewPoint();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1943
        t.wb.copyWorksheet(i, where);
1944
        t.wbModel.copyWorksheet(i, where, newName);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967
        // Делаем активным скопированный
        t.asc_showWorksheet(where);
        t.asc_setZoom(scale);
        // Посылаем callback об изменении списка листов
        t.sheetsChanged();
      }
    };

    this._getIsLockObjectSheet(lockInfo, copyWorksheet);
  };

  spreadsheet_api.prototype.asc_cleanSelection = function() {
    this.wb.getWorksheet().cleanSelection();
  };

  spreadsheet_api.prototype.asc_getZoom = function() {
    return this.wb.getZoom();
  };

  spreadsheet_api.prototype.asc_setZoom = function(scale) {
    this.wb.changeZoom(scale);
  };

Oleg Korshul's avatar
Oleg Korshul committed
1968
  spreadsheet_api.prototype.asc_enableKeyEvents = function(isEnabled, isFromInput) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1969
    if (!this.isLoadFullApi) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1970
      this.tmpFocus = isEnabled;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1971 1972 1973
      return;
    }

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1974 1975 1976
    if (this.wb) {
      this.wb.enableKeyEventsHandler(isEnabled);
    }
Oleg Korshul's avatar
Oleg Korshul committed
1977 1978

    if (isFromInput !== true && AscCommon.g_inputContext)
1979
      AscCommon.g_inputContext.setInterfaceEnableKeyEvents(isEnabled);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1980 1981
  };

1982 1983
  spreadsheet_api.prototype.asc_IsFocus = function(bIsNaturalFocus) {
    var res = true;
GoshaZotov's avatar
GoshaZotov committed
1984 1985 1986 1987 1988 1989
	if(this.wb.cellEditor.isTopLineActive)
	{
		res = false;
	}
    else if (this.wb) 
	{
1990 1991
      res = this.wb.getEnableKeyEventsHandler(bIsNaturalFocus);
    }
GoshaZotov's avatar
GoshaZotov committed
1992
	
1993 1994 1995
    return res;
  };

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1996 1997 1998 1999 2000 2001 2002
  spreadsheet_api.prototype.asc_searchEnabled = function(bIsEnabled) {
  };

  spreadsheet_api.prototype.asc_findText = function(options) {
    if (window["NATIVE_EDITOR_ENJINE"]) {
      if (this.wb.findCellText(options)) {
        var ws = this.wb.getWorksheet();
2003 2004
        var activeCell = this.wbModel.getActiveWs().selectionRange.activeCell;
        return [ws.getCellLeftRelative(activeCell.col, 0), ws.getCellTopRelative(activeCell.row, 0)];
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022
      }

      return null;
    }

    var d = this.wb.findCellText(options);
    if (d) {
      if (d.deltaX) {
        this.controller.scrollHorizontal(d.deltaX);
      }
      if (d.deltaY) {
        this.controller.scrollVertical(d.deltaY);
      }
    }
    return !!d;
  };

  spreadsheet_api.prototype.asc_replaceText = function(options) {
2023
    options.lookIn = Asc.c_oAscFindLookIn.Formulas; // При замене поиск только в формулах
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035
    this.wb.replaceCellText(options);
  };

  spreadsheet_api.prototype.asc_endFindText = function() {
    // Нужно очистить поиск
    this.wb._cleanFindResults();
  };

  /**
   * Делает активной указанную ячейку
   * @param {String} reference  Ссылка на ячейку вида A1 или R1C1
   */
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2036
  spreadsheet_api.prototype.asc_findCell = function (reference) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2037
    if (this.asc_getCellEditMode()) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2038 2039
      return;
    }
2040 2041
    var ws = this.wb.getWorksheet();
    var d = ws.findCell(reference, this.isViewMode);
2042
    if (0 === d.length) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2043 2044
      return;
    }
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2045 2046

    // Получаем sheet по имени
2047
    ws = d[0].getWorksheet();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
    if (!ws || ws.getHidden()) {
      return;
    }
    // Индекс листа
    var sheetIndex = ws.getIndex();
    // Если не совпали индекс листа и индекс текущего, то нужно сменить
    if (this.asc_getActiveWorksheetIndex() !== sheetIndex) {
      // Меняем активный лист
      this.asc_showWorksheet(sheetIndex);
      // Посылаем эвент о смене активного листа
      this.handlers.trigger("asc_onActiveSheetChanged", sheetIndex);
    }

    ws = this.wb.getWorksheet();
2062
    d = ws.setSelection(d[0].getBBox0(), true);
2063 2064 2065 2066 2067
    if (d.deltaX) {
      this.controller.scrollHorizontal(d.deltaX);
    }
    if (d.deltaY) {
      this.controller.scrollVertical(d.deltaY);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2068 2069 2070
    }
  };

2071
	spreadsheet_api.prototype.asc_closeCellEditor = function (cancel) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2072
		var result = true;
2073
		if (this.wb) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2074
			result = this.wb.closeCellEditor(cancel);
2075
		}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2076
		return result;
2077
	};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2078 2079 2080 2081 2082 2083


  // Spreadsheet interface

  spreadsheet_api.prototype.asc_getColumnWidth = function() {
    var ws = this.wb.getWorksheet();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2084
    return ws.getSelectedColumnWidthInSymbols();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098
  };

  spreadsheet_api.prototype.asc_setColumnWidth = function(width) {
    this.wb.getWorksheet().changeWorksheet("colWidth", width);
  };

  spreadsheet_api.prototype.asc_showColumns = function() {
    this.wb.getWorksheet().changeWorksheet("showCols");
  };

  spreadsheet_api.prototype.asc_hideColumns = function() {
    this.wb.getWorksheet().changeWorksheet("hideCols");
  };

2099
  spreadsheet_api.prototype.asc_autoFitColumnWidth = function() {
2100
    this.wb.getWorksheet().autoFitColumnWidth(null);
2101 2102
  };

Alexander.Trofimov's avatar
Alexander.Trofimov committed
2103 2104
  spreadsheet_api.prototype.asc_getRowHeight = function() {
    var ws = this.wb.getWorksheet();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2105
    return ws.getSelectedRowHeight();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2106 2107 2108 2109 2110
  };

  spreadsheet_api.prototype.asc_setRowHeight = function(height) {
    this.wb.getWorksheet().changeWorksheet("rowHeight", height);
  };
2111 2112 2113
  spreadsheet_api.prototype.asc_autoFitRowHeight = function() {
    this.wb.getWorksheet().autoFitRowHeight(null);
  };
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144

  spreadsheet_api.prototype.asc_showRows = function() {
    this.wb.getWorksheet().changeWorksheet("showRows");
  };

  spreadsheet_api.prototype.asc_hideRows = function() {
    this.wb.getWorksheet().changeWorksheet("hideRows");
  };

  spreadsheet_api.prototype.asc_insertCells = function(options) {
    this.wb.getWorksheet().changeWorksheet("insCell", options);
  };

  spreadsheet_api.prototype.asc_deleteCells = function(options) {
    this.wb.getWorksheet().changeWorksheet("delCell", options);
  };

  spreadsheet_api.prototype.asc_mergeCells = function(options) {
    this.wb.getWorksheet().setSelectionInfo("merge", options);
  };

  spreadsheet_api.prototype.asc_sortCells = function(options) {
    this.wb.getWorksheet().setSelectionInfo("sort", options);
  };

  spreadsheet_api.prototype.asc_emptyCells = function(options) {
    this.wb.emptyCells(options);
  };

  spreadsheet_api.prototype.asc_drawDepCells = function(se) {
    /* ToDo
2145
     if( se != AscCommonExcel.c_oAscDrawDepOptions.Clear )
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2146 2147 2148 2149 2150 2151 2152 2153 2154
     this.wb.getWorksheet().prepareDepCells(se);
     else
     this.wb.getWorksheet().cleanDepCells();*/
  };

  // Потеряем ли мы что-то при merge ячеек
  spreadsheet_api.prototype.asc_mergeCellsDataLost = function(options) {
    return this.wb.getWorksheet().getSelectionMergeInfo(options);
  };
GoshaZotov's avatar
GoshaZotov committed
2155 2156 2157 2158 2159 2160
  
  //нужно ли спрашивать пользователя о расширении диапазона
  spreadsheet_api.prototype.asc_sortCellsRangeExpand = function() {
    return this.wb.getWorksheet().getSelectionSortInfo();
  };
  
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2161 2162 2163 2164
  spreadsheet_api.prototype.asc_getSheetViewSettings = function() {
    return this.wb.getWorksheet().getSheetViewSettings();
  };

2165 2166 2167 2168 2169 2170 2171 2172 2173
	spreadsheet_api.prototype.asc_setDisplayGridlines = function (value) {
		this.wb.getWorksheet()
			.changeWorksheet("sheetViewSettings", {type: AscCH.historyitem_Worksheet_SetDisplayGridlines, value: value});
	};

	spreadsheet_api.prototype.asc_setDisplayHeadings = function (value) {
		this.wb.getWorksheet()
			.changeWorksheet("sheetViewSettings", {type: AscCH.historyitem_Worksheet_SetDisplayHeadings, value: value});
	};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186

  // Images & Charts

  spreadsheet_api.prototype.asc_drawingObjectsExist = function() {
    for (var i = 0; i < this.wb.model.aWorksheets.length; i++) {
      if (this.wb.model.aWorksheets[i].Drawings && this.wb.model.aWorksheets[i].Drawings.length) {
        return true;
      }
    }
    return false;
  };

  spreadsheet_api.prototype.asc_getChartObject = function() {		// Return new or existing chart. For image return null
2187
    this.asc_onOpenChartFrame();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2188 2189 2190 2191 2192 2193
    var ws = this.wb.getWorksheet();
    return ws.objectRender.getAscChartObject();
  };

  spreadsheet_api.prototype.asc_addChartDrawingObject = function(chart) {
    var ws = this.wb.getWorksheet();
Sergey Luzyanin's avatar
Sergey Luzyanin committed
2194 2195 2196
    var ret = ws.objectRender.addChartDrawingObject(chart);
    this.asc_onCloseChartFrame();
    return ret;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2197 2198 2199 2200
  };

  spreadsheet_api.prototype.asc_editChartDrawingObject = function(chart) {
    var ws = this.wb.getWorksheet();
Sergey Luzyanin's avatar
Sergey Luzyanin committed
2201 2202 2203
    var ret = ws.objectRender.editChartDrawingObject(chart);
    this.asc_onCloseChartFrame();
    return ret;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2204 2205
  };

2206
  spreadsheet_api.prototype.asc_addImageDrawingObject = function (imageUrl) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2207 2208 2209 2210
    var rData = {
      "id": this.documentId,
      "userid": this.documentUserId,
      "c": "imgurl",
2211
      "saveindex": g_oDocumentUrls.getMaxIndex(),
2212 2213
      "data": imageUrl
    };
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2214

Sergey.Konovalov's avatar
Sergey.Konovalov committed
2215
    var t = this;
2216
    this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.UploadImage);
2217
    this.fCurCallback = function (input) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233
      if (null != input && "imgurl" == input["type"]) {
        if ("ok" == input["status"]) {
          var data = input["data"];
          var urls = {};
          var firstUrl;
          for (var i = 0; i < data.length; ++i) {
            var elem = data[i];
            if (elem.url) {
              if (!firstUrl) {
                firstUrl = elem.url;
              }
              urls[elem.path] = elem.url;
            }
          }
          g_oDocumentUrls.addUrls(urls);
          if (firstUrl) {
Sergey.Konovalov's avatar
Sergey.Konovalov committed
2234
            var ws = t.wb.getWorksheet();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2235 2236
            ws.objectRender.addImageDrawingObject(firstUrl, null);
          } else {
2237
            t.handlers.trigger("asc_onError", c_oAscError.ID.Unknown, c_oAscError.Level.NoCritical);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2238 2239
          }
        } else {
2240 2241
          t.handlers.trigger("asc_onError", mapAscServerErrorToAscError(parseInt(input["data"])),
              c_oAscError.Level.NoCritical);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2242 2243
        }
      } else {
2244
        t.handlers.trigger("asc_onError", c_oAscError.ID.Unknown, c_oAscError.Level.NoCritical);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2245
      }
2246
      t.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.UploadImage);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2247
    };
2248
    sendCommand(this, null, rData);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2249 2250
  };

2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270

  spreadsheet_api.prototype.asc_AddMath = function(Type)
  {
    var t = this, fonts = {};
    fonts["Cambria Math"] = 1;
    t._loadFonts(fonts, function() {t.asc_AddMath2(Type);});
  };

  spreadsheet_api.prototype.asc_AddMath2 = function(Type)
  {
    var ws = this.wb.getWorksheet();
    var ret = ws.objectRender.addMath(Type);
  };

  spreadsheet_api.prototype.asc_SetMathProps = function(MathProps)
  {
    var ws = this.wb.getWorksheet();
    var ret = ws.objectRender.setMathProps(MathProps);
  };

Alexander.Trofimov's avatar
Alexander.Trofimov committed
2271
  spreadsheet_api.prototype.asc_showImageFileDialog = function() {
2272 2273
    // ToDo заменить на общую функцию для всех
    this.asc_addImage();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2274
  };
2275 2276 2277 2278 2279 2280 2281 2282 2283 2284
  spreadsheet_api.prototype._addImageUrl = function(url) {
    var ws = this.wb.getWorksheet();
    if (ws) {
      if (this.isImageChangeUrl || this.isShapeImageChangeUrl || this.isTextArtChangeUrl) {
        ws.objectRender.editImageDrawingObject(url);
      } else {
        ws.objectRender.addImageDrawingObject(url, null);
      }
    }
  };
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299
  spreadsheet_api.prototype.asc_setSelectedDrawingObjectLayer = function(layerType) {
    var ws = this.wb.getWorksheet();
    return ws.objectRender.setGraphicObjectLayer(layerType);
  };
  spreadsheet_api.prototype.asc_addTextArt = function(nStyle) {
    var ws = this.wb.getWorksheet();
    return ws.objectRender.addTextArt(nStyle);
  };

  spreadsheet_api.prototype.asc_checkDataRange = function(dialogType, dataRange, fullCheck, isRows, chartType) {
    return parserHelp.checkDataRange(this.wbModel, this.wb, dialogType, dataRange, fullCheck, isRows, chartType);
  };

  // Для вставки диаграмм в Word
  spreadsheet_api.prototype.asc_getBinaryFileWriter = function() {
2300
    return new AscCommonExcel.BinaryFileWriter(this.wbModel);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330
  };

  spreadsheet_api.prototype.asc_getWordChartObject = function() {
    var ws = this.wb.getWorksheet();
    return ws.objectRender.getWordChartObject();
  };

  spreadsheet_api.prototype.asc_cleanWorksheet = function() {
    var ws = this.wb.getWorksheet();	// Для удаления данных листа и диаграмм
    if (ws.objectRender) {
      ws.objectRender.cleanWorksheet();
    }
  };

  // Выставление данных (пока используется только для MailMerge)
  spreadsheet_api.prototype.asc_setData = function(oData) {
    this.wb.getWorksheet().setData(oData);
  };
  // Получение данных
  spreadsheet_api.prototype.asc_getData = function() {
    this.asc_closeCellEditor();
    return this.wb.getWorksheet().getData();
  };

  // Cell comment interface
  spreadsheet_api.prototype.asc_addComment = function(oComment) {
  };

  spreadsheet_api.prototype.asc_changeComment = function(id, oComment) {
    if (oComment.bDocument) {
2331
      this.wb.cellCommentator.changeComment(id, oComment);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2332 2333
    } else {
      var ws = this.wb.getWorksheet();
2334
      ws.cellCommentator.changeComment(id, oComment);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2335 2336 2337 2338 2339
    }
  };

  spreadsheet_api.prototype.asc_selectComment = function(id) {
    var ws = this.wb.getWorksheet();
2340
    ws.cellCommentator.selectComment(id, /*bMove*/true);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2341 2342 2343 2344
  };

  spreadsheet_api.prototype.asc_showComment = function(id, bNew) {
    var ws = this.wb.getWorksheet();
2345
    ws.cellCommentator.showComment(id, bNew);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2346 2347 2348 2349
  };

  spreadsheet_api.prototype.asc_findComment = function(id) {
    var ws = this.wb.getWorksheet();
2350
    return ws.cellCommentator.findComment(id);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2351 2352 2353 2354
  };

  spreadsheet_api.prototype.asc_removeComment = function(id) {
    var ws = this.wb.getWorksheet();
2355 2356
    ws.cellCommentator.removeComment(id);
    this.wb.cellCommentator.removeComment(id);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2357 2358 2359 2360
  };

  spreadsheet_api.prototype.asc_getComments = function(col, row) {
    var ws = this.wb.getWorksheet();
2361
    return ws.cellCommentator.getComments(col, row);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2362 2363 2364
  };

  spreadsheet_api.prototype.asc_getDocumentComments = function() {
2365
    return this.wb.cellCommentator.getDocumentComments();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2366 2367
  };

Alexander.Trofimov's avatar
Alexander.Trofimov committed
2368 2369
  spreadsheet_api.prototype.asc_showComments = function () {
    this.wb.showComments(true);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2370
  };
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2371 2372
  spreadsheet_api.prototype.asc_hideComments = function () {
    this.wb.showComments(false);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2373 2374 2375 2376 2377 2378
  };

  // Shapes
  spreadsheet_api.prototype.setStartPointHistory = function() {
    this.noCreatePoint = true;
    this.exucuteHistory = true;
2379
    this.asc_stopSaving();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2380 2381 2382 2383 2384
  };

  spreadsheet_api.prototype.setEndPointHistory = function() {
    this.noCreatePoint = false;
    this.exucuteHistoryEnd = true;
2385
    this.asc_continueSaving();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398
  };

  spreadsheet_api.prototype.asc_startAddShape = function(sPreset) {
    this.isStartAddShape = this.controller.isShapeAction = true;
    var ws = this.wb.getWorksheet();
    ws.objectRender.controller.startTrackNewShape(sPreset);
  };

  spreadsheet_api.prototype.asc_endAddShape = function() {
    this.isStartAddShape = false;
    this.handlers.trigger("asc_onEndAddShape");
  };

Sergey Luzyanin's avatar
Sergey Luzyanin committed
2399 2400 2401 2402 2403 2404 2405 2406 2407 2408

    spreadsheet_api.prototype.asc_addShapeOnSheet = function(sPreset) {
        if(this.wb){
          var ws = this.wb.getWorksheet();
          if(ws && ws.objectRender){
            ws.objectRender.addShapeOnSheet(sPreset);
          }
        }
    };

2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431
  spreadsheet_api.prototype.asc_addOleObjectAction = function(sLocalUrl, sData, sApplicationId, fWidth, fHeight, nWidthPix, nHeightPix)
  {
    var _image = this.ImageLoader.LoadImage(AscCommon.getFullImageSrc2(sLocalUrl), 1);
    if (null != _image){
        var ws = this.wb.getWorksheet();
      if(ws.objectRender){
        ws.objectRender.addOleObject(fWidth, fHeight, nWidthPix, nHeightPix, sLocalUrl, sData, sApplicationId);
      }
    }
  };

  spreadsheet_api.prototype.asc_editOleObjectAction = function(bResize, oOleObject, sImageUrl, sData, nPixWidth, nPixHeight)
  {
    if (oOleObject)
    {
      var ws = this.wb.getWorksheet();
      if(ws.objectRender){
        ws.objectRender.editOleObject(oOleObject, sData, sImageUrl, nPixWidth, nPixHeight, bResize);
      }
    }
  };


2432 2433 2434 2435 2436 2437 2438
    spreadsheet_api.prototype.asc_startEditCurrentOleObject = function(){
        var ws = this.wb.getWorksheet();
        if(ws && ws.objectRender){
            ws.objectRender.startEditCurrentOleObject();
        }
    };

Alexander.Trofimov's avatar
Alexander.Trofimov committed
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468
  spreadsheet_api.prototype.asc_isAddAutoshape = function() {
    return this.isStartAddShape;
  };

  spreadsheet_api.prototype.asc_canAddShapeHyperlink = function() {
    var ws = this.wb.getWorksheet();
    return ws.objectRender.controller.canAddHyperlink();
  };

  spreadsheet_api.prototype.asc_canGroupGraphicsObjects = function() {
    var ws = this.wb.getWorksheet();
    return ws.objectRender.controller.canGroup();
  };

  spreadsheet_api.prototype.asc_groupGraphicsObjects = function() {
    var ws = this.wb.getWorksheet();
    ws.objectRender.groupGraphicObjects();
  };

  spreadsheet_api.prototype.asc_canUnGroupGraphicsObjects = function() {
    var ws = this.wb.getWorksheet();
    return ws.objectRender.controller.canUnGroup();
  };

  spreadsheet_api.prototype.asc_unGroupGraphicsObjects = function() {
    var ws = this.wb.getWorksheet();
    ws.objectRender.unGroupGraphicObjects();
  };

  spreadsheet_api.prototype.asc_changeShapeType = function(value) {
2469
    this.asc_setGraphicObjectProps(new Asc.asc_CImgProperty({ShapeProperties: {type: value}}));
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480
  };

  spreadsheet_api.prototype.asc_getGraphicObjectProps = function() {
    var ws = this.wb.getWorksheet();
    if (ws && ws.objectRender && ws.objectRender.controller) {
      return ws.objectRender.controller.getGraphicObjectProps();
    }
    return null;
  };

  spreadsheet_api.prototype.asc_setGraphicObjectProps = function(props) {
2481

Alexander.Trofimov's avatar
Alexander.Trofimov committed
2482
    var ws = this.wb.getWorksheet();
2483
    var fReplaceCallback = null, sImageUrl = null;
2484
    if(!AscCommon.isNullOrEmptyString(props.ImageUrl)){
2485 2486 2487 2488 2489 2490 2491 2492
      if(!g_oDocumentUrls.getImageLocal(props.ImageUrl)){
        sImageUrl = props.ImageUrl;
        fReplaceCallback = function(sLocalUrl){
          props.ImageUrl = sLocalUrl;
        }
      }
    }
    else if(props.ShapeProperties && props.ShapeProperties.fill && props.ShapeProperties.fill.fill &&
2493
    !AscCommon.isNullOrEmptyString(props.ShapeProperties.fill.fill.url)){
2494 2495 2496 2497 2498 2499 2500 2501
      if(!g_oDocumentUrls.getImageLocal(props.ShapeProperties.fill.fill.url)){
        sImageUrl = props.ShapeProperties.fill.fill.url;
        fReplaceCallback = function(sLocalUrl){
          props.ShapeProperties.fill.fill.url = sLocalUrl;
        }
      }
    }
    if(fReplaceCallback){
2502 2503 2504 2505 2506 2507 2508 2509 2510 2511

      if (window["AscDesktopEditor"])
      {
        var firstUrl = window["AscDesktopEditor"]["LocalFileGetImageUrl"](sImageUrl);
		firstUrl = g_oDocumentUrls.getImageUrl(firstUrl);
        fReplaceCallback(firstUrl);
        ws.objectRender.setGraphicObjectProps(props);
        return;
      }

2512 2513 2514 2515 2516 2517 2518 2519
      var rData = {
        "id": this.documentId,
        "userid": this.documentUserId,
        "c": "imgurl",
        "saveindex": g_oDocumentUrls.getMaxIndex(),
        "data": sImageUrl};

      var t = this;
2520
      this.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.UploadImage);
2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540
      this.fCurCallback = function(input) {
        if (null != input && "imgurl" == input["type"]) {
          if ("ok" == input["status"]) {
            var data = input["data"];
            var urls = {};
            var firstUrl;
            for (var i = 0; i < data.length; ++i) {
              var elem = data[i];
              if (elem.url) {
                if (!firstUrl) {
                  firstUrl = elem.url;
                }
                urls[elem.path] = elem.url;
              }
            }
            g_oDocumentUrls.addUrls(urls);
            if (firstUrl) {
              fReplaceCallback(firstUrl);
              ws.objectRender.setGraphicObjectProps(props);
            } else {
2541
              t.handlers.trigger("asc_onError", c_oAscError.ID.Unknown, c_oAscError.Level.NoCritical);
2542 2543
            }
          } else {
2544
            t.handlers.trigger("asc_onError", mapAscServerErrorToAscError(parseInt(input["data"])), c_oAscError.Level.NoCritical);
2545 2546
          }
        } else {
2547
          t.handlers.trigger("asc_onError", c_oAscError.ID.Unknown, c_oAscError.Level.NoCritical);
2548
        }
2549
        t.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.UploadImage);
2550
      };
2551
      sendCommand(this, null, rData);
2552 2553 2554 2555
    }
    else{
      ws.objectRender.setGraphicObjectProps(props);
    }
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568
  };

  spreadsheet_api.prototype.asc_getOriginalImageSize = function() {
    var ws = this.wb.getWorksheet();
    return ws.objectRender.getOriginalImageSize();
  };

  spreadsheet_api.prototype.asc_setInterfaceDrawImagePlaceTextArt = function(elementId) {
    this.textArtElementId = elementId;
  };

  spreadsheet_api.prototype.asc_changeImageFromFile = function() {
    this.isImageChangeUrl = true;
2569
    this.asc_addImage();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2570 2571 2572 2573
  };

  spreadsheet_api.prototype.asc_changeShapeImageFromFile = function() {
    this.isShapeImageChangeUrl = true;
2574
    this.asc_addImage();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2575 2576 2577 2578
  };

  spreadsheet_api.prototype.asc_changeArtImageFromFile = function() {
    this.isTextArtChangeUrl = true;
2579
    this.asc_addImage();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596
  };

  spreadsheet_api.prototype.asc_putPrLineSpacing = function(type, value) {
    var ws = this.wb.getWorksheet();
    ws.objectRender.controller.putPrLineSpacing(type, value);
  };

  spreadsheet_api.prototype.asc_putLineSpacingBeforeAfter = function(type, value) { // "type == 0" means "Before", "type == 1" means "After"
    var ws = this.wb.getWorksheet();
    ws.objectRender.controller.putLineSpacingBeforeAfter(type, value);
  };

  spreadsheet_api.prototype.asc_setDrawImagePlaceParagraph = function(element_id, props) {
    var ws = this.wb.getWorksheet();
    ws.objectRender.setDrawImagePlaceParagraph(element_id, props);
  };

Sergey Luzyanin's avatar
Sergey Luzyanin committed
2597 2598 2599 2600 2601 2602 2603 2604 2605
    spreadsheet_api.prototype.asc_replaceLoadImageCallback = function(fCallback){
        if(this.wb){
            var ws = this.wb.getWorksheet();
            if(ws.objectRender){
                ws.objectRender.asyncImageEndLoaded = fCallback;
            }
        }
    };

Alexander.Trofimov's avatar
Alexander.Trofimov committed
2606 2607 2608 2609 2610 2611 2612 2613 2614 2615
  spreadsheet_api.prototype.asyncImageEndLoaded = function(_image) {
    if (this.wb) {
      var ws = this.wb.getWorksheet();
      if (ws.objectRender.asyncImageEndLoaded) {
        ws.objectRender.asyncImageEndLoaded(_image);
      }
    }
  };

  spreadsheet_api.prototype.asyncImagesDocumentEndLoaded = function() {
2616
    if (c_oAscAdvancedOptionsAction.None === this.advancedOptionsAction && this.wb && !window["NATIVE_EDITOR_ENJINE"]) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2617 2618 2619 2620
      var ws = this.wb.getWorksheet();
      ws.objectRender.showDrawingObjects(true);
      ws.objectRender.controller.getGraphicObjectProps();
    }
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2621 2622 2623 2624 2625 2626 2627 2628
  };

  spreadsheet_api.prototype.asyncImageEndLoadedBackground = function() {
    var worksheet = this.wb.getWorksheet();
    if (worksheet && worksheet.objectRender) {
      var drawing_area = worksheet.objectRender.drawingArea;
      if (drawing_area) {
        for (var i = 0; i < drawing_area.frozenPlaces.length; ++i) {
2629
          worksheet.objectRender.showDrawingObjects(false, new AscFormat.GraphicOption(worksheet, AscCommonExcel.c_oAscGraphicOption.ScrollVertical, drawing_area.frozenPlaces[i].range, {offsetX: 0, offsetY: 0}));
2630
            worksheet.objectRender.controller && worksheet.objectRender.controller.getGraphicObjectProps();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2631 2632 2633 2634 2635 2636
        }
      }
    }
  };

  // Frozen pane
2637
  spreadsheet_api.prototype.asc_freezePane = function () {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2638 2639 2640
    this.wb.getWorksheet().freezePane();
  };

Alexander.Trofimov's avatar
Alexander.Trofimov committed
2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657
	spreadsheet_api.prototype.asc_setSparklineGroup = function (id, oSparklineGroup) {
		var t = this;
		var changeSparkline = function (res) {
			if (res) {
				var changedSparkline = AscCommon.g_oTableId.Get_ById(id);
				if (changedSparkline) {
					History.Create_NewPoint();
					History.StartTransaction();
					changedSparkline.set(oSparklineGroup);
					History.EndTransaction();
					t.wb._onWSSelectionChanged();
					t.wb.getWorksheet().draw();
				}
			}
		};
		this._isLockedSparkline(id, changeSparkline);
	};
2658

Alexander.Trofimov's avatar
Alexander.Trofimov committed
2659
  // Cell interface
2660
  spreadsheet_api.prototype.asc_getCellInfo = function() {
2661
    return this.wb.getSelectionInfo();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2662 2663 2664 2665
  };

  // Получить координаты активной ячейки
  spreadsheet_api.prototype.asc_getActiveCellCoord = function() {
Sergey Luzyanin's avatar
Sergey Luzyanin committed
2666 2667 2668 2669 2670 2671 2672 2673 2674 2675
    var oWorksheet = this.wb.getWorksheet();
    if(oWorksheet){
      if(oWorksheet.isSelectOnShape){
        return oWorksheet.objectRender.getContextMenuPosition();
      }
      else{
          return oWorksheet.getActiveCellCoord();
      }
    }

Alexander.Trofimov's avatar
Alexander.Trofimov committed
2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687
  };

  // Получить координаты для каких-либо действий (для общей схемы)
  spreadsheet_api.prototype.asc_getAnchorPosition = function() {
    return this.asc_getActiveCellCoord();
  };

  // Получаем свойство: редактируем мы сейчас или нет
  spreadsheet_api.prototype.asc_getCellEditMode = function() {
    return this.wb ? this.wb.getCellEditMode() : false;
  };

2688 2689 2690 2691
  spreadsheet_api.prototype.asc_getIsTrackShape = function()  {
    return this.wb ? this.wb.getIsTrackShape() : false;
  };

Alexander.Trofimov's avatar
Alexander.Trofimov committed
2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760
  spreadsheet_api.prototype.asc_setCellFontName = function(fontName) {
    var t = this, fonts = {};
    fonts[fontName] = 1;
    t._loadFonts(fonts, function() {
      var ws = t.wb.getWorksheet();
      if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellFontName) {
        ws.objectRender.controller.setCellFontName(fontName);
      } else {
        t.wb.setFontAttributes("fn", fontName);
        t.wb.restoreFocus();
      }
    });
  };

  spreadsheet_api.prototype.asc_setCellFontSize = function(fontSize) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellFontSize) {
      ws.objectRender.controller.setCellFontSize(fontSize);
    } else {
      this.wb.setFontAttributes("fs", fontSize);
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellBold = function(isBold) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellBold) {
      ws.objectRender.controller.setCellBold(isBold);
    } else {
      this.wb.setFontAttributes("b", isBold);
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellItalic = function(isItalic) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellItalic) {
      ws.objectRender.controller.setCellItalic(isItalic);
    } else {
      this.wb.setFontAttributes("i", isItalic);
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellUnderline = function(isUnderline) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellUnderline) {
      ws.objectRender.controller.setCellUnderline(isUnderline);
    } else {
      this.wb.setFontAttributes("u", isUnderline ? Asc.EUnderline.underlineSingle : Asc.EUnderline.underlineNone);
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellStrikeout = function(isStrikeout) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellStrikeout) {
      ws.objectRender.controller.setCellStrikeout(isStrikeout);
    } else {
      this.wb.setFontAttributes("s", isStrikeout);
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellSubscript = function(isSubscript) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellSubscript) {
      ws.objectRender.controller.setCellSubscript(isSubscript);
    } else {
2761
      this.wb.setFontAttributes("fa", isSubscript ? AscCommon.vertalign_SubScript : null);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2762 2763 2764 2765 2766 2767 2768 2769 2770
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellSuperscript = function(isSuperscript) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellSuperscript) {
      ws.objectRender.controller.setCellSuperscript(isSuperscript);
    } else {
2771
      this.wb.setFontAttributes("fa", isSuperscript ? AscCommon.vertalign_SuperScript : null);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2772 2773 2774 2775 2776
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellAlign = function(align) {
2777
    var ha = AscCommonExcel.horizontalAlignFromString(align);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2778 2779
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellAlign) {
2780
      ws.objectRender.controller.setCellAlign(ha);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2781
    } else {
2782
      this.wb.getWorksheet().setSelectionInfo("a", ha);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2783 2784 2785 2786 2787
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellVertAlign = function(align) {
2788
    var va = AscCommonExcel.verticalAlignFromString(align);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2789 2790
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellVertAlign) {
2791
      ws.objectRender.controller.setCellVertAlign(va);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2792
    } else {
2793
      this.wb.getWorksheet().setSelectionInfo("va", va);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellTextWrap = function(isWrapped) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellTextWrap) {
      ws.objectRender.controller.setCellTextWrap(isWrapped);
    } else {
      this.wb.getWorksheet().setSelectionInfo("wrap", isWrapped);
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellTextShrink = function(isShrinked) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellTextShrink) {
      ws.objectRender.controller.setCellTextShrink(isShrinked);
    } else {
      this.wb.getWorksheet().setSelectionInfo("shrink", isShrinked);
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellTextColor = function(color) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellTextColor) {
      ws.objectRender.controller.setCellTextColor(color);
    } else {
2823
      if (color instanceof Asc.asc_CColor) {
2824
        color = AscCommonExcel.CorrectAscColor(color);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836
        this.wb.setFontAttributes("c", color);
        this.wb.restoreFocus();
      }
    }

  };

  spreadsheet_api.prototype.asc_setCellBackgroundColor = function(color) {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellBackgroundColor) {
      ws.objectRender.controller.setCellBackgroundColor(color);
    } else {
2837
      if (color instanceof Asc.asc_CColor || null == color) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2838
        if (null != color) {
2839
          color = AscCommonExcel.CorrectAscColor(color);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852
        }
        this.wb.getWorksheet().setSelectionInfo("bc", color);
        this.wb.restoreFocus();
      }
    }
  };

  spreadsheet_api.prototype.asc_setCellBorders = function(borders) {
    this.wb.getWorksheet().setSelectionInfo("border", borders);
    this.wb.restoreFocus();
  };

  spreadsheet_api.prototype.asc_setCellFormat = function(format) {
2853
    this.wb.setCellFormat(format);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907
    this.wb.restoreFocus();
  };

  spreadsheet_api.prototype.asc_setCellAngle = function(angle) {

    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.setCellAngle) {
      ws.objectRender.controller.setCellAngle(angle);
    } else {
      this.wb.getWorksheet().setSelectionInfo("angle", angle);
      this.wb.restoreFocus();
    }
  };

  spreadsheet_api.prototype.asc_setCellStyle = function(name) {
    this.wb.getWorksheet().setSelectionInfo("style", name);
    this.wb.restoreFocus();
  };

  spreadsheet_api.prototype.asc_increaseCellDigitNumbers = function() {
    this.wb.getWorksheet().setSelectionInfo("changeDigNum", +1);
    this.wb.restoreFocus();
  };

  spreadsheet_api.prototype.asc_decreaseCellDigitNumbers = function() {
    this.wb.getWorksheet().setSelectionInfo("changeDigNum", -1);
    this.wb.restoreFocus();
  };

  // Увеличение размера шрифта
  spreadsheet_api.prototype.asc_increaseFontSize = function() {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.increaseFontSize) {
      ws.objectRender.controller.increaseFontSize();
    } else {
      this.wb.changeFontSize("changeFontSize", true);
      this.wb.restoreFocus();
    }
  };

  // Уменьшение размера шрифта
  spreadsheet_api.prototype.asc_decreaseFontSize = function() {
    var ws = this.wb.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists() && ws.objectRender.controller.decreaseFontSize) {
      ws.objectRender.controller.decreaseFontSize();
    } else {
      this.wb.changeFontSize("changeFontSize", false);
      this.wb.restoreFocus();
    }
  };

  // Формат по образцу
  spreadsheet_api.prototype.asc_formatPainter = function(stateFormatPainter) {
    if (this.wb) {
2908
      this.wb.formatPainter(stateFormatPainter);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2909 2910 2911
    }
  };

2912 2913 2914 2915
  spreadsheet_api.prototype.asc_showAutoComplete = function() {
    this.wb.showAutoComplete();
  };

Alexander.Trofimov's avatar
Alexander.Trofimov committed
2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933
  spreadsheet_api.prototype.asc_onMouseUp = function(event, x, y) {
    this.controller._onWindowMouseUpExternal(event, x, y);
  };

  //

  spreadsheet_api.prototype.asc_selectFunction = function() {

  };

  spreadsheet_api.prototype.asc_insertHyperlink = function(options) {
    this.wb.insertHyperlink(options);
  };

  spreadsheet_api.prototype.asc_removeHyperlink = function() {
    this.wb.removeHyperlink();
  };

2934 2935
  spreadsheet_api.prototype.asc_insertFormula = function(functionName, type, autoComplete) {
    this.wb.insertFormulaInEditor(functionName, type, autoComplete);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2936 2937 2938 2939 2940 2941 2942
    this.wb.restoreFocus();
  };

  spreadsheet_api.prototype.asc_getFormulasInfo = function() {
    return this.formulasList;
  };
  spreadsheet_api.prototype.asc_getFormulaLocaleName = function(name) {
2943
    return AscCommonExcel.cFormulaFunctionToLocale ? AscCommonExcel.cFormulaFunctionToLocale[name] : name;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960
  };

  spreadsheet_api.prototype.asc_recalc = function(isRecalcWB) {
    this.wbModel.recalcWB(isRecalcWB);
  };

  spreadsheet_api.prototype.asc_setFontRenderingMode = function(mode) {
    if (mode !== this.fontRenderingMode) {
      this.fontRenderingMode = mode;
      if (this.wb) {
        this.wb.setFontRenderingMode(mode, /*isInit*/false);
      }
    }
  };

  /**
   * Режим выбора диапазона
2961
   * @param {Asc.c_oAscSelectionDialogType} selectionDialogType
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2962 2963 2964
   * @param selectRange
   */
  spreadsheet_api.prototype.asc_setSelectionDialogMode = function(selectionDialogType, selectRange) {
2965
    this.controller.setSelectionDialogMode(Asc.c_oAscSelectionDialogType.None !== selectionDialogType);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979
    if (this.wb) {
      this.wb._onStopFormatPainter();
      this.wb.setSelectionDialogMode(selectionDialogType, selectRange);
    }
  };

  spreadsheet_api.prototype.asc_SendThemeColors = function(colors, standart_colors) {
    this._gui_control_colors = { Colors: colors, StandartColors: standart_colors };
    var ret = this.handlers.trigger("asc_onSendThemeColors", colors, standart_colors);
    if (false !== ret) {
      this._gui_control_colors = null;
    }
  };

2980 2981 2982 2983
	spreadsheet_api.prototype.asc_ChangeColorScheme = function (index) {
		var t = this;
		var onChangeColorScheme = function (res) {
			if (res) {
2984 2985
				if (t.wbModel.changeColorScheme(index)) {
					t.asc_AfterChangeColorScheme();
2986 2987 2988 2989 2990 2991 2992 2993 2994
				}
			}
		};
		// ToDo поправить заглушку, сделать новый тип lock element-а
		var sheetId = -1; // Делаем не существующий лист и не существующий объект
		var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Object, /*subType*/null, sheetId,
			sheetId);
		this._getIsLockObjectSheet(lockInfo, onChangeColorScheme);
	};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2995 2996 2997 2998 2999 3000
  spreadsheet_api.prototype.asc_AfterChangeColorScheme = function() {
    this.asc_CheckGuiControlColors();
    this.asc_ApplyColorScheme(true);
  };
  spreadsheet_api.prototype.asc_ApplyColorScheme = function(bRedraw) {

Alexey.Musinov's avatar
Alexey.Musinov committed
3001
    if (window['IS_NATIVE_EDITOR'] || !window["NATIVE_EDITOR_ENJINE"]) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012
      var wsViews = Asc["editor"].wb.wsViews;
      for (var i = 0; i < wsViews.length; ++i) {
        if (wsViews[i] && wsViews[i].objectRender && wsViews[i].objectRender.controller) {
          wsViews[i].objectRender.controller.startRecalculate();
        }
      }
      this.chartPreviewManager.clearPreviews();
      this.textArtPreviewManager.clear();
    }

    // На view-режиме не нужно отправлять стили
3013
    if (true !== this.getViewMode()) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3014 3015 3016 3017 3018 3019
      // Отправка стилей
      this._sendWorkbookStyles();
    }

    if (bRedraw) {
      this.handlers.trigger("asc_onUpdateChartStyles");
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3020
      this.handlers.trigger("asc_onSelectionChanged", this.asc_getCellInfo());
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3021 3022 3023 3024 3025 3026 3027
      this.wb.drawWS();
    }
  };

  /////////////////////////////////////////////////////////////////////////
  ////////////////////////////AutoSave api/////////////////////////////////
  /////////////////////////////////////////////////////////////////////////
3028
	spreadsheet_api.prototype._autoSave = function () {
3029 3030 3031 3032 3033 3034
		if (!this.DocumentLoadComplete || (!this.canUnlockDocument && 0 === this.autoSaveGap &&
			(!this.collaborativeEditing.getFast() || !this.collaborativeEditing.getCollaborativeEditing())) ||
			this.asc_getCellEditMode() || this.asc_getIsTrackShape() || this.isOpenedChartFrame ||
			!History.IsEndTransaction() || !this.canSave) {
			return;
		}
3035

3036 3037 3038 3039
		if (this.canUnlockDocument) {
			this.asc_Save(true);
			return;
		}
3040

3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065
		if (!History.Have_Changes(true) && !(this.collaborativeEditing.getCollaborativeEditing() &&
			0 !== this.collaborativeEditing.getOwnLocksLength())) {
			if (this.collaborativeEditing.getFast() && this.collaborativeEditing.haveOtherChanges()) {
				AscCommon.CollaborativeEditing.Clear_CollaborativeMarks();

				// Принимаем чужие изменения
				this.collaborativeEditing.applyChanges();
				// Пересылаем свои изменения (просто стираем чужие lock-и, т.к. своих изменений нет)
				this.collaborativeEditing.sendChanges();
				// Шлем update для toolbar-а, т.к. когда select в lock ячейке нужно заблокировать toolbar
				this.wb._onWSSelectionChanged();
			}
			return;
		}
		if (null === this.lastSaveTime) {
			this.lastSaveTime = new Date();
			return;
		}
		var saveGap = this.collaborativeEditing.getFast() ? this.autoSaveGapRealTime :
			(this.collaborativeEditing.getCollaborativeEditing() ? this.autoSaveGapSlow : this.autoSaveGapFast);
		var gap = new Date() - this.lastSaveTime - saveGap;
		if (0 <= gap) {
			this.asc_Save(true);
		}
	};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3066

Alexander.Trofimov's avatar
Alexander.Trofimov committed
3067 3068 3069 3070 3071 3072 3073 3074 3075
	spreadsheet_api.prototype._onUpdateDocumentCanSave = function () {
		// Можно модифицировать это условие на более быстрое (менять самим состояние в аргументах, а не запрашивать каждый раз)
		var tmp = History.Have_Changes() || (this.collaborativeEditing.getCollaborativeEditing() &&
			0 !== this.collaborativeEditing.getOwnLocksLength()) || this.asc_getCellEditMode();
		if (tmp !== this.isDocumentCanSave) {
			this.isDocumentCanSave = tmp;
			this.handlers.trigger('asc_onDocumentCanSaveChanged', this.isDocumentCanSave);
		}
	};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3076 3077 3078 3079

  spreadsheet_api.prototype._onCheckCommentRemoveLock = function(lockElem) {
    var res = false;
    var sheetId = lockElem["sheetId"];
3080
    if (-1 !== sheetId && 0 === sheetId.indexOf(AscCommonExcel.CCellCommentator.sStartCommentId)) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099
      // Коммментарий
      res = true;
      this.handlers.trigger("asc_onUnLockComment", lockElem["rangeOrObjectId"]);
    }
    return res;
  };

  spreadsheet_api.prototype.onUpdateDocumentModified = function(bIsModified) {
    // Обновляем только после окончания сохранения
    if (this.canSave) {
      this.handlers.trigger("asc_onDocumentModifiedChanged", bIsModified);
      this._onUpdateDocumentCanSave();

      if (undefined !== window["AscDesktopEditor"]) {
        window["AscDesktopEditor"]["onDocumentModifiedChanged"](bIsModified);
      }
    }
  };

3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128
	// Выставление локали
	spreadsheet_api.prototype.asc_setLocalization = function (oLocalizedData) {
		if (!this.isLoadFullApi) {
			this.tmpLocalization = oLocalizedData;
			return;
		}

		if (null == oLocalizedData) {
			AscCommonExcel.cFormulaFunctionLocalized = null;
			AscCommonExcel.cFormulaFunctionToLocale = null;
		} else {
			AscCommonExcel.cFormulaFunctionLocalized = {};
			AscCommonExcel.cFormulaFunctionToLocale = {};
			var localName;
			for (var i in AscCommonExcel.cFormulaFunction) {
				localName = oLocalizedData[i] ? oLocalizedData[i] : null;
				localName = localName ? localName : i;
				AscCommonExcel.cFormulaFunctionLocalized[localName] = AscCommonExcel.cFormulaFunction[i];
				AscCommonExcel.cFormulaFunctionToLocale[i] = localName;
			}
		}
		AscCommon.build_local_rx(oLocalizedData ? oLocalizedData["LocalFormulaOperands"] : null);
		if (this.wb) {
			this.wb.initFormulasList();
		}
		if (this.wbModel) {
			this.wbModel.rebuildColors();
		}
	};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3129

alexey.musinov's avatar
alexey.musinov committed
3130
  spreadsheet_api.prototype.asc_nativeOpenFile = function(base64File, version, isUser) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3131 3132 3133
    asc["editor"] = this;

    this.SpellCheckUrl = '';
alexey.musinov's avatar
alexey.musinov committed
3134 3135 3136 3137 3138 3139
 
    if (undefined == isUser) {
        this.User = new AscCommon.asc_CUser();
        this.User.setId("TM");
        this.User.setUserName("native");
    }
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3140

3141
    this.wbModel = new AscCommonExcel.Workbook(this.handlers, this);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3142 3143
    this.initGlobalObjects(this.wbModel);

3144
    var oBinaryFileReader = new AscCommonExcel.BinaryFileReader();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3145 3146 3147 3148

    if (undefined === version) {
      oBinaryFileReader.Read(base64File, this.wbModel);
    } else {
3149
      AscCommon.CurFileVersion = version;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3150 3151 3152 3153
      oBinaryFileReader.ReadData(base64File, this.wbModel);
    }
    g_oIdCounter.Set_Load(false);

Alexander.Trofimov's avatar
Alexander.Trofimov committed
3154
    this._coAuthoringInit();
3155
    this.wb = new AscCommonExcel.WorkbookView(this.wbModel, this.controller, this.handlers, window["_null_object"], window["_null_object"], this, this.collaborativeEditing, this.fontRenderingMode);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3156 3157 3158
  };

  spreadsheet_api.prototype.asc_nativeCalculateFile = function() {
Oleg.Korshul's avatar
Oleg.Korshul committed
3159 3160
    window['DoctRendererMode'] = true;	
    this.wb._nativeCalculate();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179
  };

  spreadsheet_api.prototype.asc_nativeApplyChanges = function(changes) {
    for (var i = 0, l = changes.length; i < l; ++i) {
      this.CoAuthoringApi.onSaveChanges(changes[i], null, true);
    }
    this.collaborativeEditing.applyChanges();
  };

  spreadsheet_api.prototype.asc_nativeApplyChanges2 = function(data, isFull) {
    if (null != this.wbModel) {
      this.oRedoObjectParamNative = this.wbModel.DeserializeHistoryNative(this.oRedoObjectParamNative, data, isFull);
    }
    if (isFull) {
      this._onUpdateAfterApplyChanges();
    }
  };

  spreadsheet_api.prototype.asc_nativeGetFile = function() {
3180
    var oBinaryFileWriter = new AscCommonExcel.BinaryFileWriter(this.wbModel);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3181 3182 3183
    return oBinaryFileWriter.Write();
  };
  spreadsheet_api.prototype.asc_nativeGetFileData = function() {
3184
    var oBinaryFileWriter = new AscCommonExcel.BinaryFileWriter(this.wbModel);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215
    oBinaryFileWriter.Write2();

    var _header = oBinaryFileWriter.WriteFileHeader(oBinaryFileWriter.Memory.GetCurPosition());
    window["native"]["Save_End"](_header, oBinaryFileWriter.Memory.GetCurPosition());

    return oBinaryFileWriter.Memory.ImData.data;
  };

  spreadsheet_api.prototype.asc_nativeCheckPdfRenderer = function(_memory1, _memory2) {
    if (true) {
      // pos не должен минимизироваться!!!

      _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"];
    }

3216
    var _printer = new AscCommonExcel.CPdfPrinter();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3217 3218 3219 3220 3221 3222 3223 3224
    _printer.DocumentRenderer.Memory = _memory1;
    _printer.DocumentRenderer.VectorMemoryForPrint = _memory2;
    return _printer;
  };

  spreadsheet_api.prototype.asc_nativeCalculate = function() {
  };

3225 3226
  spreadsheet_api.prototype.asc_nativePrint = function (_printer, _page, _param) {
    var _adjustPrint = window.AscDesktopEditor_PrintData || new Asc.asc_CAdjustPrint();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3227 3228
    window.AscDesktopEditor_PrintData = undefined;

3229 3230
    var isOnePage = ((_param & 0x0100) == 0x0100);
    _param &= 0xFF;
3231
    if (1 == _param) {
3232
      _adjustPrint.asc_setPrintType(Asc.c_oAscPrintType.EntireWorkbook);
3233
      var pageSetup;
3234
      var countWorksheets = this.wbModel.getWorksheetCount();
3235
      for (var j = 0; j < countWorksheets; ++j) {
3236 3237 3238
        pageSetup = this.wbModel.getWorksheet(j).PagePrintOptions.asc_getPageSetup();
        pageSetup.asc_setFitToWidth(true);
        pageSetup.asc_setFitToHeight(true);
3239
      }
Oleg.Korshul's avatar
Oleg.Korshul committed
3240 3241
    }

Alexander.Trofimov's avatar
Alexander.Trofimov committed
3242 3243 3244
    var _printPagesData = this.wb.calcPagesPrint(_adjustPrint);

    if (undefined === _printer && _page === undefined) {
3245
      var pdf_writer = new AscCommonExcel.CPdfPrinter();
3246
      this.wb.printSheets(pdf_writer, _printPagesData);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3247 3248 3249 3250

      if (undefined !== window["AscDesktopEditor"]) {
        var pagescount = pdf_writer.DocumentRenderer.m_lPagesCount;

3251
        window["AscDesktopEditor"]["Print_Start"](this.documentId + "/", pagescount, "", -1);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3252 3253 3254 3255 3256 3257 3258 3259

        for (var i = 0; i < pagescount; i++) {
          var _start = pdf_writer.DocumentRenderer.m_arrayPages[i].StartOffset;
          var _end = pdf_writer.DocumentRenderer.Memory.pos;
          if (i != (pagescount - 1)) {
            _end = pdf_writer.DocumentRenderer.m_arrayPages[i + 1].StartOffset;
          }

3260 3261 3262
          window["AscDesktopEditor"]["Print_Page"](
            pdf_writer.DocumentRenderer.Memory.GetBase64Memory2(_start, _end - _start),
            pdf_writer.DocumentRenderer.m_arrayPages[i].Width, pdf_writer.DocumentRenderer.m_arrayPages[i].Height);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3263
        }
3264

Alexander.Trofimov's avatar
Alexander.Trofimov committed
3265 3266
        window["AscDesktopEditor"]["Print_End"]();
      }
3267
      return pdf_writer.DocumentRenderer.Memory;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3268 3269
    }

3270
    this.wb.printSheets(_printer, _printPagesData);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3271 3272 3273 3274 3275 3276 3277
    return _printer.DocumentRenderer.Memory;
  };

  spreadsheet_api.prototype.asc_nativePrintPagesCount = function() {
    return 1;
  };

Oleg.Korshul's avatar
Oleg.Korshul committed
3278 3279
  spreadsheet_api.prototype.asc_nativeGetPDF = function(_param) {
    var _ret = this.asc_nativePrint(undefined, undefined, _param);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3280 3281 3282 3283

    window["native"]["Save_End"]("", _ret.GetCurPosition());
    return _ret.data;
  };
3284

3285 3286 3287 3288 3289
  spreadsheet_api.prototype.asc_canPaste = function () {
    History.Create_NewPoint();
    History.StartTransaction();
    return true;
  };
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3290 3291 3292
  spreadsheet_api.prototype.asc_endPaste = function () {
    History.EndTransaction();
  };
3293
  spreadsheet_api.prototype.asc_Recalculate = function () {
3294
      History.EndTransaction();
3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316
      this._onUpdateAfterApplyChanges();
  };


  spreadsheet_api.prototype.pre_Paste = function(_fonts, _images, callback)
  {
    var oFontMap = {};
    for(var i = 0; i < _fonts.length; ++i){
      oFontMap[_fonts[i].name] = 1;
    }
    this._loadFonts(oFontMap, function() {

      var aImages = [];
      for(var key in _images){
        if(_images.hasOwnProperty(key)){
          aImages.push(_images[key])
        }
      }
      if(aImages.length > 0)      {
         window["Asc"]["editor"].ImageLoader.LoadDocumentImages(aImages, null);
      }
      callback();
3317
    });
3318 3319
  };

3320 3321
	spreadsheet_api.prototype._onEndLoadSdk = function () {
		History = AscCommon.History;
3322

3323
		AscCommon.baseEditorsApi.prototype._onEndLoadSdk.call(this);
3324

3325
		this.controller = new AscCommonExcel.asc_CEventsController();
3326

3327 3328 3329 3330 3331
		this.formulasList = AscCommonExcel.getFormulasInfo();
		this.asc_setLocale(this.tmpLocale);
		this.asc_setLocalization(this.tmpLocalization);
		this.asc_setViewMode(this.isViewMode);
	};
3332

Alexander.Trofimov's avatar
Alexander.Trofimov committed
3333 3334 3335 3336
	spreadsheet_api.prototype.asc_OnShowContextMenu = function() {
	  this.asc_closeCellEditor();
    };

Alexander.Trofimov's avatar
Alexander.Trofimov committed
3337 3338 3339 3340 3341 3342
  /*
   * Export
   * -----------------------------------------------------------------------------
   */

  window["AscDesktopEditor_Save"] = function() {
3343
    return window["Asc"]["editor"].asc_Save(false);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3344 3345 3346 3347 3348 3349 3350
  };

  asc["spreadsheet_api"] = spreadsheet_api;
  prot = spreadsheet_api.prototype;

  prot["asc_GetFontThumbnailsPath"] = prot.asc_GetFontThumbnailsPath;
  prot["asc_setDocInfo"] = prot.asc_setDocInfo;
3351
	prot['asc_getCurrencySymbols'] = prot.asc_getCurrencySymbols;
3352
	prot['asc_getLocaleExample'] = prot.asc_getLocaleExample;
3353
	prot['asc_getFormatCells'] = prot.asc_getFormatCells;
3354
  prot["asc_getLocaleCurrency"] = prot.asc_getLocaleCurrency;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3355 3356 3357 3358 3359 3360
  prot["asc_setLocale"] = prot.asc_setLocale;
  prot["asc_getEditorPermissions"] = prot.asc_getEditorPermissions;
  prot["asc_LoadDocument"] = prot.asc_LoadDocument;
  prot["asc_LoadEmptyDocument"] = prot.asc_LoadEmptyDocument;
  prot["asc_DownloadAs"] = prot.asc_DownloadAs;
  prot["asc_Save"] = prot.asc_Save;
konovalovsergey's avatar
konovalovsergey committed
3361 3362
  prot["forceSave"] = prot.forceSave;
  prot["asc_setIsForceSaveOnUserSave"] = prot.asc_setIsForceSaveOnUserSave;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3363 3364 3365 3366
  prot["asc_Print"] = prot.asc_Print;
  prot["asc_Resize"] = prot.asc_Resize;
  prot["asc_Copy"] = prot.asc_Copy;
  prot["asc_Paste"] = prot.asc_Paste;
GoshaZotov's avatar
GoshaZotov committed
3367
  prot["asc_SpecialPaste"] = prot.asc_SpecialPaste;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379
  prot["asc_Cut"] = prot.asc_Cut;
  prot["asc_Undo"] = prot.asc_Undo;
  prot["asc_Redo"] = prot.asc_Redo;

  prot["asc_getDocumentName"] = prot.asc_getDocumentName;
  prot["asc_isDocumentModified"] = prot.asc_isDocumentModified;
  prot["asc_isDocumentCanSave"] = prot.asc_isDocumentCanSave;
  prot["asc_getCanUndo"] = prot.asc_getCanUndo;
  prot["asc_getCanRedo"] = prot.asc_getCanRedo;

  prot["asc_setAutoSaveGap"] = prot.asc_setAutoSaveGap;

Alexander.Trofimov's avatar
Alexander.Trofimov committed
3380
  prot["asc_setViewMode"] = prot.asc_setViewMode;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391
  prot["asc_setAdvancedOptions"] = prot.asc_setAdvancedOptions;
  prot["asc_setPageOptions"] = prot.asc_setPageOptions;
  prot["asc_getPageOptions"] = prot.asc_getPageOptions;

  prot["asc_registerCallback"] = prot.asc_registerCallback;
  prot["asc_unregisterCallback"] = prot.asc_unregisterCallback;

  prot["asc_getController"] = prot.asc_getController;
  prot["asc_changeArtImageFromFile"] = prot.asc_changeArtImageFromFile;

  prot["asc_SetDocumentPlaceChangedEnabled"] = prot.asc_SetDocumentPlaceChangedEnabled;
3392
  prot["asc_SetFastCollaborative"] = prot.asc_SetFastCollaborative;
3393
	prot["asc_setThumbnailStylesSizes"] = prot.asc_setThumbnailStylesSizes;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433

  // Workbook interface

  prot["asc_getWorksheetsCount"] = prot.asc_getWorksheetsCount;
  prot["asc_getWorksheetName"] = prot.asc_getWorksheetName;
  prot["asc_getWorksheetTabColor"] = prot.asc_getWorksheetTabColor;
  prot["asc_setWorksheetTabColor"] = prot.asc_setWorksheetTabColor;
  prot["asc_getActiveWorksheetIndex"] = prot.asc_getActiveWorksheetIndex;
  prot["asc_getActiveWorksheetId"] = prot.asc_getActiveWorksheetId;
  prot["asc_getWorksheetId"] = prot.asc_getWorksheetId;
  prot["asc_isWorksheetHidden"] = prot.asc_isWorksheetHidden;
  prot["asc_isWorksheetLockedOrDeleted"] = prot.asc_isWorksheetLockedOrDeleted;
  prot["asc_isWorkbookLocked"] = prot.asc_isWorkbookLocked;
  prot["asc_getHiddenWorksheets"] = prot.asc_getHiddenWorksheets;
  prot["asc_showWorksheet"] = prot.asc_showWorksheet;
  prot["asc_showActiveWorksheet"] = prot.asc_showActiveWorksheet;
  prot["asc_hideWorksheet"] = prot.asc_hideWorksheet;
  prot["asc_renameWorksheet"] = prot.asc_renameWorksheet;
  prot["asc_addWorksheet"] = prot.asc_addWorksheet;
  prot["asc_insertWorksheet"] = prot.asc_insertWorksheet;
  prot["asc_deleteWorksheet"] = prot.asc_deleteWorksheet;
  prot["asc_moveWorksheet"] = prot.asc_moveWorksheet;
  prot["asc_copyWorksheet"] = prot.asc_copyWorksheet;
  prot["asc_cleanSelection"] = prot.asc_cleanSelection;
  prot["asc_getZoom"] = prot.asc_getZoom;
  prot["asc_setZoom"] = prot.asc_setZoom;
  prot["asc_enableKeyEvents"] = prot.asc_enableKeyEvents;
  prot["asc_searchEnabled"] = prot.asc_searchEnabled;
  prot["asc_findText"] = prot.asc_findText;
  prot["asc_replaceText"] = prot.asc_replaceText;
  prot["asc_endFindText"] = prot.asc_endFindText;
  prot["asc_findCell"] = prot.asc_findCell;
  prot["asc_closeCellEditor"] = prot.asc_closeCellEditor;

  // Spreadsheet interface

  prot["asc_getColumnWidth"] = prot.asc_getColumnWidth;
  prot["asc_setColumnWidth"] = prot.asc_setColumnWidth;
  prot["asc_showColumns"] = prot.asc_showColumns;
  prot["asc_hideColumns"] = prot.asc_hideColumns;
3434
  prot["asc_autoFitColumnWidth"] = prot.asc_autoFitColumnWidth;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3435 3436
  prot["asc_getRowHeight"] = prot.asc_getRowHeight;
  prot["asc_setRowHeight"] = prot.asc_setRowHeight;
3437
  prot["asc_autoFitRowHeight"] = prot.asc_autoFitRowHeight;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3438 3439 3440 3441 3442 3443 3444 3445
  prot["asc_showRows"] = prot.asc_showRows;
  prot["asc_hideRows"] = prot.asc_hideRows;
  prot["asc_insertCells"] = prot.asc_insertCells;
  prot["asc_deleteCells"] = prot.asc_deleteCells;
  prot["asc_mergeCells"] = prot.asc_mergeCells;
  prot["asc_sortCells"] = prot.asc_sortCells;
  prot["asc_emptyCells"] = prot.asc_emptyCells;
  prot["asc_mergeCellsDataLost"] = prot.asc_mergeCellsDataLost;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3446
  prot["asc_sortCellsRangeExpand"] = prot.asc_sortCellsRangeExpand;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3447
  prot["asc_getSheetViewSettings"] = prot.asc_getSheetViewSettings;
3448 3449
	prot["asc_setDisplayGridlines"] = prot.asc_setDisplayGridlines;
	prot["asc_setDisplayHeadings"] = prot.asc_setDisplayHeadings;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3450 3451 3452 3453 3454 3455 3456 3457 3458

  // Defined Names
  prot["asc_getDefinedNames"] = prot.asc_getDefinedNames;
  prot["asc_setDefinedNames"] = prot.asc_setDefinedNames;
  prot["asc_editDefinedNames"] = prot.asc_editDefinedNames;
  prot["asc_delDefinedNames"] = prot.asc_delDefinedNames;
  prot["asc_getDefaultDefinedName"] = prot.asc_getDefaultDefinedName;
  prot["asc_checkDefinedName"] = prot.asc_checkDefinedName;

3459
  // Auto filters interface + format as table
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3460 3461 3462
  prot["asc_addAutoFilter"] = prot.asc_addAutoFilter;
  prot["asc_changeAutoFilter"] = prot.asc_changeAutoFilter;
  prot["asc_applyAutoFilter"] = prot.asc_applyAutoFilter;
3463
  prot["asc_applyAutoFilterByType"] = prot.asc_applyAutoFilterByType;
3464
  prot["asc_reapplyAutoFilter"] = prot.asc_reapplyAutoFilter;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3465 3466 3467
  prot["asc_sortColFilter"] = prot.asc_sortColFilter;
  prot["asc_getAddFormatTableOptions"] = prot.asc_getAddFormatTableOptions;
  prot["asc_clearFilter"] = prot.asc_clearFilter;
3468
  prot["asc_clearFilterColumn"] = prot.asc_clearFilterColumn;
3469
  prot["asc_changeSelectionFormatTable"] = prot.asc_changeSelectionFormatTable;
3470
  prot["asc_changeFormatTableInfo"] = prot.asc_changeFormatTableInfo;
3471 3472
  prot["asc_insertCellsInTable"] = prot.asc_insertCellsInTable;
  prot["asc_deleteCellsInTable"] = prot.asc_deleteCellsInTable;
3473
  prot["asc_changeDisplayNameTable"] = prot.asc_changeDisplayNameTable;
3474
  prot["asc_changeTableRange"] = prot.asc_changeTableRange;
3475
  prot["asc_convertTableToRange"] = prot.asc_convertTableToRange;
3476
  prot["asc_getTablePictures"] = prot.asc_getTablePictures;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490

  // Drawing objects interface

  prot["asc_showDrawingObjects"] = prot.asc_showDrawingObjects;
  prot["asc_setChartTranslate"] = prot.asc_setChartTranslate;
  prot["asc_setTextArtTranslate"] = prot.asc_setTextArtTranslate;
  prot["asc_drawingObjectsExist"] = prot.asc_drawingObjectsExist;
  prot["asc_getChartObject"] = prot.asc_getChartObject;
  prot["asc_addChartDrawingObject"] = prot.asc_addChartDrawingObject;
  prot["asc_editChartDrawingObject"] = prot.asc_editChartDrawingObject;
  prot["asc_addImageDrawingObject"] = prot.asc_addImageDrawingObject;
  prot["asc_setSelectedDrawingObjectLayer"] = prot.asc_setSelectedDrawingObjectLayer;
  prot["asc_getChartPreviews"] = prot.asc_getChartPreviews;
  prot["asc_getTextArtPreviews"] = prot.asc_getTextArtPreviews;
3491
  prot['asc_getPropertyEditorShapes'] = prot.asc_getPropertyEditorShapes;
3492
  prot['asc_getPropertyEditorTextArts'] = prot.asc_getPropertyEditorTextArts;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3493 3494 3495 3496 3497
  prot["asc_checkDataRange"] = prot.asc_checkDataRange;
  prot["asc_getBinaryFileWriter"] = prot.asc_getBinaryFileWriter;
  prot["asc_getWordChartObject"] = prot.asc_getWordChartObject;
  prot["asc_cleanWorksheet"] = prot.asc_cleanWorksheet;
  prot["asc_showImageFileDialog"] = prot.asc_showImageFileDialog;
3498
  prot["asc_addImage"] = prot.asc_addImage;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3499 3500
  prot["asc_setData"] = prot.asc_setData;
  prot["asc_getData"] = prot.asc_getData;
3501
  prot["asc_onCloseChartFrame"] = prot.asc_onCloseChartFrame;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521

  // Cell comment interface
  prot["asc_addComment"] = prot.asc_addComment;
  prot["asc_changeComment"] = prot.asc_changeComment;
  prot["asc_findComment"] = prot.asc_findComment;
  prot["asc_removeComment"] = prot.asc_removeComment;
  prot["asc_showComment"] = prot.asc_showComment;
  prot["asc_selectComment"] = prot.asc_selectComment;

  prot["asc_showComments"] = prot.asc_showComments;
  prot["asc_hideComments"] = prot.asc_hideComments;

  prot["asc_getComments"] = prot.asc_getComments;
  prot["asc_getDocumentComments"] = prot.asc_getDocumentComments;

  // Shapes
  prot["setStartPointHistory"] = prot.setStartPointHistory;
  prot["setEndPointHistory"] = prot.setEndPointHistory;
  prot["asc_startAddShape"] = prot.asc_startAddShape;
  prot["asc_endAddShape"] = prot.asc_endAddShape;
Sergey Luzyanin's avatar
Sergey Luzyanin committed
3522
  prot["asc_addShapeOnSheet"] = prot.asc_addShapeOnSheet;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540
  prot["asc_isAddAutoshape"] = prot.asc_isAddAutoshape;
  prot["asc_canAddShapeHyperlink"] = prot.asc_canAddShapeHyperlink;
  prot["asc_canGroupGraphicsObjects"] = prot.asc_canGroupGraphicsObjects;
  prot["asc_groupGraphicsObjects"] = prot.asc_groupGraphicsObjects;
  prot["asc_canUnGroupGraphicsObjects"] = prot.asc_canUnGroupGraphicsObjects;
  prot["asc_unGroupGraphicsObjects"] = prot.asc_unGroupGraphicsObjects;
  prot["asc_getGraphicObjectProps"] = prot.asc_getGraphicObjectProps;
  prot["asc_setGraphicObjectProps"] = prot.asc_setGraphicObjectProps;
  prot["asc_getOriginalImageSize"] = prot.asc_getOriginalImageSize;
  prot["asc_changeShapeType"] = prot.asc_changeShapeType;
  prot["asc_setInterfaceDrawImagePlaceShape"] = prot.asc_setInterfaceDrawImagePlaceShape;
  prot["asc_setInterfaceDrawImagePlaceTextArt"] = prot.asc_setInterfaceDrawImagePlaceTextArt;
  prot["asc_changeImageFromFile"] = prot.asc_changeImageFromFile;
  prot["asc_putPrLineSpacing"] = prot.asc_putPrLineSpacing;
  prot["asc_addTextArt"] = prot.asc_addTextArt;
  prot["asc_putLineSpacingBeforeAfter"] = prot.asc_putLineSpacingBeforeAfter;
  prot["asc_setDrawImagePlaceParagraph"] = prot.asc_setDrawImagePlaceParagraph;
  prot["asc_changeShapeImageFromFile"] = prot.asc_changeShapeImageFromFile;
3541 3542 3543
  prot["asc_AddMath"] = prot.asc_AddMath;
  prot["asc_SetMathProps"] = prot.asc_SetMathProps;
  //----------------------------------------------------------------------------------------------------------------------
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3544 3545 3546 3547

  // Frozen pane
  prot["asc_freezePane"] = prot.asc_freezePane;

3548 3549 3550
  // Sparklines
  prot["asc_setSparklineGroup"] = prot.asc_setSparklineGroup;

Alexander.Trofimov's avatar
Alexander.Trofimov committed
3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577
  // Cell interface
  prot["asc_getCellInfo"] = prot.asc_getCellInfo;
  prot["asc_getActiveCellCoord"] = prot.asc_getActiveCellCoord;
  prot["asc_getAnchorPosition"] = prot.asc_getAnchorPosition;
  prot["asc_setCellFontName"] = prot.asc_setCellFontName;
  prot["asc_setCellFontSize"] = prot.asc_setCellFontSize;
  prot["asc_setCellBold"] = prot.asc_setCellBold;
  prot["asc_setCellItalic"] = prot.asc_setCellItalic;
  prot["asc_setCellUnderline"] = prot.asc_setCellUnderline;
  prot["asc_setCellStrikeout"] = prot.asc_setCellStrikeout;
  prot["asc_setCellSubscript"] = prot.asc_setCellSubscript;
  prot["asc_setCellSuperscript"] = prot.asc_setCellSuperscript;
  prot["asc_setCellAlign"] = prot.asc_setCellAlign;
  prot["asc_setCellVertAlign"] = prot.asc_setCellVertAlign;
  prot["asc_setCellTextWrap"] = prot.asc_setCellTextWrap;
  prot["asc_setCellTextShrink"] = prot.asc_setCellTextShrink;
  prot["asc_setCellTextColor"] = prot.asc_setCellTextColor;
  prot["asc_setCellBackgroundColor"] = prot.asc_setCellBackgroundColor;
  prot["asc_setCellBorders"] = prot.asc_setCellBorders;
  prot["asc_setCellFormat"] = prot.asc_setCellFormat;
  prot["asc_setCellAngle"] = prot.asc_setCellAngle;
  prot["asc_setCellStyle"] = prot.asc_setCellStyle;
  prot["asc_increaseCellDigitNumbers"] = prot.asc_increaseCellDigitNumbers;
  prot["asc_decreaseCellDigitNumbers"] = prot.asc_decreaseCellDigitNumbers;
  prot["asc_increaseFontSize"] = prot.asc_increaseFontSize;
  prot["asc_decreaseFontSize"] = prot.asc_decreaseFontSize;
  prot["asc_formatPainter"] = prot.asc_formatPainter;
3578
  prot["asc_showAutoComplete"] = prot.asc_showAutoComplete;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619

  prot["asc_onMouseUp"] = prot.asc_onMouseUp;

  prot["asc_selectFunction"] = prot.asc_selectFunction;
  prot["asc_insertHyperlink"] = prot.asc_insertHyperlink;
  prot["asc_removeHyperlink"] = prot.asc_removeHyperlink;
  prot["asc_insertFormula"] = prot.asc_insertFormula;
  prot["asc_getFormulasInfo"] = prot.asc_getFormulasInfo;
  prot["asc_getFormulaLocaleName"] = prot.asc_getFormulaLocaleName;
  prot["asc_setFontRenderingMode"] = prot.asc_setFontRenderingMode;
  prot["asc_setSelectionDialogMode"] = prot.asc_setSelectionDialogMode;
  prot["asc_ChangeColorScheme"] = prot.asc_ChangeColorScheme;
  /////////////////////////////////////////////////////////////////////////
  ///////////////////CoAuthoring and Chat api//////////////////////////////
  /////////////////////////////////////////////////////////////////////////
  prot["asc_coAuthoringChatSendMessage"] = prot.asc_coAuthoringChatSendMessage;
  prot["asc_coAuthoringGetUsers"] = prot.asc_coAuthoringGetUsers;
  prot["asc_coAuthoringChatGetMessages"] = prot.asc_coAuthoringChatGetMessages;
  prot["asc_coAuthoringDisconnect"] = prot.asc_coAuthoringDisconnect;

  // other
  prot["asc_stopSaving"] = prot.asc_stopSaving;
  prot["asc_continueSaving"] = prot.asc_continueSaving;

  // Version History
  prot["asc_undoAllChanges"] = prot.asc_undoAllChanges;

  prot["asc_setLocalization"] = prot.asc_setLocalization;

  // native
  prot["asc_nativeOpenFile"] = prot.asc_nativeOpenFile;
  prot["asc_nativeCalculateFile"] = prot.asc_nativeCalculateFile;
  prot["asc_nativeApplyChanges"] = prot.asc_nativeApplyChanges;
  prot["asc_nativeApplyChanges2"] = prot.asc_nativeApplyChanges2;
  prot["asc_nativeGetFile"] = prot.asc_nativeGetFile;
  prot["asc_nativeGetFileData"] = prot.asc_nativeGetFileData;
  prot["asc_nativeCheckPdfRenderer"] = prot.asc_nativeCheckPdfRenderer;
  prot["asc_nativeCalculate"] = prot.asc_nativeCalculate;
  prot["asc_nativePrint"] = prot.asc_nativePrint;
  prot["asc_nativePrintPagesCount"] = prot.asc_nativePrintPagesCount;
  prot["asc_nativeGetPDF"] = prot.asc_nativeGetPDF;
3620 3621
  
  prot['asc_isOffline'] = prot.asc_isOffline;
3622
  prot['asc_getUrlType'] = prot.asc_getUrlType;
3623 3624 3625 3626

  // Builder
  prot['asc_nativeInitBuilder'] = prot.asc_nativeInitBuilder;
  prot['asc_SetSilentMode'] = prot.asc_SetSilentMode;
Oleg Korshul's avatar
Oleg Korshul committed
3627 3628 3629 3630 3631

  // plugins
  prot["asc_pluginsRegister"]       = prot.asc_pluginsRegister;
  prot["asc_pluginRun"]             = prot.asc_pluginRun;
  prot["asc_pluginResize"]          = prot.asc_pluginResize;
Oleg Korshul's avatar
Oleg Korshul committed
3632
  prot["asc_pluginButtonClick"]     = prot.asc_pluginButtonClick;
3633 3634
  prot["asc_addOleObject"]          = prot.asc_addOleObject;
  prot["asc_editOleObject"]         = prot.asc_editOleObject;
Sergey Luzyanin's avatar
Sergey Luzyanin committed
3635
  prot["asc_startEditCurrentOleObject"]         = prot.asc_startEditCurrentOleObject;
Oleg Korshul's avatar
Oleg Korshul committed
3636
  prot["asc_pluginEnableMouseEvents"] = prot.asc_pluginEnableMouseEvents;
3637

Oleg Korshul's avatar
Oleg Korshul committed
3638 3639 3640 3641
  // system input
  prot["SetTextBoxInputMode"]       = prot.SetTextBoxInputMode;
  prot["GetTextBoxInputMode"]       = prot.GetTextBoxInputMode;

3642
  prot["asc_InputClearKeyboardElement"] = prot.asc_InputClearKeyboardElement;
3643

Oleg Korshul's avatar
Oleg Korshul committed
3644
  prot["asc_OnHideContextMenu"] = prot.asc_OnHideContextMenu;
Oleg Korshul's avatar
.  
Oleg Korshul committed
3645
  prot["asc_OnShowContextMenu"] = prot.asc_OnShowContextMenu;
Oleg Korshul's avatar
Oleg Korshul committed
3646

3647 3648
  // mobile
  prot["asc_Remove"] = prot.asc_Remove;
3649
})(window);