Workbook.js 312 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
 *
 * 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
 *
 */

33 34
"use strict";

35 36
(function(window, undefined){

37
// Import
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
	var g_memory = AscFonts.g_memory;

	var CellValueType = AscCommon.CellValueType;
	var c_oAscBorderStyles = AscCommon.c_oAscBorderStyles;
	var fSortAscending = AscCommon.fSortAscending;
	var fSortDescending = AscCommon.fSortDescending;
	var parserHelp = AscCommon.parserHelp;
	var oNumFormatCache = AscCommon.oNumFormatCache;
	var gc_nMaxRow0 = AscCommon.gc_nMaxRow0;
	var gc_nMaxCol0 = AscCommon.gc_nMaxCol0;
	var g_oCellAddressUtils = AscCommon.g_oCellAddressUtils;
	var CellAddress = AscCommon.CellAddress;
	var isRealObject = AscCommon.isRealObject;
	var History = AscCommon.History;

	var UndoRedoItemSerializable = AscCommonExcel.UndoRedoItemSerializable;
	var UndoRedoData_CellSimpleData = AscCommonExcel.UndoRedoData_CellSimpleData;
	var UndoRedoData_CellValueData = AscCommonExcel.UndoRedoData_CellValueData;
	var UndoRedoData_FromToRowCol = AscCommonExcel.UndoRedoData_FromToRowCol;
	var UndoRedoData_FromTo = AscCommonExcel.UndoRedoData_FromTo;
	var UndoRedoData_IndexSimpleProp = AscCommonExcel.UndoRedoData_IndexSimpleProp;
	var UndoRedoData_BBox = AscCommonExcel.UndoRedoData_BBox;
	var UndoRedoData_SheetAdd = AscCommonExcel.UndoRedoData_SheetAdd;
	var UndoRedoData_DefinedNames = AscCommonExcel.UndoRedoData_DefinedNames;
	var g_oDefaultFormat = AscCommonExcel.g_oDefaultFormat;
	var Border = AscCommonExcel.Border;
	var RangeDataManagerElem = AscCommonExcel.RangeDataManagerElem;
	var RangeDataManager = AscCommonExcel.RangeDataManager;

	var cElementType = AscCommonExcel.cElementType;

	var parserFormula = AscCommonExcel.parserFormula;

	var c_oAscError = Asc.c_oAscError;
	var c_oAscInsertOptions = Asc.c_oAscInsertOptions;
	var c_oAscDeleteOptions = Asc.c_oAscDeleteOptions;
	var c_oAscGetDefinedNamesList = Asc.c_oAscGetDefinedNamesList;
	var c_oAscDefinedNameReason = Asc.c_oAscDefinedNameReason;

	var g_nVerticalTextAngle = 255;
	//определяется в WorksheetView.js
	var oDefaultMetrics = {
		ColWidthChars: 0,
		RowHeight: 0
	};
	var g_sNewSheetNamePattern = "Sheet";
	var g_nSheetNameMaxLength = 31;
	var g_nAllColIndex = -1;
	var g_nAllRowIndex = -1;
	var aStandartNumFormats = [];
	var aStandartNumFormatsId = {};
	var oFormulaLocaleInfo = {
		Parse: true,
		DigitSep: true
	};
93

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
	(function(){
		aStandartNumFormats[0] = "General";
		aStandartNumFormats[1] = "0";
		aStandartNumFormats[2] = "0.00";
		aStandartNumFormats[3] = "#,##0";
		aStandartNumFormats[4] = "#,##0.00";
		aStandartNumFormats[9] = "0%";
		aStandartNumFormats[10] = "0.00%";
		aStandartNumFormats[11] = "0.00E+00";
		aStandartNumFormats[12] = "# ?/?";
		aStandartNumFormats[13] = "# ??/??";
		aStandartNumFormats[14] = "m/d/yyyy";
		aStandartNumFormats[15] = "d-mmm-yy";
		aStandartNumFormats[16] = "d-mmm";
		aStandartNumFormats[17] = "mmm-yy";
		aStandartNumFormats[18] = "h:mm AM/PM";
		aStandartNumFormats[19] = "h:mm:ss AM/PM";
		aStandartNumFormats[20] = "h:mm";
		aStandartNumFormats[21] = "h:mm:ss";
		aStandartNumFormats[22] = "m/d/yyyy h:mm";
		aStandartNumFormats[37] = "#,##0_);(#,##0)";
		aStandartNumFormats[38] = "#,##0_);[Red](#,##0)";
		aStandartNumFormats[39] = "#,##0.00_);(#,##0.00)";
		aStandartNumFormats[40] = "#,##0.00_);[Red](#,##0.00)";
		aStandartNumFormats[45] = "mm:ss";
		aStandartNumFormats[46] = "[h]:mm:ss";
		aStandartNumFormats[47] = "mm:ss.0";
		aStandartNumFormats[48] = "##0.0E+0";
		aStandartNumFormats[49] = "@";
		for(var i in aStandartNumFormats)
		{
			aStandartNumFormatsId[aStandartNumFormats[i]] = i - 0;
		}
	})();

	var c_oRangeType =
		{
			Range:0,
			Col:1,
			Row:2,
			All:3
		};
	function getRangeType(oBBox){
		if(null == oBBox)
			oBBox = this.bbox;
		if(oBBox.c1 == 0 && gc_nMaxCol0 == oBBox.c2 && oBBox.r1 == 0 && gc_nMaxRow0 == oBBox.r2)
			return c_oRangeType.All;
		if(oBBox.c1 == 0 && gc_nMaxCol0 == oBBox.c2)
			return c_oRangeType.Row;
		else if(oBBox.r1 == 0 && gc_nMaxRow0 == oBBox.r2)
			return c_oRangeType.Col;
145
		else
146
			return c_oRangeType.Range;
147
	}
148

konovalovsergey's avatar
konovalovsergey committed
149
	function getDefNameIndex(name) {
150
		//uniqueness is checked without capitalization
151
		return name ? name.toLowerCase() : name;
152 153
	}

konovalovsergey's avatar
konovalovsergey committed
154 155 156 157 158 159
	function getDefNameId(sheetId, name) {
		if (sheetId) {
			return sheetId + AscCommon.g_cCharDelimiter + getDefNameIndex(name);
		} else {
			return getDefNameIndex(name);
		}
160
	}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
161

konovalovsergey's avatar
konovalovsergey committed
162
	var g_FDNI = {sheetId: null, name: null};
163

konovalovsergey's avatar
konovalovsergey committed
164
	function getFromDefNameId(nodeId) {
165
		var index = nodeId ? nodeId.indexOf(AscCommon.g_cCharDelimiter) : -1;
konovalovsergey's avatar
konovalovsergey committed
166 167 168 169 170 171
		if (-1 != index) {
			g_FDNI.sheetId = nodeId.substring(0, index);
			g_FDNI.name = nodeId.substring(index + 1);
		} else {
			g_FDNI.sheetId = null;
			g_FDNI.name = nodeId;
172
		}
konovalovsergey's avatar
konovalovsergey committed
173 174
	}

konovalovsergey's avatar
konovalovsergey committed
175
	function DefName(wb, name, ref, sheetId, hidden, isTable) {
konovalovsergey's avatar
konovalovsergey committed
176 177 178 179 180 181
		this.wb = wb;
		this.name = name;
		this.ref = ref;
		this.sheetId = sheetId;
		this.hidden = hidden;
		this.isTable = isTable;
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
182

183 184
		this.isLock = null;
		this.parsedRef = null;
185
	}
186

konovalovsergey's avatar
konovalovsergey committed
187
	DefName.prototype = {
188 189 190
		clone: function(wb){
			return new DefName(wb, this.name, this.ref, this.sheetId, this.hidden, this.isTable);
		},
konovalovsergey's avatar
konovalovsergey committed
191
		removeDependencies: function() {
192 193
			if (this.parsedRef) {
				this.parsedRef.removeDependencies();
konovalovsergey's avatar
konovalovsergey committed
194
				this.parsedRef = null;
195
			}
konovalovsergey's avatar
konovalovsergey committed
196
		},
197
		setRef: function(ref, opt_noRemoveDependencies, opt_forceBuild) {
konovalovsergey's avatar
konovalovsergey committed
198 199
			if(!opt_noRemoveDependencies){
				this.removeDependencies();
200
			}
konovalovsergey's avatar
konovalovsergey committed
201 202 203
			this.ref = ref;
			//all ref should be 3d, so worksheet can be anyone
			this.parsedRef = new parserFormula(ref, this, AscCommonExcel.g_DefNameWorksheet);
204
			this.parsedRef.setIsTable(this.isTable);
205 206 207 208 209 210
			if (opt_forceBuild) {
				this.parsedRef.parse();
				this.parsedRef.buildDependencies();
			} else {
				this.wb.dependencyFormulas.addToBuildDependencyDefName(this);
			}
211
		},
konovalovsergey's avatar
konovalovsergey committed
212 213 214 215 216 217 218 219 220 221 222
		getNodeId: function() {
			return getDefNameId(this.sheetId, this.name);
		},
		getAscCDefName: function() {
			var index = null;
			if (this.sheetId) {
				var sheet = this.wb.getWorksheetById(this.sheetId);
				index = sheet.getIndex();
			}
			return new Asc.asc_CDefName(this.name, this.ref, index, this.isTable, this.hidden, this.isLock);
		},
223 224 225 226 227 228 229 230 231 232
		getUndoDefName: function() {
			return new UndoRedoData_DefinedNames(this.name, this.ref, this.sheetId, this.isTable);
		},
		setUndoDefName: function(newUndoName) {
			this.name = newUndoName.name;
			this.sheetId = newUndoName.sheetId;
			this.hidden = false;
			this.isTable = newUndoName.isTable;
			if (this.ref != newUndoName.ref) {
				this.setRef(newUndoName.ref);
konovalovsergey's avatar
konovalovsergey committed
233 234 235 236 237 238 239 240 241
			}
		},
		onFormulaEvent: function(type, eventData) {
			if (AscCommon.c_oNotifyParentType.CanDo === type) {
				var type = eventData.notifyData.type;
				return !(this.isTable &&
				(AscCommon.c_oNotifyType.Shift === type || AscCommon.c_oNotifyType.Move === type ||
				AscCommon.c_oNotifyType.Delete === type));
			} else if (AscCommon.c_oNotifyParentType.Change === type) {
konovalovsergey's avatar
konovalovsergey committed
242 243
				this.wb.dependencyFormulas.addToChangedDefName(this);
			} else if (AscCommon.c_oNotifyParentType.ChangeFormula === type) {
244
				var oldUndoName = this.getUndoDefName();
245 246
				this.ref = this.parsedRef.Formula = eventData.assemble;
				this.wb.dependencyFormulas.addToChangedDefName(this);
247
				var newUndoName = this.getUndoDefName();
248
				History.Add(AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_DefinedNamesChangeUndo, null,
249
							null, new UndoRedoData_FromTo(oldUndoName, newUndoName), true);
250 251
			}
		}
konovalovsergey's avatar
konovalovsergey committed
252 253 254 255 256 257 258 259 260 261 262 263 264 265
	};

	function getCellIndex(row, col) {
		return row * AscCommon.gc_nMaxCol + col;
	}

	var g_FCI = {row: null, col: null};

	function getFromCellIndex(cellIndex) {
		g_FCI.row = Math.floor(cellIndex / AscCommon.gc_nMaxCol);
		g_FCI.col = cellIndex % AscCommon.gc_nMaxCol;
	}

	function getVertexIndex(bbox) {
266 267
		//without $
		return bbox.getAbsName2(false, false, false, false);
konovalovsergey's avatar
konovalovsergey committed
268 269
	}

konovalovsergey's avatar
konovalovsergey committed
270
	function DependencyGraph(wb) {
konovalovsergey's avatar
konovalovsergey committed
271 272 273 274
		this.wb = wb;
		//listening
		this.sheetListeners = {};
		this.volatileListeners = {};
konovalovsergey's avatar
konovalovsergey committed
275
		this.defNameListeners = {};
konovalovsergey's avatar
konovalovsergey committed
276 277
		this.tempGetByCells = [];
		//set dirty
konovalovsergey's avatar
konovalovsergey committed
278 279
		this.changedCell = null;
		this.changedDefName = null;
konovalovsergey's avatar
konovalovsergey committed
280 281 282 283 284 285 286 287 288 289 290
		this.buildCell = {};
		this.buildDefName = {};
		this.cleanCellCache = {};
		//lock
		this.lockCounter = 0;
		//defined name
		this.defNames = {wb: {}, sheet: {}};
		this.tableNamePattern = "Table";
		this.tableNameIndex = 0;
	}

konovalovsergey's avatar
konovalovsergey committed
291
	DependencyGraph.prototype = {
konovalovsergey's avatar
konovalovsergey committed
292 293 294 295 296 297
		//listening
		startListeningRange: function(sheetId, bbox, listener) {
			//todo bbox clone or bbox immutable
			var listenerId = listener.getListenerId();
			var sheetContainer = this.sheetListeners[sheetId];
			if (!sheetContainer) {
298
				sheetContainer = {cellMap: {}, areaMap: {}, areaTree: new RangeTree(), defName3d: {}};
konovalovsergey's avatar
konovalovsergey committed
299 300 301 302 303 304 305 306 307
				this.sheetListeners[sheetId] = sheetContainer;
			}
			if (bbox.isOneCell()) {
				var cellIndex = getCellIndex(bbox.r1, bbox.c1);
				var cellMapElem = sheetContainer.cellMap[cellIndex];
				if (!cellMapElem) {
					cellMapElem = {count: 0, listeners: {}};
					sheetContainer.cellMap[cellIndex] = cellMapElem;
				}
konovalovsergey's avatar
konovalovsergey committed
308
				if (!cellMapElem.listeners[listenerId]) {
konovalovsergey's avatar
konovalovsergey committed
309 310 311 312 313 314 315 316 317 318 319
					cellMapElem.listeners[listenerId] = listener;
					cellMapElem.count++;
				}
			} else {
				var vertexIndex = getVertexIndex(bbox);
				var areaSheetElem = sheetContainer.areaMap[vertexIndex];
				if (!areaSheetElem) {
					areaSheetElem = {id: null, bbox: bbox, count: 0, listeners: {}};
					sheetContainer.areaMap[vertexIndex] = areaSheetElem;
					sheetContainer.areaTree.add(bbox, areaSheetElem);
				}
konovalovsergey's avatar
konovalovsergey committed
320
				if (!areaSheetElem.listeners[listenerId]) {
konovalovsergey's avatar
konovalovsergey committed
321 322 323 324 325 326 327
					areaSheetElem.listeners[listenerId] = listener;
					areaSheetElem.count++;
				}
			}
		},
		endListeningRange: function(sheetId, bbox, listener) {
			var listenerId = listener.getListenerId();
328 329 330 331 332 333 334 335 336 337 338 339
			if (null != listenerId) {
				var sheetContainer = this.sheetListeners[sheetId];
				if (sheetContainer) {
					if (bbox.isOneCell()) {
						var cellIndex = getCellIndex(bbox.r1, bbox.c1);
						var cellMapElem = sheetContainer.cellMap[cellIndex];
						if (cellMapElem && cellMapElem.listeners[listenerId]) {
							delete cellMapElem.listeners[listenerId];
							cellMapElem.count--;
							if (cellMapElem.count <= 0) {
								delete sheetContainer.cellMap[cellIndex];
							}
konovalovsergey's avatar
konovalovsergey committed
340
						}
341 342 343 344 345 346 347 348 349 350
					} else {
						var vertexIndex = getVertexIndex(bbox);
						var areaSheetElem = sheetContainer.areaMap[vertexIndex];
						if (areaSheetElem && areaSheetElem.listeners[listenerId]) {
							delete areaSheetElem.listeners[listenerId];
							areaSheetElem.count--;
							if (areaSheetElem.count <= 0) {
								delete sheetContainer.areaMap[vertexIndex];
								sheetContainer.areaTree.remove(bbox, areaSheetElem);
							}
konovalovsergey's avatar
konovalovsergey committed
351
						}
352 353 354
					}
				}
			}
konovalovsergey's avatar
konovalovsergey committed
355 356 357 358 359 360 361
		},
		startListeningVolatile: function(listener) {
			var listenerId = listener.getListenerId();
			this.volatileListeners[listenerId] = listener;
		},
		endListeningVolatile: function(listener) {
			var listenerId = listener.getListenerId();
362 363 364
			if (null != listenerId) {
				delete this.volatileListeners[listenerId];
			}
konovalovsergey's avatar
konovalovsergey committed
365
		},
366
		startListeningDefName: function(name, listener, opt_sheetId) {
konovalovsergey's avatar
konovalovsergey committed
367 368 369 370 371 372 373 374 375 376 377
			var listenerId = listener.getListenerId();
			var nameIndex = getDefNameIndex(name);
			var container = this.defNameListeners[nameIndex];
			if (!container) {
				container = {count: 0, listeners: {}};
				this.defNameListeners[nameIndex] = container;
			}
			if (!container.listeners[listenerId]) {
				container.listeners[listenerId] = listener;
				container.count++;
			}
378 379 380 381 382 383 384 385
			if(opt_sheetId){
				var sheetContainer = this.sheetListeners[opt_sheetId];
				if (!sheetContainer) {
					sheetContainer = {cellMap: {}, areaMap: {}, areaTree: new RangeTree(), defName3d: {}};
					this.sheetListeners[opt_sheetId] = sheetContainer;
				}
				sheetContainer.defName3d[listenerId] = listener;
			}
konovalovsergey's avatar
konovalovsergey committed
386
		},
konovalovsergey's avatar
konovalovsergey committed
387 388 389
		isListeningDefName: function(name) {
			return null != this.defNameListeners[getDefNameIndex(name)];
		},
390
		endListeningDefName: function(name, listener, opt_sheetId) {
konovalovsergey's avatar
konovalovsergey committed
391
			var listenerId = listener.getListenerId();
392 393 394
			if (null != listenerId) {
				var nameIndex = getDefNameIndex(name);
				var container = this.defNameListeners[nameIndex];
395
				if (container && container.listeners[listenerId]) {
396 397 398 399 400
					delete container.listeners[listenerId];
					container.count--;
					if (container.count <= 0) {
						delete this.defNameListeners[nameIndex];
					}
konovalovsergey's avatar
konovalovsergey committed
401
				}
402 403 404 405
				if(opt_sheetId){
					var sheetContainer = this.sheetListeners[opt_sheetId];
					if (sheetContainer) {
						delete sheetContainer.defName3d[listenerId];
406 407 408
					}
				}
			}
konovalovsergey's avatar
konovalovsergey committed
409
		},
konovalovsergey's avatar
konovalovsergey committed
410 411 412
		//shift, move
		deleteNodes: function(sheetId, bbox) {
			this.buildDependency();
konovalovsergey's avatar
konovalovsergey committed
413
			this._shiftMoveDelete(AscCommon.c_oNotifyType.Delete, sheetId, bbox, null);
konovalovsergey's avatar
konovalovsergey committed
414
			this.addToChangedRange(sheetId, bbox);
konovalovsergey's avatar
konovalovsergey committed
415 416 417
		},
		shift: function(sheetId, bbox, offset) {
			this.buildDependency();
418
			return this._shiftMoveDelete(AscCommon.c_oNotifyType.Shift, sheetId, bbox, offset);
konovalovsergey's avatar
konovalovsergey committed
419 420 421 422
		},
		move: function(sheetId, bboxFrom, offset) {
			this.buildDependency();
			this._shiftMoveDelete(AscCommon.c_oNotifyType.Move, sheetId, bboxFrom, offset);
konovalovsergey's avatar
konovalovsergey committed
423
			this.addToChangedRange(sheetId, bboxFrom);
konovalovsergey's avatar
konovalovsergey committed
424
		},
425
		changeSheet: function(sheetId, data, tableNamesMap, opt_collectDependencies) {
426 427 428 429 430 431 432 433 434 435 436
			this.buildDependency();
			var listeners = {};
			var sheetContainer = this.sheetListeners[sheetId];
			if (sheetContainer) {
				for (var cellIndex in sheetContainer.cellMap) {
					var cellMapElem = sheetContainer.cellMap[cellIndex];
					for (var listenerId in cellMapElem.listeners) {
						listeners[listenerId] = cellMapElem.listeners[listenerId];
					}
				}
				for (var vertexIndex in sheetContainer.areaMap) {
konovalovsergey's avatar
konovalovsergey committed
437
					var areaSheetElem = sheetContainer.areaMap[vertexIndex];
438 439 440 441
					for (var listenerId in areaSheetElem.listeners) {
						listeners[listenerId] = areaSheetElem.listeners[listenerId];
					}
				}
442 443 444
				for (var listenerId in sheetContainer.defName3d) {
					listeners[listenerId] = sheetContainer.defName3d[listenerId];
				}
445
			}
446 447 448 449 450 451 452 453 454 455 456
			if(tableNamesMap){
				for (var tableName in tableNamesMap) {
					var nameIndex = getDefNameIndex(tableName);
					var container = this.defNameListeners[nameIndex];
					if (container) {
						for (var listenerId in container.listeners) {
							listeners[listenerId] = container.listeners[listenerId];
						}
					}
				}
			}
457
			var notifyData = {type: AscCommon.c_oNotifyType.ChangeSheet, data: data, collectDependencies: opt_collectDependencies};
458 459 460 461
			for (var listenerId in listeners) {
				listeners[listenerId].notify(notifyData);
			}
		},
462
		removeSheet: function(sheetId, tableNames, opt_collectDependencies) {
463
			var t = this;
464
			//cells
465 466 467 468
			var formulas = [];
			this.wb.getWorksheetById(sheetId).getAllFormulas(formulas);
			for (var i = 0; i < formulas.length; ++i) {
				formulas[i].removeDependencies();
469
			}
470
			//defnames
471 472 473
			this._foreachDefNameSheet(sheetId, function(defName){
				if (!defName.isTable) {
					t._removeDefName(sheetId, defName.name, AscCH.historyitem_Workbook_DefinedNamesChangeUndo);
474
					}
475
			});
476
			//tables
477
			var tableNamesMap = {};
478
			for (var i = 0; i < tableNames.length; ++i) {
479
				var tableName = tableNames[i];
480
				this._removeDefName(null, tableName, null);
481
				tableNamesMap[tableName] = 1;
482 483
			}
			//dependence
484
			this.changeSheet(sheetId, {remove: sheetId, tableNamesMap: tableNamesMap}, tableNamesMap, opt_collectDependencies);
485
		},
konovalovsergey's avatar
konovalovsergey committed
486 487 488 489
		//lock
		lockRecal: function() {
			++this.lockCounter;
		},
490 491 492
		isLockRecal: function() {
			return this.lockCounter > 0;
		},
konovalovsergey's avatar
konovalovsergey committed
493 494 495 496 497 498 499 500 501
		unlockRecal: function() {
			if (0 < this.lockCounter) {
				--this.lockCounter;
			}
			if (0 >= this.lockCounter) {
				this.calcTree();
			}
		},
		//defined name
502
		getDefNameByName: function(name, sheetId, opt_exact) {
konovalovsergey's avatar
konovalovsergey committed
503 504
			var res = null;
			var nameIndex = getDefNameIndex(name);
505
			if (sheetId) {
konovalovsergey's avatar
konovalovsergey committed
506
				var sheetContainer = this.defNames.sheet[sheetId];
507
				if (sheetContainer) {
konovalovsergey's avatar
konovalovsergey committed
508 509 510
					res = sheetContainer[nameIndex];
				}
			}
511
			if (!res && !(opt_exact && sheetId)) {
konovalovsergey's avatar
konovalovsergey committed
512 513 514 515
				res = this.defNames.wb[nameIndex];
			}
			return res;
		},
konovalovsergey's avatar
konovalovsergey committed
516
		getDefNameByNodeId: function(nodeId) {
konovalovsergey's avatar
konovalovsergey committed
517
			getFromDefNameId(nodeId);
518
			return this.getDefNameByName(g_FDNI.name, g_FDNI.sheetId, true);
konovalovsergey's avatar
konovalovsergey committed
519
		},
konovalovsergey's avatar
konovalovsergey committed
520
		getDefNameByRef: function(ref, sheetId) {
521
			var getByRef = function(defName) {
konovalovsergey's avatar
konovalovsergey committed
522
				if (!defName.hidden && defName.ref == ref) {
523
					return defName.name;
konovalovsergey's avatar
konovalovsergey committed
524
				}
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
			};
			var res = this._foreachDefNameSheet(sheetId, getByRef);
			if (!res) {
				res = this._foreachDefNameBook(getByRef);
			}
			return res;
		},
		getDefinedNamesWB: function(type) {
			var names = [], activeWS;

			function getNames(defName) {
				if (defName.ref && !defName.hidden && defName.name.indexOf("_xlnm") < 0) {
					if (defName.isTable ||
						(defName.parsedRef && defName.parsedRef.isParsed && defName.parsedRef.countRef == 1 &&
						defName.parsedRef.outStack.length == 1 &&
						defName.parsedRef.calculate().errorType !== AscCommonExcel.cErrorType.bad_reference)) {
						names.push(defName.getAscCDefName());
542
					}
543 544
				}
			}
545

546 547 548
			function sort(a, b) {
				if (a.name > b.name) {
					return 1;
549
				} else if (a.name < b.name) {
550 551 552 553 554
					return -1;
				} else {
					return 0;
				}
			}
555

556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
			switch (type) {
				case c_oAscGetDefinedNamesList.Worksheet:
				case c_oAscGetDefinedNamesList.WorksheetWorkbook:
					activeWS = this.wb.getActiveWs();
					this._foreachDefNameSheet(activeWS.getId(), getNames);
					if (c_oAscGetDefinedNamesList.WorksheetWorkbook) {
						this._foreachDefNameBook(getNames);
					}
					break;
				case c_oAscGetDefinedNamesList.All:
				default:
					this._foreachDefName(function(defName) {
						if (defName.ref && !defName.hidden && defName.name.indexOf("_xlnm") < 0) {
							names.push(defName.getAscCDefName());
						}
					});
					break;
			}
			return names.sort(sort);
konovalovsergey's avatar
konovalovsergey committed
575
		},
konovalovsergey's avatar
konovalovsergey committed
576 577
		addDefNameOpen: function(name, ref, sheetIndex, hidden, isTable) {
			var sheetId = this.wb.getSheetIdByIndex(sheetIndex);
578
			var defName = new DefName(this.wb, name, ref, sheetId, hidden, isTable);
579 580
			this._addDefName(defName);
			return defName;
581 582 583 584
		},
		addDefName: function(name, ref, sheetId, hidden, isTable) {
			var defName = new DefName(this.wb, name, ref, sheetId, hidden, isTable);
			defName.setRef(defName.ref, true);
585 586
			this._addDefName(defName);
			return defName;
konovalovsergey's avatar
konovalovsergey committed
587
		},
588
		removeDefName: function(sheetId, name) {
589
			this._removeDefName(sheetId, name, AscCH.historyitem_Workbook_DefinedNamesChange);
konovalovsergey's avatar
konovalovsergey committed
590
		},
591
		editDefinesNames: function(oldUndoName, newUndoName) {
592
			var res = null;
593 594
			if (!AscCommon.rx_defName.test(getDefNameIndex(newUndoName.name)) || !newUndoName.ref ||
				newUndoName.ref.length == 0) {
595 596
				return res;
			}
597 598
			if (oldUndoName) {
				res = this.getDefNameByName(oldUndoName.name, oldUndoName.sheetId);
konovalovsergey's avatar
konovalovsergey committed
599
			} else {
600
				res = this.addDefName(newUndoName.name, newUndoName.ref, newUndoName.sheetId, false, false);
601
			}
konovalovsergey's avatar
konovalovsergey committed
602
			History.Create_NewPoint();
603 604
			if (res && oldUndoName) {
				if (oldUndoName.name != newUndoName.name) {
konovalovsergey's avatar
konovalovsergey committed
605
					this.buildDependency();
606

konovalovsergey's avatar
konovalovsergey committed
607
					res = this._delDefName(res.name, res.sheetId);
608
					res.setUndoDefName(newUndoName);
konovalovsergey's avatar
konovalovsergey committed
609
					this._addDefName(res);
610

611 612
					var notifyData = {type: AscCommon.c_oNotifyType.ChangeDefName, from: oldUndoName, to: newUndoName};
					this._broadcastDefName(oldUndoName.name, notifyData);
613

konovalovsergey's avatar
konovalovsergey committed
614 615
					this.addToChangedDefName(res);
				} else {
616
					res.setUndoDefName(newUndoName);
617
				}
618
			}
619
			History.Add(AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_DefinedNamesChange, null, null,
620
						new UndoRedoData_FromTo(oldUndoName, newUndoName));
Alexander.Trofimov's avatar
Alexander.Trofimov committed
621
			return res;
konovalovsergey's avatar
konovalovsergey committed
622
		},
623 624 625 626 627 628 629 630 631
		checkDefName: function (name, sheetIndex) {
			var res = new Asc.asc_CCheckDefName();
			var range = AscCommonExcel.g_oRangeCache.getRange3D(name) ||
				AscCommonExcel.g_oRangeCache.getAscRange(name);
			if (range || !AscCommon.rx_defName.test(name.toLowerCase())) {
				res.status = false;
				res.reason = c_oAscDefinedNameReason.WrongName;
				return res;
			}
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
632

633
			var sheetId = this.wb.getSheetIdByIndex(sheetIndex);
634
			var defName = this.getDefNameByName(name, sheetId, true);
635 636 637 638 639 640 641
			if (defName) {
				res.status = false;
				if (defName.isLock) {
					res.reason = c_oAscDefinedNameReason.IsLocked;
				} else {
					res.reason = c_oAscDefinedNameReason.Existed;
				}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
642
			} else {
konovalovsergey's avatar
konovalovsergey committed
643 644 645 646 647 648 649
				if (this.isListeningDefName(name)) {
					res.status = false;
					res.reason = c_oAscDefinedNameReason.NameReserved;
				} else {
					res.status = true;
					res.reason = c_oAscDefinedNameReason.OK;
				}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
650
			}
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
651

652
			return res;
konovalovsergey's avatar
konovalovsergey committed
653
		},
654
		copyDefNameByWorksheet: function(wsFrom, wsTo, renameParams) {
konovalovsergey's avatar
konovalovsergey committed
655
			var sheetContainerFrom = this.defNames.sheet[wsFrom.getId()];
656 657
			if (sheetContainerFrom) {
				for (var name in sheetContainerFrom) {
konovalovsergey's avatar
konovalovsergey committed
658
					var defNameOld = sheetContainerFrom[name];
659 660
					if (!defNameOld.isTable && defNameOld.parsedRef) {
						var parsedRefNew = defNameOld.parsedRef.clone();
661 662 663
						parsedRefNew.renameSheetCopy(renameParams);
						var refNew = parsedRefNew.assemble(true);
						this.addDefName(defNameOld.name, refNew, wsTo.getId(), defNameOld.hidden, defNameOld.isTable);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
664 665 666
					}
				}
			}
konovalovsergey's avatar
konovalovsergey committed
667 668 669
		},
		saveDefName: function() {
			var list = [];
konovalovsergey's avatar
konovalovsergey committed
670 671
			this._foreachDefName(function(defName) {
				if (!defName.isTable && defName.ref) {
konovalovsergey's avatar
konovalovsergey committed
672 673 674 675 676 677
					list.push(defName.getAscCDefName());
				}
			});
			return list;
		},
		unlockDefName: function() {
konovalovsergey's avatar
konovalovsergey committed
678
			this._foreachDefName(function(defName) {
679
				defName.isLock = null;
konovalovsergey's avatar
konovalovsergey committed
680 681 682
			});
		},
		checkDefNameLock: function() {
konovalovsergey's avatar
konovalovsergey committed
683
			return this._foreachDefName(function(defName) {
konovalovsergey's avatar
konovalovsergey committed
684 685 686
				return defName.isLock;
			});
		},
687
		//defined name table
konovalovsergey's avatar
konovalovsergey committed
688
		getNextTableName: function() {
konovalovsergey's avatar
konovalovsergey committed
689
			var sNewName;
konovalovsergey's avatar
konovalovsergey committed
690 691 692 693 694 695 696
			var collaborativeIndexUser = "";
			if (this.wb.oApi.collaborativeEditing.getCollaborativeEditing()) {
				collaborativeIndexUser = "_" + this.wb.oApi.CoAuthoringApi.get_indexUser();
			}
			do {
				this.tableNameIndex++;
				sNewName = this.tableNamePattern + this.tableNameIndex + collaborativeIndexUser;
697
			} while (this.getDefNameByName(sNewName, null) || this.isListeningDefName(sNewName));
konovalovsergey's avatar
konovalovsergey committed
698 699
			return sNewName;
		},
700
		addTableName: function(ws, table, opt_isOpen) {
konovalovsergey's avatar
konovalovsergey committed
701
			var ref = table.getRangeWithoutHeaderFooter();
konovalovsergey's avatar
konovalovsergey committed
702

konovalovsergey's avatar
konovalovsergey committed
703 704
			var defNameRef = parserHelp.get3DRef(ws.getName(), ref.getAbsName());
			var defName = this.getDefNameByName(table.DisplayName, null);
konovalovsergey's avatar
konovalovsergey committed
705
			if (!defName) {
706 707 708 709 710
				if(opt_isOpen){
					this.addDefNameOpen(table.DisplayName, defNameRef, null, null, true);
				} else {
					this.addDefName(table.DisplayName, defNameRef, null, null, true);
				}
konovalovsergey's avatar
konovalovsergey committed
711
			} else {
konovalovsergey's avatar
konovalovsergey committed
712
				defName.setRef(defNameRef);
konovalovsergey's avatar
konovalovsergey committed
713 714
			}
		},
715 716
		changeTableRef: function(table) {
			var defName = this.getDefNameByName(table.DisplayName, null);
717
			if (defName) {
konovalovsergey's avatar
konovalovsergey committed
718
				this.buildDependency();
719 720
				var oldUndoName = defName.getUndoDefName();
				var newUndoName = defName.getUndoDefName();
721 722
				var ref = table.getRangeWithoutHeaderFooter();
				newUndoName.ref = defName.ref.split('!')[0] + '!' + ref.getAbsName();
konovalovsergey's avatar
konovalovsergey committed
723
				History.TurnOff();
724 725
				this.editDefinesNames(oldUndoName, newUndoName);
				var notifyData = {type: AscCommon.c_oNotifyType.ChangeDefName, from: oldUndoName, to: newUndoName};
konovalovsergey's avatar
konovalovsergey committed
726
				this._broadcastDefName(defName.name, notifyData);
konovalovsergey's avatar
konovalovsergey committed
727
				History.TurnOn();
728 729
				this.addToChangedDefName(defName);
				this.calcTree();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
730
			}
731
		},
732
		changeTableName: function(tableName, newName) {
konovalovsergey's avatar
konovalovsergey committed
733
			var defName = this.getDefNameByName(tableName, null);
734
			if (defName) {
735 736 737
				var oldUndoName = defName.getUndoDefName();
				var newUndoName = defName.getUndoDefName();
				newUndoName.name = newName;
738
				History.TurnOff();
739
				this.editDefinesNames(oldUndoName, newUndoName);
740
				History.TurnOn();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
741
			}
742
		},
GoshaZotov's avatar
GoshaZotov committed
743
		delTableName: function(tableName, bConvertTableFormulaToRef) {
744 745 746 747
			this.buildDependency();
			var defName = this.getDefNameByName(tableName);
			
			this.addToChangedDefName(defName);
GoshaZotov's avatar
GoshaZotov committed
748 749
			var notifyData = {type: AscCommon.c_oNotifyType.ChangeDefName, from: defName.getUndoDefName(), to: null, bConvertTableFormulaToRef: bConvertTableFormulaToRef};
			this._broadcastDefName(tableName, notifyData);
750 751 752 753 754 755
			
			this._delDefName(tableName, null);
			if (defName) {
				defName.removeDependencies();
			}
		},
konovalovsergey's avatar
konovalovsergey committed
756 757 758 759 760
		delColumnTable: function(tableName, deleted) {
			this.buildDependency();
			var notifyData = {type: AscCommon.c_oNotifyType.DelColumnTable, tableName: tableName, deleted: deleted};
			this._broadcastDefName(tableName, notifyData);
		},
761
		renameTableColumn: function(tableName) {
762 763 764
			var defName = this.getDefNameByName(tableName, null);
			if (defName) {
				this.buildDependency();
765
				var notifyData = {type: AscCommon.c_oNotifyType.RenameTableColumn, tableName: tableName};
766 767
				this._broadcastDefName(defName.name, notifyData);
			}
konovalovsergey's avatar
konovalovsergey committed
768
			this.calcTree();
769
		},
konovalovsergey's avatar
konovalovsergey committed
770
		//set dirty
konovalovsergey's avatar
konovalovsergey committed
771 772 773
		addToChangedCell: function(cell) {
			if (!this.changedCell) {
				this.changedCell = {};
774
			}
konovalovsergey's avatar
konovalovsergey committed
775
			var sheetId = cell.ws.getId();
konovalovsergey's avatar
konovalovsergey committed
776 777 778 779 780 781
			var changedSheet = this.changedCell[sheetId];
			if (!changedSheet) {
				//{}, а не [], потому что при сборке может придти сразу много одинаковых ячеек
				changedSheet = {};
				this.changedCell[sheetId] = changedSheet;
			}
konovalovsergey's avatar
konovalovsergey committed
782
			changedSheet[getCellIndex(cell.nRow, cell.nCol)] = 1;
konovalovsergey's avatar
konovalovsergey committed
783
		},
konovalovsergey's avatar
konovalovsergey committed
784 785 786
		addToChangedDefName: function(defName) {
			if (!this.changedDefName) {
				this.changedDefName = {};
konovalovsergey's avatar
konovalovsergey committed
787
			}
konovalovsergey's avatar
konovalovsergey committed
788 789 790 791 792 793 794 795 796 797 798 799 800 801
			this.changedDefName[defName.getNodeId()] = 1;
		},
		addToChangedRange: function(sheetId, bbox) {
			var notifyData = {type: AscCommon.c_oNotifyType.Changed};
			var sheetContainer = this.sheetListeners[sheetId];
			if (sheetContainer) {
				for (var cellIndex in sheetContainer.cellMap) {
					getFromCellIndex(cellIndex);
					if (bbox.contains(g_FCI.col, g_FCI.row)) {
						var cellMapElem = sheetContainer.cellMap[cellIndex];
						for (var listenerId in cellMapElem.listeners) {
							cellMapElem.listeners[listenerId].notify(notifyData);
						}
					}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
802
				}
konovalovsergey's avatar
konovalovsergey committed
803 804 805 806 807 808 809
				for (var areaIndex in sheetContainer.areaMap) {
					var areaMapElem = sheetContainer.areaMap[areaIndex];
					var isIntersect = bbox.isIntersect(areaMapElem.bbox);
					if (isIntersect) {
						for (var listenerId in areaMapElem.listeners) {
							areaMapElem.listeners[listenerId].notify(notifyData);
						}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
810 811
					}
				}
konovalovsergey's avatar
konovalovsergey committed
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
			}
		},
		addToBuildDependencyCell: function(cell) {
			var sheetId = cell.ws.getId();
			var unparsedSheet = this.buildCell[sheetId];
			if (!unparsedSheet) {
				//{}, а не [], потому что при сборке может придти сразу много одинаковых ячеек
				unparsedSheet = {};
				this.buildCell[sheetId] = unparsedSheet;
			}
			unparsedSheet[getCellIndex(cell.nRow, cell.nCol)] = 1;
		},
		addToBuildDependencyDefName: function(defName) {
			this.buildDefName[defName.getNodeId()] = 1;
		},
		addToCleanCellCache: function(sheetId, row, col) {
			var sheetArea = this.cleanCellCache[sheetId];
			if (sheetArea) {
				sheetArea.union3(col, row);
			} else {
				this.cleanCellCache[sheetId] = Asc.Range(col, row, col, row);
			}
		},
835 836 837 838 839 840
		notifyChanged: function(changedFormulas) {
			var notifyData = {type: AscCommon.c_oNotifyType.Changed};
			for (var listenerId in changedFormulas) {
				changedFormulas[listenerId].notify(notifyData);
			}
		},
konovalovsergey's avatar
konovalovsergey committed
841 842 843 844 845 846 847 848
		//build, calc
		buildDependency: function() {
			for (var sheetId in this.buildCell) {
				var ws = this.wb.getWorksheetById(sheetId);
				if (ws) {
					var unparsedSheet = this.buildCell[sheetId];
					for (var cellIndex in unparsedSheet) {
						getFromCellIndex(cellIndex);
849 850 851
						var cell = ws._getCellNoEmpty(g_FCI.row, g_FCI.col);
						if (cell) {
							cell._BuildDependencies(true, true);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
852 853 854 855
						}
					}
				}
			}
konovalovsergey's avatar
konovalovsergey committed
856
			for (var defNameId in this.buildDefName) {
857
				var defName = this.getDefNameByNodeId(defNameId);
konovalovsergey's avatar
konovalovsergey committed
858
				if (defName && defName.parsedRef) {
konovalovsergey's avatar
konovalovsergey committed
859 860
					defName.parsedRef.parse();
					defName.parsedRef.buildDependencies();
konovalovsergey's avatar
konovalovsergey committed
861
					this.addToChangedDefName(defName);
862 863
				}
			}
konovalovsergey's avatar
konovalovsergey committed
864 865 866 867 868 869
			this.buildCell = {};
			this.buildDefName = {};
		},
		calcTree: function() {
			if (this.lockCounter > 0) {
				return;
870
			}
konovalovsergey's avatar
konovalovsergey committed
871 872 873 874
			var notifyData = {type: AscCommon.c_oNotifyType.Dirty};
			this.buildDependency();
			this._broadscastVolatile(notifyData);
			var calcTrack = [];
875
			var noCalcTrack = [];
konovalovsergey's avatar
konovalovsergey committed
876
			while (this.changedCell || this.changedDefName) {
877
				this._broadcastDefNames(notifyData, noCalcTrack);
konovalovsergey's avatar
konovalovsergey committed
878 879
				this._broadcastCells(notifyData, calcTrack);
			}
konovalovsergey's avatar
konovalovsergey committed
880
			this._broadcastCellsEnd();
881 882 883 884 885
			for (var i = 0; i < noCalcTrack.length; ++i) {
				var formula = noCalcTrack[i];
				//defName recalc when calc formula containing it. no need calc it
				formula.setIsDirty(false);
			}
konovalovsergey's avatar
konovalovsergey committed
886 887 888 889 890
			for (var i = 0; i < calcTrack.length; ++i) {
				var formula = calcTrack[i];
				if (formula.getIsDirty()) {
					formula.calculate();
				}
891
			}
892
			for (var i in this.cleanCellCache) {
konovalovsergey's avatar
konovalovsergey committed
893 894 895 896
				this.wb.handlers.trigger("cleanCellCache", i, {0: this.cleanCellCache[i]},
										 AscCommonExcel.c_oAscCanChangeColWidth.none);
			}
			this.cleanCellCache = {};
897 898
			AscCommonExcel.g_oVLOOKUPCache.clean();
			AscCommonExcel.g_oHLOOKUPCache.clean();
konovalovsergey's avatar
konovalovsergey committed
899
		},
900 901 902 903 904
		initOpen: function() {
			this._foreachDefName(function(defName) {
				defName.setRef(defName.ref, true, true);
			});
		},
905 906 907 908 909 910 911 912 913 914
		getSnapshot: function(wb) {
			var res = new DependencyGraph(wb);
			this._foreachDefName(function(defName){
				//_addDefName because we don't need dependency
				//include table defNames too.
				res._addDefName(defName.clone(wb));
			});
			res.tableNameIndex = this.tableNameIndex;
			return res;
		},
915 916
		getAllFormulas: function(formulas) {
			this._foreachDefName(function(defName) {
917
				if (defName.parsedRef) {
918 919 920 921
					formulas.push(defName.parsedRef);
				}
			});
		},
konovalovsergey's avatar
konovalovsergey committed
922
		//internal
konovalovsergey's avatar
konovalovsergey committed
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
		_addDefName: function(defName) {
			var nameIndex = getDefNameIndex(defName.name);
			var container;
			var sheetId = defName.sheetId;
			if (sheetId) {
				container = this.defNames.sheet[sheetId];
				if (!container) {
					container = {};
					this.defNames.sheet[sheetId] = container;
				}
			} else {
				container = this.defNames.wb;
			}
			var cur = container[nameIndex];
			if (cur) {
				cur.removeDependencies();
			}
			container[nameIndex] = defName;
		},
942 943 944
		_removeDefName: function(sheetId, name, historyType) {
			var defName = this._delDefName(name, sheetId);
			if (defName) {
945 946 947 948 949
				if (null != historyType) {
					History.Create_NewPoint();
					History.Add(AscCommonExcel.g_oUndoRedoWorkbook, historyType, null, null,
								new UndoRedoData_FromTo(defName.getUndoDefName(), null));
				}
950

951 952 953 954
				defName.removeDependencies();
				this.addToChangedDefName(defName);
			}
		},
955
		_delDefName: function(name, sheetId) {
konovalovsergey's avatar
konovalovsergey committed
956 957
			var res = null;
			var nameIndex = getDefNameIndex(name);
958
			var sheetContainer;
konovalovsergey's avatar
konovalovsergey committed
959
			if (sheetId) {
960 961 962 963 964 965
				sheetContainer = this.defNames.sheet[sheetId];
			}
			else {
				sheetContainer = this.defNames.wb;
			}
			if (sheetContainer) {
konovalovsergey's avatar
konovalovsergey committed
966
				res = sheetContainer[nameIndex];
967 968
				delete sheetContainer[nameIndex];
			}
konovalovsergey's avatar
konovalovsergey committed
969
			return res;
970
		},
konovalovsergey's avatar
konovalovsergey committed
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
		_foreachDefName: function(action) {
			var containerSheet;
			var sheetId;
			var name;
			var res;
			for (sheetId in this.defNames.sheet) {
				containerSheet = this.defNames.sheet[sheetId];
				for (name in containerSheet) {
					res = action(containerSheet[name], containerSheet);
					if (res) {
						break;
					}
				}
			}
			if (!res) {
986 987 988 989 990 991 992 993
				res = this._foreachDefNameBook(action);
			}
			return res;
		},
		_foreachDefNameSheet: function(sheetId, action) {
			var name;
			var res;
			var containerSheet = this.defNames.sheet[sheetId];
994
			if (containerSheet) {
995 996
				for (name in containerSheet) {
					res = action(containerSheet[name], containerSheet);
konovalovsergey's avatar
konovalovsergey committed
997 998
					if (res) {
						break;
999
					}
konovalovsergey's avatar
konovalovsergey committed
1000 1001
				}
			}
1002 1003 1004 1005 1006 1007 1008 1009 1010
			return res;
		},
		_foreachDefNameBook: function(action) {
			var containerSheet;
			var name;
			var res;
			for (name in this.defNames.wb) {
				res = action(this.defNames.wb[name], this.defNames.wb);
				if (res) {
1011 1012 1013
					break;
				}
			}
1014
			return res;
konovalovsergey's avatar
konovalovsergey committed
1015 1016 1017 1018
		},
		_broadscastVolatile: function(notifyData) {
			for (var i in this.volatileListeners) {
				this.volatileListeners[i].notify(notifyData);
1019
			}
konovalovsergey's avatar
konovalovsergey committed
1020
		},
GoshaZotov's avatar
GoshaZotov committed
1021
		_broadcastDefName: function(name, notifyData) {
konovalovsergey's avatar
konovalovsergey committed
1022 1023
			var nameIndex = getDefNameIndex(name);
			var container = this.defNameListeners[nameIndex];
1024
			if (container) {
konovalovsergey's avatar
konovalovsergey committed
1025
				for (var listenerId in container.listeners) {
GoshaZotov's avatar
GoshaZotov committed
1026
					container.listeners[listenerId].notify(notifyData);
konovalovsergey's avatar
konovalovsergey committed
1027 1028 1029
				}
			}
		},
1030
		_broadcastDefNames: function(notifyData, noCalcTrack) {
konovalovsergey's avatar
konovalovsergey committed
1031 1032 1033 1034
			if (this.changedDefName) {
				var changedDefName = this.changedDefName;
				this.changedDefName = null;
				for (var nodeId in changedDefName) {
1035
					var defName = this.getDefNameByNodeId(nodeId);
konovalovsergey's avatar
konovalovsergey committed
1036
					if (defName && defName.parsedRef) {
1037 1038
						defName.parsedRef.setIsDirty(true);
						noCalcTrack.push(defName.parsedRef);
konovalovsergey's avatar
konovalovsergey committed
1039
					}
1040
					getFromDefNameId(nodeId);
konovalovsergey's avatar
konovalovsergey committed
1041 1042
					this._broadcastDefName(g_FDNI.name, notifyData);
				}
konovalovsergey's avatar
konovalovsergey committed
1043 1044
			}
		},
konovalovsergey's avatar
konovalovsergey committed
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
		_broadcastCells: function(notifyData, calcTrack) {
			if (this.changedCell) {
				var changedCell = this.changedCell;
				this.changedCell = null;
				for (var sheetId in changedCell) {
					var changedSheet = changedCell[sheetId];
					var sheetContainer = this.sheetListeners[sheetId];
					var ws = this.wb.getWorksheetById(sheetId);
					if (sheetContainer || ws) {
						for (var cellIndex in changedSheet) {
							if (sheetContainer) {
								var cellMapElem = sheetContainer.cellMap[cellIndex];
								if (cellMapElem) {
									for (var listenerId in cellMapElem.listeners) {
										cellMapElem.listeners[listenerId].notify(notifyData);
1060 1061 1062
									}
								}
							}
konovalovsergey's avatar
konovalovsergey committed
1063 1064 1065 1066 1067 1068 1069
							if (ws) {
								getFromCellIndex(cellIndex);
								var cell = ws._getCell(g_FCI.row, g_FCI.col);
								if (cell && cell.formulaParsed) {
									cell.formulaParsed.setIsDirty(true);
									calcTrack.push(cell.formulaParsed);
								}
1070
							}
konovalovsergey's avatar
konovalovsergey committed
1071
						}
konovalovsergey's avatar
konovalovsergey committed
1072 1073 1074 1075 1076 1077 1078 1079
						if (sheetContainer) {
							var areas = sheetContainer.areaTree.getByCells(changedSheet);
							this.tempGetByCells.push({areaTree: sheetContainer.areaTree, areas: areas});
							for (var i = 0; i < areas.length; ++i) {
								var area = areas[i];
								for (var listenerId in area.data.listeners) {
									area.data.listeners[listenerId].notify(notifyData);
								}
1080 1081
							}
						}
konovalovsergey's avatar
konovalovsergey committed
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
					}
				}
			}
		},
		_broadcastCellsEnd: function() {
			for (var i = 0; i < this.tempGetByCells.length; ++i) {
				var temp = this.tempGetByCells[i];
				temp.areaTree.getByCellsEnd(temp.areas);
			}
			this.tempGetByCells = [];
		},
		_shiftMoveDelete: function(notifyType, sheetId, bbox, offset) {
1094
			var listeners = {};
konovalovsergey's avatar
konovalovsergey committed
1095 1096
			var sheetContainer = this.sheetListeners[sheetId];
			if (sheetContainer) {
1097 1098 1099 1100 1101 1102
				var bboxShift;
				if (AscCommon.c_oNotifyType.Shift == notifyType) {
					var bHor = 0 != offset.offsetCol;
					bboxShift = AscCommonExcel.shiftGetBBox(bbox, bHor);
				}
				var changed = {};
konovalovsergey's avatar
konovalovsergey committed
1103
				var isIntersect;
konovalovsergey's avatar
konovalovsergey committed
1104 1105
				for (var cellIndex in sheetContainer.cellMap) {
					getFromCellIndex(cellIndex);
konovalovsergey's avatar
konovalovsergey committed
1106 1107 1108 1109 1110 1111
					if (AscCommon.c_oNotifyType.Shift == notifyType) {
						isIntersect = bbox.isIntersectForShiftCell(g_FCI.col, g_FCI.row, offset);
					} else {
						isIntersect = bbox.contains(g_FCI.col, g_FCI.row);
					}
					if (isIntersect) {
konovalovsergey's avatar
konovalovsergey committed
1112 1113 1114 1115 1116 1117 1118 1119 1120
						var cellMapElem = sheetContainer.cellMap[cellIndex];
						for (var listenerId in cellMapElem.listeners) {
							listeners[listenerId] = cellMapElem.listeners[listenerId];
						}
					}
				}
				for (var areaIndex in sheetContainer.areaMap) {
					var areaMapElem = sheetContainer.areaMap[areaIndex];
					if (AscCommon.c_oNotifyType.Shift == notifyType) {
1121 1122 1123 1124 1125 1126
						if (bboxShift.isIntersect(areaMapElem.bbox)) {
							isIntersect = bbox.isIntersectForShift(areaMapElem.bbox, offset);
							if (!isIntersect) {
								for (var listenerId in areaMapElem.listeners) {
									changed[listenerId] = areaMapElem.listeners[listenerId];
								}
1127 1128
							}
						}
konovalovsergey's avatar
konovalovsergey committed
1129 1130 1131
					} else if (AscCommon.c_oNotifyType.Move == notifyType) {
						isIntersect = bbox.containsRange(areaMapElem.bbox);
					} else if (AscCommon.c_oNotifyType.Delete == notifyType) {
1132
						isIntersect = bbox.isIntersect(areaMapElem.bbox);
konovalovsergey's avatar
konovalovsergey committed
1133 1134 1135 1136 1137
					}
					if (isIntersect) {
						for (var listenerId in areaMapElem.listeners) {
							listeners[listenerId] = areaMapElem.listeners[listenerId];
						}
1138 1139
					}
				}
konovalovsergey's avatar
konovalovsergey committed
1140 1141 1142 1143
				var notifyData = {type: notifyType, sheetId: sheetId, bbox: bbox, offset: offset};
				for (var listenerId in listeners) {
					listeners[listenerId].notify(notifyData);
				}
1144 1145 1146 1147
				//add formula for recalculate
				for (var listenerId in changed) {
					listeners[listenerId] = changed[listenerId];
				}
1148
			}
1149
			return listeners;
1150 1151
		}
	};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1152

konovalovsergey's avatar
konovalovsergey committed
1153 1154 1155 1156 1157 1158 1159 1160
	function RangeTree() {
		this.yTree = new Asc.TreeRB();
		this.id = 0;
	}

	RangeTree.prototype = {
		add: function(bbox, data) {
			data.id = this.id++;
konovalovsergey's avatar
konovalovsergey committed
1161
			var startFlag = bbox.r1 !== bbox.r2 ? 1 : 3;
konovalovsergey's avatar
konovalovsergey committed
1162
			var dataWrap = {bbox: bbox, data: data, isOutput: false};
konovalovsergey's avatar
konovalovsergey committed
1163 1164
			var top = this.yTree.insertOrGet(new Asc.TreeRBNode(bbox.r1, {count: 0, vals: {}}));
			top.storedValue.vals[data.id] = {startFlag: startFlag, dataWrap: dataWrap};
konovalovsergey's avatar
konovalovsergey committed
1165
			top.storedValue.count++;
konovalovsergey's avatar
konovalovsergey committed
1166 1167 1168 1169 1170 1171
			if (bbox.r1 != bbox.r2) {
				startFlag = 2;
				var bottom = this.yTree.insertOrGet(new Asc.TreeRBNode(bbox.r2, {count: 0, vals: {}}));
				bottom.storedValue.vals[data.id] = {startFlag: startFlag, dataWrap: dataWrap};
				bottom.storedValue.count++;
			}
konovalovsergey's avatar
konovalovsergey committed
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
		},
		remove: function(bbox, data) {
			var top = this.yTree.getElem(bbox.r1);
			if (top) {
				if (top.storedValue.vals[data.id]) {
					delete top.storedValue.vals[data.id];
					top.storedValue.count--;
					if (top.storedValue.count <= 0) {
						this.yTree.deleteNode(top);
					}
				}
				var bottom = this.yTree.getElem(bbox.r2);
konovalovsergey's avatar
konovalovsergey committed
1184
				if (bottom && bottom.storedValue.vals[data.id]) {
konovalovsergey's avatar
konovalovsergey committed
1185 1186 1187 1188
					delete bottom.storedValue.vals[data.id];
					bottom.storedValue.count--;
					if (bottom.storedValue.count <= 0) {
						this.yTree.deleteNode(bottom);
1189 1190 1191
					}
				}
			}
konovalovsergey's avatar
konovalovsergey committed
1192 1193 1194 1195 1196 1197
		},
		getByCells: function(cells) {
			var res = [];
			var nodes = this.yTree.getNodeAll();
			var cellArr = [];
			for (var cellIndex in cells) {
konovalovsergey's avatar
konovalovsergey committed
1198
				cellArr.push(cellIndex - 0);
konovalovsergey's avatar
konovalovsergey committed
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
			}
			//sort завязана на реализацию getCellIndex
			cellArr.sort(function(a, b) {
				return a - b;
			});
			if (cellArr.length > 0 && nodes.length > 0) {
				var curNodes = {};
				var curY = null;
				var curNodeY = null;
				var curNodeYIndex = 0;
				var curCellIndex = 0;
				var curCellX = null;
				var curCellY = null;
				while (curNodeYIndex < nodes.length && curCellIndex < cellArr.length) {
					if (!curNodeY) {
						curNodeY = nodes[curNodeYIndex];
						curY = curNodeY.key;
						for (var id in curNodeY.storedValue.vals) {
							var elem = curNodeY.storedValue.vals[id];
konovalovsergey's avatar
konovalovsergey committed
1218
							if (0 !== (1 & elem.startFlag) && !elem.dataWrap.isOutput) {
1219 1220 1221 1222 1223 1224 1225 1226
								for (var i = elem.dataWrap.bbox.c1; i <= elem.dataWrap.bbox.c2; ++i) {
									var curNodesElem = curNodes[i];
									if (!curNodesElem) {
										curNodesElem = {};
										curNodes[i] = curNodesElem;
									}
									curNodesElem[id] = elem;
								}
1227 1228 1229
							}
						}
					}
konovalovsergey's avatar
konovalovsergey committed
1230 1231 1232 1233 1234 1235 1236
					if (!curCellX) {
						var cellIndex = cellArr[curCellIndex];
						getFromCellIndex(cellIndex);
						curCellX = g_FCI.col;
						curCellY = g_FCI.row;
					}
					if (curCellY <= curY) {
1237 1238 1239
						var curNodesElemX = curNodes[curCellX];
						for (var id in curNodesElemX) {
							var elem = curNodesElemX[id];
konovalovsergey's avatar
konovalovsergey committed
1240
							if (!elem.dataWrap.isOutput && elem.dataWrap.bbox.r1 <= curCellY) {
konovalovsergey's avatar
konovalovsergey committed
1241 1242
								elem.dataWrap.isOutput = true;
								res.push(elem.dataWrap);
1243 1244 1245 1246 1247 1248
								for (var i = elem.dataWrap.bbox.c1; i <= elem.dataWrap.bbox.c2; ++i) {
									var curNodesElem = curNodes[i];
									if (curNodesElem) {
										delete curNodesElem[id];
									}
								}
konovalovsergey's avatar
konovalovsergey committed
1249
							}
1250
						}
konovalovsergey's avatar
konovalovsergey committed
1251 1252 1253
						curCellIndex++;
						curCellX = null;
						curCellY = null;
1254
					} else {
konovalovsergey's avatar
konovalovsergey committed
1255 1256
						for (var id in curNodeY.storedValue.vals) {
							var elem = curNodeY.storedValue.vals[id];
konovalovsergey's avatar
konovalovsergey committed
1257
							if (0 !== (2 & elem.startFlag) && !elem.dataWrap.isOutput) {
1258 1259 1260 1261 1262 1263
								for (var i = elem.dataWrap.bbox.c1; i <= elem.dataWrap.bbox.c2; ++i) {
									var curNodesElem = curNodes[i];
									if (curNodesElem) {
										delete curNodesElem[id];
									}
								}
konovalovsergey's avatar
konovalovsergey committed
1264 1265 1266 1267
							}
						}
						curNodeYIndex++;
						curNodeY = null;
1268 1269
					}
				}
1270
			}
konovalovsergey's avatar
konovalovsergey committed
1271 1272 1273 1274 1275 1276 1277 1278
			//for(var i = 0 ; i < res.length; ++i){
			//	res[i].isOutput = false;
			//}
			return res;
		},
		getByCellsEnd: function(areas) {
			for (var i = 0; i < areas.length; ++i) {
				areas[i].isOutput = false;
1279 1280 1281
			}
		}
	};
konovalovsergey's avatar
konovalovsergey committed
1282

1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
	function ForwardTransformationFormula(elem, formula, parsed) {
		this.elem = elem;
		this.formula = formula;
		this.parsed = parsed;
	}
	ForwardTransformationFormula.prototype = {
		onFormulaEvent: function(type, eventData) {
			if (AscCommon.c_oNotifyParentType.CanDo === type) {
				return true;
			} else if (AscCommon.c_oNotifyParentType.Change === type) {
				this.parsed.setIsDirty(false);
			} else if (AscCommon.c_oNotifyParentType.ChangeFormula === type) {
				this.formula = eventData.assemble;
1296 1297
			}
		}
1298
	};
1299
	function angleFormatToInterface(val)
1300
	{
1301 1302 1303 1304
		var nRes = 0;
		if(0 <= val && val <= 180)
			nRes = val <= 90 ? val : 90 - val;
		return nRes;
1305
	}
1306
	function angleFormatToInterface2(val)
1307
	{
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
		if(g_nVerticalTextAngle == val)
			return val;
		else
			return angleFormatToInterface(val);
	}
	function angleInterfaceToFormat(val)
	{
		var nRes = val;
		if(-90 <= val && val <= 90)
		{
			if(val < 0)
				nRes = 90 - val;
1320
		}
1321 1322 1323
		else if(g_nVerticalTextAngle != val)
			nRes = 0;
		return nRes;
1324
	}
1325 1326 1327 1328
	function getUniqueKeys(array) {
		var i, o = {};
		for (i = 0; i < array.length; ++i) {
			o[array[i].v] = o.hasOwnProperty(array[i].v);
1329
		}
1330
		return o;
konovalovsergey's avatar
konovalovsergey committed
1331
	}
1332 1333 1334 1335 1336 1337 1338 1339 1340
//-------------------------------------------------------------------------------------------------
	/**
	 * @constructor
	 */
	function Workbook(eventsHandlers, oApi){
		this.oApi = oApi;
		this.handlers = eventsHandlers;
		this.dependencyFormulas = new DependencyGraph(this);
		this.nActive = 0;
1341

1342 1343
		this.theme = null;
		this.clrSchemeMap = null;
1344

1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
		this.CellStyles = new AscCommonExcel.CCellStyles();
		this.TableStyles = new Asc.CTableStyles();
		this.oStyleManager = new AscCommonExcel.StyleManager();
		this.aComments = [];	// Комментарии к документу
		this.aCommentsCoords = [];
		this.aWorksheets = [];
		this.aWorksheetsById = {};
		this.aCollaborativeActions = [];
		this.bCollaborativeChanges = false;
		this.bUndoChanges = false;
		this.bRedoChanges = false;
		this.aCollaborativeChangeElements = [];
1357

1358
		this.wsHandlers = null;
1359

1360
		this.openErrors = [];
1361

1362 1363
		this.maxDigitWidth = 0;
		this.paddingPlusBorder = 0;
1364
	}
1365 1366 1367 1368 1369
	Workbook.prototype.init=function(tableCustomFunc, bNoBuildDep, bSnapshot){
		if(this.nActive < 0)
			this.nActive = 0;
		if(this.nActive >= this.aWorksheets.length)
			this.nActive = this.aWorksheets.length - 1;
1370

1371
		var self = this;
1372

1373 1374 1375 1376 1377
		this.wsHandlers = new AscCommonExcel.asc_CHandlersList( /*handlers*/{
			"changeRefTablePart"   : function (table) {
				self.dependencyFormulas.changeTableRef(table);
			},
			"changeColumnTablePart": function ( tableName ) {
1378
				self.dependencyFormulas.renameTableColumn( tableName );
konovalovsergey's avatar
konovalovsergey committed
1379 1380 1381
			},
			"deleteColumnTablePart": function(tableName, deleted) {
				self.dependencyFormulas.delColumnTable(tableName, deleted);
1382 1383
			}, 'onFilterInfo' : function () {
				self.handlers.trigger("asc_onFilterInfo");
1384
			}
1385 1386 1387 1388
		} );
		for(var i = 0, length = tableCustomFunc.length; i < length; ++i) {
			var elem = tableCustomFunc[i];
			elem.column.applyTotalRowFormula(elem.formula, elem.ws, !bNoBuildDep);
1389
		}
1390 1391
		//ws
		for(var i = 0, length = this.aWorksheets.length; i < length; ++i)
1392
		{
1393 1394 1395 1396 1397 1398 1399
			var ws = this.aWorksheets[i];
			ws.initPostOpen(this.wsHandlers, bNoBuildDep);
		}
		//show active if it hidden
		var wsActive = this.getActiveWs();
		if (wsActive && wsActive.getHidden()) {
			wsActive.setHidden(false);
1400
		}
1401

1402 1403 1404
		if(!bNoBuildDep){
			this.dependencyFormulas.initOpen();
			this.dependencyFormulas.calcTree();
1405
		}
1406 1407
		if (bSnapshot) {
			this.snapshot = this._getSnapshot();
1408
		}
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
	};
	Workbook.prototype.rebuildColors=function(){
		AscCommonExcel.g_oColorManager.rebuildColors();
		for(var i = 0 , length = this.aWorksheets.length; i < length; ++i)
			this.aWorksheets[i].rebuildColors();
	};
	Workbook.prototype.getDefaultFont=function(){
		return g_oDefaultFormat.Font.getName();
	};
	Workbook.prototype.getDefaultSize=function(){
		return g_oDefaultFormat.Font.getSize();
	};
	Workbook.prototype.getActive=function(){
		return this.nActive;
	};
	Workbook.prototype.getActiveWs = function () {
		return this.getWorksheet(this.nActive);
	};
	Workbook.prototype.setActive=function(index){
		if(index >= 0 && index < this.aWorksheets.length){
			this.nActive = index;
			return true;
		}
		return false;
	};
1434 1435 1436 1437
	Workbook.prototype.setActiveById=function(sheetId){
		var ws = this.getWorksheetById(sheetId);
		return this.setActive(ws.getIndex());
	};
konovalovsergey's avatar
konovalovsergey committed
1438 1439 1440 1441
	Workbook.prototype.getSheetIdByIndex = function(index) {
		var ws = this.getWorksheet(index);
		return ws ? ws.getId() : null;
	};
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
	Workbook.prototype.getWorksheet=function(index){
		//index 0-based
		if(index >= 0 && index < this.aWorksheets.length){
			return this.aWorksheets[index];
		}
		return null;
	};
	Workbook.prototype.getWorksheetById=function(id){
		return this.aWorksheetsById[id];
	};
	Workbook.prototype.getWorksheetByName=function(name){
		for(var i = 0; i < this.aWorksheets.length; i++)
			if(this.aWorksheets[i].getName() == name){
				return this.aWorksheets[i];
1456
			}
1457 1458 1459 1460 1461 1462
		return null;
	};
	Workbook.prototype.getWorksheetIndexByName=function(name){
		for(var i = 0; i < this.aWorksheets.length; i++)
			if(this.aWorksheets[i].getName() == name){
				return i;
1463
			}
1464 1465 1466 1467 1468 1469 1470
		return null;
	};
	Workbook.prototype.getWorksheetCount=function(){
		return this.aWorksheets.length;
	};
	Workbook.prototype.createWorksheet=function(indexBefore, sName, sId){
		History.Create_NewPoint();
1471
		History.TurnOff();
1472
		var wsActive = this.getActiveWs();
1473 1474 1475 1476 1477 1478 1479
		var oNewWorksheet = new Woorksheet(this, this.aWorksheets.length, sId);
		if (this.checkValidSheetName(sName))
			oNewWorksheet.sName = sName;
		oNewWorksheet.initPostOpen(this.wsHandlers);
		if(null != indexBefore && indexBefore >= 0 && indexBefore < this.aWorksheets.length)
			this.aWorksheets.splice(indexBefore, 0, oNewWorksheet);
		else
1480
		{
1481 1482
			indexBefore = this.aWorksheets.length;
			this.aWorksheets.push(oNewWorksheet);
1483
		}
1484
		this.aWorksheetsById[oNewWorksheet.getId()] = oNewWorksheet;
1485
		this._updateWorksheetIndexes(wsActive);
1486
		History.TurnOn();
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
		this._insertWorksheetFormula(oNewWorksheet.index);
		History.Add(AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_SheetAdd, null, null, new UndoRedoData_SheetAdd(indexBefore, oNewWorksheet.getName(), null, oNewWorksheet.getId()));
		History.SetSheetUndo(wsActive.getId());
		History.SetSheetRedo(oNewWorksheet.getId());
		return oNewWorksheet.index;
	};
	Workbook.prototype.copyWorksheet=function(index, insertBefore, sName, sId, bFromRedo, tableNames){
		//insertBefore - optional
		if(index >= 0 && index < this.aWorksheets.length){
			//buildRecalc вызываем чтобы пересчиталося cwf(может быть пустым если сделать сдвиг формул и скопировать лист)
			this.dependencyFormulas.buildDependency();
			History.TurnOff();
			var wsActive = this.getActiveWs();
			var wsFrom = this.aWorksheets[index];
			var newSheet = new Woorksheet(this, -1, sId);
			if(null != insertBefore && insertBefore >= 0 && insertBefore < this.aWorksheets.length){
				//помещаем новый sheet перед insertBefore
				this.aWorksheets.splice(insertBefore, 0, newSheet);
			}
			else{
				//помещаем новый sheet в конец
				this.aWorksheets.push(newSheet);
			}
			this.aWorksheetsById[newSheet.getId()] = newSheet;
			this._updateWorksheetIndexes(wsActive);
			//copyFrom after sheet add because formula assemble dependce on sheet structure
			var renameParams = newSheet.copyFrom(wsFrom, sName, tableNames);
			newSheet.initPostOpen(this.wsHandlers);
			History.TurnOn();
1516

1517 1518 1519
			this.dependencyFormulas.copyDefNameByWorksheet(wsFrom, newSheet, renameParams);
			//для формул. создаем копию this.cwf[this.Id] для нового листа.
			//newSheet._BuildDependencies(wsFrom.getCwf());
1520

1521 1522
			//now insertBefore is index of inserted sheet
			this._insertWorksheetFormula(insertBefore);
1523

1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
			if (!tableNames) {
				tableNames = newSheet.getTableNames();
			}

			History.Add(AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_SheetAdd, null, null, new UndoRedoData_SheetAdd(insertBefore, newSheet.getName(), wsFrom.getId(), newSheet.getId(), tableNames));
			History.SetSheetUndo(wsActive.getId());
			History.SetSheetRedo(newSheet.getId());
			if(!(bFromRedo === true))
			{
				wsFrom.copyDrawingObjects(newSheet, wsFrom);
			}
			this.sortDependency();
1536
		}
1537 1538
	};
	Workbook.prototype.insertWorksheet = function (index, sheet) {
1539
		var wsActive = this.getActiveWs();
1540 1541 1542
		if(null != index && index >= 0 && index < this.aWorksheets.length){
			//помещаем новый sheet перед insertBefore
			this.aWorksheets.splice(index, 0, sheet);
1543
		}
1544 1545 1546 1547 1548
		else{
			//помещаем новый sheet в конец
			this.aWorksheets.push(sheet);
		}
		this.aWorksheetsById[sheet.getId()] = sheet;
1549
		this._updateWorksheetIndexes(wsActive);
1550 1551 1552 1553 1554 1555 1556 1557
		this._insertWorksheetFormula(index);
		this._insertTablePartsName(sheet);
		//восстанавливаем список ячеек с формулами для sheet
		sheet._BuildDependencies(sheet.getCwf());
		this.sortDependency();
	};
	Workbook.prototype._insertTablePartsName = function (sheet) {
		if(sheet && sheet.TableParts && sheet.TableParts.length)
1558
		{
1559 1560 1561 1562 1563 1564
			for(var i = 0; i < sheet.TableParts.length; i++)
			{
				var tablePart = sheet.TableParts[i];
				this.dependencyFormulas.addTableName(sheet, tablePart);
				tablePart.buildDependencies();
			}
1565 1566
		}
	};
1567 1568 1569 1570
	Workbook.prototype._insertWorksheetFormula=function(index){
		if( index > 0 && index < this.aWorksheets.length ) {
			var oWsBefore = this.aWorksheets[index - 1];
			this.dependencyFormulas.changeSheet(oWsBefore.getId(), {insert: index});
1571
		}
1572 1573 1574 1575 1576 1577 1578
	};
	Workbook.prototype.replaceWorksheet=function(indexFrom, indexTo){
		if(indexFrom >= 0 && indexFrom < this.aWorksheets.length &&
			indexTo >= 0 && indexTo < this.aWorksheets.length){
			var wsActive = this.getActiveWs();
			var oWsFrom = this.aWorksheets[indexFrom];
			var tempW = {
1579
				wF: oWsFrom,
1580 1581 1582 1583 1584 1585 1586
				wFI: indexFrom,
				wTI: indexTo
			};
			//wTI index insert before
			if(tempW.wFI < tempW.wTI)
				tempW.wTI++;
			this.dependencyFormulas.lockRecal();
1587
			var collectDependencies = [];
1588
			this.dependencyFormulas.changeSheet(oWsFrom.getId(), {replace: tempW}, null, collectDependencies);
1589
			//move sheets
1590 1591 1592
			var movedSheet = this.aWorksheets.splice(indexFrom, 1);
			this.aWorksheets.splice(indexTo, 0, movedSheet[0]);
			this._updateWorksheetIndexes(wsActive);
1593 1594 1595 1596
			//buildDependencies after move sheet for cArea3d
			for (var i = 0; i < collectDependencies.length; ++i) {
				collectDependencies[i].buildDependencies();
			}
1597

1598
			this._insertWorksheetFormula(indexTo);
1599

1600 1601
			History.Add(AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_SheetMove, null, null, new UndoRedoData_FromTo(indexFrom, indexTo));
			this.dependencyFormulas.unlockRecal();
1602
		}
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612
	};
	Workbook.prototype.findSheetNoHidden = function (nIndex) {
		var i, ws, oRes = null, bFound = false, countWorksheets = this.getWorksheetCount();
		for (i = nIndex; i < countWorksheets; ++i) {
			ws = this.getWorksheet(i);
			if (false === ws.getHidden()) {
				oRes = ws;
				bFound = true;
				break;
			}
1613
		}
1614 1615 1616 1617 1618 1619 1620 1621 1622
		// Не нашли справа, ищем слева от текущего
		if (!bFound) {
			for (i = nIndex - 1; i >= 0; --i) {
				ws = this.getWorksheet(i);
				if (false === ws.getHidden()) {
					oRes = ws;
					break;
				}
			}
1623
		}
1624 1625 1626 1627 1628 1629
		return oRes;
	};
	Workbook.prototype.removeWorksheet=function(nIndex, outputParams){
		//проверяем останется ли хоть один нескрытый sheet
		var bEmpty = true;
		for(var i = 0, length = this.aWorksheets.length; i < length; ++i)
1630
		{
1631 1632
			var worksheet = this.aWorksheets[i];
			if(false == worksheet.getHidden() && i != nIndex)
1633
			{
1634 1635
				bEmpty = false;
				break;
1636 1637
			}
		}
1638 1639 1640 1641 1642 1643 1644 1645
		if(bEmpty)
			return -1;

		var removedSheet = this.getWorksheet(nIndex);
		if(removedSheet)
		{
			var removedSheetId = removedSheet.getId();
			this.dependencyFormulas.lockRecal();
1646 1647 1648
			var collectDependencies = [];
			this.dependencyFormulas.removeSheet(removedSheetId, removedSheet.getTableNames(), collectDependencies);
			//delete sheet
1649 1650 1651 1652
			var wsActive = this.getActiveWs();
			var oVisibleWs = null;
			this.aWorksheets.splice(nIndex, 1);
			delete this.aWorksheetsById[removedSheetId];
1653 1654 1655 1656
			//buildDependencies after move sheet for cArea3d
			for (var i = 0; i < collectDependencies.length; ++i) {
				collectDependencies[i].buildDependencies();
			}
1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
			if (nIndex == this.getActive()) {
				oVisibleWs = this.findSheetNoHidden(nIndex);
				if (null != oVisibleWs)
					wsActive = oVisibleWs;
			}
			History.Add(AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_SheetRemove, null, null, new AscCommonExcel.UndoRedoData_SheetRemove(nIndex, removedSheetId, removedSheet));
			if (null != oVisibleWs) {
				History.SetSheetUndo(removedSheetId);
				History.SetSheetRedo(wsActive.getId());
			}
			if(null != outputParams)
1668
			{
1669
				outputParams.sheet = removedSheet;
1670
			}
1671 1672 1673
			this._updateWorksheetIndexes(wsActive);
			this.dependencyFormulas.unlockRecal();
			return wsActive.getIndex();
1674
		}
1675
		return -1;
1676
	};
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
	Workbook.prototype._updateWorksheetIndexes = function (wsActive) {
		for(var i = 0, length = this.aWorksheets.length; i < length; ++i)
			this.aWorksheets[i]._setIndex(i);
		if (null != wsActive)
			this.setActive(wsActive.getIndex());
	};
	Workbook.prototype.checkUniqueSheetName=function(name){
		var workbookSheetCount = this.getWorksheetCount();
		for (var i = 0; i < workbookSheetCount; i++){
			if (this.getWorksheet(i).getName() == name)
				return i;
1688
		}
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
		return -1;
	};
	Workbook.prototype.checkValidSheetName=function(name){
		return (name && name.length < g_nSheetNameMaxLength);
	};
	Workbook.prototype.getUniqueSheetNameFrom=function(name, bCopy){
		var nIndex = 1;
		var sNewName = "";
		var fGetPostfix = null;
		if(bCopy)
1699
		{
1700 1701 1702 1703 1704 1705 1706

			var result = /^(.*)\((\d)\)$/.exec(name);
			if(result)
			{
				fGetPostfix = function(nIndex){return "(" + nIndex +")";};
				name = result[1];
			}
1707
			else
1708 1709 1710 1711
			{
				fGetPostfix = function(nIndex){return " (" + nIndex +")";};
				name = name;
			}
1712 1713
		}
		else
1714
		{
1715
			fGetPostfix = function(nIndex){return nIndex.toString();};
1716
		}
1717 1718
		var workbookSheetCount = this.getWorksheetCount();
		while(nIndex < 10000)
1719
		{
1720
			var sPosfix = fGetPostfix(nIndex);
1721
			sNewName = name + sPosfix;
1722
			if(sNewName.length > g_nSheetNameMaxLength)
1723
			{
1724 1725 1726 1727 1728 1729
				name = name.substring(0, g_nSheetNameMaxLength - sPosfix.length);
				sNewName = name + sPosfix;
			}
			var bUniqueName = true;
			for (var i = 0; i < workbookSheetCount; i++){
				if (this.getWorksheet(i).getName() == sNewName)
Igor.Zotov's avatar
Igor.Zotov committed
1730
				{
1731 1732
					bUniqueName = false;
					break;
1733
				}
1734
			}
1735 1736 1737
			if(bUniqueName)
				break;
			nIndex++;
1738
		}
1739
		return sNewName;
1740
	};
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
	Workbook.prototype._generateFontMap=function(){
		var oFontMap = {
			"Arial"		: 1
		};

		oFontMap[g_oDefaultFormat.Font.getName()] = 1;

		for(var i = 0, length = this.aWorksheets.length; i < length; ++i)
			this.aWorksheets[i].generateFontMap(oFontMap);
		this.CellStyles.generateFontMap(oFontMap);

		return oFontMap;
	};
	Workbook.prototype.generateFontMap=function(){
		var oFontMap = this._generateFontMap();

		var aRes = [];
		for(var i in oFontMap)
			aRes.push(i);
		return aRes;
	};
	Workbook.prototype.generateFontMap2=function(){
		var oFontMap = this._generateFontMap();

		var aRes = [];
		for(var i in oFontMap)
			aRes.push(new AscFonts.CFont(i, 0, "", 0));
		return aRes;
	};
	Workbook.prototype.getAllImageUrls = function(){
		var aImageUrls = [];
		for(var i = 0; i < this.aWorksheets.length; ++i){
			this.aWorksheets[i].getAllImageUrls(aImageUrls);
Igor.Zotov's avatar
Igor.Zotov committed
1774
		}
1775 1776 1777 1778 1779
		return aImageUrls;
	};
	Workbook.prototype.reassignImageUrls = function(oImages){
		for(var i = 0; i < this.aWorksheets.length; ++i){
			this.aWorksheets[i].reassignImageUrls(oImages);
1780
		}
1781
	};
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
	Workbook.prototype.recalcWB = function(rebuild, opt_sheetId) {
		var formulas;
		if (rebuild) {
			formulas = this.getAllFormulas();
			for (var i = 0; i < formulas.length; ++i) {
				var formula = formulas[i];
				formula.removeDependencies();
				formula.setFormula(formula.getFormula());
				formula.parse();
				formula.buildDependencies();
			}
		} else if (opt_sheetId) {
			formulas = [];
1795
			var ws = this.getWorksheetById(opt_sheetId);
1796 1797 1798 1799 1800 1801
			ws.getAllFormulas(formulas);
		} else {
			formulas = this.getAllFormulas();
		}
		this.dependencyFormulas.notifyChanged(formulas);
		this.dependencyFormulas.calcTree();
1802
	};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1803
	Workbook.prototype.checkDefName = function (checkName, scope) {
1804
		return this.dependencyFormulas.checkDefName(checkName, scope);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1805
	};
1806 1807 1808 1809 1810 1811
	Workbook.prototype.getDefinedNamesWB = function (defNameListId) {
		return this.dependencyFormulas.getDefinedNamesWB(defNameListId);
	};
	Workbook.prototype.getDefinesNames = function ( name, sheetId ) {
		return this.dependencyFormulas.getDefNameByName( name, sheetId );
	};
konovalovsergey's avatar
konovalovsergey committed
1812 1813 1814 1815
	Workbook.prototype.getDefinedName = function(name) {
		var sheetId = this.getSheetIdByIndex(name.LocalSheetId);
		return this.dependencyFormulas.getDefNameByName(name.Name, sheetId);
	};
1816 1817 1818
	Workbook.prototype.delDefinesNames = function ( defName ) {
		this.delDefinesNamesUndoRedo(this.getUndoDefName(defName));
	};
1819 1820 1821 1822
	Workbook.prototype.delDefinesNamesUndoRedo = function ( defName ) {
		this.dependencyFormulas.removeDefName( defName.sheetId, defName.name );
		this.dependencyFormulas.calcTree();
	};
1823 1824 1825
	Workbook.prototype.editDefinesNames = function ( oldName, newName ) {
		return this.editDefinesNamesUndoRedo(this.getUndoDefName(oldName), this.getUndoDefName(newName));
	};
1826 1827 1828 1829 1830
	Workbook.prototype.editDefinesNamesUndoRedo = function ( oldName, newName ) {
		var res = this.dependencyFormulas.editDefinesNames( oldName, newName );
		this.dependencyFormulas.calcTree();
		return res;
	};
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855
	Workbook.prototype.findDefinesNames = function ( ref, sheetId ) {
		return this.dependencyFormulas.getDefNameByRef( ref, sheetId );
	};
	Workbook.prototype.unlockDefName = function(){
		this.dependencyFormulas.unlockDefName();
	};
	Workbook.prototype.checkDefNameLock = function(){
		return this.dependencyFormulas.checkDefNameLock();
	};
	Workbook.prototype._SerializeHistoryBase64 = function (oMemory, item, aPointChangesBase64) {
		if (!item.LocalChange) {
			var nPosStart = oMemory.GetCurPosition();
			item.Serialize(oMemory, this.oApi.collaborativeEditing);
			var nPosEnd = oMemory.GetCurPosition();
			var nLen = nPosEnd - nPosStart;
			if (nLen > 0)
				aPointChangesBase64.push(nLen + ";" + oMemory.GetBase64Memory2(nPosStart, nLen));
		}
	};
	Workbook.prototype.SerializeHistory = function(){
		var aRes = [];
		//соединяем изменения, которые были до приема данных с теми, что получились после.

		var worksheets = this.aWorksheets, t, j, length2;
		for(t = 0; t < worksheets.length; ++t)
1856
		{
1857
			worksheets[t] && worksheets[t].refreshContentChanges();
1858
		}
1859 1860
		var aActions = this.aCollaborativeActions.concat(History.GetSerializeArray());
		if(aActions.length > 0)
1861
		{
1862 1863 1864 1865 1866 1867 1868 1869
			var oMemory = new AscCommon.CMemory();
			for(var i = 0, length = aActions.length; i < length; ++i)
			{
				var aPointChanges = aActions[i];
				for (j = 0, length2 = aPointChanges.length; j < length2; ++j) {
					var item = aPointChanges[j];
					this._SerializeHistoryBase64(oMemory, item, aRes);
				}
1870
			}
1871 1872 1873 1874 1875
			this.aCollaborativeActions = [];
			this.snapshot = this._getSnapshot();
		}
		return aRes;
	};
1876 1877 1878 1879 1880 1881 1882 1883
	Workbook.prototype._getSnapshot = function() {
		var wb = new Workbook(new AscCommonExcel.asc_CHandlersList(), this.oApi);
		wb.dependencyFormulas = this.dependencyFormulas.getSnapshot(wb);
		for (var i = 0; i < this.aWorksheets.length; ++i) {
			var ws = this.aWorksheets[i].getSnapshot(wb);
			wb.aWorksheets.push(ws);
			wb.aWorksheetsById[ws.getId()] = ws;
		}
1884 1885
		//init trigger
		wb.init({}, true, false);
1886 1887
		return wb;
	};
1888 1889 1890 1891 1892 1893 1894 1895
	Workbook.prototype.getAllFormulas = function() {
		var res = [];
		this.dependencyFormulas.getAllFormulas(res);
		for (var i = 0; i < this.aWorksheets.length; ++i) {
			this.aWorksheets[i].getAllFormulas(res);
		}
		return res;
	};
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
	Workbook.prototype._forwardTransformation = function(wbSnapshot, changesMine, changesTheir) {
		History.TurnOff();
		//first mine changes to resolve conflict sheet names
		var res1 = this._forwardTransformationGetTransform(wbSnapshot, changesTheir, changesMine);
		var res2 = this._forwardTransformationGetTransform(wbSnapshot, changesMine, changesTheir);
		//modify formulas at the end - to prevent negative effect during tranformation
		var i, elem, elemWrap;
		for (i = 0; i < res1.modify.length; ++i) {
			elemWrap = res1.modify[i];
			elem = elemWrap.elem;
			elem.oClass.forwardTransformationSet(elem.nActionType, elem.oData, elem.nSheetId, elemWrap);
		}
		for (i = 0; i < res2.modify.length; ++i) {
			elemWrap = res2.modify[i];
			elem = elemWrap.elem;
			elem.oClass.forwardTransformationSet(elem.nActionType, elem.oData, elem.nSheetId, elemWrap);
		}
		//rename current wb
		for (var oldName in res1.renameSheet) {
			var ws = this.getWorksheetByName(oldName);
			if (ws) {
				ws.setName(res1.renameSheet[oldName]);
1918
			}
1919
		}
1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
		History.TurnOn();
	};
	Workbook.prototype._forwardTransformationGetTransform = function(wbSnapshot, changesMaster, changesModify) {
		var res = {modify: [], renameSheet: {}};
		var changesMasterSelected = [];
		var i, elem;
		if (changesModify.length > 0) {
			//select useful master changes
			for ( i = 0; i < changesMaster.length; ++i) {
				elem = changesMaster[i];
				if (elem.oClass && elem.oClass.forwardTransformationIsAffect &&
					elem.oClass.forwardTransformationIsAffect(elem.nActionType)) {
					changesMasterSelected.push(elem);
				}
1934 1935
			}
		}
1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
		if (changesMasterSelected.length > 0 && changesModify.length > 0) {
			var wbSnapshotCur = wbSnapshot._getSnapshot();
			var formulas = [];
			for (i = 0; i < changesModify.length; ++i) {
				elem = changesModify[i];
				var renameRes = null;
				if (elem.oClass && elem.oClass.forwardTransformationGet) {
					var getRes = elem.oClass.forwardTransformationGet(elem.nActionType, elem.oData, elem.nSheetId);
					if (getRes && getRes.formula) {
						//inserted formulas
1946
						formulas.push(new ForwardTransformationFormula(elem, getRes.formula, null));
1947 1948 1949 1950 1951 1952 1953
					}
					if (getRes && getRes.name) {
						//add/rename sheet
						//get getUniqueSheetNameFrom if need
						renameRes = this._forwardTransformationRenameStart(wbSnapshotCur._getSnapshot(),
																		   changesMasterSelected, getRes);
					}
1954
				}
1955 1956 1957 1958 1959 1960 1961
				if (elem.oClass && elem.oClass.forwardTransformationIsAffect &&
					elem.oClass.forwardTransformationIsAffect(elem.nActionType)) {
					if (formulas.length > 0) {
						//modify all formulas before apply next change
						this._forwardTransformationFormula(wbSnapshotCur._getSnapshot(), formulas,
														   changesMasterSelected, res);
						formulas = [];
1962
					}
1963 1964 1965 1966 1967 1968
					//apply useful mine change
					elem.oClass.Redo(elem.nActionType, elem.oData, elem.nSheetId, wbSnapshotCur);
				}
				if (renameRes) {
					this._forwardTransformationRenameEnd(renameRes, res.renameSheet, getRes, elem);
				}
1969
			}
1970
			this._forwardTransformationFormula(wbSnapshotCur, formulas, changesMasterSelected, res);
1971
		}
1972 1973 1974 1975 1976 1977 1978
		return res;
	};
	Workbook.prototype._forwardTransformationRenameStart = function(wbSnapshot, changes, getRes) {
		var res = {newName: null};
		for (var i = 0; i < changes.length; ++i) {
			var elem = changes[i];
			elem.oClass.Redo(elem.nActionType, elem.oData, elem.nSheetId, wbSnapshot);
1979
		}
1980 1981
		if (-1 != wbSnapshot.checkUniqueSheetName(getRes.name)) {
			res.newName = wbSnapshot.getUniqueSheetNameFrom(getRes.name, true);
1982
		}
1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
		return res;
	};
	Workbook.prototype._forwardTransformationRenameEnd = function(renameRes, renameSheet, getRes, elemCur) {
		var isChange = false;
		if (getRes.from) {
			var renameCur = renameSheet[getRes.from];
			if (renameCur) {
				//no need rename next formulas
				delete renameSheet[getRes.from];
				getRes.from = renameCur;
				isChange = true;
			}
		}
		if (renameRes && renameRes.newName) {
			renameSheet[getRes.name] = renameRes.newName;
			getRes.name = renameRes.newName;
			isChange = true;
		}
		//apply immediately cause it is conflict
		if (isChange && elemCur.oClass.forwardTransformationSet) {
			elemCur.oClass.forwardTransformationSet(elemCur.nActionType, elemCur.oData, elemCur.nSheetId, getRes);
2004
		}
2005 2006 2007
	};
	Workbook.prototype._forwardTransformationFormula = function(wbSnapshot, formulas, changes, res) {
		if (formulas.length > 0) {
2008
			var i, elem, ftFormula, ws;
2009 2010
			//parse formulas
			for (i = 0; i < formulas.length; ++i) {
2011 2012
				ftFormula = formulas[i];
				ws = wbSnapshot.getWorksheetById(ftFormula.elem.nSheetId);
2013
				if (ws) {
2014 2015 2016
					ftFormula.parsed = new parserFormula(ftFormula.formula, ftFormula, ws);
					ftFormula.parsed.parse();
					ftFormula.parsed.buildDependencies();
2017
				}
2018
			}
2019 2020 2021 2022 2023
			//rename sheet first to prevent name conflict
			for (var oldName in res.renameSheet) {
				ws = wbSnapshot.getWorksheetByName(oldName);
				if (ws) {
					ws.setName(res.renameSheet[oldName]);
2024
				}
2025 2026 2027 2028 2029 2030 2031 2032
			}
			//apply useful theirs changes
			for (i = 0; i < changes.length; ++i) {
				elem = changes[i];
				elem.oClass.Redo(elem.nActionType, elem.oData, elem.nSheetId, wbSnapshot);
			}
			//assemble
			for (i = 0; i < formulas.length; ++i) {
2033 2034 2035 2036
				ftFormula = formulas[i];
				if (ftFormula.parsed) {
					ftFormula.parsed.removeDependencies();
					res.modify.push(ftFormula);
2037
				}
2038
			}
2039
		}
2040
	};
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051
	Workbook.prototype.DeserializeHistory = function(aChanges, fCallback){
		var oThis = this;
		//сохраняем те изменения, которые были до приема данных, потому что дальше undo/redo будет очищено
		this.aCollaborativeActions = this.aCollaborativeActions.concat(History.GetSerializeArray());
		if(aChanges.length > 0)
		{
			this.bCollaborativeChanges = true;
			//собираем общую длину
			var dstLen = 0;
			var aIndexes = [], i, length = aChanges.length, sChange;
			for(i = 0; i < length; ++i)
2052
			{
2053 2054 2055 2056 2057
				sChange = aChanges[i];
				var nIndex = sChange.indexOf(";");
				if (-1 != nIndex) {
					dstLen += parseInt(sChange.substring(0, nIndex));
					nIndex++;
2058
				}
2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076
				aIndexes.push(nIndex);
			}
			var pointer = g_memory.Alloc(dstLen);
			var stream = new AscCommon.FT_Stream2(pointer.data, dstLen);
			stream.obj = pointer.obj;
			var nCurOffset = 0;
			//пробегаемся первый раз чтобы заполнить oFontMap
			var oFontMap = {};//собираем все шрифтры со всех изменений
			var aUndoRedoElems = [];
			for (i = 0; i < length; ++i) {
				sChange = aChanges[i];
				var oBinaryFileReader = new AscCommonExcel.BinaryFileReader();
				nCurOffset = oBinaryFileReader.getbase64DecodedData2(sChange, aIndexes[i], stream, nCurOffset);
				var item = new UndoRedoItemSerializable();
				item.Deserialize(stream);
				if (AscCommonExcel.g_oUndoRedoWorkbook == item.oClass && AscCH.historyitem_Workbook_AddFont == item.nActionType) {
					for (var k = 0, length3 = item.oData.elem.length; k < length3; ++k)
						oFontMap[item.oData.elem[k]] = 1;
2077
				}
2078
				aUndoRedoElems.push(item);
2079
			}
2080

2081 2082 2083 2084
			window["Asc"]["editor"]._loadFonts(oFontMap, function(){
				var wsViews = window["Asc"]["editor"].wb.wsViews;
				if(oThis.oApi.collaborativeEditing.getFast()){
					AscCommon.CollaborativeEditing.Clear_DocumentPositions();
2085
				}
2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101
				for (var i in wsViews) {
					if (isRealObject(wsViews[i]) && isRealObject(wsViews[i].objectRender) &&
						isRealObject(wsViews[i].objectRender.controller)) {
						wsViews[i].endEditChart();
						if (oThis.oApi.collaborativeEditing.getFast()) {
							var oState = wsViews[i].objectRender.saveStateBeforeLoadChanges();
							if (oState) {
								if (oState.Pos) {
									AscCommon.CollaborativeEditing.Add_DocumentPosition(oState.Pos);
								}
								if (oState.StartPos) {
									AscCommon.CollaborativeEditing.Add_DocumentPosition(oState.StartPos);
								}
								if (oState.EndPos) {
									AscCommon.CollaborativeEditing.Add_DocumentPosition(oState.EndPos);
								}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2102 2103
							}
						}
2104
						wsViews[i].objectRender.controller.resetSelection();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2105
					}
2106
				}
2107 2108 2109
				oFormulaLocaleInfo.Parse = false;
				oFormulaLocaleInfo.DigitSep = false;
				History.Clear();
2110
				History.Create_NewPoint();
2111

2112 2113
				History.SetSelection(null);
				History.SetSelectionRedo(null);
2114
				var oRedoObjectParam = new AscCommonExcel.RedoObjectParam();
2115
				History.UndoRedoPrepare(oRedoObjectParam, false);
2116 2117
				var changesMine = [].concat.apply([], oThis.aCollaborativeActions);
				oThis._forwardTransformation(oThis.snapshot, changesMine, aUndoRedoElems);
2118
				for (var i = 0, length = aUndoRedoElems.length; i < length; ++i)
2119
				{
2120 2121 2122 2123 2124 2125 2126 2127 2128 2129
					var item = aUndoRedoElems[i];
					if ((null != item.oClass || (item.oData && typeof item.oData.sChangedObjectId === "string")) && null != item.nActionType) {
						if (window["NATIVE_EDITOR_ENJINE"] === true && window["native"]["CheckNextChange"]) {
							if (!window["native"]["CheckNextChange"]())
								break;
						}
						// TODO if(g_oUndoRedoGraphicObjects == item.oClass && item.oData.drawingData)
						//     item.oData.drawingData.bCollaborativeChanges = true;
						History.RedoAdd(oRedoObjectParam, item.oClass, item.nActionType, item.nSheetId, item.oRange, item.oData);
					}
2130
				}
2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150
				if(oThis.oApi.collaborativeEditing.getFast()){


					for(var i in wsViews){
						if(isRealObject(wsViews[i]) && isRealObject(wsViews[i].objectRender) && isRealObject(wsViews[i].objectRender.controller)){
							var oState = wsViews[i].objectRender.getStateBeforeLoadChanges();
							if(oState){
								if (oState.Pos)
									AscCommon.CollaborativeEditing.Update_DocumentPosition(oState.Pos);
								if (oState.StartPos)
									AscCommon.CollaborativeEditing.Update_DocumentPosition(oState.StartPos);
								if (oState.EndPos)
									AscCommon.CollaborativeEditing.Update_DocumentPosition(oState.EndPos);
							}
							wsViews[i].objectRender.loadStateAfterLoadChanges();
						}
					}
				}
				oFormulaLocaleInfo.Parse = true;
				oFormulaLocaleInfo.DigitSep = true;
2151
				History.UndoRedoEnd(null, oRedoObjectParam, false);
2152

2153
				oThis.bCollaborativeChanges = false;
2154 2155
				//make snapshot for faormulas
				oThis.snapshot = oThis._getSnapshot();
2156 2157 2158 2159 2160
				History.Clear();
				if(null != fCallback)
					fCallback();
			});
		}
2161 2162 2163
	};
	Workbook.prototype.DeserializeHistoryNative = function(oRedoObjectParam, data, isFull){
		if(null != data)
2164
		{
2165
			this.bCollaborativeChanges = true;
2166

2167
			if(null == oRedoObjectParam)
2168
			{
2169 2170 2171 2172 2173 2174
				var wsViews = window["Asc"]["editor"].wb.wsViews;
				for (var i in wsViews) {
					if (isRealObject(wsViews[i]) && isRealObject(wsViews[i].objectRender) &&
						isRealObject(wsViews[i].objectRender.controller)) {
						wsViews[i].endEditChart();
						wsViews[i].objectRender.controller.resetSelection();
2175 2176
					}
				}
2177 2178 2179 2180 2181 2182 2183

				History.Clear();
				History.Create_NewPoint();
				History.SetSelection(null);
				History.SetSelectionRedo(null);
				oRedoObjectParam = new AscCommonExcel.RedoObjectParam();
				History.UndoRedoPrepare(oRedoObjectParam, false);
2184
			}
2185 2186 2187 2188 2189 2190 2191

			var stream = new AscCommon.FT_Stream2(data, data.length);
			stream.obj = null;
			// Применяем изменения, пока они есть
			var _count = stream.GetLong();
			var _pos = 4;
			for (var i = 0; i < _count; i++)
2192
			{
2193
				if (window["NATIVE_EDITOR_ENJINE"] === true && window["native"]["CheckNextChange"])
2194
				{
2195 2196
					if (!window["native"]["CheckNextChange"]())
						break;
2197
				}
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213

				var _len = stream.GetLong();

				_pos += 4;
				stream.size = _pos + _len;
				stream.Seek(_pos);
				stream.Seek2(_pos);

				var item = new UndoRedoItemSerializable();
				item.Deserialize(stream);
				if ((null != item.oClass || (item.oData && typeof item.oData.sChangedObjectId === "string")) && null != item.nActionType)
					History.RedoAdd(oRedoObjectParam, item.oClass, item.nActionType, item.nSheetId, item.oRange, item.oData);

				_pos += _len;
				stream.Seek2(_pos);
				stream.size = data.length;
2214
			}
2215 2216 2217 2218 2219

			if(isFull){
				History.UndoRedoEnd(null, oRedoObjectParam, false);
				History.Clear();
				oRedoObjectParam = null;
2220
			}
2221
			this.bCollaborativeChanges = false;
2222
		}
2223
		return oRedoObjectParam;
2224
	};
2225 2226 2227 2228 2229 2230 2231 2232 2233 2234
	Workbook.prototype.getTableRangeForFormula = function(name, objectParam){
		var res = null;
		for(var i = 0, length = this.aWorksheets.length; i < length; ++i)
		{
			var ws = this.aWorksheets[i];
			res = ws.getTableRangeForFormula(name, objectParam);
			if(res !== null){
				res = {wsID:ws.getId(),range:res};
				break;
			}
2235
		}
2236
		return res;
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247
	};
	Workbook.prototype.getTableIndexColumnByName = function(tableName, columnName){
		var res = null;
		for(var i = 0, length = this.aWorksheets.length; i < length; ++i)
		{
			var ws = this.aWorksheets[i];
			res = ws.getTableIndexColumnByName(tableName, columnName);
			if(res !== null){
				res = {wsID:ws.getId(), index: res, name: columnName};
				break;
			}
2248 2249
		}
		return res;
2250 2251 2252 2253 2254 2255 2256 2257 2258
	};
	Workbook.prototype.getTableNameColumnByIndex = function(tableName, columnIndex){
		var res = null;
		for(var i = 0, length = this.aWorksheets.length; i < length; ++i)
		{
			var ws = this.aWorksheets[i];
			res = ws.getTableNameColumnByIndex(tableName, columnIndex);
			if(res !== null){
				res = {wsID:ws.getId(), columnName: res};
2259 2260
				break;
			}
2261
		}
2262 2263 2264 2265 2266 2267 2268 2269 2270
		return res;
	};
	Workbook.prototype.updateSparklineCache = function (sheet, ranges) {
		for (var i = 0; i < this.aWorksheets.length; ++i) {
			this.aWorksheets[i].updateSparklineCache(sheet, ranges);
		}
	};
	Workbook.prototype.sortDependency = function (setCellFormat) {
		this.dependencyFormulas.calcTree();
2271
	};
2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282
	/**
	 * Вычисляет ширину столбца для заданного количества символов
	 * @param {Number} count  Количество символов
	 * @returns {Number}      Ширина столбца в символах
	 */
	Workbook.prototype.charCountToModelColWidth = function (count) {
		if (count <= 0) {
			return 0;
		}
		return Asc.floor((count * this.maxDigitWidth + this.paddingPlusBorder) / this.maxDigitWidth * 256) / 256;
	};
2283
	Workbook.prototype.getUndoDefName = function(ascName) {
2284 2285 2286
		if (!ascName) {
			return ascName;
		}
2287 2288 2289
		var sheetId = this.getSheetIdByIndex(ascName.LocalSheetId);
		return new UndoRedoData_DefinedNames(ascName.Name, ascName.Ref, sheetId, ascName.isTable);
	};
2290 2291 2292 2293 2294 2295
	Workbook.prototype.changeColorScheme = function (index) {
		var scheme = AscCommon.getColorThemeByIndex(index);
		if (!scheme) {
			index -= AscCommon.g_oUserColorScheme.length;
			if (index < 0 || index >= this.theme.extraClrSchemeLst.length) {
				return false;
2296
			}
2297 2298

			scheme = this.theme.extraClrSchemeLst[index].clrScheme.createDuplicate();
2299
		}
2300 2301 2302 2303 2304 2305 2306 2307
		History.Create_NewPoint();
		//не делаем Duplicate потому что предполагаем что схема не будет менять частями, а только обьектом целиком.
		History.Add(AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_ChangeColorScheme, null,
			null, new AscCommonExcel.UndoRedoData_ClrScheme(this.theme.themeElements.clrScheme, scheme));
		this.theme.themeElements.clrScheme = scheme;
		this.rebuildColors();
		return true;
	};
2308
//-------------------------------------------------------------------------------------------------
2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331
	/**
	 * @constructor
	 */
	function Woorksheet(wb, _index, sId){
		this.workbook = wb;
		this.sName = this.workbook.getUniqueSheetNameFrom(g_sNewSheetNamePattern, false);
		this.bHidden = false;
		this.oSheetFormatPr = new AscCommonExcel.SheetFormatPr();
		this.index = _index;
		this.Id = null != sId ? sId : AscCommon.g_oIdCounter.Get_NewId();
		this.nRowsCount = 0;
		this.nColsCount = 0;
		this.aGCells = {};// 0 based
		this.aCols = [];// 0 based
		this.Drawings = [];
		this.TableParts = [];
		this.AutoFilter = null;
		this.oAllCol = null;
		this.aComments = [];
		this.aCommentsCoords = [];
		var oThis = this;
		this.mergeManager = new RangeDataManager(function(data, from, to){
			if(History.Is_On() && (null != from || null != to))
2332
			{
2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347
				if(null != from)
					from = from.clone();
				if(null != to)
					to = to.clone();
				var oHistoryRange = from;
				if(null == oHistoryRange)
					oHistoryRange = to;
				History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ChangeMerge, oThis.getId(), oHistoryRange, new UndoRedoData_FromTo(new UndoRedoData_BBox(from), new UndoRedoData_BBox(to)));
			}
			//расширяем границы
			if(null != to){
				if(to.r2 >= oThis.nRowsCount)
					oThis.nRowsCount = to.r2 + 1;
				if(to.c2 >= oThis.nColsCount)
					oThis.nColsCount = to.c2 + 1;
2348
			}
2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382
		});
		this.hyperlinkManager = new RangeDataManager(function(data, from, to, oChangeParam){
			if(History.Is_On() && (null != from || null != to))
			{
				if(null != from)
					from = from.clone();
				if(null != to)
					to = to.clone();
				var oHistoryRange = from;
				if(null == oHistoryRange)
					oHistoryRange = to;
				var oHistoryData = null;
				if(null == from || null == to)
					oHistoryData = data.clone();
				History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ChangeHyperlink, oThis.getId(), oHistoryRange, new AscCommonExcel.UndoRedoData_FromToHyperlink(from, to, oHistoryData));
			}
			if (null != to)
				data.Ref = oThis.getRange3(to.r1, to.c1, to.r2, to.c2);
			else if (oChangeParam && oChangeParam.removeStyle && null != data.Ref)
				data.Ref.cleanFormat();
			//расширяем границы
			if(null != to){
				if(to.r2 >= oThis.nRowsCount)
					oThis.nRowsCount = to.r2 + 1;
				if(to.c2 >= oThis.nColsCount)
					oThis.nColsCount = to.c2 + 1;
			}
		});
		this.hyperlinkManager.setDependenceManager(this.mergeManager);
		this.DrawingDocument = new AscCommon.CDrawingDocument();
		this.sheetViews = [];
		this.aConditionalFormatting = [];
		this.sheetPr = null;
		this.aFormulaExt = null;
2383

2384
		this.autoFilters = AscCommonExcel.AutoFilters !== undefined ? new AscCommonExcel.AutoFilters(this) : null;
2385

2386 2387
		this.oDrawingOjectsManager = new DrawingObjectsManager(this);
		this.contentChanges = new AscCommon.CContentChanges();
2388

2389
		this.aSparklineGroups = [];
2390

2391
		this.selectionRange = new AscCommonExcel.SelectionRange(this);
Sergey Luzyanin's avatar
Sergey Luzyanin committed
2392

2393 2394
		/*handlers*/
		this.handlers = null;
2395
	}
2396 2397 2398 2399 2400
	Woorksheet.prototype.getSnapshot = function(wb) {
		var ws = new Woorksheet(wb, this.index, this.Id);
		ws.sName = this.sName;
		for (var i = 0; i < this.TableParts.length; ++i) {
			var table = this.TableParts[i];
2401
			ws.addTablePart(table.clone(null), false);
2402
		}
2403 2404
		for (i = 0; i < this.sheetViews.length; ++i) {
			ws.sheetViews.push(this.sheetViews[i].clone());
2405
		}
2406 2407
		return ws;
	};
2408
	Woorksheet.prototype.addContentChanges = function(changes)
2409
	{
2410 2411 2412 2413
		this.contentChanges.Add(changes);
	};

	Woorksheet.prototype.refreshContentChanges = function()
2414
	{
2415 2416 2417 2418 2419 2420 2421 2422 2423 2424
		this.contentChanges.Refresh();
		this.contentChanges.Clear();
	};

	Woorksheet.prototype.rebuildColors=function(){
		this._forEachCell(function(cell){
			cell.cleanCache();
		});
		this.rebuildTabColor();

2425
		for (var i = 0; i < this.aSparklineGroups.length; ++i) {
2426
			this.aSparklineGroups[i].cleanCache();
2427 2428
		}
	};
2429 2430 2431
	Woorksheet.prototype.generateFontMap=function(oFontMap){
		//пробегаемся по Drawing
		for(var i = 0, length = this.Drawings.length; i < length; ++i)
2432
		{
2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455
			var drawing = this.Drawings[i];
			if(drawing)
				drawing.getAllFonts(oFontMap);
		}
		if(null != this.workbook.theme)
			AscFormat.checkThemeFonts(oFontMap, this.workbook.theme.themeElements.fontScheme);
		//пробегаемся по колонкам
		for(var i in this.aCols)
		{
			var col = this.aCols[i];
			if(null != col && null != col.xfs && null != col.xfs.font)
				oFontMap[col.xfs.font.getName()] = 1;
		}
		if(null != this.oAllCol && null != this.oAllCol.xfs && null != this.oAllCol.xfs.font)
			oFontMap[this.oAllCol.xfs.font.getName()] = 1;
		//пробегаемся строкам
		for(var i in this.aGCells)
		{
			var row = this.aGCells[i];
			if(null != row && null != row.xfs && null != row.xfs.font)
				oFontMap[row.xfs.font.getName()] = 1;
			//пробегаемся по ячейкам
			for(var j in row.c)
2456
			{
2457 2458
				var cell = row.c[j];
				if(null != cell)
2459
				{
2460 2461 2462 2463
					if(null != cell.xfs && null != cell.xfs.font)
						oFontMap[cell.xfs.font.getName()] = 1;
					//смотрим в комплексных строках
					if(null != cell.oValue && null != cell.oValue.multiText)
2464
					{
2465 2466 2467 2468 2469 2470
						for(var k = 0, length3 = cell.oValue.multiText.length; k < length3; ++k)
						{
							var part = cell.oValue.multiText[k];
							if(null != part.format)
								oFontMap[part.format.getName()] = 1;
						}
2471 2472
					}
				}
2473 2474 2475
			}
		}
	};
2476 2477 2478
	Woorksheet.prototype.getAllImageUrls = function(aImages){
		for(var i = 0; i < this.Drawings.length; ++i){
			this.Drawings[i].graphicObject.getAllRasterImages(aImages);
2479 2480
		}
	};
2481 2482 2483 2484
	Woorksheet.prototype.reassignImageUrls = function(oImages){
		for(var i = 0; i < this.Drawings.length; ++i){
			this.Drawings[i].graphicObject.Reassign_ImageUrls(oImages);
		}
2485
	};
2486 2487 2488 2489 2490 2491 2492 2493 2494
	Woorksheet.prototype.copyFrom=function(wsFrom, sName, tableNames){	var i, elem, range;
		this.sName = this.workbook.checkValidSheetName(sName) ? sName : this.workbook.getUniqueSheetNameFrom(wsFrom.sName, true);
		this.bHidden = wsFrom.bHidden;
		this.oSheetFormatPr = wsFrom.oSheetFormatPr.clone();
		//this.index = wsFrom.index;
		this.nRowsCount = wsFrom.nRowsCount;
		this.nColsCount = wsFrom.nColsCount;
		var renameParams = {lastName: wsFrom.getName(), newName: this.getName(), tableNameMap: {}};
		for (i = 0; i < wsFrom.TableParts.length; ++i)
2495
		{
2496 2497 2498 2499
			var tableFrom = wsFrom.TableParts[i];
			var tableTo = tableFrom.clone(null);
			if(tableNames && tableNames.length) {
				tableTo.changeDisplayName(tableNames[i]);
konovalovsergey's avatar
konovalovsergey committed
2500 2501
			} else {
				tableTo.changeDisplayName(this.workbook.dependencyFormulas.getNextTableName());
2502
			}
2503 2504
			this.addTablePart(tableTo, true);
			renameParams.tableNameMap[tableFrom.DisplayName] = tableTo.DisplayName;
2505
		}
2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519
		for (i = 0; i < this.TableParts.length; ++i) {
			this.TableParts[i].renameSheetCopy(this, renameParams);
		}
		if(wsFrom.AutoFilter)
			this.AutoFilter = wsFrom.AutoFilter.clone();
		for (i in wsFrom.aCols) {
			var col = wsFrom.aCols[i];
			if(null != col)
				this.aCols[i] = col.clone(this);
		}
		if(null != wsFrom.oAllCol)
			this.oAllCol = wsFrom.oAllCol.clone(this);
		for(i in wsFrom.aGCells){
			this.aGCells[i] = wsFrom.aGCells[i].clone(this, renameParams);
2520
		}
2521

2522 2523
		var aMerged = wsFrom.mergeManager.getAll();
		for(i in aMerged)
2524
		{
2525 2526 2527
			elem = aMerged[i];
			range = this.getRange3(elem.bbox.r1, elem.bbox.c1, elem.bbox.r2, elem.bbox.c2);
			range.mergeOpen();
2528
		}
2529 2530
		var aHyperlinks = wsFrom.hyperlinkManager.getAll();
		for(i in aHyperlinks)
2531
		{
2532 2533 2534
			elem = aHyperlinks[i];
			range = this.getRange3(elem.bbox.r1, elem.bbox.c1, elem.bbox.r2, elem.bbox.c2);
			range.setHyperlinkOpen(elem.data);
2535
		}
2536 2537 2538 2539 2540 2541
		if(null != wsFrom.aComments) {
			for (i = 0; i < wsFrom.aComments.length; i++) {
				var comment = new Asc.asc_CCommentData(wsFrom.aComments[i]);
				comment.wsId = this.getId();
				comment.nId = "sheet" + comment.wsId + "_" + (i + 1);
				this.aComments.push(comment);
2542 2543
			}
		}
2544 2545
		for (i = 0; i < wsFrom.sheetViews.length; ++i) {
			this.sheetViews.push(wsFrom.sheetViews[i].clone());
2546
		}
2547 2548
		for (i = 0; i < wsFrom.aConditionalFormatting.length; ++i) {
			this.aConditionalFormatting.push(wsFrom.aConditionalFormatting[i].clone());
2549
		}
2550 2551
		if (wsFrom.sheetPr)
			this.sheetPr = wsFrom.sheetPr.clone();
2552

2553
		this.selectionRange = wsFrom.selectionRange.clone(this);
2554

2555 2556
		return renameParams;
	};
2557 2558 2559
	Woorksheet.prototype.copyDrawingObjects = function (oNewWs, wsFrom) {
		var i;
		if (null != this.Drawings && this.Drawings.length > 0) {
2560 2561 2562
			var drawingObjects = new AscFormat.DrawingObjects();
			oNewWs.Drawings = [];
			AscFormat.NEW_WORKSHEET_DRAWING_DOCUMENT = oNewWs.DrawingDocument;
2563
			for (i = 0; i < this.Drawings.length; ++i) {
2564 2565 2566 2567 2568
				var drawingObject = drawingObjects.cloneDrawingObject(this.Drawings[i]);
				drawingObject.graphicObject = this.Drawings[i].graphicObject.copy();
				drawingObject.graphicObject.setWorksheet(oNewWs);
				drawingObject.graphicObject.addToDrawingObjects();
				var drawingBase = this.Drawings[i];
2569
				drawingObject.graphicObject.setDrawingBaseCoords(drawingBase.from.col, drawingBase.from.colOff,
2570 2571 2572
																 drawingBase.from.row, drawingBase.from.rowOff, drawingBase.to.col, drawingBase.to.colOff,
																 drawingBase.to.row, drawingBase.to.rowOff, drawingBase.Pos.X, drawingBase.Pos.Y, drawingBase.ext.cx,
																 drawingBase.ext.cy);
Sergey Luzyanin's avatar
Sergey Luzyanin committed
2573
				if(drawingObject.graphicObject.setDrawingBaseType){
2574 2575 2576
					drawingObject.graphicObject.setDrawingBaseType(drawingBase.Type);
				}
				oNewWs.Drawings[oNewWs.Drawings.length - 1] = drawingObject;
2577
			}
2578 2579
			AscFormat.NEW_WORKSHEET_DRAWING_DOCUMENT = null;
			drawingObjects.pushToAObjects(oNewWs.Drawings);
2580
			drawingObjects.updateChartReferences2(parserHelp.getEscapeSheetName(wsFrom.sName),
2581
												  parserHelp.getEscapeSheetName(oNewWs.sName));
2582 2583
		}

2584 2585 2586
		var newSparkline;
		for (i = 0; i < this.aSparklineGroups.length; ++i) {
			newSparkline = this.aSparklineGroups[i].clone();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2587
			newSparkline.setWorksheet(oNewWs, wsFrom);
2588 2589
			oNewWs.aSparklineGroups.push(newSparkline);
		}
2590
	};
2591
	Woorksheet.prototype.initPostOpen = function (handlers, bNoBuildDep) {
2592 2593 2594 2595
		if (this.aFormulaExt) {
			var formulaShared = {};
			for (var i = 0; i < this.aFormulaExt.length; ++i) {
				var elem = this.aFormulaExt[i];
2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617
				var oCell = elem.cell;
				var oFormulaExt = elem.ext;
				var isShared = oFormulaExt.t === Asc.ECellFormulaType.cellformulatypeShared && null !== oFormulaExt.si;
				if (isShared) {
					if (null !== oFormulaExt.ref) {
						if (oFormulaExt.v.length <= AscCommon.c_oAscMaxFormulaLength) {
							oCell.formulaParsed = new parserFormula(oFormulaExt.v, oCell, this);
							oCell.formulaParsed.ca = oFormulaExt.ca;
							oCell.formulaParsed.parse();
							formulaShared[oFormulaExt.si] = {
								fVal: oCell.formulaParsed,
								fRef: AscCommonExcel.g_oRangeCache.getAscRange(oFormulaExt.ref)
							};
							if (!bNoBuildDep) {
								oCell._BuildDependencies(false);
							}
						}
					} else {
						var fs = formulaShared[oFormulaExt.si];
						if (fs && fs.fRef.contains(oCell.nCol, oCell.nRow)) {
							if (fs.fVal.isParsed) {
								var off = oCell.getOffset3(fs.fRef.c1 + 1, fs.fRef.r1 + 1);
2618

2619 2620 2621
								oCell.formulaParsed = fs.fVal.clone(null, oCell, this);
								oCell.formulaParsed.ca = oFormulaExt.ca;
								oCell.formulaParsed.changeOffset(off);
2622
								oCell.formulaParsed.Formula = oCell.formulaParsed.assemble(true);
2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643
								oFormulaExt.v = oCell.formulaParsed.Formula;
								if (!bNoBuildDep) {
									oCell._BuildDependencies(false);
								}
							}
						}
					}
				}
				if (oFormulaExt.v) {
					if (oFormulaExt.v.length <= AscCommon.c_oAscMaxFormulaLength) {
						if (!oCell.formulaParsed) {
							oCell.formulaParsed = new parserFormula(oFormulaExt.v, oCell, this);
							oCell.formulaParsed.ca = oFormulaExt.ca;
							if (!bNoBuildDep) {
								oCell._BuildDependencies(true);
							}
						}
					} else {
						this.workbook.openErrors.push(oCell.getName());
					}
				}
2644
			}
2645
			this.aFormulaExt = null;
2646
		}
2647

2648 2649 2650
		if (!this.PagePrintOptions) {
			// Даже если не было, создадим
			this.PagePrintOptions = new Asc.asc_CPageOptions();
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2651
		}
2652
		this.PagePrintOptions.init();
Alexey.Musinov's avatar
Alexey.Musinov committed
2653

2654 2655 2656 2657 2658
		// Sheet Views
		if (0 === this.sheetViews.length) {
			// Даже если не было, создадим
			this.sheetViews.push(new AscCommonExcel.asc_CSheetViewSettings());
		}
2659

2660 2661 2662
		if (window['IS_NATIVE_EDITOR']) {
			for (var j = this.sheetViews.length - 1; j >= 0; --j) {
				this.sheetViews[j].pane = null;
2663 2664
			}
		}
2665
		//this.setTableFormulaAfterOpen();
2666 2667 2668 2669 2670
		this._updateConditionalFormatting(null);

		this.handlers = handlers;
		this._setHandlersTablePart();
	};
2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686
	Woorksheet.prototype._getValuesForConditionalFormatting = function(ranges, withEmpty) {
		var res = [];
		for (var i = 0; i < ranges.length; ++i) {
			var elem = ranges[i];
			var range = this.getRange3(elem.r1, elem.c1, elem.r2, elem.c2);
			res = res.concat(range._getValues(withEmpty));
		}
		return res;
	};
	Woorksheet.prototype._isConditionalFormattingIntersect = function(range, ranges) {
		for (var i = 0; i < ranges.length; ++i) {
			if (range.isIntersect(ranges[i])) {
				return true;
			}
		}
		return false;
2687 2688 2689 2690 2691 2692 2693
	};
	Woorksheet.prototype._updateConditionalFormatting = function(range) {
		var oGradient1, oGradient2;
		var aCFs = this.aConditionalFormatting;
		var aRules, oRule;
		var oRuleElement = null;
		var o;
2694
		var i, j, l, cf, cell, ranges, values, value, v, tmp, min, mid, max, dxf, compareFunction, nc, sum;
2695
		for (i = 0; i < aCFs.length; ++i) {
2696 2697
			cf = aCFs[i]
			ranges = cf.ranges;
2698
			// ToDo убрать null === sqref когда научимся мультиселект обрабатывать (\\192.168.5.2\source\DOCUMENTS\XLSX\Matematika Quantum Sedekah.xlsx)
2699
			if (!cf.isValid()) {
2700 2701
				continue;
			}
2702 2703
			if (!range || this._isConditionalFormattingIntersect(range, ranges)) {
				aRules = cf.aRules.sort(function(v1, v2) {
2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718
					return v1.priority - v2.priority;
				});
				if (oRule = aRules[0]) {
					// ToDo dataBar, expression, iconSet (page 2679)
					if (AscCommonExcel.ECfType.colorScale === oRule.type) {
						if (1 !== oRule.aRuleElements.length) {
							break;
						}
						oRuleElement = oRule.aRuleElements[0];
						if (!(oRuleElement instanceof AscCommonExcel.CColorScale)) {
							break;
						}
						nc = 0;
						min = Number.MAX_VALUE;
						max = -Number.MAX_VALUE;
2719
						values = this._getValuesForConditionalFormatting(ranges, false);
2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763
						for (cell = 0; cell < values.length; ++cell) {
							value = values[cell];
							if (CellValueType.Number === value.c.getType() && !isNaN(tmp = parseFloat(value.v))) {
								value.v = tmp;
								min = Math.min(min, tmp);
								max = Math.max(max, tmp);
								++nc;
							} else {
								value.v = null;
							}
						}

						// ToDo CFVO Type formula (page 2681)
						l = oRuleElement.aColors.length;
						if (0 < values.length && 2 <= l) {
							oGradient1 = new AscCommonExcel.CGradient(oRuleElement.aColors[0], oRuleElement.aColors[1]);
							min = oRuleElement.getMin(min, max, values);
							max = oRuleElement.getMax(min, max, values);
							oGradient2 = null;
							if (2 < l) {
								oGradient2 = new AscCommonExcel.CGradient(oRuleElement.aColors[1], oRuleElement.aColors[2]);
								mid = oRuleElement.getMid(min, max, values);

								oGradient1.init(min, mid);
								oGradient2.init(mid, max);
							} else {
								oGradient1.init(min, max);
							}

							for (cell = 0; cell < values.length; ++cell) {
								value = values[cell];
								v = value.v;
								dxf = null;
								if (null !== v) {
									dxf = new AscCommonExcel.CellXfs();
									tmp = (oGradient2 && v > oGradient1.max) ? oGradient2 : oGradient1;
									dxf.fill = new AscCommonExcel.Fill({bg: tmp.calculateColor(v)});
								}
								value.c.setConditionalFormattingStyle(dxf);
							}
						}
					} else if (AscCommonExcel.ECfType.top10 === oRule.type) {
						if (oRule.rank > 0 && oRule.dxf) {
							nc = 0;
2764
							values = this._getValuesForConditionalFormatting(ranges, false);
2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791
							o = oRule.bottom ? -Number.MAX_VALUE : Number.MAX_VALUE;
							for (cell = 0; cell < values.length; ++cell) {
								value = values[cell];
								if (CellValueType.Number === value.c.getType() && !isNaN(tmp = parseFloat(value.v))) {
									++nc;
									value.v = tmp;
								} else {
									value.v = o;
								}
							}
							values.sort((function(condition) {
								return function(v1, v2) {
									return condition * (v2.v - v1.v);
								}
							})(oRule.bottom ? -1 : 1));

							tmp = 0;
							nc = oRule.percent ? Math.floor(nc * oRule.rank / 100) : oRule.rank;
							for (cell = 0; cell < values.length; ++cell) {
								value = values[cell];
								value.c.setConditionalFormattingStyle((o !== value.v && tmp < nc) ? (++tmp && oRule.dxf) : null);
							}
						}
					} else if (AscCommonExcel.ECfType.aboveAverage === oRule.type) {
						if (!oRule.dxf) {
							continue;
						}
2792
						values = this._getValuesForConditionalFormatting(ranges, false);
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 2822 2823 2824 2825 2826 2827
						sum = 0;
						nc = 0;
						for (cell = 0; cell < values.length; ++cell) {
							value = values[cell];
							if (!value.c.isEmptyTextString(value.v)) {
								++nc;
								if (CellValueType.Number === value.c.getType() && !isNaN(tmp = parseFloat(value.v))) {
									value.v = tmp;
									sum += tmp;
								} else {
									value.v = null;
								}
							}
						}

						tmp = sum / nc;
						/*if (oRule.hasStdDev()) {
						 sum = 0;
						 for (cell = 0; cell < values.length; ++cell) {
						 value = values[cell];
						 if (null !== value.v) {
						 sum += (value.v - tmp) * (value.v - tmp);
						 }
						 }
						 sum = Math.sqrt(sum / (nc - 1));
						 }*/

						for (cell = 0; cell < values.length; ++cell) {
							value = values[cell];
							value.c.setConditionalFormattingStyle((null !== value.v && oRule.getAverage(value.v, tmp, sum)) ? oRule.dxf : null);
						}
					} else {
						if (!oRule.dxf) {
							continue;
						}
2828
						values = this._getValuesForConditionalFormatting(ranges, true);
2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917

						switch (oRule.type) {
							case AscCommonExcel.ECfType.duplicateValues:
							case AscCommonExcel.ECfType.uniqueValues:
								o = getUniqueKeys(values);
								compareFunction = (function(obj, condition){
									return function(val) {
										return condition === obj[val];
									};
								})(o, oRule.type === AscCommonExcel.ECfType.duplicateValues);
								break;
							case AscCommonExcel.ECfType.containsText:
								compareFunction = (function(text){
									return function(val) {
										return -1 !== val.indexOf(text);
									};
								})(oRule.text);
								break;
							case AscCommonExcel.ECfType.notContainsText:
								compareFunction = (function(text){
									return function(val) {
										return -1 === val.indexOf(text);
									};
								})(oRule.text);
								break;
							case AscCommonExcel.ECfType.beginsWith:
								compareFunction = (function(text){
									return function(val) {
										return val.startsWith(text);
									};
								})(oRule.text);

								break;
							case AscCommonExcel.ECfType.endsWith:
								compareFunction = (function(text){
									return function(val) {
										return val.endsWith(text);
									};
								})(oRule.text);
								break;
							case AscCommonExcel.ECfType.containsErrors:
								compareFunction = function(val, c) {
									return CellValueType.Error === c.getType();
								};
								break;
							case AscCommonExcel.ECfType.notContainsErrors:
								compareFunction = function(val, c) {
									return CellValueType.Error !== c.getType();
								};
								break;
							case AscCommonExcel.ECfType.containsBlanks:
								compareFunction = function(val, c) {
									return c.isEmptyTextString();
								};
								break;
							case AscCommonExcel.ECfType.notContainsBlanks:
								compareFunction = function(val, c) {
									return !c.isEmptyTextString();
								};
								break;
							case AscCommonExcel.ECfType.timePeriod:
								if (oRule.timePeriod) {
									compareFunction = (function(period) {
										return function(val, c) {
											var n = parseFloat(val);
											return period.start <= n && n <= period.end;
										};
									})(oRule.getTimePeriod());
								} else {
									continue;
								}
								break;
							case AscCommonExcel.ECfType.cellIs:
								compareFunction = (function(rule, v1, v2) {
									return function(val, c) {
										return rule.cellIs(val, v1, v2);
									};
								})(oRule, oRule.aRuleElements[0] && oRule.aRuleElements[0].getValue(this), oRule.aRuleElements[1] && oRule.aRuleElements[1].getValue(this));
								break;
							default:
								continue;
								break;
						}

						for (cell = 0; cell < values.length; ++cell) {
							value = values[cell];
							value.c.setConditionalFormattingStyle(compareFunction(value.v, value.c) ? oRule.dxf : null);
						}
					}
2918 2919 2920
				}
			}
		}
2921 2922 2923 2924 2925 2926 2927 2928 2929
	};
	Woorksheet.prototype._forEachCell=function(fAction){
		for(var rowInd in this.aGCells){
			var row = this.aGCells[rowInd];
			if(row){
				for(var cellInd in row.c){
					var cell = row.c[cellInd];
					if(cell){
						fAction(cell);
2930 2931 2932 2933
					}
				}
			}
		}
2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945
	};
	Woorksheet.prototype.getId=function(){
		return this.Id;
	};
	Woorksheet.prototype.getIndex=function(){
		return this.index;
	};
	Woorksheet.prototype.getName=function(){
		return this.sName !== undefined && this.sName.length > 0 ? this.sName : "";
	};
	Woorksheet.prototype.setName=function(name, bFromUndoRedo){
		if(name.length <= g_nSheetNameMaxLength)
2946
		{
2947 2948 2949 2950 2951 2952 2953
			var lastName = this.sName;
			this.sName = name;
			History.Create_NewPoint();
			this.workbook.dependencyFormulas.changeSheet(this.getId(), {rename: {from: lastName, to: name}});

			History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_Rename, this.getId(), null, new UndoRedoData_FromTo(lastName, name));
			if(!bFromUndoRedo)
2954
			{
2955 2956 2957 2958
				var _lastName = parserHelp.getEscapeSheetName(lastName);
				var _newName = parserHelp.getEscapeSheetName(this.sName);

				for (var key in this.workbook.aWorksheets)
2959
				{
2960 2961 2962
					var wsModel = this.workbook.aWorksheets[key];
					if ( wsModel )
						wsModel.oDrawingOjectsManager.updateChartReferencesWidthHistory(_lastName, _newName, true);
2963 2964
				}
			}
2965
			this.workbook.dependencyFormulas.calcTree();
2966
		}
2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996
	};
	Woorksheet.prototype.getTabColor=function(){
		return this.sheetPr && this.sheetPr.TabColor ? Asc.colorObjToAscColor(this.sheetPr.TabColor) : null;
	};
	Woorksheet.prototype.setTabColor=function(color){
		if (!this.sheetPr)
			this.sheetPr = new AscCommonExcel.asc_CSheetPr();

		History.Create_NewPoint();
		History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_SetTabColor, this.getId(), null,
					new UndoRedoData_FromTo(this.sheetPr.TabColor ? this.sheetPr.TabColor.clone() : null, color ? color.clone() : null));

		this.sheetPr.TabColor = color;
		if (!this.workbook.bUndoChanges && !this.workbook.bRedoChanges)
			this.workbook.handlers.trigger("asc_onUpdateTabColor", this.getIndex());
	};
	Woorksheet.prototype.rebuildTabColor = function() {
		if (this.sheetPr && this.sheetPr.TabColor) {
			this.workbook.handlers.trigger("asc_onUpdateTabColor", this.getIndex());
		}
	};
	Woorksheet.prototype.getHidden=function(){
		if(null != this.bHidden)
			return false != this.bHidden;
		return false;
	};
	Woorksheet.prototype.setHidden = function (hidden) {
		var bOldHidden = this.bHidden, wb = this.workbook, wsActive = wb.getActiveWs(), oVisibleWs = null;
		this.bHidden = hidden;
		if (true == this.bHidden && this.getIndex() == wsActive.getIndex())
2997
		{
2998 2999 3000 3001 3002 3003 3004
			oVisibleWs = wb.findSheetNoHidden(this.getIndex());
			if (null != oVisibleWs) {
				var nNewIndex = oVisibleWs.getIndex();
				wb.setActive(nNewIndex);
				if (!wb.bUndoChanges && !wb.bRedoChanges)
					wb.handlers.trigger("undoRedoHideSheet", nNewIndex);
			}
3005
		}
3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017
		if (bOldHidden != hidden) {
			History.Create_NewPoint();
			History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_Hide, this.getId(), null, new UndoRedoData_FromTo(bOldHidden, hidden));
			if (null != oVisibleWs) {
				History.SetSheetUndo(wsActive.getId());
				History.SetSheetRedo(oVisibleWs.getId());
			}
		}
	};
	Woorksheet.prototype.getSheetViewSettings = function () {
		return this.sheetViews[0].clone();
	};
3018 3019 3020 3021 3022 3023 3024
	Woorksheet.prototype.setDisplayGridlines = function (value) {
		var view = this.sheetViews[0];
		if (value !== view.showGridLines) {
			History.Create_NewPoint();
			History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_SetDisplayGridlines,
				this.getId(), null, new UndoRedoData_FromTo(view.showGridLines, value));
			view.showGridLines = value;
3025

3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037
			if (!this.workbook.bUndoChanges && !this.workbook.bRedoChanges) {
				this.workbook.handlers.trigger("asc_onUpdateSheetViewSettings");
			}
		}
	};
	Woorksheet.prototype.setDisplayHeadings = function (value) {
		var view = this.sheetViews[0];
		if (value !== view.showRowColHeaders) {
			History.Create_NewPoint();
			History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_SetDisplayHeadings,
				this.getId(), null, new UndoRedoData_FromTo(view.showRowColHeaders, value));
			view.showRowColHeaders = value;
3038

3039 3040 3041 3042
			if (!this.workbook.bUndoChanges && !this.workbook.bRedoChanges) {
				this.workbook.handlers.trigger("asc_onUpdateSheetViewSettings");
			}
		}
3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062
	};
	Woorksheet.prototype.getRowsCount=function(){
		var result = this.nRowsCount;
		var pane = this.sheetViews[0].pane;
		if (null !== pane && null !== pane.topLeftFrozenCell)
			result = Math.max(result, pane.topLeftFrozenCell.getRow0());
		return result;
	};
	Woorksheet.prototype.removeRows=function(start, stop){
		var oRange = this.getRange(new CellAddress(start, 0, 0), new CellAddress(stop, gc_nMaxCol0, 0));
		oRange.deleteCellsShiftUp();
	};
	Woorksheet.prototype._removeRows=function(start, stop){
		this.workbook.dependencyFormulas.lockRecal();
		History.Create_NewPoint();
		//start, stop 0 based
		var nDif = -(stop - start + 1);
		var oActualRange = new Asc.Range(0, start, gc_nMaxCol0, stop);
		//renameDependencyNodes before move cells to store current location in history
		var changedFormulas = this.renameDependencyNodes({offsetRow: nDif, offsetCol: 0}, oActualRange);
3063
		var redrawTablesArr = this.autoFilters.insertRows( "delCell", new Asc.Range(0, start, gc_nMaxCol0, stop), c_oAscDeleteOptions.DeleteRows );
3064 3065
		var i, j, length, nIndex, aIndexes = [];
		for(i in this.aGCells)
3066
		{
3067
			nIndex = i - 0;
3068 3069 3070
			if(nIndex >= start)
				aIndexes.push(nIndex);
		}
3071
		//По возрастанию
3072
		aIndexes.sort(fSortAscending);
3073 3074
		var oDefRowPr = new AscCommonExcel.UndoRedoData_RowProp();
		for(i = 0, length = aIndexes.length; i < length; ++i)
3075
		{
3076 3077
			nIndex = aIndexes[i];
			var row = this.aGCells[nIndex];
3078 3079
			if(nIndex > stop)
			{
3080
				if(false == row.isEmpty())
3081
				{
3082 3083
					var oTargetRow = this._getRow(nIndex + nDif);
					oTargetRow.copyProperty(row);
3084
				}
3085 3086
				for (j in row.c) {
					var cell = row.c[j];
3087
					this._moveCellVer(nIndex, j - 0, nDif);
3088 3089 3090 3091 3092
					if (cell && cell.getFormula()) {
						//for #Ref
						this.workbook.dependencyFormulas.addToChangedCell(cell);
					}
				}
3093 3094 3095
			}
			else
			{
3096 3097 3098 3099 3100
				var oOldProps = row.getHeightProp();
				if (false === oOldProps.isEqual(oDefRowPr))
					History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RowProp, this.getId(), row._getUpdateRange(), new UndoRedoData_IndexSimpleProp(nIndex, true, oOldProps, oDefRowPr));
				row.setStyle(null);
				for(j in row.c)
3101
				{
3102 3103 3104
					var nColIndex = j - 0;
					//удаляем ячейку
					this._removeCell(nIndex, nColIndex);
3105 3106
				}
			}
3107
			delete this.aGCells[nIndex];
3108
		}
3109
		//notifyChanged after move cells to get new locations(for intersect ranges)
3110
		this.workbook.dependencyFormulas.notifyChanged(changedFormulas);
3111
		History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RemoveRows, this.getId(), new Asc.Range(0, start, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_FromToRowCol(true, start, stop));
3112 3113

		this.autoFilters.redrawStylesTables(redrawTablesArr);
3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128

		this.workbook.dependencyFormulas.unlockRecal();

		return true;
	};
	Woorksheet.prototype.insertRowsBefore=function(index, count){
		var oRange = this.getRange(new CellAddress(index, 0, 0), new CellAddress(index + count - 1, gc_nMaxCol0, 0));
		oRange.addCellsShiftBottom();
	};
	Woorksheet.prototype._insertRowsBefore=function(index, count){
		this.workbook.dependencyFormulas.lockRecal();
		var oActualRange = new Asc.Range(0, index, gc_nMaxCol0, index + count - 1);
		History.Create_NewPoint();
		//renameDependencyNodes before move cells to store current location in history
		var changedFormulas = this.renameDependencyNodes({offsetRow: count, offsetCol: 0}, oActualRange);
3129
		var redrawTablesArr = this.autoFilters.insertRows( "insCell", new Asc.Range(0, index, gc_nMaxCol0, index + count - 1), c_oAscInsertOptions.InsertColumns );
3130
		//index 0 based
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3131
		var aIndexes = [];
3132
		for(var i in this.aGCells)
3133
		{
3134
			var nIndex = i - 0;
3135 3136 3137
			if(nIndex >= index)
				aIndexes.push(nIndex);
		}
3138 3139 3140 3141
		var oPrevRow = null;
		if(index > 0)
			oPrevRow = this.aGCells[index - 1];
		//По убыванию
3142
		aIndexes.sort(fSortDescending);
3143
		for(var i = 0, length = aIndexes.length; i < length; ++i)
3144
		{
3145 3146 3147 3148 3149 3150 3151
			var nIndex = aIndexes[i];
			var row = this.aGCells[nIndex];
			if(false == row.isEmpty())
			{
				var oTargetRow = this._getRow(nIndex + count);
				oTargetRow.copyProperty(row);
			}
3152 3153
			for (var j in row.c) {
				var cell = row.c[j];
3154
				this._moveCellVer(nIndex, j - 0, count);
3155 3156 3157 3158 3159
				if (cell && cell.getFormula()) {
					//for #Ref
					this.workbook.dependencyFormulas.addToChangedCell(cell);
				}
			}
3160
			delete this.aGCells[nIndex];
3161
		}
3162
		if (null != oPrevRow && false == this.workbook.bUndoChanges && (false == this.workbook.bRedoChanges || true == this.workbook.bCollaborativeChanges))
3163
		{
3164 3165 3166 3167 3168 3169 3170 3171
			History.LocalChange = true;
			for(var i = 0; i < count; ++i)
			{
				var row = this._getRow(index + i);
				row.copyProperty(oPrevRow);
				row.flags &= ~AscCommonExcel.g_nRowFlag_hd;
			}
			History.LocalChange = false;
3172
		}
3173
		//notifyChanged after move cells to get new locations(for intersect ranges)
3174
		this.workbook.dependencyFormulas.notifyChanged(changedFormulas);
3175 3176
		History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_AddRows, this.getId(), new Asc.Range(0, index, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_FromToRowCol(true, index, index + count - 1));

3177
		this.autoFilters.redrawStylesTables(redrawTablesArr);
3178 3179 3180 3181 3182 3183

		this.workbook.dependencyFormulas.unlockRecal();

		this.nRowsCount += count;

		return true;
3184
	};
3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207
	Woorksheet.prototype.insertRowsAfter=function(index, count){
		//index 0 based
		return this.insertRowsBefore(index + 1, count);
	};
	Woorksheet.prototype.getColsCount=function(){
		var result = this.nColsCount;
		var pane = this.sheetViews[0].pane;
		if (null !== pane && null !== pane.topLeftFrozenCell)
			result = Math.max(result, pane.topLeftFrozenCell.getCol0());
		return result;
	};
	Woorksheet.prototype.removeCols=function(start, stop){
		var oRange = this.getRange(new CellAddress(0, start, 0), new CellAddress(gc_nMaxRow0, stop, 0));
		oRange.deleteCellsShiftLeft();
	};
	Woorksheet.prototype._removeCols=function(start, stop){
		this.workbook.dependencyFormulas.lockRecal();
		History.Create_NewPoint();
		//start, stop 0 based
		var nDif = -(stop - start + 1), i, j, length, nIndex;
		var oActualRange = new Asc.Range(start, 0, stop, gc_nMaxRow0);
		//renameDependencyNodes before move cells to store current location in history
		var changedFormulas = this.renameDependencyNodes({ offsetRow: 0, offsetCol: nDif }, oActualRange);
3208
		var redrawTablesArr = this.autoFilters.insertColumn( "delCell",  new Asc.Range(start, 0, stop, gc_nMaxRow0), c_oAscInsertOptions.InsertColumns );
3209
		for(i in this.aGCells)
3210
		{
3211 3212 3213 3214
			var nRowIndex = i - 0;
			var row = this.aGCells[i];
			var aIndexes = [];
			for(j in row.c)
3215
			{
3216 3217 3218
				nIndex = j - 0;
				if(nIndex >= start)
					aIndexes.push(nIndex);
3219
			}
3220 3221 3222
			//сортируем по возрастанию
			aIndexes.sort(fSortAscending);
			for(j = 0, length = aIndexes.length; j < length; ++j)
3223
			{
3224 3225 3226
				nIndex = aIndexes[j];
				if(nIndex > stop)
				{
3227
					var cell = row.c[nIndex];
3228
					this._moveCellHor(nRowIndex, nIndex, nDif, {r1: 0, c1: start, r2: gc_nMaxRow0, c2: stop});
3229 3230 3231 3232
					if (cell && cell.getFormula()) {
						//for #Ref
						this.workbook.dependencyFormulas.addToChangedCell(cell);
					}
3233 3234 3235 3236 3237 3238
				}
				else
				{
					//удаляем ячейку
					this._removeCell(nRowIndex, nIndex);
				}
3239
			}
3240
		}
3241 3242 3243 3244
		var oDefColPr = new AscCommonExcel.UndoRedoData_ColProp();
		for(i = start; i <= stop; ++i)
		{
			var col = this.aCols[i];
3245
			if(null != col)
3246
			{
3247 3248 3249 3250
				var oOldProps = col.getWidthProp();
				if(false === oOldProps.isEqual(oDefColPr))
					History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ColProp, this.getId(), new Asc.Range(i, 0, i, gc_nMaxRow0), new UndoRedoData_IndexSimpleProp(i, false, oOldProps, oDefColPr));
				col.setStyle(null);
3251 3252
			}
		}
3253 3254
		this.aCols.splice(start, stop - start + 1);
		for(i = start, length = this.aCols.length; i < length; ++i)
Igor.Zotov's avatar
Igor.Zotov committed
3255
		{
3256 3257 3258
			var elem = this.aCols[i];
			if(null != elem)
				elem.moveHor(nDif);
3259
		}
3260
		//notifyChanged after move cells to get new locations(for intersect ranges)
3261
		this.workbook.dependencyFormulas.notifyChanged(changedFormulas);
3262 3263
		History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RemoveCols, this.getId(), new Asc.Range(start, 0, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_FromToRowCol(false, start, stop));

3264 3265
		this.autoFilters.redrawStylesTables(redrawTablesArr);

3266 3267 3268
		this.workbook.dependencyFormulas.unlockRecal();

		return true;
3269
	};
3270 3271 3272 3273 3274 3275 3276 3277 3278 3279
	Woorksheet.prototype.insertColsBefore=function(index, count){
		var oRange = this.getRange3(0, index, gc_nMaxRow0, index + count - 1);
		oRange.addCellsShiftRight();
	};
	Woorksheet.prototype._insertColsBefore=function(index, count){
		this.workbook.dependencyFormulas.lockRecal();
		var oActualRange = new Asc.Range(index, 0, index + count - 1, gc_nMaxRow0);
		History.Create_NewPoint();
		//renameDependencyNodes before move cells to store current location in history
		var changedFormulas = this.renameDependencyNodes({offsetRow: 0, offsetCol: count}, oActualRange);
3280
		var redrawTablesArr = this.autoFilters.insertColumn( "insCells",  new Asc.Range(index, 0, index + count - 1, gc_nMaxRow0), c_oAscInsertOptions.InsertColumns );
3281 3282
		//index 0 based
		for(var i in this.aGCells)
3283
		{
3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297
			var nRowIndex = i - 0;
			var row = this.aGCells[i];
			var aIndexes = [];
			for(var j in row.c)
			{
				var nIndex = j - 0;
				if(nIndex >= index)
					aIndexes.push(nIndex);
			}
			//сортируем по убыванию
			aIndexes.sort(fSortDescending);
			for(var j = 0, length2 = aIndexes.length; j < length2; ++j)
			{
				var nIndex = aIndexes[j];
3298
				var cell = row.c[nIndex];
3299
				this._moveCellHor(nRowIndex, nIndex, count, oActualRange);
3300 3301 3302 3303
				if (cell && cell.getFormula()) {
					//for #Ref
					this.workbook.dependencyFormulas.addToChangedCell(cell);
				}
3304
			}
3305
		}
3306
		//notifyChanged after move cells to get new locations(for intersect ranges)
3307
		this.workbook.dependencyFormulas.notifyChanged(changedFormulas);
3308 3309
		History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_AddCols, this.getId(), new Asc.Range(index, 0, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_FromToRowCol(false, index, index + count - 1));

3310
		this.autoFilters.redrawStylesTables(redrawTablesArr);
3311 3312 3313 3314 3315 3316 3317 3318 3319

		this.workbook.dependencyFormulas.unlockRecal();

		var oPrevCol = null;
		if(index > 0)
			oPrevCol = this.aCols[index - 1];
		if(null == oPrevCol && null != this.oAllCol)
			oPrevCol = this.oAllCol;
		for(var i = 0; i < count; ++i)
3320
		{
3321 3322
			var oNewCol = null;
			if (null != oPrevCol && false == this.workbook.bUndoChanges && (false == this.workbook.bRedoChanges || true == this.workbook.bCollaborativeChanges))
3323
			{
3324 3325 3326 3327 3328 3329
				History.LocalChange = true;
				oNewCol = oPrevCol.clone();
				oNewCol.hd = null;
				oNewCol.BestFit = null;
				oNewCol.index = index + i;
				History.LocalChange = false;
3330
			}
3331
			this.aCols.splice(index, 0, oNewCol);
3332
		}
3333
		for(var i = index + count, length = this.aCols.length; i < length; ++i)
3334
		{
3335 3336 3337
			var elem = this.aCols[i];
			if(null != elem)
				elem.moveHor(count);
3338
		}
3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383
		this.nColsCount += count;

		return true;
	};
	Woorksheet.prototype.insertColsAfter=function(index, count){
		//index 0 based
		return this.insertColsBefore(index + 1, count);
	};
	Woorksheet.prototype.getDefaultWidth=function(){
		return this.oSheetFormatPr.dDefaultColWidth;
	};
	Woorksheet.prototype.getDefaultFontName=function(){
		return this.workbook.getDefaultFont();
	};
	Woorksheet.prototype.getDefaultFontSize=function(){
		return this.workbook.getDefaultSize();
	};
	Woorksheet.prototype.charCountToModelColWidth = function (count) {
		return this.workbook.charCountToModelColWidth(count);
	};
	Woorksheet.prototype.getColWidth=function(index){
		//index 0 based
		//Результат в пунктах
		var col = this._getColNoEmptyWithAll(index);
		if(null != col && null != col.width)
			return col.width;
		var dResult = this.oSheetFormatPr.dDefaultColWidth;
		if(dResult === undefined || dResult === null || dResult == 0)
		//dResult = (8) + 5;//(EMCA-376.page 1857.)defaultColWidth = baseColumnWidth + {margin padding (2 pixels on each side, totalling 4 pixels)} + {gridline (1pixel)}
			dResult = -1; // calc default width at presentation level
		return dResult;
	};
	Woorksheet.prototype.setColWidth=function(width, start, stop){
		width = this.charCountToModelColWidth(width);
		if(0 == width)
			return this.setColHidden(true, start, stop);

		//start, stop 0 based
		if(null == start)
			return;
		if(null == stop)
			stop = start;
		History.Create_NewPoint();
		var oSelection = History.GetSelection();
		if(null != oSelection)
3384
		{
3385 3386 3387 3388 3389
			oSelection = oSelection.clone();
			oSelection.assign(start, 0, stop, gc_nMaxRow0);
			oSelection.type = Asc.c_oAscSelectionType.RangeCol;
			History.SetSelection(oSelection);
			History.SetSelectionRedo(oSelection);
3390
		}
3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407
		var oThis = this;
		var fProcessCol = function(col){
			if(col.width != width)
			{
				var oOldProps = col.getWidthProp();
				col.width = width;
				col.CustomWidth = true;
				col.BestFit = null;
				col.hd = null;
				var oNewProps = col.getWidthProp();
				if(false == oOldProps.isEqual(oNewProps))
					History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ColProp, oThis.getId(),
								col._getUpdateRange(),
								new UndoRedoData_IndexSimpleProp(col.index, false, oOldProps, oNewProps));
			}
		};
		if(0 == start && gc_nMaxCol0 == stop)
3408
		{
3409 3410 3411 3412 3413 3414 3415
			var col = this.getAllCol();
			fProcessCol(col);
			for(var i in this.aCols){
				var col = this.aCols[i];
				if (null != col)
					fProcessCol(col);
			}
3416
		}
3417
		else
3418
		{
3419 3420 3421 3422
			for(var i = start; i <= stop; i++){
				var col = this._getCol(i);
				fProcessCol(col);
			}
3423
		}
3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441
	};
	Woorksheet.prototype.getColHidden=function(index){
		var col = this._getColNoEmptyWithAll(index);
		return col ? col.hd : false;
	};
	Woorksheet.prototype.setColHidden=function(bHidden, start, stop){
		//start, stop 0 based
		if(null == start)
			return;
		if(null == stop)
			stop = start;
		History.Create_NewPoint();
		var oThis = this;
		var fProcessCol = function(col){
			if(col.hd != bHidden)
			{
				var oOldProps = col.getWidthProp();
				if(bHidden)
3442
				{
3443 3444 3445 3446 3447
					col.hd = bHidden;
					if(null == col.width || true != col.CustomWidth)
						col.width = 0;
					col.CustomWidth = true;
					col.BestFit = null;
3448
				}
3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462
				else
				{
					col.hd = null;
					if(0 >= col.width)
						col.width = null;
				}
				var oNewProps = col.getWidthProp();
				if(false == oOldProps.isEqual(oNewProps))
					History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ColProp, oThis.getId(),
								col._getUpdateRange(),
								new UndoRedoData_IndexSimpleProp(col.index, false, oOldProps, oNewProps));
			}
		};
		if(0 != start && gc_nMaxCol0 == stop)
3463
		{
3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474
			var col = null;
			if(false == bHidden)
				col = this.oAllCol;
			else
				col = this.getAllCol();
			if(null != col)
				fProcessCol(col);
			for(var i in this.aCols){
				var col = this.aCols[i];
				if (null != col)
					fProcessCol(col);
3475 3476
			}
		}
3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487
		else
		{
			for(var i = start; i <= stop; i++){
				var col = null;
				if(false == bHidden)
					col = this._getColNoEmpty(i);
				else
					col = this._getCol(i);
				if(null != col)
					fProcessCol(col);
			}
3488
		}
3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500
	};
	Woorksheet.prototype.setColBestFit=function(bBestFit, width, start, stop){
		//start, stop 0 based
		if(null == start)
			return;
		if(null == stop)
			stop = start;
		History.Create_NewPoint();
		var oThis = this;
		var fProcessCol = function(col){
			var oOldProps = col.getWidthProp();
			if(bBestFit)
3501
			{
3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526
				col.BestFit = bBestFit;
				col.hd = null;
			}
			else
				col.BestFit = null;
			col.width = width;
			var oNewProps = col.getWidthProp();
			if(false == oOldProps.isEqual(oNewProps))
				History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ColProp, oThis.getId(),
							col._getUpdateRange(),
							new UndoRedoData_IndexSimpleProp(col.index, false, oOldProps, oNewProps));
		};
		if(0 != start && gc_nMaxCol0 == stop)
		{
			var col = null;
			if(bBestFit && oDefaultMetrics.ColWidthChars == width)
				col = this.oAllCol;
			else
				col = this.getAllCol();
			if(null != col)
				fProcessCol(col);
			for(var i in this.aCols){
				var col = this.aCols[i];
				if (null != col)
					fProcessCol(col);
3527
			}
3528
		}
3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584
		else
		{
			for(var i = start; i <= stop; i++){
				var col = null;
				if(bBestFit && oDefaultMetrics.ColWidthChars == width)
					col = this._getColNoEmpty(i);
				else
					col = this._getCol(i);
				if(null != col)
					fProcessCol(col);
			}
		}
	};
	Woorksheet.prototype.isDefaultHeightHidden=function(){
		return null != this.oSheetFormatPr.oAllRow && 0 != (AscCommonExcel.g_nRowFlag_hd & this.oSheetFormatPr.oAllRow.flags);
	};
	Woorksheet.prototype.isDefaultWidthHidden=function(){
		return null != this.oAllCol && this.oAllCol.hd;
	};
	Woorksheet.prototype.getDefaultHeight=function(){
		// ToDo http://bugzilla.onlyoffice.com/show_bug.cgi?id=19666 (флага CustomHeight нет)
		var dRes = null;
		// Нужно возвращать выставленную, только если флаг CustomHeight = true
		if(null != this.oSheetFormatPr.oAllRow && 0 != (AscCommonExcel.g_nRowFlag_CustomHeight & this.oSheetFormatPr.oAllRow.flags))
			dRes = this.oSheetFormatPr.oAllRow.h;
		return dRes;
	};
	Woorksheet.prototype.getRowHeight=function(index){
		//index 0 based
		var row = this.aGCells[index];
		if(null != row && null != row.h)
			return row.h;
		else
			return -1;
	};
	Woorksheet.prototype.setRowHeight=function(height, start, stop, isCustom){
		if(0 == height)
			return this.setRowHidden(true, start, stop);
		//start, stop 0 based
		if(null == start)
			return;
		if(null == stop)
			stop = start;
		History.Create_NewPoint();
		var oThis = this, i;
		var oSelection = History.GetSelection();
		if(null != oSelection)
		{
			oSelection = oSelection.clone();
			oSelection.assign(0, start, gc_nMaxCol0, stop);
			oSelection.type = Asc.c_oAscSelectionType.RangeRow;
			History.SetSelection(oSelection);
			History.SetSelectionRedo(oSelection);
		}
		var fProcessRow = function(row){
			if(row)
3585
			{
3586 3587 3588 3589
				var oOldProps = row.getHeightProp();
				row.h = height;
				if (isCustom) {
					row.flags |= AscCommonExcel.g_nRowFlag_CustomHeight;
3590
				}
3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602
				row.flags |= AscCommonExcel.g_nRowFlag_CalcHeight;
				row.flags &= ~AscCommonExcel.g_nRowFlag_hd;
				var oNewProps = row.getHeightProp();
				if(false === oOldProps.isEqual(oNewProps))
					History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RowProp, oThis.getId(), row._getUpdateRange(), new UndoRedoData_IndexSimpleProp(row.index, true, oOldProps, oNewProps));
			}
		};
		if(0 == start && gc_nMaxRow0 == stop)
		{
			fProcessRow(this.getAllRow());
			for(i in this.aGCells){
				fProcessRow(this.aGCells[i]);
3603
			}
3604
		}
3605 3606 3607 3608 3609
		else
		{
			for(i = start; i <= stop; ++i){
				fProcessRow(this._getRow(i));
			}
3610
		}
3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624
	};
	Woorksheet.prototype.getRowHidden=function(index){
		var row = this._getRowNoEmptyWithAll(index);
		return row ? 0 != (AscCommonExcel.g_nRowFlag_hd & row.flags) : false;
	};
	Woorksheet.prototype.setRowHidden=function(bHidden, start, stop){
		//start, stop 0 based
		if(null == start)
			return;
		if(null == stop)
			stop = start;
		History.Create_NewPoint();
		var oThis = this, i;
		var startIndex = null, endIndex = null, updateRange;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
3625

3626 3627
		var fProcessRow = function(row){
			if(row && bHidden != (0 != (AscCommonExcel.g_nRowFlag_hd & row.flags)))
3628
			{
3629 3630 3631 3632 3633 3634 3635 3636
				if(bHidden)
					row.flags |= AscCommonExcel.g_nRowFlag_hd;
				else
					row.flags &= ~AscCommonExcel.g_nRowFlag_hd;


				if(row.index === endIndex + 1 && startIndex !== null)
					endIndex++;
3637
				else
3638 3639 3640 3641 3642 3643 3644 3645 3646 3647
				{
					if(startIndex !== null)
					{
						updateRange = new Asc.Range(0, startIndex, gc_nMaxCol0, endIndex);
						History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RowHide, oThis.getId(), updateRange, new UndoRedoData_FromToRowCol(bHidden, startIndex, endIndex));
					}

					startIndex = row.index;
					endIndex = row.index;
				}
3648
			}
3649 3650 3651 3652
		};
		if(0 == start && gc_nMaxRow0 == stop)
		{
			// ToDo реализовать скрытие всех строк!
3653
		}
3654
		else
3655
		{
3656 3657 3658 3659
			for(i = start; i <= stop; ++i)
				fProcessRow(false == bHidden ? this._getRowNoEmpty(i) : this._getRow(i));

			if(startIndex !== null)//заносим последние строки
3660
			{
3661 3662
				updateRange = new Asc.Range(0, startIndex, gc_nMaxCol0, endIndex);
				History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RowHide, oThis.getId(),updateRange, new UndoRedoData_FromToRowCol(bHidden, startIndex, endIndex));
3663
			}
3664
		}
3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676
	};
	Woorksheet.prototype.setRowBestFit=function(bBestFit, height, start, stop){
		//start, stop 0 based
		if(null == start)
			return;
		if(null == stop)
			stop = start;
		History.Create_NewPoint();
		var oThis = this, i;
		var isDefaultProp = (true == bBestFit && oDefaultMetrics.RowHeight == height);
		var fProcessRow = function(row){
			if(row)
3677
			{
3678 3679 3680 3681 3682 3683 3684 3685 3686 3687
				var oOldProps = row.getHeightProp();
				if(true == bBestFit)
					row.flags &= ~AscCommonExcel.g_nRowFlag_CustomHeight;
				else
					row.flags |= AscCommonExcel.g_nRowFlag_CustomHeight;
				row.flags |= AscCommonExcel.g_nRowFlag_CalcHeight;
				row.h = height;
				var oNewProps = row.getHeightProp();
				if(false == oOldProps.isEqual(oNewProps))
					History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RowProp, oThis.getId(), row._getUpdateRange(), new UndoRedoData_IndexSimpleProp(row.index, true, oOldProps, oNewProps));
3688
			}
3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084
		};
		if(0 == start && gc_nMaxRow0 == stop)
		{
			fProcessRow(isDefaultProp ? this.oSheetFormatPr.oAllRow : this.getAllRow());
			for(i in this.aGCells)
				fProcessRow(this.aGCells[i]);
		}
		for(i = start; i <= stop; ++i)
			fProcessRow(isDefaultProp ? this._getRowNoEmpty(i) : this._getRow(i));
	};
	Woorksheet.prototype.getCell=function(oCellAdd){
		return this.getRange(oCellAdd, oCellAdd);
	};
	Woorksheet.prototype.getCell2=function(sCellAdd){
		if( sCellAdd.indexOf("$") > -1)
			sCellAdd = sCellAdd.replace(/\$/g,"");
		return this.getRange2(sCellAdd);
	};
	Woorksheet.prototype.getCell3=function(r1, c1){
		return this.getRange3(r1, c1, r1, c1);
	};
	Woorksheet.prototype.getRange=function(cellAdd1, cellAdd2){
		//Если range находится за границами ячеек расширяем их
		var nRow1 = cellAdd1.getRow0();
		var nCol1 = cellAdd1.getCol0();
		var nRow2 = cellAdd2.getRow0();
		var nCol2 = cellAdd2.getCol0();
		return this.getRange3(nRow1, nCol1, nRow2, nCol2);
	};
	Woorksheet.prototype.getRange2=function(sRange){
		var bbox = AscCommonExcel.g_oRangeCache.getAscRange(sRange);
		if(null != bbox)
			return Range.prototype.createFromBBox(this, bbox);
		return null;
	};
	Woorksheet.prototype.getRange3=function(r1, c1, r2, c2){
		var nRowMin = r1;
		var nRowMax = r2;
		var nColMin = c1;
		var nColMax = c2;
		if(r1 > r2){
			nRowMax = r1;
			nRowMin = r2;
		}
		if(c1 > c2){
			nColMax = c1;
			nColMin = c2;
		}
		return new Range(this, nRowMin, nColMin, nRowMax, nColMax);
	};
	Woorksheet.prototype._getRows=function(){
		return this.aGCells;
	};
	Woorksheet.prototype._getCols=function(){
		return this.aCols;
	};
	Woorksheet.prototype._removeCell=function(nRow, nCol, cell){
		if(null != cell)
		{
			nRow = cell.nRow;
			nCol = cell.nCol;
		}
		var row = this.aGCells[nRow];
		if(null != row)
		{
			var cell = row.c[nCol];
			if(null != cell)
			{
				var sheetId = this.getId();
				if (null != cell.getConditionalFormattingStyle() || null != cell.getTableStyle()) {
					cell.setValue("");
					cell.setStyle(null);
				}
				else {
					if (false == cell.isEmpty()) {
						var oUndoRedoData_CellData = new AscCommonExcel.UndoRedoData_CellData(cell.getValueData(), null);
						if (null != cell.xfs)
							oUndoRedoData_CellData.style = cell.xfs.clone();
						History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RemoveCell, sheetId, new Asc.Range(nCol, nRow, nCol, nRow), new UndoRedoData_CellSimpleData(nRow, nCol, oUndoRedoData_CellData, null));
					}
					delete row.c[nCol];
					if (row.isEmpty())
						delete this.aGCells[nRow];
				}
				cell.removeDependencies();
				this.workbook.dependencyFormulas.addToChangedCell(cell);
			}
		}
	};
	Woorksheet.prototype._getCell=function(row, col){
		//0-based
		var oCurRow = this._getRow(row);
		var oCurCell = oCurRow.c[col];
		if(null == oCurCell){
			oCurCell = new Cell(this);
			var oRow = this._getRowNoEmpty(row);
			var oCol = this._getColNoEmptyWithAll(col);
			var xfs = null;
			if(oRow && null != oRow.xfs)
				xfs = oRow.xfs.clone();
			else if(null != oCol && null != oCol.xfs)
				xfs = oCol.xfs.clone();
			oCurCell.create(xfs, row, col);
			oCurRow.c[col] = oCurCell;
			if(row >= this.nRowsCount)
				this.nRowsCount = row + 1;
			if(col >= this.nColsCount)
				this.nColsCount = col + 1;
			//History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_CreateCell, this.getId(), null, new UndoRedoData_CellSimpleData(row, col, null, null));
		}
		return oCurCell;
	};
	Woorksheet.prototype._getCellNoEmpty=function(row, col){
		//0-based
		var oCurRow = this.aGCells[row];
		if(oCurRow)
		{
			var cell = oCurRow.c[col];
			return cell ? cell : null;
		}
		return null;
	};
	Woorksheet.prototype._getRowNoEmpty=function(row){
		//0-based
		return this.aGCells[row];
	};
	Woorksheet.prototype._getRowNoEmptyWithAll=function(row){
		var oRes = this._getRowNoEmpty(row);
		if(!oRes)
			oRes = this.oSheetFormatPr.oAllRow;
		return oRes;
	};
	Woorksheet.prototype._getColNoEmpty=function(col){
		//0-based
		var oCurCol = this.aCols[col];
		if(oCurCol)
			return oCurCol;
		return null;
	};
	Woorksheet.prototype._getColNoEmptyWithAll=function(col){
		var oRes = this._getColNoEmpty(col);
		if(null == oRes)
			oRes = this.oAllCol;
		return oRes;
	};
	Woorksheet.prototype._getRow=function(row){
		//0-based
		var oCurRow = null;
		if (g_nAllRowIndex == row)
			oCurRow = this.getAllRow();
		else {
			oCurRow = this.aGCells[row];
			if (!oCurRow) {
				if (null != this.oSheetFormatPr.oAllRow)
					oCurRow = this.oSheetFormatPr.oAllRow.clone(this);
				else
					oCurRow = new AscCommonExcel.Row(this);
				oCurRow.create(row + 1);
				this.aGCells[row] = oCurRow;
				this.nRowsCount = row >= this.nRowsCount ? row + 1 : this.nRowsCount;
				//History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_CreateRow, this.getId(), null, new UndoRedoData_SingleProperty(row));
			}
		}
		return oCurRow;
	};
	Woorksheet.prototype._removeRow=function(index){
		delete this.aGCells[index];
	};
	Woorksheet.prototype._getCol=function(index){
		//0-based
		var oCurCol;
		if (g_nAllColIndex == index)
			oCurCol = this.getAllCol();
		else
		{
			oCurCol = this.aCols[index];
			if(null == oCurCol)
			{
				if(null != this.oAllCol)
				{
					oCurCol = this.oAllCol.clone();
					oCurCol.index = index;
				}
				else
					oCurCol = new AscCommonExcel.Col(this, index);
				this.aCols[index] = oCurCol;
				this.nColsCount = index >= this.nColsCount ? index + 1 : this.nColsCount;
				//History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_CreateCol, this.getId(), null, new UndoRedoData_SingleProperty(index));
			}
		}
		return oCurCol;
	};
	Woorksheet.prototype._removeCol=function(index){
		//0-based
		delete this.aCols[index];
	};
	Woorksheet.prototype._moveCellHor=function(nRow, nCol, dif){
		var cell = this._getCellNoEmpty(nRow, nCol);
		if(cell)
		{
			cell.moveHor(dif);
			var row = this._getRow(nRow);
			row.c[nCol + dif] = cell;
			delete row.c[nCol];
		}
	};
	Woorksheet.prototype._moveCellVer=function(nRow, nCol, dif){
		var cell = this._getCellNoEmpty(nRow, nCol);
		if(cell)
		{
			cell.moveVer(dif);
			var oCurRow = this._getRow(nRow);
			var oTargetRow = this._getRow(nRow + dif);
			delete oCurRow.c[nCol];
			oTargetRow.c[nCol] = cell;
			if(oCurRow.isEmpty())
				delete this.aGCells[nRow];
		}
	};
	Woorksheet.prototype._prepareMoveRangeGetCleanRanges=function(oBBoxFrom, oBBoxTo){
		var intersection = oBBoxFrom.intersectionSimple(oBBoxTo);
		var aRangesToCheck = [];
		if(null != intersection)
		{
			var oThis = this;
			var fAddToRangesToCheck = function(aRangesToCheck, r1, c1, r2, c2)
			{
				if(r1 <= r2 && c1 <= c2)
					aRangesToCheck.push(oThis.getRange3(r1, c1, r2, c2));
			};
			if(intersection.r1 == oBBoxTo.r1 && intersection.c1 == oBBoxTo.c1)
			{
				fAddToRangesToCheck(aRangesToCheck, oBBoxTo.r1, intersection.c2 + 1, intersection.r2, oBBoxTo.c2);
				fAddToRangesToCheck(aRangesToCheck, intersection.r2 + 1, oBBoxTo.c1, oBBoxTo.r2, oBBoxTo.c2);
			}
			else if(intersection.r2 == oBBoxTo.r2 && intersection.c1 == oBBoxTo.c1)
			{
				fAddToRangesToCheck(aRangesToCheck, oBBoxTo.r1, oBBoxTo.c1, intersection.r1 - 1, oBBoxTo.c2);
				fAddToRangesToCheck(aRangesToCheck, intersection.r1, intersection.c2 + 1, oBBoxTo.r2, oBBoxTo.c2);
			}
			else if(intersection.r1 == oBBoxTo.r1 && intersection.c2 == oBBoxTo.c2)
			{
				fAddToRangesToCheck(aRangesToCheck, oBBoxTo.r1, oBBoxTo.c1, intersection.r2, intersection.c1 - 1);
				fAddToRangesToCheck(aRangesToCheck, intersection.r2 + 1, oBBoxTo.c1, oBBoxTo.r2, oBBoxTo.c2);
			}
			else if(intersection.r2 == oBBoxTo.r2 && intersection.c2 == oBBoxTo.c2)
			{
				fAddToRangesToCheck(aRangesToCheck, oBBoxTo.r1, oBBoxTo.c1, intersection.r1 - 1, oBBoxTo.c2);
				fAddToRangesToCheck(aRangesToCheck, intersection.r1, oBBoxTo.c1, oBBoxTo.r2, intersection.c1 - 1);
			}
		}
		else
			aRangesToCheck.push(this.getRange3(oBBoxTo.r1, oBBoxTo.c1, oBBoxTo.r2, oBBoxTo.c2));
		return aRangesToCheck;
	};
	Woorksheet.prototype._prepareMoveRange=function(oBBoxFrom, oBBoxTo){
		var res = 0;
		if(oBBoxFrom.isEqual(oBBoxTo))
			return res;
		var range = this.getRange3(oBBoxTo.r1, oBBoxTo.c1, oBBoxTo.r2, oBBoxTo.c2);
		var aMerged = this.mergeManager.get(range.getBBox0());
		if(aMerged.outer.length > 0)
			return -2;
		var aRangesToCheck = this._prepareMoveRangeGetCleanRanges(oBBoxFrom, oBBoxTo);
		for(var i = 0, length = aRangesToCheck.length; i < length; i++)
		{
			range = aRangesToCheck[i];
			range._foreachNoEmpty(
				function(cell){
					if(!cell.isEmptyTextString())
					{
						res = -1;
						return res;
					}
				});
			if(0 != res)
				return res;
		}
		return res;
	};
	Woorksheet.prototype._moveRange=function(oBBoxFrom, oBBoxTo, copyRange){
		if(oBBoxFrom.isEqual(oBBoxTo))
			return;
		var oThis = this;
		History.Create_NewPoint();
		History.StartTransaction();

		var offset = { offsetRow : oBBoxTo.r1 - oBBoxFrom.r1, offsetCol : oBBoxTo.c1 - oBBoxFrom.c1 };
		var intersection = oBBoxFrom.intersectionSimple(oBBoxTo);
		var oRangeIntersection = null;
		if(null != intersection)
			oRangeIntersection = this.getRange3(intersection.r1, intersection.c1, intersection.r2, intersection.c2 );
		//запоминаем то что нужно переместить
		var aTempObj = {cells: {}, merged: null, hyperlinks: null};
		for(var i = oBBoxFrom.r1; i <= oBBoxFrom.r2; i++)
		{
			var row = this._getRowNoEmpty(i);
			if(row)
			{
				var oTempRow = {};
				aTempObj.cells[i + offset.offsetRow] = oTempRow;
				for(var j = oBBoxFrom.c1; j <= oBBoxFrom.c2; j++)
				{
					var cell = row.c[j];
					if(null != cell){
						if(copyRange)
							oTempRow[j + offset.offsetCol] = cell.clone();
						else
						{
							cell.setTableStyle(null);
							oTempRow[j + offset.offsetCol] = cell;
						}
					}
				}
			}
		}
		if(false == this.workbook.bUndoChanges && (false == this.workbook.bRedoChanges || true == this.workbook.bCollaborativeChanges))
		{
			History.LocalChange = true;
			var aMerged = this.mergeManager.get(oBBoxFrom);
			if(aMerged.inner.length > 0)
				aTempObj.merged = aMerged.inner;
			var aHyperlinks = this.hyperlinkManager.get(oBBoxFrom);
			if(aHyperlinks.inner.length > 0)
				aTempObj.hyperlinks = aHyperlinks.inner;
			var aMergedToRemove = null;
			if(!copyRange){
				aMergedToRemove = aTempObj.merged;
			}
			else if(null != intersection){
				var aMergedIntersection = this.mergeManager.get(intersection);
				if(aMergedIntersection.all.length > 0)
					aMergedToRemove = aMergedIntersection.all;
			}
			if(null != aMergedToRemove){
				for(var i = 0, length = aMergedToRemove.length; i < length; i++)
				{
					var elem = aMergedToRemove[i];
					this.mergeManager.removeElement(elem);
				}
			}
			if(!copyRange){
				if(null != aTempObj.hyperlinks)
				{
					for(var i = 0, length = aTempObj.hyperlinks.length; i < length; i++)
					{
						var elem = aTempObj.hyperlinks[i];
						this.hyperlinkManager.removeElement(elem);
					}
				}
			}
			History.LocalChange = false;
		}
		//удаляем to через историю, для undo
		var aRangesToCheck = this._prepareMoveRangeGetCleanRanges(oBBoxFrom, oBBoxTo);
		for (var i = 0, length = aRangesToCheck.length; i < length; i++) {
			var range = aRangesToCheck[i];
			range.cleanAll();
			//выставляем для slave refError
			if (!copyRange)
				this.workbook.dependencyFormulas.deleteNodes(this.getId(), range.getBBox0());
		}
		//удаляем from без истории, потому что эти данные не терются а перемещаются
		if(!copyRange || (copyRange && this.workbook.bUndoChanges)){
			var oRangeFrom = this.getRange3(oBBoxFrom.r1, oBBoxFrom.c1, oBBoxFrom.r2, oBBoxFrom.c2 );
			oRangeFrom._setPropertyNoEmpty(null, null, function(cell, nRow0, nCol0, nRowStart, nColStart){
				var row = oThis._getRowNoEmpty(nRow0);
				if(row)
					delete row.c[nCol0];
			});
		}
		else{
			//в случае копирования удаляем пересечение, чтобы затирались значения, если мы копируем пустые ячейки(все что не входит в пересечение удалилось выше через историю)
			if(null != intersection){
				oRangeIntersection._setPropertyNoEmpty(null, null, function(cell, nRow0, nCol0, nRowStart, nColStart){
					var row = oThis._getRowNoEmpty(nRow0);
					if(row)
						delete row.c[nCol0];
				});
			}
		}
		if(!copyRange){
			this.workbook.dependencyFormulas.move(this.Id, oBBoxFrom, offset);
		}

		for ( var i in aTempObj.cells ) {
			var oTempRow = aTempObj.cells[i];
			var row = this._getRow( i - 0 );
			for ( var j in oTempRow ) {
				var oTempCell = oTempRow[j];
				if ( null != oTempCell ) {
					oTempCell.moveHor( offset.offsetCol );
					oTempCell.moveVer( offset.offsetRow );
					row.c[j] = oTempCell;
					if ( oTempCell.formulaParsed ) {
						if(copyRange) {
konovalovsergey's avatar
konovalovsergey committed
4085 4086 4087 4088 4089
							//todo rework after clone formulaParsed unparsed
							oTempCell.formulaParsed.parse();
							History.TurnOff();
							oTempCell.changeOffset(offset, false, true);
							History.TurnOn();
4090
						}
konovalovsergey's avatar
konovalovsergey committed
4091
						this.workbook.dependencyFormulas.addToBuildDependencyCell(oTempCell);
4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168
					}
				}
			}
		}

		if(false == this.workbook.bUndoChanges && (false == this.workbook.bRedoChanges || true == this.workbook.bCollaborativeChanges))
		{
			History.LocalChange = true;
			if(null != aTempObj.merged)
			{
				for(var i = 0, length = aTempObj.merged.length; i < length; i++)
				{
					var elem = aTempObj.merged[i];
					var oNewBBox;
					var oNewData = elem.data;
					if(copyRange)
						oNewBBox = elem.bbox.clone();
					else
						oNewBBox = elem.bbox;
					oNewBBox.setOffset(offset);
					this.mergeManager.add(oNewBBox, oNewData);
				}
			}
			//todo сделать для пересечения
			if(null != aTempObj.hyperlinks && (!copyRange || null == intersection))
			{
				for(var i = 0, length = aTempObj.hyperlinks.length; i < length; i++)
				{
					var elem = aTempObj.hyperlinks[i];
					var oNewBBox;
					var oNewData;
					if(copyRange){
						oNewBBox = elem.bbox.clone();
						oNewData = elem.data.clone();
					}
					else{
						oNewBBox = elem.bbox;
						oNewData = elem.data;
					}
					oNewBBox.setOffset(offset);
					this.hyperlinkManager.add(oNewBBox, oNewData);
				}
			}
			History.LocalChange = false;
		}
		//расширяем границы
		if(oBBoxFrom.r2 >= this.nRowsCount)
			this.nRowsCount = oBBoxFrom.r2 + 1;
		if(oBBoxFrom.c2 >= this.nColsCount)
			this.nColsCount = oBBoxFrom.c2 + 1;
		if(oBBoxTo.r2 >= this.nRowsCount)
			this.nRowsCount = oBBoxTo.r2 + 1;
		if(oBBoxTo.c2 >= this.nColsCount)
			this.nColsCount = oBBoxTo.c2 + 1;

		this.workbook.sortDependency();

		if(true == this.workbook.bUndoChanges || true == this.workbook.bRedoChanges)
		{
			this.autoFilters.unmergeTablesAfterMove( oBBoxTo );
		}

		// ToDo возможно нужно уменьшить диапазон обновления
		History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_MoveRange,
					this.getId(), new Asc.Range(0, 0, gc_nMaxCol0, gc_nMaxRow0),
					new UndoRedoData_FromTo(new UndoRedoData_BBox(oBBoxFrom), new UndoRedoData_BBox(oBBoxTo), copyRange));

		if(false == this.workbook.bUndoChanges && false == this.workbook.bRedoChanges)
			this.autoFilters._moveAutoFilters( oBBoxTo, oBBoxFrom, null, copyRange, true, oBBoxFrom );
		History.EndTransaction();
		return true;
	};
	Woorksheet.prototype._shiftCellsLeft=function(oBBox){
		//todo удаление когда есть замерженые ячейки
		var nLeft = oBBox.c1;
		var nRight = oBBox.c2;
		var dif = nLeft - nRight - 1;
4169
		var oActualRange = new Asc.Range(nLeft, oBBox.r1, gc_nMaxCol0, oBBox.r2);
4170 4171
		//renameDependencyNodes before move cells to store current location in history
		var changedFormulas = this.renameDependencyNodes({offsetRow: 0, offsetCol: dif}, oBBox);
4172
		var redrawTablesArr = this.autoFilters.insertColumn( "delCell",  oBBox, c_oAscDeleteOptions.DeleteCellsAndShiftLeft );
4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192
		for(var i = oBBox.r1; i <= oBBox.r2; i++){
			var row = this.aGCells[i];
			if(row){
				var aIndexes = [];
				for(var cellInd in row.c)
				{
					var nIndex = cellInd - 0;
					if(nIndex >= nLeft)
						aIndexes.push(nIndex);
				}
				//По возрастанию
				aIndexes.sort(fSortAscending);
				for(var j = 0, length2 = aIndexes.length; j < length2; ++j){
					var nCellInd = aIndexes[j];
					if(nCellInd <= nRight){
						//Удаляем ячейки
						this._removeCell(i, nCellInd);
					}
					else{
						//Сдвигаем ячейки
4193
						var cell = row.c[nCellInd];
4194
						this._moveCellHor(i, nCellInd, dif, oBBox);
4195 4196 4197 4198
						if (cell && cell.getFormula()) {
							//for #Ref
							this.workbook.dependencyFormulas.addToChangedCell(cell);
						}
4199 4200 4201 4202
					}
				}
			}
		}
4203
		//notifyChanged after move cells to get new locations(for intersect ranges)
4204
		this.workbook.dependencyFormulas.notifyChanged(changedFormulas);
4205 4206 4207
		History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ShiftCellsLeft, this.getId(), oActualRange, new UndoRedoData_BBox(oBBox));

		this.autoFilters.redrawStylesTables(redrawTablesArr);
4208 4209 4210 4211 4212 4213
		//todo проверить не уменьшились ли границы таблицы
	};
	Woorksheet.prototype._shiftCellsUp=function(oBBox){
		var nTop = oBBox.r1;
		var nBottom = oBBox.r2;
		var dif = nTop - nBottom - 1;
4214
		var oActualRange = new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, gc_nMaxRow0);
4215 4216
		//renameDependencyNodes before move cells to store current location in history
		var changedFormulas = this.renameDependencyNodes({offsetRow: dif, offsetCol: 0}, oBBox);
4217
		var redrawTablesArr = this.autoFilters.insertRows( "delCell", oBBox, c_oAscDeleteOptions.DeleteCellsAndShiftTop );
4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231
		var aIndexes = [];
		for(var i in this.aGCells)
		{
			var rowInd = i - 0;
			if(rowInd >= nTop)
				aIndexes.push(rowInd);
		}
		//по возрастанию
		aIndexes.sort(fSortAscending);
		for(var i = 0, length = aIndexes.length; i < length; ++i){
			var rowInd = aIndexes[i];
			var row = this.aGCells[rowInd];
			if(row){
				if(rowInd <= nBottom){
4232
					//Удаляем ячейки
4233 4234 4235
					for(var j = oBBox.c1; j <= oBBox.c2; j++){
						this._removeCell(rowInd, j);
					}
4236 4237
				}
				else{
4238 4239
					var nIndex = rowInd + dif;
					var rowTop = this._getRow(nIndex);
4240
					//Сдвигаем ячейки
4241
					for(var j = oBBox.c1; j <= oBBox.c2; j++){
4242
						var cell = row.c[j];
4243
						this._moveCellVer(rowInd, j, dif);
4244 4245 4246 4247
						if (cell && cell.getFormula()) {
							//for #Ref
							this.workbook.dependencyFormulas.addToChangedCell(cell);
						}
4248
					}
4249 4250 4251
				}
			}
		}
4252
		//notifyChanged after move cells to get new locations(for intersect ranges)
4253
		this.workbook.dependencyFormulas.notifyChanged(changedFormulas);
4254 4255 4256
		History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ShiftCellsTop, this.getId(), oActualRange, new UndoRedoData_BBox(oBBox));

		this.autoFilters.redrawStylesTables(redrawTablesArr);
4257 4258 4259 4260 4261 4262
		//todo проверить не уменьшились ли границы таблицы
	};
	Woorksheet.prototype._shiftCellsRight=function(oBBox, displayNameFormatTable){
		var nLeft = oBBox.c1;
		var nRight = oBBox.c2;
		var dif = nRight - nLeft + 1;
4263
		var oActualRange = new Asc.Range(oBBox.c1, oBBox.r1, gc_nMaxCol0, oBBox.r2);
4264 4265
		//renameDependencyNodes before move cells to store current location in history
		var changedFormulas = this.renameDependencyNodes({offsetRow: 0, offsetCol: dif}, oBBox);
4266
		var redrawTablesArr = this.autoFilters.insertColumn( "insCells",  oBBox, c_oAscInsertOptions.InsertCellsAndShiftRight, displayNameFormatTable );
4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286
		for(var i = oBBox.r1; i <= oBBox.r2; i++){
			var row = this.aGCells[i];
			if(row){
				var aIndexes = [];
				for(var cellInd in row.c)
				{
					var nIndex = cellInd - 0;
					if(nIndex >= nLeft)
						aIndexes.push(nIndex);
				}
				//по убыванию
				aIndexes.sort(fSortDescending);
				for(var j = 0, length2 = aIndexes.length; j < length2; ++j){
					var nCellInd = aIndexes[j];
					//Сдвигаем ячейки
					var cell = row.c[nCellInd];
					if(cell){
						if(nCellInd + dif > this.nColsCount)
							this.nColsCount = nCellInd + dif;
						this._moveCellHor(/*row*/i, /*col*/nCellInd, dif, oBBox);
4287 4288 4289 4290
						if (cell && cell.getFormula()) {
							//for #Ref
							this.workbook.dependencyFormulas.addToChangedCell(cell);
						}
4291
					}
4292 4293
				}
			}
4294
		}
4295
		//notifyChanged after move cells to get new locations(for intersect ranges)
4296
		this.workbook.dependencyFormulas.notifyChanged(changedFormulas);
4297 4298 4299 4300
		History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ShiftCellsRight, this.getId(), oActualRange, new UndoRedoData_BBox(oBBox));


		this.autoFilters.redrawStylesTables(redrawTablesArr);
4301 4302 4303 4304 4305 4306
	};
	Woorksheet.prototype._shiftCellsBottom=function(oBBox, displayNameFormatTable){
		var nTop = oBBox.r1;
		var nBottom = oBBox.r2;
		var dif = nBottom - nTop + 1;
		var aIndexes = [];
4307
		var oActualRange = new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, gc_nMaxRow0);
4308 4309
		//renameDependencyNodes before move cells to store current location in history
		var changedFormulas = this.renameDependencyNodes({offsetRow: dif, offsetCol: 0}, oBBox);
4310 4311 4312 4313 4314
		var redrawTablesArr;
		if (!this.workbook.bUndoChanges) {
			redrawTablesArr = this.autoFilters.insertRows("insCell", oBBox, c_oAscInsertOptions.InsertCellsAndShiftDown,
				displayNameFormatTable);
		}
4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325
		for(var i in this.aGCells){
			var rowInd = i - 0;
			if(rowInd >= nTop)
				aIndexes.push(rowInd);
		}
		//по убыванию
		aIndexes.sort(fSortDescending);
		for(var i = 0, length = aIndexes.length; i < length; ++i){
			rowInd = aIndexes[i];
			var row = this.aGCells[rowInd];
			if(row){
4326
				var nIndex = rowInd + dif;
4327 4328
				if(nIndex + dif > this.nRowsCount)
					this.nRowsCount = nIndex + dif;
4329 4330 4331
				var rowTop = this._getRow(nIndex);
				//Сдвигаем ячейки
				for(var j = oBBox.c1; j <= oBBox.c2; j++){
4332
					var cell = row.c[j];
4333
					this._moveCellVer(rowInd, j, dif);
4334 4335 4336 4337
					if (cell && cell.getFormula()) {
						//for #Ref
						this.workbook.dependencyFormulas.addToChangedCell(cell);
					}
4338 4339 4340
				}
			}
		}
4341
		//notifyChanged after move cells to get new locations(for intersect ranges)
4342
		this.workbook.dependencyFormulas.notifyChanged(changedFormulas);
4343
		History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ShiftCellsBottom, this.getId(), oActualRange, new UndoRedoData_BBox(oBBox));
4344 4345 4346

		if(!this.workbook.bUndoChanges)
		{
4347
			this.autoFilters.redrawStylesTables(redrawTablesArr);
4348
		}
4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369

	};
	Woorksheet.prototype._setIndex=function(ind){
		this.index = ind;
	};
	Woorksheet.prototype._BuildDependencies=function(cellRange){
		/*
		 Построение графа зависимостей.
		 */
		var c, ca;
		for (var i in cellRange) {
			if (null === cellRange[i]) {
				cellRange[i] = i;
				continue;
			}

			ca = g_oCellAddressUtils.getCellAddress(i);
			c = this._getCellNoEmpty(ca.getRow0(), ca.getCol0());

			if (c) {
				c._BuildDependencies(true);
4370 4371
			}
		}
4372 4373 4374 4375 4376 4377 4378 4379
	};
	Woorksheet.prototype._setHandlersTablePart = function(){
		if(!this.TableParts)
			return;

		for(var i = 0; i < this.TableParts.length; i++)
		{
			this.TableParts[i].setHandlers(this.handlers);
4380
		}
4381 4382 4383 4384 4385 4386 4387
	};
	Woorksheet.prototype.getTableRangeForFormula = function(name, objectParam){
		var res = null;
		if(!this.TableParts)
			return res;

		for(var i = 0; i < this.TableParts.length; i++)
4388
		{
4389 4390 4391 4392 4393
			if(this.TableParts[i].DisplayName === name)
			{
				res = this.TableParts[i].getTableRangeForFormula(objectParam);
				break;
			}
4394
		}
4395
		return res;
4396 4397 4398 4399 4400 4401 4402
	};
	Woorksheet.prototype.getTableIndexColumnByName = function(tableName, columnName){
		var res = null;
		if(!this.TableParts)
			return res;

		for(var i = 0; i < this.TableParts.length; i++)
4403
		{
4404 4405 4406 4407 4408
			if(this.TableParts[i].DisplayName === tableName)
			{
				res = this.TableParts[i].getTableIndexColumnByName(columnName);
				break;
			}
4409 4410
		}
		return res;
4411 4412 4413 4414 4415 4416 4417
	};
	Woorksheet.prototype.getTableNameColumnByIndex = function(tableName, columnIndex){
		var res = null;
		if(!this.TableParts)
			return res;

		for(var i = 0; i < this.TableParts.length; i++)
4418
		{
4419 4420 4421 4422 4423
			if(this.TableParts[i].DisplayName === tableName)
			{
				res = this.TableParts[i].getTableNameColumnByIndex(columnIndex);
				break;
			}
4424
		}
4425 4426
		return res;
	};
4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447
Woorksheet.prototype.isApplyFilterBySheet = function(){
	var res = false;
	
	if(this.AutoFilter && this.AutoFilter.isApplyAutoFilter())
	{
		res = true;
	}
	
	if(false === res && this.TableParts)
	{
		for(var i = 0; i < this.TableParts.length; i++)
		{
			if(true === this.TableParts[i].isApplyAutoFilter())
			{
				res = true;
				break;
			}
		}
	}
	
	return res;
4448
};
4449 4450 4451 4452 4453 4454 4455 4456 4457
	Woorksheet.prototype.getTableNames = function() {
		var res = [];
		if (this.TableParts) {
			for (var i = 0; i < this.TableParts.length; i++) {
				res.push(this.TableParts[i].DisplayName);
			}
		}
		return res;
	};
4458
	Woorksheet.prototype.renameDependencyNodes = function(offset, oBBox){
4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485
		return this.workbook.dependencyFormulas.shift(this.Id, oBBox, offset);
	};
	Woorksheet.prototype.getAllCol = function(){
		if(null == this.oAllCol)
			this.oAllCol = new AscCommonExcel.Col(this, g_nAllColIndex);
		return this.oAllCol;
	};
	Woorksheet.prototype.getAllRow = function(){
		if (null == this.oSheetFormatPr.oAllRow) {
			this.oSheetFormatPr.oAllRow = new AscCommonExcel.Row(this);
			this.oSheetFormatPr.oAllRow.create(g_nAllRowIndex + 1);
		}
		return this.oSheetFormatPr.oAllRow;
	};
	Woorksheet.prototype.getHyperlinkByCell = function(row, col){
		var oHyperlink = this.hyperlinkManager.getByCell(row, col);
		return oHyperlink ? oHyperlink.data : null;
	};
	Woorksheet.prototype.getMergedByCell = function(row, col){
		var oMergeInfo = this.mergeManager.getByCell(row, col);
		return oMergeInfo ? oMergeInfo.bbox : null;
	};
	Woorksheet.prototype.getMergedByRange = function(bbox){
		return this.mergeManager.get(bbox);
	};
	Woorksheet.prototype._expandRangeByMergedAddToOuter = function(aOuter, range, aMerged){
		for(var i = 0, length = aMerged.all.length; i < length; i++)
4486
		{
4487 4488 4489
			var elem = aMerged.all[i];
			if(!range.containsRange(elem.bbox))
				aOuter.push(elem);
4490
		}
4491 4492 4493 4494 4495 4496
	};
	Woorksheet.prototype._expandRangeByMergedGetOuter = function(range){
		var aOuter = [];
		//смотрим только границы
		this._expandRangeByMergedAddToOuter(aOuter, range, this.mergeManager.get({r1: range.r1, c1: range.c1, r2: range.r2, c2: range.c1}));
		if(range.c1 != range.c2)
4497
		{
4498 4499
			this._expandRangeByMergedAddToOuter(aOuter, range, this.mergeManager.get({r1: range.r1, c1: range.c2, r2: range.r2, c2: range.c2}));
			if(range.c2 - range.c1 > 1)
4500
			{
4501 4502 4503
				this._expandRangeByMergedAddToOuter(aOuter, range, this.mergeManager.get({r1: range.r1, c1: range.c1 + 1, r2: range.r1, c2: range.c2 - 1}));
				if(range.r1 != range.r2)
					this._expandRangeByMergedAddToOuter(aOuter, range, this.mergeManager.get({r1: range.r2, c1: range.c1 + 1, r2: range.r2, c2: range.c2 - 1}));
4504 4505
			}
		}
4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537
		return aOuter;
	};
	Woorksheet.prototype.expandRangeByMerged = function(range){
		if(null != range)
		{
			var aOuter = this._expandRangeByMergedGetOuter(range);
			if(aOuter.length > 0)
			{
				range = range.clone();
				while(aOuter.length > 0)
				{
					for(var i = 0, length = aOuter.length; i < length; i++)
						range.union2(aOuter[i].bbox);
					aOuter = this._expandRangeByMergedGetOuter(range);
				}
			}
		}
		return range;
	};
	Woorksheet.prototype.createTablePart = function(){

		return new AscCommonExcel.TablePart(this.handlers);
	};
	Woorksheet.prototype.onUpdateRanges = function(ranges) {
		this.workbook.updateSparklineCache(this.sName, ranges);
		this._updateConditionalFormatting(new AscCommonExcel.MultiplyRange(ranges));
	};
	Woorksheet.prototype.updateSparklineCache = function(sheet, ranges) {
		for (var i = 0; i < this.aSparklineGroups.length; ++i) {
			this.aSparklineGroups[i].updateCache(sheet, ranges);
		}
	};
4538 4539 4540
	Woorksheet.prototype.getSparklineGroup = function(c, r) {
		for (var i = 0; i < this.aSparklineGroups.length; ++i) {
			if (-1 !== this.aSparklineGroups[i].contains(c, r)) {
4541
				return this.aSparklineGroups[i];
4542 4543 4544 4545
			}
		}
		return null;
	};
4546
	Woorksheet.prototype.removeSparklines = function (range) {
4547 4548
		for (var i = 0; i < this.aSparklineGroups.length; ++i) {
			if (this.aSparklineGroups[i].remove(range)) {
4549
				History.Add(this.aSparklineGroups[i], {Type: AscCH.historyitem_Sparkline_RemoveSparkline, oldPr: null, newPr: null});
4550 4551 4552 4553 4554 4555 4556
				this.aSparklineGroups.splice(i--, 1);
			}
		}
	};
	Woorksheet.prototype.removeSparklineGroups = function (range) {
		for (var i = 0; i < this.aSparklineGroups.length; ++i) {
			if (-1 !== this.aSparklineGroups[i].intersectionSimple(range)) {
4557
				History.Add(this.aSparklineGroups[i], {Type: AscCH.historyitem_Sparkline_RemoveSparkline, oldPr: null, newPr: null});
4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571
				this.aSparklineGroups.splice(i--, 1);
			}
		}
	};
	Woorksheet.prototype.insertSparklineGroup = function (sparklineGroup) {
		this.aSparklineGroups.push(sparklineGroup);
	};
	Woorksheet.prototype.removeSparklineGroup = function (id) {
		for (var i = 0; i < this.aSparklineGroups.length; ++i) {
			if (id === this.aSparklineGroups[i].Get_Id()) {
				this.aSparklineGroups.splice(i, 1);
				break;
			}
		}
4572
	};
4573
	Woorksheet.prototype.getCwf = function() {
konovalovsergey's avatar
konovalovsergey committed
4574 4575 4576 4577 4578 4579 4580 4581 4582 4583
		var cwf = {};
		var range = this.getRange3(0,0, gc_nMaxRow0, gc_nMaxCol0);
		range._setPropertyNoEmpty(null, null, function(cell){
			if(cell.formulaParsed){
				var name = cell.getName();
				cwf[name] = name;
			}
		});
		return cwf;
	};
4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595
	Woorksheet.prototype.getAllFormulas = function(formulas) {
		var range = this.getRange3(0, 0, gc_nMaxRow0, gc_nMaxCol0);
		range._setPropertyNoEmpty(null, null, function(cell) {
			if (cell.formulaParsed) {
				formulas.push(cell.formulaParsed);
			}
		});
		for (var i = 0; i < this.TableParts.length; ++i) {
			var table = this.TableParts[i];
			table.getAllFormulas(formulas);
		}
	};
4596 4597 4598 4599 4600
	Woorksheet.prototype.setTableStyleAfterOpen = function () {
		if (this.TableParts && this.TableParts.length) {
			for (var i = 0; i < this.TableParts.length; i++) {
				var table = this.TableParts[i];
				this.autoFilters._setColorStyleTable(table.Ref, table);
konovalovsergey's avatar
konovalovsergey committed
4601 4602 4603 4604 4605 4606 4607
			}
		}
	};
	Woorksheet.prototype.setTableFormulaAfterOpen = function () {
		if (this.TableParts && this.TableParts.length) {
			for (var i = 0; i < this.TableParts.length; i++) {
				var table = this.TableParts[i];
4608 4609 4610 4611 4612
				//TODO пока заменяем при открытии на TotalsRowFormula
				table.checkTotalRowFormula(this);
			}
		}
	};
4613 4614 4615
	Woorksheet.prototype.addTablePart = function (tablePart, bAddToDependencies) {
		this.TableParts.push(tablePart);
		if (bAddToDependencies) {
konovalovsergey's avatar
konovalovsergey committed
4616
			this.workbook.dependencyFormulas.addTableName(this, tablePart);
4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630
			tablePart.buildDependencies();
		}
	};
	Woorksheet.prototype.changeTablePart = function (index, tablePart, bChangeName) {
		var oldTablePart = this.TableParts[index];
		if (oldTablePart) {
			oldTablePart.removeDependencies();
		}
		this.TableParts[index] = tablePart;
		tablePart.buildDependencies();
		if (bChangeName && oldTablePart) {
			this.workbook.dependencyFormulas.changeTableName(oldTablePart.DisplayName, tablePart.DisplayName);
		}
	};
4631 4632 4633 4634 4635
	Woorksheet.prototype.deleteTablePart = function (index, bConvertTableFormulaToRef) {
		if(bConvertTableFormulaToRef)
		{
			//TODO скорее всего стоит убрать else
			var tablePart = this.TableParts[index];
GoshaZotov's avatar
GoshaZotov committed
4636
			this.workbook.dependencyFormulas.delTableName(tablePart.DisplayName, bConvertTableFormulaToRef);
4637
			tablePart.removeDependencies();
4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649
			
			//delete table
			this.TableParts.splice(index, 1);
		}
		else
		{
			var deleted = this.TableParts.splice(index, 1);
			for (var delIndex = 0; delIndex < deleted.length; ++delIndex) {
				var tablePart = deleted[delIndex];
				this.workbook.dependencyFormulas.delTableName(tablePart.DisplayName);
				tablePart.removeDependencies();
			}
4650
		}
4651
		
4652
	};
4653
//-------------------------------------------------------------------------------------------------
4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673
	/**
	 * @constructor
	 */
	function Cell(worksheet){
		this.ws = worksheet;
		this.oValue = new AscCommonExcel.CCellValue();
		this.xfs = null;
		this.tableXfs = null;
		this.conditionalFormattingXfs = null;
		this.compiledXfs = null;
		this.nRow = -1;
		this.nCol = -1;
		this.formulaParsed = null;
	}
	Cell.prototype.getStyle=function(){
		return this.xfs;
	};
	Cell.prototype.getCompiledStyle = function () {
		if (null == this.compiledXfs && (null != this.xfs || null != this.tableXfs || null != this.conditionalFormattingXfs)) {
			this.compileXfs();
4674
		}
4675 4676 4677 4678 4679
		return this.compiledXfs;
	};
	Cell.prototype.compileXfs=function(){
		this.compiledXfs = null;
		if(null != this.xfs || null != this.tableXfs || null != this.conditionalFormattingXfs)
4680
		{
4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696
			if(null != this.tableXfs)
				this.compiledXfs = this.tableXfs;
			if(null != this.xfs)
			{
				if(null != this.compiledXfs)
					this.compiledXfs = this.xfs.merge(this.compiledXfs, true);
				else
					this.compiledXfs = this.xfs;
			}
			if(null != this.conditionalFormattingXfs)
			{
				if(null != this.compiledXfs)
					this.compiledXfs = this.conditionalFormattingXfs.merge(this.compiledXfs);
				else
					this.compiledXfs = this.conditionalFormattingXfs;
			}
4697
		}
4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717
	};
	Cell.prototype.clone=function(oNewWs, renameParams){
		if(!oNewWs)
			oNewWs = this.ws;
		var oNewCell = new Cell(oNewWs);
		oNewCell.nRow = this.nRow;
		oNewCell.nCol = this.nCol;
		if(null != this.xfs)
			oNewCell.xfs = this.xfs.clone();
		oNewCell.oValue = this.oValue.clone();
		if (null != this.formulaParsed) {
			var newFormula;
			if (oNewWs != this.ws && renameParams) {
				var formula = this.formulaParsed.clone(null, null, this.ws);
				formula.renameSheetCopy(renameParams);
				newFormula = formula.assemble(true);
			} else {
				newFormula = this.formulaParsed.Formula;
			}
			oNewCell.formulaParsed = new parserFormula(newFormula, oNewCell, oNewWs);
4718
			oNewWs.workbook.dependencyFormulas.addToBuildDependencyCell(oNewCell);
4719
		}
4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774
		return oNewCell;
	};
	Cell.prototype.create=function(xfs, nRow, nCol){
		this.xfs = xfs;
		this.nRow = nRow;
		this.nCol = nCol;
	};
	Cell.prototype.isEmptyText=function(){
		this._checkDirty();
		if(false == this.oValue.isEmpty())
			return false;
		if(null != this.formulaParsed)
			return false;
		return true;
	};
	Cell.prototype.isEmptyTextString=function(){
		this._checkDirty();
		return this.oValue.isEmpty();
	};
	Cell.prototype.isEmpty=function(){
		if(false == this.isEmptyText())
			return false;
		if(null != this.xfs)
			return false;
		return true;
	};
	Cell.prototype.isFormula=function(){
		return this.formulaParsed ? true : false;
	};
	Cell.prototype.Remove=function(){
		this.ws._removeCell(null, null, this);
	};
	Cell.prototype.getName=function(){
		return g_oCellAddressUtils.getCellId(this.nRow, this.nCol);
	};
	Cell.prototype.cleanCache=function(){
		this.oValue.cleanCache();
	};
	Cell.prototype.setValue=function(val,callback, isCopyPaste) {
		var ws = this.ws;
		var wb = ws.workbook;
		var DataOld = null;
		if (History.Is_On()) {
			DataOld = this.getValueData();
		}
		var bIsTextFormat = false;
		if (!isCopyPaste) {
			var sNumFormat;
			if (null != this.xfs && null != this.xfs.num) {
				sNumFormat = this.xfs.num.getFormat();
			} else {
				sNumFormat = g_oDefaultFormat.Num.getFormat();
			}
			var numFormat = oNumFormatCache.get(sNumFormat);
			bIsTextFormat = numFormat.isTextFormat();
konovalovsergey's avatar
konovalovsergey committed
4775 4776
		}

4777 4778 4779 4780 4781 4782 4783
		var newFP = null;
		if (false == bIsTextFormat) {
			/*
			 Устанавливаем значение в Range ячеек. При этом происходит проверка значения на формулу.
			 Если значение является формулой, то проверяем содержиться ли в ячейке формула или нет, если "да" - то очищаем в графе зависимостей список, от которых зависит формула(masterNodes), позже будет построен новый. Затем выставляем флаг о необходимости дальнейшего пересчета, и заносим ячейку в список пересчитываемых ячеек.
			 */
			if (null != val && val[0] == "=" && val.length > 1) {
4784

4785
				newFP = new parserFormula(val.substring(1), this, this.ws);
4786

4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802
				var formulaLocaleParse = isCopyPaste === true ? false : oFormulaLocaleInfo.Parse;
				var formulaLocaleDigetSep = isCopyPaste === true ? false : oFormulaLocaleInfo.DigitSep;
				if (!newFP.parse(formulaLocaleParse, formulaLocaleDigetSep)) {
					switch (newFP.error[newFP.error.length - 1]) {
						case c_oAscError.ID.FrmlWrongFunctionName:
							break;
						case c_oAscError.ID.FrmlParenthesesCorrectCount:
							this.setValue("=" + newFP.Formula, callback, isCopyPaste);
							return;
						default :
						{
							wb.handlers.trigger("asc_onError", newFP.error[newFP.error.length - 1], c_oAscError.Level.NoCritical);
							if (callback) {
								callback(false);
							}
							return;
konovalovsergey's avatar
konovalovsergey committed
4803
						}
4804
					}
4805 4806
				} else {
					newFP.Formula = newFP.assemble();
4807 4808 4809
				}
			}
		}
4810 4811 4812 4813
		//удаляем старые значения
		this.oValue.clean();
		var sheetId = this.ws.getId();
		this.removeDependencies();
konovalovsergey's avatar
konovalovsergey committed
4814

4815 4816 4817 4818 4819 4820 4821 4822 4823
		if (newFP) {
			this.formulaParsed = newFP;
			wb.dependencyFormulas.addToBuildDependencyCell(this);
		} else if (val) {
			this.oValue.setValue(this, val);
			wb.dependencyFormulas.addToChangedCell(this);
		} else {
			wb.dependencyFormulas.addToChangedCell(this);
		}
konovalovsergey's avatar
konovalovsergey committed
4824

4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867
		var DataNew = null;
		if (History.Is_On()) {
			DataNew = this.getValueData();
		}
		if (History.Is_On() && false == DataOld.isEqual(DataNew)) {
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ChangeValue, this.ws.getId(),
						new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow),
						new UndoRedoData_CellSimpleData(this.nRow, this.nCol, DataOld, DataNew));
		}
		//sortDependency вызывается ниже History.Add(AscCH.historyitem_Cell_ChangeValue, потому что в ней может быть выставлен формат ячейки(если это текстовый, то принимая изменения формула станет текстом)
		this.ws.workbook.sortDependency();
		if (!this.ws.workbook.dependencyFormulas.isLockRecal()) {
			this._adjustCellFormat();
		}

		//todo не должны удаляться ссылки, если сделать merge ее части.
		if (this.isEmptyTextString()) {
			var cell = this.ws.getCell3(this.nRow, this.nCol);
			cell.removeHyperlink();
		}
	};
	Cell.prototype.setValue2=function(array){
		var DataOld = null;
		if(History.Is_On())
			DataOld = this.getValueData();
		//[{text:"",format:TextFormat},{}...]
		this.removeDependencies();
		this.oValue.clean();
		this.oValue.setValue2(this, array);
		this.ws.workbook.dependencyFormulas.addToChangedCell(this);
		this.ws.workbook.sortDependency();
		var DataNew = null;
		if(History.Is_On())
			DataNew = this.getValueData();
		if(History.Is_On() && false == DataOld.isEqual(DataNew))
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ChangeValue, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, DataOld, DataNew));
		//todo не должны удаляться ссылки, если сделать merge ее части.
		if(this.isEmptyTextString())
		{
			var cell = this.ws.getCell3(this.nRow, this.nCol);
			cell.removeHyperlink();
		}
	};
konovalovsergey's avatar
konovalovsergey committed
4868
	Cell.prototype.setFormulaTemplate = function(bHistoryUndo, action) {
konovalovsergey's avatar
konovalovsergey committed
4869 4870 4871 4872 4873 4874
		var DataOld = null;
		var DataNew = null;
		if (History.Is_On())
			DataOld = this.getValueData();

		this.oValue.clean();
konovalovsergey's avatar
konovalovsergey committed
4875 4876 4877 4878
		if (this.formulaParsed) {
			this.formulaParsed.removeDependencies();
		}
		action(this);
konovalovsergey's avatar
konovalovsergey committed
4879 4880 4881

		if (History.Is_On()) {
			DataNew = this.getValueData();
4882 4883 4884 4885
			if (false == DataOld.isEqual(DataNew)){
				var typeHistory = bHistoryUndo ? AscCH.historyitem_Cell_ChangeValueUndo : AscCH.historyitem_Cell_ChangeValue;
				History.Add(AscCommonExcel.g_oUndoRedoCell, typeHistory, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, DataOld, DataNew), bHistoryUndo);}

konovalovsergey's avatar
konovalovsergey committed
4886 4887
		}
	};
konovalovsergey's avatar
konovalovsergey committed
4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900
	Cell.prototype.setFormula = function(formula, bHistoryUndo) {
		this.setFormulaTemplate(bHistoryUndo, function(cell){
			cell.formulaParsed = new parserFormula(formula, cell, cell.ws);
			cell.ws.workbook.dependencyFormulas.addToBuildDependencyCell(cell);
		});
	};
	Cell.prototype.changeOffset = function(offset, canResize, bHistoryUndo) {
		this.setFormulaTemplate(bHistoryUndo, function(cell){
			cell.formulaParsed.changeOffset(offset, canResize);
			cell.formulaParsed.Formula = cell.formulaParsed.assemble(true);
			cell.formulaParsed.buildDependencies();
		});
	};
konovalovsergey's avatar
konovalovsergey committed
4901 4902 4903
	Cell.prototype.removeDependencies = function() {
		//удаляем сторое значение
		if (this.formulaParsed) {
konovalovsergey's avatar
konovalovsergey committed
4904 4905 4906
			this.formulaParsed.removeDependencies();
			this.formulaParsed = null;
		}
konovalovsergey's avatar
konovalovsergey committed
4907
	};
4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963
	Cell.prototype.setType=function(type){
		if(type != this.oValue.type){
			var DataOld = this.getValueData();
			this.oValue.setValueType(type);
			var DataNew = this.getValueData();
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ChangeValue, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, DataOld, DataNew));
		}
		return this.oValue.type;
	};
	Cell.prototype.getType=function(){
		this._checkDirty();
		return this.oValue.type;
	};
	Cell.prototype.setCellStyle=function(val){
		var newVal = this.ws.workbook.CellStyles._prepareCellStyle(val);
		var oRes = this.ws.workbook.oStyleManager.setCellStyle(this, newVal);
		if(History.Is_On()) {
			var oldStyleName = this.ws.workbook.CellStyles.getStyleNameByXfId(oRes.oldVal);
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Style, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oldStyleName, val));

			// Выставляем стиль
			var oStyle = this.ws.workbook.CellStyles.getStyleByXfId(oRes.newVal);
			if (oStyle.ApplyFont)
				this.setFont(oStyle.getFont());
			if (oStyle.ApplyFill)
				this.setFill(oStyle.getFill());
			if (oStyle.ApplyBorder)
				this.setBorder(oStyle.getBorder());
			if (oStyle.ApplyNumberFormat)
				this.setNumFormat(oStyle.getNumFormatStr());
		}
		this.compiledXfs = null;
		this.oValue.cleanCache();
	};
	Cell.prototype.setNumFormat=function(val){
		var oRes;
		/*if( val == aStandartNumFormats[0] &&
		 this.formulaParsed && this.formulaParsed.value && this.formulaParsed.value.numFormat !== null &&
		 this.formulaParsed.value.numFormat !== undefined && aStandartNumFormats[this.formulaParsed.value.numFormat] )
		 oRes = this.ws.workbook.oStyleManager.setNumFormat(this, aStandartNumFormats[this.formulaParsed.value.numFormat]);
		 else*/
		oRes = this.ws.workbook.oStyleManager.setNumFormat(this, val);
		if(History.Is_On() && oRes.oldVal != oRes.newVal)
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Numformat, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal));
		this.compiledXfs = null;
		this.oValue.cleanCache();
	};
	Cell.prototype.shiftNumFormat=function(nShift, dDigitsCount){
		var bRes = false;
		var sNumFormat;
		if(null != this.xfs && null != this.xfs.num)
			sNumFormat = this.xfs.num.getFormat();
		else
			sNumFormat = g_oDefaultFormat.Num.getFormat();
		var oCurNumFormat = oNumFormatCache.get(sNumFormat);
		if (null != oCurNumFormat && false == oCurNumFormat.isGeneralFormat()) {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
4964
			var output = {};
4965
			bRes = oCurNumFormat.shiftFormat(output, nShift);
konovalovsergey's avatar
konovalovsergey committed
4966
			if (true == bRes) {
4967 4968
				this.setNumFormat(output.format);
			}
4969 4970 4971 4972 4973 4974 4975 4976 4977 4978
		} else if (CellValueType.Number == this.oValue.type) {
			var sGeneral = AscCommon.DecodeGeneralFormat(this.oValue.number, this.oValue.type, dDigitsCount);
			var oGeneral = oNumFormatCache.get(sGeneral);
			if (null != oGeneral && false == oGeneral.isGeneralFormat()) {
				var output = {};
				bRes = oGeneral.shiftFormat(output, nShift);
				if (true == bRes) {
					this.setNumFormat(output.format);
				}
			}
4979
		}
4980 4981 4982 4983 4984
		this.oValue.cleanCache();
		return bRes;
	};
	Cell.prototype.setFont=function(val, bModifyValue){
		if(false != bModifyValue)
4985
		{
4986 4987
			//убираем комплексные строки
			if(null != this.oValue.multiText)
4988
			{
4989 4990 4991 4992 4993 4994 4995 4996 4997
				var oldVal = null;
				if(History.Is_On())
					oldVal = this.getValueData();
				this.oValue.makeSimpleText();
				if(History.Is_On())
				{
					var newVal = this.getValueData();
					History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ChangeValue, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oldVal, newVal));
				}
4998 4999
			}
		}
5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156
		var oRes = this.ws.workbook.oStyleManager.setFont(this, val);
		if(History.Is_On() && oRes.oldVal != oRes.newVal)
		{
			var oldVal = null;
			if(null != oRes.oldVal)
				oldVal = oRes.oldVal.clone();
			var newVal = null;
			if(null != oRes.newVal)
				newVal = oRes.newVal.clone();
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_SetFont, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oldVal, newVal));
		}
		this.compiledXfs = null;
		this.oValue.cleanCache();
	};
	Cell.prototype.setFontname=function(val){
		var oRes = this.ws.workbook.oStyleManager.setFontname(this, val);
		this.oValue.setFontname(this, val);
		if(History.Is_On() && oRes.oldVal != oRes.newVal)
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Fontname, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal));
		this.compiledXfs = null;
		this.oValue.cleanCache();
	};
	Cell.prototype.setFontsize=function(val){
		var oRes = this.ws.workbook.oStyleManager.setFontsize(this, val);
		this.oValue.setFontsize(this, val);
		if(History.Is_On() && oRes.oldVal != oRes.newVal)
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Fontsize, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal));
		this.compiledXfs = null;
		this.oValue.cleanCache();
	};
	Cell.prototype.setFontcolor=function(val){
		var oRes = this.ws.workbook.oStyleManager.setFontcolor(this, val);
		this.oValue.setFontcolor(this, val);
		if(History.Is_On() && oRes.oldVal != oRes.newVal)
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Fontcolor, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal));
		this.compiledXfs = null;
		this.oValue.cleanCache();
	};
	Cell.prototype.setBold=function(val){
		var oRes = this.ws.workbook.oStyleManager.setBold(this, val);
		this.oValue.setBold(this, val);
		if(History.Is_On() && oRes.oldVal != oRes.newVal)
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Bold, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal));
		this.compiledXfs = null;
		this.oValue.cleanCache();
	};
	Cell.prototype.setItalic=function(val){
		var oRes = this.ws.workbook.oStyleManager.setItalic(this, val);
		this.oValue.setItalic(this, val);
		if(History.Is_On() && oRes.oldVal != oRes.newVal)
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Italic, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal));
		this.compiledXfs = null;
		this.oValue.cleanCache();
	};
	Cell.prototype.setUnderline=function(val){
		var oRes = this.ws.workbook.oStyleManager.setUnderline(this, val);
		this.oValue.setUnderline(this, val);
		if(History.Is_On() && oRes.oldVal != oRes.newVal)
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Underline, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal));
		this.compiledXfs = null;
		this.oValue.cleanCache();
	};
	Cell.prototype.setStrikeout=function(val){
		var oRes = this.ws.workbook.oStyleManager.setStrikeout(this, val);
		this.oValue.setStrikeout(this, val);
		if(History.Is_On() && oRes.oldVal != oRes.newVal)
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Strikeout, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal));
		this.compiledXfs = null;
		this.oValue.cleanCache();
	};
	Cell.prototype.setFontAlign=function(val){
		var oRes = this.ws.workbook.oStyleManager.setFontAlign(this, val);
		this.oValue.setFontAlign(this, val);
		if(History.Is_On() && oRes.oldVal != oRes.newVal)
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_FontAlign, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal));
		this.compiledXfs = null;
		this.oValue.cleanCache();
	};
	Cell.prototype.setAlignVertical=function(val){
		var oRes = this.ws.workbook.oStyleManager.setAlignVertical(this, val);
		if(History.Is_On() && oRes.oldVal != oRes.newVal)
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_AlignVertical, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal));
		this.compiledXfs = null;
	};
	Cell.prototype.setAlignHorizontal=function(val){
		var oRes = this.ws.workbook.oStyleManager.setAlignHorizontal(this, val);
		if(History.Is_On() && oRes.oldVal != oRes.newVal)
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_AlignHorizontal, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal));
		this.compiledXfs = null;
	};
	Cell.prototype.setFill=function(val){
		var oRes = this.ws.workbook.oStyleManager.setFill(this, val);
		if(History.Is_On() && oRes.oldVal != oRes.newVal)
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Fill, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal));
		this.compiledXfs = null;
	};
	Cell.prototype.setBorder=function(val){
		var oRes = this.ws.workbook.oStyleManager.setBorder(this, val);
		if(History.Is_On() && oRes.oldVal != oRes.newVal){
			var oldVal = null;
			if(null != oRes.oldVal)
				oldVal = oRes.oldVal.clone();
			var newVal = null;
			if(null != oRes.newVal)
				newVal = oRes.newVal.clone();
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Border, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oldVal, newVal));
		}
		this.compiledXfs = null;
	};
	Cell.prototype.setShrinkToFit=function(val){
		var oRes = this.ws.workbook.oStyleManager.setShrinkToFit(this, val);
		if(History.Is_On() && oRes.oldVal != oRes.newVal)
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ShrinkToFit, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal));
		this.compiledXfs = null;
	};
	Cell.prototype.setWrap=function(val){
		var oRes = this.ws.workbook.oStyleManager.setWrap(this, val);
		if(History.Is_On() && oRes.oldVal != oRes.newVal)
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Wrap, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal));
		this.compiledXfs = null;
	};
	Cell.prototype.setAngle=function(val){
		var oRes = this.ws.workbook.oStyleManager.setAngle(this, val);
		if(History.Is_On() && oRes.oldVal != oRes.newVal)
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Angle, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal));
		this.compiledXfs = null;
	};
	Cell.prototype.setVerticalText=function(val){
		var oRes = this.ws.workbook.oStyleManager.setVerticalText(this, val);
		if(History.Is_On() && oRes.oldVal != oRes.newVal)
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Angle, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal));
		this.compiledXfs = null;
	};
	Cell.prototype.setQuotePrefix=function(val){
		var oRes = this.ws.workbook.oStyleManager.setQuotePrefix(this, val);
		if(History.Is_On() && oRes.oldVal != oRes.newVal)
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_SetQuotePrefix, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal));
		this.oValue.cleanCache();
	};
	Cell.prototype.setConditionalFormattingStyle=function(xfs){
		this.conditionalFormattingXfs = xfs;
		this.compiledXfs = null;
		this.oValue.cleanCache();
	};
	Cell.prototype.getConditionalFormattingStyle = function (xfs) {
		return this.conditionalFormattingXfs;
	};
	Cell.prototype.setTableStyle=function(xfs){
		this.tableXfs = xfs;
		this.compiledXfs = null;
		this.oValue.cleanCache();
	};
	Cell.prototype.getTableStyle=function(){
		return this.tableXfs;
	};
	Cell.prototype.setStyle=function(xfs){
		var oldVal = this.xfs;
5157
		var newVal = null;
5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174
		this.xfs = null;
		if(null != xfs)
		{
			this.xfs = xfs.clone();
			newVal = this.xfs;
		}
		this.compiledXfs = null;
		this.oValue.cleanCache();
		if(History.Is_On() && false == ((null == oldVal && null == newVal) || (null != oldVal && null != newVal && true == oldVal.isEqual(newVal))))
		{
			if(null != oldVal)
				oldVal = oldVal.clone();
			if(null != newVal)
				newVal = newVal.clone();
			History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_SetStyle, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oldVal, newVal));
		}
		// if(this.isEmpty())
5175
		// this.Remove();
5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190
	};
	Cell.prototype.getFormula=function(){
		if(null != this.formulaParsed)
			return this.formulaParsed.Formula;
		else
			return "";
	};
	Cell.prototype.getValueForEdit=function(numFormat){
		this._checkDirty();
		return this.oValue.getValueForEdit(this);
	};
	Cell.prototype.getValueForEdit2=function(numFormat){
		this._checkDirty();
		return this.oValue.getValueForEdit2(this);
	};
5191 5192 5193 5194
	Cell.prototype.getValueForExample=function(numFormat, cultureInfo){
		this._checkDirty();
		return this.oValue.getValueForExample(this, AscCommon.gc_nMaxDigCountView, function(){return true;}, numFormat, cultureInfo);
	};
5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221
	Cell.prototype.getValueWithoutFormat=function(){
		this._checkDirty();
		return this.oValue.getValueWithoutFormat();
	};
	Cell.prototype.getValue=function(numFormat, dDigitsCount){
		this._checkDirty();
		return this.oValue.getValue(this);
	};
	Cell.prototype.getValue2=function(dDigitsCount, fIsFitMeasurer){
		this._checkDirty();
		if(null == fIsFitMeasurer)
			fIsFitMeasurer = function(aText){return true;};
		if(null == dDigitsCount)
			dDigitsCount = AscCommon.gc_nMaxDigCountView;
		return this.oValue.getValue2(this, dDigitsCount, fIsFitMeasurer);
	};
	Cell.prototype.getNumFormatStr=function(){
		if(null != this.xfs && null != this.xfs.num)
			return this.xfs.num.getFormat();
		return g_oDefaultFormat.Num.getFormat();
	};
	Cell.prototype.getNumFormat=function(){
		return oNumFormatCache.get(this.getNumFormatStr());
	};
	Cell.prototype.getNumFormatType=function(){
		return this.getNumFormat().getType();
	};
5222 5223 5224
	Cell.prototype.getNumFormatTypeInfo=function(){
		return this.getNumFormat().getTypeInfo();
	};
5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242
	Cell.prototype.moveHor=function(val){
		this.nCol += val;
	};
	Cell.prototype.moveVer=function(val){
		this.nRow += val;
	};
	Cell.prototype.getOffset=function(cell){
		return this.getOffset3(cell.nCol + 1, cell.nRow + 1);
	};
	Cell.prototype.getOffset2=function(cellId){
		var cAddr2 = new CellAddress(cellId);
		return this.getOffset3(cAddr2.col, cAddr2.row);
	};
	Cell.prototype.getOffset3=function(col, row){
		return new AscCommonExcel.CRangeOffset((this.nCol - col + 1), (this.nRow - row + 1));
	};
	Cell.prototype.getValueData = function(){
		this._checkDirty();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5243
		var formula = this.formulaParsed ? this.formulaParsed.Formula : null;
5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270
		return new UndoRedoData_CellValueData(formula, this.oValue.clone());
	};
	Cell.prototype.setValueData = function(Val){
		//значения устанавляваются через setValue, чтобы пересчитались формулы
		if(null != Val.formula)
			this.setFormula(Val.formula);
		else if(null != Val.value)
		{
			var DataOld = null;
			var DataNew = null;
			if (History.Is_On())
				DataOld = this.getValueData();
			this.removeDependencies();
			this.oValue = Val.value.clone(this);
			this.ws.workbook.dependencyFormulas.addToChangedCell(this);
			this.ws.workbook.sortDependency();
			if (History.Is_On()) {
				DataNew = this.getValueData();
				if (false == DataOld.isEqual(DataNew))
					History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ChangeValue, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, DataOld, DataNew));
			}
		}
		else
			this.setValue("");
	};
	Cell.prototype._checkDirty = function(){
		if(this.formulaParsed && this.formulaParsed.getIsDirty()) {
konovalovsergey's avatar
konovalovsergey committed
5271
			this.formulaParsed.calculate();
5272 5273
		}
	};
5274 5275 5276 5277 5278 5279
	Cell.prototype.getFont=function(){
		var xfs = this.getCompiledStyle();
		if(null != xfs && null != xfs.font)
			return xfs.font;
		return g_oDefaultFormat.Font;
	};
5280 5281 5282
	Cell.prototype._adjustCellFormat = function() {
		if (this.formulaParsed && this.formulaParsed.value && this.formulaParsed.outStack) {
			var valueCalc = this.formulaParsed.value;
5283
			if (0 <= valueCalc.numFormat) {
5284 5285 5286
				if (aStandartNumFormatsId[this.getNumFormatStr()] == 0) {
					this.setNumFormat(aStandartNumFormats[valueCalc.numFormat]);
				}
5287
			} else if (AscCommonExcel.cNumFormatFirstCell === valueCalc.numFormat) {
5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308
				// ищет в формуле первый рэндж и устанавливает формат ячейки как формат первой ячейки в рэндже
				for (var i = 0, length = this.formulaParsed.outStack.length; i < length; i++) {
					var elem = this.formulaParsed.outStack[i];
					if (cElementType.cell === elem.type || cElementType.cell3D === elem.type ||
						cElementType.cellsRange === elem.type || cElementType.cellsRange3D === elem.type) {
						var r = elem.getRange();
						if (r && r.getNumFormatStr) {
							var sCurFormat = this.getNumFormatStr();
							if (g_oDefaultFormat.Num.getFormat() == sCurFormat) {
								var sNewFormat = r.getNumFormatStr();
								if (sCurFormat != sNewFormat) {
									this.setNumFormat(sNewFormat);
								}
							}
						}
						break;
					}
				}
			}
		}
	};
konovalovsergey's avatar
konovalovsergey committed
5309 5310
	Cell.prototype.onFormulaEvent = function(type, eventData) {
		if (AscCommon.c_oNotifyParentType.CanDo === type) {
konovalovsergey's avatar
konovalovsergey committed
5311 5312 5313
			return true;
		} else if (AscCommon.c_oNotifyParentType.GetRangeCell === type) {
			return this.ws.getCell3(this.nRow, this.nCol);
konovalovsergey's avatar
konovalovsergey committed
5314
		} else if (AscCommon.c_oNotifyParentType.Change === type) {
konovalovsergey's avatar
konovalovsergey committed
5315 5316
			this.ws.workbook.dependencyFormulas.addToChangedCell(this);
		} else if (AscCommon.c_oNotifyParentType.ChangeFormula === type) {
5317
			var DataOld = this.getValueData();
5318 5319 5320 5321 5322 5323 5324 5325
			this.formulaParsed.Formula = eventData.assemble;
			this.ws.workbook.dependencyFormulas.addToChangedCell(this);
			var DataNew = this.getValueData();
			if (false == DataOld.isEqual(DataNew)) {
				History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ChangeValueUndo, this.ws.getId(),
							new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow),
							new UndoRedoData_CellSimpleData(this.nRow, this.nCol, DataOld, DataNew), true);
				this.oValue.cleanCache();
5326
			}
konovalovsergey's avatar
konovalovsergey committed
5327 5328 5329
		} else if (AscCommon.c_oNotifyParentType.EndCalculate === type) {
			this._updateCellValue();
		}
5330
	};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5331
	Cell.prototype._calculateRefType = function () {
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5332 5333 5334
		var val = this.formulaParsed.value;
		var nF = val.numFormat;
		var ca = val.ca;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5335
		if (cElementType.cell === val.type || cElementType.cell3D === val.type) {
konovalovsergey's avatar
konovalovsergey committed
5336
			val = val.getValue();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5337 5338 5339 5340 5341 5342
			if (cElementType.empty === val.type) {
				// Bug http://bugzilla.onlyoffice.com/show_bug.cgi?id=33941
				val.value = 0;
				val.type = cElementType.number;
			}
		} else if (cElementType.array === val.type) {
konovalovsergey's avatar
konovalovsergey committed
5343
			val = val.getElement(0);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5344
		} else if (cElementType.cellsRange === val.type || cElementType.cellsRange3D === val.type) {
5345
			val = val.cross(new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), this.ws.getId());
konovalovsergey's avatar
konovalovsergey committed
5346
		}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5347 5348
		val.numFormat = nF;
		val.ca = ca;
konovalovsergey's avatar
konovalovsergey committed
5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380
		this.formulaParsed.value = val;
	};
	Cell.prototype._updateCellValue = function() {
		this._calculateRefType();
		var res = this.formulaParsed.value;
		if (res) {
			this.oValue.clean();
			switch (res.type) {
				case cElementType.number:
					this.oValue.type = CellValueType.Number;
					this.oValue.number = res.getValue();
					break;
				case cElementType.bool:
					this.oValue.type = CellValueType.Bool;
					this.oValue.number = res.value ? 1 : 0;
					break;
				case cElementType.error:
					this.oValue.type = CellValueType.Error;
					this.oValue.text = res.getValue().toString();
					break;
				case cElementType.name:
					this.oValue.type = CellValueType.Error;
					this.oValue.text = res.getValue().toString();
					break;
				default:
					this.oValue.type = CellValueType.String;
					this.oValue.text = res.getValue().toString();
			}
			this.ws.workbook.dependencyFormulas.addToCleanCellCache(this.ws.getId(), this.nRow, this.nCol);
			AscCommonExcel.g_oVLOOKUPCache.remove(this);
			AscCommonExcel.g_oHLOOKUPCache.remove(this);
		}
konovalovsergey's avatar
konovalovsergey committed
5381
	};
5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392
	Cell.prototype._BuildDependencies = function(parse, opt_dirty) {
		if (this.formulaParsed) {
			if (parse) {
				this.formulaParsed.parse();
			}
			this.formulaParsed.buildDependencies();
			if (opt_dirty || this.formulaParsed.ca || !this.oValue.getValueWithoutFormat()) {
				this.ws.workbook.dependencyFormulas.addToChangedCell(this);
			}
		}
	};
5393 5394
//-------------------------------------------------------------------------------------------------

5395 5396 5397 5398 5399 5400 5401 5402
	function CellAndValue(c, v) {
		this.c = c;
		this.v = v;
	}
	CellAndValue.prototype.valueOf = function() {
		return this.v;
	};

5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428
	/**
	 * @constructor
	 */
	function Range(worksheet, r1, c1, r2, c2){
		this.worksheet = worksheet;
		this.bbox = new Asc.Range(c1, r1, c2, r2);
	}
	Range.prototype.createFromBBox=function(worksheet, bbox){
		var oRes = new Range(worksheet, bbox.r1, bbox.c1, bbox.r2, bbox.c2);
		oRes.bbox = bbox.clone();
		return oRes;
	};
	Range.prototype.clone=function(oNewWs){
		if(!oNewWs)
			oNewWs = this.worksheet;
		return this.createFromBBox(oNewWs, this.bbox);
	};
	Range.prototype._foreach=function(action){
		if(null != action)
		{
			var oBBox = this.bbox;
			for(var i = oBBox.r1; i <= oBBox.r2; i++){
				for(var j = oBBox.c1; j <= oBBox.c2; j++){
					var oCurCell = this.worksheet._getCell(i, j);
					action(oCurCell, i, j, oBBox.r1, oBBox.c1);
				}
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
5429 5430
			}
		}
5431 5432 5433 5434 5435 5436 5437 5438
	};
	Range.prototype._foreach2=function(action){
		if(null != action)
		{
			var oBBox = this.bbox, minC = Math.min( this.worksheet.getColsCount(), oBBox.c2 ), minR = Math.min( this.worksheet.getRowsCount(), oBBox.r2 );
			for(var i = oBBox.r1; i <= minR; i++){
				for(var j = oBBox.c1; j <= minC; j++){
					var oCurCell = this.worksheet._getCellNoEmpty(i, j);
5439 5440 5441 5442 5443 5444
					var oRes = action(oCurCell, i, j, oBBox.r1, oBBox.c1);
					if(null != oRes)
						return oRes;
				}
			}
		}
5445
	};
5446
Range.prototype._foreachNoEmpty=function(action, excludeHiddenRows){
5447
		if(null != action)
5448
		{
5449 5450
			var oBBox = this.bbox, minC = Math.min( this.worksheet.getColsCount(), oBBox.c2 ), minR = Math.min( this.worksheet.getRowsCount(), oBBox.r2 );
			for(var i = oBBox.r1; i <= minR; i++){
5451 5452
			if (excludeHiddenRows && this.worksheet.getRowHidden(i)) {
				continue;
5453
			}
5454 5455
				for(var j = oBBox.c1; j <= minC; j++){
					var oCurCell = this.worksheet._getCellNoEmpty(i, j);
5456 5457
					if(null != oCurCell)
					{
5458
						var oRes = action(oCurCell, i, j, oBBox.r1, oBBox.c1);
5459 5460 5461 5462
						if(null != oRes)
							return oRes;
					}
				}
5463
			}
5464
		}
5465 5466 5467 5468 5469
	};
	Range.prototype._foreachRow=function(actionRow, actionCell){
		var oBBox = this.bbox;
		for(var i = oBBox.r1; i <= oBBox.r2; i++){
			var row = this.worksheet._getRow(i);
5470 5471
			if(row)
			{
5472 5473 5474
				if(null != actionRow)
					actionRow(row);
				if(null != actionCell)
5475 5476 5477 5478
				{
					for(var j in row.c){
						var oCurCell = row.c[j];
						if(null != oCurCell)
5479
							actionCell(oCurCell, i, j - 0, oBBox.r1, oBBox.c1);
5480
					}
5481
				}
5482 5483
			}
		}
5484 5485 5486 5487
	};
	Range.prototype._foreachRowNoEmpty=function(actionRow, actionCell){
		var oBBox = this.bbox;
		if(0 == oBBox.r1 && gc_nMaxRow0 == oBBox.r2)
5488 5489 5490 5491 5492
		{
			var aRows = this.worksheet._getRows();
			for(var i in aRows)
			{
				var row = aRows[i];
5493
				if( null != actionRow )
5494
				{
5495 5496 5497
					var oRes = actionRow(row);
					if(null != oRes)
						return oRes;
5498
				}
5499 5500
				if( null != actionCell )
					for(var j in row.c){
5501 5502
						var oCurCell = row.c[j];
						if(null != oCurCell)
5503 5504 5505 5506 5507
						{
							var oRes = actionCell(oCurCell, i - 0, j - 0, oBBox.r1, oBBox.c1);
							if(null != oRes)
								return oRes;
						}
5508 5509 5510
					}
			}
		}
5511
		else
5512
		{
5513 5514 5515
			var minR = Math.min(oBBox.r2,this.worksheet.getRowsCount());
			for(var i = oBBox.r1; i <= minR; i++){
				var row = this.worksheet._getRowNoEmpty(i);
5516 5517
				if(row)
				{
5518
					if( null != actionRow )
5519
					{
5520
						var oRes = actionRow(row);
5521 5522 5523
						if(null != oRes)
							return oRes;
					}
5524 5525
					if( null != actionCell )
						for(var j in row.c){
5526 5527 5528
							var oCurCell = row.c[j];
							if(null != oCurCell)
							{
5529
								var oRes = actionCell(oCurCell, i, j - 0, oBBox.r1, oBBox.c1);
5530 5531 5532 5533 5534 5535 5536
								if(null != oRes)
									return oRes;
							}
						}
				}
			}
		}
5537 5538 5539
	};
	Range.prototype._foreachCol=function(actionCol, actionCell){
		var oBBox = this.bbox;
5540 5541
		if(null != actionCol)
		{
5542
			for(var i = oBBox.c1; i <= oBBox.c2; ++i)
5543
			{
5544
				var col = this.worksheet._getCol(i);
5545
				if(null != col)
5546
					actionCol(col);
5547 5548 5549 5550 5551 5552 5553 5554 5555 5556
			}
		}
		if(null != actionCell)
		{
			var aRows = this.worksheet._getRows();
			for(var i in aRows)
			{
				var row = aRows[i];
				if(row)
				{
5557
					if(0 == oBBox.c1 && gc_nMaxCol0 == oBBox.c2)
5558
					{
5559
						for(var j in row.c)
5560 5561 5562
						{
							var oCurCell = row.c[j];
							if(null != oCurCell)
5563 5564 5565 5566 5567 5568 5569 5570 5571 5572
								actionCell(oCurCell, i - 0, j - 0, oBBox.r1, oBBox.c1);
						}
					}
					else
					{
						for(var j = oBBox.c1; j <= oBBox.c2; ++j)
						{
							var oCurCell = row.c[j];
							if(null != oCurCell)
								actionCell(oCurCell, i - 0, j, oBBox.r1, oBBox.c1);
5573 5574 5575 5576 5577
						}
					}
				}
			}
		}
5578 5579 5580 5581 5582
	};
	Range.prototype._foreachColNoEmpty=function(actionCol, actionCell){
		var oBBox = this.bbox;
		var minC = Math.min( oBBox.c2,this.worksheet.getColsCount() );
		if(0 == oBBox.c1 && gc_nMaxCol0 == oBBox.c2)
5583
		{
5584
			if(null != actionCol)
5585
			{
5586 5587
				var aCols = this.worksheet._getCols();
				for(var i in aCols)
5588
				{
5589 5590 5591 5592 5593
					var nIndex = i - 0;
					if(nIndex >= oBBox.c1 && nIndex <= minC )
					{
						var col = this.worksheet._getColNoEmpty(nIndex);
						if(null != col)
5594
						{
5595
							var oRes = actionCol(col);
5596 5597 5598 5599 5600 5601
							if(null != oRes)
								return oRes;
						}
					}
				}
			}
5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624
			if(null != actionCell)
			{
				var aRows = this.worksheet._getRows();
				for(var i in aRows)
				{
					var row = aRows[i];
					if(row)
					{
						for(var j in row.c)
						{
							var nIndex = j - 0;
							if(nIndex >= oBBox.c1 && nIndex <= minC)
							{
								var oCurCell = row.c[j];
								if(null != oCurCell)
								{
									var oRes = actionCell(oCurCell, i - 0, nIndex, oBBox.r1, oBBox.c1);
									if(null != oRes)
										return oRes;
								}
							}
						}
					}
5625 5626 5627
				}
			}
		}
5628
		else
5629
		{
5630
			if(null != actionCol)
5631
			{
5632
				for(var i = oBBox.c1; i <= minC; ++i)
5633
				{
5634 5635
					var col = this.worksheet._getColNoEmpty(i);
					if(null != col)
5636
					{
5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651
						var oRes = actionCol(col);
						if(null != oRes)
							return oRes;
					}
				}
			}
			if(null != actionCell)
			{
				var aRows = this.worksheet._getRows();
				for(var i in aRows)
				{
					var row = aRows[i];
					if(row)
					{
						for(var j = oBBox.c1; j <= minC; ++j)
5652
						{
5653 5654 5655 5656 5657 5658 5659
							var oCurCell = row.c[j];
							if(null != oCurCell)
							{
								var oRes = actionCell(oCurCell, i - 0, j, oBBox.r1, oBBox.c1);
								if(null != oRes)
									return oRes;
							}
5660 5661 5662 5663 5664
						}
					}
				}
			}
		}
5665 5666 5667
	};
	Range.prototype._foreachIndex=function(action){
		var oBBox = this.bbox;
5668 5669
		for(var i = oBBox.r1; i <= oBBox.r2; i++){
			for(var j = oBBox.c1; j <= oBBox.c2; j++){
5670 5671 5672
				var res = action(i, j);
				if(null != res)
					return res;
5673 5674
			}
		}
5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715
		return null;
	};
	Range.prototype._getRangeType=function(oBBox){
		if(null == oBBox)
			oBBox = this.bbox;
		return getRangeType(oBBox);
	};
	Range.prototype._getValues = function (withEmpty) {
		var res = [];
		var fAction = function(c) {
			res.push(new CellAndValue(c, c.getValueWithoutFormat()));
		};
		if (withEmpty) {
			this._setProperty(null, null, fAction);
		} else {
			this._setPropertyNoEmpty(null, null, fAction);
		}
		return res;
	};
	Range.prototype._getValuesAndMap = function (withEmpty) {
		var v, arrRes = [], mapRes = {};
		var fAction = function(c) {
			v = c.getValueWithoutFormat();
			arrRes.push(new CellAndValue(c, v));
			mapRes[v.toLowerCase()] = true;
		};
		if (withEmpty) {
			this._setProperty(null, null, fAction);
		} else {
			this._setPropertyNoEmpty(null, null, fAction);
		}
		return {values: arrRes, map: mapRes};
	};
	Range.prototype._setProperty=function(actionRow, actionCol, actionCell){
		var nRangeType = this._getRangeType();
		if(c_oRangeType.Range == nRangeType)
			this._foreach(actionCell);
		else if(c_oRangeType.Row == nRangeType)
			this._foreachRow(actionRow, actionCell);
		else if(c_oRangeType.Col == nRangeType)
			this._foreachCol(actionCol, actionCell);
5716
		else
5717
		{
5718 5719 5720
			//сюда не должны заходить вообще
			// this._foreachRow(actionRow, actionCell);
			// if(null != actionCol)
5721 5722
			// this._foreachCol(actionCol, null);
		}
5723 5724 5725 5726 5727 5728 5729 5730 5731
	};
	Range.prototype._setPropertyNoEmpty=function(actionRow, actionCol, actionCell){
		var nRangeType = this._getRangeType();
		if(c_oRangeType.Range == nRangeType)
			return this._foreachNoEmpty(actionCell);
		else if(c_oRangeType.Row == nRangeType)
			return this._foreachRowNoEmpty(actionRow, actionCell);
		else if(c_oRangeType.Col == nRangeType)
			return this._foreachColNoEmpty(actionCol, actionCell);
5732 5733
		else
		{
5734 5735 5736 5737 5738
			var oRes = this._foreachRowNoEmpty(actionRow, actionCell);
			if(null != oRes)
				return oRes;
			if(null != actionCol)
				oRes = this._foreachColNoEmpty(actionCol, null);
5739
			return oRes;
5740
		}
5741 5742 5743 5744
	};
	Range.prototype.containCell=function(cellId){
		var cellAddress = cellId;
		return 	cellAddress.getRow0() >= this.bbox.r1 && cellAddress.getCol0() >= this.bbox.c1 &&
5745
			cellAddress.getRow0() <= this.bbox.r2 && cellAddress.getCol0() <= this.bbox.c2;
5746 5747 5748
	};
	Range.prototype.containCell2=function(cell){
		return 	cell.nRow >= this.bbox.r1 && cell.nCol >= this.bbox.c1 &&
5749
			cell.nRow <= this.bbox.r2 && cell.nCol <= this.bbox.c2;
5750
	};
5751 5752
	Range.prototype.cross = function(bbox){
		if( bbox.r1 >= this.bbox.r1 && bbox.r1 <= this.bbox.r2 && this.bbox.c1 == this.bbox.c2)
5753
			return {r:bbox.r1};
5754
		if( bbox.c1 >= this.bbox.c1 && bbox.c1 <= this.bbox.c2 && this.bbox.r1 == this.bbox.r2)
5755
			return {c:bbox.c1};
5756

5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782
		return undefined;
	};
	Range.prototype.getWorksheet=function(){
		return this.worksheet;
	};
	Range.prototype.isFormula = function(){
		var nRow = this.bbox.r1;
		var nCol = this.bbox.c1;
		var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
		return cell.isFormula();
	};
	Range.prototype.isOneCell=function(){
		var oBBox = this.bbox;
		return oBBox.r1 == oBBox.r2 && oBBox.c1 == oBBox.c2;
	};
	Range.prototype.getBBox0=function(){
		//0 - based
		return this.bbox;
	};
	Range.prototype.getName=function(){
		return this.bbox.getName();
	};
	Range.prototype.getCells=function(){
		var aResult = [];
		var oBBox = this.bbox;
		if(!((0 == oBBox.c1 && gc_nMaxCol0 == oBBox.c2) || (0 == oBBox.r1 && gc_nMaxRow0 == oBBox.r2)))
5783
		{
5784 5785 5786 5787
			for(var i = oBBox.r1; i <= oBBox.r2; i++){
				for(var j = oBBox.c1; j <= oBBox.c2; j++){
					aResult.push(this.worksheet._getCell(i, j));
				}
5788 5789
			}
		}
5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811
		return aResult;
	};
	Range.prototype.setValue=function(val,callback, isCopyPaste){
		History.Create_NewPoint();
		History.StartTransaction();
		this._foreach(function(cell){
			cell.setValue(val,callback, isCopyPaste);
			// if(cell.isEmpty())
			// cell.Remove();
		});
		History.EndTransaction();
	};
	Range.prototype.setValue2=function(array){
		History.Create_NewPoint();
		History.StartTransaction();
		//[{"text":"qwe","format":{"b":true, "i":false, "u":Asc.EUnderline.underlineNone, "s":false, "fn":"Arial", "fs": 12, "c": 0xff00ff, "va": "subscript"  }},{}...]
		/*
		 Устанавливаем значение в Range ячеек. В отличае от setValue, сюда мы попадаем только в случае ввода значения отличного от формулы. Таким образом, если в ячейке была формула, то для нее в графе очищается список ячеек от которых зависела. После чего выставляем флаг о необходимости пересчета.
		 */
		this._foreach(function(cell){
			cell.setValue2(array);
			// if(cell.isEmpty())
5812
			// cell.Remove();
5813
		});
5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885
		History.EndTransaction();
	};
	Range.prototype.setCellStyle=function(val){
		History.Create_NewPoint();
		this.createCellOnRowColCross();
		var fSetProperty = this._setProperty;
		var nRangeType = this._getRangeType();
		if(c_oRangeType.All == nRangeType)
		{
			this.worksheet.getAllCol().setCellStyle(val);
			fSetProperty = this._setPropertyNoEmpty;
		}
		fSetProperty.call(this, function(row){
							  if(c_oRangeType.All == nRangeType && null == row.xfs)
								  return;
							  row.setCellStyle(val);
						  },
						  function(col){
							  col.setCellStyle(val);
						  },
						  function(cell){
							  cell.setCellStyle(val);
						  });
	};
	Range.prototype.setTableStyle=function(val){
		this.createCellOnRowColCross();
		var fSetProperty = this._setProperty;
		var nRangeType = this._getRangeType();
		if(c_oRangeType.All == nRangeType || null === val)
		{
			//this.worksheet.getAllCol().setCellStyle(val);
			fSetProperty = this._setPropertyNoEmpty;
		}
		fSetProperty.call(this, function(row){
							  if(c_oRangeType.All == nRangeType && null == row.xfs)
								  return;
							  //row.setCellStyle(val);
						  },
						  function(col){
							  //col.setCellStyle(val);
						  },
						  function(cell){
							  cell.setTableStyle(val);
						  });
	};
	Range.prototype.setNumFormat=function(val){
		History.Create_NewPoint();
		this.createCellOnRowColCross();
		var fSetProperty = this._setProperty;
		var nRangeType = this._getRangeType();
		if(c_oRangeType.All == nRangeType)
		{
			this.worksheet.getAllCol().setNumFormat(val);
			fSetProperty = this._setPropertyNoEmpty;
		}
		fSetProperty.call(this, function(row){
							  if(c_oRangeType.All == nRangeType && null == row.xfs)
								  return;
							  row.setNumFormat(val);
						  },
						  function(col){
							  col.setNumFormat(val);
						  },
						  function(cell){
							  cell.setNumFormat(val);
						  });
	};
	Range.prototype.shiftNumFormat=function(nShift, aDigitsCount){
		History.Create_NewPoint();
		var bRes = false;
		this._setPropertyNoEmpty(null, null, function(cell, nRow0, nCol0, nRowStart, nColStart){
			bRes |= cell.shiftNumFormat(nShift, aDigitsCount[nCol0 - nColStart] || 8);
5886
		});
5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183
		return bRes;
	};
	Range.prototype.setFont=function(val){
		History.Create_NewPoint();
		this.createCellOnRowColCross();
		var fSetProperty = this._setProperty;
		var nRangeType = this._getRangeType();
		if(c_oRangeType.All == nRangeType)
		{
			this.worksheet.getAllCol().setFont(val);
			fSetProperty = this._setPropertyNoEmpty;
		}
		fSetProperty.call(this, function(row){
							  if(c_oRangeType.All == nRangeType && null == row.xfs)
								  return;
							  row.setFont(val);
						  },
						  function(col){
							  col.setFont(val);
						  },
						  function(cell){
							  cell.setFont(val);
						  });
	};
	Range.prototype.setFontname=function(val){
		History.Create_NewPoint();
		this.createCellOnRowColCross();
		var fSetProperty = this._setProperty;
		var nRangeType = this._getRangeType();
		if(c_oRangeType.All == nRangeType)
		{
			this.worksheet.getAllCol().setFontname(val);
			fSetProperty = this._setPropertyNoEmpty;
		}
		fSetProperty.call(this, function(row){
							  if(c_oRangeType.All == nRangeType && null == row.xfs)
								  return;
							  row.setFontname(val);
						  },
						  function(col){
							  col.setFontname(val);
						  },
						  function(cell){
							  cell.setFontname(val);
						  });
	};
	Range.prototype.setFontsize=function(val){
		History.Create_NewPoint();
		this.createCellOnRowColCross();
		var fSetProperty = this._setProperty;
		var nRangeType = this._getRangeType();
		if(c_oRangeType.All == nRangeType)
		{
			this.worksheet.getAllCol().setFontsize(val);
			fSetProperty = this._setPropertyNoEmpty;
		}
		fSetProperty.call(this, function(row){
							  if(c_oRangeType.All == nRangeType && null == row.xfs)
								  return;
							  row.setFontsize(val);
						  },
						  function(col){
							  col.setFontsize(val);
						  },
						  function(cell){
							  cell.setFontsize(val);
						  });
	};
	Range.prototype.setFontcolor=function(val){
		History.Create_NewPoint();
		this.createCellOnRowColCross();
		var fSetProperty = this._setProperty;
		var nRangeType = this._getRangeType();
		if(c_oRangeType.All == nRangeType)
		{
			this.worksheet.getAllCol().setFontcolor(val);
			fSetProperty = this._setPropertyNoEmpty;
		}
		fSetProperty.call(this, function(row){
							  if(c_oRangeType.All == nRangeType && null == row.xfs)
								  return;
							  row.setFontcolor(val);
						  },
						  function(col){
							  col.setFontcolor(val);
						  },
						  function(cell){
							  cell.setFontcolor(val);
						  });
	};
	Range.prototype.setBold=function(val){
		History.Create_NewPoint();
		this.createCellOnRowColCross();
		var fSetProperty = this._setProperty;
		var nRangeType = this._getRangeType();
		if(c_oRangeType.All == nRangeType)
		{
			this.worksheet.getAllCol().setBold(val);
			fSetProperty = this._setPropertyNoEmpty;
		}
		fSetProperty.call(this, function(row){
							  if(c_oRangeType.All == nRangeType && null == row.xfs)
								  return;
							  row.setBold(val);
						  },
						  function(col){
							  col.setBold(val);
						  },
						  function(cell){
							  cell.setBold(val);
						  });
	};
	Range.prototype.setItalic=function(val){
		History.Create_NewPoint();
		this.createCellOnRowColCross();
		var fSetProperty = this._setProperty;
		var nRangeType = this._getRangeType();
		if(c_oRangeType.All == nRangeType)
		{
			this.worksheet.getAllCol().setItalic(val);
			fSetProperty = this._setPropertyNoEmpty;
		}
		fSetProperty.call(this, function(row){
							  if(c_oRangeType.All == nRangeType && null == row.xfs)
								  return;
							  row.setItalic(val);
						  },
						  function(col){
							  col.setItalic(val);
						  },
						  function(cell){
							  cell.setItalic(val);
						  });
	};
	Range.prototype.setUnderline=function(val){
		History.Create_NewPoint();
		this.createCellOnRowColCross();
		var fSetProperty = this._setProperty;
		var nRangeType = this._getRangeType();
		if(c_oRangeType.All == nRangeType)
		{
			this.worksheet.getAllCol().setUnderline(val);
			fSetProperty = this._setPropertyNoEmpty;
		}
		fSetProperty.call(this, function(row){
							  if(c_oRangeType.All == nRangeType && null == row.xfs)
								  return;
							  row.setUnderline(val);
						  },
						  function(col){
							  col.setUnderline(val);
						  },
						  function(cell){
							  cell.setUnderline(val);
						  });
	};
	Range.prototype.setStrikeout=function(val){
		History.Create_NewPoint();
		this.createCellOnRowColCross();
		var fSetProperty = this._setProperty;
		var nRangeType = this._getRangeType();
		if(c_oRangeType.All == nRangeType)
		{
			this.worksheet.getAllCol().setStrikeout(val);
			fSetProperty = this._setPropertyNoEmpty;
		}
		fSetProperty.call(this, function(row){
							  if(c_oRangeType.All == nRangeType && null == row.xfs)
								  return;
							  row.setStrikeout(val);
						  },
						  function(col){
							  col.setStrikeout(val);
						  },
						  function(cell){
							  cell.setStrikeout(val);
						  });
	};
	Range.prototype.setFontAlign=function(val){
		History.Create_NewPoint();
		this.createCellOnRowColCross();
		var fSetProperty = this._setProperty;
		var nRangeType = this._getRangeType();
		if(c_oRangeType.All == nRangeType)
		{
			this.worksheet.getAllCol().setFontAlign(val);
			fSetProperty = this._setPropertyNoEmpty;
		}
		fSetProperty.call(this, function(row){
							  if(c_oRangeType.All == nRangeType && null == row.xfs)
								  return;
							  row.setFontAlign(val);
						  },
						  function(col){
							  col.setFontAlign(val);
						  },
						  function(cell){
							  cell.setFontAlign(val);
						  });
	};
	Range.prototype.setAlignVertical=function(val){
		History.Create_NewPoint();
		this.createCellOnRowColCross();
		var fSetProperty = this._setProperty;
		var nRangeType = this._getRangeType();
		if(c_oRangeType.All == nRangeType)
		{
			this.worksheet.getAllCol().setAlignVertical(val);
			fSetProperty = this._setPropertyNoEmpty;
		}
		fSetProperty.call(this, function(row){
							  if(c_oRangeType.All == nRangeType && null == row.xfs)
								  return;
							  row.setAlignVertical(val);
						  },
						  function(col){
							  col.setAlignVertical(val);
						  },
						  function(cell){
							  cell.setAlignVertical(val);
						  });
	};
	Range.prototype.setAlignHorizontal=function(val){
		History.Create_NewPoint();
		this.createCellOnRowColCross();
		var fSetProperty = this._setProperty;
		var nRangeType = this._getRangeType();
		if(c_oRangeType.All == nRangeType)
		{
			this.worksheet.getAllCol().setAlignHorizontal(val);
			fSetProperty = this._setPropertyNoEmpty;
		}
		fSetProperty.call(this, function(row){
							  if(c_oRangeType.All == nRangeType && null == row.xfs)
								  return;
							  row.setAlignHorizontal(val);
						  },
						  function(col){
							  col.setAlignHorizontal(val);
						  },
						  function(cell){
							  cell.setAlignHorizontal(val);
						  });
	};
	Range.prototype.setFill=function(val){
		History.Create_NewPoint();
		this.createCellOnRowColCross();
		var fSetProperty = this._setProperty;
		var nRangeType = this._getRangeType();
		if(c_oRangeType.All == nRangeType)
		{
			this.worksheet.getAllCol().setFill(val);
			fSetProperty = this._setPropertyNoEmpty;
		}
		fSetProperty.call(this, function(row){
							  if(c_oRangeType.All == nRangeType && null == row.xfs)
								  return;
							  row.setFill(val);
						  },
						  function(col){
							  col.setFill(val);
						  },
						  function(cell){
							  cell.setFill(val);
						  });
	};
	Range.prototype.setBorderSrc=function(border){
		History.Create_NewPoint();
		History.StartTransaction();
		if (null == border)
			border = new Border();
		this.createCellOnRowColCross();
		var fSetProperty = this._setProperty;
		var nRangeType = this._getRangeType();
		if(c_oRangeType.All == nRangeType)
		{
			this.worksheet.getAllCol().setBorder(border.clone());
			fSetProperty = this._setPropertyNoEmpty;
		}
		fSetProperty.call(this, function(row){
							  if(c_oRangeType.All == nRangeType && null == row.xfs)
								  return;
							  row.setBorder(border.clone());
						  },
						  function(col){
							  col.setBorder(border.clone());
						  },
						  function(cell){
							  cell.setBorder(border.clone());
						  });
		History.EndTransaction();
	};
	Range.prototype._setBorderMerge=function(bLeft, bTop, bRight, bBottom, oNewBorder, oCurBorder){
		var oTargetBorder = new Border();
		//не делаем clone для свойств потому у нас нельзя поменять свойство отдельное свойство border можно только применить border целиком
		if(bLeft)
			oTargetBorder.l = oNewBorder.l;
6184
		else
6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202
			oTargetBorder.l = oNewBorder.iv;
		if(bTop)
			oTargetBorder.t = oNewBorder.t;
		else
			oTargetBorder.t = oNewBorder.ih;
		if(bRight)
			oTargetBorder.r = oNewBorder.r;
		else
			oTargetBorder.r = oNewBorder.iv;
		if(bBottom)
			oTargetBorder.b = oNewBorder.b;
		else
			oTargetBorder.b = oNewBorder.ih;
		oTargetBorder.d = oNewBorder.d;
		oTargetBorder.dd = oNewBorder.dd;
		oTargetBorder.du = oNewBorder.du;
		var oRes = null;
		if(null != oCurBorder)
6203
		{
6204 6205
			oCurBorder.mergeInner(oTargetBorder);
			oRes = oCurBorder;
6206
		}
6207 6208 6209 6210 6211 6212 6213
		else
			oRes = oTargetBorder;
		return oRes;
	};
	Range.prototype._setCellBorder=function(bbox, cell, oNewBorder){
		if(null == oNewBorder)
			cell.setBorder(oNewBorder);
6214 6215
		else
		{
6216 6217 6218 6219 6220 6221 6222 6223
			var oCurBorder = null;
			if(null != cell.xfs && null != cell.xfs.border)
				oCurBorder = cell.xfs.border.clone();
			else
				oCurBorder = g_oDefaultFormat.Border.clone();
			var nRow = cell.nRow;
			var nCol = cell.nCol;
			cell.setBorder(this._setBorderMerge(nCol == bbox.c1, nRow == bbox.r1, nCol == bbox.c2, nRow == bbox.r2, oNewBorder, oCurBorder));
6224
		}
6225 6226
	};
	Range.prototype._setRowColBorder=function(bbox, rowcol, bRow, oNewBorder){
6227
		if(null == oNewBorder)
6228
			rowcol.setBorder(oNewBorder);
6229
		else
6230
		{
6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254
			var oCurBorder = null;
			if(null != rowcol.xfs && null != rowcol.xfs.border)
				oCurBorder = rowcol.xfs.border.clone();
			var bLeft, bTop, bRight, bBottom = false;
			if(bRow)
			{
				bTop = rowcol.index == bbox.r1;
				bBottom = rowcol.index == bbox.r2;
			}
			else
			{
				bLeft = rowcol.index == bbox.c1;
				bRight = rowcol.index == bbox.c2;
			}
			rowcol.setBorder(this._setBorderMerge(bLeft, bTop, bRight, bBottom, oNewBorder, oCurBorder));
		}
	};
	Range.prototype._setBorderEdge=function(bbox, oItemWithXfs, nRow, nCol, oNewBorder){
		var oCurBorder = null;
		if(null != oItemWithXfs.xfs && null != oItemWithXfs.xfs.border)
			oCurBorder = oItemWithXfs.xfs.border;
		if(null != oCurBorder)
		{
			var oCurBorderProp = null;
6255
			if(nCol == bbox.c1 - 1)
6256
				oCurBorderProp = oCurBorder.r;
6257
			else if(nRow == bbox.r1 - 1)
6258
				oCurBorderProp = oCurBorder.b;
6259
			else if(nCol == bbox.c2 + 1)
6260
				oCurBorderProp = oCurBorder.l;
6261
			else if(nRow == bbox.r2 + 1)
6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279
				oCurBorderProp = oCurBorder.t;
			var oNewBorderProp = null;
			if(null == oNewBorder)
				oNewBorderProp = new AscCommonExcel.BorderProp();
			else
			{
				if(nCol == bbox.c1 - 1)
					oNewBorderProp = oNewBorder.l;
				else if(nRow == bbox.r1 - 1)
					oNewBorderProp = oNewBorder.t;
				else if(nCol == bbox.c2 + 1)
					oNewBorderProp = oNewBorder.r;
				else if(nRow == bbox.r2 + 1)
					oNewBorderProp = oNewBorder.b;
			}

			if(null != oNewBorderProp && null != oCurBorderProp && c_oAscBorderStyles.None != oCurBorderProp.s && (null == oNewBorder || c_oAscBorderStyles.None != oNewBorderProp.s) &&
				(oNewBorderProp.s != oCurBorderProp.s || oNewBorderProp.getRgbOrNull() != oCurBorderProp.getRgbOrNull())){
6280 6281
				var oTargetBorder = oCurBorder.clone();
				if(nCol == bbox.c1 - 1)
6282
					oTargetBorder.r = new AscCommonExcel.BorderProp();
6283
				else if(nRow == bbox.r1 - 1)
6284
					oTargetBorder.b = new AscCommonExcel.BorderProp();
6285
				else if(nCol == bbox.c2 + 1)
6286
					oTargetBorder.l = new AscCommonExcel.BorderProp();
6287
				else if(nRow == bbox.r2 + 1)
6288
					oTargetBorder.t = new AscCommonExcel.BorderProp();
6289
				oItemWithXfs.setBorder(oTargetBorder);
6290
			}
6291
		}
6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535
	};
	Range.prototype.setBorder=function(border){
		//border = null очисть border
		//"ih" - внутренние горизонтальные, "iv" - внутренние вертикальные
		History.Create_NewPoint();
		var _this = this;
		var oBBox = this.bbox;
		this.createCellOnRowColCross();
		var fSetProperty = this._setProperty;
		var nRangeType = this._getRangeType();
		if(c_oRangeType.All == nRangeType)
		{
			var oAllCol = this.worksheet.getAllCol();
			_this._setRowColBorder(oBBox, oAllCol, false, border);
			fSetProperty = this._setPropertyNoEmpty;
		}
		fSetProperty.call(this, function(row){
							  if(c_oRangeType.All == nRangeType && null == row.xfs)
								  return;
							  _this._setRowColBorder(oBBox, row, true, border);
						  },
						  function(col){
							  _this._setRowColBorder(oBBox, col, false, border);
						  },
						  function(cell){
							  _this._setCellBorder(oBBox, cell, border);
						  });
		//убираем граничные border
		var aEdgeBorders = [];
		if(oBBox.c1 > 0 && (null == border || !border.l.isEmpty()))
			aEdgeBorders.push(this.worksheet.getRange3(oBBox.r1, oBBox.c1 - 1, oBBox.r2, oBBox.c1 - 1));
		if(oBBox.r1 > 0 && (null == border || !border.t.isEmpty()))
			aEdgeBorders.push(this.worksheet.getRange3(oBBox.r1 - 1, oBBox.c1, oBBox.r1 - 1, oBBox.c2));
		if(oBBox.c2 < gc_nMaxCol0 && (null == border || !border.r.isEmpty()))
			aEdgeBorders.push(this.worksheet.getRange3(oBBox.r1, oBBox.c2 + 1, oBBox.r2, oBBox.c2 + 1));
		if(oBBox.r2 < gc_nMaxRow0 && (null == border || !border.b.isEmpty()))
			aEdgeBorders.push(this.worksheet.getRange3(oBBox.r2 + 1, oBBox.c1, oBBox.r2 + 1, oBBox.c2));
		for(var i = 0, length = aEdgeBorders.length; i < length; i++)
		{
			var range = aEdgeBorders[i];
			range._setPropertyNoEmpty(function(row){
										  if(c_oRangeType.All == nRangeType && null == row.xfs)
											  return;
										  _this._setBorderEdge(oBBox, row, row.index, 0, border);
									  },
									  function(col){
										  _this._setBorderEdge(oBBox, col, 0, col.index, border);
									  },
									  function(cell){
										  _this._setBorderEdge(oBBox, cell, cell.nRow, cell.nCol, border);
									  });
		}
	};
	Range.prototype.setShrinkToFit=function(val){
		History.Create_NewPoint();
		this.createCellOnRowColCross();
		var fSetProperty = this._setProperty;
		var nRangeType = this._getRangeType();
		if(c_oRangeType.All == nRangeType)
		{
			this.worksheet.getAllCol().setShrinkToFit(val);
			fSetProperty = this._setPropertyNoEmpty;
		}
		fSetProperty.call(this, function(row){
							  if(c_oRangeType.All == nRangeType && null == row.xfs)
								  return;
							  row.setShrinkToFit(val);
						  },
						  function(col){
							  col.setShrinkToFit(val);
						  },
						  function(cell){
							  cell.setShrinkToFit(val);
						  });
	};
	Range.prototype.setWrap=function(val){
		History.Create_NewPoint();
		this.createCellOnRowColCross();
		var fSetProperty = this._setProperty;
		var nRangeType = this._getRangeType();
		if(c_oRangeType.All == nRangeType)
		{
			this.worksheet.getAllCol().setWrap(val);
			fSetProperty = this._setPropertyNoEmpty;
		}
		fSetProperty.call(this, function(row){
							  if(c_oRangeType.All == nRangeType && null == row.xfs)
								  return;
							  row.setWrap(val);
						  },
						  function(col){
							  col.setWrap(val);
						  },
						  function(cell){
							  cell.setWrap(val);
						  });
	};
	Range.prototype.setAngle=function(val){
		History.Create_NewPoint();
		this.createCellOnRowColCross();
		var fSetProperty = this._setProperty;
		var nRangeType = this._getRangeType();
		if(c_oRangeType.All == nRangeType)
		{
			this.worksheet.getAllCol().setAngle(val);
			fSetProperty = this._setPropertyNoEmpty;
		}
		fSetProperty.call(this, function(row){
							  if(c_oRangeType.All == nRangeType && null == row.xfs)
								  return;
							  row.setAngle(val);
						  },
						  function(col){
							  col.setAngle(val);
						  },
						  function(cell){
							  cell.setAngle(val);
						  });
	};
	Range.prototype.setVerticalText=function(val){
		History.Create_NewPoint();
		this.createCellOnRowColCross();
		var fSetProperty = this._setProperty;
		var nRangeType = this._getRangeType();
		if(c_oRangeType.All == nRangeType)
		{
			this.worksheet.getAllCol().setVerticalText(val);
			fSetProperty = this._setPropertyNoEmpty;
		}
		fSetProperty.call(this, function(row){
							  if(c_oRangeType.All == nRangeType && null == row.xfs)
								  return;
							  row.setVerticalText(val);
						  },
						  function(col){
							  col.setVerticalText(val);
						  },
						  function(cell){
							  cell.setVerticalText(val);
						  });
	};
	Range.prototype.setType=function(type){
		History.Create_NewPoint();
		this.createCellOnRowColCross();
		var fSetProperty = this._setProperty;
		var nRangeType = this._getRangeType();
		if(c_oRangeType.All == nRangeType)
			fSetProperty = this._setPropertyNoEmpty;
		fSetProperty.call(this, null, null,
						  function(cell){
							  cell.setType(type);
						  });
	};
	Range.prototype.getType=function(){
		var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1);
		if(null != cell)
			return cell.getType();
		else
			return null;
	};
	Range.prototype.isEmptyText=function(){
		var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1);
		return (null != cell) ? cell.isEmptyText() : true;
	};
	Range.prototype.isEmptyTextString=function(){
		var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1);
		return (null != cell) ? cell.isEmptyTextString() : true;
	};
	Range.prototype.isFormula=function(){
		var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1);
		return (null != cell) ? cell.isFormula() : false;
	};
	Range.prototype.getFormula=function(){
		var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1);
		if(null != cell)
			return cell.getFormula();
		else
			return "";
	};
	Range.prototype.getValueForEdit=function(){
		var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1);
		if(null != cell)
		{
			var numFormat = this.getNumFormat();
			return cell.getValueForEdit(numFormat);
		}
		else
			return "";
	};
	Range.prototype.getValueForEdit2=function(){
		var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1);
		if(null != cell)
		{
			var numFormat = this.getNumFormat();
			return cell.getValueForEdit2(numFormat);
		}
		else
		{
			var oRow = this.worksheet._getRowNoEmpty(this.bbox.r1);
			var oCol = this.worksheet._getColNoEmptyWithAll(this.bbox.c1);
			var xfs = null;
			if(oRow && null != oRow.xfs)
				xfs = oRow.xfs.clone();
			else if(null != oCol && null != oCol.xfs)
				xfs = oCol.xfs.clone();
			var oTempCell = new Cell(this.worksheet);
			oTempCell.create(xfs, this.bbox.r1, this.bbox.c1);
			return oTempCell.getValueForEdit2();
		}
	};
	Range.prototype.getValueWithoutFormat=function(){
		var cell = this.worksheet._getCellNoEmpty(this.bbox.r1, this.bbox.c1);
		if(null != cell)
			return cell.getValueWithoutFormat();
		else
			return "";
	};
	Range.prototype.getValue=function(){
		return this.getValueWithoutFormat();
	};
	Range.prototype.getValueWithFormat=function(){
		var cell = this.worksheet._getCellNoEmpty(this.bbox.r1, this.bbox.c1);
		if(null != cell)
			return cell.getValue();
		else
			return "";
	};
	Range.prototype.getValue2=function(dDigitsCount, fIsFitMeasurer){
		//[{"text":"qwe","format":{"b":true, "i":false, "u":Asc.EUnderline.underlineNone, "s":false, "fn":"Arial", "fs": 12, "c": 0xff00ff, "va": "subscript"  }},{}...]
		var cell = this.worksheet._getCellNoEmpty(this.bbox.r1, this.bbox.c1);
		if(null != cell)
			return cell.getValue2(dDigitsCount, fIsFitMeasurer);
		else
		{
			var oRow = this.worksheet._getRowNoEmpty(this.bbox.r1);
			var oCol = this.worksheet._getColNoEmptyWithAll(this.bbox.c1);
			var xfs = null;
			if(oRow && null != oRow.xfs)
				xfs = oRow.xfs.clone();
			else if(null != oCol && null != oCol.xfs)
				xfs = oCol.xfs.clone();
			var oTempCell = new Cell(this.worksheet);
			oTempCell.create(xfs, this.bbox.r1, this.bbox.c1);
			return oTempCell.getValue2(dDigitsCount, fIsFitMeasurer);
6536
		}
6537 6538
	};
	Range.prototype.getXfId=function(){
6539 6540 6541
		var nRow = this.bbox.r1;
		var nCol = this.bbox.c1;
		var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578
		if(null != cell) {
			var xfs = cell.getCompiledStyle();
			if(null != xfs && null != xfs.XfId)
				return xfs.XfId;
		} else {
			//стили столбов и колонок
			var row = this.worksheet._getRowNoEmpty(nRow);
			if(row && null != row.xfs && null != row.xfs.XfId)
				return row.xfs.XfId;
			var col = this.worksheet._getColNoEmptyWithAll(nCol);
			if(null != col && null != col.xfs && null != col.xfs.XfId)
				return col.xfs.XfId;
		}
		return g_oDefaultFormat.XfId;
	};
	Range.prototype.getStyleName=function(){
		var res = this.worksheet.workbook.CellStyles.getStyleNameByXfId(this.getXfId());

		// ToDo убрать эту заглушку (нужно делать на открытии) в InitStyleManager
		return res || this.worksheet.workbook.CellStyles.getStyleNameByXfId(g_oDefaultFormat.XfId);
	};
	Range.prototype.getTableStyle=function(){
		var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1);
		return cell ? cell.getTableStyle() : null;
	};
	Range.prototype.getNumFormat=function(){
		return oNumFormatCache.get(this.getNumFormatStr());
	};
	Range.prototype.getNumFormatStr=function(){
		var nRow = this.bbox.r1;
		var nCol = this.bbox.c1;
		var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
		if(null != cell)
		{
			var xfs = cell.getCompiledStyle();
			if(null != xfs && null != xfs.num)
				return xfs.num.getFormat();
6579
		}
6580 6581 6582 6583 6584 6585 6586 6587 6588
		else
		{
			//стили столбов и колонок
			var row = this.worksheet._getRowNoEmpty(nRow);
			if(row && null != row.xfs && null != row.xfs.num)
				return row.xfs.num.getFormat();
			var col = this.worksheet._getColNoEmptyWithAll(nCol);
			if(null != col && null != col.xfs && null != col.xfs.num)
				return col.xfs.num.getFormat();
6589
		}
6590 6591 6592 6593 6594
		return g_oDefaultFormat.Num.getFormat();
	};
	Range.prototype.getNumFormatType=function(){
		return this.getNumFormat().getType();
	};
6595 6596 6597
	Range.prototype.getNumFormatTypeInfo=function(){
		return this.getNumFormat().getTypeInfo();
	};
6598
// Узнаем отличается ли шрифт (размер и гарнитура) в ячейке от шрифта в строке
6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619
	Range.prototype.isNotDefaultFont = function () {
		// Получаем фонт ячейки
		var cellFont = this.getFont();
		var rowFont = g_oDefaultFormat.Font;
		var row = this.worksheet._getRowNoEmpty(this.bbox.r1);
		if (row && null != row.xfs && null != row.xfs.font)
			rowFont = row.xfs.font;
		else if (null != this.worksheet.oAllCol && this.worksheet.oAllCol.xfs && this.worksheet.oAllCol.xfs.font)
			rowFont = this.worksheet.oAllCol.xfs.font;

		return (cellFont.getName() !== rowFont.getName() || cellFont.getSize() !== rowFont.getSize());
	};
	Range.prototype.getFont = function(){
		var nRow = this.bbox.r1;
		var nCol = this.bbox.c1;
		var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
		if(null != cell)
		{
			var xfs = cell.getCompiledStyle();
			if(null != xfs && null != xfs.font)
				return xfs.font;
6620
		}
6621 6622 6623 6624 6625 6626 6627 6628 6629
		else
		{
			//стили столбов и колонок
			var row = this.worksheet._getRowNoEmpty(nRow);
			if(row && null != row.xfs && null != row.xfs.font)
				return row.xfs.font;
			var col = this.worksheet._getColNoEmptyWithAll(nCol);
			if(null != col && null != col.xfs && null != col.xfs.font)
				return col.xfs.font;
6630
		}
6631 6632 6633
		return g_oDefaultFormat.Font;
	};
	Range.prototype.getAlignVertical=function(){
6634 6635 6636
		var nRow = this.bbox.r1;
		var nCol = this.bbox.c1;
		var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
6637 6638 6639 6640 6641 6642 6643
		if(null != cell)
		{
			var xfs = cell.getCompiledStyle();
			if(null != xfs)
			{
				if(null != xfs.align)
					return xfs.align.ver;
6644
				else
6645
					return g_oDefaultFormat.AlignAbs.ver;
6646
			}
6647
		}
6648
		else
6649
		{
6650 6651 6652 6653 6654 6655 6656
			//стили столбов и колонок
			var row = this.worksheet._getRowNoEmpty(nRow);
			if(row && null != row.xfs && null != row.xfs.align)
				return row.xfs.align.ver;
			var col = this.worksheet._getColNoEmptyWithAll(nCol);
			if(null != col && null != col.xfs && null != col.xfs.align)
				return col.xfs.align.ver;
6657
		}
6658 6659 6660 6661 6662 6663 6664
		return g_oDefaultFormat.Align.ver;
	};
	Range.prototype.getAlignHorizontal=function(){
		var nRow = this.bbox.r1;
		var nCol = this.bbox.c1;
		var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
		if(null != cell)
6665
		{
6666 6667
			var xfs = cell.getCompiledStyle();
			if(null != xfs)
6668
			{
6669 6670
				if(null != xfs.align)
					return xfs.align.hor;
6671
				else
6672 6673
					return g_oDefaultFormat.AlignAbs.hor;
			}
6674
		}
6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703
		else
		{
			//стили столбов и колонок
			var row = this.worksheet._getRowNoEmpty(nRow);
			if(row && null != row.xfs && null != row.xfs.align)
				return row.xfs.align.hor;
			var col = this.worksheet._getColNoEmptyWithAll(nCol);
			if(null != col && null != col.xfs && null != col.xfs.align)
				return col.xfs.align.hor;
		}
		return g_oDefaultFormat.Align.hor;
	};
	Range.prototype.getAlignHorizontalByValue=function(){
		//возвращает Align в зависимости от значния в ячейке
		//values:  none, center, justify, left , right, null
		var align = this.getAlignHorizontal();
		if(null == align){
			//пытаемся определить по значению
			var nRow = this.bbox.r1;
			var nCol = this.bbox.c1;
			var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
			if(cell){
				switch(cell.getType()){
					case CellValueType.String:align = AscCommon.align_Left;break;
					case CellValueType.Bool:
					case CellValueType.Error:align = AscCommon.align_Center;break;
					default:
						//Если есть value и не проставлен тип значит это число, у всех остальных типов значение не null
						if(this.getValueWithoutFormat())
6704
						{
6705 6706 6707 6708 6709 6710
							//смотрим
							var oNumFmt = this.getNumFormat();
							if(true == oNumFmt.isTextFormat())
								align = AscCommon.align_Left;
							else
								align = AscCommon.align_Right;
6711
						}
6712 6713 6714
						else
							align = AscCommon.align_Left;
						break;
6715 6716
				}
			}
6717 6718
			if(null == align)
				align = AscCommon.align_Left;
6719
		}
6720 6721 6722 6723 6724 6725 6726
		return align;
	};
	Range.prototype.getFill=function(){
		var nRow = this.bbox.r1;
		var nCol = this.bbox.c1;
		var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
		if(null != cell)
6727
		{
6728 6729 6730
			var xfs = cell.getCompiledStyle();
			if(null != xfs && null != xfs.fill)
				return xfs.fill.bg;
6731
		}
6732
		else
6733
		{
6734 6735 6736 6737 6738 6739 6740
			//стили столбов и колонок
			var row = this.worksheet._getRowNoEmpty(nRow);
			if(row && null != row.xfs && null != row.xfs.fill)
				return row.xfs.fill.bg;
			var col = this.worksheet._getColNoEmptyWithAll(nCol);
			if(null != col && null != col.xfs && null != col.xfs.fill)
				return col.xfs.fill.bg;
6741
		}
6742 6743
		return g_oDefaultFormat.Fill.bg;
	};
6744
	Range.prototype.getBorderSrc=function(opt_row, opt_col){
6745 6746 6747 6748 6749 6750
		//Возвращает как записано в файле, не проверяя бордеры соседних ячеек
		//формат
		//\{"l": {"s": "solid", "c": 0xff0000}, "t": {} ,"r": {} ,"b": {} ,"d": {},"dd": false ,"du": false }
		//"s" values: none, thick, thin, medium, dashDot, dashDotDot, dashed, dotted, double, hair, mediumDashDot, mediumDashDotDot, mediumDashed, slantDashDot
		//"dd" diagonal line, starting at the top left corner of the cell and moving down to the bottom right corner of the cell
		//"du" diagonal line, starting at the bottom left corner of the cell and moving up to the top right corner of the cell
6751 6752 6753
		var nRow = null != opt_row ? opt_row : this.bbox.r1;
		var nCol = null != opt_col ? opt_col : this.bbox.c1;

6754 6755
		var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
		if(null != cell)
6756
		{
6757 6758 6759
			var xfs = cell.getCompiledStyle();
			if(null != xfs && null != xfs.border)
				return xfs.border;
6760
		}
6761
		else
6762
		{
6763 6764 6765 6766 6767 6768 6769
			//стили столбов и колонок
			var row = this.worksheet._getRowNoEmpty(nRow);
			if(row && null != row.xfs && null != row.xfs.border)
				return row.xfs.border;
			var col = this.worksheet._getColNoEmptyWithAll(nCol);
			if(null != col && null != col.xfs && null != col.xfs.border)
				return col.xfs.border;
6770
		}
6771 6772
		return g_oDefaultFormat.Border;
	};
6773
	Range.prototype.getBorder=function(opt_row, opt_col){
6774 6775 6776 6777 6778 6779
		//Возвращает как записано в файле, не проверяя бордеры соседних ячеек
		//формат
		//\{"l": {"s": "solid", "c": 0xff0000}, "t": {} ,"r": {} ,"b": {} ,"d": {},"dd": false ,"du": false }
		//"s" values: none, thick, thin, medium, dashDot, dashDotDot, dashed, dotted, double, hair, mediumDashDot, mediumDashDotDot, mediumDashed, slantDashDot
		//"dd" diagonal line, starting at the top left corner of the cell and moving down to the bottom right corner of the cell
		//"du" diagonal line, starting at the bottom left corner of the cell and moving up to the top right corner of the cell
6780
		var oRes = this.getBorderSrc(opt_row, opt_col);
6781 6782
		if(null != oRes)
			return oRes;
6783
		else
6784 6785 6786 6787 6788 6789 6790 6791 6792 6793
			return g_oDefaultFormat.Border;
	};
	Range.prototype.getBorderFull=function(){
		//Возвращает как excel, т.е. проверяет бордеры соседних ячеек
		//
		//\{"l": {"s": "solid", "c": 0xff0000}, "t": {} ,"r": {} ,"b": {} ,"d": {},"dd": false ,"du": false }
		//"s" values: none, thick, thin, medium, dashDot, dashDotDot, dashed, dotted, double, hair, mediumDashDot, mediumDashDotDot, mediumDashed, slantDashDot
		//
		//"dd" diagonal line, starting at the top left corner of the cell and moving down to the bottom right corner of the cell
		//"du" diagonal line, starting at the bottom left corner of the cell and moving up to the top right corner of the cell
6794
		var borders = this.getBorder(this.bbox.r1, this.bbox.c1).clone();
6795 6796 6797 6798
		var nRow = this.bbox.r1;
		var nCol = this.bbox.c1;
		if(c_oAscBorderStyles.None === borders.l.s){
			if(nCol > 1){
6799
				var left = this.getBorder(nRow, nCol - 1);
6800 6801 6802
				if(c_oAscBorderStyles.None !== left.r.s)
					borders.l = left.r;
			}
6803
		}
6804 6805
		if(c_oAscBorderStyles.None === borders.t.s){
			if(nRow > 1){
6806
				var top = this.getBorder(nRow - 1, nCol);
6807 6808 6809 6810 6811
				if(c_oAscBorderStyles.None !== top.b.s)
					borders.t = top.b;
			}
		}
		if(c_oAscBorderStyles.None === borders.r.s){
6812
			var right = this.getBorder(nRow, nCol + 1);
6813 6814 6815 6816
			if(c_oAscBorderStyles.None !== right.l.s)
				borders.r = right.l;
		}
		if(c_oAscBorderStyles.None === borders.b.s){
6817
			var bottom = this.getBorder(nRow + 1, nCol);
6818 6819 6820 6821 6822 6823 6824 6825 6826 6827
			if(c_oAscBorderStyles.None !== bottom.t.s)
				borders.b = bottom.t;
		}
		return borders;
	};
	Range.prototype.getShrinkToFit=function(){
		var nRow = this.bbox.r1;
		var nCol = this.bbox.c1;
		var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
		if(null != cell)
6828
		{
6829 6830
			var xfs = cell.getCompiledStyle();
			if(null != xfs)
6831
			{
6832 6833
				if(null != xfs.align)
					return xfs.align.shrink;
6834
				else
6835
					return g_oDefaultFormat.AlignAbs.shrink;
6836
			}
6837 6838
		}
		else
6839
		{
6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864
			//стили столбов и колонок
			var row = this.worksheet._getRowNoEmpty(nRow);
			if(row && null != row.xfs && null != row.xfs.align)
				return row.xfs.align.shrink;
			var col = this.worksheet._getColNoEmptyWithAll(nCol);
			if(null != col && null != col.xfs && null != col.xfs.align)
				return col.xfs.align.shrink;
		}
		return g_oDefaultFormat.Align.shrink;
	};
	Range.prototype.getWrapByAlign = function (align) {
		// Для justify wrap всегда true
		return AscCommon.align_Justify === align.hor ? true : align.wrap;
	};
	Range.prototype.getWrap=function(){
		var nRow = this.bbox.r1;
		var nCol = this.bbox.c1;
		var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
		if(null != cell) {
			var xfs = cell.getCompiledStyle();
			if(null != xfs) {
				if(null != xfs.align)
					return this.getWrapByAlign(xfs.align);
				else
					return this.getWrapByAlign(g_oDefaultFormat.AlignAbs);
6865
			}
6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885
		} else {
			//стили столбов и колонок
			var row = this.worksheet._getRowNoEmpty(nRow);
			if(row && null != row.xfs && null != row.xfs.align)
				return this.getWrapByAlign(row.xfs.align);
			var col = this.worksheet._getColNoEmptyWithAll(nCol);
			if(null != col && null != col.xfs && null != col.xfs.align)
				return this.getWrapByAlign(col.xfs.align);
		}
		return this.getWrapByAlign(g_oDefaultFormat.Align);
	};
	Range.prototype.getAngle=function(){
		//угол от -90 до 90 против часовой стрелки от оси OX
		var nRow = this.bbox.r1;
		var nCol = this.bbox.c1;
		var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
		if(null != cell)
		{
			var xfs = cell.getCompiledStyle();
			if(null != xfs)
6886
			{
6887 6888 6889 6890
				if(null != xfs.align)
					return angleFormatToInterface(xfs.align.angle);
				else
					return angleFormatToInterface(g_oDefaultFormat.AlignAbs.angle);
6891 6892 6893 6894
			}
		}
		else
		{
6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924
			//стили столбов и колонок
			var row = this.worksheet._getRowNoEmpty(nRow);
			if(row && null != row.xfs && null != row.xfs.align)
				return angleFormatToInterface(row.xfs.align.angle);
			var col = this.worksheet._getColNoEmptyWithAll(nCol);
			if(null != col && null != col.xfs && null != col.xfs.align)
				return angleFormatToInterface(col.xfs.align.angle);
		}
		return angleFormatToInterface(g_oDefaultFormat.Align.angle);
	};
	Range.prototype.hasMerged=function(){
		var aMerged = this.worksheet.mergeManager.get(this.bbox);
		if(aMerged.all.length > 0)
			return aMerged.all[0].bbox;
		return null;
	};
	Range.prototype.mergeOpen=function(){
		this.worksheet.mergeManager.add(this.bbox, 1);
	};
	Range.prototype.merge=function(type){
		if(null == type)
			type = Asc.c_oAscMergeOptions.Merge;
		var oBBox = this.bbox;
		History.Create_NewPoint();
		History.StartTransaction();
		if(oBBox.r1 == oBBox.r2 && oBBox.c1 == oBBox.c2){
			if(type == Asc.c_oAscMergeOptions.MergeCenter)
				this.setAlignHorizontal(AscCommon.align_Center);
			History.EndTransaction();
			return;
6925
		}
6926
		if(this.hasMerged())
6927
		{
6928 6929
			this.unmerge();
			if(type == Asc.c_oAscMergeOptions.MergeCenter)
6930
			{
6931 6932 6933 6934
				//сбрасываем AlignHorizontal
				this.setAlignHorizontal(null);
				History.EndTransaction();
				return;
6935
			}
6936
		}
6937 6938 6939 6940 6941 6942 6943
		//пробегаемся по границе диапазона, чтобы посмотреть какие границы нужно оставлять
		var oLeftBorder = null;
		var oTopBorder = null;
		var oRightBorder = null;
		var oBottomBorder = null;
		var nRangeType = this._getRangeType(oBBox);
		if(c_oRangeType.Range == nRangeType)
6944
		{
6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990
			var oThis = this;
			var fGetBorder = function(bRow, v1, v2, v3, type)
			{
				var oRes = null;
				for(var i = v1; i <= v2; ++i)
				{
					var bNeedDelete = true;
					var oCurCell;
					if(bRow)
						oCurCell = oThis.worksheet._getCellNoEmpty(v3, i);
					else
						oCurCell = oThis.worksheet._getCellNoEmpty(i, v3);
					if(null != oCurCell && null != oCurCell.xfs && null != oCurCell.xfs.border)
					{
						var border = oCurCell.xfs.border;
						var oBorderProp;
						switch(type)
						{
							case 1: oBorderProp = border.l;break;
							case 2: oBorderProp = border.t;break;
							case 3: oBorderProp = border.r;break;
							case 4: oBorderProp = border.b;break;
						}
						if(false == oBorderProp.isEmpty())
						{
							if(null == oRes)
							{
								oRes = oBorderProp;
								bNeedDelete = false;
							}
							else if(true == oRes.isEqual(oBorderProp))
								bNeedDelete = false;
						}
					}
					if(bNeedDelete)
					{
						oRes = null;
						break;
					}
				}
				return oRes;
			};
			oLeftBorder = fGetBorder(false, oBBox.r1, oBBox.r2, oBBox.c1, 1);
			oTopBorder = fGetBorder(true, oBBox.c1, oBBox.c2, oBBox.r1, 2);
			oRightBorder = fGetBorder(false, oBBox.r1, oBBox.r2, oBBox.c2, 3);
			oBottomBorder = fGetBorder(true, oBBox.c1, oBBox.c2, oBBox.r2, 4);
6991
		}
6992
		else if(c_oRangeType.Row == nRangeType)
6993
		{
6994 6995 6996 6997
			var oTopRow = this.worksheet._getRowNoEmpty(oBBox.r1);
			if(oTopRow && null != oTopRow.xfs && null != oTopRow.xfs.border && false == oTopRow.xfs.border.t.isEmpty())
				oTopBorder = oTopRow.xfs.border.t;
			if(oBBox.r1 != oBBox.r2)
6998
			{
6999 7000 7001
				var oBottomRow = this.worksheet._getRowNoEmpty(oBBox.r2);
				if(oBottomRow && null != oBottomRow.xfs && null != oBottomRow.xfs.border && false == oBottomRow.xfs.border.b.isEmpty())
					oBottomBorder = oBottomRow.xfs.border.b;
7002 7003 7004 7005
			}
		}
		else
		{
7006 7007 7008 7009
			var oLeftCol = this.worksheet._getColNoEmptyWithAll(oBBox.c1);
			if(null != oLeftCol && null != oLeftCol.xfs && null != oLeftCol.xfs.border && false == oLeftCol.xfs.border.l.isEmpty())
				oLeftBorder = oLeftCol.xfs.border.l;
			if(oBBox.c1 != oBBox.c2)
7010
			{
7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047
				var oRightCol = this.worksheet._getColNoEmptyWithAll(oBBox.c2);
				if(null != oRightCol && null != oRightCol.xfs && null != oRightCol.xfs.border && false == oRightCol.xfs.border.r.isEmpty())
					oRightBorder = oRightCol.xfs.border.r;
			}
		}

		var bFirst = true;
		var oLeftTopCellStyle = null;
		var oFirstCellStyle = null;
		var oFirstCellValue = null;
		var oFirstCellRow = null;
		var oFirstCellCol = null;
		var oFirstCellHyperlink = null;
		this._setPropertyNoEmpty(null,null,
								 function(cell, nRow0, nCol0, nRowStart, nColStart){
									 if(bFirst && false == cell.isEmptyText())
									 {
										 bFirst = false;
										 oFirstCellStyle = cell.getStyle();
										 oFirstCellValue = cell.getValueData();
										 oFirstCellRow = cell.nRow;
										 oFirstCellCol = cell.nCol;

									 }
									 if(nRow0 == nRowStart && nCol0 == nColStart)
										 oLeftTopCellStyle = cell.getStyle();
								 });
		//правила работы с гиперссылками во время merge(отличются от Excel в случаем областей, например hyperlink: C3:D3 мержим C2:C3)
		// 1)оставляем все ссылки, которые не полностью лежат в merge области
		// 2)оставляем многоклеточные ссылки, top граница которых совпадает с top границей merge области, а высота merge > 1 или совпадает с высотой области merge
		// 3)оставляем и переносим в первую ячейку одну одноклеточную ссылку, если она находится в первой ячейке с данными
		var aHyperlinks = this.worksheet.hyperlinkManager.get(oBBox);
		var aHyperlinksToRestore = [];
		for(var i = 0, length = aHyperlinks.inner.length; i < length; i++)
		{
			var elem = aHyperlinks.inner[i];
			if(oFirstCellRow == elem.bbox.r1 && oFirstCellCol == elem.bbox.c1 && elem.bbox.r1 == elem.bbox.r2 && elem.bbox.c1 == elem.bbox.c2)
7048
			{
7049 7050 7051
				var oNewHyperlink = elem.data.clone();
				oNewHyperlink.Ref.setOffset({offsetCol:oBBox.c1 - oFirstCellCol, offsetRow:oBBox.r1 - oFirstCellRow});
				aHyperlinksToRestore.push(oNewHyperlink);
7052
			}
7053 7054
			else if( oBBox.r1 == elem.bbox.r1 && (elem.bbox.r1 != elem.bbox.r2 || (elem.bbox.c1 != elem.bbox.c2 && oBBox.r1 == oBBox.r2)))
				aHyperlinksToRestore.push(elem.data);
7055
		}
7056 7057 7058
		this.cleanAll();
		//восстанавливаем hyperlink
		for(var i = 0, length = aHyperlinksToRestore.length; i < length; i++)
7059
		{
7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070
			var elem = aHyperlinksToRestore[i];
			this.worksheet.hyperlinkManager.add(elem.Ref.getBBox0(), elem);
		}
		var oTargetStyle = null;
		if(null != oFirstCellValue && null != oFirstCellRow && null != oFirstCellCol)
		{
			if(null != oFirstCellStyle)
				oTargetStyle = oFirstCellStyle.clone();
			var oLeftTopCell = this.worksheet._getCell(oBBox.r1, oBBox.c1);
			oLeftTopCell.setValueData(oFirstCellValue);
			if(null != oFirstCellHyperlink)
7071
			{
7072 7073
				var oLeftTopRange = this.worksheet.getCell3(oBBox.r1, oBBox.c1);
				oLeftTopRange.setHyperlink(oFirstCellHyperlink, true);
7074
			}
7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252
		}
		else if(null != oLeftTopCellStyle)
			oTargetStyle = oLeftTopCellStyle.clone();

		//убираем бордеры
		if(null != oTargetStyle)
		{
			if(null != oTargetStyle.border)
				oTargetStyle.border = null;
		}
		else if(null != oLeftBorder || null != oTopBorder || null != oRightBorder || null != oBottomBorder)
			oTargetStyle = new AscCommonExcel.CellXfs();
		var fSetProperty = this._setProperty;
		var nRangeType = this._getRangeType();
		if(c_oRangeType.All == nRangeType)
		{
			fSetProperty = this._setPropertyNoEmpty;
			oTargetStyle = null
		}
		fSetProperty.call(this, function(row){
							  if(null == oTargetStyle)
								  row.setStyle(null);
							  else
							  {
								  var oNewStyle = oTargetStyle.clone();
								  if(row.index == oBBox.r1 && null != oTopBorder)
								  {
									  oNewStyle.border = new Border();
									  oNewStyle.border.t = oTopBorder.clone();
								  }
								  else if(row.index == oBBox.r2 && null != oBottomBorder)
								  {
									  oNewStyle.border = new Border();
									  oNewStyle.border.b = oBottomBorder.clone();
								  }
								  row.setStyle(oNewStyle);
							  }
						  },function(col){
							  if(null == oTargetStyle)
								  col.setStyle(null);
							  else
							  {
								  var oNewStyle = oTargetStyle.clone();
								  if(col.index == oBBox.c1 && null != oLeftBorder)
								  {
									  oNewStyle.border = new Border();
									  oNewStyle.border.l = oLeftBorder.clone();
								  }
								  else if(col.index == oBBox.c2 && null != oRightBorder)
								  {
									  oNewStyle.border = new Border();
									  oNewStyle.border.r = oRightBorder.clone();
								  }
								  col.setStyle(oNewStyle);
							  }
						  },
						  function(cell, nRow, nCol, nRowStart, nColStart){
							  //важно установить именно здесь, чтобы ячейка не удалилась после применения стилей.
							  if(null == oTargetStyle)
								  cell.setStyle(null);
							  else
							  {
								  var oNewStyle = oTargetStyle.clone();
								  if(oBBox.r1 == nRow && oBBox.c1 == nCol)
								  {
									  if(null != oLeftBorder || null != oTopBorder || (oBBox.r1 == oBBox.r2 && null != oBottomBorder) || (oBBox.c1 == oBBox.c2 && null != oRightBorder))
									  {
										  oNewStyle.border = new Border();
										  if(null != oLeftBorder)
											  oNewStyle.border.l = oLeftBorder.clone();
										  if(null != oTopBorder)
											  oNewStyle.border.t = oTopBorder.clone();
										  if(oBBox.r1 == oBBox.r2 && null != oBottomBorder)
											  oNewStyle.border.b = oBottomBorder.clone();
										  if(oBBox.c1 == oBBox.c2 && null != oRightBorder)
											  oNewStyle.border.r = oRightBorder.clone();
									  }
								  }
								  else if(oBBox.r1 == nRow && oBBox.c2 == nCol)
								  {
									  if(null != oRightBorder || null != oTopBorder || (oBBox.r1 == oBBox.r2 && null != oBottomBorder))
									  {
										  oNewStyle.border = new Border();
										  if(null != oRightBorder)
											  oNewStyle.border.r = oRightBorder.clone();
										  if(null != oTopBorder)
											  oNewStyle.border.t = oTopBorder.clone();
										  if(oBBox.r1 == oBBox.r2 && null != oBottomBorder)
											  oNewStyle.border.b = oBottomBorder.clone();
									  }
								  }
								  else if(oBBox.r2 == nRow && oBBox.c1 == nCol)
								  {
									  if(null != oLeftBorder || null != oBottomBorder || (oBBox.c1 == oBBox.c2 && null != oRightBorder))
									  {
										  oNewStyle.border = new Border();
										  if(null != oLeftBorder)
											  oNewStyle.border.l = oLeftBorder.clone();
										  if(null != oBottomBorder)
											  oNewStyle.border.b = oBottomBorder.clone();
										  if(oBBox.c1 == oBBox.c2 && null != oRightBorder)
											  oNewStyle.border.r = oRightBorder.clone();
									  }
								  }
								  else if(oBBox.r2 == nRow && oBBox.c2 == nCol)
								  {
									  if(null != oRightBorder || null != oBottomBorder)
									  {
										  oNewStyle.border = new Border();
										  if(null != oRightBorder)
											  oNewStyle.border.r = oRightBorder.clone();
										  if(null != oBottomBorder)
											  oNewStyle.border.b = oBottomBorder.clone();
									  }
								  }
								  else if(oBBox.r1 == nRow)
								  {
									  if(null != oTopBorder || (oBBox.r1 == oBBox.r2 && null != oBottomBorder))
									  {
										  oNewStyle.border = new Border();
										  if(null != oTopBorder)
											  oNewStyle.border.t = oTopBorder.clone();
										  if(oBBox.r1 == oBBox.r2 && null != oBottomBorder)
											  oNewStyle.border.b = oBottomBorder.clone();
									  }
								  }
								  else if(oBBox.r2 == nRow)
								  {
									  if(null != oBottomBorder)
									  {
										  oNewStyle.border = new Border();
										  oNewStyle.border.b = oBottomBorder.clone();
									  }
								  }
								  else if(oBBox.c1 == nCol)
								  {
									  if(null != oLeftBorder || (oBBox.c1 == oBBox.c2 && null != oRightBorder))
									  {
										  oNewStyle.border = new Border();
										  if(null != oLeftBorder)
											  oNewStyle.border.l = oLeftBorder.clone();
										  if(oBBox.c1 == oBBox.c2 && null != oRightBorder)
											  oNewStyle.border.r = oRightBorder.clone();
									  }
								  }
								  else if(oBBox.c2 == nCol)
								  {
									  if(null != oRightBorder)
									  {
										  oNewStyle.border = new Border();
										  oNewStyle.border.r = oRightBorder.clone();
									  }
								  }
								  cell.setStyle(oNewStyle);
							  }
						  });
		if(type == Asc.c_oAscMergeOptions.MergeCenter)
			this.setAlignHorizontal(AscCommon.align_Center);
		if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges)
			this.worksheet.mergeManager.add(this.bbox, 1);
		History.EndTransaction();
	};
	Range.prototype.unmerge=function(bOnlyInRange){
		History.Create_NewPoint();
		History.StartTransaction();
		if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges)
			this.worksheet.mergeManager.remove(this.bbox);
		History.EndTransaction();
	};
	Range.prototype._getHyperlinks=function(){
		var nRangeType = this._getRangeType();
		var result = [];
		var oThis = this;
		if(c_oRangeType.Range == nRangeType)
		{
			var oTempRows = {};
			var fAddToTempRows = function(oTempRows, bbox, data){
				if(null != bbox)
7253
				{
7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268
					for(var i = bbox.r1; i <= bbox.r2; i++)
					{
						var row = oTempRows[i];
						if(null == row)
						{
							row = {};
							oTempRows[i] = row;
						}
						for(var j = bbox.c1; j <= bbox.c2; j++)
						{
							var cell = row[j];
							if(null == cell)
								row[j] = data;
						}
					}
7269
				}
7270 7271 7272 7273
			};
			//todo возможно надо сделать оптимизацию для скрытых строк
			var aHyperlinks = this.worksheet.hyperlinkManager.get(this.bbox);
			for(var i = 0, length = aHyperlinks.all.length; i < length; i++)
7274
			{
7275 7276 7277 7278 7279 7280
				var hyp = aHyperlinks.all[i];
				var hypBBox = hyp.bbox.intersectionSimple(this.bbox);
				fAddToTempRows(oTempRows, hypBBox, hyp.data);
				//расширяем гиперссылки на merge ячейках
				var aMerged = this.worksheet.mergeManager.get(hyp.bbox);
				for(var j = 0, length2 = aMerged.all.length; j < length2; j++)
7281
				{
7282 7283 7284
					var merge = aMerged.all[j];
					var mergeBBox = merge.bbox.intersectionSimple(this.bbox);
					fAddToTempRows(oTempRows, mergeBBox, hyp.data);
7285 7286
				}
			}
7287 7288
			//формируем результат
			for(var i in oTempRows)
7289
			{
7290 7291 7292
				var nRowIndex = i - 0;
				var row = oTempRows[i];
				for(var j in row)
7293
				{
7294 7295 7296
					var nColIndex = j - 0;
					var oCurHyp = row[j];
					result.push({hyperlink: oCurHyp, col: nColIndex, row: nRowIndex});
7297 7298
				}
			}
7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326
		}
		return result;
	};
	Range.prototype.getHyperlink=function(){
		var aHyperlinks = this._getHyperlinks();
		if(null != aHyperlinks && aHyperlinks.length > 0)
			return aHyperlinks[0].hyperlink;
		return null;
	};
	Range.prototype.getHyperlinks=function(){
		return this._getHyperlinks();
	};
	Range.prototype.setHyperlinkOpen=function(val){
		if(null != val && false == val.isValid())
			return;
		this.worksheet.hyperlinkManager.add(val.Ref.getBBox0(), val);
	};
	Range.prototype.setHyperlink=function(val, bWithoutStyle){
		if(null != val && false == val.isValid())
			return;
		//проверяем, может эта ссылка уже существует
		var i, length, hyp;
		var bExist = false;
		var aHyperlinks = this.worksheet.hyperlinkManager.get(this.bbox);
		for(i = 0, length = aHyperlinks.all.length; i < length; i++)
		{
			hyp = aHyperlinks.all[i];
			if(hyp.data.isEqual(val))
7327
			{
7328 7329
				bExist = true;
				break;
7330 7331
			}
		}
7332 7333 7334 7335 7336
		if(false == bExist)
		{
			History.Create_NewPoint();
			History.StartTransaction();
			if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges)
7337
			{
7338 7339
				//удаляем ссылки с тем же адресом
				for(i = 0, length = aHyperlinks.all.length; i < length; i++)
7340
				{
7341 7342 7343
					hyp = aHyperlinks.all[i];
					if(hyp.bbox.isEqual(this.bbox))
						this.worksheet.hyperlinkManager.removeElement(hyp);
7344 7345
				}
			}
7346 7347
			//todo перейти на CellStyle
			if(true != bWithoutStyle)
7348
			{
7349 7350 7351 7352 7353 7354 7355 7356 7357 7358
				var oHyperlinkFont = new AscCommonExcel.Font();
				oHyperlinkFont.setName(this.worksheet.workbook.getDefaultFont());
				oHyperlinkFont.setSize(this.worksheet.workbook.getDefaultSize());
				oHyperlinkFont.setUnderline(Asc.EUnderline.underlineSingle);
				oHyperlinkFont.setColor(AscCommonExcel.g_oColorManager.getThemeColor(AscCommonExcel.g_nColorHyperlink));
				this.setFont(oHyperlinkFont);
			}
			if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges)
				this.worksheet.hyperlinkManager.add(val.Ref.getBBox0(), val);
			History.EndTransaction();
7359
		}
7360 7361 7362 7363 7364
	};
	Range.prototype.removeHyperlink = function (val, removeStyle) {
		var bbox = this.bbox;
		var elem = null;
		if(null != val)
7365
		{
7366 7367
			bbox = val.Ref.getBBox0();
			elem = new RangeDataManagerElem(bbox, val);
7368
		}
7369
		if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges)
7370
		{
7371 7372 7373 7374 7375 7376 7377 7378
			History.Create_NewPoint();
			History.StartTransaction();
			var oChangeParam = { removeStyle: removeStyle };
			if(null != elem)
				this.worksheet.hyperlinkManager.removeElement(elem, oChangeParam);
			else
				this.worksheet.hyperlinkManager.remove(bbox, !bbox.isOneCell(), oChangeParam);
			History.EndTransaction();
7379
		}
7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414
	};
	Range.prototype.deleteCellsShiftUp=function(preDeleteAction){
		return this._shiftUpDown(true, preDeleteAction);
	};
	Range.prototype.addCellsShiftBottom=function(displayNameFormatTable){
		return this._shiftUpDown(false, null, displayNameFormatTable);
	};
	Range.prototype.addCellsShiftRight=function(displayNameFormatTable){
		return this._shiftLeftRight(false, null,displayNameFormatTable);
	};
	Range.prototype.deleteCellsShiftLeft=function(preDeleteAction){
		return this._shiftLeftRight(true, preDeleteAction);
	};
	Range.prototype._canShiftLeftRight=function(bLeft){
		var aColsToDelete = [], aCellsToDelete = [];
		var oBBox = this.bbox;
		var nRangeType = this._getRangeType(oBBox);
		if(c_oRangeType.Range != nRangeType && c_oRangeType.Col != nRangeType)
			return null;

		var nWidth = oBBox.c2 - oBBox.c1 + 1;
		if(!bLeft && !this.worksheet.workbook.bUndoChanges && !this.worksheet.workbook.bRedoChanges){
			var rangeEdge = this.worksheet.getRange3(oBBox.r1, gc_nMaxCol0 - nWidth + 1, oBBox.r2, gc_nMaxCol0);
			var aMerged = this.worksheet.mergeManager.get(rangeEdge.bbox);
			if(aMerged.all.length > 0)
				return null;
			var aHyperlink = this.worksheet.hyperlinkManager.get(rangeEdge.bbox);
			if(aHyperlink.all.length > 0)
				return null;

			var bError = rangeEdge._setPropertyNoEmpty(null, function(col){
				if(null != col){
					if(null != col && null != col.xfs && null != col.xfs.fill && null != col.xfs.fill.getRgbOrNull())
						return true;
					aColsToDelete.push(col);
7415
				}
7416 7417 7418 7419 7420 7421 7422
			}, function(cell){
				if(null != cell){
					if(null != cell.xfs && null != cell.xfs.fill && null != cell.xfs.fill.getRgbOrNull())
						return true;
					if(!cell.isEmptyText())
						return true;
					aCellsToDelete.push(cell);
7423
				}
7424 7425 7426
			});
			if(bError)
				return null;
7427
		}
7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452
		return {aColsToDelete: aColsToDelete, aCellsToDelete: aCellsToDelete};
	};
	Range.prototype._shiftLeftRight=function(bLeft, preDeleteAction, displayNameFormatTable){
		var canShiftRes = this._canShiftLeftRight(bLeft);
		if(null === canShiftRes)
			return false;

		if (preDeleteAction)
			preDeleteAction();

		//удаляем крайние колонки и ячейки
		var i, length, colIndex;
		for(i = 0, length = canShiftRes.aColsToDelete.length; i < length; ++i){
			colIndex = canShiftRes.aColsToDelete[i].index;
			this.worksheet._removeCols(colIndex, colIndex);
		}
		for(i = 0, length = canShiftRes.aCellsToDelete.length; i < length; ++i)
			this.worksheet._removeCell(null, null, canShiftRes.aCellsToDelete[i]);

		var oBBox = this.bbox;
		var nWidth = oBBox.c2 - oBBox.c1 + 1;
		var nRangeType = this._getRangeType(oBBox);
		var mergeManager = this.worksheet.mergeManager;
		this.worksheet.workbook.dependencyFormulas.lockRecal();
		//todo вставить предупреждение, что будет unmerge
7453 7454
		History.Create_NewPoint();
		History.StartTransaction();
7455 7456
		var oShiftGet = null;
		if (false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges))
7457
		{
7458 7459 7460 7461
			History.LocalChange = true;
			oShiftGet = mergeManager.shiftGet(this.bbox, true);
			var aMerged = oShiftGet.elems;
			if(null != aMerged.outer && aMerged.outer.length > 0)
7462
			{
7463 7464
				var bChanged = false;
				for(i = 0, length = aMerged.outer.length; i < length; i++)
7465
				{
7466 7467
					var elem = aMerged.outer[i];
					if(!(elem.bbox.c1 < oShiftGet.bbox.c1 && oShiftGet.bbox.r1 <= elem.bbox.r1 && elem.bbox.r2 <= oShiftGet.bbox.r2))
7468
					{
7469 7470
						mergeManager.removeElement(elem);
						bChanged = true;
7471
					}
7472
				}
7473 7474
				if(bChanged)
					oShiftGet = null;
7475
			}
7476
			History.LocalChange = false;
7477
		}
7478 7479
		//сдвигаем ячейки
		if(bLeft)
7480
		{
7481 7482 7483 7484
			if(c_oRangeType.Range == nRangeType)
				this.worksheet._shiftCellsLeft(oBBox);
			else
				this.worksheet._removeCols(oBBox.c1, oBBox.c2);
7485
		}
7486
		else
7487
		{
7488 7489 7490 7491
			if(c_oRangeType.Range == nRangeType)
				this.worksheet._shiftCellsRight(oBBox, displayNameFormatTable);
			else
				this.worksheet._insertColsBefore(oBBox.c1, nWidth);
7492
		}
7493
		if (false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges))
7494
		{
7495 7496 7497 7498
			History.LocalChange = true;
			mergeManager.shift(this.bbox, !bLeft, true, oShiftGet);
			this.worksheet.hyperlinkManager.shift(this.bbox, !bLeft, true);
			History.LocalChange = false;
7499
		}
7500
		History.EndTransaction();
7501 7502 7503 7504 7505 7506 7507 7508
		this.worksheet.workbook.dependencyFormulas.unlockRecal();
		return true;
	};
	Range.prototype._canShiftUpDown=function(bUp){
		var aRowsToDelete = [], aCellsToDelete = [];
		var oBBox = this.bbox;
		var nRangeType = this._getRangeType(oBBox);
		if(c_oRangeType.Range != nRangeType && c_oRangeType.Row != nRangeType)
7509 7510
			return null;

7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525
		var nHeight = oBBox.r2 - oBBox.r1 + 1;
		if(!bUp && !this.worksheet.workbook.bUndoChanges && !this.worksheet.workbook.bRedoChanges){
			var rangeEdge = this.worksheet.getRange3(gc_nMaxRow0 - nHeight + 1, oBBox.c1, gc_nMaxRow0, oBBox.c2);
			var aMerged = this.worksheet.mergeManager.get(rangeEdge.bbox);
			if(aMerged.all.length > 0)
				return null;
			var aHyperlink = this.worksheet.hyperlinkManager.get(rangeEdge.bbox);
			if(aHyperlink.all.length > 0)
				return null;

			var bError = rangeEdge._setPropertyNoEmpty(function(row){
				if(null != row){
					if(null != row.xfs && null != row.xfs.fill && null != row.xfs.fill.getRgbOrNull())
						return true;
					aRowsToDelete.push(row);
7526
				}
7527 7528 7529 7530 7531 7532 7533
			}, null,  function(cell){
				if(null != cell){
					if(null != cell.xfs && null != cell.xfs.fill && null != cell.xfs.fill.getRgbOrNull())
						return true;
					if(!cell.isEmptyText())
						return true;
					aCellsToDelete.push(cell);
7534
				}
7535 7536 7537
			});
			if(bError)
				return null;
7538
		}
7539 7540 7541 7542 7543 7544
		return {aRowsToDelete: aRowsToDelete, aCellsToDelete: aCellsToDelete};
	};
	Range.prototype._shiftUpDown = function (bUp, preDeleteAction, displayNameFormatTable) {
		var canShiftRes = this._canShiftUpDown(bUp);
		if(null === canShiftRes)
			return false;
7545

7546 7547
		if (preDeleteAction)
			preDeleteAction();
7548

7549 7550 7551 7552 7553 7554 7555 7556
		//удаляем крайние колонки и ячейки
		var i, length, rowIndex;
		for(i = 0, length = canShiftRes.aRowsToDelete.length; i < length; ++i){
			rowIndex = canShiftRes.aRowsToDelete[i].index;
			this.worksheet._removeRows(rowIndex, rowIndex);
		}
		for(i = 0, length = canShiftRes.aCellsToDelete.length; i < length; ++i)
			this.worksheet._removeCell(null, null, canShiftRes.aCellsToDelete[i]);
7557

7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572
		var oBBox = this.bbox;
		var nHeight = oBBox.r2 - oBBox.r1 + 1;
		var nRangeType = this._getRangeType(oBBox);
		var mergeManager = this.worksheet.mergeManager;
		this.worksheet.workbook.dependencyFormulas.lockRecal();
		//todo вставить предупреждение, что будет unmerge
		History.Create_NewPoint();
		History.StartTransaction();
		var oShiftGet = null;
		if (false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges))
		{
			History.LocalChange = true;
			oShiftGet = mergeManager.shiftGet(this.bbox, false);
			var aMerged = oShiftGet.elems;
			if(null != aMerged.outer && aMerged.outer.length > 0)
7573
			{
7574 7575
				var bChanged = false;
				for(i = 0, length = aMerged.outer.length; i < length; i++)
7576
				{
7577 7578 7579 7580 7581 7582
					var elem = aMerged.outer[i];
					if(!(elem.bbox.r1 < oShiftGet.bbox.r1 && oShiftGet.bbox.c1 <= elem.bbox.c1 && elem.bbox.c2 <= oShiftGet.bbox.c2))
					{
						mergeManager.removeElement(elem);
						bChanged = true;
					}
7583
				}
7584 7585
				if(bChanged)
					oShiftGet = null;
7586
			}
7587 7588 7589 7590 7591 7592 7593 7594 7595
			History.LocalChange = false;
		}
		//сдвигаем ячейки
		if(bUp)
		{
			if(c_oRangeType.Range == nRangeType)
				this.worksheet._shiftCellsUp(oBBox);
			else
				this.worksheet._removeRows(oBBox.r1, oBBox.r2);
7596 7597
		}
		else
7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667
		{
			if(c_oRangeType.Range == nRangeType)
				this.worksheet._shiftCellsBottom(oBBox, displayNameFormatTable);
			else
				this.worksheet._insertRowsBefore(oBBox.r1, nHeight);
		}
		if (false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges))
		{
			History.LocalChange = true;
			mergeManager.shift(this.bbox, !bUp, false, oShiftGet);
			this.worksheet.hyperlinkManager.shift(this.bbox, !bUp, false);
			History.LocalChange = false;
		}
		History.EndTransaction();
		this.worksheet.workbook.dependencyFormulas.unlockRecal();
		return true;
	};
	Range.prototype.setOffset=function(offset){//offset = AscCommonExcel.CRangeOffset
		this.bbox.c1 += offset.offsetCol;
		if( this.bbox.c1 < 0 )
			this.bbox.c1 = 0;
		this.bbox.r1 += offset.offsetRow;
		if( this.bbox.r1 < 0 )
			this.bbox.r1 = 0;
		this.bbox.c2 += offset.offsetCol;
		if( this.bbox.c2 < 0 )
			this.bbox.c2 = 0;
		this.bbox.r2 += offset.offsetRow;
		if( this.bbox.r2 < 0 )
			this.bbox.r2 = 0;
	};
	Range.prototype.setOffsetFirst=function(offset){//offset = {offsetCol:intNumber, offsetRow:intNumber}
		this.bbox.c1 += offset.offsetCol;
		if( this.bbox.c1 < 0 )
			this.bbox.c1 = 0;
		this.bbox.r1 += offset.offsetRow;
		if( this.bbox.r1 < 0 )
			this.bbox.r1 = 0;
	};
	Range.prototype.setOffsetLast=function(offset){//offset = {offsetCol:intNumber, offsetRow:intNumber}
		this.bbox.c2 += offset.offsetCol;
		if( this.bbox.c2 < 0 )
			this.bbox.c2 = 0;
		this.bbox.r2 += offset.offsetRow;
		if( this.bbox.r2 < 0 )
			this.bbox.r2 = 0;
	};
	Range.prototype.intersect=function(range){
		var oBBox1 = this.bbox;
		var oBBox2 = range.bbox;
		var r1 = Math.max(oBBox1.r1, oBBox2.r1);
		var c1 = Math.max(oBBox1.c1, oBBox2.c1);
		var r2 = Math.min(oBBox1.r2, oBBox2.r2);
		var c2 = Math.min(oBBox1.c2, oBBox2.c2);
		if(r1 <= r2 && c1 <= c2)
			return this.worksheet.getRange3(r1, c1, r2, c2);
		return null;
	};
	Range.prototype.cleanCache=function(){
		this._setPropertyNoEmpty(null,null,function(cell, nRow0, nCol0, nRowStart, nColStart){
			cell.cleanCache();
		});
	};
	Range.prototype.cleanFormat=function(){
		History.Create_NewPoint();
		History.StartTransaction();
		this.unmerge();
		this._setPropertyNoEmpty(function(row){
			row.setStyle(null);
			// if(row.isEmpty())
7668
			// row.Remove();
7669 7670 7671
		},function(col){
			col.setStyle(null);
			// if(col.isEmpty())
7672
			// col.Remove();
7673 7674
		},function(cell, nRow0, nCol0, nRowStart, nColStart){
			cell.setStyle(null);
7675
			// if(cell.isEmpty())
7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702
			// cell.Remove();
		});
		History.EndTransaction();
	};
	Range.prototype.cleanText=function(){
		History.Create_NewPoint();
		History.StartTransaction();
		this._setPropertyNoEmpty(null, null,
								 function(cell, nRow0, nCol0, nRowStart, nColStart){
									 cell.setValue("");
									 // if(cell.isEmpty())
									 // cell.Remove();
								 });
		History.EndTransaction();
	};
	Range.prototype.cleanAll=function(){
		History.Create_NewPoint();
		History.StartTransaction();
		this.unmerge();
		//удаляем только гиперссылки, которые полностью лежат в области
		var aHyperlinks = this.worksheet.hyperlinkManager.get(this.bbox);
		for(var i = 0, length = aHyperlinks.inner.length; i < length; ++i)
			this.removeHyperlink(aHyperlinks.inner[i].data);
		var oThis = this;
		this._setPropertyNoEmpty(function(row){
			row.setStyle(null);
			// if(row.isEmpty())
7703
			// row.Remove();
7704 7705 7706
		},function(col){
			col.setStyle(null);
			// if(col.isEmpty())
7707
			// col.Remove();
7708 7709
		},function(cell, nRow0, nCol0, nRowStart, nColStart){
			oThis.worksheet._removeCell(nRow0, nCol0);
7710
		});
7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760

		this.worksheet.workbook.dependencyFormulas.calcTree();
		History.EndTransaction();
	};
	Range.prototype.cleanHyperlinks=function(){
		History.Create_NewPoint();
		History.StartTransaction();
		//удаляем только гиперссылки, которые полностью лежат в области
		var aHyperlinks = this.worksheet.hyperlinkManager.get(this.bbox);
		for(var i = 0, length = aHyperlinks.inner.length; i < length; ++i)
			this.removeHyperlink(aHyperlinks.inner[i].data);
		History.EndTransaction();
	};
	Range.prototype.sort=function(nOption, nStartCol, sortColor, opt_guessHeader){
		var bbox = this.bbox;
		if (opt_guessHeader && bbox.r1 < bbox.r2) {
			//если тип ячеек первого и второго row попарно совпадает, то считаем первую строку заголовком
			//todo рассмотреть замерженые ячейки. стили тоже влияют, но непонятно как сравнивать border
			var rowFirst = this.worksheet.getRange3(bbox.r1, bbox.c1, bbox.r1, bbox.c2);
			var rowSecond = this.worksheet.getRange3(bbox.r1 + 1, bbox.c1, bbox.r1 + 1, bbox.c2);
			var typesFirst = [];
			var typesSecond = [];
			rowFirst._setPropertyNoEmpty(null, null, function(cell, row, col) {
				if (cell && !cell.isEmptyTextString()) {
					typesFirst.push({col: col, type: cell.getType()});
				}
			});
			rowSecond._setPropertyNoEmpty(null, null, function(cell, row, col) {
				if (cell && !cell.isEmptyTextString()) {
					typesSecond.push({col: col, type: cell.getType()});
				}
			});
			var indexFirst = 0;
			var indexSecond = 0;
			while (indexFirst < typesFirst.length && indexSecond < typesSecond.length) {
				var curFirst = typesFirst[indexFirst];
				var curSecond = typesSecond[indexSecond];
				if (curFirst.col < curSecond.col) {
					indexFirst++;
				} else if (curFirst.col > curSecond.col) {
					indexSecond++;
				} else {
					if (curFirst.type != curSecond.type) {
						//has head
						bbox = bbox.clone();
						bbox.r1++;
						break;
					}
					indexFirst++;
					indexSecond++;
7761 7762 7763
				}
			}
		}
7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814
		//todo горизонтальная сортировка
		var aMerged = this.worksheet.mergeManager.get(bbox);
		if(aMerged.outer.length > 0 || (aMerged.inner.length > 0 && null == _isSameSizeMerged(bbox, aMerged.inner)))
			return null;
		var nMergedHeight = 1;
		if(aMerged.inner.length > 0)
		{
			var merged = aMerged.inner[0];
			nMergedHeight = merged.bbox.r2 - merged.bbox.r1 + 1;
			//меняем nStartCol, потому что приходит колонка той ячейки, на которой начали выделение
			nStartCol = merged.bbox.c1;
		}
		this.worksheet.workbook.dependencyFormulas.lockRecal();
		var colorFill = nOption === Asc.c_oAscSortOptions.ByColorFill;
		var colorText = nOption === Asc.c_oAscSortOptions.ByColorFont;
		var isSortColor = !!(colorFill || colorText);

		var oRes = null;
		var oThis = this;
		var bAscent = false;
		if(nOption == Asc.c_oAscSortOptions.Ascending)
			bAscent = true;
		var nRowFirst0 = bbox.r1;
		var nRowLast0 = bbox.r2;
		var nColFirst0 = bbox.c1;
		var nColLast0 = bbox.c2;
		var bWholeCol = false;
		var bWholeRow = false;
		if(0 == nRowFirst0 && gc_nMaxRow0 == nRowLast0)
			bWholeCol = true;
		if(0 == nColFirst0 && gc_nMaxCol0 == nColLast0)
			bWholeRow = true;
		var oRangeCol = this.worksheet.getRange(new CellAddress(nRowFirst0, nStartCol, 0), new CellAddress(nRowLast0, nStartCol, 0));
		var nLastRow0 = 0;
		var nLastCol0 = nColLast0;
		if(true == bWholeRow)
		{
			nLastCol0 = 0;
			this._foreachRowNoEmpty(function(){}, function(cell){
				var nCurCol0 = cell.nCol;
				if(nCurCol0 > nLastCol0)
					nLastCol0 = nCurCol0;
			});
		}
		//собираем массив обьектов для сортировки
		var aSortElems = [];
		var aHiddenRow = {};
		var fAddSortElems = function(oCell, nRow0, nCol0,nRowStart0, nColStart0){
			//не сортируем сткрытие строки
			var row = oThis.worksheet._getRowNoEmpty(nRow0);
			if(row)
7815
			{
7816 7817 7818
				if(0 != (AscCommonExcel.g_nRowFlag_hd & row.flags))
					aHiddenRow[nRow0] = 1;
				else
Alexander.Trofimov's avatar
Alexander.Trofimov committed
7819
				{
7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831
					if(nLastRow0 < nRow0)
						nLastRow0 = nRow0;
					var val = oCell.getValueWithoutFormat();

					//for sort color
					var colorFillCell, colorsTextCell = null;
					if(colorFill)
					{
						var styleCell = oCell.getStyle();
						colorFillCell = styleCell !== null && styleCell.fill ? styleCell.fill.bg : null;
					}
					else if(colorText)
Alexander.Trofimov's avatar
Alexander.Trofimov committed
7832
					{
7833 7834
						var value2 = oCell.getValue2();
						for(var n = 0; n < value2.length; n++)
GoshaZotov's avatar
GoshaZotov committed
7835
						{
7836 7837 7838 7839 7840 7841
							if(null === colorsTextCell)
							{
								colorsTextCell = [];
							}

							colorsTextCell.push(value2[n].format.getColor());
Alexander.Trofimov's avatar
Alexander.Trofimov committed
7842
						}
7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858
					}

					var nNumber = null;
					var sText = null;
					if("" != val)
					{
						var nVal = val - 0;
						if(nVal == val)
							nNumber = nVal;
						else
							sText = val;
						aSortElems.push({row: nRow0, num: nNumber, text: sText, colorFill: colorFillCell, colorsText: colorsTextCell});
					}
					else if(isSortColor)
					{
						aSortElems.push({row: nRow0, num: nNumber, text: sText, colorFill: colorFillCell, colorsText: colorsTextCell});
Alexander.Trofimov's avatar
Alexander.Trofimov committed
7859
					}
GoshaZotov's avatar
GoshaZotov committed
7860
				}
7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871
			}
		};
		if(nColFirst0 == nStartCol)
		{
			while(0 == aSortElems.length && nStartCol <= nLastCol0)
			{
				if(false == bWholeCol)
					oRangeCol._foreachNoEmpty(fAddSortElems);
				else
					oRangeCol._foreachColNoEmpty(null, fAddSortElems);
				if(0 == aSortElems.length)
Alexander.Trofimov's avatar
Alexander.Trofimov committed
7872
				{
7873 7874
					nStartCol++;
					oRangeCol = this.worksheet.getRange(new CellAddress(nRowFirst0, nStartCol, 0), new CellAddress(nRowLast0, nStartCol, 0));
7875 7876 7877
				}
			}
		}
7878
		else
7879 7880 7881 7882 7883 7884
		{
			if(false == bWholeCol)
				oRangeCol._foreachNoEmpty(fAddSortElems);
			else
				oRangeCol._foreachColNoEmpty(null, fAddSortElems);
		}
7885
		function strcmp ( str1, str2 ) {
7886
			return ( ( str1 == str2 ) ? 0 : ( ( str1 > str2 ) ? 1 : -1 ) );
Alexander.Trofimov's avatar
Alexander.Trofimov committed
7887
		}
7888 7889 7890 7891


		//color sort
		var colorFillCmp = function(color1, color2)
Alexander.Trofimov's avatar
Alexander.Trofimov committed
7892
		{
7893 7894 7895
			var res = false;
			//TODO возможно так сравнивать не правильно, позже пересмотреть
			if(colorFill)
Alexander.Trofimov's avatar
Alexander.Trofimov committed
7896
			{
7897
				res = (color1 !== null && color2 !== null && color1.rgb === color2.rgb) || (color1 === color2) ? true : false;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
7898
			}
7899
			else if(colorText && color1 && color1.length)
Alexander.Trofimov's avatar
Alexander.Trofimov committed
7900
			{
7901 7902 7903 7904 7905 7906 7907 7908
				for(var n = 0; n < color1.length; n++)
				{
					if(color1[n] && color2 !== null && color1[n].rgb === color2.rgb)
					{
						res = true;
						break;
					}
				}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
7909
			}
7910

Alexander.Trofimov's avatar
Alexander.Trofimov committed
7911
			return res;
7912 7913 7914
		};

		if(isSortColor)
Alexander.Trofimov's avatar
Alexander.Trofimov committed
7915
		{
7916 7917 7918 7919
			var newArrayNeedColor = [];
			var newArrayAnotherColor = [];

			for(var i = 0; i < aSortElems.length; i++)
Alexander.Trofimov's avatar
Alexander.Trofimov committed
7920
			{
7921 7922
				var color = colorFill ? aSortElems[i].colorFill : aSortElems[i].colorsText;
				if(colorFillCmp(color, sortColor))
Alexander.Trofimov's avatar
Alexander.Trofimov committed
7923
				{
7924 7925 7926
					newArrayNeedColor.push(aSortElems[i]);
				}
				else
7927
				{
7928
					newArrayAnotherColor.push(aSortElems[i]);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
7929 7930
				}
			}
7931 7932

			aSortElems = newArrayNeedColor.concat(newArrayAnotherColor);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
7933
		}
7934
		else
7935
		{
7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957
			aSortElems.sort(function(a, b){
				var res = 0;
				if(null != a.text)
				{
					if(null != b.text)
						res = strcmp(a.text.toUpperCase(), b.text.toUpperCase());
					else
						res = 1;
				}
				else if(null != a.num)
				{
					if(null != b.num)
						res = a.num - b.num;
					else
						res = -1;
				}
				if(0 == res)
					res = a.row - b.row;
				else if(!bAscent)
					res = -res;
				return res;
			});
7958
		}
7959 7960 7961 7962 7963 7964 7965 7966 7967

		//проверяем что это не пустая операция
		var aSortData = [];
		var nHiddenCount = 0;
		var oFromArray = {};
		var nRowMax = 0;
		var nRowMin = gc_nMaxRow0;
		var nToMax = 0;
		for(var i = 0, length = aSortElems.length; i < length; ++i)
Alexander.Trofimov's avatar
Alexander.Trofimov committed
7968
		{
7969 7970 7971
			var item = aSortElems[i];
			var nNewIndex = i * nMergedHeight + nRowFirst0 + nHiddenCount;
			while(null != aHiddenRow[nNewIndex])
Alexander.Trofimov's avatar
Alexander.Trofimov committed
7972
			{
7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991
				nHiddenCount++;
				nNewIndex = i * nMergedHeight + nRowFirst0 + nHiddenCount;
			}
			var oNewElem = new UndoRedoData_FromToRowCol(true, item.row, nNewIndex);
			oFromArray[item.row] = 1;
			if(nRowMax < item.row)
				nRowMax = item.row;
			if(nRowMax < nNewIndex)
				nRowMax = nNewIndex;
			if(nRowMin > item.row)
				nRowMin = item.row;
			if(nRowMin > nNewIndex)
				nRowMin = nNewIndex;
			if(nToMax < nNewIndex)
				nToMax = nNewIndex;
			if(oNewElem.from != oNewElem.to)
				aSortData.push(oNewElem);
		}
		if(aSortData.length > 0)
7992
		{
7993 7994
			//добавляем индексы перехода пустых ячеек(нужно для сортировки комментариев)
			for(var i = nRowMin; i <= nRowMax; ++i)
Alexander.Trofimov's avatar
Alexander.Trofimov committed
7995
			{
7996
				if(null == oFromArray[i] && null == aHiddenRow[i])
7997
				{
7998 7999 8000 8001 8002 8003 8004 8005 8006
					var nFrom = i;
					var nTo = ++nToMax;
					while(null != aHiddenRow[nTo])
						nTo = ++nToMax;
					if(nFrom != nTo)
					{
						var oNewElem = new UndoRedoData_FromToRowCol(true, nFrom, nTo);
						aSortData.push(oNewElem);
					}
8007
				}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
8008
			}
8009 8010 8011
			History.Create_NewPoint();
			var oSelection = History.GetSelection();
			if(null != oSelection)
Alexander.Trofimov's avatar
Alexander.Trofimov committed
8012
			{
8013 8014 8015 8016
				oSelection = oSelection.clone();
				oSelection.assign(nColFirst0, nRowFirst0, nLastCol0, nLastRow0);
				History.SetSelection(oSelection);
				History.SetSelectionRedo(oSelection);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
8017
			}
8018 8019 8020
			var oUndoRedoBBox = new UndoRedoData_BBox({r1:nRowFirst0, c1:nColFirst0, r2:nLastRow0, c2:nLastCol0});
			oRes = new AscCommonExcel.UndoRedoData_SortData(oUndoRedoBBox, aSortData);
			this._sortByArray(oUndoRedoBBox, aSortData);
konovalovsergey's avatar
konovalovsergey committed
8021
			History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_Sort, this.worksheet.getId(), new Asc.Range(0, nRowFirst0, gc_nMaxCol0, nLastRow0), oRes);
8022
		}
8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034
		this.worksheet.workbook.dependencyFormulas.unlockRecal();
		return oRes;
	};
	Range.prototype._sortByArray=function(oBBox, aSortData, bUndo){
		var rec = {length:0};
		var oSortedIndexes = {};
		for(var i = 0, length = aSortData.length; i < length; ++i)
		{
			var item = aSortData[i];
			var nFrom = item.from;
			var nTo = item.to;
			if(true == this.worksheet.workbook.bUndoChanges)
Alexander.Trofimov's avatar
Alexander.Trofimov committed
8035
			{
8036 8037
				nFrom = item.to;
				nTo = item.from;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
8038
			}
8039 8040 8041 8042 8043
			oSortedIndexes[nFrom] = nTo;
		}
		//сортируются только одинарные гиперссылки, все неодинарные оставляем
		var aSortedHyperlinks = [];
		if(false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges))
8044
		{
8045 8046 8047
			History.LocalChange = true;
			var aHyperlinks = this.worksheet.hyperlinkManager.get(this.bbox);
			for(var i = 0, length = aHyperlinks.inner.length; i < length; i++)
8048
			{
8049 8050 8051
				var elem = aHyperlinks.inner[i];
				var hyp = elem.data;
				if(hyp.Ref.isOneCell())
8052
				{
8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064
					var nFrom = elem.bbox.r1;
					var nTo = oSortedIndexes[nFrom];
					if(null != nTo)
					{
						//удаляем ссылки, а не перемещаем, чтобы не было конфликтов(например в случае если все ячейки имеют ссылки
						// и их надо передвинуть)
						var oTempBBox = hyp.Ref.getBBox0();
						this.worksheet.hyperlinkManager.removeElement(new RangeDataManagerElem(oTempBBox, hyp));
						var oNewHyp = hyp.clone();
						oNewHyp.Ref.setOffset({offsetCol: 0, offsetRow: nTo - nFrom});
						aSortedHyperlinks.push(oNewHyp);
					}
8065 8066
				}
			}
8067
			History.LocalChange = false;
8068
		}
8069 8070 8071 8072
		//окончательно устанавливаем ячейки
		var nColFirst0 = oBBox.c1;
		var nLastCol0 = oBBox.c2;
		for(var i = nColFirst0; i <= nLastCol0; ++i)
8073
		{
8074 8075 8076
			//запоминаем ячейки в которые уже что-то передвинули, чтобы не потерять их
			var oTempCellsTo = {};
			for(var j in oSortedIndexes)
8077
			{
8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089
				var nIndexFrom = j - 0;
				var nIndexTo = oSortedIndexes[j];
				var shift = nIndexTo - nIndexFrom;
				var rowFrom = this.worksheet._getRow(nIndexFrom);
				var rowTo = this.worksheet._getRow(nIndexTo);

				var oCurCell;
				if(oTempCellsTo.hasOwnProperty(nIndexFrom))
					oCurCell = oTempCellsTo[nIndexFrom];
				else{
					oCurCell = rowFrom.c[i];
					delete rowFrom.c[i];
8090
				}
8091 8092
				oTempCellsTo[nIndexTo] = rowTo.c[i];
				if(null != oCurCell)
8093
				{
konovalovsergey's avatar
konovalovsergey committed
8094 8095 8096
					if (oCurCell.formulaParsed) {
						oCurCell.changeOffset({offsetCol: 0, offsetRow: shift}, true, true);
					}
8097 8098
					oCurCell.moveVer(shift);
					rowTo.c[i] = oCurCell;
konovalovsergey's avatar
konovalovsergey committed
8099 8100 8101
					if (oCurCell && oCurCell.getFormula()) {
						//for #Ref
						this.worksheet.workbook.dependencyFormulas.addToChangedCell(oCurCell);
8102
					}
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
8103
				}
8104
				else
8105
				{
8106 8107 8108 8109 8110
					if(null != rowTo.c[i])
					{
						//здесь достаточно простого delete, потому что на самом деле в функции ячейки только меняются местами, удаления не происходит
						delete rowTo.c[i];
					}
8111 8112 8113
				}
			}
		}
8114
		this.worksheet.workbook.dependencyFormulas.addToChangedRange(this.worksheet.getId(), new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
8115

8116 8117
		this.worksheet.workbook.dependencyFormulas.calcTree();
		if(false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges))
8118
		{
8119 8120 8121
			History.LocalChange = true;
			//восстанавливаем удаленые гиперссылки
			if(aSortedHyperlinks.length > 0)
8122
			{
8123 8124 8125 8126 8127
				for(var i = 0, length = aSortedHyperlinks.length; i < length; i++)
				{
					var hyp = aSortedHyperlinks[i];
					this.worksheet.hyperlinkManager.add(hyp.Ref.getBBox0(), hyp);
				}
8128
			}
8129
			History.LocalChange = false;
8130
		}
8131 8132 8133 8134 8135 8136
	};
	function _isSameSizeMerged(bbox, aMerged) {
		var oRes = null;
		var nWidth = null;
		var nHeight = null;
		for(var i = 0, length = aMerged.length; i < length; i++)
8137
		{
8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151
			var mergedBBox = aMerged[i].bbox;
			var nCurWidth = mergedBBox.c2 - mergedBBox.c1 + 1;
			var nCurHeight = mergedBBox.r2 - mergedBBox.r1 + 1;
			if(null == nWidth || null == nHeight)
			{
				nWidth = nCurWidth;
				nHeight = nCurHeight;
			}
			else if(nCurWidth != nWidth || nCurHeight != nHeight)
			{
				nWidth = null;
				nHeight = null;
				break;
			}
8152
		}
8153
		if(null != nWidth && null != nHeight)
8154
		{
8155 8156 8157 8158
			//проверяем что merge ячеки полностью заполняют область
			var nBBoxWidth = bbox.c2 - bbox.c1 + 1;
			var nBBoxHeight = bbox.r2 - bbox.r1 + 1;
			if(nBBoxWidth == nWidth || nBBoxHeight == nHeight)
8159
			{
8160 8161 8162 8163 8164
				var bRes = false;
				var aRowColTest = null;
				if(nBBoxWidth == nWidth && nBBoxHeight == nHeight)
					bRes = true;
				else if(nBBoxWidth == nWidth)
8165
				{
8166 8167 8168 8169 8170 8171 8172
					aRowColTest = new Array(nBBoxHeight);
					for(var i = 0, length = aMerged.length; i < length; i++)
					{
						var merged = aMerged[i];
						for(var j = merged.bbox.r1; j <= merged.bbox.r2; j++)
							aRowColTest[j - bbox.r1] = 1;
					}
8173
				}
8174
				else if(nBBoxHeight == nHeight)
8175
				{
8176 8177 8178 8179 8180 8181 8182
					aRowColTest = new Array(nBBoxWidth);
					for(var i = 0, length = aMerged.length; i < length; i++)
					{
						var merged = aMerged[i];
						for(var j = merged.bbox.c1; j <= merged.bbox.c2; j++)
							aRowColTest[j - bbox.c1] = 1;
					}
8183
				}
8184
				if(null != aRowColTest)
8185
				{
8186 8187
					var bExistNull = false;
					for(var i = 0, length = aRowColTest.length; i < length; i++)
8188
					{
8189 8190 8191 8192 8193
						if(null == aRowColTest[i])
						{
							bExistNull = true;
							break;
						}
8194
					}
8195 8196
					if(!bExistNull)
						bRes = true;
8197
				}
8198 8199
				if(bRes)
					oRes = {width: nWidth, height: nHeight};
8200 8201
			}
		}
8202
		return oRes;
8203
	}
8204 8205 8206 8207 8208 8209 8210 8211 8212 8213
	function _canPromote(from, wsFrom, to, wsTo, bIsPromote, nWidth, nHeight, bVertical, nIndex) {
		var oRes = {oMergedFrom: null, oMergedTo: null, to: to};
		//если надо только удалить внутреннее содержимое не смотрим на замерженость
		if(!bIsPromote || !((true == bVertical && nIndex >= 0 && nIndex < nHeight) || (false == bVertical && nIndex >= 0 && nIndex < nWidth)))
		{
			if(null != to){
				var oMergedTo = wsTo.mergeManager.get(to);
				if(oMergedTo.outer.length > 0)
					oRes = null;
				else
8214
				{
8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231
					var oMergedFrom = wsFrom.mergeManager.get(from);
					oRes.oMergedFrom = oMergedFrom;
					if(oMergedTo.inner.length > 0)
					{
						oRes.oMergedTo = oMergedTo;
						if (bIsPromote) {
							if (oMergedFrom.inner.length > 0) {
								//merge области должны иметь одинаковый размер
								var oSizeFrom = _isSameSizeMerged(from, oMergedFrom.inner);
								var oSizeTo = _isSameSizeMerged(to, oMergedTo.inner);
								if (!(null != oSizeFrom && null != oSizeTo && oSizeTo.width == oSizeFrom.width && oSizeTo.height == oSizeFrom.height))
									oRes = null;
							}
							else
								oRes = null;
						}
					}
8232 8233 8234
				}
			}
		}
8235
		return oRes;
8236
	}
8237
// Подготовка Copy Style
8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252
	function preparePromoteFromTo(from, to) {
		var bSuccess = true;
		if (to.isOneCell())
			to.setOffsetLast({offsetCol: (from.c2 - from.c1) - (to.c2 - to.c1), offsetRow: (from.r2 - from.r1) - (to.r2 - to.r1)});

		if(!from.isIntersect(to)) {
			var bFromWholeCol = (0 == from.c1 && gc_nMaxCol0 == from.c2);
			var bFromWholeRow = (0 == from.r1 && gc_nMaxRow0 == from.r2);
			var bToWholeCol = (0 == to.c1 && gc_nMaxCol0 == to.c2);
			var bToWholeRow = (0 == to.r1 && gc_nMaxRow0 == to.r2);
			bSuccess = (bFromWholeCol === bToWholeCol && bFromWholeRow === bToWholeRow);
		} else
			bSuccess = false;
		return bSuccess;
	}
8253
// Перед promoteFromTo обязательно должна быть вызывана функция preparePromoteFromTo
8254 8255 8256 8257 8258 8259
	function promoteFromTo(from, wsFrom, to, wsTo) {
		var bVertical = true;
		var nIndex = 1;
		//проверяем можно ли осуществить promote
		var oCanPromote = _canPromote(from, wsFrom, to, wsTo, false, 1, 1, bVertical, nIndex);
		if(null != oCanPromote)
8260
		{
8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278
			History.Create_NewPoint();
			var oSelection = History.GetSelection();
			if(null != oSelection)
			{
				oSelection = oSelection.clone();
				oSelection.assign(from.c1, from.r1, from.c2, from.r2);
				History.SetSelection(oSelection);
			}
			var oSelectionRedo = History.GetSelectionRedo();
			if(null != oSelectionRedo)
			{
				oSelectionRedo = oSelectionRedo.clone();
				oSelectionRedo.assign(to.c1, to.r1, to.c2, to.r2);
				History.SetSelectionRedo(oSelectionRedo);
			}
			//удаляем merge ячейки в to(после _canPromote должны остаться только inner)
			wsTo.mergeManager.remove(to, true);
			_promoteFromTo(from, wsFrom, to, wsTo, false, oCanPromote, false, bVertical, nIndex);
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8279 8280
		}
	}
8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295
	Range.prototype.canPromote=function(bCtrl, bVertical, nIndex){
		var oBBox = this.bbox;
		var nWidth = oBBox.c2 - oBBox.c1 + 1;
		var nHeight = oBBox.r2 - oBBox.r1 + 1;
		var bWholeCol = false;	var bWholeRow = false;
		if(0 == oBBox.r1 && gc_nMaxRow0 == oBBox.r2)
			bWholeCol = true;
		if(0 == oBBox.c1 && gc_nMaxCol0 == oBBox.c2)
			bWholeRow = true;
		if((bWholeCol && bWholeRow) || (true == bVertical && bWholeCol) || (false == bVertical && bWholeRow))
			return null;
		var oPromoteAscRange = null;
		if(0 == nIndex)
			oPromoteAscRange = Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2);
		else
8296
		{
8297
			if(bVertical)
8298
			{
8299 8300 8301 8302 8303 8304 8305
				if(nIndex > 0)
				{
					if(nIndex >= nHeight)
						oPromoteAscRange = Asc.Range(oBBox.c1, oBBox.r2 + 1, oBBox.c2, oBBox.r1 + nIndex);
					else
						oPromoteAscRange = Asc.Range(oBBox.c1, oBBox.r1 + nIndex, oBBox.c2, oBBox.r2);
				}
8306
				else
8307
					oPromoteAscRange = Asc.Range(oBBox.c1, oBBox.r1 + nIndex, oBBox.c2, oBBox.r1 - 1);
8308
			}
8309
			else
8310
			{
8311 8312 8313 8314 8315 8316 8317
				if(nIndex > 0)
				{
					if(nIndex >= nWidth)
						oPromoteAscRange = Asc.Range(oBBox.c2 + 1, oBBox.r1, oBBox.c1 + nIndex, oBBox.r2);
					else
						oPromoteAscRange = Asc.Range(oBBox.c1 + nIndex, oBBox.r1, oBBox.c2, oBBox.r2);
				}
8318
				else
8319
					oPromoteAscRange = Asc.Range(oBBox.c1 + nIndex, oBBox.r1, oBBox.c1 - 1, oBBox.r2);
8320 8321
			}
		}
8322 8323 8324
		//проверяем можно ли осуществить promote
		return _canPromote(oBBox, this.worksheet, oPromoteAscRange, this.worksheet, true, nWidth, nHeight, bVertical, nIndex);
	};
8325 8326 8327 8328 8329 8330 8331 8332
	Range.prototype.promote=function(bCtrl, bVertical, nIndex, oCanPromote){
		//todo отдельный метод для promote в таблицах и merge в таблицах
		if (!oCanPromote) {
			oCanPromote = this.canPromote(bCtrl, bVertical, nIndex);
		}
		var oBBox = this.bbox;
		var nWidth = oBBox.c2 - oBBox.c1 + 1;
		var nHeight = oBBox.r2 - oBBox.r1 + 1;
8333

8334 8335 8336
		History.Create_NewPoint();
		var oSelection = History.GetSelection();
		if(null != oSelection)
8337
		{
8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380
			oSelection = oSelection.clone();
			oSelection.assign(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2);
			History.SetSelection(oSelection);
		}
		var oSelectionRedo = History.GetSelectionRedo();
		if(null != oSelectionRedo)
		{
			oSelectionRedo = oSelectionRedo.clone();
			if(0 == nIndex)
				oSelectionRedo.assign(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2);
			else
			{
				if(bVertical)
				{
					if(nIndex > 0)
					{
						if(nIndex >= nHeight)
							oSelectionRedo.assign(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r1 + nIndex);
						else
							oSelectionRedo.assign(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r1 + nIndex - 1);
					}
					else
						oSelectionRedo.assign(oBBox.c1, oBBox.r1 + nIndex, oBBox.c2, oBBox.r2);
				}
				else
				{
					if(nIndex > 0)
					{
						if(nIndex >= nWidth)
							oSelectionRedo.assign(oBBox.c1, oBBox.r1, oBBox.c1 + nIndex, oBBox.r2);
						else
							oSelectionRedo.assign(oBBox.c1, oBBox.r1, oBBox.c1 + nIndex - 1, oBBox.r2);
					}
					else
						oSelectionRedo.assign(oBBox.c1 + nIndex, oBBox.r1, oBBox.c2, oBBox.r2);
				}
			}
			History.SetSelectionRedo(oSelectionRedo);
		}
		_promoteFromTo(oBBox, this.worksheet, oCanPromote.to, this.worksheet, true, oCanPromote, bCtrl, bVertical, nIndex);
	};
	function _promoteFromTo(from, wsFrom, to, wsTo, bIsPromote, oCanPromote, bCtrl, bVertical, nIndex) {
		var wb = wsFrom.workbook;
8381

8382 8383 8384 8385 8386 8387 8388 8389
		wb.dependencyFormulas.lockRecal();
		History.StartTransaction();

		var toRange = wsTo.getRange3(to.r1, to.c1, to.r2, to.c2);
		var fromRange = wsFrom.getRange3(from.r1, from.c1, from.r2, from.c2);
		var bChangeRowColProp = false;
		var nLastCol = from.c2;
		if (0 == from.c1 && gc_nMaxCol0 == from.c2)
8390
		{
8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401
			var aRowProperties = [];
			nLastCol = 0;
			fromRange._foreachRowNoEmpty(function(row){
				if(!row.isEmptyProp())
					aRowProperties.push({index: row.index - from.r1, prop: row.getHeightProp(), style: row.getStyle()});
			}, function(cell){
				var nCurCol0 = cell.nCol;
				if(nCurCol0 > nLastCol)
					nLastCol = nCurCol0;
			});
			if(aRowProperties.length > 0)
8402
			{
8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428
				bChangeRowColProp = true;
				var nCurCount = 0;
				var nCurIndex = 0;
				while (true) {
					for (var i = 0, length = aRowProperties.length; i < length; ++i) {
						var propElem = aRowProperties[i];
						nCurIndex = to.r1 + nCurCount * (from.r2 - from.r1 + 1) + propElem.index;
						if (nCurIndex > to.r2)
							break;
						else{
							var row = wsTo._getRow(nCurIndex);
							if (null != propElem.style)
								row.setStyle(propElem.style);
							if (null != propElem.prop) {
								var oNewProps = propElem.prop;
								var oOldProps = row.getHeightProp();
								if (false === oOldProps.isEqual(oNewProps)) {
									row.setHeightProp(oNewProps);
									History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RowProp, wsTo.getId(), row._getUpdateRange(), new UndoRedoData_IndexSimpleProp(nCurIndex, true, oOldProps, oNewProps));
								}
							}
						}
					}
					nCurCount++;
					if (nCurIndex > to.r2)
						break;
8429
				}
8430
			}
8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445
		}
		var nLastRow = from.r2;
		if (0 == from.r1 && gc_nMaxRow0 == from.r2)
		{
			var aColProperties = [];
			nLastRow = 0;
			fromRange._foreachColNoEmpty(function(col){
				if(!col.isEmpty())
					aColProperties.push({ index: col.index - from.c1, prop: col.getWidthProp(), style: col.getStyle() });
			}, function(cell){
				var nCurRow0 = cell.nRow;
				if(nCurRow0 > nLastRow)
					nLastRow = nCurRow0;
			});
			if (aColProperties.length > 0)
8446
			{
8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472
				bChangeRowColProp = true;
				var nCurCount = 0;
				var nCurIndex = 0;
				while (true) {
					for (var i = 0, length = aColProperties.length; i < length; ++i) {
						var propElem = aColProperties[i];
						nCurIndex = to.c1 + nCurCount * (from.c2 - from.c1 + 1) + propElem.index;
						if (nCurIndex > to.c2)
							break;
						else{
							var col = wsTo._getCol(nCurIndex);
							if (null != propElem.style)
								col.setStyle(propElem.style);
							if (null != propElem.prop) {
								var oNewProps = propElem.prop;
								var oOldProps = col.getWidthProp();
								if (false == oOldProps.isEqual(oNewProps)) {
									col.setWidthProp(oNewProps);
									History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ColProp, wsTo.getId(), new Asc.Range(nCurIndex, 0, nCurIndex, gc_nMaxRow0), new UndoRedoData_IndexSimpleProp(nCurIndex, false, oOldProps, oNewProps));
								}
							}
						}
					}
					nCurCount++;
					if (nCurIndex > to.c2)
						break;
8473
				}
8474 8475
			}
		}
8476 8477 8478 8479 8480 8481 8482 8483 8484
		if (bChangeRowColProp)
			wb.handlers.trigger("changeWorksheetUpdate", wsTo.getId());
		if(nLastCol != from.c2 || nLastRow != from.r2)
		{
			var offset = {offsetCol:nLastCol - from.c2, offsetRow:nLastRow - from.r2};
			toRange.setOffsetLast(offset);
			to = toRange.getBBox0();
			fromRange.setOffsetLast(offset);
			from = fromRange.getBBox0();
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8485
		}
8486 8487 8488 8489 8490 8491 8492
		var nWidth = from.c2 - from.c1 + 1;
		var nHeight = from.r2 - from.r1 + 1;
		//удаляем текст или все в области для заполнения
		if(bIsPromote && nIndex >= 0 && ((true == bVertical && nHeight > nIndex) || (false == bVertical && nWidth > nIndex)))
		{
			//удаляем только текст в области для заполнения
			toRange.cleanText();
8493
		}
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8494
		else
8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507
		{
			//удаляем все в области для заполнения
			if(bIsPromote)
				toRange.cleanAll();
			else
				toRange.cleanFormat();
			//собираем все данные
			var bReverse = false;
			if(nIndex < 0)
				bReverse = true;
			var oPromoteHelper = new PromoteHelper(bVertical, bReverse, from);
			fromRange._foreachNoEmpty(function(oCell, nRow0, nCol0, nRowStart0, nColStart0){
				if(null != oCell)
8508
				{
8509 8510 8511 8512 8513
					var nVal = null;
					var bDelimiter = false;
					var sPrefix = null;
					var bDate = false;
					if(bIsPromote)
8514
					{
8515
						if (!oCell.formulaParsed)
8516
						{
8517 8518
							var sValue = oCell.getValueWithoutFormat();
							if("" != sValue)
8519
							{
8520 8521 8522
								bDelimiter = true;
								var nType = oCell.getType();
								if(CellValueType.Number == nType || CellValueType.String == nType)
8523
								{
8524 8525 8526
									if(CellValueType.Number == nType)
										nVal = sValue - 0;
									else
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8527
									{
8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542
										//если текст заканчивается на цифру тоже используем ее
										var nEndIndex = sValue.length;
										for(var k = sValue.length - 1; k >= 0; --k)
										{
											var sCurChart = sValue[k];
											if('0' <= sCurChart && sCurChart <= '9')
												nEndIndex--;
											else
												break;
										}
										if(sValue.length != nEndIndex)
										{
											sPrefix = sValue.substring(0, nEndIndex);
											nVal = sValue.substring(nEndIndex) - 0;
										}
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8543
									}
8544
								}
8545 8546 8547 8548 8549 8550 8551
								if(null != oCell.xfs && null != oCell.xfs.num && null != oCell.xfs.num.getFormat()){
									var numFormat = oNumFormatCache.get(oCell.xfs.num.getFormat());
									if(numFormat.isDateTimeFormat())
										bDate = true;
								}
								if(null != nVal)
									bDelimiter = false;
8552
							}
8553
						}
8554 8555
						else
							bDelimiter = true;
8556
					}
8557
					oPromoteHelper.add(nRow0 - nRowStart0, nCol0 - nColStart0, nVal, bDelimiter, sPrefix, bDate, oCell);
8558
				}
8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569
			});
			var bCopy = false;
			if(bCtrl)
				bCopy = true;
			//в случае одной ячейки с числом меняется смысл bCtrl
			if(1 == nWidth && 1 == nHeight && oPromoteHelper.isOnlyIntegerSequence())
				bCopy = !bCopy;
			oPromoteHelper.finishAdd(bCopy);
			//заполняем ячейки данными
			var nStartRow, nEndRow, nStartCol, nEndCol, nColDx, bRowFirst;
			if(bVertical)
8570
			{
8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585
				nStartRow = to.c1;
				nEndRow = to.c2;
				bRowFirst = false;
				if(bReverse)
				{
					nStartCol = to.r2;
					nEndCol = to.r1;
					nColDx = -1;
				}
				else
				{
					nStartCol = to.r1;
					nEndCol = to.r2;
					nColDx = 1;
				}
8586 8587 8588
			}
			else
			{
8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603
				nStartRow = to.r1;
				nEndRow = to.r2;
				bRowFirst = true;
				if(bReverse)
				{
					nStartCol = to.c2;
					nEndCol = to.c1;
					nColDx = -1;
				}
				else
				{
					nStartCol = to.c1;
					nEndCol = to.c2;
					nColDx = 1;
				}
8604
			}
8605
			for(var i = nStartRow; i <= nEndRow; i ++)
8606
			{
8607 8608
				oPromoteHelper.setIndex(i - nStartRow);
				for(var j = nStartCol; (nStartCol - j) * (nEndCol - j) <= 0; j += nColDx)
8609
				{
8610 8611
					var data = oPromoteHelper.getNext();
					if(null != data && (data.oAdditional || (false == bCopy && null != data.nCurValue)))
8612
					{
8613 8614 8615 8616 8617 8618 8619
						var oFromCell = data.oAdditional;
						var oCopyCell = null;
						if(bRowFirst)
							oCopyCell = wsTo._getCell(i, j);
						else
							oCopyCell = wsTo._getCell(j, i);
						if(bIsPromote)
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8620
						{
8621 8622 8623 8624 8625 8626 8627 8628
							if(false == bCopy && null != data.nCurValue)
							{
								var sVal = "";
								if(null != data.sPrefix)
									sVal += data.sPrefix;
								//change javascript NumberDecimalSeparator '.' , to cultural NumberDecimalSeparator
								sVal += data.nCurValue.toString().replace(/\./g, AscCommon.g_oDefaultCultureInfo.NumberDecimalSeparator);
								oCopyCell.setValue(sVal);
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8629
							}
8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640
							else if(null != oFromCell)
							{
								//копируем полностью
								if(!oFromCell.formulaParsed){
									var DataOld = oCopyCell.getValueData();
									oCopyCell.oValue = oFromCell.oValue.clone();
									var DataNew = oCopyCell.getValueData();
									if(false == DataOld.isEqual(DataNew))
										History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ChangeValue, wsTo.getId(), new Asc.Range(oCopyCell.nCol, oCopyCell.nRow, oCopyCell.nCol, oCopyCell.nRow), new UndoRedoData_CellSimpleData(oCopyCell.nRow, oCopyCell.nCol, DataOld, DataNew));
									//todo
									// if(oCopyCell.isEmptyTextString())
8641
									// wsTo._getHyperlink().remove({r1: oCopyCell.nRow, c1: oCopyCell.nCol, r2: oCopyCell.nRow, c2: oCopyCell.nCol});
8642 8643 8644 8645
								} else {
									var _p_ = oFromCell.formulaParsed.clone(null, oFromCell, this);
									var assemb = _p_.changeOffset(oCopyCell.getOffset2(oFromCell.getName())).assemble(true);
									oCopyCell.setFormula(assemb);
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8646 8647
								}
							}
8648
						}
8649 8650 8651 8652 8653 8654
						//выставляем стиль после текста, потому что если выставить числовой стиль ячейки 'text', то после этого не применится формула
						if (null != oFromCell) {
							oCopyCell.setStyle(oFromCell.getStyle());
							if (bIsPromote)
								oCopyCell.setType(oFromCell.getType());
						}
8655 8656
					}
				}
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8657
			}
8658 8659
			if(bIsPromote) {
				wb.dependencyFormulas.addToChangedRange( wsTo.Id, to );
8660
			}
8661 8662 8663 8664 8665
			//добавляем замерженые области
			var nDx = from.c2 - from.c1 + 1;
			var nDy = from.r2 - from.r1 + 1;
			var oMergedFrom = oCanPromote.oMergedFrom;
			if(null != oMergedFrom && oMergedFrom.all.length > 0)
8666
			{
8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680
				for (var i = to.c1; i <= to.c2; i += nDx) {
					for (var j = to.r1; j <= to.r2; j += nDy) {
						for (var k = 0, length3 = oMergedFrom.all.length; k < length3; k++) {
							var oMergedBBox = oMergedFrom.all[k].bbox;
							var oNewMerged = Asc.Range(i + oMergedBBox.c1 - from.c1, j + oMergedBBox.r1 - from.r1, i + oMergedBBox.c2 - from.c1, j + oMergedBBox.r2 - from.r1);
							if(to.contains(oNewMerged.c1, oNewMerged.r1)) {
								if(to.c2 < oNewMerged.c2)
									oNewMerged.c2 = to.c2;
								if(to.r2 < oNewMerged.r2)
									oNewMerged.r2 = to.r2;
								if(!oNewMerged.isOneCell())
									wsTo.mergeManager.add(oNewMerged, 1);
							}
						}
8681
					}
8682
				}
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8683
			}
8684
			if(bIsPromote)
8685
			{
8686 8687 8688 8689
				//добавляем ссылки
				//не как в Excel поддерживаются ссылки на диапазоны
				var oHyperlinks = wsFrom.hyperlinkManager.get(from);
				if(oHyperlinks.inner.length > 0)
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8690
				{
8691 8692 8693 8694 8695 8696 8697 8698 8699
					for (var i = to.c1; i <= to.c2; i += nDx) {
						for (var j = to.r1; j <= to.r2; j += nDy) {
							for(var k = 0, length3 = oHyperlinks.inner.length; k < length3; k++){
								var oHyperlink = oHyperlinks.inner[k];
								var oHyperlinkBBox = oHyperlink.bbox;
								var oNewHyperlink = Asc.Range(i + oHyperlinkBBox.c1 - from.c1, j + oHyperlinkBBox.r1 - from.r1, i + oHyperlinkBBox.c2 - from.c1, j + oHyperlinkBBox.r2 - from.r1);
								if (to.containsRange(oNewHyperlink))
									wsTo.hyperlinkManager.add(oNewHyperlink, oHyperlink.data.clone());
							}
8700
						}
8701 8702
					}
				}
8703 8704
			}
		}
8705 8706
		History.EndTransaction();
		wb.dependencyFormulas.unlockRecal();
8707
	}
8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732
	Range.prototype.createCellOnRowColCross=function(){
		var oThis = this;
		var bbox = this.bbox;
		var nRangeType = this._getRangeType(bbox);
		if(c_oRangeType.Row == nRangeType)
		{
			this._foreachColNoEmpty(function(col){
				if(null != col.xfs)
				{
					for(var i = bbox.r1; i <= bbox.r2; ++i)
						oThis.worksheet._getCell(i, col.index);
				}
			}, null);
		}
		else if(c_oRangeType.Col == nRangeType)
		{
			this._foreachRowNoEmpty(function(row){
				if(null != row.xfs)
				{
					for(var i = bbox.c1; i <= bbox.c2; ++i)
						oThis.worksheet._getCell(row.index, i);
				}
			}, null);
		}
	};
8733
//-------------------------------------------------------------------------------------------------
8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747
	/**
	 * @constructor
	 */
	function PromoteHelper(bVerical, bReverse, bbox){
		//автозаполнение происходит всегда в правую сторону, поэтому менются индексы в методе add, и это надо учитывать при вызове getNext
		this.bVerical = bVerical;
		this.bReverse = bReverse;
		this.bbox = bbox;
		this.oDataRow = {};
		//для get
		this.oCurRow = null;
		this.nCurColIndex = null;
		this.nRowLength = 0;
		this.nColLength = 0;
8748 8749
		if(this.bVerical)
		{
8750 8751
			this.nRowLength = this.bbox.c2 - this.bbox.c1 + 1;
			this.nColLength = this.bbox.r2 - this.bbox.r1 + 1;
8752
		}
8753
		else
8754
		{
8755 8756
			this.nRowLength = this.bbox.r2 - this.bbox.r1 + 1;
			this.nColLength = this.bbox.c2 - this.bbox.c1 + 1;
8757
		}
8758 8759 8760 8761
	}
	PromoteHelper.prototype = {
		add: function(nRow, nCol, nVal, bDelimiter, sPrefix, bDate, oAdditional){
			if(this.bVerical)
8762
			{
8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784
				//транспонируем для удобства
				var temp = nRow;
				nRow = nCol;
				nCol = temp;
			}
			if(this.bReverse)
				nCol = this.nColLength - nCol - 1;
			var row = this.oDataRow[nRow];
			if(null == row)
			{
				row = {};
				this.oDataRow[nRow] = row;
			}
			row[nCol] = {nCol: nCol, nVal: nVal, bDelimiter: bDelimiter, sPrefix: sPrefix, bDate: bDate, oAdditional: oAdditional, oSequence: null, nCurValue: null};
		},
		isOnlyIntegerSequence: function(){
			var bRes = true;
			var bEmpty = true;
			for(var i in this.oDataRow)
			{
				var row = this.oDataRow[i];
				for(var j in row)
8785
				{
8786 8787 8788 8789 8790 8791 8792
					var data = row[j];
					bEmpty = false;
					if(!(null != data.nVal && true != data.bDate && null == data.sPrefix))
					{
						bRes = false;
						break;
					}
8793
				}
8794 8795
				if(!bRes)
					break;
8796
			}
8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811
			if(bEmpty)
				bRes = false;
			return bRes;
		},
		_promoteSequence: function(aDigits){
			// Это коэффициенты линейного приближения (http://office.microsoft.com/ru-ru/excel-help/HP010072685.aspx)
			// y=a1*x+a0 (где: x=0,1....; y=значения в ячейках; a0 и a1 - это решения приближения функции методом наименьших квадратов
			// (n+1)*a0        + (x0+x1+....)      *a1=(y0+y1+...)
			// (x0+x1+....)*a0 + (x0*x0+x1*x1+....)*a1=(y0*x0+y1*x1+...)
			// http://www.exponenta.ru/educat/class/courses/vvm/theme_7/theory.asp
			var a0 = 0.0;
			var a1 = 0.0;
			// Индекс X
			var nX = 0;
			if(1 == aDigits.length)
8812
			{
8813 8814 8815 8816 8817
				nX = 1;
				a1 = 1;
				a0 = aDigits[0].y;
			}
			else
8818
			{
8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831
				// (n+1)
				var nN = aDigits.length;
				// (x0+x1+....)
				var nXi = 0;
				// (x0*x0+x1*x1+....)
				var nXiXi = 0;
				// (y0+y1+...)
				var dYi = 0.0;
				// (y0*x0+y1*x1+...)
				var dYiXi = 0.0;

				// Цикл по всем строкам
				for (var i = 0, length = aDigits.length; i < length; ++i)
8832
				{
8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864
					var data = aDigits[i];
					nX = data.x;
					var dValue = data.y;

					// Вычисляем значения
					nXi += nX;
					nXiXi += nX * nX;
					dYi += dValue;
					dYiXi += dValue * nX;
				}
				nX++;

				// Теперь решаем систему уравнений
				// Общий детерминант
				var dD = nN * nXiXi - nXi * nXi;
				// Детерминант первого корня
				var dD1 = dYi * nXiXi - nXi * dYiXi;
				// Детерминант второго корня
				var dD2 = nN * dYiXi - dYi * nXi;

				a0 = dD1 / dD;
				a1 = dD2 / dD;
			}
			return {a0: a0, a1: a1, nX: nX};
		},
		_addSequenceToRow : function(nRowIndex, aSortRowIndex, row, aCurSequence){
			if(aCurSequence.length > 0)
			{
				var oFirstData = aCurSequence[0];
				var bCanPromote = true;
				//если последовательность состоит из одного числа и той же колонке есть еще последовательности, то надо копировать, а не автозаполнять
				if(1 == aCurSequence.length)
8865
				{
8866 8867 8868
					var bVisitRowIndex = false;
					var oVisitData = null;
					for(var i = 0, length = aSortRowIndex.length; i < length; i++)
8869
					{
8870 8871
						var nCurRowIndex = aSortRowIndex[i];
						if(nRowIndex == nCurRowIndex)
8872
						{
8873 8874 8875 8876 8877 8878
							bVisitRowIndex = true;
							if(oVisitData && oFirstData.sPrefix == oVisitData.sPrefix && oFirstData.bDate == oVisitData.bDate)
							{
								bCanPromote = false;
								break;
							}
8879
						}
8880
						else
8881
						{
8882 8883
							var oCurRow = this.oDataRow[nCurRowIndex];
							if(oCurRow)
8884
							{
8885 8886
								var data = oCurRow[oFirstData.nCol];
								if(null != data)
8887
								{
8888
									if(null != data.nVal)
8889
									{
8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902
										oVisitData = data;
										if(bVisitRowIndex)
										{
											if(oFirstData.sPrefix == oVisitData.sPrefix && oFirstData.bDate == oVisitData.bDate)
												bCanPromote = false;
											break;
										}
									}
									else if(data.bDelimiter)
									{
										oVisitData = null;
										if(bVisitRowIndex)
											break;
8903 8904 8905 8906 8907 8908
									}
								}
							}
						}
					}
				}
8909
				if(bCanPromote)
8910
				{
8911 8912 8913 8914 8915 8916 8917 8918 8919 8920
					var nMinIndex = null;
					var nMaxIndex = null;
					var bValidIndexDif = true;
					var nPrevX = null;
					var nPrevVal = null;
					var nIndexDif = null;
					var nValueDif = null;
					//анализируем последовательность, если числа расположены не на одинаковом расстоянии, то считаем их сплошной последовательностью
					//последовательность с промежутками может быть только целочисленной
					for(var i = 0, length = aCurSequence.length; i < length; i++)
8921
					{
8922 8923 8924 8925 8926
						var data = aCurSequence[i];
						var nCurX = data.nCol;
						if(null == nMinIndex || null == nMaxIndex)
							nMinIndex = nMaxIndex = nCurX;
						else
8927
						{
8928 8929 8930 8931 8932 8933 8934 8935
							if(nCurX < nMinIndex)
								nMinIndex = nCurX;
							if(nCurX > nMaxIndex)
								nMaxIndex = nCurX;
						}
						if(bValidIndexDif)
						{
							if(null != nPrevX && null != nPrevVal)
8936
							{
8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948
								var nCurDif = nCurX - nPrevX;
								var nCurValDif = data.nVal - nPrevVal;
								if(null == nIndexDif || null == nCurValDif)
								{
									nIndexDif = nCurDif;
									nValueDif = nCurValDif;
								}
								else if(nIndexDif != nCurDif || nValueDif != nCurValDif)
								{
									nIndexDif = null;
									bValidIndexDif = false;
								}
8949 8950
							}
						}
8951 8952
						nPrevX = nCurX;
						nPrevVal = data.nVal;
8953
					}
8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965
					var bWithSpace = false;
					if(null != nIndexDif)
					{
						nIndexDif = Math.abs(nIndexDif);
						if(nIndexDif > 1)
							bWithSpace = true;
					}
					//заполняем массив с координатами
					var bExistSpace = false;
					nPrevX = null;
					var aDigits = [];
					for(var i = 0, length = aCurSequence.length; i < length; i++)
8966
					{
8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979
						var data = aCurSequence[i];
						var nCurX = data.nCol;
						var x = nCurX - nMinIndex;
						if(null != nIndexDif && nIndexDif > 0)
							x /= nIndexDif;
						if(null != nPrevX && nCurX - nPrevX > 1)
							bExistSpace = true;
						var y = data.nVal;
						//даты автозаполняем только по целой части
						if(data.bDate)
							y = parseInt(y);
						aDigits.push({x: x, y: y});
						nPrevX = nCurX;
8980
					}
8981
					if(aDigits.length > 0)
8982
					{
8983 8984
						var oSequence = this._promoteSequence(aDigits);
						if(1 == aDigits.length && this.bReverse)
8985
						{
8986 8987 8988 8989 8990 8991 8992 8993
							//меняем коэффициенты для случая одного числа в последовательности, иначе она в любую сторону будет возрастающей
							oSequence.a1 *= -1;
						}
						var bIsIntegerSequence = oSequence.a1 != parseInt(oSequence.a1);
						//для дат и чисел с префиксом автозаполняются только целочисленные последовательности
						if(!((null != oFirstData.sPrefix || true == oFirstData.bDate) && bIsIntegerSequence))
						{
							if(false == bWithSpace && bExistSpace)
8994
							{
8995
								for(var i = nMinIndex; i <= nMaxIndex; i++)
8996
								{
8997 8998 8999 9000 9001 9002 9003
									var data = row[i];
									if(null == data)
									{
										data = {nCol: i, nVal: null, bDelimiter: oFirstData.bDelimiter, sPrefix: oFirstData.sPrefix, bDate: oFirstData.bDate, oAdditional: null, oSequence: null, nCurValue: null};
										row[i] = data;
									}
									data.oSequence = oSequence;
9004 9005
								}
							}
9006
							else
9007
							{
9008 9009 9010 9011 9012 9013
								for(var i = 0, length = aCurSequence.length; i < length; i++)
								{
									var nCurX = aCurSequence[i].nCol;
									if(null != nCurX)
										row[nCurX].oSequence = oSequence;
								}
9014 9015 9016 9017 9018
							}
						}
					}
				}
			}
9019 9020 9021
		},
		finishAdd : function(bCopy){
			if(true != bCopy)
9022
			{
9023 9024 9025 9026 9027
				var aSortRowIndex = [];
				for(var i in this.oDataRow)
					aSortRowIndex.push(i - 0);
				aSortRowIndex.sort(fSortAscending);
				for(var i = 0, length = aSortRowIndex.length; i < length; i++)
9028
				{
9029 9030 9031 9032 9033 9034 9035 9036 9037 9038
					var nRowIndex = aSortRowIndex[i];
					var row = this.oDataRow[nRowIndex];
					//собираем информация о последовательностях в row
					var aSortIndex = [];
					for(var j in row)
						aSortIndex.push(j - 0);
					aSortIndex.sort(fSortAscending);
					var aCurSequence = [];
					var oPrevData = null;
					for(var j = 0, length2 = aSortIndex.length; j < length2; j++)
9039
					{
9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054
						var nColIndex = aSortIndex[j];
						var data = row[nColIndex];
						var bAddToSequence = false;
						if(null != data.nVal)
						{
							bAddToSequence = true;
							if(null != oPrevData && (oPrevData.bDelimiter != data.bDelimiter || oPrevData.sPrefix != data.sPrefix || oPrevData.bDate != data.bDate))
							{
								this._addSequenceToRow(nRowIndex, aSortRowIndex, row, aCurSequence);
								aCurSequence = [];
								oPrevData = null;
							}
							oPrevData = data;
						}
						else if(data.bDelimiter)
9055 9056 9057 9058 9059
						{
							this._addSequenceToRow(nRowIndex, aSortRowIndex, row, aCurSequence);
							aCurSequence = [];
							oPrevData = null;
						}
9060 9061
						if(bAddToSequence)
							aCurSequence.push(data);
9062
					}
9063
					this._addSequenceToRow(nRowIndex, aSortRowIndex, row, aCurSequence);
9064 9065
				}
			}
9066 9067 9068 9069 9070 9071 9072 9073 9074 9075
		},
		setIndex: function(index){
			if(0 != this.nRowLength && index >= this.nRowLength)
				index = index % (this.nRowLength);
			this.oCurRow = this.oDataRow[index];
			this.nCurColIndex = 0;
		},
		getNext: function(){
			var oRes = null;
			if(this.oCurRow)
9076
			{
9077 9078
				var oRes = this.oCurRow[this.nCurColIndex];
				if(null != oRes)
9079
				{
9080 9081 9082 9083 9084 9085 9086 9087 9088 9089
					oRes.nCurValue = null;
					if(null != oRes.oSequence)
					{
						var sequence = oRes.oSequence;
						if(oRes.bDate || null != oRes.sPrefix)
							oRes.nCurValue = Math.abs(sequence.a1 * sequence.nX + sequence.a0);
						else
							oRes.nCurValue = sequence.a1 * sequence.nX + sequence.a0;
						sequence.nX ++;
					}
9090
				}
9091 9092 9093
				this.nCurColIndex++;
				if(this.nCurColIndex >= this.nColLength)
					this.nCurColIndex = 0;
9094
			}
9095
			return oRes;
9096
		}
9097
	};
9098 9099 9100

//-------------------------------------------------------------------------------------------------

9101 9102 9103
	/**
	 * @constructor
	 */
9104

9105 9106 9107 9108
	function DrawingObjectsManager(worksheet)
	{
		this.worksheet = worksheet;
	}
9109

9110 9111 9112 9113 9114 9115
	DrawingObjectsManager.prototype.updateChartReferences = function(oldWorksheet, newWorksheet)
	{
		AscFormat.ExecuteNoHistory(function(){
			this.updateChartReferencesWidthHistory(oldWorksheet, newWorksheet);
		}, this, []);
	};
9116

9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127
	DrawingObjectsManager.prototype.updateChartReferencesWidthHistory = function(oldWorksheet, newWorksheet, bNoRebuildCache)
	{
		var aObjects = this.worksheet.Drawings;
		for (var i = 0; i < aObjects.length; i++) {
			var graphicObject = aObjects[i].graphicObject;
			if ( graphicObject.updateChartReferences )
			{
				graphicObject.updateChartReferences(oldWorksheet, newWorksheet, bNoRebuildCache);
			}
		}
	};
9128 9129


9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140
	DrawingObjectsManager.prototype.rebuildCharts = function(data)
	{
		var aObjects = this.worksheet.Drawings;
		for(var i = 0; i < aObjects.length; ++i)
		{
			if(aObjects[i].graphicObject.rebuildSeries)
			{
				aObjects[i].graphicObject.rebuildSeries(data);
			}
		}
	};
9141

9142 9143 9144 9145 9146
	window['AscCommonExcel'] = window['AscCommonExcel'] || {};
	window['AscCommonExcel'].g_nVerticalTextAngle = g_nVerticalTextAngle;
	window['AscCommonExcel'].oDefaultMetrics = oDefaultMetrics;
	window['AscCommonExcel'].g_nAllColIndex = g_nAllColIndex;
	window['AscCommonExcel'].g_nAllRowIndex = g_nAllRowIndex;
9147
	window['AscCommonExcel'].g_DefNameWorksheet = null;
9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162
	window['AscCommonExcel'].aStandartNumFormats = aStandartNumFormats;
	window['AscCommonExcel'].aStandartNumFormatsId = aStandartNumFormatsId;
	window['AscCommonExcel'].oFormulaLocaleInfo = oFormulaLocaleInfo;
	window['AscCommonExcel'].getDefNameIndex = getDefNameIndex;
	window['AscCommonExcel'].angleFormatToInterface2 = angleFormatToInterface2;
	window['AscCommonExcel'].angleInterfaceToFormat = angleInterfaceToFormat;
	window['AscCommonExcel'].Workbook = Workbook;
	window['AscCommonExcel'].Woorksheet = Woorksheet;
	window['AscCommonExcel'].Cell = Cell;
	window['AscCommonExcel'].Range = Range;
	window['AscCommonExcel'].DefName = DefName;
	window['AscCommonExcel'].RangeTree = RangeTree;
	window['AscCommonExcel'].DependencyGraph = DependencyGraph;
	window['AscCommonExcel'].preparePromoteFromTo = preparePromoteFromTo;
	window['AscCommonExcel'].promoteFromTo = promoteFromTo;
9163
})(window);