WorkbookView.js 113 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

35
(/**
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
36 37 38
 * @param {Window} window
 * @param {undefined} undefined
 */
39
  function(window, undefined) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
40 41 42 43 44 45


  /*
   * Import
   * -----------------------------------------------------------------------------
   */
46
  var c_oAscFormatPainterState = AscCommon.c_oAscFormatPainterState;
47
  var AscBrowser = AscCommon.AscBrowser;
48
  var CColor = AscCommon.CColor;
49
  var cBoolLocal = AscCommon.cBoolLocal;
50
  var History = AscCommon.History;
51

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
52
  var asc = window["Asc"];
53
  var asc_applyFunction = AscCommonExcel.applyFunction;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
54 55
  var asc_round = asc.round;
  var asc_typeof = asc.typeOf;
56 57
  var asc_CMM = AscCommonExcel.asc_CMouseMoveData;
  var asc_CPrintPagesData = AscCommonExcel.CPrintPagesData;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
58
  var asc_getcvt = asc.getCvtRatio;
59
  var asc_CSP = AscCommonExcel.asc_CStylesPainter;
60 61 62 63 64 65 66
  var c_oTargetType = AscCommonExcel.c_oTargetType;
  var c_oAscError = asc.c_oAscError;
  var c_oAscCleanOptions = asc.c_oAscCleanOptions;
  var c_oAscSelectionDialogType = asc.c_oAscSelectionDialogType;
  var c_oAscMouseMoveType = asc.c_oAscMouseMoveType;
  var c_oAscCellEditorState = asc.c_oAscCellEditorState;
  var c_oAscPopUpSelectorType = asc.c_oAscPopUpSelectorType;
67 68 69
  var c_oAscAsyncAction = asc.c_oAscAsyncAction;
  var c_oAscFontRenderingModeType = asc.c_oAscFontRenderingModeType;
  var c_oAscAsyncActionType = asc.c_oAscAsyncActionType;
70 71
  
  var g_clipboardExcel = AscCommonExcel.g_clipboardExcel;
72

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
73

Alexander.Trofimov's avatar
Alexander.Trofimov committed
74
  function WorkbookCommentsModel(handlers, aComments) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
75
    this.workbook = {handlers: handlers};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
76
    this.aComments = aComments;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
77 78 79
  }

  WorkbookCommentsModel.prototype.getId = function() {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
80
    return null;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
81 82 83 84 85 86 87
  };
  WorkbookCommentsModel.prototype.getMergedByCell = function() {
    return null;
  };

  function WorksheetViewSettings() {
    this.header = {
88
      style: [// Header colors
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
89
        { // kHeaderDefault
90 91 92 93 94 95 96 97
          background: new CColor(244, 244, 244), border: new CColor(213, 213, 213), color: new CColor(54, 54, 54)
        }, { // kHeaderActive
          background: new CColor(193, 193, 193), border: new CColor(146, 146, 146), color: new CColor(54, 54, 54)
        }, { // kHeaderHighlighted
          background: new CColor(223, 223, 223), border: new CColor(175, 175, 175), color: new CColor(101, 106, 112)
        }, { // kHeaderSelected
          background: new CColor(170, 170, 170), border: new CColor(117, 119, 122), color: new CColor(54, 54, 54)
        }], cornerColor: new CColor(193, 193, 193)
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
98 99 100
    };
    this.cells = {
      defaultState: {
101 102
        background: new CColor(255, 255, 255), border: new CColor(212, 212, 212), color: new CColor(0, 0, 0)
      }, padding: -1, /*px horizontal padding*/
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
103 104 105
      paddingPlusBorder: -1
    };
    this.activeCellBorderColor = new CColor(126, 152, 63);
106
    this.activeCellBorderColor2 = new CColor(255, 255, 255, 1);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123

    // Цвет закрепленных областей
    this.frozenColor = new CColor(105, 119, 62, 1);

    // Число знаков для математической информации
    this.mathMaxDigCount = 9;

    var cnv = document.createElement("canvas");
    cnv.width = 2;
    cnv.height = 2;
    var ctx = cnv.getContext("2d");
    ctx.clearRect(0, 0, 2, 2);
    ctx.fillStyle = "#000";
    ctx.fillRect(0, 0, 1, 1);
    ctx.fillRect(1, 1, 1, 1);
    this.ptrnLineDotted1 = ctx.createPattern(cnv, "repeat");

Alexander.Trofimov's avatar
Alexander.Trofimov committed
124 125
    this.halfSelection = false;

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
126 127 128 129 130 131 132
    return this;
  }


  /**
   * Widget for displaying and editing Workbook object
   * -----------------------------------------------------------------------------
133
   * @param {AscCommonExcel.Workbook} model                        Workbook
134
   * @param {AscCommonExcel.asc_CEventsController} controller          Events controller
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
135 136 137 138 139 140 141 142 143 144 145 146 147
   * @param {HandlersList} handlers                  Events handlers for WorkbookView events
   * @param {Element} elem                          Container element
   * @param {Element} inputElem                      Input element for top line editor
   * @param {Object} Api
   * @param {CCollaborativeEditing} collaborativeEditing
   * @param {c_oAscFontRenderingModeType} fontRenderingMode
   *
   * @constructor
   * @memberOf Asc
   */
  function WorkbookView(model, controller, handlers, elem, inputElem, Api, collaborativeEditing, fontRenderingMode) {
    this.defaults = {
      scroll: {
148 149
        widthPx: 14, heightPx: 14
      }, worksheetView: new WorksheetViewSettings()
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
150 151 152
    };

    this.model = model;
153
    this.enableKeyEvents = true;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
154 155 156 157 158 159 160 161
    this.controller = controller;
    this.handlers = handlers;
    this.wsViewHandlers = null;
    this.element = elem;
    this.input = inputElem;
    this.Api = Api;
    this.collaborativeEditing = collaborativeEditing;
    this.lastSendInfoRange = null;
162
    this.oSelectionInfo = null;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
163 164 165 166 167 168 169 170 171 172 173 174 175 176
    this.canUpdateAfterShiftUp = false;	// Нужно ли обновлять информацию после отпускания Shift

    //----- declaration -----
    this.canvas = undefined;
    this.canvasOverlay = undefined;
    this.canvasGraphic = undefined;
    this.canvasGraphicOverlay = undefined;
    this.wsActive = -1;
    this.wsMustDraw = false; // Означает, что мы выставили активный, но не отрисовали его
    this.wsViews = [];
    this.cellEditor = undefined;
    this.fontRenderingMode = null;
    this.lockDraw = false;		// Lock отрисовки на некоторое время

177
    this.isCellEditMode = false;
178

Alexander.Trofimov's avatar
Alexander.Trofimov committed
179 180
    this.isShowComments = true;

Alexander.Trofimov's avatar
Alexander.Trofimov committed
181
    this.formulasList = [];		// Список всех формул
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
182 183 184
    this.lastFormulaPos = -1; 		// Последняя позиция формулы
    this.lastFormulaNameLength = '';		// Последний кусок формулы
    this.skipHelpSelector = false;	// Пока true - не показываем окно подсказки
Alexander.Trofimov's avatar
Alexander.Trofimov committed
185 186
    // Константы для подстановке формулы (что не нужно добавлять скобки)
    this.arrExcludeFormulas = [];
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
187 188 189 190 191 192 193 194 195 196

    this.lastFindOptions = null;	// Последний поиск (параметры)
    this.lastFindResults = {};		// Результаты поиска (для поиска по всей книге, чтобы перейти на другой лист)
    this.fReplaceCallback = null;	// Callback для замены текста

    // Фонт, который выставлен в DrawingContext, он должен быть один на все DrawingContext-ы
    this.m_oFont = new asc.FontProperties(this.model.getDefaultFont(), this.model.getDefaultSize());

    // Теперь у нас 2 FontManager-а на весь документ + 1 для автофигур (а не на каждом листе свой)
    this.fmgrGraphics = [];						// FontManager for draw (1 для обычного + 1 для поворотного текста)
197 198
    this.fmgrGraphics.push(new AscFonts.CFontManager({mode:"cell"}));	// Для обычного
    this.fmgrGraphics.push(new AscFonts.CFontManager({mode:"cell"}));	// Для поворотного
199
    this.fmgrGraphics.push(new AscFonts.CFontManager());	// Для автофигур
200
    this.fmgrGraphics.push(new AscFonts.CFontManager({mode:"cell"}));	// Для измерений
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
201 202 203 204 205 206 207 208 209 210 211 212 213

    this.fmgrGraphics[0].Initialize(true); // IE memory enable
    this.fmgrGraphics[1].Initialize(true); // IE memory enable
    this.fmgrGraphics[2].Initialize(true); // IE memory enable
    this.fmgrGraphics[3].Initialize(true); // IE memory enable

    this.buffers = {};
    this.drawingCtx = undefined;
    this.overlayCtx = undefined;
    this.drawingGraphicCtx = undefined;
    this.overlayGraphicCtx = undefined;
    this.stringRender = undefined;

214 215 216
    this.stateFormatPainter = c_oAscFormatPainterState.kOff;
    this.rangeFormatPainter = null;

217
    this.selectionDialogType = c_oAscSelectionDialogType.None;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
    this.copyActiveSheet = -1;

    // Комментарии для всего документа
    this.cellCommentator = null;

    // Флаг о подписке на эвенты о смене позиции документа (скролл) для меню
    this.isDocumentPlaceChangedEnabled = false;

    // Максимальная ширина числа из 0,1,2...,9, померенная в нормальном шрифте(дефалтовый для книги) в px(целое)
    // Ecma-376 Office Open XML Part 1, пункт 18.3.1.13
    this.maxDigitWidth = 0;
    this.defaultFont = new asc.FontProperties(this.model.getDefaultFont(), this.model.getDefaultSize());
    //-----------------------

    this.m_dScrollY = 0;
    this.m_dScrollX = 0;
    this.m_dScrollY_max = 1;
    this.m_dScrollX_max = 1;

    this.MobileTouchManager = null;

    this.defNameAllowCreate = true;

    this._init(fontRenderingMode);

    return this;
  }

  WorkbookView.prototype._init = function(fontRenderingMode) {
    var self = this;

    // Init font managers rendering
    // Изначально мы инициализируем c_oAscFontRenderingModeType.hintingAndSubpixeling
    this.setFontRenderingMode(fontRenderingMode, /*isInit*/true);

    // add style
    var _head = document.getElementsByTagName('head')[0];
    var style0 = document.createElement('style');
    style0.type = 'text/css';
    style0.innerHTML = ".block_elem { position:absolute;padding:0;margin:0; }";
    _head.appendChild(style0);

    // create canvas
    if (null != this.element) {
      this.element.innerHTML = '<div id="ws-canvas-outer">\
263 264
											<canvas id="ws-canvas"></canvas>\
											<canvas id="ws-canvas-overlay"></canvas>\
265 266
											<canvas id="ws-canvas-graphic"></canvas>\
											<canvas id="ws-canvas-graphic-overlay"></canvas>\
267
											<canvas id="id_target_cursor" class="block_elem" width="1" height="1"\
Oleg Korshul's avatar
.  
Oleg Korshul committed
268
												style="width:2px;height:13px;display:none;z-index:9;"></canvas>\
269 270
										</div>';

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
      this.canvas = document.getElementById("ws-canvas");
      this.canvasOverlay = document.getElementById("ws-canvas-overlay");
      this.canvasGraphic = document.getElementById("ws-canvas-graphic");
      this.canvasGraphicOverlay = document.getElementById("ws-canvas-graphic-overlay");
    }

    this.buffers.main = new asc.DrawingContext({
      canvas: this.canvas, units: 1/*pt*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont
    });
    this.buffers.overlay = new asc.DrawingContext({
      canvas: this.canvasOverlay, units: 1/*pt*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont
    });

    this.buffers.mainGraphic = new asc.DrawingContext({
      canvas: this.canvasGraphic, units: 1/*pt*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont
    });
    this.buffers.overlayGraphic = new asc.DrawingContext({
      canvas: this.canvasGraphicOverlay, units: 1/*pt*/, fmgrGraphics: this.fmgrGraphics, font: this.m_oFont
    });

    this.drawingCtx = this.buffers.main;
    this.overlayCtx = this.buffers.overlay;
    this.drawingGraphicCtx = this.buffers.mainGraphic;
    this.overlayGraphicCtx = this.buffers.overlayGraphic;

    // Обновляем размеры (чуть ниже, потому что должны быть проинициализированы ctx)
    this._canResize();

    // Shapes
    var canvasWidth = this.drawingGraphicCtx.canvas.width;
    var canvasHeight = this.drawingGraphicCtx.canvas.height;
302
    this.buffers.shapeCtx = new AscCommon.CGraphics();
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
303 304 305 306 307
    this.buffers.shapeCtx.init(this.drawingGraphicCtx.ctx, canvasWidth, canvasHeight, (canvasWidth * 25.4 / this.drawingGraphicCtx.ppiX), (canvasHeight * 25.4 / this.drawingGraphicCtx.ppiY));
    this.buffers.shapeCtx.m_oFontManager = this.fmgrGraphics[2];

    var overlayWidth = this.overlayGraphicCtx.canvas.width;
    var overlayHeight = this.overlayGraphicCtx.canvas.height;
308
    this.buffers.shapeOverlayCtx = new AscCommon.CGraphics();
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
309 310 311
    this.buffers.shapeOverlayCtx.init(this.overlayGraphicCtx.ctx, overlayWidth, overlayHeight, (overlayWidth * 25.4 / this.overlayGraphicCtx.ppiX), (overlayHeight * 25.4 / this.overlayGraphicCtx.ppiY));
    this.buffers.shapeOverlayCtx.m_oFontManager = this.fmgrGraphics[2];

312
    this.stringRender = new AscCommonExcel.StringRender(this.buffers.main);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
313 314 315 316 317
    this.stringRender.setDefaultFont(this.defaultFont);

    // Мерить нужно только со 100% и один раз для всего документа
    this._calcMaxDigitWidth();

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
	  if (!window["NATIVE_EDITOR_ENJINE"]) {
		  // initialize events controller
		  this.controller.init(this, this.element, /*this.canvasOverlay*/ this.canvasGraphicOverlay, /*handlers*/{
			  "resize": function () {
				  self.resize.apply(self, arguments);
			  }, "reinitializeScroll": function () {
				  self._onScrollReinitialize.apply(self, arguments);
			  }, "scrollY": function () {
				  self._onScrollY.apply(self, arguments);
			  }, "scrollX": function () {
				  self._onScrollX.apply(self, arguments);
			  }, "changeSelection": function () {
				  self._onChangeSelection.apply(self, arguments);
			  }, "changeSelectionDone": function () {
				  self._onChangeSelectionDone.apply(self, arguments);
			  }, "changeSelectionRightClick": function () {
				  self._onChangeSelectionRightClick.apply(self, arguments);
			  }, "selectionActivePointChanged": function () {
				  self._onSelectionActivePointChanged.apply(self, arguments);
			  }, "updateWorksheet": function () {
				  self._onUpdateWorksheet.apply(self, arguments);
			  }, "resizeElement": function () {
				  self._onResizeElement.apply(self, arguments);
			  }, "resizeElementDone": function () {
				  self._onResizeElementDone.apply(self, arguments);
			  }, "changeFillHandle": function () {
				  self._onChangeFillHandle.apply(self, arguments);
			  }, "changeFillHandleDone": function () {
				  self._onChangeFillHandleDone.apply(self, arguments);
			  }, "moveRangeHandle": function () {
				  self._onMoveRangeHandle.apply(self, arguments);
			  }, "moveRangeHandleDone": function () {
				  self._onMoveRangeHandleDone.apply(self, arguments);
			  }, "moveResizeRangeHandle": function () {
				  self._onMoveResizeRangeHandle.apply(self, arguments);
			  }, "moveResizeRangeHandleDone": function () {
				  self._onMoveResizeRangeHandleDone.apply(self, arguments);
			  }, "editCell": function () {
				  self._onEditCell.apply(self, arguments);
			  }, "stopCellEditing": function () {
				  return self._onStopCellEditing.apply(self, arguments);
			  }, "getCellEditMode": function () {
				  return self.isCellEditMode;
			  }, "empty": function () {
				  self._onEmpty.apply(self, arguments);
			  }, "canEnterCellRange": function () {
				  self.cellEditor.setFocus(false);
				  var ret = self.cellEditor.canEnterCellRange();
				  ret ? self.cellEditor.activateCellRange() : true;
				  return ret;
			  }, "enterCellRange": function () {
				  self.lockDraw = true;
				  self.cellEditor.setFocus(false);
				  self.getWorksheet().enterCellRange(self.cellEditor);
				  self.lockDraw = false;
			  }, "undo": function () {
				  self.undo.apply(self, arguments);
			  }, "redo": function () {
				  self.redo.apply(self, arguments);
			  }, "addColumn": function () {
				  self._onAddColumn.apply(self, arguments);
			  }, "addRow": function () {
				  self._onAddRow.apply(self, arguments);
			  }, "mouseDblClick": function () {
				  self._onMouseDblClick.apply(self, arguments);
			  }, "showNextPrevWorksheet": function () {
				  self._onShowNextPrevWorksheet.apply(self, arguments);
			  }, "setFontAttributes": function () {
				  self._onSetFontAttributes.apply(self, arguments);
			  }, "setCellFormat": function () {
				  self._onSetCellFormat.apply(self, arguments);
			  }, "selectColumnsByRange": function () {
				  self._onSelectColumnsByRange.apply(self, arguments);
			  }, "selectRowsByRange": function () {
				  self._onSelectRowsByRange.apply(self, arguments);
			  }, "save": function () {
				  self.Api.asc_Save();
			  }, "showCellEditorCursor": function () {
				  self._onShowCellEditorCursor.apply(self, arguments);
			  }, "print": function () {
				  self.Api.onPrint();
			  }, "addFunction": function () {
				  self.insertFormulaInEditor.apply(self, arguments);
			  }, "canvasClick": function () {
				  self.enableKeyEventsHandler(true);
			  }, "autoFiltersClick": function () {
				  self._onAutoFiltersClick.apply(self, arguments);
			  }, "commentCellClick": function () {
				  self._onCommentCellClick.apply(self, arguments);
			  }, "isGlobalLockEditCell": function () {
				  return self.collaborativeEditing.getGlobalLockEditCell();
			  }, "updateSelectionName": function () {
				  self._onUpdateSelectionName.apply(self, arguments);
			  }, "stopFormatPainter": function () {
				  self._onStopFormatPainter.apply(self, arguments);
			  },

			  // Shapes
			  "graphicObjectMouseDown": function () {
				  self._onGraphicObjectMouseDown.apply(self, arguments);
			  }, "graphicObjectMouseMove": function () {
				  self._onGraphicObjectMouseMove.apply(self, arguments);
			  }, "graphicObjectMouseUp": function () {
				  self._onGraphicObjectMouseUp.apply(self, arguments);
			  }, "graphicObjectMouseUpEx": function () {
				  self._onGraphicObjectMouseUpEx.apply(self, arguments);
			  }, "graphicObjectWindowKeyDown": function () {
				  return self._onGraphicObjectWindowKeyDown.apply(self, arguments);
			  }, "graphicObjectWindowKeyPress": function () {
				  return self._onGraphicObjectWindowKeyPress.apply(self, arguments);
			  }, "getGraphicsInfo": function () {
				  return self._onGetGraphicsInfo.apply(self, arguments);
			  }, "updateSelectionShape": function () {
				  return self._onUpdateSelectionShape.apply(self, arguments);
			  }, "canReceiveKeyPress": function () {
				  return self.getWorksheet().objectRender.controller.canReceiveKeyPress();
			  }, "stopAddShape": function () {
				  self.getWorksheet().objectRender.controller.checkEndAddShape();
			  },

			  // Frozen anchor
			  "moveFrozenAnchorHandle": function () {
				  self._onMoveFrozenAnchorHandle.apply(self, arguments);
			  }, "moveFrozenAnchorHandleDone": function () {
				  self._onMoveFrozenAnchorHandleDone.apply(self, arguments);
			  },

			  // AutoComplete
			  "showAutoComplete": function () {
				  self.showAutoComplete.apply(self, arguments);
			  }, "onContextMenu": function (event) {
				  self.handlers.trigger("asc_onContextMenu", event);
			  },

			  // FormatPainter
			  'isFormatPainter': function () {
				  return self.stateFormatPainter;
			  },

			  //calcAll
			  'calcAll': function (ctrlKey, altKey, shiftKey) {
				  if (ctrlKey && altKey && shiftKey) {
					  self.model.recalcWB(true);
				  } else if (shiftKey) {
					  var ws = self.model.getActiveWs();
					  self.model.recalcWB(false, ws.getId());
				  } else {
					  self.model.recalcWB(false);
				  }
467 468 469 470 471
			  },
			  
			  //special paste
			  "hideSpecialPasteOptions": function () {
				  self.handlers.trigger("hideSpecialPasteOptions");
472 473
			  }
		  });
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
474 475

      if (this.input && this.input.addEventListener) {
476
        this.input.addEventListener("focus", function () {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
477 478 479 480 481 482 483
          self.input.isFocused = true;
          if (self.controller.settings.isViewerMode) {
            return;
          }
          self._onStopFormatPainter();
          self.controller.setStrictClose(true);
          self.cellEditor.callTopLineMouseup = true;
484
          if (!self.getCellEditMode() && !self.controller.isFillHandleMode) {
485
            self._onEditCell(/*isFocus*/true);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
486 487
          }
        }, false);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
488

489
        this.input.addEventListener('keydown', function (event) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
490
          if (self.isCellEditMode) {
491 492 493 494
            self.handlers.trigger('asc_onInputKeyDown', event);
            if (!event.defaultPrevented) {
              self.cellEditor._onWindowKeyDown(event, true);
            }
Alexander.Trofimov's avatar
Alexander.Trofimov committed
495 496
          }
        }, false);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
497
      }
498 499 500 501

      this.Api.onKeyDown = function (event) {
        self.controller._onWindowKeyDown(event);
        if (self.isCellEditMode) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
502
          self.cellEditor._onWindowKeyDown(event, false);
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
        }
      };
      this.Api.onKeyPress = function (event) {
        self.controller._onWindowKeyPress(event);
        if (self.isCellEditMode) {
          self.cellEditor._onWindowKeyPress(event);
        }
      };
      this.Api.onKeyUp = function (event) {
        self.controller._onWindowKeyUp(event);
        if (self.isCellEditMode) {
          self.cellEditor._onWindowKeyUp(event);
        }
      };
      this.Api.Begin_CompositeInput = function () {
Sergey Luzyanin's avatar
Sergey Luzyanin committed
518 519 520 521 522 523 524 525
        var oWSView = self.getWorksheet();
        if(oWSView && oWSView.isSelectOnShape){
          if(oWSView.objectRender){
            oWSView.objectRender.Begin_CompositeInput();
          }
          return;
        }

526 527 528 529
        if (!self.isCellEditMode) {
          self._onEditCell(false, true, undefined, true, function () {
            self.cellEditor.Begin_CompositeInput();
          });
530 531
        } else {
          self.cellEditor.Begin_CompositeInput();
532 533 534
        }
      };
      this.Api.Replace_CompositeText = function (arrCharCodes) {
Sergey Luzyanin's avatar
Sergey Luzyanin committed
535 536 537 538 539 540 541
        var oWSView = self.getWorksheet();
        if(oWSView && oWSView.isSelectOnShape){
          if(oWSView.objectRender){
            oWSView.objectRender.Replace_CompositeText(arrCharCodes);
          }
          return;
        }
542 543 544 545 546
        if (self.isCellEditMode) {
          self.cellEditor.Replace_CompositeText(arrCharCodes);
        }
      };
      this.Api.End_CompositeInput = function () {
Sergey Luzyanin's avatar
Sergey Luzyanin committed
547 548 549 550 551 552 553
        var oWSView = self.getWorksheet();
        if(oWSView && oWSView.isSelectOnShape){
          if(oWSView.objectRender){
            oWSView.objectRender.End_CompositeInput();
          }
          return;
        }
554 555 556 557 558
        if (self.isCellEditMode) {
          self.cellEditor.End_CompositeInput();
        }
      };
      this.Api.Set_CursorPosInCompositeText = function (nPos) {
Sergey Luzyanin's avatar
Sergey Luzyanin committed
559 560 561 562 563 564 565
        var oWSView = self.getWorksheet();
        if(oWSView && oWSView.isSelectOnShape){
          if(oWSView.objectRender){
            oWSView.objectRender.Set_CursorPosInCompositeText(nPos);
          }
          return;
        }
566 567 568 569 570 571
        if (self.isCellEditMode) {
          self.cellEditor.Set_CursorPosInCompositeText(nPos);
        }
      };
      this.Api.Get_CursorPosInCompositeText = function () {
        var res = 0;
Sergey Luzyanin's avatar
Sergey Luzyanin committed
572 573 574 575 576 577 578
        var oWSView = self.getWorksheet();
        if(oWSView && oWSView.isSelectOnShape){
          if(oWSView.objectRender){
            res = oWSView.objectRender.Get_CursorPosInCompositeText();
          }
        }
        else if (self.isCellEditMode) {
579 580 581 582 583
          res = self.cellEditor.Get_CursorPosInCompositeText();
        }
        return res;
      };
      this.Api.Get_MaxCursorPosInCompositeText = function () {
Sergey Luzyanin's avatar
Sergey Luzyanin committed
584 585 586 587 588 589 590
        var res = 0; var oWSView = self.getWorksheet();
        if(oWSView && oWSView.isSelectOnShape){
          if(oWSView.objectRender){
            res = oWSView.objectRender.Get_CursorPosInCompositeText();
          }
        }
        else if (self.isCellEditMode) {
591 592 593
          res = self.cellEditor.Get_MaxCursorPosInCompositeText();
        }
        return res;
594 595 596
      };
      AscCommon.InitBrowserInputContext(this.Api, "id_target_cursor");
    }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
597

598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
	  this.cellEditor =
		  new AscCommonExcel.CellEditor(this.element, this.input, this.fmgrGraphics, this.m_oFont, /*handlers*/{
			  "closed": function () {
				  self._onCloseCellEditor.apply(self, arguments);
			  }, "updated": function () {
				  self.Api.checkLastWork();
				  self._onUpdateCellEditor.apply(self, arguments);
			  }, "gotFocus": function (hasFocus) {
				  self.controller.setFocus(!hasFocus);
			  }, "updateFormulaEditMod": function () {
				  self.controller.setFormulaEditMode.apply(self.controller, arguments);
				  var ws = self.getWorksheet();
				  if (ws) {
					  if (!self.lockDraw) {
						  ws.cleanSelection();
					  }
					  for (var i in self.wsViews) {
						  self.wsViews[i].cleanFormulaRanges();
					  }
617
//            ws.cleanFormulaRanges();
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
					  ws.setFormulaEditMode.apply(ws, arguments);
				  }
			  }, "updateEditorState": function (state) {
				  self.handlers.trigger("asc_onEditCell", state);
			  }, "isGlobalLockEditCell": function () {
				  return self.collaborativeEditing.getGlobalLockEditCell();
			  }, "updateFormulaEditModEnd": function () {
				  if (!self.lockDraw) {
					  self.getWorksheet().updateSelection();
				  }
			  }, "newRange": function (range, ws) {
				  if (!ws) {
					  self.getWorksheet().addFormulaRange(range);
				  } else {
					  self.getWorksheet(self.model.getWorksheetIndexByName(ws)).addFormulaRange(range);
				  }
			  }, "existedRange": function (range, ws) {
				  var editRangeSheet = ws ? self.model.getWorksheetIndexByName(ws) : self.copyActiveSheet;
				  if (-1 === editRangeSheet || editRangeSheet === self.wsActive) {
					  self.getWorksheet().activeFormulaRange(range);
				  } else {
					  self.getWorksheet(editRangeSheet).removeFormulaRange(range);
					  self.getWorksheet().addFormulaRange(range);
				  }
			  }, "updateUndoRedoChanged": function (bCanUndo, bCanRedo) {
				  self.handlers.trigger("asc_onCanUndoChanged", bCanUndo);
				  self.handlers.trigger("asc_onCanRedoChanged", bCanRedo);
			  }, "applyCloseEvent": function () {
				  self.controller._onWindowKeyDown.apply(self.controller, arguments);
			  }, "isViewerMode": function () {
				  return self.controller.settings.isViewerMode;
			  }, "getFormulaRanges": function () {
				  return self.cellFormulaEnterWSOpen ? self.cellFormulaEnterWSOpen.getFormulaRanges() :
					  self.getWorksheet().getFormulaRanges();
			  }, "getCellFormulaEnterWSOpen": function () {
				  return self.cellFormulaEnterWSOpen;
			  }, "getActiveWS": function () {
				  return self.getWorksheet().model;
			  }, "setStrictClose": function (val) {
				  self.controller.setStrictClose(val);
			  }, "updateEditorSelectionInfo": function (info) {
				  self.handlers.trigger("asc_onEditorSelectionChanged", info);
			  }, "onContextMenu": function (event) {
				  self.handlers.trigger("asc_onContextMenu", event);
			  }
		  }, /*settings*/{
			  font: this.defaultFont, padding: this.defaults.worksheetView.cells.padding
		  });

	  this.wsViewHandlers = new AscCommonExcel.asc_CHandlersList(/*handlers*/{
		  "getViewerMode": function () {
			  return self.controller.getViewerMode ? self.controller.getViewerMode() : true;
		  }, "reinitializeScroll": function () {
			  self.controller.reinitializeScroll(/*All*/);
		  }, "reinitializeScrollY": function () {
			  self.controller.reinitializeScroll(/*vertical*/1);
		  }, "reinitializeScrollX": function () {
			  self.controller.reinitializeScroll(/*horizontal*/2);
		  }, "selectionChanged": function () {
			  self._onWSSelectionChanged();
		  }, "selectionNameChanged": function () {
			  self._onSelectionNameChanged.apply(self, arguments);
		  }, "selectionMathInfoChanged": function () {
			  self._onSelectionMathInfoChanged.apply(self, arguments);
		  }, 'onFilterInfo': function (countFilter, countRecords) {
			  self.handlers.trigger("asc_onFilterInfo", countFilter, countRecords);
		  }, "onErrorEvent": function (errorId, level) {
			  self.handlers.trigger("asc_onError", errorId, level);
		  }, "slowOperation": function (isStart) {
			  (isStart ? self.Api.sync_StartAction : self.Api.sync_EndAction).call(self.Api,
				  c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.SlowOperation);
		  }, "setAutoFiltersDialog": function (arrVal) {
			  self.handlers.trigger("asc_onSetAFDialog", arrVal);
		  }, "selectionRangeChanged": function (val) {
			  self.handlers.trigger("asc_onSelectionRangeChanged", val);
		  }, "onRenameCellTextEnd": function (countFind, countReplace) {
			  self.handlers.trigger("asc_onRenameCellTextEnd", countFind, countReplace);
		  }, 'onStopFormatPainter': function () {
			  self._onStopFormatPainter();
		  }, 'getRangeFormatPainter': function () {
			  return self.rangeFormatPainter;
		  }, "onDocumentPlaceChanged": function () {
			  self._onDocumentPlaceChanged();
		  }, "updateSheetViewSettings": function () {
			  self.handlers.trigger("asc_onUpdateSheetViewSettings");
		  }, "onScroll": function (d) {
			  self.controller.scroll(d);
		  }, "getLockDefNameManagerStatus": function () {
			  return self.defNameAllowCreate;
		  }, 'isActive': function () {
			  return (-1 === self.copyActiveSheet || self.wsActive === self.copyActiveSheet);
		  }, "getCellEditMode": function () {
			  return self.isCellEditMode;
		  }, "drawMobileSelection": function (color) {
			  if (self.MobileTouchManager) {
				  var _canvas = self.getWorksheet().objectRender.getDrawingCanvas();
				  if (_canvas) {
					  self.MobileTouchManager.CheckSelect(_canvas.trackOverlay, color);
				  }
			  }
		  }, "showSpecialPasteOptions": function (val) {
			  self.handlers.trigger("asc_onShowSpecialPasteOptions", val);
			  if (!window['AscCommon'].g_clipboardBase.showSpecialPasteButton) {
				  window['AscCommon'].g_clipboardBase.showSpecialPasteButton = true;
			  }
		  }, 'checkLastWork': function () {
			  self.Api.checkLastWork();
		  }
	  });
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
727

Alexander.Trofimov's avatar
Alexander.Trofimov committed
728
    this.model.handlers.add("cleanCellCache", function(wsId, oRanges, bLockDraw, updateHeight) {
729
      var ws = self.getWorksheetById(wsId, true);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
730
      if (ws) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
731
        ws.updateRanges(oRanges, bLockDraw || wsId != self.getWorksheet(self.wsActive).model.getId(), updateHeight);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
      }
    });
    this.model.handlers.add("changeWorksheetUpdate", function(wsId, val) {
      var ws = self.getWorksheetById(wsId);
      if (ws) {
        ws.changeWorksheet("update", val);
      }
    });
    this.model.handlers.add("showWorksheet", function(wsId) {
      var wsModel = self.model.getWorksheetById(wsId), index;
      if (wsModel) {
        index = wsModel.getIndex();
        self.showWorksheet(index, false, true);
        self.handlers.trigger("asc_onActiveSheetChanged", index);
      }
    });
    this.model.handlers.add("setSelection", function() {
      self._onSetSelection.apply(self, arguments);
    });
    this.model.handlers.add("getSelectionState", function() {
      return self._onGetSelectionState.apply(self);
    });
    this.model.handlers.add("setSelectionState", function() {
      self._onSetSelectionState.apply(self, arguments);
    });
    this.model.handlers.add("reInit", function() {
      self.reInit.apply(self, arguments);
    });
    this.model.handlers.add("drawWS", function() {
      self.drawWS.apply(self, arguments);
    });
    this.model.handlers.add("showDrawingObjects", function() {
      self.onShowDrawingObjects.apply(self, arguments);
    });
    this.model.handlers.add("setCanUndo", function(bCanUndo) {
      self.handlers.trigger("asc_onCanUndoChanged", bCanUndo);
    });
    this.model.handlers.add("setCanRedo", function(bCanRedo) {
      self.handlers.trigger("asc_onCanRedoChanged", bCanRedo);
    });
    this.model.handlers.add("setDocumentModified", function(bIsModified) {
      self.Api.onUpdateDocumentModified(bIsModified);
    });
    this.model.handlers.add("replaceWorksheet", function(from, to) {
      self.replaceWorksheet(from, to);
    });
    this.model.handlers.add("removeWorksheet", function(nIndex) {
      self.removeWorksheet(nIndex);
    });
    this.model.handlers.add("spliceWorksheet", function() {
      self.spliceWorksheet.apply(self, arguments);
    });
    this.model.handlers.add("updateWorksheetByModel", function() {
      self.updateWorksheetByModel.apply(self, arguments);
    });
    this.model.handlers.add("undoRedoAddRemoveRowCols", function(sheetId, type, range, bUndo) {
      if (true === bUndo) {
789
        if (AscCH.historyitem_Worksheet_AddRows === type) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
790 791
          self.collaborativeEditing.removeRowsRange(sheetId, range.clone(true));
          self.collaborativeEditing.undoRows(sheetId, range.r2 - range.r1 + 1);
792
        } else if (AscCH.historyitem_Worksheet_RemoveRows === type) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
793 794
          self.collaborativeEditing.addRowsRange(sheetId, range.clone(true));
          self.collaborativeEditing.undoRows(sheetId, range.r2 - range.r1 + 1);
795
        } else if (AscCH.historyitem_Worksheet_AddCols === type) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
796 797
          self.collaborativeEditing.removeColsRange(sheetId, range.clone(true));
          self.collaborativeEditing.undoCols(sheetId, range.c2 - range.c1 + 1);
798
        } else if (AscCH.historyitem_Worksheet_RemoveCols === type) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
799 800 801 802
          self.collaborativeEditing.addColsRange(sheetId, range.clone(true));
          self.collaborativeEditing.undoCols(sheetId, range.c2 - range.c1 + 1);
        }
      } else {
803
        if (AscCH.historyitem_Worksheet_AddRows === type) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
804 805
          self.collaborativeEditing.addRowsRange(sheetId, range.clone(true));
          self.collaborativeEditing.addRows(sheetId, range.r1, range.r2 - range.r1 + 1);
806
        } else if (AscCH.historyitem_Worksheet_RemoveRows === type) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
807 808
          self.collaborativeEditing.removeRowsRange(sheetId, range.clone(true));
          self.collaborativeEditing.removeRows(sheetId, range.r1, range.r2 - range.r1 + 1);
809
        } else if (AscCH.historyitem_Worksheet_AddCols === type) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
810 811
          self.collaborativeEditing.addColsRange(sheetId, range.clone(true));
          self.collaborativeEditing.addCols(sheetId, range.c1, range.c2 - range.c1 + 1);
812
        } else if (AscCH.historyitem_Worksheet_RemoveCols === type) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
813 814 815 816 817 818 819 820 821 822
          self.collaborativeEditing.removeColsRange(sheetId, range.clone(true));
          self.collaborativeEditing.removeCols(sheetId, range.c1, range.c2 - range.c1 + 1);
        }
      }
    });
    this.model.handlers.add("undoRedoHideSheet", function(sheetId) {
      self.showWorksheet(sheetId);
      // Посылаем callback об изменении списка листов
      self.handlers.trigger("asc_onSheetsChanged");
    });
823

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
824
    this.handlers.add("asc_onLockDefNameManager", function(reason) {
825
      self.defNameAllowCreate = !(reason == Asc.c_oAscDefinedNameReason.LockDefNameManager);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
826
    });
Alexander.Trofimov's avatar
Alexander.Trofimov committed
827
    this.handlers.add('addComment', function (id, data) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
828 829 830
      self._onWSSelectionChanged();
      self.handlers.trigger('asc_onAddComment', id, data);
    });
Alexander.Trofimov's avatar
Alexander.Trofimov committed
831
    this.handlers.add('removeComment', function (id) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
832 833 834
      self._onWSSelectionChanged();
      self.handlers.trigger('asc_onRemoveComment', id);
    });
Alexander.Trofimov's avatar
Alexander.Trofimov committed
835 836 837
    this.handlers.add('hiddenComments', function () {
      return !self.isShowComments;
    });
838
	this.model.handlers.add("hideSpecialPasteOptions", function() {
839
      if(window['AscCommon'].g_clipboardBase.showSpecialPasteButton)
840 841
	  {
		self.handlers.trigger("asc_onHideSpecialPasteOptions");
842
		window['AscCommon'].g_clipboardBase.showSpecialPasteButton = false;
843
	  }
844
    });
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
845

846
    this.cellCommentator = new AscCommonExcel.CCellCommentator({
Alexander.Trofimov's avatar
Alexander.Trofimov committed
847
      model: new WorkbookCommentsModel(this.handlers, this.model.aComments),
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
848 849 850 851 852 853 854 855 856
      collaborativeEditing: this.collaborativeEditing,
      draw: function() {
      },
      handlers: {
        trigger: function() {
          return true;
        }
      }
    });
857 858
    if (0 < this.model.aComments.length) {
      this.handlers.trigger("asc_onAddComments", this.model.aComments);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
    }

    this.initFormulasList();

    this.fReplaceCallback = function() {
      self._replaceCellTextCallback.apply(self, arguments);
    };

    return this;
  };

  WorkbookView.prototype.destroy = function() {
    this.controller.destroy();
    this.cellEditor.destroy();
    return this;
  };

  WorkbookView.prototype._createWorksheetView = function(wsModel) {
877
    return new AscCommonExcel.WorksheetView(wsModel, this.wsViewHandlers, this.buffers, this.stringRender, this.maxDigitWidth, this.collaborativeEditing, this.defaults.worksheetView);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
878
  };
879

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
880 881 882
  WorkbookView.prototype._onSelectionNameChanged = function(name) {
    this.handlers.trigger("asc_onSelectionNameChanged", name);
  };
883

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
884 885 886
  WorkbookView.prototype._onSelectionMathInfoChanged = function(info) {
    this.handlers.trigger("asc_onSelectionMathChanged", info);
  };
887

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
888 889
  // Проверяет, сменили ли мы диапазон (для того, чтобы не отправлять одинаковую информацию о диапазоне)
  WorkbookView.prototype._isEqualRange = function(range, isSelectOnShape) {
890
    if (null === this.lastSendInfoRange) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
891
      return false;
892 893
    }

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
894 895
    return this.lastSendInfoRange.isEqual(range) && this.lastSendInfoRangeIsSelectOnShape === isSelectOnShape;
  };
896

897
  WorkbookView.prototype._updateSelectionInfo = function () {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
898
    var ws = this.cellFormulaEnterWSOpen ? this.cellFormulaEnterWSOpen : this.getWorksheet();
899
    this.oSelectionInfo = ws.getSelectionInfo();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
900
    this.lastSendInfoRange = ws.model.selectionRange.clone();
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
901
    this.lastSendInfoRangeIsSelectOnShape = ws.getSelectionShape();
902
  };
903 904
  WorkbookView.prototype._onWSSelectionChanged = function() {
    this._updateSelectionInfo();
905

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
906
    // При редактировании ячейки не нужно пересылать изменения
907
    if (this.input && false === this.getCellEditMode() && c_oAscSelectionDialogType.None === this.selectionDialogType) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
908 909 910 911 912 913
      // Сами запретим заходить в строку формул, когда выделен shape
      if (this.lastSendInfoRangeIsSelectOnShape) {
        this.input.disabled = true;
        this.input.value = '';
      } else {
        this.input.disabled = false;
914
        this.input.value = this.oSelectionInfo.text;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
915 916
      }
    }
917
    this.handlers.trigger("asc_onSelectionChanged", this.oSelectionInfo);
918
    this.handlers.trigger("asc_onSelectionEnd");
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
919 920 921 922
  };


  WorkbookView.prototype._onScrollReinitialize = function(whichSB, callback) {
923 924 925
    var ws = this.getWorksheet(), vsize = !whichSB || whichSB === 1 ? ws.getVerticalScrollRange() : undefined, hsize = !whichSB || whichSB === 2 ? ws.getHorizontalScrollRange() : undefined;

    if (vsize != undefined) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
926
      this.m_dScrollY_max = Math.max(this.controller.settings.vscrollStep * (vsize + 1), 1);
927 928
    }
    if (hsize != undefined) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
929 930 931 932
      this.m_dScrollX_max = Math.max(this.controller.settings.hscrollStep * (hsize + 1), 1);
    }

    asc_applyFunction(callback, vsize, hsize);
Oleg Korshul's avatar
Oleg Korshul committed
933 934 935 936

	if (this.Api.isMobileVersion) {
	  this.MobileTouchManager.Resize();
	}
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
  };

  WorkbookView.prototype._onScrollY = function(pos) {
    var ws = this.getWorksheet();
    var delta = asc_round(pos - ws.getFirstVisibleRow(/*allowPane*/true));
    if (delta !== 0) {
      ws.scrollVertical(delta, this.cellEditor);
    }
  };

  WorkbookView.prototype._onScrollX = function(pos) {
    var ws = this.getWorksheet();
    var delta = asc_round(pos - ws.getFirstVisibleCol(/*allowPane*/true));
    if (delta !== 0) {
      ws.scrollHorizontal(delta, this.cellEditor);
    }
  };

  WorkbookView.prototype._onSetSelection = function(range, validRange) {
    var ws = this.getWorksheet();
    ws._checkSelectionShape();
958
    var d = ws.setSelection(range, validRange);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
959 960 961 962 963
    this.controller.scroll(d);
  };

  WorkbookView.prototype._onGetSelectionState = function() {
    var res = null;
964 965
    var ws = this.getWorksheet(null, true);
    if (ws && AscCommon.isRealObject(ws.objectRender) && AscCommon.isRealObject(ws.objectRender.controller)) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
      res = ws.objectRender.controller.getSelectionState();
    }
    return (res && res[0] && res[0].focus) ? res : null;
  };

  WorkbookView.prototype._onSetSelectionState = function(state) {
    if (null !== state) {
      var ws = this.getWorksheetById(state[0].worksheetId);
      if (ws && ws.objectRender && ws.objectRender.controller) {
        ws.objectRender.controller.setSelectionState(state);
        ws.setSelectionShape(true);
        var d = ws._calcActiveCellOffset(ws.objectRender.getSelectedDrawingsRange());
        this.controller.scroll(d);
        ws.objectRender.showDrawingObjectsEx(true);
        ws.objectRender.controller.updateOverlay();
        ws.objectRender.controller.updateSelectionState();
      }
      // Селектим после выставления состояния
    }
  };
986

Alexander.Trofimov's avatar
Alexander.Trofimov committed
987
  WorkbookView.prototype._onChangeSelection = function (isStartPoint, dc, dr, isCoord, isSelectMode, isCtrl, callback) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
988
    var ws = this.getWorksheet();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
989
    var d = isStartPoint ? ws.changeSelectionStartPoint(dc, dr, isCoord, isSelectMode, isCtrl) :
Alexander.Trofimov's avatar
Alexander.Trofimov committed
990
      ws.changeSelectionEndPoint(dc, dr, isCoord, isSelectMode);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
991 992 993 994 995 996 997 998 999
    if (!isCoord && !isStartPoint && !isSelectMode) {
      // Выделение с зажатым shift
      this.canUpdateAfterShiftUp = true;
    }
    asc_applyFunction(callback, d);
  };

  // Окончание выделения
  WorkbookView.prototype._onChangeSelectionDone = function(x, y) {
1000
    if (c_oAscSelectionDialogType.None !== this.selectionDialogType) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1001 1002 1003 1004 1005 1006
      return;
    }
    var ws = this.getWorksheet();
    ws.changeSelectionDone();
    this._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false));
    // Проверим, нужно ли отсылать информацию о ячейке
1007
    var ar = ws.model.selectionRange.getLast();
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1008
    var isSelectOnShape = ws.getSelectionShape();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1009
    if (!this._isEqualRange(ws.model.selectionRange, isSelectOnShape)) {
1010
      this._onWSSelectionChanged();
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1011 1012 1013 1014 1015 1016 1017 1018
      this._onSelectionMathInfoChanged(ws.getSelectionMathInfo());
    }

    // Нужно очистить поиск
    this._cleanFindResults();

    var ct = ws.getCursorTypeFromXY(x, y, this.controller.settings.isViewerMode);

1019
    if (c_oTargetType.Hyperlink === ct.target) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1020 1021
      // Проверим замерженность
      var isHyperlinkClick = false;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1022
      if (ar.isOneCell() || isSelectOnShape) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1023
        isHyperlinkClick = true;
1024
      } else {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1025
        var mergedRange = ws.model.getMergedByCell(ar.r1, ar.c1);
1026
        if (mergedRange && ar.isEqual(mergedRange)) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1027 1028
          isHyperlinkClick = true;
        }
1029
      }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1030 1031 1032
      if (isHyperlinkClick) {
        if (false === ct.hyperlink.hyperlinkModel.getVisited() && !isSelectOnShape) {
          ct.hyperlink.hyperlinkModel.setVisited(true);
1033
          if (ct.hyperlink.hyperlinkModel.Ref) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1034 1035 1036 1037
            ws.updateRange(ct.hyperlink.hyperlinkModel.Ref.getBBox0(), false, false);
          }
        }
        switch (ct.hyperlink.asc_getType()) {
1038
          case Asc.c_oAscHyperlinkType.WebLink:
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1039 1040
            this.handlers.trigger("asc_onHyperlinkClick", ct.hyperlink.asc_getHyperlinkUrl());
            break;
1041
          case Asc.c_oAscHyperlinkType.RangeLink:
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1042 1043 1044 1045
            // ToDo надо поправить отрисовку комментария для данной ячейки (с которой уходим)
            this.handlers.trigger("asc_onHideComment");
            this.Api._asc_setWorksheetRange(ct.hyperlink);
            break;
1046
        }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
      }
    }
  };

  // Обработка нажатия правой кнопки мыши
  WorkbookView.prototype._onChangeSelectionRightClick = function(dc, dr) {
    var ws = this.getWorksheet();
    ws.changeSelectionStartPointRightClick(dc, dr);
  };

  // Обработка движения в выделенной области
  WorkbookView.prototype._onSelectionActivePointChanged = function(dc, dr, callback) {
    var ws = this.getWorksheet();
    var d = ws.changeSelectionActivePoint(dc, dr);
    asc_applyFunction(callback, d);
  };

  WorkbookView.prototype._onUpdateWorksheet = function(canvasElem, x, y, ctrlKey, callback) {
    var ws = this.getWorksheet(), ct = undefined;
    var arrMouseMoveObjects = [];					// Теперь это массив из объектов, над которыми курсор

    //ToDo: включить определение target, если находимся в режиме редактирования ячейки.
1069
    if (this.getCellEditMode() && !this.controller.isFormulaEditMode) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1070 1071 1072 1073 1074 1075 1076 1077
      canvasElem.style.cursor = "";
    } else if (x === undefined && y === undefined) {
      ws.cleanHighlightedHeaders();
    } else {
      ct = ws.getCursorTypeFromXY(x, y, this.controller.settings.isViewerMode);

      // Отправление эвента об удалении всего листа (именно удалении, т.к. если просто залочен, то не рисуем рамку вокруг)
      if (undefined !== ct.userIdAllSheet) {
1078
        arrMouseMoveObjects.push(new asc_CMM({
1079
          type: c_oAscMouseMoveType.LockedObject,
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1080 1081
          x: AscCommon.AscBrowser.convertToRetinaValue(ct.lockAllPosLeft),
          y: AscCommon.AscBrowser.convertToRetinaValue(ct.lockAllPosTop),
1082
          userId: ct.userIdAllSheet,
1083
          lockedObjectType: Asc.c_oAscMouseMoveLockedObjectType.Sheet
1084
        }));
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1085 1086 1087
      } else {
        // Отправление эвента о залоченности свойств всего листа (только если не удален весь лист)
        if (undefined !== ct.userIdAllProps) {
1088
          arrMouseMoveObjects.push(new asc_CMM({
1089
            type: c_oAscMouseMoveType.LockedObject,
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1090 1091
            x: AscCommon.AscBrowser.convertToRetinaValue(ct.lockAllPosLeft),
            y: AscCommon.AscBrowser.convertToRetinaValue(ct.lockAllPosTop),
1092
            userId: ct.userIdAllProps,
1093
            lockedObjectType: Asc.c_oAscMouseMoveLockedObjectType.TableProperties
1094
          }));
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1095 1096 1097 1098
        }
      }
      // Отправление эвента о наведении на залоченный объект
      if (undefined !== ct.userId) {
1099
        arrMouseMoveObjects.push(new asc_CMM({
1100
          type: c_oAscMouseMoveType.LockedObject,
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1101 1102
          x: AscCommon.AscBrowser.convertToRetinaValue(ct.lockRangePosLeft),
          y: AscCommon.AscBrowser.convertToRetinaValue(ct.lockRangePosTop),
1103
          userId: ct.userId,
1104
          lockedObjectType: Asc.c_oAscMouseMoveLockedObjectType.Range
1105
        }));
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1106
      }
1107

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1108 1109
      // Проверяем комментарии ячейки
      if (undefined !== ct.commentIndexes) {
1110
        arrMouseMoveObjects.push(new asc_CMM({
1111
          type: c_oAscMouseMoveType.Comment,
1112 1113 1114 1115 1116
          x: ct.commentCoords.asc_getLeftPX(),
          reverseX: ct.commentCoords.asc_getReverseLeftPX(),
          y: ct.commentCoords.asc_getTopPX(),
          aCommentIndexes: ct.commentIndexes
        }));
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1117 1118
      }
      // Проверяем гиперссылку
1119
      if (ct.target === c_oTargetType.Hyperlink) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1120 1121 1122 1123 1124
        if (true === ctrlKey) {
          // Мы без нажатия на гиперлинк
        } else {
          ct.cursor = ct.cellCursor.cursor;
        }
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1125 1126 1127 1128 1129 1130
		  arrMouseMoveObjects.push(new asc_CMM({
			  type: c_oAscMouseMoveType.Hyperlink,
			  x: AscCommon.AscBrowser.convertToRetinaValue(x),
			  y: AscCommon.AscBrowser.convertToRetinaValue(y),
			  hyperlink: ct.hyperlink
		  }));
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1131 1132 1133 1134 1135 1136 1137
      }

      /* Проверяем, может мы на никаком объекте (такая схема оказалась приемлимой
       * для отдела разработки приложений)
       */
      if (0 === arrMouseMoveObjects.length) {
        // Отправляем эвент, что мы ни на какой области
1138
        arrMouseMoveObjects.push(new asc_CMM({type: c_oAscMouseMoveType.None}));
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1139 1140 1141 1142
      }
      // Отсылаем эвент с объектами
      this.handlers.trigger("asc_onMouseMove", arrMouseMoveObjects);

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1143
      if (ct.target === c_oTargetType.MoveRange && ctrlKey && ct.cursor === "move") {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1144 1145 1146 1147 1148 1149
        ct.cursor = "copy";
      }

      if (canvasElem.style.cursor !== ct.cursor) {
        canvasElem.style.cursor = ct.cursor;
      }
1150
      if (ct.target === c_oTargetType.ColumnHeader || ct.target === c_oTargetType.RowHeader) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
        ws.drawHighlightedHeaders(ct.col, ct.row);
      } else {
        ws.cleanHighlightedHeaders();
      }
    }
    asc_applyFunction(callback, ct);
  };

  WorkbookView.prototype._onResizeElement = function(target, x, y) {
    var arrMouseMoveObjects = [];
1161
    if (target.target === c_oTargetType.ColumnResize) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1162
      arrMouseMoveObjects.push(this.getWorksheet().drawColumnGuides(target.col, x, y, target.mouseX));
1163
    } else if (target.target === c_oTargetType.RowResize) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1164 1165 1166 1167 1168 1169 1170 1171
      arrMouseMoveObjects.push(this.getWorksheet().drawRowGuides(target.row, x, y, target.mouseY));
    }

    /* Проверяем, может мы на никаком объекте (такая схема оказалась приемлимой
     * для отдела разработки приложений)
     */
    if (0 === arrMouseMoveObjects.length) {
      // Отправляем эвент, что мы ни на какой области
1172
      arrMouseMoveObjects.push(new asc_CMM({type: c_oAscMouseMoveType.None}));
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1173 1174 1175 1176 1177 1178 1179 1180
    }
    // Отсылаем эвент с объектами
    this.handlers.trigger("asc_onMouseMove", arrMouseMoveObjects);
  };

  WorkbookView.prototype._onResizeElementDone = function(target, x, y, isResizeModeMove) {
    var ws = this.getWorksheet();
    if (isResizeModeMove) {
1181
      if (ws.objectRender) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1182 1183
        ws.objectRender.saveSizeDrawingObjects();
      }
1184
      if (target.target === c_oTargetType.ColumnResize) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1185
        ws.changeColumnWidth(target.col, x, target.mouseX);
1186
      } else if (target.target === c_oTargetType.RowResize) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1187 1188 1189 1190
        ws.changeRowHeight(target.row, y, target.mouseY);
      }

      ws.cellCommentator.updateCommentPosition();
1191
      ws.updateSpecialPasteOptionsPosition();
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1192 1193 1194 1195 1196
      this._onDocumentPlaceChanged();
    }
    ws.draw();

    // Отсылаем окончание смены размеров (в FF не срабатывало обычное движение)
1197
    this.handlers.trigger("asc_onMouseMove", [new asc_CMM({type: c_oAscMouseMoveType.None})]);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
  };

  // Обработка автозаполнения
  WorkbookView.prototype._onChangeFillHandle = function(x, y, callback) {
    var ws = this.getWorksheet();
    var d = ws.changeSelectionFillHandle(x, y);
    asc_applyFunction(callback, d);
  };

  // Обработка окончания автозаполнения
  WorkbookView.prototype._onChangeFillHandleDone = function(x, y, ctrlPress) {
    var ws = this.getWorksheet();
    ws.applyFillHandle(x, y, ctrlPress);
  };

  // Обработка перемещения диапазона
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1214
  WorkbookView.prototype._onMoveRangeHandle = function(x, y, callback) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1215
    var ws = this.getWorksheet();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1216
    var d = ws.changeSelectionMoveRangeHandle(x, y);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
    asc_applyFunction(callback, d);
  };

  // Обработка окончания перемещения диапазона
  WorkbookView.prototype._onMoveRangeHandleDone = function(ctrlKey) {
    var ws = this.getWorksheet();
    ws.applyMoveRangeHandle(ctrlKey);
  };

  WorkbookView.prototype._onMoveResizeRangeHandle = function(x, y, target, callback) {
    var ws = this.getWorksheet();
    var d = ws.changeSelectionMoveResizeRangeHandle(x, y, target, this.cellEditor);
    asc_applyFunction(callback, d);
  };

  WorkbookView.prototype._onMoveResizeRangeHandleDone = function(target) {
    var ws = this.getWorksheet();
    ws.applyMoveResizeRangeHandle(target);
  };

  // Frozen anchor
  WorkbookView.prototype._onMoveFrozenAnchorHandle = function(x, y, target) {
    var ws = this.getWorksheet();
    ws.drawFrozenGuides(x, y, target);
  };

  WorkbookView.prototype._onMoveFrozenAnchorHandleDone = function(x, y, target) {
    // Закрепляем область
    var ws = this.getWorksheet();
    ws.applyFrozenAnchor(x, y, target);
  };

1249
  WorkbookView.prototype.showAutoComplete = function() {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1250
    var ws = this.getWorksheet();
1251
    var arrValues = ws.getCellAutoCompleteValues(ws.model.selectionRange.activeCell);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1252 1253 1254 1255
    this.handlers.trigger('asc_onEntriesListMenu', arrValues);
  };

  WorkbookView.prototype._onAutoFiltersClick = function(idFilter) {
1256
    this.getWorksheet().af_setDialogProp(idFilter);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1257 1258 1259 1260 1261
  };

  WorkbookView.prototype._onCommentCellClick = function(x, y) {
    var ws = this.getWorksheet();
    var comments = ws.cellCommentator.getCommentsXY(x, y);
1262
    if (comments.length) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1263
      ws.cellCommentator.showComment(comments[0].asc_getId());
1264
    }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1265
  };
1266

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1267 1268 1269 1270 1271 1272 1273
  WorkbookView.prototype._onUpdateSelectionName = function() {
    if (this.canUpdateAfterShiftUp) {
      this.canUpdateAfterShiftUp = false;
      var ws = this.getWorksheet();
      this._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false));
    }
  };
1274

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1275
  WorkbookView.prototype._onStopFormatPainter = function() {
1276 1277
    if (this.stateFormatPainter) {
      this.formatPainter(c_oAscFormatPainterState.kOff);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
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
    }
  };

  // Shapes
  WorkbookView.prototype._onGraphicObjectMouseDown = function(e, x, y) {
    var ws = this.getWorksheet();
    ws.objectRender.graphicObjectMouseDown(e, x, y);
  };

  WorkbookView.prototype._onGraphicObjectMouseMove = function(e, x, y) {
    var ws = this.getWorksheet();
    ws.objectRender.graphicObjectMouseMove(e, x, y);
  };

  WorkbookView.prototype._onGraphicObjectMouseUp = function(e, x, y) {
    var ws = this.getWorksheet();
    ws.objectRender.graphicObjectMouseUp(e, x, y);
  };

  WorkbookView.prototype._onGraphicObjectMouseUpEx = function(e, x, y) {
    //var ws = this.getWorksheet();
    //ws.objectRender.coordsManager.calculateCell(x, y);
  };

  WorkbookView.prototype._onGraphicObjectWindowKeyDown = function(e) {
1303 1304
    var objectRender = this.getWorksheet().objectRender;
    return (0 < objectRender.getSelectedGraphicObjects().length) ? objectRender.graphicObjectKeyDown(e) : false;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1305 1306 1307
  };

  WorkbookView.prototype._onGraphicObjectWindowKeyPress = function(e) {
1308 1309
    var objectRender = this.getWorksheet().objectRender;
    return (0 < objectRender.getSelectedGraphicObjects().length) ? objectRender.graphicObjectKeyPress(e) : false;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
  };

  WorkbookView.prototype._onGetGraphicsInfo = function(x, y) {
    var ws = this.getWorksheet();
    return ws.objectRender.checkCursorDrawingObject(x, y);
  };

  WorkbookView.prototype._onUpdateSelectionShape = function(isSelectOnShape) {
    var ws = this.getWorksheet();
    return ws.setSelectionShape(isSelectOnShape);
  };

  // Double click
  WorkbookView.prototype._onMouseDblClick = function(x, y, isHideCursor, callback) {
    var ws = this.getWorksheet();
    var ct = ws.getCursorTypeFromXY(x, y, this.controller.settings.isViewerMode);

1327
    if (ct.target === c_oTargetType.ColumnResize || ct.target === c_oTargetType.RowResize) {
1328
      ct.target === c_oTargetType.ColumnResize ? ws.autoFitColumnWidth(ct.col, ct.col) : ws.autoFitRowHeight(ct.row, ct.row);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1329 1330
      asc_applyFunction(callback);
    } else {
1331
      if (ct.col >= 0 && ct.row >= 0) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1332
        this.controller.setStrictClose(!ws._isCellEmptyText(ct.col, ct.row));
1333 1334
      }

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1335
      // Для нажатия на колонку/строку/all/frozenMove обрабатывать dblClick не нужно
1336
      if (c_oTargetType.ColumnHeader === ct.target || c_oTargetType.RowHeader === ct.target || c_oTargetType.Corner === ct.target || c_oTargetType.FrozenAnchorH === ct.target || c_oTargetType.FrozenAnchorV === ct.target) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1337 1338 1339
        asc_applyFunction(callback);
        return;
      }
1340

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1341 1342 1343 1344
      if (ws.objectRender.checkCursorDrawingObject(x, y)) {
        asc_applyFunction(callback);
        return;
      }
1345

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1346
      // При dbl клике фокус выставляем в зависимости от наличия текста в ячейке
1347
      this._onEditCell(/*isFocus*/undefined, /*isClearCell*/undefined, /*isHideCursor*/isHideCursor, /*isQuickInput*/false);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1348 1349
    }
  };
1350

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1351
  WorkbookView.prototype._onEditCell = function(isFocus, isClearCell, isHideCursor, isQuickInput, callback) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1352
    var t = this;
1353

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1354
    // Проверка глобального лока
1355
    if (this.collaborativeEditing.getGlobalLock() || this.controller.isResizeMode) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1356
      return;
1357 1358
    }

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1359
    var ws = t.getWorksheet();
1360
    var activeCellRange = ws.getActiveCell(0, 0, false);
1361
    var selectionRange = ws.model.selectionRange.clone();
1362

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1363
    var editFunction = function() {
1364
      t.setCellEditMode(true);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1365
      ws.setCellEditMode(true);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1366
      ws.openCellEditor(t.cellEditor, /*fragments*/undefined, /*cursorPos*/undefined, isFocus, isClearCell,
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1367
        /*isHideCursor*/isHideCursor, /*isQuickInput*/isQuickInput, selectionRange);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1368
      t.input.disabled = false;
1369
      t.handlers.trigger("asc_onEditCell", c_oAscCellEditorState.editStart);
1370

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1371 1372 1373 1374 1375 1376 1377
      // Эвент на обновление состояния редактора
      t.cellEditor._updateEditorState();
      asc_applyFunction(callback, true);
    };

    var editLockCallback = function(res) {
      if (!res) {
1378
        t.setCellEditMode(false);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1379 1380 1381 1382 1383 1384 1385 1386 1387
        t.controller.setStrictClose(false);
        t.controller.setFormulaEditMode(false);
        ws.setCellEditMode(false);
        ws.setFormulaEditMode(false);
        t.input.disabled = true;

        // Выключаем lock для редактирования ячейки
        t.collaborativeEditing.onStopEditCell();
        t.cellEditor.close(false);
1388
        t._onWSSelectionChanged();
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1389 1390
      }
    };
1391

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1392 1393 1394 1395 1396 1397 1398
    // Стартуем редактировать ячейку
    this.collaborativeEditing.onStartEditCell();
    if (ws._isLockedCells(activeCellRange, /*subType*/null, editLockCallback)) {
      editFunction();
    }
  };

1399 1400
  WorkbookView.prototype._onStopCellEditing = function(cancel) {
    return this.cellEditor.close(!cancel);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1401 1402 1403
  };

  WorkbookView.prototype._onCloseCellEditor = function() {
1404
    this.setCellEditMode(false);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1405 1406
    this.controller.setStrictClose(false);
    this.controller.setFormulaEditMode(false);
1407
      var ws = this.getWorksheet(), isCellEditMode, index;
1408
	  isCellEditMode = ws.getCellEditMode();
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1409
      ws.setCellEditMode(false);
1410 1411

      if( this.cellFormulaEnterWSOpen ){
1412 1413 1414
		  index = this.cellFormulaEnterWSOpen.model.getIndex();
		  isCellEditMode = isCellEditMode ? isCellEditMode : this.cellFormulaEnterWSOpen.getCellEditMode();
		  this.cellFormulaEnterWSOpen.setCellEditMode(false);
1415
		  this.cellFormulaEnterWSOpen = null;
1416 1417 1418 1419
		  if( index != ws.model.getIndex() ){
			  this.showWorksheet(index);
			  this.handlers.trigger("asc_onActiveSheetChanged", index);
		  }
1420
		  ws = this.getWorksheet(index);
1421 1422
     }

1423
	  ws.cleanSelection();
1424 1425

	  for (var i in this.wsViews) {
1426
		  this.wsViews[i].setFormulaEditMode(false);
1427 1428 1429
		  this.wsViews[i].cleanFormulaRanges();
	  }

1430 1431
	  ws.updateSelectionWithSparklines();

1432
    if (isCellEditMode) {
1433
      this.handlers.trigger("asc_onEditCell", c_oAscCellEditorState.editEnd);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1434 1435 1436 1437
    }
    // Обновляем состояние Undo/Redo
    History._sendCanUndoRedo();
    // Обновляем состояние информации
1438
    this._onWSSelectionChanged();
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449

    // Закрываем подбор формулы
    if (-1 !== this.lastFormulaPos) {
      this.handlers.trigger('asc_onFormulaCompleteMenu', null);
      this.lastFormulaPos = -1;
      this.lastFormulaNameLength = 0;
    }

  };

  WorkbookView.prototype._onEmpty = function() {
1450
    this.getWorksheet().emptySelection(c_oAscCleanOptions.Text);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1451 1452
  };

1453 1454
  WorkbookView.prototype._onAddColumn = function() {
    var res = this.getWorksheet().expandColsOnScroll(true);
1455
    this.controller.reinitializeScroll(/*horizontal*/2, !res);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1456 1457
  };

1458 1459
  WorkbookView.prototype._onAddRow = function() {
    var res = this.getWorksheet().expandRowsOnScroll(true);
1460
    this.controller.reinitializeScroll(/*vertical*/1, !res);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1461 1462 1463 1464 1465 1466
  };

  WorkbookView.prototype._onShowNextPrevWorksheet = function(direction) {
    // Колличество листов
    var countWorksheets = this.model.getWorksheetCount();
    // Покажем следующий лист или предыдущий (если больше нет)
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1467 1468 1469 1470 1471 1472 1473 1474
    var i = this.wsActive + direction, ws;
    while (i !== this.wsActive) {
      if (0 > i) {
        i = countWorksheets - 1;
      } else  if (i >= countWorksheets) {
        i = 0;
      }

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1475
      ws = this.model.getWorksheet(i);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1476
      if (!ws.getHidden()) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1477 1478 1479 1480 1481
        this.showWorksheet(i);
        this.handlers.trigger("asc_onActiveSheetChanged", i);
        return true;
      }

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1482 1483
      i += direction;
    }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
    return false;
  };

  WorkbookView.prototype._onSetFontAttributes = function(prop) {
    var val;
    var selectionInfo = this.getWorksheet().getSelectionInfo().asc_getFont();
    switch (prop) {
      case "b":
        val = !(selectionInfo.asc_getBold());
        break;
      case "i":
        val = !(selectionInfo.asc_getItalic());
        break;
      case "u":
        // ToDo для двойного подчеркивания нужно будет немного переделать схему
        val = !(selectionInfo.asc_getUnderline());
        val = val ? Asc.EUnderline.underlineSingle : Asc.EUnderline.underlineNone;
        break;
      case "s":
        val = !(selectionInfo.asc_getStrikeout());
        break;
    }
    return this.setFontAttributes(prop, val);
  };

1509 1510 1511 1512 1513 1514 1515 1516
	WorkbookView.prototype._onSetCellFormat = function (prop) {
	  var info = new Asc.asc_CFormatCellsInfo();
	  info.asc_setSymbol(AscCommon.g_oDefaultCultureInfo.LCID);
	  info.asc_setType(Asc.c_oAscNumFormatType.None);
	  var formats = AscCommon.getFormatCells(info);
	  this.setCellFormat(formats[prop]);
	};

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
  WorkbookView.prototype._onSelectColumnsByRange = function() {
    this.getWorksheet()._selectColumnsByRange();
  };

  WorkbookView.prototype._onSelectRowsByRange = function() {
    this.getWorksheet()._selectRowsByRange();
  };

  WorkbookView.prototype._onShowCellEditorCursor = function() {
    var ws = this.getWorksheet();
    // Показываем курсор
1528
    if (ws.getCellEditMode()) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1529
      this.cellEditor.showCursor();
1530
    }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1531
  };
1532

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1533
  WorkbookView.prototype._onDocumentPlaceChanged = function() {
1534
    if (this.isDocumentPlaceChangedEnabled) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1535
      this.handlers.trigger("asc_onDocumentPlaceChanged");
1536
    }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1537
  };
1538

1539 1540
  WorkbookView.prototype.getTablePictures = function(props) {
      return this.af_getTablePictures(this.model, this.fmgrGraphics, this.m_oFont, props);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1541
  };
1542

1543 1544
  WorkbookView.prototype.getCellStyles = function(width, height) {
    var oStylesPainter = new asc_CSP(width, height);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1545 1546 1547
    oStylesPainter.generateStylesAll(this.model.CellStyles, this.fmgrGraphics, this.m_oFont, this.stringRender);
    return oStylesPainter;
  };
1548

1549
  WorkbookView.prototype.getWorksheetById = function(id, onlyExist) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1550
    var wsModel = this.model.getWorksheetById(id);
1551
    if (wsModel) {
1552
      return this.getWorksheet(wsModel.getIndex(), onlyExist);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1553 1554 1555 1556 1557 1558
    }
    return null;
  };

  /**
   * @param {Number} [index]
1559
   * @param {Boolean} [onlyExist]
1560
   * @return {AscCommonExcel.WorksheetView}
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1561
   */
1562
  WorkbookView.prototype.getWorksheet = function(index, onlyExist) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1563 1564 1565
    var wb = this.model;
    var i = asc_typeof(index) === "number" && index >= 0 ? index : wb.getActive();
    var ws = this.wsViews[i];
1566
    if (!ws && !onlyExist) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
      ws = this.wsViews[i] = this._createWorksheetView(wb.getWorksheet(i));
      ws._prepareComments();
      ws._prepareDrawingObjects();
    }
    return ws;
  };

  /**
   *
   * @param index
   * @param [isResized]
   * @param [bLockDraw]
   * @returns {WorkbookView}
   */
1581
  WorkbookView.prototype.showWorksheet = function (index, isResized, bLockDraw) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1582
    // ToDo disable method for assembly
1583 1584 1585 1586 1587
    if (index === this.wsActive) {
      return this;
    }

    var isSendInfo = (-1 === this.wsActive) || !isResized, tmpWorksheet, selectionRange = null;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1588 1589 1590 1591 1592
    // Только если есть активный
    if (-1 !== this.wsActive) {
      var ws = this.getWorksheet();
      // Останавливаем ввод данных в редакторе ввода. Если в режиме ввода формул, то продолжаем работать с cellEditor'ом, чтобы можно было
      // выбирать ячейки для формулы
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
      if (ws.getCellEditMode()) {
        if (this.cellEditor && this.cellEditor.formulaIsOperator()) {

          this.copyActiveSheet = this.wsActive;
          if (!this.cellFormulaEnterWSOpen) {
            this.cellFormulaEnterWSOpen = ws;
          } else {
            ws.setFormulaEditMode(false);
          }
        } else {
          if (!isResized) {
            this._onStopCellEditing();
          }
1606
        }
1607
      }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1608 1609 1610
      // Делаем очистку селекта
      ws.cleanSelection();
      this.stopTarget(ws);
1611

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1612 1613
    }

1614
    if (c_oAscSelectionDialogType.Chart === this.selectionDialogType) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1615 1616
      // Когда идет выбор диапазона, то должны на закрываемом листе отменить выбор диапазона
      tmpWorksheet = this.getWorksheet();
1617
      selectionRange = tmpWorksheet.model.selectionRange.getLast().clone(true);
1618
      tmpWorksheet.setSelectionDialogMode(c_oAscSelectionDialogType.None);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1619
    }
1620 1621 1622 1623
    if (this.stateFormatPainter) {
      // Должны отменить выбор на закрываемом листе
      this.getWorksheet().formatPainter(c_oAscFormatPainterState.kOff);
    }
1624

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1625 1626
    var wb = this.model;
    if (asc_typeof(index) === "number" && index >= 0) {
1627 1628 1629
      if (index !== wb.getActive()) {
        wb.setActive(index);
      }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1630 1631 1632 1633 1634
    } else {
      index = wb.getActive();
    }
    this.wsActive = index;
    this.wsMustDraw = bLockDraw;
1635

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1636 1637
    ws = this.getWorksheet(index);
    // Мы делали resize или меняли zoom, но не перерисовывали данный лист (он был не активный)
1638 1639 1640 1641 1642 1643 1644
    if (ws.updateResize && ws.updateZoom) {
      ws.changeZoomResize();
    } else if (ws.updateResize) {
      ws.resize(true);
    } else if (ws.updateZoom) {
      ws.changeZoom(true);
    }
1645

1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
    if (this.cellEditor && this.cellFormulaEnterWSOpen) {
      if (ws === this.cellFormulaEnterWSOpen) {
        this.cellFormulaEnterWSOpen.setFormulaEditMode(true);
        this.cellEditor._showCanvas();
      } else if (this.cellFormulaEnterWSOpen.getCellEditMode() && this.cellEditor.isFormula()) {
        this.cellFormulaEnterWSOpen.setFormulaEditMode(false);
        /*скрываем cellEditor, в редактор добавляем %selected sheet name%+"!" */
        this.cellEditor._hideCanvas();
        ws.cleanSelection();
        ws.setFormulaEditMode(true);
1656
      }
1657
    }
1658

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1659 1660
    if (!bLockDraw) {
      ws.draw();
1661 1662
    }

1663
    if (c_oAscSelectionDialogType.Chart === this.selectionDialogType) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1664 1665 1666 1667
      // Когда идет выбор диапазона, то на показываемом листе должны выставить нужный режим
      ws.setSelectionDialogMode(this.selectionDialogType, selectionRange);
      this.handlers.trigger("asc_onSelectionRangeChanged", ws.getSelectionRangeValue());
    }
1668 1669 1670 1671
    if (this.stateFormatPainter) {
      // Должны отменить выбор на закрываемом листе
      this.getWorksheet().formatPainter(this.stateFormatPainter);
    }
1672
    if (!bLockDraw) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1673 1674 1675
      ws.objectRender.controller.updateSelectionState();
      ws.objectRender.controller.updateOverlay();
    }
1676

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1677
    if (isSendInfo && !window["NATIVE_EDITOR_ENJINE"]) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1678
      this._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false));
1679
      this._onWSSelectionChanged();
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1680 1681 1682
      this._onSelectionMathInfoChanged(ws.getSelectionMathInfo());
    }
    this.controller.reinitializeScroll();
1683
    if (this.Api.isMobileVersion) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1684 1685 1686 1687 1688 1689
      this.MobileTouchManager.Resize();
    }
    // Zoom теперь на каждом листе одинаковый, не отправляем смену

    // Нужно очистить поиск
    this._cleanFindResults();
1690
	this.handlers.trigger("hideSpecialPasteOptions");
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
    return this;
  };

  /** @param nIndex {Number} массив индексов */
  WorkbookView.prototype.removeWorksheet = function(nIndex) {
    this.stopTarget(null);
    this.wsViews.splice(nIndex, 1);
    // Сбрасываем активный (чтобы не досчитывать после смены)
    this.wsActive = -1;
  };

  // Меняет местами 2 элемента просмотра
  WorkbookView.prototype.replaceWorksheet = function(indexFrom, indexTo) {
    // Только если есть активный
    if (-1 !== this.wsActive) {
      var ws = this.getWorksheet(this.wsActive);
      // Останавливаем ввод данных в редакторе ввода
1708
      if (ws.getCellEditMode()) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1709
        this._onStopCellEditing();
1710
      }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1711 1712
      // Делаем очистку селекта
      ws.cleanSelection();
1713

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1714 1715 1716 1717 1718 1719 1720 1721
      this.stopTarget(ws);
      this.wsActive = -1;
      // Чтобы поменять, нужно его добавить
      this.getWorksheet(indexTo);
    }
    var movedSheet = this.wsViews.splice(indexFrom, 1);
    this.wsViews.splice(indexTo, 0, movedSheet[0])
  };
1722

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1723
  WorkbookView.prototype.stopTarget = function(ws) {
1724
    if (null === ws && -1 !== this.wsActive) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1725
      ws = this.getWorksheet(this.wsActive);
1726 1727
    }
    if (null !== ws && ws.objectRender && ws.objectRender.drawingDocument) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1728
      ws.objectRender.drawingDocument.TargetEnd();
1729
    }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1730
  };
1731

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1732 1733 1734 1735 1736 1737
  // Копирует элемент перед другим элементом
  WorkbookView.prototype.copyWorksheet = function(index, insertBefore) {
    // Только если есть активный
    if (-1 !== this.wsActive) {
      var ws = this.getWorksheet();
      // Останавливаем ввод данных в редакторе ввода
1738
      if (ws.getCellEditMode()) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1739
        this._onStopCellEditing();
1740
      }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1741 1742
      // Делаем очистку селекта
      ws.cleanSelection();
1743

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1744 1745 1746
      this.stopTarget(ws);
      this.wsActive = -1;
    }
1747

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1748 1749 1750 1751 1752
    if (null != insertBefore && insertBefore >= 0 && insertBefore < this.wsViews.length) {
      // Помещаем нулевой элемент перед insertBefore
      this.wsViews.splice(insertBefore, 0, null);
    }
  };
1753

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1754 1755 1756
  WorkbookView.prototype.updateWorksheetByModel = function() {
    // ToDo Сделал небольшую заглушку с показом листа. Нужно как мне кажется перейти от wsViews на wsViewsId (хранить по id)
    var oldActiveWs;
1757
    if (-1 !== this.wsActive) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1758
      oldActiveWs = this.wsViews[this.wsActive];
1759 1760
    }

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1761 1762
    //расставляем ws так как они идут в модели.
    var oNewWsViews = [];
1763
    for (var i in this.wsViews) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1764
      var item = this.wsViews[i];
1765
      if (null != item && null != this.model.getWorksheetById(item.model.getId())) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1766 1767
        oNewWsViews[item.model.getIndex()] = item;
      }
1768
    }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1769 1770 1771 1772 1773 1774 1775 1776
    this.wsViews = oNewWsViews;
    var wsActive = this.model.getActive();

    var newActiveWs = this.wsViews[wsActive];
    if (undefined === newActiveWs || oldActiveWs !== newActiveWs) {
      // Если сменили, то покажем
      this.wsActive = -1;
      this.showWorksheet(undefined, false, true);
1777
    } else {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797
      this.wsActive = wsActive;
    }
  };

  WorkbookView.prototype.spliceWorksheet = function() {
    this.stopTarget(null);
    this.wsViews.splice.apply(this.wsViews, arguments);
    this.wsActive = -1;
  };

  WorkbookView.prototype._canResize = function() {
    var oldWidth = this.canvas.width;
    var oldHeight = this.canvas.height;
    var width = this.element.offsetWidth - (this.Api.isMobileVersion ? 0 : this.defaults.scroll.widthPx);
    var height = this.element.offsetHeight - (this.Api.isMobileVersion ? 0 : this.defaults.scroll.heightPx);
    var styleWidth, styleHeight, isRetina = AscBrowser.isRetina;

    if (isRetina) {
      styleWidth = width;
      styleHeight = height;
1798 1799
      width = AscCommon.AscBrowser.convertToRetinaValue(width, true);
      height = AscCommon.AscBrowser.convertToRetinaValue(height, true);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1800
    }
1801 1802

    if (oldWidth === width && oldHeight === height) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1803
      return false;
1804 1805 1806 1807
    }

    this.canvas.width = this.canvasOverlay.width = this.canvasGraphic.width = this.canvasGraphicOverlay.width = width;
    this.canvas.height = this.canvasOverlay.height = this.canvasGraphic.height = this.canvasGraphicOverlay.height = height;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1808
    if (isRetina) {
1809 1810
      this.canvas.style.width = this.canvasOverlay.style.width = this.canvasGraphic.style.width = this.canvasGraphicOverlay.style.width = styleWidth + 'px';
      this.canvas.style.height = this.canvasOverlay.style.height = this.canvasGraphic.style.height = this.canvasGraphicOverlay.style.height = styleHeight + 'px';
Oleg Korshul's avatar
Oleg Korshul committed
1811 1812 1813
    } else {
      this.canvas.style.width = this.canvasOverlay.style.width = this.canvasGraphic.style.width = this.canvasGraphicOverlay.style.width = width + 'px';
      this.canvas.style.height = this.canvasOverlay.style.height = this.canvasGraphic.style.height = this.canvasGraphicOverlay.style.height = height + 'px';
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
    }

    return true;
  };

  /** @param event {jQuery.Event} */
  WorkbookView.prototype.resize = function(event) {
    if (this._canResize()) {
      var item;
      var activeIndex = this.model.getActive();
      for (var i in this.wsViews) {
        item = this.wsViews[i];
        // Делаем resize (для не активных сменим как только сделаем его активным)
        item.resize(/*isDraw*/i == activeIndex);
      }
      this.showWorksheet(undefined, true);
    } else {
      // ToDo не должно происходить ничего, но нам приходит resize сверху, поэтому проверим отрисовывали ли мы
1832
      if (-1 === this.wsActive || this.wsMustDraw) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1833 1834 1835 1836 1837 1838
        this.showWorksheet(undefined, true);
      }
    }
    this.wsMustDraw = false;
  };

1839 1840 1841 1842 1843 1844 1845
  WorkbookView.prototype.getSelectionInfo = function () {
    if (!this.oSelectionInfo) {
      this._updateSelectionInfo();
    }
    return this.oSelectionInfo;
  };

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1846 1847
  // Получаем свойство: редактируем мы сейчас или нет
  WorkbookView.prototype.getCellEditMode = function() {
1848
	  return this.isCellEditMode;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1849 1850
  };

1851 1852 1853 1854
	WorkbookView.prototype.setCellEditMode = function(flag) {
		this.isCellEditMode = !!flag;
	};

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1855 1856 1857 1858 1859 1860 1861
  WorkbookView.prototype.getIsTrackShape = function() {
    var ws = this.getWorksheet();
    if (!ws) {
      return false;
    }
    if (ws.objectRender && ws.objectRender.controller) {
      return ws.objectRender.controller.checkTrackDrawings();
1862
    }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1863
  };
1864

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1865 1866 1867
  WorkbookView.prototype.getZoom = function() {
    return this.drawingCtx.getZoom();
  };
1868

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894
  WorkbookView.prototype.changeZoom = function(factor) {
    if (factor === this.getZoom()) {
      return;
    }

    this.buffers.main.changeZoom(factor);
    this.buffers.overlay.changeZoom(factor);
    this.buffers.mainGraphic.changeZoom(factor);
    this.buffers.overlayGraphic.changeZoom(factor);
    // Нужно сбросить кэш букв
    var i, length;
    for (i = 0, length = this.fmgrGraphics.length; i < length; ++i)
      this.fmgrGraphics[i].ClearFontsRasterCache();

    var item;
    var activeIndex = this.model.getActive();
    for (i in this.wsViews) {
      item = this.wsViews[i];
      // Меняем zoom (для не активных сменим как только сделаем его активным)
      item.changeZoom(/*isDraw*/i == activeIndex);
      item.objectRender.changeZoom(this.drawingCtx.scaleFactor);
      if (i == activeIndex) {
        item.draw();
        //ToDo item.drawDepCells();
      }
    }
1895

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1896 1897 1898
    this.controller.reinitializeScroll();
    this.handlers.trigger("asc_onZoomChanged", this.getZoom());
  };
1899

1900 1901 1902 1903 1904 1905 1906
  WorkbookView.prototype.getEnableKeyEventsHandler = function(bIsNaturalFocus) {
    var res = this.enableKeyEvents;
    if (res && bIsNaturalFocus && this.getCellEditMode() && this.input.isFocused) {
      res = false;
    }
    return res;
  };
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1907
  WorkbookView.prototype.enableKeyEventsHandler = function(f) {
1908 1909
    this.enableKeyEvents = !!f;
    this.controller.enableKeyEventsHandler(this.enableKeyEvents);
1910
    if (this.cellEditor) {
1911
      this.cellEditor.enableKeyEventsHandler(this.enableKeyEvents);
1912
    }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1913
  };
1914

Alexander.Trofimov's avatar
Alexander.Trofimov committed
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924
	// Останавливаем ввод данных в редакторе ввода
	WorkbookView.prototype.closeCellEditor = function (cancel) {
		var result = true;
		var ws = this.getWorksheet();
		// Останавливаем ввод данных в редакторе ввода
		if (ws.getCellEditMode()) {
			result = this._onStopCellEditing(cancel);
		}
		return result;
	};
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945

  WorkbookView.prototype.restoreFocus = function() {
    if (window["NATIVE_EDITOR_ENJINE"]) {
      return;
    }

    if (this.cellEditor.hasFocus) {
      this.cellEditor.restoreFocus();
    }
  };

  WorkbookView.prototype._onUpdateCellEditor = function(text, cursorPosition, isFormula, formulaPos, formulaName) {
    if (this.skipHelpSelector) {
      return;
    }
    // ToDo для ускорения можно завести объект, куда класть результаты поиска по формулам и второй раз не искать.
    var i, arrResult = [], defNamesList, defName;
    if (isFormula && formulaName) {
      formulaName = formulaName.toUpperCase();
      for (i = 0; i < this.formulasList.length; ++i) {
        if (0 === this.formulasList[i].indexOf(formulaName)) {
1946
          arrResult.push(new AscCommonExcel.asc_CCompleteMenu(this.formulasList[i], c_oAscPopUpSelectorType.Func));
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1947 1948
        }
      }
1949
      defNamesList = this.getDefinedNames(Asc.c_oAscGetDefinedNamesList.WorksheetWorkbook);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1950 1951 1952 1953
      formulaName = formulaName.toLowerCase();
      for (i = 0; i < defNamesList.length; ++i) {
        defName = defNamesList[i];
        if (0 === defName.Name.toLowerCase().indexOf(formulaName)) {
1954
          arrResult.push(new AscCommonExcel.asc_CCompleteMenu(defName.Name, !defName.isTable ? c_oAscPopUpSelectorType.Range : c_oAscPopUpSelectorType.Table));
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
        }
      }
    }
    if (0 < arrResult.length) {
      this.handlers.trigger('asc_onFormulaCompleteMenu', arrResult);

      this.lastFormulaPos = formulaPos;
      this.lastFormulaNameLength = formulaName.length;
    } else {
      this.handlers.trigger('asc_onFormulaCompleteMenu', null);

      this.lastFormulaPos = -1;
      this.lastFormulaNameLength = 0;
    }
  };

  // Вставка формулы в редактор
  WorkbookView.prototype.insertFormulaInEditor = function(name, type, autoComplete) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1973
    var t = this, ws = this.getWorksheet(), cursorPos, isNotFunction, tmp;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1974

1975
    if (c_oAscPopUpSelectorType.None === type) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1976 1977 1978 1979
      this.getWorksheet().setSelectionInfo("value", name, /*onlyActive*/true);
      return;
    }

1980
    isNotFunction = c_oAscPopUpSelectorType.Func !== type;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992

    // Проверяем, открыт ли редактор
    if (ws.getCellEditMode()) {
      if (isNotFunction) {
        this.skipHelpSelector = true;
      }
      if (-1 !== this.lastFormulaPos) {
        if (-1 === this.arrExcludeFormulas.indexOf(name) && !isNotFunction) {
          name += '('; // ToDo сделать проверки при добавлении, чтобы не вызывать постоянно окно
        } else {
          this.skipHelpSelector = true;
        }
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1993 1994
        tmp = this.cellEditor.skipTLUpdate;
        this.cellEditor.skipTLUpdate = false;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1995
        this.cellEditor.replaceText(this.lastFormulaPos, this.lastFormulaNameLength, name);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1996
        this.cellEditor.skipTLUpdate = tmp;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031
      } else if (false === this.cellEditor.insertFormula(name, isNotFunction)) {
        // Не смогли вставить формулу, закроем редактор, с сохранением текста
        this.cellEditor.close(true);
      }
      this.skipHelpSelector = false;
    } else {
      // Проверка глобального лока
      if (this.collaborativeEditing.getGlobalLock()) {
        return false;
      }

      // Редактор закрыт
      var cellRange = null;
      // Если нужно сделать автозаполнение формулы, то ищем ячейки)
      if (autoComplete) {
        cellRange = ws.autoCompleteFormula(name);
      }
      if (isNotFunction) {
        name = "=" + name;
      } else {
        if (cellRange) {
          if (cellRange.notEditCell) {
            // Мы уже ввели все что нужно, редактор открывать не нужно
            return;
          }
          // Меняем значение ячейки
          name = "=" + name + "(" + cellRange.text + ")";
        } else {
          // Меняем значение ячейки
          name = "=" + name + "()";
        }
        // Вычисляем позицию курсора (он должен быть в функции)
        cursorPos = name.length - 1;
      }

2032
      var selectionRange = ws.model.selectionRange.clone();
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2033 2034 2035 2036

      var openEditor = function(res) {
        if (res) {
          // Выставляем переменные, что мы редактируем
2037
          t.setCellEditMode(true);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2038 2039
          ws.setCellEditMode(true);

2040
          t.handlers.trigger("asc_onEditCell", c_oAscCellEditorState.editStart);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2041 2042 2043 2044
          if (isNotFunction) {
            t.skipHelpSelector = true;
          }
          // Открываем, с выставлением позиции курсора
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2045
          if (!ws.openCellEditorWithText(t.cellEditor, name, cursorPos, /*isFocus*/false, selectionRange)) {
2046
            t.handlers.trigger("asc_onEditCell", c_oAscCellEditorState.editEnd);
2047
            t.setCellEditMode(false);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2048 2049 2050 2051 2052 2053 2054 2055 2056
            t.controller.setStrictClose(false);
            t.controller.setFormulaEditMode(false);
            ws.setCellEditMode(false);
            ws.setFormulaEditMode(false);
          }
          if (isNotFunction) {
            t.skipHelpSelector = false;
          }
        } else {
2057
          t.setCellEditMode(false);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2058 2059 2060 2061 2062 2063 2064
          t.controller.setStrictClose(false);
          t.controller.setFormulaEditMode(false);
          ws.setCellEditMode(false);
          ws.setFormulaEditMode(false);
        }
      };

2065
      var activeCellRange = ws.getActiveCell(0, 0, false);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2066 2067 2068 2069 2070
      ws._isLockedCells(activeCellRange, /*subType*/null, openEditor);
    }
  };

  WorkbookView.prototype.bIsEmptyClipboard = function() {
2071
    return g_clipboardExcel.bIsEmptyClipboard(this.getCellEditMode());
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2072
  };
2073

2074
   WorkbookView.prototype.checkCopyToClipboard = function(_clipboard, _formats) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2075
    var t = this, ws;
2076
    ws = t.getWorksheet();
2077
    g_clipboardExcel.checkCopyToClipboard(ws, _clipboard, _formats);
2078
  };
2079

GoshaZotov's avatar
GoshaZotov committed
2080
  WorkbookView.prototype.pasteData = function(_format, data1, data2, text_data) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2081
    var t = this, ws;
2082
    ws = t.getWorksheet();
2083
    g_clipboardExcel.pasteData(ws, _format, data1, data2, text_data);
2084
  };
2085
  
2086
  WorkbookView.prototype.specialPasteData = function(props) {
2087
    if (!this.getCellEditMode()) {
2088
		this.getWorksheet().specialPaste(props);
2089 2090
	}
  };
2091

GoshaZotov's avatar
GoshaZotov committed
2092
  WorkbookView.prototype.selectionCut = function() {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2093 2094
    if (this.getCellEditMode()) {
      this.cellEditor.cutSelection();
GoshaZotov's avatar
GoshaZotov committed
2095
    } else {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2096
      this.getWorksheet().emptySelection(c_oAscCleanOptions.All);
GoshaZotov's avatar
GoshaZotov committed
2097 2098 2099
    }
  };

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2100
  WorkbookView.prototype.undo = function() {
2101 2102 2103
    var oFormulaLocaleInfo = AscCommonExcel.oFormulaLocaleInfo;
    oFormulaLocaleInfo.Parse = false;
    oFormulaLocaleInfo.DigitSep = false;
2104
    if (!this.getCellEditMode()) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2105 2106 2107 2108 2109 2110
      if (!History.Undo() && this.collaborativeEditing.getFast() && this.collaborativeEditing.getCollaborativeEditing()) {
        this.Api.sync_TryUndoInFastCollaborative();
      }
    } else {
      this.cellEditor.undo();
    }
2111 2112
    oFormulaLocaleInfo.Parse = true;
    oFormulaLocaleInfo.DigitSep = true;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2113 2114 2115
  };

  WorkbookView.prototype.redo = function() {
2116
    if (!this.getCellEditMode()) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2117 2118 2119 2120 2121 2122 2123
      History.Redo();
    } else {
      this.cellEditor.redo();
    }
  };

  WorkbookView.prototype.setFontAttributes = function(prop, val) {
2124
    if (!this.getCellEditMode()) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2125 2126 2127 2128 2129 2130 2131
      this.getWorksheet().setSelectionInfo(prop, val);
    } else {
      this.cellEditor.setTextStyle(prop, val);
    }
  };

  WorkbookView.prototype.changeFontSize = function(prop, val) {
2132
    if (!this.getCellEditMode()) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2133 2134 2135 2136 2137 2138
      this.getWorksheet().setSelectionInfo(prop, val);
    } else {
      this.cellEditor.setTextStyle(prop, val);
    }
  };

2139 2140 2141 2142
	WorkbookView.prototype.setCellFormat = function (format) {
		this.getWorksheet().setSelectionInfo("format", format);
	};

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2143
  WorkbookView.prototype.emptyCells = function(options) {
2144
    if (!this.getCellEditMode()) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2145 2146 2147 2148 2149 2150 2151 2152
      this.getWorksheet().emptySelection(options);
      this.restoreFocus();
    } else {
      this.cellEditor.empty(options);
    }
  };

  WorkbookView.prototype.setSelectionDialogMode = function(selectionDialogType, selectRange) {
2153
    if (selectionDialogType === this.selectionDialogType) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2154 2155 2156
      return;
    }

2157
    if (c_oAscSelectionDialogType.None === selectionDialogType) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169
      this.selectionDialogType = selectionDialogType;
      this.getWorksheet().setSelectionDialogMode(selectionDialogType, selectRange);
      if (this.copyActiveSheet !== this.wsActive) {
        this.showWorksheet(this.copyActiveSheet);
        // Посылаем эвент о смене активного листа
        this.handlers.trigger("asc_onActiveSheetChanged", this.copyActiveSheet);
      }
      this.copyActiveSheet = -1;
      this.input.disabled = false;
    } else {
      this.copyActiveSheet = this.wsActive;

2170
      var index, tmpSelectRange = AscCommon.parserHelp.parse3DRef(selectRange);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2171
      if (tmpSelectRange) {
2172
        if (c_oAscSelectionDialogType.Chart === selectionDialogType) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2173 2174
          // Получаем sheet по имени
          var ws = this.model.getWorksheetByName(tmpSelectRange.sheet);
2175
          if (!ws || ws.getHidden()) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2176
            tmpSelectRange = null;
2177
          } else {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2178 2179 2180 2181
            index = ws.getIndex();
            this.showWorksheet(index);
            // Посылаем эвент о смене активного листа
            this.handlers.trigger("asc_onActiveSheetChanged", index);
2182

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2183 2184
            tmpSelectRange = tmpSelectRange.range;
          }
2185 2186
        } else {
          tmpSelectRange = tmpSelectRange.range;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199
        }
      } else {
        // Это не 3D ссылка
        tmpSelectRange = selectRange;
      }

      this.getWorksheet().setSelectionDialogMode(selectionDialogType, tmpSelectRange);
      // Нужно выставить после, т.к. при смене листа не должны проставлять режим
      this.selectionDialogType = selectionDialogType;
      this.input.disabled = true;
    }
  };

2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212
  WorkbookView.prototype.formatPainter = function(stateFormatPainter) {
    // Если передали состояние, то выставляем его. Если нет - то меняем на противоположное.
    this.stateFormatPainter = (null != stateFormatPainter) ? stateFormatPainter : ((c_oAscFormatPainterState.kOff !== this.stateFormatPainter) ? c_oAscFormatPainterState.kOff : c_oAscFormatPainterState.kOn);

    this.rangeFormatPainter = this.getWorksheet().formatPainter(this.stateFormatPainter);
    if (this.stateFormatPainter) {
      this.copyActiveSheet = this.wsActive;
    } else {
      this.copyActiveSheet = -1;
      this.handlers.trigger('asc_onStopFormatPainter');
    }
  };

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2213 2214 2215 2216 2217 2218 2219 2220
  WorkbookView.prototype._cleanFindResults = function() {
    this.lastFindOptions = null;
    this.lastFindResults = {};
  };

  // Поиск текста в листе
  WorkbookView.prototype.findCellText = function(options) {
    // Для поиска эта переменная не нужна (но она может остаться от replace)
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2221
    options.activeCell = null;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2222 2223 2224

    var ws = this.getWorksheet();
    // Останавливаем ввод данных в редакторе ввода
2225
    if (ws.getCellEditMode()) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
      this._onStopCellEditing();
    }
    var result = ws.findCellText(options);
    if (false === options.scanOnOnlySheet) {
      // Поиск по всей книге
      var key = result ? (result.c1 + "-" + result.r1) : null;
      if (null === key || options.isEqual(this.lastFindOptions)) {
        if (null === key || this.lastFindResults[key]) {
          // Мы уже находили данную ячейку, попробуем на другом листе
          var i, active = this.model.getActive(), start = 0, end = this.model.getWorksheetCount();
          var inc = options.scanForward ? +1 : -1;
          var tmpWs, tmpResult = null;
          for (i = active + inc; i < end && i >= start; i += inc) {
            tmpWs = this.getWorksheet(i);
            tmpResult = tmpWs.findCellText(options);
2241
            if (tmpResult) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2242 2243
              break;
            }
2244
          }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2245 2246 2247
          if (!tmpResult) {
            // Мы дошли до конца или начала (в зависимости от направления, теперь пойдем до активного)
            if (options.scanForward) {
2248 2249
              i = 0;
              end = active;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2250 2251 2252 2253 2254 2255 2256 2257
            } else {
              i = end - 1;
              start = active + 1;
            }
            inc *= -1;
            for (; i < end && i >= start; i += inc) {
              tmpWs = this.getWorksheet(i);
              tmpResult = tmpWs.findCellText(options);
2258
              if (tmpResult) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2259 2260 2261
                break;
              }
            }
2262 2263
          }

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2264 2265 2266 2267 2268 2269 2270 2271
          if (tmpResult) {
            ws = tmpWs;
            result = tmpResult;
            this.showWorksheet(i);
            // Посылаем эвент о смене активного листа
            this.handlers.trigger("asc_onActiveSheetChanged", i);
            key = result.c1 + "-" + result.r1;
          }
2272

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2273 2274 2275 2276 2277 2278 2279
          this.lastFindResults = {};
        }
      }
      if (null !== key) {
        this.lastFindOptions = options.clone();
        this.lastFindResults[key] = true;
      }
2280
    }
2281

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2282
    if (result) {
2283
      return ws.setSelection(result);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2284 2285 2286 2287 2288 2289 2290 2291 2292
    }
    this._cleanFindResults();
    return null;
  };

  // Замена текста в листе
  WorkbookView.prototype.replaceCellText = function(options) {
    var ws = this.getWorksheet();
    // Останавливаем ввод данных в редакторе ввода
2293
    if (ws.getCellEditMode()) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2294
      this._onStopCellEditing();
2295 2296
    }

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2297 2298
    History.Create_NewPoint();
    History.StartTransaction();
2299

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2300 2301 2302 2303 2304
    options.clearFindAll();
    if (options.isReplaceAll) {
      // На ReplaceAll ставим медленную операцию
      this.Api.sync_StartAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.SlowOperation);
    }
2305

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2306 2307 2308
    ws.replaceCellText(options, false, this.fReplaceCallback);
  };
  WorkbookView.prototype._replaceCellTextCallback = function(options) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323
    if (!options.error) {
		options.updateFindAll();
		if (!options.scanOnOnlySheet && options.isReplaceAll) {
			// Замена на всей книге
			var i = ++options.sheetIndex;
			if (this.model.getActive() === i) {
				i = ++options.sheetIndex;
			}

			if (i < this.model.getWorksheetCount()) {
				var ws = this.getWorksheet(i);
				ws.replaceCellText(options, true, this.fReplaceCallback);
				return;
			}
		}
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2324

Alexander.Trofimov's avatar
Alexander.Trofimov committed
2325
		this.handlers.trigger("asc_onRenameCellTextEnd", options.countFindAll, options.countReplaceAll);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2326
    }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2327

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2328 2329 2330 2331 2332 2333
    History.EndTransaction();
    if (options.isReplaceAll) {
      // Заканчиваем медленную операцию
      this.Api.sync_EndAction(c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.SlowOperation);
    }
  };
2334

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2335 2336 2337
  WorkbookView.prototype.getDefinedNames = function(defNameListId) {
    return this.model.getDefinedNamesWB(defNameListId);
  };
2338

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2339 2340
  WorkbookView.prototype.setDefinedNames = function(defName) {
    //ToDo проверка defName.ref на знак "=" в начале ссылки. знака нет тогда это либо число либо строка, так делает Excel.
2341

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2342 2343
    this.model.setDefinesNames(defName.Name, defName.Ref, defName.Scope);
    this.handlers.trigger("asc_onDefName");
2344

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2345
  };
2346

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2347 2348
  WorkbookView.prototype.editDefinedNames = function(oldName, newName) {
    //ToDo проверка defName.ref на знак "=" в начале ссылки. знака нет тогда это либо число либо строка, так делает Excel.
2349
    if (this.collaborativeEditing.getGlobalLock()) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2350
      return;
2351 2352 2353 2354
    }

    var ws = this.getWorksheet(), t = this;

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2355 2356
    var editDefinedNamesCallback = function(res) {
      if (res) {
2357 2358 2359 2360 2361
        if (oldName && oldName.asc_getIsTable()) {
          ws.model.autoFilters.changeDisplayNameTable(oldName.asc_getName(), newName.asc_getName());
        } else {
          t.model.editDefinesNames(oldName, newName);
        }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2362
        t.handlers.trigger("asc_onEditDefName", oldName, newName);
2363 2364 2365 2366 2367
        //условие исключает второй вызов asc_onRefreshDefNameList(первый в unlockDefName)
        if(!(t.collaborativeEditing.getCollaborativeEditing() && t.collaborativeEditing.getFast()))
        {
          t.handlers.trigger("asc_onRefreshDefNameList");
        }
2368
      } else {
2369
        t.handlers.trigger("asc_onError", c_oAscError.ID.LockCreateDefName, c_oAscError.Level.NoCritical);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2370 2371 2372 2373 2374 2375
      }
      t._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false));
    };
    var defNameId;
    if (oldName) {
      defNameId = t.model.getDefinedName(oldName);
2376
      defNameId = defNameId ? defNameId.getNodeId() : null;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2377
    }
2378

2379 2380 2381
    var callback = function() {
      ws._isLockedDefNames(editDefinedNamesCallback, defNameId);
    };
2382

2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399
    var tableRange;
    if(oldName && true === oldName.isTable)
    {
      var table = ws.model.autoFilters._getFilterByDisplayName(oldName.Name);
      if(table)
      {
        tableRange = table.Ref;
      }
    }
    if(tableRange)
    {
      ws._isLockedCells( tableRange, null, callback );
    }
    else
    {
      callback();
    }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2400
  };
2401

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2402 2403
  WorkbookView.prototype.delDefinedNames = function(oldName) {
    //ToDo проверка defName.ref на знак "=" в начале ссылки. знака нет тогда это либо число либо строка, так делает Excel.
2404
    if (this.collaborativeEditing.getGlobalLock()) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2405
      return;
2406 2407 2408 2409
    }

    var ws = this.getWorksheet(), t = this

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2410
    if (oldName) {
2411

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2412 2413
      var delDefinedNamesCallback = function(res) {
        if (res) {
2414
          t.model.delDefinesNames(oldName);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2415
          t.handlers.trigger("asc_onRefreshDefNameList");
2416
        } else {
2417
          t.handlers.trigger("asc_onError", c_oAscError.ID.LockCreateDefName, c_oAscError.Level.NoCritical);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2418 2419 2420
        }
        t._onSelectionNameChanged(ws.getSelectionName(/*bRangeText*/false));
      };
2421
      var defNameId = t.model.getDefinedName(oldName).getNodeId();
2422

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2423
      ws._isLockedDefNames(delDefinedNamesCallback, defNameId);
2424

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2425 2426 2427 2428 2429 2430 2431 2432
    }

  };

  WorkbookView.prototype.getDefaultDefinedName = function() {
    //ToDo проверка defName.ref на знак "=" в начале ссылки. знака нет тогда это либо число либо строка, так делает Excel.

    var ws = this.getWorksheet();
2433 2434
    var oRangeValue = ws.getSelectionRangeValue();
    return new Asc.asc_CDefName("", oRangeValue.asc_getName(), null);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2435 2436 2437 2438 2439

  };
  WorkbookView.prototype.unlockDefName = function() {
    this.model.unlockDefName();
    this.handlers.trigger("asc_onRefreshDefNameList");
2440
    this.handlers.trigger("asc_onLockDefNameManager", Asc.c_oAscDefinedNameReason.OK);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2441 2442 2443 2444 2445 2446 2447
  };

  WorkbookView.prototype._onCheckDefNameLock = function() {
    return this.model.checkDefNameLock();
  };

  // Печать
2448
  WorkbookView.prototype.printSheets = function(pdf_writer, printPagesData) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2449
    var ws;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2450
    if (0 === printPagesData.arrPages.length) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466
      // Печать пустой страницы
      ws = this.getWorksheet();
      ws.drawForPrint(pdf_writer, null);
    } else {
      var indexWorksheet = -1;
      var indexWorksheetTmp = -1;
      for (var i = 0; i < printPagesData.arrPages.length; ++i) {
        indexWorksheetTmp = printPagesData.arrPages[i].indexWorksheet;
        if (indexWorksheetTmp !== indexWorksheet) {
          ws = this.getWorksheet(indexWorksheetTmp);
          indexWorksheet = indexWorksheetTmp;
        }
        ws.drawForPrint(pdf_writer, printPagesData.arrPages[i]);
      }
    }
  };
2467

2468
  WorkbookView.prototype.calcPagesPrint = function (adjustPrint) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2469 2470 2471 2472 2473
    var ws = null;
    var wb = this.model;
    var activeWs;
    var printPagesData = new asc_CPrintPagesData();
    var printType = adjustPrint.asc_getPrintType();
2474
    if (printType === Asc.c_oAscPrintType.ActiveSheets) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2475
      activeWs = wb.getActive();
2476
      ws = this.getWorksheet(activeWs);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2477
      ws.calcPagesPrint(wb.getWorksheet(activeWs).PagePrintOptions, false, activeWs, printPagesData.arrPages);
2478
    } else if (printType === Asc.c_oAscPrintType.EntireWorkbook) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2479 2480 2481 2482
      // Колличество листов
      var countWorksheets = this.model.getWorksheetCount();
      for (var i = 0; i < countWorksheets; ++i) {
        ws = this.getWorksheet(i);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2483
        ws.calcPagesPrint(wb.getWorksheet(i).PagePrintOptions, false, i, printPagesData.arrPages);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2484
      }
2485
    } else if (printType === Asc.c_oAscPrintType.Selection) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2486
      activeWs = wb.getActive();
2487
      ws = this.getWorksheet(activeWs);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2488
      ws.calcPagesPrint(wb.getWorksheet(activeWs).PagePrintOptions, true, activeWs, printPagesData.arrPages);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2489 2490
    }

Alexander.Trofimov's avatar
Alexander.Trofimov committed
2491 2492 2493
    if (AscCommonExcel.c_kMaxPrintPages === printPagesData.arrPages.length) {
      this.handlers.trigger("asc_onError", c_oAscError.ID.PrintMaxPagesCount, c_oAscError.Level.NoCritical);
    }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2494 2495 2496 2497 2498 2499 2500 2501
    return printPagesData;
  };

  // Вызывать только для нативной печати
  WorkbookView.prototype._nativeCalculate = function() {
    var item;
    for (var i in this.wsViews) {
      item = this.wsViews[i];
2502
      item._cleanCellsTextMetricsCache();
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2503 2504 2505 2506 2507
      item._prepareDrawingObjects();
    }
  };

  WorkbookView.prototype._initCommentsToSave = function() {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2508
    var isFirst = true, wsView, wsModel, tmpWs;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2509 2510 2511
    // Колличество листов
    var countWorksheets = this.model.getWorksheetCount();
    for (var i = 0; i < countWorksheets; ++i) {
2512
      tmpWs = this.model.getWorksheet(i);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2513
      if (tmpWs && (0 < tmpWs.aComments.length || isFirst)) {
2514 2515 2516
        wsView = this.getWorksheet(i);
        wsModel = wsView.model;
        wsModel.aCommentsCoords = wsView.cellCommentator.getCoordsToSave();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2517 2518 2519

        if (isFirst) {
          isFirst = false;
2520
          tmpWs = this.cellCommentator.worksheet;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2521 2522 2523
          this.cellCommentator.worksheet = wsView;
          this.cellCommentator.overlayCtx = wsView.overlayCtx;
          this.cellCommentator.drawingCtx = wsView.drawingCtx;
2524 2525
          this.model.aCommentsCoords = this.cellCommentator.getCoordsToSave();
          this.cellCommentator.worksheet = tmpWs;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2526
        }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2527 2528 2529 2530 2531 2532
      }
    }
  };

  WorkbookView.prototype.reInit = function() {
    var ws = this.getWorksheet();
2533
    ws._initCellsArea(AscCommonExcel.recalcType.full);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547
    ws._updateVisibleColsCount();
    ws._updateVisibleRowsCount();
  };
  WorkbookView.prototype.drawWS = function() {
    this.getWorksheet().draw();
  };
  WorkbookView.prototype.onShowDrawingObjects = function(clearCanvas) {
    var ws = this.getWorksheet();
    ws.objectRender.showDrawingObjects(clearCanvas);
  };

  WorkbookView.prototype.insertHyperlink = function(options) {
    var ws = this.getWorksheet();
    if (ws.objectRender.selectedGraphicObjectsExists()) {
2548
      if (ws.objectRender.controller.canAddHyperlink()) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2549 2550 2551 2552 2553 2554 2555 2556 2557
        ws.objectRender.controller.insertHyperlink(options);
      }
    } else {
      ws.setSelectionInfo("hyperlink", options);
      this.restoreFocus();
    }
  };
  WorkbookView.prototype.removeHyperlink = function() {
    var ws = this.getWorksheet();
2558
    if (ws.objectRender.selectedGraphicObjectsExists()) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2559
      ws.objectRender.controller.removeHyperlink();
2560
    } else {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2561 2562 2563 2564 2565 2566 2567 2568
      ws.setSelectionInfo("rh");
    }
  };

  WorkbookView.prototype.setDocumentPlaceChangedEnabled = function(val) {
    this.isDocumentPlaceChangedEnabled = val;
  };

Alexander.Trofimov's avatar
Alexander.Trofimov committed
2569 2570 2571 2572 2573 2574 2575
  WorkbookView.prototype.showComments = function (val) {
    if (this.isShowComments !== val) {
      this.isShowComments = val;
      this.drawWS();
    }
  };

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2576 2577 2578 2579 2580 2581 2582
  /*
   * @param {c_oAscRenderingModeType} mode Режим отрисовки
   * @param {Boolean} isInit инициализация или нет
   */
  WorkbookView.prototype.setFontRenderingMode = function(mode, isInit) {
    if (mode !== this.fontRenderingMode) {
      this.fontRenderingMode = mode;
2583
      if (c_oAscFontRenderingModeType.noHinting === mode) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2584
        this._setHintsProps(false, false);
2585
      } else if (c_oAscFontRenderingModeType.hinting === mode) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2586
        this._setHintsProps(true, false);
2587
      } else if (c_oAscFontRenderingModeType.hintingAndSubpixeling === mode) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2588 2589 2590 2591
        this._setHintsProps(true, true);
      }

      if (!isInit) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2592
        this.drawWS();
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2593 2594 2595 2596 2597 2598 2599
        this.cellEditor.setFontRenderingMode(mode);
      }
    }
  };

  WorkbookView.prototype.initFormulasList = function() {
    this.formulasList = [];
2600 2601
    var oFormulaList = AscCommonExcel.cFormulaFunctionLocalized ? AscCommonExcel.cFormulaFunctionLocalized :
      AscCommonExcel.cFormulaFunction;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2602
    for (var f in oFormulaList) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2603
      this.formulasList.push(f);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2604 2605
    }
    this.arrExcludeFormulas = [cBoolLocal["t"].toUpperCase(), cBoolLocal["f"].toUpperCase()];
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2606 2607 2608 2609 2610 2611 2612
  };

  WorkbookView.prototype._setHintsProps = function(bIsHinting, bIsSubpixHinting) {
    var manager, hintProps;
    for (var i = 0, length = this.fmgrGraphics.length; i < length; ++i) {
      manager = this.fmgrGraphics[i];
      hintProps = manager.m_oLibrary.tt_hint_props;
2613
      if (!hintProps) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2614
        continue;
2615 2616
      }

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2617 2618 2619 2620
      // Последний без хинтования (только для измерения)
      if (i === length - 1) {
        bIsHinting = bIsSubpixHinting = false;
      }
2621

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2622 2623 2624
      if (bIsHinting && bIsSubpixHinting) {
        hintProps.TT_USE_BYTECODE_INTERPRETER = true;
        hintProps.TT_CONFIG_OPTION_SUBPIXEL_HINTING = true;
2625

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2626 2627 2628 2629
        manager.LOAD_MODE = 40968;
      } else if (bIsHinting) {
        hintProps.TT_USE_BYTECODE_INTERPRETER = true;
        hintProps.TT_CONFIG_OPTION_SUBPIXEL_HINTING = false;
2630

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2631 2632 2633 2634
        manager.LOAD_MODE = 40968;
      } else {
        hintProps.TT_USE_BYTECODE_INTERPRETER = true;
        hintProps.TT_CONFIG_OPTION_SUBPIXEL_HINTING = false;
2635

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2636 2637
        manager.LOAD_MODE = 40970;
      }
2638

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2639 2640 2641
      manager.ClearFontsRasterCache();
    }
  };
2642

2643
  WorkbookView.prototype._calcMaxDigitWidth = function () {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2644 2645 2646
    // set default worksheet header font for calculations
    this.buffers.main.setFont(this.defaultFont);
    // Измеряем в pt
2647
    this.stringRender.measureString("0123456789", new AscCommonExcel.CellFlags());
2648

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2649 2650
    var ppiX = 96; // Мерить только с 96
    var ptConvToPx = asc_getcvt(1/*pt*/, 0/*px*/, ppiX);
2651

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2652 2653 2654
    // Максимальная ширина в Pt
    var maxWidthInPt = this.stringRender.getWidestCharWidth();
    // Переводим в px и приводим к целому (int)
2655
    this.model.maxDigitWidth = this.maxDigitWidth = asc_round(maxWidthInPt * ptConvToPx);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2656
    // Проверка для Calibri 11 должно быть this.maxDigitWidth = 7
2657 2658 2659 2660 2661

    if (!this.maxDigitWidth) {
      throw "Error: can't measure text string";
    }

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2662 2663
    // Padding рассчитывается исходя из maxDigitWidth (http://social.msdn.microsoft.com/Forums/en-US/9a6a9785-66ad-4b6b-bb9f-74429381bd72/margin-padding-in-cell-excel?forum=os_binaryfile)
    this.defaults.worksheetView.cells.padding = Math.max(asc.ceil(this.maxDigitWidth / 4), 2);
2664 2665 2666 2667 2668 2669 2670
    this.model.paddingPlusBorder = this.defaults.worksheetView.cells.paddingPlusBorder = 2 * this.defaults.worksheetView.cells.padding + 1;
  };

  WorkbookView.prototype.af_getTablePictures = function (wb, fmgrGraphics, oFont, props) {
    var styleThumbnailWidth = 61;
    var styleThumbnailHeight = 46;
    if (AscBrowser.isRetina) {
2671 2672
      styleThumbnailWidth = AscCommon.AscBrowser.convertToRetinaValue(styleThumbnailWidth, true);
      styleThumbnailHeight = AscCommon.AscBrowser.convertToRetinaValue(styleThumbnailHeight, true);
2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692
    }

    var canvas = document.createElement('canvas');
    canvas.width = styleThumbnailWidth;
    canvas.height = styleThumbnailHeight;
    var customStyles = wb.TableStyles.CustomStyles;
    var result = [];
    var options;
    var n = 0;
    if (customStyles) {
      for (var i in customStyles) {
        if (customStyles[i].table) {
          options = {
            name: i,
            displayName: customStyles[i].displayName,
            type: 'custom',
            image: this.af_getSmallIconTable(canvas, customStyles[i], fmgrGraphics, oFont, props)
          };
          result[n] = new AscCommonExcel.formatTablePictures(options);
          n++;
2693
        }
2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707
      }
    }
    var defaultStyles = wb.TableStyles.DefaultStyles;
    if (defaultStyles) {
      for (var i in defaultStyles) {
        if (defaultStyles[i].table) {
          options = {
            name: i,
            displayName: defaultStyles[i].displayName,
            type: 'default',
            image: this.af_getSmallIconTable(canvas, defaultStyles[i], fmgrGraphics, oFont, props)
          };
          result[n] = new AscCommonExcel.formatTablePictures(options);
          n++;
2708
        }
2709 2710 2711 2712
      }
    }
    return result;
  };
2713

2714
  WorkbookView.prototype.af_getSmallIconTable = function (canvas, style, fmgrGraphics, oFont, props) {
GoshaZotov's avatar
GoshaZotov committed
2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737
	var ctx = new Asc.DrawingContext({canvas: canvas, units: 1/*pt*/, fmgrGraphics: fmgrGraphics, font: oFont});

	//по умолчанию ставим строку заголовка и чередующиеся строки, позже нужно будет получать параметр
	var styleInfo;
	if (props) {
		styleInfo = {
			ShowColumnStripes: props.asc_getBandVer(),
			ShowFirstColumn: props.asc_getFirstCol(),
			ShowLastColumn: props.asc_getLastCol(),
			ShowRowStripes: props.asc_getBandHor(),
			HeaderRowCount: props.asc_getFirstRow(),
			TotalsRowCount: props.asc_getLastRow()
		};
	} else {
		styleInfo = {
			ShowColumnStripes: false,
			ShowFirstColumn: false,
			ShowLastColumn: false,
			ShowRowStripes: true,
			HeaderRowCount: true,
			TotalsRowCount: false
		};
	}
2738
	
GoshaZotov's avatar
GoshaZotov committed
2739
	var pxToMM = 72 / 96;
2740 2741
	var startX = 1 * pxToMM;
	var startY = 1 * pxToMM;
2742

GoshaZotov's avatar
GoshaZotov committed
2743 2744
	var ySize = 45 * pxToMM - 2 * startY;
	var xSize = 61 * pxToMM - 2 * startX;
2745
	
GoshaZotov's avatar
GoshaZotov committed
2746 2747 2748
	var stepY = (ySize) / 5;
	var stepX = (xSize) / 5;
	var lineStepX = (xSize - 1 * pxToMM) / 5;
2749
	
GoshaZotov's avatar
GoshaZotov committed
2750 2751 2752 2753 2754 2755 2756 2757 2758 2759
	var whiteColor = new CColor(255, 255, 255);
	var blackColor = new CColor(0, 0, 0);

	var defaultColor;
	if (!style || !style.wholeTable || !style.wholeTable.dxf.font) {
		defaultColor = blackColor;
	} else {
		defaultColor = style.wholeTable.dxf.font.getColor();
	}

2760 2761 2762 2763 2764 2765 2766
	var headerRowCount = 1;
	var totalsRowCount = 0;
	if(null != styleInfo.HeaderRowCount)
		headerRowCount = styleInfo.HeaderRowCount;
	if(null != styleInfo.TotalsRowCount)
		totalsRowCount = styleInfo.TotalsRowCount;
	
GoshaZotov's avatar
GoshaZotov committed
2767 2768 2769 2770
	ctx.setFillStyle(whiteColor);
	ctx.fillRect(0, 0, xSize + 2 * startX, ySize + 2 * startY);
	if (style.wholeTable && style.wholeTable.dxf.fill && null != style.wholeTable.dxf.fill.bg) {
		ctx.setFillStyle(style.wholeTable.dxf.fill.bg);
2771 2772 2773 2774 2775
		ctx.fillRect(startX, startY, xSize, ySize);
	}
	
	var calculateLineVer = function(color, x, y1, y2)
	{
2776 2777
		ctx.beginPath();
		ctx.setStrokeStyle(color);
2778 2779 2780

		ctx.lineVer(x + startX, y1 + startY, y2 + startY);

2781 2782
		ctx.stroke();
		ctx.closePath();
2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 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
	};
	
	var calculateLineHor = function(color, x1, y, x2)
	{
		ctx.beginPath();
		ctx.setStrokeStyle(color);

		ctx.lineHor(x1 + startX, y + startY, x2 + startX);

		ctx.stroke();
		ctx.closePath();
	};
	
	var calculateRect = function(color, x1, y1, w, h)
	{
		ctx.beginPath();
		ctx.setFillStyle(color);
		ctx.fillRect(x1 + startX, y1 + startY, w, h);
		ctx.closePath();
	};
	
	var bbox = {c1: 0, r1: 0, c2: 4, r2: 4};
	for (var i = 0; i < 5; i++) {
		for (var j = 0; j < 5; j++) {
			var color = null;
			var curStyle = style.getStyle(bbox, i, j, styleInfo, headerRowCount, totalsRowCount);
			
			//fill
			if(curStyle && curStyle.fill && curStyle.fill.bg)
			{
				color = curStyle.fill.bg;
				calculateRect(color, j * stepX, i * stepY, (j + 1) * stepX - j * stepX, (i + 1) * stepY - i * stepY);
			}
			
			//borders
			//left
			if(curStyle && curStyle.border && curStyle.border.l && curStyle.border.l.w !== 0)
			{
				color = curStyle.border.l.c;
GoshaZotov's avatar
GoshaZotov committed
2822
				calculateLineVer(color, j * lineStepX, i * stepY, (i + 1) * stepY);
2823 2824 2825 2826 2827
			}
			//right
			if(curStyle && curStyle.border && curStyle.border.r && curStyle.border.r.w !== 0)
			{
				color = curStyle.border.r.c;
GoshaZotov's avatar
GoshaZotov committed
2828
				calculateLineVer(color, (j + 1) * lineStepX, i * stepY, (i + 1) * stepY);
2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848
			}
			//top
			if(curStyle && curStyle.border && curStyle.border.t && curStyle.border.t.w !== 0)
			{
				color = curStyle.border.t.c;
				calculateLineHor(color, j * stepX, i * stepY, (j + 1) * stepX);
			}
			//bottom
			if(curStyle && curStyle.border && curStyle.border.b && curStyle.border.b.w !== 0)
			{
				color = curStyle.border.b.c;
				calculateLineHor(color, j * stepX, (i + 1) * stepY, (j + 1) * stepX);
			}
			
			//marks
			var color = defaultColor;
			if(curStyle && curStyle.font && curStyle.font.c)
			{
				color = curStyle.font.c;
			}
GoshaZotov's avatar
GoshaZotov committed
2849
			calculateLineHor(color, j * lineStepX + 3 * pxToMM, (i + 1) * stepY - stepY / 2, (j + 1) * lineStepX - 2 * pxToMM);
2850
		}
2851
	}
2852 2853 2854

    return canvas.toDataURL("image/png");
  };
2855

2856
	WorkbookView.prototype.IsSelectionUse = function () {
2857 2858
        return !this.getWorksheet().getSelectionShape();
    };
2859
	WorkbookView.prototype.GetSelectionRectsBounds = function () {
Oleg Korshul's avatar
.  
Oleg Korshul committed
2860 2861 2862
		if (this.getWorksheet().getSelectionShape())
		  return null;

2863
		var ws = this.getWorksheet();
2864 2865
		var range = ws.model.selectionRange.getLast();
		var type = range.type;
2866 2867
		var l = ws.getCellLeft(range.c1, 3);
		var t = ws.getCellTop(range.r1, 3);
Oleg Korshul's avatar
Oleg Korshul committed
2868 2869 2870 2871

		var _offX = ws.cellsLeft * asc_getcvt(1/*pt*/, 3/*mm*/, ws._getPPIX());
		var _offY = ws.cellsTop * asc_getcvt(1/*pt*/, 3/*mm*/, ws._getPPIY());

2872
		return {
2873 2874 2875
			X: asc.c_oAscSelectionType.RangeRow === type ? -_offX : l - _offX,
			Y: asc.c_oAscSelectionType.RangeCol === type ? -_offY : t - _offY,
			W: asc.c_oAscSelectionType.RangeRow === type ? _offX :
2876
				ws.getCellLeft(range.c2, 3) - l + ws.getColumnWidth(range.c2, 3),
2877
			H: asc.c_oAscSelectionType.RangeCol === type ? _offY :
2878 2879
				ws.getCellTop(range.r2, 3) - t + ws.getRowHeight(range.r2, 3),
			T: type
2880
		};
2881
	};
2882 2883 2884 2885 2886 2887 2888 2889
	WorkbookView.prototype.GetCaptionSize = function()
	{
		var ws = this.getWorksheet();
		return {
			W:  ws.cellsLeft * asc_getcvt(1/*pt*/, 3/*mm*/, ws._getPPIX()),
			H: ws.cellsTop * asc_getcvt(1/*pt*/, 3/*mm*/, ws._getPPIY())
		};
	};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2890 2891 2892
	WorkbookView.prototype.ConvertXYToLogic = function (x, y) {
	  return this.getWorksheet().ConvertXYToLogic(x, y);
	};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2893 2894 2895
	WorkbookView.prototype.ConvertLogicToXY = function (xL, yL) {
		return this.getWorksheet().ConvertLogicToXY(xL, yL);
	};
2896

2897 2898 2899
  //------------------------------------------------------------export---------------------------------------------------
  window['AscCommonExcel'] = window['AscCommonExcel'] || {};
  window["AscCommonExcel"].WorkbookView = WorkbookView;
2900
})(window);