Workbook.js 281 KB
Newer Older
1 2 3 4
var d1,d2,d3;
var g_nHSLMaxValue = 240;
var g_nVerticalTextAngle = 255;
var gc_dDefaultColWidthCharsAttribute;//определяется в WorksheetView.js
5
var gc_dDefaultRowHeightAttribute;//определяется в WorksheetView.js
6 7 8 9 10 11 12
var g_nNextWorksheetId = 1;
var g_sNewSheetNamePattern = "Sheet";
var g_nSheetNameMaxLength = 31;
var g_nAllColIndex = -1;
var History;
var aStandartNumFormats;
var aStandartNumFormatsId;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
13
var start, end, cCharDelimiter = String.fromCharCode(5), arrRecalc = {}, 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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148

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

/** @constructor */
function DependencyGraph(wb) {
	var nodes = {}, badRes = [], result = [], nodeslength = 0, nodesfirst, __nodes = {}, areaNodes = {}, thas = this;
	
	this.wb = wb;
	
	this.clear = function(){
		nodes = {};
		__nodes = {};
		areaNodes = {};
		badRes = [];
		result = [];
		nodeslength = 0;
		nodesfirst = null;
	}
	
	this.nodeExist = function(node){
		return nodes[node.nodeId] !== undefined;
	}

	this.nodeExist2 = function(sheetId, cellId){
		var n = new Vertex(sheetId, cellId);
		var exist = nodes[n.nodeId] !== undefined;
		if ( !exist ){
			for( var id in areaNodes){
				if( areaNodes[id].containCell(n) )
					return true;
			}
		}
		return exist;
	}
	
	//добавляем вершину по id листа и по id ячейки
	this.addNode = function(sheetId, cellId){
		var node = new Vertex(sheetId, cellId,this.wb);
		if (nodes[node.nodeId] === undefined){
			if (nodeslength == 0){
				nodesfirst = node.nodeId;
			}
			nodes[node.nodeId] = node;
			nodeslength++;
			if( node.isArea && !areaNodes[node.nodeId] ){
				areaNodes[node.nodeId] = node;
			}
		}
	}

	//добавляем уже существующую вершину
	this.addNode2 = function(node){
		if (nodes[node.nodeId] === undefined) {
			if (nodeslength == 0){
				nodesfirst = node.nodeId;
			}
			nodes[node.nodeId] = node;
			nodeslength ++;
			if( node.isArea && !areaNodes[node.nodeId] ){
				areaNodes[node.nodeId] = node;
			}
		}
	}
	
	//добавление ребер между вершинами
	this.addEdge = function(sheetIdFrom, cellIdFrom, sheetIdTo, cellIdTo){
		var n1 = new Vertex(sheetIdFrom, cellIdFrom,this.wb),
			n2 = new Vertex(sheetIdTo, cellIdTo,this.wb);
			
		if( !this.nodeExist(n1) ){
			this.addNode2(n1);
		}
		
		if( !this.nodeExist(n2) ){
			this.addNode2(n2);
		}
		
		nodes[n1.nodeId].addMasterEdge(nodes[n2.nodeId]);
		nodes[n2.nodeId].addSlaveEdge(nodes[n1.nodeId]);
	}

	this.addEdge2 = function(nodeFrom, nodeTo){

		if( !this.nodeExist(nodeFrom) ){
			this.addNode2(nodeFrom);
		}
		
		if( !this.nodeExist(nodeTo) ){
			this.addNode2(nodeTo);
		}
		
		nodes[nodeFrom.nodeId].addMasterEdge(nodes[nodeTo.nodeId]);
		nodes[nodeTo.nodeId].addSlaveEdge(nodes[nodeFrom.nodeId]);
	}
	
	this.renameNode = function(sheetIdFrom, cellIdFrom, sheetIdTo, cellIdTo){
		if( sheetIdFrom == sheetIdTo && cellIdFrom == cellIdTo ){
			return;
		}
		nodes[getVertexId(sheetIdTo, cellIdTo)] = nodes[getVertexId(sheetIdFrom, cellIdFrom)];
		if( !nodes[getVertexId(sheetIdTo, cellIdTo)] )
			return;
		nodes[getVertexId(sheetIdFrom, cellIdFrom)] = undefined;
		delete nodes[getVertexId(sheetIdFrom, cellIdFrom)];
		nodes[getVertexId(sheetIdTo, cellIdTo)].changeCellId(cellIdTo);
	}
	
	this.getNode = function(sheetId, cellId){
		var n = new Vertex(sheetId, cellId)
		if( this.nodeExist(n) )
			return nodes[n.nodeId];
	}
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165

    this.getNode2 = function(sheetId, cellId){
        var n = new Vertex( sheetId, cellId );
        var exist = nodes[n.nodeId] !== undefined, res = [];
        if ( exist ) {
            res.push( nodes[n.nodeId] )
        }
        else {
            for ( var id in areaNodes ) {
                if ( areaNodes[id].containCell( n ) ) {
                    res.push( areaNodes[id] )
                }
            }
        }
        return res.length > 0 ? res : null;
    }

166 167 168 169
	this.getNodeByNodeId = function(nodeId){
		if( nodes[nodeId] )
			return nodes[nodeId];
	}
170

171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
	this.getNodeBySheetId = function(sheetId){
		var arr = [];
		for(var id in nodes){
			if ( nodes[id].sheetId == sheetId && nodes[id].getSlaveEdges()){
				arr.push(nodes[id]);
				var n = nodes[id].getSlaveEdges()
				for(var id2 in n){
					n[id2].weightNode++;
					// arr.push(n[id2]);
				}
			}
		}
		return arr;
	}
	
	this.deleteNode = function(n){
		if( this.nodeExist(n) ){
			var _n = nodes[n.nodeId];
			_n.deleteAllMasterEdges();
			_n.deleteAllSlaveEdges();
			nodes[_n.nodeId] = null;
			delete nodes[_n.nodeId];
			nodeslength--;
		}
	}
	
	this.deleteMasterNodes = function(sheetId, cellId){
		var n = new Vertex(sheetId, cellId);
		if( this.nodeExist(n) ){
			var arr = nodes[n.nodeId].deleteAllMasterEdges();
			for(var i = 0; i < arr.length; i++){
				if( nodes[arr[i]].refCount <= 0 ){
					nodes[arr[i]] = null;
					delete nodes[arr[i]];
					nodeslength--;
				}
			}
		}
	}
	
	this.deleteSlaveNodes = function(sheetId, cellId){
		var n = new Vertex(sheetId, cellId);
		if( this.nodeExist(n) ){
			nodes[n.nodeId].deleteAllSlaveEdges();
		}
	}
	
	this.getSlaveNodes = function(sheetId, cellId){
		var node = new Vertex(sheetId, cellId);
		if( this.nodeExist(node) ){
			return nodes[node.nodeId].getSlaveEdges();
		}
		else{
			var _t = {}, f = false;
			for( var id in areaNodes ){
				if( areaNodes[id].containCell(node) ){
					_t[id] = areaNodes[id];
					f = true;
				}
			}
			if (f)
				return _t;
		}
		return null;
	}

	this.getMasterNodes = function(sheetId, cellId){
		var n = new Vertex(sheetId, cellId);
		if( this.nodeExist(n) ){
			return nodes[n.nodeId].getMasterEdges();
		}
		return null;
	}
	
	//объект __nodes является копией объекта nodes. чтобы не бегать по всему графу в поисках очередной вершины, будем бегать по __nodes и удалять полученную новую вершину из __nodes.
	this.addN = function(sheetId,cellId){
		var n = new Vertex(sheetId,cellId,this.wb);
		if( !(n.nodeId in __nodes) ){
			__nodes[n.nodeId] = n;
		}
	}
	
	//сортировка по зависимым(ведомым) ячейкам. у объекта берем массив slaveEdges и по нему бегаем.
	this.t_sort_slave = function(sheetId,cellId){
	
		for( var id in nodes ){
			if( !nodes[id].isArea ){
				for( var id2  in areaNodes ){
					if( areaNodes[id2].containCell(nodes[id]) ){
						areaNodes[id2].addMasterEdge(nodes[id]);
						nodes[id].addSlaveEdge(areaNodes[id2]);
					}
				}
			}
		}
	
		function getFirstNode(sheetId,cellId) {
			
			var n = new Vertex(sheetId,cellId,thas.wb);
			if ( !nodes[n.nodeId] ){
				var a = [];
				for( var id in areaNodes ){
					if( areaNodes[id].containCell(n) )
						a.push(areaNodes[id])
				}
				if( a.length > 0 ){
					for( var i in a ){
						n.addSlaveEdge( a[i] );
					}
					n.valid = false;
					return n;
				}
				else{
					return undefined;
				}
			}
			else
				return nodes[n.nodeId];
		}
		
		function getNextNode(node) {
			for (var id in node.slaveEdges){
				var n = nodes[id];
				if (n !== undefined){
					if ((n.isBlack === undefined || !n.isBlack) && !n.isBad) {
						return n;
					}
				}
				else {
					delete node.slaveEdges[id];
				}
			}
			return undefined;
		}
		
		var stack = [],	n = getFirstNode(sheetId,cellId),__t = true, next, badResS = [], resultS = [];

		if( !n ){
			return {depF: resultS.reverse(), badF: badResS}
		}
		
		while (1) {
			if ( n.isGray && !n.isArea ){
				for( var i = stack.length-1; i>=0;i--){
					var bad = stack.pop();
					bad.isBad = true;
					badResS.push(bad);
					if ( stack[i] == n )
						break;
				}
				if (stack.length < 1) {
					for (var id in __nodes){
						if( nodes[id] !== undefined && ((nodes[id].isBlack === undefined || !nodes[id].isBlack) && !nodes[id].isBad) ){
							n = nodes[id];
							delete __nodes[id];
						}
					}
				}
			}
			next = getNextNode(n);
			if (next !== undefined) {
				n.isGray = true;
				stack.push(n);
				n = next;
			}
			else {
				n.isBlack = true;
				n.isGray = false;
				resultS.push(n);
				if (stack.length < 1)
					break;
				n = stack.pop();
				n.isGray = false;
			}
		}
		
		for(var i = 0; i < resultS.length; i++){
			resultS[i].isBlack = false;
			resultS[i].isBad = false;
			resultS[i].isGray = false;
		}
		for(var i = 0; i < badResS.length; i++){
			badResS[i].isBlack = false;
			badResS[i].isBad = false;
			badResS[i].isGray = false;
		}
		
		return {depF: resultS.reverse(), badF: badResS}
		
	}
	
	//сортировка по ведущим ячейкам. у объекта берем массив masterEdges и по нему бегаем.
	this.t_sort_master = function(sheetId,cellId){
364 365 366 367 368 369 370 371 372 373 374 375

        for( var id in nodes ){
            if( !nodes[id].isArea ){
                for( var id2  in areaNodes ){
                    if( areaNodes[id2].containCell(nodes[id]) ){
                        areaNodes[id2].addMasterEdge(nodes[id]);
                        nodes[id].addSlaveEdge(areaNodes[id2]);
                    }
                }
            }
        }

376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 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 566 567 568 569 570 571 572 573 574 575 576 577
		function getFirstNode(sheetId,cellId) {
			
			var n = new Vertex(sheetId,cellId,thas.wb);
			if ( !nodes[n.nodeId] ){
				var a = [];
				for( var id in areaNodes ){
					if( areaNodes[id].containCell(n) )
						a.push(areaNodes[id])
				}
				if( a.length > 0 ){
					for( var i in a ){
						n.addSlaveEdge( a[i] );
					}
					n.valid = false;
					return n;
				}
				else{
					return undefined;
				}
			}
			else
				return nodes[n.nodeId];
		}
		
		function getNextNode(node) {
			if(node){
				for (var id in node.masterEdges){
					var n = nodes[id];
					if (n !== undefined){
						if ((n.isBlack === undefined || !n.isBlack) && !n.isBad) {
							return n;
						}
					}
					else {
						delete node.masterEdges[id];
					}
				}
			}
			return undefined;
		}
		
		var stack = [],	n = getFirstNode(sheetId,cellId), __t = true, next, badResS = [], resultS = [];
		
		if( !n ){
			return {depF: resultS, badF: badResS}
		}
		
		while (1) {
			if( n ){
				if ( n.isGray && !n.isArea ){
					for( var i = stack.length-1; i>=0;i--){
						var bad = stack.pop();
						bad.isBad = true;
						badResS.push(bad);
					}
				}
			}
			if( n.valid && !n.isArea ){
				for( var id in areaNodes ){
					if( areaNodes[id].containCell(n) ){
						areaNodes[id].addMasterEdge(n);
						n.addSlaveEdge(areaNodes[id]);
					}
				}
				n.valid = false;
			}
			next = getNextNode(n);
			if (next !== undefined) {
				n.isGray = true;
				stack.push(n);
				n = next;
			}
			else {
				n.isBlack = true;
				n.isGray = false;
				resultS.push(n);
				if (stack.length < 1)
					break;
				n = stack.pop();
				n.isGray = false;
			}
		}
		
		for(var i = 0; i < resultS.length; i++){
			resultS[i].isBlack = false;
			resultS[i].isBad = false;
			resultS[i].isGray = false;
		}
		for(var i = 0; i < badResS.length; i++){
			badResS[i].isBlack = false;
			badResS[i].isBad = false;
			badResS[i].isGray = false;
		}
		
		return {depF: resultS, badF: badResS}
	}
	
	//сортировка всего графа по всем вершинам.
	this.t_sort = function() {
	
		for(var i in nodes){
			nodes[i].isBlack = false;
			nodes[i].isBad = false;
			nodes[i].isGray = false;
		}
	
		function getFirstNode() {
			return nodes[nodesfirst];
		}
		
		function getNextNode(node) {
			for (var id in node.masterEdges){
				var n = nodes[id];
				if (n !== undefined){
					if ((n.isBlack === undefined || !n.isBlack) && !n.isBad) {
						return n;
					}
				}
				else {
					delete node.masterEdges[id];
				}
			}
			return undefined;
		}

		var stack = [],
				n = getFirstNode(),__t = true,
				next;
		while (1) {
			if ( n.isGray ){
				for( var i = stack.length-1; i>=0;i--){
					var bad = stack.pop();
					bad.isBad = true;
					badRes.push(bad);
					if ( stack[i] == n )
						break;
				}
				if (stack.length < 1) {
					for (var id in __nodes){
						if( nodes[id] !== undefined && ((nodes[id].isBlack === undefined || !nodes[id].isBlack) && !nodes[id].isBad) ){
							n = nodes[id];
							delete __nodes[id];
						}
					}
				}
			}
			next = getNextNode(n);
			if (next !== undefined) {
				n.isGray = true;
				stack.push(n);
				n = next;
			}
			else {
				n.isBlack = true;
				n.isGray = false;
				result.push(n);
				if (stack.length < 1) {
					n = undefined;
					for (var id in __nodes){
						if( nodes[id] !== undefined && ((nodes[id].isBlack === undefined || !nodes[id].isBlack) && !nodes[id].isBad) ){
							n = nodes[id];
							delete __nodes[id];
							break;
						}
						else{
							delete __nodes[id];
						}
					}
					if (n)
						continue;
					else break;
				}
				n = stack.pop();
				n.isGray = false;
			}
		}

		return {depF: result, badF: badRes}
		
	}

	this.returnNode = function(){
		return nodes;
	}
	
	this.getNodesLength = function(){
		return nodeslength;
	}
	
	this.getResult = function(){
		return {depF:result, badF:badRes};
	}
	
	this.checkOffset = function(BBox, offset, wsId, noDelete){
		var move = {}, stretch = {}, recalc = {};
		for( var id in nodes ){
			if( nodes[id].sheetId != wsId )
				continue;
			var n = { r1:nodes[id].firstCellAddress.getRow0(), c1:nodes[id].firstCellAddress.getCol0(),
					  r2:nodes[id].lastCellAddress.getRow0(), c2:nodes[id].lastCellAddress.getCol0() }
			if( nodes[id].isArea ){
				/* 
578 579
					Есть 2 области. Первая - это диапазон, что участвует в формуле, второй - это который удаляют/вставляют. Нужно определить положение двух этих областей относительно друг друга.
					Если вторая область находится ( ( выше и левее ) или правее или ниже ) первой, такая область нас не интересуею. Она не повлияет на сдвиг диапазона.
580 581 582 583 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 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
					Если же она находится выше или левее, перекрывает частично или полностью диапазон, необходимо отследить какой сдвиг будет следовать - по вертикали или по горизонтали. После чего следует выполнить соответсвтующие действия - расширить диапазон, сдвинуть диапазон, просто пересчитать.
					Для проверки на способ перекрытия переношу начало координат в левый верхний угол диапазона, меняю координаты у второй области и сравниваю возможные варианты расположения используя координаты углов обоих областей. 
					PS вариант не нравится, слишком много if. Хотелось бы поэллегантнее решение.
				*/
				var n1 = { r1: n.r1 - n.r1, c1: n.c1 - n.c1, 
						   r2: n.r2 - n.r1, c2: n.c2 - n.c1 };
					n1.height = n1.r2 - n1.r1;
					n1.width = n1.c2 - n1.c1;
						   
				var BBox1 = { r1: BBox.r1 - n.r1, c1: BBox.c1 - n.c1,
							  r2: BBox.r2 - n.r1, c2: BBox.c2 - n.c1 };
					n1.height = BBox1.r2 - BBox1.r1;
					n1.width = BBox1.c2 - BBox1.c1;
							  
				if( BBox1.r1 > n1.r2 || BBox1.c1 > n1.c2 || ( BBox.r2 < 0 && BBox1.c2 < 0 ) )//(слева и выше) или справа или снизу
					continue;
				else{
				
					if( offset.offsetRow == 0 ){
					
						if( offset.offsetCol == 0 ){
							continue;
						}
						else{
							if( BBox1.r2 < n1.r1 ) continue;
							else if( BBox1.r2 < n1.r2 || BBox1.r1 > n1.r1 ){
								recalc[id] = nodes[id];
							}
							else{
								if( offset.offsetCol > 0 ){
									if( BBox1.r1 <= n1.r1 && BBox1.r2 >= n1.r2){
										if( BBox1.c2 <= n1.c2 && BBox1.c1 <= n1.c1 || BBox1.c1 == n1.c1 && BBox1.c2 > n1.c2 )
											move[id] = { node : nodes[id], offset : offset };
										else if( BBox1.c1 > n1.c1 && BBox1.c1 <= n1.c2 ){
											stretch[id] = { node : nodes[id], offset : offset };
										}
									}
								}
								else{
									if( BBox1.r1 <= n1.r1 && BBox1.r2 >= n1.r2){
										if( BBox1.c2 < n1.c1 ){
											move[id] = { node : nodes[id], offset : offset };
										}
										else if( BBox1.c2 >= n1.c1 && BBox1.c1 <= n1.c1 ){
											if(	n1.r1 >= BBox1.r1 && n1.r2 <= BBox1.r2 && n1.c1 >= BBox1.c1 && n1.c2 <= BBox1.c2 ){
												move[id] = { node : nodes[id], offset : offset , toDelete: !noDelete };
												recalc[id] = nodes[id];
											}
											else{
												move[id] = { node : nodes[id], offset : { offsetCol : -Math.abs(n1.c1-BBox1.c1), offsetRow: offset.offsetRow } };
												stretch[id] = { node : nodes[id], offset : { offsetCol : -Math.abs(n1.c1-BBox1.c2)-1, offsetRow: offset.offsetRow } };
												recalc[id] = nodes[id];
											}
										}
										else if( BBox1.c1 > n1.c1 && BBox1.c1 <= n1.c2 || BBox1.c1 == n1.c1 && BBox1.c2 >= n1.c1 ){
											if( BBox1.c2 > n1.c2 ){
												stretch[id] = { node : nodes[id], offset : { offsetCol : -Math.abs(n1.c2-BBox1.c1)-1, offsetRow: offset.offsetRow } };
												recalc[id] = nodes[id];
											}
											else{
												stretch[id] = { node : nodes[id], offset : offset };
												recalc[id] = nodes[id];
											}
										}
									}
								}
							}
						}
						
					}
					else{
						if( BBox1.c2 < n1.c1 ) continue;
						else if( BBox1.c2 < n1.c2 || BBox1.c1 > n1.c1 ){
							recalc[id] = nodes[id];
						}
						else{
							if( offset.offsetRow > 0 ){
								if( BBox1.c1 <= n1.c1 && BBox1.c2 >= n1.c2){
									if( BBox1.r2 <= n1.r2 && BBox1.r1 <= n1.r1 || BBox1.r1 == n1.r1 && BBox1.r2 > n1.r2 )
										move[id] = { node : nodes[id], offset : offset };
									else if( BBox1.r1 > n1.r1 && BBox1.r1 <= n1.r2 ){
										stretch[id] = { node : nodes[id], offset : offset };
									}
								}
							}
							else{
								if( BBox1.c1 <= n1.c1 && BBox1.c2 >= n1.c2){
									if( BBox1.r2 < n1.r1 ){
										move[id] = { node : nodes[id], offset : offset };
									}
									else if( BBox1.r2 >= n1.r1 && BBox1.r1 <= n1.r1 ){
										if(	n1.r1 >= BBox1.r1 && n1.r2 <= BBox1.r2 && n1.c1 >= BBox1.c1 && n1.c2 <= BBox1.c2 ){
											move[id] = { node : nodes[id], offset : offset , toDelete: !noDelete };
											recalc[id] = nodes[id];
										}
										else{
											move[id] = { node : nodes[id], offset : { offsetRow : -Math.abs(n1.r1-BBox1.r1), offsetCol: offset.offsetCol } };
											stretch[id] = { node : nodes[id], offset : { offsetRow : -Math.abs(n1.r1-BBox1.r2)-1, offsetCol: offset.offsetCol } };
											recalc[id] = nodes[id];
										}
									}
									else if( BBox1.r1 > n1.r1 && BBox1.r1 <= n1.r2 || BBox1.r1 == n1.r1 && BBox1.r2 >= n1.r1 ){
										if( BBox1.r2 > n1.r2 ){
											stretch[id] = { node : nodes[id], offset : { offsetRow : -Math.abs(n1.r2-BBox1.r1)-1, offsetCol: offset.offsetCol } };
											recalc[id] = nodes[id];
										}
										else{
											stretch[id] = { node : nodes[id], offset : offset };
											recalc[id] = nodes[id];
										}
									}
								}
							}
						}
					}
				}
			}
			else{
				//сдвиг для одиночной ячейки 
				if( ( n.r1 >= BBox.r1 && n.r1 <= BBox.r2 && n.c1 >= BBox.c2 && offset.offsetCol != 0 ) ||
					( n.c1 >= BBox.c1 && n.c1 <= BBox.c2 && n.r1 >= BBox.r2 && offset.offsetRow != 0 ) ||
					( n.r1 >= BBox.r1 && n.r2 <= BBox.r2 && n.c1 >= BBox.c1 && n.c2 <= BBox.c2 ) )
				{
					move[id] = { node : nodes[id], offset : offset , toDelete: false };
					if(	n.r1 >= BBox.r1 && n.r2 <= BBox.r2 && n.c1 >= BBox.c1 && n.c2 <= BBox.c2 && !noDelete && ( offset.offsetCol < 0 || offset.offsetRow < 0 ) ){
						move[id].toDelete = true;
						recalc[id] = nodes[id];
					}
				}
			}
		}
		
		return {move:move,stretch:stretch,recalc:recalc};
	}
	
	this.helper = function(BBox,wsId){
		var move = {}, recalc = {},
			range = this.wb.getWorksheetById(wsId).getRange(new CellAddress(BBox.r1, BBox.c1, 0), new CellAddress(BBox.r2, BBox.c2, 0)),
718
			n = new Vertex(range.getWorksheet().getId(),range.getName());
719 720 721 722 723 724
		
		if( n.isArea ){
			if( n.nodeId in nodes ){
				move[n.nodeId] = nodes[n.nodeId];
			}
			else{
725 726 727 728 729 730
                for( var id2 in areaNodes ){
                    if( n.containCell(areaNodes[id2]) ){
                        move[areaNodes[id2].nodeId] = nodes[areaNodes[id2].nodeId];
                    }
                }

731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
				range = range.getCells();
				for( var id in range ){
					n = new Vertex(wsId,range[id].getName());
					if( n.nodeId in nodes ){
						move[n.nodeId] = nodes[n.nodeId];
					}
					for( var id2 in areaNodes ){
						if( areaNodes[id2].containCell(n) ){
							recalc[id2] = areaNodes[id2];
						}
					}
				}
			}
		}
		else {
			if( n.nodeId in nodes ){
				move[n.nodeId] = nodes[n.nodeId];
			}
			for( var id  in areaNodes ){
				if( areaNodes[id].containCell(n) ){
					recalc[id] = areaNodes[id];
				}
			}
		}
755

756 757 758 759
		return {move:move,recalc:recalc};
	}

	this.drawDep = function(cellId,se){
760
		// ToDo неиспользуемая функция, реализовать после выпуска
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
		if( !cellId )
			return;
		var _wsV = this.wb.oApi.wb.getWorksheet(),
			_getCellMetrics = _wsV.cellCommentator.getCellMetrics,
			_cc = _wsV.cellCommentator,
			ctx = _wsV.overlayCtx,
			_wsVM = _wsV.model,
			nodeId = getVertexId(_wsVM.getId(), cellId),
			node = this.getNode(_wsVM.getId(), cellId),
			cell;
		
			function gCM(_this,col,row){
				var metrics = { top: 0, left: 0, width: 0, height: 0, result: false }; 	// px

				var fvr = _this.getFirstVisibleRow();
				var fvc = _this.getFirstVisibleCol();
777
				var mergedRange = _wsVM.getMergedByCell(row, col);
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803

				if (mergedRange && (fvc < mergedRange.c2) && (fvr < mergedRange.r2)) {

					var startCol = (mergedRange.c1 > fvc) ? mergedRange.c1 : fvc;
					var startRow = (mergedRange.r1 > fvr) ? mergedRange.r1 : fvr;

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

					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{

					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;
				}
		
804
				return metrics;
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
			}
		
		if( !node )
			return;
			
		cell = node.returnCell();
			
		if( !cell )
			return;
			
		var m = [cell.getCellAddress().getRow0(),cell.getCellAddress().getCol0()],
			rc = [], me = se?node.getSlaveEdges():node.getMasterEdges();
		
		for( var id in me ){
			if( me[id].sheetId != node.sheetId )
				return;
			
			if( !me[id].isArea ){
				var _t1 = gCM(_wsV,me[id].returnCell().getCellAddress().getCol0(),me[id].returnCell().getCellAddress().getRow0())
				
				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].firstCellAddress.getCol0(),me[id].firstCellAddress.getRow0()),
					_t2 = gCM(_wsV,me[id].lastCellAddress.getCol0(),me[id].lastCellAddress.getRow0());
					
				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;
		
		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;
843
			// ToDo посмотреть на четкость moveTo, lineTo
844 845 846
			context.save()
				.setLineWidth(1)
				.beginPath()
847 848
				.moveTo(_cc.pxToPt(fromx), _cc.pxToPt(fromy))
				.lineTo(_cc.pxToPt(tox), _cc.pxToPt(toy));
849 850 851 852
				// .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)),
853 854
					_cc.pxToPt(toy - headlen * Math.sin(angle - _a)))
				.lineTo(_cc.pxToPt(tox), _cc.pxToPt(toy))
855 856
				.lineTo(
					_cc.pxToPt(tox - headlen * Math.cos(angle + _a)),
857
					_cc.pxToPt(toy - headlen * Math.sin(angle + _a)))
858 859
				.lineTo(
					_cc.pxToPt(tox - headlen * Math.cos(angle - _a)),
860
					_cc.pxToPt(toy - headlen * Math.sin(angle - _a)))
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
				.setStrokeStyle("#0000FF")
				.setFillStyle("#0000FF")
				.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;
881 882

				// ToDo посмотреть на четкость rect
883 884 885 886
				if( m2.apl > 0 && m2.apt >0)
					ctx.save()
						.setLineWidth(1)
						.setStrokeStyle("#0000FF")
887
						.rect( _cc.pxToPt(m2.l),_cc.pxToPt(m2.t),_cc.pxToPt(m2.w-1),_cc.pxToPt(m2.h-1) )
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
						.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("#0000FF")
						.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);
	}
	
	this.removeNodeBySheetId = function(sheetId){
		var arr = false;
		this.wb.needRecalc = [];
		this.wb.needRecalc.length = 0;
		for(var id in nodes){
			if(nodes[id].sheetId == sheetId){
				var se = nodes[id].getSlaveEdges();
				for(var id2 in se){
					if(se[id2].sheetId != sheetId){
						if(!arr) arr = true;
						this.wb.needRecalc[id2] = [se[id2].sheetId,se[id2].cellId];
						this.wb.needRecalc.length++;
						// arr.push(se[id2]);
					}
				}
				nodes[id].deleteAllMasterEdges();
				nodes[id].deleteAllSlaveEdges();
				nodes[id] = null;
				delete nodes[id];
				nodeslength--;
			}
		}
		return arr;
	}
}

/** @constructor */
function Vertex(sheetId,cellId,wb){
	
	this.sheetId = sheetId;
	this.cellId = cellId;
	this.valid = true;
	this.nodeId = sheetId + cCharDelimiter + cellId;
	
	var nIndex = cellId.indexOf(":");
	if( this.isArea = (nIndex > -1) ){
		var sFirstCell = cellId.substring(0, nIndex);
		var sLastCell = cellId.substring(nIndex + 1);
		
		if( !sFirstCell.match(/[^a-z]/ig) ){
			this.firstCellAddress = new CellAddress(sFirstCell+"1");
			this.lastCellAddress = new CellAddress(sLastCell+gc_nMaxRow.toString());
		}
		else if( !sFirstCell.match(/[^0-9]/ig) ){
			this.firstCellAddress = new CellAddress("A"+sFirstCell);
			this.lastCellAddress = new CellAddress(g_oCellAddressUtils.colnumToColstr(gc_nMaxCol)+sLastCell);
		}
		else{
			this.firstCellAddress = new CellAddress(sFirstCell);
			this.lastCellAddress = new CellAddress(sLastCell);
		}
		
		this.containCell = function(node){
			if( this.sheetId != node.sheetId )
				return false;
			if( node.firstCellAddress.row >= this.firstCellAddress.row &&
				node.firstCellAddress.col >= this.firstCellAddress.col &&
				node.lastCellAddress.row <= this.lastCellAddress.row &&
				node.lastCellAddress.col <= this.lastCellAddress.col
			){
				return true;
			}
			return false;
		}

	}
	else{
		this.firstCellAddress = this.lastCellAddress = new CellAddress(cellId);
	}

	if( wb && !this.isArea ){
		this.wb = wb;
993 994
		var c = new CellAddress(this.cellId);
		this.cell = this.wb.getWorksheetById(this.sheetId)._getCellNoEmpty(c.getRow0(),c.getCol0());
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
	}
	
	//вершина которую мы прошли и поставили в очередь обхода
	this.isBlack = false;
	
	//вершина которую мы прошли, но не поставили в очередь обхода. нужно для определения петель в графе.
	this.isGray = false;
	
	//если вершина входит в цикличный путь, то она помечается плохой и запоминается в списке плохих вершин.
	this.isBad = false;
	
	//masterEdges содержит ячейки, от которых зависит текущая ячейка
	this.masterEdges = null;
	
	this.helpMasterEdges = {};
	
	//slaveEdges содержит ячейки, которые зависят от данной ячейки
	this.slaveEdges = null;
	
	this.refCount = 0;
	
	this.weightNode = 0;
}
Vertex.prototype = {	
	
	constructor: Vertex,
	
	changeCellId : function(cellId){
		var lastId = this.nodeId;
		this.cellId = cellId;
		this.nodeId = this.sheetId + cCharDelimiter + cellId;
		for( var id in this.masterEdges ){
			if( lastId in this.masterEdges[id].slaveEdges ){
				this.masterEdges[id].slaveEdges[this.nodeId] = this.masterEdges[id].slaveEdges[lastId];
				this.masterEdges[id].slaveEdges[lastId] = null;
				delete this.masterEdges[id].slaveEdges[lastId];
			}
		}
		for( var id in this.slaveEdges ){
			if( lastId in this.slaveEdges[id].masterEdges ){
				this.slaveEdges[id].masterEdges[this.nodeId] = this.slaveEdges[id].masterEdges[lastId];
				this.slaveEdges[id].masterEdges[lastId] = null;
				delete this.slaveEdges[id].masterEdges[lastId];
			}
		}
	},
	
	//добавляем ведущую ячейку.
	addMasterEdge : function(node){
		if( !this.masterEdges )
			this.masterEdges = {};
		this.masterEdges[node.nodeId] = node;
		this.refCount ++;
	},

	addHelpMasterEdge : function(node){
		this.helpMasterEdges[node.nodeId] = node;
	},
	
	//добавляем зависимую(ведомую) ячейку.
	addSlaveEdge : function(node){
		if( !this.slaveEdges )
			this.slaveEdges = {};
		this.slaveEdges[node.nodeId] = node;
		this.refCount ++;
	},
	
	getMasterEdges : function(){
		return this.masterEdges;
	},

	getHelpMasterEdges : function(){
		return this.helpMasterEdges;
	},
	
	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;
	},
	
	//удаляем ребро между конкретной ведущей ячейки.
	deleteMasterEdge : function(node){
		this.masterEdges[node.nodeId] = null;
		delete this.masterEdges[node.nodeId];
		this.refCount--;
	},

	deleteHelpMasterEdge : function(node){
		delete this.helpMasterEdges[node.nodeId];
	},

	//удаляем ребро между конкретной зависимой(ведомой) ячейки.
	deleteSlaveEdge : function(node){
		this.slaveEdges[node.nodeId] = null;
		delete this.slaveEdges[node.nodeId];
		this.refCount--;
	},

	//очищаем все ребра по ведущим ячейкам.
	deleteAllMasterEdges : function(){
		var ret = [];
		for( var id in this.masterEdges ){
			this.masterEdges[id].deleteSlaveEdge(this);
			this.masterEdges[id] = null;
			delete this.masterEdges[id];
			this.refCount--;
			ret.push(id);
		}
		this.masterEdges = null;
		return ret;
	},
	
	//очищаем все ребра по ведомым ячейкам.
	deleteAllSlaveEdges : function(){
		var ret = [];
		for( var id in this.slaveEdges ){
			this.slaveEdges[id].deleteMasterEdge(this);
			this.slaveEdges[id] = null;
			delete this.slaveEdges[id];
			this.refCount--;
			ret.push(id);
		}
		this.slaveEdges = null;
		return ret;
	},

	returnCell : function(){
		return this.cell;
	}
	
}

function getVertexId(sheetId, cellId){
	return sheetId + cCharDelimiter + cellId;
}
function lockDraw(wb){
1142
    lc++;
1143 1144 1145 1146
	wb.isNeedCacheClean = false;
	arrRecalc = {};
}
function unLockDraw(wb){
1147 1148 1149 1150 1151
    lc--;
	if( lc == 0 ){
        wb.isNeedCacheClean = true;
        arrRecalc = {};
    }
1152
}
1153
function buildRecalc(_wb,notrec){
1154 1155
	var ws;
    if( lc > 1 ) return;
1156
	for( var id in arrRecalc ){
1157
		ws = _wb.getWorksheetById(id);
1158
		if (ws) {
1159
			ws._BuildDependencies(arrRecalc[id]);
1160 1161
		}
	}
1162 1163
    if(!notrec)
	    recalc(_wb)
1164
}
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1165
function searchCleenCacheArea(o1,o2){
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
	var o3 = {};
	for (var _item in o2){
		if (o1 && o1.hasOwnProperty(_item)){
			if(o1[_item].min.getRow() > o2[_item].min.getRow()) o1[_item].min = new CellAddress(o2[_item].min.getRow(),o1[_item].min.getCol());
			if(o1[_item].min.getCol() > o2[_item].min.getCol()) o1[_item].min = new CellAddress(o1[_item].min.getRow(),o2[_item].min.getCol());
				
			if(o1[_item].max.getRow() < o2[_item].max.getRow()) o1[_item].max = new CellAddress(o2[_item].max.getRow(),o1[_item].max.getCol());
			if(o1[_item].max.getCol() < o2[_item].max.getCol()) o1[_item].max = new CellAddress(o1[_item].max.getRow(),o2[_item].max.getCol());
			
			o3[_item] = o1[_item];
		}
		else{
			o3[_item] = o2[_item];
		}
	}
	for (var _item in o1){
		if (o3 && o3.hasOwnProperty(_item)){
			if(o1[_item].min.getRow() > o3[_item].min.getRow()) o1[_item].min = new CellAddress(o3[_item].min.getRow(),o1[_item].min.getCol());
			if(o1[_item].min.getCol() > o3[_item].min.getCol()) o1[_item].min = new CellAddress(o1[_item].min.getRow(),o3[_item].min.getCol());
				
			if(o1[_item].max.getRow() < o3[_item].max.getRow()) o1[_item].max = new CellAddress(o3[_item].max.getRow(),o1[_item].max.getCol());
			if(o1[_item].max.getCol() < o3[_item].max.getCol()) o1[_item].max = new CellAddress(o1[_item].max.getRow(),o3[_item].max.getCol());
			
			o3[_item] = o1[_item];
		}
		else{
			o3[_item] = o1[_item];
		}
	}
	
	return o3;
}
function helpRecalc(dep1, nR, calculatedCells, wb){
	var sr1, sr2;
	for(var i = 0; i < dep1.badF.length; i++){
		for(var j = 0; j < dep1.depF.length; j++){
			if(dep1.badF[i] == dep1.depF[j])
				dep1.depF.splice(j,1);
		}
	}
	for(var j = 0; j < dep1.depF.length; j++){
		if( dep1.depF[j].nodeId in nR){
			nR[dep1.depF[j].nodeId] = undefined;
			delete nR[dep1.depF[j].nodeId]
			nR.length--;
		}
	}
	for(var j = 0; j < dep1.badF.length; j++){
		if( dep1.badF[j].nodeId in nR){
			nR[dep1.badF[j].nodeId] = undefined;
			delete nR[dep1.badF[j].nodeId]
			nR.length--;
		}
	}
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1220 1221
	sr1 = wb.recalcDependency(dep1.badF,true);

1222 1223 1224 1225 1226 1227
	for(var k = 0; k < dep1.depF.length; k++){
		if(dep1.depF[k].nodeId in calculatedCells){
			dep1.depF.splice(k,1);
			k--;
		}
	}
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1228 1229
	sr2 = wb.recalcDependency(dep1.depF,false);

1230 1231 1232
	for(var k = 0; k < dep1.depF.length; k++){
		calculatedCells[dep1.depF[k].nodeId] = dep1.depF[k].nodeId
	}
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1233
	return searchCleenCacheArea(sr1,sr2);
1234 1235 1236
}

function sortDependency(ws, ar){
1237
	var wb = ws.workbook, dep, sr1, sr2, sr, calculatedCells = {};
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
	/*
		Если необходим пересчет, то по списку пересчитываемых ячеек сортируем граф зависимостей и пересчиываем в получившемся порядке. Плохим ячейкам с цикличискими ссылками выставляем ошибку "#REF!".
	*/
	ws._BuildDependencies(ar);
	
	for(var id in ar){
		if( !wb.dependencyFormulas.nodeExist2( ws.Id, ar[id]) ) continue;
		dep = wb.dependencyFormulas.t_sort_slave( ws.Id, ar[id] );
		for(var i = 0; i < dep.badF.length; i++){
			for(var j = 0; j < dep.depF.length; j++){
				if(dep.badF[i] == dep.depF[j]){
					dep.depF.splice(j,1);
				}
			}
		}
1253 1254 1255 1256
//        sr1 = wb.recalcDependency(dep.badF,true);
        sr1 = helpRecalc(dep, wb.needRecalc, calculatedCells, wb);
//		sr2 = wb.recalcDependency(dep.depF,false);
		sr = searchCleenCacheArea( sr, sr1 );
1257 1258 1259 1260 1261 1262 1263
	}
	
	for(var _item in sr){
		wb.handlers.trigger("cleanCellCache",_item,new Asc.Range(0, sr[_item].min.getRow0(), wb.getWorksheetById(_item).getColsCount()-1, sr[_item].max.getRow0()), c_oAscCanChangeColWidth.numbers);
	}
}
function recalc(wb){
1264 1265
	var nR = wb.needRecalc, thas = wb, calculatedCells = new Object(), nRLength = nR.length, first = true,
        startActionOn = false, timerID, timeStart, timeEnd, timeCount = 0, timeoutID1, timeoutID2, sr = new Object();
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281

	function R(){
		if( nR.length > 0 ){
			timeStart = (new Date()).getTime();
			var dep1, f = false, id;
			for(var id1 in nR) {
				if( id1 == "length" ){
					continue;
				}
				id = id1;
				break;
			}
			
			if( id === undefined ) nR.length = 0;
			
			if( id in nR){
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1282
				var nRId0 = nR[id][0], nRId1 = nR[id][1], sr1,sr2;
1283 1284 1285 1286 1287 1288
				dep1 = thas.dependencyFormulas.t_sort_master( nRId0, nRId1 );
				sr1 = helpRecalc(dep1, nR, calculatedCells, thas);

				dep1 = thas.dependencyFormulas.t_sort_slave( nRId0, nRId1 );
				sr2 = helpRecalc(dep1, nR, calculatedCells, thas);
				
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1289
				sr = searchCleenCacheArea(sr,searchCleenCacheArea(sr1,sr2));
1290 1291 1292 1293 1294
                if ( nR[id] ) {
                    delete nR[id];
                    nR.length--;
                }
                id = undefined;
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
			}
			clearTimeout(timerID);
			timeEnd = (new Date()).getTime();
			timeCount += (timeEnd - timeStart);
			if(first){
				timeoutID1 = setTimeout(
					function(){
						var pr = Math.round( (nRLength - nR.length)/nRLength*10000 )/100;
						if( pr == 0 || timeCount*100/pr > 2000 ){
							timeoutID2 = setTimeout(
								function(){
									startActionOn = true;
									thas.handlers.trigger("asc_onStartAction",c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.Recalc);
								},
								0
							)
						}
					},
					500
				)
				first = false;
			}
			timerID = setTimeout(R,0);
		}
		else{
			first = false;
			thas.isNeedCacheClean = true;
			for(var _item in sr){
				thas.handlers.trigger("cleanCellCache",_item,new Asc.Range(0, sr[_item].min.getRow0(), thas.getWorksheetById(_item).getColsCount()-1, sr[_item].max.getRow0()), c_oAscCanChangeColWidth.numbers);
			}
			clearTimeout(timeoutID1);
			clearTimeout(timeoutID2);
			if( startActionOn )
				thas.handlers.trigger("asc_onEndAction",c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.Recalc);
			nR.length = 0;
		}
	}
	if( nR.length > 0 ){
		R();
	}
}

1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
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;
}
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
//-------------------------------------------------------------------------------------------------
$(function(){
	aStandartNumFormats = new Array();
	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";
1384
	aStandartNumFormats[22] = "m/d/yyyy h:mm";
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
	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] = "@";
	aStandartNumFormatsId = new Object();
	for(var i in aStandartNumFormats)
	{
		aStandartNumFormatsId[aStandartNumFormats[i]] = i - 0;
	}
});
//-------------------------------------------------------------------------------------------------
/**
 * @constructor
 */
function Workbook(sUrlPath, eventsHandlers, oApi){
	this.oApi = oApi;
	this.sUrlPath = sUrlPath;
	this.handlers = eventsHandlers;
	this.needRecalc = {length:0};
	this.dependencyFormulas = new DependencyGraph(this);
	this.nActive = 0;

Dmitry.Vikulov's avatar
Dmitry.Vikulov committed
1412 1413
	// Histoey & global counters
	History = new CHistory(this);
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
1414 1415

    g_oIdCounter = new CIdCounter();
Dmitry.Vikulov's avatar
minor  
Dmitry.Vikulov committed
1416
	g_oTableId = new CTableId();
1417 1418
	if ( this.oApi.User )
		g_oIdCounter.Set_UserId(this.oApi.User.asc_getId());
Dmitry.Vikulov's avatar
minor  
Dmitry.Vikulov committed
1419
	
1420 1421
	this.theme = null;
	this.clrSchemeMap = null;
1422 1423
	
	this.DefinedNames = new Object();
1424 1425
	this.oRealDefinedNames = new Object();
	this.oNameGenerator = new NameGenerator(this);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1426
	this.CellStyles = new CCellStyles();
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
	this.TableStyles = new CTableStyles();
	this.oStyleManager = new StyleManager(this);
	this.calcChain = new Array();
	this.aWorksheets = new Array();
	this.aWorksheetsById = new Object();
	this.cwf = {};
	this.isNeedCacheClean = true;
	this.startActionOn = false;
	this.aCollaborativeActions = new Array();
	this.bCollaborativeChanges = false;
1437 1438
	this.bUndoChanges = false;
	this.bRedoChanges = false;
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
	this.aCollaborativeChangeElements = new Array();
};
Workbook.prototype.initGlobalObjects=function(){
	g_oUndoRedoCell = new UndoRedoCell(this);
	g_oUndoRedoWorksheet = new UndoRedoWoorksheet(this);
	g_oUndoRedoWorkbook = new UndoRedoWorkbook(this);
	g_oUndoRedoCol = new UndoRedoRowCol(this, false);
	g_oUndoRedoRow = new UndoRedoRowCol(this, true);
	g_oUndoRedoComment = new UndoRedoComment(this);
	g_oUndoRedoAutoFilters = new UndoRedoAutoFilters(this);
1449
    g_oUndoRedoGraphicObjects = new UndoRedoGraphicObjects(this);
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
1450
    g_oIdCounter.Set_Load(false);
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
}
Workbook.prototype.init=function(){
	if(this.nActive < 0)
		this.nActive = 0;
	if(this.nActive >= this.aWorksheets.length)
		this.nActive = this.aWorksheets.length - 1;
	/*
		buildDependency необходимо запускать для построения графа зависимостей между ячейками.
		Сортировка графа производится при необходимости пересчета формул: 
			при открытии документа если есть ячейки помеченные как пересчитываемые или есть ячейки без значения.
	*/
1462 1463
    this.buildDependency();
	var nR = this.needRecalc, thas = this, calculatedCells = {}, nRLength = nR.length, timeStart, timeEnd, timeCount = 0, first = true, sr;
1464

1465
    if( nR.length > 0 ){
1466 1467 1468 1469 1470 1471 1472
        for ( var id in nR ) {
            var sr1, sr2;
            timeStart = (new Date()).getTime();
            var dep1, f = false;
            if ( id == "length" ) {
                continue;
            }
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1473

1474
            dep1 = thas.dependencyFormulas.t_sort_master( nR[id][0], nR[id][1] );
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 1517 1518 1519 1520 1521 1522 1523
            for ( var i = 0; i < dep1.badF.length; i++ ) {
                for ( var j = 0; j < dep1.depF.length; j++ ) {
                    if ( dep1.badF[i] == dep1.depF[j] )
                        dep1.depF.splice( j, 1 );
                }
            }
            for ( var j = 0; j < dep1.depF.length; j++ ) {
                if ( dep1.depF[j].nodeId in nR ) {
                    nR[dep1.depF[j].nodeId] = undefined;
                    delete nR[dep1.depF[j].nodeId]
                    nR.length--;
                }
            }
            for ( var j = 0; j < dep1.badF.length; j++ ) {
                if ( dep1.badF[j].nodeId in nR ) {
                    nR[dep1.badF[j].nodeId] = undefined;
                    delete nR[dep1.badF[j].nodeId]
                    nR.length--;
                }
            }
            sr1 = thas.recalcDependency( dep1.badF, true, true );

            for ( var k = 0; k < dep1.depF.length; k++ ) {
                if ( dep1.depF[k].nodeId in calculatedCells ) {
                    dep1.depF.splice( k, 1 );
                    k--;
                }
            }
            sr2 = thas.recalcDependency( dep1.depF, false );

            for ( var k = 0; k < dep1.depF.length; k++ ) {
                calculatedCells[dep1.depF[k].nodeId] = dep1.depF[k].nodeId
            }
            sr = searchCleenCacheArea( sr, searchCleenCacheArea( sr1, sr2 ) );

            timeEnd = (new Date()).getTime();
            timeCount += (timeEnd - timeStart);

        }

        first = false;
        thas.isNeedCacheClean = true;
        var ws = thas.getWorksheet( thas.getActive() );
        thas.handlers.trigger( "cleanCellCache", ws.getId(), new Asc.Range( 0, 0, ws.getColsCount() - 1, ws.getRowsCount() - 1 ), c_oAscCanChangeColWidth.numbers );
        thas.startActionOn = false;
        thas.handlers.trigger( "asc_onEndAction", c_oAscAsyncActionType.BlockInteraction, c_oAscAsyncAction.Recalc );

    }
1524

1525 1526 1527 1528 1529 1530 1531 1532
	//charts
	for(var i = 0, length = this.aWorksheets.length; i < length; ++i)
	{
		var ws = this.aWorksheets[i];
		ws.initPostOpen();
	}
};
Workbook.prototype.rebuildColors=function(){
1533 1534 1535
	g_oColorManager.rebuildColors();
	for(var i = 0 , length = this.aWorksheets.length; i < length; ++i)
		this.aWorksheets[i].rebuildColors();;
1536 1537 1538 1539
}
Workbook.prototype.getDefaultFont=function(){
	return g_oDefaultFont.fn;
};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
1540
Workbook.prototype.getDefaultSize=function(){
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
	return g_oDefaultFont.fs;
};
Workbook.prototype.getActive=function(){
	return this.nActive;
};
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){
	History.TurnOff();
    var oNewWorksheet = new Woorksheet(this, this.aWorksheets.length, true, sId);
	if(null != sName)
	{
		if(true == this.checkValidSheetName(sName))
			oNewWorksheet.sName = sName;
	}
    oNewWorksheet.init();
1589
	oNewWorksheet.initPostOpen();
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
	if(indexBefore >= 0 && indexBefore < this.aWorksheets.length)
		this.aWorksheets.splice(indexBefore, 0, oNewWorksheet);
	else
	{
		indexBefore = this.aWorksheets.length;
		this.aWorksheets.push(oNewWorksheet);
	}
	this.aWorksheetsById[oNewWorksheet.getId()] = oNewWorksheet;
	this._updateWorksheetIndexes();
	this.setActive(oNewWorksheet.index);
	if( indexBefore > 0 && indexBefore < this.aWorksheets.length-1 ){
		var sheetStart = this.getWorksheet(indexBefore-1).getId(),
			sheetStop  = this.getWorksheet(indexBefore+1).getId(),
			nodesSheetStart = this.dependencyFormulas.getNodeBySheetId(sheetStart),
			nodesSheetStop = this.dependencyFormulas.getNodeBySheetId(sheetStop),
			arr = {};
			
		for( var i = 0; i < nodesSheetStart.length; i++ ){
			var n = nodesSheetStart[i].getSlaveEdges();
			for( var id in n ){
				if( n[id].weightNode == 2 ){
					arr[n[id].nodeId] = n[id];
				}
				n[id].weightNode = 0;
			}
		}
		
		for( var i = 0; i < nodesSheetStop.length; i++ ){
			var n = nodesSheetStop[i].getSlaveEdges();
			for( var id in n ){
				if( n[id].weightNode == 2 ){
					arr[n[id].nodeId] = n[id];
				}
				n[id].weightNode = 0;
			}
		}
		
		for( var id in arr ){
			arr[id].cell.formulaParsed.buildDependencies();
		}
	}
	History.TurnOn();
	History.Create_NewPoint();
	History.Add(g_oUndoRedoWorkbook, historyitem_Workbook_SheetAdd, null, null, new UndoRedoData_SheetAdd(indexBefore, oNewWorksheet.getName(), null, oNewWorksheet.getId()));
	return oNewWorksheet.index;
};
Workbook.prototype.copyWorksheet=function(index, insertBefore, sName, sId){
	//insertBefore - optional
	if(index >= 0 && index < this.aWorksheets.length){
		History.TurnOff();
		var wsFrom = this.aWorksheets[index];
		var nameSheet = wsFrom.getName();
		var newSheet = wsFrom.clone(sId);
		if(null != sName)
		{
			if(true == this.checkValidSheetName(sName))
				newSheet.sName = sName;
		}
		newSheet.init();
1649
		newSheet.initPostOpen();
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
		if(null != insertBefore && insertBefore >= 0 && insertBefore < this.aWorksheets.length){
			//помещаем новый sheet перед insertBefore
			this.aWorksheets.splice(insertBefore, 0, newSheet);
		}
		else{
			//помещаем новый sheet в конец
			this.aWorksheets.push(newSheet);
		}
		this.aWorksheetsById[newSheet.getId()] = newSheet;
		this._updateWorksheetIndexes();

		//для формул. создаем копию this.cwf[this.Id] для нового листа.
		if ( this.cwf[wsFrom.getId()] ){
			this.cwf[newSheet.getId()] = { cells:{} };
			for( var id in this.cwf[wsFrom.getId()].cells ){
				this.cwf[newSheet.getId()].cells[id] = this.cwf[wsFrom.getId()].cells[id];
			}

			//очищаем и создаем новый граф зависимостей
			this.buildDependency();
		}
		History.TurnOn();
		History.Create_NewPoint();
		History.Add(g_oUndoRedoWorkbook, historyitem_Workbook_SheetAdd, null, null, new UndoRedoData_SheetAdd(insertBefore, newSheet.getName(), wsFrom.getId(), newSheet.getId()));
	}
};
Workbook.prototype.insertWorksheet=function(index, sheet, cwf){
	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;
	this._updateWorksheetIndexes();
	
	//восстанавливаем список ячеек с формулами для sheet
	this.cwf[sheet.getId()] = cwf;
	//очищаем и создаем новый граф зависимостей
	this.buildDependency();
}
Workbook.prototype.replaceWorksheet=function(indexFrom, indexTo){
	if(indexFrom >= 0 && indexFrom < this.aWorksheets.length &&
		indexTo >= 0 && indexTo < this.aWorksheets.length){
		History.TurnOff();
		var oWsTo = this.aWorksheets[indexTo];
		var tempW = {
					wFN: this.aWorksheets[indexFrom].getName(),
					wFI: indexFrom,
					wFId: this.aWorksheets[indexFrom].getId(),
					wTN: oWsTo.getName(),
					wTI: indexTo,
					wTId: oWsTo.getId()
				}
				
		var movedSheet = this.aWorksheets.splice(indexFrom,1);
		this.aWorksheets.splice(indexTo,0,movedSheet[0])
		this._updateWorksheetIndexes();

		/*
			Формулы:
				перестройка графа для трехмерных формул вида Sheet1:Sheet3!A1:A3, Sheet1:Sheet3!A1.
				пересчет трехмерных формул, перестройка формул при изменении положения листа: Sheet1, Sheet2, Sheet3, Sheet4 - Sheet1:Sheet4!A1 -> Sheet4, Sheet1, Sheet2, Sheet3 - Sheet1:Sheet3!A1;
		*/
		lockDraw(this);
		var a = this.dependencyFormulas.getNodeBySheetId(movedSheet[0].getId());
		for(var i=0;i<a.length;i++){
			var se = a[i].getSlaveEdges();
			if(se){
				for(var id in se){
1722
					var cID = se[id].cellId, _ws = this.getWorksheetById(se[id].sheetId), f = _ws.getCell2(cID).getCells()[0].sFormula;
1723 1724 1725
                    if( f == null || f == undefined ){
                        continue;
                    }
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
					if( f.indexOf(tempW.wFN+":") > 0 || f.indexOf(":"+tempW.wFN) > 0 ){
						var _c = _ws.getCell2(cID).getCells()[0];
						_c.setFormula(_c.formulaParsed.moveSheet(tempW).assemble());//Перестраиваем трехмерные ссылки в формуле.
						this.dependencyFormulas.deleteMasterNodes(_ws.Id, cID);
						if( !arrRecalc[_ws.getId()] ){
							arrRecalc[_ws.getId()] = {};
						}
						arrRecalc[_ws.getId()][cID] = cID;
						this.needRecalc[ getVertexId(_ws.getId(),cID) ] = [ _ws.getId(),cID ];
						if( this.needRecalc.length < 0) this.needRecalc.length = 0;
							this.needRecalc.length++;
					}
					else if( f.indexOf(_ws.getName()) < 0 ){
						this.dependencyFormulas.deleteMasterNodes(_ws.Id, cID);
						_ws._BuildDependencies({id:cID});
						if( !arrRecalc[_ws.getId()] ){
							arrRecalc[_ws.getId()] = {};
						}
						arrRecalc[_ws.getId()][cID] = cID;
						this.needRecalc[ getVertexId(_ws.getId(),cID) ] = [ _ws.getId(),cID ];
						if( this.needRecalc.length < 0) this.needRecalc.length = 0;
							this.needRecalc.length++;
					}
				}
			}
		}
		
		History.TurnOn();
		History.Create_NewPoint();
		History.Add(g_oUndoRedoWorkbook, historyitem_Workbook_SheetMove, null, null, new UndoRedoData_FromTo(indexFrom, indexTo), true);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1756
		buildRecalc(this);
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
		unLockDraw(this);
	}
};
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;
	
	var nNewActive = this.nActive;
	var removedSheet = this.aWorksheets.splice(nIndex, 1);
	if(removedSheet.length > 0)
	{
		History.TurnOff();
		//по всем удаленным листам пробегаемся и удаляем из workbook.cwf (cwf - cells with forluma) элементы с названием соответствующего листа.
		var _cwf;
		for(var i=0; i<removedSheet.length;i++){
			var name = removedSheet[i];
			_cwf = this.cwf[name.getId()];
			this.cwf[name.getId()] = null;
			delete this.cwf[name.getId()];
			delete this.aWorksheetsById[name.getId()];
		}
		
		lockDraw(this);
		var a = this.dependencyFormulas.getNodeBySheetId(removedSheet[0].getId());
		for(var i=0;i<a.length;i++){
			var se = a[i].getSlaveEdges();
			if(se){
				for(var id in se){
					if( se[id].sheetId != removedSheet[0].getId() ){
						var _ws = this.getWorksheetById(se[id].sheetId), f = _ws.getCell2(se[id].cellId).getCells()[0].sFormula, cID = se[id].cellId;
						if( !arrRecalc[_ws.getId()] ){
							arrRecalc[_ws.getId()] = {};
						}
						arrRecalc[_ws.getId()][cID] = cID;
						this.needRecalc[ getVertexId(_ws.getId(),cID) ] = [ _ws.getId(),cID ];
						if( this.needRecalc.length < 0) this.needRecalc.length = 0;
							this.needRecalc.length++;
					}
				}
			}
		}
		this.dependencyFormulas.removeNodeBySheetId(name.getId());
		var bFind = false;
		if(nNewActive < this.aWorksheets.length)
		{
			for(var i = nNewActive; i < this.aWorksheets.length; ++i)
				if(false == this.aWorksheets[i].getHidden())
				{
					bFind = true;
					nNewActive = i;
					break;
				}
		}
		if(false == bFind)
		{
			for(var i = nNewActive - 1; i >= 0; --i)
				if(false == this.aWorksheets[i].getHidden())
				{
					nNewActive = i;
					break;
				}
		}
		History.TurnOn();
		History.Create_NewPoint();
		var oRemovedSheet = removedSheet[0];
		History.Add(g_oUndoRedoWorkbook, historyitem_Workbook_SheetRemove, null, null, new UndoRedoData_SheetRemove(nIndex, oRemovedSheet.getId(), oRemovedSheet, _cwf));
		if(null != outputParams)
		{
			outputParams.sheet = oRemovedSheet;
			outputParams.cwf = _cwf;
		}
		this._updateWorksheetIndexes();
		this.nActive = nNewActive;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1841
		buildRecalc(this);
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918
		unLockDraw(this);
		return nNewActive;
	}
	return -1;
};
Workbook.prototype._updateWorksheetIndexes=function(){
	for(var i = 0, length = this.aWorksheets.length; i < length; ++i)
		this.aWorksheets[i]._setIndex(i);
};
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;
}
Workbook.prototype.checkValidSheetName=function(name){
	return name.length < g_nSheetNameMaxLength;
}
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;
}
Workbook.prototype.generateFontMap=function(){
	var oFontMap = new Object();
	oFontMap["Calibri"] = 1;
	oFontMap["Arial"] = 1;

	if(null != g_oDefaultFont.fn)
		oFontMap[g_oDefaultFont.fn] = 1;
	
	for(var i = 0, length = this.aWorksheets.length; i < length; ++i)
		this.aWorksheets[i].generateFontMap(oFontMap);
1919
	this.CellStyles.generateFontMap(oFontMap);
1920 1921 1922 1923 1924 1925
	
	var aRes = new Array();
	for(var i in oFontMap)
		aRes.push(i);
	return aRes;
};
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1926
Workbook.prototype.recalcWB = function(is3D){
1927 1928 1929 1930 1931 1932
	var dep1, thas = this, sr, sr1, sr2;
	if( this.dependencyFormulas.getNodesLength() > 0){
		if(is3D){
			for(var i=0; i<this.getWorksheetCount();i++){
				__ws = this.getWorksheet(i);
				for(var id in this.cwf[__ws.Id].cells){
1933 1934
					var c = new CellAddress(id);
					if( __ws._getCellNoEmpty(c.getRow0(),c.getCol0()).formulaParsed.is3D ){
1935
						dep1 = this.dependencyFormulas.t_sort_slave( __ws.Id, id );
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1936 1937 1938
						sr1 = thas.recalcDependency(dep1.badF,true);
						sr2 = thas.recalcDependency(dep1.depF,false);
						sr = searchCleenCacheArea( sr, searchCleenCacheArea( sr1, sr2 ) );
1939 1940 1941 1942 1943
					}
				}
			}
		}
		else{
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
1944 1945 1946 1947
            dep1 = this.dependencyFormulas.t_sort();
			sr1 = thas.recalcDependency(dep1.badF,true);
			sr2 = thas.recalcDependency(dep1.depF,false);
			sr = searchCleenCacheArea( sr, searchCleenCacheArea( sr1, sr2 ) );
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001
		}
		for(var _item in sr){
			this.handlers.trigger("cleanCellCache",_item,new Asc.Range(0, sr[_item].min.getRow0(),  this.getWorksheetById(_item).getColsCount()-1, sr[_item].max.getRow0()), c_oAscCanChangeColWidth.numbers);
		}
	}
}
Workbook.prototype.isDefinedNamesExists = function(name, sheetId){
	if(null != sheetId)
	{
		var ws = this.getWorksheetById(sheetId);
		if(null != ws)
		{
			var bExist = false;
			if( ws.DefinedNames )
				bExist = !!ws.DefinedNames[name];
			if(bExist)
				return bExist;
		}
	}
	if( this.DefinedNames ){
		return !!this.DefinedNames[name];
	}
	return false;
}
Workbook.prototype.getDefinesNames = function(name, sheetId){
	if(null != sheetId)
	{
		var ws = this.getWorksheetById(sheetId);
		if(null != ws)
		{
			if( ws.DefinedNames )
			{
				var oDefName = ws.DefinedNames[name];
				if(null != oDefName)
					return oDefName;
			}
		}
	}
	if( this.DefinedNames ){
		var oDefName = this.DefinedNames[name];
		if(null != oDefName)
			return oDefName;
	}
	return false;
}
Workbook.prototype.buildDependency = function(){
	dep = null;
	this.dependencyFormulas.clear();
	this.dependencyFormulas = null;
	this.dependencyFormulas = new DependencyGraph(this);
	for(var i in this.cwf){
		this.getWorksheetById(i)._BuildDependencies(this.cwf[i].cells);
	}
}
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
Workbook.prototype.recalcDependency = function(f,bad,notRecalc){
    if(f.length > 0){

        var sr = {};

        for(var i = 0; i < f.length; i++){
            if( f[i].cellId.indexOf(":") > -1 ) continue;

            var l = new CellAddress(f[i].cellId);

            if( !(f[i].sheetId in sr) ){
                sr[f[i].sheetId] = {max:new CellAddress(f[i].cellId),min:new CellAddress(f[i].cellId)}
            }

            if ( sr[f[i].sheetId].min.getRow() > l.getRow() )
                sr[f[i].sheetId].min = new CellAddress( l.getRow(), sr[f[i].sheetId].min.getCol() );

            if ( sr[f[i].sheetId].min.getCol() > l.getCol() )
                sr[f[i].sheetId].min = new CellAddress( sr[f[i].sheetId].min.getRow(), l.getCol() );

            if ( sr[f[i].sheetId].max.getRow() < l.getRow() )
                sr[f[i].sheetId].max = new CellAddress( l.getRow(), sr[f[i].sheetId].max.getCol() );

            if ( sr[f[i].sheetId].max.getCol() < l.getCol() )
                sr[f[i].sheetId].max = new CellAddress( sr[f[i].sheetId].max.getRow(), l.getCol() );

            if( !notRecalc )
                this.getWorksheetById( f[i].sheetId )._RecalculatedFunctions( f[i].cellId, bad );
        }

        return sr;
    }
}
2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108
Workbook.prototype.SerializeHistory = function(){
	var aRes = new Array();
	//соединяем изменения, которые были до приема данных с теми, что получились после.
	var aActions = this.aCollaborativeActions.concat(History.GetSerializeArray());
	if(aActions.length > 0)
	{
		var oMemory = new CMemory();
		var oThis = this;
		//создаем еще один элемент в undo/redo - взаимное расположение Sheet, чтобы не запутываться в add, move событиях
		var oSheetPlaceData = new Array();
		for(var i = 0, length = this.aWorksheets.length; i < length; ++i)
			oSheetPlaceData.push(this.aWorksheets[i].getId());
		aActions.push(new UndoRedoItemSerializable(g_oUndoRedoWorkbook, historyitem_Workbook_SheetPositions, null, null, new UndoRedoData_SheetPositions(oSheetPlaceData)));
		for(var i = 0, length = aActions.length; i < length; ++i)
		{
			var nPosStart = oMemory.GetCurPosition();
			var item = aActions[i];
			item.Serialize(oMemory, this.oApi.collaborativeEditing);
			var nPosEnd = oMemory.GetCurPosition();
			var nLen = nPosEnd - nPosStart;
			if(nLen > 0)
				aRes.push(nLen + ";" + oMemory.GetBase64Memory2(nPosStart, nLen));
		}
		//добавляем элемент, который содержит все используемые шрифты, чтобы их можно было загрузить в начале
		aRes.push("0;fontmap" + this.generateFontMap().join(","));
		this.aCollaborativeActions = new Array();
	}
	return aRes;
}
Workbook.prototype.DeserializeHistory = function(aChanges, fCallback){
	var bRes = false;
	var oThis = this;
	//сохраняем те изменения, которые были до приема данных, потому что дальше undo/redo будет очищено
	this.aCollaborativeActions = this.aCollaborativeActions.concat(History.GetSerializeArray());
	if(aChanges.length > 0)
	{
		this.bCollaborativeChanges = true;
		//собираем общую длину
		var dstLen = 0;
		var aIndexes = new Array();
		for(var i = 0, length = aChanges.length;i < length; ++i)
		{
			var sChange = aChanges[i];
			var nIndex = sChange.indexOf(";");
			if(-1 != nIndex)
			{
				dstLen += parseInt(sChange.substring(0, nIndex));
				nIndex++;
			}
			aIndexes.push(nIndex);
		}
		var pointer = g_memory.Alloc(dstLen);
		var stream = new FT_Stream2(pointer.data, dstLen);
		stream.obj = pointer.obj;
		var nCurOffset = 0;
		//пробегаемся первый раз чтобы заполнить oFontMap
		var oFontMap = new Object();//собираем все шрифтры со всех изменений
		var sFontMapString = "0;fontmap";
		for(var i = 0, length = aChanges.length; i < length; ++i)
		{
			var sChange = aChanges[i];
			if(sFontMapString == sChange.substring(0, sFontMapString.length))
			{
				var sFonts = sChange.substring(sFontMapString.length);
				var aFonts = sFonts.split(",");
				for(var j = 0, length2 = aFonts.length; j < length2; ++j)
					oFontMap[aFonts[j]] = 1;
			}
		}
		var aFontMap = new Array();
		for(var i in oFontMap)
			aFontMap.push(i);
		
		window["Asc"]["editor"]._loadFonts(aFontMap, function(){
2109 2110 2111
				History.Clear();
				History.Create_NewPoint();
				History.SetSelection(null, true);
2112
				var oHistoryPositions = null;//нужен самый последний historyitem_Workbook_SheetPositions
2113 2114
				var oRedoObjectParam = new Asc.RedoObjectParam();
				History.RedoPrepare(oRedoObjectParam);
2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128
				for(var i = 0, length = aChanges.length; i < length; ++i)
				{
					var sChange = aChanges[i];
					if(sFontMapString != sChange.substring(0, sFontMapString.length))
					{
						var oBinaryFileReader = new BinaryFileReader();
						nCurOffset = oBinaryFileReader.getbase64DecodedData2(sChange, aIndexes[i], stream, nCurOffset);
						var item = new UndoRedoItemSerializable();
						item.Deserialize(stream);
						if(null != item.oClass && null != item.nActionType)
						{
							if(g_oUndoRedoWorkbook == item.oClass && historyitem_Workbook_SheetPositions == item.nActionType)
								oHistoryPositions = item;
							else
2129
								History.RedoAdd(oRedoObjectParam, item.oClass, item.nActionType, item.nSheetId, item.oRange, item.oData);
2130 2131 2132 2133
						}
					}
				}
				if(null != oHistoryPositions)
2134
					History.RedoAdd(oRedoObjectParam, oHistoryPositions.oClass, oHistoryPositions.nActionType, oHistoryPositions.nSheetId, oHistoryPositions.oRange, oHistoryPositions.oData);
2135
			
2136
				History.RedoEnd(null, oRedoObjectParam);
2137
				oThis.bCollaborativeChanges = false;
2138 2139 2140 2141 2142
				History.Clear();
				if(null != fCallback)
					fCallback();
			});
	}
2143
};
2144 2145 2146 2147 2148 2149 2150 2151 2152
//-------------------------------------------------------------------------------------------------
/**
 * @constructor
 */
function Woorksheet(wb, _index, bAddUserId, sId){
	this.workbook = wb;
	this.DefinedNames = new Object();
	this.sName = this.workbook.getUniqueSheetNameFrom(g_sNewSheetNamePattern, false);
	this.bHidden = false;
2153
	this.dDefaultColWidth = null;
2154
	this.dDefaultheight = null;
2155
	this.nBaseColWidth = null;
2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171
	this.index = _index;
	this.Id = null;
	if(null != sId)
		this.Id = sId;
	else
	{
		if(bAddUserId)
			this.Id = this.workbook.oApi.User.asc_getId() + "_" + g_nNextWorksheetId++;
		else
			this.Id = g_nNextWorksheetId++;
	}

	this.nRowsCount = 0;
	this.nColsCount = 0;
	this.aGCells = new Object();// 0 based
	this.aCols = new Array();// 0 based
2172
	this.Drawings = new Array();
2173 2174
	this.TableParts = new Array();
	this.AutoFilter = null;
2175 2176 2177 2178
	this.oAllCol = null;
	this.objForRebuldFormula = {};
	this.aComments = new Array();
	this.aCommentsCoords = new Array();
2179 2180
	var oThis = this;
	this.mergeManager = new RangeDataManager(false, function(data, from, to){
2181
		if(History.Is_On() && (null != from || null != to))
2182 2183 2184
		{
			if(null != from)
				from = from.clone();
2185
			if(null != to)
2186
				to = to.clone();
2187 2188 2189 2190
			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)));
2191 2192 2193
		}
	});
	this.hyperlinkManager = new RangeDataManager(true, function(data, from, to){
2194
		if(History.Is_On() && (null != from || null != to))
2195
		{
2196 2197
			if(null != from)
				from = from.clone();
2198
			if(null != to)
2199
				to = to.clone();
2200 2201 2202
			var oHistoryRange = from;
			if(null == oHistoryRange)
				oHistoryRange = to;
2203 2204 2205 2206
			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));
2207
		}
2208 2209
		if(null != to)
			data.Ref = oThis.getRange3(to.r1, to.c1, to.r2, to.c2);
2210 2211
	});
	this.hyperlinkManager.setDependenceManager(this.mergeManager);
2212

2213
	this.sheetViews = [];
2214
	this.aConditionalFormatting = [];
2215
	this.sheetPr = null;
2216 2217 2218 2219
	
	this.nMaxRowId = 1;
	this.nMaxColId = 1;
};
2220 2221 2222 2223 2224
Woorksheet.prototype.rebuildColors=function(){
	this._forEachCell(function(cell){
		cell.cleanCache();
	});
}
2225
Woorksheet.prototype.generateFontMap=function(oFontMap){
2226 2227 2228 2229 2230 2231 2232
	//пробегаемся по Drawing
	for(var i = 0, length = this.Drawings.length; i < length; ++i)
	{
		var drawing = this.Drawings[i];
		if(drawing)
			drawing.getAllFonts(oFontMap);
	}
2233 2234 2235 2236 2237 2238 2239 2240
	//пробегаемся по колонкам
	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
2241
		oFontMap[this.oAllCol.xfs.font.fn] = 1;
2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277
	//пробегаемся строкам
	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;
					}
				}
			}
		}
	}
}
Woorksheet.prototype.clone=function(sNewId){
	var oNewWs;
	if(null != sNewId)
		oNewWs = new Woorksheet(this.workbook, this.workbook.aWorksheets.length, true, sNewId);
	else
		oNewWs = new Woorksheet(this.workbook, this.workbook.aWorksheets.length, true);
	oNewWs.sName = this.workbook.getUniqueSheetNameFrom(this.sName, true);
	oNewWs.bHidden = this.bHidden;
2278 2279
	oNewWs.nBaseColWidth = this.nBaseColWidth;
	oNewWs.dDefaultColWidth = this.dDefaultColWidth;
2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293
	oNewWs.dDefaultheight = this.dDefaultheight;
	oNewWs.index = this.index;
	oNewWs.nRowsCount = this.nRowsCount;
	oNewWs.nColsCount = this.nColsCount;
	if(this.TableParts)
		oNewWs.TableParts = Asc.clone(this.TableParts);
	if(this.AutoFilter)
		oNewWs.AutoFilter = Asc.clone(this.AutoFilter);
	for(var i in this.aCols)
		oNewWs.aCols[i] = this.aCols[i].clone();
	if(null != this.oAllCol)
		oNewWs.oAllCol = this.oAllCol.clone();
	for(var i in this.aGCells)
		oNewWs.aGCells[i] = this.aGCells[i].clone();
2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311
	var aMerged = this.mergeManager.getAll();
	oNewWs.mergeManager.stopRecalculate();
	for(var i in aMerged)
	{
		var elem = aMerged[i];
		var range = oNewWs.getRange3(elem.bbox.r1, elem.bbox.c1, elem.bbox.r2, elem.bbox.c2);
		range.mergeOpen();
	}
	oNewWs.mergeManager.startRecalculate();
	var aHyperlinks = this.hyperlinkManager.getAll();
	oNewWs.hyperlinkManager.stopRecalculate();
	for(var i in aHyperlinks)
	{
		var elem = aHyperlinks[i];
		var range = oNewWs.getRange3(elem.bbox.r1, elem.bbox.c1, elem.bbox.r2, elem.bbox.c2);
		range.setHyperlinkOpen(elem.data);
	}
	oNewWs.hyperlinkManager.startRecalculate();
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
2312
	if(null != this.Drawings && this.Drawings.length > 0)
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
2313 2314 2315 2316 2317 2318 2319 2320 2321
    {
        oNewWs.Drawings = [];
        var w = new CMemory();
        for(var i = 0; i < this.Drawings.length; ++i)
        {
            this.Drawings[i].graphicObject.writeToBinaryForCopyPaste(w);
        }
        var binary = w.pos + ";" + w.GetBase64Memory();
        var stream = CreateBinaryReader(binary, 0, binary.length);
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332
        var drawingObjects;
        if(this.Drawings[0] && this.Drawings[0].graphicObject && this.Drawings[0].graphicObject.drawingObjects)
        {
            drawingObjects = this.Drawings[0].graphicObject.drawingObjects;
        }
        else
        {
            drawingObjects = new DrawingObjects();
            drawingObjects.drawingDocument = new CDrawingDocument(drawingObjects);
        }
        //drawingObjects.init(new WorksheetView());
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
2333 2334 2335
        for(var i = 0; i < this.Drawings.length; ++i)
        {
            var obj = null;
2336 2337
			var objectType = stream.GetLong();
            switch (objectType)
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353
            {
                case CLASS_TYPE_SHAPE:
                {
                    obj = new CShape(null, null, null);
                    break;
                }
                case CLASS_TYPE_IMAGE:
                {
                    obj = new CImageShape(null, null);
                    break;
                }
                case CLASS_TYPE_GROUP:
                {
                    obj = new CGroupShape(null, null);
                    break;
                }
2354
                case CLASS_TYPE_CHART_AS_GROUP:
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
2355 2356 2357 2358 2359 2360 2361
                {
                    obj = new CChartAsGroup(null, null);
                    break;
                }
            }
            if(isRealObject(obj))
            {
2362 2363
                var drawingObject = drawingObjects.cloneDrawingObject(this.Drawings[i]);
                obj.readFromBinaryForCopyPaste2(stream, null, drawingObjects, null, null);
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
2364 2365 2366 2367 2368 2369
                drawingObject.graphicObject = obj;
                oNewWs.Drawings.push(drawingObject);
            }
        }
        //oNewWs.Drawings = this.Drawings.concat();
    }
2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453
	if(null != this.aComments) {
		for (var i = 0; i < this.aComments.length; i++) {
			var comment = new asc_CCommentData(this.aComments[i]);
			comment.wsId = oNewWs.getId();
			comment.setId();
			oNewWs.aComments.push(comment);
		}
	}		
	return oNewWs;
};
Woorksheet.prototype.init=function(){
	this.workbook.cwf[this.Id]={ cells:{} };
	var formulaShared = {};
	for(var rowid in this.aGCells)
	{
		var row = this.aGCells[rowid];
		for(var cellid in row.c)
		{
			var oCell = row.c[cellid];
			var sCellId = oCell.oId.getID();
			/*
				Проверяем содержит ли ячейка атрибуты f.t и f.si, если содержит, то у указанного диапазона, атрибут f.ref, достраиваем формулы.
			*/
			if(null != oCell.oFormulaExt)
			{
				if( oCell.oFormulaExt.t == ECellFormulaType.cellformulatypeShared ){
					if(null != oCell.oFormulaExt.si){
						if(null != oCell.oFormulaExt.ref){
							formulaShared[oCell.oFormulaExt.si] = 	{
																		fVal:new parserFormula(oCell.oFormulaExt.v,"",this),
																		fRef:function(t){
																				var r = t.getRange2(oCell.oFormulaExt.ref);
																				return {
																							c:r,
																							first:r.first
																						};
																			}(this)
																	}
								formulaShared[oCell.oFormulaExt.si].fVal.parse();
						}
						else{
							if( formulaShared[oCell.oFormulaExt.si] ){
								var fr = formulaShared[oCell.oFormulaExt.si].fRef;
								if( fr.c.containCell(oCell.oId) ){
									if( formulaShared[oCell.oFormulaExt.si].fVal.isParsed ){
										var off = oCell.getOffset3(fr.first);
										formulaShared[oCell.oFormulaExt.si].fVal.changeOffset(off);
										oCell.oFormulaExt.v = formulaShared[oCell.oFormulaExt.si].fVal.assemble();
										off.offsetCol *=-1;
										off.offsetRow *=-1;
										formulaShared[oCell.oFormulaExt.si].fVal.changeOffset(off);
									}
									this.workbook.cwf[this.Id].cells[sCellId] = sCellId;
								}
							}
						}
					}
				}
				if(oCell.oFormulaExt.v)
					oCell.setFormula(oCell.oFormulaExt.v);
					
				if(oCell.oFormulaExt.ca)
					oCell.sFormulaCA = true;
				
				/*
					Если ячейка содержит в себе формулу, то добавляем ее в список ячеек с формулами.
				*/
				if(oCell.sFormula){
					this.workbook.cwf[this.Id].cells[sCellId] = sCellId;
				}
				/*
					Строится список ячеек, которые необходимо пересчитать при открытии. Это ячейки имеющие атрибут f.ca или значение в которых неопределено.
				*/
				if(oCell.sFormula && (oCell.oFormulaExt.ca || !oCell.oValue.getValueWithoutFormat()) ){
					this.workbook.needRecalc[ getVertexId( this.Id, sCellId ) ] = [this.Id, sCellId];
					this.workbook.needRecalc.length++;
				}
				//в редакторе не работаем с расширенными формулами
				delete oCell.oFormulaExt;
			}
		}
	}
};
Woorksheet.prototype.initPostOpen = function(){
2454 2455
	this.mergeManager.startRecalculate();
	this.hyperlinkManager.startRecalculate();
2456 2457 2458 2459 2460 2461 2462
	//chart
	if(null != this.Drawings)
	{
		var oThis = this;
		for(var i = this.Drawings.length - 1; i >= 0; --i)
		{
			var obj = this.Drawings[i];
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
2463
			if(obj.graphicObject && obj.graphicObject.chart)
2464
			{
Sergey.Luzyanin's avatar
Sergey.Luzyanin committed
2465
				var chart = obj.graphicObject.chart;
2466
				if(chart.range.interval)
2467
				{
2468 2469 2470 2471 2472 2473
					var oRefParsed = parserHelp.parse3DRef(chart.range.interval);
					if (null !== oRefParsed) {
						// Получаем sheet по имени
						var ws = oThis.workbook.getWorksheetByName (oRefParsed.sheet);
						if (ws)
							chart.range.intervalObject = ws.getRange2(oRefParsed.range);
2474
					}
2475
				}
2476 2477
				if(null == chart.range.intervalObject)
					this.Drawings.splice(i, 1);
2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519
			}
		}
	}
	if (!this.PagePrintOptions) {
		// Даже если не было, создадим
		this.PagePrintOptions = new Asc.asc_CPageOptions();
	}
	if(null != this.PagePrintOptions)
	{
		var oPageMargins = this.PagePrintOptions.asc_getPageMargins();
		if(null == oPageMargins)
		{
			oPageMargins = new Asc.asc_CPageMargins ();
			this.PagePrintOptions.asc_setPageMargins(oPageMargins);
		}
		if(null == oPageMargins.asc_getLeft())
			oPageMargins.asc_setLeft(c_oAscPrintDefaultSettings.PageLeftField);
		if(null == oPageMargins.asc_getTop())
			oPageMargins.asc_setTop(c_oAscPrintDefaultSettings.PageTopField);
		if(null == oPageMargins.asc_getRight())
			oPageMargins.asc_setRight(c_oAscPrintDefaultSettings.PageRightField);
		if(null == oPageMargins.asc_getBottom())
			oPageMargins.asc_setBottom(c_oAscPrintDefaultSettings.PageBottomField);
		
		var oPageSetup = this.PagePrintOptions.asc_getPageSetup();
		if(null == oPageSetup)
		{
			oPageSetup = new Asc.asc_CPageSetup ();
			this.PagePrintOptions.asc_setPageSetup(oPageSetup);
		}
		if(null == oPageSetup.asc_getOrientation())
			oPageSetup.asc_setOrientation(c_oAscPrintDefaultSettings.PageOrientation);
		if(null == oPageSetup.asc_getWidth())
			oPageSetup.asc_setWidth(c_oAscPrintDefaultSettings.PageWidth);
		if(null == oPageSetup.asc_getHeight())
			oPageSetup.asc_setHeight(c_oAscPrintDefaultSettings.PageHeight);
		
		if(null == this.PagePrintOptions.asc_getGridLines())
			this.PagePrintOptions.asc_setGridLines(c_oAscPrintDefaultSettings.PageGridLines);
		if(null == this.PagePrintOptions.asc_getHeadings())
			this.PagePrintOptions.asc_setHeadings(c_oAscPrintDefaultSettings.PageHeadings);
	}
2520 2521 2522 2523 2524 2525

	// Sheet Views
	if (0 === this.sheetViews.length) {
		// Даже если не было, создадим
		this.sheetViews[0] = new asc.asc_CSheetViewSettings();
	}
2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565
};
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.getNextRowId=function(){
	return this.nMaxRowId++;
};
Woorksheet.prototype.getNextColId=function(){
	return this.nMaxColId++;
};
Woorksheet.prototype.getId=function(){
	return this.Id;
};
Woorksheet.prototype.getIndex=function(){
	return this.index;
};
Woorksheet.prototype.getName=function(){
	return this.sName !== undefined && this.sName.length > 0 ? this.sName : "";
};
Woorksheet.prototype.setName=function(name){
	if(name.length <= g_nSheetNameMaxLength)
	{
		var lastName = this.sName;
			this.sName = name;
		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);
2566
		}
2567 2568 2569
			
		if ( this.Drawings ) {
			for (var i = 0; i < this.Drawings.length; i++) {
2570 2571
				var drawingObject = this.Drawings[i];
				if ( drawingObject.graphicObject && drawingObject.isChart() ) {
2572
						var _lastName =  !rx_test_ws_name.test(lastName) ? "'" + lastName + "'" : lastName;
2573 2574 2575
						if ( drawingObject.graphicObject.chart.range.interval.indexOf(_lastName + "!") >= 0 ) {
							drawingObject.graphicObject.chart.range.interval = drawingObject.graphicObject.chart.range.interval.replace(_lastName, !rx_test_ws_name.test(this.sName) ? "'" + this.sName + "'" : this.sName);
						drawingObject.graphicObject.chart.rebuildSeries();
2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647
					}
				}
			}
		}
	}
};
Woorksheet.prototype.renameWsToCollaborate=function(name){
	var lastname = this.getName();
	//из-за особенностей реализации формул, сначала делаем parse со старым именем, потом преименовываем, потом assemble
	var aFormulas = new Array();
	//переименование для отправки изменений
	for(var i = 0, length = this.workbook.aCollaborativeActions.length; i < length; ++i)
	{
		var action = this.workbook.aCollaborativeActions[i];
		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});
						
					}
				}
			}
		}
	}
	//переименование для локальной версии
	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;
};
Woorksheet.prototype.setHidden=function(hidden){
	if(this.bHidden != hidden)
	{
		History.Create_NewPoint();
		History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_Hide, this.getId(), null, new UndoRedoData_FromTo(this.bHidden, hidden));
	}
	this.bHidden = hidden;
	if(true == this.bHidden && this.getIndex() == this.workbook.getActive())
	{
		//выбираем новый активный
		var activeWorksheet = this.getIndex();
2648 2649 2650 2651 2652 2653 2654
		var countWorksheets = this.workbook.getWorksheetCount();
		// Покажем следующий лист или предыдущий (если больше нет)
		var i, ws;
		for (i = activeWorksheet + 1; i < countWorksheets; ++i) {
			ws = this.workbook.getWorksheet(i);
			if (false === ws.getHidden()) {
				this.workbook.handlers.trigger("undoRedoHideSheet", i);
2655 2656 2657 2658
				return;
			}
		}
		// Не нашли справа, ищем слева от текущего
2659 2660 2661 2662
		for (i = activeWorksheet - 1; i >= 0; --i) {
			ws = this.workbook.getWorksheet(i);
			if (false === ws.getHidden()) {
				this.workbook.handlers.trigger("undoRedoHideSheet", i);
2663 2664 2665 2666 2667
				return;
			}
		}
	}
};
2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678
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()));

2679
	this.sheetViews[0].setSettings(options);
2680
};
2681 2682 2683 2684 2685 2686
Woorksheet.prototype.getRowsCount=function(){
	return this.nRowsCount;
};
Woorksheet.prototype.removeRows=function(start, stop){
	var oRange = this.getRange(new CellAddress(start, 0, 0), new CellAddress(stop, gc_nMaxCol0, 0));
	oRange.deleteCellsShiftUp();
2687
};
2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702
Woorksheet.prototype._removeRows=function(start, stop){
	lockDraw(this.workbook);
	History.Create_NewPoint();
	History.SetSelection(null, true);
	//start, stop 0 based
	var nDif = -(stop - start + 1);
	var aIndexes = new Array();
	for(var i in this.aGCells)
	{
		var nIndex = i - 0;
		if(nIndex >= start)
			aIndexes.push(nIndex);
	}
	//По возрастанию
	aIndexes.sort(fSortAscending);
2703
	var oDefRowPr = new UndoRedoData_RowProp();
2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719
	for(var i = 0, length = aIndexes.length; i < length; ++i)
	{
		var nIndex = aIndexes[i];
		var row = this.aGCells[nIndex];
		if(nIndex > stop)
		{
			if(false == row.isEmpty())
			{
				var oTargetRow = this._getRow(nIndex + nDif);
				oTargetRow.copyProperty(row);
			}
			for(var j in row.c)
				this._moveCellVer(nIndex, j - 0, nDif);	
		}
		else
		{
2720 2721 2722 2723
			var oOldProps = row.getHeightProp();
			if(false == Asc.isEqual(oOldProps, oDefRowPr))
				History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_RowProp, this.getId(), new Asc.Range(0, nIndex, gc_nMaxCol0, nIndex), new UndoRedoData_IndexSimpleProp(nIndex, true, oOldProps, oDefRowPr));
			row.setStyle(null);
2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734
			for(var j in row.c)
			{
				var nColIndex = j - 0;
				//удаляем ячейку
				this._removeCell(nIndex, nColIndex);
			}
            delete this.aGCells[nIndex];
		}
	}
	var oActualRange = {r1: start, c1: 0, r2: stop, c2: gc_nMaxCol0};
	var res = this.renameDependencyNodes( {offsetRow:nDif,offsetCol:0}, oActualRange );
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2735
	buildRecalc(this.workbook);
2736 2737
	unLockDraw(this.workbook);
		
2738 2739
//	for(var id  in res)
//		History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_RemoveCell, this.getId(), new Asc.Range(0, res[id].nRow, gc_nMaxCol0, res[id].nRow), new UndoRedoData_CellSimpleData(res[id].nRow, res[id].nCol, res[id].data, null));
2740 2741 2742 2743 2744 2745 2746
		
	History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_RemoveRows, this.getId(), new Asc.Range(0, start, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_FromToRowCol(true, start, stop));
	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();
2747
};
2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773
Woorksheet.prototype._insertRowsBefore=function(index, count){
	lockDraw(this.workbook);
	var oActualRange = {r1: index, c1: 0, r2: index + count - 1, c2: gc_nMaxCol0};
	History.Create_NewPoint();
	History.SetSelection(null, true);
	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));
	History.TurnOff();
	//index 0 based
	var aIndexes = new Array();
	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())
		{
2774
			var oTargetRow = this._getRow(nIndex + count);
2775 2776 2777 2778 2779 2780
			oTargetRow.copyProperty(row);
		}
		for(var j in row.c)
			this._moveCellVer(nIndex, j - 0, count);
        delete this.aGCells[nIndex];
	}
2781
    if(null != oPrevRow && false == this.workbook.bUndoChanges && false == this.workbook.bRedoChanges)
2782 2783 2784 2785 2786
    {
        for(var i = 0; i < count; ++i)
        {
            var row = this._getRow(index + i);
            row.copyProperty(oPrevRow);
2787
			row.hd = null;
2788 2789 2790
        }
    }
	var res = this.renameDependencyNodes({offsetRow:count,offsetCol:0},oActualRange);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2791
	buildRecalc(this.workbook);
2792 2793 2794 2795
	unLockDraw(this.workbook);
	
	this.nRowsCount += count;
	
2796 2797
//	for(var id  in res)
//		History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_RemoveCell, this.getId(), new Asc.Range(0, res[id].nRow, gc_nMaxCol0, res[id].nRow), new UndoRedoData_CellSimpleData(res[id].nRow, res[id].nCol, res[id].data, null));
2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811
		
	History.TurnOn();
	return true;
};
Woorksheet.prototype.insertRowsAfter=function(index, count){
	//index 0 based
	return this.insertRowsBefore(index + 1, count);
};
Woorksheet.prototype.getColsCount=function(){
	return this.nColsCount;
};
Woorksheet.prototype.removeCols=function(start, stop){
	var oRange = this.getRange(new CellAddress(0, start, 0), new CellAddress(gc_nMaxRow0, stop, 0));
	oRange.deleteCellsShiftLeft();
2812
};
2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847
Woorksheet.prototype._removeCols=function(start, stop){
	lockDraw(this.workbook);
	History.Create_NewPoint();
	History.SetSelection(null, true);
	//start, stop 0 based
	var nDif = -(stop - start + 1);
	for(var i in this.aGCells)
	{
		var nRowIndex = i - 0;
		var row = this.aGCells[i];
		var aIndexes = new Array();
		for(var j in row.c)
		{
			var nIndex = j - 0;
			if(nIndex >= start)
				aIndexes.push(nIndex);
		}
		//сортируем по возрастанию
		aIndexes.sort(fSortAscending);
		for(var j = 0, length = aIndexes.length; j < length; ++j)
		{
			var nIndex = aIndexes[j];
			if(nIndex > stop)
			{
				this._moveCellHor(nRowIndex, nIndex, nDif, {r1: 0, c1: start, r2: gc_nMaxRow0, c2: stop});
			}
			else
			{
				//удаляем ячейку
				this._removeCell(nRowIndex, nIndex);
			}
		}
	}
	var oActualRange = {r1: 0, c1: start, r2: gc_nMaxRow0, c2: stop};
	var res = this.renameDependencyNodes( {offsetRow:0,offsetCol:nDif}, oActualRange );
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2848
	buildRecalc(this.workbook);
2849 2850
	unLockDraw(this.workbook);
	
2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862
	var oDefColPr = new UndoRedoData_ColProp();
	for(var i = start; i <= stop; ++i)
	{
		var col = this.aCols[i];
		if(null != col)
		{
			var oOldProps = col.getWidthProp();
			if(false == Asc.isEqual(oOldProps, oDefColPr))
				History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_ColProp, this.getId(), new Asc.Range(0, 0, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_IndexSimpleProp(i, false, oOldProps, oDefColPr));
			col.setStyle(null);
		}
	}
2863
	this.aCols.splice(start, stop - start + 1);
2864 2865 2866 2867 2868 2869
	for(var i = start, length = this.aCols.length; i < length; ++i)
	{
		var elem = this.aCols[i];
		if(null != elem)
			elem.moveHor(nDif);
	}
2870
	
2871 2872
//	for(var id  in res)
//		History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_RemoveCell, this.getId(), new Asc.Range(0, res[id].nRow, gc_nMaxCol0, res[id].nRow), new UndoRedoData_CellSimpleData(res[id].nRow, res[id].nCol, res[id].data, null));
2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909
		
	History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_RemoveCols, this.getId(), new Asc.Range(0, 0, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_FromToRowCol(false, start, stop));
	return true;
};
Woorksheet.prototype.insertColsBefore=function(index, count){
	var oRange = this.getRange(new CellAddress(0, index, 0), new CellAddress(gc_nMaxRow0, index + count - 1, 0));
	oRange.addCellsShiftRight();
};
Woorksheet.prototype._insertColsBefore=function(index, count){
	lockDraw(this.workbook);
	var oActualRange = {r1: 0, c1: index, r2: gc_nMaxRow0, c2: index + count - 1};
	History.Create_NewPoint();
	History.SetSelection(null, true);
	History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_AddCols, this.getId(), new Asc.Range(0, 0, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_FromToRowCol(false, index, index + count - 1));
	History.TurnOff();
	//index 0 based
	for(var i in this.aGCells)
	{
		var nRowIndex = i - 0;
		var row = this.aGCells[i];
		var aIndexes = new Array();
		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);
		}
	}
	
	var res = this.renameDependencyNodes({offsetRow:0,offsetCol:count},oActualRange);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
2910
	buildRecalc(this.workbook);
2911 2912 2913 2914 2915 2916 2917 2918 2919 2920
	unLockDraw(this.workbook);
	
    var oPrevCol = null;
    if(index > 0)
        oPrevCol = this.aCols[index - 1];
	if(null != this.oAllCol)
		oPrevCol = this.oAllCol;
	for(var i = 0; i < count; ++i)
    {
        var oNewCol = null;
2921
        if(null != oPrevCol && false == this.workbook.bUndoChanges && false == this.workbook.bRedoChanges)
2922 2923
        {
           oNewCol = oPrevCol.clone();
2924
		   oNewCol.hd = null;
2925 2926 2927 2928 2929
           oNewCol.BestFit = null;
           oNewCol.index = index + i; 
        }
		this.aCols.splice(index, 0, oNewCol);
    }
2930 2931 2932 2933 2934 2935
	for(var i = index + count, length = this.aCols.length; i < length; ++i)
	{
		var elem = this.aCols[i];
		if(null != elem)
			elem.moveHor(count);
	}
2936 2937
	this.nColsCount += count;
	
2938 2939
//	for(var id  in res)
//		History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_RemoveCell, this.getId(), new Asc.Range(0, res[id].nRow, gc_nMaxCol0, res[id].nRow), new UndoRedoData_CellSimpleData(res[id].nRow, res[id].nCol, res[id].data, null));
2940 2941 2942 2943 2944 2945 2946 2947 2948
	
	History.TurnOn();
	return true;
};
Woorksheet.prototype.insertColsAfter=function(index, count){
	//index 0 based
	return this.insertColsBefore(index + 1, count);
};
Woorksheet.prototype.getDefaultWidth=function(){
2949
	return this.dDefaultColWidth;
2950 2951 2952 2953 2954 2955 2956
};
Woorksheet.prototype.getColWidth=function(index){
	//index 0 based
	//Результат в пунктах
	var col = this._getColNoEmptyWithAll(index);
	if(null != col && null != col.width)
		return col.width;
2957
	var dResult = this.dDefaultColWidth;
2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033
	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();
	History.SetSelection(null, true);
	var oThis = this;
	var fProcessCol = function(col){
		if(col.width != width)
		{
			var oOldProps = col.getWidthProp();
			col.width = width;
			col.CustomWidth = true;
			col.BestFit = null;
			col.hd = null;
			var oNewProps = col.getWidthProp();
			if(false == oOldProps.isEqual(oNewProps))
				History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_ColProp, oThis.getId(), new Asc.Range(0, 0, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_IndexSimpleProp(col.index, false, oOldProps, oNewProps));
		}
	};
	if(0 == start && gc_nMaxCol0 == stop)
	{
		var col = this.getAllCol();
		fProcessCol(col);
	}
	else
	{
		for(var i = start; i <= stop; i++){
			var col = this._getCol(i);
			fProcessCol(col);
		}
	}
};
Woorksheet.prototype.setColHidden=function(bHidden, start, stop){
	//start, stop 0 based
	if(null == start)
		return;
	if(null == stop)
		stop = start;
	History.Create_NewPoint();
	History.SetSelection(null, true);
	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))
				History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_ColProp, oThis.getId(), new Asc.Range(0, 0, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_IndexSimpleProp(col.index, false, oOldProps, oNewProps));
		}
	};
	if(0 != start && gc_nMaxCol0 == stop)
	{
3034 3035 3036 3037 3038 3039 3040
		var col = null;
		if(false == bHidden)
			col = this.oAllCol;
		else
			col = this.getAllCol();
		if(null != col)
			fProcessCol(col);
3041 3042 3043 3044
	}
	else
	{
		for(var i = start; i <= stop; i++){
3045 3046 3047 3048 3049 3050 3051
			var col = null;
			if(false == bHidden)
				col = this._getColNoEmpty(i);
			else
				col = this._getCol(i);
			if(null != col)
				fProcessCol(col);
3052 3053 3054
		}
	}
};
3055
Woorksheet.prototype.setColBestFit=function(bBestFit, width, start, stop){
3056 3057 3058 3059 3060 3061 3062 3063 3064
	//start, stop 0 based
	if(null == start)
		return;
	if(null == stop)
		stop = start;
	History.Create_NewPoint();
	History.SetSelection(null, true);
	var oThis = this;
	var fProcessCol = function(col){
3065 3066
		var oOldProps = col.getWidthProp();
		if(bBestFit)
3067
		{
3068 3069 3070 3071 3072 3073 3074 3075 3076
			col.BestFit = bBestFit;
			col.hd = null;
		}
		else
			col.BestFit = null;
		col.width = width;
		var oNewProps = col.getWidthProp();
		if(false == oOldProps.isEqual(oNewProps))
			History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_ColProp, oThis.getId(), new Asc.Range(0, 0, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_IndexSimpleProp(col.index, false, oOldProps, oNewProps));
3077 3078 3079
	};
	if(0 != start && gc_nMaxCol0 == stop)
	{
3080 3081 3082 3083 3084 3085 3086
		var col = null;
		if(bBestFit && gc_dDefaultColWidthCharsAttribute == width)
			col = this.oAllCol;
		else
			col = this.getAllCol();
		if(null != col)
			fProcessCol(col);
3087 3088 3089 3090
	}
	else
	{
		for(var i = start; i <= stop; i++){
3091 3092 3093 3094 3095 3096 3097
			var col = null;
			if(bBestFit && gc_dDefaultColWidthCharsAttribute == width)
				col = this._getColNoEmpty(i);
			else
				col = this._getCol(i);
			if(null != col)
				fProcessCol(col);
3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144
		}
	}
};
Woorksheet.prototype.getDefaultHeight=function(){
	return this.dDefaultheight;
};
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();
	History.SetSelection(null, true);
	for(var i = start;i <= stop; i++){
		var oCurRow = this._getRow(i);
		if(oCurRow.h != height)
		{
			var oOldProps = oCurRow.getHeightProp();
			oCurRow.h = height;
			oCurRow.CustomHeight = true;
			oCurRow.hd = null;
			var oNewProps = oCurRow.getHeightProp();
			if(false == Asc.isEqual(oOldProps, oNewProps))
				History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_RowProp, this.getId(), new Asc.Range(0, i, gc_nMaxCol0, i), new UndoRedoData_IndexSimpleProp(i, true, oOldProps, oNewProps));
		}
	}
};
Woorksheet.prototype.setRowHidden=function(bHidden, start, stop){
	//start, stop 0 based
	if(null == start)
		return;
	if(null == stop)
		stop = start;
	History.Create_NewPoint();
	History.SetSelection(null, true);
	for(var i = start;i <= stop; i++){
3145 3146 3147 3148 3149 3150
		var oCurRow = null;
		if(false == bHidden)
			oCurRow = this._getRowNoEmpty(i);
		else
			oCurRow = this._getRow(i);
		if(null != oCurRow && oCurRow.hd != bHidden)
3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162
		{
			var oOldProps = oCurRow.getHeightProp();
			if(bHidden)
				oCurRow.hd = bHidden;
			else
				oCurRow.hd = null;
			var oNewProps = oCurRow.getHeightProp();
			if(false == Asc.isEqual(oOldProps, oNewProps))
				History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_RowProp, this.getId(), new Asc.Range(0, i, gc_nMaxCol0, i), new UndoRedoData_IndexSimpleProp(i, true, oOldProps, oNewProps));
		}
	}
};
3163
Woorksheet.prototype.setRowBestFit=function(bBestFit, height, start, stop){
3164 3165 3166 3167 3168 3169 3170 3171
	//start, stop 0 based
	if(null == start)
		return;
	if(null == stop)
		stop = start;
	History.Create_NewPoint();
	History.SetSelection(null, true);
	for(var i = start;i <= stop; i++){
3172 3173 3174 3175 3176 3177
		var oCurRow = null;
		if(true == bBestFit && gc_dDefaultRowHeightAttribute == height)
			oCurRow = this._getRowNoEmpty(i);
		else
			oCurRow = this._getRow(i);
		if(null != oCurRow)
3178 3179 3180 3181
		{
			var oOldProps = oCurRow.getHeightProp();
			if(true == bBestFit)
				oCurRow.CustomHeight = null;
3182 3183 3184
			else
				oCurRow.CustomHeight = true;
			oCurRow.height = height;
3185
			var oNewProps = oCurRow.getHeightProp();
3186
			if(false == oOldProps.isEqual(oNewProps))
3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307
				History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_RowProp, this.getId(), new Asc.Range(0, i, gc_nMaxCol0, i), new UndoRedoData_IndexSimpleProp(i, true, oOldProps, oNewProps));
		}
	}
};
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){
	if( sRange.indexOf("$") > -1)
		sRange = sRange.replace(/\$/g,"");
	var nIndex = sRange.indexOf(":");
	if(-1 != nIndex){
		var sFirstCell = sRange.substring(0, nIndex);
		var sLastCell = sRange.substring(nIndex + 1);
		var oFirstAddr, oLastAddr;
		
		if( sFirstCell == sLastCell ){
			if( !sFirstCell.match(/[^a-z]/ig) ){
				oFirstAddr = new CellAddress(sFirstCell+"1");
				oLastAddr = new CellAddress(sLastCell+(gc_nMaxRow+""));
			}
			else if( !sFirstCell.match(/[^0-9]/) ){
				oFirstAddr = new CellAddress("A"+sFirstCell);
				oLastAddr = new CellAddress(g_oCellAddressUtils.colnumToColstr(gc_nMaxCol)+sLastCell);
			}
			else{
				oFirstAddr = new CellAddress(sFirstCell);
				oLastAddr = new CellAddress(sLastCell);
			}
		}
		else{
			oFirstAddr = new CellAddress(sFirstCell);
			oLastAddr = new CellAddress(sLastCell);
		}
		if(oFirstAddr.isValid() && oLastAddr.isValid()){
			if( (gc_nMaxCol == oFirstAddr.getCol() || gc_nMaxRow == oFirstAddr.getRow()) && oFirstAddr.id != sRange.toUpperCase()){
				//    A:  1:2
				if(gc_nMaxRow == oFirstAddr.getRow())
					return this.getRange(new CellAddress(1, oFirstAddr.getCol()), new CellAddress(gc_nMaxRow, oLastAddr.getCol()));
				else
					return this.getRange(new CellAddress( oFirstAddr.getRow(), 1), new CellAddress(oLastAddr.getRow(), gc_nMaxCol));
			}
			else
				return this.getRange(oFirstAddr, oLastAddr);
		}
		return null;
	}
	else{
		var oCellAddr = new CellAddress(sRange);
		if(oCellAddr.isValid()){
			if( (gc_nMaxCol == oCellAddr.getCol() || gc_nMaxRow == oCellAddr.getRow()) && oCellAddr.id != sRange.toUpperCase()){
				//    A:  1:2
				if(gc_nMaxRow == oCellAddr.getRow())
					return this.getRange(new CellAddress(1, oCellAddr.getCol()), new CellAddress(gc_nMaxRow, oCellAddr.getCol()));
				else
					return this.getRange(new CellAddress( oCellAddr.getRow(), 1), new CellAddress(oCellAddr.getRow(), gc_nMaxCol));
			}
			else
				return this.getRange(oCellAddr, oCellAddr);
		}
	}
	return null;
};
Woorksheet.prototype.getRange3=function(r1, c1, r2, c2){
	var nRowMin = r1;
	var nRowMax = r2;
	var nColMin = c1;
	var nColMax = c2;
	if(r1 > r2){
		nRowMax = r1;
		nRowMin = r2;
	}
	if(c1 > c2){
		nColMax = c1;
		nColMin = c2;
	}
	return new Range(this, nRowMin, nColMin, nRowMax, nColMax);
}
Woorksheet.prototype._getRows=function(){
	return this.aGCells;
};
Woorksheet.prototype._getCols=function(){
	return this.aCols;
};
Woorksheet.prototype._removeCell=function(nRow, nCol, cell){
	if(null != cell)
	{
		nRow = cell.oId.getRow0();
		nCol = cell.oId.getCol0();
	}
	var row = this.aGCells[nRow];
	if(null != row)
	{
		var cell = row.c[nCol];
		if(null != cell)
		{
			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, this.getId(), new Asc.Range(0, nRow, gc_nMaxCol0, nRow), new UndoRedoData_CellSimpleData(nRow, nCol, oUndoRedoData_CellData, null));
			}
			
			this.helperRebuildFormulas(cell,cell.getName(),cell.getName());
3308

3309
            var node = this.workbook.dependencyFormulas.getNode2( this.Id, cell.getName() );
3310
            if ( node ) {
3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322
                for ( var i = 0; i < node.length; i++ ) {
                    var n = node[i].getSlaveEdges();
                    if ( n ) {
                        for ( var id in n ) {
                            if ( n[id].cell && n[id].cell.sFormula ) {
                                History.Add( g_oUndoRedoWorksheet,
                                    historyitem_Worksheet_RemoveCellFormula,
                                    n[id].sheetId,
                                    new Asc.Range( n[id].cell.oId.getCol0(), n[id].cell.oId.getRow0(), n[id].cell.oId.getCol0(), n[id].cell.oId.getRow0() ),
                                    new UndoRedoData_CellSimpleData( n[id].cell.oId.getRow0(), n[id].cell.oId.getCol0(), null, null, n[id].cell.sFormula )
                                );
                            }
3323 3324 3325 3326 3327
                        }
                    }
                }
            }

3328 3329 3330 3331
			if( !arrRecalc[this.getId()] ){
				arrRecalc[this.getId()] = {};
			}
			arrRecalc[this.getId()][cell.getName()] = cell.getName();
Sergey.Konovalov's avatar
Sergey.Konovalov committed
3332
            if( this.workbook.dependencyFormulas.getNode(this.getId(),this.getName()) && !this.workbook.needRecalc[ getVertexId(this.getId(),cell.getName()) ] ){
3333 3334 3335 3336
                this.workbook.needRecalc[ getVertexId(this.getId(),cell.getName()) ] = [ this.getId(),cell.getName() ];
                if( this.workbook.needRecalc.length < 0) this.workbook.needRecalc.length = 0;
                this.workbook.needRecalc.length++;
            }
3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362
			
			delete row.c[nCol];
			if(row.isEmpty())
				delete this.aGCells[nRow];
		}
	}
};
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();
		oCurCell.create(xfs, new CellAddress(row, col, 0));
		oCurRow.c[col] = oCurCell;
		if(row + 1 > this.nRowsCount)
			this.nRowsCount = row + 1;
		if(col + 1 > this.nColsCount)
			this.nColsCount = col + 1;
3363
		//History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_CreateCell, this.getId(), null, new UndoRedoData_CellSimpleData(row, col, null, null));
3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375
	}
	return oCurCell;
};
Woorksheet.prototype._getCell2=function(cellId){
	var oCellAddress = new CellAddress(cellId);
	return this._getCell(oCellAddress.getRow0(), oCellAddress.getCow0());
};
Woorksheet.prototype._getCellNoEmpty=function(row, col){
	//0-based
	var oCurCell;
	var oCurRow = this.aGCells[row];
	if(oCurRow)
Sergey.Konovalov's avatar
Sergey.Konovalov committed
3376 3377 3378 3379
	{
		var cell = oCurRow.c[col];
		return cell ? cell : null;
	}
3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407
	return null;
};
Woorksheet.prototype._getRowNoEmpty=function(row){
	//0-based
	var oCurRow = this.aGCells[row];
	if(oCurRow)
		return oCurRow;
	return null;
};
Woorksheet.prototype._getColNoEmpty=function(col){
	//0-based
	var oCurCol = this.aCols[col];
	if(oCurCol)
		return oCurCol;
	return null;
};
Woorksheet.prototype._getColNoEmptyWithAll=function(col){
	var oRes = this._getColNoEmpty(col);
	if(null == oRes)
		oRes = this.oAllCol;
	return oRes;
};
Woorksheet.prototype._getRow=function(row){
	//0-based
	var oCurRow = this.aGCells[row];
	if(!oCurRow){
		oCurRow = new Row(this);
		oCurRow.create(row + 1);
3408 3409
		if(null != this.oAllCol && null != this.oAllCol.xfs)
			oCurRow.xfs = this.oAllCol.xfs.clone();
3410 3411
		this.aGCells[row] = oCurRow;
		this.nRowsCount = row > this.nRowsCount ? row : this.nRowsCount ;
3412
		//History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_CreateRow, this.getId(), null, new UndoRedoData_SingleProperty(row));
3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437
	}
	return oCurRow;
};
Woorksheet.prototype._removeRow=function(index){
	delete this.aGCells[index];
};
Woorksheet.prototype._getCol=function(index){
	//0-based
	var oCurCol;
	if(-1 == index)
		oCurCol = this.getAllCol();
	else
	{
		oCurCol = this.aCols[index];
		if(null == oCurCol)
		{
			if(null != this.oAllCol)
			{
				oCurCol = this.oAllCol.clone();
				oCurCol.index = index;
			}
			else
				oCurCol = new Col(this, index);
			this.aCols[index] = oCurCol;
			this.nColsCount = index > this.nColsCount ? index : this.nColsCount;
3438
			//History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_CreateCol, this.getId(), null, new UndoRedoData_SingleProperty(index));
3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477
		}
	}
	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)
	{
		var lastName = cell.getName();//старое имя
		cell.moveHor(dif);
		var newName = cell.getName();
		var row = this._getRow(nRow);
		row.c[nCol + dif] = cell;
		delete row.c[nCol];
		
		this.helperRebuildFormulas(cell,lastName,cell.getName());
		
	}
};
Woorksheet.prototype._moveCellVer=function(nRow, nCol, dif){
	var cell = this._getCellNoEmpty(nRow, nCol);
	if(cell)
	{
		var lastName = cell.getName();//старое имя
		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];

		this.helperRebuildFormulas(cell,lastName,cell.getName());
	}
};
3478
Woorksheet.prototype._prepareMoveRangeGetCleanRanges=function(oBBoxFrom, oBBoxTo){
3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507
	var intersection = oBBoxFrom.intersectionSimple(oBBoxTo);
	var aRangesToCheck = [];
	if(null != intersection)
	{
		var oThis = this;
		var fAddToRangesToCheck = function(aRangesToCheck, r1, c1, r2, c2)
		{
			if(r1 <= r2 && c1 <= c2)
				aRangesToCheck.push(oThis.getRange3(r1, c1, r2, c2));
		}
		if(intersection.r1 == oBBoxTo.r1 && intersection.c1 == oBBoxTo.c1)
		{
			fAddToRangesToCheck(aRangesToCheck, oBBoxTo.r1, intersection.c2 + 1, intersection.r2, oBBoxTo.c2);
			fAddToRangesToCheck(aRangesToCheck, intersection.r2 + 1, oBBoxTo.c1, oBBoxTo.r2, oBBoxTo.c2);
		}
		else if(intersection.r2 == oBBoxTo.r2 && intersection.c1 == oBBoxTo.c1)
		{
			fAddToRangesToCheck(aRangesToCheck, oBBoxTo.r1, oBBoxTo.c1, intersection.r1 - 1, oBBoxTo.c2);
			fAddToRangesToCheck(aRangesToCheck, intersection.r1, intersection.c2 + 1, oBBoxTo.r2, oBBoxTo.c2);
		}
		else if(intersection.r1 == oBBoxTo.r1 && intersection.c2 == oBBoxTo.c2)
		{
			fAddToRangesToCheck(aRangesToCheck, oBBoxTo.r1, oBBoxTo.c1, intersection.r2, intersection.c1 - 1);
			fAddToRangesToCheck(aRangesToCheck, intersection.r2 + 1, oBBoxTo.c1, oBBoxTo.r2, oBBoxTo.c2);
		}
		else if(intersection.r2 == oBBoxTo.r2 && intersection.c2 == oBBoxTo.c2)
		{
			fAddToRangesToCheck(aRangesToCheck, oBBoxTo.r1, oBBoxTo.c1, intersection.r1 - 1, oBBoxTo.c2);
			fAddToRangesToCheck(aRangesToCheck, intersection.r1, oBBoxTo.c1, oBBoxTo.r2, intersection.c1 - 1);
3508 3509
		}
	}
3510 3511
	else
		aRangesToCheck.push(this.getRange3(oBBoxTo.r1, oBBoxTo.c1, oBBoxTo.r2, oBBoxTo.c2));
3512 3513 3514 3515 3516 3517 3518
	return aRangesToCheck;
}
Woorksheet.prototype._prepareMoveRange=function(oBBoxFrom, oBBoxTo){
	var res = 0;
	if(oBBoxFrom.isEqual(oBBoxTo))
		return res;
	var aRangesToCheck = this._prepareMoveRangeGetCleanRanges(oBBoxFrom, oBBoxTo);
3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535
	for(var i = 0, length = aRangesToCheck.length; i < length; i++)
	{
		var range = aRangesToCheck[i];
		var aMerged = this.mergeManager.get(range.getBBox0());
		if(aMerged.outer.length > 0)
			return -2;
		range._foreachNoEmpty(
			function(cell){
				if(!cell.isEmptyTextString())
				{
					res = -1;
					return res;
				}
			});
		if(0 != res)
			return res;
	}
3536 3537
	return res;
}
3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566
Woorksheet.prototype._moveRecalcGraph=function(oBBoxFrom, offset){
    var move = this.workbook.dependencyFormulas.helper(oBBoxFrom,this.Id), rec = {length:0};
    for(var id in move.recalc){
        var n = move.recalc[id];
        var _sn = n.getSlaveEdges2();
        for( var _id in _sn ){
            rec[_sn[_id].nodeId] = [ _sn[_id].sheetId, _sn[_id].cellId ];
            rec.length++;
        }
    }

    for( var id in move.move ){
        var n = move.move[id];
        var _sn = n.getSlaveEdges2();
        for( var _id in _sn ){
            var cell = _sn[_id].returnCell();
            if( undefined == cell || null == cell ) { continue; }
            if( cell.formulaParsed ){
                cell.formulaParsed.shiftCells( offset, oBBoxFrom, n, this.Id, false );
                cell.setFormula(cell.formulaParsed.assemble());
                rec[cell.getName()] = [ cell.ws.getId(), cell.getName() ];
                rec.length++;
            }
        }
    }

    return rec;
}
Woorksheet.prototype._moveRange=function(oBBoxFrom, oBBoxTo){
3567 3568 3569
	if(oBBoxFrom.isEqual(oBBoxTo))
		return;
	var oThis = this;
3570 3571 3572
	History.Create_NewPoint();
	History.SetSelection(new Asc.Range(oBBoxFrom.c1, oBBoxFrom.r1, oBBoxFrom.c2, oBBoxFrom.r2));
	History.SetSelectionRedo(new Asc.Range(oBBoxTo.c1, oBBoxTo.r1, oBBoxTo.c2, oBBoxTo.r2));
3573
	History.StartTransaction();
3574
	
3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589
	var offset = { offsetRow : oBBoxTo.r1 - oBBoxFrom.r1, offsetCol : oBBoxTo.c1 - oBBoxFrom.c1 };
	//запоминаем то что нужно переместить
	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];
				if(null != cell)
					oTempRow[j + offset.offsetCol] = cell;
3590 3591 3592
			}
		}
	}
3593
	if(false == this.workbook.bUndoChanges && false == this.workbook.bRedoChanges)
3594
	{
3595 3596
		var aMerged = this.mergeManager.get(oBBoxFrom);
		if(aMerged.inner.length > 0)
3597
		{
3598 3599 3600 3601 3602 3603
			aTempObj.merged = aMerged.inner;
			for(var i = 0, length = aTempObj.merged.length; i < length; i++)
			{
				var elem = aTempObj.merged[i];
				this.mergeManager.remove(elem.bbox, elem);
			}
3604
		}
3605 3606
		var aHyperlinks = this.hyperlinkManager.get(oBBoxFrom);
		if(aHyperlinks.inner.length > 0)
3607
		{
3608 3609 3610 3611 3612 3613
			aTempObj.hyperlinks = aHyperlinks.inner;
			for(var i = 0, length = aTempObj.hyperlinks.length; i < length; i++)
			{
				var elem = aTempObj.hyperlinks[i];
				this.hyperlinkManager.remove(elem.bbox, elem);
			}
3614 3615 3616
		}
	}
	//удаляем to через историю, для undo
3617 3618 3619
	var aRangesToCheck = this._prepareMoveRangeGetCleanRanges(oBBoxFrom, oBBoxTo);
	for(var i = 0, length = aRangesToCheck.length; i < length; i++)
		aRangesToCheck[i].cleanAll();
3620 3621 3622 3623 3624 3625 3626
	//перемещаем без истории
	History.TurnOff();
	//удаляем from без истории, потому что эти данные не терются а перемещаются
	var oRangeFrom = this.getRange3(oBBoxFrom.r1, oBBoxFrom.c1, oBBoxFrom.r2, oBBoxFrom.c2);
	oRangeFrom._setPropertyNoEmpty(null, null, function(cell, nRow0, nCol0, nRowStart, nColStart){
		var row = oThis._getRowNoEmpty(nRow0);
		if(null != row)
3627
			delete row.c[nCol0];
3628 3629
	});
	//lockDraw(this.workbook);
3630
    var rec = this._moveRecalcGraph(oBBoxFrom, offset);
3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645
	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;
				// var sFormula = oTempCell.getFormula();
				// if("" != sFormula)
					// oTempCell.setValue("=" + sFormula);
3646 3647 3648 3649 3650 3651

                if( oTempCell.sFormula ){
                    this.workbook.cwf[this.Id].cells[oTempCell.getName()] = oTempCell.getName();
                    rec[ oTempCell.getName() ] = [ this.Id, oTempCell.getName() ];
                    rec.length++;
                }
3652 3653 3654
			}
		}
	}
3655

3656 3657 3658 3659 3660 3661 3662 3663 3664 3665
    var move = this.workbook.dependencyFormulas.helper(oBBoxTo,this.Id);
    for(var id in move.recalc){
        var n = move.recalc[id];
        var _sn = n.getSlaveEdges2();
        for( var _id in _sn ){
            rec[_sn[_id].nodeId] = [ _sn[_id].sheetId, _sn[_id].cellId ];
            rec.length++;
        }
    }

3666 3667 3668
	this.workbook.buildDependency();
	this.workbook.needRecalc = rec;
	recalc(this.workbook);
3669 3670 3671 3672
	
	// this.renameDependencyNodes( offset, oBBoxFrom );
	// buildRecalc(this.workbook);
	// unLockDraw(this.workbook);
3673 3674
	History.TurnOn();
	if(false == this.workbook.bUndoChanges && false == this.workbook.bRedoChanges)
3675
	{
3676
		if(null != aTempObj.merged)
3677
		{
3678 3679 3680 3681 3682 3683
			for(var i = 0, length = aTempObj.merged.length; i < length; i++)
			{
				var elem = aTempObj.merged[i];
				elem.bbox.setOffset(offset);
				this.mergeManager.add(elem.bbox, elem.data);
			}
3684
		}
3685
		if(null != aTempObj.hyperlinks)
3686
		{
3687 3688 3689 3690 3691 3692
			for(var i = 0, length = aTempObj.hyperlinks.length; i < length; i++)
			{
				var elem = aTempObj.hyperlinks[i];
				elem.bbox.setOffset(offset);
				this.hyperlinkManager.add(elem.bbox, elem.data);
			}
3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704
		}
	}
	//расширяем границы
	if(oBBoxFrom.r2 > this.nRowsCount)
		this.nRowsCount = oBBoxFrom.r2 + 1;
	if(oBBoxFrom.c2 > this.nColsCount)
		this.nColsCount = oBBoxFrom.c2 + 1;
	if(oBBoxTo.r2 > this.nRowsCount)
		this.nRowsCount = oBBoxTo.r2 + 1;
	if(oBBoxTo.c2 > this.nColsCount)
		this.nColsCount = oBBoxTo.c2 + 1;
	
3705 3706
	History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_MoveRange,
				this.getId(), new Asc.Range(0, 0, gc_nMaxCol0, gc_nMaxRow0),
3707
				new UndoRedoData_FromTo(new UndoRedoData_BBox(oBBoxFrom), new UndoRedoData_BBox(oBBoxTo)));
3708
	History.EndTransaction();
3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743
	return true;
}
Woorksheet.prototype._shiftCellsLeft=function(oBBox){
	lockDraw(this.workbook);
	//todo удаление когда есть замерженые ячейки
	var nLeft = oBBox.c1;
	var nRight = oBBox.c2;
	var dif = nLeft - nRight - 1;
	for(var i = oBBox.r1; i <= oBBox.r2; i++){
		var row = this.aGCells[i];
		if(row){
			var aIndexes = new Array();
			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);
				}
			}
		}
	}
	
	var res = this.renameDependencyNodes( {offsetRow:0,offsetCol:dif}, oBBox );
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
3744
	buildRecalc(this.workbook);
3745 3746 3747 3748
	unLockDraw(this.workbook);
	
	//todo проверить не уменьшились ли границы таблицы
	
3749 3750
//	for(var id  in res)
//		History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_RemoveCell, this.getId(), new Asc.Range(0, res[id].nRow, gc_nMaxCol0, res[id].nRow), new UndoRedoData_CellSimpleData(res[id].nRow, res[id].nCol, res[id].data, null));
3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789
	
	History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_ShiftCellsLeft, this.getId(), new Asc.Range(0, oBBox.r1, gc_nMaxCol0, oBBox.r1), new UndoRedoData_BBox(oBBox));
};
Woorksheet.prototype._shiftCellsUp=function(oBBox){
	lockDraw(this.workbook);
	var nTop = oBBox.r1;
	var nBottom = oBBox.r2;
	var dif = nTop - nBottom - 1;
	var aIndexes = new Array();
	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);
				}
			}
		}
	}
	
	var res = this.renameDependencyNodes({offsetRow:dif,offsetCol:0}, oBBox );
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
3790
	buildRecalc(this.workbook);
3791 3792 3793 3794
	unLockDraw(this.workbook);
	
	//todo проверить не уменьшились ли границы таблицы
	
3795 3796 3797
//	for(var id  in res)
//		History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_RemoveCell, this.getId(), new Asc.Range(0, res[id].nRow, gc_nMaxCol0, res[id].nRow), new UndoRedoData_CellSimpleData(res[id].nRow, res[id].nCol, res[id].data, null));

3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832
	History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_ShiftCellsTop, this.getId(), new Asc.Range(0, oBBox.r1, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_BBox(oBBox));
};
Woorksheet.prototype._shiftCellsRight=function(oBBox){
	lockDraw(this.workbook);
	History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_ShiftCellsRight, this.getId(), new Asc.Range(0, oBBox.r1, gc_nMaxCol0, oBBox.r1), new UndoRedoData_BBox(oBBox));
	History.TurnOff();
	var nLeft = oBBox.c1;
	var nRight = oBBox.c2;
	var dif = nRight - nLeft + 1;
	for(var i = oBBox.r1; i <= oBBox.r2; i++){
		var row = this.aGCells[i];
		if(row){
			var aIndexes = new Array();
			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);
				}
			}
		}
	}
	
	var res = this.renameDependencyNodes({offsetRow:0,offsetCol:dif}, oBBox);;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
3833
	buildRecalc(this.workbook);
3834 3835
	unLockDraw(this.workbook);
		
3836 3837
//	for(var id  in res)
//		History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_RemoveCell, this.getId(), new Asc.Range(0, res[id].nRow, gc_nMaxCol0, res[id].nRow), new UndoRedoData_CellSimpleData(res[id].nRow, res[id].nCol, res[id].data, null));
3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871
	
	History.TurnOn();
};
Woorksheet.prototype._shiftCellsBottom=function(oBBox){
	lockDraw(this.workbook);
	History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_ShiftCellsBottom, this.getId(), new Asc.Range(0, oBBox.r1, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_BBox(oBBox));
	History.TurnOff();
	var nTop = oBBox.r1;
	var nBottom = oBBox.r2;
	var dif = nBottom - nTop + 1;
	var aIndexes = new Array();
	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);
			}
		}
	}

	var res = this.renameDependencyNodes({offsetRow:dif,offsetCol:0}, oBBox);
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
3872
	buildRecalc(this.workbook);
3873 3874
	unLockDraw(this.workbook);
		
3875 3876
//	for(var id  in res)
//		History.Add(g_oUndoRedoWorksheet, historyitem_Worksheet_RemoveCell, this.getId(), new Asc.Range(0, res[id].nRow, gc_nMaxCol0, res[id].nRow), new UndoRedoData_CellSimpleData(res[id].nRow, res[id].nCol, res[id].data, null));
3877 3878 3879 3880 3881 3882 3883 3884 3885 3886
	
	History.TurnOn();
};
Woorksheet.prototype._setIndex=function(ind){
	this.index = ind;
}
Woorksheet.prototype._BuildDependencies=function(cellRange){
	/*
		Построение графа зависимостей.
	*/
3887
	var c, ca;
3888
	for(var i in cellRange){
3889 3890
		ca = new CellAddress(i);
		c = this._getCellNoEmpty(ca.getRow0(),ca.getCol0());
3891

3892
		if( c && c.sFormula ){
3893
			c.formulaParsed = new parserFormula( c.sFormula, c.oId.getID(), this );
3894
                c.formulaParsed.parse();
3895 3896
			c.formulaParsed.buildDependencies();
		}
3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914
	}
}
Woorksheet.prototype._RecalculatedFunctions=function(cell,bad){
	var thas = this;
	function adjustCellFormat(c, ftext) {
		// ищет в формуле первый рэндж и устанавливает формат ячейки как формат первой ячейки в рэндже
		var match = (/[^a-z0-9:]([a-z]+\d+:[a-z]+\d+|[a-z]+:[a-z]+|\d+:\d+|[a-z]+\d+)/i).exec('='+ftext);
		if (!match) {return;}
		var m = match[1].split(":")[0];
		if (m.search(/^[a-z]+$/i) >= 0) {
			m = m + "1";
		} else if (m.search(/^\d+$/) >= 0) {
			m = "A" + m;
		}
		var ca = new CellAddress(m);
		if( g_oDefaultNum.f == c.getNumFormatStr() )
			c.setNumFormat(thas.getCell(ca).getNumFormatStr());
	}
3915
	
3916 3917
	if( cell.indexOf(":")>-1 ) return;
	
3918 3919 3920 3921
	var celladd = this.getRange2(cell).getFirst(),
		__cell = this._getCellNoEmpty( celladd.getRow0(),celladd.getCol0() ), res;
	
	if( !__cell || !__cell.sFormula )
3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962
		return;

	/*
		bad - флаг, показывающий, что ячейка находится в списке плохих ячеек (имеются циклические ссылки на ячейку), после сортировки графа зависимостей.
	*/
	if(!bad){
		res = __cell.formulaParsed.calculate();
	}
	else {
		res = new cError( cErrorType.bad_reference )
	}
	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;
3963 3964 3965 3966
            case cElementType.name:
				__cell.oValue.type = CellValueType.Error;
				__cell.oValue.text = res.getValue().toString();
				break;
3967 3968 3969 3970 3971 3972
			default:
				__cell.oValue.type = CellValueType.String;
				__cell.oValue.text = res.getValue().toString();
		}
		__cell.setFormulaCA(res.ca);
		if( res.numFormat !== undefined && res.numFormat >= 0){
3973 3974 3975 3976

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

3977 3978 3979 3980 3981 3982
		}
		else if( res.numFormat !== undefined && res.numFormat == -1 ){
			adjustCellFormat(__cell,__cell.sFormula);
		}
	}
}
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
3983
Woorksheet.prototype._ReBuildFormulas=function(cellRange){
3984 3985 3986
	/*
		Если существуют трехмерные ссылки на ячейки, то у них необходимо поменять имя листа на новое после переименования листа.
	*/
3987
	var c, ca;
3988
	for(var i in cellRange){
3989 3990 3991 3992
		ca = new CellAddress(i);
		c = this._getCellNoEmpty(ca.getRow0(),ca.getCol0());
		
		if( c && c.formulaParsed && c.formulaParsed.is3D ){
3993 3994 3995 3996
			c.setFormula(c.formulaParsed.assemble());
		}
	}
}
3997
Woorksheet.prototype.renameDependencyNodes = function(offset, oBBox, rec, noDelete){
3998
	var objForRebuldFormula = this.workbook.dependencyFormulas.checkOffset(oBBox, offset, this.Id, noDelete);
3999
	var c = {};
4000 4001 4002 4003
	for ( var id in objForRebuldFormula.move ){
		var n = objForRebuldFormula.move[id].node;
		var _sn = n.getSlaveEdges2();
		for( var _id in _sn ){
4004
			var cell = _sn[_id].returnCell(), cellName;
4005
			if( undefined == cell ) { continue; }
4006
            cellName = cell.getName();
4007 4008 4009
			if( cell.formulaParsed ){
				cell.formulaParsed.shiftCells( objForRebuldFormula.move[id].offset, oBBox, n, this.Id, objForRebuldFormula.move[id].toDelete );
				cell.setFormula(cell.formulaParsed.assemble());
4010
				c[cellName] = cell;
4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029
			}
		}
		if( n.cellId.indexOf(":")<0){
			var cell = n.returnCell();
			if( cell && cell.formulaParsed ){
				c[cell.getName()] = cell;
			}
		}
	}
	for ( var id in objForRebuldFormula.stretch ){
		var n = objForRebuldFormula.stretch[id].node;
		var _sn = n.getSlaveEdges2();
		if( _sn == null ){
			if ( n.newCellId ){
				n = this.workbook.dependencyFormulas.getNode(n.sheetId,n.newCellId)
				_sn = n.getSlaveEdges2();
			}
		}
		for( var _id in _sn ){
4030
			var cell = _sn[_id].returnCell(), cellName = cell.getName();
4031 4032 4033
			if( cell && cell.formulaParsed ){
				cell.formulaParsed.stretchArea( objForRebuldFormula.stretch[id].offset, oBBox, n, this.Id );
				cell.setFormula(cell.formulaParsed.assemble());
4034
				c[cellName] = cell;
4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046
			}
		}
	}
	
	var id = null;
	for ( id in objForRebuldFormula ){
		if( id == "recalc" ) continue;
		for(var _id in objForRebuldFormula[id] )
			this.workbook.dependencyFormulas.deleteNode( objForRebuldFormula[id][_id].node );
	}
	
	for( var i in c ){
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
4047 4048 4049 4050 4051 4052 4053 4054 4055
        var ws = c[i].ws;
        if( ws.getCell2(c[i].getName()).getCells()[0].formulaParsed ){
            var n = c[i].getName();
            c[i].formulaParsed.setCellId( n );
            this.workbook.cwf[c[i].ws.Id].cells[n] = n;
            c[i].formulaParsed.buildDependencies();
            this.workbook.needRecalc[ getVertexId( c[i].ws.Id, n ) ] = [ c[i].ws.Id, n ];
            this.workbook.needRecalc.length++;
        }
4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070
		c[i] = null;
		delete c[i];
	}

	for( var id in objForRebuldFormula.recalc ){
		var n = objForRebuldFormula.recalc[id];
		var _sn = n.getSlaveEdges();
		for( var _id in _sn ){
			if( !_sn[_id].isArea ){
				this.workbook.needRecalc[ _sn[_id].nodeId ] = [ _sn[_id].sheetId, _sn[_id].cellId ];
				this.workbook.needRecalc.length++;
			}
		}
	}
	
4071
	if ( false !== rec && lc <= 1 )
4072 4073 4074
		recalc(this.workbook);
	
}
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
4075
Woorksheet.prototype.helperRebuildFormulas = function(cell,lastName){
4076 4077 4078 4079 4080 4081 4082 4083 4084 4085
	if( cell.sFormula ){
		this.workbook.cwf[this.Id].cells[lastName] = null;
		delete this.workbook.cwf[this.Id].cells[lastName];
	}
}
Woorksheet.prototype.getAllCol = function(){
	if(null == this.oAllCol)
		this.oAllCol = new Col(this, g_nAllColIndex);
	return this.oAllCol;
}
4086
Woorksheet.prototype.getHyperlinkByCell = function(row, col){
4087 4088 4089
	var oHyperlink = this.hyperlinkManager.getByCell(row, col);
	return oHyperlink ? oHyperlink.data : null;
};
4090
Woorksheet.prototype.getMergedByCell = function(row, col){
4091 4092 4093
	var oMergeInfo = this.mergeManager.getByCell(row, col);
	return oMergeInfo ? oMergeInfo.bbox : null;
};
4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117
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);
	}
}
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;
}
4118 4119 4120
Woorksheet.prototype.expandRangeByMerged = function(range){
	if(null != range)
	{
4121 4122
		var aOuter = this._expandRangeByMergedGetOuter(range);
		if(aOuter.length > 0)
4123 4124
		{
			range = range.clone();
4125
			while(aOuter.length > 0)
4126
			{
4127 4128 4129
				for(var i = 0, length = aOuter.length; i < length; i++)
					range.union2(aOuter[i].bbox);
				aOuter = this._expandRangeByMergedGetOuter(range);
4130 4131 4132 4133
			}
		}
	}
	return range;
4134
};
4135 4136 4137 4138 4139 4140 4141
//-------------------------------------------------------------------------------------------------
/**
 * @constructor
 */
function Cell(worksheet){
	this.ws = worksheet;
	this.sm = worksheet.workbook.oStyleManager;
4142
	this.cs = worksheet.workbook.CellStyles;
4143 4144
	this.oValue = new CCellValue(this);
	this.xfs = null;
4145 4146
	this.tableXfs = null;
	this.conditionalFormattingXfs = null;
4147
	this.bNeedCompileXfs = true;
4148
	this.compiledXfs = null;
4149 4150 4151 4152
	this.oId = null;
	this.oFormulaExt = null;
	this.sFormula = null;
	this.formulaParsed = null;
4153
}
4154 4155 4156 4157 4158 4159 4160
Cell.prototype.getStyle=function(){
	if(this.bNeedCompileXfs)
	{
		this.bNeedCompileXfs = false;
		this.compileXfs();
	}
	return this.compiledXfs;
4161
};
4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182
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;
		}
	}
4183
};
4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223
Cell.prototype.clone=function(){
	var oNewCell = new Cell(this.ws);
	oNewCell.oId = new CellAddress(this.oId.getRow(), this.oId.getCol());
	if(null != this.xfs)
		oNewCell.xfs = this.xfs.clone();
	oNewCell.oValue = this.oValue.clone(oNewCell);
	if(null != this.sFormula)
		oNewCell.sFormula = this.sFormula;
	return oNewCell;
};
Cell.prototype.create=function(xfs, oId){
	this.xfs = xfs;
	this.oId = oId;
};
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;
}
Cell.prototype.Remove=function(){
	this.ws._removeCell(null, null, this);
};
Cell.prototype.getName=function(){
	return this.oId.getID();
};
4224 4225 4226
Cell.prototype.cleanCache=function(){
	this.oValue.cleanCache();
}
4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250
Cell.prototype.setFormula=function(val){
	this.sFormula = val;
	this.oValue.cleanCache();
}
Cell.prototype.setValue=function(val,callback){
	var ret = true;
	var DataOld = null;
	if(History.Is_On())
		DataOld = this.getValueData();
    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);
	var wb = this.ws.workbook;
	var ws = this.ws;
	if(false == numFormat.isTextFormat())
	{
		/*
			Устанавливаем значение в Range ячеек. При этом происходит проверка значения на формулу.
			Если значение является формулой, то проверяем содержиться ли в ячейке формула или нет, если "да" - то очищаем в графе зависимостей список, от которых зависит формула(masterNodes), позже будет построен новый. Затем выставляем флаг о необходимости дальнейшего пересчета, и заносим ячейку в список пересчитываемых ячеек.
		*/
		if( null != val && val[0] == "=" && val.length > 1){
4251 4252 4253 4254 4255 4256 4257

            var oldFP = undefined;

            if( this.formulaParsed  )
                oldFP = this.formulaParsed;

            this.formulaParsed = new parserFormula(val.substring(1),this.oId.getID(),this.ws);
4258 4259 4260 4261 4262 4263 4264 4265
			if( !this.formulaParsed.parse() ){
				switch( this.formulaParsed.error[this.formulaParsed.error.length-1] ){
					case c_oAscError.ID.FrmlWrongFunctionName:
						break;
					default :{
						wb.handlers.trigger("asc_onError",this.formulaParsed.error[this.formulaParsed.error.length-1], c_oAscError.Level.NoCritical);
						if( callback )
							callback(false);
4266 4267 4268
                        if( oldFP !== undefined ){
                            this.formulaParsed = oldFP;
                        }
4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302
						return;
					}
				}
			}
			else{
				val = "="+this.formulaParsed.assemble();
			}
		}
	}
	//удаляем старые значения
	this.oValue.clean();
	var needRecalc = false;
	var ar = {};
	if( null != val && val[0] != "=" || true == numFormat.isTextFormat()){
		if (this.sFormula){
			if ( this.oId.getID() in wb.cwf[ws.Id].cells){
				wb.dependencyFormulas.deleteMasterNodes( ws.Id, this.oId.getID() );
				delete wb.cwf[ws.Id].cells[this.oId.getID()];
			}
			needRecalc = true;
			ar[this.oId.getID()] = this.oId.getID();
		}
		else{
			if( wb.dependencyFormulas.nodeExist2( ws.Id, this.oId.getID() ) ){
				needRecalc = true;
				ar[this.oId.getID()] = this.oId.getID();
			}
		}
	}
	else{
		wb.dependencyFormulas.deleteMasterNodes( ws.Id, this.oId.getID() );
		needRecalc = true;
		wb.cwf[ws.Id].cells[this.oId.getID()] = this.oId.getID();
		ar[this.oId.getID()] = this.oId.getID();
4303 4304 4305 4306 4307 4308
        if( !arrRecalc[this.ws.getId()] ){
            arrRecalc[this.ws.getId()] = {};
        }
        arrRecalc[this.ws.getId()][this.oId.getID()] = this.oId.getID();
        wb.needRecalc[ getVertexId(this.ws.getId(),this.oId.getID()) ] = [ this.ws.getId(),this.oId.getID() ];
        wb.needRecalc.length++;
4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326
	}
	this.sFormula = null;
	this.setFormulaCA(false);
	if(val){
		if(false == numFormat.isTextFormat() && val[0] == "=" && val.length > 1){
			this.setFormula( val.substring(1) );
		}
		else {
			this.oValue.setValue(val);
		}
	}
	if ( needRecalc && this.ws.workbook.isNeedCacheClean ){
		/*
			Если необходим пересчет, то по списку пересчитываемых ячеек сортируем граф зависимостей и пересчиываем в получившемся порядке. Плохим ячейкам с цикличискими ссылками выставляем ошибку "#REF!".
		*/
		sortDependency(this.ws, ar);
	}
	else if( this.ws.workbook.isNeedCacheClean == false ){
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
4327
        if( ws.workbook.dependencyFormulas.nodeExist2(this.ws.getId(),this.getName()) ){
4328 4329 4330 4331 4332 4333 4334
            if( !arrRecalc[this.ws.getId()] ){
                arrRecalc[this.ws.getId()] = {};
            }
            arrRecalc[this.ws.getId()][this.oId.getID()] = this.oId.getID();
            wb.needRecalc[ getVertexId(this.ws.getId(),this.oId.getID()) ] = [ this.ws.getId(),this.oId.getID() ];
            wb.needRecalc.length++;
        }
4335 4336 4337 4338 4339 4340
	}
	var DataNew = null;
	if(History.Is_On())
		DataNew = this.getValueData();
	if(History.Is_On() && false == DataOld.isEqual(DataNew))
		History.Add(g_oUndoRedoCell, historyitem_Cell_ChangeValue, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), DataOld, DataNew));
4341 4342 4343 4344 4345 4346
	//todo не должны удаляться ссылки, если сделать merge ее части.
	if(this.isEmptyTextString())
	{
		var cell = this.ws.getCell(this.oId);
		cell.removeHyperlink();
	}
4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388
	return ret;
};
Cell.prototype.setValue2=function(array){
	var DataOld = null;
	if(History.Is_On())
		DataOld = this.getValueData();
	//[{text:"",format:TextFormat},{}...]
	
	//удаляем сторое значение
	var ws = this.ws;
	var wb = this.ws.workbook;
	var needRecalc = false;
	var ar = new Array();
	if (this.sFormula){
		if ( this.oId.getID() in wb.cwf[ws.Id].cells){
			wb.dependencyFormulas.deleteMasterNodes( ws.Id, this.oId.getID() );
			delete wb.cwf[ws.Id].cells[this.oId.getID()];
		}
		needRecalc = true;
		ar.push(this.oId.getID());
	}
	else{
		if( wb.dependencyFormulas.nodeExist2( ws.Id, this.oId.getID() ) ){
			needRecalc = true;
			ar.push(this.oId.getID());
		}
	}
	this.sFormula = null;
	this.oValue.clean();
	this.setFormulaCA(false);
	this.oValue.setValue2(array);
	if (needRecalc){
		/*
			Если необходим пересчет, то по списку пересчитываемых ячеек сортируем граф зависимостей и пересчиываем в получившемся порядке. Плохим ячейкам с цикличискими ссылками выставляем ошибку "#REF!".
		*/
		sortDependency(this.ws, ar);
	}
	var DataNew = null;
	if(History.Is_On())
		DataNew = this.getValueData();
	if(History.Is_On() && false == DataOld.isEqual(DataNew))
		History.Add(g_oUndoRedoCell, historyitem_Cell_ChangeValue, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), DataOld, DataNew));
4389 4390 4391 4392 4393 4394
	//todo не должны удаляться ссылки, если сделать merge ее части.
	if(this.isEmptyTextString())
	{
		var cell = this.ws.getCell(this.oId);
		cell.removeHyperlink();
	}
4395 4396 4397 4398 4399 4400 4401
};
Cell.prototype.setType=function(type){
	return this.oValue.type = type;
};
Cell.prototype.getType=function(){
	return this.oValue.type;
};
4402 4403 4404
Cell.prototype.setCellStyle=function(val){
	var newVal = this.cs._prepareCellStyle(val);
	var oRes = this.sm.setCellStyle(this, newVal);
Alexander.Trofimov's avatar
Alexander.Trofimov committed
4405
	if(History.Is_On()) {
4406 4407 4408 4409 4410
		var oldStyleName = this.cs.getStyleNameByXfId(oRes.oldVal);
		History.Add(g_oUndoRedoCell, historyitem_Cell_Style, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), oldStyleName, val));

		// Выставляем стиль
		var oStyle = this.cs.getStyleByXfId(oRes.newVal);
4411 4412 4413 4414 4415 4416 4417 4418
		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());
4419 4420 4421 4422
	}
	this.bNeedCompileXfs = true;
	this.oValue.cleanCache();
};
4423
Cell.prototype.setNumFormat=function(val){
4424 4425 4426 4427 4428 4429 4430
	var oRes;
    if( val == aStandartNumFormats[0] &&
        this.formulaParsed && this.formulaParsed.value && this.formulaParsed.value.numFormat !== null &&
        this.formulaParsed.value.numFormat !== undefined && aStandartNumFormats[this.formulaParsed.value.numFormat] )
        oRes = this.sm.setNumFormat(this, aStandartNumFormats[this.formulaParsed.value.numFormat]);
    else
        oRes = this.sm.setNumFormat(this, val);
4431 4432
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
        History.Add(g_oUndoRedoCell, historyitem_Cell_Numformat, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), oRes.oldVal, oRes.newVal));
4433
	this.bNeedCompileXfs = true;
4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501
	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;
			var output = new Object();
			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())
			{
				var output = new Object();
				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();
				History.Add(g_oUndoRedoCell, historyitem_Cell_ChangeValue, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), oldVal, newVal));
			}
		}
	}
	var oRes = this.sm.setFont(this, val);
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
	{
		var oldVal = null;
		if(null != oRes.oldVal)
			oldVal = oRes.oldVal.clone();
		var newVal = null;
		if(null != oRes.newVal)
			newVal = oRes.newVal.clone();
        History.Add(g_oUndoRedoCell, historyitem_Cell_SetFont, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), oldVal, newVal));
	}
4502
	this.bNeedCompileXfs = true;
4503 4504 4505 4506 4507 4508 4509
	this.oValue.cleanCache();
};
Cell.prototype.setFontname=function(val){
	this.oValue.setFontname(val);
	var oRes = this.sm.setFontname(this, val);
	if(History.Is_On() && oRes.oldVal != oRes.newVal)
		History.Add(g_oUndoRedoCell, historyitem_Cell_Fontname, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), oRes.oldVal, oRes.newVal));
4510
	this.bNeedCompileXfs = true;
4511 4512 4513 4514 4515 4516 4517
	this.oValue.cleanCache();
};
Cell.prototype.setFontsize=function(val){
	this.oValue.setFontsize(val);
	var oRes = this.sm.setFontsize(this, val);
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
        History.Add(g_oUndoRedoCell, historyitem_Cell_Fontsize, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), oRes.oldVal, oRes.newVal));
4518
	this.bNeedCompileXfs = true;
4519 4520 4521 4522 4523 4524 4525
	this.oValue.cleanCache();
};
Cell.prototype.setFontcolor=function(val){
	this.oValue.setFontcolor(val);
	var oRes = this.sm.setFontcolor(this, val);
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
        History.Add(g_oUndoRedoCell, historyitem_Cell_Fontcolor, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), oRes.oldVal, oRes.newVal));
4526
	this.bNeedCompileXfs = true;
4527 4528 4529 4530 4531 4532 4533
	this.oValue.cleanCache();
};
Cell.prototype.setBold=function(val){
	this.oValue.setBold(val);
	var oRes = this.sm.setBold(this, val);
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
        History.Add(g_oUndoRedoCell, historyitem_Cell_Bold, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), oRes.oldVal, oRes.newVal));
4534
	this.bNeedCompileXfs = true;
4535 4536 4537 4538 4539 4540 4541
	this.oValue.cleanCache();
};
Cell.prototype.setItalic=function(val){
	this.oValue.setItalic(val);
	var oRes = this.sm.setItalic(this, val);
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
        History.Add(g_oUndoRedoCell, historyitem_Cell_Italic, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), oRes.oldVal, oRes.newVal));
4542
	this.bNeedCompileXfs = true;
4543 4544 4545 4546 4547 4548 4549
	this.oValue.cleanCache();
};
Cell.prototype.setUnderline=function(val){
	this.oValue.setUnderline(val);
	var oRes = this.sm.setUnderline(this, val);
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
        History.Add(g_oUndoRedoCell, historyitem_Cell_Underline, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), oRes.oldVal, oRes.newVal));
4550
	this.bNeedCompileXfs = true;
4551 4552 4553 4554 4555 4556 4557
	this.oValue.cleanCache();
};
Cell.prototype.setStrikeout=function(val){
	this.oValue.setStrikeout(val);
	var oRes = this.sm.setStrikeout(this, val);
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
        History.Add(g_oUndoRedoCell, historyitem_Cell_Strikeout, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), oRes.oldVal, oRes.newVal));
4558
	this.bNeedCompileXfs = true;
4559 4560 4561 4562 4563 4564 4565
	this.oValue.cleanCache();
};
Cell.prototype.setFontAlign=function(val){
	this.oValue.setFontAlign(val);
	var oRes = this.sm.setFontAlign(this, val);
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
        History.Add(g_oUndoRedoCell, historyitem_Cell_FontAlign, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), oRes.oldVal, oRes.newVal));
4566
	this.bNeedCompileXfs = true;
4567 4568 4569 4570 4571 4572
	this.oValue.cleanCache();
}
Cell.prototype.setAlignVertical=function(val){
	var oRes = this.sm.setAlignVertical(this, val);
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
        History.Add(g_oUndoRedoCell, historyitem_Cell_AlignVertical, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), oRes.oldVal, oRes.newVal));
4573
	this.bNeedCompileXfs = true;
4574 4575 4576 4577 4578
};
Cell.prototype.setAlignHorizontal=function(val){
	var oRes = this.sm.setAlignHorizontal(this, val);
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
        History.Add(g_oUndoRedoCell, historyitem_Cell_AlignHorizontal, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), oRes.oldVal, oRes.newVal));
4579
	this.bNeedCompileXfs = true;
4580 4581 4582 4583 4584
};
Cell.prototype.setFill=function(val){
	var oRes = this.sm.setFill(this, val);
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
        History.Add(g_oUndoRedoCell, historyitem_Cell_Fill, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), oRes.oldVal, oRes.newVal));
4585
	this.bNeedCompileXfs = true;
4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597
};
Cell.prototype.setBorder=function(val){
	var oRes = this.sm.setBorder(this, val);
    if(History.Is_On() && oRes.oldVal != oRes.newVal){
		var oldVal = null;
		if(null != oRes.oldVal)
			oldVal = oRes.oldVal.clone();
		var newVal = null;
		if(null != oRes.newVal)
			newVal = oRes.newVal.clone();
        History.Add(g_oUndoRedoCell, historyitem_Cell_Border, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), oldVal, newVal));
	}
4598
	this.bNeedCompileXfs = true;
4599 4600 4601 4602 4603
};
Cell.prototype.setShrinkToFit=function(val){
	var oRes = this.sm.setShrinkToFit(this, val);
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
        History.Add(g_oUndoRedoCell, historyitem_Cell_ShrinkToFit, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), oRes.oldVal, oRes.newVal));
4604
	this.bNeedCompileXfs = true;
4605 4606 4607 4608 4609
};
Cell.prototype.setWrap=function(val){
	var oRes = this.sm.setWrap(this, val);
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
        History.Add(g_oUndoRedoCell, historyitem_Cell_Wrap, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), oRes.oldVal, oRes.newVal));
4610
	this.bNeedCompileXfs = true;
4611 4612 4613 4614 4615
};
Cell.prototype.setAngle=function(val){
    var oRes = this.sm.setAngle(this, val);
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
        History.Add(g_oUndoRedoCell, historyitem_Cell_Angle, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), oRes.oldVal, oRes.newVal));
4616
    this.bNeedCompileXfs = true;
4617 4618 4619 4620 4621
};
Cell.prototype.setVerticalText=function(val){
    var oRes = this.sm.setVerticalText(this, val);
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
        History.Add(g_oUndoRedoCell, historyitem_Cell_Angle, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), oRes.oldVal, oRes.newVal));
4622
    this.bNeedCompileXfs = true;
4623 4624 4625 4626 4627 4628 4629
};
Cell.prototype.setQuotePrefix=function(val){
	var oRes = this.sm.setQuotePrefix(this, val);
    if(History.Is_On() && oRes.oldVal != oRes.newVal)
        History.Add(g_oUndoRedoCell, historyitem_Cell_SetQuotePrefix, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), oRes.oldVal, oRes.newVal));
	this.oValue.cleanCache();
};
4630 4631 4632 4633 4634 4635 4636 4637 4638 4639
Cell.prototype.setConditionalFormattingStyle=function(xfs){
	this.conditionalFormattingXfs = xfs;
	this.bNeedCompileXfs = true;
	this.oValue.cleanCache();
}
Cell.prototype.setTableStyle=function(xfs){
	this.tableXfs = xfs;
	this.bNeedCompileXfs = true;
	this.oValue.cleanCache();
}
4640 4641 4642 4643 4644 4645 4646 4647 4648
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;
	}
4649
	this.bNeedCompileXfs = true;
4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770
	this.oValue.cleanCache();
	if(History.Is_On() && false == ((null == oldVal && null == newVal) || (null != oldVal && null != newVal && true == oldVal.isEqual(newVal))))
	{
		if(null != oldVal)
			oldVal = oldVal.clone();
		if(null != newVal)
			newVal = newVal.clone();
		History.Add(g_oUndoRedoCell, historyitem_Cell_SetStyle, this.ws.getId(), new Asc.Range(0, this.oId.getRow0(), gc_nMaxCol0, this.oId.getRow0()), new UndoRedoData_CellSimpleData(this.oId.getRow0(), this.oId.getCol0(), oldVal, newVal));
	}
	// if(this.isEmpty())
		// this.Remove();
};
Cell.prototype.getFormula=function(){
	if(null != this.sFormula)
		return this.sFormula;
	else
		return "";
};
Cell.prototype.getValueForEdit=function(numFormat){
	return this.oValue.getValueForEdit();
};
Cell.prototype.getValueForEdit2=function(numFormat){
	return this.oValue.getValueForEdit2();
};
Cell.prototype.getValueWithoutFormat=function(){
	return this.oValue.getValueWithoutFormat();
};
Cell.prototype.getValue=function(numFormat, dDigitsCount){
	return this.oValue.getValue();
};
Cell.prototype.getValue2=function(dDigitsCount, fIsFitMeasurer){
	if(null == fIsFitMeasurer)
		fIsFitMeasurer = function(aText){return true;}
	if(null == dDigitsCount)
		dDigitsCount = gc_nMaxDigCountView;
	return this.oValue.getValue2(dDigitsCount, fIsFitMeasurer);
};
Cell.prototype.getNumFormatStr=function(){
	if(null != this.xfs && null != this.xfs.num)
            return this.xfs.num.f;
	return g_oDefaultNum.f;
}
Cell.prototype.moveHor=function(val){
	this.oId.moveCol(val);
};
Cell.prototype.moveVer=function(val){
	this.oId.moveRow(val);
};
Cell.prototype.getOffset=function(cell){
	var cAddr1 = this.oId, cAddr2 = cell.oId;
	return {offsetCol:(cAddr1.col - cAddr2.col), offsetRow:(cAddr1.row - cAddr2.row)};
}
Cell.prototype.getOffset2=function(cellId){
	var cAddr1 = this.oId, cAddr2 = new CellAddress(cellId);
	return {offsetCol:(cAddr1.col - cAddr2.col), offsetRow:(cAddr1.row - cAddr2.row)};
}
Cell.prototype.getOffset3=function(cellAddr){
	var cAddr1 = this.oId, cAddr2 = cellAddr;
	return {offsetCol:(cAddr1.col - cAddr2.col), offsetRow:(cAddr1.row - cAddr2.row)};
}
Cell.prototype.getCellAddress = function(){
	return this.oId;
}
Cell.prototype.getValueData = function(){
	return new UndoRedoData_CellValueData(this.sFormula, this.oValue.clone(null));
}
Cell.prototype.setValueData = function(Val){
	//значения устанавляваются через setValue, чтобы пересчитались формулы
	if(null != Val.formula)
		this.setValue("=" + Val.formula);
	else if(null != Val.value)
	{
		if(null != Val.value.number)
			this.setValue(Val.value.number.toString());
		else if(null != Val.value.text)
			this.setValue(Val.value.text);
		else if(null != Val.value.multiText)
			this.setValue2(Val.value._cloneMultiText());
		else
			this.setValue("");
	}
	else
		this.setValue("");
}
Cell.prototype.setFormulaCA = function(ca){
	if(ca) this.sFormulaCA = true;
	else if( this.sFormulaCA ) delete this.sFormulaCA;
}
//-------------------------------------------------------------------------------------------------

/**
 * @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);
};
Range.prototype.clone=function(){
	return new Range(this.worksheet, this.bbox.r1, this.bbox.c1, this.bbox.r2, this.bbox.c2);
}
Range.prototype.getFirst=function(){
	return this.first;
}
Range.prototype.getLast=function(){
	return this.last;
}
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
4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784
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;
			}
		}
	}
};
4785 4786 4787 4788 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 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 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 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016
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)
					{
						var oRes = actionCell(oCurCell, i, j - 0, oBBox.r1, oBBox.c1);
						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 nRangeType = this._getRangeType();
		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)
							actionCell(oCurCell, i - 0, j, oBBox.r1, oBBox.c1);
					}
				}
				else
				{
					for(var j = oBBox.c1; j <= oBBox.c2; ++j)
					{
						var oCurCell = row.c[j];
						if(null != oCurCell)
							actionCell(oCurCell, i - 0, j, oBBox.r1, oBBox.c1);
					}
				}
			}
		}
	}
};
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)
							{
								var oRes = actionCell(oCurCell, i - 0, j, oBBox.r1, oBBox.c1);
								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;
5017
	return getRangeType(oBBox);
5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150
}
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);
	}
}
Range.prototype._setPropertyNoEmpty=function(actionRow, actionCol, actionCell){
	var nRangeType = this._getRangeType();
	if(c_oRangeType.Range == nRangeType)
		this._foreachNoEmpty(actionCell);
	else if(c_oRangeType.Row == nRangeType)
		this._foreachRowNoEmpty(actionRow, actionCell);
	else if(c_oRangeType.Col == nRangeType)
		this._foreachColNoEmpty(actionCol, actionCell);
	else
	{
		this._foreachRowNoEmpty(actionRow, actionCell);
		if(null != actionCol)
			this._foreachColNoEmpty(actionCol, null);
	}
}
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;
}
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;
}
Range.prototype.getWorksheet=function(){
	return this.worksheet;
};
Range.prototype.isFormula = function(){
	var nRow = this.bbox.r1;
	var nCol = this.bbox.c1;
	var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
	return cell.isFormula();
}
Range.prototype.isOneCell=function(){
	var oBBox = this.bbox;
	return oBBox.r1 == oBBox.r2 && oBBox.c1 == oBBox.c2;
}
Range.prototype.isColumn = function(){
	if(this.first.getRow() == 1 && this.last.getRow() == gc_nMaxRow)
		return true;
	else
		return false;
}
Range.prototype.isRow = function(){
	if(this.first.getCol() == 1 && this.last.getCol() == gc_nMaxCol)
		return true;
	else
		return false;
}
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(){
	var first = this.getFirst();
	var sRes = first.getID();
	if(false == this.isOneCell())
	{
		var last = this.getLast();
		sRes = sRes + ":" + last.getID();
	}
	return sRes;
};
Range.prototype.getCells=function(){
	var aResult = new Array();
	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;
};
Range.prototype.setValue=function(val,callback){
	History.Create_NewPoint();
	var oBBox = this.bbox;
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	History.StartTransaction();
	var oThis = this;
	this._foreach(function(cell){
		cell.setValue(val,callback);
		// if(cell.isEmpty())
			// cell.Remove();
	});
	History.EndTransaction();
};
Range.prototype.setValue2=function(array){
	History.Create_NewPoint();
	var oBBox = this.bbox;
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	History.StartTransaction();
	var wb = this.worksheet.workbook, ws = this.worksheet, needRecalc = false, ar =[];
	//[{"text":"qwe","format":{"b":true, "i":false, "u":"none", "s":false, "fn":"Arial", "fs": 12, "c": 0xff00ff, "va": "subscript"  }},{}...]
	var oThis = this;
	/*
		Устанавливаем значение в Range ячеек. В отличае от setValue, сюда мы попадаем только в случае ввода значения отличного от формулы. Таким образом, если в ячейке была формула, то для нее в графе очищается список ячеек от которых зависела. После чего выставляем флаг о необходимости пересчета.
	*/
	this._foreach(function(cell){
		cell.setValue2(array);
		// if(cell.isEmpty())
			// cell.Remove();
	});
	History.EndTransaction();
};
5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174
Range.prototype.setCellStyle=function(val){
	History.Create_NewPoint();
	var oBBox = this.bbox;
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	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);
		});
};
5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195
Range.prototype.setTableStyle=function(val){
	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.setTableStyle(val);
		});
};
5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230
Range.prototype.setNumFormat=function(val){
	History.Create_NewPoint();
	var oBBox = this.bbox;
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	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 oBBox = this.bbox;
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	var bRes = false;
	var oThis = this;
	this._setPropertyNoEmpty(null, null, function(cell, nRow0, nCol0, nRowStart, nColStart){
		bRes |= cell.shiftNumFormat(nShift, aDigitsCount[nCol0 - nColStart] || 8);
	});
	return bRes;
}
5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253
Range.prototype.setFont=function(val){
	History.Create_NewPoint();
	History.SetSelection(this.bbox.clone());
	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);
	});
};
5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519
Range.prototype.setFontname=function(val){
	History.Create_NewPoint();
	var oBBox = this.bbox;
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	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();
	var oBBox = this.bbox;
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	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();
	var oBBox = this.bbox;
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	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();
	var oBBox = this.bbox;
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	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();
	var oBBox = this.bbox;
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	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();
	var oBBox = this.bbox;
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	this.createCellOnRowColCross();
	var fSetProperty = this._setProperty;
	var nRangeType = this._getRangeType();
	if(c_oRangeType.All == nRangeType)
	{
		this.worksheet.getAllCol().setUnderline(val);
		fSetProperty = this._setPropertyNoEmpty;
	}
	fSetProperty.call(this, function(row){
		if(c_oRangeType.All == nRangeType && null == row.xfs)
			return;
		row.setUnderline(val);
	},
	function(col){
		col.setUnderline(val);
	},
	function(cell){
		cell.setUnderline(val);
	});
};
Range.prototype.setStrikeout=function(val){
	History.Create_NewPoint();
	var oBBox = this.bbox;
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	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();
	var oBBox = this.bbox;
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	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();
	var oBBox = this.bbox;
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	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();
	var oBBox = this.bbox;
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	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();
	var oBBox = this.bbox;
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	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);
	});
};
5520
Range.prototype.setBorderSrc=function(border){
5521 5522 5523 5524
	History.Create_NewPoint();
	var oBBox = this.bbox;
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	History.StartTransaction();
5525 5526
	if (null == border)
		border = new Border();
5527 5528 5529 5530 5531
	this.createCellOnRowColCross();
	var fSetProperty = this._setProperty;
	var nRangeType = this._getRangeType();
	if(c_oRangeType.All == nRangeType)
	{
5532
		this.worksheet.getAllCol().setBorder(border.clone());
5533 5534 5535 5536 5537
		fSetProperty = this._setPropertyNoEmpty;
	}
	fSetProperty.call(this, function(row){
		if(c_oRangeType.All == nRangeType && null == row.xfs)
			return;
5538
		row.setBorder(border.clone());
5539 5540
	},
	function(col){
5541
		col.setBorder(border.clone());
5542 5543
	},
	function(cell){
5544
		cell.setBorder(border.clone());
5545 5546
	});
	History.EndTransaction();
5547
};
5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569
Range.prototype.setBorder=function(border){
	History.Create_NewPoint();
	//border = null очисть border
	//"ih" - внутренние горизонтальные, "iv" - внутренние вертикальные
	var oBBox = this.bbox;
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	var nRangeType = this._getRangeType();
	var oThis = this;
	var fSetBorder = function(nRow, nCol, oNewBorder)
	{
		if(null == oNewBorder)
		{
			var cell = oThis.worksheet._getCellNoEmpty(nRow, nCol);
			if(null != cell)
				cell.setBorder(oNewBorder);
		}
		else
		{
			if(oNewBorder.isEqual(g_oDefaultBorderAbs))
				return;
			var _cell = oThis.worksheet.getCell(new CellAddress(nRow, nCol, 0));
			var oCurBorder = _cell.getBorderSrc().clone();
5570
			oCurBorder.mergeInner(oNewBorder);
5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587
			var cell = oThis.worksheet._getCell(nRow, nCol);
			cell.setBorder(oCurBorder);
		}
	};
	var fSetBorderRowCol = function(rowcol, oNewBorder)
	{
		if(null == oNewBorder)
			rowcol.setBorder(null);
		else
		{
			if(oNewBorder.isEqual(g_oDefaultBorderAbs))
				return;
			var oCurBorder;
			if(null != rowcol.xfs && null != rowcol.xfs.border)
				oCurBorder = rowcol.xfs.border.clone();
			else
				oCurBorder = new Border();
5588
			oCurBorder.mergeInner(oNewBorder);
5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626
            rowcol.setBorder(oNewBorder);
		}
	};
	var nEdgeTypeLeft = 1;
	var nEdgeTypeTop = 2;
	var nEdgeTypeRight = 3;
	var nEdgeTypeBottom = 4;
	var fSetBorderEdge = function(nRow, nCol, oNewBorder, type)
	{
		var _cell = oThis.worksheet.getCell(new CellAddress(nRow, nCol, 0));
		var oCurBorder = _cell.getBorderSrc().clone();
		var oCurBorderProp;
		var oNewBorderProp = null;
		if(null == oNewBorder)
			oNewBorderProp = new BorderProp();
		switch(type)
		{
			case nEdgeTypeLeft:
				oCurBorderProp = oCurBorder.r;
				if(null != oNewBorder)
					oNewBorderProp = oNewBorder.l;
				break;
			case nEdgeTypeTop:
				oCurBorderProp = oCurBorder.b;
				if(null != oNewBorder)
					oNewBorderProp = oNewBorder.t;
				break;
			case nEdgeTypeRight:
				oCurBorderProp = oCurBorder.l;
				if(null != oNewBorder)
					oNewBorderProp = oNewBorder.r;
				break;
			case nEdgeTypeBottom:
				oCurBorderProp = oCurBorder.t;
				if(null != oNewBorder)
					oNewBorderProp = oNewBorder.b;
				break;
		}
5627
		if(null != oNewBorderProp && null != oCurBorderProp && c_oAscBorderStyles.None != oCurBorderProp.s && (null == oNewBorder || c_oAscBorderStyles.None != oNewBorderProp.s) &&
5628
			(oNewBorderProp.s != oCurBorderProp.s || oNewBorderProp.getRgbOrNull() != oCurBorderProp.getRgbOrNull())){
5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671
			switch(type)
			{
				case nEdgeTypeLeft: oCurBorder.r = new BorderProp(); break;
				case nEdgeTypeTop: oCurBorder.b = new BorderProp(); break;
				case nEdgeTypeRight: oCurBorder.l = new BorderProp(); break;
				case nEdgeTypeBottom: oCurBorder.t = new BorderProp(); break;
			}
			var cell = oThis.worksheet._getCell(nRow, nCol);
			cell.setBorder(oCurBorder);
		}
	};
	var fSetBorderRowColEdge = function(rowcol, oNewBorder, type)
	{
		if(null != rowcol.xfs && null != rowcol.xfs.border)
		{
			var oCurBorder = rowcol.xfs.border.clone();
			var oCurBorderProp;
			var oNewBorderProp;
			if(null == oNewBorder)
				oNewBorderProp = new BorderProp();
			switch(type)
			{
				case nEdgeTypeLeft:
					oCurBorderProp = oCurBorder.r;
					if(null != oNewBorder)
						oNewBorderProp = oNewBorder.l;
					break;
				case nEdgeTypeTop:
					oCurBorderProp = oCurBorder.b;
					if(null != oNewBorder)
						oNewBorderProp = oNewBorder.t;
					break;
				case nEdgeTypeRight:
					oCurBorderProp = oCurBorder.l;
					if(null != oNewBorder)
						oNewBorderProp = oNewBorder.r;
					break;
				case nEdgeTypeBottom:
					oCurBorderProp = oCurBorder.t;
					if(null != oNewBorder)
						oNewBorderProp = oNewBorder.b;
					break;
			}
5672
			if(null != oNewBorderProp && null != oCurBorderProp && c_oAscBorderStyles.None != oCurBorderProp.s && (null == oNewBorder || c_oAscBorderStyles.None != oNewBorderProp.s) &&
5673
				(oNewBorderProp.s != oCurBorderProp.s || oNewBorderProp.getRgbOrNull() != oCurBorderProp.getRgbOrNull())){
5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684
				switch(type)
				{
					case nEdgeTypeLeft: oCurBorder.r = new BorderProp(); break;
					case nEdgeTypeTop: oCurBorder.b = new BorderProp(); break;
					case nEdgeTypeRight: oCurBorder.l = new BorderProp(); break;
					case nEdgeTypeBottom: oCurBorder.t = new BorderProp(); break;
				}
				rowcol.setBorder(oCurBorder);
			}
		}
	};
5685 5686
	if (null != border && border.isEqual(g_oDefaultBorderAbs))
		border = null;
5687 5688 5689 5690 5691 5692 5693 5694
	if(nRangeType == c_oRangeType.Col)
	{
		var oLeftOuter = null;
		var oLeftInner = null;
		var oInner = null;
		var oRightInner = null;
		var oRightOuter = null;
		var nWidth = oBBox.c2 - oBBox.c1 + 1;
5695
		if(null != border)
5696
		{
5697
			if(oBBox.c1 > 0 && null != border.l)
5698 5699
			{
				oLeftOuter = new Border();
5700
				oLeftOuter.l = border.l;
5701
			}
5702
			if(oBBox.c2 < gc_nMaxCol0 && null != border.r)
5703 5704
			{
				oRightOuter = new Border();
5705
				oRightOuter.r = border.r;
5706 5707
			}
			oLeftInner = new Border();
5708 5709
			oLeftInner.l = border.l;
			oLeftInner.t = border.ih;
5710
			if(nWidth > 1)
5711
				oLeftInner.r = border.iv;
5712
			else
5713 5714 5715 5716 5717
				oLeftInner.r = border.r;
			oLeftInner.b = border.ih;
			oLeftInner.d = border.d;
			oLeftInner.dd = border.dd;
			oLeftInner.du = border.du;
5718 5719 5720 5721 5722
			if(oLeftInner.isEqual(g_oDefaultBorderAbs))
				oLeftInner = null;
			if(nWidth > 1)
			{
				oRightInner = new Border();
5723 5724 5725 5726 5727 5728 5729
				oRightInner.l = border.iv;
				oRightInner.t = border.ih;
				oRightInner.r = border.r;
				oRightInner.b = border.ih;
				oRightInner.d = border.d;
				oRightInner.dd = border.dd;
				oRightInner.du = border.du;
5730 5731 5732 5733 5734 5735
				if(oRightInner.isEqual(g_oDefaultBorderAbs))
					oRightInner = null;
			}
			if(nWidth > 2)
			{
				oInner = new Border();
5736 5737 5738 5739 5740 5741 5742
				oInner.l = border.iv;
				oInner.t = border.ih;
				oInner.r = border.iv;
				oInner.b = border.ih;
				oInner.d = border.d;
				oInner.dd = border.dd;
				oInner.du = border.du;
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 5780 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
				if(oInner.isEqual(g_oDefaultBorderAbs))
					oInner = null;
			}
		}
		//oLeftOuter
		if(oBBox.c1 > 0)
		{
			var oTempRange = this.worksheet.getRange(new CellAddress(0, oBBox.c1 - 1, 0), new CellAddress(gc_nMaxRow0, oBBox.c1 - 1, 0));
			oTempRange._foreachColNoEmpty(function(col){
				if(null != col.xfs)
					fSetBorderRowColEdge(col, oLeftOuter, nEdgeTypeLeft);
			},
			function(cell, nRow, nCol, nRowStart, nColStart){
				fSetBorderEdge(nRow, nCol ,oLeftOuter, nEdgeTypeLeft);
			});
		}
		//oLeftInner
		var oTempRange = this.worksheet.getRange(new CellAddress(0, oBBox.c1, 0), new CellAddress(gc_nMaxRow0, oBBox.c1, 0));
		oTempRange._foreachCol(function(col){
			fSetBorderRowCol(col, oLeftInner);
		},
		function(cell, nRow, nCol, nRowStart, nColStart){
			fSetBorder(nRow, nCol ,oLeftInner);
		});
		//oInner
		if(nWidth > 2)
		{
			var oTempRange = this.worksheet.getRange(new CellAddress(0, oBBox.c1 + 1, 0), new CellAddress(gc_nMaxRow0, oBBox.c2 - 1, 0));
			oTempRange._foreachCol(function(col){
				fSetBorderRowCol(col, oInner);
			},
			function(cell, nRow, nCol, nRowStart, nColStart){
				fSetBorder(nRow, nCol ,oInner);
			});
		}
		//oRightInner
		if(nWidth > 1)
		{
			var oTempRange = this.worksheet.getRange(new CellAddress(0, oBBox.c2, 0), new CellAddress(gc_nMaxRow0, oBBox.c2, 0));
			oTempRange._foreachCol(function(col){
				fSetBorderRowCol(col, oRightInner);
			},
			function(cell, nRow, nCol, nRowStart, nColStart){
				fSetBorder(nRow, nCol ,oRightInner);
			});
		}
		//oRightOuter
		if(oBBox.c2 < gc_nMaxCol0)
		{
			var oTempRange = this.worksheet.getRange(new CellAddress(0, oBBox.c2 + 1, 0), new CellAddress(gc_nMaxRow0, oBBox.c2 + 1, 0));
			oTempRange._foreachColNoEmpty(function(col){
				if(null != col.xfs)
					fSetBorderRowColEdge(col, oRightOuter, nEdgeTypeRight);
			},
			function(cell, nRow, nCol, nRowStart, nColStart){
				fSetBorderEdge(nRow, nCol ,oRightOuter, nEdgeTypeRight);
			});
		}
	}
	else if(nRangeType == c_oRangeType.Row)
	{
		var oTopOuter = null;
		var oTopInner = null;
		var oInner = null;
		var oBottomInner = null;
		var oBottomOuter = null;
		var nHeight = oBBox.r2 - oBBox.r1 + 1;
5810
		if(null != border)
5811
		{
5812
			if(oBBox.r1 > 0 && null != border.t)
5813 5814
			{
				oTopOuter = new Border();
5815
				oTopOuter.t = border.t;
5816
			}
5817
			if(oBBox.r2 < gc_nMaxRow0 && null != border.b)
5818 5819
			{
				oBottomOuter = new Border();
5820
				oBottomOuter.b = border.b;
5821 5822
			}
			oTopInner = new Border();
5823 5824 5825
			oTopInner.l = border.iv;
			oTopInner.t = border.t;
			oTopInner.r = border.iv;
5826
			if(nHeight > 1)
5827
				oTopInner.b = border.ih;
5828
			else
5829 5830 5831 5832
				oTopInner.b = border.b;
			oTopInner.d = border.d;
			oTopInner.dd = border.dd;
			oTopInner.du = border.du;
5833 5834 5835 5836 5837
			if(oTopInner.isEqual(g_oDefaultBorderAbs))
				oTopInner = null;
			if(nHeight > 1)
			{
				oBottomInner = new Border();
5838 5839 5840 5841 5842 5843 5844
				oBottomInner.l = border.iv;
				oBottomInner.t = border.ih;
				oBottomInner.r = border.iv;
				oBottomInner.b = border.b;
				oBottomInner.d = border.d;
				oBottomInner.dd = border.dd;
				oBottomInner.du = border.du;
5845 5846 5847 5848 5849 5850
				if(oBottomInner.isEqual(g_oDefaultBorderAbs))
					oBottomInner = null;
			}
			if(nHeight > 2)
			{
				oInner = new Border();
5851 5852 5853 5854 5855 5856 5857
				oInner.l = border.iv;
				oInner.t = border.ih;
				oInner.r = border.iv;
				oInner.b = border.ih;
				oInner.d = border.d;
				oInner.dd = border.dd;
				oInner.du = border.du;
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 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922
				if(oInner.isEqual(g_oDefaultBorderAbs))
					oInner = null;
			}
		}
		//oTopOuter
		if(oBBox.r1 > 0)
		{
			var oTempRange = this.worksheet.getRange(new CellAddress(oBBox.r1 - 1, 0, 0), new CellAddress(oBBox.r1 - 1, gc_nMaxCol0, 0));
			oTempRange._foreachRowNoEmpty(function(row){
				if(null != row.xfs)
					fSetBorderRowColEdge(row, oTopOuter, nEdgeTypeTop);
			},
			function(cell, nRow, nCol, nRowStart, nColStart){
				fSetBorderEdge(nRow, nCol ,oTopOuter, nEdgeTypeTop);
			});
		}
		//oTopInner
		var oTempRange = this.worksheet.getRange(new CellAddress(oBBox.r1, 0, 0), new CellAddress(oBBox.r1, gc_nMaxCol0, 0));
		oTempRange._foreachRow(function(row){
			fSetBorderRowCol(row, oTopInner);
		},
		function(cell, nRow, nCol, nRowStart, nColStart){
			fSetBorder(nRow, nCol ,oTopInner);
		});
		//oInner
		if(nHeight > 2)
		{
			var oTempRange = this.worksheet.getRange(new CellAddress(oBBox.r1 + 1, 0, 0), new CellAddress(oBBox.r2 - 1, gc_nMaxCol0, 0));
			oTempRange._foreachRow(function(row){
				fSetBorderRowCol(row, oInner);
			},
			function(cell, nRow, nCol, nRowStart, nColStart){
				fSetBorder(nRow, nCol ,oInner);
			});
		}
		//oBottomInner
		if(nHeight > 1)
		{
			var oTempRange = this.worksheet.getRange(new CellAddress(oBBox.r2, 0, 0), new CellAddress(oBBox.r2, gc_nMaxCol0, 0));
			oTempRange._foreachRow(function(row){
				fSetBorderRowCol(row, oBottomInner);
			},
			function(cell, nRow, nCol, nRowStart, nColStart){
				fSetBorder(nRow, nCol ,oBottomInner);
			});
		}
		//oBottomOuter
		if(oBBox.r2 < gc_nMaxRow0)
		{
			var oTempRange = this.worksheet.getRange(new CellAddress(oBBox.r2 + 1, 0, 0), new CellAddress(oBBox.r2 + 1, gc_nMaxCol0, 0));
			oTempRange._foreachRowNoEmpty(function(row){
				if(null != row.xfs)
					fSetBorderRowColEdge(row, oBottomOuter, nEdgeTypeBottom);
			},
			function(cell, nRow, nCol, nRowStart, nColStart){
				fSetBorderEdge(nRow, nCol ,oBottomOuter, nEdgeTypeBottom);
			});
		}
	}
	else if(nRangeType == c_oRangeType.Range)
	{
		var bLeftBorder = false;
		var bTopBorder = false;
		var bRightBorder = false;
		var bBottomBorder = false;
5923
		if(null == border){
5924
			this._foreachNoEmpty(function(cell){
5925
				cell.setBorder(border);
5926 5927 5928 5929 5930 5931 5932
			});
			bLeftBorder = true;
			bTopBorder = true;
			bRightBorder = true;
			bBottomBorder = true;
		}
		else{
5933 5934 5935 5936 5937 5938 5939
			bLeftBorder = null != border.l;
			bTopBorder = null != border.t;
			bRightBorder = null != border.r;
			bBottomBorder = null != border.b;
			var bInnerHBorder = null != border.ih;
			var bInnerVBorder = null != border.iv;
			var bDiagonal = null != border.d;
5940 5941
			if(oBBox.c1 == oBBox.c2 && oBBox.r1 == oBBox.r2){
				//Если ячейка одна
5942
				fSetBorder(oBBox.r1, oBBox.c1, border);
5943 5944 5945 5946 5947 5948
			}
			else{
				//бордеры угловых ячеек
				if(oBBox.c1 == oBBox.c2){
					if(bLeftBorder || bTopBorder || bRightBorder || bInnerHBorder || bDiagonal){
						var oLTBorder = new Border();
5949 5950 5951 5952 5953 5954 5955
						oLTBorder.l = border.l;
						oLTBorder.t = border.t;
						oLTBorder.r = border.r;
						oLTBorder.b = border.ih;
						oLTBorder.d = border.d;
						oLTBorder.dd = border.dd;
						oLTBorder.du = border.du;
5956 5957 5958 5959
						fSetBorder(oBBox.r1, oBBox.c1, oLTBorder);
					}
					if(bLeftBorder || bBottomBorder || bRightBorder || bInnerHBorder || bDiagonal){
						var oLBBorder = new Border();
5960 5961 5962 5963 5964 5965 5966
						oLBBorder.l = border.l;
						oLBBorder.t = border.ih;
						oLBBorder.r = border.r;
						oLBBorder.b = border.b;
						oLBBorder.d = border.d;
						oLBBorder.dd = border.dd;
						oLBBorder.du = border.du;
5967 5968 5969 5970 5971 5972
						fSetBorder(oBBox.r2, oBBox.c1, oLBBorder);
					}
				}
				else{
					if(bLeftBorder || bTopBorder || bInnerVBorder || (oBBox.r1 == oBBox.r2 ? bBottomBorder : bInnerHBorder) || bDiagonal){
						var oLTBorder = new Border();
5973 5974 5975
						oLTBorder.l = border.l;
						oLTBorder.t = border.t;
						oLTBorder.r = border.iv;
5976
						if(oBBox.r1 == oBBox.r2)
5977
							oLTBorder.b = border.b;
5978
						else
5979 5980 5981 5982
							oLTBorder.b = border.ih;
						oLTBorder.d = border.d;
						oLTBorder.dd = border.dd;
						oLTBorder.du = border.du;
5983 5984 5985 5986
						fSetBorder(oBBox.r1, oBBox.c1, oLTBorder);
					}
					if(oBBox.r1 != oBBox.r2 && (bLeftBorder || bInnerVBorder || bInnerHBorder || bBottomBorder || bDiagonal)){
						var oLBBorder = new Border();
5987 5988 5989 5990 5991 5992 5993
						oLBBorder.l = border.l;
						oLBBorder.t = border.ih;
						oLBBorder.r = border.iv;
						oLBBorder.b = border.b;
						oLBBorder.d = border.d;
						oLBBorder.dd = border.dd;
						oLBBorder.du = border.du;
5994 5995 5996 5997
						fSetBorder(oBBox.r2, oBBox.c1, oLBBorder);
					}
					if(bRightBorder || bTopBorder || bInnerVBorder || (oBBox.r1 == oBBox.r2 ? bBottomBorder : bInnerHBorder) || bDiagonal){
						var oRTBorder = new Border();
5998 5999 6000
						oRTBorder.l = border.iv;
						oRTBorder.t = border.t;
						oRTBorder.r = border.r;
6001
						if(oBBox.r1 == oBBox.r2)
6002
							oRTBorder.b = border.b;
6003
						else
6004 6005 6006 6007
							oRTBorder.b = border.ih;
						oRTBorder.d = border.d;
						oRTBorder.dd = border.dd;
						oRTBorder.du = border.du;
6008 6009 6010 6011
						fSetBorder(oBBox.r1, oBBox.c2, oRTBorder);
					}
					if(oBBox.r1 != oBBox.r2 && (bRightBorder || bInnerHBorder || bInnerVBorder || bBottomBorder || bDiagonal) ){
						var oRBBorder = new Border();
6012 6013 6014 6015 6016 6017 6018
						oRBBorder.l = border.iv;
						oRBBorder.t = border.ih;
						oRBBorder.r = border.r;
						oRBBorder.b = border.b;
						oRBBorder.d = border.d;
						oRBBorder.dd = border.dd;
						oRBBorder.du = border.du;
6019 6020 6021 6022 6023 6024 6025
						fSetBorder(oBBox.r2, oBBox.c2, oRBBorder);
					}
				}
				//граничные бордеры
				if(bTopBorder || bInnerVBorder || (oBBox.r1 == oBBox.r2 ? bBottomBorder : bInnerHBorder) || bDiagonal){
					for(var  i = oBBox.c1 + 1 ; i < oBBox.c2; i++){
						var oTopBorder = new Border();
6026 6027 6028
						oTopBorder.l = border.iv;
						oTopBorder.t = border.t;
						oTopBorder.r = border.iv;
6029
						if(oBBox.r1 == oBBox.r2)
6030
							oTopBorder.b = border.b;
6031
						else
6032 6033 6034 6035
							oTopBorder.b = border.ih;
						oTopBorder.d = border.d;
						oTopBorder.dd = border.dd;
						oTopBorder.du = border.du;
6036 6037 6038 6039 6040 6041
						fSetBorder(oBBox.r1, i, oTopBorder);
					}
				}
				if(oBBox.r1 != oBBox.r2 && (bBottomBorder || bInnerVBorder || bInnerHBorder || bDiagonal)){
					for(var  i = oBBox.c1 + 1 ; i < oBBox.c2; i++){
						var oBottomBorder = new Border();
6042 6043 6044 6045 6046 6047 6048
						oBottomBorder.l = border.iv;
						oBottomBorder.t = border.ih;
						oBottomBorder.r = border.iv;
						oBottomBorder.b = border.b;
						oBottomBorder.d = border.d;
						oBottomBorder.dd = border.dd;
						oBottomBorder.du = border.du;
6049 6050 6051 6052 6053 6054
						fSetBorder(oBBox.r2, i, oBottomBorder);
					}
				}
				if(bLeftBorder || bInnerHBorder || (oBBox.c1 == oBBox.c2 ? bRightBorder : bInnerVBorder) || bDiagonal){
					for(var  i = oBBox.r1 + 1 ; i < oBBox.r2; i++){
						var oLeftBorder = new Border();
6055 6056
						oLeftBorder.l = border.l;
						oLeftBorder.t = border.ih;
6057
						if(oBBox.c1 == oBBox.c2)
6058
							oLeftBorder.r = border.r;
6059
						else
6060 6061 6062 6063 6064
							oLeftBorder.r = border.iv;
						oLeftBorder.b = border.ih;
						oLeftBorder.d = border.d;
						oLeftBorder.dd = border.dd;
						oLeftBorder.du = border.du;
6065 6066 6067 6068 6069 6070
						fSetBorder(i, oBBox.c1, oLeftBorder);
					}
				}
				if(oBBox.c1 != oBBox.c2 && (bRightBorder || bInnerVBorder || bInnerHBorder || bDiagonal)){
					for(var  i = oBBox.r1 + 1 ; i < oBBox.r2; i++){
						var oRightBorder = new Border();
6071 6072 6073 6074 6075 6076 6077
						oRightBorder.l = border.iv;
						oRightBorder.t = border.ih;
						oRightBorder.r = border.r;
						oRightBorder.b = border.ih;
						oRightBorder.d = border.d;
						oRightBorder.dd = border.dd;
						oRightBorder.du = border.du;
6078 6079 6080 6081 6082 6083 6084 6085
						fSetBorder(i, oBBox.c2, oRightBorder);
					}
				}
				//Внутренние границы
				if(bInnerHBorder || bInnerVBorder || bDiagonal){
					for(var  i = oBBox.r1 + 1 ; i < oBBox.r2; i++){
						for(var  j = oBBox.c1 + 1 ; j < oBBox.c2; j++){
							var oInnerBorder = new Border();
6086 6087 6088 6089 6090 6091 6092
							oInnerBorder.l = border.iv;
							oInnerBorder.t = border.ih;
							oInnerBorder.r = border.iv;
							oInnerBorder.b = border.ih;
							oInnerBorder.d = border.d;
							oInnerBorder.dd = border.dd;
							oInnerBorder.du = border.du;
6093 6094 6095 6096 6097 6098 6099 6100 6101 6102
							fSetBorder(i, j, oInnerBorder);
						}
					}
				}
			}
		}
		//для граничных ячеек стираем border
		if(bLeftBorder && oBBox.c1 > 0){
			var nCol = oBBox.c1 - 1;
			for(var  i = oBBox.r1 ; i <= oBBox.r2; i++)
6103
				fSetBorderEdge(i, nCol, border, nEdgeTypeLeft);
6104 6105 6106 6107
		}
		if(bTopBorder && oBBox.r1 > 0){
			var nRow = oBBox.r1 - 1;
			for(var  i = oBBox.c1 ; i <= oBBox.c2; i++)
6108
				fSetBorderEdge(nRow, i, border, nEdgeTypeTop);
6109 6110 6111 6112
		}
		if(bRightBorder && oBBox.c2 + 1 < this.worksheet.getColsCount()){
			var nCol = oBBox.c2 + 1;
			for(var  i = oBBox.r1 ; i <= oBBox.r2; i++)
6113
				fSetBorderEdge(i, nCol, border, nEdgeTypeRight);
6114 6115 6116 6117
		}
		if(bBottomBorder && oBBox.r2 + 1 < this.worksheet.getRowsCount()){
			var nRow = oBBox.r2 + 1;
			for(var  i = oBBox.c1 ; i <= oBBox.c2; i++)
6118
				fSetBorderEdge(nRow, i, border, nEdgeTypeBottom);
6119 6120 6121 6122
		}
	}
	else
	{
6123
		this.worksheet.getAllCol().setBorder(border);
6124
		this._setPropertyNoEmpty(function(row){
6125
			row.setBorder(border);
6126 6127
		},
		function(col){
6128
			col.setBorder(border);
6129 6130
		},
		function(cell){
6131
			cell.setBorder(border);
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 6241 6242 6243 6244 6245 6246 6247 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
		});
	}
};
Range.prototype.setShrinkToFit=function(val){
	History.Create_NewPoint();
	var oBBox = this.bbox;
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	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();
	var oBBox = this.bbox;
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	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();
    var oBBox = this.bbox;
    History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	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();
    var oBBox = this.bbox;
    History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	this.createCellOnRowColCross();
	var fSetProperty = this._setProperty;
	var nRangeType = this._getRangeType();
	if(c_oRangeType.All == nRangeType)
	{
		this.worksheet.getAllCol().setVerticalText(val);
		fSetProperty = this._setPropertyNoEmpty;
	}
	fSetProperty.call(this, function(row){
		if(c_oRangeType.All == nRangeType && null == row.xfs)
			return;
		row.setVerticalText(val);
	},
	function(col){
		col.setVerticalText(val);
	},
	function(cell){
		cell.setVerticalText(val);
	});
};
Range.prototype.getType=function(){
	var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1);
	if(null != cell)
		return cell.getType();
	else
		return null;
};
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);
		oTempCell.create(xfs, this.getFirst());
		return oTempCell.getValueForEdit2();
	}
};
Range.prototype.getValueWithoutFormat=function(){
	var cell = this.worksheet._getCellNoEmpty(this.bbox.r1, this.bbox.c1);
	if(null != cell)
		return cell.getValueWithoutFormat();
	else
		return "";
};
Range.prototype.getValue=function(){
	return this.getValueWithoutFormat();
};
Range.prototype.getValueWithFormat=function(){
	var cell = this.worksheet._getCellNoEmpty(this.bbox.r1, this.bbox.c1);
	if(null != cell)
		return cell.getValue();
	else
		return "";
};
Range.prototype.getValue2=function(dDigitsCount, fIsFitMeasurer){
	//[{"text":"qwe","format":{"b":true, "i":false, "u":"none", "s":false, "fn":"Arial", "fs": 12, "c": 0xff00ff, "va": "subscript"  }},{}...]
	var nRow0 = this.bbox.r1;
	var nCol0 = this.bbox.c1;
	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);
		oTempCell.create(xfs, this.getFirst());
		return oTempCell.getValue2(dDigitsCount, fIsFitMeasurer);
	}
};
Alexander.Trofimov's avatar
Alexander.Trofimov committed
6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332
Range.prototype.getXfId=function(){
	var nRow = this.bbox.r1;
	var nCol = this.bbox.c1;
	var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
	if(null != cell) {
		var xfs = cell.getStyle();
		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;
};
6333
Range.prototype.getStyleName=function(){
6334 6335 6336 6337
	var res = this.worksheet.workbook.CellStyles.getStyleNameByXfId(this.getXfId());

	// ToDo убрать эту заглушку (нужно делать на открытии) в InitStyleManager
	return res || this.worksheet.workbook.CellStyles.getStyleNameByXfId(g_oDefaultXfId);
6338
};
6339 6340 6341 6342 6343 6344 6345 6346 6347
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)
    {
6348 6349 6350
		var xfs = cell.getStyle();
        if(null != xfs && null != xfs.num)
            return xfs.num.f;
6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363
    }
	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;
};
6364 6365 6366
Range.prototype.getNumFormatType=function(){
	return this.getNumFormat().getType();
}
6367 6368 6369 6370 6371 6372
Range.prototype.getFont = function(){
	var nRow = this.bbox.r1;
	var nCol = this.bbox.c1;
	var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
	if(null != cell)
    {
6373 6374 6375
		var xfs = cell.getStyle();
        if(null != xfs && null != xfs.font)
            return xfs.font;
6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394
    }
	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;
}
Range.prototype.getFontname=function(){
	var nRow = this.bbox.r1;
	var nCol = this.bbox.c1;
	var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
	if(null != cell)
    {
6395 6396 6397
		var xfs = cell.getStyle();
        if(null != xfs && null != xfs.font)
            return xfs.font.fn;
6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416
    }
	else
	{
		//стили столбов и колонок
		var row = this.worksheet._getRowNoEmpty(nRow);
		if(null != row && null != row.xfs && null != row.xfs.font)
			return row.xfs.font.fn;
		var col = this.worksheet._getColNoEmptyWithAll(nCol);
		if(null != col && null != col.xfs && null != col.xfs.font)
			return col.xfs.font.fn;
	}
    return g_oDefaultFont.fn;
};
Range.prototype.getFontsize=function(){
	var nRow = this.bbox.r1;
	var nCol = this.bbox.c1;
	var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
	if(null != cell)
    {
6417 6418 6419
		var xfs = cell.getStyle();
        if(null != xfs && null != xfs.font)
            return xfs.font.fs;
6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438
    }
	else
	{
		//стили столбов и колонок
		var row = this.worksheet._getRowNoEmpty(nRow);
		if(null != row && null != row.xfs && null != row.xfs.font)
			return row.xfs.font.fs;
		var col = this.worksheet._getColNoEmptyWithAll(nCol);
		if(null != col && null != col.xfs && null != col.xfs.font)
			return col.xfs.font.fs;
	}
    return g_oDefaultFont.fs;
};
Range.prototype.getFontcolor=function(){
	var nRow = this.bbox.r1;
	var nCol = this.bbox.c1;
	var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
	if(null != cell)
    {
6439 6440 6441
		var xfs = cell.getStyle();
        if(null != xfs && null != xfs.font)
            return xfs.font.c;
6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460
    }
	else
	{
		//стили столбов и колонок
		var row = this.worksheet._getRowNoEmpty(nRow);
		if(null != row && null != row.xfs && null != row.xfs.font)
			return row.xfs.font.c;
		var col = this.worksheet._getColNoEmptyWithAll(nCol);
		if(null != col && null != col.xfs && null != col.xfs.font)
			return col.xfs.font.c;
	}
    return g_oDefaultFont.c;
};
Range.prototype.getBold=function(){
	var nRow = this.bbox.r1;
	var nCol = this.bbox.c1;
	var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
	if(null != cell)
    {
6461 6462 6463
		var xfs = cell.getStyle();
        if(null != xfs && null != xfs.font)
            return xfs.font.b;
6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482
    }
	else
	{
		//стили столбов и колонок
		var row = this.worksheet._getRowNoEmpty(nRow);
		if(null != row && null != row.xfs && null != row.xfs.font)
			return row.xfs.font.b;
		var col = this.worksheet._getColNoEmptyWithAll(nCol);
		if(null != col && null != col.xfs && null != col.xfs.font)
			return col.xfs.font.b;
	}
    return g_oDefaultFont.b;
};
Range.prototype.getItalic=function(){
	var nRow = this.bbox.r1;
	var nCol = this.bbox.c1;
	var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
	if(null != cell)
    {
6483 6484 6485
		var xfs = cell.getStyle();
        if(null != xfs && null != xfs.font)
            return xfs.font.i;
6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504
    }
	else
	{
		//стили столбов и колонок
		var row = this.worksheet._getRowNoEmpty(nRow);
		if(null != row && null != row.xfs && null != row.xfs.font)
			return row.xfs.font.i;
		var col = this.worksheet._getColNoEmptyWithAll(nCol);
		if(null != col && null != col.xfs && null != col.xfs.font)
			return col.xfs.font.i;
	}
    return g_oDefaultFont.i;
};
Range.prototype.getUnderline=function(){
	var nRow = this.bbox.r1;
	var nCol = this.bbox.c1;
	var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
	if(null != cell)
    {
6505 6506 6507
		var xfs = cell.getStyle();
        if(null != xfs && null != xfs.font)
            return xfs.font.u;
6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526
    }
	else
	{
		//стили столбов и колонок
		var row = this.worksheet._getRowNoEmpty(nRow);
		if(null != row && null != row.xfs && null != row.xfs.font)
			return row.xfs.font.u;
		var col = this.worksheet._getColNoEmptyWithAll(nCol);
		if(null != col && null != col.xfs && null != col.xfs.font)
			return col.xfs.font.u;
	}
    return g_oDefaultFont.u;
};
Range.prototype.getStrikeout=function(val){
	var nRow = this.bbox.r1;
	var nCol = this.bbox.c1;
	var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
	if(null != cell)
    {
6527 6528 6529
		var xfs = cell.getStyle();
        if(null != xfs && null != xfs.font)
            return xfs.font.s;
6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548
    }
	else
	{
		//стили столбов и колонок
		var row = this.worksheet._getRowNoEmpty(nRow);
		if(null != row && null != row.xfs && null != row.xfs.font)
			return row.xfs.font.s;
		var col = this.worksheet._getColNoEmptyWithAll(nCol);
		if(null != col && null != col.xfs && null != col.xfs.font)
			return col.xfs.font.s;
	}
    return g_oDefaultFont.s;
};
Range.prototype.getFontAlign=function(){
	var nRow = this.bbox.r1;
	var nCol = this.bbox.c1;
	var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
	if(null != cell)
    {
6549 6550 6551
		var xfs = cell.getStyle();
        if(null != xfs && null != xfs.font)
            return xfs.font.va;
6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568
    }
	else
	{
		//стили столбов и колонок
		var row = this.worksheet._getRowNoEmpty(nRow);
		if(null != row && null != row.xfs && null != row.xfs.font)
			return row.xfs.font.va;
		var col = this.worksheet._getColNoEmptyWithAll(nCol);
		if(null != col && null != col.xfs && null != col.xfs.font)
			return col.xfs.font.va;
	}
    return g_oDefaultFont.va;
};
Range.prototype.getQuotePrefix=function(){
	var nRow = this.bbox.r1;
	var nCol = this.bbox.c1;
	var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
6569 6570 6571 6572 6573 6574
	if(null != cell)
	{
		var xfs = cell.getStyle();
		if(null != xfs && null != xfs.QuotePrefix)
			return xfs.QuotePrefix;
	}
6575 6576 6577 6578 6579 6580 6581 6582
	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)
    {
6583
		var xfs = cell.getStyle();
6584 6585 6586 6587 6588 6589 6590
        if(null != xfs)
		{
			if(null != xfs.align)
				return xfs.align.ver;
			else
				return g_oDefaultAlignAbs.ver;
		}
6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609
    }
	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)
    {
6610
		var xfs = cell.getStyle();
6611 6612 6613 6614 6615 6616 6617
        if(null != xfs)
		{
			if(null != xfs.align)
				return xfs.align.hor;
			else
				return g_oDefaultAlignAbs.hor;
		}
6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671
    }
	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)
    {
6672 6673 6674
		var xfs = cell.getStyle();
        if(null != xfs && null != xfs.fill)
            return xfs.fill.bg;
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
    }
	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)
    {
6702 6703 6704
		var xfs = cell.getStyle();
        if(null != xfs && null != xfs.border)
            return xfs.border;
6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742
    }
	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;    
6743
	if(c_oAscBorderStyles.None === borders.l.s){
6744
		if(nCol > 1){
6745
			var left = this.getBorder(new CellAddress(nRow, nCol - 1, 0));
6746
			if(c_oAscBorderStyles.None !== left.r.s)
6747 6748 6749
				borders.l = left.r;
		}
	}
6750
	if(c_oAscBorderStyles.None === borders.t.s){
6751
		if(nRow > 1){
6752
			var top = this.getBorder(new CellAddress(nRow - 1, nCol, 0));
6753
			if(c_oAscBorderStyles.None !== top.b.s)
6754 6755 6756
				borders.t = top.b;
		}
	}
6757
	if(c_oAscBorderStyles.None === borders.r.s){
6758
		var right = this.getBorder(new CellAddress(nRow, nCol + 1, 0));
6759
		if(c_oAscBorderStyles.None !== right.l.s)
6760 6761
			borders.r = right.l;
	}
6762
	if(c_oAscBorderStyles.None === borders.b.s){
6763
		var bottom = this.getBorder(new CellAddress(nRow + 1, nCol, 0));
6764
		if(c_oAscBorderStyles.None !== bottom.t.s)
6765 6766 6767 6768 6769 6770 6771 6772 6773 6774
			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)
    {
6775
		var xfs = cell.getStyle();
6776 6777 6778 6779 6780 6781 6782
        if(null != xfs)
		{
			if(null != xfs.align)
				return xfs.align.shrink;
			else
				return g_oDefaultAlignAbs.shrink;
		}
6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795
    }
	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;
};
6796 6797 6798 6799
Range.prototype.getWrapByAlign = function (align) {
	// Для justify wrap всегда true
	return "justify" === align.hor ? true : align.wrap;
};
6800 6801 6802 6803
Range.prototype.getWrap=function(){
	var nRow = this.bbox.r1;
	var nCol = this.bbox.c1;
	var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
6804
	if(null != cell) {
6805
		var xfs = cell.getStyle();
6806
        if(null != xfs) {
6807
			if(null != xfs.align)
6808
				return this.getWrapByAlign(xfs.align);
6809
			else
6810
				return this.getWrapByAlign(g_oDefaultAlignAbs);
6811
		}
6812
    } else {
6813 6814 6815
		//стили столбов и колонок
		var row = this.worksheet._getRowNoEmpty(nRow);
		if(null != row && null != row.xfs && null != row.xfs.align)
6816
			return this.getWrapByAlign(row.xfs.align);
6817 6818
		var col = this.worksheet._getColNoEmptyWithAll(nCol);
		if(null != col && null != col.xfs && null != col.xfs.align)
6819
			return this.getWrapByAlign(col.xfs.align);
6820
	}
6821
    return this.getWrapByAlign(g_oDefaultAlign);
6822 6823 6824 6825 6826 6827 6828 6829
};
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)
    {
6830
		var xfs = cell.getStyle();
6831 6832 6833 6834 6835 6836 6837
        if(null != xfs)
		{
			if(null != xfs.align)
				return angleFormatToInterface(xfs.align.angle);
			else
				return angleFormatToInterface(g_oDefaultAlignAbs.angle);
		}
6838 6839 6840 6841 6842 6843
    }
	else
	{
		//стили столбов и колонок
		var row = this.worksheet._getRowNoEmpty(nRow);
		if(null != row && null != row.xfs && null != row.xfs.align)
6844
			return angleFormatToInterface(row.xfs.align.angle);
6845 6846
		var col = this.worksheet._getColNoEmptyWithAll(nCol);
		if(null != col && null != col.xfs && null != col.xfs.align)
6847
			return angleFormatToInterface(col.xfs.align.angle);
6848
	}
6849
    return angleFormatToInterface(g_oDefaultAlign.angle);
6850 6851 6852 6853 6854 6855 6856
};
Range.prototype.getVerticalText=function(){
	var nRow = this.bbox.r1;
	var nCol = this.bbox.c1;
	var cell = this.worksheet._getCellNoEmpty(nRow, nCol);
	if(null != cell)
    {
6857
		var xfs = cell.getStyle();
6858 6859 6860 6861 6862 6863 6864
        if(null != xfs)
		{
			if(null != xfs.align)
				return g_nVerticalTextAngle == xfs.align.angle;
			else
				return g_nVerticalTextAngle == g_oDefaultAlignAbs.angle;
		}
6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876
    }
	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
6877
}
6878 6879
Range.prototype.hasMerged=function(){
	var oThis = this;
6880 6881 6882
	var aMerged = this.worksheet.mergeManager.get(this.bbox);
	if(aMerged.all.length > 0)
		return aMerged.all[0].bbox;
6883 6884 6885
	return null;
};
Range.prototype.mergeOpen=function(){
6886
	this.worksheet.mergeManager.add(this.bbox, 1);
6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899
}
Range.prototype.merge=function(type){
	if(null == type)
		type = c_oAscMergeOptions.Merge;
	var oBBox = this.bbox;
	if(oBBox.r1 == oBBox.r2 && oBBox.c1 == oBBox.c2)
		return;
	History.Create_NewPoint();
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	History.StartTransaction();
	if(this.hasMerged())
	{
		this.unmerge();
6900 6901 6902 6903 6904 6905 6906
		if(type == c_oAscMergeOptions.MergeCenter)
		{
			//сбрасываем AlignHorizontal
			this.setAlignHorizontal("none");
			History.EndTransaction();
			return;
		}
6907 6908 6909 6910 6911 6912 6913 6914 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 6969 6970 6971 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 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009
	}
	//пробегаемся по границе диапазона, чтобы посмотреть какие границы нужно оставлять
	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;
		}
		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;
		}
	}
	//правила работы с гиперссылками во время merge(отличются от Excel в случаем областей, например hyperlink: C3:D3 мержим C2:C3)
	//1) Если первой встретилась ссылка в одной ячейке, то эта ссылка переходит в первую ячейку мерженой области, останые одноклеточные ссылки внутри мерженой области стираются
	//2) Если встретилась многоклеточная ссылка, которая полностью лежит в замерженой области(но не совпадает с ней), она удаляется
	//3) Если встретилась многоклеточная ссылка, которая не полностью лежит в замерженой области(или совпадает с ней), то такие ссылки оставляем без изменений.
	//4) Ссылки в строках, столбцах всегда остаются без изменений
	
	var bFirst = true;
	var oThis = this;
	var oLeftTopCellStyle = null;
	var oFirstCellStyle = null;
	var oFirstCellValue = null;
	var oFirstCellRow = null;
	var oFirstCellCol = null;
	var oFirstCellHyperlink = null;
	this._setPropertyNoEmpty(null,null,
	function(cell, nRow0, nCol0, nRowStart, nColStart){
		if(bFirst && false == cell.isEmptyText())
		{
			bFirst = false;
			oFirstCellStyle = cell.getStyle();
			oFirstCellValue = cell.getValueData();
			oFirstCellRow = cell.oId.getRow0();
			oFirstCellCol = cell.oId.getCol0();
7010 7011 7012
			var oCurHyp = oThis.worksheet.hyperlinkManager.getByCell(oFirstCellRow, oFirstCellCol);
			//todo надо весь массив просмотреть
			if(null != oCurHyp && oCurHyp.data.Ref.isOneCell())
7013
			{
7014
				oFirstCellHyperlink = oCurHyp.data;
7015 7016
			}
		}
7017
		if(nRow0 == nRowStart && nCol0 == nColStart)
7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193
			oLeftTopCellStyle = cell.getStyle();
		
		cell.setValue("");
	});
	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)
		{
			var oLeftTopRange = this.worksheet.getCell(new CellAddress(oBBox.r1, oBBox.c1, 0));
			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 bEmptyStyle = true;
	var bEmptyBorder = true;
	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");
7194
	if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges)
7195
		this.worksheet.mergeManager.add(this.bbox, 1);
7196 7197 7198
	History.EndTransaction();
};
Range.prototype.unmerge=function(bOnlyInRange){
7199 7200 7201
	History.Create_NewPoint();
	History.SetSelection(this.bbox.clone());
	History.StartTransaction();
7202
	if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges)
7203
		this.worksheet.mergeManager.remove(this.bbox, null);
7204
	History.EndTransaction();
7205
};
7206
Range.prototype._getHyperlinks=function(){
7207 7208 7209 7210 7211
	var nRangeType = this._getRangeType();
	var result = [];
	var oThis = this;
	if(c_oRangeType.Range == nRangeType)
	{
7212 7213 7214
		var oTempRows = {};
		var fAddToTempRows = function(oTempRows, bbox, data){
			if(null != bbox)
7215
			{
7216 7217 7218 7219
				for(var i = bbox.r1; i <= bbox.r2; i++)
				{
					var row = oTempRows[i];
					if(null == row)
7220
					{
7221 7222
						row = {};
						oTempRows[i] = row;
7223
					}
7224
					for(var j = bbox.c1; j <= bbox.c2; j++)
7225
					{
7226 7227 7228
						var cell = row[j];
						if(null == cell)
							row[j] = data;
7229
					}
7230
				}
7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246
			}
		};
		//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);
7247
			}
7248
		}
7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264
		//формируем результат
		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;
}
Range.prototype.getHyperlink=function(){
7265
	var aHyperlinks = this._getHyperlinks();
7266 7267 7268 7269 7270
	if(null != aHyperlinks && aHyperlinks.length > 0)
		return aHyperlinks[0].hyperlink;
	return null;
};
Range.prototype.getHyperlinks=function(){
7271
	return this._getHyperlinks();
7272
};
7273 7274 7275
Range.prototype.setHyperlinkOpen=function(val){
	if(null != val && false == val.isValid())
		return;
7276
	this.worksheet.hyperlinkManager.add(val.Ref.getBBox0(), val);
7277
}
7278 7279 7280
Range.prototype.setHyperlink=function(val, bWithoutStyle){
	if(null != val && false == val.isValid())
		return;
7281 7282
	//проверяем, может эта ссылка уже существует
	var bExist = false;
7283 7284
	var aHyperlinks = this.worksheet.hyperlinkManager.get(this.bbox);
	for(var i = 0, length = aHyperlinks.all.length; i < length; i++)
7285
	{
7286 7287
		var hyp = aHyperlinks.all[i];
		if(hyp.data.isEqual(val))
7288 7289 7290 7291 7292
		{
			bExist = true;
			break;
		}
	}
7293 7294 7295 7296 7297 7298
	if(false == bExist)
	{
		var oThis = this;
		History.Create_NewPoint();
		History.SetSelection(this.bbox.clone());
		History.StartTransaction();
7299
		if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges)
7300
		{
7301 7302 7303 7304 7305
			//удаляем ссылки с тем же адресом
			for(var i = 0, length = aHyperlinks.all.length; i < length; i++)
			{
				var hyp = aHyperlinks.all[i];
				if(hyp.bbox.isEqual(this.bbox))
7306
					this.worksheet.hyperlinkManager.remove(hyp.bbox, hyp);
7307
			}
7308
		}
7309
		//todo перейти на CellStyle
7310
		if(true != bWithoutStyle)
7311 7312 7313 7314 7315 7316 7317 7318
		{
			var oHyperlinkFont = new Font();
			oHyperlinkFont.fn = this.worksheet.workbook.getDefaultFont();
			oHyperlinkFont.fs = this.worksheet.workbook.getDefaultSize();
			oHyperlinkFont.u = "single";
			oHyperlinkFont.c = g_oColorManager.getThemeColor(g_nColorHyperlink);
			this.setFont(oHyperlinkFont);
		}
7319
		if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges)
7320
			this.worksheet.hyperlinkManager.add(val.Ref.getBBox0(), val);
7321
		History.EndTransaction();
7322 7323 7324
	}
};
Range.prototype.removeHyperlink=function(val){
7325 7326
	var bbox = this.bbox;
	var elem = null;
7327 7328
	if(null != val)
	{
7329 7330
		bbox = val.Ref.getBBox0();
		elem = new RangeDataManagerElem(bbox, val);
7331
	}
7332 7333 7334
	History.Create_NewPoint();
	History.SetSelection(bbox.clone());
	History.StartTransaction();
7335
	if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges)
7336
		this.worksheet.hyperlinkManager.remove(bbox, elem);
7337 7338 7339 7340 7341 7342 7343 7344 7345 7346
	History.EndTransaction();
}
Range.prototype.deleteCellsShiftUp=function(){
	return this._shiftUpDown(true);
};
Range.prototype.addCellsShiftBottom=function(){
	return this._shiftUpDown(false);
};
Range.prototype.addCellsShiftRight=function(){
	return this._shiftLeftRight(false);
7347
};
7348 7349 7350 7351 7352 7353 7354 7355 7356
Range.prototype.deleteCellsShiftLeft=function(){
	return this._shiftLeftRight(true);
};
Range.prototype._shiftLeftRight=function(bLeft){
	var oBBox = this.bbox;
	var nWidth = oBBox.c2 - oBBox.c1 + 1;
	var nRangeType = this._getRangeType(oBBox);
	if(c_oRangeType.Range != nRangeType && c_oRangeType.Col != nRangeType)
		return false;
7357 7358
	var mergeManager = this.worksheet.mergeManager;
	//todo вставить предупреждение, что будет unmerge
7359 7360 7361
	History.Create_NewPoint();
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	History.StartTransaction();
7362
	if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges)
7363
	{
7364 7365 7366
		var oShiftGet = mergeManager.shiftGet(this.bbox, true);
		var aMerged = oShiftGet.elems;
		if(null != aMerged.outer && aMerged.outer.length > 0)
7367
		{
7368 7369
			var bChanged = false;
			for(var i = 0, length = aMerged.outer.length; i < length; i++)
7370
			{
7371 7372 7373
				var elem = aMerged.outer[i];
				if(!(elem.bbox.c1 < oShiftGet.bbox.c1 && oShiftGet.bbox.r1 <= elem.bbox.r1 && elem.bbox.r2 <= oShiftGet.bbox.r2))
				{
7374
					mergeManager.remove(elem.bbox, elem);
7375 7376
					bChanged = true;
				}
7377
			}
7378 7379
			if(bChanged)
				oShiftGet = null;
7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396
		}
	}
	//сдвигаем ячейки
	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);
	}
7397
	if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges)
7398 7399 7400 7401
	{
		mergeManager.shift(this.bbox, !bLeft, true, oShiftGet);
		this.worksheet.hyperlinkManager.shift(this.bbox, !bLeft, true);
	}
7402 7403 7404 7405 7406 7407 7408 7409 7410
	History.EndTransaction();
	return true;
};
Range.prototype._shiftUpDown=function(bUp){
	var oBBox = this.bbox;
	var nHeight = oBBox.r2 - oBBox.r1 + 1;
	var nRangeType = this._getRangeType(oBBox);
	if(c_oRangeType.Range != nRangeType && c_oRangeType.Row != nRangeType)
		return false;
7411 7412
	var mergeManager = this.worksheet.mergeManager;
	//todo вставить предупреждение, что будет unmerge
7413 7414 7415
	History.Create_NewPoint();
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	History.StartTransaction();
7416 7417 7418 7419 7420 7421 7422 7423
	if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges)
	{
		var oShiftGet = mergeManager.shiftGet(this.bbox, false);
		var aMerged = oShiftGet.elems;
		if(null != aMerged.outer && aMerged.outer.length > 0)
		{	
			var bChanged = false;
			for(var i = 0, length = aMerged.outer.length; i < length; i++)
7424
			{
7425 7426 7427
				var elem = aMerged.outer[i];
				if(!(elem.bbox.r1 < oShiftGet.bbox.r1 && oShiftGet.bbox.c1 <= elem.bbox.c1 && elem.bbox.c2 <= oShiftGet.bbox.c2))
				{
7428
					mergeManager.remove(elem.bbox, elem);
7429 7430
					bChanged = true;
				}
7431
			}
7432 7433
			if(bChanged)
				oShiftGet = null;
7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450
		}
	}
	//сдвигаем ячейки
	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);
	}
7451
	if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges)
7452 7453 7454 7455
	{
		mergeManager.shift(this.bbox, !bUp, false, oShiftGet);
		this.worksheet.hyperlinkManager.shift(this.bbox, !bUp, false);
	}
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 7503
	History.EndTransaction();
	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);
}
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);
}
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);
}
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;
}
7504 7505 7506 7507 7508
Range.prototype.cleanCache=function(){
	this._setPropertyNoEmpty(null,null,function(cell, nRow0, nCol0, nRowStart, nColStart){
		cell.cleanCache();
	});
}
7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550
Range.prototype.cleanFormat=function(){
	History.Create_NewPoint();
	var oBBox = this.bbox;
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	History.StartTransaction();
	this.unmerge();
	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){
		cell.setStyle(null);
		// if(cell.isEmpty())
			// cell.Remove();
	});
	History.EndTransaction();
}
Range.prototype.cleanText=function(){
	History.Create_NewPoint();
	var oBBox = this.bbox;
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	History.StartTransaction();
	var oThis = this;
	this._setPropertyNoEmpty(null, null,
		function(cell, nRow0, nCol0, nRowStart, nColStart){
			cell.setValue("");
			// if(cell.isEmpty())
				// cell.Remove();
	});
	History.EndTransaction();
}
Range.prototype.cleanAll=function(){
	History.Create_NewPoint();
	var oBBox = this.bbox;
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	History.StartTransaction();
	this.unmerge();
7551 7552 7553 7554
	//удаляем только гиперссылки, которые полностью лежат в области
	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);
7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566
	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
7567
	buildRecalc(this.worksheet.workbook);
7568 7569 7570 7571 7572
	History.EndTransaction();
}
Range.prototype.sort=function(nOption, nStartCol){
	//todo sort с замержеными ячейками.
	//todo горизонтальная сортировка
7573
    lockDraw(this.worksheet.workbook);
7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657
	if(null != this.hasMerged())
		return null;
	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){
			var nCurCol0 = cell.oId.getCol0();
			if(nCurCol0 > nLastCol0)
				nLastCol0 = nCurCol0;
		});
	}
	//собираем массив обьектов для сортировки
	var aSortElems = new Array();
	var aHiddenRow = new Object();
	var fAddSortElems = function(oCell, nRow0, nCol0,nRowStart0, nColStart0){
		//не сортируем сткрытие строки
		var row = oThis.worksheet._getRowNoEmpty(nRow0);
		if(null != row)
		{
			if(true == row.hd)
				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){
7658
		var res = 0;
7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672
		if(null != a.text)
		{
			if(null != b.text)
				res = strcmp(a.text, b.text);
			else
				res = 1;
		}
		else if(null != a.num)
		{
			if(null != b.num)
				res = a.num - b.num;
			else
				res = -1;
		}
7673 7674 7675 7676 7677
		if(0 == res)
			res = a.row - b.row;
		else if(!bAscent)
			res = -res;
		return res;
7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734
	});
	//проверяем что это не пустая операция
	var aSortData = new Array();
	var nHiddenCount = 0;
	var oFromArray = new Object();
	var nRowMax = 0;
	var nRowMin = gc_nMaxRow0;
	var nToMax = 0;
	for(var i = 0, length = aSortElems.length; i < length; ++i)
	{
		var item = aSortElems[i];
		var nNewIndex = i + nRowFirst0 + nHiddenCount;
		while(null != aHiddenRow[nNewIndex])
		{
			nHiddenCount++;
			nNewIndex = i + nRowFirst0 + nHiddenCount;
		}
		var oNewElem = new UndoRedoData_FromToRowCol(true, item.row, nNewIndex);
		oFromArray[item.row] = 1;
		if(nRowMax < item.row)
			nRowMax = item.row;
		if(nRowMax < nNewIndex)
			nRowMax = nNewIndex;
		if(nRowMin > item.row)
			nRowMin = item.row;
		if(nRowMin > nNewIndex)
			nRowMin = nNewIndex;
		if(nToMax < nNewIndex)
			nToMax = nNewIndex;
		if(oNewElem.from != oNewElem.to)
			aSortData.push(oNewElem);
	}
	if(aSortData.length > 0)
	{
		//добавляем индексы перехода пустых ячеек(нужно для сортировки комментариев)
		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();
		History.SetSelection(new Asc.Range(nColFirst0, nRowFirst0, nLastCol0, nLastRow0));
		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);
		this._sortByArray(oUndoRedoBBox, aSortData, false);
	}
7735 7736
    buildRecalc(this.worksheet.workbook,true);
    unLockDraw(this.worksheet.workbook);
7737 7738 7739
	return oRes;
}
Range.prototype._sortByArray=function(oBBox, aSortData, bUndo){
7740
    var rec = {length:0};
7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753
	var oSortedIndexes = new Object();
	for(var i = 0, length = aSortData.length; i < length; ++i)
	{
		var item = aSortData[i];
		var nFrom = item.from;
		var nTo = item.to;
		if(bUndo)
		{
			nFrom = item.to;
			nTo = item.from;
		}
		oSortedIndexes[nFrom] = nTo;
	}
7754 7755
	//сортируются только одинарные гиперссылки, все неодинарные оставляем
	var aSortedHyperlinks = new Array();
7756
	if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges)
7757
	{
7758 7759
		var aHyperlinks = this.worksheet.hyperlinkManager.get(this.bbox);
		for(var i = 0, length = aHyperlinks.inner.length; i < length; i++)
7760
		{
7761 7762 7763
			var elem = aHyperlinks.inner[i];
			var hyp = elem.data;
			if(hyp.Ref.isOneCell())
7764
			{
7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775
				var nFrom = elem.bbox.r1;
				var nTo = oSortedIndexes[nFrom];
				if(null != nTo)
				{
					//удаляем ссылки, а не перемеаем, чтобы не было конфликтов(например в случае если все ячейки имеют ссылки и их надо передвинуть)
					var oTempBBox = hyp.Ref.getBBox0();
					this.worksheet.hyperlinkManager.remove(oTempBBox, new RangeDataManagerElem(oTempBBox, hyp));
					var oNewHyp = hyp.clone();
					oNewHyp.Ref.setOffset({offsetCol: 0, offsetRow: nTo - nFrom});
					aSortedHyperlinks.push(oNewHyp);
				}
7776 7777 7778
			}
		}
	}
7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811
	//окончательно устанавливаем ячейки
	var nColFirst0 = oBBox.c1;
	var nLastCol0 = oBBox.c2;
	for(var i = nColFirst0; i <= nLastCol0; ++i)
	{
		//запоминаем ячейки в которые уже что-то передвинули, чтобы не потерять их
		var oTempCellsTo = new Object();
		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;
			var oTempCell = oTempCellsTo[nIndexFrom];
			if(oTempCellsTo.hasOwnProperty(nIndexFrom))
				oCurCell = oTempCell;
			else
				oCurCell = rowFrom.c[i];
			oTempCellsTo[nIndexTo] = rowTo.c[i];
			if(null != oCurCell)
			{
				var lastName = oCurCell.getName();
				oCurCell.moveVer(shift);
				rowTo.c[i] = oCurCell;
				var sNewName = oCurCell.getName();
				if(oCurCell.sFormula)
				{
					oCurCell.setFormula(oCurCell.formulaParsed.changeOffset({offsetCol:0, offsetRow:shift}).assemble());//получаем новую формулу, путем сдвига входящих в нее ссылок на ячейки на offsetCol и offsetRow. не путать с shiftCells - меняет одну конкретную ячейку в формуле, changeOffset - меняет оффсет для всех входящих в формулу ячеек.
					this.worksheet.workbook.dependencyFormulas.deleteMasterNodes( this.worksheet.Id, lastName );//разрываем ссылки между старой ячейкой и ведущими ячейками для нее.
					delete this.worksheet.workbook.cwf[this.worksheet.Id].cells[lastName];
7812 7813 7814 7815 7816

                    if( !arrRecalc[this.worksheet.getId()] ){
                        arrRecalc[this.worksheet.getId()] = {};
                    }
                    arrRecalc[this.worksheet.getId()][sNewName] = sNewName;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
7817
                    /*this.worksheet.workbook.needRecalc[ getVertexId(this.worksheet.getId(),sNewName) ] = [ this.worksheet.getId(),sNewName ];
7818
                    if( this.worksheet.workbook.needRecalc.length < 0) this.worksheet.workbook.needRecalc.length = 0;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
7819
                    this.worksheet.workbook.needRecalc.length++;*/
7820

7821 7822
				}
				else{
7823
//					sortDependency(this.worksheet, {sNewName:sNewName});
7824 7825 7826 7827 7828 7829 7830 7831 7832
				}
			}
			else
			{
				if(null != rowTo.c[i])
				{
					//здесь достаточно простого delete, потому что на самом деле в функции ячейки только меняются местами, удаления не происходит
					delete rowTo.c[i];
					var sNewName = (new CellAddress(nIndexTo, i, 0)).getID();
7833 7834 7835 7836
                    if( !arrRecalc[this.worksheet.getId()] ){
                        arrRecalc[this.worksheet.getId()] = {};
                    }
                    arrRecalc[this.worksheet.getId()][sNewName] = sNewName;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
7837
                    /*this.worksheet.workbook.needRecalc[ getVertexId(this.worksheet.getId(),sNewName) ] = [ this.worksheet.getId(),sNewName ];
7838
                    if( this.worksheet.workbook.needRecalc.length < 0) this.worksheet.workbook.needRecalc.length = 0;
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
7839
                    this.worksheet.workbook.needRecalc.length++;*/
7840
//					sortDependency(this.worksheet, {sNewName:sNewName});
7841 7842 7843 7844
				}
			}
		}
	}
7845
//    this.worksheet.workbook.buildDependency();
7846
//    this.worksheet.workbook.needRecalc = rec;
7847

7848
//    recalc(this.worksheet.workbook);
7849
	if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges)
7850
	{
7851 7852
		//восстанавливаем удаленые гиперссылки
		if(aSortedHyperlinks.length > 0)
7853
		{
7854 7855 7856 7857 7858
			for(var i = 0, length = aSortedHyperlinks.length; i < length; i++)
			{
				var hyp = aSortedHyperlinks[i];
				this.worksheet.hyperlinkManager.add(hyp.Ref.getBBox0(), hyp);
			}
7859 7860
		}
	}
7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897
};
Range.prototype.promote=function(bCtrl, bVertical, nIndex){
	var oBBox = this.bbox;
	var nWidth = oBBox.c2 - oBBox.c1 + 1;
    var nHeight = oBBox.r2 - oBBox.r1 + 1;
	var bWholeCol = false;	var bWholeRow = false;
	if(0 == oBBox.r1 && gc_nMaxRow0 == oBBox.r2)
		bWholeCol = true;
 	if(0 == oBBox.c1 && gc_nMaxCol0 == oBBox.c2)
		bWholeRow = true;
	if((bWholeCol && bWholeRow) || (true == bVertical && bWholeCol) || (false == bVertical && bWholeRow))
		return;
	var oPromoteRange = null;
	if(bVertical)
	{
		if(nHeight < nIndex)
			oPromoteRange = this.worksheet.getRange3(oBBox.r2 + 1, oBBox.c1, oBBox.r2 + nIndex - nHeight, oBBox.c2);
		else if(nIndex < 0)
			oPromoteRange = this.worksheet.getRange3(oBBox.r1 - 1, oBBox.c1, oBBox.r1 + nIndex, oBBox.c2);
	}
	else
	{
		if(nWidth < nIndex)
			oPromoteRange = this.worksheet.getRange3(oBBox.r1, oBBox.c2 + 1, oBBox.r2, oBBox.c2 + nIndex - nWidth);
		else if(nIndex < 0)
			oPromoteRange = this.worksheet.getRange3(oBBox.r1, oBBox.c1 - 1, oBBox.r2, oBBox.c1 + nIndex);
	}
	if(null != oPromoteRange && oPromoteRange.hasMerged())
		return;
	lockDraw(this.worksheet.workbook);
	History.Create_NewPoint();
	var recalcArr = [];
	History.SetSelection(new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2));
	History.StartTransaction();
    
	if((true == bVertical && 1 == nHeight) || (false == bVertical && 1 == nWidth))
		bCtrl = !bCtrl;
7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909
	var fFinishSection = function(param, oPromoteHelper)
	{
		if(null != param && null != param.prefix)
		{
			if(false == oPromoteHelper.isOnlyIntegerSequence())
			{
				param.valid = false;
				oPromoteHelper.removeLast();
			}
		}
		oPromoteHelper.finishSection();
	}
7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943
    if(true == bVertical)
    {
		//todo слишком простое решение, возможно в случае строки надо создавать массив колонок
		var nLastCol = oBBox.c2;
		if(bWholeRow)
		{
			nLastCol = 0;
			this._foreachRowNoEmpty(function(){}, function(cell){
				var nCurCol0 = cell.oId.getCol0();
				if(nCurCol0 > nLastCol0)
					nLastCol0 = nCurCol0;
			});
		}
        if(nIndex >= 0 && nHeight > nIndex)
        {
			//удаляем содержимое
            for(var i = oBBox.c1; i <= nLastCol; ++i)
            {
                for(var j = oBBox.r1 + nIndex; j <= oBBox.r2; ++j)
                {
                    var oCurCell = this.worksheet._getCellNoEmpty(j, i);
                    if(null != oCurCell)
                        oCurCell.setValue("");
                }
            }
        }
        else
        {
            //копируем содержимое
            for(var i = oBBox.c1; i <= nLastCol; ++i)
            {
                //пробегаемся по диапазону запоминаем ячеек смотрим какие из них числа
                var aCells = new Array();
				var oPromoteHelper = new PromoteHelper();
7944
				var oDigParams = null;
7945 7946 7947 7948
                for(var j = oBBox.r1; j <= oBBox.r2; ++j)
                {
                    var oCurCell = this.worksheet._getCellNoEmpty(j, i);
                    var nVal = null, nF = null;
7949
					var sCurPrefix = null;
7950 7951 7952 7953 7954
                    if(null != oCurCell)
                    {
						if (!oCurCell.sFormula)
                        {
							var nType = oCurCell.getType();
7955
							if(CellValueType.Number == nType || CellValueType.String == nType)
7956 7957 7958 7959
							{
                                var sValue = oCurCell.getValueWithoutFormat();
                                if("" != sValue)
                                {
7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995
									if(CellValueType.Number == nType)
										nVal = sValue - 0;
									else
									{
										//если текст заканчивается на цифру тоже используем ее
										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)
										{
											sCurPrefix = sValue.substring(0, nEndIndex);
											nVal = sValue.substring(nEndIndex) - 0;
										}
									}
									if(null != nVal)
									{
										if(null == oDigParams)
											oDigParams = {valid: true, prefix: sCurPrefix};
										else if(sCurPrefix != oDigParams.prefix)
										{
											fFinishSection(oDigParams, oPromoteHelper);
											oDigParams = {valid: true, prefix: sCurPrefix};
										}
										oPromoteHelper.add(nVal);
									}
									else
									{
										fFinishSection(oDigParams, oPromoteHelper);
										oDigParams = null;
									}
7996 7997 7998 7999
                                }
                            }
						}
						else{
8000 8001
							fFinishSection(oDigParams, oPromoteHelper);
							oDigParams = null;
8002 8003 8004
							nF = true;
						}
                    }
8005 8006 8007 8008
					if(null == nVal)
						aCells.push({digparams: null, cell: oCurCell, formula:nF});
					else
						aCells.push({digparams: oDigParams, cell: oCurCell, formula:nF});
8009
                }
8010
				fFinishSection(oDigParams, oPromoteHelper);
8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058
				oPromoteHelper.finishAdd();
                var bExistDigit = false;
                if(false == bCtrl && false == oPromoteHelper.isEmpty())
                {
                    bExistDigit = true;
					oPromoteHelper.calc();
                }
                var nCellsLength = aCells.length;
                var nCellsIndex;
                var nStart;
                var nEnd;
                var nDj;
                var nDCellsIndex;
                var fCondition;
                if(nIndex > 0)
                {
                    nStart = oBBox.r2 + 1;
                    nEnd = oBBox.r2 + (nIndex - nHeight + 1);
                    nCellsIndex = 0;
                    nDj = 1;
                    nDCellsIndex = 1;
                    fCondition = function(j , nEnd){return j <= nEnd;}
                }
                else
                {
					oPromoteHelper.reverse();
                    nStart = oBBox.r1 - 1;
                    nEnd = oBBox.r1 + nIndex;
                    if(nEnd < 0)
                        nEnd = 0;
                    nCellsIndex = nCellsLength - 1;
                    nDj = -1;
                    nDCellsIndex = -1;
                    fCondition = function(j , nEnd){return j >= nEnd;}
                }
                for(var j = nStart; fCondition(j, nEnd); j += nDj)
                {
                    var oCurItem = aCells[nCellsIndex];
                    //удаляем текущее содержимое ячейки
                    var oCurCell = this.worksheet._getCellNoEmpty(j, i);
                    if(null != oCurCell){
						this.worksheet._removeCell(j, i);
					}
                    if(null != oCurItem.cell)
                    {
                        var oCopyCell = this.worksheet._getCell(j, i);
                        oCopyCell.setStyle(oCurItem.cell.getStyle());
                        oCopyCell.setType(oCurItem.cell.getType());
8059
                        if(bExistDigit && null != oCurItem.digparams && true == oCurItem.digparams.valid)
8060 8061
                        {
							var dNewValue = oPromoteHelper.getNext();
8062 8063 8064 8065 8066
							var sVal = "";
							if(null != oCurItem.digparams.prefix)
								sVal += oCurItem.digparams.prefix;
							sVal += dNewValue;
                            oCopyCell.setValue(sVal);
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 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146
                        }
                        else
                        {
                            //копируем полностью
							if(!oCurItem.formula){
								var DataOld = oCopyCell.getValueData();
								oCopyCell.oValue = oCurItem.cell.oValue.clone(oCopyCell);
								var DataNew = oCopyCell.getValueData();
								if(false == DataOld.isEqual(DataNew))
									History.Add(g_oUndoRedoCell, historyitem_Cell_ChangeValue, this.worksheet.getId(), new Asc.Range(0, oCopyCell.oId.getRow0(), gc_nMaxCol0, oCopyCell.oId.getRow0()), new UndoRedoData_CellSimpleData(oCopyCell.oId.getRow0(), oCopyCell.oId.getCol0(), DataOld, DataNew));
								//todo
								// if(oCopyCell.isEmptyTextString())
									// this.worksheet._getHyperlink().remove({r1: oCopyCell.oId.getRow0(), c1: oCopyCell.oId.getCol0(), r2: oCopyCell.oId.getRow0(), c2: oCopyCell.oId.getCol0()});
								
								if( !arrRecalc[this.worksheet.getId()] ){
									arrRecalc[this.worksheet.getId()] = {};
								}
								arrRecalc[this.worksheet.getId()][oCopyCell.getName()] = oCopyCell.getName();
								this.worksheet.workbook.needRecalc[ getVertexId(this.worksheet.getId(),oCopyCell.getName()) ] = [ this.worksheet.getId(),oCopyCell.getName() ];
								if( this.worksheet.workbook.needRecalc.length < 0) this.worksheet.workbook.needRecalc.length = 0;
								this.worksheet.workbook.needRecalc.length++;
							}
							else{
								var assemb;
								var _p_ = new parserFormula(oCurItem.cell.sFormula,oCopyCell.getName(),this.worksheet);
								if( _p_.parse() ){
									assemb = _p_.changeOffset(oCopyCell.getOffset2(oCurItem.cell.getName())).assemble();
									oCopyCell.setValue("="+assemb);
									
								}
								this.worksheet.workbook.needRecalc[ getVertexId(this.worksheet.getId(),oCopyCell.getName()) ] = [ this.worksheet.getId(),oCopyCell.getName() ];
								if( this.worksheet.workbook.needRecalc.length < 0) this.worksheet.workbook.needRecalc.length = 0;
								this.worksheet.workbook.needRecalc.length++;
							}
                        }
                    }
                    
                    nCellsIndex += nDCellsIndex;
                    if(nDCellsIndex > 0 && nCellsIndex >= nCellsLength)
                        nCellsIndex = 0;
                    else if(nCellsIndex < 0)
                        nCellsIndex = nCellsLength - 1;
                        
                }
            }
		}
    }
	else
	{
		var nLastRow = oBBox.r2;
		if(bWholeCol)
		{
			nLastRow = 0;
			this._foreachColNoEmpty(function(){}, function(cell){
				var nCurRow0 = cell.oId.getRow0();
				if(nCurRow0 > nLastRow)
					nLastRow = nCurRow0;
			});
		}
		if(nIndex >= 0 && nWidth > nIndex)
        {
			//удаляем содержимое
            for(var i = oBBox.r1; i <= nLastRow; ++i)
            {
                for(var j = oBBox.c1 + nIndex; j <= oBBox.c2; ++j)
                {
                    var oCurCell = this.worksheet._getCellNoEmpty(i, j);
                    if(null != oCurCell)
                        oCurCell.setValue("");
                }
            }
        }
		else
        {
            //копируем содержимое
            for(var i = oBBox.r1; i <= nLastRow; ++i)
            {
                //пробегаемся по диапазону запоминаем ячеек смотрим какие из них числа
                var aCells = new Array();
				var oPromoteHelper = new PromoteHelper();
8147
				var oDigParams = null;
8148 8149 8150 8151
                for(var j = oBBox.c1; j <= oBBox.c2; ++j)
                {
                    var oCurCell = this.worksheet._getCellNoEmpty(i, j);
                    var nVal = null, nF = null;
8152
					var sCurPrefix = null;
8153 8154 8155 8156 8157
                    if(null != oCurCell)
                    {
                        if (!oCurCell.sFormula)
						{
							var nType = oCurCell.getType();
8158
							if(CellValueType.Number == nType || CellValueType.String == nType)
8159 8160 8161 8162
							{
								var sValue = oCurCell.getValueWithoutFormat();
                                if("" != sValue)
                                {
8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198
									if(CellValueType.Number == nType)
										nVal = sValue - 0;
									else
									{
										//если текст заканчивается на цифру тоже используем ее
										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)
										{
											sCurPrefix = sValue.substring(0, nEndIndex);
											nVal = sValue.substring(nEndIndex) - 0;
										}
									}
									if(null != nVal)
									{
										if(null == oDigParams)
											oDigParams = {valid: true, prefix: sCurPrefix};
										else if(sCurPrefix != oDigParams.prefix)
										{
											fFinishSection(oDigParams, oPromoteHelper);
											oDigParams = {valid: true, prefix: sCurPrefix};
										}
										oPromoteHelper.add(nVal);
									}
									else
									{
										fFinishSection(oDigParams, oPromoteHelper);
										oDigParams = null;
									}
8199 8200 8201 8202
                                }
                            }
                        }
						else{
8203 8204
							fFinishSection(oDigParams, oPromoteHelper);
							oDigParams = null;
8205 8206 8207
							nF = true;
						}
                    }
8208 8209 8210 8211
                    if(null == nVal)
						aCells.push({digparams: null, cell: oCurCell, formula:nF});
					else
						aCells.push({digparams: oDigParams, cell: oCurCell, formula:nF});
8212
                }
8213
				fFinishSection(oDigParams, oPromoteHelper);
8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260
				oPromoteHelper.finishAdd();
                var bExistDigit = false;
                if(false == bCtrl && false == oPromoteHelper.isEmpty())
                {
                    bExistDigit = true;
					oPromoteHelper.calc();
                }
                var nCellsLength = aCells.length;
                var nCellsIndex;
                var nStart;
                var nEnd;
                var nDj;
                var nDCellsIndex;
                var fCondition;
                if(nIndex > 0)
                {
                    nStart = oBBox.c2 + 1;
                    nEnd = oBBox.c2 + (nIndex - nWidth + 1);
                    nCellsIndex = 0;
                    nDj = 1;
                    nDCellsIndex = 1;
                    fCondition = function(j , nEnd){return j <= nEnd;}
                }
                else
                {
					oPromoteHelper.reverse();
                    nStart = oBBox.c1 - 1;
                    nEnd = oBBox.c1 + nIndex;
                    if(nEnd < 0)
                        nEnd = 0;
                    nCellsIndex = nCellsLength - 1;
                    nDj = -1;
                    nDCellsIndex = -1;
                    fCondition = function(j , nEnd){return j >= nEnd;}
                }
                for(var j = nStart; fCondition(j, nEnd); j += nDj)
                {
                    var oCurItem = aCells[nCellsIndex];
                    //удаляем текущее содержимое ячейки
                    var oCurCell = this.worksheet._getCellNoEmpty(i, j);
                    if(null != oCurCell)
						this.worksheet._removeCell(i, j);
                    if(null != oCurItem.cell)
                    {
                        var oCopyCell = this.worksheet._getCell(i, j);
                        oCopyCell.setStyle(oCurItem.cell.getStyle());
                        oCopyCell.setType(oCurItem.cell.getType());
8261
                        if(bExistDigit && null != oCurItem.digparams && true == oCurItem.digparams.valid)
8262 8263
                        {
							var dNewValue = oPromoteHelper.getNext();
8264 8265 8266 8267 8268
							var sVal = "";
							if(null != oCurItem.digparams.prefix)
								sVal += oCurItem.digparams.prefix;
							sVal += dNewValue;
                            oCopyCell.setValue(sVal);
8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314
                        }
                        else
                        {
                            //копируем полностью
							if(!oCurItem.formula){
								var DataOld = oCopyCell.getValueData();
								oCopyCell.oValue = oCurItem.cell.oValue.clone(oCopyCell);
								var DataNew = oCopyCell.getValueData();
								if(false == DataOld.isEqual(DataNew))
									History.Add(g_oUndoRedoCell, historyitem_Cell_ChangeValue, this.worksheet.getId(), new Asc.Range(0, oCopyCell.oId.getRow0(), gc_nMaxCol0, oCopyCell.oId.getRow0()), new UndoRedoData_CellSimpleData(oCopyCell.oId.getRow0(), oCopyCell.oId.getCol0(), DataOld, DataNew));
								//todo
								// if(oCopyCell.isEmptyTextString())
									// this.worksheet._getHyperlink().remove({r1: oCopyCell.oId.getRow0(), c1: oCopyCell.oId.getCol0(), r2: oCopyCell.oId.getRow0(), c2: oCopyCell.oId.getCol0()});
								
								if( !arrRecalc[this.worksheet.getId()] ){
									arrRecalc[this.worksheet.getId()] = {};
								}
								arrRecalc[this.worksheet.getId()][oCopyCell.getName()] = oCopyCell.getName();
								this.worksheet.workbook.needRecalc[ getVertexId(this.worksheet.getId(),oCopyCell.getName()) ] = [ this.worksheet.getId(),oCopyCell.getName() ];
								if( this.worksheet.workbook.needRecalc.length < 0) this.worksheet.workbook.needRecalc.length = 0;
								this.worksheet.workbook.needRecalc.length++;
							}
							else{
								var assemb;
								var _p_ = new parserFormula(oCurItem.cell.sFormula,oCopyCell.getName(),this.worksheet);
								if( _p_.parse() ){
									assemb = _p_.changeOffset(oCopyCell.getOffset2(oCurItem.cell.getName())).assemble();
									oCopyCell.setValue("="+assemb);
								}
								this.worksheet.workbook.needRecalc[ getVertexId(this.worksheet.getId(),oCopyCell.getName()) ] = [ this.worksheet.getId(),oCopyCell.getName() ];
								if( this.worksheet.workbook.needRecalc.length < 0) this.worksheet.workbook.needRecalc.length = 0;
								this.worksheet.workbook.needRecalc.length++;
							}
                        }
                    }
                    
                    nCellsIndex += nDCellsIndex;
                    if(nDCellsIndex > 0 && nCellsIndex >= nCellsLength)
                        nCellsIndex = 0;
                    else if(nCellsIndex < 0)
                        nCellsIndex = nCellsLength - 1;
                }
            }
		}
	}
	History.EndTransaction();
Dmitry.Shahtanov's avatar
Dmitry.Shahtanov committed
8315
	buildRecalc(this.worksheet.workbook);
8316 8317 8318 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
	unLockDraw(this.worksheet.workbook);
}
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){
			for(var i = bbox.r1; i <= bbox.r2; ++i)
				oThis.worksheet._getCell(i, col.index);
		}, null);
	}
	else if(c_oRangeType.Col == nRangeType)
	{
		this._foreachRowNoEmpty(function(row){
			for(var i = bbox.c1; i <= bbox.c2; ++i)
				oThis.worksheet._getCell(row.index, i);
		}, null);
	}
}
//-------------------------------------------------------------------------------------------------
/**
 * @constructor
 */
function PromoteHelper(){
	//для открытия 
	this.aCurDigits = new Array();
	//для get
	this.nCurSequence = 0;
	this.nCurSequenceIndex = 0;
	this.nDx = 1;
	//общее
	this.aSequence = new Array();
	this.nSequenceLength = 0;
};
PromoteHelper.prototype = {
	add: function(dVal){
		this.aCurDigits.push(dVal);
	},
	finishSection: function()
	{
		if(this.aCurDigits.length > 0)
		{
			this.aSequence.push({digits: this.aCurDigits, a0: 0, a1: 0, nX: 0, length: this.aCurDigits.length});
			this.aCurDigits = new Array();
		}
	},
8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389
	isOnlyIntegerSequence: function()
	{
		var bRes = true;
		var nPrevValue = null;
		var nDiff = null;
		for(var i = 0, length = this.aCurDigits.length; i < length; ++i)
		{
			var nCurValue = this.aCurDigits[i];
			if(null != nPrevValue)
			{
				if(null == nDiff)
					nDiff = nCurValue - nPrevValue;
				else if(nCurValue != nPrevValue + nDiff)
				{
					bRes = false;
					break;
				}
			}
			nPrevValue = nCurValue;
		}
		return bRes;
	},
	removeLast: function()
	{
		this.aCurDigits = new Array();
	},
8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498
	finishAdd: function(){
		if(this.aCurDigits.length > 0)
			this.aSequence.push({digits: this.aCurDigits, a0: 0, a1: 0, nX: 0, length: this.aCurDigits.length});
		this.nSequenceLength = this.aSequence.length;
	},
	isEmpty : function()
	{
		return 0 == this.nSequenceLength;
	},
	calc: function(){
		for(var i = 0, length = this.aSequence.length; i < length; ++i)
		{
			var sequence = this.aSequence[i];
			var sequenceParams = this._promoteSequence(sequence.digits);
			sequence.a0 = sequenceParams.a0;
			sequence.a1 = sequenceParams.a1;
			sequence.nX = sequenceParams.nX;
		}
	},
	reverse: function(){
		if(this.isEmpty())
			return;
		this.nCurSequence = this.nSequenceLength - 1;
		this.nCurSequenceIndex = this.aSequence[this.nCurSequence].length - 1;
		this.nDx = -1;
		for(var i = 0, length = this.aSequence.length; i < length; ++i)
			this.aSequence[i].nX = -1;
	},
	getNext: function(){
		var sequence = this.aSequence[this.nCurSequence];
		var dNewVal = sequence.a1 * sequence.nX + sequence.a0;
		sequence.nX += this.nDx;
		this.nCurSequenceIndex += this.nDx;
        if(this.nDx > 0)
		{
			if(this.nCurSequenceIndex >= sequence.length)
			{
				this.nCurSequenceIndex = 0;
				this.nCurSequence++;
				if(this.nCurSequence >= this.nSequenceLength)
					this.nCurSequence = 0;
			}
		}
        else
		{
			if(this.nCurSequenceIndex < 0)
			{
				this.nCurSequence--;
				if(this.nCurSequence < 0)
					this.nCurSequence = this.nSequenceLength - 1;
				this.nCurSequenceIndex = this.aSequence[this.nCurSequence].length - 1;
			}
		}
		return dNewVal
	},
	_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;
			a0 = aDigits[0];
		}
		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;

			// Цикл по всем строкам
			for (var i = 0, length = aDigits.length; i < length; ++i, ++nX)
			{
				var dValue = aDigits[i];

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

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

			a0 = dD1 / dD;
			a1 = dD2 / dD;
		}
		return {a0: a0, a1: a1, nX: nX};
	}
8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549
};
function DefinedName(){
	this.Name = null;
	this.Ref = null;
	this.LocalSheetId = null;
	this.bTable = false;
}
function NameGenerator(wb){
	this.wb = wb;
	this.aExistNames = new Object();
	this.sTableNamePattern = "Table";
	this.nTableNameMaxIndex = 0;
};
NameGenerator.prototype = {
	addName : function(sName){
		this.aExistNames[sName] = 1;
	},
	addLocalDefinedName : function(oDefinedName){
		this.addName(oDefinedName.Name);
	},
	addDefinedName : function(oDefinedName){
		this.wb.DefinedNames[oDefinedName.Name] = oDefinedName;
		this.addName(oDefinedName.Name);
	},
	addTableName : function(sName, ws, Ref){
		var sDefinedNameRef = ws.getName();
		if(false == rx_test_ws_name.test(sDefinedNameRef))
			sDefinedNameRef = "'" + sDefinedNameRef + "'";
		sDefinedNameRef += "!" + Ref;
		var oNewDefinedName = new DefinedName();
		oNewDefinedName.Name = sName;
		oNewDefinedName.Ref = sDefinedNameRef;
		oNewDefinedName.bTable = true;
		this.addDefinedName(oNewDefinedName);
	},
	isExist : function(sName)
	{
		return null != this.aExistNames[sName];
	},
	getNextTableName : function(ws, Ref){
		this.nTableNameMaxIndex++;
		var sNewName = this.sTableNamePattern + this.nTableNameMaxIndex;
		while(null != this.aExistNames[sNewName])
		{
			this.nTableNameMaxIndex++;
			sNewName = this.sTableNamePattern + this.nTableNameMaxIndex;
		}
		this.addTableName(sNewName, ws, Ref);
		return sNewName;
	}
}