Workbook.js 324 KB
Newer Older
1 2
"use strict";

3
var g_nHSLMaxValue = 255;
4 5
var g_nVerticalTextAngle = 255;
var gc_dDefaultColWidthCharsAttribute;//определяется в WorksheetView.js
6
var gc_dDefaultRowHeightAttribute;//определяется в WorksheetView.js
7 8 9
var g_sNewSheetNamePattern = "Sheet";
var g_nSheetNameMaxLength = 31;
var g_nAllColIndex = -1;
10
var g_nAllRowIndex = -1;
11 12
var aStandartNumFormats;
var aStandartNumFormatsId;
13
var start, end, arrRecalc = {}, arrDefNameRecalc = {}, lc = 0;
14 15 16 17 18 19 20 21

var c_oRangeType =
{
    Range:0,
    Col:1,
    Row:2,
	All:3
};
22 23 24 25 26 27 28 29 30 31 32 33
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;
	else
		return c_oRangeType.Range;
}
34 35 36 37 38 39 40

function consolelog(text){
	if( window.g_debug_mode && console && console.log )
		console.log(text);
}

/** @constructor */
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
41 42 43 44 45
function DependencyGraph( wb ) {
    this.wb = wb;
    this.nodesId = null;
    this.nodesCell = null;
    this.nodesArea = null;
46
    this.defNameList = {};
47
    this.defNameSheets = {};
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
48
    this.nodeslength = null;
49 50
    this.bSetRefError = false;
    this.oChangeNodeSlave = null;
51 52
    this.sTableNamePattern = "Table";
    this.nTableNameMaxIndex = 0;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
53
    this.clear();
54 55
}
DependencyGraph.prototype = {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
56 57 58 59 60
    clear:function () {
        this.nodesId = {};
        this.nodesCell = {};
        this.nodesArea = {};
        this.nodeslength = 0;
61
		this.bSetRefError = false;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
    },
    nodeExist:function ( node ) {
        return this.nodeExist2( node.sheetId, node.cellId );
    },
    nodeExist2:function ( sheetId, cellId ) {
        return null != this.getNode( sheetId, cellId );
    },
    nodeExistWithArea:function ( sheetId, cellId ) {
        var bRes = this.nodeExist2( sheetId, cellId );
        if ( !bRes ) {
            var nodesSheetArea = this.nodesArea[sheetId];
            if ( null != nodesSheetArea ) {
                var bbox = Asc.g_oRangeCache.getAscRange( cellId );
                bRes = nodesSheetArea.get( bbox ).all.length > 0;
            }
        }
        return bRes;
    },
80 81 82
    getNode3:function ( nodeId ) {
        return this.nodesId[nodeId];
    },
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
83 84 85 86 87 88
    getNode2:function ( node ) {
        return this.nodesId[node.nodeId];
    },
    getNode:function ( sheetId, cellId ) {
        return this.nodesId[getVertexId( sheetId, cellId )];
    },
89

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
90 91 92 93
    addNode2:function ( node ) {
        return this.addNode( node.sheetId, node.cellId );
    },
    addNode:function ( sheetId, cellId ) {
94
		var _this = this;
95
        var nodeId = getVertexId( sheetId, cellId );
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
96 97
        var oRes = this.nodesId[nodeId];
        if ( null == oRes ) {
98
            var node = new Vertex( sheetId, cellId, this.wb );
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
99 100 101 102
            var oBBoxNode = node.getBBox();
            if ( node.isArea ) {
                var nodesSheetArea = this.nodesArea[node.sheetId];
                if ( null == nodesSheetArea ) {
103
					nodesSheetArea = new RangeDataManager(function(data, from, to){_this._changeNode(data, from, to);});
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
104 105 106 107 108 109 110
                    this.nodesArea[node.sheetId] = nodesSheetArea;
                }
                nodesSheetArea.add( oBBoxNode, node );
            }
            else {
                var nodesSheetCell = this.nodesCell[node.sheetId];
                if ( null == nodesSheetCell ) {
111
					nodesSheetCell = new CellArea(function(data, from, to){_this._changeNode(data, from, to);});
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
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
                    this.nodesCell[node.sheetId] = nodesSheetCell;
                }
                nodesSheetCell.add( oBBoxNode.r1, oBBoxNode.c1, node );
            }
            oRes = node;
        }
        return oRes;
    },
    addEdge2:function ( nodeFrom, nodeTo ) {
        nodeFrom.addMasterEdge( nodeTo );
        nodeTo.addSlaveEdge( nodeFrom );
    },
    addEdge:function ( sheetIdFrom, cellIdFrom, sheetIdTo, cellIdTo ) {
        var n1 = this.addNode( sheetIdFrom, cellIdFrom ),
            n2 = this.addNode( sheetIdTo, cellIdTo );
        this.addEdge2( n1, n2 );
    },
    getNodeBySheetId:function ( sheetId ) {
        var arr = [];
        var nodesSheetCell = this.nodesCell[sheetId];
        if ( nodesSheetCell ) {
            var aNodes = nodesSheetCell.getAll();
            for ( var i = 0, length = aNodes.length; i < length; i++ ) {
                var node = aNodes[i].data;
                var n = node.getSlaveEdges();
                if ( n ) {
                    arr.push( node );
                }
            }
141 142 143 144 145 146 147 148 149 150 151
        }
		var nodesSheetArea = this.nodesArea[sheetId];
        if ( nodesSheetArea ) {
            var aNodes = nodesSheetArea.getAll();
            for ( var i = 0, length = aNodes.length; i < length; i++ ) {
                var node = aNodes[i].data;
                var n = node.getSlaveEdges();
                if ( n ) {
                    arr.push( node );
                }
            }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
152 153
        }
        return arr;
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
    },
    getNodeBySheetIdAll:function ( sheetId ) {
        var arr = [];
        var nodesSheetCell = this.nodesCell[sheetId];
        if ( nodesSheetCell ) {
            var aNodes = nodesSheetCell.getAll();
            for ( var i = 0, length = aNodes.length; i < length; i++ ) {
                arr.push( aNodes[i].data );
            }
        }
		var nodesSheetArea = this.nodesArea[sheetId];
        if ( nodesSheetArea ) {
            var aNodes = nodesSheetArea.getAll();
            for ( var i = 0, length = aNodes.length; i < length; i++ ) {
                arr.push( aNodes[i].data );
            }
        }
        return arr;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
172
    },
173 174 175 176 177 178 179 180 181 182 183 184 185
    deleteNode:function ( node ) {
        if(node.isDefinedName) return;
        if ( node.isArea ) {
            var nodesSheetArea = this.nodesArea[node.sheetId];
            if ( nodesSheetArea )
                nodesSheetArea.removeElement( new RangeDataManagerElem( node.getBBox(), node ) );
        }
        else {
            var nodesSheetCell = this.nodesCell[node.sheetId];
            if ( nodesSheetCell )
                nodesSheetCell.removeElement( new RangeDataManagerElem( node.getBBox(), node ) );
        }
    },
186 187 188
	deleteNodes : function(sheetId, bbox){
		var bSetRefErrorOld = this.bSetRefError;
		this.bSetRefError = true;
189
		this.oChangeNodeSlave = { toDelete: {}, toMove: {} };
190 191 192 193 194 195 196
		var nodesSheetArea = this.nodesArea[sheetId];
		var oGetRes;
		if(nodesSheetArea)
		{
			oGetRes = nodesSheetArea.get(bbox);
			for(var i = 0, length = oGetRes.inner.length; i < length; ++i)
				nodesSheetArea.removeElement(oGetRes.inner[i]);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
197
        }
198 199 200 201 202 203 204
		var nodesSheetCell = this.nodesCell[sheetId];
		if(nodesSheetCell)
		{
			oGetRes = nodesSheetCell.get(bbox);
			for(var i = 0, length = oGetRes.length; i < length; ++i)
				nodesSheetCell.removeElement(oGetRes[i]);
		}
205
		this.changeNodeEnd();
206
		this.bSetRefError = bSetRefErrorOld;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
207 208 209 210 211 212 213 214 215 216 217
    },
    deleteMasterNodes:function ( sheetId, cellId ) {
        var node = this.getNode( sheetId, cellId );
        if ( node ) {
            var arr = node.deleteAllMasterEdges();
            for ( var i in arr ) {
                var nodeMaster = arr[i];
                if ( nodeMaster.refCount <= 0 )
                    this.deleteNode( nodeMaster );
            }
        }
218
		return node;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
219
    },
220 221 222 223 224 225
	deleteMasterNodes2 : function(sheetId, cellId){
		var node = this.deleteMasterNodes(sheetId, cellId);
		if(node && node.refCount <= 0)
			this.deleteNode(node);
		return node;
	},
226 227 228 229 230 231 232 233
	deleteMasterNodes3:function ( node ) {
	    var arr = node.deleteAllMasterEdges();
	    for (var i in arr) {
	        var nodeMaster = arr[i];
	        if (nodeMaster.refCount <= 0)
	            this.deleteNode(nodeMaster);
	    }
	},
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
234 235 236 237 238 239 240 241 242 243 244 245
    getSlaveNodes:function ( sheetId, cellId ) {
        //todo
        return null;
    },
    getMasterNodes:function ( sheetId, cellId ) {
        //todo
        return null;
    },
    getNodesLength:function () {
        return this.nodeslength;
    },
    checkOffset:function ( BBox, offset, wsId, noDelete ) {
246 247 248 249
        var _this = this,
            bHor = 0 != offset.offsetCol,
            toDelete = offset.offsetCol < 0 || offset.offsetRow < 0,
            bSetRefErrorOld = this.bSetRefError;
250
		this.bSetRefError = true;
251
		var oShiftGetBBox = shiftGetBBox(BBox, bHor);
252 253 254
		var sShiftGetBBoxName = oShiftGetBBox.getName();
		this.wb.needRecalc.nodes[getVertexId(wsId, sShiftGetBBoxName)] = [wsId, sShiftGetBBoxName];
		this.wb.needRecalc.length++;
255
		this.oChangeNodeSlave = { toDelete: {}, toMove: {}};
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
256
        var nodesSheetArea = this.nodesArea[wsId];
257
		if(nodesSheetArea)
258
			nodesSheetArea.shift(BBox, !toDelete, bHor);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
259
        var nodesSheetCell = this.nodesCell[wsId];
260
		if(nodesSheetCell)
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
261
            nodesSheetCell.shift( BBox, !toDelete, bHor );
262
		this.changeNodeEnd();
263
		this.bSetRefError = bSetRefErrorOld;
264 265 266
    },
    changeNodeProcessDelete: function (node, oFormulas, toDelete) {
        //todo deleteAllSlaveEdges deleteMasterNodes
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
267
        var oSlaves = node.deleteAllSlaveEdges(), slave, formula;
268 269 270
        if (this.bSetRefError) {
            //выставляем #REF!
            for (var i in oSlaves) {
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
271 272
                slave = oSlaves[i];
                if( slave instanceof DefNameVertex ){
273
                    this.wb.delDefinesNames(slave.getAscCDefName());
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
274 275
                    continue;
                }
276
                if (null == toDelete || slave != toDelete[slave.nodeId]) {
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
277
                    formula = slave.setRefError(node);
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
                    if (null != formula) {
                        if (oFormulas)
                            oFormulas[slave.nodeId] = { node: slave, formula: formula };
                        else
                            slave.setFormula(formula, true, false);
                    }
                }
            }
        }
        this.deleteMasterNodes3(node);
    },
    changeNodeProcessMove: function (node, from, to, oFormulas, toDelete) {
        if (null == toDelete || node != toDelete[node.nodeId])
            node.moveOuter(from, to, oFormulas);
    },
    changeNodeEnd : function(){
        var oChangeNodeSlave = this.oChangeNodeSlave;
        //обнуляем, потому что в цикле можем опять попасть в _changeNode со старым this.oChangeNodeSlave
        this.oChangeNodeSlave = null;
        //накапливаем формулы, потому что когда мы меняем формулу мы удаляем masterNodes, а эти node могут быть необработаными и влиять на формулу(C2=A2+B2 -> C1=A1+B2)
        var oFormulas = {};
        for (var i in oChangeNodeSlave.toDelete) {
            var elem = oChangeNodeSlave.toDelete[i];
            this.changeNodeProcessDelete(elem.node, oFormulas, oChangeNodeSlave.toDelete);
        }
        for (var i in oChangeNodeSlave.toMove) {
            var elem = oChangeNodeSlave.toMove[i];
            this.changeNodeProcessMove(elem.node, elem.from, elem.to, oFormulas, oChangeNodeSlave.toDelete);
        }
        for (var i in oFormulas) {
            var elem = oFormulas[i];
            if (null == elem.formula) {
                var node = elem.node;
                var cell = node.returnCell();
                if (cell && cell.formulaParsed) {
                    this.wb.dependencyFormulas.deleteMasterNodes2(node.sheetId, node.cellId);
                    addToArrRecalc(node.sheetId, cell);
                }
            }
            else
                elem.node.setFormula(elem.formula, true, false);
        }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
320
    },
321
	_changeNode : function(node, from, to){
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
322
        var toDelete = null == to;
323 324
		var toAdd = null == from;
		var wsId = node.sheetId;
325
		var sOldCellId = node.cellId;
326 327 328 329 330 331 332
		if(toAdd)
		{
			this.nodesId[node.nodeId] = node;
			this.nodeslength++;
		}
		else if(toDelete)
		{
333 334 335 336
			if (this.oChangeNodeSlave)
			    this.oChangeNodeSlave.toDelete[node.nodeId] = { node: node, from: from, to: to };
			else {
			    this.changeNodeProcessDelete(node, null);
337 338 339 340
			}
			delete this.nodesId[node.nodeId];
			this.nodeslength--;
		}
341 342 343 344 345 346 347
		else {
		    var sOldnodeId = node.nodeId;
		    node.moveInner(to);
		    if (this.oChangeNodeSlave)
		        this.oChangeNodeSlave.toMove[node.nodeId] = { node: node, from: from, to: to };
		    else
		        this.changeNodeProcessMove(node, from, to, null);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
348 349
            delete this.nodesId[sOldnodeId];
            this.nodesId[node.nodeId] = node;
350
		}
351
		//важно что ячейки уже сдвинулись, поэтому до вызова returnCell нужно сделать node.move и сдвинуть ячейки в aGCells
352 353
		if(!node.isArea)
		{
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
354
            var cwf = this.wb.cwf[wsId];
355
			if(cwf)
356
			{
357 358 359 360 361 362 363 364
				if(!toAdd)
					delete cwf.cells[sOldCellId];
				if(!toDelete)
				{
					var cell = node.returnCell();
					if ( cell && cell.formulaParsed )
						cwf.cells[node.cellId] = node.cellId;
				}
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
365 366 367
            }
        }
    },
368 369
	getCellInRange : function(sheetId, bbox){
		var res = [], oGetRes, nodesSheetCell = this.nodesCell[sheetId];
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
370
        if ( nodesSheetCell ) {
371
			oGetRes = nodesSheetCell.get(bbox);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
372
            for ( var i = 0, length = oGetRes.length; i < length; i++ ) {
373
				res.push(oGetRes[i].data);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
374 375 376 377 378 379 380 381 382 383 384
            }
        }
		return res;
	},
	getAreaInRange : function(sheetId, bbox){
		var res = [], oGetRes, nodesSheetArea = this.nodesArea[sheetId];
		if(nodesSheetArea)
		{
			oGetRes = nodesSheetArea.get(bbox);
			for(var i = 0, length = oGetRes.all.length; i < length; i++)
			{
385
				res.push(oGetRes.all[i].data);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
386 387 388 389
            }
		}
		return res;
    },
390 391
	getInRange : function(sheetId, bbox){
		return this.getCellInRange(sheetId, bbox).concat(this.getAreaInRange(sheetId, bbox));
392 393 394
	},
	helper : function(BBoxFrom, oBBoxTo, wsId){
		var oGetRes, node, nodesSheetCell = this.nodesCell[wsId], nodesSheetArea = this.nodesArea[wsId];
395 396
		var offset = { offsetCol: oBBoxTo.c1 - BBoxFrom.c1, offsetRow: oBBoxTo.r1 - BBoxFrom.r1 };
		this.oChangeNodeSlave = { toDelete: {}, toMove: {} };
397 398
		var elem, bbox;
		if(nodesSheetCell)
399
			oGetRes = nodesSheetCell.move(BBoxFrom, oBBoxTo);
400
		if(nodesSheetArea)
401 402
		    oGetRes = nodesSheetArea.move(BBoxFrom, oBBoxTo);
		this.changeNodeEnd();
403
	},
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
404 405 406 407 408 409 410 411 412 413 414
    drawDep:function ( cellId, se ) {
        // ToDo неиспользуемая функция, реализовать после выпуска
        if ( !cellId )
            return;
        var _wsV = this.wb.oApi.wb.getWorksheet(),
            _cc = _wsV.cellCommentator,
            ctx = _wsV.overlayCtx,
            _wsVM = _wsV.model,
            nodeId = getVertexId( _wsVM.getId(), cellId ),
            node = this.getNode( _wsVM.getId(), cellId ),
            cell;
415

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
416 417
        function gCM( _this, col, row ) {
            var metrics = { top:0, left:0, width:0, height:0, result:false }; 	// px
418

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
419 420 421
            var fvr = _this.getFirstVisibleRow();
            var fvc = _this.getFirstVisibleCol();
            var mergedRange = _wsVM.getMergedByCell( row, col );
422

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
423
            if ( mergedRange && (fvc < mergedRange.c2) && (fvr < mergedRange.r2) ) {
424

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
425 426
                var startCol = (mergedRange.c1 > fvc) ? mergedRange.c1 : fvc;
                var startRow = (mergedRange.r1 > fvr) ? mergedRange.r1 : fvr;
427

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
428 429
                metrics.top = _this.getCellTop( startRow, 0 ) - _this.getCellTop( fvr, 0 ) + _this.getCellTop( 0, 0 );
                metrics.left = _this.getCellLeft( startCol, 0 ) - _this.getCellLeft( fvc, 0 ) + _this.getCellLeft( 0, 0 );
430

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
431 432 433 434 435 436 437 438 439
                for ( var i = startCol; i <= mergedRange.c2; i++ ) {
                    metrics.width += _this.getColumnWidth( i, 0 )
                }
                for ( var i = startRow; i <= mergedRange.r2; i++ ) {
                    metrics.height += _this.getRowHeight( i, 0 )
                }
                metrics.result = true;
            }
            else {
440

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
441 442 443 444 445 446
                metrics.top = _this.getCellTop( row, 0 ) - _this.getCellTop( fvr, 0 ) + _this.getCellTop( 0, 0 );
                metrics.left = _this.getCellLeft( col, 0 ) - _this.getCellLeft( fvc, 0 ) + _this.getCellLeft( 0, 0 );
                metrics.width = _this.getColumnWidth( col, 0 );
                metrics.height = _this.getRowHeight( row, 0 );
                metrics.result = true;
            }
447

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
448 449
            return metrics;
        }
450

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
451 452 453 454 455 456 457 458
        if ( !node )
            return;

        cell = node.returnCell();

        if ( !cell )
            return;

459
        var m = [cell.nRow, cell.nCol],
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
460 461 462 463 464 465 466
            rc = [], me = se ? node.getSlaveEdges() : node.getMasterEdges();

        for ( var id in me ) {
            if ( me[id].sheetId != node.sheetId )
                return;

            if ( !me[id].isArea ) {
467
                var _t1 = gCM( _wsV, me[id].returnCell().nCol, me[id].returnCell().nRow )
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565

                rc.push( { t:_t1.top, l:_t1.left, w:_t1.width, h:_t1.height, apt:_t1.top + _t1.height / 2, apl:_t1.left + _t1.width / 4} );
            }
            else {
                var _t1 = gCM( _wsV, me[id].getBBox().c1, me[id].getBBox().r1 ),
                    _t2 = gCM( _wsV, me[id].getBBox().c2, me[id].getBBox().r2 );

                rc.push( { t:_t1.top, l:_t1.left, w:_t2.left + _t2.width - _t1.left, h:_t2.top + _t2.height - _t1.top, apt:_t1.top + _t1.height / 2, apl:_t1.left + _t1.width / 4  } );
            }
        }

        if ( rc.length == 0 )
            return;

        var color = new CColor( 0, 0, 255 );

        function draw_arrow( context, fromx, fromy, tox, toy ) {
            var headlen = 9;
            var dx = tox - fromx;
            var dy = toy - fromy;
            var angle = Math.atan2( dy, dx ), _a = Math.PI / 18;
            // ToDo посмотреть на четкость moveTo, lineTo
            context.save()
                .setLineWidth( 1 )
                .beginPath()
                .moveTo( _cc.pxToPt( fromx ), _cc.pxToPt( fromy ) )
                .lineTo( _cc.pxToPt( tox ), _cc.pxToPt( toy ) );
            // .dashLine(_cc.pxToPt(fromx-.5), _cc.pxToPt(fromy-.5), _cc.pxToPt(tox-.5), _cc.pxToPt(toy-.5), 15, 5)
            context
                .moveTo(
                _cc.pxToPt( tox - headlen * Math.cos( angle - _a ) ),
                _cc.pxToPt( toy - headlen * Math.sin( angle - _a ) ) )
                .lineTo( _cc.pxToPt( tox ), _cc.pxToPt( toy ) )
                .lineTo(
                _cc.pxToPt( tox - headlen * Math.cos( angle + _a ) ),
                _cc.pxToPt( toy - headlen * Math.sin( angle + _a ) ) )
                .lineTo(
                _cc.pxToPt( tox - headlen * Math.cos( angle - _a ) ),
                _cc.pxToPt( toy - headlen * Math.sin( angle - _a ) ) )
                .setStrokeStyle( color )
                .setFillStyle( color )
                .stroke()
                .fill()
                .closePath()
                .restore();
        }

        function h( m, rc ) {
            var m = gCM( _wsV, m[1], m[0] );
            var arrowPointTop = 10, arrowPointLeft = 10;
            for ( var i = 0; i < rc.length; i++ ) {
                var m2 = rc[i],
                    x1 = Math.floor( m2.apl ),
                    y1 = Math.floor( m2.apt ),
                    x2 = Math.floor( m.left + m.width / 4 ),
                    y2 = Math.floor( m.top + m.height / 2 );

                if ( x1 < 0 && x2 < 0 || y1 < 0 && y2 < 0 )
                    continue;

                // ToDo посмотреть на четкость rect
                if ( m2.apl > 0 && m2.apt > 0 )
                    ctx.save()
                        .setLineWidth( 1 )
                        .setStrokeStyle( color )
                        .rect( _cc.pxToPt( m2.l ), _cc.pxToPt( m2.t ), _cc.pxToPt( m2.w - 1 ), _cc.pxToPt( m2.h - 1 ) )
                        .stroke()
                        .restore();
                if ( y1 < 0 && x1 != x2 )
                    x1 = x1 - Math.floor( Math.sqrt( ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) * y1 * y1 / ((y2 - y1) * (y2 - y1)) ) / 2 )
                if ( x1 < 0 && y1 != y2 )
                    y1 = y1 - Math.floor( Math.sqrt( ((y1 - y2) * (y1 - y2) + (x1 - x2) * (x1 - x2)) * x1 * x1 / ((x2 - x1) * (x2 - x1)) ) / 2 )

                draw_arrow( ctx, x1 < 0 ? _wsV.getCellLeft( 0, 0 ) : x1, y1 < 0 ? _wsV.getCellTop( 0, 0 ) : y1, x2, y2 );

                if ( m2.apl > 0 && m2.apt > 0 )
                    ctx.save()
                        .beginPath()
                        .arc( _cc.pxToPt( Math.floor( m2.apl ) ),
                        _cc.pxToPt( Math.floor( m2.apt ) ),
                        3, 0, 2 * Math.PI, false, -0.5, -0.5 )
                        .setFillStyle( color )
                        .fill()
                        .closePath()
                        .restore();
            }
        }

        ctx.clear();
        _wsV._drawSelection();

        if ( se ) {
            for ( var i = 0; i < rc.length; i++ )
                h( rc[i], [m] );
        }
        else
            h( m, rc );
    },
566 567
    removeNodeBySheetId: function (sheetId) {
        this.oChangeNodeSlave = { toDelete: {}, toMove: {} };
568 569 570 571 572
		var nodesSheetArea = this.nodesArea[sheetId];
		if(nodesSheetArea)
			nodesSheetArea.removeAll();
        var nodesSheetCell = this.nodesCell[sheetId];
		if(nodesSheetCell)
573 574
		    nodesSheetCell.removeAll();
		this.changeNodeEnd();
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
575
    },
576
    getNodeDependence:function ( aElems, aDefinedNames ) {
577 578 579 580 581 582 583
        var oRes = { oMasterNodes: {}, oMasterAreaNodes: {}, oMasterAreaNodesRestricted: {}, oWeightMap: {}, oNodeToArea: {}, nCounter: 0 },
            aWeightMapMasters = [],
            aWeightMapMastersNodes = [],
            node,
            elem,
            oSheetRanges = {},
            oSheetWithArea = {};//все sheet на которых есть area для пересчета
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
        while ( null != aElems || null != aDefinedNames ) {
            if(null != aElems){
				for ( var i in aElems ) {
					elem = aElems[i];
					var sheetId = elem[0];
					var cellId = elem[1];
					//нужно обавлять в oSheetRanges даже несушествующие node, чтобы поддержать именении ячеек в SUM(A1:B2)
					this._getNodeDependenceNodeToRange(sheetId, Asc.g_oRangeCache.getAscRange(cellId), oSheetRanges);
					node = this.getNode(sheetId, cellId);
					if ( node && null == oRes.oWeightMap[node.nodeId] ) {
						//все node из aElems записываем в master
						var oWeightMapElem = { id: oRes.nCounter++, cur: 0, max: 0, gray: false, bad: false, master: true, area: node.isArea };
						if (node.isArea)
							oSheetWithArea[node.sheetId] = 1;
						aWeightMapMasters.push( oWeightMapElem );
						aWeightMapMastersNodes.push( node );
						oRes.oWeightMap[node.nodeId] = oWeightMapElem;
						this._getNodeDependence( oRes, oSheetRanges, node );
					}
				}
			}
			if(null != aDefinedNames){
				for(var i = 0; i < aDefinedNames.length; ++i){
					var node = aDefinedNames[i];
					if ( node && null == oRes.oWeightMap[node.nodeId] ) {
						//все node из aDefinedNames записываем в master
						var oWeightMapElem = { id: oRes.nCounter++, cur: 0, max: 0, gray: false, bad: false, master: true, area: false };
						aWeightMapMasters.push( oWeightMapElem );
						aWeightMapMastersNodes.push( node );
						oRes.oWeightMap[node.nodeId] = oWeightMapElem;
						this._getNodeDependence( oRes, oSheetRanges, node );
					}
				}
			}
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
618
            aElems = null;
619
			aDefinedNames = null;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
            //расширяем за счет area nodes
            for ( var i in oSheetRanges ) {
                var oSheetRange = oSheetRanges[i];
                if ( oSheetRange.changed ) {
                    oSheetRange.changed = false;
                    var nodesSheetArea = this.nodesArea[i];
                    if ( null != nodesSheetArea ) {
                        var aAllOuter = null;
                        if ( null == oSheetRange.prevRange ) {
                            var oGetRes = nodesSheetArea.get( oSheetRange.range );
                            if ( oGetRes.all.length > 0 )
                                aAllOuter = oGetRes.all;
                        }
                        else {
                            var aEdgeBBox = [];
635 636 637 638 639
							var bLeft = oSheetRange.range.c1 < oSheetRange.prevRange.c1;
							var bRight = oSheetRange.range.c2 > oSheetRange.prevRange.c2;
							var bTop = oSheetRange.range.r1 < oSheetRange.prevRange.r1;
							var bBottom = oSheetRange.range.r2 > oSheetRange.prevRange.r2;
                            if (bLeft)
640
                                aEdgeBBox.push(new Asc.Range(oSheetRange.range.c1, oSheetRange.range.r1, oSheetRange.prevRange.c1 - 1, oSheetRange.range.r2));
641
                            if (bRight)
642
                                aEdgeBBox.push(new Asc.Range(oSheetRange.prevRange.c2 + 1, oSheetRange.range.r1, oSheetRange.range.c2, oSheetRange.range.r2));
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
                            if (bTop || bBottom){
								var nNewC1, nNewC2;
								if(bLeft)
									nNewC1 = oSheetRange.range.c1 + 1;
								else
									nNewC1 = oSheetRange.range.c1;
								if(bRight)
									nNewC2 = oSheetRange.range.c2 - 1;
								else
									nNewC2 = oSheetRange.range.c2;
								if(bTop)
									aEdgeBBox.push(new Asc.Range(nNewC1, oSheetRange.range.r1, nNewC2, oSheetRange.prevRange.r1 - 1));
								if(bBottom)
									aEdgeBBox.push(new Asc.Range(nNewC1, oSheetRange.prevRange.r2 + 1, nNewC2, oSheetRange.range.r2));
							}
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
658 659 660 661 662 663 664 665 666 667 668 669 670
                            aAllOuter = [];
                            for ( var j = 0, length = aEdgeBBox.length; j < length; j++ ) {
                                var bbox = aEdgeBBox[j];
                                var oGetRes = nodesSheetArea.get( bbox );
                                if ( oGetRes.all.length > 0 )
                                    aAllOuter = aAllOuter.concat( oGetRes.all );
                            }
                        }
                        if ( aAllOuter && aAllOuter.length > 0 ) {
                            if ( null == aElems )
                                aElems = [];
                            for ( var j in aAllOuter ) {
                                var node = aAllOuter[j].data;
671
								aElems[node.nodeId] = [node.sheetId, node.cellId];
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
672 673 674 675 676 677
                            }
                        }
                    }
                }
            }
        }
678 679
        var bMasterAreaNodesExist = false;
        var oAllMasterAreaNodes = {};
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
680 681 682 683 684
        for ( var i = 0, length = aWeightMapMasters.length; i < length; i++ ) {
            var oWeightMapElem = aWeightMapMasters[i];
            //возвращаем только настощие master
            if ( oWeightMapElem.master ) {
                node = aWeightMapMastersNodes[i];
685 686 687 688
                if (oWeightMapElem.area) {
                    bMasterAreaNodesExist = true;
                    oAllMasterAreaNodes[node.nodeId] = node;
                }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
689 690 691 692
                else
                    oRes.oMasterNodes[node.nodeId] = node;
            }
        }
693 694 695 696 697
        if (bMasterAreaNodesExist) {
            //заносим все одинарные ячейки для пересчета в CellArea, чтобы определить какие из них лежат внутри area
            var oCellsForCalculation = {};
            for (var i in oRes.oWeightMap) {
                var elem = oRes.oWeightMap[i];
698
                if (!elem.area && !elem.isDefinedName) {
699 700 701
                    var node = this.wb.dependencyFormulas.nodesId[i];
                    //если ячейка из oMasterNodes, даже если в ней формула, то она не может иметь master из oWeightMap(иначе она бы перестала быть master) - такие ячейки не добавляем
                    //остальные ячейки имеют master из oWeightMap их надо проверять
702
                    if (node && oSheetWithArea[node.sheetId] && !oRes.oMasterNodes[node.nodeId]) {
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
                        var oCellsForCalculationSheet = oCellsForCalculation[node.sheetId];
                        if (null == oCellsForCalculationSheet) {
                            oCellsForCalculationSheet = new CellArea(null);
                            oCellsForCalculation[node.sheetId] = oCellsForCalculationSheet;
                        }
                        var bbox = node.getBBox();
                        oCellsForCalculationSheet.add(bbox.r1, bbox.c1, node);
                    }
                }
            }
            //делим oAllMasterAreaNodes на те что можно посчитать сразу и те что имеют внутри себя непосчитанные ячейки.
            //заполняем oNodeToArea ячейками и ссылками на AreaNode в которых ини лежат
            for (var i in oAllMasterAreaNodes) {
                var nodeMaster = oAllMasterAreaNodes[i];
                //элемент запоминает сколько node надо посечить прежде чем считать nodeMaster
                var nodeMasterElement = { node: nodeMaster, cur: 0, max: 0 };
                var bRestricted = false;
                var oCellsForCalculationSheet = oCellsForCalculation[nodeMaster.sheetId];
                if (oCellsForCalculationSheet) {
                    var oGetRes = oCellsForCalculationSheet.get(nodeMaster.getBBox());
                    if (oGetRes.length > 0) {
                        bRestricted = true;
                        for (var j = 0; j < oGetRes.length; ++j) {
                            var node = oGetRes[j].data;
                            var oNodeToAreaElement = oRes.oNodeToArea[node.nodeId];
                            if (null == oNodeToAreaElement) {
                                oNodeToAreaElement = [];
                                oRes.oNodeToArea[node.nodeId] = oNodeToAreaElement;
                            }
                            nodeMasterElement.max++;
                            oNodeToAreaElement.push(nodeMasterElement);
                        }
                    }
                }
                if (bRestricted)
                    oRes.oMasterAreaNodesRestricted[nodeMaster.nodeId] = nodeMasterElement;
                else
                    oRes.oMasterAreaNodes[nodeMaster.nodeId] = nodeMaster;
            }
        }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
743 744 745
        return oRes;
    },
    _getNodeDependence:function ( oRes, oSheetRanges, node ) {
746
        var oResMapCycle = null;
747
        var bStop = false;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
748 749
        var oWeightMapElem = oRes.oWeightMap[node.nodeId];
        if ( null == oWeightMapElem ) {
750 751 752 753
			if(node.isDefinedName)
				oWeightMapElem = { id: oRes.nCounter++, cur: 0, max: 1, gray: false, bad: false, master: false, area: false };
			else
				oWeightMapElem = { id: oRes.nCounter++, cur: 0, max: 1, gray: false, bad: false, master: false, area: node.isArea };
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
754 755 756 757 758
            oRes.oWeightMap[node.nodeId] = oWeightMapElem;
        }
        else {
            oWeightMapElem.max++;
            //если пришли в gray node, то это цикл
759 760
            if (oWeightMapElem.gray) {
                bStop = true;
761 762 763 764
                oResMapCycle = {};
                oResMapCycle[oWeightMapElem.id] = oWeightMapElem;
                oWeightMapElem.bad = true;
                oWeightMapElem.max--;
765
            }
766 767 768 769 770
            else if (oWeightMapElem.master && oWeightMapElem.max > 1) {
                bStop = true;
                //если повторно пришли в master node, то не считаем ее master
                oWeightMapElem.master = false;
                oWeightMapElem.max--;
771
            }
772
		}
773
        if (!bStop && 1 == oWeightMapElem.max && !node.isDefinedName )
774 775
            this._getNodeDependenceNodeToRange( node.sheetId, node.getBBox(), oSheetRanges );
        if (!bStop && oWeightMapElem.max <= 1) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
776 777
            oWeightMapElem.gray = true;
            var aNext = node.getSlaveEdges();
778 779 780 781 782 783 784 785 786 787 788 789 790
            for (var i in aNext) {
                var oCurMapCycle = this._getNodeDependence(oRes, oSheetRanges, aNext[i], oWeightMapElem);
                if (null != oCurMapCycle) {
                    oWeightMapElem.bad = true;
                    for (var i in oCurMapCycle) {
                        var oCurElem = oCurMapCycle[i];
                        if (oWeightMapElem != oCurElem) {
                            if (null == oResMapCycle)
                                oResMapCycle = {};
                            oResMapCycle[oCurElem.id] = oCurElem;
                        }
                    }
                }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
791 792 793
            }
            oWeightMapElem.gray = false;
        }
794
        return oResMapCycle;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
    },
    _getNodeDependenceNodeToRange:function ( sheetId, bbox, oSheetRanges ) {
        var oSheetRange = oSheetRanges[sheetId];
        if ( null == oSheetRange ) {
            oSheetRange = {range:null, changed:false, prevRange:null};
            oSheetRanges[sheetId] = oSheetRange;
        }
        if ( null == oSheetRange.range || !oSheetRange.range.containsRange( bbox ) ) {
            if ( null == oSheetRange.range )
                oSheetRange.range = bbox.clone();
            else {
                if ( !oSheetRange.changed )
                    oSheetRange.prevRange = oSheetRange.range.clone();
                oSheetRange.range.union2( bbox );
            }
            oSheetRange.changed = true;
        }
    },
    getAll:function () {
        return this.nodesId;
815 816 817 818
    },

    /*Defined Names section*/
    getDefNameNode:function ( node ) {
819
        var ret = this.defNameList[node];
820
        return ret && ret.Ref == null ? null : ret;
821
    },
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
822
    getDefNameNodeByName:function ( name, sheetId ) {
823 824 825

        name = name.toLowerCase();

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
826
        var sheetNodeList,
827
            nodeId,
828 829
            oRes = false;

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
830 831 832 833
        if ( !rx_defName.test( name ) ) {
            return oRes ;
        }

834 835
        if ( null != sheetId ) {
            sheetNodeList = this.defNameSheets[sheetId];
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
836
            if ( sheetNodeList ) {
837 838
                nodeId = getDefNameVertexId( sheetId, name );
                oRes = sheetNodeList[nodeId];
839
                if ( oRes && oRes.Ref ) return oRes;
840 841 842 843
            }
        }

        sheetNodeList = this.defNameSheets["WB"];
844 845 846 847
        if( sheetNodeList ){
            nodeId = getDefNameVertexId( null, name );
            oRes = sheetNodeList[nodeId];
        }
848
        if ( oRes && !oRes.Ref ) oRes = false;
849 850 851

        return oRes;
    },
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
852
    getDefNameNodeByRef:function ( ref, sheetId ) {
853 854 855 856
        var sheetNodeList;

        if ( null != sheetId ) {
            sheetNodeList = this.defNameSheets[sheetId];
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
857 858
            for ( var id in sheetNodeList ) {
                if ( sheetNodeList[id].Ref == ref ) {
859 860 861 862 863 864 865 866 867 868 869 870 871 872
                    return sheetNodeList[id].Name;
                }
            }
        }

        sheetNodeList = this.defNameSheets["WB"];
        for ( var id in sheetNodeList ) {
            if ( sheetNodeList[id].Ref === ref ) {
                return sheetNodeList[id].Name;
            }
        }

        return false;
    },
873
    addDefinedNameNode:function ( defName, sheetId, defRef, defHidden, bUndo ) {
874

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
875
        var ws = this.wb.getWorksheet( sheetId )
876 877
        ws ? sheetId = ws.getId() : null;

878 879
        var nodeId = getDefNameVertexId( sheetId, defName ),
            oRes = this.defNameList[nodeId], dfv, defNameSheetsList;
880

881
        if ( null == oRes || ( null == oRes.Ref && null == defRef ) ) {
882
            dfv = new DefNameVertex( sheetId, defName, defRef, defHidden, this.wb );
883 884
            oRes = (this.defNameList[dfv.nodeId] = dfv);
            defNameSheetsList = this.defNameSheets[dfv.sheetId];
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
885
            if ( defNameSheetsList == null ) {
886 887 888 889 890
                defNameSheetsList = {};
                this.defNameSheets[dfv.sheetId] = defNameSheetsList;
            }
            defNameSheetsList[dfv.nodeId] = dfv;
        }
891 892
        else if( null == oRes.Ref && null != defRef ){
            oRes.Ref = defRef;
893
            oRes.isTable = undefined;
894
            addToArrDefNameRecalc(oRes);
895
        }
896

Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
897 898
        /*поставить зависимость между ячейками и текущим ИД*/

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
899
        if ( bUndo ) {
900 901 902
            oRes.Ref = defRef;
        }

Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
903
        if( !oRes.isTable && oRes.Ref != undefined && oRes.Ref != null ){
904
            addToArrDefNameRecalc(oRes);
905
        }
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
906

907 908 909
        return oRes;

    },
910
    removeDefName:function ( sheetId, name ) {
911

912
        var ws = this.wb.getWorksheet( sheetId );
913 914
        ws ? sheetId = ws.getId() : null;

915
        var nodeId = getDefNameVertexId( sheetId, name ),
916
            oRes = this.defNameList[nodeId], ret = null;
917

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
918
        if ( oRes ) {
919 920
            this.defNameList[nodeId].Ref = null;
            ret = oRes;
921
            addToArrDefNameRecalc(oRes);
922 923 924 925
        }

        return ret;

926 927 928
    },
    removeDefNameBySheet:function ( sheetId ) {

Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
929
        var nodesList = this.defNameList, retRes = {}, defN, seUndoRedo = [], nSE, wsIndex, ws = this.wb.getWorksheetById(sheetId ), wsName = ws.getName();
930

931
        for ( var id in nodesList ) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
932 933 934 935 936 937 938
            defN = nodesList[id];
            if ( defN.isTable && defN.Ref ){
                var a = defN.Ref.split("!")[0];
                if( a.localeCompare(parserHelp.getEscapeSheetName(wsName)) == 0 ){
                    History.Add( g_oUndoRedoWorkbook, historyitem_Workbook_DefinedNamesDelete, null, null, new UndoRedoData_DefinedNames( defN.Name, defN.Ref, undefined, defN.isTable ) );
                    defN.Ref = null;
                }
939
                continue;
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
940
            }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
941
            if ( !defN.isTable && defN.parsedRef && defN.parsedRef.removeSheet( sheetId ) ) {
942
                seUndoRedo = [];
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
943

944
                nSE = defN.getSlaveEdges();
945 946
                for ( var nseID in nSE ) {
                    seUndoRedo.push( nseID );
947 948
                }

949
                wsIndex = this.wb.getWorksheetById( defN.sheetId );
950

951
                History.Add( g_oUndoRedoWorkbook, historyitem_Workbook_DefinedNamesDelete, null, null,
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
952
                    new UndoRedoData_DefinedNames( defN.Name, defN.Ref, wsIndex ? wsIndex.getIndex() : undefined, defN.isTable, seUndoRedo ) );
953

954
                if ( defN.sheetId == sheetId ) {
955 956 957 958
                    defN.Ref = null;
                    defN.parsedRef = null;
                    retRes[id] = defN;
                }
959 960
                else {
                    defN.Ref = defN.parsedRef.Formula = defN.parsedRef.assemble( true );
961 962
                    retRes[id] = defN;
                }
963
                addToArrDefNameRecalc(defN);
964 965 966
            }
        }
        return retRes;
967
    },
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
968
    changeDefName:function ( oldDefName, newDefName ) {
969

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
970
        var ws = this.wb.getWorksheet( oldDefName.LocalSheetId ), sheetId = null;
971 972 973
        ws ? sheetId = ws.getId() : null;

        var oldN = this.getDefNameNodeByName( oldDefName.Name, sheetId ),
974 975 976
            res = null, sheetNodeList, nodeId,
            name = oldDefName.Name;

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
977 978
        sheetNodeList = this.defNameSheets[sheetId || "WB"];
        nodeId = getDefNameVertexId( sheetId || "WB", name );
979

980
        sheetNodeList ? delete sheetNodeList[nodeId] : null;
981 982 983

        delete this.defNameList[nodeId];

984 985 986 987
        if(!oldN){
            return false;
        }

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
988
        oldN.changeDefName( newDefName );
989 990 991 992

        this.defNameList[oldN.nodeId] = oldN;
        sheetNodeList[oldN.nodeId] = oldN;

993 994 995 996 997 998 999 1000
        if(oldDefName.isTable){
            var tableParts = this.wb.getActiveWs().TableParts;
            for(var i = 0; i < tableParts.length; i++){
                if( tableParts[i].DisplayName == name ){
                    tableParts[i].DisplayName = oldN.Name;
                }
            }
        }
1001 1002
        else{
            oldN.deleteAllMasterEdges();
1003
            addToArrDefNameRecalc(oldN);
1004
        }
1005

1006 1007
        return oldN;
    },
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
    copyDefNameByWorksheet:function( oldSheetId, newSheetId ){

        var obj = {}, oldS = this.defNameSheets[oldSheetId], defNamNode,
            oldWS = this.wb.getWorksheetById(oldSheetId ),
            newWS = this.wb.getWorksheetById(newSheetId);

        for( var id in oldS ){
            defNamNode = oldS[id].clone();
            defNamNode.changeScope(newSheetId);
            defNamNode.changeRefToNewSheet(oldWS.getName(),newWS.getName());
            obj[defNamNode.nodeId] = defNamNode;
            this.defNameList[defNamNode.nodeId] = defNamNode;
        }

        this.defNameSheets[newSheetId] = obj;

    },
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
1025
    relinkDefNameByWorksheet:function (oName, nName){
1026

1027
        var oldS = this.defNameList, dN;
1028
        for( var id in oldS ){
1029 1030 1031 1032
            dN = oldS[id];
            if(dN.isTable ){
                if(dN.Ref)
                    dN.Ref = dN.Ref.replace(oName,nName);
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
1033 1034
            }
            else{
1035
                dN.relinkRef(oName, nName);
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
1036
            }
1037 1038 1039
        }

    },
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1040
    saveDefName:function () {
1041
        var list = [], defN;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1042
        for ( var id in this.defNameList ) {
1043
            defN = this.defNameList[id];
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1044 1045 1046 1047 1048
            if ( defN.isTable ) {
                continue;
            }
            if ( defN.Ref != null ) {
                list.push( defN.getAscCDefName() );
1049 1050 1051 1052
            }
        }
        return list;
    },
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
    unlockDefName:function(){
        var nodesList = this.defNameList;

        for ( var id in nodesList ) {
            if ( nodesList[id].isLock ) {
                delete nodesList[id].isLock;
            }
        }
    },
    checkDefNameLock:function(){
1063
        var nodesList = this.defNameList, countNodes = 0;
1064 1065

        for ( var id in nodesList ) {
1066
            countNodes++;
1067 1068 1069 1070
            if ( nodesList[id].isLock ) {
                return true;
            }
        }
1071 1072
        return !countNodes;
//        return false;
1073 1074
    },

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1075
    getNextTableName:function ( ws, Ref ) {
1076 1077
        this.nTableNameMaxIndex++;
        var sNewName = this.sTableNamePattern + this.nTableNameMaxIndex,
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1078 1079
            name = getDefNameVertexId( null, sNewName );
        while ( this.defNameList[name] ) {
1080 1081
            this.nTableNameMaxIndex++;
            sNewName = this.sTableNamePattern + this.nTableNameMaxIndex;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1082
            name = getDefNameVertexId( null, sNewName );
1083
        }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1084
        this.addTableName( sNewName, ws, Ref );
1085 1086
        return sNewName;
    },
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1087
    addTableName:function ( sName, ws, Ref ) {
1088
        var refClone = Ref.clone(true ), dfv, defNameSheetsList;
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
1089
        refClone.r1++;
1090 1091
        dfv = new DefNameVertex( null, sName, parserHelp.get3DRef( ws.getName(), refClone.getAbsName() ), null, this.wb, true );
        defNameSheetsList = this.defNameSheets[dfv.sheetId];
1092
        this.defNameList[dfv.nodeId] = dfv;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1093
        if ( defNameSheetsList == null ) {
1094 1095 1096 1097
            defNameSheetsList = {};
            this.defNameSheets[dfv.sheetId] = defNameSheetsList;
        }
        defNameSheetsList[dfv.nodeId] = dfv;
1098 1099
    },
    changeTableName:function(tableName, ws, newRef){
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
1100 1101 1102 1103 1104
        var table = this.getDefNameNodeByName( tableName, ws ),
            newRefClone = newRef.clone(true);
        newRefClone.r1++;
        table.Ref = table.Ref.split("!")[0]+"!"+newRefClone.getAbsName();
//        table.Ref = parserHelp.getEscapeSheetName(ws.getName())+"!"+newRef.getAbsName();
1105 1106 1107 1108
    },
    delTableName:function(name,ws){
        var table = this.getDefNameNodeByName( name, ws );
        table.Ref = null;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1109
    }
1110
};
1111 1112

/** @constructor */
1113
function Vertex(sheetId, cellId, wb){
1114 1115 1116
	
	this.sheetId = sheetId;
	this.cellId = cellId;
1117 1118
	this.bbox = Asc.g_oRangeCache.getAscRange(this.cellId);
	this.isArea = !this.bbox.isOneCell();
1119
	this.valid = true;
1120
	this.nodeId = getVertexId(this.sheetId, this.cellId);
1121
    this.wb = wb;
1122
	this.cell = null;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1123
	
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
	//вершина которую мы прошли и поставили в очередь обхода
	this.isBlack = false;
	
	//вершина которую мы прошли, но не поставили в очередь обхода. нужно для определения петель в графе.
	this.isGray = false;
	
	//если вершина входит в цикличный путь, то она помечается плохой и запоминается в списке плохих вершин.
	this.isBad = false;
	
	//masterEdges содержит ячейки, от которых зависит текущая ячейка
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
1134
	this.masterEdges = {};
1135 1136
	
	//slaveEdges содержит ячейки, которые зависят от данной ячейки
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
1137
	this.slaveEdges = {};
1138 1139
	
	this.refCount = 0;
1140 1141
	
	this.isDefinedName = false;
1142 1143 1144 1145 1146
}
Vertex.prototype = {	
	
	constructor: Vertex,
	
1147 1148
	getBBox : function()
	{
1149
		return this.bbox;
1150
	},
1151
	setFormula : function(sFormula, bAddToHistory, bAddNeedRecalc)
1152
	{
1153 1154 1155 1156
	    this.wb.dependencyFormulas.deleteMasterNodes2(this.sheetId, this.cellId);
	    var cell = this.returnCell();
	    if (null != sFormula)
	        cell.setFormula(sFormula, bAddToHistory);
1157
		addToArrRecalc(this.sheetId, cell);
1158
		if(bAddNeedRecalc)
1159 1160 1161 1162 1163
		{
			this.wb.needRecalc.nodes[this.nodeId] = [this.sheetId, this.cellId ];
			this.wb.needRecalc.length++;
		}
	},
1164
	setRefError : function(wsId, cellId)
1165
	{
1166
	    var sRes = null;
1167 1168
		var cell = this.returnCell();
		if( cell && cell.formulaParsed )
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1169
		{
1170 1171
		    cell.formulaParsed.setRefError(wsId, cellId);
		    sRes = cell.formulaParsed.assemble(true);
1172
		}
1173
		return sRes;
1174
	},
1175 1176
	moveInner: function (bboxTo) {
	    //удаляем старые ссылки slave и master
1177 1178 1179
        var slave, master;
        for (var i in this.slaveEdges) {
	        slave = this.slaveEdges[i];
1180 1181 1182
	        slave.deleteMasterEdge(this);
	    }
	    for (var i in this.masterEdges) {
1183
	        master = this.masterEdges[i];
1184 1185 1186 1187 1188
	        master.deleteSlaveEdge(this);
	    }
	    this.bbox = bboxTo;
	    this.cellId = bboxTo.getName();
	    this.nodeId = getVertexId(this.sheetId, this.cellId);
1189
	    this.wb.needRecalc.nodes[this.nodeId] = [this.sheetId, this.cellId];
1190 1191 1192
	    this.wb.needRecalc.length++;
	    //добавляем новые slave и master
	    for (var i in this.slaveEdges) {
1193
	        slave = this.slaveEdges[i];
1194 1195 1196
	        slave.addMasterEdge(this);
	    }
	    for (var i in this.masterEdges) {
1197
	        master = this.masterEdges[i];
1198 1199
	        master.addSlaveEdge(this);
	    }
1200
	},
1201 1202
	moveOuter: function (from, to, oFormulas) {
	    if ((from.r1 == to.r1 && from.c1 == to.c1) || (from.r2 == to.r2 && from.c2 == to.c2)) {
1203
	        /*вставляем/удаляем по вертикали/горизонтали внутри диапазона*/
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
1204
	        var _sn = this.getSlaveEdges(), slave, cell;
1205
	        for (var _id in _sn) {
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
	            slave = _sn[_id];
                if( slave instanceof DefNameVertex ){
                    if ( false == this.wb.bUndoChanges && (false == this.wb.bRedoChanges || true == this.wb.bCollaborativeChanges )){
                        History.LocalChange = true;
                        var oN = slave.getAscCDefName(), nN;
                        slave.parsedRef.stretchArea(this, from, to);
                        nN = slave.getAscCDefName();
                        nN.Ref = slave.parsedRef.assemble();
                        this.wb.editDefinesNames( oN, nN );
                        History.LocalChange = false;
                    }
                    continue;
                }
	            cell = slave.returnCell();
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
	            if (cell && cell.formulaParsed) {
	                cell.formulaParsed.stretchArea(this, from, to);
	                var formula = cell.formulaParsed.assemble();
	                if (null != formula) {
	                    if (oFormulas)
	                        oFormulas[slave.nodeId] = { node: slave, formula: formula };
	                    else
	                        slave.setFormula(formula, true, false);
	                }
	            }
	        }
	    }
	    else {
1233
	        /*вставляем.удаляем левее/выше вне диапазона*/
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
	        if (oFormulas) {
	            if (null == oFormulas[this.nodeId])
	                oFormulas[this.nodeId] = { node: this, formula: null };
	        }
	        else {
	            var cell = this.returnCell();
	            if (cell && cell.formulaParsed) {
	                this.wb.dependencyFormulas.deleteMasterNodes2(this.sheetId, this.cellId);
	                addToArrRecalc(this.sheetId, cell);
	            }
	        }
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
1245
	        var _sn = this.getSlaveEdges(), slave, cell;
1246
	        for (var _id in _sn) {
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
	            slave = _sn[_id]
                if( slave instanceof DefNameVertex ){
                    /*slave.parsedRef.shiftCells(this, from, to);
                    slave.relinkRef();*/

                    if ( false == this.wb.bUndoChanges && (false == this.wb.bRedoChanges || true == this.wb.bCollaborativeChanges )){
                        History.LocalChange = true;
                        var oN = slave.getAscCDefName(), nN;
                        slave.parsedRef.shiftCells(this, from, to);
                        nN = slave.getAscCDefName();
                        nN.Ref = slave.parsedRef.assemble();
                        this.wb.editDefinesNames( oN, nN );
                        History.LocalChange = false;
                    }

                    continue;
                }
                cell = slave.returnCell();
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
	            if (cell && cell.formulaParsed) {
	                cell.formulaParsed.shiftCells(this, from, to);
	                var formula = cell.formulaParsed.assemble();
	                if (null != formula) {
	                    if (oFormulas)
	                        oFormulas[slave.nodeId] = { node: slave, formula: formula };
	                    else
	                        slave.setFormula(formula, true, false);
	                }
	            }
	        }
	    }
1277 1278 1279
	},
	//добавляем ведущую ячейку.
	addMasterEdge : function(node){
1280
		if( !this.masterEdges ){
1281
			this.masterEdges = {};
1282 1283 1284 1285 1286
        }
        if( !this.masterEdges[node.nodeId] ){
		    this.masterEdges[node.nodeId] = node;
    		this.refCount ++;
        }
1287 1288 1289 1290
	},

	//добавляем зависимую(ведомую) ячейку.
	addSlaveEdge : function(node){
1291
		if( !this.slaveEdges ){
1292
			this.slaveEdges = {};
1293 1294 1295 1296 1297
        }
        if( !this.slaveEdges[node.nodeId] ){
            this.slaveEdges[node.nodeId] = node;
            this.refCount ++;
        }
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
	},
	
	getMasterEdges : function(){
		return this.masterEdges;
	},

	getSlaveEdges : function(){
		return this.slaveEdges;
	},

	getSlaveEdges2 : function(){
		var ret = {}, count = 0;
		for(var id in this.slaveEdges){
			ret[id] = this.slaveEdges[id];
			count++;
		}
		if ( count > 0 ) 
			return ret; 
		else
			return null;
	},
	
	//удаляем ребро между конкретной ведущей ячейки.
1321 1322
	deleteMasterEdge: function (node) {
	    if (this.masterEdges) {
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
1323 1324
            delete this.masterEdges[node.nodeId];
            this.refCount--;
1325
	    }
1326 1327 1328
	},

	//удаляем ребро между конкретной зависимой(ведомой) ячейки.
1329 1330
	deleteSlaveEdge: function (node) {
	    if (this.slaveEdges) {
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
1331 1332
            delete this.slaveEdges[node.nodeId];
            this.refCount--;
1333
	    }
1334 1335 1336 1337
	},

	//очищаем все ребра по ведущим ячейкам.
	deleteAllMasterEdges : function(){
1338
		var ret = {};
1339
		for( var id in this.masterEdges ){
1340 1341
			var masterEdge = this.masterEdges[id];
			masterEdge.deleteSlaveEdge(this);
1342 1343
			delete this.masterEdges[id];
			this.refCount--;
1344
			ret[id] = masterEdge;
1345
		}
1346
		this.masterEdges = {};
1347 1348 1349 1350 1351
		return ret;
	},
	
	//очищаем все ребра по ведомым ячейкам.
	deleteAllSlaveEdges : function(){
1352
		var ret = {};
1353
		for( var id in this.slaveEdges ){
1354 1355
			var slaveEdge = this.slaveEdges[id];
			slaveEdge.deleteMasterEdge(this);
1356 1357
			delete this.slaveEdges[id];
			this.refCount--;
1358
			ret[id] = slaveEdge;
1359
		}
1360
		this.slaveEdges = {};
1361 1362 1363 1364
		return ret;
	},

	returnCell : function(){
1365 1366 1367 1368 1369
		//todo
		if(null == this.cell && this.wb && !this.isArea)
		{
			var ws = this.wb.getWorksheetById(this.sheetId);
			if(ws)
1370 1371
				this.cell = ws._getCell(this.bbox.r1, this.bbox.c1);
//				this.cell = ws._getCellNoEmpty(this.bbox.r1, this.bbox.c1);
1372
		}
1373 1374 1375
		return this.cell;
	}
	
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1376
};
1377

1378
function DefNameVertex( scope, defName, defRef, defHidden, wb, isTable ) {
1379

1380
    this.sheetId = scope === null || scope === undefined ? "WB" : scope;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1381 1382
    this.cellId = defName.toLowerCase();
    this.Ref = defRef;
1383
    this.Name = defName;
1384
    this.Hidden = defHidden;
1385
    this.isTable = isTable;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1386
    this.nodeId = getDefNameVertexId( this.sheetId, defName );
1387 1388
    this.wb = wb;

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1389 1390
    //вершина которую мы прошли и поставили в очередь обхода
    this.isBlack = false;
1391

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1392 1393
    //вершина которую мы прошли, но не поставили в очередь обхода. нужно для определения петель в графе.
    this.isGray = false;
1394

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1395 1396
    //если вершина входит в цикличный путь, то она помечается плохой и запоминается в списке плохих вершин.
    this.isBad = false;
1397

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1398
    //masterEdges содержит ячейки, от которых зависит текущая ячейка
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
1399
    this.masterEdges = {};
1400

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1401
    //slaveEdges содержит ячейки, которые зависят от данной ячейки
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
1402
    this.slaveEdges = {};
1403

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1404
    this.refCount = 0;
1405

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1406
    this.isDefinedName = true;
1407 1408 1409
}
DefNameVertex.prototype = {

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1410
    constructor:Vertex,
1411

1412
    clone:function(){
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
1413 1414 1415 1416 1417 1418 1419
        var dN = new DefNameVertex( this.sheetId, this.cellId, this.Ref, this.Hidden, this.wb, this.isTable );
        dN.parsedRef = new parserFormula( dN.Ref, "", this.wb.getWorksheet(0) );
        if( dN.Ref ){
            dN.parsedRef.parse();
//            dN.parsedRef.buildDependencies();
        }
        return dN;
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
    },

    changeScope:function( newScope ){
        this.sheetId = newScope === null || newScope === undefined ? "WB" : newScope;
        this.nodeId = getDefNameVertexId( this.sheetId, this.Name );
    },

    changeRefToNewSheet:function( lastName, newName ){
        if( this.parsedRef.isParsed ){
            this.parsedRef = this.parsedRef.changeSheet( lastName, newName );
            this.Ref = this.parsedRef.assemble();
        }
    },

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1434 1435 1436 1437 1438
    moveInner:function ( bboxTo ) {
        //удаляем старые ссылки slave и master
        for ( var i in this.slaveEdges ) {
            var slave = this.slaveEdges[i];
            slave.deleteMasterEdge( this );
1439
        }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1440 1441 1442
        for ( var i in this.masterEdges ) {
            var master = this.masterEdges[i];
            master.deleteSlaveEdge( this );
1443
        }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
        var sOldNodeId = this.nodeId;
        this.bbox = bboxTo;
        this.cellId = bboxTo.getName();
        this.nodeId = getVertexId( this.sheetId, this.cellId );
        this.wb.needRecalc.nodes[this.nodeId] = [this.sheetId, this.cellId ];
        this.wb.needRecalc.length++;
        //добавляем новые slave и master
        for ( var i in this.slaveEdges ) {
            var slave = this.slaveEdges[i];
            slave.addMasterEdge( this );
        }
        for ( var i in this.masterEdges ) {
            var master = this.masterEdges[i];
            master.addSlaveEdge( this );
        }
    },
    moveOuter:function ( from, to, oFormulas ) {
        if ( (from.r1 == to.r1 && from.c1 == to.c1) || (from.r2 == to.r2 && from.c2 == to.c2) ) {
            var _sn = this.getSlaveEdges();
            for ( var _id in _sn ) {
                var slave = _sn[_id];
                var cell = slave.returnCell();
                if ( cell && cell.formulaParsed ) {
                    cell.formulaParsed.stretchArea( this, from, to );
                    var formula = cell.formulaParsed.assemble();
                    if ( null != formula ) {
                        if ( oFormulas )
                            oFormulas[slave.nodeId] = { node:slave, formula:formula };
                        else
                            slave.setFormula( formula, true, false );
                    }
                }
            }
        }
        else {
            if ( oFormulas ) {
                if ( null == oFormulas[this.nodeId] )
                    oFormulas[this.nodeId] = { node:this, formula:null };
            }
            else {
                var cell = this.returnCell();
                if ( cell && cell.formulaParsed ) {
                    this.wb.dependencyFormulas.deleteMasterNodes2( this.sheetId, this.cellId );
                    addToArrRecalc( this.sheetId, cell );
                }
            }
            var _sn = this.getSlaveEdges();
            for ( var _id in _sn ) {
                var slave = _sn[_id]
                var cell = slave.returnCell();
                if ( cell && cell.formulaParsed ) {
                    cell.formulaParsed.shiftCells( this, from, to );
                    var formula = cell.formulaParsed.assemble();
                    if ( null != formula ) {
                        if ( oFormulas )
                            oFormulas[slave.nodeId] = { node:slave, formula:formula };
                        else
                            slave.setFormula( formula, true, false );
                    }
                }
            }
        }
    },
    //добавляем ведущую ячейку.
    addMasterEdge:function ( node ) {
        if ( !this.masterEdges ) {
            this.masterEdges = {};
        }
        if ( !this.masterEdges[node.nodeId] ) {
            this.masterEdges[node.nodeId] = node;
            this.refCount++;
        }
    },
1517

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1518 1519 1520 1521
    //добавляем зависимую(ведомую) ячейку.
    addSlaveEdge:function ( node ) {
        if ( !this.slaveEdges ) {
            this.slaveEdges = {};
1522
        }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1523
        if ( !this.slaveEdges[node.nodeId] ) {
1524
            this.slaveEdges[node.nodeId] = node;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1525
            this.refCount++;
1526
        }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1527
    },
1528

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1529 1530 1531
    getMasterEdges:function () {
        return this.masterEdges;
    },
1532

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1533 1534 1535
    getSlaveEdges:function () {
        return this.slaveEdges;
    },
1536

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
    getSlaveEdges2:function () {
        var ret = {}, count = 0;
        for ( var id in this.slaveEdges ) {
            ret[id] = this.slaveEdges[id];
            count++;
        }
        if ( count > 0 )
            return ret;
        else
            return null;
    },
1548

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1549 1550 1551
    //удаляем ребро между конкретной ведущей ячейки.
    deleteMasterEdge:function ( node ) {
        if ( this.masterEdges ) {
1552 1553
            delete this.masterEdges[node.nodeId];
            this.refCount--;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1554 1555
        }
    },
1556

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1557 1558 1559
    //удаляем ребро между конкретной зависимой(ведомой) ячейки.
    deleteSlaveEdge:function ( node ) {
        if ( this.slaveEdges ) {
1560 1561
            delete this.slaveEdges[node.nodeId];
            this.refCount--;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1562 1563
        }
    },
1564

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
    //очищаем все ребра по ведущим ячейкам.
    deleteAllMasterEdges:function () {
        var ret = {};
        for ( var id in this.masterEdges ) {
            var masterEdge = this.masterEdges[id];
            masterEdge.deleteSlaveEdge( this );
            this.masterEdges[id] = null;
            delete this.masterEdges[id];
            this.refCount--;
            ret[id] = masterEdge;
        }
        this.masterEdges = {};
        return ret;
    },
1579

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593
    //очищаем все ребра по ведомым ячейкам.
    deleteAllSlaveEdges:function () {
        var ret = {};
        for ( var id in this.slaveEdges ) {
            var slaveEdge = this.slaveEdges[id];
            slaveEdge.deleteMasterEdge( this );
            this.slaveEdges[id] = null;
            delete this.slaveEdges[id];
            this.refCount--;
            ret[id] = slaveEdge;
        }
        this.slaveEdges = {};
        return ret;
    },
1594

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1595 1596
    returnCell:function () {
        //todo
1597 1598 1599 1600 1601 1602 1603
        return false;
//        if ( null == this.cell && this.wb && !this.isArea && this.Ref !== null && this.Ref !== undefined ) {
//            var ws = this.wb.getWorksheetById( this.sheetId );
//            if ( ws )
//                this.cell = ws._getCellNoEmpty( this.bbox.r1, this.bbox.c1 );
//        }
//        return this.cell;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1604
    },
1605

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1606
    getAscCDefName:function () {
1607 1608 1609 1610
        var a = this.wb.getWorksheetById( this.sheetId );
        return new Asc.asc_CDefName( this.Name,
            this.Ref,
            this.sheetId == "WB" ? null : a ? a.getIndex() : null,
1611
            this.isTable, this.Hidden, this.isLock );
1612 1613
    },

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1614
    changeDefName:function ( newName ) {
1615 1616 1617
        this.cellId = newName.Name.toLowerCase();
        this.Ref = newName.Ref;
        this.Name = newName.Name;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1618
        this.nodeId = getDefNameVertexId( this.sheetId, newName.Name );
1619 1620
    },

1621
    relinkRef:function(oName, nName){
1622
        if( this.parsedRef && this.parsedRef.isParsed ){
1623 1624
            this.Ref = this.parsedRef.assemble();
        }
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664
    },

    renameDefNameToCollaborate:function(name){
        var lastname = this.Name;
        //из-за особенностей реализации формул, сначала делаем parse со старым именем, потом преименовываем, потом assemble
        var aFormulas = [];
        //переименование для отправки изменений
        for(var i = 0, length = this.wb.aCollaborativeActions.length; i < length; ++i)
        {
            var aPointActions = this.wb.aCollaborativeActions[i];
            for (var j = 0, length2 = aPointActions.length; j < length2; ++j) {
                var action = aPointActions[j];
                if (g_oUndoRedoWorkbook == action.oClass) {
                    if (historyitem_Workbook_DefinedNamesAdd == action.nActionType) {
                        if (lastname == action.oData.newName.Name)
                            action.oData.newName.Name = name;
                    }
                }
                else if (g_oUndoRedoCell == action.oClass) {
                    if (action.oData instanceof UndoRedoData_CellSimpleData) {
                        if (action.oData.oNewVal instanceof UndoRedoData_CellValueData) {
                            var oNewVal = action.oData.oNewVal;
                            if (null != oNewVal.formula && -1 != oNewVal.formula.indexOf(lastname)) {
                                var oParser = new parserFormula(oNewVal.formula, "A1", this.wb.getWorksheet(0));
                                oParser.parse();
                                aFormulas.push({ formula: oParser, value: oNewVal });
                            }
                        }
                    }
                }
            }
        }
        var clone = this.clone();
        clone.Name = name;
        this.wb.editDefinesNames( this.getAscCDefName(), clone.getAscCDefName() );
        for(var i = 0, length = aFormulas.length; i < length; ++i)
        {
            var item = aFormulas[i];
            item.value.formula = item.formula.assemble();
        }
1665 1666 1667 1668 1669 1670 1671 1672
    },

    rebuild:function(){
        if(this.Ref){
            this.parsedRef = new parserFormula(this.Ref, "", this.wb.getWorksheet(0));
            this.parsedRef.parse();
            this.parsedRef.buildDependencies(null,this);
        }
1673
    }
1674 1675 1676

};

1677
function getVertexId(sheetId, cellId){
1678
	return sheetId + g_cCharDelimiter + cellId;
1679
}
1680
function getDefNameVertexId(scope, name){
1681
	return ( scope === null || scope === undefined ? "WB" : scope ) + g_cCharDelimiter + name.toLowerCase();
1682
}
1683
function lockDraw(wb){
1684
    lc++;
1685
	wb.isNeedCacheClean = false;
1686 1687 1688
    if( lc == 0 ){
        arrRecalc = {};
    }
1689 1690
}
function unLockDraw(wb){
1691
    lc>0?lc--:true;
1692 1693 1694 1695
	if( lc == 0 ){
        wb.isNeedCacheClean = true;
        arrRecalc = {};
    }
1696
}
1697
function addToArrRecalc(sheetId, cell){
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708
    var temp = arrRecalc[sheetId];
    if( !temp )
    {
        temp = [];
        arrRecalc[sheetId] = temp;
    }
    temp.push(cell);
}
function addToArrDefNameRecalc(name){
    arrDefNameRecalc[name.nodeId] = name;
}
1709
function buildRecalc(_wb,notrec, bForce){
1710
	var ws;
1711
    if( lc > 1 && !bForce) return;
1712 1713 1714 1715 1716 1717
    if(!bForce){
        for(var id in arrDefNameRecalc ){
            arrDefNameRecalc[id].rebuild();
        }
        arrDefNameRecalc = {};
    }
1718
	for( var id in arrRecalc ){
1719
		ws = _wb.getWorksheetById(id);
1720
		if (ws) {
1721 1722 1723 1724
			var temp = arrRecalc[id];
			var _rec = {};
			for(var i = 0, length = temp.length; i < length; ++i)
			{
1725 1726
				var cell = temp[i];
				var cellId = g_oCellAddressUtils.getCellId(cell.nRow, cell.nCol);
1727 1728 1729
				_rec[cellId] = cellId;
				_wb.needRecalc.nodes[getVertexId(id, cellId)] = [id, cellId ];
				_wb.needRecalc.length++;
1730 1731 1732
            }
            ws._BuildDependencies(_rec);
        }
1733
	}
1734

1735
    if(!notrec)
1736
	    sortDependency(_wb)
1737 1738
}

1739
function sortDependency( wb, setCellFormat ) {
1740 1741 1742 1743
	if ( wb.isNeedCacheClean ){
		buildRecalc(wb, true);
		arrRecalc = {};
	}
1744
    var i;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1745
    var nR = wb.needRecalc;
1746
	if(nR && (nR.length > 0))
1747
	{
1748 1749
	    var oCleanCellCacheArea = {};
	    var oNodeDependence = wb.dependencyFormulas.getNodeDependence(nR.nodes);
1750 1751 1752
        for (i in oNodeDependence.oMasterNodes)
            _sortDependency(wb, oNodeDependence.oMasterNodes[i], oNodeDependence, oNodeDependence.oMasterAreaNodes,
                false, oCleanCellCacheArea, setCellFormat);
1753 1754 1755 1756 1757
	    //те AreaNodes 
        var oCurMasterAreaNodes = oNodeDependence.oMasterAreaNodes;
        while (true) {
            var bEmpty = true;
            var oNewMasterAreaNodes = {};
1758
            for (i in oCurMasterAreaNodes) {
1759
                bEmpty = false;
1760 1761
                _sortDependency(wb, oCurMasterAreaNodes[i], oNodeDependence, oNewMasterAreaNodes, false,
                    oCleanCellCacheArea, setCellFormat);
1762 1763 1764 1765 1766
            }
            oCurMasterAreaNodes = oNewMasterAreaNodes;
            if (bEmpty) {
                //все оставшиеся считаем как bad
                //todo сделать как в Excel, которой определяет циклические ссылки на момент подсчета(пример A1=VLOOKUP(1,B1:D2,2),B2 = 1, D1=A1 - это не циклическая ссылка)
1767 1768 1769
                for (i in oNodeDependence.oMasterAreaNodesRestricted) {
                    _sortDependency(wb, oNodeDependence.oMasterAreaNodesRestricted[i].node, oNodeDependence, null,
                        true, oCleanCellCacheArea, setCellFormat);
1770 1771 1772
                }
                break;
            }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1773
        }
1774 1775 1776
        for (i in oCleanCellCacheArea)
            wb.handlers.trigger("cleanCellCache", i, oCleanCellCacheArea[i], c_oAscCanChangeColWidth.numbers);

1777
		g_oVLOOKUPCache.clean();
1778
        g_oHLOOKUPCache.clean();
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1779
    }
1780
	wb.needRecalc = {nodes: {}, length:0};
1781
}
1782
function _sortDependency(wb, node, oNodeDependence, oNewMasterAreaNodes, bBad, oCleanCellCacheArea, setCellFormat) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1783
    if ( node ) {
1784
        var oWeightMapElem = oNodeDependence.oWeightMap[node.nodeId];
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1785 1786
        if ( oWeightMapElem ) {
            oWeightMapElem.cur++;
1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
            if (oWeightMapElem.cur == oWeightMapElem.max && !oWeightMapElem.gray) {
				if(null != oNewMasterAreaNodes){
					var oNodeToAreaElement = oNodeDependence.oNodeToArea[node.nodeId];
					if (oNodeToAreaElement) {
						for (var i = 0, length = oNodeToAreaElement.length; i < length; ++i) {
							var elem = oNodeToAreaElement[i];
							elem.cur++;
							if (elem.cur == elem.max) {
								oNewMasterAreaNodes[elem.node.nodeId] = elem.node;
								delete oNodeDependence.oMasterAreaNodesRestricted[elem.node.nodeId];
							}
						}
					}
				}
                var bCurBad = oWeightMapElem.bad || bBad;
1802 1803
				if(node.isDefinedName){
					//todo
1804
                    //Обрабатываем тут все, что было сделано с именованной ссылкой: переименована;
1805 1806 1807 1808 1809
                    //перемещен диапазон; сдвиг/удаление ячеек, приведшие к сдвигу ячеек; удаление именованного диапазона.
                    //
//                    var ws = wb.getWorksheetById( node.sheetId );
//                    ws._ReBuildFormulas
//                    ws._RecalculatedFunctions(node.cellId, bCurBad, setCellFormat);
1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
				}
				else{
					//пересчитываем функцию
					var ws = wb.getWorksheetById( node.sheetId );
					ws._RecalculatedFunctions(node.cellId, bCurBad, setCellFormat);
					//запоминаем области для удаления cache
					var sheetArea = oCleanCellCacheArea[node.sheetId];
					if ( null == sheetArea ) {
						sheetArea = {};
						oCleanCellCacheArea[node.sheetId] = sheetArea;
					}
					if(!node.isArea)
						sheetArea[node.cellId] = node.getBBox();
				}
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1824 1825 1826 1827 1828
                //обрабатываем child
                oWeightMapElem.gray = true;
                var oSlaveNodes = node.getSlaveEdges();
                if ( oSlaveNodes ) {
                    for ( var i in oSlaveNodes )
1829
                        _sortDependency(wb, oSlaveNodes[i], oNodeDependence, oNewMasterAreaNodes, bBad, oCleanCellCacheArea);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1830 1831 1832 1833 1834
                }
                oWeightMapElem.gray = false;
            }
        }
    }
1835 1836
}

1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
function angleFormatToInterface(val)
{
	var nRes = 0;
	if(0 <= val && val <= 180)
		nRes = val <= 90 ? val : 90 - val;
	return nRes;
}
function angleFormatToInterface2(val)
{
	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;
	}
	else if(g_nVerticalTextAngle != val)
		nRes = 0;
	return nRes;
}
1863 1864
//-------------------------------------------------------------------------------------------------
$(function(){
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1865
	aStandartNumFormats = [];
1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883
	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";
1884
	aStandartNumFormats[22] = "m/d/yyyy h:mm";
1885 1886 1887 1888 1889 1890 1891 1892 1893
	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] = "@";
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1894
	aStandartNumFormatsId = {};
1895 1896 1897 1898 1899 1900 1901 1902 1903
	for(var i in aStandartNumFormats)
	{
		aStandartNumFormatsId[aStandartNumFormats[i]] = i - 0;
	}
});
//-------------------------------------------------------------------------------------------------
/**
 * @constructor
 */
1904
function Workbook(eventsHandlers, oApi){
1905 1906
	this.oApi = oApi;
	this.handlers = eventsHandlers;
1907
	this.needRecalc = {nodes: {}, length:0};
1908 1909
	this.dependencyFormulas = new DependencyGraph(this);
	this.nActive = 0;
Dmitry.Vikulov's avatar
minor  
Dmitry.Vikulov committed
1910
	
1911 1912
	this.theme = null;
	this.clrSchemeMap = null;
1913
	
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1914 1915
	this.DefinedNames = {};
	this.oRealDefinedNames = {};
1916
//	this.oNameGenerator = new NameGenerator(this);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1917
	this.CellStyles = new CCellStyles();
1918
	this.TableStyles = new Asc.CTableStyles();
1919
	this.oStyleManager = new StyleManager();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1920
	this.calcChain = [];
1921 1922
	this.aComments = [];	// Комментарии к документу
	this.aCommentsCoords = [];
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1923
	this.aWorksheets = [];
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1924
	this.aWorksheetsById = {};
1925 1926 1927
	this.cwf = {};
	this.isNeedCacheClean = true;
	this.startActionOn = false;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1928
	this.aCollaborativeActions = [];
1929
	this.bCollaborativeChanges = false;
1930 1931
	this.bUndoChanges = false;
	this.bRedoChanges = false;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1932
	this.aCollaborativeChangeElements = [];
1933 1934
	
	this.wsHandlers = null;
1935
}
1936
Workbook.prototype.init=function(bNoBuildDep){
1937 1938 1939 1940
	if(this.nActive < 0)
		this.nActive = 0;
	if(this.nActive >= this.aWorksheets.length)
		this.nActive = this.aWorksheets.length - 1;
1941 1942
	
	var self = this;
1943
	
1944 1945 1946 1947 1948
	this.wsHandlers = new asc.asc_CHandlersList(/*handlers*/{
		"changeRefTablePart"    : function (displayName, ref) {
			self.dependencyFormulas.changeTableName( displayName, null, ref );
		}
	});
1949
	
1950 1951 1952 1953
    //charts
    for(var i = 0, length = this.aWorksheets.length; i < length; ++i)
    {
        var ws = this.aWorksheets[i];
1954
        ws.initPostOpen(this.wsHandlers);
1955
    }
1956 1957 1958 1959 1960 1961 1962 1963 1964
	if(!bNoBuildDep){
		/*
			buildDependency необходимо запускать для построения графа зависимостей между ячейками.
			Сортировка графа производится при необходимости пересчета формул: 
				при открытии документа если есть ячейки помеченные как пересчитываемые или есть ячейки без значения.
		*/
		this.buildDependency();
		sortDependency(this);
	}
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
1965

1966 1967
};
Workbook.prototype.rebuildColors=function(){
1968 1969
	g_oColorManager.rebuildColors();
	for(var i = 0 , length = this.aWorksheets.length; i < length; ++i)
1970
		this.aWorksheets[i].rebuildColors();
1971
};
1972 1973 1974
Workbook.prototype.getDefaultFont=function(){
	return g_oDefaultFont.fn;
};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1975
Workbook.prototype.getDefaultSize=function(){
1976 1977 1978 1979 1980
	return g_oDefaultFont.fs;
};
Workbook.prototype.getActive=function(){
	return this.nActive;
};
1981 1982 1983
Workbook.prototype.getActiveWs = function () {
    return this.getWorksheet(this.nActive);
};
1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
Workbook.prototype.setActive=function(index){
	if(index >= 0 && index < this.aWorksheets.length){
		this.nActive = index;
		return true;
	}
	return false;
};
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];
		}
	return null;
};
Workbook.prototype.getWorksheetIndexByName=function(name){
	for(var i = 0; i < this.aWorksheets.length; i++)
		if(this.aWorksheets[i].getName() == name){
			return i;
		}
	return null;
};
Workbook.prototype.getWorksheetCount=function(){
	return this.aWorksheets.length;
};
Workbook.prototype.createWorksheet=function(indexBefore, sName, sId){
2019
	History.Create_NewPoint();
2020
	History.TurnOff();
2021
	var wsActive = this.getActiveWs();
2022
    var oNewWorksheet = new Woorksheet(this, this.aWorksheets.length, sId);
2023 2024
	if (this.checkValidSheetName(sName))
		oNewWorksheet.sName = sName;
2025
	oNewWorksheet.initPostOpen(this.wsHandlers);
2026
	if(null != indexBefore && indexBefore >= 0 && indexBefore < this.aWorksheets.length)
2027 2028 2029 2030 2031 2032 2033
		this.aWorksheets.splice(indexBefore, 0, oNewWorksheet);
	else
	{
		indexBefore = this.aWorksheets.length;
		this.aWorksheets.push(oNewWorksheet);
	}
	this.aWorksheetsById[oNewWorksheet.getId()] = oNewWorksheet;
2034
	this._updateWorksheetIndexes(wsActive);
2035
	History.TurnOn();
2036
	this._insertWorksheetFormula(oNewWorksheet.index);
2037
	History.Add(g_oUndoRedoWorkbook, historyitem_Workbook_SheetAdd, null, null, new UndoRedoData_SheetAdd(indexBefore, oNewWorksheet.getName(), null, oNewWorksheet.getId()));
2038 2039
	History.SetSheetUndo(wsActive.getId());
	History.SetSheetRedo(oNewWorksheet.getId());
2040 2041
	return oNewWorksheet.index;
};
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
2042
Workbook.prototype.copyWorksheet=function(index, insertBefore, sName, sId, bFromRedo){
2043 2044
	//insertBefore - optional
	if(index >= 0 && index < this.aWorksheets.length){
2045
		History.Create_NewPoint();
2046
		History.TurnOff();
2047
		var wsActive = this.getActiveWs();
2048
		var wsFrom = this.aWorksheets[index];
2049
		var newSheet = wsFrom.clone(sId, sName);
2050
		newSheet.initPostOpen(this.wsHandlers);
2051 2052 2053 2054 2055 2056 2057 2058 2059
		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;
2060
		this._updateWorksheetIndexes(wsActive);
2061 2062
		History.TurnOn();
		this._insertWorksheetFormula(insertBefore);
2063 2064 2065

        this.dependencyFormulas.copyDefNameByWorksheet( wsFrom.getId(), newSheet.getId() );

2066 2067
		//для формул. создаем копию this.cwf[this.Id] для нового листа.
		if ( this.cwf[wsFrom.getId()] ){
2068 2069 2070 2071 2072 2073 2074 2075
			var cwf = { cells:{} };
			var newSheetId = newSheet.getId();
			var cwfFrom = this.cwf[wsFrom.getId()];
			this.cwf[newSheetId] = cwf;
			for( var id in cwfFrom.cells ){
				cwf.cells[id] = cwfFrom.cells[id];
				this.needRecalc.nodes[getVertexId(newSheetId, id)] = [newSheetId, id];
				this.needRecalc.length++;
2076
			}
2077
			newSheet._BuildDependencies(cwf.cells);
2078
		}
2079

2080
		sortDependency(this);
2081
		History.Add(g_oUndoRedoWorkbook, historyitem_Workbook_SheetAdd, null, null, new UndoRedoData_SheetAdd(insertBefore, newSheet.getName(), wsFrom.getId(), newSheet.getId()));
2082 2083
		History.SetSheetUndo(wsActive.getId());
		History.SetSheetRedo(newSheet.getId());
2084 2085
        if(!(bFromRedo === true))
        {
2086
            wsFrom.copyDrawingObjects(newSheet, wsFrom);
2087
        }
2088 2089
	}
};
2090 2091
Workbook.prototype.insertWorksheet = function (index, sheet, cwf) {
    var wsActive = this.getActiveWs();
2092 2093 2094 2095 2096 2097 2098 2099 2100
	if(null != index && index >= 0 && index < this.aWorksheets.length){
		//помещаем новый sheet перед insertBefore
		this.aWorksheets.splice(index, 0, sheet);
	}
	else{
		//помещаем новый sheet в конец
		this.aWorksheets.push(sheet);
	}
	this.aWorksheetsById[sheet.getId()] = sheet;
2101
	this._updateWorksheetIndexes(wsActive);
2102
	this._insertWorksheetFormula(index);
2103 2104
	//восстанавливаем список ячеек с формулами для sheet
	this.cwf[sheet.getId()] = cwf;
2105 2106
	sheet._BuildDependencies(cwf.cells);
	sortDependency(this);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2107
};
2108 2109 2110 2111 2112 2113 2114 2115 2116 2117
Workbook.prototype._insertWorksheetFormula=function(index){
	if( index > 0 && index < this.aWorksheets.length - 1 ){
		var oWsTo = this.aWorksheets[index - 1];
		var nodesSheetTo = this.dependencyFormulas.getNodeBySheetId(oWsTo.getId());
		for( var i = 0; i < nodesSheetTo.length; i++ ){
			var se = nodesSheetTo[i].getSlaveEdges();
			if(se)
			{
				for( var id in se ){
					var slave = se[id];
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
2118 2119 2120
                    if(slave.isDefinedName){
                        continue;
                    }
2121 2122 2123 2124 2125 2126 2127 2128 2129 2130
					var cell = slave.returnCell();
					if( cell && cell.formulaParsed && cell.formulaParsed.is3D )
					{
						if(cell.formulaParsed.insertSheet(index))
							slave.setFormula(null, false, true);
					}
				}
			}
		}
	}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2131
};
2132 2133 2134
Workbook.prototype.replaceWorksheet=function(indexFrom, indexTo){
	if(indexFrom >= 0 && indexFrom < this.aWorksheets.length &&
		indexTo >= 0 && indexTo < this.aWorksheets.length){
2135
		History.Create_NewPoint();
2136
		History.TurnOff();
2137
		var wsActive = this.getActiveWs();
2138
		var oWsFrom = this.aWorksheets[indexFrom];
2139 2140
		var oWsTo = this.aWorksheets[indexTo];
		var tempW = {
2141
					wFN: oWsFrom.getName(),
2142
					wFI: indexFrom,
2143
					wFId: oWsFrom.getId(),
2144 2145 2146
					wTN: oWsTo.getName(),
					wTI: indexTo,
					wTId: oWsTo.getId()
2147
				};
2148 2149 2150
		//переводим обратно в индекс sheet перед которым надо вставить
		if(tempW.wFI < tempW.wTI)
			tempW.wTI++;
2151 2152 2153 2154 2155 2156
		/*
			Формулы:
				перестройка графа для трехмерных формул вида Sheet1:Sheet3!A1:A3, Sheet1:Sheet3!A1.
				пересчет трехмерных формул, перестройка формул при изменении положения листа: Sheet1, Sheet2, Sheet3, Sheet4 - Sheet1:Sheet4!A1 -> Sheet4, Sheet1, Sheet2, Sheet3 - Sheet1:Sheet3!A1;
		*/
		lockDraw(this);
2157
		var a = this.dependencyFormulas.getNodeBySheetId(tempW.wFId);
2158 2159 2160 2161
		for(var i=0;i<a.length;i++){
			var se = a[i].getSlaveEdges();
			if(se){
				for(var id in se){
2162
					var slave = se[id];
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
2163
                    if( slave.isDefinedName ) continue;
2164 2165 2166 2167 2168 2169 2170 2171
					var cell = slave.returnCell();
					if( cell && cell.formulaParsed && cell.formulaParsed.is3D )
					{
						var nMoveRes = cell.formulaParsed.moveSheet(tempW, true);
						if(2 == nMoveRes)
							slave.setFormula(cell.formulaParsed.assemble(), true, true);
						else if(1 == nMoveRes)
							slave.setFormula(null, false, true);
2172 2173 2174 2175 2176
					}
				}
			}
		}
		History.TurnOn();
2177
		var movedSheet = this.aWorksheets.splice(indexFrom, 1);
2178
		this.aWorksheets.splice(indexTo, 0, movedSheet[0]);
2179
		this._updateWorksheetIndexes(wsActive);
2180 2181 2182
		
		this._insertWorksheetFormula(tempW.wTI);
		
2183
		History.Add(g_oUndoRedoWorkbook, historyitem_Workbook_SheetMove, null, null, new UndoRedoData_FromTo(indexFrom, indexTo), true);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2184
		buildRecalc(this);
2185 2186 2187
		unLockDraw(this);
	}
};
2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208
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;
        }
    }
    // Не нашли справа, ищем слева от текущего
    if (!bFound) {
        for (i = nIndex - 1; i >= 0; --i) {
            ws = this.getWorksheet(i);
            if (false === ws.getHidden()) {
                oRes = ws;
                break;
            }
        }
    }
    return oRes;
2209
};
2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223
Workbook.prototype.removeWorksheet=function(nIndex, outputParams){
	//проверяем останется ли хоть один нескрытый sheet
	var bEmpty = true;
	for(var i = 0, length = this.aWorksheets.length; i < length; ++i)
	{
		var worksheet = this.aWorksheets[i];
		if(false == worksheet.getHidden() && i != nIndex)
		{
			bEmpty = false;
			break;
		}
	}
	if(bEmpty)
		return -1;
2224

2225 2226
	var removedSheet = this.getWorksheet(nIndex);
	if(removedSheet)
2227
	{
2228
		History.Create_NewPoint();
2229
		var removedSheetId = removedSheet.getId();
2230
		lockDraw(this);
2231
        var retRes = this.dependencyFormulas.removeDefNameBySheet( removedSheetId ), nSE, se, seUndoRedo = [];
2232 2233 2234
		var a = this.dependencyFormulas.getNodeBySheetId(removedSheetId);
		for(var i = 0; i < a.length; i++)
		{
2235 2236
			var node = a[i];
			var se = node.getSlaveEdges();
2237 2238
			if(se){
				for(var id in se){
2239
					var slave = se[id];
2240 2241 2242 2243
					var cell = slave.returnCell();
					if( cell && cell.formulaParsed && cell.formulaParsed.is3D )
					{
						if(cell.formulaParsed.removeSheet(removedSheetId))
2244
							slave.setFormula(cell.formulaParsed.assemble(true), true, true);
2245
					}
2246 2247 2248
				}
			}
		}
2249

2250
	    //по всем удаленным листам пробегаемся и удаляем из workbook.cwf (cwf - cells with forluma) элементы с названием соответствующего листа.
2251 2252 2253
		this.dependencyFormulas.removeNodeBySheetId(removedSheetId);
		var _cwf = this.cwf[removedSheetId];
		delete this.cwf[removedSheetId];
2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286

        if ( retRes ) {
            /*
             * #1. поменяли название - перестроили формулу. нужно вызвать пересборку формул в ячейках, в которыйх есть эта именованная ссылка.
             *  для этого пробегаемся по всем slave, и вызываем пересборку. в результате должна получиться новая формула, где используется новый диапазон.
             * #2. поменяли диапазон. нужно перестроить граф зависимосте и пересчитать формулу. находим диапазон; меняем в нем ссылку; разбираем ссылку;
             *  удаляем старые master и добавляем новые, которые получились в результате разбора новой ссылки; пересчитываем формулу.
             * */

            for( var defNameID in retRes ){
                nSE = retRes[defNameID].getSlaveEdges();
                retRes[defNameID].deleteAllMasterEdges();

                for ( var id in nSE ) {
//                    seUndoRedo.push( id );
                    se = nSE[id];
                    se.deleteMasterEdge( retRes[defNameID] );

                    this.needRecalc.nodes[se.nodeId] = [se.sheetId, se.cellId ];
                    this.needRecalc.length++;

                    se = se.returnCell();
                    se ? function () {
                        se.setFormula( se.formulaParsed.assemble() );
                        se.formulaParsed.isParsed = false;
                        se.formulaParsed.parse();
                        se.formulaParsed.buildDependencies();
                    }() : null;

                }
            }
        }

2287 2288 2289 2290 2291 2292 2293 2294
		var wsActive = this.getActiveWs();
		var oVisibleWs = null;
		this.aWorksheets.splice(nIndex, 1);
		delete this.aWorksheetsById[removedSheetId];
		if (nIndex == this.getActive()) {
		    oVisibleWs = this.findSheetNoHidden(nIndex);
		    if (null != oVisibleWs)
		        wsActive = oVisibleWs;
2295
		}
2296

2297
		History.Add(g_oUndoRedoWorkbook, historyitem_Workbook_SheetRemove, null, null, new UndoRedoData_SheetRemove(nIndex, removedSheetId, removedSheet, _cwf));
2298 2299 2300 2301
		if (null != oVisibleWs) {
		    History.SetSheetUndo(removedSheetId);
		    History.SetSheetRedo(wsActive.getId());
		}
2302 2303
		if(null != outputParams)
		{
2304
			outputParams.sheet = removedSheet;
2305 2306
			outputParams.cwf = _cwf;
		}
2307
		this._updateWorksheetIndexes(wsActive);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2308
		buildRecalc(this);
2309
		unLockDraw(this);
2310
		return wsActive.getIndex();
2311 2312 2313
	}
	return -1;
};
2314
Workbook.prototype._updateWorksheetIndexes = function (wsActive) {
2315 2316
	for(var i = 0, length = this.aWorksheets.length; i < length; ++i)
		this.aWorksheets[i]._setIndex(i);
2317 2318
	if (null != wsActive)
	    this.setActive(wsActive.getIndex());
2319 2320 2321 2322 2323 2324 2325 2326
};
Workbook.prototype.checkUniqueSheetName=function(name){
	var workbookSheetCount = this.getWorksheetCount();
	for (var i = 0; i < workbookSheetCount; i++){
		if (this.getWorksheet(i).getName() == name)
			return i;
	}
	return -1;
2327
};
2328
Workbook.prototype.checkValidSheetName=function(name){
2329
	return (name && name.length < g_nSheetNameMaxLength);
2330
};
2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 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
Workbook.prototype.getUniqueSheetNameFrom=function(name, bCopy){
	var nIndex = 1;
	var sNewName = "";
	var fGetPostfix = null;
	if(bCopy)
	{
		
		var result = /^(.*)\((\d)\)$/.exec(name);
		if(result)
		{
			fGetPostfix = function(nIndex){return "(" + nIndex +")";};
			name = result[1];
		}
		else
		{
			fGetPostfix = function(nIndex){return " (" + nIndex +")";};
			name = name;
		}
	}
	else
	{
		fGetPostfix = function(nIndex){return nIndex.toString();};
	}
	var workbookSheetCount = this.getWorksheetCount();
	while(nIndex < 10000)
	{
		var sPosfix = fGetPostfix(nIndex);
		sNewName = name + sPosfix;
		if(sNewName.length > g_nSheetNameMaxLength)
		{
			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)
			{
				bUniqueName = false;
				break;
			}
		}
		if(bUniqueName)
			break;
		nIndex++;
	}
	return sNewName;
2377 2378 2379 2380 2381
};
Workbook.prototype._generateFontMap=function(){
	var oFontMap = {
		"Arial"		: 1
	};
2382

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2383
	if(null != g_oDefaultFont.fn)
2384
		oFontMap[g_oDefaultFont.fn] = 1;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2385 2386
	
	for(var i = 0, length = this.aWorksheets.length; i < length; ++i)
2387
		this.aWorksheets[i].generateFontMap(oFontMap);
2388
	this.CellStyles.generateFontMap(oFontMap);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2389
	
2390 2391 2392 2393
	return oFontMap;
};
Workbook.prototype.generateFontMap=function(){
	var oFontMap = this._generateFontMap();
2394
	
2395
	var aRes = [];
2396 2397 2398 2399
	for(var i in oFontMap)
		aRes.push(i);
	return aRes;
};
2400 2401 2402 2403 2404 2405 2406 2407
Workbook.prototype.generateFontMap2=function(){
	var oFontMap = this._generateFontMap();

	var aRes = [];
	for(var i in oFontMap)
		aRes.push(new CFont(i, 0, "", 0));
	return aRes;
};
2408
Workbook.prototype.recalcWB = function(isRecalcWB){
2409
	//todo
2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
    if ( this.dependencyFormulas.getNodesLength() > 0 ) {
        var aNodes = isRecalcWB ? this.dependencyFormulas.getAll() : this.dependencyFormulas.getNodeBySheetIdAll(this.getWorksheet(this.getActive()).getId());
        var nR = this.needRecalc;
        for ( var i in aNodes ) {
            var node = aNodes[i];
            if ( !node.isArea ) {
                nR.nodes[node.nodeId] = [node.sheetId, node.cellId];
                nR.length++;
            }
        }
        sortDependency( this );
    }
2422
};
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2423 2424
Workbook.prototype.checkDefName = function ( checkName, scope ) {

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2425
    var rxTest = rx_defName.test( checkName ), res = new Asc.asc_CCheckDefName();
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2426
    if ( !rxTest ) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2427 2428 2429
        res.status = false;
        res.reason = c_oAscDefinedNameReason.WrongName;
        return res;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2430 2431 2432 2433 2434 2435 2436 2437
    }

    if( scope !== null ){
        scope = this.getWorksheet(scope).getId();
    }

    var defName = this.dependencyFormulas.getDefNameNode(getDefNameVertexId(scope, checkName));

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453
    if(defName){
        defName = defName.getAscCDefName();
        res.status = false;
        if(defName.isLock){
            res.reason = c_oAscDefinedNameReason.IsLocked;
        }
        else{
            res.reason = c_oAscDefinedNameReason.Existed;
        }
    }
    else{
        res.status = true;
        res.reason = c_oAscDefinedNameReason.OK;
    }

    return res;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2454

2455
};
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2456
Workbook.prototype.isDefinedNamesExists = function ( name, sheetId ) {
2457
    var n = name.toLowerCase();
2458
    return !!this.dependencyFormulas.defNameList[getDefNameVertexId(sheetId, n)];
2459
};
2460
Workbook.prototype.getDefinedNamesWB = function (defNameListId) {
2461
    var names = [], name, thas = this, activeWS;
2462 2463 2464 2465 2466 2467 2468 2469 2470

    /*c_oAscGetDefinedNamesList.
        Worksheet           :   0,
        WorksheetWorkbook   :   1,
        All*/

    function getNames(id,arr){
        var listDN = thas.dependencyFormulas.defNameSheets[id], name;
        for ( var id in listDN ) {
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
2471
            name = listDN[id]
2472

2473
            if ( name.Ref && !name.Hidden && name.Name.indexOf("_xlnm") < 0 ) {
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
2474
                if( name.isTable || name.parsedRef && name.parsedRef.isParsed && name.parsedRef.countRef == 1 && name.parsedRef.outStack.length == 1 && name.parsedRef.calculate().errorType !== cErrorType.bad_reference ){
Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
2475 2476
                    arr.push( name.getAscCDefName() );
                }
2477
            }
2478
        }
2479 2480
    }

2481 2482 2483 2484 2485
    function sort(a,b){
        if (a.Name > b.Name) return 1;
        if (a.Name < b.Name) return -1;
    }

2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500
    switch(defNameListId){
        case c_oAscGetDefinedNamesList.Worksheet:
        case c_oAscGetDefinedNamesList.WorksheetWorkbook:
            activeWS = this.getActiveWs();

            getNames(activeWS.getId(),names);

            if( c_oAscGetDefinedNamesList.WorksheetWorkbook ){
                getNames("WB",names);
            }
            break;
        case c_oAscGetDefinedNamesList.All:
        default:
            for ( var id in this.dependencyFormulas.defNameList ) {
                name = this.dependencyFormulas.defNameList[id].getAscCDefName()
2501
                if ( name.Ref && !name.Hidden && name.Name.indexOf("_xlnm") < 0 ) {
2502 2503 2504 2505 2506 2507
                    names.push( name );
                }
            }
            break;
    }

2508
    return names.sort(sort);
2509
};
2510
Workbook.prototype.getDefinesNames = function ( name, sheetId ) {
2511 2512 2513
    return this.dependencyFormulas.getDefNameNodeByName( name, sheetId );
};
Workbook.prototype.getDefinedName = function ( name ) {
2514 2515 2516
    var ws = this.getWorksheet( name.LocalSheetId ), sheetId = null;
    ws ? sheetId = ws.getId() : null;
    return this.dependencyFormulas.getDefNameNodeByName( name.Name, sheetId );
2517
};
2518
Workbook.prototype.delDefinesNames = function ( defName, bUndo ) {
2519
    History.Create_NewPoint();
2520
    var retRes = false;
2521

2522
    retRes = this.dependencyFormulas.removeDefName( defName.LocalSheetId, defName.Name );
2523

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2524
    if ( retRes ) {
2525 2526 2527 2528 2529 2530 2531
        /*
         * #1. поменяли название - перестроили формулу. нужно вызвать пересборку формул в ячейках, в которыйх есть эта именованная ссылка.
         *  для этого пробегаемся по всем slave, и вызываем пересборку. в результате должна получиться новая формула, где используется новый диапазон.
         * #2. поменяли диапазон. нужно перестроить граф зависимосте и пересчитать формулу. находим диапазон; меняем в нем ссылку; разбираем ссылку;
         *  удаляем старые master и добавляем новые, которые получились в результате разбора новой ссылки; пересчитываем формулу.
         * */

2532
        var nSE, se, seUndoRedo = [];
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2533
        nSE = retRes.getSlaveEdges();
2534

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2535
        retRes.deleteAllMasterEdges();
2536

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2537 2538 2539
        for ( var id in nSE ) {
            seUndoRedo.push( id );
            se = nSE[id];
2540
            addToArrRecalc(se.sheetId, se.cell);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2541 2542 2543
            this.needRecalc.nodes[se.nodeId] = [se.sheetId, se.cellId ];
            this.needRecalc.length++;
        }
2544

2545 2546 2547
        if(!bUndo)
            buildRecalc( this );

Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
2548
        History.Add( g_oUndoRedoWorkbook, historyitem_Workbook_DefinedNamesDelete, null, null, new UndoRedoData_DefinedNames( defName.Name, defName.Ref, defName.LocalSheetId, defName.isTable, seUndoRedo ) );
2549 2550 2551 2552
    }

    return retRes;

2553
};
2554
Workbook.prototype.editDefinesNames = function ( oldName, newName, bUndo ) {
2555

2556
    var newN = newName.Name.toLowerCase(), retRes = null, rename = false, nSE, se;
2557

2558
    if ( !rx_defName.test( newN ) ) {
2559 2560 2561
        return retRes;
    }

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2562
    if ( oldName ) {
2563 2564
        retRes = this.dependencyFormulas.changeDefName( oldName, newName );
        rename = true;
2565
    }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2566
    else {
2567
        retRes = this.dependencyFormulas.addDefinedNameNode( newName.Name, newName.LocalSheetId, newName.Ref, newName.Hidden, bUndo );
2568 2569
    }

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2570
    if ( retRes ) {
2571 2572

        History.Create_NewPoint();
2573

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2574 2575
        if ( rename ) {
            History.Add( g_oUndoRedoWorkbook, historyitem_Workbook_DefinedNamesChange, null, null, new UndoRedoData_DefinedNamesChange( oldName, newName ) );
2576
        }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2577 2578
        else {
            History.Add( g_oUndoRedoWorkbook, historyitem_Workbook_DefinedNamesAdd, null, null, new UndoRedoData_DefinedNamesChange( oldName, newName ) );
2579
        }
2580

2581 2582 2583 2584 2585 2586

        /*  #1. поменяли название - перестроили формулу. нужно вызвать пересборку формул в ячейках, в которыйх есть эта именованная ссылка.
           для этого пробегаемся по всем slave, и вызываем пересборку. в результате должна получиться новая формула, где используется новый диапазон.
          #2. поменяли диапазон. нужно перестроить граф зависимосте и пересчитать формулу. находим диапазон; меняем в нем ссылку; разбираем ссылку;
           удаляем старые master и добавляем новые, которые получились в результате разбора новой ссылки; пересчитываем формулу.*/

2587

2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600
        if( !rename ){
            retRes = this.dependencyFormulas.getDefNameNodeByName(newName.Name)
        }

        if(retRes){
            nSE = retRes.getSlaveEdges();
        }

        for ( var id in nSE ) {
            se = nSE[id];
            se.deleteMasterEdge( retRes );
            this.needRecalc.nodes[se.nodeId] = [se.sheetId, se.cellId ];
            this.needRecalc.length++;
2601
            addToArrRecalc(se.sheetId, se.cell);
2602 2603 2604 2605
            se = se.returnCell();
            if ( se ) {
                se.setFormula( se.formulaParsed.assemble() );
                if ( !rename ) {
2606
                    se.formulaParsed.setFormula(se.sFormula);
2607
                }
2608
            }
2609
        }
2610
        /*if(retRes){
2611
            retRes = retRes.getAscCDefName();
2612
        }*/
2613
    }
2614 2615
    if(!bUndo)
        buildRecalc(this);
2616 2617
    return retRes;

2618
};
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2619 2620
Workbook.prototype.findDefinesNames = function ( ref, sheetId ) {
    return this.dependencyFormulas.getDefNameNodeByRef( ref, sheetId );
2621
};
2622 2623 2624 2625 2626 2627
Workbook.prototype.unlockDefName = function(){
    this.dependencyFormulas.unlockDefName();
};
Workbook.prototype.checkDefNameLock = function(){
    return this.dependencyFormulas.checkDefNameLock();
};
2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667
Workbook.prototype.getUniqueDefinedNameFrom=function(name, bCopy){
    var nIndex = 1,
        dnNewName = "",
        fGetPostfix = null,
        name = name.Name,
        sheetId = name.sheetId;
    if(bCopy)
    {

        var result = /^(.*)(\d)$/.exec(name);
        if(result)
        {
            fGetPostfix = function(nIndex){return "" + nIndex;};
            name = result[1];
        }
        else
        {
            fGetPostfix = function(nIndex){return "_" + nIndex;};
            name = name;
        }
    }
    else
    {
        fGetPostfix = function(nIndex){return nIndex.toString();};
    }
    while(nIndex < 10000)
    {
        var sPosfix = fGetPostfix(nIndex);
        dnNewName = name + sPosfix;
        var bUniqueName = false;
        if(!this.isDefinedNamesExists( dnNewName, sheetId )){
            bUniqueName = true;
            break;
        }
        if(bUniqueName)
            break;
        nIndex++;
    }
    return dnNewName;
};
2668 2669
Workbook.prototype.buildDependency = function(){
	this.dependencyFormulas.clear();
2670 2671
//	this.dependencyFormulas = null;
//	this.dependencyFormulas = new DependencyGraph(this);
2672 2673 2674
	for(var i in this.cwf){
		this.getWorksheetById(i)._BuildDependencies(this.cwf[i].cells);
	}
2675
};
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2676 2677 2678 2679 2680 2681
Workbook.prototype.recalcDependency = function(f,bad,notRecalc){
    if(f.length > 0){

        var sr = {};

        for(var i = 0; i < f.length; i++){
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2682 2683
            var sheetID = f[i].sheetId, cellID = f[i].cellId, selectedSheet;
            if( cellID.indexOf(":") > -1 ) continue;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2684

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2685 2686
            var l = new CellAddress(cellID);
            var lRow = l.getRow(), lCol = l.getCol();
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2687

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2688 2689
            if( !(sheetID in sr) ){
                sr[sheetID] = {max:new CellAddress(cellID),min:new CellAddress(cellID)}
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2690 2691
            }

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2692 2693 2694 2695
            selectedSheet = sr[sheetID];

            if ( selectedSheet.min.getRow() > lRow )
                selectedSheet.min = new CellAddress( lRow, selectedSheet.min.getCol() );
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2696

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2697 2698
            if ( selectedSheet.min.getCol() > lCol )
                selectedSheet.min = new CellAddress( selectedSheet.min.getRow(), lCol );
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2699

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2700 2701
            if ( selectedSheet.max.getRow() < lRow )
                selectedSheet.max = new CellAddress( lRow, selectedSheet.max.getCol() );
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2702

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2703 2704
            if ( selectedSheet.max.getCol() < lCol )
                selectedSheet.max = new CellAddress( selectedSheet.max.getRow(), lCol );
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2705 2706

            if( !notRecalc )
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2707
                this.getWorksheetById( sheetID )._RecalculatedFunctions( cellID, bad );
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2708 2709 2710 2711
        }

        return sr;
    }
2712
};
2713 2714 2715 2716 2717 2718 2719 2720 2721
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));
    }
2722
};
2723
Workbook.prototype.SerializeHistory = function(){
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2724
	var aRes = [];
2725
	//соединяем изменения, которые были до приема данных с теми, что получились после.
2726

2727
    var worksheets = this.aWorksheets, t, j, length2;
2728
    for(t = 0; t < worksheets.length; ++t)
2729
    {
2730
        worksheets[t] && worksheets[t].refreshContentChanges();
2731
    }
2732 2733 2734 2735
	var aActions = this.aCollaborativeActions.concat(History.GetSerializeArray());
	if(aActions.length > 0)
	{
		var oMemory = new CMemory();
2736
		var bChangeSheetPlace = false;
2737 2738
		for(var i = 0, length = aActions.length; i < length; ++i)
		{
2739
		    var aPointChanges = aActions[i];
2740
		    bChangeSheetPlace = false;
2741
		    for (j = 0, length2 = aPointChanges.length; j < length2; ++j) {
2742 2743
		        var item = aPointChanges[j];
		        if (g_oUndoRedoWorkbook == item.oClass) {
2744
		            if (historyitem_Workbook_SheetAdd == item.nActionType || historyitem_Workbook_SheetRemove == item.nActionType || historyitem_Workbook_SheetMove == item.nActionType)
2745 2746
		                bChangeSheetPlace = true;
		        }
2747 2748 2749
		        else if (g_oUndoRedoWorksheet === item.oClass && historyitem_Worksheet_Hide === item.nActionType) {
		            bChangeSheetPlace = true;
		        }
2750
		        this._SerializeHistoryBase64(oMemory, item, aRes);
2751
		    }
2752
			var oUndoRedoData_SheetPositions;
2753 2754 2755 2756
		    if (bChangeSheetPlace) {
		        //создаем еще один элемент в undo/redo - взаимное расположение Sheet, чтобы не запутываться в add, move событиях
		        //добавляем не после конца aActions, чтобы можно было делать undo/redo и просто удалять хвост изменений.
		        var oSheetPlaceData = [];
2757
		        for (j = 0, length2 = this.aWorksheets.length; j < length2; ++j)
2758
		            oSheetPlaceData.push(this.aWorksheets[j].getId());
2759
		        oUndoRedoData_SheetPositions = new UndoRedoData_SheetPositions(oSheetPlaceData);
2760
		    }
2761 2762
			else
				oUndoRedoData_SheetPositions = new UndoRedoData_SheetPositions();
2763
			this._SerializeHistoryBase64(oMemory, new UndoRedoItemSerializable(g_oUndoRedoWorkbook, historyitem_Workbook_SheetPositions, null, null, oUndoRedoData_SheetPositions), aRes);
2764
		}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2765
		this.aCollaborativeActions = [];
2766 2767
	}
	return aRes;
2768
};
2769 2770 2771 2772 2773 2774 2775 2776 2777
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;
2778 2779
		var aIndexes = [], i, length = aChanges.length, sChange;
		for(i = 0; i < length; ++i)
2780
		{
2781 2782 2783 2784 2785 2786 2787
		    sChange = aChanges[i];
			var nIndex = sChange.indexOf(";");
			if (-1 != nIndex) {
				dstLen += parseInt(sChange.substring(0, nIndex));
				nIndex++;
			}
			aIndexes.push(nIndex);
2788 2789 2790 2791 2792 2793
		}
		var pointer = g_memory.Alloc(dstLen);
		var stream = new FT_Stream2(pointer.data, dstLen);
		stream.obj = pointer.obj;
		var nCurOffset = 0;
		//пробегаемся первый раз чтобы заполнить oFontMap
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2794
		var oFontMap = {};//собираем все шрифтры со всех изменений
2795
		var aUndoRedoElems = [];
2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806
		for (i = 0; i < length; ++i) {
		    sChange = aChanges[i];
			var oBinaryFileReader = new Asc.BinaryFileReader();
			nCurOffset = oBinaryFileReader.getbase64DecodedData2(sChange, aIndexes[i], stream, nCurOffset);
			var item = new UndoRedoItemSerializable();
			item.Deserialize(stream);
			if (g_oUndoRedoWorkbook == item.oClass && historyitem_Workbook_AddFont == item.nActionType) {
				for (var k = 0, length3 = item.oData.elem.length; k < length3; ++k)
					oFontMap[item.oData.elem[k]] = 1;
			}
			aUndoRedoElems.push(item);
2807
		}
2808

2809
		window["Asc"]["editor"]._loadFonts(oFontMap, function(){
2810 2811 2812 2813 2814
                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))
                    {
2815 2816 2817 2818
                        if ( wsViews[i].isChartAreaEditMode ) {
                            wsViews[i].isChartAreaEditMode = false;
                            wsViews[i].arrActiveChartsRanges = [];
                        }
2819 2820 2821 2822
                        wsViews[i].objectRender.controller.resetSelection();
                    }
                }
                History.Clear();
2823
				History.Create_NewPoint();
2824

2825 2826
				History.SetSelection(null);
				History.SetSelectionRedo(null);
2827
				var oRedoObjectParam = new Asc.RedoObjectParam();
2828
				History.UndoRedoPrepare(oRedoObjectParam, false);
2829
				for (var i = 0, length = aUndoRedoElems.length; i < length; ++i)
2830
				{
2831
				    var item = aUndoRedoElems[i];
2832
				    if ((null != item.oClass || (item.oData && typeof item.oData.sChangedObjectId === "string")) && null != item.nActionType) {
2833 2834 2835 2836
				        if (window["NATIVE_EDITOR_ENJINE"] === true && window["native"]["CheckNextChange"]) {
				            if (!window["native"]["CheckNextChange"]())
				                break;
				        }
2837 2838 2839
				        // 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);
2840
				    }
2841 2842
				}
			
2843
				History.UndoRedoEnd(null, oRedoObjectParam, false);
2844

2845
				oThis.bCollaborativeChanges = false;
2846 2847 2848 2849 2850
				History.Clear();
				if(null != fCallback)
					fCallback();
			});
	}
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
Workbook.prototype.DeserializeHistoryNative = function(oRedoObjectParam, data, isFull){
	if(null != data)
	{
		this.bCollaborativeChanges = true;
		
		if(null == oRedoObjectParam)
		{
			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))
				{
					if ( wsViews[i].isChartAreaEditMode ) {
						wsViews[i].isChartAreaEditMode = false;
						wsViews[i].arrActiveChartsRanges = [];
					}
					wsViews[i].objectRender.controller.resetSelection();
				}
			}
			
			History.Clear();
			History.Create_NewPoint();
			History.SetSelection(null);
			History.SetSelectionRedo(null);
			oRedoObjectParam = new Asc.RedoObjectParam();
			History.UndoRedoPrepare(oRedoObjectParam, false);
		}
		
		var stream = new FT_Stream2(data, data.length);
		stream.obj = null;
		// Применяем изменения, пока они есть
		var _count = stream.GetLong();
		var _pos = 4;
		for (var i = 0; i < _count; i++)
		{
			if (window["NATIVE_EDITOR_ENJINE"] === true && window["native"]["CheckNextChange"])
			{
				if (!window["native"]["CheckNextChange"]())
					break;
			}
			
2893
			var _len = stream.GetLong();
2894 2895 2896

			_pos += 4;
			stream.size = _pos + _len;
2897
            stream.Seek(_pos);
2898 2899 2900 2901
			stream.Seek2(_pos);
			
			var item = new UndoRedoItemSerializable();
			item.Deserialize(stream);
2902
			if ((null != item.oClass || (item.oData && typeof item.oData.sChangedObjectId === "string")) && null != item.nActionType)
2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917
				History.RedoAdd(oRedoObjectParam, item.oClass, item.nActionType, item.nSheetId, item.oRange, item.oData);

			_pos += _len;
			stream.Seek2(_pos);
			stream.size = data.length;
		}
				
		if(isFull){
			History.UndoRedoEnd(null, oRedoObjectParam, false);
			History.Clear();
			oRedoObjectParam = null;
		}
		this.bCollaborativeChanges = false;
	}
	return oRedoObjectParam;
2918
};
2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929
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)
			break;
    }
	return res;
};
2930 2931 2932 2933
//-------------------------------------------------------------------------------------------------
/**
 * @constructor
 */
2934
function Woorksheet(wb, _index, sId){
2935
	this.workbook = wb;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2936
	this.DefinedNames = {};
2937 2938
	this.sName = this.workbook.getUniqueSheetNameFrom(g_sNewSheetNamePattern, false);
	this.bHidden = false;
2939
	this.oSheetFormatPr = new SheetFormatPr();
2940
	this.index = _index;
2941
	this.Id = null != sId ? sId : g_oIdCounter.Get_NewId();
2942 2943
	this.nRowsCount = 0;
	this.nColsCount = 0;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2944
	this.aGCells = {};// 0 based
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2945 2946 2947
	this.aCols = [];// 0 based
	this.Drawings = [];
	this.TableParts = [];
2948
	this.AutoFilter = null;
2949
	this.oAllCol = null;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
2950 2951
	this.aComments = [];
	this.aCommentsCoords = [];
2952
	var oThis = this;
2953
	this.mergeManager = new RangeDataManager(function(data, from, to){
2954
		if(History.Is_On() && (null != from || null != to))
2955 2956 2957
		{
			if(null != from)
				from = from.clone();
2958
			if(null != to)
2959
				to = to.clone();
2960 2961 2962 2963
			var oHistoryRange = from;
			if(null == oHistoryRange)
				oHistoryRange = to;
			History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_ChangeMerge, oThis.getId(), oHistoryRange, new UndoRedoData_FromTo(new UndoRedoData_BBox(from), new UndoRedoData_BBox(to)));
2964
		}
2965 2966
		//расширяем границы
		if(null != to){
2967
			if(to.r2 >= oThis.nRowsCount)
2968
				oThis.nRowsCount = to.r2 + 1;
2969
			if(to.c2 >= oThis.nColsCount)
2970 2971
				oThis.nColsCount = to.c2 + 1;
		}
2972
	});
2973
	this.hyperlinkManager = new RangeDataManager(function(data, from, to, oChangeParam){
2974
		if(History.Is_On() && (null != from || null != to))
2975
		{
2976 2977
			if(null != from)
				from = from.clone();
2978
			if(null != to)
2979
				to = to.clone();
2980 2981 2982
			var oHistoryRange = from;
			if(null == oHistoryRange)
				oHistoryRange = to;
2983 2984 2985 2986
			var oHistoryData = null;
			if(null == from || null == to)
				oHistoryData = data.clone();
			History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_ChangeHyperlink, oThis.getId(), oHistoryRange, new UndoRedoData_FromToHyperlink(from, to, oHistoryData));
2987
		}
2988 2989 2990 2991
		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();
2992 2993
		//расширяем границы
		if(null != to){
2994
			if(to.r2 >= oThis.nRowsCount)
2995
				oThis.nRowsCount = to.r2 + 1;
2996
			if(to.c2 >= oThis.nColsCount)
2997 2998
				oThis.nColsCount = to.c2 + 1;
		}
2999 3000
	});
	this.hyperlinkManager.setDependenceManager(this.mergeManager);
3001
    this.DrawingDocument = new CDrawingDocument();
3002
	this.sheetViews = [];
3003
	this.aConditionalFormatting = [];
3004
	this.sheetPr = null;
3005
	this.aFormulaExt = null;
3006 3007

    this.oDrawingOjectsManager = new DrawingObjectsManager(this);
3008
    this.contentChanges = new CContentChanges();
3009 3010 3011
	
	/*handlers*/
	this.handlers = null;
3012
}
3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024

Woorksheet.prototype.addContentChanges = function(changes)
{
    this.contentChanges.Add(changes);
};

Woorksheet.prototype.refreshContentChanges = function()
{
    this.contentChanges.Refresh();
    this.contentChanges.Clear();
};

3025 3026 3027 3028
Woorksheet.prototype.rebuildColors=function(){
	this._forEachCell(function(cell){
		cell.cleanCache();
	});
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3029
  this.rebuildTabColor();
3030
};
3031
Woorksheet.prototype.generateFontMap=function(oFontMap){
3032 3033 3034 3035 3036 3037 3038
	//пробегаемся по Drawing
	for(var i = 0, length = this.Drawings.length; i < length; ++i)
	{
		var drawing = this.Drawings[i];
		if(drawing)
			drawing.getAllFonts(oFontMap);
	}
3039 3040
	if(null != this.workbook.theme)
		checkThemeFonts(oFontMap, this.workbook.theme.themeElements.fontScheme);
3041 3042 3043 3044 3045 3046 3047 3048
	//пробегаемся по колонкам
	for(var i in this.aCols)
	{
		var col = this.aCols[i];
		if(null != col && null != col.xfs && null != col.xfs.font && null != col.xfs.font.fn)
			oFontMap[col.xfs.font.fn] = 1;
	}
	if(null != this.oAllCol && null != this.oAllCol.xfs && null != this.oAllCol.xfs.font && null != this.oAllCol.xfs.font.fn)
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3049
		oFontMap[this.oAllCol.xfs.font.fn] = 1;
3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076
	//пробегаемся строкам
	for(var i in this.aGCells)
	{
		var row = this.aGCells[i];
		if(null != row && null != row.xfs && null != row.xfs.font && null != row.xfs.font.fn)
			oFontMap[row.xfs.font.fn] = 1;
		//пробегаемся по ячейкам
		for(var j in row.c)
		{
			var cell = row.c[j];
			if(null != cell)
			{
				if(null != cell.xfs && null != cell.xfs.font && null != cell.xfs.font.fn)
					oFontMap[cell.xfs.font.fn] = 1;
				//смотрим в комплексных строках
				if(null != cell.oValue && null != cell.oValue.multiText)
				{
					for(var k = 0, length3 = cell.oValue.multiText.length; k < length3; ++k)
					{
						var part = cell.oValue.multiText[k];
						if(null != part.format && null != part.format.fn)
							oFontMap[part.format.fn] = 1;
					}
				}
			}
		}
	}
3077
};
3078 3079 3080 3081
Woorksheet.prototype.clone=function(sNewId, sName){
	var i, elem, range;
	var oNewWs = new Woorksheet(this.workbook, this.workbook.aWorksheets.length, sNewId);
	oNewWs.sName = this.workbook.checkValidSheetName(sName) ? sName : this.workbook.getUniqueSheetNameFrom(this.sName, true);
3082
	oNewWs.bHidden = this.bHidden;
3083
	oNewWs.oSheetFormatPr = this.oSheetFormatPr.clone();
3084 3085 3086
	oNewWs.index = this.index;
	oNewWs.nRowsCount = this.nRowsCount;
	oNewWs.nColsCount = this.nColsCount;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3087
	for (i = 0; i < this.TableParts.length; ++i)
3088
		oNewWs.TableParts.push(this.TableParts[i].clone(oNewWs));
3089
	if(this.AutoFilter)
3090
		oNewWs.AutoFilter = this.AutoFilter.clone();
3091 3092 3093 3094 3095
	for (i in this.aCols) {
	    var col = this.aCols[i];
	    if(null != col)
	        oNewWs.aCols[i] = col.clone(oNewWs);
	}
3096
	if(null != this.oAllCol)
3097
		oNewWs.oAllCol = this.oAllCol.clone(oNewWs);
3098
	for(i in this.aGCells)
3099
		oNewWs.aGCells[i] = this.aGCells[i].clone(oNewWs);
3100
	var aMerged = this.mergeManager.getAll();
3101
	for(i in aMerged)
3102
	{
3103 3104
		elem = aMerged[i];
		range = oNewWs.getRange3(elem.bbox.r1, elem.bbox.c1, elem.bbox.r2, elem.bbox.c2);
3105 3106 3107
		range.mergeOpen();
	}
	var aHyperlinks = this.hyperlinkManager.getAll();
3108
	for(i in aHyperlinks)
3109
	{
3110 3111
		elem = aHyperlinks[i];
		range = oNewWs.getRange3(elem.bbox.r1, elem.bbox.c1, elem.bbox.r2, elem.bbox.c2);
3112 3113
		range.setHyperlinkOpen(elem.data);
	}
3114
	if(null != this.aComments) {
3115
		for (i = 0; i < this.aComments.length; i++) {
3116 3117 3118 3119 3120
			var comment = new asc_CCommentData(this.aComments[i]);
			comment.wsId = oNewWs.getId();
			comment.setId();
			oNewWs.aComments.push(comment);
		}
3121 3122 3123 3124 3125 3126 3127 3128 3129
	}
	for (i = 0; i < this.sheetViews.length; ++i) {
		oNewWs.sheetViews.push(this.sheetViews[i].clone());
	}
	for (i = 0; i < this.aConditionalFormatting.length; ++i) {
		oNewWs.aConditionalFormatting.push(this.aConditionalFormatting[i].clone(oNewWs));
	}
	if (this.sheetPr)
		oNewWs.sheetPr = this.sheetPr.clone();
3130

3131 3132
	return oNewWs;
};
3133
Woorksheet.prototype.copyDrawingObjects=function(oNewWs, wsFrom)
3134 3135
{
    if(null != this.Drawings && this.Drawings.length > 0)
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
3136
    {
3137
        var drawingObjects = new DrawingObjects();
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
3138
        oNewWs.Drawings = [];
3139
        NEW_WORKSHEET_DRAWING_DOCUMENT = oNewWs.DrawingDocument;
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
3140 3141
        for(var i = 0; i < this.Drawings.length; ++i)
        {
3142 3143 3144
            var drawingObject = drawingObjects.cloneDrawingObject(this.Drawings[i]);
            drawingObject.graphicObject = this.Drawings[i].graphicObject.copy();
            drawingObject.graphicObject.setWorksheet(oNewWs);
3145
            drawingObject.graphicObject.addToDrawingObjects();
3146 3147
            var drawingBase = this.Drawings[i];
            drawingObject.graphicObject.setDrawingBaseCoords(drawingBase.from.col, drawingBase.from.colOff, drawingBase.from.row, drawingBase.from.rowOff, drawingBase.to.col, drawingBase.to.colOff, drawingBase.to.row, drawingBase.to.rowOff);
3148
            oNewWs.Drawings[oNewWs.Drawings.length - 1] = drawingObject;
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
3149
        }
3150
        NEW_WORKSHEET_DRAWING_DOCUMENT = null;
3151
        drawingObjects.pushToAObjects(oNewWs.Drawings);
3152
        drawingObjects.updateChartReferences2(parserHelp.getEscapeSheetName(wsFrom.sName), parserHelp.getEscapeSheetName(oNewWs.sName));
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
3153
    }
3154
};
3155
Woorksheet.prototype.initPostOpen = function(handlers){
3156
	this.workbook.cwf[this.Id]={ cells:{} };
3157
	if(this.aFormulaExt){
3158
		var formulaShared = {};
3159 3160
		for(var i = 0; i < this.aFormulaExt.length; ++i){
			var elem = this.aFormulaExt[i];
3161
			var oCell = elem.cell;
3162
			var sCellId = g_oCellAddressUtils.getCellId(oCell.nRow, oCell.nCol);
3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175
			var oFormulaExt = elem.ext;
			if (oFormulaExt.t == Asc.ECellFormulaType.cellformulatypeShared) {
				if(null != oFormulaExt.si){
					if(null != oFormulaExt.ref){
						formulaShared[oFormulaExt.si] = 	{
																	fVal:new parserFormula(oFormulaExt.v,"",this),
																	fRef:function(t){
																			var r = t.getRange2(oFormulaExt.ref);
																			return {
																						c:r,
																						first:r.first
																					};
																		}(this)
3176
																};
3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189
							formulaShared[oFormulaExt.si].fVal.parse();
					}
					else{
						if( formulaShared[oFormulaExt.si] ){
							var fr = formulaShared[oFormulaExt.si].fRef;
							if( fr.c.containCell2(oCell) ){
								if( formulaShared[oFormulaExt.si].fVal.isParsed ){
									var off = oCell.getOffset3(fr.first);
									formulaShared[oFormulaExt.si].fVal.changeOffset(off);
									oFormulaExt.v = formulaShared[oFormulaExt.si].fVal.assemble();
									off.offsetCol *=-1;
									off.offsetRow *=-1;
									formulaShared[oFormulaExt.si].fVal.changeOffset(off);
3190
								}
3191
								this.workbook.cwf[this.Id].cells[sCellId] = sCellId;
3192 3193 3194 3195
							}
						}
					}
				}
3196 3197 3198
			}
			if(oFormulaExt.v)
				oCell.setFormula(oFormulaExt.v);
3199
				
3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214
			if(oFormulaExt.ca)
				oCell.sFormulaCA = true;
			
			/*
				Если ячейка содержит в себе формулу, то добавляем ее в список ячеек с формулами.
			*/
			if(oCell.sFormula){
				this.workbook.cwf[this.Id].cells[sCellId] = sCellId;
			}
			/*
				Строится список ячеек, которые необходимо пересчитать при открытии. Это ячейки имеющие атрибут f.ca или значение в которых неопределено.
			*/
			if(oCell.sFormula && (oFormulaExt.ca || !oCell.oValue.getValueWithoutFormat()) ){
				this.workbook.needRecalc.nodes[ getVertexId( this.Id, sCellId ) ] = [this.Id, sCellId];
				this.workbook.needRecalc.length++;
3215 3216
			}
		}
3217
		this.aFormulaExt = null;
3218
	}
3219
	
3220 3221 3222 3223
	if (!this.PagePrintOptions) {
		// Даже если не было, создадим
		this.PagePrintOptions = new Asc.asc_CPageOptions();
	}
3224
	this.PagePrintOptions.init();
3225 3226 3227 3228

	// Sheet Views
	if (0 === this.sheetViews.length) {
		// Даже если не было, создадим
3229
		this.sheetViews.push(new asc.asc_CSheetViewSettings());
3230
	}
3231
	
3232 3233
	this.handlers = handlers;
	this._setHandlersTablePart();
3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256
};
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);
				}
			}
		}
	}
};
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 : "";
};
3257
Woorksheet.prototype.setName=function(name, bFromUndoRedo){
3258 3259 3260
	if(name.length <= g_nSheetNameMaxLength)
	{
		var lastName = this.sName;
3261
		this.sName = name;
3262 3263 3264 3265 3266 3267
		History.Create_NewPoint();
		History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_Rename, this.getId(), null, new UndoRedoData_FromTo(lastName, name));

		//перестраиваем формулы, если у них были ссылки на лист со старым именем.
		for(var id in this.workbook.cwf) {
			this.workbook.getWorksheetById(id)._ReBuildFormulas(this.workbook.cwf[id].cells,lastName,this.sName);
3268
		}
3269

Dmitry.Shahtanov's avatar
fix:  
Dmitry.Shahtanov committed
3270
        this.workbook.dependencyFormulas.relinkDefNameByWorksheet(lastName, name);
3271

3272
        if(!bFromUndoRedo)
3273
        {
3274 3275 3276 3277 3278 3279 3280
            var _lastName = parserHelp.getEscapeSheetName(lastName);
            var _newName = parserHelp.getEscapeSheetName(this.sName);

            for (var key in this.workbook.aWorksheets)
            {
                var wsModel = this.workbook.aWorksheets[key];
                if ( wsModel )
3281
                    wsModel.oDrawingOjectsManager.updateChartReferencesWidthHistory(_lastName, _newName, true);
3282
            }
3283
        }
3284 3285
	}
};
3286
Woorksheet.prototype.getTabColor=function(){
3287
	return this.sheetPr && this.sheetPr.TabColor ? Asc.colorObjToAscColor(this.sheetPr.TabColor) : null;
3288 3289 3290 3291
};
Woorksheet.prototype.setTabColor=function(color){
	if (!this.sheetPr)
		this.sheetPr = new Asc.asc_CSheetPr();
3292 3293 3294 3295 3296

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

3297
	this.sheetPr.TabColor = color;
3298 3299
	if (!this.workbook.bUndoChanges && !this.workbook.bRedoChanges)
	    this.workbook.handlers.trigger("asc_onUpdateTabColor", this.getIndex());
3300
};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3301 3302 3303 3304 3305
Woorksheet.prototype.rebuildTabColor = function() {
  if (this.sheetPr && this.sheetPr.TabColor) {
    this.workbook.handlers.trigger("asc_onUpdateTabColor", this.getIndex());
  }
};
3306
Woorksheet.prototype.renameWsToCollaborate=function(name){
3307
    var lastname = this.getName();
3308
	//из-за особенностей реализации формул, сначала делаем parse со старым именем, потом преименовываем, потом assemble
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3309
	var aFormulas = [];
3310 3311 3312
	//переименование для отправки изменений
	for(var i = 0, length = this.workbook.aCollaborativeActions.length; i < length; ++i)
	{
3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341
	    var aPointActions = this.workbook.aCollaborativeActions[i];
	    for (var j = 0, length2 = aPointActions.length; j < length2; ++j) {
	        var action = aPointActions[j];
	        if (g_oUndoRedoWorkbook == action.oClass) {
	            if (historyitem_Workbook_SheetAdd == action.nActionType) {
	                if (lastname == action.oData.name)
	                    action.oData.name = name;
	            }
	        }
	        else if (g_oUndoRedoWorksheet == action.oClass) {
	            if (historyitem_Worksheet_Rename == action.nActionType) {
	                if (lastname == action.oData.to)
	                    action.oData.to = name;
	            }
	        }
	        else if (g_oUndoRedoCell == action.oClass) {
	            if (action.oData instanceof UndoRedoData_CellSimpleData) {
	                if (action.oData.oNewVal instanceof UndoRedoData_CellValueData) {
	                    var oNewVal = action.oData.oNewVal;
	                    if (null != oNewVal.formula && -1 != oNewVal.formula.indexOf(lastname)) {
	                        var oParser = new parserFormula(oNewVal.formula, "A1", this);
	                        oParser.parse();
	                        aFormulas.push({ formula: oParser, value: oNewVal });

	                    }
	                }
	            }
	        }
	    }
3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355
	}
	//переименование для локальной версии
	this.setName(name);
	for(var i = 0, length = aFormulas.length; i < length; ++i)
	{
		var item = aFormulas[i];
		item.value.formula = item.formula.assemble();
	}
};
Woorksheet.prototype.getHidden=function(){
	if(null != this.bHidden)
		return false != this.bHidden;
	return false;
};
3356 3357 3358 3359
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())
3360
	{
3361 3362 3363 3364 3365 3366 3367
	    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);
	    }
3368
	}
3369 3370 3371 3372 3373 3374 3375
	if (bOldHidden != hidden) {
	    History.Create_NewPoint();
	    History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_Hide, this.getId(), null, new UndoRedoData_FromTo(bOldHidden, hidden));
	    if (null != oVisibleWs) {
	        History.SetSheetUndo(wsActive.getId());
	        History.SetSheetRedo(oVisibleWs.getId());
	    }
3376 3377
	}
};
3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388
Woorksheet.prototype.getSheetViewSettings = function () {
	return this.sheetViews[0].clone();
};
Woorksheet.prototype.setSheetViewSettings = function (options) {
	var current = this.getSheetViewSettings();
	if (current.isEqual(options))
		return;

	History.Create_NewPoint();
	History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_SetViewSettings, this.getId(), null, new UndoRedoData_FromTo(current, options.clone()));

3389
	this.sheetViews[0].setSettings(options);
3390 3391
	if (!this.workbook.bUndoChanges && !this.workbook.bRedoChanges)
	    this.workbook.handlers.trigger("asc_onUpdateSheetViewSettings");
3392
};
3393
Woorksheet.prototype.getRowsCount=function(){
3394 3395 3396 3397 3398
	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;
3399 3400 3401 3402
};
Woorksheet.prototype.removeRows=function(start, stop){
	var oRange = this.getRange(new CellAddress(start, 0, 0), new CellAddress(stop, gc_nMaxCol0, 0));
	oRange.deleteCellsShiftUp();
3403
};
3404
Woorksheet.prototype._removeRows=function(start, stop){
3405 3406 3407 3408
	//до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc
	//чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся
	//например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows
	buildRecalc(this.workbook, true, true);
3409 3410 3411 3412
	lockDraw(this.workbook);
	History.Create_NewPoint();
	//start, stop 0 based
	var nDif = -(stop - start + 1);
3413 3414
    var oActualRange = {r1: start, c1: 0, r2: stop, c2: gc_nMaxCol0};
    this.renameDependencyNodes({offsetRow:nDif,offsetCol:0}, oActualRange);
3415 3416
	var i, j, length, nIndex, aIndexes = [];
	for(i in this.aGCells)
3417
	{
3418
		nIndex = i - 0;
3419 3420 3421 3422 3423
		if(nIndex >= start)
			aIndexes.push(nIndex);
	}
	//По возрастанию
	aIndexes.sort(fSortAscending);
3424
	var oDefRowPr = new UndoRedoData_RowProp();
3425
	for(i = 0, length = aIndexes.length; i < length; ++i)
3426
	{
3427
		nIndex = aIndexes[i];
3428 3429 3430 3431 3432 3433 3434 3435
		var row = this.aGCells[nIndex];
		if(nIndex > stop)
		{
			if(false == row.isEmpty())
			{
				var oTargetRow = this._getRow(nIndex + nDif);
				oTargetRow.copyProperty(row);
			}
3436 3437
			for(j in row.c)
				this._moveCellVer(nIndex, j - 0, nDif);
3438 3439 3440
		}
		else
		{
3441
			var oOldProps = row.getHeightProp();
3442
			if (false === oOldProps.isEqual(oDefRowPr))
3443
			    History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_RowProp, this.getId(), row._getUpdateRange(), new UndoRedoData_IndexSimpleProp(nIndex, true, oOldProps, oDefRowPr));
3444
			row.setStyle(null);
3445
			for(j in row.c)
3446 3447 3448 3449 3450 3451
			{
				var nColIndex = j - 0;
				//удаляем ячейку
				this._removeCell(nIndex, nColIndex);
			}
		}
3452
		delete this.aGCells[nIndex];
3453
	}
3454

3455 3456

	History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_RemoveRows, this.getId(), new Asc.Range(0, start, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_FromToRowCol(true, start, stop));
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
3457
	buildRecalc(this.workbook);
3458 3459 3460 3461 3462 3463 3464
	unLockDraw(this.workbook);
		
	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();
3465
};
3466
Woorksheet.prototype._insertRowsBefore=function(index, count){
3467 3468 3469 3470
	//до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc
	//чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся
	//например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows
	buildRecalc(this.workbook, true, true);
3471 3472 3473
	lockDraw(this.workbook);
	var oActualRange = {r1: index, c1: 0, r2: index + count - 1, c2: gc_nMaxCol0};
	History.Create_NewPoint();
3474
    this.renameDependencyNodes({offsetRow:count,offsetCol:0},oActualRange);
3475 3476
	History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_AddRows, this.getId(), new Asc.Range(0, index, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_FromToRowCol(true, index, index + count - 1));
	//index 0 based
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3477
	var aIndexes = [];
3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494
	for(var i in this.aGCells)
	{
		var nIndex = i - 0;
		if(nIndex >= index)
			aIndexes.push(nIndex);
	}
    var oPrevRow = null;
    if(index > 0)
        oPrevRow = this.aGCells[index - 1];
	//По убыванию
	aIndexes.sort(fSortDescending);
	for(var i = 0, length = aIndexes.length; i < length; ++i)
	{
		var nIndex = aIndexes[i];
		var row = this.aGCells[nIndex];
		if(false == row.isEmpty())
		{
3495
			var oTargetRow = this._getRow(nIndex + count);
3496 3497 3498 3499 3500 3501
			oTargetRow.copyProperty(row);
		}
		for(var j in row.c)
			this._moveCellVer(nIndex, j - 0, count);
        delete this.aGCells[nIndex];
	}
3502 3503 3504
	if (null != oPrevRow && false == this.workbook.bUndoChanges && (false == this.workbook.bRedoChanges || true == this.workbook.bCollaborativeChanges))
	{
	    History.LocalChange = true;
3505 3506 3507 3508
        for(var i = 0; i < count; ++i)
        {
            var row = this._getRow(index + i);
            row.copyProperty(oPrevRow);
3509
			row.flags &= ~g_nRowFlag_hd;
3510
        }
3511
        History.LocalChange = false;
3512
    }
3513

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
3514
	buildRecalc(this.workbook);
3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525
	unLockDraw(this.workbook);
	
	this.nRowsCount += count;
	
	return true;
};
Woorksheet.prototype.insertRowsAfter=function(index, count){
	//index 0 based
	return this.insertRowsBefore(index + 1, count);
};
Woorksheet.prototype.getColsCount=function(){
3526 3527 3528 3529 3530
	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;
3531 3532 3533 3534
};
Woorksheet.prototype.removeCols=function(start, stop){
	var oRange = this.getRange(new CellAddress(0, start, 0), new CellAddress(gc_nMaxRow0, stop, 0));
	oRange.deleteCellsShiftLeft();
3535
};
3536
Woorksheet.prototype._removeCols=function(start, stop){
3537 3538 3539 3540
	//до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc
	//чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся
	//например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows
	buildRecalc(this.workbook, true, true);
3541 3542 3543
	lockDraw(this.workbook);
	History.Create_NewPoint();
	//start, stop 0 based
3544
	var nDif = -(stop - start + 1), i, j, length, nIndex;
3545 3546
    var oActualRange = { r1: 0, c1: start, r2: gc_nMaxRow0, c2: stop };
    this.renameDependencyNodes({ offsetRow: 0, offsetCol: nDif }, oActualRange);
3547
	for(i in this.aGCells)
3548 3549 3550
	{
		var nRowIndex = i - 0;
		var row = this.aGCells[i];
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3551
		var aIndexes = [];
3552
		for(j in row.c)
3553
		{
3554
			nIndex = j - 0;
3555 3556 3557 3558 3559
			if(nIndex >= start)
				aIndexes.push(nIndex);
		}
		//сортируем по возрастанию
		aIndexes.sort(fSortAscending);
3560
		for(j = 0, length = aIndexes.length; j < length; ++j)
3561
		{
3562
			nIndex = aIndexes[j];
3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574
			if(nIndex > stop)
			{
				this._moveCellHor(nRowIndex, nIndex, nDif, {r1: 0, c1: start, r2: gc_nMaxRow0, c2: stop});
			}
			else
			{
				//удаляем ячейку
				this._removeCell(nRowIndex, nIndex);
			}
		}
	}
	
3575
	var oDefColPr = new UndoRedoData_ColProp();
3576
	for(i = start; i <= stop; ++i)
3577 3578 3579 3580 3581
	{
		var col = this.aCols[i];
		if(null != col)
		{
			var oOldProps = col.getWidthProp();
3582
			if(false === oOldProps.isEqual(oDefColPr))
3583
				History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_ColProp, this.getId(), new Asc.Range(i, 0, i, gc_nMaxRow0), new UndoRedoData_IndexSimpleProp(i, false, oOldProps, oDefColPr));
3584 3585 3586
			col.setStyle(null);
		}
	}
3587
	this.aCols.splice(start, stop - start + 1);
3588
	for(i = start, length = this.aCols.length; i < length; ++i)
3589 3590 3591 3592 3593
	{
		var elem = this.aCols[i];
		if(null != elem)
			elem.moveHor(nDif);
	}
3594 3595


3596
	History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_RemoveCols, this.getId(), new Asc.Range(start, 0, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_FromToRowCol(false, start, stop));
3597 3598
	buildRecalc(this.workbook);
	unLockDraw(this.workbook);
3599

3600 3601 3602
	return true;
};
Woorksheet.prototype.insertColsBefore=function(index, count){
3603
	var oRange = this.getRange3(0, index, gc_nMaxRow0, index + count - 1);
3604 3605 3606
	oRange.addCellsShiftRight();
};
Woorksheet.prototype._insertColsBefore=function(index, count){
3607 3608 3609 3610
	//до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc
	//чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся
	//например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows
	buildRecalc(this.workbook, true, true);
3611 3612 3613
	lockDraw(this.workbook);
	var oActualRange = {r1: 0, c1: index, r2: gc_nMaxRow0, c2: index + count - 1};
	History.Create_NewPoint();
3614 3615
    this.renameDependencyNodes({offsetRow:0,offsetCol:count},oActualRange);
    History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_AddCols, this.getId(), new Asc.Range(index, 0, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_FromToRowCol(false, index, index + count - 1));
3616 3617 3618 3619 3620
	//index 0 based
	for(var i in this.aGCells)
	{
		var nRowIndex = i - 0;
		var row = this.aGCells[i];
Alexander.Trofimov's avatar
Alexander.Trofimov committed
3621
		var aIndexes = [];
3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636
		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];
			this._moveCellHor(nRowIndex, nIndex, count, oActualRange);
		}
	}
	
3637

Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
3638
	buildRecalc(this.workbook);
3639 3640 3641 3642 3643
	unLockDraw(this.workbook);
	
    var oPrevCol = null;
    if(index > 0)
        oPrevCol = this.aCols[index - 1];
3644
	if(null == oPrevCol && null != this.oAllCol)
3645 3646 3647 3648
		oPrevCol = this.oAllCol;
	for(var i = 0; i < count; ++i)
    {
        var oNewCol = null;
3649
        if (null != oPrevCol && false == this.workbook.bUndoChanges && (false == this.workbook.bRedoChanges || true == this.workbook.bCollaborativeChanges))
3650
        {
3651
           History.LocalChange = true;
3652
           oNewCol = oPrevCol.clone();
3653
		   oNewCol.hd = null;
3654 3655
           oNewCol.BestFit = null;
           oNewCol.index = index + i; 
3656
           History.LocalChange = false;
3657 3658 3659
        }
		this.aCols.splice(index, 0, oNewCol);
    }
3660 3661 3662 3663 3664 3665
	for(var i = index + count, length = this.aCols.length; i < length; ++i)
	{
		var elem = this.aCols[i];
		if(null != elem)
			elem.moveHor(count);
	}
3666
	this.nColsCount += count;
3667

3668 3669 3670 3671 3672 3673 3674
	return true;
};
Woorksheet.prototype.insertColsAfter=function(index, count){
	//index 0 based
	return this.insertColsBefore(index + 1, count);
};
Woorksheet.prototype.getDefaultWidth=function(){
3675
	return this.oSheetFormatPr.dDefaultColWidth;
3676
};
3677 3678 3679 3680 3681 3682
Woorksheet.prototype.getDefaultFontName=function(){
	return this.workbook.getDefaultFont();
};
Woorksheet.prototype.getDefaultFontSize=function(){
	return this.workbook.getDefaultSize();
};
3683 3684 3685 3686 3687 3688
Woorksheet.prototype.getColWidth=function(index){
	//index 0 based
	//Результат в пунктах
	var col = this._getColNoEmptyWithAll(index);
	if(null != col && null != col.width)
		return col.width;
3689
	var dResult = this.oSheetFormatPr.dDefaultColWidth;
3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703
	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){
	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();
3704 3705 3706 3707 3708 3709 3710 3711 3712
	var oSelection = History.GetSelection();
	if(null != oSelection)
	{
		oSelection = oSelection.clone();
		oSelection.assign(start, 0, stop, gc_nMaxRow0);
		oSelection.type = c_oAscSelectionType.RangeCol;
		History.SetSelection(oSelection);
		History.SetSelectionRedo(oSelection);
	}
3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723
	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))
3724
				History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_ColProp, oThis.getId(),
3725
					col._getUpdateRange(),
3726
					new UndoRedoData_IndexSimpleProp(col.index, false, oOldProps, oNewProps));
3727 3728 3729 3730 3731 3732
		}
	};
	if(0 == start && gc_nMaxCol0 == stop)
	{
		var col = this.getAllCol();
		fProcessCol(col);
3733
		for(var i in this.aCols){
3734 3735 3736
		    var col = this.aCols[i];
		    if (null != col)
			    fProcessCol(col);
3737
		}
3738 3739 3740 3741 3742 3743 3744 3745 3746
	}
	else
	{
		for(var i = start; i <= stop; i++){
			var col = this._getCol(i);
			fProcessCol(col);
		}
	}
};
3747 3748 3749 3750
Woorksheet.prototype.getColHidden=function(index){
	var col = this._getColNoEmptyWithAll(index);
	return col ? col.hd : false;
};
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
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)
			{
				col.hd = bHidden;
				if(null == col.width || true != col.CustomWidth)
					col.width = 0;
				col.CustomWidth = true;
				col.BestFit = null;
			}
			else
			{
				col.hd = null;
				if(0 == col.width)
					col.width = null;
			}
			var oNewProps = col.getWidthProp();
			if(false == oOldProps.isEqual(oNewProps))
3779
				History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_ColProp, oThis.getId(),
3780
					col._getUpdateRange(),
3781
					new UndoRedoData_IndexSimpleProp(col.index, false, oOldProps, oNewProps));
3782 3783 3784 3785
		}
	};
	if(0 != start && gc_nMaxCol0 == stop)
	{
3786 3787 3788 3789 3790 3791 3792
		var col = null;
		if(false == bHidden)
			col = this.oAllCol;
		else
			col = this.getAllCol();
		if(null != col)
			fProcessCol(col);
3793
		for(var i in this.aCols){
3794 3795 3796
		    var col = this.aCols[i];
		    if (null != col)
			    fProcessCol(col);
3797
		}
3798 3799 3800 3801
	}
	else
	{
		for(var i = start; i <= stop; i++){
3802 3803 3804 3805 3806 3807 3808
			var col = null;
			if(false == bHidden)
				col = this._getColNoEmpty(i);
			else
				col = this._getCol(i);
			if(null != col)
				fProcessCol(col);
3809 3810 3811
		}
	}
};
3812
Woorksheet.prototype.setColBestFit=function(bBestFit, width, start, stop){
3813 3814 3815 3816 3817 3818 3819 3820
	//start, stop 0 based
	if(null == start)
		return;
	if(null == stop)
		stop = start;
	History.Create_NewPoint();
	var oThis = this;
	var fProcessCol = function(col){
3821 3822
		var oOldProps = col.getWidthProp();
		if(bBestFit)
3823
		{
3824 3825 3826 3827 3828 3829 3830 3831
			col.BestFit = bBestFit;
			col.hd = null;
		}
		else
			col.BestFit = null;
		col.width = width;
		var oNewProps = col.getWidthProp();
		if(false == oOldProps.isEqual(oNewProps))
3832
			History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_ColProp, oThis.getId(),
3833
				col._getUpdateRange(),
3834
				new UndoRedoData_IndexSimpleProp(col.index, false, oOldProps, oNewProps));
3835 3836 3837
	};
	if(0 != start && gc_nMaxCol0 == stop)
	{
3838 3839 3840 3841 3842 3843 3844
		var col = null;
		if(bBestFit && gc_dDefaultColWidthCharsAttribute == width)
			col = this.oAllCol;
		else
			col = this.getAllCol();
		if(null != col)
			fProcessCol(col);
3845
		for(var i in this.aCols){
3846 3847 3848
		    var col = this.aCols[i];
		    if (null != col)
			    fProcessCol(col);
3849
		}
3850 3851 3852 3853
	}
	else
	{
		for(var i = start; i <= stop; i++){
3854 3855 3856 3857 3858 3859 3860
			var col = null;
			if(bBestFit && gc_dDefaultColWidthCharsAttribute == width)
				col = this._getColNoEmpty(i);
			else
				col = this._getCol(i);
			if(null != col)
				fProcessCol(col);
3861 3862 3863
		}
	}
};
3864
Woorksheet.prototype.isDefaultHeightHidden=function(){
3865
	return null != this.oSheetFormatPr.oAllRow && 0 != (g_nRowFlag_hd & this.oSheetFormatPr.oAllRow.flags);
3866 3867 3868 3869
};
Woorksheet.prototype.isDefaultWidthHidden=function(){
	return null != this.oAllCol && this.oAllCol.hd;
};
3870
Woorksheet.prototype.getDefaultHeight=function(){
3871
    // ToDo http://bugzserver/show_bug.cgi?id=19666 (флага CustomHeight нет)
3872
	var dRes = null;
3873
	// Нужно возвращать выставленную, только если флаг CustomHeight = true
3874
	if(null != this.oSheetFormatPr.oAllRow && 0 != (g_nRowFlag_CustomHeight & this.oSheetFormatPr.oAllRow.flags))
3875 3876
		dRes = this.oSheetFormatPr.oAllRow.h;
	return dRes;
3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894
};
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){
	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();
3895
	var oThis = this, i;
3896 3897 3898 3899 3900 3901 3902 3903 3904
	var oSelection = History.GetSelection();
	if(null != oSelection)
	{
		oSelection = oSelection.clone();
		oSelection.assign(0, start, gc_nMaxCol0, stop);
		oSelection.type = c_oAscSelectionType.RangeRow;
		History.SetSelection(oSelection);
		History.SetSelectionRedo(oSelection);
	}
3905
	var fProcessRow = function(row){
3906
		if(row)
3907
		{
3908 3909
			var oOldProps = row.getHeightProp();
			row.h = height;
3910 3911
			row.flags |= g_nRowFlag_CustomHeight;
			row.flags &= ~g_nRowFlag_hd;
3912
			var oNewProps = row.getHeightProp();
3913
			if(false === oOldProps.isEqual(oNewProps))
3914
			    History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_RowProp, oThis.getId(), row._getUpdateRange(), new UndoRedoData_IndexSimpleProp(row.index, true, oOldProps, oNewProps));
3915 3916 3917 3918
		}
	};
	if(0 == start && gc_nMaxRow0 == stop)
	{
3919 3920 3921
		fProcessRow(this.getAllRow());
		for(i in this.aGCells){
			fProcessRow(this.aGCells[i]);
3922 3923 3924 3925
		}
	}
	else
	{
3926 3927
		for(i = start; i <= stop; ++i){
			fProcessRow(this._getRow(i));
3928 3929 3930
		}
	}
};
3931 3932
Woorksheet.prototype.getRowHidden=function(index){
	var row = this._getRowNoEmptyWithAll(index);
3933
	return row ? 0 != (g_nRowFlag_hd & row.flags) : false;
3934
};
3935 3936 3937 3938 3939 3940 3941
Woorksheet.prototype.setRowHidden=function(bHidden, start, stop){
	//start, stop 0 based
	if(null == start)
		return;
	if(null == stop)
		stop = start;
	History.Create_NewPoint();
3942
	var oThis = this, i;
Igor.Zotov's avatar
Igor.Zotov committed
3943
	var startIndex = null, endIndex = null, updateRange;
3944
	
3945
	var fProcessRow = function(row){
3946
		if(row && bHidden != (0 != (g_nRowFlag_hd & row.flags)))
3947 3948
		{
			if(bHidden)
3949
				row.flags |= g_nRowFlag_hd;
3950
			else
3951
				row.flags &= ~g_nRowFlag_hd;
3952
			
Igor.Zotov's avatar
Igor.Zotov committed
3953 3954 3955 3956
			
			if(row.index === endIndex + 1 && startIndex !== null)
				endIndex++;
			else
3957
			{
Igor.Zotov's avatar
Igor.Zotov committed
3958 3959 3960 3961 3962 3963
				if(startIndex !== null)
				{
					updateRange = new Asc.Range(0, startIndex, gc_nMaxCol0, endIndex);
					History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_RowHide, oThis.getId(), updateRange, new UndoRedoData_FromToRowCol(bHidden, startIndex, endIndex));
				}	
				
3964
				startIndex = row.index;
Igor.Zotov's avatar
Igor.Zotov committed
3965
				endIndex = row.index;
3966 3967
			}
		}
3968 3969 3970
	};
	if(0 == start && gc_nMaxRow0 == stop)
	{
3971
        // ToDo реализовать скрытие всех строк!
3972 3973 3974
	}
	else
	{
3975 3976
		for(i = start; i <= stop; ++i)
			fProcessRow(false == bHidden ? this._getRowNoEmpty(i) : this._getRow(i));
Igor.Zotov's avatar
Igor.Zotov committed
3977 3978 3979 3980 3981 3982
		
		if(startIndex !== null)//заносим последние строки
		{
			updateRange = new Asc.Range(0, startIndex, gc_nMaxCol0, endIndex);
			History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_RowHide, oThis.getId(),updateRange, new UndoRedoData_FromToRowCol(bHidden, startIndex, endIndex));
		}
3983 3984
	}
};
3985
Woorksheet.prototype.setRowBestFit=function(bBestFit, height, start, stop){
3986 3987 3988 3989 3990 3991
	//start, stop 0 based
	if(null == start)
		return;
	if(null == stop)
		stop = start;
	History.Create_NewPoint();
3992 3993
	var oThis = this, i;
    var isDefaultProp = (true == bBestFit && gc_dDefaultRowHeightAttribute == height);
3994 3995
	var fProcessRow = function(row){
		if(row)
3996
		{
3997
			var oOldProps = row.getHeightProp();
3998
			if(true == bBestFit)
3999
				row.flags &= ~g_nRowFlag_CustomHeight;
4000
			else
4001
				row.flags |= g_nRowFlag_CustomHeight;
4002
			row.h = height;
4003
			var oNewProps = row.getHeightProp();
4004
			if(false == oOldProps.isEqual(oNewProps))
4005
			    History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_RowProp, oThis.getId(), row._getUpdateRange(), new UndoRedoData_IndexSimpleProp(row.index, true, oOldProps, oNewProps));
4006
		}
4007 4008 4009
	};
	if(0 == start && gc_nMaxRow0 == stop)
	{
4010 4011 4012
		fProcessRow(isDefaultProp ? this.oSheetFormatPr.oAllRow : this.getAllRow());
		for(i in this.aGCells)
			fProcessRow(this.aGCells[i]);
4013
	}
4014 4015
	for(i = start; i <= stop; ++i)
		fProcessRow(isDefaultProp ? this._getRowNoEmpty(i) : this._getRow(i));
4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036
};
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){
4037
	var bbox = Asc.g_oRangeCache.getAscRange(sRange);
4038
	if(null != bbox)
4039
		return Range.prototype.createFromBBox(this, bbox);
4040
	return null;
4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055
};
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);
4056
};
4057 4058 4059 4060 4061 4062 4063 4064 4065
Woorksheet.prototype._getRows=function(){
	return this.aGCells;
};
Woorksheet.prototype._getCols=function(){
	return this.aCols;
};
Woorksheet.prototype._removeCell=function(nRow, nCol, cell){
	if(null != cell)
	{
4066 4067
		nRow = cell.nRow;
		nCol = cell.nCol;
4068 4069 4070 4071 4072 4073 4074
	}
	var row = this.aGCells[nRow];
	if(null != row)
	{
		var cell = row.c[nCol];
		if(null != cell)
		{
4075 4076
		    var sheetId = this.getId();
		    var cellId = cell.getName();
4077
			if(cell.formulaParsed)
4078 4079 4080
			    this.workbook.dependencyFormulas.deleteMasterNodes2(sheetId, cellId);
			this.workbook.needRecalc.nodes[getVertexId(sheetId, cellId)] = [sheetId, cellId];
			this.workbook.needRecalc.length++;
4081
			
4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096
			if (null != cell.getConditionalFormattingStyle() || null != cell.getTableStyle()) {
			    cell.setValue("");
			    cell.setStyle(null);
			}
			else {
			    if (false == cell.isEmpty()) {
			        var oUndoRedoData_CellData = new UndoRedoData_CellData(cell.getValueData(), null);
			        if (null != cell.xfs)
			            oUndoRedoData_CellData.style = cell.xfs.clone();
			        History.Add(g_oUndoRedoWorksheet, 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];
			}
4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112
		}
	}
};
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(null != oRow && null != oRow.xfs)
			xfs = oRow.xfs.clone();
		else if(null != oCol && null != oCol.xfs)
			xfs = oCol.xfs.clone();
4113
		oCurCell.create(xfs, row, col);
4114
		oCurRow.c[col] = oCurCell;
4115
		if(row >= this.nRowsCount)
4116
			this.nRowsCount = row + 1;
4117
		if(col >= this.nColsCount)
4118
			this.nColsCount = col + 1;
4119
		//History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_CreateCell, this.getId(), null, new UndoRedoData_CellSimpleData(row, col, null, null));
4120 4121 4122 4123 4124 4125 4126
	}
	return oCurCell;
};
Woorksheet.prototype._getCellNoEmpty=function(row, col){
	//0-based
	var oCurRow = this.aGCells[row];
	if(oCurRow)
Sergey.Konovalov's avatar
Sergey.Konovalov committed
4127 4128 4129 4130
	{
		var cell = oCurRow.c[col];
		return cell ? cell : null;
	}
4131 4132 4133 4134 4135 4136 4137 4138
	return null;
};
Woorksheet.prototype._getRowNoEmpty=function(row){
	//0-based
	var oCurRow = this.aGCells[row];
	if(oCurRow)
		return oCurRow;
	return null;
4139
};
4140 4141
Woorksheet.prototype._getRowNoEmptyWithAll=function(row){
	var oRes = this._getRowNoEmpty(row);
4142 4143 4144
	if(null == oRes)
		oRes = this.oSheetFormatPr.oAllRow;
	return oRes;
4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160
};
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
4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172
    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 Row(this);
            oCurRow.create(row + 1);
            this.aGCells[row] = oCurRow;
4173
            this.nRowsCount = row >= this.nRowsCount ? row + 1 : this.nRowsCount;
4174 4175 4176
            //History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_CreateRow, this.getId(), null, new UndoRedoData_SingleProperty(row));
        }
    }
4177 4178 4179 4180 4181 4182 4183 4184
	return oCurRow;
};
Woorksheet.prototype._removeRow=function(index){
	delete this.aGCells[index];
};
Woorksheet.prototype._getCol=function(index){
	//0-based
	var oCurCol;
4185
	if (g_nAllColIndex == index)
4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199
		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 Col(this, index);
			this.aCols[index] = oCurCol;
4200
			this.nColsCount = index >= this.nColsCount ? index + 1 : this.nColsCount;
4201
			//History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_CreateCol, this.getId(), null, new UndoRedoData_SingleProperty(index));
4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232
		}
	}
	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];
	}
};
4233
Woorksheet.prototype._prepareMoveRangeGetCleanRanges=function(oBBoxFrom, oBBoxTo){
4234 4235 4236 4237 4238 4239 4240 4241 4242
	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));
4243
		};
4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262
		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);
4263 4264
		}
	}
4265 4266
	else
		aRangesToCheck.push(this.getRange3(oBBoxTo.r1, oBBoxTo.c1, oBBoxTo.r2, oBBoxTo.c2));
4267
	return aRangesToCheck;
4268
};
4269 4270 4271 4272
Woorksheet.prototype._prepareMoveRange=function(oBBoxFrom, oBBoxTo){
	var res = 0;
	if(oBBoxFrom.isEqual(oBBoxTo))
		return res;
4273 4274 4275 4276
	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;
4277
	var aRangesToCheck = this._prepareMoveRangeGetCleanRanges(oBBoxFrom, oBBoxTo);
4278 4279
	for(var i = 0, length = aRangesToCheck.length; i < length; i++)
	{
4280
		range = aRangesToCheck[i];
4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291
		range._foreachNoEmpty(
			function(cell){
				if(!cell.isEmptyTextString())
				{
					res = -1;
					return res;
				}
			});
		if(0 != res)
			return res;
	}
4292
	return res;
4293
};
4294
Woorksheet.prototype._moveRange=function(oBBoxFrom, oBBoxTo, copyRange){
4295 4296 4297
	if(oBBoxFrom.isEqual(oBBoxTo))
		return;
	var oThis = this;
4298
	History.Create_NewPoint();
4299
	History.StartTransaction();
4300
	
4301
	var offset = { offsetRow : oBBoxTo.r1 - oBBoxFrom.r1, offsetCol : oBBoxTo.c1 - oBBoxFrom.c1 };
4302 4303 4304 4305
	var intersection = oBBoxFrom.intersectionSimple(oBBoxTo);
	var oRangeIntersection = null;
	if(null != intersection)
		oRangeIntersection = this.getRange3(intersection.r1, intersection.c1, intersection.r2, intersection.c2 );
4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317
	//запоминаем то что нужно переместить
	var aTempObj = {cells: {}, merged: null, hyperlinks: null};
	for(var i = oBBoxFrom.r1; i <= oBBoxFrom.r2; i++)
	{
		var row = this._getRowNoEmpty(i);
		if(null != row)
		{
			var oTempRow = {};
			aTempObj.cells[i + offset.offsetRow] = oTempRow;
			for(var j = oBBoxFrom.c1; j <= oBBoxFrom.c2; j++)
			{
				var cell = row.c[j];
4318 4319 4320 4321 4322 4323
				if(null != cell){
                    if(copyRange)
					    oTempRow[j + offset.offsetCol] = cell.clone();
                    else
					    oTempRow[j + offset.offsetCol] = cell;
                }
4324 4325 4326
			}
		}
	}
4327
	if(false == this.workbook.bUndoChanges && (false == this.workbook.bRedoChanges || true == this.workbook.bCollaborativeChanges))
4328
	{
4329
	    History.LocalChange = true;
4330 4331 4332
		var aMerged = this.mergeManager.get(oBBoxFrom);
		if(aMerged.inner.length > 0)
			aTempObj.merged = aMerged.inner;
4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346
		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++)
4347
			{
4348
				var elem = aMergedToRemove[i];
4349
				this.mergeManager.removeElement(elem);
4350
			}
4351
		}
4352 4353
		if(!copyRange){
			if(null != aTempObj.hyperlinks)
4354
			{
4355 4356 4357 4358 4359
				for(var i = 0, length = aTempObj.hyperlinks.length; i < length; i++)
				{
					var elem = aTempObj.hyperlinks[i];
					this.hyperlinkManager.removeElement(elem);
				}
4360
			}
4361
		}
4362
		History.LocalChange = false;
4363 4364
	}
	//удаляем to через историю, для undo
4365
	var aRangesToCheck = this._prepareMoveRangeGetCleanRanges(oBBoxFrom, oBBoxTo);
4366 4367 4368 4369 4370 4371 4372
	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());
	}
4373
	//удаляем from без истории, потому что эти данные не терются а перемещаются
4374
    if(!copyRange || (copyRange && this.workbook.bUndoChanges)){
4375
		var oRangeFrom = this.getRange3(oBBoxFrom.r1, oBBoxFrom.c1, oBBoxFrom.r2, oBBoxFrom.c2 );
4376 4377 4378 4379 4380 4381
        oRangeFrom._setPropertyNoEmpty(null, null, function(cell, nRow0, nCol0, nRowStart, nColStart){
            var row = oThis._getRowNoEmpty(nRow0);
            if(null != row)
                delete row.c[nCol0];
        });
    }
4382 4383 4384 4385 4386 4387 4388 4389 4390 4391
	else{
		//в случае копирования удаляем пересечение, чтобы затирались значения, если мы копируем пустые ячейки(все что не входит в пересечение удалилось выше через историю)
		if(null != intersection){
			oRangeIntersection._setPropertyNoEmpty(null, null, function(cell, nRow0, nCol0, nRowStart, nColStart){
				var row = oThis._getRowNoEmpty(nRow0);
				if(null != row)
					delete row.c[nCol0];
			});
		}
	}
4392
    if(!copyRange){
4393 4394 4395 4396
		//до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc
		//чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся
		//например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows
		buildRecalc(this.workbook, true, true);
4397
        this.workbook.dependencyFormulas.helper(oBBoxFrom, oBBoxTo,this.Id);
4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411
    }

    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.sFormula ) {
                    if(copyRange){
4412
                        oTempCell.formulaParsed = new parserFormula( oTempCell.sFormula, g_oCellAddressUtils.getCellId(oTempCell.nRow, oTempCell.nCol), this );
4413 4414 4415
                        oTempCell.formulaParsed.parse();
                        oTempCell.formulaParsed = oTempCell.formulaParsed.changeOffset(offset);
                        oTempCell.sFormula = oTempCell.formulaParsed.assemble();
4416
						
4417
						addToArrRecalc(this.getId(), oTempCell);
4418
                    }
4419
                }
4420 4421 4422
            }
        }
    }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
4423

4424
	if(false == this.workbook.bUndoChanges && (false == this.workbook.bRedoChanges || true == this.workbook.bCollaborativeChanges))
4425
	{
4426
	    History.LocalChange = true;
4427
		if(null != aTempObj.merged)
4428
		{
4429 4430 4431
			for(var i = 0, length = aTempObj.merged.length; i < length; i++)
			{
				var elem = aTempObj.merged[i];
4432 4433 4434 4435 4436 4437 4438 4439
				var oNewBBox;
				var oNewData = elem.data;
				if(copyRange)
					oNewBBox = elem.bbox.clone();
				else
					oNewBBox = elem.bbox;
				oNewBBox.setOffset(offset);
				this.mergeManager.add(oNewBBox, oNewData);
4440
			}
4441
		}
4442 4443
		//todo сделать для пересечения
		if(null != aTempObj.hyperlinks && (!copyRange || null == intersection))
4444
		{
4445 4446 4447
			for(var i = 0, length = aTempObj.hyperlinks.length; i < length; i++)
			{
				var elem = aTempObj.hyperlinks[i];
4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459
				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);
4460
			}
4461
		}
4462
		History.LocalChange = false;
4463 4464
	}
	//расширяем границы
4465
	if(oBBoxFrom.r2 >= this.nRowsCount)
4466
		this.nRowsCount = oBBoxFrom.r2 + 1;
4467
	if(oBBoxFrom.c2 >= this.nColsCount)
4468
		this.nColsCount = oBBoxFrom.c2 + 1;
4469
	if(oBBoxTo.r2 >= this.nRowsCount)
4470
		this.nRowsCount = oBBoxTo.r2 + 1;
4471
	if(oBBoxTo.c2 >= this.nColsCount)
4472
		this.nColsCount = oBBoxTo.c2 + 1;
4473

4474
	if(!copyRange){
4475 4476 4477
		var sBBoxFromName = oBBoxFrom.getName();
		this.workbook.needRecalc.nodes[getVertexId(this.getId(), sBBoxFromName)] = [this.getId(), sBBoxFromName];
		this.workbook.needRecalc.length++;
4478
	}
4479 4480 4481 4482 4483 4484 4485
	var sBBoxToName = oBBoxTo.getName();
	this.workbook.needRecalc.nodes[getVertexId(this.getId(), sBBoxToName)] = [this.getId(), sBBoxToName];
	this.workbook.needRecalc.length++;
	if ( this.workbook.isNeedCacheClean ){
		/*
			Если необходим пересчет, то по списку пересчитываемых ячеек сортируем граф зависимостей и пересчиываем в получившемся порядке. Плохим ячейкам с цикличискими ссылками выставляем ошибку "#REF!".
		*/
4486
        sortDependency(this.workbook);
4487
	}
4488
	// ToDo возможно нужно уменьшить диапазон обновления
4489
    History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_MoveRange,
4490
				this.getId(), new Asc.Range(0, 0, gc_nMaxCol0, gc_nMaxRow0),
4491
				new UndoRedoData_FromTo(new UndoRedoData_BBox(oBBoxFrom), new UndoRedoData_BBox(oBBoxTo), copyRange));
4492
	History.EndTransaction();
4493
	return true;
4494
};
4495
Woorksheet.prototype._shiftCellsLeft=function(oBBox){
4496 4497 4498 4499
	//до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc
	//чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся
	//например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows
	buildRecalc(this.workbook, true, true);
4500 4501 4502 4503
	//todo удаление когда есть замерженые ячейки
	var nLeft = oBBox.c1;
	var nRight = oBBox.c2;
	var dif = nLeft - nRight - 1;
4504
    this.renameDependencyNodes( {offsetRow:0,offsetCol:dif}, oBBox );
4505 4506 4507
	for(var i = oBBox.r1; i <= oBBox.r2; i++){
		var row = this.aGCells[i];
		if(row){
Alexander.Trofimov's avatar
Alexander.Trofimov committed
4508
			var aIndexes = [];
4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529
			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{
					//Сдвигаем ячейки
					this._moveCellHor(i, nCellInd, dif, oBBox);
				}
			}
		}
	}
4530

4531
	History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_ShiftCellsLeft, this.getId(), new Asc.Range(nLeft, oBBox.r1, gc_nMaxCol0, oBBox.r2), new UndoRedoData_BBox(oBBox));
4532 4533 4534
	//todo проверить не уменьшились ли границы таблицы
};
Woorksheet.prototype._shiftCellsUp=function(oBBox){
4535 4536 4537 4538
	//до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc
	//чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся
	//например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows
	buildRecalc(this.workbook, true, true);
4539 4540 4541
	var nTop = oBBox.r1;
	var nBottom = oBBox.r2;
	var dif = nTop - nBottom - 1;
4542
    this.renameDependencyNodes({offsetRow:dif,offsetCol:0}, oBBox );
Alexander.Trofimov's avatar
Alexander.Trofimov committed
4543
	var aIndexes = [];
4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571
	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){
				//Удаляем ячейки
				for(var j = oBBox.c1; j <= oBBox.c2; j++){
					this._removeCell(rowInd, j);
				}
			}
			else{
				var nIndex = rowInd + dif;
				var rowTop = this._getRow(nIndex);
				//Сдвигаем ячейки
				for(var j = oBBox.c1; j <= oBBox.c2; j++){
					this._moveCellVer(rowInd, j, dif);
				}
			}
		}
	}
4572

4573
	History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_ShiftCellsTop, this.getId(), new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, gc_nMaxRow0), new UndoRedoData_BBox(oBBox));
4574 4575 4576
	//todo проверить не уменьшились ли границы таблицы
};
Woorksheet.prototype._shiftCellsRight=function(oBBox){
4577 4578 4579 4580
	//до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc
	//чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся
	//например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows
	buildRecalc(this.workbook, true, true);
4581 4582 4583
	var nLeft = oBBox.c1;
	var nRight = oBBox.c2;
	var dif = nRight - nLeft + 1;
4584
    this.renameDependencyNodes({offsetRow:0,offsetCol:dif}, oBBox);
4585 4586 4587
	for(var i = oBBox.r1; i <= oBBox.r2; i++){
		var row = this.aGCells[i];
		if(row){
Alexander.Trofimov's avatar
Alexander.Trofimov committed
4588
			var aIndexes = [];
4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608
			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);
				}
			}
		}
	}
4609

4610
	History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_ShiftCellsRight, this.getId(), new Asc.Range(oBBox.c1, oBBox.r1, gc_nMaxCol0, oBBox.r2), new UndoRedoData_BBox(oBBox));
4611 4612
};
Woorksheet.prototype._shiftCellsBottom=function(oBBox){
4613 4614 4615 4616
	//до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc
	//чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся
	//например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows
	buildRecalc(this.workbook, true, true);
4617 4618 4619
	var nTop = oBBox.r1;
	var nBottom = oBBox.r2;
	var dif = nBottom - nTop + 1;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
4620
	var aIndexes = [];
4621
    this.renameDependencyNodes({offsetRow:dif,offsetCol:0}, oBBox);
4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643
	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){
			var nIndex = rowInd + dif;
			if(nIndex + dif > this.nRowsCount)
				this.nRowsCount = nIndex + dif;
			var rowTop = this._getRow(nIndex);
			//Сдвигаем ячейки
			for(var j = oBBox.c1; j <= oBBox.c2; j++){
				this._moveCellVer(rowInd, j, dif);
			}
		}
	}

4644
	History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_ShiftCellsBottom, this.getId(), new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, gc_nMaxRow0), new UndoRedoData_BBox(oBBox));
4645 4646 4647
};
Woorksheet.prototype._setIndex=function(ind){
	this.index = ind;
4648
};
4649 4650 4651 4652
Woorksheet.prototype._BuildDependencies=function(cellRange){
	/*
		Построение графа зависимостей.
	*/
4653
	var c, ca, oLengthCache = {};
4654
	for(var i in cellRange){
4655
		ca = g_oCellAddressUtils.getCellAddress(i);
4656
		c = this._getCellNoEmpty(ca.getRow0(),ca.getCol0());
4657

4658
		if( c && c.sFormula ){
4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673
			var elem = oLengthCache[c.sFormula.length];
			if(null == elem)
			{
				elem = [];
				oLengthCache[c.sFormula.length] = elem;
			}
			elem.push(c);
		}
	}
	for(var i in oLengthCache)
	{
		var temp = oLengthCache[i];
		var aCache = [];
		for(var j = 0, length2 = temp.length; j < length2; j++)
		{
4674 4675 4676 4677 4678
			var c = temp[j],
			    cellId = g_oCellAddressUtils.getCellId(c.nRow, c.nCol ),
                aRefs = [],
                cache = inCache(aCache, c.sFormula, aRefs ),
                bInCache = false;
4679 4680 4681
			if(cache)
			{
				bInCache = true;
4682
				var oNewFormula = cache.formulaParsed.clone(c.sFormula, cellId, this);
4683 4684 4685 4686 4687 4688 4689
				var RefPos = cache.formulaParsed.RefPos;
				for(var k = 0, length3 = RefPos.length; k < length3; k++)
				{
					var pos = RefPos[k];
					var elem = oNewFormula.outStack[pos.index];
					if(elem)
					{
4690
						//todo случай ,если ref число или именованный диапазон
4691 4692 4693 4694 4695 4696 4697
						var ref = aRefs[k];
						var range = Asc.g_oRangeCache.getAscRange(ref);
						if(null != range)
						{
							var oNewElem;
							if(range.isOneCell())
							{
4698 4699 4700
								if(elem instanceof cRef3D)
									oNewElem = new cRef3D(ref, elem.ws.getName(), elem._wb);
								else if(elem instanceof cArea3D)
4701 4702 4703
								{
									var wsFrom = elem._wb.getWorksheetById( elem.wsFrom ).getName();
									var wsTo = elem._wb.getWorksheetById( elem.wsTo ).getName();
4704
									oNewElem = new cArea3D(ref, wsFrom, wsTo, elem._wb);
4705
								}
4706 4707
								else if(-1 != ref.indexOf(":"))//случай "A1:A1"
									oNewElem = new cArea(ref, elem.ws);
4708
								else
4709
									oNewElem = new cRef(ref, elem.ws);
4710 4711 4712
							}
							else
							{
4713 4714 4715
								if(elem instanceof cRef3D)
									oNewElem = new cArea3D(ref, elem.ws.getName(), elem.ws.getName(), elem._wb);
								else if(elem instanceof cArea3D)
4716 4717 4718
								{
									var wsFrom = elem._wb.getWorksheetById( elem.wsFrom ).getName();
									var wsTo = elem._wb.getWorksheetById( elem.wsTo ).getName();
4719
									oNewElem = new cArea3D(ref, wsFrom, wsTo, elem._wb);
4720 4721
								}
								else
4722
									oNewElem = new cArea(ref, elem.ws);
4723 4724
							}
							if ( ref.indexOf( "$" ) > -1 )
4725
								oNewElem.isAbsolute = true; // ToDo - пересмотреть этот параметр (есть в Range информация о абсолютной ссылке)
4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739
							oNewFormula.outStack[pos.index] = oNewElem;
						}
						else
							bInCache = false;
					}
				}
				if(bInCache)
				{
					c.formulaParsed = oNewFormula;
					c.formulaParsed.buildDependencies();
				}
			}
			if(!bInCache)
			{
4740
				c.formulaParsed = new parserFormula( c.sFormula, cellId, this );
4741 4742
				c.formulaParsed.parse();
				c.formulaParsed.buildDependencies();
4743 4744 4745
				//error не добавляем в кеш у них не распознались RefPos, их бессмысленно сравнивать.Это только добавит торозов
				if(0 == c.formulaParsed.error.length)
					aCache.push(c);
4746 4747 4748
			}
		}
	}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
4749
};
4750
Woorksheet.prototype._setHandlersTablePart = function(){
4751
	if(!this.TableParts)
4752 4753
		return;
	
4754
	for(var i = 0; i < this.TableParts.length; i++)
4755
	{
4756
		this.TableParts[i].setHandlers(this.handlers);
4757 4758
	}
};
4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773
Woorksheet.prototype.getTableRangeForFormula = function(name, objectParam){
	var res = null;
	if(!this.TableParts)
		return res;
	
	for(var i = 0; i < this.TableParts.length; i++)
	{
		if(this.TableParts[i].Name === name)
		{
			res = this.TableParts[i].getTableRangeForFormula(objectParam);
			break;
		}
	}
	return res;
};
4774

4775 4776 4777 4778 4779 4780 4781
function inCache(aCache, sFormula, aRefs)
{
	var oRes = null;
	for(var i = 0, length = aCache.length; i < length; i++)
	{
		var cache = aCache[i];
		var sCurFormula = cache.sFormula;
4782 4783 4784 4785 4786 4787 4788
		if(null != cache.formulaParsed){
			var RefPos = cache.formulaParsed.RefPos;
			//todo свое сравнение для error
			if(0 == cache.formulaParsed.error.length && inCacheStrcmp(sCurFormula, sFormula, RefPos, aRefs)){
				oRes = cache;
				break;
			}
4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826
		}
	}
	return oRes;
}
function inCacheStrcmp(str1, str2, RefPos, aRefs)
{
	var bRes = true;
	var nStartIndex = 0;
	for(var i = 0, length = RefPos.length; i < length; i++)
	{
		var mask = RefPos[i];
		for(var j = nStartIndex; j < mask.start; j++)
		{
			if(str1[j] != str2[j])
			{
				bRes = false;
				break;
			}
		}
		nStartIndex = mask.end;
	}
	if(bRes)
	{
		for(var i = nStartIndex; i < str1.length; i++)
		{
			if(str1[i] != str2[i])
			{
				bRes = false;
				break;
			}
		}
	}
	if(bRes)
	{
		for(var i = 0, length = RefPos.length; i < length; i++)
		{
			var mask = RefPos[i];
			aRefs.push(str2.substring(mask.start, mask.end));
4827
		}
4828
	}
4829
	return bRes;
4830
}
4831
Woorksheet.prototype._RecalculatedFunctions=function(cell,bad,setCellFormat){
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
4832 4833 4834 4835 4836 4837
    function adjustCellFormat( c ) {
        // ищет в формуле первый рэндж и устанавливает формат ячейки как формат первой ячейки в рэндже
        var elem = null;
        if ( c.formulaParsed && c.formulaParsed.outStack ) {
            for ( var i = 0, length = c.formulaParsed.outStack.length; i < length; i++ ) {
                elem = c.formulaParsed.outStack[i];
4838
                if ( elem instanceof cRef || elem instanceof cRef3D || elem instanceof cArea || elem instanceof cArea3D ) {
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
4839
                    var r = elem.getRange();
4840
                    if ( elem instanceof cArea3D && r.length > 0 )
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854
                        r = r[0];
                    if ( r && r.getNumFormatStr ) {
                        var sCurFormat = c.getNumFormatStr();
                        if ( g_oDefaultNum.f == sCurFormat ) {
                            var sNewFormat = r.getNumFormatStr();
                            if ( sCurFormat != sNewFormat )
                                c.setNumFormat( sNewFormat );
                        }
                    }
                    break;
                }
            }
        }
    }
4855
	
4856 4857
	if( cell.indexOf(":")>-1 ) return;
	
4858 4859 4860 4861
	var celladd = this.getRange2(cell).getFirst(),
		__cell = this._getCellNoEmpty( celladd.getRow0(),celladd.getCol0() ), res;
	
	if( !__cell || !__cell.sFormula )
4862 4863 4864 4865 4866 4867 4868 4869 4870
		return;

	/*
		bad - флаг, показывающий, что ячейка находится в списке плохих ячеек (имеются циклические ссылки на ячейку), после сортировки графа зависимостей.
	*/
	if(!bad){
		res = __cell.formulaParsed.calculate();
	}
	else {
4871
		res = new cError( cErrorType.bad_reference )
4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902
	}
	if(res){
		if( res.type == cElementType.cell){
			var nF = res.numFormat;
			res = res.getValue();
			res.numFormat = nF;
		}
		else if( res.type == cElementType.array ){
			var nF = res.numFormat;
			res = res.getElement(0);
			res.numFormat = nF;
		}
		else if( res.type == cElementType.cellsRange ){
			var nF = res.numFormat;
			res = res.cross(new CellAddress(cell))
			res.numFormat = nF;
		}
		__cell.oValue.clean();
		switch (res.type){
			case cElementType.number:
				__cell.oValue.type = CellValueType.Number;
				__cell.oValue.number = res.getValue();
				break;
			case cElementType.bool:
				__cell.oValue.type = CellValueType.Bool;
				__cell.oValue.number = res.value ? 1 : 0;
				break;
			case cElementType.error:
				__cell.oValue.type = CellValueType.Error;
				__cell.oValue.text = res.getValue().toString();
				break;
4903 4904 4905 4906
            case cElementType.name:
				__cell.oValue.type = CellValueType.Error;
				__cell.oValue.text = res.getValue().toString();
				break;
4907 4908 4909 4910
			default:
				__cell.oValue.type = CellValueType.String;
				__cell.oValue.text = res.getValue().toString();
		}
4911 4912
		g_oVLOOKUPCache.remove(__cell);
		g_oHLOOKUPCache.remove(__cell);
4913
		__cell.setFormulaCA(res.ca);
4914 4915
        if(setCellFormat){
            if( res.numFormat !== undefined && res.numFormat >= 0){
4916

4917 4918
                if( aStandartNumFormatsId[__cell.getNumFormatStr()] == 0 )
                    __cell.setNumFormat(aStandartNumFormats[res.numFormat])
4919

4920 4921 4922 4923 4924
            }
            else if( res.numFormat !== undefined && res.numFormat == -1 ){
                adjustCellFormat(__cell,__cell.sFormula);
            }
        }
4925
	}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
4926
};
4927
Woorksheet.prototype._ReBuildFormulas=function(cellRange){
4928 4929 4930
	/*
		Если существуют трехмерные ссылки на ячейки, то у них необходимо поменять имя листа на новое после переименования листа.
	*/
4931
	var c, ca;
4932
	for(var i in cellRange){
4933 4934 4935 4936
		ca = new CellAddress(i);
		c = this._getCellNoEmpty(ca.getRow0(),ca.getCol0());
		
		if( c && c.formulaParsed && c.formulaParsed.is3D ){
4937 4938 4939
			c.setFormula(c.formulaParsed.assemble());
		}
	}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
4940
};
4941
Woorksheet.prototype.renameDependencyNodes = function(offset, oBBox, rec, noDelete){
4942
	this.workbook.dependencyFormulas.checkOffset(oBBox, offset, this.Id, noDelete);
4943
};
4944 4945 4946 4947
Woorksheet.prototype.getAllCol = function(){
	if(null == this.oAllCol)
		this.oAllCol = new Col(this, g_nAllColIndex);
	return this.oAllCol;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
4948
};
4949
Woorksheet.prototype.getAllRow = function(){
4950 4951 4952 4953
    if (null == this.oSheetFormatPr.oAllRow) {
        this.oSheetFormatPr.oAllRow = new Row(this);
        this.oSheetFormatPr.oAllRow.create(g_nAllRowIndex + 1);
    }
4954
	return this.oSheetFormatPr.oAllRow;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
4955
};
4956
Woorksheet.prototype.getHyperlinkByCell = function(row, col){
4957 4958 4959
	var oHyperlink = this.hyperlinkManager.getByCell(row, col);
	return oHyperlink ? oHyperlink.data : null;
};
4960
Woorksheet.prototype.getMergedByCell = function(row, col){
4961 4962 4963
	var oMergeInfo = this.mergeManager.getByCell(row, col);
	return oMergeInfo ? oMergeInfo.bbox : null;
};
4964 4965 4966
Woorksheet.prototype.getMergedByRange = function(bbox){
	return this.mergeManager.get(bbox);
};
4967 4968 4969 4970 4971 4972 4973
Woorksheet.prototype._expandRangeByMergedAddToOuter = function(aOuter, range, aMerged){
	for(var i = 0, length = aMerged.all.length; i < length; i++)
	{
		var elem = aMerged.all[i];
		if(!range.containsRange(elem.bbox))
			aOuter.push(elem);
	}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
4974
};
4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989
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)
	{
		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)
		{
			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}));
		}
	}
	return aOuter;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
4990
};
4991 4992 4993
Woorksheet.prototype.expandRangeByMerged = function(range){
	if(null != range)
	{
4994 4995
		var aOuter = this._expandRangeByMergedGetOuter(range);
		if(aOuter.length > 0)
4996 4997
		{
			range = range.clone();
4998
			while(aOuter.length > 0)
4999
			{
5000 5001 5002
				for(var i = 0, length = aOuter.length; i < length; i++)
					range.union2(aOuter[i].bbox);
				aOuter = this._expandRangeByMergedGetOuter(range);
5003 5004 5005 5006
			}
		}
	}
	return range;
5007
};
5008 5009 5010 5011
Woorksheet.prototype.createTablePart = function(){
	
	return new TablePart(this.handlers);
};
5012 5013 5014 5015 5016 5017
//-------------------------------------------------------------------------------------------------
/**
 * @constructor
 */
function Cell(worksheet){
	this.ws = worksheet;
5018
	this.oValue = new CCellValue();
5019
	this.xfs = null;
5020 5021 5022
	this.tableXfs = null;
	this.conditionalFormattingXfs = null;
	this.compiledXfs = null;
5023 5024
	this.nRow = -1;
	this.nCol = -1;
5025
	this.sFormula = null;
5026
	this.sFormulaCA = null;
5027
	this.formulaParsed = null;
5028
}
5029
Cell.prototype.getStyle=function(){
5030 5031 5032
	return this.xfs;
};
Cell.prototype.getCompiledStyle = function () {
5033
    if (null == this.compiledXfs && (null != this.xfs || null != this.tableXfs || null != this.conditionalFormattingXfs)) {
5034 5035 5036
        this.compileXfs();
    }
    return this.compiledXfs;
5037
};
5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058
Cell.prototype.compileXfs=function(){
	this.compiledXfs = null;
	if(null != this.xfs || null != this.tableXfs || null != this.conditionalFormattingXfs)
	{
		if(null != this.tableXfs)
			this.compiledXfs = this.tableXfs;
		if(null != this.xfs)
		{
			if(null != this.compiledXfs)
				this.compiledXfs = this.xfs.merge(this.compiledXfs);
			else
				this.compiledXfs = this.xfs;
		}
		if(null != this.conditionalFormattingXfs)
		{
			if(null != this.compiledXfs)
				this.compiledXfs = this.conditionalFormattingXfs.merge(this.compiledXfs);
			else
				this.compiledXfs = this.xfs;
		}
	}
5059
};
5060 5061 5062 5063
Cell.prototype.clone=function(oNewWs){
    if(!oNewWs)
        oNewWs = this.ws;
	var oNewCell = new Cell(oNewWs);
5064
	oNewCell.nRow = this.nRow;
5065
	oNewCell.nCol = this.nCol;
5066 5067
	if(null != this.xfs)
		oNewCell.xfs = this.xfs.clone();
5068
	oNewCell.oValue = this.oValue.clone();
5069 5070 5071 5072
	if(null != this.sFormula)
		oNewCell.sFormula = this.sFormula;
	return oNewCell;
};
5073
Cell.prototype.create=function(xfs, nRow, nCol){
5074
	this.xfs = xfs;
5075 5076
	this.nRow = nRow;
	this.nCol = nCol;
5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096
};
Cell.prototype.isEmptyText=function(){
	if(false == this.oValue.isEmpty())
		return false;
	if(null != this.sFormula)
		return false;
	return true;
};
Cell.prototype.isEmptyTextString=function(){
	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.sFormula ? true : false;
5097
};
5098 5099 5100 5101
Cell.prototype.Remove=function(){
	this.ws._removeCell(null, null, this);
};
Cell.prototype.getName=function(){
5102
	return g_oCellAddressUtils.getCellId(this.nRow, this.nCol);
5103
};
5104 5105
Cell.prototype.cleanCache=function(){
	this.oValue.cleanCache();
5106
};
5107 5108 5109
Cell.prototype.setFormula=function(val, bAddToHistory){
	if(bAddToHistory)
	{
5110
		History.Add( g_oUndoRedoWorksheet, historyitem_Worksheet_RemoveCellFormula, this.ws.getId(), new Asc.Range( this.nCol, this.nRow, this.nCol, this.nRow ), new UndoRedoData_CellSimpleData( this.nRow, this.nCol, null, null, this.sFormula ));
5111
	}
5112 5113
	this.sFormula = val;
	this.oValue.cleanCache();
5114
};
5115
Cell.prototype.setValue=function(val,callback, isCopyPaste){
5116 5117 5118 5119
	var ret = true;
	var DataOld = null;
	if(History.Is_On())
		DataOld = this.getValueData();
5120 5121 5122 5123 5124 5125 5126 5127 5128 5129
	var bIsTextFormat = false;
	if(!isCopyPaste){
		var sNumFormat;
		if(null != this.xfs && null != this.xfs.num)
			sNumFormat = this.xfs.num.f;
		else
			sNumFormat = g_oDefaultNum.f;
		var numFormat = oNumFormatCache.get(sNumFormat);
		bIsTextFormat = numFormat.isTextFormat();
	}
5130 5131
	var wb = this.ws.workbook;
	var ws = this.ws;
5132
	if(false == bIsTextFormat)
5133 5134 5135 5136 5137 5138
	{
		/*
			Устанавливаем значение в Range ячеек. При этом происходит проверка значения на формулу.
			Если значение является формулой, то проверяем содержиться ли в ячейке формула или нет, если "да" - то очищаем в графе зависимостей список, от которых зависит формула(masterNodes), позже будет построен новый. Затем выставляем флаг о необходимости дальнейшего пересчета, и заносим ячейку в список пересчитываемых ячеек.
		*/
		if( null != val && val[0] == "=" && val.length > 1){
5139 5140 5141 5142 5143

            var oldFP = undefined;

            if( this.formulaParsed  )
                oldFP = this.formulaParsed;
5144 5145
			var cellId = g_oCellAddressUtils.getCellId(this.nRow, this.nCol);
            this.formulaParsed = new parserFormula(val.substring(1),cellId,this.ws);
5146
			if( !this.formulaParsed.parse(true,true) ){
5147 5148 5149
				switch( this.formulaParsed.error[this.formulaParsed.error.length-1] ){
					case c_oAscError.ID.FrmlWrongFunctionName:
						break;
5150
                    case c_oAscError.ID.FrmlParenthesesCorrectCount:
5151
                        this.setValue("="+this.formulaParsed.Formula, callback, isCopyPaste);
5152
                        return;
5153 5154 5155 5156
					default :{
						wb.handlers.trigger("asc_onError",this.formulaParsed.error[this.formulaParsed.error.length-1], c_oAscError.Level.NoCritical);
						if( callback )
							callback(false);
5157 5158 5159
                        if( oldFP !== undefined ){
                            this.formulaParsed = oldFP;
                        }
5160 5161 5162 5163 5164
						return;
					}
				}
			}
			else{
5165
				val = "="+this.formulaParsed.assemble();
5166
			}
5167

5168
		}
5169 5170 5171
        else{
            this.formulaParsed = null;
        }
5172 5173 5174
	}
	//удаляем старые значения
	this.oValue.clean();
5175
	var sheetId = this.ws.getId();
5176
	var cellId = g_oCellAddressUtils.getCellId(this.nRow, this.nCol);
5177
	if (this.sFormula)
5178
		wb.dependencyFormulas.deleteMasterNodes2( ws.Id, cellId );
5179
	if( !(null != val && val[0] != "=" || true == bIsTextFormat))
5180
		addToArrRecalc(this.ws.getId(), this);
5181
	wb.needRecalc.nodes[getVertexId(sheetId,cellId)] = [sheetId, cellId];
5182
    wb.needRecalc.length++;
5183
	
5184 5185 5186
	this.sFormula = null;
	this.setFormulaCA(false);
	if(val){
5187
		if(false == bIsTextFormat && val[0] == "=" && val.length > 1){
5188 5189 5190
			this.setFormula( val.substring(1) );
		}
		else {
5191
			this.oValue.setValue(this, val);
5192
            this.formulaParsed = null;
5193 5194
		}
	}
5195 5196 5197 5198
	var DataNew = null;
	if(History.Is_On())
		DataNew = this.getValueData();
	if(History.Is_On() && false == DataOld.isEqual(DataNew))
5199
	    History.Add(g_oUndoRedoCell, 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));
5200
    if ( this.ws.workbook.isNeedCacheClean ){
5201 5202 5203
		/*
			Если необходим пересчет, то по списку пересчитываемых ячеек сортируем граф зависимостей и пересчиываем в получившемся порядке. Плохим ячейкам с цикличискими ссылками выставляем ошибку "#REF!".
		*/
5204
        //sortDependency вызывается ниже History.Add(historyitem_Cell_ChangeValue, потому что в ней может быть выставлен формат ячейки(если это текстовый, то принимая изменения формула станет текстом)
5205
		sortDependency(this.ws.workbook,true);
5206
	}
5207 5208 5209
	//todo не должны удаляться ссылки, если сделать merge ее части.
	if(this.isEmptyTextString())
	{
5210
		var cell = this.ws.getCell3(this.nRow, this.nCol);
5211 5212
		cell.removeHyperlink();
	}
5213 5214 5215 5216 5217 5218 5219
	return ret;
};
Cell.prototype.setValue2=function(array){
	var DataOld = null;
	if(History.Is_On())
		DataOld = this.getValueData();
	//[{text:"",format:TextFormat},{}...]
5220 5221
	this.setValueCleanFormula();
    this.oValue.clean();
5222
    this.oValue.setValue2(this, array);
5223
    sortDependency(this.ws.workbook);
5224 5225 5226 5227
	var DataNew = null;
	if(History.Is_On())
		DataNew = this.getValueData();
	if(History.Is_On() && false == DataOld.isEqual(DataNew))
5228
		History.Add(g_oUndoRedoCell, 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));
5229 5230 5231
	//todo не должны удаляться ссылки, если сделать merge ее части.
	if(this.isEmptyTextString())
	{
5232
		var cell = this.ws.getCell3(this.nRow, this.nCol);
5233 5234
		cell.removeHyperlink();
	}
5235
};
5236 5237 5238 5239 5240
Cell.prototype.setValueCleanFormula = function (array) {
    //удаляем сторое значение
    var ws = this.ws;
    var wb = this.ws.workbook;
    var sheetId = this.ws.getId();
5241
    var cellId = g_oCellAddressUtils.getCellId(this.nRow, this.nCol);
5242 5243 5244 5245 5246 5247 5248 5249 5250
    if (this.sFormula)
        wb.dependencyFormulas.deleteMasterNodes2(ws.Id, cellId);

    this.sFormula = null;
    this.formulaParsed = null;
    this.setFormulaCA(false);

    wb.needRecalc.nodes[getVertexId(sheetId, cellId)] = [sheetId, cellId];
    wb.needRecalc.length++;
5251
};
5252
Cell.prototype.setType=function(type){
5253 5254 5255 5256
	if(type != this.oValue.type){
		var DataOld = this.getValueData();
		this.oValue.setValueType(type);
		var DataNew = this.getValueData();
5257
		History.Add(g_oUndoRedoCell, 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));
5258 5259
	}
	return this.oValue.type;
5260 5261 5262 5263
};
Cell.prototype.getType=function(){
	return this.oValue.type;
};
5264
Cell.prototype.setCellStyle=function(val){
5265 5266
	var newVal = this.ws.workbook.CellStyles._prepareCellStyle(val);
	var oRes = this.ws.workbook.oStyleManager.setCellStyle(this, newVal);
5267
	if(History.Is_On()) {
5268
		var oldStyleName = this.ws.workbook.CellStyles.getStyleNameByXfId(oRes.oldVal);
5269
		History.Add(g_oUndoRedoCell, 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));
5270 5271

		// Выставляем стиль
5272
		var oStyle = this.ws.workbook.CellStyles.getStyleByXfId(oRes.newVal);
5273 5274 5275 5276 5277 5278 5279 5280
		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());
5281
	}
5282
	this.compiledXfs = null;
5283 5284
	this.oValue.cleanCache();
};
5285
Cell.prototype.setNumFormat=function(val){
5286
	var oRes;
5287
    /*if( val == aStandartNumFormats[0] &&
5288 5289
        this.formulaParsed && this.formulaParsed.value && this.formulaParsed.value.numFormat !== null &&
        this.formulaParsed.value.numFormat !== undefined && aStandartNumFormats[this.formulaParsed.value.numFormat] )
5290
        oRes = this.ws.workbook.oStyleManager.setNumFormat(this, aStandartNumFormats[this.formulaParsed.value.numFormat]);
5291
    else*/
5292
        oRes = this.ws.workbook.oStyleManager.setNumFormat(this, val);
5293
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
5294
        History.Add(g_oUndoRedoCell, 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));
5295
	this.compiledXfs = null;
5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311
	this.oValue.cleanCache();
};
Cell.prototype.shiftNumFormat=function(nShift, dDigitsCount){
	var bRes = false;
	var bGeneral = true;
    var sNumFormat;
    if(null != this.xfs && null != this.xfs.num)
        sNumFormat = this.xfs.num.f;
    else
        sNumFormat = g_oDefaultNum.f;
	if("General" != sNumFormat)
	{
		var oCurNumFormat = oNumFormatCache.get(sNumFormat);
		if(null != oCurNumFormat && false == oCurNumFormat.isGeneralFormat())
		{
			bGeneral = false;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5312
			var output = {};
5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325
			bRes = oCurNumFormat.shiftFormat(output, nShift);
			if(true == bRes)
				this.setNumFormat(output.format);
		}
	}
	if(bGeneral)
	{
		if(CellValueType.Number == this.oValue.type)
		{
			var sGeneral = DecodeGeneralFormat(this.oValue.number, this.oValue.type, dDigitsCount);
			var oGeneral = oNumFormatCache.get(sGeneral);
			if(null != oGeneral && false == oGeneral.isGeneralFormat())
			{
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5326
				var output = {};
5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348
				bRes = oGeneral.shiftFormat(output, nShift);
				if(true == bRes)
					this.setNumFormat(output.format);
			}
		}
	}
	this.oValue.cleanCache();
	return bRes;
};
Cell.prototype.setFont=function(val, bModifyValue){
	if(false != bModifyValue)
	{
		//убираем комплексные строки
		if(null != this.oValue.multiText)
		{
			var oldVal = null;
			if(History.Is_On())
				oldVal = this.getValueData();
			this.oValue.makeSimpleText();
			if(History.Is_On())
			{
				var newVal = this.getValueData();
5349
				History.Add(g_oUndoRedoCell, 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));
5350 5351 5352
			}
		}
	}
5353
	var oRes = this.ws.workbook.oStyleManager.setFont(this, val);
5354 5355 5356 5357 5358 5359 5360 5361
    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();
5362
        History.Add(g_oUndoRedoCell, 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));
5363
	}
5364
	this.compiledXfs = null;
5365 5366 5367
	this.oValue.cleanCache();
};
Cell.prototype.setFontname=function(val){
5368
    var oRes = this.ws.workbook.oStyleManager.setFontname(this, val);
5369
	this.oValue.setFontname(this, val);
5370
	if(History.Is_On() && oRes.oldVal != oRes.newVal)
5371
		History.Add(g_oUndoRedoCell, 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));
5372
	this.compiledXfs = null;
5373 5374 5375
	this.oValue.cleanCache();
};
Cell.prototype.setFontsize=function(val){
5376
    var oRes = this.ws.workbook.oStyleManager.setFontsize(this, val);
5377
	this.oValue.setFontsize(this, val);
5378
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
5379
        History.Add(g_oUndoRedoCell, 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));
5380
	this.compiledXfs = null;
5381 5382 5383
	this.oValue.cleanCache();
};
Cell.prototype.setFontcolor=function(val){
5384
    var oRes = this.ws.workbook.oStyleManager.setFontcolor(this, val);
5385
	this.oValue.setFontcolor(this, val);
5386
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
5387
        History.Add(g_oUndoRedoCell, 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));
5388
	this.compiledXfs = null;
5389 5390 5391
	this.oValue.cleanCache();
};
Cell.prototype.setBold=function(val){
5392
    var oRes = this.ws.workbook.oStyleManager.setBold(this, val);
5393
	this.oValue.setBold(this, val);
5394
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
5395
        History.Add(g_oUndoRedoCell, 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));
5396
	this.compiledXfs = null;
5397 5398 5399
	this.oValue.cleanCache();
};
Cell.prototype.setItalic=function(val){
5400
    var oRes = this.ws.workbook.oStyleManager.setItalic(this, val);
5401
	this.oValue.setItalic(this, val);
5402
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
5403
        History.Add(g_oUndoRedoCell, 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));
5404
	this.compiledXfs = null;
5405 5406 5407
	this.oValue.cleanCache();
};
Cell.prototype.setUnderline=function(val){
5408
    var oRes = this.ws.workbook.oStyleManager.setUnderline(this, val);
5409
	this.oValue.setUnderline(this, val);
5410
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
5411
        History.Add(g_oUndoRedoCell, 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));
5412
	this.compiledXfs = null;
5413 5414 5415
	this.oValue.cleanCache();
};
Cell.prototype.setStrikeout=function(val){
5416
    var oRes = this.ws.workbook.oStyleManager.setStrikeout(this, val);
5417
	this.oValue.setStrikeout(this, val);
5418
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
5419
        History.Add(g_oUndoRedoCell, 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));
5420
	this.compiledXfs = null;
5421 5422 5423
	this.oValue.cleanCache();
};
Cell.prototype.setFontAlign=function(val){
5424
    var oRes = this.ws.workbook.oStyleManager.setFontAlign(this, val);
5425
	this.oValue.setFontAlign(this, val);
5426
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
5427
        History.Add(g_oUndoRedoCell, 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));
5428
	this.compiledXfs = null;
5429
	this.oValue.cleanCache();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5430
};
5431
Cell.prototype.setAlignVertical=function(val){
5432
	var oRes = this.ws.workbook.oStyleManager.setAlignVertical(this, val);
5433
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
5434
        History.Add(g_oUndoRedoCell, 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));
5435
	this.compiledXfs = null;
5436 5437
};
Cell.prototype.setAlignHorizontal=function(val){
5438
	var oRes = this.ws.workbook.oStyleManager.setAlignHorizontal(this, val);
5439
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
5440
        History.Add(g_oUndoRedoCell, 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));
5441
	this.compiledXfs = null;
5442 5443
};
Cell.prototype.setFill=function(val){
5444
	var oRes = this.ws.workbook.oStyleManager.setFill(this, val);
5445
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
5446
        History.Add(g_oUndoRedoCell, 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));
5447
	this.compiledXfs = null;
5448 5449
};
Cell.prototype.setBorder=function(val){
5450
	var oRes = this.ws.workbook.oStyleManager.setBorder(this, val);
5451 5452 5453 5454 5455 5456 5457
    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();
5458
        History.Add(g_oUndoRedoCell, 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));
5459
	}
5460
	this.compiledXfs = null;
5461 5462
};
Cell.prototype.setShrinkToFit=function(val){
5463
	var oRes = this.ws.workbook.oStyleManager.setShrinkToFit(this, val);
5464
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
5465
        History.Add(g_oUndoRedoCell, 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));
5466
	this.compiledXfs = null;
5467 5468
};
Cell.prototype.setWrap=function(val){
5469
	var oRes = this.ws.workbook.oStyleManager.setWrap(this, val);
5470
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
5471
        History.Add(g_oUndoRedoCell, 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));
5472
	this.compiledXfs = null;
5473 5474
};
Cell.prototype.setAngle=function(val){
5475
    var oRes = this.ws.workbook.oStyleManager.setAngle(this, val);
5476
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
5477
        History.Add(g_oUndoRedoCell, 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));
5478
    this.compiledXfs = null;
5479 5480
};
Cell.prototype.setVerticalText=function(val){
5481
    var oRes = this.ws.workbook.oStyleManager.setVerticalText(this, val);
5482
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
5483
        History.Add(g_oUndoRedoCell, 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));
5484
    this.compiledXfs = null;
5485 5486
};
Cell.prototype.setQuotePrefix=function(val){
5487
	var oRes = this.ws.workbook.oStyleManager.setQuotePrefix(this, val);
5488
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
5489
        History.Add(g_oUndoRedoCell, 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));
5490 5491
	this.oValue.cleanCache();
};
5492 5493
Cell.prototype.setConditionalFormattingStyle=function(xfs){
	this.conditionalFormattingXfs = xfs;
5494
	this.compiledXfs = null;
5495
	this.oValue.cleanCache();
5496
};
5497 5498 5499
Cell.prototype.getConditionalFormattingStyle = function (xfs) {
    return this.conditionalFormattingXfs;
};
5500 5501
Cell.prototype.setTableStyle=function(xfs){
	this.tableXfs = xfs;
5502
	this.compiledXfs = null;
5503
	this.oValue.cleanCache();
5504
};
5505
Cell.prototype.getTableStyle=function(){
5506 5507
    return this.tableXfs;
};
5508 5509 5510 5511 5512 5513 5514 5515 5516
Cell.prototype.setStyle=function(xfs){
	var oldVal = this.xfs;
	var newVal = null;
    this.xfs = null;
	if(null != xfs)
	{
        this.xfs = xfs.clone();
        newVal = this.xfs;
	}
5517
	this.compiledXfs = null;
5518 5519 5520 5521 5522 5523 5524
	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();
5525
		History.Add(g_oUndoRedoCell, 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));
5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536
	}
	// if(this.isEmpty())
		// this.Remove();
};
Cell.prototype.getFormula=function(){
	if(null != this.sFormula)
		return this.sFormula;
	else
		return "";
};
Cell.prototype.getValueForEdit=function(numFormat){
5537
	return this.oValue.getValueForEdit(this);
5538 5539
};
Cell.prototype.getValueForEdit2=function(numFormat){
5540
	return this.oValue.getValueForEdit2(this);
5541 5542 5543 5544 5545
};
Cell.prototype.getValueWithoutFormat=function(){
	return this.oValue.getValueWithoutFormat();
};
Cell.prototype.getValue=function(numFormat, dDigitsCount){
5546
	return this.oValue.getValue(this);
5547 5548 5549
};
Cell.prototype.getValue2=function(dDigitsCount, fIsFitMeasurer){
	if(null == fIsFitMeasurer)
5550
		fIsFitMeasurer = function(aText){return true;};
5551 5552
	if(null == dDigitsCount)
		dDigitsCount = gc_nMaxDigCountView;
5553
	return this.oValue.getValue2(this, dDigitsCount, fIsFitMeasurer);
5554 5555 5556 5557 5558
};
Cell.prototype.getNumFormatStr=function(){
	if(null != this.xfs && null != this.xfs.num)
            return this.xfs.num.f;
	return g_oDefaultNum.f;
5559
};
5560 5561 5562 5563 5564 5565
Cell.prototype.getNumFormat=function(){
    return oNumFormatCache.get(this.getNumFormatStr());
};
Cell.prototype.getNumFormatType=function(){
    return this.getNumFormat().getType();
};
5566
Cell.prototype.moveHor=function(val){
5567
	this.nCol += val;
5568 5569
};
Cell.prototype.moveVer=function(val){
5570
	this.nRow += val;
5571 5572
};
Cell.prototype.getOffset=function(cell){
5573
	return {offsetCol:(this.nCol - cell.nCol), offsetRow:(this.nRow - cell.nRow)};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5574
};
5575
Cell.prototype.getOffset2=function(cellId){
5576
	var cAddr2 = new CellAddress(cellId);
5577
	return {offsetCol:(this.nCol - cAddr2.col + 1), offsetRow:(this.nRow - cAddr2.row + 1)};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5578
};
5579
Cell.prototype.getOffset3=function(cellAddr){
5580
	var cAddr2 = cellAddr;
5581
	return {offsetCol:(this.nCol - cAddr2.col + 1), offsetRow:(this.nRow - cAddr2.row + 1)};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5582
};
5583
Cell.prototype.getValueData = function(){
5584
	return new UndoRedoData_CellValueData(this.sFormula, this.oValue.clone());
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5585
};
5586 5587 5588 5589 5590 5591
Cell.prototype.setValueData = function(Val){
	//значения устанавляваются через setValue, чтобы пересчитались формулы
	if(null != Val.formula)
		this.setValue("=" + Val.formula);
	else if(null != Val.value)
	{
5592 5593 5594 5595
	    var DataOld = null;
	    var DataNew = null;
	    if (History.Is_On())
	        DataOld = this.getValueData();
5596 5597 5598
	    this.setValueCleanFormula();
	    this.oValue = Val.value.clone(this);
	    sortDependency(this.ws.workbook);
5599 5600 5601
	    if (History.Is_On()) {
	        DataNew = this.getValueData();
	        if (false == DataOld.isEqual(DataNew))
5602
	            History.Add(g_oUndoRedoCell, 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));
5603 5604
	    }
    }
5605 5606
	else
		this.setValue("");
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5607
};
5608 5609
Cell.prototype.setFormulaCA = function(ca){
	if(ca) this.sFormulaCA = true;
5610
	else if( this.sFormulaCA ) this.sFormulaCA = null;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5611
};
5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622
//-------------------------------------------------------------------------------------------------

/**
 * @constructor
 */
function Range(worksheet, r1, c1, r2, c2){
	this.worksheet = worksheet;
	this.bbox = new Asc.Range(c1, r1, c2, r2);
	//first last устарели, не убраны только для совместимости
	this.first = new CellAddress(this.bbox.r1, this.bbox.c1, 0);
	this.last = new CellAddress(this.bbox.r2, this.bbox.c2, 0);
5623
}
5624 5625 5626 5627
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;
5628
};
5629 5630 5631 5632
Range.prototype.clone=function(oNewWs){
	if(!oNewWs)
		oNewWs = this.worksheet;
	return new Range(oNewWs, this.bbox.r1, this.bbox.c1, this.bbox.r2, this.bbox.c2);
5633
};
5634 5635
Range.prototype.getFirst=function(){
	return this.first;
5636
};
5637 5638
Range.prototype.getLast=function(){
	return this.last;
5639
};
5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651
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
5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665
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);
				var oRes = action(oCurCell, i, j, oBBox.r1, oBBox.c1);
				if(null != oRes)
					return oRes;
			}
		}
	}
};
5666 5667 5668 5669 5670 5671 5672 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 5716 5717 5718 5719 5720
Range.prototype._foreachNoEmpty=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);
				if(null != oCurCell)
				{
					var oRes = action(oCurCell, i, j, oBBox.r1, oBBox.c1);
					if(null != oRes)
						return oRes;
				}
			}
		}
	}
};
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);
		if(row)
		{
			if(null != actionRow)
				actionRow(row);
			if(null != actionCell)
			{
				for(var j in row.c){
					var oCurCell = row.c[j];
					if(null != oCurCell)
						actionCell(oCurCell, i, j - 0, oBBox.r1, oBBox.c1);
				}
			}
		}
	}
};
Range.prototype._foreachRowNoEmpty=function(actionRow, actionCell){
	var oBBox = this.bbox;
	if(0 == oBBox.r1 && gc_nMaxRow0 == oBBox.r2)
	{
		var aRows = this.worksheet._getRows();
		for(var i in aRows)
		{
			var row = aRows[i];
			if( null != actionRow )
			{
				var oRes = actionRow(row);
				if(null != oRes)
					return oRes;
			}
			if( null != actionCell )
				for(var j in row.c){
					var oCurCell = row.c[j];
					if(null != oCurCell)
					{
5721
						var oRes = actionCell(oCurCell, i - 0, j - 0, oBBox.r1, oBBox.c1);
5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779
						if(null != oRes)
							return oRes;
					}
				}
		}
	}
	else
	{
		var minR = Math.min(oBBox.r2,this.worksheet.getRowsCount());
		for(var i = oBBox.r1; i <= minR; i++){
			var row = this.worksheet._getRowNoEmpty(i);
			if(row)
			{
				if( null != actionRow )
				{
					var oRes = actionRow(row);
					if(null != oRes)
						return oRes;
				}
				if( null != actionCell )
					for(var j in row.c){
						var oCurCell = row.c[j];
						if(null != oCurCell)
						{
							var oRes = actionCell(oCurCell, i, j - 0, oBBox.r1, oBBox.c1);
							if(null != oRes)
								return oRes;
						}
					}
			}
		}
	}
};
Range.prototype._foreachCol=function(actionCol, actionCell){
	var oBBox = this.bbox;
	if(null != actionCol)
	{
		for(var i = oBBox.c1; i <= oBBox.c2; ++i)
		{
			var col = this.worksheet._getCol(i);
			if(null != col)
				actionCol(col);
		}
	}
	if(null != actionCell)
	{
		var aRows = this.worksheet._getRows();
		for(var i in aRows)
		{
			var row = aRows[i];
			if(row)
			{
				if(0 == oBBox.c1 && gc_nMaxCol0 == oBBox.c2)
				{
					for(var j in row.c)
					{
						var oCurCell = row.c[j];
						if(null != oCurCell)
5780
							actionCell(oCurCell, i - 0, j - 0, oBBox.r1, oBBox.c1);
5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834
					}
				}
				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);
					}
				}
			}
		}
	}
};
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)
	{
		if(null != actionCol)
		{
			var aCols = this.worksheet._getCols();
			for(var i in aCols)
			{
				var nIndex = i - 0;
				if(nIndex >= oBBox.c1 && nIndex <= minC )
				{
					var col = this.worksheet._getColNoEmpty(nIndex);
					if(null != col)
					{
						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 in row.c)
					{
						var nIndex = j - 0;
						if(nIndex >= oBBox.c1 && nIndex <= minC)
						{
							var oCurCell = row.c[j];
							if(null != oCurCell)
							{
5835
								var oRes = actionCell(oCurCell, i - 0, nIndex, oBBox.r1, oBBox.c1);
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 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896
								if(null != oRes)
									return oRes;
							}
						}
					}
				}
			}
		}
	}
	else
	{
		if(null != actionCol)
		{
			for(var i = oBBox.c1; i <= minC; ++i)
			{
				var col = this.worksheet._getColNoEmpty(i);
				if(null != col)
				{
					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)
					{
						var oCurCell = row.c[j];
						if(null != oCurCell)
						{
							var oRes = actionCell(oCurCell, i - 0, j, oBBox.r1, oBBox.c1);
							if(null != oRes)
								return oRes;
						}
					}
				}
			}
		}
	}
};
Range.prototype._foreachIndex=function(action){
	var oBBox = this.bbox;
	for(var i = oBBox.r1; i <= oBBox.r2; i++){
		for(var j = oBBox.c1; j <= oBBox.c2; j++){
			var res = action(i, j);
			if(null != res)
				return res;
		}
	}
	return null;
};
Range.prototype._getRangeType=function(oBBox){
	if(null == oBBox)
		oBBox = this.bbox;
5897
	return getRangeType(oBBox);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5898
};
5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913
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);
	else
	{
		//сюда не должны заходить вообще
		// this._foreachRow(actionRow, actionCell);
		// if(null != actionCol)
			// this._foreachCol(actionCol, null);
	}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5914
};
5915 5916 5917
Range.prototype._setPropertyNoEmpty=function(actionRow, actionCol, actionCell){
	var nRangeType = this._getRangeType();
	if(c_oRangeType.Range == nRangeType)
5918
		return this._foreachNoEmpty(actionCell);
5919
	else if(c_oRangeType.Row == nRangeType)
5920
		return this._foreachRowNoEmpty(actionRow, actionCell);
5921
	else if(c_oRangeType.Col == nRangeType)
5922
		return this._foreachColNoEmpty(actionCol, actionCell);
5923 5924
	else
	{
5925 5926 5927 5928
		var oRes = this._foreachRowNoEmpty(actionRow, actionCell);
		if(null != oRes && null != actionCol)
			oRes = this._foreachColNoEmpty(actionCol, null);
		return oRes;
5929
	}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5930
};
5931 5932 5933 5934
Range.prototype.containCell=function(cellId){
	var cellAddress = cellId;
	return 	cellAddress.getRow0() >= this.bbox.r1 && cellAddress.getCol0() >= this.bbox.c1 &&
			cellAddress.getRow0() <= this.bbox.r2 && cellAddress.getCol0() <= this.bbox.c2;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5935
};
5936 5937 5938 5939
Range.prototype.containCell2=function(cell){
	return 	cell.nRow >= this.bbox.r1 && cell.nCol >= this.bbox.c1 &&
			cell.nRow <= this.bbox.r2 && cell.nCol <= this.bbox.c2;
};
5940 5941 5942 5943 5944 5945 5946 5947
Range.prototype.cross = function(cellAddress){

	if( cellAddress.getRow0() >= this.bbox.r1 && cellAddress.getRow0() <= this.bbox.r2 && this.bbox.c1 == this.bbox.c2)
		return {r:cellAddress.getRow()};
	if( cellAddress.getCol0() >= this.bbox.c1 && cellAddress.getCol0() <= this.bbox.c2 && this.bbox.r1 == this.bbox.r2)
		return {c:cellAddress.getCol()};

	return undefined;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5948
};
5949 5950 5951 5952 5953 5954 5955 5956
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();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5957
};
5958 5959 5960
Range.prototype.isOneCell=function(){
	var oBBox = this.bbox;
	return oBBox.r1 == oBBox.r2 && oBBox.c1 == oBBox.c2;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5961
};
5962 5963 5964 5965 5966
Range.prototype.isColumn = function(){
	if(this.first.getRow() == 1 && this.last.getRow() == gc_nMaxRow)
		return true;
	else
		return false;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5967
};
5968 5969 5970 5971 5972
Range.prototype.isRow = function(){
	if(this.first.getCol() == 1 && this.last.getCol() == gc_nMaxCol)
		return true;
	else
		return false;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5973
};
5974 5975 5976 5977 5978 5979 5980 5981 5982
Range.prototype.getBBox=function(){
	//1 - based
	return {r1: this.bbox.r1 + 1, r2: this.bbox.r2 + 1, c1: this.bbox.c1 + 1, c2: this.bbox.c2 + 1};
};
Range.prototype.getBBox0=function(){
	//0 - based
	return this.bbox;
};
Range.prototype.getName=function(){
5983
    return this.bbox.getName();
5984 5985
};
Range.prototype.getCells=function(){
Alexander.Trofimov's avatar
Alexander.Trofimov committed
5986
	var aResult = [];
5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997
	var oBBox = this.bbox;
	if(!((0 == oBBox.c1 && gc_nMaxCol0 == oBBox.c2) || (0 == oBBox.r1 && gc_nMaxRow0 == oBBox.r2)))
	{
		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));
			}
		}
	}
	return aResult;
};
5998
Range.prototype.setValue=function(val,callback, isCopyPaste){
5999 6000 6001
	History.Create_NewPoint();
	History.StartTransaction();
	this._foreach(function(cell){
6002
		cell.setValue(val,callback, isCopyPaste);
6003 6004 6005 6006 6007 6008 6009 6010
		// if(cell.isEmpty())
			// cell.Remove();
	});
	History.EndTransaction();
};
Range.prototype.setValue2=function(array){
	History.Create_NewPoint();
	History.StartTransaction();
6011
    //[{"text":"qwe","format":{"b":true, "i":false, "u":Asc.EUnderline.underlineNone, "s":false, "fn":"Arial", "fs": 12, "c": 0xff00ff, "va": "subscript"  }},{}...]
6012 6013 6014 6015 6016 6017 6018 6019 6020 6021
	/*
		Устанавливаем значение в Range ячеек. В отличае от setValue, сюда мы попадаем только в случае ввода значения отличного от формулы. Таким образом, если в ячейке была формула, то для нее в графе очищается список ячеек от которых зависела. После чего выставляем флаг о необходимости пересчета.
	*/
	this._foreach(function(cell){
		cell.setValue2(array);
		// if(cell.isEmpty())
			// cell.Remove();
	});
	History.EndTransaction();
};
6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043
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);
		});
};
6044 6045 6046 6047
Range.prototype.setTableStyle=function(val){
	this.createCellOnRowColCross();
	var fSetProperty = this._setProperty;
	var nRangeType = this._getRangeType();
6048
	if(c_oRangeType.All == nRangeType || null === val)
6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064
	{
		//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);
		});
};
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
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);
	});
	return bRes;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
6094
};
6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116
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);
	});
};
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 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240
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);
6241 6242 6243 6244 6245 6246 6247
        },
        function(col){
            col.setUnderline(val);
        },
        function(cell){
            cell.setUnderline(val);
        });
6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 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
};
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();
	if("none" == val)
		val = null;
	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);
	});
};
6361
Range.prototype.setBorderSrc=function(border){
6362 6363
	History.Create_NewPoint();
	History.StartTransaction();
6364 6365
	if (null == border)
		border = new Border();
6366 6367 6368 6369 6370
	this.createCellOnRowColCross();
	var fSetProperty = this._setProperty;
	var nRangeType = this._getRangeType();
	if(c_oRangeType.All == nRangeType)
	{
6371
		this.worksheet.getAllCol().setBorder(border.clone());
6372 6373 6374 6375 6376
		fSetProperty = this._setPropertyNoEmpty;
	}
	fSetProperty.call(this, function(row){
		if(c_oRangeType.All == nRangeType && null == row.xfs)
			return;
6377
		row.setBorder(border.clone());
6378 6379
	},
	function(col){
6380
		col.setBorder(border.clone());
6381 6382
	},
	function(cell){
6383
		cell.setBorder(border.clone());
6384 6385
	});
	History.EndTransaction();
6386
};
6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405
Range.prototype._setBorderMerge=function(bLeft, bTop, bRight, bBottom, oNewBorder, oCurBorder){
	var oTargetBorder = new Border();
	//не делаем clone для свойств потому у нас нельзя поменять свойство отдельное свойство border можно только применить border целиком
	if(bLeft)
		oTargetBorder.l = oNewBorder.l;
	else
		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;
6406
	oTargetBorder.d = oNewBorder.d;
6407 6408 6409 6410
	oTargetBorder.dd = oNewBorder.dd;
	oTargetBorder.du = oNewBorder.du;
	var oRes = null;
	if(null != oCurBorder)
6411
	{
6412 6413 6414 6415 6416 6417
		oCurBorder.mergeInner(oTargetBorder);
		oRes = oCurBorder;
	}
	else
		oRes = oTargetBorder;
	return oRes;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
6418
};
6419 6420 6421 6422 6423 6424 6425 6426
Range.prototype._setCellBorder=function(bbox, cell, oNewBorder){
	if(null == oNewBorder)
		cell.setBorder(oNewBorder);
	else
	{
		var oCurBorder = null;
        if(null != cell.xfs && null != cell.xfs.border)
			oCurBorder = cell.xfs.border.clone();
6427 6428
		else
			oCurBorder = g_oDefaultBorder.clone();
6429 6430
		var nRow = cell.nRow;
		var nCol = cell.nCol;
6431 6432
		cell.setBorder(this._setBorderMerge(nCol == bbox.c1, nRow == bbox.r1, nCol == bbox.c2, nRow == bbox.r2, oNewBorder, oCurBorder));
	}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
6433
};
6434 6435 6436 6437 6438 6439 6440 6441 6442 6443
Range.prototype._setRowColBorder=function(bbox, rowcol, bRow, oNewBorder){
	if(null == oNewBorder)
		rowcol.setBorder(oNewBorder);
	else
	{
		var oCurBorder = null;
		if(null != rowcol.xfs && null != rowcol.xfs.border)
			oCurBorder = rowcol.xfs.border.clone();
		var bLeft, bTop, bRight, bBottom = false;
		if(bRow)
6444
		{
6445 6446
			bTop = rowcol.index == bbox.r1;
			bBottom = rowcol.index == bbox.r2;
6447 6448 6449
		}
		else
		{
6450 6451
			bLeft = rowcol.index == bbox.c1;
			bRight = rowcol.index == bbox.c2;
6452
		}
6453 6454
		rowcol.setBorder(this._setBorderMerge(bLeft, bTop, bRight, bBottom, oNewBorder, oCurBorder));
	}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
6455
};
6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470
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;
		if(nCol == bbox.c1 - 1)
			oCurBorderProp = oCurBorder.r;
		else if(nRow == bbox.r1 - 1)
			oCurBorderProp = oCurBorder.b;
		else if(nCol == bbox.c2 + 1)
			oCurBorderProp = oCurBorder.l;
		else if(nRow == bbox.r2 + 1)
			oCurBorderProp = oCurBorder.t;
6471 6472 6473
		var oNewBorderProp = null;
		if(null == oNewBorder)
			oNewBorderProp = new BorderProp();
6474
		else
6475
		{
6476 6477 6478 6479 6480 6481 6482 6483
			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;
6484
		}
6485
		
6486
		if(null != oNewBorderProp && null != oCurBorderProp && c_oAscBorderStyles.None != oCurBorderProp.s && (null == oNewBorder || c_oAscBorderStyles.None != oNewBorderProp.s) &&
6487
			(oNewBorderProp.s != oCurBorderProp.s || oNewBorderProp.getRgbOrNull() != oCurBorderProp.getRgbOrNull())){
6488 6489
				var oTargetBorder = oCurBorder.clone();
				if(nCol == bbox.c1 - 1)
6490
					oTargetBorder.r = new BorderProp();
6491
				else if(nRow == bbox.r1 - 1)
6492
					oTargetBorder.b = new BorderProp();
6493
				else if(nCol == bbox.c2 + 1)
6494
					oTargetBorder.l = new BorderProp();
6495
				else if(nRow == bbox.r2 + 1)
6496
					oTargetBorder.t = new BorderProp();
6497
				oItemWithXfs.setBorder(oTargetBorder);
6498 6499
			}
	}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
6500
};
6501 6502 6503 6504 6505 6506 6507 6508 6509 6510
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)
6511
	{
6512 6513 6514
		var oAllCol = this.worksheet.getAllCol();
		_this._setRowColBorder(oBBox, oAllCol, false, border);
		fSetProperty = this._setPropertyNoEmpty;
6515
	}
6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543
	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);
6544 6545
		},
		function(col){
6546
			_this._setBorderEdge(oBBox, col, 0, col.index, border);
6547 6548
		},
		function(cell){
6549
			_this._setBorderEdge(oBBox, cell, cell.nRow, cell.nCol, border);
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 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640
		});
	}
};
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);
	});
};
6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652
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);
	});
};
6653 6654 6655 6656 6657 6658 6659
Range.prototype.getType=function(){
	var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1);
	if(null != cell)
		return cell.getType();
	else
		return null;
};
6660 6661 6662 6663 6664 6665 6666 6667
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;
};
6668 6669 6670 6671
Range.prototype.isFormula=function(){
	var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1);
	return (null != cell) ? cell.isFormula() : false;
};
6672 6673 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 6704 6705
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(null != 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);
6706
		oTempCell.create(xfs, this.bbox.r1, this.bbox.c1);
6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727
		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){
6728
    //[{"text":"qwe","format":{"b":true, "i":false, "u":Asc.EUnderline.underlineNone, "s":false, "fn":"Arial", "fs": 12, "c": 0xff00ff, "va": "subscript"  }},{}...]
6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741
	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(null != 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);
6742
		oTempCell.create(xfs, this.bbox.r1, this.bbox.c1);
6743 6744 6745
		return oTempCell.getValue2(dDigitsCount, fIsFitMeasurer);
	}
};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
6746 6747 6748 6749 6750
Range.prototype.getXfId=function(){
	var nRow = this.bbox.r1;
	var nCol = this.bbox.c1;
	var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
	if(null != cell) {
6751
	    var xfs = cell.getCompiledStyle();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764
		if(null != xfs && null != xfs.XfId)
			return xfs.XfId;
	} else {
		//стили столбов и колонок
		var row = this.worksheet._getRowNoEmpty(nRow);
		if(null != 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_oDefaultXfId;
};
6765
Range.prototype.getStyleName=function(){
6766 6767 6768 6769
	var res = this.worksheet.workbook.CellStyles.getStyleNameByXfId(this.getXfId());

	// ToDo убрать эту заглушку (нужно делать на открытии) в InitStyleManager
	return res || this.worksheet.workbook.CellStyles.getStyleNameByXfId(g_oDefaultXfId);
6770
};
6771 6772 6773 6774
Range.prototype.getTableStyle=function(){
    var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1);
    return cell ? cell.getTableStyle() : null;
};
6775 6776 6777 6778 6779 6780 6781 6782 6783
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)
    {
6784
	    var xfs = cell.getCompiledStyle();
6785 6786
        if(null != xfs && null != xfs.num)
            return xfs.num.f;
6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799
    }
	else
	{
		//стили столбов и колонок
		var row = this.worksheet._getRowNoEmpty(nRow);
		if(null != row && null != row.xfs && null != row.xfs.num)
			return row.xfs.num.f;
		var col = this.worksheet._getColNoEmptyWithAll(nCol);
		if(null != col && null != col.xfs && null != col.xfs.num)
			return col.xfs.num.f;
	}
    return g_oDefaultNum.f;
};
6800 6801
Range.prototype.getNumFormatType=function(){
	return this.getNumFormat().getType();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
6802
};
6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815
// Узнаем отличается ли шрифт (размер и гарнитура) в ячейке от шрифта в строке
Range.prototype.isNotDefaultFont = function () {
	// Получаем фонт ячейки
	var cellFont = this.getFont();
	var rowFont = g_oDefaultFont;
	var row = this.worksheet._getRowNoEmpty(this.bbox.r1);
	if (null != row && null != row.xfs && null != row.xfs.font)
		rowFont = row.xfs.font;
	else if (null != this.oAllCol)
		rowFont = this.oAllCol;

	return (cellFont.fn !== rowFont.fn || cellFont.fs !== rowFont.fs);
};
6816 6817 6818 6819 6820 6821
Range.prototype.getFont = function(){
	var nRow = this.bbox.r1;
	var nCol = this.bbox.c1;
	var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
	if(null != cell)
    {
6822
		var xfs = cell.getCompiledStyle();
6823 6824
        if(null != xfs && null != xfs.font)
            return xfs.font;
6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836
    }
	else
	{
		//стили столбов и колонок
		var row = this.worksheet._getRowNoEmpty(nRow);
		if(null != 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;
	}
    return g_oDefaultFont;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
6837
};
6838
Range.prototype.getFontname=function(){
6839
	return this.getFont().fn;
6840 6841
};
Range.prototype.getFontsize=function(){
6842
	return this.getFont().fs;
6843 6844
};
Range.prototype.getFontcolor=function(){
6845
	return this.getFont().c;
6846 6847
};
Range.prototype.getBold=function(){
6848
	return this.getFont().b;
6849 6850
};
Range.prototype.getItalic=function(){
6851
	return this.getFont().i;
6852 6853
};
Range.prototype.getUnderline=function(){
6854
	return this.getFont().u;
6855
};
6856
Range.prototype.getStrikeout=function(){
6857
	return this.getFont().s;
6858 6859
};
Range.prototype.getFontAlign=function(){
6860
	return this.getFont().va;
6861 6862 6863 6864 6865
};
Range.prototype.getQuotePrefix=function(){
	var nRow = this.bbox.r1;
	var nCol = this.bbox.c1;
	var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
6866 6867
	if(null != cell)
	{
6868
		var xfs = cell.getCompiledStyle();
6869 6870 6871
		if(null != xfs && null != xfs.QuotePrefix)
			return xfs.QuotePrefix;
	}
6872 6873 6874 6875 6876 6877 6878 6879
	return false;
};
Range.prototype.getAlignVertical=function(){
	var nRow = this.bbox.r1;
	var nCol = this.bbox.c1;
	var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
	if(null != cell)
    {
6880
		var xfs = cell.getCompiledStyle();
6881 6882 6883 6884 6885 6886 6887
        if(null != xfs)
		{
			if(null != xfs.align)
				return xfs.align.ver;
			else
				return g_oDefaultAlignAbs.ver;
		}
6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906
    }
	else
	{
		//стили столбов и колонок
		var row = this.worksheet._getRowNoEmpty(nRow);
		if(null != 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;
	}
    return g_oDefaultAlign.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)
    {
6907
		var xfs = cell.getCompiledStyle();
6908 6909 6910 6911 6912 6913 6914
        if(null != xfs)
		{
			if(null != xfs.align)
				return xfs.align.hor;
			else
				return g_oDefaultAlignAbs.hor;
		}
6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 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
    }
	else
	{
		//стили столбов и колонок
		var row = this.worksheet._getRowNoEmpty(nRow);
		if(null != 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_oDefaultAlign.hor;
};
Range.prototype.getAlignHorizontalByValue=function(){
	//возвращает Align в зависимости от значния в ячейке
	//values:  none, center, justify, left , right, null
	var align = this.getAlignHorizontal();
	if("none" == 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 = "left";break;
				case CellValueType.Bool:
				case CellValueType.Error:align = "center";break;
				default:
				//Если есть value и не проставлен тип значит это число, у всех остальных типов значение не null
				if(this.getValueWithoutFormat())
				{
					//смотрим 
					var oNumFmt = this.getNumFormat();
					if(true == oNumFmt.isTextFormat())
						align = "left";
					else
						align = "right";
				}
				else
					align = "left";
				break;
			}
		}
		if("none" == align)
			align = "left";
	}
	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)
    {
6969
		var xfs = cell.getCompiledStyle();
6970 6971
        if(null != xfs && null != xfs.fill)
            return xfs.fill.bg;
6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998
    }
	else
	{
		//стили столбов и колонок
		var row = this.worksheet._getRowNoEmpty(nRow);
		if(null != 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;
	}
    return g_oDefaultFill.bg;
};
Range.prototype.getBorderSrc=function(_cell){
	//Возвращает как записано в файле, не проверяя бордеры соседних ячеек
	//формат
	//\{"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
    if(null == _cell)
        _cell = this.getFirst();
 	var nRow = _cell.getRow0();
	var nCol = _cell.getCol0();
	var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
	if(null != cell)
    {
6999
		var xfs = cell.getCompiledStyle();
7000 7001
        if(null != xfs && null != xfs.border)
            return xfs.border;
7002 7003 7004 7005 7006 7007 7008 7009 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
    }
	else
	{
		//стили столбов и колонок
		var row = this.worksheet._getRowNoEmpty(nRow);
		if(null != 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;
	}
    return g_oDefaultBorder;
};
Range.prototype.getBorder=function(_cell){
	//_cell - optional
	//Возвращает как записано в файле, не проверяя бордеры соседних ячеек
	//формат
	//\{"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
    var oRes = this.getBorderSrc(_cell);
    if(null != oRes)
        return oRes;
    else
        return g_oDefaultBorder;
};
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
	var borders = this.getBorder(this.getFirst()).clone();
	var nRow = this.bbox.r1;
	var nCol = this.bbox.c1;    
7040
	if(c_oAscBorderStyles.None === borders.l.s){
7041
		if(nCol > 1){
7042
			var left = this.getBorder(new CellAddress(nRow, nCol - 1, 0));
7043
			if(c_oAscBorderStyles.None !== left.r.s)
7044 7045 7046
				borders.l = left.r;
		}
	}
7047
	if(c_oAscBorderStyles.None === borders.t.s){
7048
		if(nRow > 1){
7049
			var top = this.getBorder(new CellAddress(nRow - 1, nCol, 0));
7050
			if(c_oAscBorderStyles.None !== top.b.s)
7051 7052 7053
				borders.t = top.b;
		}
	}
7054
	if(c_oAscBorderStyles.None === borders.r.s){
7055
		var right = this.getBorder(new CellAddress(nRow, nCol + 1, 0));
7056
		if(c_oAscBorderStyles.None !== right.l.s)
7057 7058
			borders.r = right.l;
	}
7059
	if(c_oAscBorderStyles.None === borders.b.s){
7060
		var bottom = this.getBorder(new CellAddress(nRow + 1, nCol, 0));
7061
		if(c_oAscBorderStyles.None !== bottom.t.s)
7062 7063 7064 7065 7066 7067 7068 7069 7070 7071
			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)
    {
7072
		var xfs = cell.getCompiledStyle();
7073 7074 7075 7076 7077 7078 7079
        if(null != xfs)
		{
			if(null != xfs.align)
				return xfs.align.shrink;
			else
				return g_oDefaultAlignAbs.shrink;
		}
7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092
    }
	else
	{
		//стили столбов и колонок
		var row = this.worksheet._getRowNoEmpty(nRow);
		if(null != 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_oDefaultAlign.shrink;
};
7093 7094 7095 7096
Range.prototype.getWrapByAlign = function (align) {
	// Для justify wrap всегда true
	return "justify" === align.hor ? true : align.wrap;
};
7097 7098 7099 7100
Range.prototype.getWrap=function(){
	var nRow = this.bbox.r1;
	var nCol = this.bbox.c1;
	var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
7101
	if(null != cell) {
7102
		var xfs = cell.getCompiledStyle();
7103
        if(null != xfs) {
7104
			if(null != xfs.align)
7105
				return this.getWrapByAlign(xfs.align);
7106
			else
7107
				return this.getWrapByAlign(g_oDefaultAlignAbs);
7108
		}
7109
    } else {
7110 7111 7112
		//стили столбов и колонок
		var row = this.worksheet._getRowNoEmpty(nRow);
		if(null != row && null != row.xfs && null != row.xfs.align)
7113
			return this.getWrapByAlign(row.xfs.align);
7114 7115
		var col = this.worksheet._getColNoEmptyWithAll(nCol);
		if(null != col && null != col.xfs && null != col.xfs.align)
7116
			return this.getWrapByAlign(col.xfs.align);
7117
	}
7118
    return this.getWrapByAlign(g_oDefaultAlign);
7119 7120 7121 7122 7123 7124 7125 7126
};
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)
    {
7127
		var xfs = cell.getCompiledStyle();
7128 7129 7130 7131 7132 7133 7134
        if(null != xfs)
		{
			if(null != xfs.align)
				return angleFormatToInterface(xfs.align.angle);
			else
				return angleFormatToInterface(g_oDefaultAlignAbs.angle);
		}
7135 7136 7137 7138 7139 7140
    }
	else
	{
		//стили столбов и колонок
		var row = this.worksheet._getRowNoEmpty(nRow);
		if(null != row && null != row.xfs && null != row.xfs.align)
7141
			return angleFormatToInterface(row.xfs.align.angle);
7142 7143
		var col = this.worksheet._getColNoEmptyWithAll(nCol);
		if(null != col && null != col.xfs && null != col.xfs.align)
7144
			return angleFormatToInterface(col.xfs.align.angle);
7145
	}
7146
    return angleFormatToInterface(g_oDefaultAlign.angle);
7147 7148 7149 7150 7151 7152 7153
};
Range.prototype.getVerticalText=function(){
	var nRow = this.bbox.r1;
	var nCol = this.bbox.c1;
	var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
	if(null != cell)
    {
7154
		var xfs = cell.getCompiledStyle();
7155 7156 7157 7158 7159 7160 7161
        if(null != xfs)
		{
			if(null != xfs.align)
				return g_nVerticalTextAngle == xfs.align.angle;
			else
				return g_nVerticalTextAngle == g_oDefaultAlignAbs.angle;
		}
7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173
    }
	else
	{
		//стили столбов и колонок
		var row = this.worksheet._getRowNoEmpty(nRow);
		if(null != row && null != row.xfs && null != row.xfs.align)
			return g_nVerticalTextAngle == row.xfs.align.angle;
		var col = this.worksheet._getColNoEmptyWithAll(nCol);
		if(null != col && null != col.xfs && null != col.xfs.align)
			return g_nVerticalTextAngle == col.xfs.align.angle;
	}
    return g_nVerticalTextAngle == g_oDefaultAlign.angle;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
7174
};
7175
Range.prototype.hasMerged=function(){
7176 7177 7178
	var aMerged = this.worksheet.mergeManager.get(this.bbox);
	if(aMerged.all.length > 0)
		return aMerged.all[0].bbox;
7179 7180 7181
	return null;
};
Range.prototype.mergeOpen=function(){
7182
	this.worksheet.mergeManager.add(this.bbox, 1);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
7183
};
7184 7185 7186 7187 7188
Range.prototype.merge=function(type){
	if(null == type)
		type = c_oAscMergeOptions.Merge;
	var oBBox = this.bbox;
	History.Create_NewPoint();
7189 7190 7191 7192 7193 7194 7195
	History.StartTransaction();	
	if(oBBox.r1 == oBBox.r2 && oBBox.c1 == oBBox.c2){
		if(type == c_oAscMergeOptions.MergeCenter)
			this.setAlignHorizontal("center");
		History.EndTransaction();
		return;
	}
7196 7197 7198
	if(this.hasMerged())
	{
		this.unmerge();
7199 7200 7201 7202 7203 7204 7205
		if(type == c_oAscMergeOptions.MergeCenter)
		{
			//сбрасываем AlignHorizontal
			this.setAlignHorizontal("none");
			History.EndTransaction();
			return;
		}
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 7253 7254 7255
	}
	//пробегаемся по границе диапазона, чтобы посмотреть какие границы нужно оставлять
	var oLeftBorder = null;
	var oTopBorder = null;
	var oRightBorder = null;
	var oBottomBorder = null;
	var nRangeType = this._getRangeType(oBBox);
	if(c_oRangeType.Range == nRangeType)
	{
		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;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
7256
		};
7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300
		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);
	}
	else if(c_oRangeType.Row == nRangeType)
	{
		var oTopRow = this.worksheet._getRowNoEmpty(oBBox.r1);
		if(null != oTopRow && null != oTopRow.xfs && null != oTopRow.xfs.border && false == oTopRow.xfs.border.t.isEmpty())
			oTopBorder = oTopRow.xfs.border.t;
		if(oBBox.r1 != oBBox.r2)
		{
			var oBottomRow = this.worksheet._getRowNoEmpty(oBBox.r2);
			if(null != oBottomRow && null != oBottomRow.xfs && null != oBottomRow.xfs.border && false == oBottomRow.xfs.border.b.isEmpty())
				oBottomBorder = oBottomRow.xfs.border.b;
		}
	}
	else
	{
		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)
		{
			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();
7301 7302
			oFirstCellRow = cell.nRow;
			oFirstCellCol = cell.nCol;
7303

7304
		}
7305
		if(nRow0 == nRowStart && nCol0 == nColStart)
7306 7307
			oLeftTopCellStyle = cell.getStyle();
	});
7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332
	//правила работы с гиперссылками во время 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)
		{
			var oNewHyperlink = elem.data.clone();
			oNewHyperlink.Ref.setOffset({offsetCol:oBBox.c1 - oFirstCellCol, offsetRow:oBBox.r1 - oFirstCellRow});
			aHyperlinksToRestore.push(oNewHyperlink);
		}
		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);
	}
	this.cleanAll();
	//восстанавливаем hyperlink
	for(var i = 0, length = aHyperlinksToRestore.length; i < length; i++)
	{
		var elem = aHyperlinksToRestore[i];
		this.worksheet.hyperlinkManager.add(elem.Ref.getBBox0(), elem);
	}
7333 7334 7335 7336 7337 7338 7339 7340 7341
	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)
		{
7342
			var oLeftTopRange = this.worksheet.getCell3(oBBox.r1, oBBox.c1);
7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 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 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 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 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502
			oLeftTopRange.setHyperlink(oFirstCellHyperlink, true);
		}
	}
	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 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 == c_oAscMergeOptions.MergeCenter)
		this.setAlignHorizontal("center");
7503
	if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges)
7504
		this.worksheet.mergeManager.add(this.bbox, 1);
7505 7506 7507
	History.EndTransaction();
};
Range.prototype.unmerge=function(bOnlyInRange){
7508 7509
	History.Create_NewPoint();
	History.StartTransaction();
7510
	if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges)
7511
		this.worksheet.mergeManager.remove(this.bbox);
7512
	History.EndTransaction();
7513
};
7514
Range.prototype._getHyperlinks=function(){
7515 7516 7517 7518 7519
	var nRangeType = this._getRangeType();
	var result = [];
	var oThis = this;
	if(c_oRangeType.Range == nRangeType)
	{
7520 7521 7522
		var oTempRows = {};
		var fAddToTempRows = function(oTempRows, bbox, data){
			if(null != bbox)
7523
			{
7524 7525 7526 7527
				for(var i = bbox.r1; i <= bbox.r2; i++)
				{
					var row = oTempRows[i];
					if(null == row)
7528
					{
7529 7530
						row = {};
						oTempRows[i] = row;
7531
					}
7532
					for(var j = bbox.c1; j <= bbox.c2; j++)
7533
					{
7534 7535 7536
						var cell = row[j];
						if(null == cell)
							row[j] = data;
7537
					}
7538
				}
7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554
			}
		};
		//todo возможно надо сделать оптимизацию для скрытых строк
		var aHyperlinks = this.worksheet.hyperlinkManager.get(this.bbox);
		for(var i = 0, length = aHyperlinks.all.length; i < length; i++)
		{
			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++)
			{
				var merge = aMerged.all[j];
				var mergeBBox = merge.bbox.intersectionSimple(this.bbox);
				fAddToTempRows(oTempRows, mergeBBox, hyp.data);
7555
			}
7556
		}
7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570
		//формируем результат
		for(var i in oTempRows)
		{
			var nRowIndex = i - 0;
			var row = oTempRows[i];
			for(var j in row)
			{
				var nColIndex = j - 0;
				var oCurHyp = row[j];
				result.push({hyperlink: oCurHyp, col: nColIndex, row: nRowIndex});
			}
		}
	}
	return result;
7571
};
7572
Range.prototype.getHyperlink=function(){
7573
	var aHyperlinks = this._getHyperlinks();
7574 7575 7576 7577 7578
	if(null != aHyperlinks && aHyperlinks.length > 0)
		return aHyperlinks[0].hyperlink;
	return null;
};
Range.prototype.getHyperlinks=function(){
7579
	return this._getHyperlinks();
7580
};
7581 7582 7583
Range.prototype.setHyperlinkOpen=function(val){
	if(null != val && false == val.isValid())
		return;
7584
	this.worksheet.hyperlinkManager.add(val.Ref.getBBox0(), val);
7585
};
7586 7587 7588
Range.prototype.setHyperlink=function(val, bWithoutStyle){
	if(null != val && false == val.isValid())
		return;
7589
	//проверяем, может эта ссылка уже существует
7590
    var i, length, hyp;
7591
	var bExist = false;
7592
	var aHyperlinks = this.worksheet.hyperlinkManager.get(this.bbox);
7593
	for(i = 0, length = aHyperlinks.all.length; i < length; i++)
7594
	{
7595
		hyp = aHyperlinks.all[i];
7596
		if(hyp.data.isEqual(val))
7597 7598 7599 7600 7601
		{
			bExist = true;
			break;
		}
	}
7602 7603 7604 7605
	if(false == bExist)
	{
		History.Create_NewPoint();
		History.StartTransaction();
7606
		if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges)
7607
		{
7608
			//удаляем ссылки с тем же адресом
7609
			for(i = 0, length = aHyperlinks.all.length; i < length; i++)
7610
			{
7611
				hyp = aHyperlinks.all[i];
7612
				if(hyp.bbox.isEqual(this.bbox))
7613
					this.worksheet.hyperlinkManager.removeElement(hyp);
7614
			}
7615
		}
7616
		//todo перейти на CellStyle
7617
		if(true != bWithoutStyle)
7618 7619 7620 7621
		{
			var oHyperlinkFont = new Font();
			oHyperlinkFont.fn = this.worksheet.workbook.getDefaultFont();
			oHyperlinkFont.fs = this.worksheet.workbook.getDefaultSize();
7622
			oHyperlinkFont.u = Asc.EUnderline.underlineSingle;
7623 7624 7625
			oHyperlinkFont.c = g_oColorManager.getThemeColor(g_nColorHyperlink);
			this.setFont(oHyperlinkFont);
		}
7626
		if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges)
7627
			this.worksheet.hyperlinkManager.add(val.Ref.getBBox0(), val);
7628
		History.EndTransaction();
7629 7630
	}
};
7631
Range.prototype.removeHyperlink = function (val, removeStyle) {
7632 7633
	var bbox = this.bbox;
	var elem = null;
7634 7635
	if(null != val)
	{
7636 7637
		bbox = val.Ref.getBBox0();
		elem = new RangeDataManagerElem(bbox, val);
7638
	}
7639
	if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges)
7640
	{
7641 7642 7643
	    History.Create_NewPoint();
	    History.StartTransaction();
	    var oChangeParam = { removeStyle: removeStyle };
7644
		if(null != elem)
7645
		    this.worksheet.hyperlinkManager.removeElement(elem, oChangeParam);
7646
		else
7647 7648
		    this.worksheet.hyperlinkManager.remove(bbox, !bbox.isOneCell(), oChangeParam);
		History.EndTransaction();
7649
	}
7650
};
7651 7652
Range.prototype.deleteCellsShiftUp=function(preDeleteAction){
	return this._shiftUpDown(true, preDeleteAction);
7653 7654 7655 7656 7657 7658
};
Range.prototype.addCellsShiftBottom=function(){
	return this._shiftUpDown(false);
};
Range.prototype.addCellsShiftRight=function(){
	return this._shiftLeftRight(false);
7659
};
7660 7661
Range.prototype.deleteCellsShiftLeft=function(preDeleteAction){
	return this._shiftLeftRight(true, preDeleteAction);
7662
};
7663
Range.prototype._canShiftLeftRight=function(bLeft){
7664
	var aColsToDelete = [], aCellsToDelete = [];
7665 7666 7667
	var oBBox = this.bbox;
	var nRangeType = this._getRangeType(oBBox);
	if(c_oRangeType.Range != nRangeType && c_oRangeType.Col != nRangeType)
7668 7669 7670
		return null;

	var nWidth = oBBox.c2 - oBBox.c1 + 1;
7671 7672
	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);
7673 7674 7675 7676 7677 7678 7679
		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;

7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695
		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);
			}
		}, 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);
			}
		});
		if(bError)
7696
			return null;
7697
	}
7698
	return {aColsToDelete: aColsToDelete, aCellsToDelete: aCellsToDelete};
7699
};
7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716
Range.prototype._shiftLeftRight=function(bLeft, preDeleteAction){
	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]);

7717 7718 7719
	var oBBox = this.bbox;
	var nWidth = oBBox.c2 - oBBox.c1 + 1;
	var nRangeType = this._getRangeType(oBBox);
7720
	var mergeManager = this.worksheet.mergeManager;
7721
	lockDraw(this.worksheet.workbook);
7722
	//todo вставить предупреждение, что будет unmerge
7723 7724
	History.Create_NewPoint();
	History.StartTransaction();
7725 7726
	var oShiftGet = null;
	if (false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges))
7727
	{
7728 7729
	    History.LocalChange = true;
		oShiftGet = mergeManager.shiftGet(this.bbox, true);
7730 7731
		var aMerged = oShiftGet.elems;
		if(null != aMerged.outer && aMerged.outer.length > 0)
7732
		{
7733
			var bChanged = false;
7734
			for(i = 0, length = aMerged.outer.length; i < length; i++)
7735
			{
7736 7737 7738
				var elem = aMerged.outer[i];
				if(!(elem.bbox.c1 < oShiftGet.bbox.c1 && oShiftGet.bbox.r1 <= elem.bbox.r1 && elem.bbox.r2 <= oShiftGet.bbox.r2))
				{
7739
					mergeManager.removeElement(elem);
7740 7741
					bChanged = true;
				}
7742
			}
7743 7744
			if(bChanged)
				oShiftGet = null;
7745
		}
7746
		History.LocalChange = false;
7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762
	}
	//сдвигаем ячейки
	if(bLeft)
	{
		if(c_oRangeType.Range == nRangeType)
			this.worksheet._shiftCellsLeft(oBBox);
		else
			this.worksheet._removeCols(oBBox.c1, oBBox.c2);
	}
	else
	{
		if(c_oRangeType.Range == nRangeType)
			this.worksheet._shiftCellsRight(oBBox);
		else
			this.worksheet._insertColsBefore(oBBox.c1, nWidth);
	}
7763
	if (false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges))
7764
	{
7765
	    History.LocalChange = true;
7766 7767
		mergeManager.shift(this.bbox, !bLeft, true, oShiftGet);
		this.worksheet.hyperlinkManager.shift(this.bbox, !bLeft, true);
7768
		History.LocalChange = false;
7769
	}
7770
	History.EndTransaction();
7771 7772
    buildRecalc(this.worksheet.workbook);
    unLockDraw(this.worksheet.workbook);
7773 7774
	return true;
};
7775
Range.prototype._canShiftUpDown=function(bUp){
7776
	var aRowsToDelete = [], aCellsToDelete = [];
7777 7778 7779
	var oBBox = this.bbox;
	var nRangeType = this._getRangeType(oBBox);
	if(c_oRangeType.Range != nRangeType && c_oRangeType.Row != nRangeType)
7780 7781 7782
		return null;

	var nHeight = oBBox.r2 - oBBox.r1 + 1;
7783 7784
	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);
7785 7786 7787 7788 7789 7790 7791
		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;

7792 7793
		var bError = rangeEdge._setPropertyNoEmpty(function(row){
			if(null != row){
7794
				if(null != row.xfs && null != row.xfs.fill && null != row.xfs.fill.getRgbOrNull())
7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807
					return true;
				aRowsToDelete.push(row);
			}
		}, 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);
			}
		});
		if(bError)
7808
			return null;
7809
	}
7810
	return {aRowsToDelete: aRowsToDelete, aCellsToDelete: aCellsToDelete};
7811
};
7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828
Range.prototype._shiftUpDown = function (bUp, preDeleteAction) {
	var canShiftRes = this._canShiftUpDown(bUp);
	if(null === canShiftRes)
		return false;

	if (preDeleteAction)
		preDeleteAction();

	//удаляем крайние колонки и ячейки
	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]);

7829 7830 7831
	var oBBox = this.bbox;
	var nHeight = oBBox.r2 - oBBox.r1 + 1;
	var nRangeType = this._getRangeType(oBBox);
7832
	var mergeManager = this.worksheet.mergeManager;
7833
	lockDraw(this.worksheet.workbook);
7834
	//todo вставить предупреждение, что будет unmerge
7835 7836
	History.Create_NewPoint();
	History.StartTransaction();
7837 7838
	var oShiftGet = null;
	if (false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges))
7839
	{
7840 7841
	    History.LocalChange = true;
		oShiftGet = mergeManager.shiftGet(this.bbox, false);
7842 7843 7844 7845
		var aMerged = oShiftGet.elems;
		if(null != aMerged.outer && aMerged.outer.length > 0)
		{	
			var bChanged = false;
7846
			for(i = 0, length = aMerged.outer.length; i < length; i++)
7847
			{
7848 7849 7850
				var elem = aMerged.outer[i];
				if(!(elem.bbox.r1 < oShiftGet.bbox.r1 && oShiftGet.bbox.c1 <= elem.bbox.c1 && elem.bbox.c2 <= oShiftGet.bbox.c2))
				{
7851
					mergeManager.removeElement(elem);
7852 7853
					bChanged = true;
				}
7854
			}
7855 7856
			if(bChanged)
				oShiftGet = null;
7857
		}
7858
		History.LocalChange = false;
7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874
	}
	//сдвигаем ячейки
	if(bUp)
	{
		if(c_oRangeType.Range == nRangeType)
			this.worksheet._shiftCellsUp(oBBox);
		else
			this.worksheet._removeRows(oBBox.r1, oBBox.r2);
	}
	else
	{
		if(c_oRangeType.Range == nRangeType)
			this.worksheet._shiftCellsBottom(oBBox);
		else
			this.worksheet._insertRowsBefore(oBBox.r1, nHeight);
	}
7875
	if (false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges))
7876
	{
7877
	    History.LocalChange = true;
7878 7879
		mergeManager.shift(this.bbox, !bUp, false, oShiftGet);
		this.worksheet.hyperlinkManager.shift(this.bbox, !bUp, false);
7880
		History.LocalChange = false;
7881
	}
7882
	History.EndTransaction();
7883 7884
	buildRecalc(this.worksheet.workbook);
	unLockDraw(this.worksheet.workbook);
7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901
	return true;
};
Range.prototype.setOffset=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;
	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;
	this.first = new CellAddress(this.bbox.r1, this.bbox.c1, 0);
	this.last = new CellAddress(this.bbox.r2, this.bbox.c2, 0);
7902
};
7903 7904 7905 7906 7907 7908 7909 7910
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;
	this.first = new CellAddress(this.bbox.r1, this.bbox.c1, 0);
7911
};
7912 7913 7914 7915 7916 7917 7918 7919
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;
	this.last = new CellAddress(this.bbox.r2, this.bbox.c2, 0);
7920
};
7921 7922 7923 7924 7925 7926 7927 7928 7929 7930
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;
7931
};
7932 7933 7934 7935
Range.prototype.cleanCache=function(){
	this._setPropertyNoEmpty(null,null,function(cell, nRow0, nCol0, nRowStart, nColStart){
		cell.cleanCache();
	});
7936
};
7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954
Range.prototype.cleanFormat=function(){
	History.Create_NewPoint();
	History.StartTransaction();
	this.unmerge();
	this._setPropertyNoEmpty(function(row){
		row.setStyle(null);
		// if(row.isEmpty())
			// row.Remove();
	},function(col){
		col.setStyle(null);
		// if(col.isEmpty())
			// col.Remove();
	},function(cell, nRow0, nCol0, nRowStart, nColStart){
		cell.setStyle(null);
		// if(cell.isEmpty())
			// cell.Remove();
	});
	History.EndTransaction();
7955
};
7956 7957 7958 7959 7960 7961 7962 7963 7964 7965
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();
7966
};
7967 7968 7969 7970
Range.prototype.cleanAll=function(){
	History.Create_NewPoint();
	History.StartTransaction();
	this.unmerge();
7971 7972 7973 7974
	//удаляем только гиперссылки, которые полностью лежат в области
	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);
7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986
	var oThis = this;
	this._setPropertyNoEmpty(function(row){
		row.setStyle(null);
		// if(row.isEmpty())
			// row.Remove();
	},function(col){
		col.setStyle(null);
		// if(col.isEmpty())
			// col.Remove();
	},function(cell, nRow0, nCol0, nRowStart, nColStart){
		oThis.worksheet._removeCell(nRow0, nCol0);
	});
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
7987
	buildRecalc(this.worksheet.workbook);
7988
	History.EndTransaction();
7989
};
7990 7991 7992 7993 7994 7995 7996 7997 7998
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();
};
7999 8000
Range.prototype.sort=function(nOption, nStartCol){
	//todo горизонтальная сортировка
8001 8002
	var aMerged = this.worksheet.mergeManager.get(this.bbox);
	if(aMerged.outer.length > 0 || (aMerged.inner.length > 0 && null == this._isSameSizeMerged(this.bbox, aMerged.inner)))
8003
		return null;
8004 8005 8006 8007 8008 8009 8010 8011 8012
	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;
	}
	lockDraw(this.worksheet.workbook);
8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034
	var oRes = null;
	var oThis = this;
	var bAscent = false;
	if(nOption == c_oAscSortOptions.Ascending)
		bAscent = true;
	var nRowFirst0 = this.bbox.r1;
	var nRowLast0 = this.bbox.r2;
	var nColFirst0 = this.bbox.c1;
	var nColLast0 = this.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){
8035
			var nCurCol0 = cell.nCol;
8036 8037 8038 8039 8040
			if(nCurCol0 > nLastCol0)
				nLastCol0 = nCurCol0;
		});
	}
	//собираем массив обьектов для сортировки
Alexander.Trofimov's avatar
Alexander.Trofimov committed
8041
	var aSortElems = [];
Alexander.Trofimov's avatar
Alexander.Trofimov committed
8042
	var aHiddenRow = {};
8043 8044 8045 8046 8047
	var fAddSortElems = function(oCell, nRow0, nCol0,nRowStart0, nColStart0){
		//не сортируем сткрытие строки
		var row = oThis.worksheet._getRowNoEmpty(nRow0);
		if(null != row)
		{
8048
			if(0 != (g_nRowFlag_hd & row.flags))
8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094
				aHiddenRow[nRow0] = 1;
			else
			{
				if(nLastRow0 < nRow0)
					nLastRow0 = nRow0;
				var val = oCell.getValueWithoutFormat();
				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});
				}
			}
		}
	};
	if(nColFirst0 == nStartCol)
	{
		while(0 == aSortElems.length && nStartCol <= nLastCol0)
		{
			if(false == bWholeCol)
				oRangeCol._foreachNoEmpty(fAddSortElems);
			else
				oRangeCol._foreachColNoEmpty(null, fAddSortElems);
			if(0 == aSortElems.length)
			{
				nStartCol++;
				oRangeCol = this.worksheet.getRange(new CellAddress(nRowFirst0, nStartCol, 0), new CellAddress(nRowLast0, nStartCol, 0));
			}
		}
	}
	else
	{
		if(false == bWholeCol)
			oRangeCol._foreachNoEmpty(fAddSortElems);
		else
			oRangeCol._foreachColNoEmpty(null, fAddSortElems);
	}
	function strcmp ( str1, str2 ) {
			return ( ( str1 == str2 ) ? 0 : ( ( str1 > str2 ) ? 1 : -1 ) );
		}
	aSortElems.sort(function(a, b){
8095
		var res = 0;
8096 8097 8098
		if(null != a.text)
		{
			if(null != b.text)
8099
				res = strcmp(a.text.toUpperCase(), b.text.toUpperCase());
8100 8101 8102 8103 8104 8105 8106 8107 8108 8109
			else
				res = 1;
		}
		else if(null != a.num)
		{
			if(null != b.num)
				res = a.num - b.num;
			else
				res = -1;
		}
8110 8111 8112 8113 8114
		if(0 == res)
			res = a.row - b.row;
		else if(!bAscent)
			res = -res;
		return res;
8115 8116
	});
	//проверяем что это не пустая операция
Alexander.Trofimov's avatar
Alexander.Trofimov committed
8117
	var aSortData = [];
8118
	var nHiddenCount = 0;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
8119
	var oFromArray = {};
8120 8121 8122 8123 8124 8125
	var nRowMax = 0;
	var nRowMin = gc_nMaxRow0;
	var nToMax = 0;
	for(var i = 0, length = aSortElems.length; i < length; ++i)
	{
		var item = aSortElems[i];
8126
		var nNewIndex = i * nMergedHeight + nRowFirst0 + nHiddenCount;
8127 8128 8129
		while(null != aHiddenRow[nNewIndex])
		{
			nHiddenCount++;
8130
			nNewIndex = i * nMergedHeight + nRowFirst0 + nHiddenCount;
8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165
		}
		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)
	{
		//добавляем индексы перехода пустых ячеек(нужно для сортировки комментариев)
		for(var i = nRowMin; i <= nRowMax; ++i)
		{
			if(null == oFromArray[i] && null == aHiddenRow[i])
			{
				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);
				}
			}
		}
		History.Create_NewPoint();
8166 8167 8168 8169 8170 8171 8172 8173
		var oSelection = History.GetSelection();
		if(null != oSelection)
		{
			oSelection = oSelection.clone();
			oSelection.assign(nColFirst0, nRowFirst0, nLastCol0, nLastRow0);
			History.SetSelection(oSelection);
			History.SetSelectionRedo(oSelection);
		}
8174 8175 8176
		var oUndoRedoBBox = new UndoRedoData_BBox({r1:nRowFirst0, c1:nColFirst0, r2:nLastRow0, c2:nLastCol0});
		oRes = new UndoRedoData_SortData(oUndoRedoBBox, aSortData);
		History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_Sort, this.worksheet.getId(), new Asc.Range(0, nRowFirst0, gc_nMaxCol0, nLastRow0), oRes);
8177
		this._sortByArray(oUndoRedoBBox, aSortData);
8178
	}
8179
    buildRecalc(this.worksheet.workbook);
8180
    unLockDraw(this.worksheet.workbook);
8181
	return oRes;
8182
};
8183
Range.prototype._sortByArray=function(oBBox, aSortData, bUndo){
8184
    var rec = {length:0};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
8185
	var oSortedIndexes = {};
8186 8187 8188 8189 8190
	for(var i = 0, length = aSortData.length; i < length; ++i)
	{
		var item = aSortData[i];
		var nFrom = item.from;
		var nTo = item.to;
8191
		if(true == this.worksheet.workbook.bUndoChanges)
8192 8193 8194 8195 8196 8197
		{
			nFrom = item.to;
			nTo = item.from;
		}
		oSortedIndexes[nFrom] = nTo;
	}
8198
	//сортируются только одинарные гиперссылки, все неодинарные оставляем
Alexander.Trofimov's avatar
Alexander.Trofimov committed
8199
	var aSortedHyperlinks = [];
8200
	if(false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges))
8201
	{
8202
	    History.LocalChange = true;
8203 8204
		var aHyperlinks = this.worksheet.hyperlinkManager.get(this.bbox);
		for(var i = 0, length = aHyperlinks.inner.length; i < length; i++)
8205
		{
8206 8207 8208
			var elem = aHyperlinks.inner[i];
			var hyp = elem.data;
			if(hyp.Ref.isOneCell())
8209
			{
8210 8211 8212 8213 8214 8215
				var nFrom = elem.bbox.r1;
				var nTo = oSortedIndexes[nFrom];
				if(null != nTo)
				{
					//удаляем ссылки, а не перемеаем, чтобы не было конфликтов(например в случае если все ячейки имеют ссылки и их надо передвинуть)
					var oTempBBox = hyp.Ref.getBBox0();
8216
					this.worksheet.hyperlinkManager.removeElement(new RangeDataManagerElem(oTempBBox, hyp));
8217 8218 8219 8220
					var oNewHyp = hyp.clone();
					oNewHyp.Ref.setOffset({offsetCol: 0, offsetRow: nTo - nFrom});
					aSortedHyperlinks.push(oNewHyp);
				}
8221 8222
			}
		}
8223
		History.LocalChange = false;
8224
	}
8225 8226 8227 8228 8229 8230
	//окончательно устанавливаем ячейки
	var nColFirst0 = oBBox.c1;
	var nLastCol0 = oBBox.c2;
	for(var i = nColFirst0; i <= nLastCol0; ++i)
	{
		//запоминаем ячейки в которые уже что-то передвинули, чтобы не потерять их
Alexander.Trofimov's avatar
Alexander.Trofimov committed
8231
		var oTempCellsTo = {};
8232 8233 8234 8235 8236 8237 8238 8239 8240 8241
		for(var j in oSortedIndexes)
		{
			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))
8242 8243
				oCurCell = oTempCellsTo[nIndexFrom];
			else{
8244
				oCurCell = rowFrom.c[i];
8245 8246
				delete rowFrom.c[i];
			}
8247 8248 8249 8250 8251 8252 8253 8254
			oTempCellsTo[nIndexTo] = rowTo.c[i];
			if(null != oCurCell)
			{
				var lastName = oCurCell.getName();
				oCurCell.moveVer(shift);
				rowTo.c[i] = oCurCell;
				if(oCurCell.sFormula)
				{
8255
					var sNewName = oCurCell.getName();
8256
					oCurCell.setFormula(oCurCell.formulaParsed.changeOffset({offsetCol:0, offsetRow:shift}).assemble());//получаем новую формулу, путем сдвига входящих в нее ссылок на ячейки на offsetCol и offsetRow. не путать с shiftCells - меняет одну конкретную ячейку в формуле, changeOffset - меняет оффсет для всех входящих в формулу ячеек.
8257
					this.worksheet.workbook.dependencyFormulas.deleteMasterNodes2( this.worksheet.Id, lastName );//разрываем ссылки между старой ячейкой и ведущими ячейками для нее.
8258
					addToArrRecalc(this.worksheet.getId(), oCurCell);
8259
				}
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
8260
				}
8261 8262 8263 8264 8265 8266 8267 8268 8269 8270
			else
			{
				if(null != rowTo.c[i])
				{
					//здесь достаточно простого delete, потому что на самом деле в функции ячейки только меняются местами, удаления не происходит
					delete rowTo.c[i];
				}
			}
		}
	}
8271 8272 8273 8274 8275 8276 8277 8278 8279 8280
	var aNodes = this.worksheet.workbook.dependencyFormulas.getInRange( this.worksheet.Id, new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2) );
	if(aNodes && aNodes.length > 0)
	{
		for(var i = 0, length = aNodes.length; i < length; ++i)
		{
			var node = aNodes[i];
			this.worksheet.workbook.needRecalc.nodes[ node.nodeId ] = [ node.sheetId, node.cellId ];
			this.worksheet.workbook.needRecalc.length++;
		}
	}
8281

8282 8283
	if (this.worksheet.workbook.isNeedCacheClean)
		sortDependency(this.worksheet.workbook);
8284
	if(false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges))
8285
	{
8286
	    History.LocalChange = true;
8287 8288
		//восстанавливаем удаленые гиперссылки
		if(aSortedHyperlinks.length > 0)
8289
		{
8290 8291 8292 8293 8294
			for(var i = 0, length = aSortedHyperlinks.length; i < length; i++)
			{
				var hyp = aSortedHyperlinks[i];
				this.worksheet.hyperlinkManager.add(hyp.Ref.getBBox0(), hyp);
			}
8295
		}
8296
		History.LocalChange = false;
8297
	}
8298
};
8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318
Range.prototype._isSameSizeMerged=function(bbox, aMerged){
	var oRes = null;
	var nWidth = null;
	var nHeight = null;
	for(var i = 0, length = aMerged.length; i < length; i++)
	{
		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;
		}
8319
	}
8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 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
	if(null != nWidth && null != nHeight)
	{
		//проверяем что merge ячеки полностью заполняют область
		var nBBoxWidth = bbox.c2 - bbox.c1 + 1;
		var nBBoxHeight = bbox.r2 - bbox.r1 + 1;
		if(nBBoxWidth == nWidth || nBBoxHeight == nHeight)
		{
			var bRes = false;
			var aRowColTest = null;
			if(nBBoxWidth == nWidth && nBBoxHeight == nHeight)
				bRes = true;
			else if(nBBoxWidth == nWidth)
			{
				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;
				}
			}
			else if(nBBoxHeight == nHeight)
			{
				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;
				}
			}
			if(null != aRowColTest)
			{
				var bExistNull = false;
				for(var i = 0, length = aRowColTest.length; i < length; i++)
				{
					if(null == aRowColTest[i])
					{
						bExistNull = true;
						break;
					}
				}
				if(!bExistNull)
					bRes = true;
			}
			if(bRes)
				oRes = {width: nWidth, height: nHeight};
		}
	}
	return oRes;
8370
};
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8371
Range.prototype._canPromote=function(from, to, bIsPromote, nWidth, nHeight, bVertical, nIndex){
8372 8373
	var oRes = {oMergedFrom: null, oMergedTo: null};
	//если надо только удалить внутреннее содержимое не смотрим на замерженость
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8374
	if(!bIsPromote || !((true == bVertical && nIndex >= 0 && nIndex < nHeight) || (false == bVertical && nIndex >= 0 && nIndex < nWidth)))
8375
	{
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8376 8377
		if(null != to){
			var oMergedTo = this.worksheet.mergeManager.get(to);
8378 8379 8380 8381
			if(oMergedTo.outer.length > 0)
				oRes = null;
			else
			{
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8382
				var oMergedFrom = this.worksheet.mergeManager.get(from);
8383 8384 8385
				oRes.oMergedFrom = oMergedFrom;				
				if(oMergedTo.inner.length > 0)
				{
8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397
				    oRes.oMergedTo = oMergedTo;
				    if (bIsPromote) {
				        if (oMergedFrom.inner.length > 0) {
				            //merge области должны иметь одинаковый размер
				            var oSizeFrom = this._isSameSizeMerged(from, oMergedFrom.inner);
				            var oSizeTo = this._isSameSizeMerged(to, oMergedTo.inner);
				            if (!(null != oSizeFrom && null != oSizeTo && oSizeTo.width == oSizeFrom.width && oSizeTo.height == oSizeFrom.height))
				                oRes = null;
				        }
				        else
				            oRes = null;
				    }
8398 8399 8400 8401 8402
				}
			}
		}
	}
	return oRes;
8403
};
8404 8405 8406 8407
// Подготовка Copy Style
Range.prototype.preparePromoteFromTo = function (from, to) {
	var bSuccess = true;
	if (to.isOneCell())
8408
		to.setOffsetLast({offsetCol: (from.c2 - from.c1) - (to.c2 - to.c1), offsetRow: (from.r2 - from.r1) - (to.r2 - to.r1)});
8409 8410

	if(!from.isIntersect(to)) {
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8411 8412 8413 8414
		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);
8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430
		bSuccess = (bFromWholeCol === bToWholeCol && bFromWholeRow === bToWholeRow);
	} else
		bSuccess = false;
	return bSuccess;
};
// Перед promoteFromTo обязательно должна быть вызывана функция preparePromoteFromTo
Range.prototype.promoteFromTo=function(from, to){
	var bVertical = true;
	var nIndex = 1;
	//проверяем можно ли осуществить promote
	var oCanPromote = this._canPromote(from, to, false, 1, 1, bVertical, nIndex);
	if(null != oCanPromote)
	{
		History.Create_NewPoint();
		var oSelection = History.GetSelection();
		if(null != oSelection)
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8431
		{
8432 8433 8434 8435 8436 8437 8438 8439 8440 8441
			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);
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8442
		}
8443 8444 8445
		//удаляем merge ячейки в to(после _canPromote должны остаться только inner)
		this.worksheet.mergeManager.remove(to, true);
		this._promoteFromTo(from, to, false, oCanPromote, false, bVertical, nIndex);
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8446
	}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
8447
};
8448
Range.prototype.promote=function(bCtrl, bVertical, nIndex){
8449
	//todo отдельный метод для promote в таблицах и merge в таблицах
8450 8451 8452 8453 8454 8455 8456 8457 8458
	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))
8459
		return false;
8460 8461 8462
	var oPromoteAscRange = null;
	if(0 == nIndex)
		oPromoteAscRange = Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2);
8463 8464
	else
	{
8465 8466 8467 8468 8469 8470 8471 8472 8473
		if(bVertical)
		{
			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);
			}
8474
			else
8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485
				oPromoteAscRange = Asc.Range(oBBox.c1, oBBox.r1 + nIndex, oBBox.c2, oBBox.r1 - 1);
		}
		else
		{
			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);
			}
8486
			else
8487 8488
				oPromoteAscRange = Asc.Range(oBBox.c1 + nIndex, oBBox.r1, oBBox.c1 - 1, oBBox.r2);
		}
8489
	}
8490
	//проверяем можно ли осуществить promote
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8491
	var oCanPromote = this._canPromote(oBBox, oPromoteAscRange, true, nWidth, nHeight, bVertical, nIndex);
8492
	if(null == oCanPromote)
8493
		return false;
8494

8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513
	History.Create_NewPoint();
	var oSelection = History.GetSelection();
	if(null != oSelection)
	{
		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)
8514 8515 8516 8517 8518 8519
				{
					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);
				}
8520
				else
8521 8522 8523 8524 8525
					oSelectionRedo.assign(oBBox.c1, oBBox.r1 + nIndex, oBBox.c2, oBBox.r2);
			}
			else
			{
				if(nIndex > 0)
8526 8527 8528 8529 8530 8531
				{
					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);
				}
8532
				else
8533 8534 8535 8536 8537
					oSelectionRedo.assign(oBBox.c1 + nIndex, oBBox.r1, oBBox.c2, oBBox.r2);
			}
		}
		History.SetSelectionRedo(oSelectionRedo);
	}
8538
	this._promoteFromTo(oBBox, oPromoteAscRange, true, oCanPromote, bCtrl, bVertical, nIndex);
8539
	return true;
Alexander.Trofimov's avatar
Alexander.Trofimov committed
8540
};
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8541 8542
Range.prototype._promoteFromTo=function(from, to, bIsPromote, oCanPromote, bCtrl, bVertical, nIndex){
	lockDraw(this.worksheet.workbook);
8543
    History.StartTransaction();
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8544 8545 8546
	
	var toRange = this.worksheet.getRange3(to.r1, to.c1, to.r2, to.c2);
	var fromRange = this.worksheet.getRange3(from.r1, from.c1, from.r2, from.c2);
8547
	var bChangeRowColProp = false;
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8548
	var nLastCol = from.c2;
8549
	if (0 == from.c1 && gc_nMaxCol0 == from.c2)
8550
	{
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8551
		var aRowProperties = [];
8552
		nLastCol = 0;
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8553 8554
		fromRange._foreachRowNoEmpty(function(row){
			if(!row.isEmptyProp())
8555
				aRowProperties.push({index: row.index - from.r1, prop: row.getHeightProp(), style: row.getStyle()});
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8556
		}, function(cell){
8557
			var nCurCol0 = cell.nCol;
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8558 8559
			if(nCurCol0 > nLastCol)
				nLastCol = nCurCol0;
8560
		});
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8561 8562
		if(aRowProperties.length > 0)
		{
8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578
		    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 = this.worksheet._getRow(nCurIndex);
		                if (null != propElem.style)
		                    row.setStyle(propElem.style);
		                if (null != propElem.prop) {
		                    var oNewProps = propElem.prop;
		                    var oOldProps = row.getHeightProp();
8579
		                    if (false === oOldProps.isEqual(oNewProps)) {
8580
		                        row.setHeightProp(oNewProps);
8581
		                        History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_RowProp, this.worksheet.getId(), row._getUpdateRange(), new UndoRedoData_IndexSimpleProp(nCurIndex, true, oOldProps, oNewProps));
8582 8583 8584 8585 8586 8587 8588 8589
		                    }
		                }
		            }
		        }
		        nCurCount++;
		        if (nCurIndex > to.r2)
		            break;
		    }
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8590
		}
8591
	}
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8592
	var nLastRow = from.r2;
8593
	if (0 == from.r1 && gc_nMaxRow0 == from.r2)
8594
	{
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8595
		var aColProperties = [];
8596
		nLastRow = 0;
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8597 8598
		fromRange._foreachColNoEmpty(function(col){
			if(!col.isEmpty())
8599
			    aColProperties.push({ index: col.index - from.c1, prop: col.getWidthProp(), style: col.getStyle() });
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8600
		}, function(cell){
8601
			var nCurRow0 = cell.nRow;
8602 8603 8604
			if(nCurRow0 > nLastRow)
				nLastRow = nCurRow0;
		});
8605
		if (aColProperties.length > 0)
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8606
		{
8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637
		    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 = this.worksheet._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(g_oUndoRedoWorksheet, historyitem_Worksheet_ColProp, this.worksheet.getId(), new Asc.Range(nCurIndex, 0, nCurIndex, gc_nMaxRow0), new UndoRedoData_IndexSimpleProp(nCurIndex, false, oOldProps, oNewProps));
		                    }
		                }
		            }
		        }
		        nCurCount++;
		        if (nCurIndex > to.c2)
		            break;
		    }
		}
	}
	if (bChangeRowColProp)
	    this.worksheet.workbook.handlers.trigger("changeWorksheetUpdate", this.worksheet.getId());
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8638
	if(nLastCol != from.c2 || nLastRow != from.r2)
8639
	{
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8640 8641 8642 8643 8644
		var offset = {offsetCol:nLastCol - from.c2, offsetRow:nLastRow - from.r2};
		toRange.setOffsetLast(offset);
		to = toRange.getBBox0();
		fromRange.setOffsetLast(offset);
		from = fromRange.getBBox0();
8645
	}
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8646 8647
	var nWidth = from.c2 - from.c1 + 1;
	var nHeight = from.r2 - from.r1 + 1;
8648
	//удаляем текст или все в области для заполнения
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8649
	if(bIsPromote && nIndex >= 0 && ((true == bVertical && nHeight > nIndex) || (false == bVertical && nWidth > nIndex)))
8650 8651
	{
		//удаляем только текст в области для заполнения
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8652
		toRange.cleanText();
8653 8654 8655 8656
	}
	else
	{
		//удаляем все в области для заполнения
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8657 8658 8659 8660
		if(bIsPromote)
			toRange.cleanAll();
		else
			toRange.cleanFormat();
Alexander.Trofimov's avatar
Alexander.Trofimov committed
8661
		//собираем все данные
8662 8663 8664
		var bReverse = false;
		if(nIndex < 0)
			bReverse = true;
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8665 8666
		var oPromoteHelper = new PromoteHelper(bVertical, bReverse, from);
		fromRange._foreachNoEmpty(function(oCell, nRow0, nCol0, nRowStart0, nColStart0){
8667 8668 8669 8670 8671 8672
			 if(null != oCell)
			 {
				var nVal = null;
				var bDelimiter = false;
				var sPrefix = null;
				var bDate = false;
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8673
				if(bIsPromote)
8674
				{
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8675
					if (!oCell.sFormula)
8676
					{
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8677 8678
						var sValue = oCell.getValueWithoutFormat();
						if("" != sValue)
8679
						{
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8680 8681 8682
							bDelimiter = true;
							var nType = oCell.getType();
							if(CellValueType.Number == nType || CellValueType.String == nType)
8683
							{
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8684 8685 8686
								if(CellValueType.Number == nType)
									nVal = sValue - 0;
								else
8687
								{
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702
									//если текст заканчивается на цифру тоже используем ее
									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;
									}
8703 8704
								}
							}
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8705 8706 8707 8708 8709 8710 8711
							if(null != oCell.xfs && null != oCell.xfs.num && null != oCell.xfs.num.f){
								var numFormat = oNumFormatCache.get(oCell.xfs.num.f);
								if(numFormat.isDateTimeFormat())
									bDate = true;
							}
							if(null != nVal)
								bDelimiter = false;
8712 8713
						}
					}
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8714 8715
					else
						bDelimiter = true;
8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729
				}
				oPromoteHelper.add(nRow0 - nRowStart0, nCol0 - nColStart0, nVal, bDelimiter, sPrefix, bDate, oCell);
             }
		});
		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)
8730
		{
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8731 8732
			nStartRow = to.c1;
			nEndRow = to.c2;
8733 8734 8735
			bRowFirst = false;
			if(bReverse)
			{
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8736 8737
				nStartCol = to.r2;
				nEndCol = to.r1;
8738 8739 8740 8741
				nColDx = -1;
			}
			else
			{
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8742 8743
				nStartCol = to.r1;
				nEndCol = to.r2;
8744 8745
				nColDx = 1;
			}
8746 8747
		}
		else
8748
		{
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8749 8750
			nStartRow = to.r1;
			nEndRow = to.r2;
8751 8752 8753
			bRowFirst = true;
			if(bReverse)
			{
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8754 8755
				nStartCol = to.c2;
				nEndCol = to.c1;
8756 8757 8758 8759
				nColDx = -1;
			}
			else
			{
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8760 8761
				nStartCol = to.c1;
				nEndCol = to.c2;
8762 8763 8764 8765
				nColDx = 1;
			}
		}
		for(var i = nStartRow; i <= nEndRow; i ++)
8766
        {
8767 8768
			oPromoteHelper.setIndex(i - nStartRow);
            for(var j = nStartCol; (nStartCol - j) * (nEndCol - j) <= 0; j += nColDx)
8769
            {
8770 8771 8772 8773 8774 8775 8776
                var data = oPromoteHelper.getNext();
				if(null != data && (data.oAdditional || (false == bCopy && null != data.nCurValue)))
				{
					var oFromCell = data.oAdditional;
					var oCopyCell = null;
					if(bRowFirst)
						oCopyCell = this.worksheet._getCell(i, j);
8777
					else
8778
						oCopyCell = this.worksheet._getCell(j, i);
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8779
					if(bIsPromote)
8780
					{
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8781 8782 8783 8784 8785 8786 8787
						if(false == bCopy && null != data.nCurValue)
						{
							var sVal = "";
							if(null != data.sPrefix)
								sVal += data.sPrefix;
							sVal += data.nCurValue;
							oCopyCell.setValue(sVal);
8788
						}
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8789 8790 8791 8792 8793
						else if(null != oFromCell)
						{
							//копируем полностью
							if(!oFromCell.formulaParsed){
								var DataOld = oCopyCell.getValueData();
8794
								oCopyCell.oValue = oFromCell.oValue.clone();
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8795 8796
								var DataNew = oCopyCell.getValueData();
								if(false == DataOld.isEqual(DataNew))
8797
									History.Add(g_oUndoRedoCell, historyitem_Cell_ChangeValue, this.worksheet.getId(), new Asc.Range(oCopyCell.nCol, oCopyCell.nRow, oCopyCell.nCol, oCopyCell.nRow), new UndoRedoData_CellSimpleData(oCopyCell.nRow, oCopyCell.nCol, DataOld, DataNew));
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8798 8799
								//todo
								// if(oCopyCell.isEmptyTextString())
8800
									// this.worksheet._getHyperlink().remove({r1: oCopyCell.nRow, c1: oCopyCell.nCol, r2: oCopyCell.nRow, c2: oCopyCell.nCol});
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8801 8802 8803 8804 8805 8806 8807 8808 8809
							}
							else{
								var assemb;
								var _p_ = new parserFormula(oFromCell.sFormula,oCopyCell.getName(),this.worksheet);
								if( _p_.parse() ){
										assemb = _p_.changeOffset(oCopyCell.getOffset2(oFromCell.getName())).assemble();
										oCopyCell.setValue("="+assemb);
								}
							}
8810 8811
						}
					}
8812 8813 8814 8815 8816 8817
                    //выставляем стиль после текста, потому что если выставить числовой стиль ячейки 'text', то после этого не применится формула
					if (null != oFromCell) {
					    oCopyCell.setStyle(oFromCell.getStyle());
					    if (bIsPromote)
					        oCopyCell.setType(oFromCell.getType());
					}
8818
				}
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8819
			}
8820
		}
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8821
		if(bIsPromote)
8822
		{
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8823 8824
			var aNodes = this.worksheet.workbook.dependencyFormulas.getInRange( this.worksheet.Id, to );
			if(aNodes && aNodes.length > 0)
8825
			{
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8826 8827 8828 8829 8830 8831
				for(var i = 0, length = aNodes.length; i < length; ++i)
				{
					var node = aNodes[i];
					this.worksheet.workbook.needRecalc.nodes[ node.nodeId ] = [ node.sheetId, node.cellId ];
					this.worksheet.workbook.needRecalc.length++;
				}
8832 8833
			}
		}
8834
		//добавляем замерженые области
8835 8836
		var nDx = from.c2 - from.c1 + 1;
		var nDy = from.r2 - from.r1 + 1;
8837 8838 8839
		var oMergedFrom = oCanPromote.oMergedFrom;
		if(null != oMergedFrom && oMergedFrom.all.length > 0)
		{
8840 8841 8842 8843 8844
		    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);
8845 8846 8847 8848 8849 8850 8851 8852
						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())
								this.worksheet.mergeManager.add(oNewMerged, 1);	
						}
8853 8854 8855
		            }
		        }
		    }
8856
		}
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8857
		if(bIsPromote)
8858
		{
Sergey.Konovalov's avatar
Sergey.Konovalov committed
8859 8860 8861 8862
			//добавляем ссылки
			//не как в Excel поддерживаются ссылки на диапазоны
			var oHyperlinks = this.worksheet.hyperlinkManager.get(from);
			if(oHyperlinks.inner.length > 0)
8863
			{
8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874
			    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))
			                    this.worksheet.hyperlinkManager.add(oNewHyperlink, oHyperlink.data.clone());
			            }
			        }
			    }
8875 8876
			}
		}
8877 8878
	}
	History.EndTransaction();
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
8879
	buildRecalc(this.worksheet.workbook);
8880
	unLockDraw(this.worksheet.workbook);
8881
};
8882 8883 8884 8885 8886 8887 8888
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){
8889 8890 8891 8892 8893
			if(null != col.xfs)
			{
				for(var i = bbox.r1; i <= bbox.r2; ++i)
					oThis.worksheet._getCell(i, col.index);
			}
8894 8895 8896 8897 8898
		}, null);
	}
	else if(c_oRangeType.Col == nRangeType)
	{
		this._foreachRowNoEmpty(function(row){
8899 8900 8901 8902 8903
			if(null != row.xfs)
			{
				for(var i = bbox.c1; i <= bbox.c2; ++i)
					oThis.worksheet._getCell(row.index, i);
			}
8904 8905
		}, null);
	}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
8906
};
8907 8908 8909 8910
//-------------------------------------------------------------------------------------------------
/**
 * @constructor
 */
8911 8912 8913 8914 8915 8916
function PromoteHelper(bVerical, bReverse, bbox){
	//автозаполнение происходит всегда в правую сторону, поэтому менются индексы в методе add, и это надо учитывать при вызове getNext
	this.bVerical = bVerical;
	this.bReverse = bReverse;
	this.bbox = bbox;
	this.oDataRow = {};
8917
	//для get
8918 8919
	this.oCurRow = null;
	this.nCurColIndex = null;
8920
	this.nRowLength = 0;
8921 8922
	this.nColLength = 0;
	if(this.bVerical)
8923 8924
	{
		this.nRowLength = this.bbox.c2 - this.bbox.c1 + 1;
8925
		this.nColLength = this.bbox.r2 - this.bbox.r1 + 1;
8926
	}
8927
	else
8928 8929
	{
		this.nRowLength = this.bbox.r2 - this.bbox.r1 + 1;
8930
		this.nColLength = this.bbox.c2 - this.bbox.c1 + 1;
8931
	}
Alexander.Trofimov's avatar
Alexander.Trofimov committed
8932
}
8933
PromoteHelper.prototype = {
8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945
	add: function(nRow, nCol, nVal, bDelimiter, sPrefix, bDate, oAdditional){
		if(this.bVerical)
		{
			//транспонируем для удобства
			var temp = nRow;
			nRow = nCol;
			nCol = temp;
		}
		if(this.bReverse)
			nCol = this.nColLength - nCol - 1;
		var row = this.oDataRow[nRow];
		if(null == row)
8946
		{
8947 8948
			row = {};
			this.oDataRow[nRow] = row;
8949
		}
8950
		row[nCol] = {nCol: nCol, nVal: nVal, bDelimiter: bDelimiter, sPrefix: sPrefix, bDate: bDate, oAdditional: oAdditional, oSequence: null, nCurValue: null};
8951
	},
8952
	isOnlyIntegerSequence: function(){
8953
		var bRes = true;
8954 8955
		var bEmpty = true;
		for(var i in this.oDataRow)
8956
		{
8957 8958
			var row = this.oDataRow[i];
			for(var j in row)
8959
			{
8960 8961 8962
				var data = row[j];
				bEmpty = false;
				if(!(null != data.nVal && true != data.bDate && null == data.sPrefix))
8963 8964 8965 8966 8967
				{
					bRes = false;
					break;
				}
			}
8968 8969
			if(!bRes)
				break;
8970
		}
8971 8972
		if(bEmpty)
			bRes = false;
8973 8974
		return bRes;
	},
8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988
	_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)
		{
			nX = 1;
			a1 = 1;
8989
			a0 = aDigits[0].y;
8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004
		}
		else
		{
			// (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;

			// Цикл по всем строкам
9005
			for (var i = 0, length = aDigits.length; i < length; ++i)
9006
			{
9007 9008 9009
				var data = aDigits[i];
				nX = data.x;
				var dValue = data.y;
9010 9011 9012 9013 9014 9015 9016

				// Вычисляем значения
				nXi += nX;
				nXiXi += nX * nX;
				dYi += dValue;
				dYiXi += dValue * nX;
			}
9017
			nX++;
9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030

			// Теперь решаем систему уравнений
			// Общий детерминант
			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};
9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241
	},
	_addSequenceToRow : function(nRowIndex, aSortRowIndex, row, aCurSequence){
		if(aCurSequence.length > 0)
		{
			var oFirstData = aCurSequence[0];
			var bCanPromote = true;
			//если последовательность состоит из одного числа и той же колонке есть еще последовательности, то надо копировать, а не автозаполнять
			if(1 == aCurSequence.length)
			{
				var bVisitRowIndex = false;
				var oVisitData = null;
				for(var i = 0, length = aSortRowIndex.length; i < length; i++)
				{
					var nCurRowIndex = aSortRowIndex[i];
					if(nRowIndex == nCurRowIndex)
					{
						bVisitRowIndex = true;
						if(oVisitData && oFirstData.sPrefix == oVisitData.sPrefix && oFirstData.bDate == oVisitData.bDate)
						{
							bCanPromote = false;
							break;
						}
					}
					else
					{
						var oCurRow = this.oDataRow[nCurRowIndex];
						if(oCurRow)
						{
							var data = oCurRow[oFirstData.nCol];
							if(null != data)
							{
								if(null != data.nVal)
								{
									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;
								}
							}
						}
					}
				}
			}
			if(bCanPromote)
			{
				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++)
				{
					var data = aCurSequence[i];
					var nCurX = data.nCol;
					if(null == nMinIndex || null == nMaxIndex)
						nMinIndex = nMaxIndex = nCurX;
					else
					{
						if(nCurX < nMinIndex)
							nMinIndex = nCurX;
						if(nCurX > nMaxIndex)
							nMaxIndex = nCurX;
					}
					if(bValidIndexDif)
					{
						if(null != nPrevX && null != nPrevVal)
						{
							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;
							}
						}
					}
					nPrevX = nCurX;
					nPrevVal = data.nVal;
				}
				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++)
				{
					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;
				}
				if(aDigits.length > 0)
				{
					var oSequence = this._promoteSequence(aDigits);
					if(1 == aDigits.length && this.bReverse)
					{
						//меняем коэффициенты для случая одного числа в последовательности, иначе она в любую сторону будет возрастающей
						oSequence.a1 *= -1;
					}
					var bIsIntegerSequence = oSequence.a1 != parseInt(oSequence.a1);
					//для дат и чисел с префиксом автозаполняются только целочисленные последовательности
					if(!((null != oFirstData.sPrefix || true == oFirstData.bDate) && bIsIntegerSequence))
					{
						if(false == bWithSpace && bExistSpace)
						{
							for(var i = nMinIndex; i <= nMaxIndex; i++)
							{
								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;
							}
						}
						else
						{
							for(var i = 0, length = aCurSequence.length; i < length; i++)
							{
								var nCurX = aCurSequence[i].nCol;
								if(null != nCurX)
									row[nCurX].oSequence = oSequence;
							}
						}
					}
				}
			}
		}
	},
	finishAdd : function(bCopy){
		if(true != bCopy)
		{
			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++)
			{
				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++)
				{
					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)
					{
						this._addSequenceToRow(nRowIndex, aSortRowIndex, row, aCurSequence);
						aCurSequence = [];
						oPrevData = null;
					}
					if(bAddToSequence)
						aCurSequence.push(data);
				}
				this._addSequenceToRow(nRowIndex, aSortRowIndex, row, aCurSequence);
			}
		}
	},
	setIndex: function(index){
9242 9243
		if(0 != this.nRowLength && index >= this.nRowLength)
			index = index % (this.nRowLength);
9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269
		this.oCurRow = this.oDataRow[index];
		this.nCurColIndex = 0;
	},
	getNext: function(){
		var oRes = null;
		if(this.oCurRow)
		{
			var oRes = this.oCurRow[this.nCurColIndex];
			if(null != oRes)
			{
				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 ++;
				}
			}
			this.nCurColIndex++;
			if(this.nCurColIndex >= this.nColLength)
				this.nCurColIndex = 0;
		}
		return oRes;
9270
	}
9271 9272 9273 9274 9275
};
function DefinedName(){
	this.Name = null;
	this.Ref = null;
	this.LocalSheetId = null;
9276
    this.Hidden = null;
9277 9278
	this.bTable = false;
}
9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297

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

/**
 * @constructor
 */

function DrawingObjectsManager(worksheet)
{
    this.worksheet = worksheet;
}

DrawingObjectsManager.prototype.updateChartReferences = function(oldWorksheet, newWorksheet)
{
    ExecuteNoHistory(function(){
        this.updateChartReferencesWidthHistory(oldWorksheet, newWorksheet);
    }, this, []);
};

9298
DrawingObjectsManager.prototype.updateChartReferencesWidthHistory = function(oldWorksheet, newWorksheet, bNoRebuildCache)
9299 9300 9301 9302 9303 9304
{
    var aObjects = this.worksheet.Drawings;
    for (var i = 0; i < aObjects.length; i++) {
        var graphicObject = aObjects[i].graphicObject;
        if ( graphicObject.updateChartReferences )
        {
9305
            graphicObject.updateChartReferences(oldWorksheet, newWorksheet, bNoRebuildCache);
9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320
        }
    }
};


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);
        }
    }
9321
};